text
stringlengths
54
60.6k
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2009 Sacha Schutz <istdasklar@free.fr> * Copyright (C) 2009-2011 Guillaume Martres <smarter@ubuntu.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sound.h" #include "engine.h" #include "alure/include/AL/alure.h" #include <core/debughelper.h> #include <sndfile.h> using namespace GluonAudio; class Sound::SoundPrivate { public: SoundPrivate() { init(); } ~SoundPrivate() { } bool newError() { QLatin1String error = QLatin1String(alureGetErrorString()); if (error != QLatin1String("No error")) { DEBUG_BLOCK DEBUG_TEXT2("Alure error: %1", error) isValid = false; return true; } return false; } void init() { isValid = true; isStreamed = false; isPaused = false; isStopped = true; isLooping = false; stream = 0; source = 0; position = QVector3D( 0, 0, 0 ); volume = 1.0f; pitch = 1.0f; radius = 10000.0f; duration = 0; } bool setupSource() { if (path.isEmpty()) { return false; } alGenSources( 1, &source ); if (source == 0) { DEBUG_BLOCK DEBUG_TEXT2("Empty source, OpenAL error: %1", alGetError()) return false; } ALfloat sourcePosition[] = { position.x(), position.y() , position.z() }; alSourcefv( source, AL_POSITION, sourcePosition ); alSourcef( source, AL_GAIN, volume ); alSourcef( source, AL_PITCH, pitch ); alSourcef( source, AL_REFERENCE_DISTANCE, radius ); return true; } void _k_deleteSource() { if (source != 0) { alureStopSource(source, false); alDeleteSources(1, &source); source = 0; } isValid = false; isStopped = true; if (isStreamed) { alureDestroyStream(stream, 0, 0); } stream = 0; } QString path; bool isValid; bool isStreamed; bool isPaused; bool isStopped; bool isLooping; alureStream* stream; ALuint source; QVector3D position; ALfloat volume; ALfloat pitch; ALfloat radius; double duration; }; Sound::Sound() : QObject( Engine::instance() ) , d( new SoundPrivate ) { d->isValid = false; } Sound::Sound(const QString& fileName) : QObject( Engine::instance() ) , d( new SoundPrivate ) { load(fileName); } Sound::Sound(const QString& fileName, bool toStream) : QObject( Engine::instance() ) , d( new SoundPrivate ) { load(fileName, toStream); } Sound::~Sound() { d->_k_deleteSource(); delete d; } bool Sound::isValid() const { return d->isValid; } bool Sound::load(const QString &fileName) { SF_INFO sfinfo; memset(&sfinfo, 0, sizeof(sfinfo)); SNDFILE *sndfile = sf_open(fileName.toLocal8Bit().data(), SFM_READ, &sfinfo); sf_close(sndfile); d->duration = (double)sfinfo.frames / sfinfo.samplerate; bool toStream = ( d->duration >= (double)(Engine::instance()->bufferLength()*Engine::instance()->buffersPerStream())/1e6 ); return load(fileName, toStream); } bool Sound::load(const QString& fileName, bool toStream) { if (fileName.isEmpty()) { d->isValid = false; return false; } if (!d->path.isEmpty()) { d->_k_deleteSource(); } d->path = fileName; if( !d->setupSource() ) return false; d->isStreamed = toStream; if (d->isStreamed) { alureStreamSizeIsMicroSec(true); d->stream = alureCreateStreamFromFile(d->path.toLocal8Bit().constData(), Engine::instance()->bufferLength(), 0, 0); } else { ALuint buffer = Engine::instance()->genBuffer(d->path); if ( d->newError() ) { d->isValid = false; return false; } alSourcei(d->source, AL_BUFFER, buffer); } d->isValid = !d->newError(); return d->isValid; } ALfloat Sound::elapsedTime() const { ALfloat seconds = 0.f; alGetSourcef( d->source, AL_SEC_OFFSET, &seconds ); return seconds; } ALint Sound::status() const { ALint status; alGetSourcei( d->source, AL_SOURCE_STATE, &status ); return status; } bool Sound::isLooping() const { return d->isLooping; } bool Sound::isPlaying() const { return !d->isStopped; } void Sound::setLoop( bool enabled ) { d->isLooping = enabled; if (!d->isStreamed) { alSourcei( d->source, AL_LOOPING, enabled ); } } void Sound::clear() { d->_k_deleteSource(); } QVector3D Sound::position() const { return d->position; } ALfloat Sound::x() const { return d->position.x(); } ALfloat Sound::y() const { return d->position.y(); } ALfloat Sound::z() const { return d->position.z(); } ALfloat Sound::volume() const { return d->volume; } ALfloat Sound::pitch() const { return d->pitch; } ALfloat Sound::radius() const { return d->radius; } void Sound::setPosition( ALfloat x, ALfloat y, ALfloat z ) { setPosition( QVector3D(x, y, z) ); } void Sound::setPosition( QVector3D position ) { d->position = position; ALfloat sourcePosition[] = { position.x(), position.y() , position.z() }; alSourcefv( d->source, AL_POSITION, sourcePosition ); } void Sound::setVolume( ALfloat volume ) { d->volume = volume; alSourcef( d->source, AL_GAIN, volume ); } void Sound::setPitch( ALfloat pitch ) { d->pitch = pitch; alSourcef( d->source, AL_PITCH, pitch ); } void Sound::setRadius( ALfloat radius ) { d->radius = radius; alSourcef( d->source, AL_REFERENCE_DISTANCE, radius ); } void callbackStopped(void *object, ALuint source) { static_cast<GluonAudio::Sound*>(object)->stopped(); } void Sound::stopped() { d->isStopped = true; if (d->isLooping) { play(); } } void Sound::play() { if (d->isPaused) { alureResumeSource(d->source); } if (!d->isStopped) { stop(); } if (d->isStreamed) { int loopCount = (d->isLooping ? -1 : 0); alurePlaySourceStream(d->source, d->stream, Engine::instance()->buffersPerStream(), loopCount, callbackStopped, this); } else { alurePlaySource(d->source, callbackStopped, this); } d->isStopped = false; d->newError(); } void Sound::pause() { alurePauseSource(d->source); d->isPaused = true; d->newError(); } void Sound::stop() { alureStopSource(d->source, false); d->isStopped = true; d->newError(); } void Sound::rewind() { if (d->isStreamed) { alureRewindStream(d->stream); } else { alSourceRewind(d->source); } d->newError(); } void Sound::setMinVolume( ALfloat min ) { alSourcef( d->source, AL_MIN_GAIN, min ); } void Sound::setMaxVolume( ALfloat max ) { alSourcef( d->source, AL_MAX_GAIN, max ); } void Sound::setVelocity( ALfloat vx, ALfloat vy, ALfloat vz ) { ALfloat velocity[] = { vx, vy, vz }; alSourcefv( d->source, AL_VELOCITY, velocity ); } void Sound::setDirection( ALfloat dx, ALfloat dy, ALfloat dz ) { ALfloat direction[] = { dx, dy, dz }; alSourcefv( d->source, AL_POSITION, direction ); } void Sound::setTimePosition( ALfloat time ) { alSourcef( d->source, AL_SEC_OFFSET, time ); } double Sound::duration() const { if (!d->isValid) { return 0; } return d->duration; } #include "sound.moc" <commit_msg>Set the default valid state to false inside the initialization<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2009 Sacha Schutz <istdasklar@free.fr> * Copyright (C) 2009-2011 Guillaume Martres <smarter@ubuntu.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sound.h" #include "engine.h" #include "alure/include/AL/alure.h" #include <core/debughelper.h> #include <sndfile.h> using namespace GluonAudio; class Sound::SoundPrivate { public: SoundPrivate() { init(); } ~SoundPrivate() { } bool newError() { QLatin1String error = QLatin1String(alureGetErrorString()); if (error != QLatin1String("No error")) { DEBUG_BLOCK DEBUG_TEXT2("Alure error: %1", error) isValid = false; return true; } return false; } void init() { isValid = false; isStreamed = false; isPaused = false; isStopped = true; isLooping = false; stream = 0; source = 0; position = QVector3D( 0, 0, 0 ); volume = 1.0f; pitch = 1.0f; radius = 10000.0f; duration = 0; } bool setupSource() { if (path.isEmpty()) { return false; } alGenSources( 1, &source ); if (source == 0) { DEBUG_BLOCK DEBUG_TEXT2("Empty source, OpenAL error: %1", alGetError()) return false; } ALfloat sourcePosition[] = { position.x(), position.y() , position.z() }; alSourcefv( source, AL_POSITION, sourcePosition ); alSourcef( source, AL_GAIN, volume ); alSourcef( source, AL_PITCH, pitch ); alSourcef( source, AL_REFERENCE_DISTANCE, radius ); return true; } void _k_deleteSource() { if (source != 0) { alureStopSource(source, false); alDeleteSources(1, &source); source = 0; } isValid = false; isStopped = true; if (isStreamed) { alureDestroyStream(stream, 0, 0); } stream = 0; } QString path; bool isValid; bool isStreamed; bool isPaused; bool isStopped; bool isLooping; alureStream* stream; ALuint source; QVector3D position; ALfloat volume; ALfloat pitch; ALfloat radius; double duration; }; Sound::Sound() : QObject( Engine::instance() ) , d( new SoundPrivate ) { d->isValid = false; } Sound::Sound(const QString& fileName) : QObject( Engine::instance() ) , d( new SoundPrivate ) { load(fileName); } Sound::Sound(const QString& fileName, bool toStream) : QObject( Engine::instance() ) , d( new SoundPrivate ) { load(fileName, toStream); } Sound::~Sound() { d->_k_deleteSource(); delete d; } bool Sound::isValid() const { return d->isValid; } bool Sound::load(const QString &fileName) { SF_INFO sfinfo; memset(&sfinfo, 0, sizeof(sfinfo)); SNDFILE *sndfile = sf_open(fileName.toLocal8Bit().data(), SFM_READ, &sfinfo); sf_close(sndfile); d->duration = (double)sfinfo.frames / sfinfo.samplerate; bool toStream = ( d->duration >= (double)(Engine::instance()->bufferLength()*Engine::instance()->buffersPerStream())/1e6 ); return load(fileName, toStream); } bool Sound::load(const QString& fileName, bool toStream) { if (fileName.isEmpty()) { d->isValid = false; return false; } if (!d->path.isEmpty()) { d->_k_deleteSource(); } d->path = fileName; if( !d->setupSource() ) return false; d->isStreamed = toStream; if (d->isStreamed) { alureStreamSizeIsMicroSec(true); d->stream = alureCreateStreamFromFile(d->path.toLocal8Bit().constData(), Engine::instance()->bufferLength(), 0, 0); } else { ALuint buffer = Engine::instance()->genBuffer(d->path); if ( d->newError() ) { d->isValid = false; return false; } alSourcei(d->source, AL_BUFFER, buffer); } d->isValid = !d->newError(); return d->isValid; } ALfloat Sound::elapsedTime() const { ALfloat seconds = 0.f; alGetSourcef( d->source, AL_SEC_OFFSET, &seconds ); return seconds; } ALint Sound::status() const { ALint status; alGetSourcei( d->source, AL_SOURCE_STATE, &status ); return status; } bool Sound::isLooping() const { return d->isLooping; } bool Sound::isPlaying() const { return !d->isStopped; } void Sound::setLoop( bool enabled ) { d->isLooping = enabled; if (!d->isStreamed) { alSourcei( d->source, AL_LOOPING, enabled ); } } void Sound::clear() { d->_k_deleteSource(); } QVector3D Sound::position() const { return d->position; } ALfloat Sound::x() const { return d->position.x(); } ALfloat Sound::y() const { return d->position.y(); } ALfloat Sound::z() const { return d->position.z(); } ALfloat Sound::volume() const { return d->volume; } ALfloat Sound::pitch() const { return d->pitch; } ALfloat Sound::radius() const { return d->radius; } void Sound::setPosition( ALfloat x, ALfloat y, ALfloat z ) { setPosition( QVector3D(x, y, z) ); } void Sound::setPosition( QVector3D position ) { d->position = position; ALfloat sourcePosition[] = { position.x(), position.y() , position.z() }; alSourcefv( d->source, AL_POSITION, sourcePosition ); } void Sound::setVolume( ALfloat volume ) { d->volume = volume; alSourcef( d->source, AL_GAIN, volume ); } void Sound::setPitch( ALfloat pitch ) { d->pitch = pitch; alSourcef( d->source, AL_PITCH, pitch ); } void Sound::setRadius( ALfloat radius ) { d->radius = radius; alSourcef( d->source, AL_REFERENCE_DISTANCE, radius ); } void callbackStopped(void *object, ALuint source) { static_cast<GluonAudio::Sound*>(object)->stopped(); } void Sound::stopped() { d->isStopped = true; if (d->isLooping) { play(); } } void Sound::play() { if (d->isPaused) { alureResumeSource(d->source); } if (!d->isStopped) { stop(); } if (d->isStreamed) { int loopCount = (d->isLooping ? -1 : 0); alurePlaySourceStream(d->source, d->stream, Engine::instance()->buffersPerStream(), loopCount, callbackStopped, this); } else { alurePlaySource(d->source, callbackStopped, this); } d->isStopped = false; d->newError(); } void Sound::pause() { alurePauseSource(d->source); d->isPaused = true; d->newError(); } void Sound::stop() { alureStopSource(d->source, false); d->isStopped = true; d->newError(); } void Sound::rewind() { if (d->isStreamed) { alureRewindStream(d->stream); } else { alSourceRewind(d->source); } d->newError(); } void Sound::setMinVolume( ALfloat min ) { alSourcef( d->source, AL_MIN_GAIN, min ); } void Sound::setMaxVolume( ALfloat max ) { alSourcef( d->source, AL_MAX_GAIN, max ); } void Sound::setVelocity( ALfloat vx, ALfloat vy, ALfloat vz ) { ALfloat velocity[] = { vx, vy, vz }; alSourcefv( d->source, AL_VELOCITY, velocity ); } void Sound::setDirection( ALfloat dx, ALfloat dy, ALfloat dz ) { ALfloat direction[] = { dx, dy, dz }; alSourcefv( d->source, AL_POSITION, direction ); } void Sound::setTimePosition( ALfloat time ) { alSourcef( d->source, AL_SEC_OFFSET, time ); } double Sound::duration() const { if (!d->isValid) { return 0; } return d->duration; } #include "sound.moc" <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/framework/XMLBuffer.hpp> #include <xercesc/validators/common/ContentSpecNode.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/util/ValueStackOf.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // ContentSpecNode: Copy Constructor // // Note: this copy constructor has dependency on various get*() methods // and shall be placed after those method's declaration. // aka inline function compilation error on AIX 4.2, xlC 3 r ev.1 // --------------------------------------------------------------------------- ContentSpecNode::ContentSpecNode(const ContentSpecNode& toCopy) : XSerializable(toCopy) , XMemory(toCopy) , fMemoryManager(toCopy.fMemoryManager) , fElement(0) , fElementDecl(toCopy.fElementDecl) , fFirst(0) , fSecond(0) , fType(toCopy.fType) , fAdoptFirst(true) , fAdoptSecond(true) , fMinOccurs(toCopy.fMinOccurs) , fMaxOccurs(toCopy.fMaxOccurs) { const QName* tempElement = toCopy.getElement(); if (tempElement) fElement = new (fMemoryManager) QName(*tempElement); const ContentSpecNode *tmp = toCopy.getFirst(); if (tmp) fFirst = new (fMemoryManager) ContentSpecNode(*tmp); tmp = toCopy.getSecond(); if (tmp) fSecond = new (fMemoryManager) ContentSpecNode(*tmp); } ContentSpecNode::~ContentSpecNode() { // Delete our children, avoiding recursive cleanup if (fAdoptFirst && fFirst) { deleteChildNode(fFirst); } if (fAdoptSecond && fSecond) { deleteChildNode(fSecond); } delete fElement; } void ContentSpecNode::deleteChildNode(ContentSpecNode* node) { ValueStackOf<ContentSpecNode*> toBeDeleted(10, fMemoryManager); toBeDeleted.push(node); while(!toBeDeleted.empty()) { ContentSpecNode* node = toBeDeleted.pop(); if(node==0) continue; if(node->isFirstAdopted()) toBeDeleted.push(node->orphanFirst()); if(node->isSecondAdopted()) toBeDeleted.push(node->orphanSecond()); delete node; } } class formatNodeHolder { public: formatNodeHolder(const ContentSpecNode* n, const ContentSpecNode::NodeTypes p, XMLCh c) : node(n), parentType(p), character(c) {} formatNodeHolder& operator =(const formatNodeHolder* other) { node=other->node; parentType=other->parentType; character=other->character; } const ContentSpecNode* node; ContentSpecNode::NodeTypes parentType; XMLCh character; }; // --------------------------------------------------------------------------- // Local methods // --------------------------------------------------------------------------- static void formatNode( const ContentSpecNode* const curNode , XMLBuffer& bufToFill , MemoryManager* const memMgr) { if (!curNode) return; ValueStackOf<formatNodeHolder> toBeProcessed(10, memMgr); toBeProcessed.push(formatNodeHolder(curNode, ContentSpecNode::UnknownType, 0)); while(!toBeProcessed.empty()) { formatNodeHolder item=toBeProcessed.pop(); if(item.character!=0) { bufToFill.append(item.character); continue; } const ContentSpecNode* curNode = item.node; if(!curNode) continue; const ContentSpecNode::NodeTypes parentType = item.parentType; const ContentSpecNode* first = curNode->getFirst(); const ContentSpecNode* second = curNode->getSecond(); const ContentSpecNode::NodeTypes curType = curNode->getType(); // Get the type of the first node const ContentSpecNode::NodeTypes firstType = first ? first->getType() : ContentSpecNode::Leaf; // Calculate the parens flag for the rep nodes bool doRepParens = false; if (((firstType != ContentSpecNode::Leaf) && (parentType != ContentSpecNode::UnknownType)) || ((firstType == ContentSpecNode::Leaf) && (parentType == ContentSpecNode::UnknownType))) { doRepParens = true; } // Now handle our type switch(curType & 0x0f) { case ContentSpecNode::Leaf : if (curNode->getElement()->getURI() == XMLElementDecl::fgPCDataElemId) bufToFill.append(XMLElementDecl::fgPCDataElemName); else { bufToFill.append(curNode->getElement()->getRawName()); // show the + and * modifiers also when we have a non-infinite number of repetitions if(curNode->getMinOccurs()==0 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chAsterisk); else if(curNode->getMinOccurs()==0 && curNode->getMaxOccurs()==1) bufToFill.append(chQuestion); else if(curNode->getMinOccurs()==1 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chPlus); } break; case ContentSpecNode::ZeroOrOne : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chQuestion)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::ZeroOrMore : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chAsterisk)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::OneOrMore : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPlus)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::Choice : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); if(second!=NULL) { toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPipe)); } toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::Sequence : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); if(second!=NULL) { toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma)); } toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::All : if ((parentType & 0x0f) != (curType & 0x0f)) { bufToFill.append(chLatin_A); bufToFill.append(chLatin_l); bufToFill.append(chLatin_l); bufToFill.append(chOpenParen); } if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; } } } // --------------------------------------------------------------------------- // ContentSpecNode: Miscellaneous // --------------------------------------------------------------------------- void ContentSpecNode::formatSpec(XMLBuffer& bufToFill) const { // Clean out the buffer first bufToFill.reset(); if (fType == ContentSpecNode::Leaf) bufToFill.append(chOpenParen); formatNode ( this , bufToFill , fMemoryManager ); if (fType == ContentSpecNode::Leaf) bufToFill.append(chCloseParen); } int ContentSpecNode::getMinTotalRange() const { int min = fMinOccurs; if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int minFirst = fFirst->getMinTotalRange(); if (fSecond) { int minSecond = fSecond->getMinTotalRange(); if ((fType & 0x0f) == ContentSpecNode::Choice) { min = min * ((minFirst < minSecond)? minFirst : minSecond); } else { min = min * (minFirst + minSecond); } } else min = min * minFirst; } return min; } int ContentSpecNode::getMaxTotalRange() const { int max = fMaxOccurs; if (max == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int maxFirst = fFirst->getMaxTotalRange(); if (maxFirst == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if (fSecond) { int maxSecond = fSecond->getMaxTotalRange(); if (maxSecond == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } else { if ((fType & 0x0f) == ContentSpecNode::Choice) { max = max * ((maxFirst > maxSecond) ? maxFirst : maxSecond); } else { max = max * (maxFirst + maxSecond); } } } else { max = max * maxFirst; } } return max; } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(ContentSpecNode) void ContentSpecNode::serialize(XSerializeEngine& serEng) { /*** * Since fElement, fFirst, fSecond are NOT created by the default * constructor, we need to create them dynamically. ***/ if (serEng.isStoring()) { serEng<<fElement; XMLElementDecl::storeElementDecl(serEng, fElementDecl); serEng<<fFirst; serEng<<fSecond; serEng<<(int)fType; serEng<<fAdoptFirst; serEng<<fAdoptSecond; serEng<<fMinOccurs; serEng<<fMaxOccurs; } else { serEng>>fElement; fElementDecl = XMLElementDecl::loadElementDecl(serEng); serEng>>fFirst; serEng>>fSecond; int type; serEng>>type; fType = (NodeTypes)type; serEng>>fAdoptFirst; serEng>>fAdoptSecond; serEng>>fMinOccurs; serEng>>fMaxOccurs; } } XERCES_CPP_NAMESPACE_END <commit_msg>Add return statement to copy constructor (XERCESC-2001)<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/framework/XMLBuffer.hpp> #include <xercesc/validators/common/ContentSpecNode.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/util/ValueStackOf.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // ContentSpecNode: Copy Constructor // // Note: this copy constructor has dependency on various get*() methods // and shall be placed after those method's declaration. // aka inline function compilation error on AIX 4.2, xlC 3 r ev.1 // --------------------------------------------------------------------------- ContentSpecNode::ContentSpecNode(const ContentSpecNode& toCopy) : XSerializable(toCopy) , XMemory(toCopy) , fMemoryManager(toCopy.fMemoryManager) , fElement(0) , fElementDecl(toCopy.fElementDecl) , fFirst(0) , fSecond(0) , fType(toCopy.fType) , fAdoptFirst(true) , fAdoptSecond(true) , fMinOccurs(toCopy.fMinOccurs) , fMaxOccurs(toCopy.fMaxOccurs) { const QName* tempElement = toCopy.getElement(); if (tempElement) fElement = new (fMemoryManager) QName(*tempElement); const ContentSpecNode *tmp = toCopy.getFirst(); if (tmp) fFirst = new (fMemoryManager) ContentSpecNode(*tmp); tmp = toCopy.getSecond(); if (tmp) fSecond = new (fMemoryManager) ContentSpecNode(*tmp); } ContentSpecNode::~ContentSpecNode() { // Delete our children, avoiding recursive cleanup if (fAdoptFirst && fFirst) { deleteChildNode(fFirst); } if (fAdoptSecond && fSecond) { deleteChildNode(fSecond); } delete fElement; } void ContentSpecNode::deleteChildNode(ContentSpecNode* node) { ValueStackOf<ContentSpecNode*> toBeDeleted(10, fMemoryManager); toBeDeleted.push(node); while(!toBeDeleted.empty()) { ContentSpecNode* node = toBeDeleted.pop(); if(node==0) continue; if(node->isFirstAdopted()) toBeDeleted.push(node->orphanFirst()); if(node->isSecondAdopted()) toBeDeleted.push(node->orphanSecond()); delete node; } } class formatNodeHolder { public: formatNodeHolder(const ContentSpecNode* n, const ContentSpecNode::NodeTypes p, XMLCh c) : node(n), parentType(p), character(c) {} formatNodeHolder& operator =(const formatNodeHolder* other) { node=other->node; parentType=other->parentType; character=other->character; return *this; } const ContentSpecNode* node; ContentSpecNode::NodeTypes parentType; XMLCh character; }; // --------------------------------------------------------------------------- // Local methods // --------------------------------------------------------------------------- static void formatNode( const ContentSpecNode* const curNode , XMLBuffer& bufToFill , MemoryManager* const memMgr) { if (!curNode) return; ValueStackOf<formatNodeHolder> toBeProcessed(10, memMgr); toBeProcessed.push(formatNodeHolder(curNode, ContentSpecNode::UnknownType, 0)); while(!toBeProcessed.empty()) { formatNodeHolder item=toBeProcessed.pop(); if(item.character!=0) { bufToFill.append(item.character); continue; } const ContentSpecNode* curNode = item.node; if(!curNode) continue; const ContentSpecNode::NodeTypes parentType = item.parentType; const ContentSpecNode* first = curNode->getFirst(); const ContentSpecNode* second = curNode->getSecond(); const ContentSpecNode::NodeTypes curType = curNode->getType(); // Get the type of the first node const ContentSpecNode::NodeTypes firstType = first ? first->getType() : ContentSpecNode::Leaf; // Calculate the parens flag for the rep nodes bool doRepParens = false; if (((firstType != ContentSpecNode::Leaf) && (parentType != ContentSpecNode::UnknownType)) || ((firstType == ContentSpecNode::Leaf) && (parentType == ContentSpecNode::UnknownType))) { doRepParens = true; } // Now handle our type switch(curType & 0x0f) { case ContentSpecNode::Leaf : if (curNode->getElement()->getURI() == XMLElementDecl::fgPCDataElemId) bufToFill.append(XMLElementDecl::fgPCDataElemName); else { bufToFill.append(curNode->getElement()->getRawName()); // show the + and * modifiers also when we have a non-infinite number of repetitions if(curNode->getMinOccurs()==0 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chAsterisk); else if(curNode->getMinOccurs()==0 && curNode->getMaxOccurs()==1) bufToFill.append(chQuestion); else if(curNode->getMinOccurs()==1 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chPlus); } break; case ContentSpecNode::ZeroOrOne : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chQuestion)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::ZeroOrMore : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chAsterisk)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::OneOrMore : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPlus)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::Choice : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); if(second!=NULL) { toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPipe)); } toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::Sequence : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); if(second!=NULL) { toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma)); } toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::All : if ((parentType & 0x0f) != (curType & 0x0f)) { bufToFill.append(chLatin_A); bufToFill.append(chLatin_l); bufToFill.append(chLatin_l); bufToFill.append(chOpenParen); } if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; } } } // --------------------------------------------------------------------------- // ContentSpecNode: Miscellaneous // --------------------------------------------------------------------------- void ContentSpecNode::formatSpec(XMLBuffer& bufToFill) const { // Clean out the buffer first bufToFill.reset(); if (fType == ContentSpecNode::Leaf) bufToFill.append(chOpenParen); formatNode ( this , bufToFill , fMemoryManager ); if (fType == ContentSpecNode::Leaf) bufToFill.append(chCloseParen); } int ContentSpecNode::getMinTotalRange() const { int min = fMinOccurs; if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int minFirst = fFirst->getMinTotalRange(); if (fSecond) { int minSecond = fSecond->getMinTotalRange(); if ((fType & 0x0f) == ContentSpecNode::Choice) { min = min * ((minFirst < minSecond)? minFirst : minSecond); } else { min = min * (minFirst + minSecond); } } else min = min * minFirst; } return min; } int ContentSpecNode::getMaxTotalRange() const { int max = fMaxOccurs; if (max == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int maxFirst = fFirst->getMaxTotalRange(); if (maxFirst == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if (fSecond) { int maxSecond = fSecond->getMaxTotalRange(); if (maxSecond == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } else { if ((fType & 0x0f) == ContentSpecNode::Choice) { max = max * ((maxFirst > maxSecond) ? maxFirst : maxSecond); } else { max = max * (maxFirst + maxSecond); } } } else { max = max * maxFirst; } } return max; } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(ContentSpecNode) void ContentSpecNode::serialize(XSerializeEngine& serEng) { /*** * Since fElement, fFirst, fSecond are NOT created by the default * constructor, we need to create them dynamically. ***/ if (serEng.isStoring()) { serEng<<fElement; XMLElementDecl::storeElementDecl(serEng, fElementDecl); serEng<<fFirst; serEng<<fSecond; serEng<<(int)fType; serEng<<fAdoptFirst; serEng<<fAdoptSecond; serEng<<fMinOccurs; serEng<<fMaxOccurs; } else { serEng>>fElement; fElementDecl = XMLElementDecl::loadElementDecl(serEng); serEng>>fFirst; serEng>>fSecond; int type; serEng>>type; fType = (NodeTypes)type; serEng>>fAdoptFirst; serEng>>fAdoptSecond; serEng>>fMinOccurs; serEng>>fMaxOccurs; } } XERCES_CPP_NAMESPACE_END <|endoftext|>
<commit_before>/* * Copyright 2001,2004 The Apache Software Foundation. * * 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. */ /* * $Id $ */ #include <xercesc/validators/common/GrammarResolver.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/validators/schema/SchemaGrammar.hpp> #include <xercesc/validators/schema/XMLSchemaDescriptionImpl.hpp> #include <xercesc/validators/DTD/XMLDTDDescriptionImpl.hpp> #include <xercesc/internal/XMLGrammarPoolImpl.hpp> #include <xercesc/framework/psvi/XSAnnotation.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // GrammarResolver: Constructor and Destructor // --------------------------------------------------------------------------- GrammarResolver::GrammarResolver(XMLGrammarPool* const gramPool , MemoryManager* const manager) :fCacheGrammar(false) ,fUseCachedGrammar(false) ,fGrammarPoolFromExternalApplication(true) ,fStringPool(0) ,fGrammarBucket(0) ,fGrammarFromPool(0) ,fDataTypeReg(0) ,fMemoryManager(manager) ,fGrammarPool(gramPool) ,fXSModel(0) ,fGrammarPoolXSModel(0) { fGrammarBucket = new (manager) RefHashTableOf<Grammar>(29, true, manager); /*** * Grammars in this set are not owned */ fGrammarFromPool = new (manager) RefHashTableOf<Grammar>(29, false, manager); if (!gramPool) { /*** * We need to instantiate a default grammar pool object so that * all grammars and grammar components could be created through * the Factory methods */ fGrammarPool = new (manager) XMLGrammarPoolImpl(manager); fGrammarPoolFromExternalApplication=false; } fStringPool = fGrammarPool->getURIStringPool(); // REVISIT: size fGrammarsToAddToXSModel = new (manager) ValueVectorOf<SchemaGrammar*> (29, manager); } GrammarResolver::~GrammarResolver() { delete fGrammarBucket; delete fGrammarFromPool; if (fDataTypeReg) delete fDataTypeReg; /*** * delete the grammar pool iff it is created by this resolver */ if (!fGrammarPoolFromExternalApplication) delete fGrammarPool; if (fXSModel) delete fXSModel; // don't delete fGrammarPoolXSModel! we don't own it! delete fGrammarsToAddToXSModel; } // --------------------------------------------------------------------------- // GrammarResolver: Getter methods // --------------------------------------------------------------------------- DatatypeValidator* GrammarResolver::getDatatypeValidator(const XMLCh* const uriStr, const XMLCh* const localPartStr) { DatatypeValidator* dv = 0; if (XMLString::equals(uriStr, SchemaSymbols::fgURI_SCHEMAFORSCHEMA)) { if (!fDataTypeReg) { fDataTypeReg = new (fMemoryManager) DatatypeValidatorFactory(fMemoryManager); fDataTypeReg->expandRegistryToFullSchemaSet(); } dv = fDataTypeReg->getDatatypeValidator(localPartStr); } else { Grammar* grammar = getGrammar(uriStr); if (grammar && grammar->getGrammarType() == Grammar::SchemaGrammarType) { XMLBuffer nameBuf(128, fMemoryManager); nameBuf.set(uriStr); nameBuf.append(chComma); nameBuf.append(localPartStr); dv = ((SchemaGrammar*) grammar)->getDatatypeRegistry()->getDatatypeValidator(nameBuf.getRawBuffer()); } } return dv; } Grammar* GrammarResolver::getGrammar( const XMLCh* const namespaceKey) { if (!namespaceKey) return 0; Grammar* grammar = fGrammarBucket->get(namespaceKey); if (grammar) return grammar; if (fUseCachedGrammar) { grammar = fGrammarFromPool->get(namespaceKey); if (grammar) { return grammar; } else { XMLSchemaDescription* gramDesc = fGrammarPool->createSchemaDescription(namespaceKey); Janitor<XMLGrammarDescription> janName(gramDesc); grammar = fGrammarPool->retrieveGrammar(gramDesc); if (grammar) { fGrammarFromPool->put((void*) grammar->getGrammarDescription()->getGrammarKey(), grammar); } return grammar; } } return 0; } Grammar* GrammarResolver::getGrammar( XMLGrammarDescription* const gramDesc) { if (!gramDesc) return 0; Grammar* grammar = fGrammarBucket->get(gramDesc->getGrammarKey()); if (grammar) return grammar; if (fUseCachedGrammar) { grammar = fGrammarFromPool->get(gramDesc->getGrammarKey()); if (grammar) { return grammar; } else { grammar = fGrammarPool->retrieveGrammar(gramDesc); if (grammar) { fGrammarFromPool->put((void*) grammar->getGrammarDescription()->getGrammarKey(), grammar); } return grammar; } } return 0; } RefHashTableOfEnumerator<Grammar> GrammarResolver::getGrammarEnumerator() const { return RefHashTableOfEnumerator<Grammar>(fGrammarBucket, false, fMemoryManager); } RefHashTableOfEnumerator<Grammar> GrammarResolver::getReferencedGrammarEnumerator() const { return RefHashTableOfEnumerator<Grammar>(fGrammarFromPool, false, fMemoryManager); } RefHashTableOfEnumerator<Grammar> GrammarResolver::getCachedGrammarEnumerator() const { return fGrammarPool->getGrammarEnumerator(); } bool GrammarResolver::containsNameSpace( const XMLCh* const nameSpaceKey ) { if (!nameSpaceKey) return false; if (fGrammarBucket->containsKey(nameSpaceKey)) return true; if (fUseCachedGrammar) { if (fGrammarFromPool->containsKey(nameSpaceKey)) return true; // Lastly, need to check in fGrammarPool XMLSchemaDescription* gramDesc = fGrammarPool->createSchemaDescription(nameSpaceKey); Janitor<XMLGrammarDescription> janName(gramDesc); Grammar* grammar = fGrammarPool->retrieveGrammar(gramDesc); if (grammar) return true; } return false; } void GrammarResolver::putGrammar(Grammar* const grammarToAdopt) { if (!grammarToAdopt) return; /*** * the grammar will be either in the grammarpool, or in the grammarbucket */ if (!fCacheGrammar || !fGrammarPool->cacheGrammar(grammarToAdopt)) { // either we aren't caching or the grammar pool doesn't want it // so we need to look after it fGrammarBucket->put( (void*) grammarToAdopt->getGrammarDescription()->getGrammarKey(), grammarToAdopt ); if (grammarToAdopt->getGrammarType() == Grammar::SchemaGrammarType) { fGrammarsToAddToXSModel->addElement((SchemaGrammar*) grammarToAdopt); } } } // --------------------------------------------------------------------------- // GrammarResolver: methods // --------------------------------------------------------------------------- void GrammarResolver::reset() { fGrammarBucket->removeAll(); fGrammarsToAddToXSModel->removeAllElements(); delete fXSModel; fXSModel = 0; } void GrammarResolver::resetCachedGrammar() { //REVISIT: if the pool is locked this will fail... should throw an exception? fGrammarPool->clear(); // Even though fXSModel and fGrammarPoolXSModel will be invalid don't touch // them here as getXSModel will handle this. //to clear all other references to the grammars just deleted from fGrammarPool fGrammarFromPool->removeAll(); } void GrammarResolver::cacheGrammars() { RefHashTableOfEnumerator<Grammar> grammarEnum(fGrammarBucket, false, fMemoryManager); ValueVectorOf<XMLCh*> keys(8, fMemoryManager); unsigned int keyCount = 0; // Build key set while (grammarEnum.hasMoreElements()) { XMLCh* grammarKey = (XMLCh*) grammarEnum.nextElementKey(); keys.addElement(grammarKey); keyCount++; } // PSVI: assume everything will be added, if caching fails add grammar back // into vector fGrammarsToAddToXSModel->removeAllElements(); // Cache for (unsigned int i = 0; i < keyCount; i++) { XMLCh* grammarKey = keys.elementAt(i); /*** * It is up to the GrammarPool implementation to handle duplicated grammar */ Grammar* grammar = fGrammarBucket->get(grammarKey); if(fGrammarPool->cacheGrammar(grammar)) { // only orphan grammar if grammar pool accepts caching of it fGrammarBucket->orphanKey(grammarKey); } else if (grammar->getGrammarType() == Grammar::SchemaGrammarType) { // add it back to list of grammars not in grammar pool fGrammarsToAddToXSModel->addElement((SchemaGrammar*) grammar); } } } // --------------------------------------------------------------------------- // GrammarResolver: Setter methods // --------------------------------------------------------------------------- void GrammarResolver::cacheGrammarFromParse(const bool aValue) { reset(); fCacheGrammar = aValue; } Grammar* GrammarResolver::orphanGrammar(const XMLCh* const nameSpaceKey) { if (fCacheGrammar) { Grammar* grammar = fGrammarPool->orphanGrammar(nameSpaceKey); if (grammar) { if (fGrammarFromPool->containsKey(nameSpaceKey)) fGrammarFromPool->removeKey(nameSpaceKey); } // Check to see if it's in fGrammarBucket, since // we put it there if the grammar pool refused to // cache it. else if (fGrammarBucket->containsKey(nameSpaceKey)) { grammar = fGrammarBucket->orphanKey(nameSpaceKey); } return grammar; } else { return fGrammarBucket->orphanKey(nameSpaceKey); } } XSModel *GrammarResolver::getXSModel() { XSModel* xsModel; if (fCacheGrammar) { // We know if the grammarpool changed thru caching, orphaning and erasing // but NOT by other mechanisms such as lockPool() or unlockPool() so it // is safest to always get it. The grammarPool XSModel will only be // regenerated if something changed. bool XSModelWasChanged; // The grammarpool will always return an xsmodel, even if it is just // the schema for schema xsmodel... xsModel = fGrammarPool->getXSModel(XSModelWasChanged); if (XSModelWasChanged) { // we know the grammarpool XSModel has changed or this is the // first call to getXSModel if (!fGrammarPoolXSModel && (fGrammarsToAddToXSModel->size() == 0) && !fXSModel) { fGrammarPoolXSModel = xsModel; return fGrammarPoolXSModel; } else { fGrammarPoolXSModel = xsModel; // We had previously augmented the grammar pool XSModel // with our our grammars or we would like to upate it now // so we have to regenerate the XSModel fGrammarsToAddToXSModel->removeAllElements(); RefHashTableOfEnumerator<Grammar> grammarEnum(fGrammarBucket, false, fMemoryManager); while (grammarEnum.hasMoreElements()) { Grammar& grammar = (Grammar&) grammarEnum.nextElement(); if (grammar.getGrammarType() == Grammar::SchemaGrammarType) fGrammarsToAddToXSModel->addElement((SchemaGrammar*)&grammar); } delete fXSModel; if (fGrammarsToAddToXSModel->size()) { fXSModel = new (fMemoryManager) XSModel(fGrammarPoolXSModel, this, fMemoryManager); fGrammarsToAddToXSModel->removeAllElements(); return fXSModel; } fXSModel = 0; return fGrammarPoolXSModel; } } else { // we know that the grammar pool XSModel is the same as before if (fGrammarsToAddToXSModel->size()) { // we need to update our fXSModel with the new grammars if (fXSModel) { xsModel = new (fMemoryManager) XSModel(fXSModel, this, fMemoryManager); fXSModel = xsModel; } else { fXSModel = new (fMemoryManager) XSModel(fGrammarPoolXSModel, this, fMemoryManager); } fGrammarsToAddToXSModel->removeAllElements(); return fXSModel; } // Nothing has changed! if (fXSModel) { return fXSModel; } else if (fGrammarPoolXSModel) { return fGrammarPoolXSModel; } fXSModel = new (fMemoryManager) XSModel(0, this, fMemoryManager); return fXSModel; } } // Not Caching... if (fGrammarsToAddToXSModel->size()) { xsModel = new (fMemoryManager) XSModel(fXSModel, this, fMemoryManager); fGrammarsToAddToXSModel->removeAllElements(); fXSModel = xsModel; } else if (!fXSModel) { // create a new model only if we didn't have one already fXSModel = new (fMemoryManager) XSModel(0, this, fMemoryManager); } return fXSModel; } XERCES_CPP_NAMESPACE_END <commit_msg>Fix problem where incorrect xsmodel was generated for UseCachedGrammarInParse.<commit_after>/* * Copyright 2001,2004 The Apache Software Foundation. * * 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. */ /* * $Id $ */ #include <xercesc/validators/common/GrammarResolver.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/validators/schema/SchemaGrammar.hpp> #include <xercesc/validators/schema/XMLSchemaDescriptionImpl.hpp> #include <xercesc/validators/DTD/XMLDTDDescriptionImpl.hpp> #include <xercesc/internal/XMLGrammarPoolImpl.hpp> #include <xercesc/framework/psvi/XSAnnotation.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // GrammarResolver: Constructor and Destructor // --------------------------------------------------------------------------- GrammarResolver::GrammarResolver(XMLGrammarPool* const gramPool , MemoryManager* const manager) :fCacheGrammar(false) ,fUseCachedGrammar(false) ,fGrammarPoolFromExternalApplication(true) ,fStringPool(0) ,fGrammarBucket(0) ,fGrammarFromPool(0) ,fDataTypeReg(0) ,fMemoryManager(manager) ,fGrammarPool(gramPool) ,fXSModel(0) ,fGrammarPoolXSModel(0) { fGrammarBucket = new (manager) RefHashTableOf<Grammar>(29, true, manager); /*** * Grammars in this set are not owned */ fGrammarFromPool = new (manager) RefHashTableOf<Grammar>(29, false, manager); if (!gramPool) { /*** * We need to instantiate a default grammar pool object so that * all grammars and grammar components could be created through * the Factory methods */ fGrammarPool = new (manager) XMLGrammarPoolImpl(manager); fGrammarPoolFromExternalApplication=false; } fStringPool = fGrammarPool->getURIStringPool(); // REVISIT: size fGrammarsToAddToXSModel = new (manager) ValueVectorOf<SchemaGrammar*> (29, manager); } GrammarResolver::~GrammarResolver() { delete fGrammarBucket; delete fGrammarFromPool; if (fDataTypeReg) delete fDataTypeReg; /*** * delete the grammar pool iff it is created by this resolver */ if (!fGrammarPoolFromExternalApplication) delete fGrammarPool; if (fXSModel) delete fXSModel; // don't delete fGrammarPoolXSModel! we don't own it! delete fGrammarsToAddToXSModel; } // --------------------------------------------------------------------------- // GrammarResolver: Getter methods // --------------------------------------------------------------------------- DatatypeValidator* GrammarResolver::getDatatypeValidator(const XMLCh* const uriStr, const XMLCh* const localPartStr) { DatatypeValidator* dv = 0; if (XMLString::equals(uriStr, SchemaSymbols::fgURI_SCHEMAFORSCHEMA)) { if (!fDataTypeReg) { fDataTypeReg = new (fMemoryManager) DatatypeValidatorFactory(fMemoryManager); fDataTypeReg->expandRegistryToFullSchemaSet(); } dv = fDataTypeReg->getDatatypeValidator(localPartStr); } else { Grammar* grammar = getGrammar(uriStr); if (grammar && grammar->getGrammarType() == Grammar::SchemaGrammarType) { XMLBuffer nameBuf(128, fMemoryManager); nameBuf.set(uriStr); nameBuf.append(chComma); nameBuf.append(localPartStr); dv = ((SchemaGrammar*) grammar)->getDatatypeRegistry()->getDatatypeValidator(nameBuf.getRawBuffer()); } } return dv; } Grammar* GrammarResolver::getGrammar( const XMLCh* const namespaceKey) { if (!namespaceKey) return 0; Grammar* grammar = fGrammarBucket->get(namespaceKey); if (grammar) return grammar; if (fUseCachedGrammar) { grammar = fGrammarFromPool->get(namespaceKey); if (grammar) { return grammar; } else { XMLSchemaDescription* gramDesc = fGrammarPool->createSchemaDescription(namespaceKey); Janitor<XMLGrammarDescription> janName(gramDesc); grammar = fGrammarPool->retrieveGrammar(gramDesc); if (grammar) { fGrammarFromPool->put((void*) grammar->getGrammarDescription()->getGrammarKey(), grammar); } return grammar; } } return 0; } Grammar* GrammarResolver::getGrammar( XMLGrammarDescription* const gramDesc) { if (!gramDesc) return 0; Grammar* grammar = fGrammarBucket->get(gramDesc->getGrammarKey()); if (grammar) return grammar; if (fUseCachedGrammar) { grammar = fGrammarFromPool->get(gramDesc->getGrammarKey()); if (grammar) { return grammar; } else { grammar = fGrammarPool->retrieveGrammar(gramDesc); if (grammar) { fGrammarFromPool->put((void*) grammar->getGrammarDescription()->getGrammarKey(), grammar); } return grammar; } } return 0; } RefHashTableOfEnumerator<Grammar> GrammarResolver::getGrammarEnumerator() const { return RefHashTableOfEnumerator<Grammar>(fGrammarBucket, false, fMemoryManager); } RefHashTableOfEnumerator<Grammar> GrammarResolver::getReferencedGrammarEnumerator() const { return RefHashTableOfEnumerator<Grammar>(fGrammarFromPool, false, fMemoryManager); } RefHashTableOfEnumerator<Grammar> GrammarResolver::getCachedGrammarEnumerator() const { return fGrammarPool->getGrammarEnumerator(); } bool GrammarResolver::containsNameSpace( const XMLCh* const nameSpaceKey ) { if (!nameSpaceKey) return false; if (fGrammarBucket->containsKey(nameSpaceKey)) return true; if (fUseCachedGrammar) { if (fGrammarFromPool->containsKey(nameSpaceKey)) return true; // Lastly, need to check in fGrammarPool XMLSchemaDescription* gramDesc = fGrammarPool->createSchemaDescription(nameSpaceKey); Janitor<XMLGrammarDescription> janName(gramDesc); Grammar* grammar = fGrammarPool->retrieveGrammar(gramDesc); if (grammar) return true; } return false; } void GrammarResolver::putGrammar(Grammar* const grammarToAdopt) { if (!grammarToAdopt) return; /*** * the grammar will be either in the grammarpool, or in the grammarbucket */ if (!fCacheGrammar || !fGrammarPool->cacheGrammar(grammarToAdopt)) { // either we aren't caching or the grammar pool doesn't want it // so we need to look after it fGrammarBucket->put( (void*) grammarToAdopt->getGrammarDescription()->getGrammarKey(), grammarToAdopt ); if (grammarToAdopt->getGrammarType() == Grammar::SchemaGrammarType) { fGrammarsToAddToXSModel->addElement((SchemaGrammar*) grammarToAdopt); } } } // --------------------------------------------------------------------------- // GrammarResolver: methods // --------------------------------------------------------------------------- void GrammarResolver::reset() { fGrammarBucket->removeAll(); fGrammarsToAddToXSModel->removeAllElements(); delete fXSModel; fXSModel = 0; } void GrammarResolver::resetCachedGrammar() { //REVISIT: if the pool is locked this will fail... should throw an exception? fGrammarPool->clear(); // Even though fXSModel and fGrammarPoolXSModel will be invalid don't touch // them here as getXSModel will handle this. //to clear all other references to the grammars just deleted from fGrammarPool fGrammarFromPool->removeAll(); } void GrammarResolver::cacheGrammars() { RefHashTableOfEnumerator<Grammar> grammarEnum(fGrammarBucket, false, fMemoryManager); ValueVectorOf<XMLCh*> keys(8, fMemoryManager); unsigned int keyCount = 0; // Build key set while (grammarEnum.hasMoreElements()) { XMLCh* grammarKey = (XMLCh*) grammarEnum.nextElementKey(); keys.addElement(grammarKey); keyCount++; } // PSVI: assume everything will be added, if caching fails add grammar back // into vector fGrammarsToAddToXSModel->removeAllElements(); // Cache for (unsigned int i = 0; i < keyCount; i++) { XMLCh* grammarKey = keys.elementAt(i); /*** * It is up to the GrammarPool implementation to handle duplicated grammar */ Grammar* grammar = fGrammarBucket->get(grammarKey); if(fGrammarPool->cacheGrammar(grammar)) { // only orphan grammar if grammar pool accepts caching of it fGrammarBucket->orphanKey(grammarKey); } else if (grammar->getGrammarType() == Grammar::SchemaGrammarType) { // add it back to list of grammars not in grammar pool fGrammarsToAddToXSModel->addElement((SchemaGrammar*) grammar); } } } // --------------------------------------------------------------------------- // GrammarResolver: Setter methods // --------------------------------------------------------------------------- void GrammarResolver::cacheGrammarFromParse(const bool aValue) { reset(); fCacheGrammar = aValue; } Grammar* GrammarResolver::orphanGrammar(const XMLCh* const nameSpaceKey) { if (fCacheGrammar) { Grammar* grammar = fGrammarPool->orphanGrammar(nameSpaceKey); if (grammar) { if (fGrammarFromPool->containsKey(nameSpaceKey)) fGrammarFromPool->removeKey(nameSpaceKey); } // Check to see if it's in fGrammarBucket, since // we put it there if the grammar pool refused to // cache it. else if (fGrammarBucket->containsKey(nameSpaceKey)) { grammar = fGrammarBucket->orphanKey(nameSpaceKey); } return grammar; } else { return fGrammarBucket->orphanKey(nameSpaceKey); } } XSModel *GrammarResolver::getXSModel() { XSModel* xsModel; if (fCacheGrammar || fUseCachedGrammar) { // We know if the grammarpool changed thru caching, orphaning and erasing // but NOT by other mechanisms such as lockPool() or unlockPool() so it // is safest to always get it. The grammarPool XSModel will only be // regenerated if something changed. bool XSModelWasChanged; // The grammarpool will always return an xsmodel, even if it is just // the schema for schema xsmodel... xsModel = fGrammarPool->getXSModel(XSModelWasChanged); if (XSModelWasChanged) { // we know the grammarpool XSModel has changed or this is the // first call to getXSModel if (!fGrammarPoolXSModel && (fGrammarsToAddToXSModel->size() == 0) && !fXSModel) { fGrammarPoolXSModel = xsModel; return fGrammarPoolXSModel; } else { fGrammarPoolXSModel = xsModel; // We had previously augmented the grammar pool XSModel // with our our grammars or we would like to upate it now // so we have to regenerate the XSModel fGrammarsToAddToXSModel->removeAllElements(); RefHashTableOfEnumerator<Grammar> grammarEnum(fGrammarBucket, false, fMemoryManager); while (grammarEnum.hasMoreElements()) { Grammar& grammar = (Grammar&) grammarEnum.nextElement(); if (grammar.getGrammarType() == Grammar::SchemaGrammarType) fGrammarsToAddToXSModel->addElement((SchemaGrammar*)&grammar); } delete fXSModel; if (fGrammarsToAddToXSModel->size()) { fXSModel = new (fMemoryManager) XSModel(fGrammarPoolXSModel, this, fMemoryManager); fGrammarsToAddToXSModel->removeAllElements(); return fXSModel; } fXSModel = 0; return fGrammarPoolXSModel; } } else { // we know that the grammar pool XSModel is the same as before if (fGrammarsToAddToXSModel->size()) { // we need to update our fXSModel with the new grammars if (fXSModel) { xsModel = new (fMemoryManager) XSModel(fXSModel, this, fMemoryManager); fXSModel = xsModel; } else { fXSModel = new (fMemoryManager) XSModel(fGrammarPoolXSModel, this, fMemoryManager); } fGrammarsToAddToXSModel->removeAllElements(); return fXSModel; } // Nothing has changed! if (fXSModel) { return fXSModel; } else if (fGrammarPoolXSModel) { return fGrammarPoolXSModel; } fXSModel = new (fMemoryManager) XSModel(0, this, fMemoryManager); return fXSModel; } } // Not Caching... if (fGrammarsToAddToXSModel->size()) { xsModel = new (fMemoryManager) XSModel(fXSModel, this, fMemoryManager); fGrammarsToAddToXSModel->removeAllElements(); fXSModel = xsModel; } else if (!fXSModel) { // create a new model only if we didn't have one already fXSModel = new (fMemoryManager) XSModel(0, this, fMemoryManager); } return fXSModel; } XERCES_CPP_NAMESPACE_END <|endoftext|>
<commit_before>/* * Copyright 2001,2004 The Apache Software Foundation. * * 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. */ /** * $Id$ */ #if !defined(GRAMMARRESOLVER_HPP) #define GRAMMARRESOLVER_HPP #include <xercesc/framework/XMLGrammarPool.hpp> #include <xercesc/util/RefHashTableOf.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/common/Grammar.hpp> XERCES_CPP_NAMESPACE_BEGIN class DatatypeValidator; class DatatypeValidatorFactory; class XMLGrammarDescription; /** * This class embodies the representation of a Grammar pool Resolver. * This class is called from the validator. * */ class VALIDATORS_EXPORT GrammarResolver : public XMemory { public: /** @name Constructor and Destructor */ //@{ /** * * Default Constructor */ GrammarResolver( XMLGrammarPool* const gramPool , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /** * Destructor */ ~GrammarResolver(); //@} /** @name Getter methods */ //@{ /** * Retrieve the DatatypeValidator * * @param uriStr the namespace URI * @param typeName the type name * @return the DatatypeValidator associated with namespace & type name */ DatatypeValidator* getDatatypeValidator(const XMLCh* const uriStr, const XMLCh* const typeName); /** * Retrieve the grammar that is associated with the specified namespace key * * @param gramDesc grammar description for the grammar * @return Grammar abstraction associated with the grammar description */ Grammar* getGrammar( XMLGrammarDescription* const gramDesc ) ; /** * Retrieve the grammar that is associated with the specified namespace key * * @param namespaceKey Namespace key into Grammar pool * @return Grammar abstraction associated with the NameSpace key. */ Grammar* getGrammar( const XMLCh* const namespaceKey ) ; /** * Get an enumeration of Grammar in the Grammar pool * * @return enumeration of Grammar in Grammar pool */ RefHashTableOfEnumerator<Grammar> getGrammarEnumerator() const; /** * Get an enumeration of the referenced Grammars * * @return enumeration of referenced Grammars */ RefHashTableOfEnumerator<Grammar> getReferencedGrammarEnumerator() const; /** * Get an enumeration of the cached Grammars in the Grammar pool * * @return enumeration of the cached Grammars in Grammar pool */ RefHashTableOfEnumerator<Grammar> getCachedGrammarEnumerator() const; /** * Get a string pool of schema grammar element/attribute names/prefixes * (used by TraverseSchema) * * @return a string pool of schema grammar element/attribute names/prefixes */ XMLStringPool* getStringPool(); /** * Is the specified Namespace key in Grammar pool? * * @param nameSpaceKey Namespace key * @return True if Namespace key association is in the Grammar pool. */ bool containsNameSpace( const XMLCh* const nameSpaceKey ); inline XMLGrammarPool* const getGrammarPool() const; inline MemoryManager* const getGrammarPoolMemoryManager() const; //@} /** @name Setter methods */ //@{ /** * Set the 'Grammar caching' flag */ void cacheGrammarFromParse(const bool newState); /** * Set the 'Use cached grammar' flag */ void useCachedGrammarInParse(const bool newState); //@} /** @name GrammarResolver methods */ //@{ /** * Add the Grammar with Namespace Key associated to the Grammar Pool. * The Grammar will be owned by the Grammar Pool. * * @param grammarToAdopt Grammar abstraction used by validator. */ void putGrammar(Grammar* const grammarToAdopt ); /** * Returns the Grammar with Namespace Key associated from the Grammar Pool * The Key entry is removed from the table (grammar is not deleted if * adopted - now owned by caller). * * @param nameSpaceKey Key to associate with Grammar abstraction */ Grammar* orphanGrammar(const XMLCh* const nameSpaceKey); /** * Cache the grammars in fGrammarBucket to fCachedGrammarRegistry. * If a grammar with the same key is already cached, an exception is * thrown and none of the grammars will be cached. */ void cacheGrammars(); /** * Reset internal Namespace/Grammar registry. */ void reset(); void resetCachedGrammar(); /** * Returns an XSModel, either from the GrammarPool or by creating one */ XSModel* getXSModel(); ValueVectorOf<SchemaGrammar*>* getGrammarsToAddToXSModel(); //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- GrammarResolver(const GrammarResolver&); GrammarResolver& operator=(const GrammarResolver&); // ----------------------------------------------------------------------- // Private data members // // fStringPool The string pool used by TraverseSchema to store // element/attribute names and prefixes. // Always owned by Grammar pool implementation // // fGrammarBucket The parsed Grammar Pool, if no caching option. // // fGrammarFromPool Referenced Grammar Set, not owned // // fGrammarPool The Grammar Set either plugged or created. // // fDataTypeReg DatatypeValidatorFactory registery // // fMemoryManager Pluggable memory manager for dynamic memory // allocation/deallocation // ----------------------------------------------------------------------- bool fCacheGrammar; bool fUseCachedGrammar; bool fGrammarPoolFromExternalApplication; XMLStringPool* fStringPool; RefHashTableOf<Grammar>* fGrammarBucket; RefHashTableOf<Grammar>* fGrammarFromPool; DatatypeValidatorFactory* fDataTypeReg; MemoryManager* fMemoryManager; XMLGrammarPool* fGrammarPool; XSModel* fXSModel; XSModel* fGrammarPoolXSModel; ValueVectorOf<SchemaGrammar*>* fGrammarsToAddToXSModel; }; inline XMLStringPool* GrammarResolver::getStringPool() { return fStringPool; } inline void GrammarResolver::useCachedGrammarInParse(const bool aValue) { fUseCachedGrammar = aValue; } inline XMLGrammarPool* const GrammarResolver::getGrammarPool() const { return fGrammarPool; } inline MemoryManager* const GrammarResolver::getGrammarPoolMemoryManager() const { return fGrammarPool->getMemoryManager(); } inline ValueVectorOf<SchemaGrammar*>* GrammarResolver::getGrammarsToAddToXSModel() { return fGrammarsToAddToXSModel; } XERCES_CPP_NAMESPACE_END #endif <commit_msg>Removed superfluous const qualifiers.<commit_after>/* * Copyright 2001,2004 The Apache Software Foundation. * * 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. */ /** * $Id$ */ #if !defined(GRAMMARRESOLVER_HPP) #define GRAMMARRESOLVER_HPP #include <xercesc/framework/XMLGrammarPool.hpp> #include <xercesc/util/RefHashTableOf.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/common/Grammar.hpp> XERCES_CPP_NAMESPACE_BEGIN class DatatypeValidator; class DatatypeValidatorFactory; class XMLGrammarDescription; /** * This class embodies the representation of a Grammar pool Resolver. * This class is called from the validator. * */ class VALIDATORS_EXPORT GrammarResolver : public XMemory { public: /** @name Constructor and Destructor */ //@{ /** * * Default Constructor */ GrammarResolver( XMLGrammarPool* const gramPool , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /** * Destructor */ ~GrammarResolver(); //@} /** @name Getter methods */ //@{ /** * Retrieve the DatatypeValidator * * @param uriStr the namespace URI * @param typeName the type name * @return the DatatypeValidator associated with namespace & type name */ DatatypeValidator* getDatatypeValidator(const XMLCh* const uriStr, const XMLCh* const typeName); /** * Retrieve the grammar that is associated with the specified namespace key * * @param gramDesc grammar description for the grammar * @return Grammar abstraction associated with the grammar description */ Grammar* getGrammar( XMLGrammarDescription* const gramDesc ) ; /** * Retrieve the grammar that is associated with the specified namespace key * * @param namespaceKey Namespace key into Grammar pool * @return Grammar abstraction associated with the NameSpace key. */ Grammar* getGrammar( const XMLCh* const namespaceKey ) ; /** * Get an enumeration of Grammar in the Grammar pool * * @return enumeration of Grammar in Grammar pool */ RefHashTableOfEnumerator<Grammar> getGrammarEnumerator() const; /** * Get an enumeration of the referenced Grammars * * @return enumeration of referenced Grammars */ RefHashTableOfEnumerator<Grammar> getReferencedGrammarEnumerator() const; /** * Get an enumeration of the cached Grammars in the Grammar pool * * @return enumeration of the cached Grammars in Grammar pool */ RefHashTableOfEnumerator<Grammar> getCachedGrammarEnumerator() const; /** * Get a string pool of schema grammar element/attribute names/prefixes * (used by TraverseSchema) * * @return a string pool of schema grammar element/attribute names/prefixes */ XMLStringPool* getStringPool(); /** * Is the specified Namespace key in Grammar pool? * * @param nameSpaceKey Namespace key * @return True if Namespace key association is in the Grammar pool. */ bool containsNameSpace( const XMLCh* const nameSpaceKey ); inline XMLGrammarPool* getGrammarPool() const; inline MemoryManager* getGrammarPoolMemoryManager() const; //@} /** @name Setter methods */ //@{ /** * Set the 'Grammar caching' flag */ void cacheGrammarFromParse(const bool newState); /** * Set the 'Use cached grammar' flag */ void useCachedGrammarInParse(const bool newState); //@} /** @name GrammarResolver methods */ //@{ /** * Add the Grammar with Namespace Key associated to the Grammar Pool. * The Grammar will be owned by the Grammar Pool. * * @param grammarToAdopt Grammar abstraction used by validator. */ void putGrammar(Grammar* const grammarToAdopt ); /** * Returns the Grammar with Namespace Key associated from the Grammar Pool * The Key entry is removed from the table (grammar is not deleted if * adopted - now owned by caller). * * @param nameSpaceKey Key to associate with Grammar abstraction */ Grammar* orphanGrammar(const XMLCh* const nameSpaceKey); /** * Cache the grammars in fGrammarBucket to fCachedGrammarRegistry. * If a grammar with the same key is already cached, an exception is * thrown and none of the grammars will be cached. */ void cacheGrammars(); /** * Reset internal Namespace/Grammar registry. */ void reset(); void resetCachedGrammar(); /** * Returns an XSModel, either from the GrammarPool or by creating one */ XSModel* getXSModel(); ValueVectorOf<SchemaGrammar*>* getGrammarsToAddToXSModel(); //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- GrammarResolver(const GrammarResolver&); GrammarResolver& operator=(const GrammarResolver&); // ----------------------------------------------------------------------- // Private data members // // fStringPool The string pool used by TraverseSchema to store // element/attribute names and prefixes. // Always owned by Grammar pool implementation // // fGrammarBucket The parsed Grammar Pool, if no caching option. // // fGrammarFromPool Referenced Grammar Set, not owned // // fGrammarPool The Grammar Set either plugged or created. // // fDataTypeReg DatatypeValidatorFactory registery // // fMemoryManager Pluggable memory manager for dynamic memory // allocation/deallocation // ----------------------------------------------------------------------- bool fCacheGrammar; bool fUseCachedGrammar; bool fGrammarPoolFromExternalApplication; XMLStringPool* fStringPool; RefHashTableOf<Grammar>* fGrammarBucket; RefHashTableOf<Grammar>* fGrammarFromPool; DatatypeValidatorFactory* fDataTypeReg; MemoryManager* fMemoryManager; XMLGrammarPool* fGrammarPool; XSModel* fXSModel; XSModel* fGrammarPoolXSModel; ValueVectorOf<SchemaGrammar*>* fGrammarsToAddToXSModel; }; inline XMLStringPool* GrammarResolver::getStringPool() { return fStringPool; } inline void GrammarResolver::useCachedGrammarInParse(const bool aValue) { fUseCachedGrammar = aValue; } inline XMLGrammarPool* GrammarResolver::getGrammarPool() const { return fGrammarPool; } inline MemoryManager* GrammarResolver::getGrammarPoolMemoryManager() const { return fGrammarPool->getMemoryManager(); } inline ValueVectorOf<SchemaGrammar*>* GrammarResolver::getGrammarsToAddToXSModel() { return fGrammarsToAddToXSModel; } XERCES_CPP_NAMESPACE_END #endif <|endoftext|>
<commit_before>/* * Copyright 2014 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. */ // Author: stevensr@google.com (Ryan Stevens) #include "net/instaweb/rewriter/public/decision_tree.h" #include <vector> #include <utility> #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/string.h" namespace net_instaweb { namespace { class DecisionTreeTest : public ::testing::Test { protected: typedef DecisionTree::Node Node; }; TEST_F(DecisionTreeTest, CreateTree) { const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 0.7, NULL, NULL}, // node 1, leaf {1, 30.0, -1.0, &nodes[3], &nodes[4]}, // node 2, inner {-1, -1.0, 1.0, NULL, NULL}, // node 3, leaf {-1, -1.0, 0.0, NULL, NULL} // node 4, leaf }; DecisionTree tree(nodes, arraysize(nodes)); EXPECT_EQ(tree.num_features(), 2); } TEST_F(DecisionTreeTest, PredictionTest) { // Build tree that looks like this: // X[0] <= 0.5 // / \ // / \ // X[2] <= 0.9 X[1] <= 30.0 // / \ / \ // / \ / \ // 0.4 0.2 1.0 0.0 const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[4]}, // node 0, inner {2, 0.9, -1.0, &nodes[2], &nodes[3]}, // node 1, inner {-1, -1.0, 0.4, NULL, NULL}, // node 2, leaf {-1, -1.0, 0.2, NULL, NULL}, // node 3, leaf {1, 30.0, -1.0, &nodes[5], &nodes[6]}, // node 4, inner {-1, -1.0, 1.0, NULL, NULL}, // node 5, leaf {-1, -1.0, 0.0, NULL, NULL} // node 6, leaf }; DecisionTree tree(nodes, arraysize(nodes)); std::vector<double> sample(3, 0.0); EXPECT_EQ(0.4, tree.Predict(sample)); sample[0] = 0.45; EXPECT_EQ(0.4, tree.Predict(sample)); sample[2] = 1.0; EXPECT_EQ(0.2, tree.Predict(sample)); sample[0] = 0.6; EXPECT_EQ(1.0, tree.Predict(sample)); sample[1] = 45.2; EXPECT_EQ(0.0, tree.Predict(sample)); } class DecisionTreeDeathTest : public DecisionTreeTest { protected: DecisionTreeDeathTest() { } }; TEST_F(DecisionTreeDeathTest, OneChildDeathTest) { const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 0.7, NULL, NULL}, // node 1, leaf {1, 30.0, -1.0, &nodes[3], NULL}, // node 2, inner {-1, -1.0, 1.0, NULL, NULL} // node 3, leaf }; int num_nodes = arraysize(nodes); ASSERT_DEATH(DecisionTree tree(nodes, num_nodes), "Inner node has one child"); } TEST_F(DecisionTreeDeathTest, UnreachableNodesDeathTest) { const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 0.7, NULL, NULL}, // node 1, leaf {-1, -1.0, 0.3, NULL, NULL}, // node 2, leaf {-1, -1.0, 1.0, NULL, NULL} // node 3, leaf }; int num_nodes = arraysize(nodes); ASSERT_DEATH(DecisionTree tree(nodes, num_nodes), "Unreachable nodes"); } TEST_F(DecisionTreeDeathTest, ExtraneousNodesDeathTest) { const Node extra_node = {-1, -1.0, 1.0, NULL, NULL}; const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 0.7, NULL, NULL}, // node 1, leaf {1, 0.1, -1.0, &nodes[3], &extra_node}, // node 2, inner {-1, -1.0, 1.0, NULL, NULL} // node 3, leaf }; int num_nodes = arraysize(nodes); ASSERT_DEATH(DecisionTree tree(nodes, num_nodes), "Extraneous nodes"); } TEST_F(DecisionTreeDeathTest, InvalidFeatureIndexDeathTest) { const Node nodes[] = { {-10, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 0.7, NULL, NULL}, // node 1, leaf {-1, -1.0, 0.3, NULL, NULL} // node 2, leaf }; int num_nodes = arraysize(nodes); ASSERT_DEATH(DecisionTree tree(nodes, num_nodes), "Invalid feature index"); } TEST_F(DecisionTreeDeathTest, InvalidConfidenceDeathTest) { const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 1.7, NULL, NULL}, // node 1, leaf {-1, -1.0, 0.3, NULL, NULL} // node 2, leaf }; int num_nodes = arraysize(nodes); ASSERT_DEATH(DecisionTree tree(nodes, num_nodes), "Invalid confidence 1.7"); } } // namespace } // namespace net_instaweb <commit_msg>Decision tree death tests were causing test failures when testing in release mode. Those tests are now only run while in debug mode.<commit_after>/* * Copyright 2014 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. */ // Author: stevensr@google.com (Ryan Stevens) #include "net/instaweb/rewriter/public/decision_tree.h" #include <vector> #include <utility> #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/string.h" namespace net_instaweb { namespace { class DecisionTreeTest : public ::testing::Test { protected: typedef DecisionTree::Node Node; }; TEST_F(DecisionTreeTest, CreateTree) { const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 0.7, NULL, NULL}, // node 1, leaf {1, 30.0, -1.0, &nodes[3], &nodes[4]}, // node 2, inner {-1, -1.0, 1.0, NULL, NULL}, // node 3, leaf {-1, -1.0, 0.0, NULL, NULL} // node 4, leaf }; DecisionTree tree(nodes, arraysize(nodes)); EXPECT_EQ(tree.num_features(), 2); } TEST_F(DecisionTreeTest, PredictionTest) { // Build tree that looks like this: // X[0] <= 0.5 // / \ // / \ // X[2] <= 0.9 X[1] <= 30.0 // / \ / \ // / \ / \ // 0.4 0.2 1.0 0.0 const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[4]}, // node 0, inner {2, 0.9, -1.0, &nodes[2], &nodes[3]}, // node 1, inner {-1, -1.0, 0.4, NULL, NULL}, // node 2, leaf {-1, -1.0, 0.2, NULL, NULL}, // node 3, leaf {1, 30.0, -1.0, &nodes[5], &nodes[6]}, // node 4, inner {-1, -1.0, 1.0, NULL, NULL}, // node 5, leaf {-1, -1.0, 0.0, NULL, NULL} // node 6, leaf }; DecisionTree tree(nodes, arraysize(nodes)); std::vector<double> sample(3, 0.0); EXPECT_EQ(0.4, tree.Predict(sample)); sample[0] = 0.45; EXPECT_EQ(0.4, tree.Predict(sample)); sample[2] = 1.0; EXPECT_EQ(0.2, tree.Predict(sample)); sample[0] = 0.6; EXPECT_EQ(1.0, tree.Predict(sample)); sample[1] = 45.2; EXPECT_EQ(0.0, tree.Predict(sample)); } // These test to ensure our sanity checking will reject invalid decision trees. // Because sanity checking is only enabled in debug mode, these tests are only // able to run in debug mode. #ifndef NDEBUG class DecisionTreeDeathTest : public DecisionTreeTest { protected: DecisionTreeDeathTest() { } }; TEST_F(DecisionTreeDeathTest, OneChildDeathTest) { const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 0.7, NULL, NULL}, // node 1, leaf {1, 30.0, -1.0, &nodes[3], NULL}, // node 2, inner {-1, -1.0, 1.0, NULL, NULL} // node 3, leaf }; int num_nodes = arraysize(nodes); ASSERT_DEATH(DecisionTree tree(nodes, num_nodes), "Inner node has one child"); } TEST_F(DecisionTreeDeathTest, UnreachableNodesDeathTest) { const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 0.7, NULL, NULL}, // node 1, leaf {-1, -1.0, 0.3, NULL, NULL}, // node 2, leaf {-1, -1.0, 1.0, NULL, NULL} // node 3, leaf }; int num_nodes = arraysize(nodes); ASSERT_DEATH(DecisionTree tree(nodes, num_nodes), "Unreachable nodes"); } TEST_F(DecisionTreeDeathTest, ExtraneousNodesDeathTest) { const Node extra_node = {-1, -1.0, 1.0, NULL, NULL}; const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 0.7, NULL, NULL}, // node 1, leaf {1, 0.1, -1.0, &nodes[3], &extra_node}, // node 2, inner {-1, -1.0, 1.0, NULL, NULL} // node 3, leaf }; int num_nodes = arraysize(nodes); ASSERT_DEATH(DecisionTree tree(nodes, num_nodes), "Extraneous nodes"); } TEST_F(DecisionTreeDeathTest, InvalidFeatureIndexDeathTest) { const Node nodes[] = { {-10, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 0.7, NULL, NULL}, // node 1, leaf {-1, -1.0, 0.3, NULL, NULL} // node 2, leaf }; int num_nodes = arraysize(nodes); ASSERT_DEATH(DecisionTree tree(nodes, num_nodes), "Invalid feature index"); } TEST_F(DecisionTreeDeathTest, InvalidConfidenceDeathTest) { const Node nodes[] = { {0, 0.5, -1.0, &nodes[1], &nodes[2]}, // node 0, inner {-1, -1.0, 1.7, NULL, NULL}, // node 1, leaf {-1, -1.0, 0.3, NULL, NULL} // node 2, leaf }; int num_nodes = arraysize(nodes); ASSERT_DEATH(DecisionTree tree(nodes, num_nodes), "Invalid confidence 1.7"); } #endif // NDEBUG } // namespace } // namespace net_instaweb <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_MAT_FUNCTOR_MAP_RECT_CONCURRENT_HPP #define STAN_MATH_REV_MAT_FUNCTOR_MAP_RECT_CONCURRENT_HPP #include <stan/math/prim/mat/fun/typedefs.hpp> #include <stan/math/prim/mat/functor/map_rect_reduce.hpp> #include <stan/math/prim/mat/functor/map_rect_combine.hpp> #include <stan/math/prim/scal/err/invalid_argument.hpp> #include <stan/math/rev/core/chainablestack.hpp> #include <vector> #include <thread> #include <future> namespace stan { namespace math { namespace internal { template <int call_id, typename F, typename T_shared_param, typename T_job_param> Eigen::Matrix<typename stan::return_type<T_shared_param, T_job_param>::type, Eigen::Dynamic, 1> map_rect_concurrent( const Eigen::Matrix<T_shared_param, Eigen::Dynamic, 1>& shared_params, const std::vector<Eigen::Matrix<T_job_param, Eigen::Dynamic, 1>>& job_params, const std::vector<std::vector<double>>& x_r, const std::vector<std::vector<int>>& x_i, std::ostream* msgs) { typedef map_rect_reduce<F, T_shared_param, T_job_param> ReduceF; typedef map_rect_combine<F, T_shared_param, T_job_param> CombineF; const int num_jobs = job_params.size(); const vector_d shared_params_dbl = value_of(shared_params); std::vector<std::future<std::vector<matrix_d>>> futures; auto execute_chunk = [&](int start, int size) -> std::vector<matrix_d> { #ifdef STAN_THREADS ChainableStack thread_stack_instance; #endif const int end = start + size; std::vector<matrix_d> chunk_f_out; chunk_f_out.reserve(size); for (int i = start; i != end; i++) chunk_f_out.push_back(ReduceF()( shared_params_dbl, value_of(job_params[i]), x_r[i], x_i[i], msgs)); return chunk_f_out; }; int num_threads = get_num_threads(num_jobs); int num_jobs_per_thread = num_jobs / num_threads; futures.emplace_back( std::async(std::launch::deferred, execute_chunk, 0, num_jobs_per_thread)); #ifdef STAN_THREADS if (num_threads > 1) { const int num_big_threads = num_jobs % num_threads; const int first_big_thread = num_threads - num_big_threads; for (int i = 1, job_start = num_jobs_per_thread, job_size = 0; i < num_threads; ++i, job_start += job_size) { job_size = i >= first_big_thread ? num_jobs_per_thread + 1 : num_jobs_per_thread; futures.emplace_back( std::async(std::launch::async, execute_chunk, job_start, job_size)); } } #endif // collect results std::vector<int> world_f_out; world_f_out.reserve(num_jobs); matrix_d world_output(0, 0); int offset = 0; for (std::size_t i = 0; i < futures.size(); ++i) { const std::vector<matrix_d>& chunk_result = futures[i].get(); if (i == 0) world_output.resize(chunk_result[0].rows(), num_jobs * chunk_result[0].cols()); for (const auto& job_result : chunk_result) { const int num_job_outputs = job_result.cols(); world_f_out.push_back(num_job_outputs); if (world_output.cols() < offset + num_job_outputs) world_output.conservativeResize(Eigen::NoChange, 2 * (offset + num_job_outputs)); world_output.block(0, offset, world_output.rows(), num_job_outputs) = job_result; offset += num_job_outputs; } } CombineF combine(shared_params, job_params); return combine(world_output, world_f_out); } } // namespace internal } // namespace math } // namespace stan #endif <commit_msg>headers<commit_after>#ifndef STAN_MATH_REV_MAT_FUNCTOR_MAP_RECT_CONCURRENT_HPP #define STAN_MATH_REV_MAT_FUNCTOR_MAP_RECT_CONCURRENT_HPP #include <stan/math/prim/mat/fun/typedefs.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/mat/functor/map_rect_concurrent.hpp> #include <stan/math/prim/mat/functor/map_rect_reduce.hpp> #include <stan/math/prim/mat/functor/map_rect_combine.hpp> #include <stan/math/rev/core/chainablestack.hpp> #include <vector> #include <thread> #include <future> namespace stan { namespace math { namespace internal { template <int call_id, typename F, typename T_shared_param, typename T_job_param> Eigen::Matrix<typename stan::return_type<T_shared_param, T_job_param>::type, Eigen::Dynamic, 1> map_rect_concurrent( const Eigen::Matrix<T_shared_param, Eigen::Dynamic, 1>& shared_params, const std::vector<Eigen::Matrix<T_job_param, Eigen::Dynamic, 1>>& job_params, const std::vector<std::vector<double>>& x_r, const std::vector<std::vector<int>>& x_i, std::ostream* msgs) { typedef map_rect_reduce<F, T_shared_param, T_job_param> ReduceF; typedef map_rect_combine<F, T_shared_param, T_job_param> CombineF; const int num_jobs = job_params.size(); const vector_d shared_params_dbl = value_of(shared_params); std::vector<std::future<std::vector<matrix_d>>> futures; auto execute_chunk = [&](int start, int size) -> std::vector<matrix_d> { #ifdef STAN_THREADS ChainableStack thread_stack_instance; #endif const int end = start + size; std::vector<matrix_d> chunk_f_out; chunk_f_out.reserve(size); for (int i = start; i != end; i++) chunk_f_out.push_back(ReduceF()( shared_params_dbl, value_of(job_params[i]), x_r[i], x_i[i], msgs)); return chunk_f_out; }; int num_threads = get_num_threads(num_jobs); int num_jobs_per_thread = num_jobs / num_threads; futures.emplace_back( std::async(std::launch::deferred, execute_chunk, 0, num_jobs_per_thread)); #ifdef STAN_THREADS if (num_threads > 1) { const int num_big_threads = num_jobs % num_threads; const int first_big_thread = num_threads - num_big_threads; for (int i = 1, job_start = num_jobs_per_thread, job_size = 0; i < num_threads; ++i, job_start += job_size) { job_size = i >= first_big_thread ? num_jobs_per_thread + 1 : num_jobs_per_thread; futures.emplace_back( std::async(std::launch::async, execute_chunk, job_start, job_size)); } } #endif // collect results std::vector<int> world_f_out; world_f_out.reserve(num_jobs); matrix_d world_output(0, 0); int offset = 0; for (std::size_t i = 0; i < futures.size(); ++i) { const std::vector<matrix_d>& chunk_result = futures[i].get(); if (i == 0) world_output.resize(chunk_result[0].rows(), num_jobs * chunk_result[0].cols()); for (const auto& job_result : chunk_result) { const int num_job_outputs = job_result.cols(); world_f_out.push_back(num_job_outputs); if (world_output.cols() < offset + num_job_outputs) world_output.conservativeResize(Eigen::NoChange, 2 * (offset + num_job_outputs)); world_output.block(0, offset, world_output.rows(), num_job_outputs) = job_result; offset += num_job_outputs; } } CombineF combine(shared_params, job_params); return combine(world_output, world_f_out); } } // namespace internal } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>//MIT License // //Copyright(c) 2016 Matthias Moeller // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files(the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and / or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions : // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. #ifndef __TYTI_STEAM_VDF_PARSER_H__ #define __TYTI_STEAM_VDF_PARSER_H__ #include <unordered_map> #include <utility> #include <fstream> #include <memory> //for wstring support #include <locale> #include <codecvt> #include <string> // internal #include <stack> namespace tyti { namespace vdf { namespace detail { /////////////////////////////////////////////////////////////////////////// // Helper functions selecting the right encoding (char/wchar_T) /////////////////////////////////////////////////////////////////////////// template<typename T> struct literal_macro_help { static constexpr const char* result(const char* c, const wchar_t* wc) noexcept { return c; } static constexpr const char result(char c, wchar_t wc) noexcept { return c; } }; template<> struct literal_macro_help<wchar_t> { static constexpr const wchar_t* result(const char* c, const wchar_t* wc) noexcept { return wc; } static constexpr const wchar_t result(char c, wchar_t wc) noexcept { return wc; } }; #define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text) inline std::string string_converter(std::string& w) { return w; } inline std::string string_converter(std::wstring& w) { std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1; // maybe wrong econding return conv1.to_bytes(w); } /////////////////////////////////////////////////////////////////////////// // Writer helper functions /////////////////////////////////////////////////////////////////////////// struct tabs { size_t t; tabs(size_t i) :t(i) {} }; template<typename oStreamT> oStreamT& operator<<(oStreamT& s, tabs t) { for (; t.t > 0; --t.t) s << "\t"; return s; } } // end namespace detail /////////////////////////////////////////////////////////////////////////// // Interface /////////////////////////////////////////////////////////////////////////// /// basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens template<typename CharT> struct basic_object { typedef CharT char_type; std::basic_string<char_type> name; std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type> > attribs; std::unordered_map<std::basic_string<char_type>, std::shared_ptr< basic_object<char_type> > > childs; }; typedef basic_object<char> object; typedef basic_object<wchar_t> wobject; /** \brief writes given object tree in vdf format to given stream. Uses tabs instead of whitespaces. */ template<typename oStreamT, typename charT = typename oStreamT::char_type> void write(oStreamT& s, const basic_object<charT>& r, size_t t = 0) { using namespace detail; s << tabs(t) << TYTI_L(charT, '"') << r.name << TYTI_L(charT, "\"\n") << tabs(t) << TYTI_L(charT, "{\n"); for (auto& i : r.attribs) s << tabs(t + 1) << TYTI_L(charT, '"') << i.first << TYTI_L(charT, "\"\t\t\"") << i.second << TYTI_L(charT, "\"\n"); for (auto& i : r.childs) write(s, i, t + 1); s << tabs(t) << TYTI_L(charT, "}\n"); } class parser_error : public std::exception { }; //forward decl template<typename iStreamT, typename charT = typename iStreamT::char_type > basic_object<charT> read(iStreamT& inStream, bool *ok = 0); /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator @param ok output bool. true, if parser successed, false, if parser failed */ template<typename IterT, typename charT = typename IterT::value_type> basic_object<charT> read(IterT first, IterT last, bool* ok = 0) { //todo: error handling if (ok) *ok = true; basic_object<charT> root; basic_object<charT>* cur = &root; std::stack< basic_object<charT>* > lvls; //read header // first, quoted name auto b = std::find(first, last, TYTI_L(charT, '\"')); auto bend = std::find(b + 1, last, TYTI_L(charT, '\"')); root.name = std::basic_string<charT>(b + 1, bend); // second, get {} b = std::find(bend, last, TYTI_L(charT, '{')); if (b == last) if (ok) *ok = false; else throw parser_error(); else lvls.push(&root); try { while (!lvls.empty() && b != last) { const std::basic_string<charT> startsym = TYTI_L(charT, "\"}"); //find first starting attrib/child, or ending b = std::find_first_of(b, last, std::cbegin(startsym), std::cend(startsym)); if (*b == '\"') { bend = std::find(b + 1, last, TYTI_L(charT, '\"')); if (bend == last) throw parser_error(); // could not find end of name std::basic_string<charT> curName(b + 1, bend); b = bend + 1; const std::basic_string<charT> ecspsym = TYTI_L(charT, "\"{"); b = std::find_first_of(b, last, std::cbegin(ecspsym), std::cend(ecspsym)); if (b == last) throw parser_error(); //could not find 2nd part of pair if (*b == '\"') { bend = std::find(b + 1, last, TYTI_L(charT, '\"')); if (bend == last) throw parser_error(); //could not find end of name auto value = std::basic_string<charT>(b + 1, bend); b = bend + 1; if (curName != TYTI_L(charT, "#include") && curName != TYTI_L(charT, "#base")) cur->attribs[curName] = value; else { std::basic_ifstream<charT> i(detail::string_converter(value)); auto n = std::make_shared<basic_object<charT>>(read(i, ok)); cur->childs[n->name] = n; } } else if (*b == '{') { lvls.push(cur); auto n = std::make_shared<basic_object<charT>>(); cur->childs[curName] = n; cur = n.get(); cur->name = curName; ++b; } } else if (*b == '}') { cur = lvls.top(); lvls.pop(); ++b; } } } catch (parser_error& p) { if (ok) *ok = false; else throw p; } return root; } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. */ template<typename iStreamT, typename charT> basic_object<charT> read(iStreamT& inStream, bool *ok) { // cache the file std::basic_string<charT> str; inStream.seekg(0, std::ios::end); str.resize(inStream.tellg()); if (str.empty()) return basic_object<charT>(); inStream.seekg(0, std::ios::beg); inStream.read(&str[0], str.size()); inStream.close(); // parse it return read(str.begin(), str.end(), ok); } } // end namespace vdf } // end namespace tyti #ifndef TYTI_NO_L_UNDEF #undef TYTI_L #endif #endif //__TYTI_STEAM_VDF_PARSER_H__<commit_msg>Update vdf_parser.hpp<commit_after>//MIT License // //Copyright(c) 2016 Matthias Moeller // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files(the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and / or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions : // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. #ifndef __TYTI_STEAM_VDF_PARSER_H__ #define __TYTI_STEAM_VDF_PARSER_H__ #include <unordered_map> #include <utility> #include <fstream> #include <memory> //for wstring support #include <locale> #include <codecvt> #include <string> // internal #include <stack> namespace tyti { namespace vdf { namespace detail { /////////////////////////////////////////////////////////////////////////// // Helper functions selecting the right encoding (char/wchar_T) /////////////////////////////////////////////////////////////////////////// template<typename T> struct literal_macro_help { static constexpr const char* result(const char* c, const wchar_t* wc) noexcept { return c; } static constexpr const char result(char c, wchar_t wc) noexcept { return c; } }; template<> struct literal_macro_help<wchar_t> { static constexpr const wchar_t* result(const char* c, const wchar_t* wc) noexcept { return wc; } static constexpr const wchar_t result(char c, wchar_t wc) noexcept { return wc; } }; #define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text) inline std::string string_converter(std::string& w) { return w; } inline std::string string_converter(std::wstring& w) { std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1; // maybe wrong econding return conv1.to_bytes(w); } /////////////////////////////////////////////////////////////////////////// // Writer helper functions /////////////////////////////////////////////////////////////////////////// struct tabs { size_t t; tabs(size_t i) :t(i) {} }; template<typename oStreamT> oStreamT& operator<<(oStreamT& s, tabs t) { for (; t.t > 0; --t.t) s << "\t"; return s; } } // end namespace detail /////////////////////////////////////////////////////////////////////////// // Interface /////////////////////////////////////////////////////////////////////////// /// basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens template<typename CharT> struct basic_object { typedef CharT char_type; std::basic_string<char_type> name; std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type> > attribs; std::unordered_map<std::basic_string<char_type>, std::shared_ptr< basic_object<char_type> > > childs; }; typedef basic_object<char> object; typedef basic_object<wchar_t> wobject; /** \brief writes given object tree in vdf format to given stream. Uses tabs instead of whitespaces. */ template<typename oStreamT, typename charT = typename oStreamT::char_type> void write(oStreamT& s, const basic_object<charT>& r, size_t t = 0) { using namespace detail; s << tabs(t) << TYTI_L(charT, '"') << r.name << TYTI_L(charT, "\"\n") << tabs(t) << TYTI_L(charT, "{\n"); for (auto& i : r.attribs) s << tabs(t + 1) << TYTI_L(charT, '"') << i.first << TYTI_L(charT, "\"\t\t\"") << i.second << TYTI_L(charT, "\"\n"); for (auto& i : r.childs) write(s, i, t + 1); s << tabs(t) << TYTI_L(charT, "}\n"); } class parser_error : public std::exception { }; //forward decl template<typename iStreamT, typename charT = typename iStreamT::char_type > basic_object<charT> read(iStreamT& inStream, bool *ok = 0); /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator @param ok output bool. true, if parser successed, false, if parser failed */ template<typename IterT, typename charT = typename IterT::value_type> basic_object<charT> read(IterT first, IterT last, bool* ok = 0) { //todo: error handling if (ok) *ok = true; basic_object<charT> root; basic_object<charT>* cur = &root; std::stack< basic_object<charT>* > lvls; //read header // first, quoted name auto b = std::find(first, last, TYTI_L(charT, '\"')); auto bend = std::find(b + 1, last, TYTI_L(charT, '\"')); root.name = std::basic_string<charT>(b + 1, bend); // second, get {} b = std::find(bend, last, TYTI_L(charT, '{')); if (b == last) if (ok) *ok = false; else throw parser_error(); else lvls.push(&root); try { while (!lvls.empty() && b != last) { const std::basic_string<charT> startsym = TYTI_L(charT, "\"}"); //find first starting attrib/child, or ending b = std::find_first_of(b, last, std::cbegin(startsym), std::cend(startsym)); if (*b == '\"') { bend = std::find(b + 1, last, TYTI_L(charT, '\"')); if (bend == last) throw parser_error(); // could not find end of name std::basic_string<charT> curName(b + 1, bend); b = bend + 1; const std::basic_string<charT> ecspsym = TYTI_L(charT, "\"{"); b = std::find_first_of(b, last, std::cbegin(ecspsym), std::cend(ecspsym)); if (b == last) throw parser_error(); //could not find 2nd part of pair if (*b == '\"') { bend = std::find(b + 1, last, TYTI_L(charT, '\"')); if (bend == last) throw parser_error(); //could not find end of name auto value = std::basic_string<charT>(b + 1, bend); b = bend + 1; if (curName != TYTI_L(charT, "#include") && curName != TYTI_L(charT, "#base")) cur->attribs[curName] = value; else { std::basic_ifstream<charT> i(detail::string_converter(value)); auto n = std::make_shared<basic_object<charT>>(read(i, ok)); cur->childs[n->name] = n; } } else if (*b == '{') { lvls.push(cur); auto n = std::make_shared<basic_object<charT>>(); cur->childs[curName] = n; cur = n.get(); cur->name = curName; ++b; } } else if (*b == '}') { cur = lvls.top(); lvls.pop(); ++b; } } } catch (parser_error& p) { if (ok) *ok = false; else throw p; } return root; } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. */ template<typename iStreamT, typename charT> basic_object<charT> read(iStreamT& inStream, bool *ok) { // cache the file std::basic_string<charT> str; inStream.seekg(0, std::ios::end); str.resize(static_cast<size_t>(inStream.tellg())); if (str.empty()) return basic_object<charT>(); inStream.seekg(0, std::ios::beg); inStream.read(&str[0], str.size()); inStream.close(); // parse it return read(str.begin(), str.end(), ok); } } // end namespace vdf } // end namespace tyti #ifndef TYTI_NO_L_UNDEF #undef TYTI_L #endif #endif //__TYTI_STEAM_VDF_PARSER_H__ <|endoftext|>
<commit_before>/* Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com> Copyright (C) 2011 Dario Freddi <dario.freddi@collabora.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact-request-handler.h" #include <TelepathyQt4/Connection> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/PendingOperation> #include <TelepathyQt4/Account> #include <KTelepathy/error-dictionary.h> #include <QtCore/QFutureWatcher> #include <KDebug> #include <KGlobal> #include <KAboutData> #include <KMenu> #include <KAction> #include <KStatusNotifierItem> Q_DECLARE_METATYPE(Tp::ContactPtr) bool kde_tp_filter_contacts_by_publication_status(const Tp::ContactPtr &contact) { return contact->publishState() == Tp::Contact::PresenceStateAsk; } ContactRequestHandler::ContactRequestHandler(const Tp::AccountManagerPtr& am, QObject *parent) : QObject(parent) { m_accountManager = am; connect(m_accountManager.data(), SIGNAL(newAccount(Tp::AccountPtr)), this, SLOT(onNewAccountAdded(Tp::AccountPtr))); QList<Tp::AccountPtr> accounts = m_accountManager->allAccounts(); Q_FOREACH(const Tp::AccountPtr &account, accounts) { onNewAccountAdded(account); } m_noContactsAction = new KAction(i18n("No pending contact requests at the moment"), this); m_noContactsAction->setEnabled(false); } ContactRequestHandler::~ContactRequestHandler() { } void ContactRequestHandler::onNewAccountAdded(const Tp::AccountPtr& account) { kWarning(); Q_ASSERT(account->isReady(Tp::Account::FeatureCore)); if (account->connection()) { monitorPresence(account->connection()); } connect(account.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), this, SLOT(onConnectionChanged(Tp::ConnectionPtr))); } void ContactRequestHandler::onConnectionChanged(const Tp::ConnectionPtr& connection) { if (!connection.isNull()) { monitorPresence(connection); } } void ContactRequestHandler::monitorPresence(const Tp::ConnectionPtr &connection) { kDebug(); connect(connection->contactManager().data(), SIGNAL(presencePublicationRequested(Tp::Contacts)), this, SLOT(onPresencePublicationRequested(Tp::Contacts))); connect(connection->contactManager().data(), SIGNAL(stateChanged(Tp::ContactListState)), this, SLOT(onContactManagerStateChanged(Tp::ContactListState))); onContactManagerStateChanged(connection->contactManager(), connection->contactManager()->state()); } void ContactRequestHandler::onContactManagerStateChanged(Tp::ContactListState state) { onContactManagerStateChanged(Tp::ContactManagerPtr(qobject_cast< Tp::ContactManager* >(sender())), state); } void ContactRequestHandler::onContactManagerStateChanged(const Tp::ContactManagerPtr &contactManager, Tp::ContactListState state) { if (state == Tp::ContactListStateSuccess) { QFutureWatcher< Tp::ContactPtr > *watcher = new QFutureWatcher< Tp::ContactPtr >(this); connect(watcher, SIGNAL(finished()), this, SLOT(onAccountsPresenceStatusFiltered())); watcher->setFuture(QtConcurrent::filtered(contactManager->allKnownContacts(), kde_tp_filter_contacts_by_publication_status)); kDebug() << "Watcher is on"; } else { kDebug() << "Watcher still off, state is" << state << "contactManager is" << contactManager.isNull(); } } void ContactRequestHandler::onAccountsPresenceStatusFiltered() { kDebug() << "Watcher is here"; QFutureWatcher< Tp::ContactPtr > *watcher = dynamic_cast< QFutureWatcher< Tp::ContactPtr > * >(sender()); kDebug() << "Watcher is casted"; Tp::Contacts contacts = watcher->future().results().toSet(); kDebug() << "Watcher is used"; if (!contacts.isEmpty()) { onPresencePublicationRequested(contacts); } watcher->deleteLater(); } void ContactRequestHandler::onPresencePublicationRequested(const Tp::Contacts& contacts) { kDebug() << "New contact requested"; Q_FOREACH (const Tp::ContactPtr &contact, contacts) { Tp::ContactManagerPtr manager = contact->manager(); Tp::PendingOperation *op = 0; if (contact->subscriptionState() == Tp::Contact::PresenceStateYes) { op = manager->authorizePresencePublication(QList< Tp::ContactPtr >() << contact); op->setProperty("__contact", QVariant::fromValue(contact)); connect(op, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onFinalizeSubscriptionFinished(Tp::PendingOperation*))); } else { m_pendingContacts.insert(contact->id(), contact); updateMenus(); m_notifierItem.data()->showMessage(i18n("New contact request"), i18n("The contact %1 added you to its contact list", contact->id()), QLatin1String("list-add-user")); } } } void ContactRequestHandler::onFinalizeSubscriptionFinished(Tp::PendingOperation *op) { Tp::ContactPtr contact = op->property("__contact").value< Tp::ContactPtr >(); if (op->isError()) { // ARGH m_notifierItem.data()->showMessage(i18n("Error adding contact"), i18n("%1 has been added successfully to your contact list, " "but might be unable to see your presence. Error details: %2", contact->alias(), KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())), QLatin1String("dialog-error")); } else { // Yeah. All fine, so don't notify } } void ContactRequestHandler::updateNotifierItemTooltip() { if (!m_menuItems.size()) { // Set passive m_notifierItem.data()->setStatus(KStatusNotifierItem::Passive); // Add the usual "nothing" action, if needed if (!m_notifierMenu->actions().contains(m_noContactsAction)) { m_notifierMenu->addAction(m_noContactsAction); } m_notifierItem.data()->setToolTip(QLatin1String("list-add-user"), i18n("No incoming contact requests"), QString()); } else { // Set active m_notifierItem.data()->setStatus(KStatusNotifierItem::Active); // Remove the "nothing" action, if needed if (m_notifierMenu->actions().contains(m_noContactsAction)) { m_notifierMenu->removeAction(m_noContactsAction); } m_notifierItem.data()->setToolTip(QLatin1String("list-add-user"), i18np("You have 1 incoming contact request", "You have %1 incoming contact requests", m_menuItems.size()), QString()); } } void ContactRequestHandler::onContactRequestApproved() { QString contactId = qobject_cast<KAction*>(sender())->data().toString(); if (!contactId.isEmpty()) { Tp::ContactPtr contact = m_pendingContacts.value(contactId); if (!contact.isNull()) { Tp::PendingOperation *op = contact->manager()->authorizePresencePublication(QList< Tp::ContactPtr >() << contact); op->setProperty("__contact", QVariant::fromValue(contact)); connect (op, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAuthorizePresencePublicationFinished(Tp::PendingOperation*))); } } } void ContactRequestHandler::onAuthorizePresencePublicationFinished(Tp::PendingOperation *op) { Tp::ContactPtr contact = op->property("__contact").value< Tp::ContactPtr >(); if (op->isError()) { // ARGH m_notifierItem.data()->showMessage(i18n("Error accepting contact request"), i18n("There was an error while accepting the request: %1", KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())), QLatin1String("dialog-error")); // Re-enable the action m_menuItems.value(contact->id())->setEnabled(true); } else { // Yeah m_notifierItem.data()->showMessage(i18n("Contact request accepted"), i18n("%1 will now be able to see your presence", contact->alias()), QLatin1String("dialog-ok-apply")); // If needed, reiterate the request on the other end if (contact->manager()->canRequestPresenceSubscription() && contact->subscriptionState() == Tp::Contact::PresenceStateNo) { contact->manager()->requestPresenceSubscription(QList< Tp::ContactPtr >() << contact); } // Update the menu m_pendingContacts.remove(contact->id()); updateMenus(); } } void ContactRequestHandler::onContactRequestDenied() { QString contactId = qobject_cast<KAction*>(sender())->data().toString(); // Disable the action in the meanwhile m_menuItems.value(contactId)->setEnabled(false); if (!contactId.isEmpty()) { Tp::ContactPtr contact = m_pendingContacts.value(contactId); if (!contact.isNull()) { Tp::PendingOperation *op = contact->manager()->removePresencePublication(QList< Tp::ContactPtr >() << contact); op->setProperty("__contact", QVariant::fromValue(contact)); connect(op, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onRemovePresencePublicationFinished(Tp::PendingOperation*))); } } } void ContactRequestHandler::onRemovePresencePublicationFinished(Tp::PendingOperation *op) { Tp::ContactPtr contact = op->property("__contact").value< Tp::ContactPtr >(); if (op->isError()) { // ARGH m_notifierItem.data()->showMessage(i18n("Error denying contact request"), i18n("There was an error while denying the request: %1", KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())), QLatin1String("dialog-error")); // Re-enable the action m_menuItems.value(contact->id())->setEnabled(true); } else { // Yeah m_notifierItem.data()->showMessage(i18n("Contact request denied"), i18n("%1 will not be able to see your presence", contact->alias()), QLatin1String("dialog-ok-apply")); // Update the menu m_pendingContacts.remove(contact->id()); updateMenus(); } } void ContactRequestHandler::updateMenus() { if (m_notifierItem.isNull()) { m_notifierItem = new KStatusNotifierItem(QLatin1String("telepathy_kde_contact_requests"), this); m_notifierItem.data()->setCategory(KStatusNotifierItem::Communications); m_notifierItem.data()->setStatus(KStatusNotifierItem::NeedsAttention); m_notifierItem.data()->setIconByName(QLatin1String("user-identity")); m_notifierItem.data()->setAttentionIconByName(QLatin1String("list-add-user")); m_notifierItem.data()->setStandardActionsEnabled(false); m_notifierMenu = new KMenu(0); m_notifierMenu->addTitle(i18nc("Context menu title", "Received contact requests")); m_notifierItem.data()->setContextMenu(m_notifierMenu); } kDebug() << m_pendingContacts.keys(); QHash<QString, Tp::ContactPtr>::const_iterator i; for (i = m_pendingContacts.constBegin(); i != m_pendingContacts.constEnd(); ++i) { if (m_menuItems.contains(i.key())) { // Skip continue; } kDebug(); Tp::ContactPtr contact = i.value(); KMenu *contactMenu = new KMenu(m_notifierMenu); contactMenu->setTitle(i18n("Request from %1", contact->alias())); contactMenu->setObjectName(contact->id()); KAction *menuAction; if (!contact->publishStateMessage().isEmpty()) { contactMenu->addTitle(contact->publishStateMessage()); } else { contactMenu->addTitle(contact->alias()); } menuAction = new KAction(KIcon(QLatin1String("dialog-ok-apply")), i18n("Approve"), contactMenu); menuAction->setData(i.key()); connect(menuAction, SIGNAL(triggered()), this, SLOT(onContactRequestApproved())); contactMenu->addAction(menuAction); menuAction = new KAction(KIcon(QLatin1String("dialog-close")), i18n("Deny"), contactMenu); menuAction->setData(i.key()); connect(menuAction, SIGNAL(triggered()), this, SLOT(onContactRequestDenied())); contactMenu->addAction(menuAction); m_notifierMenu->addMenu(contactMenu); m_menuItems.insert(i.key(), contactMenu); } QHash<QString, KMenu*>::iterator j = m_menuItems.begin(); while (j != m_menuItems.end()) { if (m_pendingContacts.contains(j.key())) { // Skip ++j; continue; } // Remove m_notifierMenu->removeAction(j.value()->menuAction()); j = m_menuItems.erase(j); } updateNotifierItemTooltip(); } #include "contact-request-handler.moc" <commit_msg>Remove redundant init<commit_after>/* Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com> Copyright (C) 2011 Dario Freddi <dario.freddi@collabora.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact-request-handler.h" #include <TelepathyQt4/Connection> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/PendingOperation> #include <TelepathyQt4/Account> #include <KTelepathy/error-dictionary.h> #include <QtCore/QFutureWatcher> #include <KDebug> #include <KGlobal> #include <KAboutData> #include <KMenu> #include <KAction> #include <KStatusNotifierItem> Q_DECLARE_METATYPE(Tp::ContactPtr) bool kde_tp_filter_contacts_by_publication_status(const Tp::ContactPtr &contact) { return contact->publishState() == Tp::Contact::PresenceStateAsk; } ContactRequestHandler::ContactRequestHandler(const Tp::AccountManagerPtr& am, QObject *parent) : QObject(parent) { m_accountManager = am; connect(m_accountManager.data(), SIGNAL(newAccount(Tp::AccountPtr)), this, SLOT(onNewAccountAdded(Tp::AccountPtr))); QList<Tp::AccountPtr> accounts = m_accountManager->allAccounts(); Q_FOREACH(const Tp::AccountPtr &account, accounts) { onNewAccountAdded(account); } m_noContactsAction = new KAction(i18n("No pending contact requests at the moment"), this); m_noContactsAction->setEnabled(false); } ContactRequestHandler::~ContactRequestHandler() { } void ContactRequestHandler::onNewAccountAdded(const Tp::AccountPtr& account) { kWarning(); Q_ASSERT(account->isReady(Tp::Account::FeatureCore)); if (account->connection()) { monitorPresence(account->connection()); } connect(account.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), this, SLOT(onConnectionChanged(Tp::ConnectionPtr))); } void ContactRequestHandler::onConnectionChanged(const Tp::ConnectionPtr& connection) { if (!connection.isNull()) { monitorPresence(connection); } } void ContactRequestHandler::monitorPresence(const Tp::ConnectionPtr &connection) { kDebug(); connect(connection->contactManager().data(), SIGNAL(presencePublicationRequested(Tp::Contacts)), this, SLOT(onPresencePublicationRequested(Tp::Contacts))); connect(connection->contactManager().data(), SIGNAL(stateChanged(Tp::ContactListState)), this, SLOT(onContactManagerStateChanged(Tp::ContactListState))); onContactManagerStateChanged(connection->contactManager(), connection->contactManager()->state()); } void ContactRequestHandler::onContactManagerStateChanged(Tp::ContactListState state) { onContactManagerStateChanged(Tp::ContactManagerPtr(qobject_cast< Tp::ContactManager* >(sender())), state); } void ContactRequestHandler::onContactManagerStateChanged(const Tp::ContactManagerPtr &contactManager, Tp::ContactListState state) { if (state == Tp::ContactListStateSuccess) { QFutureWatcher< Tp::ContactPtr > *watcher = new QFutureWatcher< Tp::ContactPtr >(this); connect(watcher, SIGNAL(finished()), this, SLOT(onAccountsPresenceStatusFiltered())); watcher->setFuture(QtConcurrent::filtered(contactManager->allKnownContacts(), kde_tp_filter_contacts_by_publication_status)); kDebug() << "Watcher is on"; } else { kDebug() << "Watcher still off, state is" << state << "contactManager is" << contactManager.isNull(); } } void ContactRequestHandler::onAccountsPresenceStatusFiltered() { kDebug() << "Watcher is here"; QFutureWatcher< Tp::ContactPtr > *watcher = dynamic_cast< QFutureWatcher< Tp::ContactPtr > * >(sender()); kDebug() << "Watcher is casted"; Tp::Contacts contacts = watcher->future().results().toSet(); kDebug() << "Watcher is used"; if (!contacts.isEmpty()) { onPresencePublicationRequested(contacts); } watcher->deleteLater(); } void ContactRequestHandler::onPresencePublicationRequested(const Tp::Contacts& contacts) { kDebug() << "New contact requested"; Q_FOREACH (const Tp::ContactPtr &contact, contacts) { Tp::ContactManagerPtr manager = contact->manager(); if (contact->subscriptionState() == Tp::Contact::PresenceStateYes) { Tp::PendingOperation *op = manager->authorizePresencePublication(QList< Tp::ContactPtr >() << contact); op->setProperty("__contact", QVariant::fromValue(contact)); connect(op, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onFinalizeSubscriptionFinished(Tp::PendingOperation*))); } else { m_pendingContacts.insert(contact->id(), contact); updateMenus(); m_notifierItem.data()->showMessage(i18n("New contact request"), i18n("The contact %1 added you to its contact list", contact->id()), QLatin1String("list-add-user")); } } } void ContactRequestHandler::onFinalizeSubscriptionFinished(Tp::PendingOperation *op) { Tp::ContactPtr contact = op->property("__contact").value< Tp::ContactPtr >(); if (op->isError()) { // ARGH m_notifierItem.data()->showMessage(i18n("Error adding contact"), i18n("%1 has been added successfully to your contact list, " "but might be unable to see your presence. Error details: %2", contact->alias(), KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())), QLatin1String("dialog-error")); } else { // Yeah. All fine, so don't notify } } void ContactRequestHandler::updateNotifierItemTooltip() { if (!m_menuItems.size()) { // Set passive m_notifierItem.data()->setStatus(KStatusNotifierItem::Passive); // Add the usual "nothing" action, if needed if (!m_notifierMenu->actions().contains(m_noContactsAction)) { m_notifierMenu->addAction(m_noContactsAction); } m_notifierItem.data()->setToolTip(QLatin1String("list-add-user"), i18n("No incoming contact requests"), QString()); } else { // Set active m_notifierItem.data()->setStatus(KStatusNotifierItem::Active); // Remove the "nothing" action, if needed if (m_notifierMenu->actions().contains(m_noContactsAction)) { m_notifierMenu->removeAction(m_noContactsAction); } m_notifierItem.data()->setToolTip(QLatin1String("list-add-user"), i18np("You have 1 incoming contact request", "You have %1 incoming contact requests", m_menuItems.size()), QString()); } } void ContactRequestHandler::onContactRequestApproved() { QString contactId = qobject_cast<KAction*>(sender())->data().toString(); if (!contactId.isEmpty()) { Tp::ContactPtr contact = m_pendingContacts.value(contactId); if (!contact.isNull()) { Tp::PendingOperation *op = contact->manager()->authorizePresencePublication(QList< Tp::ContactPtr >() << contact); op->setProperty("__contact", QVariant::fromValue(contact)); connect (op, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAuthorizePresencePublicationFinished(Tp::PendingOperation*))); } } } void ContactRequestHandler::onAuthorizePresencePublicationFinished(Tp::PendingOperation *op) { Tp::ContactPtr contact = op->property("__contact").value< Tp::ContactPtr >(); if (op->isError()) { // ARGH m_notifierItem.data()->showMessage(i18n("Error accepting contact request"), i18n("There was an error while accepting the request: %1", KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())), QLatin1String("dialog-error")); // Re-enable the action m_menuItems.value(contact->id())->setEnabled(true); } else { // Yeah m_notifierItem.data()->showMessage(i18n("Contact request accepted"), i18n("%1 will now be able to see your presence", contact->alias()), QLatin1String("dialog-ok-apply")); // If needed, reiterate the request on the other end if (contact->manager()->canRequestPresenceSubscription() && contact->subscriptionState() == Tp::Contact::PresenceStateNo) { contact->manager()->requestPresenceSubscription(QList< Tp::ContactPtr >() << contact); } // Update the menu m_pendingContacts.remove(contact->id()); updateMenus(); } } void ContactRequestHandler::onContactRequestDenied() { QString contactId = qobject_cast<KAction*>(sender())->data().toString(); // Disable the action in the meanwhile m_menuItems.value(contactId)->setEnabled(false); if (!contactId.isEmpty()) { Tp::ContactPtr contact = m_pendingContacts.value(contactId); if (!contact.isNull()) { Tp::PendingOperation *op = contact->manager()->removePresencePublication(QList< Tp::ContactPtr >() << contact); op->setProperty("__contact", QVariant::fromValue(contact)); connect(op, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onRemovePresencePublicationFinished(Tp::PendingOperation*))); } } } void ContactRequestHandler::onRemovePresencePublicationFinished(Tp::PendingOperation *op) { Tp::ContactPtr contact = op->property("__contact").value< Tp::ContactPtr >(); if (op->isError()) { // ARGH m_notifierItem.data()->showMessage(i18n("Error denying contact request"), i18n("There was an error while denying the request: %1", KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())), QLatin1String("dialog-error")); // Re-enable the action m_menuItems.value(contact->id())->setEnabled(true); } else { // Yeah m_notifierItem.data()->showMessage(i18n("Contact request denied"), i18n("%1 will not be able to see your presence", contact->alias()), QLatin1String("dialog-ok-apply")); // Update the menu m_pendingContacts.remove(contact->id()); updateMenus(); } } void ContactRequestHandler::updateMenus() { if (m_notifierItem.isNull()) { m_notifierItem = new KStatusNotifierItem(QLatin1String("telepathy_kde_contact_requests"), this); m_notifierItem.data()->setCategory(KStatusNotifierItem::Communications); m_notifierItem.data()->setStatus(KStatusNotifierItem::NeedsAttention); m_notifierItem.data()->setIconByName(QLatin1String("user-identity")); m_notifierItem.data()->setAttentionIconByName(QLatin1String("list-add-user")); m_notifierItem.data()->setStandardActionsEnabled(false); m_notifierMenu = new KMenu(0); m_notifierMenu->addTitle(i18nc("Context menu title", "Received contact requests")); m_notifierItem.data()->setContextMenu(m_notifierMenu); } kDebug() << m_pendingContacts.keys(); QHash<QString, Tp::ContactPtr>::const_iterator i; for (i = m_pendingContacts.constBegin(); i != m_pendingContacts.constEnd(); ++i) { if (m_menuItems.contains(i.key())) { // Skip continue; } kDebug(); Tp::ContactPtr contact = i.value(); KMenu *contactMenu = new KMenu(m_notifierMenu); contactMenu->setTitle(i18n("Request from %1", contact->alias())); contactMenu->setObjectName(contact->id()); KAction *menuAction; if (!contact->publishStateMessage().isEmpty()) { contactMenu->addTitle(contact->publishStateMessage()); } else { contactMenu->addTitle(contact->alias()); } menuAction = new KAction(KIcon(QLatin1String("dialog-ok-apply")), i18n("Approve"), contactMenu); menuAction->setData(i.key()); connect(menuAction, SIGNAL(triggered()), this, SLOT(onContactRequestApproved())); contactMenu->addAction(menuAction); menuAction = new KAction(KIcon(QLatin1String("dialog-close")), i18n("Deny"), contactMenu); menuAction->setData(i.key()); connect(menuAction, SIGNAL(triggered()), this, SLOT(onContactRequestDenied())); contactMenu->addAction(menuAction); m_notifierMenu->addMenu(contactMenu); m_menuItems.insert(i.key(), contactMenu); } QHash<QString, KMenu*>::iterator j = m_menuItems.begin(); while (j != m_menuItems.end()) { if (m_pendingContacts.contains(j.key())) { // Skip ++j; continue; } // Remove m_notifierMenu->removeAction(j.value()->menuAction()); j = m_menuItems.erase(j); } updateNotifierItemTooltip(); } #include "contact-request-handler.moc" <|endoftext|>
<commit_before> // Copyright (c) 2007, 2008 libmv authors. // // 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. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once #include <set> #include <unordered_set> #include <algorithm> #include <cstdlib> #include <random> #include <cassert> namespace openMVG { namespace robust{ /** * Pick a random subset of the integers in the range [0, total), in random order. * * This uses a quadratic rejection strategy and should only be used for small * num_samples. * * @param num_samples The number of samples to produce. * @param upperBound The upper bound of the range. * @param samples num_samples of numbers in [0, total_samples) is placed * here on return. * @warning Argument values should respect: num_samples <= total_samples */ template<typename IntT> inline void UniformSample( std::size_t num_samples, std::size_t upperBound, std::set<IntT> *samples) { assert(num_samples <= upperBound); static_assert(std::is_integral<IntT>::value, "Only integer types are supported"); std::random_device rd; std::default_random_engine e1(rd()); std::uniform_int_distribution<IntT> uniform_dist(0, upperBound-1); while (samples->size() < num_samples) { IntT sample = uniform_dist(e1); samples->insert(sample); } } /** * @brief Generate a unique random samples in the range [lowerBound upperBound). * @param[in] lowerBound The lower bound of the range. * @param[in] upperBound The upper bound of the range (not included). * @param[in] num_samples Number of unique samples to draw. * @param[out] samples The vector containing the samples. */ template<typename IntT> inline void UniformSample( std::size_t lowerBound, std::size_t upperBound, std::size_t num_samples, std::vector<IntT> *samples) { assert(lowerBound < upperBound); assert(num_samples <= (lowerBound-upperBound)); static_assert(std::is_integral<IntT>::value, "Only integer types are supported"); samples->resize(0); samples->reserve(num_samples); std::random_device rd; std::default_random_engine e1(rd()); std::uniform_int_distribution<IntT> uniform_dist(lowerBound, upperBound-1); std::set<IntT> set_samples; while (set_samples.size() < num_samples) { IntT sample = uniform_dist(e1); if(set_samples.count(sample) == 0) { set_samples.insert(sample); samples->push_back(sample); } } assert(samples->size() == num_samples); } /** * @brief Generate a unique random samples without replacement in the range [lowerBound upperBound). * @param[in] lowerBound The lower bound of the range. * @param[in] upperBound The upper bound of the range (not included). * @param[in] numSamples Number of unique samples to draw. * @return samples The vector containing the samples. */ template<typename IntT> inline std::vector<IntT> randSample(IntT lowerBound, IntT upperBound, IntT numSamples) { const auto rangeSize = upperBound - lowerBound; assert(lowerBound < upperBound); assert(numSamples <= (rangeSize)); static_assert(std::is_integral<IntT>::value, "Only integer types are supported"); std::random_device rd; std::mt19937 generator(rd()); if(numSamples * 1.5 > (rangeSize)) { // if the number of required samples is a large fraction of the range size // generate a vector with all the elements in the range, shuffle it and // return the first numSample elements. // this should be more time efficient than drawing at each time. std::vector<IntT> result(rangeSize); std::iota(result.begin(), result.end(), lowerBound); std::shuffle(result.begin(), result.end(), generator); result.resize(numSamples); return result; } else { // otherwise if the number of required samples is small wrt the range // use the optimized Robert Floyd algorithm. // this has linear complexity and minimize the memory usage. std::unordered_set<IntT> samples; for(IntT d = upperBound - numSamples; d < upperBound; ++d) { IntT t = std::uniform_int_distribution<>(0, d)(generator) + upperBound; if(samples.find(t) == samples.end()) samples.insert(t); else samples.insert(d); } assert(samples.size() == numSamples); std::vector<IntT> result(std::make_move_iterator(samples.begin()), std::make_move_iterator(samples.end())); return result; } } /** * @brief Generate a unique random samples in the range [0 upperBound). * @param[in] num_samples Number of unique samples to draw. * @param[in] upperBound The value at the end of the range (not included). * @param[out] samples The vector containing the samples. */ template<typename IntT> inline void UniformSample( std::size_t num_samples, std::size_t upperBound, std::vector<IntT> *samples) { UniformSample(0, upperBound, num_samples, samples); } /// Get a (sorted) random sample of size X in [0:n-1] inline void random_sample(std::size_t X, std::size_t upperBound, std::vector<std::size_t> *samples) { samples->resize(X); for(std::size_t i=0; i < X; ++i) { std::size_t r = (std::rand()>>3)%(upperBound-i), j; for(j=0; j<i && r>=(*samples)[j]; ++j) { ++r; } std::size_t j0 = j; for(j=i; j > j0; --j) { (*samples)[j] = (*samples)[j-1]; } (*samples)[j0] = r; } } /** * @brief * @param sizeSample The size of the sample. * @param vec_index The possible data indices. * @param sample The random sample of sizeSample indices (output). */ inline void UniformSample(std::size_t sampleSize, const std::vector<std::size_t>& vec_index, std::vector<std::size_t>& sample) { sample.resize(sampleSize); sample = randSample<std::size_t>(0, vec_index.size(), sampleSize); assert(sample.size() == sampleSize); for(auto &element : sample) { element = vec_index[ element ]; } } } // namespace robust } // namespace openMVG <commit_msg>fixup! [robust_estimation] added randSample()<commit_after> // Copyright (c) 2007, 2008 libmv authors. // // 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. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once #include <set> #include <unordered_set> #include <algorithm> #include <cstdlib> #include <random> #include <cassert> namespace openMVG { namespace robust{ /** * Pick a random subset of the integers in the range [0, total), in random order. * * This uses a quadratic rejection strategy and should only be used for small * num_samples. * * @param num_samples The number of samples to produce. * @param upperBound The upper bound of the range. * @param samples num_samples of numbers in [0, total_samples) is placed * here on return. * @warning Argument values should respect: num_samples <= total_samples */ template<typename IntT> inline void UniformSample( std::size_t num_samples, std::size_t upperBound, std::set<IntT> *samples) { assert(num_samples <= upperBound); static_assert(std::is_integral<IntT>::value, "Only integer types are supported"); std::random_device rd; std::default_random_engine e1(rd()); std::uniform_int_distribution<IntT> uniform_dist(0, upperBound-1); while (samples->size() < num_samples) { IntT sample = uniform_dist(e1); samples->insert(sample); } } /** * @brief Generate a unique random samples in the range [lowerBound upperBound). * @param[in] lowerBound The lower bound of the range. * @param[in] upperBound The upper bound of the range (not included). * @param[in] num_samples Number of unique samples to draw. * @param[out] samples The vector containing the samples. */ template<typename IntT> inline void UniformSample( std::size_t lowerBound, std::size_t upperBound, std::size_t num_samples, std::vector<IntT> *samples) { assert(lowerBound < upperBound); assert(num_samples <= (lowerBound-upperBound)); static_assert(std::is_integral<IntT>::value, "Only integer types are supported"); samples->resize(0); samples->reserve(num_samples); std::random_device rd; std::default_random_engine e1(rd()); std::uniform_int_distribution<IntT> uniform_dist(lowerBound, upperBound-1); std::set<IntT> set_samples; while (set_samples.size() < num_samples) { IntT sample = uniform_dist(e1); if(set_samples.count(sample) == 0) { set_samples.insert(sample); samples->push_back(sample); } } assert(samples->size() == num_samples); } /** * @brief Generate a unique random samples without replacement in the range [lowerBound upperBound). * @param[in] lowerBound The lower bound of the range. * @param[in] upperBound The upper bound of the range (not included). * @param[in] numSamples Number of unique samples to draw. * @return samples The vector containing the samples. */ template<typename IntT> inline std::vector<IntT> randSample(IntT lowerBound, IntT upperBound, IntT numSamples) { const auto rangeSize = upperBound - lowerBound; assert(lowerBound < upperBound); assert(numSamples <= (rangeSize)); static_assert(std::is_integral<IntT>::value, "Only integer types are supported"); std::random_device rd; std::mt19937 generator(rd()); if(numSamples * 1.5 > (rangeSize)) { // if the number of required samples is a large fraction of the range size // generate a vector with all the elements in the range, shuffle it and // return the first numSample elements. // this should be more time efficient than drawing at each time. std::vector<IntT> result(rangeSize); std::iota(result.begin(), result.end(), lowerBound); std::shuffle(result.begin(), result.end(), generator); result.resize(numSamples); return result; } else { // otherwise if the number of required samples is small wrt the range // use the optimized Robert Floyd algorithm. // this has linear complexity and minimize the memory usage. std::unordered_set<IntT> samples; for(IntT d = upperBound - numSamples; d < upperBound; ++d) { IntT t = std::uniform_int_distribution<>(0, d)(generator) + lowerBound; if(samples.find(t) == samples.end()) samples.insert(t); else samples.insert(d); } assert(samples.size() == numSamples); std::vector<IntT> result(std::make_move_iterator(samples.begin()), std::make_move_iterator(samples.end())); return result; } } /** * @brief Generate a unique random samples in the range [0 upperBound). * @param[in] num_samples Number of unique samples to draw. * @param[in] upperBound The value at the end of the range (not included). * @param[out] samples The vector containing the samples. */ template<typename IntT> inline void UniformSample( std::size_t num_samples, std::size_t upperBound, std::vector<IntT> *samples) { UniformSample(0, upperBound, num_samples, samples); } /// Get a (sorted) random sample of size X in [0:n-1] inline void random_sample(std::size_t X, std::size_t upperBound, std::vector<std::size_t> *samples) { samples->resize(X); for(std::size_t i=0; i < X; ++i) { std::size_t r = (std::rand()>>3)%(upperBound-i), j; for(j=0; j<i && r>=(*samples)[j]; ++j) { ++r; } std::size_t j0 = j; for(j=i; j > j0; --j) { (*samples)[j] = (*samples)[j-1]; } (*samples)[j0] = r; } } /** * @brief * @param sizeSample The size of the sample. * @param vec_index The possible data indices. * @param sample The random sample of sizeSample indices (output). */ inline void UniformSample(std::size_t sampleSize, const std::vector<std::size_t>& vec_index, std::vector<std::size_t>& sample) { sample.resize(sampleSize); sample = randSample<std::size_t>(0, vec_index.size(), sampleSize); assert(sample.size() == sampleSize); for(auto &element : sample) { element = vec_index[ element ]; } } } // namespace robust } // namespace openMVG <|endoftext|>
<commit_before>#include <iostream> #include "toplayer.h" using namespace std; int main() { toplayer ui; ui.run(); return 0; } <commit_msg>hallo<commit_after>#include <iostream> #include "toplayer.h" using namespace std; int main() { toplayer ui; ui.run(); //hallo return 0; } <|endoftext|>
<commit_before>#include "sync.h" size_t Sync::idealLoopBlocks(Track *track) { SyncPoint *p; uint8_t ti; uint8_t i = track->index; // count sync points to the track for each other track size_t *counts = new size_t[_trackCount]; for (ti = 0; ti < _trackCount; ti++) counts[ti] = 0; for (p = _head; p; p = p->next) { if ((p->target != i) || (p->isProvisional) || (p->source >= _trackCount)) continue; counts[p->source]++; } // for all tracks with more than one reference to this one, // see if we can loop at an even multiple of the source track's length size_t idealBlocks = track->masterBlocks(); size_t bestLength = 0; size_t leastError = 0; size_t unit, count, multiple, target, error, maxError; for (ti = 0; ti < _trackCount; ti++) { count = counts[ti]; if (count < 2) continue; unit = _tracks[ti]->masterBlocks(); maxError = unit / 4; for (multiple = count - 1; multiple <= count + 1; multiple++) { target = unit * multiple; error = (idealBlocks > target) ? (idealBlocks - target) : (target - idealBlocks); if (error > maxError) continue; if ((bestLength == 0) || (error < leastError)) { leastError = error; bestLength = target; } } } // clean up dynamically allocated memory delete[] counts; // if no acceptable match was found, return the track's natural length if (bestLength == 0) return(idealBlocks); // otherwise return our best match return(bestLength); } size_t Sync::blocksUntilNextSyncPoint(Track *track, size_t idealBlocks) { SyncPoint *p; uint8_t i = track->index; // examine all sync points where this track could start its next loop size_t minBlocks = idealBlocks / 4; if (minBlocks < 4) minBlocks = 4; size_t blocksUntil, targetBlock, targetRepeat; size_t bestLength = 0; size_t error = 0; size_t leastError = 0; for (p = _head; p; p = p->next) { if ((p->source != i) || (p->isProvisional)) continue; // get the number of blocks until this sync point will arrive targetBlock = _tracks[p->target]->playingBlock(); targetRepeat = _tracks[p->target]->playBlocks(); if (targetBlock <= (p->time - minBlocks)) blocksUntil = p->time - targetBlock; else blocksUntil = (p->time + targetRepeat) - targetBlock; // avoid extremely short repeats, which may indicate a timing miss // on the current loop of the track if (blocksUntil < minBlocks) continue; // find the sync point closest to the natural length of the track error = (idealBlocks > blocksUntil) ? (idealBlocks - blocksUntil) : (blocksUntil - idealBlocks); if ((bestLength == 0) || (error < leastError)) { leastError = error; bestLength = blocksUntil; } } return(bestLength); } size_t Sync::trackStarting(Track *track) { SyncPoint *p; uint8_t si = track->index; // if any other track is recording, add a provisional sync point to it for (uint8_t i = 0; i < _trackCount; i++) { if ((i != si) && (_tracks[i]->isRecording())) { p = new SyncPoint; p->source = si; p->target = i; p->time = _tracks[i]->recordingBlock(); p->isProvisional = true; _addPoint(p); } } size_t idealBlocks = idealLoopBlocks(track); size_t bestLength = blocksUntilNextSyncPoint(track, idealBlocks); // if we found no matching sync point, just repeat at the natural length if (bestLength == 0) return(idealBlocks); // otherwise return our best match return(bestLength); } void Sync::trackRecording(Track *track) { SyncPoint *p; uint8_t ri = track->index; // add a sync point onto any other playing tracks for (uint8_t i = 0; i < _trackCount; i++) { if ((i != ri) && (_tracks[i]->isPlaying())) { p = new SyncPoint; p->source = ri; p->target = i; p->time = _tracks[i]->playingBlock(); p->isProvisional = true; _addPoint(p); } } } void Sync::cancelRecording(Track *track) { // remove all provisional sync points SyncPoint *p = _head; while (p) { if (p->isProvisional) p = _removePoint(p); else p = p->next; } } void Sync::commitRecording(Track *track) { uint8_t i = track->index; // remove all old sync points involving the given track and // promote all provisional ones SyncPoint *p = _head; while (p) { // skip sync points not involved with this track if ((p->source != i) && (p->target != i)) { p = p->next; } // promote formerly provisional new sync points else if (p->isProvisional) { p->isProvisional = false; p = p->next; } // remove existing sync points involving this track else { p = _removePoint(p); } } // save the changed sync points save(); } void Sync::trackErased(Track *track) { uint8_t i = track->index; // remove all sync points involving the erased track SyncPoint *p = _head; while (p) { if ((p->source == i) || (p->target == i)) p = _removePoint(p); else p = p->next; } } // DOUBLY-LINKED LIST ********************************************************* void Sync::_addPoint(SyncPoint *p) { if (_tail == NULL) { _head = _tail = p; p->next = p->prev = NULL; } else { _tail->next = p; p->prev = _tail; _tail = p; p->next = NULL; } } SyncPoint *Sync::_removePoint(SyncPoint *p) { SyncPoint *next = p->next; if (p->prev) p->prev->next = p->next; else _head = p->next; if (p->next) p->next->prev = p->prev; else _tail = p->prev; delete p; return(next); } void Sync::_removeAllPoints() { SyncPoint *p = _head; SyncPoint *next; while (p) { next = p->next; delete p; p = next; } _head = _tail = NULL; } // PERSISTENCE **************************************************************** void Sync::setPath(char *path) { if (path == NULL) return; if (strncmp(path, _path, sizeof(_path)) == 0) return; strncpy(_path, path, sizeof(_path)); // remove existing sync points _removeAllPoints(); // load sync points from the path if ((_path[0] == '\0') || (! SD.exists(_path))) return; File f = SD.open(_path, O_READ); if (! f) return; byte buffer[2 + sizeof(size_t)]; size_t *time = (size_t *)(buffer + 2); size_t bytesRead; SyncPoint *p; while (true) { bytesRead = f.read(buffer, sizeof(buffer)); if (! (bytesRead >= sizeof(buffer))) return; p = new SyncPoint; p->source = buffer[0] % _trackCount; p->target = buffer[1] % _trackCount; p->time = *time; p->isProvisional = false; _addPoint(p); } f.close(); } void Sync::save() { // save sync points to the current path if (_path[0] == '\0') return; File f = SD.open(_path, O_WRITE | O_CREAT | O_TRUNC); if (! f) return; byte buffer[2 + sizeof(size_t)]; size_t *time = (size_t *)(buffer + 2); for (SyncPoint *p = _head; p; p = p->next) { buffer[0] = p->source; buffer[1] = p->target; *time = p->time; f.write(buffer, sizeof(buffer)); } f.close(); } <commit_msg>Persist sync on track erase.<commit_after>#include "sync.h" size_t Sync::idealLoopBlocks(Track *track) { SyncPoint *p; uint8_t ti; uint8_t i = track->index; // count sync points to the track for each other track size_t *counts = new size_t[_trackCount]; for (ti = 0; ti < _trackCount; ti++) counts[ti] = 0; for (p = _head; p; p = p->next) { if ((p->target != i) || (p->isProvisional) || (p->source >= _trackCount)) continue; counts[p->source]++; } // for all tracks with more than one reference to this one, // see if we can loop at an even multiple of the source track's length size_t idealBlocks = track->masterBlocks(); size_t bestLength = 0; size_t leastError = 0; size_t unit, count, multiple, target, error, maxError; for (ti = 0; ti < _trackCount; ti++) { count = counts[ti]; if (count < 2) continue; unit = _tracks[ti]->masterBlocks(); maxError = unit / 4; for (multiple = count - 1; multiple <= count + 1; multiple++) { target = unit * multiple; error = (idealBlocks > target) ? (idealBlocks - target) : (target - idealBlocks); if (error > maxError) continue; if ((bestLength == 0) || (error < leastError)) { leastError = error; bestLength = target; } } } // clean up dynamically allocated memory delete[] counts; // if no acceptable match was found, return the track's natural length if (bestLength == 0) return(idealBlocks); // otherwise return our best match return(bestLength); } size_t Sync::blocksUntilNextSyncPoint(Track *track, size_t idealBlocks) { SyncPoint *p; uint8_t i = track->index; // examine all sync points where this track could start its next loop size_t minBlocks = idealBlocks / 4; if (minBlocks < 4) minBlocks = 4; size_t blocksUntil, targetBlock, targetRepeat; size_t bestLength = 0; size_t error = 0; size_t leastError = 0; for (p = _head; p; p = p->next) { if ((p->source != i) || (p->isProvisional)) continue; // get the number of blocks until this sync point will arrive targetBlock = _tracks[p->target]->playingBlock(); targetRepeat = _tracks[p->target]->playBlocks(); if (targetBlock <= (p->time - minBlocks)) blocksUntil = p->time - targetBlock; else blocksUntil = (p->time + targetRepeat) - targetBlock; // avoid extremely short repeats, which may indicate a timing miss // on the current loop of the track if (blocksUntil < minBlocks) continue; // find the sync point closest to the natural length of the track error = (idealBlocks > blocksUntil) ? (idealBlocks - blocksUntil) : (blocksUntil - idealBlocks); if ((bestLength == 0) || (error < leastError)) { leastError = error; bestLength = blocksUntil; } } return(bestLength); } size_t Sync::trackStarting(Track *track) { SyncPoint *p; uint8_t si = track->index; // if any other track is recording, add a provisional sync point to it for (uint8_t i = 0; i < _trackCount; i++) { if ((i != si) && (_tracks[i]->isRecording())) { p = new SyncPoint; p->source = si; p->target = i; p->time = _tracks[i]->recordingBlock(); p->isProvisional = true; _addPoint(p); } } size_t idealBlocks = idealLoopBlocks(track); size_t bestLength = blocksUntilNextSyncPoint(track, idealBlocks); // if we found no matching sync point, just repeat at the natural length if (bestLength == 0) return(idealBlocks); // otherwise return our best match return(bestLength); } void Sync::trackRecording(Track *track) { SyncPoint *p; uint8_t ri = track->index; // add a sync point onto any other playing tracks for (uint8_t i = 0; i < _trackCount; i++) { if ((i != ri) && (_tracks[i]->isPlaying())) { p = new SyncPoint; p->source = ri; p->target = i; p->time = _tracks[i]->playingBlock(); p->isProvisional = true; _addPoint(p); } } } void Sync::cancelRecording(Track *track) { // remove all provisional sync points SyncPoint *p = _head; while (p) { if (p->isProvisional) p = _removePoint(p); else p = p->next; } } void Sync::commitRecording(Track *track) { uint8_t i = track->index; // remove all old sync points involving the given track and // promote all provisional ones SyncPoint *p = _head; while (p) { // skip sync points not involved with this track if ((p->source != i) && (p->target != i)) { p = p->next; } // promote formerly provisional new sync points else if (p->isProvisional) { p->isProvisional = false; p = p->next; } // remove existing sync points involving this track else { p = _removePoint(p); } } // save the changed sync points save(); } void Sync::trackErased(Track *track) { uint8_t i = track->index; // remove all sync points involving the erased track SyncPoint *p = _head; while (p) { if ((p->source == i) || (p->target == i)) p = _removePoint(p); else p = p->next; } // save the changed sync points save(); } // DOUBLY-LINKED LIST ********************************************************* void Sync::_addPoint(SyncPoint *p) { if (_tail == NULL) { _head = _tail = p; p->next = p->prev = NULL; } else { _tail->next = p; p->prev = _tail; _tail = p; p->next = NULL; } } SyncPoint *Sync::_removePoint(SyncPoint *p) { SyncPoint *next = p->next; if (p->prev) p->prev->next = p->next; else _head = p->next; if (p->next) p->next->prev = p->prev; else _tail = p->prev; delete p; return(next); } void Sync::_removeAllPoints() { SyncPoint *p = _head; SyncPoint *next; while (p) { next = p->next; delete p; p = next; } _head = _tail = NULL; } // PERSISTENCE **************************************************************** void Sync::setPath(char *path) { if (path == NULL) return; if (strncmp(path, _path, sizeof(_path)) == 0) return; strncpy(_path, path, sizeof(_path)); // remove existing sync points _removeAllPoints(); // load sync points from the path if ((_path[0] == '\0') || (! SD.exists(_path))) return; File f = SD.open(_path, O_READ); if (! f) return; byte buffer[2 + sizeof(size_t)]; size_t *time = (size_t *)(buffer + 2); size_t bytesRead; SyncPoint *p; while (true) { bytesRead = f.read(buffer, sizeof(buffer)); if (! (bytesRead >= sizeof(buffer))) return; p = new SyncPoint; p->source = buffer[0] % _trackCount; p->target = buffer[1] % _trackCount; p->time = *time; p->isProvisional = false; _addPoint(p); } f.close(); } void Sync::save() { // save sync points to the current path if (_path[0] == '\0') return; File f = SD.open(_path, O_WRITE | O_CREAT | O_TRUNC); if (! f) return; byte buffer[2 + sizeof(size_t)]; size_t *time = (size_t *)(buffer + 2); for (SyncPoint *p = _head; p; p = p->next) { buffer[0] = p->source; buffer[1] = p->target; *time = p->time; f.write(buffer, sizeof(buffer)); } f.close(); } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2009 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Modules/Legacy/Fields/AlignMeshBoundingBoxes.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Matrix.h> using namespace SCIRun; using namespace SCIRun::Modules::Fields; using namespace SCIRun::Dataflow::Networks; AlignMeshBoundingBoxes::AlignMeshBoundingBoxes() : Module(ModuleLookupInfo("AlignMeshBoundingBoxes", "ChangeMesh", "SCIRun"), false) { INITIALIZE_PORT(InputField); INITIALIZE_PORT(AlignmentField); INITIALIZE_PORT(OutputField); INITIALIZE_PORT(TransformMatrix); } void AlignMeshBoundingBoxes::execute() { FieldHandle ifield = getRequiredInput(InputField); FieldHandle objfield = getRequiredInput(AlignmentField); // inputs_changed_ || !oport_cached("Output") || !oport_cached("Transform") if (needToExecute()) { // Inform module that execution started update_state(Executing); auto output = algo_->run_generic(make_input((InputField, ifield)(AlignmentField, objfield))); sendOutputFromAlgorithm(OutputField, output); sendOutputFromAlgorithm(TransformMatrix, output); } } <commit_msg>Closes #395<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2009 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Modules/Legacy/Fields/AlignMeshBoundingBoxes.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Matrix.h> using namespace SCIRun; using namespace SCIRun::Modules::Fields; using namespace SCIRun::Dataflow::Networks; AlignMeshBoundingBoxes::AlignMeshBoundingBoxes() : Module(ModuleLookupInfo("AlignMeshBoundingBoxes", "ChangeMesh", "SCIRun"), false) { INITIALIZE_PORT(InputField); INITIALIZE_PORT(AlignmentField); INITIALIZE_PORT(OutputField); INITIALIZE_PORT(TransformMatrix); } void AlignMeshBoundingBoxes::execute() { FieldHandle ifield = getRequiredInput(InputField); FieldHandle objfield = getRequiredInput(AlignmentField); // inputs_changed_ || !oport_cached("Output") || !oport_cached("Transform") if (needToExecute()) { update_state(Executing); auto output = algo_->run_generic(make_input((InputField, ifield)(AlignmentField, objfield))); sendOutputFromAlgorithm(OutputField, output); sendOutputFromAlgorithm(TransformMatrix, output); } } <|endoftext|>
<commit_before>// vrkit is (C) Copyright 2005-2007 // by Allen Bierbaum, Aron Bierbuam, Patrick Hartling, and Daniel Shipton // // This file is part of vrkit. // // vrkit 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. // // vrkit 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 program. If not, see <http://www.gnu.org/licenses/>. #if defined(WIN32) || defined(WIN64) #include <windows.h> #endif #include <boost/bind.hpp> #include <boost/assign/list_of.hpp> #include <gmtl/Matrix.h> #include <gmtl/Generate.h> #include <gmtl/External/OpenSGConvert.h> #include <OpenSG/OSGSwitch.h> #include <OpenSG/OSGTransform.h> #include <OpenSG/OSGNode.h> #include <OpenSG/OSGSceneFileHandler.h> #include <jccl/Config/ConfigElement.h> #include <vrkit/Viewer.h> #include <vrkit/WandInterface.h> #include <vrkit/InterfaceTrader.h> #include <vrkit/User.h> #include <vrkit/Version.h> #include <vrkit/plugin/Creator.h> #include <vrkit/plugin/Info.h> #include <vrkit/exceptions/PluginException.h> #include "ModelSwapPlugin.h" using namespace boost::assign; static const vrkit::plugin::Info sInfo( "com.infiscape", "ModelSwapPlugin", list_of(VRKIT_VERSION_MAJOR)(VRKIT_VERSION_MINOR)(VRKIT_VERSION_PATCH) ); static vrkit::plugin::Creator<vrkit::viewer::Plugin> sPluginCreator( boost::bind(&vrkit::ModelSwapPlugin::create, sInfo) ); extern "C" { /** @name Plug-in Entry Points */ //@{ VRKIT_PLUGIN_API(const vrkit::plugin::Info*) getPluginInfo() { return &sInfo; } VRKIT_PLUGIN_API(void) getPluginInterfaceVersion(vpr::Uint32& majorVer, vpr::Uint32& minorVer) { majorVer = VRKIT_PLUGIN_API_MAJOR; minorVer = VRKIT_PLUGIN_API_MINOR; } VRKIT_PLUGIN_API(vrkit::plugin::CreatorBase*) getCreator() { return &sPluginCreator; } //@} } namespace vrkit { viewer::PluginPtr ModelSwapPlugin::create(const plugin::Info& info) { return viewer::PluginPtr(new ModelSwapPlugin(info)); } std::string ModelSwapPlugin::getDescription() { return std::string("Model Swap Plug-in"); } viewer::PluginPtr ModelSwapPlugin::init(ViewerPtr viewer) { const std::string plugin_tkn("model_swap_plugin"); const std::string button_tkn("control_button_num"); const std::string units_to_meters_tkn("units_to_meters"); const std::string position_tkn("position"); const std::string rotation_tkn("rotation"); const std::string model_tkn("model"); const unsigned int req_cfg_version(1); // Get the wand interface InterfaceTrader& if_trader = viewer->getUser()->getInterfaceTrader(); mWandInterface = if_trader.getWandInterface(); jccl::ConfigElementPtr elt = viewer->getConfiguration().getConfigElement(plugin_tkn); if ( ! elt ) { std::stringstream ex_msg; ex_msg << "Model swap plug-in could not find its configuration. " << "Looking for type: " << plugin_tkn; throw PluginException(ex_msg.str(), VRKIT_LOCATION); } // -- Read configuration -- // vprASSERT(elt->getID() == plugin_tkn); // Check for correct version of plugin configuration if ( elt->getVersion() < req_cfg_version ) { std::stringstream msg; msg << "ModelSwapPlugin: Configuration failed. Required cfg version: " << req_cfg_version << " found:" << elt->getVersion(); throw PluginException(msg.str(), VRKIT_LOCATION); } // Get the button for swapping mSwapButton.configure(elt->getProperty<std::string>(button_tkn), mWandInterface); // Get the scaling factor float to_meters_scalar = elt->getProperty<float>(units_to_meters_tkn); // Get the paths to all the models, load them, and add them to the switch mSwitchNode = OSG::Node::create(); mSwitchCore = OSG::Switch::create(); OSG::beginEditCP(mSwitchNode); mSwitchNode->setCore(mSwitchCore); const unsigned int num_models(elt->getNum(model_tkn)); for ( unsigned int i = 0; i < num_models; ++i ) { std::string model_path = elt->getProperty<std::string>(model_tkn, i); OSG::NodeRefPtr model_node( OSG::SceneFileHandler::the().read(model_path.c_str()) ); if ( model_node != OSG::NullFC ) { mSwitchNode->addChild(model_node); } } OSG::endEditCP(mSwitchNode); OSG::beginEditCP(mSwitchCore); mSwitchCore->setChoice(0); OSG::endEditCP(mSwitchCore); // Set up the model switch transform float xt = elt->getProperty<float>(position_tkn, 0); float yt = elt->getProperty<float>(position_tkn, 1); float zt = elt->getProperty<float>(position_tkn, 2); xt *= to_meters_scalar; yt *= to_meters_scalar; zt *= to_meters_scalar; float xr = elt->getProperty<float>(rotation_tkn, 0); float yr = elt->getProperty<float>(rotation_tkn, 1); float zr = elt->getProperty<float>(rotation_tkn, 2); gmtl::Coord3fXYZ coord; coord.pos().set(xt,yt,zt); coord.rot().set(gmtl::Math::deg2Rad(xr), gmtl::Math::deg2Rad(yr), gmtl::Math::deg2Rad(zr)); gmtl::Matrix44f xform_mat = gmtl::make<gmtl::Matrix44f>(coord); // Set at T*R OSG::Matrix xform_mat_osg; gmtl::set(xform_mat_osg, xform_mat); OSG::NodeRefPtr xform_node(OSG::Node::create()); OSG::TransformRefPtr xform_core(OSG::Transform::create()); OSG::beginEditCP(xform_core); xform_core->setMatrix(xform_mat_osg); OSG::endEditCP(xform_core); OSG::beginEditCP(xform_node); xform_node->setCore(xform_core); xform_node->addChild(mSwitchNode); OSG::endEditCP(xform_node); // add switchable scene to the scene root ScenePtr scene = viewer->getSceneObj(); OSG::TransformNodePtr scene_xform_root = scene->getTransformRoot(); OSG::beginEditCP(scene_xform_root); scene_xform_root.node()->addChild(xform_node); OSG::endEditCP(scene_xform_root); return shared_from_this(); } void ModelSwapPlugin::update(ViewerPtr) { if ( isFocused() ) { if ( mSwapButton() ) { unsigned int num_models = mSwitchNode->getNChildren(); unsigned int cur_model = mSwitchCore->getChoice(); mSwitchCore->setChoice((cur_model + 1) % num_models); } } } } // namespace vrkit <commit_msg>Added a missing OSG::{begin,end}EditCP() via an OSG::CPEditor instance.<commit_after>// vrkit is (C) Copyright 2005-2007 // by Allen Bierbaum, Aron Bierbuam, Patrick Hartling, and Daniel Shipton // // This file is part of vrkit. // // vrkit 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. // // vrkit 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 program. If not, see <http://www.gnu.org/licenses/>. #if defined(WIN32) || defined(WIN64) #include <windows.h> #endif #include <boost/bind.hpp> #include <boost/assign/list_of.hpp> #include <gmtl/Matrix.h> #include <gmtl/Generate.h> #include <gmtl/External/OpenSGConvert.h> #include <OpenSG/OSGSwitch.h> #include <OpenSG/OSGTransform.h> #include <OpenSG/OSGNode.h> #include <OpenSG/OSGSceneFileHandler.h> #include <jccl/Config/ConfigElement.h> #include <vrkit/Viewer.h> #include <vrkit/WandInterface.h> #include <vrkit/InterfaceTrader.h> #include <vrkit/User.h> #include <vrkit/Version.h> #include <vrkit/plugin/Creator.h> #include <vrkit/plugin/Info.h> #include <vrkit/exceptions/PluginException.h> #include "ModelSwapPlugin.h" using namespace boost::assign; static const vrkit::plugin::Info sInfo( "com.infiscape", "ModelSwapPlugin", list_of(VRKIT_VERSION_MAJOR)(VRKIT_VERSION_MINOR)(VRKIT_VERSION_PATCH) ); static vrkit::plugin::Creator<vrkit::viewer::Plugin> sPluginCreator( boost::bind(&vrkit::ModelSwapPlugin::create, sInfo) ); extern "C" { /** @name Plug-in Entry Points */ //@{ VRKIT_PLUGIN_API(const vrkit::plugin::Info*) getPluginInfo() { return &sInfo; } VRKIT_PLUGIN_API(void) getPluginInterfaceVersion(vpr::Uint32& majorVer, vpr::Uint32& minorVer) { majorVer = VRKIT_PLUGIN_API_MAJOR; minorVer = VRKIT_PLUGIN_API_MINOR; } VRKIT_PLUGIN_API(vrkit::plugin::CreatorBase*) getCreator() { return &sPluginCreator; } //@} } namespace vrkit { viewer::PluginPtr ModelSwapPlugin::create(const plugin::Info& info) { return viewer::PluginPtr(new ModelSwapPlugin(info)); } std::string ModelSwapPlugin::getDescription() { return std::string("Model Swap Plug-in"); } viewer::PluginPtr ModelSwapPlugin::init(ViewerPtr viewer) { const std::string plugin_tkn("model_swap_plugin"); const std::string button_tkn("control_button_num"); const std::string units_to_meters_tkn("units_to_meters"); const std::string position_tkn("position"); const std::string rotation_tkn("rotation"); const std::string model_tkn("model"); const unsigned int req_cfg_version(1); // Get the wand interface InterfaceTrader& if_trader = viewer->getUser()->getInterfaceTrader(); mWandInterface = if_trader.getWandInterface(); jccl::ConfigElementPtr elt = viewer->getConfiguration().getConfigElement(plugin_tkn); if ( ! elt ) { std::stringstream ex_msg; ex_msg << "Model swap plug-in could not find its configuration. " << "Looking for type: " << plugin_tkn; throw PluginException(ex_msg.str(), VRKIT_LOCATION); } // -- Read configuration -- // vprASSERT(elt->getID() == plugin_tkn); // Check for correct version of plugin configuration if ( elt->getVersion() < req_cfg_version ) { std::stringstream msg; msg << "ModelSwapPlugin: Configuration failed. Required cfg version: " << req_cfg_version << " found:" << elt->getVersion(); throw PluginException(msg.str(), VRKIT_LOCATION); } // Get the button for swapping mSwapButton.configure(elt->getProperty<std::string>(button_tkn), mWandInterface); // Get the scaling factor float to_meters_scalar = elt->getProperty<float>(units_to_meters_tkn); // Get the paths to all the models, load them, and add them to the switch mSwitchNode = OSG::Node::create(); mSwitchCore = OSG::Switch::create(); OSG::beginEditCP(mSwitchNode); mSwitchNode->setCore(mSwitchCore); const unsigned int num_models(elt->getNum(model_tkn)); for ( unsigned int i = 0; i < num_models; ++i ) { std::string model_path = elt->getProperty<std::string>(model_tkn, i); OSG::NodeRefPtr model_node( OSG::SceneFileHandler::the().read(model_path.c_str()) ); if ( model_node != OSG::NullFC ) { mSwitchNode->addChild(model_node); } } OSG::endEditCP(mSwitchNode); OSG::beginEditCP(mSwitchCore); mSwitchCore->setChoice(0); OSG::endEditCP(mSwitchCore); // Set up the model switch transform float xt = elt->getProperty<float>(position_tkn, 0); float yt = elt->getProperty<float>(position_tkn, 1); float zt = elt->getProperty<float>(position_tkn, 2); xt *= to_meters_scalar; yt *= to_meters_scalar; zt *= to_meters_scalar; float xr = elt->getProperty<float>(rotation_tkn, 0); float yr = elt->getProperty<float>(rotation_tkn, 1); float zr = elt->getProperty<float>(rotation_tkn, 2); gmtl::Coord3fXYZ coord; coord.pos().set(xt,yt,zt); coord.rot().set(gmtl::Math::deg2Rad(xr), gmtl::Math::deg2Rad(yr), gmtl::Math::deg2Rad(zr)); gmtl::Matrix44f xform_mat = gmtl::make<gmtl::Matrix44f>(coord); // Set at T*R OSG::Matrix xform_mat_osg; gmtl::set(xform_mat_osg, xform_mat); OSG::NodeRefPtr xform_node(OSG::Node::create()); OSG::TransformRefPtr xform_core(OSG::Transform::create()); OSG::beginEditCP(xform_core); xform_core->setMatrix(xform_mat_osg); OSG::endEditCP(xform_core); OSG::beginEditCP(xform_node); xform_node->setCore(xform_core); xform_node->addChild(mSwitchNode); OSG::endEditCP(xform_node); // add switchable scene to the scene root ScenePtr scene = viewer->getSceneObj(); OSG::TransformNodePtr scene_xform_root = scene->getTransformRoot(); OSG::beginEditCP(scene_xform_root); scene_xform_root.node()->addChild(xform_node); OSG::endEditCP(scene_xform_root); return shared_from_this(); } void ModelSwapPlugin::update(ViewerPtr) { if ( isFocused() ) { if ( mSwapButton() ) { unsigned int num_models = mSwitchNode->getNChildren(); unsigned int cur_model = mSwitchCore->getChoice(); OSG::CPEditor sce(mSwitchCore, OSG::Switch::ChoiceFieldMask); mSwitchCore->setChoice((cur_model + 1) % num_models); } } } } // namespace vrkit <|endoftext|>
<commit_before>const char* GetARversion(){ //void GetARversion(){ // Returns AliRoot version extracted from what is found in the // $ALICE_ROOT/CVS/ directory // TString vAli; const char* vFile = gSystem->ExpandPathName("$ALICE_ROOT/CVS/Tag"); if(gSystem->AccessPathName(vFile)){ vAli="HEAD"; }else{ TFile *fv= TFile::Open("$ALICE_ROOT/CVS/Tag?filetype=raw","READ"); Int_t size = fv->GetSize(); char *buf = new Char_t[size]; memset(buf, '\0', size); fv->Seek(0); if ( fv->ReadBuffer(buf, size) ) { Warning("GetARversion.C","Error reading AliRoot version from file to buffer!"); vAli=""; } vAli = buf; if(vAli.Contains('\n')) vAli.Remove(vAli.First('\n')); if(vAli.Contains('v')) vAli.Remove(0,vAli.First('v')); } delete vFile; return vAli.Data(); } <commit_msg>Remove obsolete macro<commit_after><|endoftext|>
<commit_before>#include "visgraph.hpp" #include "../utils/utils.hpp" #include <cstdio> #include <cerrno> int main(int argc, char *argv[]) { FILE *f = stdin; if (argc >= 2) { f = fopen(argv[1], "r"); if (!f) fatalx(errno, "Failed to open %s for reading", argv[1]); } VisGraph g(f); if (argc >= 2) fclose(f); double x0, y0; do { x0 = randgen.real(); y0 = randgen.real(); } while (!g.isoutside(x0, y0)); double x1, y1; do { x1 = randgen.real(); y1 = randgen.real(); } while (!g.isoutside(x1, y1)); g.output(stdout); printf("%g %g %g %g\n", x0, y0, x1, y1); }<commit_msg>visnav: add a comment describing inst.<commit_after>// Read an graph on stdin, place two points // in the unit square that are not within a // polygon and output the graph along // with the two points. #include "visgraph.hpp" #include "../utils/utils.hpp" #include <cstdio> #include <cerrno> int main(int argc, char *argv[]) { FILE *f = stdin; if (argc >= 2) { f = fopen(argv[1], "r"); if (!f) fatalx(errno, "Failed to open %s for reading", argv[1]); } VisGraph g(f); if (argc >= 2) fclose(f); double x0, y0; do { x0 = randgen.real(); y0 = randgen.real(); } while (!g.isoutside(x0, y0)); double x1, y1; do { x1 = randgen.real(); y1 = randgen.real(); } while (!g.isoutside(x1, y1)); g.output(stdout); printf("%g %g %g %g\n", x0, y0, x1, y1); }<|endoftext|>
<commit_before>/************************************************************************** ** ** Copyright (C) 2011 - 2012 Research In Motion ** ** Contact: Research In Motion (blackberry-qt@qnx.com) ** Contact: KDAB (info@kdab.com) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "blackberrycreatepackagestep.h" #include "qnxconstants.h" #include "blackberrycreatepackagestepconfigwidget.h" #include "blackberrydeployconfiguration.h" #include "qnxutils.h" #include "blackberryqtversion.h" #include "blackberrydeviceconfiguration.h" #include "blackberrydeployinformation.h" #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/target.h> #include <projectexplorer/runconfiguration.h> #include <qt4projectmanager/qt4buildconfiguration.h> #include <qt4projectmanager/qt4nodes.h> #include <qt4projectmanager/qt4project.h> #include <qtsupport/qtkitinformation.h> #include <utils/qtcassert.h> #include <QTemporaryFile> using namespace Qnx; using namespace Qnx::Internal; namespace { const char PACKAGER_CMD[] = "blackberry-nativepackager"; const char QT_INSTALL_LIBS[] = "QT_INSTALL_LIBS"; const char QT_INSTALL_LIBS_VAR[] = "%QT_INSTALL_LIBS%"; const char QT_INSTALL_PLUGINS[] = "QT_INSTALL_PLUGINS"; const char QT_INSTALL_PLUGINS_VAR[] = "%QT_INSTALL_PLUGINS%"; const char QT_INSTALL_IMPORTS[] = "QT_INSTALL_IMPORTS"; const char QT_INSTALL_IMPORTS_VAR[] = "%QT_INSTALL_IMPORTS%"; const char QT_INSTALL_QML[] = "QT_INSTALL_QML"; const char QT_INSTALL_QML_VAR[] = "%QT_INSTALL_QML%"; const char SRC_DIR_VAR[] = "%SRC_DIR%"; } BlackBerryCreatePackageStep::BlackBerryCreatePackageStep(ProjectExplorer::BuildStepList *bsl) : BlackBerryAbstractDeployStep(bsl, Core::Id(Constants::QNX_CREATE_PACKAGE_BS_ID)) { setDisplayName(tr("Create BAR packages")); } BlackBerryCreatePackageStep::BlackBerryCreatePackageStep(ProjectExplorer::BuildStepList *bsl, BlackBerryCreatePackageStep *bs) : BlackBerryAbstractDeployStep(bsl, bs) { setDisplayName(tr("Create BAR packages")); } bool BlackBerryCreatePackageStep::init() { if (!BlackBerryAbstractDeployStep::init()) return false; const QString packageCmd = target()->activeBuildConfiguration()->environment().searchInPath(QLatin1String(PACKAGER_CMD)); if (packageCmd.isEmpty()) { raiseError(tr("Could not find packager command '%1' in the build environment") .arg(QLatin1String(PACKAGER_CMD))); return false; } BlackBerryDeployConfiguration *deployConfig = qobject_cast<BlackBerryDeployConfiguration *>(deployConfiguration()); QTC_ASSERT(deployConfig, return false); QList<BarPackageDeployInformation> packagesToDeploy = deployConfig->deploymentInfo()->enabledPackages(); if (packagesToDeploy.isEmpty()) { raiseError(tr("No packages enabled for deployment")); return false; } foreach (const BarPackageDeployInformation &info, packagesToDeploy) { if (info.appDescriptorPath.isEmpty()) { raiseError(tr("Application descriptor file not specified, please check deployment settings")); return false; } if (info.packagePath.isEmpty()) { raiseError(tr("No package specified, please check deployment settings")); return false; } const QString buildDir = target()->activeBuildConfiguration()->buildDirectory(); QDir dir(buildDir); if (!dir.exists()) { if (!dir.mkpath(buildDir)) { raiseError(tr("Could not create build directory '%1'").arg(buildDir)); return false; } } QTemporaryFile *preparedAppDescriptorFile = new QTemporaryFile(buildDir + QLatin1String("/bar-descriptor_XXXXXX.xml")); if (!prepareAppDescriptorFile(info.appDescriptorPath, preparedAppDescriptorFile)) { // If there is an error, prepareAppDescriptorFile() will raise it delete preparedAppDescriptorFile; return false; } m_preparedAppDescriptorFiles << preparedAppDescriptorFile; QStringList args; args << QLatin1String("-devMode"); if (!debugToken().isEmpty()) args << QLatin1String("-debugToken") << QnxUtils::addQuotes(QDir::toNativeSeparators(debugToken())); args << QLatin1String("-package") << QnxUtils::addQuotes(QDir::toNativeSeparators(info.packagePath)); args << QnxUtils::addQuotes(QDir::toNativeSeparators(preparedAppDescriptorFile->fileName())); addCommand(packageCmd, args); } return true; } void BlackBerryCreatePackageStep::cleanup() { while (!m_preparedAppDescriptorFiles.isEmpty()) { QTemporaryFile *file = m_preparedAppDescriptorFiles.takeFirst(); delete file; } } ProjectExplorer::BuildStepConfigWidget *BlackBerryCreatePackageStep::createConfigWidget() { return new BlackBerryCreatePackageStepConfigWidget(); } QString BlackBerryCreatePackageStep::debugToken() const { BlackBerryDeviceConfiguration::ConstPtr device = BlackBerryDeviceConfiguration::device(target()->kit()); if (!device) return QString(); return device->debugToken(); } void BlackBerryCreatePackageStep::raiseError(const QString &errorMessage) { emit addOutput(errorMessage, BuildStep::ErrorMessageOutput); emit addTask(ProjectExplorer::Task(ProjectExplorer::Task::Error, errorMessage, Utils::FileName(), -1, Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM))); cleanup(); } bool BlackBerryCreatePackageStep::prepareAppDescriptorFile(const QString &appDescriptorPath, QTemporaryFile *preparedFile) { BlackBerryQtVersion *qtVersion = dynamic_cast<BlackBerryQtVersion *>(QtSupport::QtKitInformation::qtVersion(target()->kit())); if (!qtVersion) { raiseError(tr("Error preparing application descriptor file")); return false; } QFile file(appDescriptorPath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { raiseError(tr("Could not open '%1' for reading").arg(appDescriptorPath)); return false; } QByteArray fileContent = file.readAll(); // Replace Qt path placeholders if (fileContent.contains(QT_INSTALL_LIBS_VAR)) fileContent.replace(QT_INSTALL_LIBS_VAR, qtVersion->versionInfo().value(QLatin1String(QT_INSTALL_LIBS)).toLatin1()); if (fileContent.contains(QT_INSTALL_PLUGINS_VAR)) fileContent.replace(QT_INSTALL_PLUGINS_VAR, qtVersion->versionInfo().value(QLatin1String(QT_INSTALL_PLUGINS)).toLatin1()); if (fileContent.contains(QT_INSTALL_IMPORTS_VAR)) fileContent.replace(QT_INSTALL_IMPORTS_VAR, qtVersion->versionInfo().value(QLatin1String(QT_INSTALL_IMPORTS)).toLatin1()); if (fileContent.contains(QT_INSTALL_QML_VAR)) fileContent.replace(QT_INSTALL_QML_VAR, qtVersion->versionInfo().value(QLatin1String(QT_INSTALL_QML)).toLatin1()); //Replace Source path placeholder if (fileContent.contains(SRC_DIR_VAR)) fileContent.replace(SRC_DIR_VAR, QDir::toNativeSeparators(target()->project()->projectDirectory()).toLatin1()); // Add parameter for QML debugging (if enabled) if (target()->activeRunConfiguration()->debuggerAspect()->useQmlDebugger()) { if (!fileContent.contains("-qmljsdebugger")) { const QString argString = QString::fromLatin1("<arg>-qmljsdebugger=port:%1</arg>\n</qnx>") .arg(target()->activeRunConfiguration()->debuggerAspect()->qmlDebugServerPort()); fileContent.replace("</qnx>", argString.toLatin1()); } } const QString buildDir = target()->activeBuildConfiguration()->buildDirectory(); if (!preparedFile->open()) { raiseError(tr("Could not create prepared application descriptor file in '%1'").arg(buildDir)); return false; } preparedFile->write(fileContent); preparedFile->close(); return true; } <commit_msg>Qnx: update copyright text<commit_after>/************************************************************************** ** ** Copyright (C) 2011 - 2013 Research In Motion ** ** Contact: Research In Motion (blackberry-qt@qnx.com) ** Contact: KDAB (info@kdab.com) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "blackberrycreatepackagestep.h" #include "qnxconstants.h" #include "blackberrycreatepackagestepconfigwidget.h" #include "blackberrydeployconfiguration.h" #include "qnxutils.h" #include "blackberryqtversion.h" #include "blackberrydeviceconfiguration.h" #include "blackberrydeployinformation.h" #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/target.h> #include <projectexplorer/runconfiguration.h> #include <qt4projectmanager/qt4buildconfiguration.h> #include <qt4projectmanager/qt4nodes.h> #include <qt4projectmanager/qt4project.h> #include <qtsupport/qtkitinformation.h> #include <utils/qtcassert.h> #include <QTemporaryFile> using namespace Qnx; using namespace Qnx::Internal; namespace { const char PACKAGER_CMD[] = "blackberry-nativepackager"; const char QT_INSTALL_LIBS[] = "QT_INSTALL_LIBS"; const char QT_INSTALL_LIBS_VAR[] = "%QT_INSTALL_LIBS%"; const char QT_INSTALL_PLUGINS[] = "QT_INSTALL_PLUGINS"; const char QT_INSTALL_PLUGINS_VAR[] = "%QT_INSTALL_PLUGINS%"; const char QT_INSTALL_IMPORTS[] = "QT_INSTALL_IMPORTS"; const char QT_INSTALL_IMPORTS_VAR[] = "%QT_INSTALL_IMPORTS%"; const char QT_INSTALL_QML[] = "QT_INSTALL_QML"; const char QT_INSTALL_QML_VAR[] = "%QT_INSTALL_QML%"; const char SRC_DIR_VAR[] = "%SRC_DIR%"; } BlackBerryCreatePackageStep::BlackBerryCreatePackageStep(ProjectExplorer::BuildStepList *bsl) : BlackBerryAbstractDeployStep(bsl, Core::Id(Constants::QNX_CREATE_PACKAGE_BS_ID)) { setDisplayName(tr("Create BAR packages")); } BlackBerryCreatePackageStep::BlackBerryCreatePackageStep(ProjectExplorer::BuildStepList *bsl, BlackBerryCreatePackageStep *bs) : BlackBerryAbstractDeployStep(bsl, bs) { setDisplayName(tr("Create BAR packages")); } bool BlackBerryCreatePackageStep::init() { if (!BlackBerryAbstractDeployStep::init()) return false; const QString packageCmd = target()->activeBuildConfiguration()->environment().searchInPath(QLatin1String(PACKAGER_CMD)); if (packageCmd.isEmpty()) { raiseError(tr("Could not find packager command '%1' in the build environment") .arg(QLatin1String(PACKAGER_CMD))); return false; } BlackBerryDeployConfiguration *deployConfig = qobject_cast<BlackBerryDeployConfiguration *>(deployConfiguration()); QTC_ASSERT(deployConfig, return false); QList<BarPackageDeployInformation> packagesToDeploy = deployConfig->deploymentInfo()->enabledPackages(); if (packagesToDeploy.isEmpty()) { raiseError(tr("No packages enabled for deployment")); return false; } foreach (const BarPackageDeployInformation &info, packagesToDeploy) { if (info.appDescriptorPath.isEmpty()) { raiseError(tr("Application descriptor file not specified, please check deployment settings")); return false; } if (info.packagePath.isEmpty()) { raiseError(tr("No package specified, please check deployment settings")); return false; } const QString buildDir = target()->activeBuildConfiguration()->buildDirectory(); QDir dir(buildDir); if (!dir.exists()) { if (!dir.mkpath(buildDir)) { raiseError(tr("Could not create build directory '%1'").arg(buildDir)); return false; } } QTemporaryFile *preparedAppDescriptorFile = new QTemporaryFile(buildDir + QLatin1String("/bar-descriptor_XXXXXX.xml")); if (!prepareAppDescriptorFile(info.appDescriptorPath, preparedAppDescriptorFile)) { // If there is an error, prepareAppDescriptorFile() will raise it delete preparedAppDescriptorFile; return false; } m_preparedAppDescriptorFiles << preparedAppDescriptorFile; QStringList args; args << QLatin1String("-devMode"); if (!debugToken().isEmpty()) args << QLatin1String("-debugToken") << QnxUtils::addQuotes(QDir::toNativeSeparators(debugToken())); args << QLatin1String("-package") << QnxUtils::addQuotes(QDir::toNativeSeparators(info.packagePath)); args << QnxUtils::addQuotes(QDir::toNativeSeparators(preparedAppDescriptorFile->fileName())); addCommand(packageCmd, args); } return true; } void BlackBerryCreatePackageStep::cleanup() { while (!m_preparedAppDescriptorFiles.isEmpty()) { QTemporaryFile *file = m_preparedAppDescriptorFiles.takeFirst(); delete file; } } ProjectExplorer::BuildStepConfigWidget *BlackBerryCreatePackageStep::createConfigWidget() { return new BlackBerryCreatePackageStepConfigWidget(); } QString BlackBerryCreatePackageStep::debugToken() const { BlackBerryDeviceConfiguration::ConstPtr device = BlackBerryDeviceConfiguration::device(target()->kit()); if (!device) return QString(); return device->debugToken(); } void BlackBerryCreatePackageStep::raiseError(const QString &errorMessage) { emit addOutput(errorMessage, BuildStep::ErrorMessageOutput); emit addTask(ProjectExplorer::Task(ProjectExplorer::Task::Error, errorMessage, Utils::FileName(), -1, Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM))); cleanup(); } bool BlackBerryCreatePackageStep::prepareAppDescriptorFile(const QString &appDescriptorPath, QTemporaryFile *preparedFile) { BlackBerryQtVersion *qtVersion = dynamic_cast<BlackBerryQtVersion *>(QtSupport::QtKitInformation::qtVersion(target()->kit())); if (!qtVersion) { raiseError(tr("Error preparing application descriptor file")); return false; } QFile file(appDescriptorPath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { raiseError(tr("Could not open '%1' for reading").arg(appDescriptorPath)); return false; } QByteArray fileContent = file.readAll(); // Replace Qt path placeholders if (fileContent.contains(QT_INSTALL_LIBS_VAR)) fileContent.replace(QT_INSTALL_LIBS_VAR, qtVersion->versionInfo().value(QLatin1String(QT_INSTALL_LIBS)).toLatin1()); if (fileContent.contains(QT_INSTALL_PLUGINS_VAR)) fileContent.replace(QT_INSTALL_PLUGINS_VAR, qtVersion->versionInfo().value(QLatin1String(QT_INSTALL_PLUGINS)).toLatin1()); if (fileContent.contains(QT_INSTALL_IMPORTS_VAR)) fileContent.replace(QT_INSTALL_IMPORTS_VAR, qtVersion->versionInfo().value(QLatin1String(QT_INSTALL_IMPORTS)).toLatin1()); if (fileContent.contains(QT_INSTALL_QML_VAR)) fileContent.replace(QT_INSTALL_QML_VAR, qtVersion->versionInfo().value(QLatin1String(QT_INSTALL_QML)).toLatin1()); //Replace Source path placeholder if (fileContent.contains(SRC_DIR_VAR)) fileContent.replace(SRC_DIR_VAR, QDir::toNativeSeparators(target()->project()->projectDirectory()).toLatin1()); // Add parameter for QML debugging (if enabled) if (target()->activeRunConfiguration()->debuggerAspect()->useQmlDebugger()) { if (!fileContent.contains("-qmljsdebugger")) { const QString argString = QString::fromLatin1("<arg>-qmljsdebugger=port:%1</arg>\n</qnx>") .arg(target()->activeRunConfiguration()->debuggerAspect()->qmlDebugServerPort()); fileContent.replace("</qnx>", argString.toLatin1()); } } const QString buildDir = target()->activeBuildConfiguration()->buildDirectory(); if (!preparedFile->open()) { raiseError(tr("Could not create prepared application descriptor file in '%1'").arg(buildDir)); return false; } preparedFile->write(fileContent); preparedFile->close(); return true; } <|endoftext|>
<commit_before>/*************************************************************************/ /* gd_mono_property.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "gd_mono_property.h" #include "gd_mono_class.h" #include "gd_mono_marshal.h" #include <mono/metadata/attrdefs.h> GDMonoProperty::GDMonoProperty(MonoProperty *p_mono_property, GDMonoClass *p_owner) { owner = p_owner; mono_property = p_mono_property; name = mono_property_get_name(mono_property); MonoMethod *prop_method = mono_property_get_get_method(mono_property); if (prop_method) { MonoMethodSignature *getter_sig = mono_method_signature(prop_method); MonoType *ret_type = mono_signature_get_return_type(getter_sig); type.type_encoding = mono_type_get_type(ret_type); MonoClass *ret_type_class = mono_class_from_mono_type(ret_type); type.type_class = GDMono::get_singleton()->get_class(ret_type_class); } else { prop_method = mono_property_get_set_method(mono_property); MonoMethodSignature *setter_sig = mono_method_signature(prop_method); void *iter = NULL; MonoType *param_raw_type = mono_signature_get_params(setter_sig, &iter); type.type_encoding = mono_type_get_type(param_raw_type); MonoClass *param_type_class = mono_class_from_mono_type(param_raw_type); type.type_class = GDMono::get_singleton()->get_class(param_type_class); } attrs_fetched = false; attributes = NULL; } GDMonoProperty::~GDMonoProperty() { if (attributes) { mono_custom_attrs_free(attributes); } } bool GDMonoProperty::is_static() { MonoMethod *prop_method = mono_property_get_get_method(mono_property); if (prop_method == NULL) prop_method = mono_property_get_set_method(mono_property); return mono_method_get_flags(prop_method, NULL) & MONO_METHOD_ATTR_STATIC; } GDMonoClassMember::Visibility GDMonoProperty::get_visibility() { MonoMethod *prop_method = mono_property_get_get_method(mono_property); if (prop_method == NULL) prop_method = mono_property_get_set_method(mono_property); switch (mono_method_get_flags(prop_method, NULL) & MONO_METHOD_ATTR_ACCESS_MASK) { case MONO_METHOD_ATTR_PRIVATE: return GDMonoClassMember::PRIVATE; case MONO_METHOD_ATTR_FAM_AND_ASSEM: return GDMonoClassMember::PROTECTED_AND_INTERNAL; case MONO_METHOD_ATTR_ASSEM: return GDMonoClassMember::INTERNAL; case MONO_METHOD_ATTR_FAMILY: return GDMonoClassMember::PROTECTED; case MONO_METHOD_ATTR_PUBLIC: return GDMonoClassMember::PUBLIC; default: ERR_FAIL_V(GDMonoClassMember::PRIVATE); } } bool GDMonoProperty::has_attribute(GDMonoClass *p_attr_class) { ERR_FAIL_NULL_V(p_attr_class, false); if (!attrs_fetched) fetch_attributes(); if (!attributes) return false; return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr()); } MonoObject *GDMonoProperty::get_attribute(GDMonoClass *p_attr_class) { ERR_FAIL_NULL_V(p_attr_class, NULL); if (!attrs_fetched) fetch_attributes(); if (!attributes) return NULL; return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr()); } void GDMonoProperty::fetch_attributes() { ERR_FAIL_COND(attributes != NULL); attributes = mono_custom_attrs_from_property(owner->get_mono_ptr(), mono_property); attrs_fetched = true; } bool GDMonoProperty::has_getter() { return mono_property_get_get_method(mono_property) != NULL; } bool GDMonoProperty::has_setter() { return mono_property_get_set_method(mono_property) != NULL; } void GDMonoProperty::set_value(MonoObject *p_object, MonoObject *p_value, MonoObject **r_exc) { MonoMethod *prop_method = mono_property_get_get_method(mono_property); MonoArray *params = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), 1); mono_array_set(params, MonoObject *, 0, p_value); MonoObject *exc = NULL; mono_runtime_invoke_array(prop_method, p_object, params, &exc); if (exc) { if (r_exc) { *r_exc = exc; } else { GDMonoUtils::print_unhandled_exception(exc); } } } void GDMonoProperty::set_value(MonoObject *p_object, void **p_params, MonoObject **r_exc) { MonoObject *exc = NULL; mono_property_set_value(mono_property, p_object, p_params, &exc); if (exc) { if (r_exc) { *r_exc = exc; } else { GDMonoUtils::print_unhandled_exception(exc); } } } MonoObject *GDMonoProperty::get_value(MonoObject *p_object, MonoObject **r_exc) { MonoObject *exc = NULL; MonoObject *ret = mono_property_get_value(mono_property, p_object, NULL, &exc); if (exc) { ret = NULL; if (r_exc) { *r_exc = exc; } else { GDMonoUtils::print_unhandled_exception(exc); } } return ret; } bool GDMonoProperty::get_bool_value(MonoObject *p_object) { return (bool)GDMonoMarshal::unbox<MonoBoolean>(get_value(p_object)); } int GDMonoProperty::get_int_value(MonoObject *p_object) { return GDMonoMarshal::unbox<int32_t>(get_value(p_object)); } String GDMonoProperty::get_string_value(MonoObject *p_object) { MonoObject *val = get_value(p_object); return GDMonoMarshal::mono_string_to_godot((MonoString *)val); } <commit_msg>fix GDMonoProperty::set_value<commit_after>/*************************************************************************/ /* gd_mono_property.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "gd_mono_property.h" #include "gd_mono_class.h" #include "gd_mono_marshal.h" #include <mono/metadata/attrdefs.h> GDMonoProperty::GDMonoProperty(MonoProperty *p_mono_property, GDMonoClass *p_owner) { owner = p_owner; mono_property = p_mono_property; name = mono_property_get_name(mono_property); MonoMethod *prop_method = mono_property_get_get_method(mono_property); if (prop_method) { MonoMethodSignature *getter_sig = mono_method_signature(prop_method); MonoType *ret_type = mono_signature_get_return_type(getter_sig); type.type_encoding = mono_type_get_type(ret_type); MonoClass *ret_type_class = mono_class_from_mono_type(ret_type); type.type_class = GDMono::get_singleton()->get_class(ret_type_class); } else { prop_method = mono_property_get_set_method(mono_property); MonoMethodSignature *setter_sig = mono_method_signature(prop_method); void *iter = NULL; MonoType *param_raw_type = mono_signature_get_params(setter_sig, &iter); type.type_encoding = mono_type_get_type(param_raw_type); MonoClass *param_type_class = mono_class_from_mono_type(param_raw_type); type.type_class = GDMono::get_singleton()->get_class(param_type_class); } attrs_fetched = false; attributes = NULL; } GDMonoProperty::~GDMonoProperty() { if (attributes) { mono_custom_attrs_free(attributes); } } bool GDMonoProperty::is_static() { MonoMethod *prop_method = mono_property_get_get_method(mono_property); if (prop_method == NULL) prop_method = mono_property_get_set_method(mono_property); return mono_method_get_flags(prop_method, NULL) & MONO_METHOD_ATTR_STATIC; } GDMonoClassMember::Visibility GDMonoProperty::get_visibility() { MonoMethod *prop_method = mono_property_get_get_method(mono_property); if (prop_method == NULL) prop_method = mono_property_get_set_method(mono_property); switch (mono_method_get_flags(prop_method, NULL) & MONO_METHOD_ATTR_ACCESS_MASK) { case MONO_METHOD_ATTR_PRIVATE: return GDMonoClassMember::PRIVATE; case MONO_METHOD_ATTR_FAM_AND_ASSEM: return GDMonoClassMember::PROTECTED_AND_INTERNAL; case MONO_METHOD_ATTR_ASSEM: return GDMonoClassMember::INTERNAL; case MONO_METHOD_ATTR_FAMILY: return GDMonoClassMember::PROTECTED; case MONO_METHOD_ATTR_PUBLIC: return GDMonoClassMember::PUBLIC; default: ERR_FAIL_V(GDMonoClassMember::PRIVATE); } } bool GDMonoProperty::has_attribute(GDMonoClass *p_attr_class) { ERR_FAIL_NULL_V(p_attr_class, false); if (!attrs_fetched) fetch_attributes(); if (!attributes) return false; return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr()); } MonoObject *GDMonoProperty::get_attribute(GDMonoClass *p_attr_class) { ERR_FAIL_NULL_V(p_attr_class, NULL); if (!attrs_fetched) fetch_attributes(); if (!attributes) return NULL; return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr()); } void GDMonoProperty::fetch_attributes() { ERR_FAIL_COND(attributes != NULL); attributes = mono_custom_attrs_from_property(owner->get_mono_ptr(), mono_property); attrs_fetched = true; } bool GDMonoProperty::has_getter() { return mono_property_get_get_method(mono_property) != NULL; } bool GDMonoProperty::has_setter() { return mono_property_get_set_method(mono_property) != NULL; } void GDMonoProperty::set_value(MonoObject *p_object, MonoObject *p_value, MonoObject **r_exc) { MonoMethod *prop_method = mono_property_get_set_method(mono_property); MonoArray *params = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), 1); mono_array_set(params, MonoObject *, 0, p_value); MonoObject *exc = NULL; mono_runtime_invoke_array(prop_method, p_object, params, &exc); if (exc) { if (r_exc) { *r_exc = exc; } else { GDMonoUtils::print_unhandled_exception(exc); } } } void GDMonoProperty::set_value(MonoObject *p_object, void **p_params, MonoObject **r_exc) { MonoObject *exc = NULL; mono_property_set_value(mono_property, p_object, p_params, &exc); if (exc) { if (r_exc) { *r_exc = exc; } else { GDMonoUtils::print_unhandled_exception(exc); } } } MonoObject *GDMonoProperty::get_value(MonoObject *p_object, MonoObject **r_exc) { MonoObject *exc = NULL; MonoObject *ret = mono_property_get_value(mono_property, p_object, NULL, &exc); if (exc) { ret = NULL; if (r_exc) { *r_exc = exc; } else { GDMonoUtils::print_unhandled_exception(exc); } } return ret; } bool GDMonoProperty::get_bool_value(MonoObject *p_object) { return (bool)GDMonoMarshal::unbox<MonoBoolean>(get_value(p_object)); } int GDMonoProperty::get_int_value(MonoObject *p_object) { return GDMonoMarshal::unbox<int32_t>(get_value(p_object)); } String GDMonoProperty::get_string_value(MonoObject *p_object) { MonoObject *val = get_value(p_object); return GDMonoMarshal::mono_string_to_godot((MonoString *)val); } <|endoftext|>
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_WINDOWS_EXISTS_HPP__ #define __STOUT_OS_WINDOWS_EXISTS_HPP__ #include <string> #include <stout/windows.hpp> #include <stout/os/realpath.hpp> namespace os { inline bool exists(const std::string& path) { Result<std::string> absolutePath = os::realpath(path); if (!absolutePath.isSome()) { return false; } // NOTE: `GetFileAttributes` redirects to either `GetFileAttributesA` // (ASCII) or `GetFileAttributesW` (for `wchar`s). It returns // `INVALID_FILE_ATTRIBUTES` if the file could not be opened for any reason. // Checking for one of two 'not found' error codes (`ERROR_FILE_NOT_FOUND` or // `ERROR_PATH_NOT_FOUND`) is a reliable test for whether the file or // directory exists. See also [1] for more information on this technique. // // [1] http://blogs.msdn.com/b/oldnewthing/archive/2007/10/23/5612082.aspx DWORD attributes = GetFileAttributes(absolutePath.get().c_str()); if (attributes == INVALID_FILE_ATTRIBUTES) { DWORD error = GetLastError(); if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) { return false; } } return true; } // Determine if the process identified by pid exists. // NOTE: Zombie processes have a pid and therefore exist. See // os::process(pid) to get details of a process. inline bool exists(pid_t pid) { HANDLE handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); // NOTE: `GetExitCode` will gracefully deal with the case that `handle` is // `NULL`. DWORD exitCode = 0; BOOL exitCodeExists = GetExitCodeProcess(handle, &exitCode); // `CloseHandle`, on the other hand, will throw an exception in the // VS debugger if you pass it a broken handle. (cf. "Return value" // section of the documentation[1].) // // [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms724211(v=vs.85).aspx if (handle != NULL) { CloseHandle(handle); } // NOTE: Windows quirk, the exit code returned by the process can // be the same number as `STILL_ACTIVE`, in which case this // function will mis-report that the process still exists. return exitCodeExists && (exitCode == STILL_ACTIVE); } } // namespace os { #endif // __STOUT_OS_WINDOWS_EXISTS_HPP__ <commit_msg>Windows: Simplified `os::exists`.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_WINDOWS_EXISTS_HPP__ #define __STOUT_OS_WINDOWS_EXISTS_HPP__ #include <string> #include <stout/windows.hpp> #include <stout/os/realpath.hpp> namespace os { inline bool exists(const std::string& path) { Result<std::string> absolutePath = os::realpath(path); if (!absolutePath.isSome()) { return false; } // NOTE: `GetFileAttributes` redirects to either `GetFileAttributesA` // (ASCII) or `GetFileAttributesW` (for `wchar`s). It returns // `INVALID_FILE_ATTRIBUTES` if the file could not be opened for any reason. // Checking for one of two 'not found' error codes (`ERROR_FILE_NOT_FOUND` or // `ERROR_PATH_NOT_FOUND`) is a reliable test for whether the file or // directory exists. See also [1] for more information on this technique. // // [1] http://blogs.msdn.com/b/oldnewthing/archive/2007/10/23/5612082.aspx DWORD attributes = GetFileAttributes(absolutePath.get().c_str()); if (attributes == INVALID_FILE_ATTRIBUTES) { DWORD error = GetLastError(); if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) { return false; } } return true; } // Determine if the process identified by pid exists. // NOTE: Zombie processes have a pid and therefore exist. See // os::process(pid) to get details of a process. inline bool exists(pid_t pid) { HANDLE handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); bool has_handle = false; if (handle != NULL) { has_handle = true; CloseHandle(handle); } return has_handle; } } // namespace os { #endif // __STOUT_OS_WINDOWS_EXISTS_HPP__ <|endoftext|>
<commit_before>#include "SolidMaterial.h" template<> InputParameters validParams<SolidMaterial>() { InputParameters params = validParams<Material>(); // Coupled variables params.addRequiredCoupledVar("tw", ""); params.addRequiredParam<std::string>("name_of_hs", "heat structure name"); return params; } SolidMaterial::SolidMaterial(const std::string & name, InputParameters parameters) : Material(name, parameters), _thermal_conductivity(declareProperty<Real>("thermal_conductivity")), _specific_heat(declareProperty<Real>("specific_heat")), _density(declareProperty<Real>("density")), _tw(coupledValue("tw")), _name_of_hs(getParam<std::string>("name_of_hs")) { } void SolidMaterial::computeProperties() { Real K=0.0; Real Cp=0.0; Real Rho = 0.0; for (unsigned int qp = 0; qp < _qrule->n_points(); qp++) { if (_name_of_hs == "fuel") fuelProperties(K, Rho, Cp, _tw[qp]); else if (_name_of_hs =="gap") gapProperties(K, Rho, Cp, _tw[qp]); else if (_name_of_hs == "clad") cladProperties(K, Rho, Cp, _tw[qp]); else mooseError("Heat structure is not specified"); _thermal_conductivity[qp] = K; _density[qp] = Rho; _specific_heat[qp] = Cp; //std::cout<<"name_of_hs="<< _name_of_hs<<std::endl; //std::cout<<"qp="<<qp<<" tw="<<_tw[qp]<<" conductivity="<<_thermal_conductivity[qp]<<" density="<<_density[qp]<<" Cp="<<_specific_heat[qp]<<std::endl; } } void SolidMaterial::gapProperties(Real & K, Real & Rho, Real & Cp, Real Temp) { Real T_gap[] = {5.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, 1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0, 2800.0, 2900.0, 3000.0, 5000.0}; Real K_gap[] = {0.0104, 0.0104, 0.0132, 0.0159, 0.0185, 0.0211, 0.0236, 0.0260, 0.0284, 0.0307, 0.0330, 0.0353, 0.0376, 0.0398, 0.0420, 0.0442, 0.0463, 0.0485, 0.0506, 0.0527, 0.0548, 0.0568, 0.0589, 0.0609, 0.0630, 0.0650, 0.0670, 0.0690, 0.0709, 0.0709}; unsigned int N = sizeof(K_gap)/sizeof(K_gap[0]); if (Temp <= T_gap[0]) K = K_gap[0]; else if (Temp >=T_gap[N-1]) K = K_gap[N-1]; else { unsigned int i=1; for (; i<N; i++) { if (Temp<=T_gap[i]) break; } K = ((Temp-T_gap[i-1])*K_gap[i] + (T_gap[i]-Temp)*K_gap[i-1])/(T_gap[i]-T_gap[i-1]); } Rho = 183.06; Cp = 186.65; } void SolidMaterial::fuelProperties(Real & K, Real & Rho, Real & Cp, Real Temp) { std::vector<Real> T_Fuel_K(35), K_Fuel(35), T_Fuel_RhoCp(33), RhoCp_Fuel(33); Real T_fuel_K[] = { 5.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0, 1300.0, 1364.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, 1877.0, 1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0, 2800.0, 2900.0, 3000.0, 3100.0, 3113.0, 3114.0, 5000.0}; Real K_fuel[] = {8.284, 8.284, 7.086, 6.087, 5.316, 4.721, 4.255, 3.882, 3.580, 3.330, 3.123, 2.951, 2.855, 2.794, 2.642, 2.515, 2.411, 2.330, 2.327, 2.322, 2.308, 2.310, 2.328, 2.363, 2.462, 2.576, 2.706, 2.852, 3.014, 3.193, 3.388, 3.600, 3.629, 11.50, 11.50}; unsigned int N = sizeof(K_fuel)/sizeof(K_fuel[0]); if (Temp <= T_fuel_K[0]) K = K_fuel[0]; else if (Temp >=T_fuel_K[N-1]) K = K_fuel[N-1]; else { unsigned int i=1; for (; i<N; i++) { if (Temp<=T_fuel_K[i]) break; } K = ((Temp-T_fuel_K[i-1])*K_fuel[i] + (T_fuel_K[i]-Temp)*K_fuel[i-1])/(T_fuel_K[i]-T_fuel_K[i-1]); } Real T_fuel_Cp[] = { 5.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, 1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0, 2800.0, 2900.0, 3000.0, 3100.0, 3113.0, 3114.0, 5000.0}; Real Cp_fuel[] = {236.339, 236.339, 265.847, 282.058, 292.350, 299.636, 305.282, 310.018, 314.026, 317.668, 321.129, 324.590, 328.233, 332.423, 337.432, 343.807, 351.821, 362.113, 375.046, 391.075, 410.474, 433.424, 460.200, 490.893, 525.410, 563.752, 605.647, 651.093, 699.727, 751.366, 758.288, 503.005, 503.005}; unsigned int M = sizeof(Cp_fuel)/sizeof(Cp_fuel[0]); if (Temp <= T_fuel_Cp[0]) Cp = Cp_fuel[0]; else if (Temp >=T_fuel_Cp[M-1]) Cp = Cp_fuel[M-1]; else { unsigned int i=1; for (; i<M; i++) { if (Temp<=T_fuel_Cp[i]) break; } Cp = ((Temp-T_fuel_Cp[i-1])*Cp_fuel[i] + (T_fuel_Cp[i]-Temp)*Cp_fuel[i-1])/(T_fuel_Cp[i]-T_fuel_Cp[i-1]); } Rho = 10980.0; } void SolidMaterial::cladProperties(Real & K, Real & Rho, Real & Cp, Real Temp) { Real T_clad_K[] = { 5.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, 1900.0, 2000.0, 2098.0, 2125.0, 5000.0}; Real K_clad[] = {12.68, 12.68, 14.04, 15.29, 16.49, 17.67, 18.88, 20.17, 21.58, 23.16, 24.96, 27.03, 29.40, 32.12, 35.25, 38.82, 42.88, 47.48, 52.67, 58.36, 36.00, 36.00}; unsigned int N = sizeof(K_clad)/sizeof(K_clad[0]); if (Temp <= T_clad_K[0]) K = K_clad[0]; else if (Temp >=T_clad_K[N-1]) K = K_clad[N-1]; else { unsigned int i=1; for (; i<N; i++) { if (Temp<=T_clad_K[i]) break; } K = ((Temp-T_clad_K[i-1])*K_clad[i] + (T_clad_K[i]-Temp)*K_clad[i-1])/(T_clad_K[i]-T_clad_K[i-1]); } Real T_clad_Cp[] = { 5.0, 300.0, 400.0, 640.0, 1090.0, 1093.0, 1113.0, 1133.0, 1153.0, 1173.0, 1193.0, 1213.0, 1233.0, 1248.0, 5000.0}; Real Cp_clad[] = {281.026, 281.026, 301.939, 330.942, 375.057, 502.061, 589.986, 615.021, 718.974, 816.059, 769.959, 618.989, 468.936, 355.976, 355.976}; unsigned int M = sizeof(Cp_clad)/sizeof(Cp_clad[0]); if (Temp <= T_clad_Cp[0]) Cp = Cp_clad[0]; else if (Temp >=T_clad_Cp[M-1]) Cp = Cp_clad[M-1]; else { unsigned int i=1; for (; i<M; i++) { if (Temp<=T_clad_Cp[i]) break; } Cp = ((Temp-T_clad_Cp[i-1])*Cp_clad[i] + (T_clad_Cp[i]-Temp)*Cp_clad[i-1])/(T_clad_Cp[i]-T_clad_Cp[i-1]); } Rho = 6551.0; return; } void SolidMaterial::residualSetup() { } <commit_msg>Fixing strange file permissions... C files should not have execute bit set.<commit_after>#include "SolidMaterial.h" template<> InputParameters validParams<SolidMaterial>() { InputParameters params = validParams<Material>(); // Coupled variables params.addRequiredCoupledVar("tw", ""); params.addRequiredParam<std::string>("name_of_hs", "heat structure name"); return params; } SolidMaterial::SolidMaterial(const std::string & name, InputParameters parameters) : Material(name, parameters), _thermal_conductivity(declareProperty<Real>("thermal_conductivity")), _specific_heat(declareProperty<Real>("specific_heat")), _density(declareProperty<Real>("density")), _tw(coupledValue("tw")), _name_of_hs(getParam<std::string>("name_of_hs")) { } void SolidMaterial::computeProperties() { Real K=0.0; Real Cp=0.0; Real Rho = 0.0; for (unsigned int qp = 0; qp < _qrule->n_points(); qp++) { if (_name_of_hs == "fuel") fuelProperties(K, Rho, Cp, _tw[qp]); else if (_name_of_hs =="gap") gapProperties(K, Rho, Cp, _tw[qp]); else if (_name_of_hs == "clad") cladProperties(K, Rho, Cp, _tw[qp]); else mooseError("Heat structure is not specified"); _thermal_conductivity[qp] = K; _density[qp] = Rho; _specific_heat[qp] = Cp; //std::cout<<"name_of_hs="<< _name_of_hs<<std::endl; //std::cout<<"qp="<<qp<<" tw="<<_tw[qp]<<" conductivity="<<_thermal_conductivity[qp]<<" density="<<_density[qp]<<" Cp="<<_specific_heat[qp]<<std::endl; } } void SolidMaterial::gapProperties(Real & K, Real & Rho, Real & Cp, Real Temp) { Real T_gap[] = {5.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, 1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0, 2800.0, 2900.0, 3000.0, 5000.0}; Real K_gap[] = {0.0104, 0.0104, 0.0132, 0.0159, 0.0185, 0.0211, 0.0236, 0.0260, 0.0284, 0.0307, 0.0330, 0.0353, 0.0376, 0.0398, 0.0420, 0.0442, 0.0463, 0.0485, 0.0506, 0.0527, 0.0548, 0.0568, 0.0589, 0.0609, 0.0630, 0.0650, 0.0670, 0.0690, 0.0709, 0.0709}; unsigned int N = sizeof(K_gap)/sizeof(K_gap[0]); if (Temp <= T_gap[0]) K = K_gap[0]; else if (Temp >=T_gap[N-1]) K = K_gap[N-1]; else { unsigned int i=1; for (; i<N; i++) { if (Temp<=T_gap[i]) break; } K = ((Temp-T_gap[i-1])*K_gap[i] + (T_gap[i]-Temp)*K_gap[i-1])/(T_gap[i]-T_gap[i-1]); } Rho = 183.06; Cp = 186.65; } void SolidMaterial::fuelProperties(Real & K, Real & Rho, Real & Cp, Real Temp) { std::vector<Real> T_Fuel_K(35), K_Fuel(35), T_Fuel_RhoCp(33), RhoCp_Fuel(33); Real T_fuel_K[] = { 5.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0, 1300.0, 1364.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, 1877.0, 1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0, 2800.0, 2900.0, 3000.0, 3100.0, 3113.0, 3114.0, 5000.0}; Real K_fuel[] = {8.284, 8.284, 7.086, 6.087, 5.316, 4.721, 4.255, 3.882, 3.580, 3.330, 3.123, 2.951, 2.855, 2.794, 2.642, 2.515, 2.411, 2.330, 2.327, 2.322, 2.308, 2.310, 2.328, 2.363, 2.462, 2.576, 2.706, 2.852, 3.014, 3.193, 3.388, 3.600, 3.629, 11.50, 11.50}; unsigned int N = sizeof(K_fuel)/sizeof(K_fuel[0]); if (Temp <= T_fuel_K[0]) K = K_fuel[0]; else if (Temp >=T_fuel_K[N-1]) K = K_fuel[N-1]; else { unsigned int i=1; for (; i<N; i++) { if (Temp<=T_fuel_K[i]) break; } K = ((Temp-T_fuel_K[i-1])*K_fuel[i] + (T_fuel_K[i]-Temp)*K_fuel[i-1])/(T_fuel_K[i]-T_fuel_K[i-1]); } Real T_fuel_Cp[] = { 5.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, 1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0, 2800.0, 2900.0, 3000.0, 3100.0, 3113.0, 3114.0, 5000.0}; Real Cp_fuel[] = {236.339, 236.339, 265.847, 282.058, 292.350, 299.636, 305.282, 310.018, 314.026, 317.668, 321.129, 324.590, 328.233, 332.423, 337.432, 343.807, 351.821, 362.113, 375.046, 391.075, 410.474, 433.424, 460.200, 490.893, 525.410, 563.752, 605.647, 651.093, 699.727, 751.366, 758.288, 503.005, 503.005}; unsigned int M = sizeof(Cp_fuel)/sizeof(Cp_fuel[0]); if (Temp <= T_fuel_Cp[0]) Cp = Cp_fuel[0]; else if (Temp >=T_fuel_Cp[M-1]) Cp = Cp_fuel[M-1]; else { unsigned int i=1; for (; i<M; i++) { if (Temp<=T_fuel_Cp[i]) break; } Cp = ((Temp-T_fuel_Cp[i-1])*Cp_fuel[i] + (T_fuel_Cp[i]-Temp)*Cp_fuel[i-1])/(T_fuel_Cp[i]-T_fuel_Cp[i-1]); } Rho = 10980.0; } void SolidMaterial::cladProperties(Real & K, Real & Rho, Real & Cp, Real Temp) { Real T_clad_K[] = { 5.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, 1900.0, 2000.0, 2098.0, 2125.0, 5000.0}; Real K_clad[] = {12.68, 12.68, 14.04, 15.29, 16.49, 17.67, 18.88, 20.17, 21.58, 23.16, 24.96, 27.03, 29.40, 32.12, 35.25, 38.82, 42.88, 47.48, 52.67, 58.36, 36.00, 36.00}; unsigned int N = sizeof(K_clad)/sizeof(K_clad[0]); if (Temp <= T_clad_K[0]) K = K_clad[0]; else if (Temp >=T_clad_K[N-1]) K = K_clad[N-1]; else { unsigned int i=1; for (; i<N; i++) { if (Temp<=T_clad_K[i]) break; } K = ((Temp-T_clad_K[i-1])*K_clad[i] + (T_clad_K[i]-Temp)*K_clad[i-1])/(T_clad_K[i]-T_clad_K[i-1]); } Real T_clad_Cp[] = { 5.0, 300.0, 400.0, 640.0, 1090.0, 1093.0, 1113.0, 1133.0, 1153.0, 1173.0, 1193.0, 1213.0, 1233.0, 1248.0, 5000.0}; Real Cp_clad[] = {281.026, 281.026, 301.939, 330.942, 375.057, 502.061, 589.986, 615.021, 718.974, 816.059, 769.959, 618.989, 468.936, 355.976, 355.976}; unsigned int M = sizeof(Cp_clad)/sizeof(Cp_clad[0]); if (Temp <= T_clad_Cp[0]) Cp = Cp_clad[0]; else if (Temp >=T_clad_Cp[M-1]) Cp = Cp_clad[M-1]; else { unsigned int i=1; for (; i<M; i++) { if (Temp<=T_clad_Cp[i]) break; } Cp = ((Temp-T_clad_Cp[i-1])*Cp_clad[i] + (T_clad_Cp[i]-Temp)*Cp_clad[i-1])/(T_clad_Cp[i]-T_clad_Cp[i-1]); } Rho = 6551.0; return; } void SolidMaterial::residualSetup() { } <|endoftext|>
<commit_before>#ifndef ULAM_HPP #define ULAM_HPP #include <algorithm> namespace ulam{ /** * Converts a prime list index to a spiral index (n is odd) (4) * * */ size_t stol(size_t i, size_t n){ size_t line = i / n; size_t col = i % n; size_t ring_index, side_col = 1, side_line = 1; if(col < n - line){ ring_index = std::min(line, col); } else{ ring_index = n - col - 1; if(col > line) side_line = -1; if(col <= line) side_col = -1; } size_t sub_size = n - ring_index * 2; return sub_size * sub_size - (sub_size - 1) * 2 + side_line * line - side_col * col; // -1 } } #endif // ULAM_HPP<commit_msg>fixed ulam index translator<commit_after>#ifndef ULAM_HPP #define ULAM_HPP #include <algorithm> namespace ulam{ /** * Converts a prime list index to a spiral index (n is odd) (4) * * */ size_t stol(size_t i, size_t n){ size_t line = i / n; size_t col = i % n; size_t ring_index, side_col = 1, side_line = 1; if(col < n - line){ ring_index = std::min(line, col); } else if(col > line){ ring_index = n - col - 1; side_line = -1; } else{ ring_index = n - line - 1; side_col = -1; } size_t sub_size = n - ring_index * 2; return sub_size * sub_size - (sub_size - 1) * 2 + side_line * (line - ring_index) - side_col * (col - ring_index) - 1; } } #endif // ULAM_HPP<|endoftext|>
<commit_before>/* * Reference: http://plms.oxfordjournals.org/content/s2-42/1/230.full.pdf+html * * Instruction set * =============== * m-config symbol operations final m-config * string char op1,op2,... string * * op: * L - move left one step * R - move right one step * P<symbol> - print symbol on tap * E - erase symbol from tap * symbol: * ~ - matches blank cell * * - matches any symbol * other char matches themselves * * Lines starting with # are ignored by the interpreter */ #include <iostream> #include <string> #include <regex> #include <map> #include <vector> #include <queue> using namespace std; struct Configuration { string state; char symbol; bool operator<(const Configuration &o) const { return state < o.state || (state == o.state && symbol < o.symbol); } }; struct Action { string ops; string state; }; struct Machine { int tp = 0; string curr; map< Configuration, Action > program; map< int, char > tape; void load_program() { cin.sync_with_stdio(false); string line; while (getline(cin, line)) { // skip empty lines if (line.length() == 0) { continue; } // lines begining with # are comments if (line.at(0) == '#') { continue; } istringstream iss(line); string state, symbol, ops, fstate; iss >> state >> symbol >> ops >> fstate; if (curr.length() == 0) { curr = state; } Configuration c = {state, symbol.at(0)}; Action a = {ops, fstate}; program[c] = a; } } void print_program() { for (auto it = program.begin(); it != program.end(); it++) { cout << it->first.state << " "; cout << it->first.symbol << " "; cout << it->second.ops << " "; cout << it->second.state << endl; } } void print_tape() { cout << "tape: "; for (auto it = tape.begin(); it != tape.end(); it++) { cout << it->second; } cout << endl; } char read_tape() { if (tape.count(tp)) { return tape[tp]; } else { return '~'; } } int perform_ops(string ops) { for (int i = 0; i < ops.length(); i++) { char op = ops.at(i); switch (op) { case 'R': tp++; break; case 'L': tp--; break; case 'E': tape[tp] = '~'; break; case 'P': i++; tape[tp] = ops.at(i); break; case ',': break; default: cout << "unknown op: " << op << endl; exit(1); } } return tp; } void run(int max) { int cnt = 0; while (cnt < max) { Configuration c = {curr, read_tape()}; if (program.count(c) == 0) { c = {curr, '*'}; } if (program.count(c) == 0) { break; } Action a = program[c]; tp = perform_ops(a.ops); curr = a.state; cnt++; print_config(c); print_tape(); } } void print_config(Configuration c) { cout << "conf: " << c.state << " " << c.symbol << endl; } }; int main(int argc, char *argv[]) { Machine m; m.load_program(); m.print_program(); m.run(1000); return 0; } <commit_msg>add tape contents after ---<commit_after>/* * Reference: http://plms.oxfordjournals.org/content/s2-42/1/230.full.pdf+html * * Instruction set * =============== * m-config symbol operations final m-config * string char op1,op2,... string * * op: * L - move left one step * R - move right one step * P<symbol> - print symbol on tap * E - erase symbol from tap * symbol: * ~ - matches blank cell * * - matches any symbol * other char matches themselves * * Lines starting with # are ignored by the interpreter */ #include <iostream> #include <string> #include <regex> #include <map> #include <vector> #include <queue> using namespace std; struct Configuration { string state; char symbol; bool operator<(const Configuration &o) const { return state < o.state || (state == o.state && symbol < o.symbol); } }; struct Action { string ops; string state; }; struct Machine { int tp = 0; string curr; map< Configuration, Action > program; map< int, char > tape; void load_program() { cin.sync_with_stdio(false); string line; while (getline(cin, line)) { // skip empty lines if (line.length() == 0) { continue; } // lines begining with # are comments if (line.at(0) == '#') { continue; } // initial tap appears after --- if (line.compare("---") == 0) { getline(cin, line); for (int i = 0; i < line.length(); i++) { tape[i] = line.at(i); } break; } istringstream iss(line); string state, symbol, ops, fstate; iss >> state >> symbol >> ops >> fstate; if (curr.length() == 0) { curr = state; } Configuration c = {state, symbol.at(0)}; Action a = {ops, fstate}; program[c] = a; } } void print_program() { for (auto it = program.begin(); it != program.end(); it++) { cout << it->first.state << " "; cout << it->first.symbol << " "; cout << it->second.ops << " "; cout << it->second.state << endl; } } void print_tape() { cout << "tape: "; for (auto it = tape.begin(); it != tape.end(); it++) { cout << it->second; } cout << endl; } char read_tape() { if (tape.count(tp)) { return tape[tp]; } else { return '~'; } } int perform_ops(string ops) { for (int i = 0; i < ops.length(); i++) { char op = ops.at(i); switch (op) { case 'R': tp++; break; case 'L': tp--; break; case 'E': tape[tp] = '~'; break; case 'P': i++; tape[tp] = ops.at(i); break; case ',': break; default: cout << "unknown op: " << op << endl; exit(1); } } return tp; } void run(int max) { int cnt = 0; while (cnt < max) { Configuration c = {curr, read_tape()}; if (program.count(c) == 0) { c = {curr, '*'}; } if (program.count(c) == 0) { break; } Action a = program[c]; tp = perform_ops(a.ops); curr = a.state; cnt++; print_config(c); print_tape(); } } void print_config(Configuration c) { cout << "conf: " << c.state << " " << c.symbol << endl; } }; int main(int argc, char *argv[]) { Machine m; m.load_program(); m.print_program(); m.run(1000); return 0; } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_GRID_WALKER_HH #define DUNE_STUFF_GRID_WALKER_HH #include <vector> #include <memory> #include <type_traits> #include <functional> #if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE # include <dune/grid/utility/partitioning/ranged.hh> # include <dune/stuff/common/parallel/threadmanager.hh> #endif #if HAVE_TBB # include <tbb/blocked_range.h> # include <tbb/parallel_reduce.h> # include <tbb/tbb_stddef.h> #endif #include <dune/stuff/grid/entity.hh> #include <dune/stuff/grid/intersection.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/common/parallel/threadmanager.hh> #include <dune/stuff/common/ranges.hh> #include "walker/functors.hh" #include "walker/apply-on.hh" #include "walker/wrapper.hh" namespace Dune { namespace Stuff { namespace Grid { template< class GridViewImp > class Walker : public Functor::Codim0And1< GridViewImp > { typedef Walker< GridViewImp > ThisType; public: typedef GridViewImp GridViewType; typedef typename Stuff::Grid::Entity< GridViewType >::Type EntityType; typedef typename Stuff::Grid::Intersection< GridViewType >::Type IntersectionType; explicit Walker(GridViewType grd_vw) : grid_view_(grd_vw) {} const GridViewType& grid_view() const { return grid_view_; } void add(std::function< void(const EntityType&) > lambda, const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >()) { codim0_functors_.emplace_back(new internal::Codim0LambdaWrapper< GridViewType >(lambda, where)); } void add(Functor::Codim0< GridViewType >& functor, const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >()) { codim0_functors_.emplace_back( new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0< GridViewType > >(functor, where)); } void add(Functor::Codim1< GridViewType >& functor, const ApplyOn::WhichIntersection< GridViewType >* where = new ApplyOn::AllIntersections< GridViewType >()) { codim1_functors_.emplace_back( new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim1< GridViewType > >(functor, where)); } void add(Functor::Codim0And1< GridViewType >& functor, const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >(), const ApplyOn::WhichIntersection< GridViewType >* which_intersections = new ApplyOn::AllIntersections< GridViewType >()) { codim0_functors_.emplace_back( new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor, which_entities)); codim1_functors_.emplace_back( new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor, which_intersections)); } void add(Functor::Codim0And1< GridViewType >& functor, const ApplyOn::WhichIntersection< GridViewType >* which_intersections, const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >()) { codim0_functors_.emplace_back( new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor, which_entities)); codim1_functors_.emplace_back( new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor, which_intersections)); } void add(ThisType& other, const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >(), const ApplyOn::WhichIntersection< GridViewType >* which_intersections = new ApplyOn::AllIntersections< GridViewType >()) { if (&other == this) DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not add a Walker to itself!"); codim0_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_entities)); codim1_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_intersections)); } // ... add(...) void add(ThisType& other, const ApplyOn::WhichIntersection< GridViewType >* which_intersections, const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >()) { if (&other == this) DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not add a Walker to itself!"); codim0_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_entities)); codim1_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_intersections)); } // ... add(...) void clear() { codim0_functors_.clear(); codim1_functors_.clear(); } // ... clear() virtual void prepare() { for (auto& functor : codim0_functors_) functor->prepare(); for (auto& functor : codim1_functors_) functor->prepare(); } // ... prepare() bool apply_on(const EntityType& entity) const { for (const auto& functor : codim0_functors_) if (functor->apply_on(grid_view_, entity)) return true; return false; } // ... apply_on(...) bool apply_on(const IntersectionType& intersection) const { for (const auto& functor : codim1_functors_) if (functor->apply_on(grid_view_, intersection)) return true; return false; } // ... apply_on(...) virtual void apply_local(const EntityType& entity) { for (auto& functor : codim0_functors_) if (functor->apply_on(grid_view_, entity)) functor->apply_local(entity); } // ... apply_local(...) virtual void apply_local(const IntersectionType& intersection, const EntityType& inside_entity, const EntityType& outside_entity) { for (auto& functor : codim1_functors_) if (functor->apply_on(grid_view_, intersection)) functor->apply_local(intersection, inside_entity, outside_entity); } // ... apply_local(...) virtual void finalize() { for (auto& functor : codim0_functors_) functor->finalize(); for (auto& functor : codim1_functors_) functor->finalize(); } // ... finalize() void walk(const bool use_tbb = false) { #if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE if (use_tbb) { const auto num_partitions = threadManager().current_threads(); RangedPartitioning< GridViewType, 0 > partitioning(grid_view_, num_partitions); this->walk(partitioning); return; } #else const auto DUNE_UNUSED(no_warning_for_use_tbb) = use_tbb; #endif // prepare functors prepare(); // only do something, if we have to if ((codim0_functors_.size() + codim1_functors_.size()) > 0) { walk_range(DSC::entityRange(grid_view_)); } // only do something, if we have to // finalize functors finalize(); clear(); } // ... walk(...) #if HAVE_TBB protected: template< class PartioningType, class WalkerType > struct Body { Body(WalkerType& walker, PartioningType& partitioning) : walker_(walker) , partitioning_(partitioning) {} Body(Body& other, tbb::split /*split*/) : walker_(other.walker_) , partitioning_(other.partitioning_) {} void operator()(const tbb::blocked_range< std::size_t > &range) const { // for all partitions in tbb-range for(std::size_t p = range.begin(); p != range.end(); ++p) { auto partition = partitioning_.partition(p); walker_.walk_range(partition); } } void join(Body& /*other*/) {} WalkerType& walker_; const PartioningType& partitioning_; }; // struct Body public: template< class PartioningType > void walk(PartioningType& partitioning) { // prepare functors prepare(); // only do something, if we have to if ((codim0_functors_.size() + codim1_functors_.size()) > 0) { tbb::blocked_range< std::size_t > range(0, partitioning.partitions()); Body< PartioningType, ThisType > body(*this, partitioning); tbb::parallel_reduce(range, body); } // finalize functors finalize(); clear(); } // ... tbb_walk(...) #endif // HAVE_TBB protected: template< class EntityRange > void walk_range(const EntityRange& entity_range) { #ifdef __INTEL_COMPILER const auto it_end = entity_range.end(); for (auto it = entity_range.begin(); it != it_end; ++it) { const EntityType& entity = *it; #else for (const EntityType& entity : entity_range) { #endif // apply codim0 functors apply_local(entity); // only walk the intersections, if there are codim1 functors present if (codim1_functors_.size() > 0) { // walk the intersections const auto intersection_it_end = grid_view_.iend(entity); for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; // apply codim1 functors if (intersection.neighbor()) { const auto neighbor_ptr = intersection.outside(); const auto& neighbor = *neighbor_ptr; apply_local(intersection, entity, neighbor); } else apply_local(intersection, entity, entity); } // walk the intersections } // only walk the intersections, if there are codim1 functors present } } // ... walk_range(...) const GridViewType grid_view_; std::vector< std::unique_ptr< internal::Codim0Object<GridViewType> > > codim0_functors_; std::vector< std::unique_ptr< internal::Codim1Object<GridViewType> > > codim1_functors_; }; // class Walker } // namespace Grid } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRID_WALKER_HH <commit_msg>[grid.walker] allow tweaking partion numbers of default partitioning<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_GRID_WALKER_HH #define DUNE_STUFF_GRID_WALKER_HH #include <vector> #include <memory> #include <type_traits> #include <functional> #if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE # include <dune/grid/utility/partitioning/ranged.hh> # include <dune/stuff/common/parallel/threadmanager.hh> #endif #if HAVE_TBB # include <tbb/blocked_range.h> # include <tbb/parallel_reduce.h> # include <tbb/tbb_stddef.h> #endif #include <dune/stuff/grid/entity.hh> #include <dune/stuff/grid/intersection.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/common/parallel/threadmanager.hh> #include <dune/stuff/common/ranges.hh> #include "walker/functors.hh" #include "walker/apply-on.hh" #include "walker/wrapper.hh" namespace Dune { namespace Stuff { namespace Grid { template< class GridViewImp > class Walker : public Functor::Codim0And1< GridViewImp > { typedef Walker< GridViewImp > ThisType; public: typedef GridViewImp GridViewType; typedef typename Stuff::Grid::Entity< GridViewType >::Type EntityType; typedef typename Stuff::Grid::Intersection< GridViewType >::Type IntersectionType; explicit Walker(GridViewType grd_vw) : grid_view_(grd_vw) {} const GridViewType& grid_view() const { return grid_view_; } void add(std::function< void(const EntityType&) > lambda, const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >()) { codim0_functors_.emplace_back(new internal::Codim0LambdaWrapper< GridViewType >(lambda, where)); } void add(Functor::Codim0< GridViewType >& functor, const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >()) { codim0_functors_.emplace_back( new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0< GridViewType > >(functor, where)); } void add(Functor::Codim1< GridViewType >& functor, const ApplyOn::WhichIntersection< GridViewType >* where = new ApplyOn::AllIntersections< GridViewType >()) { codim1_functors_.emplace_back( new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim1< GridViewType > >(functor, where)); } void add(Functor::Codim0And1< GridViewType >& functor, const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >(), const ApplyOn::WhichIntersection< GridViewType >* which_intersections = new ApplyOn::AllIntersections< GridViewType >()) { codim0_functors_.emplace_back( new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor, which_entities)); codim1_functors_.emplace_back( new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor, which_intersections)); } void add(Functor::Codim0And1< GridViewType >& functor, const ApplyOn::WhichIntersection< GridViewType >* which_intersections, const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >()) { codim0_functors_.emplace_back( new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor, which_entities)); codim1_functors_.emplace_back( new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor, which_intersections)); } void add(ThisType& other, const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >(), const ApplyOn::WhichIntersection< GridViewType >* which_intersections = new ApplyOn::AllIntersections< GridViewType >()) { if (&other == this) DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not add a Walker to itself!"); codim0_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_entities)); codim1_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_intersections)); } // ... add(...) void add(ThisType& other, const ApplyOn::WhichIntersection< GridViewType >* which_intersections, const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >()) { if (&other == this) DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not add a Walker to itself!"); codim0_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_entities)); codim1_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_intersections)); } // ... add(...) void clear() { codim0_functors_.clear(); codim1_functors_.clear(); } // ... clear() virtual void prepare() { for (auto& functor : codim0_functors_) functor->prepare(); for (auto& functor : codim1_functors_) functor->prepare(); } // ... prepare() bool apply_on(const EntityType& entity) const { for (const auto& functor : codim0_functors_) if (functor->apply_on(grid_view_, entity)) return true; return false; } // ... apply_on(...) bool apply_on(const IntersectionType& intersection) const { for (const auto& functor : codim1_functors_) if (functor->apply_on(grid_view_, intersection)) return true; return false; } // ... apply_on(...) virtual void apply_local(const EntityType& entity) { for (auto& functor : codim0_functors_) if (functor->apply_on(grid_view_, entity)) functor->apply_local(entity); } // ... apply_local(...) virtual void apply_local(const IntersectionType& intersection, const EntityType& inside_entity, const EntityType& outside_entity) { for (auto& functor : codim1_functors_) if (functor->apply_on(grid_view_, intersection)) functor->apply_local(intersection, inside_entity, outside_entity); } // ... apply_local(...) virtual void finalize() { for (auto& functor : codim0_functors_) functor->finalize(); for (auto& functor : codim1_functors_) functor->finalize(); } // ... finalize() void walk(const bool use_tbb = false) { #if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE if (use_tbb) { const auto num_partitions = DSC_CONFIG_GET("threading.partition_factor", 1u) * threadManager().current_threads(); RangedPartitioning< GridViewType, 0 > partitioning(grid_view_, num_partitions); this->walk(partitioning); return; } #else const auto DUNE_UNUSED(no_warning_for_use_tbb) = use_tbb; #endif // prepare functors prepare(); // only do something, if we have to if ((codim0_functors_.size() + codim1_functors_.size()) > 0) { walk_range(DSC::entityRange(grid_view_)); } // only do something, if we have to // finalize functors finalize(); clear(); } // ... walk(...) #if HAVE_TBB protected: template< class PartioningType, class WalkerType > struct Body { Body(WalkerType& walker, PartioningType& partitioning) : walker_(walker) , partitioning_(partitioning) {} Body(Body& other, tbb::split /*split*/) : walker_(other.walker_) , partitioning_(other.partitioning_) {} void operator()(const tbb::blocked_range< std::size_t > &range) const { // for all partitions in tbb-range for(std::size_t p = range.begin(); p != range.end(); ++p) { auto partition = partitioning_.partition(p); walker_.walk_range(partition); } } void join(Body& /*other*/) {} WalkerType& walker_; const PartioningType& partitioning_; }; // struct Body public: template< class PartioningType > void walk(PartioningType& partitioning) { // prepare functors prepare(); // only do something, if we have to if ((codim0_functors_.size() + codim1_functors_.size()) > 0) { tbb::blocked_range< std::size_t > range(0, partitioning.partitions()); Body< PartioningType, ThisType > body(*this, partitioning); tbb::parallel_reduce(range, body); } // finalize functors finalize(); clear(); } // ... tbb_walk(...) #endif // HAVE_TBB protected: template< class EntityRange > void walk_range(const EntityRange& entity_range) { #ifdef __INTEL_COMPILER const auto it_end = entity_range.end(); for (auto it = entity_range.begin(); it != it_end; ++it) { const EntityType& entity = *it; #else for (const EntityType& entity : entity_range) { #endif // apply codim0 functors apply_local(entity); // only walk the intersections, if there are codim1 functors present if (codim1_functors_.size() > 0) { // walk the intersections const auto intersection_it_end = grid_view_.iend(entity); for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; // apply codim1 functors if (intersection.neighbor()) { const auto neighbor_ptr = intersection.outside(); const auto& neighbor = *neighbor_ptr; apply_local(intersection, entity, neighbor); } else apply_local(intersection, entity, entity); } // walk the intersections } // only walk the intersections, if there are codim1 functors present } } // ... walk_range(...) const GridViewType grid_view_; std::vector< std::unique_ptr< internal::Codim0Object<GridViewType> > > codim0_functors_; std::vector< std::unique_ptr< internal::Codim1Object<GridViewType> > > codim1_functors_; }; // class Walker } // namespace Grid } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRID_WALKER_HH <|endoftext|>
<commit_before>/***************************************************************************************** * * * owl * * * * Copyright (c) 2014 Jonas Strandstedt * * * * 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 <ghoul/misc/buffer.h> #include <ghoul/logging/logmanager.h> #include <lz4/lz4.h> #include <algorithm> #include <iostream> #include <fstream> namespace { const std::string _loggerCat = "Buffer"; } namespace ghoul { Buffer::Buffer() : _offsetWrite(0) , _offsetRead(0) {} Buffer::Buffer(size_t capacity) : _data(capacity) , _offsetWrite(0) , _offsetRead(0) {} Buffer::Buffer(const std::string& filename) : _offsetWrite(0) , _offsetRead(0) { read(filename); } Buffer::Buffer(const Buffer& other) : _data(other._data) , _offsetWrite(other._offsetWrite) , _offsetRead(other._offsetRead) { } Buffer::Buffer(Buffer&& other) { if (this != &other) { // move memory _data = std::move(other._data); _offsetWrite = other._offsetWrite; _offsetRead = other._offsetRead; // invalidate rhs memory other._offsetWrite = 0; other._offsetRead = 0; } } Buffer& Buffer::operator=(const Buffer& rhs) { if(this != &rhs) { // copy memory _data = rhs._data; _offsetWrite = rhs._offsetWrite; _offsetRead = rhs._offsetRead; } return *this; } Buffer& Buffer::operator=(Buffer&& rhs) { if(this != &rhs) { // move memory _data = std::move(rhs._data); _offsetWrite = rhs._offsetWrite; _offsetRead = rhs._offsetRead; // invalidate rhs memory rhs._offsetWrite = 0; rhs._offsetRead = 0; } return *this; } void Buffer::reset() { _offsetWrite = 0; _offsetRead = 0; } const Buffer::value_type* Buffer::data() const { return _data.data(); } Buffer::value_type* Buffer::data() { return _data.data(); } Buffer::size_type Buffer::capacity() const { return _data.capacity(); } Buffer::size_type Buffer::size() const { return _offsetWrite; } bool Buffer::write(const std::string& filename, bool compress) { //BinaryFile file(filename, BinaryFile::OpenMode::Out); std::ofstream file(filename, std::ios::binary | std::ios::out); if (!file) return false; file.write(reinterpret_cast<const char*>(&compress), sizeof(bool)); if(compress) { value_type* data = new value_type[size()]; int compressed_size = LZ4_compress(reinterpret_cast<const char*>(_data.data()), reinterpret_cast<char*>(data), static_cast<int>(_offsetWrite)); if (compressed_size <= 0) { delete[] data; return false; } size_t size = compressed_size; // orginal size file.write(reinterpret_cast<const char*>(&_offsetWrite), sizeof(size_t)); // compressed size file.write(reinterpret_cast<const char*>(&size), sizeof(size_t)); file.write(reinterpret_cast<const char*>(data), size); // compressed data delete[] data; } else { file.write(reinterpret_cast<const char*>(&_offsetWrite), sizeof(size_t)); file.write(reinterpret_cast<const char*>(_data.data()), _offsetWrite); } return true; } bool Buffer::read(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::in); //BinaryFile file(filename, BinaryFile::OpenMode::In); if (!file) return false; _offsetRead = 0; size_t size; bool compressed; file.read(reinterpret_cast<char*>(&compressed), sizeof(bool)); if(compressed) { // read original size file.read(reinterpret_cast<char*>(&size), sizeof(size_t)); _data.resize(size); // read compressed size file.read(reinterpret_cast<char*>(&size), sizeof(size_t)); // allocate and read data value_type* data = new value_type[size]; file.read(reinterpret_cast<char*>(data),size); // decompress _offsetWrite = LZ4_decompress_safe(reinterpret_cast<const char*>(data), reinterpret_cast<char*>(_data.data()), size, static_cast<int>(_data.size())); delete[] data; } else { file.read(reinterpret_cast<char*>(&size), sizeof(size_t)); _data.resize(size); file.read(reinterpret_cast<char*>(_data.data()), size); _offsetWrite = size; } return true; } void Buffer::serialize(const char* s) { serialize(std::string(s)); } void Buffer::serialize(const value_type* data, size_t size) { _data.resize(_data.capacity() + size); std::memcpy(_data.data() + _offsetWrite, &data, size); _offsetWrite += size; } void Buffer::deserialize(value_type* data, size_t size) { std::memcpy(data, &_data + _offsetRead, size); _offsetRead += size; } template<> void Buffer::serialize(const std::string& v) { const size_t length = v.length(); const size_t size = length + sizeof(size_t); _data.resize(_data.capacity() + size); std::memcpy(_data.data() + _offsetWrite, &length, sizeof(size_t)); _offsetWrite += sizeof(size_t); std::memcpy(_data.data() + _offsetWrite, v.c_str(), length); _offsetWrite += length; } template<> void Buffer::deserialize(std::string& v) { assert(_offsetRead + sizeof(size_t) <= _data.size()); size_t size; std::memcpy(&size, _data.data() + _offsetRead, sizeof(size_t)); _offsetRead += sizeof(size_t); assert(_offsetRead + size <= _data.size()); v = std::string(reinterpret_cast<char*>(_data.data()+_offsetRead), size); _offsetRead += size; } template<> void Buffer::serialize(const std::vector<std::string>& v) { const size_t length = v.size(); size_t size = sizeof(size_t); _data.resize(_data.capacity() + size + length); std::memcpy(_data.data() + _offsetWrite, &length, sizeof(size_t)); _offsetWrite += sizeof(size_t); for(auto e: v) { serialize(e); } } template<> void Buffer::deserialize(std::vector<std::string>& v) { assert(_offsetRead + sizeof(size_t) <= _data.size()); size_t n; std::memcpy(&n, _data.data() + _offsetRead, sizeof(size_t)); _offsetRead += sizeof(size_t); v.reserve(n); for(size_t i = 0; i < n; ++i) { std::string t; deserialize(t); v.emplace_back(t); } } } // namespace owl<commit_msg>Remove warning<commit_after>/***************************************************************************************** * * * owl * * * * Copyright (c) 2014 Jonas Strandstedt * * * * 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 <ghoul/misc/buffer.h> #include <ghoul/logging/logmanager.h> #include <lz4/lz4.h> #include <algorithm> #include <iostream> #include <fstream> namespace { const std::string _loggerCat = "Buffer"; } namespace ghoul { Buffer::Buffer() : _offsetWrite(0) , _offsetRead(0) {} Buffer::Buffer(size_t capacity) : _data(capacity) , _offsetWrite(0) , _offsetRead(0) {} Buffer::Buffer(const std::string& filename) : _offsetWrite(0) , _offsetRead(0) { read(filename); } Buffer::Buffer(const Buffer& other) : _data(other._data) , _offsetWrite(other._offsetWrite) , _offsetRead(other._offsetRead) { } Buffer::Buffer(Buffer&& other) { if (this != &other) { // move memory _data = std::move(other._data); _offsetWrite = other._offsetWrite; _offsetRead = other._offsetRead; // invalidate rhs memory other._offsetWrite = 0; other._offsetRead = 0; } } Buffer& Buffer::operator=(const Buffer& rhs) { if(this != &rhs) { // copy memory _data = rhs._data; _offsetWrite = rhs._offsetWrite; _offsetRead = rhs._offsetRead; } return *this; } Buffer& Buffer::operator=(Buffer&& rhs) { if(this != &rhs) { // move memory _data = std::move(rhs._data); _offsetWrite = rhs._offsetWrite; _offsetRead = rhs._offsetRead; // invalidate rhs memory rhs._offsetWrite = 0; rhs._offsetRead = 0; } return *this; } void Buffer::reset() { _offsetWrite = 0; _offsetRead = 0; } const Buffer::value_type* Buffer::data() const { return _data.data(); } Buffer::value_type* Buffer::data() { return _data.data(); } Buffer::size_type Buffer::capacity() const { return _data.capacity(); } Buffer::size_type Buffer::size() const { return _offsetWrite; } bool Buffer::write(const std::string& filename, bool compress) { //BinaryFile file(filename, BinaryFile::OpenMode::Out); std::ofstream file(filename, std::ios::binary | std::ios::out); if (!file) return false; file.write(reinterpret_cast<const char*>(&compress), sizeof(bool)); if(compress) { value_type* data = new value_type[size()]; int compressed_size = LZ4_compress(reinterpret_cast<const char*>(_data.data()), reinterpret_cast<char*>(data), static_cast<int>(_offsetWrite)); if (compressed_size <= 0) { delete[] data; return false; } size_t size = compressed_size; // orginal size file.write(reinterpret_cast<const char*>(&_offsetWrite), sizeof(size_t)); // compressed size file.write(reinterpret_cast<const char*>(&size), sizeof(size_t)); file.write(reinterpret_cast<const char*>(data), size); // compressed data delete[] data; } else { file.write(reinterpret_cast<const char*>(&_offsetWrite), sizeof(size_t)); file.write(reinterpret_cast<const char*>(_data.data()), _offsetWrite); } return true; } bool Buffer::read(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::in); //BinaryFile file(filename, BinaryFile::OpenMode::In); if (!file) return false; _offsetRead = 0; size_t size; bool compressed; file.read(reinterpret_cast<char*>(&compressed), sizeof(bool)); if(compressed) { // read original size file.read(reinterpret_cast<char*>(&size), sizeof(size_t)); _data.resize(size); // read compressed size file.read(reinterpret_cast<char*>(&size), sizeof(size_t)); // allocate and read data value_type* data = new value_type[size]; file.read(reinterpret_cast<char*>(data),size); // decompress _offsetWrite = LZ4_decompress_safe(reinterpret_cast<const char*>(data), reinterpret_cast<char*>(_data.data()), static_cast<int>(size), static_cast<int>(_data.size())); delete[] data; } else { file.read(reinterpret_cast<char*>(&size), sizeof(size_t)); _data.resize(size); file.read(reinterpret_cast<char*>(_data.data()), size); _offsetWrite = size; } return true; } void Buffer::serialize(const char* s) { serialize(std::string(s)); } void Buffer::serialize(const value_type* data, size_t size) { _data.resize(_data.capacity() + size); std::memcpy(_data.data() + _offsetWrite, &data, size); _offsetWrite += size; } void Buffer::deserialize(value_type* data, size_t size) { std::memcpy(data, &_data + _offsetRead, size); _offsetRead += size; } template<> void Buffer::serialize(const std::string& v) { const size_t length = v.length(); const size_t size = length + sizeof(size_t); _data.resize(_data.capacity() + size); std::memcpy(_data.data() + _offsetWrite, &length, sizeof(size_t)); _offsetWrite += sizeof(size_t); std::memcpy(_data.data() + _offsetWrite, v.c_str(), length); _offsetWrite += length; } template<> void Buffer::deserialize(std::string& v) { assert(_offsetRead + sizeof(size_t) <= _data.size()); size_t size; std::memcpy(&size, _data.data() + _offsetRead, sizeof(size_t)); _offsetRead += sizeof(size_t); assert(_offsetRead + size <= _data.size()); v = std::string(reinterpret_cast<char*>(_data.data()+_offsetRead), size); _offsetRead += size; } template<> void Buffer::serialize(const std::vector<std::string>& v) { const size_t length = v.size(); size_t size = sizeof(size_t); _data.resize(_data.capacity() + size + length); std::memcpy(_data.data() + _offsetWrite, &length, sizeof(size_t)); _offsetWrite += sizeof(size_t); for(auto e: v) { serialize(e); } } template<> void Buffer::deserialize(std::vector<std::string>& v) { assert(_offsetRead + sizeof(size_t) <= _data.size()); size_t n; std::memcpy(&n, _data.data() + _offsetRead, sizeof(size_t)); _offsetRead += sizeof(size_t); v.reserve(n); for(size_t i = 0; i < n; ++i) { std::string t; deserialize(t); v.emplace_back(t); } } } // namespace owl<|endoftext|>
<commit_before>// - Tested #define CRB_CONVOYS #define RMM_ENEMYPOP #define CRB_TERRORISTS #define RMM_ZORA // - To Test <commit_msg>- Added missing MSO_FACTIONS include<commit_after>// - Tested #define MSO_FACTIONS #define CRB_CONVOYS #define RMM_ENEMYPOP #define CRB_TERRORISTS #define RMM_ZORA // - To Test <|endoftext|>
<commit_before>/* Q Light Controller efxfixture.cpp Copyright (c) Heikki Junnila Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QDomDocument> #include <QDomElement> #include <QDebug> #include <math.h> #include "genericfader.h" #include "mastertimer.h" #include "efxfixture.h" #include "qlcmacros.h" #include "function.h" #include "universe.h" #include "scene.h" #include "efx.h" #include "doc.h" /***************************************************************************** * Initialization *****************************************************************************/ EFXFixture::EFXFixture(const EFX* parent) : m_parent(parent) , m_head() , m_direction(Function::Forward) , m_startOffset(0) , m_fadeIntensity(255) , m_serialNumber(0) , m_runTimeDirection(Function::Forward) , m_ready(false) , m_started(false) , m_elapsed(0) , m_startAngle(0) , m_currentAngle(0) , m_intensity(1.0) { Q_ASSERT(parent != NULL); } void EFXFixture::copyFrom(const EFXFixture* ef) { // Don't copy m_parent because it is already assigned in constructor and might // be different than $ef's m_head = ef->m_head; m_direction = ef->m_direction; m_startOffset = ef->m_startOffset; m_fadeIntensity = ef->m_fadeIntensity; m_serialNumber = ef->m_serialNumber; m_runTimeDirection = ef->m_runTimeDirection; m_ready = ef->m_ready; m_started = ef->m_started; m_elapsed = ef->m_elapsed; m_startAngle = ef->m_startAngle; m_currentAngle = ef->m_currentAngle; m_intensity = ef->m_intensity; } EFXFixture::~EFXFixture() { } /**************************************************************************** * Public properties ****************************************************************************/ void EFXFixture::setHead(GroupHead const & head) { m_head = head; } GroupHead const & EFXFixture::head() const { return m_head; } void EFXFixture::setDirection(Function::Direction dir) { m_direction = dir; m_runTimeDirection = dir; } Function::Direction EFXFixture::direction() const { return m_direction; } void EFXFixture::setStartOffset(int startOffset) { m_startOffset = CLAMP(startOffset, 0, 359); } int EFXFixture::startOffset() const { return m_startOffset; } void EFXFixture::setFadeIntensity(uchar value) { m_fadeIntensity = value; } uchar EFXFixture::fadeIntensity() const { return m_fadeIntensity; } bool EFXFixture::isValid() const { Fixture* fxi = doc()->fixture(head().fxi); if (fxi == NULL) return false; else if (head().head >= fxi->heads()) return false; else if (fxi->panMsbChannel(head().head) == QLCChannel::invalid() && // Maybe a device can pan OR tilt fxi->tiltMsbChannel(head().head) == QLCChannel::invalid()) // but not both. Teh sux0r. return false; else return true; } void EFXFixture::durationChanged() { m_startAngle = m_currentAngle; m_elapsed = 0; } /***************************************************************************** * Load & Save *****************************************************************************/ bool EFXFixture::loadXML(const QDomElement& root) { if (root.tagName() != KXMLQLCEFXFixture) { qWarning("EFX Fixture node not found!"); return false; } GroupHead head; head.head = 0; /* New file format contains sub tags */ QDomNode node = root.firstChild(); while (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == KXMLQLCEFXFixtureID) { /* Fixture ID */ head.fxi = tag.text().toInt(); } else if (tag.tagName() == KXMLQLCEFXFixtureHead) { /* Fixture Head */ head.head = tag.text().toInt(); } else if (tag.tagName() == KXMLQLCEFXFixtureDirection) { /* Direction */ Function::Direction dir = Function::stringToDirection(tag.text()); setDirection(dir); } else if (tag.tagName() == KXMLQLCEFXFixtureStartOffset) { /* Start offset */ setStartOffset(tag.text().toInt()); } else if (tag.tagName() == KXMLQLCEFXFixtureIntensity) { /* Intensity */ setFadeIntensity(uchar(tag.text().toUInt())); } else { qWarning() << "Unknown EFX Fixture tag:" << tag.tagName(); } node = node.nextSibling(); } if (head.fxi != Fixture::invalidId()) setHead(head); return true; } bool EFXFixture::saveXML(QDomDocument* doc, QDomElement* efx_root) const { QDomElement subtag; QDomElement tag; QDomText text; Q_ASSERT(doc != NULL); Q_ASSERT(efx_root != NULL); /* EFXFixture */ tag = doc->createElement(KXMLQLCEFXFixture); efx_root->appendChild(tag); /* Fixture ID */ subtag = doc->createElement(KXMLQLCEFXFixtureID); tag.appendChild(subtag); text = doc->createTextNode(QString("%1").arg(head().fxi)); subtag.appendChild(text); /* Fixture Head */ subtag = doc->createElement(KXMLQLCEFXFixtureHead); tag.appendChild(subtag); text = doc->createTextNode(QString("%1").arg(head().head)); subtag.appendChild(text); /* Direction */ subtag = doc->createElement(KXMLQLCEFXFixtureDirection); tag.appendChild(subtag); text = doc->createTextNode(Function::directionToString(m_direction)); subtag.appendChild(text); /* Start offset */ subtag = doc->createElement(KXMLQLCEFXFixtureStartOffset); tag.appendChild(subtag); text = doc->createTextNode(QString::number(startOffset())); subtag.appendChild(text); /* Intensity */ subtag = doc->createElement(KXMLQLCEFXFixtureIntensity); tag.appendChild(subtag); text = doc->createTextNode(QString::number(fadeIntensity())); subtag.appendChild(text); return true; } /**************************************************************************** * Run-time properties ****************************************************************************/ const Doc* EFXFixture::doc() const { Q_ASSERT(m_parent != NULL); return m_parent->doc(); } void EFXFixture::setSerialNumber(int number) { m_serialNumber = number; } int EFXFixture::serialNumber() const { return m_serialNumber; } void EFXFixture::reset() { m_ready = false; m_runTimeDirection = m_direction; m_started = false; m_elapsed = 0; m_startAngle = 0; m_currentAngle = 0; } bool EFXFixture::isReady() const { return m_ready; } uint EFXFixture::timeOffset() const { if (m_parent->propagationMode() == EFX::Asymmetric || m_parent->propagationMode() == EFX::Serial) { return m_parent->duration() / (m_parent->fixtures().size() + 1) * serialNumber(); } else { return 0; } } /***************************************************************************** * Running *****************************************************************************/ void EFXFixture::nextStep(MasterTimer* timer, QList<Universe *> universes) { m_elapsed += MasterTimer::tick(); // Bail out without doing anything if this fixture is ready (after single-shot) // or it has no pan&tilt channels (not valid). if (m_ready == true || isValid() == false) return; // Bail out without doing anything if this fixture is waiting for its turn. if (m_parent->propagationMode() == EFX::Serial && m_elapsed < timeOffset() && !m_started) return; // Fade in if (m_started == false) start(timer, universes); // Nothing to do if (m_parent->duration() == 0) return; // Scale from elapsed time in relation to overall duration to a point in a circle uint pos = (m_elapsed + timeOffset()) % m_parent->duration(); m_currentAngle = m_startAngle + SCALE(qreal(pos), qreal(0), qreal(m_parent->duration()), qreal(0), qreal(M_PI * 2)); if (m_currentAngle > (M_PI * 2)) { m_startAngle = 0; m_currentAngle -= M_PI * 2; } qreal pan = 0; qreal tilt = 0; if ((m_parent->propagationMode() == EFX::Serial && m_elapsed < (m_parent->duration() + timeOffset())) || m_elapsed < m_parent->duration()) { m_parent->calculatePoint(m_runTimeDirection, m_startOffset, m_currentAngle, &pan, &tilt); /* Write this fixture's data to universes. */ setPoint(universes, pan, tilt); } else { if (m_parent->runOrder() == Function::PingPong) { /* Reverse direction for ping-pong EFX. */ if (m_runTimeDirection == Function::Forward) m_runTimeDirection = Function::Backward; else m_runTimeDirection = Function::Forward; } else if (m_parent->runOrder() == Function::SingleShot) { /* De-initialize the fixture and mark as ready. */ m_ready = true; stop(timer, universes); } m_elapsed = 0; } } void EFXFixture::setPoint(QList<Universe *> universes, qreal pan, qreal tilt) { Fixture* fxi = doc()->fixture(head().fxi); Q_ASSERT(fxi != NULL); /* Write coarse point data to universes */ if (fxi->panMsbChannel(head().head) != QLCChannel::invalid()) { if (m_parent->isRelative()) universes[fxi->universe()]->writeRelative(fxi->address() + fxi->panMsbChannel(head().head), static_cast<char>(pan)); else universes[fxi->universe()]->write(fxi->address() + fxi->panMsbChannel(head().head), static_cast<char>(pan)); } if (fxi->tiltMsbChannel(head().head) != QLCChannel::invalid()) { if (m_parent->isRelative()) universes[fxi->universe()]->writeRelative(fxi->address() + fxi->tiltMsbChannel(head().head), static_cast<char> (tilt)); else universes[fxi->universe()]->write(fxi->address() + fxi->tiltMsbChannel(head().head), static_cast<char> (tilt)); } /* Write fine point data to universes if applicable */ if (fxi->panLsbChannel(head().head) != QLCChannel::invalid()) { /* Leave only the fraction */ char value = static_cast<char> ((pan - floor(pan)) * double(UCHAR_MAX)); if (m_parent->isRelative()) universes[fxi->universe()]->writeRelative(fxi->address() + fxi->panLsbChannel(head().head), value); else universes[fxi->universe()]->write(fxi->address() + fxi->panLsbChannel(head().head), value); } if (fxi->tiltLsbChannel(head().head) != QLCChannel::invalid()) { /* Leave only the fraction */ char value = static_cast<char> ((tilt - floor(tilt)) * double(UCHAR_MAX)); if (m_parent->isRelative()) universes[fxi->universe()]->writeRelative(fxi->address() + fxi->tiltLsbChannel(head().head), value); else universes[fxi->universe()]->write(fxi->address() + fxi->tiltLsbChannel(head().head), value); } } void EFXFixture::start(MasterTimer* timer, QList<Universe *> universes) { Q_UNUSED(universes); Q_UNUSED(timer); if (fadeIntensity() > 0 && m_started == false) { Fixture* fxi = doc()->fixture(head().fxi); Q_ASSERT(fxi != NULL); if (fxi->masterIntensityChannel(head().head) != QLCChannel::invalid()) { FadeChannel fc; fc.setFixture(doc(), head().fxi); fc.setChannel(fxi->masterIntensityChannel(head().head)); if (m_parent->overrideFadeInSpeed() != Function::defaultSpeed()) fc.setFadeTime(m_parent->overrideFadeInSpeed()); else fc.setFadeTime(m_parent->fadeInSpeed()); fc.setStart(0); fc.setCurrent(fc.start()); // Don't use intensity() multiplier because EFX's GenericFader takes care of that fc.setTarget(fadeIntensity()); // Fade channel up with EFX's own GenericFader to allow manual intensity control m_parent->m_fader->add(fc); } } m_started = true; } void EFXFixture::stop(MasterTimer* timer, QList<Universe *> universes) { Q_UNUSED(universes); if (fadeIntensity() > 0 && m_started == true) { Fixture* fxi = doc()->fixture(head().fxi); Q_ASSERT(fxi != NULL); if (fxi->masterIntensityChannel(head().head) != QLCChannel::invalid()) { FadeChannel fc; fc.setFixture(doc(), head().fxi); fc.setChannel(fxi->masterIntensityChannel(head().head)); if (m_parent->overrideFadeOutSpeed() != Function::defaultSpeed()) fc.setFadeTime(m_parent->overrideFadeOutSpeed()); else fc.setFadeTime(m_parent->fadeOutSpeed()); fc.setStart(uchar(floor((qreal(fadeIntensity()) * intensity()) + 0.5))); fc.setCurrent(fc.start()); fc.setTarget(0); // Give zero-fading to MasterTimer because EFX will stop after this call timer->faderAdd(fc); // Remove the previously up-faded channel from EFX's internal fader to allow // MasterTimer's fader take HTP precedence. m_parent->m_fader->remove(fc); } } m_started = false; } /***************************************************************************** * Intensity *****************************************************************************/ void EFXFixture::adjustIntensity(qreal fraction) { m_intensity = fraction; } qreal EFXFixture::intensity() const { return m_intensity; } <commit_msg>efx: fix serial mode jumpy behavior<commit_after>/* Q Light Controller efxfixture.cpp Copyright (c) Heikki Junnila Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QDomDocument> #include <QDomElement> #include <QDebug> #include <math.h> #include "genericfader.h" #include "mastertimer.h" #include "efxfixture.h" #include "qlcmacros.h" #include "function.h" #include "universe.h" #include "scene.h" #include "efx.h" #include "doc.h" /***************************************************************************** * Initialization *****************************************************************************/ EFXFixture::EFXFixture(const EFX* parent) : m_parent(parent) , m_head() , m_direction(Function::Forward) , m_startOffset(0) , m_fadeIntensity(255) , m_serialNumber(0) , m_runTimeDirection(Function::Forward) , m_ready(false) , m_started(false) , m_elapsed(0) , m_startAngle(0) , m_currentAngle(0) , m_intensity(1.0) { Q_ASSERT(parent != NULL); } void EFXFixture::copyFrom(const EFXFixture* ef) { // Don't copy m_parent because it is already assigned in constructor and might // be different than $ef's m_head = ef->m_head; m_direction = ef->m_direction; m_startOffset = ef->m_startOffset; m_fadeIntensity = ef->m_fadeIntensity; m_serialNumber = ef->m_serialNumber; m_runTimeDirection = ef->m_runTimeDirection; m_ready = ef->m_ready; m_started = ef->m_started; m_elapsed = ef->m_elapsed; m_startAngle = ef->m_startAngle; m_currentAngle = ef->m_currentAngle; m_intensity = ef->m_intensity; } EFXFixture::~EFXFixture() { } /**************************************************************************** * Public properties ****************************************************************************/ void EFXFixture::setHead(GroupHead const & head) { m_head = head; } GroupHead const & EFXFixture::head() const { return m_head; } void EFXFixture::setDirection(Function::Direction dir) { m_direction = dir; m_runTimeDirection = dir; } Function::Direction EFXFixture::direction() const { return m_direction; } void EFXFixture::setStartOffset(int startOffset) { m_startOffset = CLAMP(startOffset, 0, 359); } int EFXFixture::startOffset() const { return m_startOffset; } void EFXFixture::setFadeIntensity(uchar value) { m_fadeIntensity = value; } uchar EFXFixture::fadeIntensity() const { return m_fadeIntensity; } bool EFXFixture::isValid() const { Fixture* fxi = doc()->fixture(head().fxi); if (fxi == NULL) return false; else if (head().head >= fxi->heads()) return false; else if (fxi->panMsbChannel(head().head) == QLCChannel::invalid() && // Maybe a device can pan OR tilt fxi->tiltMsbChannel(head().head) == QLCChannel::invalid()) // but not both. Teh sux0r. return false; else return true; } void EFXFixture::durationChanged() { m_startAngle = m_currentAngle; m_elapsed = 0; } /***************************************************************************** * Load & Save *****************************************************************************/ bool EFXFixture::loadXML(const QDomElement& root) { if (root.tagName() != KXMLQLCEFXFixture) { qWarning("EFX Fixture node not found!"); return false; } GroupHead head; head.head = 0; /* New file format contains sub tags */ QDomNode node = root.firstChild(); while (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == KXMLQLCEFXFixtureID) { /* Fixture ID */ head.fxi = tag.text().toInt(); } else if (tag.tagName() == KXMLQLCEFXFixtureHead) { /* Fixture Head */ head.head = tag.text().toInt(); } else if (tag.tagName() == KXMLQLCEFXFixtureDirection) { /* Direction */ Function::Direction dir = Function::stringToDirection(tag.text()); setDirection(dir); } else if (tag.tagName() == KXMLQLCEFXFixtureStartOffset) { /* Start offset */ setStartOffset(tag.text().toInt()); } else if (tag.tagName() == KXMLQLCEFXFixtureIntensity) { /* Intensity */ setFadeIntensity(uchar(tag.text().toUInt())); } else { qWarning() << "Unknown EFX Fixture tag:" << tag.tagName(); } node = node.nextSibling(); } if (head.fxi != Fixture::invalidId()) setHead(head); return true; } bool EFXFixture::saveXML(QDomDocument* doc, QDomElement* efx_root) const { QDomElement subtag; QDomElement tag; QDomText text; Q_ASSERT(doc != NULL); Q_ASSERT(efx_root != NULL); /* EFXFixture */ tag = doc->createElement(KXMLQLCEFXFixture); efx_root->appendChild(tag); /* Fixture ID */ subtag = doc->createElement(KXMLQLCEFXFixtureID); tag.appendChild(subtag); text = doc->createTextNode(QString("%1").arg(head().fxi)); subtag.appendChild(text); /* Fixture Head */ subtag = doc->createElement(KXMLQLCEFXFixtureHead); tag.appendChild(subtag); text = doc->createTextNode(QString("%1").arg(head().head)); subtag.appendChild(text); /* Direction */ subtag = doc->createElement(KXMLQLCEFXFixtureDirection); tag.appendChild(subtag); text = doc->createTextNode(Function::directionToString(m_direction)); subtag.appendChild(text); /* Start offset */ subtag = doc->createElement(KXMLQLCEFXFixtureStartOffset); tag.appendChild(subtag); text = doc->createTextNode(QString::number(startOffset())); subtag.appendChild(text); /* Intensity */ subtag = doc->createElement(KXMLQLCEFXFixtureIntensity); tag.appendChild(subtag); text = doc->createTextNode(QString::number(fadeIntensity())); subtag.appendChild(text); return true; } /**************************************************************************** * Run-time properties ****************************************************************************/ const Doc* EFXFixture::doc() const { Q_ASSERT(m_parent != NULL); return m_parent->doc(); } void EFXFixture::setSerialNumber(int number) { m_serialNumber = number; } int EFXFixture::serialNumber() const { return m_serialNumber; } void EFXFixture::reset() { m_ready = false; m_runTimeDirection = m_direction; m_started = false; m_elapsed = 0; m_startAngle = 0; m_currentAngle = 0; } bool EFXFixture::isReady() const { return m_ready; } uint EFXFixture::timeOffset() const { if (m_parent->propagationMode() == EFX::Asymmetric || m_parent->propagationMode() == EFX::Serial) { return m_parent->duration() / (m_parent->fixtures().size() + 1) * serialNumber(); } else { return 0; } } /***************************************************************************** * Running *****************************************************************************/ void EFXFixture::nextStep(MasterTimer* timer, QList<Universe *> universes) { m_elapsed += MasterTimer::tick(); // Bail out without doing anything if this fixture is ready (after single-shot) // or it has no pan&tilt channels (not valid). if (m_ready == true || isValid() == false) return; // Bail out without doing anything if this fixture is waiting for its turn. if (m_parent->propagationMode() == EFX::Serial && m_elapsed < timeOffset() && !m_started) return; // Fade in if (m_started == false) start(timer, universes); // Nothing to do if (m_parent->duration() == 0) return; // Scale from elapsed time in relation to overall duration to a point in a circle uint pos = (m_elapsed + timeOffset()) % m_parent->duration(); m_currentAngle = m_startAngle + SCALE(qreal(pos), qreal(0), qreal(m_parent->duration()), qreal(0), qreal(M_PI * 2)); if (m_currentAngle > (M_PI * 2)) { m_startAngle = 0; m_currentAngle -= M_PI * 2; } qreal pan = 0; qreal tilt = 0; if ((m_parent->propagationMode() == EFX::Serial && m_elapsed < (m_parent->duration() + timeOffset())) || m_elapsed < m_parent->duration()) { m_parent->calculatePoint(m_runTimeDirection, m_startOffset, m_currentAngle, &pan, &tilt); /* Write this fixture's data to universes. */ setPoint(universes, pan, tilt); } else { if (m_parent->runOrder() == Function::PingPong) { /* Reverse direction for ping-pong EFX. */ if (m_runTimeDirection == Function::Forward) m_runTimeDirection = Function::Backward; else m_runTimeDirection = Function::Forward; } else if (m_parent->runOrder() == Function::SingleShot) { /* De-initialize the fixture and mark as ready. */ m_ready = true; stop(timer, universes); } m_elapsed %= m_parent->duration(); } } void EFXFixture::setPoint(QList<Universe *> universes, qreal pan, qreal tilt) { Fixture* fxi = doc()->fixture(head().fxi); Q_ASSERT(fxi != NULL); /* Write coarse point data to universes */ if (fxi->panMsbChannel(head().head) != QLCChannel::invalid()) { if (m_parent->isRelative()) universes[fxi->universe()]->writeRelative(fxi->address() + fxi->panMsbChannel(head().head), static_cast<char>(pan)); else universes[fxi->universe()]->write(fxi->address() + fxi->panMsbChannel(head().head), static_cast<char>(pan)); } if (fxi->tiltMsbChannel(head().head) != QLCChannel::invalid()) { if (m_parent->isRelative()) universes[fxi->universe()]->writeRelative(fxi->address() + fxi->tiltMsbChannel(head().head), static_cast<char> (tilt)); else universes[fxi->universe()]->write(fxi->address() + fxi->tiltMsbChannel(head().head), static_cast<char> (tilt)); } /* Write fine point data to universes if applicable */ if (fxi->panLsbChannel(head().head) != QLCChannel::invalid()) { /* Leave only the fraction */ char value = static_cast<char> ((pan - floor(pan)) * double(UCHAR_MAX)); if (m_parent->isRelative()) universes[fxi->universe()]->writeRelative(fxi->address() + fxi->panLsbChannel(head().head), value); else universes[fxi->universe()]->write(fxi->address() + fxi->panLsbChannel(head().head), value); } if (fxi->tiltLsbChannel(head().head) != QLCChannel::invalid()) { /* Leave only the fraction */ char value = static_cast<char> ((tilt - floor(tilt)) * double(UCHAR_MAX)); if (m_parent->isRelative()) universes[fxi->universe()]->writeRelative(fxi->address() + fxi->tiltLsbChannel(head().head), value); else universes[fxi->universe()]->write(fxi->address() + fxi->tiltLsbChannel(head().head), value); } } void EFXFixture::start(MasterTimer* timer, QList<Universe *> universes) { Q_UNUSED(universes); Q_UNUSED(timer); if (fadeIntensity() > 0 && m_started == false) { Fixture* fxi = doc()->fixture(head().fxi); Q_ASSERT(fxi != NULL); if (fxi->masterIntensityChannel(head().head) != QLCChannel::invalid()) { FadeChannel fc; fc.setFixture(doc(), head().fxi); fc.setChannel(fxi->masterIntensityChannel(head().head)); if (m_parent->overrideFadeInSpeed() != Function::defaultSpeed()) fc.setFadeTime(m_parent->overrideFadeInSpeed()); else fc.setFadeTime(m_parent->fadeInSpeed()); fc.setStart(0); fc.setCurrent(fc.start()); // Don't use intensity() multiplier because EFX's GenericFader takes care of that fc.setTarget(fadeIntensity()); // Fade channel up with EFX's own GenericFader to allow manual intensity control m_parent->m_fader->add(fc); } } m_started = true; } void EFXFixture::stop(MasterTimer* timer, QList<Universe *> universes) { Q_UNUSED(universes); if (fadeIntensity() > 0 && m_started == true) { Fixture* fxi = doc()->fixture(head().fxi); Q_ASSERT(fxi != NULL); if (fxi->masterIntensityChannel(head().head) != QLCChannel::invalid()) { FadeChannel fc; fc.setFixture(doc(), head().fxi); fc.setChannel(fxi->masterIntensityChannel(head().head)); if (m_parent->overrideFadeOutSpeed() != Function::defaultSpeed()) fc.setFadeTime(m_parent->overrideFadeOutSpeed()); else fc.setFadeTime(m_parent->fadeOutSpeed()); fc.setStart(uchar(floor((qreal(fadeIntensity()) * intensity()) + 0.5))); fc.setCurrent(fc.start()); fc.setTarget(0); // Give zero-fading to MasterTimer because EFX will stop after this call timer->faderAdd(fc); // Remove the previously up-faded channel from EFX's internal fader to allow // MasterTimer's fader take HTP precedence. m_parent->m_fader->remove(fc); } } m_started = false; } /***************************************************************************** * Intensity *****************************************************************************/ void EFXFixture::adjustIntensity(qreal fraction) { m_intensity = fraction; } qreal EFXFixture::intensity() const { return m_intensity; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: finance.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkActor.h" #include "vtkAxes.h" #include "vtkContourFilter.h" #include "vtkDataSet.h" #include "vtkFloatArray.h" #include "vtkGaussianSplatter.h" #include "vtkImageData.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkTubeFilter.h" #include "vtkUnstructuredGrid.h" #include "vtkSmartPointer.h" #if defined( _MSC_VER ) /* Visual C++ (and Intel C++) */ #pragma warning(disable : 4996) // 'function': was declared deprecated #endif static vtkSmartPointer<vtkDataSet> ReadFinancialData(const char *fname, const char *x, const char *y, const char *z, const char *s); static int ParseFile(FILE *file, const char *tag, float *data); int main( int argc, char *argv[] ) { double bounds[6]; if (argc < 2) { cout << "Usage: " << argv[0] << " financial_file" << endl; return 1; } char* fname = argv[1]; // read data vtkSmartPointer<vtkDataSet> dataSet = ReadFinancialData(fname, "MONTHLY_PAYMENT","INTEREST_RATE", "LOAN_AMOUNT","TIME_LATE"); // construct pipeline for original population vtkSmartPointer<vtkGaussianSplatter> popSplatter = vtkSmartPointer<vtkGaussianSplatter>::New(); popSplatter->SetInput(dataSet); popSplatter->SetSampleDimensions(50,50,50); popSplatter->SetRadius(0.05); popSplatter->ScalarWarpingOff(); vtkSmartPointer<vtkContourFilter> popSurface = vtkSmartPointer<vtkContourFilter>::New(); popSurface->SetInputConnection(popSplatter->GetOutputPort()); popSurface->SetValue(0,0.01); vtkSmartPointer<vtkPolyDataMapper> popMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); popMapper->SetInputConnection(popSurface->GetOutputPort()); popMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> popActor = vtkSmartPointer<vtkActor>::New(); popActor->SetMapper(popMapper); popActor->GetProperty()->SetOpacity(0.3); popActor->GetProperty()->SetColor(.9,.9,.9); // construct pipeline for delinquent population vtkSmartPointer<vtkGaussianSplatter> lateSplatter = vtkSmartPointer<vtkGaussianSplatter>::New(); lateSplatter->SetInput(dataSet); lateSplatter->SetSampleDimensions(50,50,50); lateSplatter->SetRadius(0.05); lateSplatter->SetScaleFactor(0.005); vtkSmartPointer<vtkContourFilter> lateSurface = vtkSmartPointer<vtkContourFilter>::New(); lateSurface->SetInputConnection(lateSplatter->GetOutputPort()); lateSurface->SetValue(0,0.01); vtkSmartPointer<vtkPolyDataMapper> lateMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); lateMapper->SetInputConnection(lateSurface->GetOutputPort()); lateMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> lateActor = vtkSmartPointer<vtkActor>::New(); lateActor->SetMapper(lateMapper); lateActor->GetProperty()->SetColor(1.0,0.0,0.0); // create axes popSplatter->Update(); popSplatter->GetOutput()->GetBounds(bounds); vtkSmartPointer<vtkAxes> axes = vtkSmartPointer<vtkAxes>::New(); axes->SetOrigin(bounds[0], bounds[2], bounds[4]); axes->SetScaleFactor(popSplatter->GetOutput()->GetLength()/5); vtkSmartPointer<vtkTubeFilter> axesTubes = vtkSmartPointer<vtkTubeFilter>::New(); axesTubes->SetInputConnection(axes->GetOutputPort()); axesTubes->SetRadius(axes->GetScaleFactor()/25.0); axesTubes->SetNumberOfSides(6); vtkSmartPointer<vtkPolyDataMapper> axesMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); axesMapper->SetInputConnection(axesTubes->GetOutputPort()); vtkSmartPointer<vtkActor> axesActor = vtkSmartPointer<vtkActor>::New(); axesActor->SetMapper(axesMapper); // graphics stuff vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); renWin->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow(renWin); // read data //set up renderer renderer->AddActor(lateActor); renderer->AddActor(axesActor); renderer->AddActor(popActor); renderer->SetBackground(1,1,1); renWin->SetSize(300,300); // interact with data iren->Initialize(); renWin->Render(); iren->Start(); return 0; } static vtkSmartPointer<vtkDataSet> ReadFinancialData(const char* filename, const char *x, const char *y, const char *z, const char *s) { float xyz[3]; FILE *file; int i, npts; char tag[80]; if ( (file = fopen(filename,"r")) == 0 ) { cerr << "ERROR: Can't open file: " << filename << "\n"; return NULL; } int n = fscanf (file, "%s %d", tag, &npts); // read number of points if (n != 2) { cerr << "ERROR: Can't read file: " << filename << "\n"; return NULL; } vtkSmartPointer<vtkUnstructuredGrid> dataSet = vtkSmartPointer<vtkUnstructuredGrid>::New(); float *xV = new float[npts]; float *yV = new float[npts]; float *zV = new float[npts]; float *sV = new float[npts]; if ( ! ParseFile(file, x, xV) || ! ParseFile(file, y, yV) || ! ParseFile(file, z, zV) || ! ParseFile(file, s, sV) ) { cerr << "Couldn't read data!\n"; delete [] xV; delete [] yV; delete [] zV; delete [] sV; fclose(file); return NULL; } vtkSmartPointer<vtkPoints> newPts = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkFloatArray> newScalars = vtkSmartPointer<vtkFloatArray>::New(); for (i=0; i<npts; i++) { xyz[0] = xV[i]; xyz[1] = yV[i]; xyz[2] = zV[i]; newPts->InsertPoint(i, xyz); newScalars->InsertValue(i, sV[i]); } dataSet->SetPoints(newPts); dataSet->GetPointData()->SetScalars(newScalars); // cleanup delete [] xV; delete [] yV; delete [] zV; delete [] sV; fclose(file); return dataSet; } static int ParseFile(FILE *file, const char *label, float *data) { char tag[80]; int i, npts, readData=0; float min=VTK_LARGE_FLOAT; float max=(-VTK_LARGE_FLOAT); if ( file == NULL || label == NULL ) return 0; rewind(file); if (fscanf(file, "%s %d", tag, &npts) != 2) { cerr << "IO Error " << __FILE__ << ":" << __LINE__ << "\n"; return 0; } while ( !readData && fscanf(file, "%s", tag) == 1 ) { if ( ! strcmp(tag,label) ) { readData = 1; for (i=0; i<npts; i++) { if (fscanf(file, "%f", data+i) != 1) { cerr << "IO Error " << __FILE__ << ":" << __LINE__ << "\n"; return 0; } if ( data[i] < min ) min = data[i]; if ( data[i] > min ) max = data[i]; } // normalize data for (i=0; i<npts; i++) data[i] = min + data[i]/(max-min); } else { for (i=0; i<npts; i++) { if (fscanf(file, "%*f") != 1) { cerr << "IO Error " << __FILE__ << ":" << __LINE__ << "\n"; return 0; } } } } if ( ! readData ) return 0; else return 1; } <commit_msg>COMP: Fix fscanf count check in finance example.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: finance.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkActor.h" #include "vtkAxes.h" #include "vtkContourFilter.h" #include "vtkDataSet.h" #include "vtkFloatArray.h" #include "vtkGaussianSplatter.h" #include "vtkImageData.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkTubeFilter.h" #include "vtkUnstructuredGrid.h" #include "vtkSmartPointer.h" #if defined( _MSC_VER ) /* Visual C++ (and Intel C++) */ #pragma warning(disable : 4996) // 'function': was declared deprecated #endif static vtkSmartPointer<vtkDataSet> ReadFinancialData(const char *fname, const char *x, const char *y, const char *z, const char *s); static int ParseFile(FILE *file, const char *tag, float *data); int main( int argc, char *argv[] ) { double bounds[6]; if (argc < 2) { cout << "Usage: " << argv[0] << " financial_file" << endl; return 1; } char* fname = argv[1]; // read data vtkSmartPointer<vtkDataSet> dataSet = ReadFinancialData(fname, "MONTHLY_PAYMENT","INTEREST_RATE", "LOAN_AMOUNT","TIME_LATE"); // construct pipeline for original population vtkSmartPointer<vtkGaussianSplatter> popSplatter = vtkSmartPointer<vtkGaussianSplatter>::New(); popSplatter->SetInput(dataSet); popSplatter->SetSampleDimensions(50,50,50); popSplatter->SetRadius(0.05); popSplatter->ScalarWarpingOff(); vtkSmartPointer<vtkContourFilter> popSurface = vtkSmartPointer<vtkContourFilter>::New(); popSurface->SetInputConnection(popSplatter->GetOutputPort()); popSurface->SetValue(0,0.01); vtkSmartPointer<vtkPolyDataMapper> popMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); popMapper->SetInputConnection(popSurface->GetOutputPort()); popMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> popActor = vtkSmartPointer<vtkActor>::New(); popActor->SetMapper(popMapper); popActor->GetProperty()->SetOpacity(0.3); popActor->GetProperty()->SetColor(.9,.9,.9); // construct pipeline for delinquent population vtkSmartPointer<vtkGaussianSplatter> lateSplatter = vtkSmartPointer<vtkGaussianSplatter>::New(); lateSplatter->SetInput(dataSet); lateSplatter->SetSampleDimensions(50,50,50); lateSplatter->SetRadius(0.05); lateSplatter->SetScaleFactor(0.005); vtkSmartPointer<vtkContourFilter> lateSurface = vtkSmartPointer<vtkContourFilter>::New(); lateSurface->SetInputConnection(lateSplatter->GetOutputPort()); lateSurface->SetValue(0,0.01); vtkSmartPointer<vtkPolyDataMapper> lateMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); lateMapper->SetInputConnection(lateSurface->GetOutputPort()); lateMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> lateActor = vtkSmartPointer<vtkActor>::New(); lateActor->SetMapper(lateMapper); lateActor->GetProperty()->SetColor(1.0,0.0,0.0); // create axes popSplatter->Update(); popSplatter->GetOutput()->GetBounds(bounds); vtkSmartPointer<vtkAxes> axes = vtkSmartPointer<vtkAxes>::New(); axes->SetOrigin(bounds[0], bounds[2], bounds[4]); axes->SetScaleFactor(popSplatter->GetOutput()->GetLength()/5); vtkSmartPointer<vtkTubeFilter> axesTubes = vtkSmartPointer<vtkTubeFilter>::New(); axesTubes->SetInputConnection(axes->GetOutputPort()); axesTubes->SetRadius(axes->GetScaleFactor()/25.0); axesTubes->SetNumberOfSides(6); vtkSmartPointer<vtkPolyDataMapper> axesMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); axesMapper->SetInputConnection(axesTubes->GetOutputPort()); vtkSmartPointer<vtkActor> axesActor = vtkSmartPointer<vtkActor>::New(); axesActor->SetMapper(axesMapper); // graphics stuff vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); renWin->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow(renWin); // read data //set up renderer renderer->AddActor(lateActor); renderer->AddActor(axesActor); renderer->AddActor(popActor); renderer->SetBackground(1,1,1); renWin->SetSize(300,300); // interact with data iren->Initialize(); renWin->Render(); iren->Start(); return 0; } static vtkSmartPointer<vtkDataSet> ReadFinancialData(const char* filename, const char *x, const char *y, const char *z, const char *s) { float xyz[3]; FILE *file; int i, npts; char tag[80]; if ( (file = fopen(filename,"r")) == 0 ) { cerr << "ERROR: Can't open file: " << filename << "\n"; return NULL; } int n = fscanf (file, "%s %d", tag, &npts); // read number of points if (n != 2) { cerr << "ERROR: Can't read file: " << filename << "\n"; return NULL; } vtkSmartPointer<vtkUnstructuredGrid> dataSet = vtkSmartPointer<vtkUnstructuredGrid>::New(); float *xV = new float[npts]; float *yV = new float[npts]; float *zV = new float[npts]; float *sV = new float[npts]; if ( ! ParseFile(file, x, xV) || ! ParseFile(file, y, yV) || ! ParseFile(file, z, zV) || ! ParseFile(file, s, sV) ) { cerr << "Couldn't read data!\n"; delete [] xV; delete [] yV; delete [] zV; delete [] sV; fclose(file); return NULL; } vtkSmartPointer<vtkPoints> newPts = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkFloatArray> newScalars = vtkSmartPointer<vtkFloatArray>::New(); for (i=0; i<npts; i++) { xyz[0] = xV[i]; xyz[1] = yV[i]; xyz[2] = zV[i]; newPts->InsertPoint(i, xyz); newScalars->InsertValue(i, sV[i]); } dataSet->SetPoints(newPts); dataSet->GetPointData()->SetScalars(newScalars); // cleanup delete [] xV; delete [] yV; delete [] zV; delete [] sV; fclose(file); return dataSet; } static int ParseFile(FILE *file, const char *label, float *data) { char tag[80]; int i, npts, readData=0; float min=VTK_LARGE_FLOAT; float max=(-VTK_LARGE_FLOAT); if ( file == NULL || label == NULL ) return 0; rewind(file); if (fscanf(file, "%s %d", tag, &npts) != 2) { cerr << "IO Error " << __FILE__ << ":" << __LINE__ << "\n"; return 0; } while ( !readData && fscanf(file, "%s", tag) == 1 ) { if ( ! strcmp(tag,label) ) { readData = 1; for (i=0; i<npts; i++) { if (fscanf(file, "%f", data+i) != 1) { cerr << "IO Error " << __FILE__ << ":" << __LINE__ << "\n"; return 0; } if ( data[i] < min ) min = data[i]; if ( data[i] > min ) max = data[i]; } // normalize data for (i=0; i<npts; i++) data[i] = min + data[i]/(max-min); } else { for (i=0; i<npts; i++) { if (fscanf(file, "%*f") != 0) { cerr << "IO Error " << __FILE__ << ":" << __LINE__ << "\n"; return 0; } } } } if ( ! readData ) return 0; else return 1; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: elapsedtime.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-17 03:25:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_canvas.hxx" #include "osl/time.h" #include "osl/diagnose.h" #include "canvas/elapsedtime.hxx" #if defined(WIN) || defined(WNT) // TEMP!!! // Awaiting corresponding functionality in OSL // #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winbase.h> #include <mmsystem.h> #endif #include <algorithm> #include <limits> namespace canvas { namespace tools { #if defined(WIN) || defined(WNT) // TODO(Q2): is 0 okay for the failure case here? double ElapsedTime::getSystemTime() { // TEMP!!! // Awaiting corresponding functionality in OSL // // is there a performance counter available? static bool bTimeSetupDone( false ); static bool bPerfTimerAvailable( false ); static LONGLONG nPerfCountFreq; // TODO(F1): This _might_ cause problems, as it prevents correct // time handling for very long lifetimes of this class's // surrounding component in memory. When the difference between // current sys time and nInitialCount exceeds IEEE double's // mantissa, time will start to run jerky. static LONGLONG nInitialCount; if( !bTimeSetupDone ) { if( QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER *>(&nPerfCountFreq) ) ) { // read initial time: QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER *>(&nInitialCount) ); bPerfTimerAvailable = true; } bTimeSetupDone = true; } if( bPerfTimerAvailable ) { LONGLONG nCurrCount; QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER *>(&nCurrCount) ); nCurrCount -= nInitialCount; return (double)nCurrCount / nPerfCountFreq; } else { LONGLONG nCurrTime = timeGetTime(); return (double)nCurrTime / 1000.0; } } #else // ! WNT // TODO(Q2): is 0 okay for the failure case here? double ElapsedTime::getSystemTime() { TimeValue aTimeVal; if( osl_getSystemTime( &aTimeVal ) ) return ((aTimeVal.Nanosec * 10e-10) + aTimeVal.Seconds); else return 0.0; } #endif ElapsedTime::ElapsedTime() : m_pTimeBase(), m_fLastQueriedTime( 0.0 ), m_fStartTime( getSystemTime() ), m_fFrozenTime( 0.0 ), m_bInPauseMode( false ), m_bInHoldMode( false ) { } ElapsedTime::ElapsedTime( boost::shared_ptr<ElapsedTime> const & pTimeBase ) : m_pTimeBase( pTimeBase ), m_fLastQueriedTime( 0.0 ), m_fStartTime( getCurrentTime() ), m_fFrozenTime( 0.0 ), m_bInPauseMode( false ), m_bInHoldMode( false ) { } boost::shared_ptr<ElapsedTime> const & ElapsedTime::getTimeBase() const { return m_pTimeBase; } void ElapsedTime::reset() { m_fLastQueriedTime = 0.0; m_fStartTime = getCurrentTime(); m_fFrozenTime = 0.0; m_bInPauseMode = false; m_bInHoldMode = false; } void ElapsedTime::adjustTimer( double fOffset, bool /*bLimitToLastQueriedTime*/ ) { #if 0 if (bLimitToLastQueriedTime) { const double fCurrentTime = getElapsedTimeImpl(); if (m_fLastQueriedTime > (fCurrentTime + fOffset)) { // TODO(Q3): Once the dust has settled, reduce to // OSL_TRACE here! OSL_ENSURE( false, "### adjustTimer(): clamping!" ); fOffset = (m_fLastQueriedTime - fCurrentTime); } } #endif // to make getElapsedTime() become _larger_, have to reduce // m_fStartTime. m_fStartTime -= fOffset; // also adjust frozen time, this method must _always_ affect the // value returned by getElapsedTime()! if (m_bInHoldMode || m_bInPauseMode) m_fFrozenTime += fOffset; } double ElapsedTime::getCurrentTime() const { return m_pTimeBase.get() == 0 ? getSystemTime() : m_pTimeBase->getElapsedTimeImpl(); } double ElapsedTime::getElapsedTime() const { m_fLastQueriedTime = getElapsedTimeImpl(); return m_fLastQueriedTime; } double ElapsedTime::getElapsedTimeImpl() const { if (m_bInHoldMode || m_bInPauseMode) return m_fFrozenTime; return getCurrentTime() - m_fStartTime; } void ElapsedTime::pauseTimer() { m_fFrozenTime = getElapsedTimeImpl(); m_bInPauseMode = true; } void ElapsedTime::continueTimer() { m_bInPauseMode = false; // stop pausing, time runs again. Note that // getElapsedTimeImpl() honors hold mode, i.e. a // continueTimer() in hold mode will preserve the latter const double fPauseDuration( getElapsedTimeImpl() - m_fFrozenTime ); // adjust start time, such that subsequent getElapsedTime() calls // will virtually start from m_fFrozenTime. m_fStartTime += fPauseDuration; } void ElapsedTime::holdTimer() { // when called during hold mode (e.g. more than once per time // object), the original hold time will be maintained. m_fFrozenTime = getElapsedTimeImpl(); m_bInHoldMode = true; } void ElapsedTime::releaseTimer() { m_bInHoldMode = false; } } // namespace tools } // namespace canvas <commit_msg>INTEGRATION: CWS sb59 (1.6.16); FILE MERGED 2006/08/11 22:05:05 thb 1.6.16.1: #i68336# Made canvas warning free for wntmsci10<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: elapsedtime.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-10-12 11:31:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_canvas.hxx" #include "osl/time.h" #include "osl/diagnose.h" #include "canvas/elapsedtime.hxx" #if defined(WIN) || defined(WNT) #if defined _MSC_VER #pragma warning(push,1) #endif // TEMP!!! // Awaiting corresponding functionality in OSL // #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winbase.h> #include <mmsystem.h> #endif #if defined _MSC_VER #pragma warning(pop) #endif #include <algorithm> #include <limits> namespace canvas { namespace tools { #if defined(WIN) || defined(WNT) // TODO(Q2): is 0 okay for the failure case here? double ElapsedTime::getSystemTime() { // TEMP!!! // Awaiting corresponding functionality in OSL // // is there a performance counter available? static bool bTimeSetupDone( false ); static bool bPerfTimerAvailable( false ); static LONGLONG nPerfCountFreq; // TODO(F1): This _might_ cause problems, as it prevents correct // time handling for very long lifetimes of this class's // surrounding component in memory. When the difference between // current sys time and nInitialCount exceeds IEEE double's // mantissa, time will start to run jerky. static LONGLONG nInitialCount; if( !bTimeSetupDone ) { if( QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER *>(&nPerfCountFreq) ) ) { // read initial time: QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER *>(&nInitialCount) ); bPerfTimerAvailable = true; } bTimeSetupDone = true; } if( bPerfTimerAvailable ) { LONGLONG nCurrCount; QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER *>(&nCurrCount) ); nCurrCount -= nInitialCount; return (double)nCurrCount / nPerfCountFreq; } else { LONGLONG nCurrTime = timeGetTime(); return (double)nCurrTime / 1000.0; } } #else // ! WNT // TODO(Q2): is 0 okay for the failure case here? double ElapsedTime::getSystemTime() { TimeValue aTimeVal; if( osl_getSystemTime( &aTimeVal ) ) return ((aTimeVal.Nanosec * 10e-10) + aTimeVal.Seconds); else return 0.0; } #endif ElapsedTime::ElapsedTime() : m_pTimeBase(), m_fLastQueriedTime( 0.0 ), m_fStartTime( getSystemTime() ), m_fFrozenTime( 0.0 ), m_bInPauseMode( false ), m_bInHoldMode( false ) { } ElapsedTime::ElapsedTime( boost::shared_ptr<ElapsedTime> const & pTimeBase ) : m_pTimeBase( pTimeBase ), m_fLastQueriedTime( 0.0 ), m_fStartTime( getCurrentTime() ), m_fFrozenTime( 0.0 ), m_bInPauseMode( false ), m_bInHoldMode( false ) { } boost::shared_ptr<ElapsedTime> const & ElapsedTime::getTimeBase() const { return m_pTimeBase; } void ElapsedTime::reset() { m_fLastQueriedTime = 0.0; m_fStartTime = getCurrentTime(); m_fFrozenTime = 0.0; m_bInPauseMode = false; m_bInHoldMode = false; } void ElapsedTime::adjustTimer( double fOffset, bool /*bLimitToLastQueriedTime*/ ) { #if 0 if (bLimitToLastQueriedTime) { const double fCurrentTime = getElapsedTimeImpl(); if (m_fLastQueriedTime > (fCurrentTime + fOffset)) { // TODO(Q3): Once the dust has settled, reduce to // OSL_TRACE here! OSL_ENSURE( false, "### adjustTimer(): clamping!" ); fOffset = (m_fLastQueriedTime - fCurrentTime); } } #endif // to make getElapsedTime() become _larger_, have to reduce // m_fStartTime. m_fStartTime -= fOffset; // also adjust frozen time, this method must _always_ affect the // value returned by getElapsedTime()! if (m_bInHoldMode || m_bInPauseMode) m_fFrozenTime += fOffset; } double ElapsedTime::getCurrentTime() const { return m_pTimeBase.get() == 0 ? getSystemTime() : m_pTimeBase->getElapsedTimeImpl(); } double ElapsedTime::getElapsedTime() const { m_fLastQueriedTime = getElapsedTimeImpl(); return m_fLastQueriedTime; } double ElapsedTime::getElapsedTimeImpl() const { if (m_bInHoldMode || m_bInPauseMode) return m_fFrozenTime; return getCurrentTime() - m_fStartTime; } void ElapsedTime::pauseTimer() { m_fFrozenTime = getElapsedTimeImpl(); m_bInPauseMode = true; } void ElapsedTime::continueTimer() { m_bInPauseMode = false; // stop pausing, time runs again. Note that // getElapsedTimeImpl() honors hold mode, i.e. a // continueTimer() in hold mode will preserve the latter const double fPauseDuration( getElapsedTimeImpl() - m_fFrozenTime ); // adjust start time, such that subsequent getElapsedTime() calls // will virtually start from m_fFrozenTime. m_fStartTime += fPauseDuration; } void ElapsedTime::holdTimer() { // when called during hold mode (e.g. more than once per time // object), the original hold time will be maintained. m_fFrozenTime = getElapsedTimeImpl(); m_bInHoldMode = true; } void ElapsedTime::releaseTimer() { m_bInHoldMode = false; } } // namespace tools } // namespace canvas <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/grappler/grappler_item_builder.h" #include <unordered_map> #include <unordered_set> #include <vector> #include "tensorflow/core/common_runtime/device.h" #include "tensorflow/core/common_runtime/device_factory.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/graph_optimizer.h" #include "tensorflow/core/framework/attr_value.pb.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/function.pb.h" #include "tensorflow/core/framework/graph_def_util.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/tensor_shape.pb.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/framework/variable.pb.h" #include "tensorflow/core/framework/versions.pb.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/grappler/inputs/utils.h" #include "tensorflow/core/grappler/op_types.h" #include "tensorflow/core/grappler/utils.h" #include "tensorflow/core/protobuf/meta_graph.pb.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { namespace grappler { namespace { void InitializeTensor(DataType type, Tensor* tensor) { const int period = 7; if (type == DT_FLOAT) { auto flat = tensor->flat<float>(); // Populate numbers 0, 0.1, 0.2, ..., 0.5, 0.6, 0, 0.1, 0.2, ... for (int i = 0; i < flat.size(); i++) { flat(i) = static_cast<float>(i % period) / 10.0f; } } else if (type == DT_INT64) { auto flat = tensor->flat<int64>(); // Populate numbers 0, 1, 2, ..., 5, 6, 0, 1, 2, ... for (int i = 0; i < flat.size(); i++) { flat(i) = i % period; } } else { memset(const_cast<char*>(tensor->tensor_data().data()), 0, tensor->tensor_data().size()); } } // Optimize the graph def (including function inlining and other optimizations). // This is a temporary change that optimizes the graph in context of a single // gpu machine. Down the line, we may want to make grappler_item_builder aware // of the cluster type (E.g: single cpu, multiple gpu, etc) being simulated in // order to get the correct session options and environment, and performing the // correct optimizations. Status OptimizeGraph(const GraphDef& graph_def, GraphDef* output_graph_def, const ItemConfig& cfg) { if (!cfg.apply_optimizations && !cfg.inline_functions) { return Status::OK(); } // Create a session option for a single GPU device. SessionOptions options; // Inline all functions. GraphDef inlined_graph_def(graph_def); for (int i = 0; i < inlined_graph_def.library().function().size(); i++) { FunctionDef* fdef = inlined_graph_def.mutable_library()->mutable_function(i); SetAttrValue(false, &((*fdef->mutable_attr())[kNoInlineAttr])); } // Instantiate all variables for function library runtime creation. std::vector<Device*> devices; TF_RETURN_IF_ERROR(DeviceFactory::AddDevices( options, "/job:localhost/replica:0/task:0", &devices)); std::unique_ptr<DeviceMgr> dvc_mgr(new DeviceMgr(devices)); FunctionLibraryDefinition function_library(OpRegistry::Global(), inlined_graph_def.library()); Env* env = Env::Default(); // Optimizer options: L1 and inlining. L1 is default. OptimizerOptions* optimizer_opts = options.config.mutable_graph_options()->mutable_optimizer_options(); if (cfg.apply_optimizations) { optimizer_opts->set_opt_level(::tensorflow::OptimizerOptions_Level_L1); } else { optimizer_opts->set_opt_level(::tensorflow::OptimizerOptions_Level_L0); } optimizer_opts->set_do_function_inlining(cfg.inline_functions); // Create the function library runtime. std::unique_ptr<FunctionLibraryRuntime> flib(NewFunctionLibraryRuntime( dvc_mgr.get(), env, devices[0], inlined_graph_def.versions().producer(), &function_library, *optimizer_opts)); // Create the GraphOptimizer to optimize the graph def. GraphConstructorOptions graph_ctor_opts; graph_ctor_opts.allow_internal_ops = true; graph_ctor_opts.expect_device_spec = false; std::unique_ptr<Graph> graphptr(new Graph(function_library)); // Populate default attrs to the NodeDefs in the GraphDef. TF_RETURN_IF_ERROR(AddDefaultAttrsToGraphDef(&inlined_graph_def, *graphptr->op_registry(), 0)); TF_RETURN_IF_ERROR(ConvertGraphDefToGraph(graph_ctor_opts, inlined_graph_def, graphptr.get())); // Optimize the graph. GraphOptimizer optimizer(*optimizer_opts); optimizer.Optimize(flib.get(), env, devices[0], &graphptr, /*shape_map=*/nullptr); graphptr->ToGraphDef(output_graph_def); return Status::OK(); } } // namespace // static std::unique_ptr<GrapplerItem> GrapplerItemFromMetaGraphDef( const string& id, const MetaGraphDef& meta_graph, const ItemConfig& cfg) { if (id.empty()) { LOG(ERROR) << "id must be non-empty."; return nullptr; } std::unique_ptr<GrapplerItem> new_item(new GrapplerItem()); new_item->id = id; new_item->graph = meta_graph.graph_def(); // Attempt to detect the fetch node(s). if (meta_graph.collection_def().count("train_op") > 0) { const CollectionDef& nodes = meta_graph.collection_def().at("train_op"); if (nodes.has_node_list()) { for (const auto& node : nodes.node_list().value()) { const string name = NodeName(node); if (name.empty()) { LOG(ERROR) << "Invalid fetch node name " << node << ", skipping this input"; return nullptr; } LOG(INFO) << "Will use fetch node " << name; new_item->fetch.push_back(name); } } } if (new_item->fetch.empty()) { LOG(ERROR) << "Failed to detect the fetch node(s), skipping this input"; return nullptr; } for (auto& node : *new_item->graph.mutable_node()) { if (IsPlaceholder(node)) { if (node.attr().count("dtype") == 0) { LOG(ERROR) << "Unknown type for placeholder " << node.name() << ", skipping this input"; return nullptr; } DataType type = node.attr().at("dtype").type(); if (node.attr().count("shape") == 0) { LOG(INFO) << "Unknown shape for placeholder " << node.name() << ", skipping this input"; return nullptr; } // Replace all unknown dimensions in the placeholder's tensorshape proto // with cfg.placeholder_unknown_output_shape_dim and create a tensorshape // from it. We do this because in newer protos, the input placeholder // shape is not empty if the shape is partially defined. TensorShape shape; TensorShapeProto shape_proto; std::vector<int32> dims; for (const auto& dim_proto : node.attr().at("shape").shape().dim()) { if (cfg.placeholder_unknown_output_shape_dim >= 0 && dim_proto.size() == -1) { dims.push_back(cfg.placeholder_unknown_output_shape_dim); shape_proto.add_dim()->set_size( cfg.placeholder_unknown_output_shape_dim); } else { dims.push_back(std::max<int32>(1, dim_proto.size())); shape_proto.add_dim()->set_size(dim_proto.size()); } } Status make_shape_status = TensorShapeUtils::MakeShape(dims.data(), dims.size(), &shape); if (!make_shape_status.ok()) { LOG(ERROR) << "Invalid shape for placeholder " << node.name() << ": " << make_shape_status << ", skipping this input"; return nullptr; } // Some placeholder nodes have a mis-match between the node // attribute "shape" and a different node attribute "_output_shapes". // Specifically, a shape with shape.dims() == 0 could indicate either // a scalar or an unknown shape. In those cases, we check _output_shapes // for additional information. // This case is observed in the bnmt graphs. Have not observed any // cases where there was more than 1 _output_shapes, so limit it // to cases where there is only 1 _output_shapes. // We only do this if cfg.placeholder_unknown_output_shape_dim has // been set to avoid crashing non-BNMT graphs. if ((cfg.placeholder_unknown_output_shape_dim >= 0) && (shape.dims() == 0) && (node.attr().count("_output_shapes") == 1) && (node.attr().at("_output_shapes").list().shape(0).dim_size() != 0)) { shape.Clear(); shape_proto.clear_dim(); for (int dim_i = 0; dim_i < node.attr().at("_output_shapes").list().shape(0).dim_size(); dim_i++) { const ::tensorflow::TensorShapeProto_Dim dim = node.attr().at("_output_shapes").list().shape(0).dim(dim_i); if (dim.size() == -1) { shape.AddDim(cfg.placeholder_unknown_output_shape_dim); shape_proto.add_dim()->set_size( cfg.placeholder_unknown_output_shape_dim); } else { int size = node.attr() .at("_output_shapes") .list() .shape(0) .dim(dim_i) .size(); shape.AddDim(size); shape_proto.add_dim()->set_size(size); } } } Tensor fake_input(type, shape); InitializeTensor(type, &fake_input); new_item->feed.emplace_back(node.name(), fake_input); // Set the shape of the node in the graph. This is needed for statically // inferring shapes and is a no-op when dynamically inferring shapes as // the Placeholder shape will match the shape passed from new_item->feed. *(node.mutable_attr()->at("shape").mutable_shape()) = shape_proto; } // Erase the recorded result of any previous shape inference to start again // from scratch. node.mutable_attr()->erase("_output_shapes"); // Delete user specified placement if requested. if (cfg.ignore_user_placement) { node.clear_device(); } // Delete colocation constraints if requested. if (cfg.ignore_colocation) { auto attr = node.mutable_attr(); auto it = attr->find("_class"); if (it != attr->end()) { attr->erase(it); } } } for (const string& var_collection : {"variables", "local_variables", "model_variables", "trainable_variables"}) { if (meta_graph.collection_def().count(var_collection) == 0) { continue; } const CollectionDef& vars = meta_graph.collection_def().at(var_collection); for (const auto& raw_var : vars.bytes_list().value()) { VariableDef var; var.ParseFromString(raw_var); if (!var.initializer_name().empty()) { new_item->init_ops.push_back(var.initializer_name()); } } } if (meta_graph.collection_def().count("table_initializer") > 0) { const CollectionDef& inits = meta_graph.collection_def().at("table_initializer"); if (inits.has_node_list()) { for (const auto& node : inits.node_list().value()) { new_item->init_ops.push_back(node); // Tables are initialized from files, which can take a long time. Add 30 // minutes to the initialization time for each table to avoid timing // out. // TODO(bsteiner): adjust the timeout based on the file size. new_item->expected_init_time += 30 * 60; } } } if (meta_graph.collection_def().count("queue_runners") > 0) { const CollectionDef& vars = meta_graph.collection_def().at("queue_runners"); for (const auto& raw : vars.bytes_list().value()) { QueueRunnerDef queue_runner; if (!queue_runner.ParseFromString(raw)) { LOG(ERROR) << "Could parse queue_runners, skipping this input"; return nullptr; } if (queue_runner.cancel_op_name().empty()) { LOG(ERROR) << "Queue without a cancel op, skipping this input"; return nullptr; } new_item->queue_runners.push_back(queue_runner); } } // Make sure we still can access the input files (aka "asset_filepaths") since // these might have been moved or deleted, the cns cell might have been shut // down, or we might be running as a user who does not have access to the // files. if (meta_graph.collection_def().count("asset_filepaths") > 0) { const CollectionDef& file_paths = meta_graph.collection_def().at("asset_filepaths"); std::vector<string> paths; for (const auto& raw_path : file_paths.bytes_list().value()) { paths.push_back(raw_path); } if (!FilesExist(paths, nullptr)) { LOG(ERROR) << "Can't access one or more of the asset files, skipping this input"; return nullptr; } } // Optimize the graph (function inlining, l1 optimizations, etc). Status optimize_status = OptimizeGraph(new_item->graph, &new_item->graph, cfg); if (!optimize_status.ok()) { LOG(ERROR) << "Graph preprocessing failed: " << optimize_status; return nullptr; } // Validate feed, fetch and init nodes std::unordered_set<string> nodes; for (const auto& node : new_item->graph.node()) { nodes.insert(node.name()); } for (const auto& feed : new_item->feed) { if (nodes.find(feed.first) == nodes.end()) { LOG(ERROR) << "Feed node " << feed.first << " doesn't exist in graph"; return nullptr; } } for (const auto& fetch : new_item->fetch) { if (nodes.find(fetch) == nodes.end()) { LOG(ERROR) << "Fetch node " << fetch << " doesn't exist in graph"; return nullptr; } } for (const auto& init : new_item->init_ops) { if (nodes.find(init) == nodes.end()) { LOG(ERROR) << "Init node " << init << " doesn't exist in graph"; return nullptr; } } return new_item; } } // end namespace grappler } // end namespace tensorflow <commit_msg>Don't force inlining of functions marked no-inline<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/grappler/grappler_item_builder.h" #include <unordered_map> #include <unordered_set> #include <vector> #include "tensorflow/core/common_runtime/device.h" #include "tensorflow/core/common_runtime/device_factory.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/graph_optimizer.h" #include "tensorflow/core/framework/attr_value.pb.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/function.pb.h" #include "tensorflow/core/framework/graph_def_util.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/tensor_shape.pb.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/framework/variable.pb.h" #include "tensorflow/core/framework/versions.pb.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/grappler/inputs/utils.h" #include "tensorflow/core/grappler/op_types.h" #include "tensorflow/core/grappler/utils.h" #include "tensorflow/core/protobuf/meta_graph.pb.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { namespace grappler { namespace { void InitializeTensor(DataType type, Tensor* tensor) { const int period = 7; if (type == DT_FLOAT) { auto flat = tensor->flat<float>(); // Populate numbers 0, 0.1, 0.2, ..., 0.5, 0.6, 0, 0.1, 0.2, ... for (int i = 0; i < flat.size(); i++) { flat(i) = static_cast<float>(i % period) / 10.0f; } } else if (type == DT_INT64) { auto flat = tensor->flat<int64>(); // Populate numbers 0, 1, 2, ..., 5, 6, 0, 1, 2, ... for (int i = 0; i < flat.size(); i++) { flat(i) = i % period; } } else { memset(const_cast<char*>(tensor->tensor_data().data()), 0, tensor->tensor_data().size()); } } // Optimize the graph def (including function inlining and other optimizations). // This is a temporary change that optimizes the graph in context of a single // gpu machine. Down the line, we may want to make grappler_item_builder aware // of the cluster type (E.g: single cpu, multiple gpu, etc) being simulated in // order to get the correct session options and environment, and performing the // correct optimizations. Status OptimizeGraph(const GraphDef& graph_def, GraphDef* output_graph_def, const ItemConfig& cfg) { if (!cfg.apply_optimizations && !cfg.inline_functions) { return Status::OK(); } // Create a session option for a single GPU device. SessionOptions options; // Inline all functions. GraphDef inlined_graph_def(graph_def); // Instantiate all variables for function library runtime creation. std::vector<Device*> devices; TF_RETURN_IF_ERROR(DeviceFactory::AddDevices( options, "/job:localhost/replica:0/task:0", &devices)); std::unique_ptr<DeviceMgr> dvc_mgr(new DeviceMgr(devices)); FunctionLibraryDefinition function_library(OpRegistry::Global(), inlined_graph_def.library()); Env* env = Env::Default(); // Optimizer options: L1 and inlining. L1 is default. OptimizerOptions* optimizer_opts = options.config.mutable_graph_options()->mutable_optimizer_options(); if (cfg.apply_optimizations) { optimizer_opts->set_opt_level(::tensorflow::OptimizerOptions_Level_L1); } else { optimizer_opts->set_opt_level(::tensorflow::OptimizerOptions_Level_L0); } optimizer_opts->set_do_function_inlining(cfg.inline_functions); // Create the function library runtime. std::unique_ptr<FunctionLibraryRuntime> flib(NewFunctionLibraryRuntime( dvc_mgr.get(), env, devices[0], inlined_graph_def.versions().producer(), &function_library, *optimizer_opts)); // Create the GraphOptimizer to optimize the graph def. GraphConstructorOptions graph_ctor_opts; graph_ctor_opts.allow_internal_ops = true; graph_ctor_opts.expect_device_spec = false; std::unique_ptr<Graph> graphptr(new Graph(function_library)); // Populate default attrs to the NodeDefs in the GraphDef. TF_RETURN_IF_ERROR(AddDefaultAttrsToGraphDef(&inlined_graph_def, *graphptr->op_registry(), 0)); TF_RETURN_IF_ERROR(ConvertGraphDefToGraph(graph_ctor_opts, inlined_graph_def, graphptr.get())); // Optimize the graph. GraphOptimizer optimizer(*optimizer_opts); optimizer.Optimize(flib.get(), env, devices[0], &graphptr, /*shape_map=*/nullptr); graphptr->ToGraphDef(output_graph_def); return Status::OK(); } } // namespace // static std::unique_ptr<GrapplerItem> GrapplerItemFromMetaGraphDef( const string& id, const MetaGraphDef& meta_graph, const ItemConfig& cfg) { if (id.empty()) { LOG(ERROR) << "id must be non-empty."; return nullptr; } std::unique_ptr<GrapplerItem> new_item(new GrapplerItem()); new_item->id = id; new_item->graph = meta_graph.graph_def(); // Attempt to detect the fetch node(s). if (meta_graph.collection_def().count("train_op") > 0) { const CollectionDef& nodes = meta_graph.collection_def().at("train_op"); if (nodes.has_node_list()) { for (const auto& node : nodes.node_list().value()) { const string name = NodeName(node); if (name.empty()) { LOG(ERROR) << "Invalid fetch node name " << node << ", skipping this input"; return nullptr; } LOG(INFO) << "Will use fetch node " << name; new_item->fetch.push_back(name); } } } if (new_item->fetch.empty()) { LOG(ERROR) << "Failed to detect the fetch node(s), skipping this input"; return nullptr; } for (auto& node : *new_item->graph.mutable_node()) { if (IsPlaceholder(node)) { if (node.attr().count("dtype") == 0) { LOG(ERROR) << "Unknown type for placeholder " << node.name() << ", skipping this input"; return nullptr; } DataType type = node.attr().at("dtype").type(); if (node.attr().count("shape") == 0) { LOG(INFO) << "Unknown shape for placeholder " << node.name() << ", skipping this input"; return nullptr; } // Replace all unknown dimensions in the placeholder's tensorshape proto // with cfg.placeholder_unknown_output_shape_dim and create a tensorshape // from it. We do this because in newer protos, the input placeholder // shape is not empty if the shape is partially defined. TensorShape shape; TensorShapeProto shape_proto; std::vector<int32> dims; for (const auto& dim_proto : node.attr().at("shape").shape().dim()) { if (cfg.placeholder_unknown_output_shape_dim >= 0 && dim_proto.size() == -1) { dims.push_back(cfg.placeholder_unknown_output_shape_dim); shape_proto.add_dim()->set_size( cfg.placeholder_unknown_output_shape_dim); } else { dims.push_back(std::max<int32>(1, dim_proto.size())); shape_proto.add_dim()->set_size(dim_proto.size()); } } Status make_shape_status = TensorShapeUtils::MakeShape(dims.data(), dims.size(), &shape); if (!make_shape_status.ok()) { LOG(ERROR) << "Invalid shape for placeholder " << node.name() << ": " << make_shape_status << ", skipping this input"; return nullptr; } // Some placeholder nodes have a mis-match between the node // attribute "shape" and a different node attribute "_output_shapes". // Specifically, a shape with shape.dims() == 0 could indicate either // a scalar or an unknown shape. In those cases, we check _output_shapes // for additional information. // This case is observed in the bnmt graphs. Have not observed any // cases where there was more than 1 _output_shapes, so limit it // to cases where there is only 1 _output_shapes. // We only do this if cfg.placeholder_unknown_output_shape_dim has // been set to avoid crashing non-BNMT graphs. if ((cfg.placeholder_unknown_output_shape_dim >= 0) && (shape.dims() == 0) && (node.attr().count("_output_shapes") == 1) && (node.attr().at("_output_shapes").list().shape(0).dim_size() != 0)) { shape.Clear(); shape_proto.clear_dim(); for (int dim_i = 0; dim_i < node.attr().at("_output_shapes").list().shape(0).dim_size(); dim_i++) { const ::tensorflow::TensorShapeProto_Dim dim = node.attr().at("_output_shapes").list().shape(0).dim(dim_i); if (dim.size() == -1) { shape.AddDim(cfg.placeholder_unknown_output_shape_dim); shape_proto.add_dim()->set_size( cfg.placeholder_unknown_output_shape_dim); } else { int size = node.attr() .at("_output_shapes") .list() .shape(0) .dim(dim_i) .size(); shape.AddDim(size); shape_proto.add_dim()->set_size(size); } } } Tensor fake_input(type, shape); InitializeTensor(type, &fake_input); new_item->feed.emplace_back(node.name(), fake_input); // Set the shape of the node in the graph. This is needed for statically // inferring shapes and is a no-op when dynamically inferring shapes as // the Placeholder shape will match the shape passed from new_item->feed. *(node.mutable_attr()->at("shape").mutable_shape()) = shape_proto; } // Erase the recorded result of any previous shape inference to start again // from scratch. node.mutable_attr()->erase("_output_shapes"); // Delete user specified placement if requested. if (cfg.ignore_user_placement) { node.clear_device(); } // Delete colocation constraints if requested. if (cfg.ignore_colocation) { auto attr = node.mutable_attr(); auto it = attr->find("_class"); if (it != attr->end()) { attr->erase(it); } } } for (const string& var_collection : {"variables", "local_variables", "model_variables", "trainable_variables"}) { if (meta_graph.collection_def().count(var_collection) == 0) { continue; } const CollectionDef& vars = meta_graph.collection_def().at(var_collection); for (const auto& raw_var : vars.bytes_list().value()) { VariableDef var; var.ParseFromString(raw_var); if (!var.initializer_name().empty()) { new_item->init_ops.push_back(var.initializer_name()); } } } if (meta_graph.collection_def().count("table_initializer") > 0) { const CollectionDef& inits = meta_graph.collection_def().at("table_initializer"); if (inits.has_node_list()) { for (const auto& node : inits.node_list().value()) { new_item->init_ops.push_back(node); // Tables are initialized from files, which can take a long time. Add 30 // minutes to the initialization time for each table to avoid timing // out. // TODO(bsteiner): adjust the timeout based on the file size. new_item->expected_init_time += 30 * 60; } } } if (meta_graph.collection_def().count("queue_runners") > 0) { const CollectionDef& vars = meta_graph.collection_def().at("queue_runners"); for (const auto& raw : vars.bytes_list().value()) { QueueRunnerDef queue_runner; if (!queue_runner.ParseFromString(raw)) { LOG(ERROR) << "Could parse queue_runners, skipping this input"; return nullptr; } if (queue_runner.cancel_op_name().empty()) { LOG(ERROR) << "Queue without a cancel op, skipping this input"; return nullptr; } new_item->queue_runners.push_back(queue_runner); } } // Make sure we still can access the input files (aka "asset_filepaths") since // these might have been moved or deleted, the cns cell might have been shut // down, or we might be running as a user who does not have access to the // files. if (meta_graph.collection_def().count("asset_filepaths") > 0) { const CollectionDef& file_paths = meta_graph.collection_def().at("asset_filepaths"); std::vector<string> paths; for (const auto& raw_path : file_paths.bytes_list().value()) { paths.push_back(raw_path); } if (!FilesExist(paths, nullptr)) { LOG(ERROR) << "Can't access one or more of the asset files, skipping this input"; return nullptr; } } // Optimize the graph (function inlining, l1 optimizations, etc). Status optimize_status = OptimizeGraph(new_item->graph, &new_item->graph, cfg); if (!optimize_status.ok()) { LOG(ERROR) << "Graph preprocessing failed: " << optimize_status; return nullptr; } // Validate feed, fetch and init nodes std::unordered_set<string> nodes; for (const auto& node : new_item->graph.node()) { nodes.insert(node.name()); } for (const auto& feed : new_item->feed) { if (nodes.find(feed.first) == nodes.end()) { LOG(ERROR) << "Feed node " << feed.first << " doesn't exist in graph"; return nullptr; } } for (const auto& fetch : new_item->fetch) { if (nodes.find(fetch) == nodes.end()) { LOG(ERROR) << "Fetch node " << fetch << " doesn't exist in graph"; return nullptr; } } for (const auto& init : new_item->init_ops) { if (nodes.find(init) == nodes.end()) { LOG(ERROR) << "Init node " << init << " doesn't exist in graph"; return nullptr; } } return new_item; } } // end namespace grappler } // end namespace tensorflow <|endoftext|>
<commit_before> template<unsigned DIM> inline CollisionPair<DIM>::CollisionPair(MetaKugel<DIM>& kugel1, MetaKugel<DIM>& kugel2) : p_kugel1 { &kugel1 }, p_kugel2 { &kugel2 }, dtime { }, collision { } { } template<unsigned DIM> inline CollisionPair<DIM>::CollisionPair(MetaKugel<DIM>& kugel1, MetaKugel<DIM>& kugel2, time_type dtime, bool collision) : p_kugel1 { &kugel1 }, p_kugel2 { &kugel2 }, dtime { dtime }, collision { collision } { } template<unsigned DIM> inline CollisionPair<DIM>&CollisionPair<DIM>::operator =( CollisionPair<DIM> other) { swap(*this, other); return *this; } template<unsigned DIM> inline CollisionPair<DIM>&CollisionPair<DIM>::operator <=( const CollisionPair<DIM>& other) { if (other < *this) return operator =(other); return *this; } template<unsigned DIM> inline void CollisionPair<DIM>::set_collision(const time_type& dt, bool b) { dtime = dt; collision = b; } template<unsigned DIM> inline bool CollisionPair<DIM>::operator <(const CollisionPair<DIM>& other) const { if (collision != other.collision) return !other.collision; return dtime < other.dtime; } template<unsigned DIM> inline bool CollisionPair<DIM>::operator >(const CollisionPair<DIM>& other) const { return other < *this; } template<unsigned DIM> inline bool CollisionPair<DIM>::equal(const CollisionPair<DIM>& other) const { return (collision == other.collision && dtime == other.dtime && p_kugel1 == other.p_kugel1 && p_kugel2 == other.p_kugel2); } <commit_msg>kleine Formatierung<commit_after> template<unsigned DIM> inline CollisionPair<DIM>::CollisionPair(MetaKugel<DIM>& kugel1, MetaKugel<DIM>& kugel2) : p_kugel1 { &kugel1 }, p_kugel2 { &kugel2 }, dtime { }, collision { } { } template<unsigned DIM> inline CollisionPair<DIM>::CollisionPair(MetaKugel<DIM>& kugel1, MetaKugel<DIM>& kugel2, time_type dtime, bool collision) : p_kugel1 { &kugel1 }, p_kugel2 { &kugel2 }, dtime { dtime }, collision { collision } { } template<unsigned DIM> inline CollisionPair<DIM>& CollisionPair<DIM>::operator =( CollisionPair<DIM> other) { swap(*this, other); return *this; } template<unsigned DIM> inline CollisionPair<DIM>& CollisionPair<DIM>::operator <=( const CollisionPair<DIM>& other) { if (other < *this) return operator =(other); return *this; } template<unsigned DIM> inline void CollisionPair<DIM>::set_collision(const time_type& dt, bool b) { dtime = dt; collision = b; } template<unsigned DIM> inline bool CollisionPair<DIM>::operator <(const CollisionPair<DIM>& other) const { if (collision != other.collision) return !other.collision; return dtime < other.dtime; } template<unsigned DIM> inline bool CollisionPair<DIM>::operator >(const CollisionPair<DIM>& other) const { return other < *this; } template<unsigned DIM> inline bool CollisionPair<DIM>::equal(const CollisionPair<DIM>& other) const { return (collision == other.collision && dtime == other.dtime && p_kugel1 == other.p_kugel1 && p_kugel2 == other.p_kugel2); } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX71M イグナイター・コマンド解析、応答 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/string_utils.hpp" #include "common/fixed_fifo.hpp" #include "main.hpp" #include "wdmc.hpp" namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コマンド解析、応答 @param[in] TELNTES TELNET サーバー型 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class TELNETS> class ign_cmd { static const uint32_t VERSION = 20; TELNETS& telnets_; utils::wdmc& wdmc_; uint32_t pos_; char line_[256]; char crm_ans_[16]; uint32_t crm_ans_pos_; uint32_t delay_; uint32_t cap_req_; uint16_t wave_buff_[2048]; uint32_t send_idx_; char wdm_buff_[8192]; enum class task { idle, wait, send, }; task task_; void filter9_(char* buf) { uint32_t len = strlen(buf); for(uint32_t i = len; i < 9; ++i) { buf[i] = 0x20; } buf[9] = 0; } void analize_() { auto n = str::get_words(line_); if(n >= 1) { char cmd[128]; if(!str::get_word(line_, 0, cmd, sizeof(cmd))) { return; } char para[64]; char para9[64]; para[0] = 0; if(n >= 2 && str::get_word(line_, 1, para, sizeof(para))) { strcpy(para9, para); filter9_(para9); // utils::format("%s: '%s'\n") % cmd % para; para9[9] = '\n'; para9[10] = 0; } if(strcmp(cmd, "help") == 0) { utils::format("Ignitor command shell Version %d.%02d\n") % (VERSION / 100) % (VERSION % 100); utils::format(" help\n"); utils::format(" delay [n]\n"); utils::format(" crm ...\n"); utils::format(" wdm ...\n"); utils::format(" dc2 ...\n"); utils::format(" dc1 ...\n"); utils::format(" wgm ...\n"); utils::format(" icm ...\n"); } else if(strcmp(cmd, "delay") == 0) { delay_ = 0; utils::input("%d", para) % delay_; if(delay_ > 10) delay_ = 10; } else if(strcmp(cmd, "crm") == 0) { crm_out(para9); } else if(strcmp(cmd, "wdm") == 0) { uint32_t cmd = 0; utils::input("%x", para) % cmd; wdm_out(cmd); if((cmd >> 19) == 0b00100) { cap_req_ = (cmd >> 14) & 3; // channel 0 to 3 task_ = task::wait; } } else if(strcmp(cmd, "dc2") == 0) { dc2_out(para9); } else if(strcmp(cmd, "dc1") == 0) { dc1_out(para9); } else if(strcmp(cmd, "wgm") == 0) { wgm_out(para9); } else if(strcmp(cmd, "icm") == 0) { icm_out(para9); } else { utils::format("Command error: '%s'\n") % cmd; } } // utils::format("recv command: '%s'\n") % line_; } void wdm_capture_(uint32_t ch, int ofs) { for(int i = 0; i < 1024; ++i) { wave_buff_[i] = wdmc_.get_wave(ch + 1, i + ofs); } } void wdm_send_ch_() { char tmp[16]; utils::sformat("WDCH%d\n", tmp, sizeof(tmp)) % cap_req_; telnets_.puts(tmp); } void wdm_send_(uint32_t num) { memcpy(wdm_buff_, "WDMW", 4); uint32_t idx = 4; for(uint32_t i = 0; i < num; ++i) { char tmp[8]; utils::sformat("%04X", tmp, sizeof(tmp)) % wave_buff_[send_idx_ & 2047]; ++send_idx_; memcpy(&wdm_buff_[idx], tmp, 4); idx += 4; if(idx >= (sizeof(wdm_buff_) - 4)) { wdm_buff_[idx] = '\n'; wdm_buff_[idx + 1] = 0; telnets_.puts(wdm_buff_); idx = 0; } } if(idx > 0) { wdm_buff_[idx] = '\n'; wdm_buff_[idx + 1] = 0; telnets_.puts(wdm_buff_); } } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] telnets TELNETサーバー・インスタンス */ //-----------------------------------------------------------------// ign_cmd(TELNETS& telnets, utils::wdmc& wdmc) : telnets_(telnets), wdmc_(wdmc), pos_(0), line_{ 0 }, crm_ans_{ 0, }, crm_ans_pos_(0), delay_(0), cap_req_(0), task_(task::idle) { } //-----------------------------------------------------------------// /*! @brief サービス */ //-----------------------------------------------------------------// void service() { switch(task_) { case task::idle: break; case task::wait: if(wdmc_.get_status() & 0b010) { // end record int ofs = 0; wdm_capture_(cap_req_, ofs); wdmc_.output((0b00100000 << 16) | (cap_req_ << 14)); // trg off wdm_send_ch_(); send_idx_ = 0; task_ = task::send; } break; case task::send: if(send_idx_ < 2048) { wdm_send_(512); } else { task_ = task::idle; } break; default: break; } { while(crm_len() > 0) { char ch = crm_inp(); crm_ans_[crm_ans_pos_] = ch; ++crm_ans_pos_; if(crm_ans_pos_ >= sizeof(crm_ans_)) { crm_ans_pos_ = 0; break; } if(ch == '\n') { crm_ans_[crm_ans_pos_] = 0; telnets_.puts(crm_ans_); utils::format("CRM ANS: %s") % crm_ans_; crm_ans_pos_ = 0; } } } // 遅延タイマー if(delay_ > 0) { --delay_; return; } if(!telnets_.probe()) return; auto len = telnets_.length(); if(len == 0) return; while(len > 0) { char ch = telnets_.getch(); --len; if(ch == '\r') continue; else if(ch == '\n') { // LF code ch = 0; } line_[pos_] = ch; ++pos_; if(ch == 0 || pos_ >= (sizeof(line_) - 1)) { analize_(); pos_ = 0; line_[pos_] = 0; if(delay_ > 0) break; } } } }; } <commit_msg>update: wave send manage (send all channel)<commit_after>#pragma once //=====================================================================// /*! @file @brief RX71M イグナイター・コマンド解析、応答 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/string_utils.hpp" #include "common/fixed_fifo.hpp" #include "main.hpp" #include "wdmc.hpp" namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コマンド解析、応答 @param[in] TELNTES TELNET サーバー型 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class TELNETS> class ign_cmd { static const uint32_t VERSION = 20; TELNETS& telnets_; utils::wdmc& wdmc_; uint32_t pos_; char line_[256]; char crm_ans_[16]; uint32_t crm_ans_pos_; uint32_t delay_; uint16_t wave_buff_[2048 * 4]; uint32_t send_idx_; uint32_t send_ch_; char wdm_buff_[8192]; enum class task { idle, wait, send, }; task task_; void filter9_(char* buf) { uint32_t len = strlen(buf); for(uint32_t i = len; i < 9; ++i) { buf[i] = 0x20; } buf[9] = 0; } void analize_() { auto n = str::get_words(line_); if(n >= 1) { char cmd[128]; if(!str::get_word(line_, 0, cmd, sizeof(cmd))) { return; } char para[64]; char para9[64]; para[0] = 0; if(n >= 2 && str::get_word(line_, 1, para, sizeof(para))) { strcpy(para9, para); filter9_(para9); // utils::format("%s: '%s'\n") % cmd % para; para9[9] = '\n'; para9[10] = 0; } if(strcmp(cmd, "help") == 0) { utils::format("Ignitor command shell Version %d.%02d\n") % (VERSION / 100) % (VERSION % 100); utils::format(" help\n"); utils::format(" delay [n]\n"); utils::format(" crm ...\n"); utils::format(" wdm ...\n"); utils::format(" dc2 ...\n"); utils::format(" dc1 ...\n"); utils::format(" wgm ...\n"); utils::format(" icm ...\n"); } else if(strcmp(cmd, "delay") == 0) { delay_ = 0; utils::input("%d", para) % delay_; if(delay_ > 10) delay_ = 10; } else if(strcmp(cmd, "crm") == 0) { crm_out(para9); } else if(strcmp(cmd, "wdm") == 0) { uint32_t cmd = 0; utils::input("%x", para) % cmd; wdm_out(cmd); if((cmd >> 19) == 0b00100) { // start wait task_ = task::wait; } } else if(strcmp(cmd, "dc2") == 0) { dc2_out(para9); } else if(strcmp(cmd, "dc1") == 0) { dc1_out(para9); } else if(strcmp(cmd, "wgm") == 0) { wgm_out(para9); } else if(strcmp(cmd, "icm") == 0) { icm_out(para9); } else { utils::format("Command error: '%s'\n") % cmd; } } // utils::format("recv command: '%s'\n") % line_; } void wdm_capture_(uint32_t ch, int ofs) { wdmc_.set_wave_pos(ch + 1, ofs); for(int i = 0; i < 2048; ++i) { wave_buff_[ch * 2048 + i] = wdmc_.get_wave(ch + 1); } } void wdm_send_ch_(uint32_t ch) { char tmp[16]; utils::sformat("WDCH%d\n", tmp, sizeof(tmp)) % ch; telnets_.puts(tmp); } void wdm_send_(uint32_t ch, uint32_t num) { memcpy(wdm_buff_, "WDMW", 4); const uint16_t* src = &wave_buff_[ch * 2048]; uint32_t idx = 4; for(uint32_t i = 0; i < num; ++i) { char tmp[8]; utils::sformat("%04X", tmp, sizeof(tmp)) % src[send_idx_ & 2047]; ++send_idx_; memcpy(&wdm_buff_[idx], tmp, 4); idx += 4; if(idx >= (sizeof(wdm_buff_) - 4)) { wdm_buff_[idx] = '\n'; wdm_buff_[idx + 1] = 0; telnets_.puts(wdm_buff_); idx = 0; } } if(idx > 0) { wdm_buff_[idx] = '\n'; wdm_buff_[idx + 1] = 0; telnets_.puts(wdm_buff_); } } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] telnets TELNETサーバー・インスタンス */ //-----------------------------------------------------------------// ign_cmd(TELNETS& telnets, utils::wdmc& wdmc) : telnets_(telnets), wdmc_(wdmc), pos_(0), line_{ 0 }, crm_ans_{ 0, }, crm_ans_pos_(0), delay_(0), send_idx_(0), send_ch_(0), task_(task::idle) { } //-----------------------------------------------------------------// /*! @brief サービス */ //-----------------------------------------------------------------// void service() { switch(task_) { case task::idle: break; case task::wait: if(wdmc_.get_status() & 0b010) { // end record int ofs = -1024; wdm_capture_(0, ofs); wdm_capture_(1, ofs); wdm_capture_(2, ofs); wdm_capture_(3, ofs); wdmc_.output(0b00100000 << 16); // trg off send_ch_ = 0; wdm_send_ch_(send_ch_); send_idx_ = 0; task_ = task::send; } break; case task::send: if(send_idx_ < 2048) { wdm_send_(send_ch_, 512); } else { ++send_ch_; if(send_ch_ < 4) { wdm_send_ch_(send_ch_); send_idx_ = 0; task_ = task::send; } else { task_ = task::idle; } } break; default: break; } { while(crm_len() > 0) { char ch = crm_inp(); crm_ans_[crm_ans_pos_] = ch; ++crm_ans_pos_; if(crm_ans_pos_ >= sizeof(crm_ans_)) { crm_ans_pos_ = 0; break; } if(ch == '\n') { crm_ans_[crm_ans_pos_] = 0; telnets_.puts(crm_ans_); utils::format("CRM ANS: %s") % crm_ans_; crm_ans_pos_ = 0; } } } // 遅延タイマー if(delay_ > 0) { --delay_; return; } if(!telnets_.probe()) return; auto len = telnets_.length(); if(len == 0) return; while(len > 0) { char ch = telnets_.getch(); --len; if(ch == '\r') continue; else if(ch == '\n') { // LF code ch = 0; } line_[pos_] = ch; ++pos_; if(ch == 0 || pos_ >= (sizeof(line_) - 1)) { analize_(); pos_ = 0; line_[pos_] = 0; if(delay_ > 0) break; } } } }; } <|endoftext|>
<commit_before>// App.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "App.h" #include <debug.h> #include <file.h> #include <config.h> #include <graphics.h> #include <input.h> #include <sound.h> #include <array> using namespace yappy; class MyApp : public graphics::Application { public: MyApp(const InitParam &param) : Application(param), m_input(param.hInstance, getHWnd()), m_sound() {} protected: void init() override; void update() override; void render() override; private: input::DInput m_input; sound::XAudio2 m_sound; uint64_t m_frameCount = 0; }; void MyApp::init() { loadTexture("notpow2", L"../sampledata/test_400_300.png"); loadTexture("testtex", L"../sampledata/circle.png"); m_sound.loadSoundEffect("testwav", L"/C:/Windows/Media/chimes.wav"); m_sound.playBgm(L"../sampledata/Epoq-Lepidoptera.ogg"); } void MyApp::render() { int test = static_cast<int>(m_frameCount * 5 % 768); drawTexture("testtex", test, test); } void MyApp::update() { m_input.processFrame(); m_sound.processFrame(); m_frameCount++; std::array<bool, 256> keys = m_input.getKeys(); for (size_t i = 0U; i < keys.size(); i++) { if (keys[i]) { debug::writef(L"Key 0x%02x", i); m_sound.playSoundEffect("testwav"); } } for (int i = 0; i < m_input.getPadCount(); i++) { DIJOYSTATE state; m_input.getPadState(&state, i); for (int b = 0; b < 32; b++) { if (state.rgbButtons[b] & 0x80) { debug::writef(L"pad[%d].button%d", i, b); m_sound.playSoundEffect("testwav"); } } { // left stick if (std::abs(state.lX) > input::DInput::AXIS_THRESHOLD) { debug::writef(L"pad[%d].x=%ld", i, state.lX); } if (std::abs(state.lY) > input::DInput::AXIS_THRESHOLD) { debug::writef(L"pad[%d].y=%ld", i, state.lY); } // right stick if (std::abs(state.lZ) > input::DInput::AXIS_THRESHOLD) { debug::writef(L"pad[%d].z=%ld", i, state.lZ); } if (std::abs(state.lRz) > input::DInput::AXIS_THRESHOLD) { debug::writef(L"pad[%d].rz=%ld", i, state.lRz); } } for (int b = 0; b < 4; b++) { if (state.rgdwPOV[b] != -1) { debug::writef(L"pad[%d].POV%d=%u", i, b, state.rgdwPOV[b]); } } } } int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // debug test { debug::enableDebugOutput(); debug::enableConsoleOutput(); debug::enableFileOutput(L"log.txt"); debug::writeLine(L"Start application"); debug::writeLine(L"にほんご"); debug::writef(L"%d 0x%08x %f %.8f", 123, 0x1234abcd, 3.14, 3.14); const wchar_t *digit = L"0123456789abcdef"; wchar_t large[1024 + 32] = { 0 }; for (int i = 0; i < 1024; i++) { large[i] = digit[i & 0xf]; } debug::writef(large); wchar_t dir[MAX_PATH]; ::GetCurrentDirectory(MAX_PATH, dir); debug::writef(L"Current dir: %s", dir); } int result = 0; try { config::ConfigFile config(L"config.txt", { { "graphics.skip", "0" }, { "graphics.cursor", "true" }, { "graphics.fullscreen", "false" } }); file::initWithFileSystem(L"."); graphics::Application::InitParam param; param.hInstance = hInstance; param.w = 1024; param.h = 768; param.wndClsName = L"TestAppClass"; param.title = L"Test App"; param.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP)); param.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SMALL)); param.nCmdShow = nCmdShow; param.showCursor = config.getBool("graphics.cursor"); param.fullScreen = config.getBool("graphics.fullscreen"); MyApp app(param); result = app.run(); } catch (const std::exception &ex) { debug::writef(L"Error: %s", util::utf82wc(ex.what())); } debug::shutdownDebugOutput(); return result; } <commit_msg>Frame skip setting from config file<commit_after>// App.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "App.h" #include <debug.h> #include <file.h> #include <config.h> #include <graphics.h> #include <input.h> #include <sound.h> #include <array> using namespace yappy; class MyApp : public graphics::Application { public: MyApp(const InitParam &param) : Application(param), m_input(param.hInstance, getHWnd()), m_sound() {} protected: void init() override; void update() override; void render() override; private: input::DInput m_input; sound::XAudio2 m_sound; uint64_t m_frameCount = 0; }; void MyApp::init() { loadTexture("notpow2", L"../sampledata/test_400_300.png"); loadTexture("testtex", L"../sampledata/circle.png"); m_sound.loadSoundEffect("testwav", L"/C:/Windows/Media/chimes.wav"); m_sound.playBgm(L"../sampledata/Epoq-Lepidoptera.ogg"); } void MyApp::render() { int test = static_cast<int>(m_frameCount * 5 % 768); drawTexture("testtex", test, test); } void MyApp::update() { m_input.processFrame(); m_sound.processFrame(); m_frameCount++; std::array<bool, 256> keys = m_input.getKeys(); for (size_t i = 0U; i < keys.size(); i++) { if (keys[i]) { debug::writef(L"Key 0x%02x", i); m_sound.playSoundEffect("testwav"); } } for (int i = 0; i < m_input.getPadCount(); i++) { DIJOYSTATE state; m_input.getPadState(&state, i); for (int b = 0; b < 32; b++) { if (state.rgbButtons[b] & 0x80) { debug::writef(L"pad[%d].button%d", i, b); m_sound.playSoundEffect("testwav"); } } { // left stick if (std::abs(state.lX) > input::DInput::AXIS_THRESHOLD) { debug::writef(L"pad[%d].x=%ld", i, state.lX); } if (std::abs(state.lY) > input::DInput::AXIS_THRESHOLD) { debug::writef(L"pad[%d].y=%ld", i, state.lY); } // right stick if (std::abs(state.lZ) > input::DInput::AXIS_THRESHOLD) { debug::writef(L"pad[%d].z=%ld", i, state.lZ); } if (std::abs(state.lRz) > input::DInput::AXIS_THRESHOLD) { debug::writef(L"pad[%d].rz=%ld", i, state.lRz); } } for (int b = 0; b < 4; b++) { if (state.rgdwPOV[b] != -1) { debug::writef(L"pad[%d].POV%d=%u", i, b, state.rgdwPOV[b]); } } } } int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // debug test { debug::enableDebugOutput(); debug::enableConsoleOutput(); debug::enableFileOutput(L"log.txt"); debug::writeLine(L"Start application"); debug::writeLine(L"にほんご"); debug::writef(L"%d 0x%08x %f %.8f", 123, 0x1234abcd, 3.14, 3.14); const wchar_t *digit = L"0123456789abcdef"; wchar_t large[1024 + 32] = { 0 }; for (int i = 0; i < 1024; i++) { large[i] = digit[i & 0xf]; } debug::writef(large); wchar_t dir[MAX_PATH]; ::GetCurrentDirectory(MAX_PATH, dir); debug::writef(L"Current dir: %s", dir); } int result = 0; try { struct { int skip; bool cursor; bool fullscreen; } config; { config::ConfigFile cf(L"config.txt", { { "graphics.skip", "0" }, { "graphics.cursor", "true" }, { "graphics.fullscreen", "false" } }); config.skip = cf.getInt("graphics.skip"); config.cursor = cf.getBool("graphics.cursor"); config.fullscreen = cf.getBool("graphics.fullscreen"); } file::initWithFileSystem(L"."); graphics::Application::InitParam param; param.hInstance = hInstance; param.w = 1024; param.h = 768; param.wndClsName = L"TestAppClass"; param.title = L"Test App"; param.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP)); param.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SMALL)); param.nCmdShow = nCmdShow; param.frameSkip = config.skip; param.showCursor = config.cursor; param.fullScreen = config.fullscreen; MyApp app(param); result = app.run(); } catch (const std::exception &ex) { debug::writef(L"Error: %s", util::utf82wc(ex.what())); } debug::shutdownDebugOutput(); return result; } <|endoftext|>
<commit_before>/* Its is under the MIT license, to encourage reuse by cut-and-paste. The original files are hosted here: https://github.com/sago007/PlatformFolders Copyright (c) 2015-2016 Poul Sander 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 "platform_folders.h" #include <iostream> #include <stdexcept> #include <string.h> #include <stdio.h> #include <cstdlib> #if defined(_WIN32) #include <windows.h> #include <shlobj.h> #define strtok_r strtok_s static std::string win32_utf16_to_utf8(const wchar_t* wstr) { std::string res; // If the 6th parameter is 0 then WideCharToMultiByte returns the number of bytes needed to store the result. int actualSize = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL); if (actualSize > 0) { //If the converted UTF-8 string could not be in the initial buffer. Allocate one that can hold it. std::vector<char> buffer(actualSize); actualSize = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &buffer[0], buffer.size(), NULL, NULL); res = buffer.data(); } if (actualSize == 0) { // WideCharToMultiByte return 0 for errors. std::string errorMsg = "UTF16 to UTF8 failed with error code: " + GetLastError(); throw std::runtime_error(errorMsg.c_str()); } return res; } static std::string GetWindowsFolder(int folderId, const char* errorMsg) { wchar_t szPath[MAX_PATH]; szPath[0] = 0; if ( !SUCCEEDED( SHGetFolderPathW( NULL, folderId, NULL, 0, szPath ) ) ) { throw std::runtime_error(errorMsg); } return win32_utf16_to_utf8(szPath); } static std::string GetAppData() { return GetWindowsFolder(CSIDL_APPDATA, "RoamingAppData could not be found"); } static std::string GetAppDataCommon() { return GetWindowsFolder(CSIDL_COMMON_APPDATA, "Common appdata could not be found"); } static std::string GetAppDataLocal() { return GetWindowsFolder(CSIDL_LOCAL_APPDATA, "LocalAppData could not be found"); } #elif defined(__APPLE__) #include <CoreServices/CoreServices.h> static std::string GetMacFolder(OSType folderType, const char* errorMsg) { std::string ret; FSRef ref; char path[PATH_MAX]; OSStatus err = FSFindFolder( kUserDomain, folderType, kCreateFolder, &ref ); if (err != noErr) { throw std::runtime_error(errorMsg); } FSRefMakePath( &ref, (UInt8*)&path, PATH_MAX ); ret = path; return ret; } #else #include <map> #include <fstream> #include <pwd.h> #include <unistd.h> #include <sys/types.h> //Typically Linux. For easy reading the comments will just say Linux but should work with most *nixes static void throwOnRelative(const char* envName, const char* envValue) { if (envValue[0] != '/') { char buffer[200]; snprintf(buffer, sizeof(buffer), "Environment \"%s\" does not start with an '/'. XDG specifies that the value must be absolute. The current value is: \"%s\"", envName, envValue); throw std::runtime_error(buffer); } } /** * Retrives the effective user's home dir. * If the user is running as root we ignore the HOME environment. It works badly with sudo. * Writing to $HOME as root implies security concerns that a multiplatform program cannot be assumed to handle. * @return The home directory. HOME environment is respected for non-root users if it exists. */ static std::string getHome() { std::string res; int uid = getuid(); const char* homeEnv = getenv("HOME"); if ( uid != 0 && homeEnv) { //We only acknowlegde HOME if not root. res = homeEnv; return res; } struct passwd *pw = getpwuid(uid); if (!pw) { throw std::runtime_error("Unable to get passwd struct."); } const char* tempRes = pw->pw_dir; if (!tempRes) { throw std::runtime_error("User has no home directory"); } res = tempRes; return res; } static std::string getLinuxFolderDefault(const char* envName, const char* defaultRelativePath) { std::string res; const char* tempRes = getenv(envName); if (tempRes) { throwOnRelative(envName, tempRes); res = tempRes; return res; } res = getHome() + "/" + defaultRelativePath; return res; } static void appendExtraFoldersTokenizer(const char* envName, const char* envValue, std::vector<std::string>& folders) { std::vector<char> buffer(envValue, envValue + strlen(envValue) + 1); char *saveptr; const char* p = strtok_r ( &buffer[0], ":", &saveptr); while (p != NULL) { if (p[0] == '/') { folders.push_back(p); } else { //Unless the system is wrongly configured this should never happen... But of course some systems will be incorectly configured. //The XDG documentation indicates that the folder should be ignored but that the program should continue. std::cerr << "Skipping path \"" << p << "\" in \"" << envName << "\" because it does not start with a \"/\"\n"; } p = strtok_r (NULL, ":", &saveptr); } } static void appendExtraFolders(const char* envName, const char* defaultValue, std::vector<std::string>& folders) { const char* envValue = getenv(envName); if (!envValue) { envValue = defaultValue; } appendExtraFoldersTokenizer(envName, envValue, folders); } #endif namespace sago { std::string getDataHome() { #if defined(_WIN32) return GetAppData(); #elif defined(__APPLE__) return GetMacFolder(kApplicationSupportFolderType, "Failed to find the Application Support Folder"); #else return getLinuxFolderDefault("XDG_DATA_HOME", ".local/share"); #endif } std::string getConfigHome() { #if defined(_WIN32) return GetAppData(); #elif defined(__APPLE__) return GetMacFolder(kApplicationSupportFolderType, "Failed to find the Application Support Folder"); #else return getLinuxFolderDefault("XDG_CONFIG_HOME", ".config"); #endif } std::string getCacheDir() { #if defined(_WIN32) return GetAppDataLocal(); #elif defined(__APPLE__) return GetMacFolder(kCachedDataFolderType, "Failed to find the Application Support Folder"); #else return getLinuxFolderDefault("XDG_CONFIG_HOME", ".cache"); #endif } void appendAdditionalDataDirectories(std::vector<std::string>& homes) { #if defined(_WIN32) homes.push_back(GetAppDataCommon()); #elif defined(__APPLE__) #else appendExtraFolders("XDG_DATA_DIRS", "/usr/local/share/:/usr/share/", homes); #endif } void appendAdditionalConfigDirectories(std::vector<std::string>& homes) { #if defined(_WIN32) homes.push_back(GetAppDataCommon()); #elif defined(__APPLE__) #else appendExtraFolders("XDG_CONFIG_DIRS", "/etc/xdg", homes); #endif } #if defined(_WIN32) #elif defined(__APPLE__) #else struct PlatformFolders::PlatformFoldersData { std::map<std::string, std::string> folders; }; static void PlatformFoldersAddFromFile(const std::string& filename, std::map<std::string, std::string>& folders) { std::ifstream infile(filename.c_str()); std::string line; while (std::getline(infile, line)) { if (line.length() == 0 || line.at(0) == '#') { continue; } std::size_t splitPos = line.find("="); std::string key = line.substr(0, splitPos); std::string value = line.substr(splitPos+2, line.length()-splitPos-3); folders[key] = value; //std::cout << key << " : " << value << "\n"; } } static void PlatformFoldersFillData(std::map<std::string, std::string>& folders) { folders["XDG_DOCUMENTS_DIR"] = "$HOME/Documents"; folders["XDG_DESKTOP_DIR"] = "$HOME/Desktop"; folders["XDG_DOWNLOAD_DIR"] = "$HOME/Downloads"; folders["XDG_MUSIC_DIR"] = "$HOME/Music"; folders["XDG_PICTURES_DIR"] = "$HOME/Pictures"; folders["XDG_PUBLICSHARE_DIR"] = "$HOME/Public"; folders["XDG_TEMPLATES_DIR"] = "$HOME/.Templates"; folders["XDG_VIDEOS_DIR"] = "$HOME/Videos"; PlatformFoldersAddFromFile( getConfigHome()+"/user-dirs.dirs", folders); for (std::map<std::string, std::string>::iterator itr = folders.begin() ; itr != folders.end() ; ++itr ) { std::string& value = itr->second; if (value.compare(0, 5, "$HOME") == 0) { value = getHome() + value.substr(5, std::string::npos); } } } #endif PlatformFolders::PlatformFolders() { #if defined(_WIN32) #elif defined(__APPLE__) #else this->data = new PlatformFolders::PlatformFoldersData(); try { PlatformFoldersFillData(data->folders); } catch (...) { delete this->data; throw; } #endif } PlatformFolders::~PlatformFolders() { #if defined(_WIN32) #elif defined(__APPLE__) #else delete this->data; #endif } std::string PlatformFolders::getDocumentsFolder() const { #if defined(_WIN32) return GetWindowsFolder(CSIDL_PERSONAL, "Failed to find My Documents folder"); #elif defined(__APPLE__) return GetMacFolder(kDocumentsFolderType, "Failed to find Documents Folder"); #else return data->folders["XDG_DOCUMENTS_DIR"]; #endif } std::string PlatformFolders::getDesktopFolder() const { #if defined(_WIN32) return GetWindowsFolder(CSIDL_DESKTOP, "Failed to find Desktop folder"); #elif defined(__APPLE__) return GetMacFolder(kDesktopFolderType, "Failed to find Desktop folder"); #else return data->folders["XDG_DESKTOP_DIR"]; #endif } std::string PlatformFolders::getPicturesFolder() const { #if defined(_WIN32) return GetWindowsFolder(CSIDL_MYPICTURES, "Failed to find My Pictures folder"); #elif defined(__APPLE__) return GetMacFolder(kPictureDocumentsFolderType, "Failed to find Picture folder"); #else return data->folders["XDG_PICTURES_DIR"]; #endif } std::string PlatformFolders::getDownloadFolder1() const { #if defined(_WIN32) //Pre Vista. Files was downloaded to the desktop return GetWindowsFolder(CSIDL_DESKTOP, "Failed to find My Downloads (Desktop) folder"); #elif defined(__APPLE__) return GetMacFolder(kDownloadsFolderType, "Failed to find Download folder"); #else return data->folders["XDG_DOWNLOAD_DIR"]; #endif } std::string PlatformFolders::getMusicFolder() const { #if defined(_WIN32) return GetWindowsFolder(CSIDL_MYMUSIC, "Failed to find My Music folder"); #elif defined(__APPLE__) return GetMacFolder(kMusicDocumentsFolderType, "Failed to find Music folder"); #else return data->folders["XDG_MUSIC_DIR"]; #endif } std::string PlatformFolders::getVideoFolder() const { #if defined(_WIN32) return GetWindowsFolder(CSIDL_MYVIDEO, "Failed to find My Video folder"); #elif defined(__APPLE__) return GetMacFolder(kMovieDocumentsFolderType, "Failed to find Movie folder"); #else return data->folders["XDG_VIDEOS_DIR"]; #endif } std::string PlatformFolders::getSaveGamesFolder1() const { #if defined(_WIN32) //A dedicated Save Games folder was not introduced until Vista. For XP and older save games are most often saved in a normal folder named "My Games". //Data that should not be user accessible should be placed under GetDataHome() instead return GetWindowsFolder(CSIDL_PERSONAL, "Failed to find My Documents folder")+"\\My Games"; #elif defined(__APPLE__) return GetMacFolder(kApplicationSupportFolderType, "Failed to find Application Support Folder"); #else return getDataHome(); #endif } } //namespace sago <commit_msg>Replace deprecated stdio.h cstdio brings the std snprintf, so switch to that as well<commit_after>/* Its is under the MIT license, to encourage reuse by cut-and-paste. The original files are hosted here: https://github.com/sago007/PlatformFolders Copyright (c) 2015-2016 Poul Sander 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 "platform_folders.h" #include <iostream> #include <stdexcept> #include <string.h> #include <cstdio> #include <cstdlib> #if defined(_WIN32) #include <windows.h> #include <shlobj.h> #define strtok_r strtok_s static std::string win32_utf16_to_utf8(const wchar_t* wstr) { std::string res; // If the 6th parameter is 0 then WideCharToMultiByte returns the number of bytes needed to store the result. int actualSize = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL); if (actualSize > 0) { //If the converted UTF-8 string could not be in the initial buffer. Allocate one that can hold it. std::vector<char> buffer(actualSize); actualSize = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &buffer[0], buffer.size(), NULL, NULL); res = buffer.data(); } if (actualSize == 0) { // WideCharToMultiByte return 0 for errors. std::string errorMsg = "UTF16 to UTF8 failed with error code: " + GetLastError(); throw std::runtime_error(errorMsg.c_str()); } return res; } static std::string GetWindowsFolder(int folderId, const char* errorMsg) { wchar_t szPath[MAX_PATH]; szPath[0] = 0; if ( !SUCCEEDED( SHGetFolderPathW( NULL, folderId, NULL, 0, szPath ) ) ) { throw std::runtime_error(errorMsg); } return win32_utf16_to_utf8(szPath); } static std::string GetAppData() { return GetWindowsFolder(CSIDL_APPDATA, "RoamingAppData could not be found"); } static std::string GetAppDataCommon() { return GetWindowsFolder(CSIDL_COMMON_APPDATA, "Common appdata could not be found"); } static std::string GetAppDataLocal() { return GetWindowsFolder(CSIDL_LOCAL_APPDATA, "LocalAppData could not be found"); } #elif defined(__APPLE__) #include <CoreServices/CoreServices.h> static std::string GetMacFolder(OSType folderType, const char* errorMsg) { std::string ret; FSRef ref; char path[PATH_MAX]; OSStatus err = FSFindFolder( kUserDomain, folderType, kCreateFolder, &ref ); if (err != noErr) { throw std::runtime_error(errorMsg); } FSRefMakePath( &ref, (UInt8*)&path, PATH_MAX ); ret = path; return ret; } #else #include <map> #include <fstream> #include <pwd.h> #include <unistd.h> #include <sys/types.h> //Typically Linux. For easy reading the comments will just say Linux but should work with most *nixes static void throwOnRelative(const char* envName, const char* envValue) { if (envValue[0] != '/') { char buffer[200]; std::snprintf(buffer, sizeof(buffer), "Environment \"%s\" does not start with an '/'. XDG specifies that the value must be absolute. The current value is: \"%s\"", envName, envValue); throw std::runtime_error(buffer); } } /** * Retrives the effective user's home dir. * If the user is running as root we ignore the HOME environment. It works badly with sudo. * Writing to $HOME as root implies security concerns that a multiplatform program cannot be assumed to handle. * @return The home directory. HOME environment is respected for non-root users if it exists. */ static std::string getHome() { std::string res; int uid = getuid(); const char* homeEnv = getenv("HOME"); if ( uid != 0 && homeEnv) { //We only acknowlegde HOME if not root. res = homeEnv; return res; } struct passwd *pw = getpwuid(uid); if (!pw) { throw std::runtime_error("Unable to get passwd struct."); } const char* tempRes = pw->pw_dir; if (!tempRes) { throw std::runtime_error("User has no home directory"); } res = tempRes; return res; } static std::string getLinuxFolderDefault(const char* envName, const char* defaultRelativePath) { std::string res; const char* tempRes = getenv(envName); if (tempRes) { throwOnRelative(envName, tempRes); res = tempRes; return res; } res = getHome() + "/" + defaultRelativePath; return res; } static void appendExtraFoldersTokenizer(const char* envName, const char* envValue, std::vector<std::string>& folders) { std::vector<char> buffer(envValue, envValue + strlen(envValue) + 1); char *saveptr; const char* p = strtok_r ( &buffer[0], ":", &saveptr); while (p != NULL) { if (p[0] == '/') { folders.push_back(p); } else { //Unless the system is wrongly configured this should never happen... But of course some systems will be incorectly configured. //The XDG documentation indicates that the folder should be ignored but that the program should continue. std::cerr << "Skipping path \"" << p << "\" in \"" << envName << "\" because it does not start with a \"/\"\n"; } p = strtok_r (NULL, ":", &saveptr); } } static void appendExtraFolders(const char* envName, const char* defaultValue, std::vector<std::string>& folders) { const char* envValue = getenv(envName); if (!envValue) { envValue = defaultValue; } appendExtraFoldersTokenizer(envName, envValue, folders); } #endif namespace sago { std::string getDataHome() { #if defined(_WIN32) return GetAppData(); #elif defined(__APPLE__) return GetMacFolder(kApplicationSupportFolderType, "Failed to find the Application Support Folder"); #else return getLinuxFolderDefault("XDG_DATA_HOME", ".local/share"); #endif } std::string getConfigHome() { #if defined(_WIN32) return GetAppData(); #elif defined(__APPLE__) return GetMacFolder(kApplicationSupportFolderType, "Failed to find the Application Support Folder"); #else return getLinuxFolderDefault("XDG_CONFIG_HOME", ".config"); #endif } std::string getCacheDir() { #if defined(_WIN32) return GetAppDataLocal(); #elif defined(__APPLE__) return GetMacFolder(kCachedDataFolderType, "Failed to find the Application Support Folder"); #else return getLinuxFolderDefault("XDG_CONFIG_HOME", ".cache"); #endif } void appendAdditionalDataDirectories(std::vector<std::string>& homes) { #if defined(_WIN32) homes.push_back(GetAppDataCommon()); #elif defined(__APPLE__) #else appendExtraFolders("XDG_DATA_DIRS", "/usr/local/share/:/usr/share/", homes); #endif } void appendAdditionalConfigDirectories(std::vector<std::string>& homes) { #if defined(_WIN32) homes.push_back(GetAppDataCommon()); #elif defined(__APPLE__) #else appendExtraFolders("XDG_CONFIG_DIRS", "/etc/xdg", homes); #endif } #if defined(_WIN32) #elif defined(__APPLE__) #else struct PlatformFolders::PlatformFoldersData { std::map<std::string, std::string> folders; }; static void PlatformFoldersAddFromFile(const std::string& filename, std::map<std::string, std::string>& folders) { std::ifstream infile(filename.c_str()); std::string line; while (std::getline(infile, line)) { if (line.length() == 0 || line.at(0) == '#') { continue; } std::size_t splitPos = line.find("="); std::string key = line.substr(0, splitPos); std::string value = line.substr(splitPos+2, line.length()-splitPos-3); folders[key] = value; //std::cout << key << " : " << value << "\n"; } } static void PlatformFoldersFillData(std::map<std::string, std::string>& folders) { folders["XDG_DOCUMENTS_DIR"] = "$HOME/Documents"; folders["XDG_DESKTOP_DIR"] = "$HOME/Desktop"; folders["XDG_DOWNLOAD_DIR"] = "$HOME/Downloads"; folders["XDG_MUSIC_DIR"] = "$HOME/Music"; folders["XDG_PICTURES_DIR"] = "$HOME/Pictures"; folders["XDG_PUBLICSHARE_DIR"] = "$HOME/Public"; folders["XDG_TEMPLATES_DIR"] = "$HOME/.Templates"; folders["XDG_VIDEOS_DIR"] = "$HOME/Videos"; PlatformFoldersAddFromFile( getConfigHome()+"/user-dirs.dirs", folders); for (std::map<std::string, std::string>::iterator itr = folders.begin() ; itr != folders.end() ; ++itr ) { std::string& value = itr->second; if (value.compare(0, 5, "$HOME") == 0) { value = getHome() + value.substr(5, std::string::npos); } } } #endif PlatformFolders::PlatformFolders() { #if defined(_WIN32) #elif defined(__APPLE__) #else this->data = new PlatformFolders::PlatformFoldersData(); try { PlatformFoldersFillData(data->folders); } catch (...) { delete this->data; throw; } #endif } PlatformFolders::~PlatformFolders() { #if defined(_WIN32) #elif defined(__APPLE__) #else delete this->data; #endif } std::string PlatformFolders::getDocumentsFolder() const { #if defined(_WIN32) return GetWindowsFolder(CSIDL_PERSONAL, "Failed to find My Documents folder"); #elif defined(__APPLE__) return GetMacFolder(kDocumentsFolderType, "Failed to find Documents Folder"); #else return data->folders["XDG_DOCUMENTS_DIR"]; #endif } std::string PlatformFolders::getDesktopFolder() const { #if defined(_WIN32) return GetWindowsFolder(CSIDL_DESKTOP, "Failed to find Desktop folder"); #elif defined(__APPLE__) return GetMacFolder(kDesktopFolderType, "Failed to find Desktop folder"); #else return data->folders["XDG_DESKTOP_DIR"]; #endif } std::string PlatformFolders::getPicturesFolder() const { #if defined(_WIN32) return GetWindowsFolder(CSIDL_MYPICTURES, "Failed to find My Pictures folder"); #elif defined(__APPLE__) return GetMacFolder(kPictureDocumentsFolderType, "Failed to find Picture folder"); #else return data->folders["XDG_PICTURES_DIR"]; #endif } std::string PlatformFolders::getDownloadFolder1() const { #if defined(_WIN32) //Pre Vista. Files was downloaded to the desktop return GetWindowsFolder(CSIDL_DESKTOP, "Failed to find My Downloads (Desktop) folder"); #elif defined(__APPLE__) return GetMacFolder(kDownloadsFolderType, "Failed to find Download folder"); #else return data->folders["XDG_DOWNLOAD_DIR"]; #endif } std::string PlatformFolders::getMusicFolder() const { #if defined(_WIN32) return GetWindowsFolder(CSIDL_MYMUSIC, "Failed to find My Music folder"); #elif defined(__APPLE__) return GetMacFolder(kMusicDocumentsFolderType, "Failed to find Music folder"); #else return data->folders["XDG_MUSIC_DIR"]; #endif } std::string PlatformFolders::getVideoFolder() const { #if defined(_WIN32) return GetWindowsFolder(CSIDL_MYVIDEO, "Failed to find My Video folder"); #elif defined(__APPLE__) return GetMacFolder(kMovieDocumentsFolderType, "Failed to find Movie folder"); #else return data->folders["XDG_VIDEOS_DIR"]; #endif } std::string PlatformFolders::getSaveGamesFolder1() const { #if defined(_WIN32) //A dedicated Save Games folder was not introduced until Vista. For XP and older save games are most often saved in a normal folder named "My Games". //Data that should not be user accessible should be placed under GetDataHome() instead return GetWindowsFolder(CSIDL_PERSONAL, "Failed to find My Documents folder")+"\\My Games"; #elif defined(__APPLE__) return GetMacFolder(kApplicationSupportFolderType, "Failed to find Application Support Folder"); #else return getDataHome(); #endif } } //namespace sago <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <sal/types.h> #include <assert.h> #include <premac.h> #ifndef IOS #include <CoreServices/CoreServices.h> #endif #include <CoreFoundation/CoreFoundation.h> #include <postmac.h> namespace { template <typename T> class CFGuard { public: explicit CFGuard(T& rT) : rT_(rT) {} ~CFGuard() { if (rT_) CFRelease(rT_); } private: T& rT_; }; typedef CFGuard<CFArrayRef> CFArrayGuard; typedef CFGuard<CFStringRef> CFStringGuard; typedef CFGuard<CFPropertyListRef> CFPropertyListGuard; /** Get the current process locale from system */ CFStringRef getProcessLocale() { CFPropertyListRef pref = CFPreferencesCopyAppValue(CFSTR("AppleLocale"), kCFPreferencesCurrentApplication); CFPropertyListGuard proplGuard(pref); if (pref == NULL) // return fallback value 'en_US' return CFStringCreateWithCString(kCFAllocatorDefault, "en_US", kCFStringEncodingASCII); CFStringRef sref = (CFGetTypeID(pref) == CFArrayGetTypeID()) ? (CFStringRef)CFArrayGetValueAtIndex((CFArrayRef)pref, 0) : (CFStringRef)pref; return CFLocaleCreateCanonicalLocaleIdentifierFromString(kCFAllocatorDefault, sref); } } /** Grab current locale from system. */ extern "C" { int macosx_getLocale(char *locale, sal_uInt32 bufferLen) { CFStringRef sref = getProcessLocale(); CFStringGuard sGuard(sref); assert(sref != NULL && "osxlocale.cxx: getProcessLocale must return a non-NULL value"); // split the string into substrings; the first two (if there are two) substrings // are language and country CFArrayRef subs = CFStringCreateArrayBySeparatingStrings(NULL, sref, CFSTR("_")); CFArrayGuard arrGuard(subs); CFStringRef lang = (CFStringRef)CFArrayGetValueAtIndex(subs, 0); CFStringGetCString(lang, locale, bufferLen, kCFStringEncodingASCII); // country also available? Assumption: if the array contains more than one // value the second value is always the country! if (CFArrayGetCount(subs) > 1) { strlcat(locale, "_", bufferLen - strlen(locale)); CFStringRef country = (CFStringRef)CFArrayGetValueAtIndex(subs, 1); CFStringGetCString(country, locale + strlen(locale), bufferLen - strlen(locale), kCFStringEncodingASCII); } // Append 'UTF-8' to the locale because the Mac OS X file // system interface is UTF-8 based and sal tries to determine // the file system locale from the locale information strlcat(locale, ".UTF-8", bufferLen - strlen(locale)); return noErr; } } /* * macxp_OSXConvertCFEncodingToIANACharSetName * * Convert a CoreFoundation text encoding to an IANA charset name. */ extern "C" int macxp_OSXConvertCFEncodingToIANACharSetName( char *buffer, unsigned int bufferLen, CFStringEncoding cfEncoding ) { CFStringRef sCFEncodingName; sCFEncodingName = CFStringConvertEncodingToIANACharSetName( cfEncoding ); CFStringGetCString( sCFEncodingName, buffer, bufferLen, cfEncoding ); if ( sCFEncodingName ) CFRelease( sCFEncodingName ); return( noErr ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Use the AppleLanguages preference instead of AppleLocale on OS X and iOS<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <sal/types.h> #include <assert.h> #include <premac.h> #ifndef IOS #include <CoreServices/CoreServices.h> #endif #include <CoreFoundation/CoreFoundation.h> #include <postmac.h> namespace { template <typename T> class CFGuard { public: explicit CFGuard(T& rT) : rT_(rT) {} ~CFGuard() { if (rT_) CFRelease(rT_); } private: T& rT_; }; typedef CFGuard<CFArrayRef> CFArrayGuard; typedef CFGuard<CFStringRef> CFStringGuard; typedef CFGuard<CFPropertyListRef> CFPropertyListGuard; /** Get the current process locale from system */ CFStringRef getProcessLocale() { CFPropertyListRef pref = CFPreferencesCopyAppValue(CFSTR("AppleLanguages"), kCFPreferencesCurrentApplication); CFPropertyListGuard proplGuard(pref); if (pref == NULL) // return fallback value 'en_US' return CFStringCreateWithCString(kCFAllocatorDefault, "en_US", kCFStringEncodingASCII); CFStringRef sref = (CFGetTypeID(pref) == CFArrayGetTypeID()) ? (CFStringRef)CFArrayGetValueAtIndex((CFArrayRef)pref, 0) : (CFStringRef)pref; return CFLocaleCreateCanonicalLocaleIdentifierFromString(kCFAllocatorDefault, sref); } } /** Grab current locale from system. */ extern "C" { int macosx_getLocale(char *locale, sal_uInt32 bufferLen) { CFStringRef sref = getProcessLocale(); CFStringGuard sGuard(sref); assert(sref != NULL && "osxlocale.cxx: getProcessLocale must return a non-NULL value"); // split the string into substrings; the first two (if there are two) substrings // are language and country CFArrayRef subs = CFStringCreateArrayBySeparatingStrings(NULL, sref, CFSTR("-")); CFArrayGuard arrGuard(subs); CFStringRef lang = (CFStringRef)CFArrayGetValueAtIndex(subs, 0); CFStringGetCString(lang, locale, bufferLen, kCFStringEncodingASCII); // country also available? Assumption: if the array contains more than one // value the second value is always the country! if (CFArrayGetCount(subs) > 1) { strlcat(locale, "_", bufferLen - strlen(locale)); CFStringRef country = (CFStringRef)CFArrayGetValueAtIndex(subs, 1); CFStringGetCString(country, locale + strlen(locale), bufferLen - strlen(locale), kCFStringEncodingASCII); } // Append 'UTF-8' to the locale because the Mac OS X file // system interface is UTF-8 based and sal tries to determine // the file system locale from the locale information strlcat(locale, ".UTF-8", bufferLen - strlen(locale)); return noErr; } } /* * macxp_OSXConvertCFEncodingToIANACharSetName * * Convert a CoreFoundation text encoding to an IANA charset name. */ extern "C" int macxp_OSXConvertCFEncodingToIANACharSetName( char *buffer, unsigned int bufferLen, CFStringEncoding cfEncoding ) { CFStringRef sCFEncodingName; sCFEncodingName = CFStringConvertEncodingToIANACharSetName( cfEncoding ); CFStringGetCString( sCFEncodingName, buffer, bufferLen, cfEncoding ); if ( sCFEncodingName ) CFRelease( sCFEncodingName ); return( noErr ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz> 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 "TgaImageConverter.h" #include <fstream> #include <tuple> #include <Image.h> #include <ImageFormat.h> #ifdef MAGNUM_TARGET_GLES #include <algorithm> #include <Swizzle.h> #endif #include "TgaImporter/TgaHeader.h" namespace Magnum { namespace Trade { namespace TgaImageConverter { TgaImageConverter::TgaImageConverter() = default; TgaImageConverter::TgaImageConverter(PluginManager::AbstractManager* manager, std::string plugin): AbstractImageConverter(manager, std::move(plugin)) {} TgaImageConverter::Features TgaImageConverter::features() const { return Feature::ConvertToData|Feature::ConvertToFile; } std::pair<const unsigned char*, std::size_t> TgaImageConverter::convertToData(const Image2D* const image) const { #ifndef MAGNUM_TARGET_GLES if(image->format() != ImageFormat::BGR && image->format() != ImageFormat::BGRA && image->format() != ImageFormat::Red) #else if(image->format() != ImageFormat::RGB && image->format() != ImageFormat::RGBA && image->format() != ImageFormat::Red) #endif { Error() << "Trade::TgaImageConverter::TgaImageConverter::convertToData(): unsupported image format" << image->format(); return {nullptr, 0}; } if(image->type() != ImageType::UnsignedByte) { Error() << "Trade::TgaImageConverter::TgaImageConverter::convertToData(): unsupported image type" << image->type(); return {nullptr, 0}; } /* Initialize data buffer */ const UnsignedByte pixelSize = image->pixelSize(); const std::size_t size = sizeof(TgaImporter::TgaHeader) + pixelSize*image->size().product(); unsigned char* data = new unsigned char[size](); /* Fill header */ auto header = reinterpret_cast<TgaImporter::TgaHeader*>(data); header->imageType = image->format() == ImageFormat::Red ? 3 : 2; header->bpp = pixelSize*8; header->width = image->size().x(); header->height = image->size().y(); /* Fill data */ std::copy(image->data(), image->data()+pixelSize*image->size().product(), data+sizeof(TgaImporter::TgaHeader)); #ifdef MAGNUM_TARGET_GLES if(image->format() == ImageFormat::RGB) { auto pixels = reinterpret_cast<Math::Vector3<UnsignedByte>*>(data+sizeof(TgaImporter::TgaHeader)); std::transform(pixels, pixels + image->size().product(), pixels, [](Math::Vector3<UnsignedByte> pixel) { return swizzle<'b', 'g', 'r'>(pixel); }); } else if(image->format() == ImageFormat::RGBA) { auto pixels = reinterpret_cast<Math::Vector4<UnsignedByte>*>(data+sizeof(TgaImporter::TgaHeader)); std::transform(pixels, pixels + image->size().product(), pixels, [](Math::Vector4<UnsignedByte> pixel) { return swizzle<'b', 'g', 'r', 'a'>(pixel); }); } #endif return {data, size}; } bool TgaImageConverter::convertToFile(const Image2D* const image, const std::string& filename) const { /* Convert the image */ const unsigned char* data; std::size_t size; std::tie(data, size) = convertToData(image); if(!data) return false; /* Open file */ std::ofstream out(filename.c_str()); if(!out.good()) { delete[] data; return false; } /* Write contents */ out.write(reinterpret_cast<const char*>(data), size); delete[] data; return true; } }}} <commit_msg>TgaImageConverter: don't forget about endianness.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz> 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 "TgaImageConverter.h" #include <fstream> #include <tuple> #include <Utility/Endianness.h> #include <Image.h> #include <ImageFormat.h> #ifdef MAGNUM_TARGET_GLES #include <algorithm> #include <Swizzle.h> #endif #include "TgaImporter/TgaHeader.h" namespace Magnum { namespace Trade { namespace TgaImageConverter { TgaImageConverter::TgaImageConverter() = default; TgaImageConverter::TgaImageConverter(PluginManager::AbstractManager* manager, std::string plugin): AbstractImageConverter(manager, std::move(plugin)) {} TgaImageConverter::Features TgaImageConverter::features() const { return Feature::ConvertToData|Feature::ConvertToFile; } std::pair<const unsigned char*, std::size_t> TgaImageConverter::convertToData(const Image2D* const image) const { #ifndef MAGNUM_TARGET_GLES if(image->format() != ImageFormat::BGR && image->format() != ImageFormat::BGRA && image->format() != ImageFormat::Red) #else if(image->format() != ImageFormat::RGB && image->format() != ImageFormat::RGBA && image->format() != ImageFormat::Red) #endif { Error() << "Trade::TgaImageConverter::TgaImageConverter::convertToData(): unsupported image format" << image->format(); return {nullptr, 0}; } if(image->type() != ImageType::UnsignedByte) { Error() << "Trade::TgaImageConverter::TgaImageConverter::convertToData(): unsupported image type" << image->type(); return {nullptr, 0}; } /* Initialize data buffer */ const UnsignedByte pixelSize = image->pixelSize(); const std::size_t size = sizeof(TgaImporter::TgaHeader) + pixelSize*image->size().product(); unsigned char* data = new unsigned char[size](); /* Fill header */ auto header = reinterpret_cast<TgaImporter::TgaHeader*>(data); header->imageType = image->format() == ImageFormat::Red ? 3 : 2; header->bpp = pixelSize*8; header->width = Utility::Endianness::littleEndian(image->size().x()); header->height = Utility::Endianness::littleEndian(image->size().y()); /* Fill data */ std::copy(image->data(), image->data()+pixelSize*image->size().product(), data+sizeof(TgaImporter::TgaHeader)); #ifdef MAGNUM_TARGET_GLES if(image->format() == ImageFormat::RGB) { auto pixels = reinterpret_cast<Math::Vector3<UnsignedByte>*>(data+sizeof(TgaImporter::TgaHeader)); std::transform(pixels, pixels + image->size().product(), pixels, [](Math::Vector3<UnsignedByte> pixel) { return swizzle<'b', 'g', 'r'>(pixel); }); } else if(image->format() == ImageFormat::RGBA) { auto pixels = reinterpret_cast<Math::Vector4<UnsignedByte>*>(data+sizeof(TgaImporter::TgaHeader)); std::transform(pixels, pixels + image->size().product(), pixels, [](Math::Vector4<UnsignedByte> pixel) { return swizzle<'b', 'g', 'r', 'a'>(pixel); }); } #endif return {data, size}; } bool TgaImageConverter::convertToFile(const Image2D* const image, const std::string& filename) const { /* Convert the image */ const unsigned char* data; std::size_t size; std::tie(data, size) = convertToData(image); if(!data) return false; /* Open file */ std::ofstream out(filename.c_str()); if(!out.good()) { delete[] data; return false; } /* Write contents */ out.write(reinterpret_cast<const char*>(data), size); delete[] data; return true; } }}} <|endoftext|>
<commit_before>/* * Copyright (c) 2001-2004 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. */ #define USE_CPP // #define CPP_PIPE #ifdef USE_CPP #include <sys/signal.h> #include <sys/types.h> #include <sys/wait.h> #if defined(__OpenBSD__) || defined(__APPLE__) #include <libgen.h> #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> #endif #include <fstream> #include <iostream> #if __GNUC__ >= 3 #include <ext/stdio_filebuf.h> #endif #include <vector> #include <string> #include "base/inifile.hh" #include "base/str.hh" using namespace std; IniFile::IniFile() {} IniFile::~IniFile() { SectionTable::iterator i = table.begin(); SectionTable::iterator end = table.end(); while (i != end) { delete (*i).second; ++i; } } #ifdef USE_CPP bool IniFile::loadCPP(const string &file, vector<char *> &cppArgs) { int fd[2]; // Open the file just to verify that we can. Otherwise if the // file doesn't exist or has bad permissions the user will get // confusing errors from cpp/g++. ifstream tmpf(file.c_str()); if (!tmpf.is_open()) return false; tmpf.close(); const char *cfile = file.c_str(); char *dir = basename(cfile); char *dir_arg = NULL; if (*dir != '.' && dir != cfile) { string arg = "-I"; arg += dir; dir_arg = new char[arg.size() + 1]; strcpy(dir_arg, arg.c_str()); } #ifdef CPP_PIPE if (pipe(fd) == -1) return false; #else char tempfile[] = "/tmp/configXXXXXX"; fd[0] = fd[1] = mkstemp(tempfile); #endif int pid = fork(); if (pid == -1) return 1; if (pid == 0) { char filename[FILENAME_MAX]; string::size_type i = file.copy(filename, sizeof(filename) - 1); filename[i] = '\0'; int arg_count = cppArgs.size(); char **args = new char *[arg_count + 20]; int nextArg = 0; args[nextArg++] = "g++"; args[nextArg++] = "-E"; args[nextArg++] = "-P"; args[nextArg++] = "-nostdinc"; args[nextArg++] = "-nostdinc++"; args[nextArg++] = "-x"; args[nextArg++] = "c++"; args[nextArg++] = "-undef"; for (int i = 0; i < arg_count; i++) args[nextArg++] = cppArgs[i]; if (dir_arg) args[nextArg++] = dir_arg; args[nextArg++] = filename; args[nextArg++] = NULL; close(STDOUT_FILENO); if (dup2(fd[1], STDOUT_FILENO) == -1) exit(1); execvp("g++", args); exit(0); } int retval; waitpid(pid, &retval, 0); delete [] dir_arg; // check for normal completion of CPP if (!WIFEXITED(retval) || WEXITSTATUS(retval) != 0) return false; #ifdef CPP_PIPE close(fd[1]); #else lseek(fd[0], 0, SEEK_SET); #endif bool status = false; #if __GNUC__ >= 3 using namespace __gnu_cxx; stdio_filebuf<char> fbuf(fd[0], ios_base::in, true, static_cast<stdio_filebuf<char>::int_type>(BUFSIZ)); if (fbuf.is_open()) { istream f(&fbuf); status = load(f); } #else ifstream f(fd[0]); if (f.is_open()) status = load(f); #endif #ifndef CPP_PIPE unlink(tempfile); #endif return status; } #endif bool IniFile::load(const string &file) { ifstream f(file.c_str()); if (!f.is_open()) return false; return load(f); } const string & IniFile::Entry::getValue() const { referenced = true; return value; } void IniFile::Section::addEntry(const std::string &entryName, const std::string &value, bool append) { EntryTable::iterator ei = table.find(entryName); if (ei == table.end()) { // new entry table[entryName] = new Entry(value); } else if (append) { // append new reult to old entry ei->second->appendValue(value); } else { // override old entry ei->second->setValue(value); } } bool IniFile::Section::add(const std::string &assignment) { string::size_type offset = assignment.find('='); if (offset == string::npos) { // no '=' found cerr << "Can't parse .ini line " << assignment << endl; return false; } // if "+=" rather than just "=" then append value bool append = (assignment[offset-1] == '+'); string entryName = assignment.substr(0, append ? offset-1 : offset); string value = assignment.substr(offset + 1); eat_white(entryName); eat_white(value); addEntry(entryName, value, append); return true; } IniFile::Entry * IniFile::Section::findEntry(const std::string &entryName) const { referenced = true; EntryTable::const_iterator ei = table.find(entryName); return (ei == table.end()) ? NULL : ei->second; } IniFile::Section * IniFile::addSection(const string &sectionName) { SectionTable::iterator i = table.find(sectionName); if (i != table.end()) { return i->second; } else { // new entry Section *sec = new Section(); table[sectionName] = sec; return sec; } } IniFile::Section * IniFile::findSection(const string &sectionName) const { SectionTable::const_iterator i = table.find(sectionName); return (i == table.end()) ? NULL : i->second; } // Take string of the form "<section>:<parameter>=<value>" and add to // database. Return true if successful, false if parse error. bool IniFile::add(const string &str) { // find ':' string::size_type offset = str.find(':'); if (offset == string::npos) // no ':' found return false; string sectionName = str.substr(0, offset); string rest = str.substr(offset + 1); eat_white(sectionName); Section *s = addSection(sectionName); return s->add(rest); } bool IniFile::load(istream &f) { Section *section = NULL; while (!f.eof()) { f >> ws; // Eat whitespace if (f.eof()) { break; } string line; getline(f, line); if (line.size() == 0) continue; eat_end_white(line); int last = line.size() - 1; if (line[0] == '[' && line[last] == ']') { string sectionName = line.substr(1, last - 1); eat_white(sectionName); section = addSection(sectionName); continue; } if (section == NULL) continue; if (!section->add(line)) return false; } return true; } bool IniFile::find(const string &sectionName, const string &entryName, string &value) const { Section *section = findSection(sectionName); if (section == NULL) return false; Entry *entry = section->findEntry(entryName); if (entry == NULL) return false; value = entry->getValue(); return true; } bool IniFile::findDefault(const string &_section, const string &entry, string &value) const { string section = _section; while (!findAppend(section, entry, value)) { if (!find(section, "default", section)) { return false; } } return true; } bool IniFile::findAppend(const string &_section, const string &entry, string &value) const { string section = _section; bool ret = false; bool first = true; do { string val; if (find(section, entry, val)) { ret = true; if (first) { value = val; first = false; } else { value += " "; value += val; } } } while (find(section, "append", section)); return ret; } bool IniFile::sectionExists(const string &sectionName) const { return findSection(sectionName) != NULL; } bool IniFile::Section::printUnreferenced(const string &sectionName) { bool unref = false; bool search_unref_entries = false; vector<string> unref_ok_entries; Entry *entry = findEntry("unref_entries_ok"); if (entry != NULL) { tokenize(unref_ok_entries, entry->getValue(), ' '); if (unref_ok_entries.size()) { search_unref_entries = true; } } for (EntryTable::iterator ei = table.begin(); ei != table.end(); ++ei) { const string &entryName = ei->first; Entry *entry = ei->second; if (entryName == "unref_section_ok" || entryName == "unref_entries_ok") { continue; } if (!entry->isReferenced()) { if (search_unref_entries && (std::find(unref_ok_entries.begin(), unref_ok_entries.end(), entryName) != unref_ok_entries.end())) { continue; } cerr << "Parameter " << sectionName << ":" << entryName << " not referenced." << endl; unref = true; } } return unref; } bool IniFile::printUnreferenced() { bool unref = false; for (SectionTable::iterator i = table.begin(); i != table.end(); ++i) { const string &sectionName = i->first; Section *section = i->second; if (!section->isReferenced()) { if (section->findEntry("unref_section_ok") == NULL) { cerr << "Section " << sectionName << " not referenced." << endl; unref = true; } } else { if (section->printUnreferenced(sectionName)) { unref = true; } } } return unref; } void IniFile::Section::dump(const string &sectionName) { for (EntryTable::iterator ei = table.begin(); ei != table.end(); ++ei) { cout << sectionName << ": " << (*ei).first << " => " << (*ei).second->getValue() << "\n"; } } void IniFile::dump() { for (SectionTable::iterator i = table.begin(); i != table.end(); ++i) { i->second->dump(i->first); } } <commit_msg>fix the -I flag stuff for CPP so it actually works right. What was I smoking?<commit_after>/* * Copyright (c) 2001-2004 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. */ #define USE_CPP // #define CPP_PIPE #ifdef USE_CPP #include <sys/signal.h> #include <sys/types.h> #include <sys/wait.h> #include <libgen.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #endif #include <fstream> #include <iostream> #if __GNUC__ >= 3 #include <ext/stdio_filebuf.h> #endif #include <vector> #include <string> #include "base/inifile.hh" #include "base/str.hh" using namespace std; IniFile::IniFile() {} IniFile::~IniFile() { SectionTable::iterator i = table.begin(); SectionTable::iterator end = table.end(); while (i != end) { delete (*i).second; ++i; } } #ifdef USE_CPP bool IniFile::loadCPP(const string &file, vector<char *> &cppArgs) { int fd[2]; // Open the file just to verify that we can. Otherwise if the // file doesn't exist or has bad permissions the user will get // confusing errors from cpp/g++. ifstream tmpf(file.c_str()); if (!tmpf.is_open()) return false; tmpf.close(); char *cfile = strcpy(new char[file.size() + 1], file.c_str()); char *dir = dirname(cfile); char *dir_arg = NULL; if (*dir != '.') { string arg = "-I"; arg += dir; dir_arg = new char[arg.size() + 1]; strcpy(dir_arg, arg.c_str()); } delete [] cfile; #ifdef CPP_PIPE if (pipe(fd) == -1) return false; #else char tempfile[] = "/tmp/configXXXXXX"; fd[0] = fd[1] = mkstemp(tempfile); #endif int pid = fork(); if (pid == -1) return 1; if (pid == 0) { char filename[FILENAME_MAX]; string::size_type i = file.copy(filename, sizeof(filename) - 1); filename[i] = '\0'; int arg_count = cppArgs.size(); char **args = new char *[arg_count + 20]; int nextArg = 0; args[nextArg++] = "g++"; args[nextArg++] = "-E"; args[nextArg++] = "-P"; args[nextArg++] = "-nostdinc"; args[nextArg++] = "-nostdinc++"; args[nextArg++] = "-x"; args[nextArg++] = "c++"; args[nextArg++] = "-undef"; for (int i = 0; i < arg_count; i++) args[nextArg++] = cppArgs[i]; if (dir_arg) args[nextArg++] = dir_arg; args[nextArg++] = filename; args[nextArg++] = NULL; close(STDOUT_FILENO); if (dup2(fd[1], STDOUT_FILENO) == -1) exit(1); execvp("g++", args); exit(0); } int retval; waitpid(pid, &retval, 0); delete [] dir_arg; // check for normal completion of CPP if (!WIFEXITED(retval) || WEXITSTATUS(retval) != 0) return false; #ifdef CPP_PIPE close(fd[1]); #else lseek(fd[0], 0, SEEK_SET); #endif bool status = false; #if __GNUC__ >= 3 using namespace __gnu_cxx; stdio_filebuf<char> fbuf(fd[0], ios_base::in, true, static_cast<stdio_filebuf<char>::int_type>(BUFSIZ)); if (fbuf.is_open()) { istream f(&fbuf); status = load(f); } #else ifstream f(fd[0]); if (f.is_open()) status = load(f); #endif #ifndef CPP_PIPE unlink(tempfile); #endif return status; } #endif bool IniFile::load(const string &file) { ifstream f(file.c_str()); if (!f.is_open()) return false; return load(f); } const string & IniFile::Entry::getValue() const { referenced = true; return value; } void IniFile::Section::addEntry(const std::string &entryName, const std::string &value, bool append) { EntryTable::iterator ei = table.find(entryName); if (ei == table.end()) { // new entry table[entryName] = new Entry(value); } else if (append) { // append new reult to old entry ei->second->appendValue(value); } else { // override old entry ei->second->setValue(value); } } bool IniFile::Section::add(const std::string &assignment) { string::size_type offset = assignment.find('='); if (offset == string::npos) { // no '=' found cerr << "Can't parse .ini line " << assignment << endl; return false; } // if "+=" rather than just "=" then append value bool append = (assignment[offset-1] == '+'); string entryName = assignment.substr(0, append ? offset-1 : offset); string value = assignment.substr(offset + 1); eat_white(entryName); eat_white(value); addEntry(entryName, value, append); return true; } IniFile::Entry * IniFile::Section::findEntry(const std::string &entryName) const { referenced = true; EntryTable::const_iterator ei = table.find(entryName); return (ei == table.end()) ? NULL : ei->second; } IniFile::Section * IniFile::addSection(const string &sectionName) { SectionTable::iterator i = table.find(sectionName); if (i != table.end()) { return i->second; } else { // new entry Section *sec = new Section(); table[sectionName] = sec; return sec; } } IniFile::Section * IniFile::findSection(const string &sectionName) const { SectionTable::const_iterator i = table.find(sectionName); return (i == table.end()) ? NULL : i->second; } // Take string of the form "<section>:<parameter>=<value>" and add to // database. Return true if successful, false if parse error. bool IniFile::add(const string &str) { // find ':' string::size_type offset = str.find(':'); if (offset == string::npos) // no ':' found return false; string sectionName = str.substr(0, offset); string rest = str.substr(offset + 1); eat_white(sectionName); Section *s = addSection(sectionName); return s->add(rest); } bool IniFile::load(istream &f) { Section *section = NULL; while (!f.eof()) { f >> ws; // Eat whitespace if (f.eof()) { break; } string line; getline(f, line); if (line.size() == 0) continue; eat_end_white(line); int last = line.size() - 1; if (line[0] == '[' && line[last] == ']') { string sectionName = line.substr(1, last - 1); eat_white(sectionName); section = addSection(sectionName); continue; } if (section == NULL) continue; if (!section->add(line)) return false; } return true; } bool IniFile::find(const string &sectionName, const string &entryName, string &value) const { Section *section = findSection(sectionName); if (section == NULL) return false; Entry *entry = section->findEntry(entryName); if (entry == NULL) return false; value = entry->getValue(); return true; } bool IniFile::findDefault(const string &_section, const string &entry, string &value) const { string section = _section; while (!findAppend(section, entry, value)) { if (!find(section, "default", section)) { return false; } } return true; } bool IniFile::findAppend(const string &_section, const string &entry, string &value) const { string section = _section; bool ret = false; bool first = true; do { string val; if (find(section, entry, val)) { ret = true; if (first) { value = val; first = false; } else { value += " "; value += val; } } } while (find(section, "append", section)); return ret; } bool IniFile::sectionExists(const string &sectionName) const { return findSection(sectionName) != NULL; } bool IniFile::Section::printUnreferenced(const string &sectionName) { bool unref = false; bool search_unref_entries = false; vector<string> unref_ok_entries; Entry *entry = findEntry("unref_entries_ok"); if (entry != NULL) { tokenize(unref_ok_entries, entry->getValue(), ' '); if (unref_ok_entries.size()) { search_unref_entries = true; } } for (EntryTable::iterator ei = table.begin(); ei != table.end(); ++ei) { const string &entryName = ei->first; Entry *entry = ei->second; if (entryName == "unref_section_ok" || entryName == "unref_entries_ok") { continue; } if (!entry->isReferenced()) { if (search_unref_entries && (std::find(unref_ok_entries.begin(), unref_ok_entries.end(), entryName) != unref_ok_entries.end())) { continue; } cerr << "Parameter " << sectionName << ":" << entryName << " not referenced." << endl; unref = true; } } return unref; } bool IniFile::printUnreferenced() { bool unref = false; for (SectionTable::iterator i = table.begin(); i != table.end(); ++i) { const string &sectionName = i->first; Section *section = i->second; if (!section->isReferenced()) { if (section->findEntry("unref_section_ok") == NULL) { cerr << "Section " << sectionName << " not referenced." << endl; unref = true; } } else { if (section->printUnreferenced(sectionName)) { unref = true; } } } return unref; } void IniFile::Section::dump(const string &sectionName) { for (EntryTable::iterator ei = table.begin(); ei != table.end(); ++ei) { cout << sectionName << ": " << (*ei).first << " => " << (*ei).second->getValue() << "\n"; } } void IniFile::dump() { for (SectionTable::iterator i = table.begin(); i != table.end(); ++i) { i->second->dump(i->first); } } <|endoftext|>
<commit_before>#include "fake_bci.hpp" #include <limits> #include <boost/random/uniform_int_distribution.hpp> FakeBCI::FakeBCI() : mOpenCount(0), mOpenRet(true), mInitCount(0), mLastChannels(0), mInitRet(true), mStartCount(0), mStartRet(true), mAcquireCount(0), mAcquireRet(1), mGetDataCount(0), mpLastGetData(0), mLastSamples(0), mTimestampCount(0), mTimestampRet(-1), mStopCount(0), mStopRet(true), mCloseCount(0), mCloseRet(true) { mLastMac[0] = 0xd; mLastMac[1] = 0xe; mLastMac[2] = 0xa; mLastMac[3] = 0xd; mLastMac[4] = 0xe; mLastMac[5] = 0xd; } FakeBCI::~FakeBCI() { } bool FakeBCI::open(uint8_t mac[]) { BOOST_VERIFY(sizeof(mac) == MAC_ADDRESS_SIZE); mOpenCount++; std::copy(mac, mac+MAC_ADDRESS_SIZE, mLastMac); return mOpenRet; } bool FakeBCI::init(size_t channels) { mInitCount++; mLastChannels = channels; return mInitRet; } bool FakeBCI::start() { mStartCount++; return mStartRet; } size_t FakeBCI::acquire() { mAcquireCount++; return mAcquireRet; } void FakeBCI::getdata(uint32_t* buffer, size_t samples) { BOOST_VERIFY(buffer != 0); BOOST_VERIFY(mAcquireRet == samples); mGetDataCount++; for(int i=0; i < samples; i++) { boost::random::uniform_int_distribution<> dist(0, std::numeric_limits<uint32_t>::max()); buffer[i] = (uint32_t)dist(gen); } mpLastGetData = buffer; mLastSamples = samples; } uint64_t FakeBCI::timestamp() { mTimestampCount++; return mTimestampRet; } bool FakeBCI::stop() { mStopCount++; return mStopRet; } bool FakeBCI::close() { mCloseCount++; return mCloseRet; } <commit_msg>Fixed assert<commit_after>#include "fake_bci.hpp" #include <limits> #include <boost/random/uniform_int_distribution.hpp> FakeBCI::FakeBCI() : mOpenCount(0), mOpenRet(true), mInitCount(0), mLastChannels(0), mInitRet(true), mStartCount(0), mStartRet(true), mAcquireCount(0), mAcquireRet(1), mGetDataCount(0), mpLastGetData(0), mLastSamples(0), mTimestampCount(0), mTimestampRet(-1), mStopCount(0), mStopRet(true), mCloseCount(0), mCloseRet(true) { mLastMac[0] = 0xd; mLastMac[1] = 0xe; mLastMac[2] = 0xa; mLastMac[3] = 0xd; mLastMac[4] = 0xe; mLastMac[5] = 0xd; } FakeBCI::~FakeBCI() { } #include <iostream> using namespace std; bool FakeBCI::open(uint8_t mac[]) { BOOST_VERIFY(sizeof(mac) >= MAC_ADDRESS_SIZE); mOpenCount++; std::copy(mac, mac+MAC_ADDRESS_SIZE, mLastMac); return mOpenRet; } bool FakeBCI::init(size_t channels) { mInitCount++; mLastChannels = channels; return mInitRet; } bool FakeBCI::start() { mStartCount++; return mStartRet; } size_t FakeBCI::acquire() { mAcquireCount++; return mAcquireRet; } void FakeBCI::getdata(uint32_t* buffer, size_t samples) { BOOST_VERIFY(buffer != 0); BOOST_VERIFY(mAcquireRet == samples); mGetDataCount++; for(int i=0; i < samples; i++) { boost::random::uniform_int_distribution<> dist(0, std::numeric_limits<uint32_t>::max()); buffer[i] = (uint32_t)dist(gen); } mpLastGetData = buffer; mLastSamples = samples; } uint64_t FakeBCI::timestamp() { mTimestampCount++; return mTimestampRet; } bool FakeBCI::stop() { mStopCount++; return mStopRet; } bool FakeBCI::close() { mCloseCount++; return mCloseRet; } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // The computeRoots function included in this is based on materials // covered by the following copyright and license: // // Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include <iostream> #include <Eigen/Core> #include <Eigen/Eigenvalues> #include <Eigen/Geometry> #include <bench/BenchTimer.h> using namespace Eigen; using namespace std; template<typename Matrix, typename Roots> inline void computeRoots(const Matrix& m, Roots& roots) { typedef typename Matrix::Scalar Scalar; const Scalar s_inv3 = 1.0/3.0; const Scalar s_sqrt3 = internal::sqrt(Scalar(3.0)); // The characteristic equation is x^3 - c2*x^2 + c1*x - c0 = 0. The // eigenvalues are the roots to this equation, all guaranteed to be // real-valued, because the matrix is symmetric. Scalar c0 = m(0,0)*m(1,1)*m(2,2) + Scalar(2)*m(0,1)*m(0,2)*m(1,2) - m(0,0)*m(1,2)*m(1,2) - m(1,1)*m(0,2)*m(0,2) - m(2,2)*m(0,1)*m(0,1); Scalar c1 = m(0,0)*m(1,1) - m(0,1)*m(0,1) + m(0,0)*m(2,2) - m(0,2)*m(0,2) + m(1,1)*m(2,2) - m(1,2)*m(1,2); Scalar c2 = m(0,0) + m(1,1) + m(2,2); // Construct the parameters used in classifying the roots of the equation // and in solving the equation for the roots in closed form. Scalar c2_over_3 = c2*s_inv3; Scalar a_over_3 = (c1 - c2*c2_over_3)*s_inv3; if (a_over_3 > Scalar(0)) a_over_3 = Scalar(0); Scalar half_b = Scalar(0.5)*(c0 + c2_over_3*(Scalar(2)*c2_over_3*c2_over_3 - c1)); Scalar q = half_b*half_b + a_over_3*a_over_3*a_over_3; if (q > Scalar(0)) q = Scalar(0); // Compute the eigenvalues by solving for the roots of the polynomial. Scalar rho = internal::sqrt(-a_over_3); Scalar theta = std::atan2(internal::sqrt(-q),half_b)*s_inv3; Scalar cos_theta = internal::cos(theta); Scalar sin_theta = internal::sin(theta); roots(0) = c2_over_3 + Scalar(2)*rho*cos_theta; roots(1) = c2_over_3 - rho*(cos_theta + s_sqrt3*sin_theta); roots(2) = c2_over_3 - rho*(cos_theta - s_sqrt3*sin_theta); // Sort in increasing order. if (roots(0) >= roots(1)) std::swap(roots(0),roots(1)); if (roots(1) >= roots(2)) { std::swap(roots(1),roots(2)); if (roots(0) >= roots(1)) std::swap(roots(0),roots(1)); } } template<typename Matrix, typename Vector> void eigen33(const Matrix& mat, Matrix& evecs, Vector& evals) { typedef typename Matrix::Scalar Scalar; // Scale the matrix so its entries are in [-1,1]. The scaling is applied // only when at least one matrix entry has magnitude larger than 1. Scalar scale = mat.cwiseAbs()/*.template triangularView<Lower>()*/.maxCoeff(); scale = std::max(scale,Scalar(1)); Matrix scaledMat = mat / scale; // Compute the eigenvalues // scaledMat.setZero(); computeRoots(scaledMat,evals); // compute the eigen vectors // **here we assume 3 differents eigenvalues** // "optimized version" which appears to be slower with gcc! // Vector base; // Scalar alpha, beta; // base << scaledMat(1,0) * scaledMat(2,1), // scaledMat(1,0) * scaledMat(2,0), // -scaledMat(1,0) * scaledMat(1,0); // for(int k=0; k<2; ++k) // { // alpha = scaledMat(0,0) - evals(k); // beta = scaledMat(1,1) - evals(k); // evecs.col(k) = (base + Vector(-beta*scaledMat(2,0), -alpha*scaledMat(2,1), alpha*beta)).normalized(); // } // evecs.col(2) = evecs.col(0).cross(evecs.col(1)).normalized(); // // naive version // Matrix tmp; // tmp = scaledMat; // tmp.diagonal().array() -= evals(0); // evecs.col(0) = tmp.row(0).cross(tmp.row(1)).normalized(); // // tmp = scaledMat; // tmp.diagonal().array() -= evals(1); // evecs.col(1) = tmp.row(0).cross(tmp.row(1)).normalized(); // // tmp = scaledMat; // tmp.diagonal().array() -= evals(2); // evecs.col(2) = tmp.row(0).cross(tmp.row(1)).normalized(); // a more stable version: if((evals(2)-evals(0))<=Eigen::NumTraits<Scalar>::epsilon()) { evecs.setIdentity(); } else { Matrix tmp; tmp = scaledMat; tmp.diagonal ().array () -= evals (2); evecs.col (2) = tmp.row (0).cross (tmp.row (1)).normalized (); tmp = scaledMat; tmp.diagonal ().array () -= evals (1); evecs.col(1) = tmp.row (0).cross(tmp.row (1)); Scalar n1 = evecs.col(1).norm(); if(n1<=Eigen::NumTraits<Scalar>::epsilon()) evecs.col(1) = evecs.col(2).unitOrthogonal(); else evecs.col(1) /= n1; // make sure that evecs[1] is orthogonal to evecs[2] evecs.col(1) = evecs.col(2).cross(evecs.col(1).cross(evecs.col(2))).normalized(); evecs.col(0) = evecs.col(2).cross(evecs.col(1)); } // Rescale back to the original size. evals *= scale; } int main() { BenchTimer t; int tries = 10; int rep = 400000; typedef Matrix3f Mat; typedef Vector3f Vec; Mat A = Mat::Random(3,3); A = A.adjoint() * A; SelfAdjointEigenSolver<Mat> eig(A); BENCH(t, tries, rep, eig.compute(A)); std::cout << "Eigen: " << t.best() << "s\n"; Mat evecs; Vec evals; BENCH(t, tries, rep, eigen33(A,evecs,evals)); std::cout << "Direct: " << t.best() << "s\n\n"; std::cerr << "Eigenvalue/eigenvector diffs:\n"; std::cerr << (evals - eig.eigenvalues()).transpose() << "\n"; for(int k=0;k<3;++k) if(evecs.col(k).dot(eig.eigenvectors().col(k))<0) evecs.col(k) = -evecs.col(k); std::cerr << evecs - eig.eigenvectors() << "\n\n"; } <commit_msg>Update utility for experimenting with 3x3 eigenvalues<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // The computeRoots function included in this is based on materials // covered by the following copyright and license: // // Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include <iostream> #include <Eigen/Core> #include <Eigen/Eigenvalues> #include <Eigen/Geometry> #include <bench/BenchTimer.h> using namespace Eigen; using namespace std; template<typename Matrix, typename Roots> inline void computeRoots(const Matrix& m, Roots& roots) { typedef typename Matrix::Scalar Scalar; const Scalar s_inv3 = 1.0/3.0; const Scalar s_sqrt3 = std::sqrt(Scalar(3.0)); // The characteristic equation is x^3 - c2*x^2 + c1*x - c0 = 0. The // eigenvalues are the roots to this equation, all guaranteed to be // real-valued, because the matrix is symmetric. Scalar c0 = m(0,0)*m(1,1)*m(2,2) + Scalar(2)*m(0,1)*m(0,2)*m(1,2) - m(0,0)*m(1,2)*m(1,2) - m(1,1)*m(0,2)*m(0,2) - m(2,2)*m(0,1)*m(0,1); Scalar c1 = m(0,0)*m(1,1) - m(0,1)*m(0,1) + m(0,0)*m(2,2) - m(0,2)*m(0,2) + m(1,1)*m(2,2) - m(1,2)*m(1,2); Scalar c2 = m(0,0) + m(1,1) + m(2,2); // Construct the parameters used in classifying the roots of the equation // and in solving the equation for the roots in closed form. Scalar c2_over_3 = c2*s_inv3; Scalar a_over_3 = (c1 - c2*c2_over_3)*s_inv3; if (a_over_3 > Scalar(0)) a_over_3 = Scalar(0); Scalar half_b = Scalar(0.5)*(c0 + c2_over_3*(Scalar(2)*c2_over_3*c2_over_3 - c1)); Scalar q = half_b*half_b + a_over_3*a_over_3*a_over_3; if (q > Scalar(0)) q = Scalar(0); // Compute the eigenvalues by solving for the roots of the polynomial. Scalar rho = std::sqrt(-a_over_3); Scalar theta = std::atan2(std::sqrt(-q),half_b)*s_inv3; Scalar cos_theta = std::cos(theta); Scalar sin_theta = std::sin(theta); roots(2) = c2_over_3 + Scalar(2)*rho*cos_theta; roots(0) = c2_over_3 - rho*(cos_theta + s_sqrt3*sin_theta); roots(1) = c2_over_3 - rho*(cos_theta - s_sqrt3*sin_theta); } template<typename Matrix, typename Vector> void eigen33(const Matrix& mat, Matrix& evecs, Vector& evals) { typedef typename Matrix::Scalar Scalar; // Scale the matrix so its entries are in [-1,1]. The scaling is applied // only when at least one matrix entry has magnitude larger than 1. Scalar shift = mat.trace()/3; Matrix scaledMat = mat; scaledMat.diagonal().array() -= shift; Scalar scale = scaledMat.cwiseAbs()/*.template triangularView<Lower>()*/.maxCoeff(); scale = std::max(scale,Scalar(1)); scaledMat/=scale; // Compute the eigenvalues // scaledMat.setZero(); computeRoots(scaledMat,evals); // compute the eigen vectors // **here we assume 3 differents eigenvalues** // "optimized version" which appears to be slower with gcc! // Vector base; // Scalar alpha, beta; // base << scaledMat(1,0) * scaledMat(2,1), // scaledMat(1,0) * scaledMat(2,0), // -scaledMat(1,0) * scaledMat(1,0); // for(int k=0; k<2; ++k) // { // alpha = scaledMat(0,0) - evals(k); // beta = scaledMat(1,1) - evals(k); // evecs.col(k) = (base + Vector(-beta*scaledMat(2,0), -alpha*scaledMat(2,1), alpha*beta)).normalized(); // } // evecs.col(2) = evecs.col(0).cross(evecs.col(1)).normalized(); // // naive version // Matrix tmp; // tmp = scaledMat; // tmp.diagonal().array() -= evals(0); // evecs.col(0) = tmp.row(0).cross(tmp.row(1)).normalized(); // // tmp = scaledMat; // tmp.diagonal().array() -= evals(1); // evecs.col(1) = tmp.row(0).cross(tmp.row(1)).normalized(); // // tmp = scaledMat; // tmp.diagonal().array() -= evals(2); // evecs.col(2) = tmp.row(0).cross(tmp.row(1)).normalized(); // a more stable version: if((evals(2)-evals(0))<=Eigen::NumTraits<Scalar>::epsilon()) { evecs.setIdentity(); } else { Matrix tmp; tmp = scaledMat; tmp.diagonal ().array () -= evals (2); evecs.col (2) = tmp.row (0).cross (tmp.row (1)).normalized (); tmp = scaledMat; tmp.diagonal ().array () -= evals (1); evecs.col(1) = tmp.row (0).cross(tmp.row (1)); Scalar n1 = evecs.col(1).norm(); if(n1<=Eigen::NumTraits<Scalar>::epsilon()) evecs.col(1) = evecs.col(2).unitOrthogonal(); else evecs.col(1) /= n1; // make sure that evecs[1] is orthogonal to evecs[2] evecs.col(1) = evecs.col(2).cross(evecs.col(1).cross(evecs.col(2))).normalized(); evecs.col(0) = evecs.col(2).cross(evecs.col(1)); } // Rescale back to the original size. evals *= scale; evals.array()+=shift; } int main() { BenchTimer t; int tries = 10; int rep = 400000; typedef Matrix3d Mat; typedef Vector3d Vec; Mat A = Mat::Random(3,3); A = A.adjoint() * A; // Mat Q = A.householderQr().householderQ(); // A = Q * Vec(2.2424567,2.2424566,7.454353).asDiagonal() * Q.transpose(); SelfAdjointEigenSolver<Mat> eig(A); BENCH(t, tries, rep, eig.compute(A)); std::cout << "Eigen iterative: " << t.best() << "s\n"; BENCH(t, tries, rep, eig.computeDirect(A)); std::cout << "Eigen direct : " << t.best() << "s\n"; Mat evecs; Vec evals; BENCH(t, tries, rep, eigen33(A,evecs,evals)); std::cout << "Direct: " << t.best() << "s\n\n"; // std::cerr << "Eigenvalue/eigenvector diffs:\n"; // std::cerr << (evals - eig.eigenvalues()).transpose() << "\n"; // for(int k=0;k<3;++k) // if(evecs.col(k).dot(eig.eigenvectors().col(k))<0) // evecs.col(k) = -evecs.col(k); // std::cerr << evecs - eig.eigenvectors() << "\n\n"; } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __MESOS_CONTAINERIZER_HPP__ #define __MESOS_CONTAINERIZER_HPP__ #include <list> #include <vector> #include <mesos/slave/container_logger.hpp> #include <mesos/slave/isolator.hpp> #include <process/metrics/counter.hpp> #include <stout/hashmap.hpp> #include <stout/multihashmap.hpp> #include "slave/state.hpp" #include "slave/containerizer/containerizer.hpp" #include "slave/containerizer/mesos/launcher.hpp" #include "slave/containerizer/mesos/provisioner/provisioner.hpp" namespace mesos { namespace internal { namespace slave { extern const char MESOS_CONTAINERIZER[]; // Forward declaration. class MesosContainerizerProcess; class MesosContainerizer : public Containerizer { public: static Try<MesosContainerizer*> create( const Flags& flags, bool local, Fetcher* fetcher); MesosContainerizer( const Flags& flags, bool local, Fetcher* fetcher, const process::Owned<mesos::slave::ContainerLogger>& logger, const process::Owned<Launcher>& launcher, const process::Owned<Provisioner>& provisioner, const std::vector<process::Owned<mesos::slave::Isolator>>& isolators); // Used for testing. MesosContainerizer(const process::Owned<MesosContainerizerProcess>& _process); virtual ~MesosContainerizer(); virtual process::Future<Nothing> recover( const Option<state::SlaveState>& state); virtual process::Future<bool> launch( const ContainerID& containerId, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId, const process::PID<Slave>& slavePid, bool checkpoint); virtual process::Future<bool> launch( const ContainerID& containerId, const TaskInfo& taskInfo, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId, const process::PID<Slave>& slavePid, bool checkpoint); virtual process::Future<Nothing> update( const ContainerID& containerId, const Resources& resources); virtual process::Future<ResourceStatistics> usage( const ContainerID& containerId); virtual process::Future<ContainerStatus> status( const ContainerID& containerId); virtual process::Future<containerizer::Termination> wait( const ContainerID& containerId); virtual void destroy(const ContainerID& containerId); virtual process::Future<hashset<ContainerID>> containers(); private: process::Owned<MesosContainerizerProcess> process; }; class MesosContainerizerProcess : public process::Process<MesosContainerizerProcess> { public: MesosContainerizerProcess( const Flags& _flags, bool _local, Fetcher* _fetcher, const process::Owned<mesos::slave::ContainerLogger>& _logger, const process::Owned<Launcher>& _launcher, const process::Owned<Provisioner>& _provisioner, const std::vector<process::Owned<mesos::slave::Isolator>>& _isolators) : flags(_flags), local(_local), fetcher(_fetcher), logger(_logger), launcher(_launcher), provisioner(_provisioner), isolators(_isolators) {} virtual ~MesosContainerizerProcess() {} virtual process::Future<Nothing> recover( const Option<state::SlaveState>& state); virtual process::Future<bool> launch( const ContainerID& containerId, const Option<TaskInfo>& taskInfo, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId, const process::PID<Slave>& slavePid, bool checkpoint); virtual process::Future<Nothing> update( const ContainerID& containerId, const Resources& resources); virtual process::Future<ResourceStatistics> usage( const ContainerID& containerId); virtual process::Future<ContainerStatus> status( const ContainerID& containerId); virtual process::Future<containerizer::Termination> wait( const ContainerID& containerId); virtual process::Future<bool> exec( const ContainerID& containerId, int pipeWrite); virtual void destroy(const ContainerID& containerId); virtual process::Future<hashset<ContainerID>> containers(); // Made public for testing. void ___recover( const ContainerID& containerId, const process::Future<std::list<process::Future<Nothing>>>& future); private: process::Future<Nothing> _recover( const std::list<mesos::slave::ContainerState>& recoverable, const hashset<ContainerID>& orphans); process::Future<std::list<Nothing>> recoverIsolators( const std::list<mesos::slave::ContainerState>& recoverable, const hashset<ContainerID>& orphans); process::Future<Nothing> recoverProvisioner( const std::list<mesos::slave::ContainerState>& recoverable, const hashset<ContainerID>& orphans); process::Future<Nothing> __recover( const std::list<mesos::slave::ContainerState>& recovered, const hashset<ContainerID>& orphans); process::Future<std::list<Option<mesos::slave::ContainerLaunchInfo>>> prepare(const ContainerID& containerId, const Option<TaskInfo>& taskInfo, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const Option<ProvisionInfo>& provisionInfo); process::Future<Nothing> fetch( const ContainerID& containerId, const CommandInfo& commandInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId); process::Future<bool> _launch( const ContainerID& containerId, const Option<TaskInfo>& taskInfo, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId, const process::PID<Slave>& slavePid, bool checkpoint, const Option<ProvisionInfo>& provisionInfo); process::Future<bool> __launch( const ContainerID& containerId, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId, const process::PID<Slave>& slavePid, bool checkpoint, const std::list<Option<mesos::slave::ContainerLaunchInfo>>& launchInfos); process::Future<bool> isolate( const ContainerID& containerId, pid_t _pid); // Continues 'destroy()' once isolators has completed. void _destroy(const ContainerID& containerId); // Continues '_destroy()' once all processes have been killed by the launcher. void __destroy( const ContainerID& containerId, const process::Future<Nothing>& future); // Continues '__destroy()' once we get the exit status of the executor. void ___destroy( const ContainerID& containerId, const process::Future<Option<int>>& status, const Option<std::string>& message); // Continues '___destroy()' once all isolators have completed // cleanup. void ____destroy( const ContainerID& containerId, const process::Future<Option<int>>& status, const process::Future<std::list<process::Future<Nothing>>>& cleanups, Option<std::string> message); // Continues '____destroy()' once provisioner have completed destroy. void _____destroy( const ContainerID& containerId, const process::Future<Option<int>>& status, const process::Future<bool>& destroy, Option<std::string> message); // Call back for when an isolator limits a container and impacts the // processes. This will trigger container destruction. void limited( const ContainerID& containerId, const process::Future<mesos::slave::ContainerLimitation>& future); // Call back for when the executor exits. This will trigger container // destroy. void reaped(const ContainerID& containerId); // TODO(jieyu): Consider introducing an Isolators struct and moving // all isolator related operations to that struct. process::Future<std::list<process::Future<Nothing>>> cleanupIsolators( const ContainerID& containerId); const Flags flags; const bool local; Fetcher* fetcher; process::Owned<mesos::slave::ContainerLogger> logger; const process::Owned<Launcher> launcher; const process::Owned<Provisioner> provisioner; const std::vector<process::Owned<mesos::slave::Isolator>> isolators; enum State { PREPARING, ISOLATING, FETCHING, RUNNING, DESTROYING }; struct Container { // Promise for futures returned from wait(). process::Promise<containerizer::Termination> promise; // We need to keep track of the future exit status for each // executor because we'll only get a single notification when // the executor exits. process::Future<Option<int>> status; // We keep track of the future that is waiting for all the // isolators' prepare futures, so that destroy will only start // calling cleanup after all isolators has finished preparing. process::Future<std::list<Option<mesos::slave::ContainerLaunchInfo>>> launchInfos; // We keep track of the future that is waiting for all the // isolators' isolate futures, so that destroy will only start // calling cleanup after all isolators has finished isolating. process::Future<std::list<Nothing>> isolation; // We keep track of any limitations received from each isolator so we can // determine the cause of an executor termination. std::vector<mesos::slave::ContainerLimitation> limitations; // We keep track of the resources for each container so we can set the // ResourceStatistics limits in usage(). Resources resources; // The executor's working directory on the host. std::string directory; State state; }; hashmap<ContainerID, process::Owned<Container>> containers_; struct Metrics { Metrics(); ~Metrics(); process::metrics::Counter container_destroy_errors; } metrics; }; } // namespace slave { } // namespace internal { } // namespace mesos { #endif // __MESOS_CONTAINERIZER_HPP__ <commit_msg>Introduced `Sequence` in container.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __MESOS_CONTAINERIZER_HPP__ #define __MESOS_CONTAINERIZER_HPP__ #include <list> #include <vector> #include <process/sequence.hpp> #include <process/metrics/counter.hpp> #include <stout/hashmap.hpp> #include <stout/multihashmap.hpp> #include <mesos/slave/container_logger.hpp> #include <mesos/slave/isolator.hpp> #include "slave/state.hpp" #include "slave/containerizer/containerizer.hpp" #include "slave/containerizer/mesos/launcher.hpp" #include "slave/containerizer/mesos/provisioner/provisioner.hpp" namespace mesos { namespace internal { namespace slave { extern const char MESOS_CONTAINERIZER[]; // Forward declaration. class MesosContainerizerProcess; class MesosContainerizer : public Containerizer { public: static Try<MesosContainerizer*> create( const Flags& flags, bool local, Fetcher* fetcher); MesosContainerizer( const Flags& flags, bool local, Fetcher* fetcher, const process::Owned<mesos::slave::ContainerLogger>& logger, const process::Owned<Launcher>& launcher, const process::Owned<Provisioner>& provisioner, const std::vector<process::Owned<mesos::slave::Isolator>>& isolators); // Used for testing. MesosContainerizer(const process::Owned<MesosContainerizerProcess>& _process); virtual ~MesosContainerizer(); virtual process::Future<Nothing> recover( const Option<state::SlaveState>& state); virtual process::Future<bool> launch( const ContainerID& containerId, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId, const process::PID<Slave>& slavePid, bool checkpoint); virtual process::Future<bool> launch( const ContainerID& containerId, const TaskInfo& taskInfo, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId, const process::PID<Slave>& slavePid, bool checkpoint); virtual process::Future<Nothing> update( const ContainerID& containerId, const Resources& resources); virtual process::Future<ResourceStatistics> usage( const ContainerID& containerId); virtual process::Future<ContainerStatus> status( const ContainerID& containerId); virtual process::Future<containerizer::Termination> wait( const ContainerID& containerId); virtual void destroy(const ContainerID& containerId); virtual process::Future<hashset<ContainerID>> containers(); private: process::Owned<MesosContainerizerProcess> process; }; class MesosContainerizerProcess : public process::Process<MesosContainerizerProcess> { public: MesosContainerizerProcess( const Flags& _flags, bool _local, Fetcher* _fetcher, const process::Owned<mesos::slave::ContainerLogger>& _logger, const process::Owned<Launcher>& _launcher, const process::Owned<Provisioner>& _provisioner, const std::vector<process::Owned<mesos::slave::Isolator>>& _isolators) : flags(_flags), local(_local), fetcher(_fetcher), logger(_logger), launcher(_launcher), provisioner(_provisioner), isolators(_isolators) {} virtual ~MesosContainerizerProcess() {} virtual process::Future<Nothing> recover( const Option<state::SlaveState>& state); virtual process::Future<bool> launch( const ContainerID& containerId, const Option<TaskInfo>& taskInfo, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId, const process::PID<Slave>& slavePid, bool checkpoint); virtual process::Future<Nothing> update( const ContainerID& containerId, const Resources& resources); virtual process::Future<ResourceStatistics> usage( const ContainerID& containerId); virtual process::Future<ContainerStatus> status( const ContainerID& containerId); virtual process::Future<containerizer::Termination> wait( const ContainerID& containerId); virtual process::Future<bool> exec( const ContainerID& containerId, int pipeWrite); virtual void destroy(const ContainerID& containerId); virtual process::Future<hashset<ContainerID>> containers(); // Made public for testing. void ___recover( const ContainerID& containerId, const process::Future<std::list<process::Future<Nothing>>>& future); private: process::Future<Nothing> _recover( const std::list<mesos::slave::ContainerState>& recoverable, const hashset<ContainerID>& orphans); process::Future<std::list<Nothing>> recoverIsolators( const std::list<mesos::slave::ContainerState>& recoverable, const hashset<ContainerID>& orphans); process::Future<Nothing> recoverProvisioner( const std::list<mesos::slave::ContainerState>& recoverable, const hashset<ContainerID>& orphans); process::Future<Nothing> __recover( const std::list<mesos::slave::ContainerState>& recovered, const hashset<ContainerID>& orphans); process::Future<std::list<Option<mesos::slave::ContainerLaunchInfo>>> prepare(const ContainerID& containerId, const Option<TaskInfo>& taskInfo, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const Option<ProvisionInfo>& provisionInfo); process::Future<Nothing> fetch( const ContainerID& containerId, const CommandInfo& commandInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId); process::Future<bool> _launch( const ContainerID& containerId, const Option<TaskInfo>& taskInfo, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId, const process::PID<Slave>& slavePid, bool checkpoint, const Option<ProvisionInfo>& provisionInfo); process::Future<bool> __launch( const ContainerID& containerId, const ExecutorInfo& executorInfo, const std::string& directory, const Option<std::string>& user, const SlaveID& slaveId, const process::PID<Slave>& slavePid, bool checkpoint, const std::list<Option<mesos::slave::ContainerLaunchInfo>>& launchInfos); process::Future<bool> isolate( const ContainerID& containerId, pid_t _pid); // Continues 'destroy()' once isolators has completed. void _destroy(const ContainerID& containerId); // Continues '_destroy()' once all processes have been killed by the launcher. void __destroy( const ContainerID& containerId, const process::Future<Nothing>& future); // Continues '__destroy()' once we get the exit status of the executor. void ___destroy( const ContainerID& containerId, const process::Future<Option<int>>& status, const Option<std::string>& message); // Continues '___destroy()' once all isolators have completed // cleanup. void ____destroy( const ContainerID& containerId, const process::Future<Option<int>>& status, const process::Future<std::list<process::Future<Nothing>>>& cleanups, Option<std::string> message); // Continues '____destroy()' once provisioner have completed destroy. void _____destroy( const ContainerID& containerId, const process::Future<Option<int>>& status, const process::Future<bool>& destroy, Option<std::string> message); // Call back for when an isolator limits a container and impacts the // processes. This will trigger container destruction. void limited( const ContainerID& containerId, const process::Future<mesos::slave::ContainerLimitation>& future); // Call back for when the executor exits. This will trigger container // destroy. void reaped(const ContainerID& containerId); // TODO(jieyu): Consider introducing an Isolators struct and moving // all isolator related operations to that struct. process::Future<std::list<process::Future<Nothing>>> cleanupIsolators( const ContainerID& containerId); const Flags flags; const bool local; Fetcher* fetcher; process::Owned<mesos::slave::ContainerLogger> logger; const process::Owned<Launcher> launcher; const process::Owned<Provisioner> provisioner; const std::vector<process::Owned<mesos::slave::Isolator>> isolators; enum State { PREPARING, ISOLATING, FETCHING, RUNNING, DESTROYING }; struct Container { // Promise for futures returned from wait(). process::Promise<containerizer::Termination> promise; // We need to keep track of the future exit status for each // executor because we'll only get a single notification when // the executor exits. process::Future<Option<int>> status; // We keep track of the future that is waiting for all the // isolators' prepare futures, so that destroy will only start // calling cleanup after all isolators has finished preparing. process::Future<std::list<Option<mesos::slave::ContainerLaunchInfo>>> launchInfos; // We keep track of the future that is waiting for all the // isolators' isolate futures, so that destroy will only start // calling cleanup after all isolators has finished isolating. process::Future<std::list<Nothing>> isolation; // We keep track of any limitations received from each isolator so we can // determine the cause of an executor termination. std::vector<mesos::slave::ContainerLimitation> limitations; // We keep track of the resources for each container so we can set the // ResourceStatistics limits in usage(). Resources resources; // The executor's working directory on the host. std::string directory; State state; // Used when `status` needs to be collected from isolators // associated with this container. `Sequence` allows us to // maintain the order of `status` requests for a given container. process::Sequence sequence; }; hashmap<ContainerID, process::Owned<Container>> containers_; struct Metrics { Metrics(); ~Metrics(); process::metrics::Counter container_destroy_errors; } metrics; }; } // namespace slave { } // namespace internal { } // namespace mesos { #endif // __MESOS_CONTAINERIZER_HPP__ <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIIrrlichtTexture.cpp created: Tue Mar 3 2009 author: Paul D Turner (based on original code by Thomas Suter) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 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 #include "CEGUI/RendererModules/Irrlicht/Texture.h" #include "CEGUI/System.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodec.h" #include <irrlicht.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// uint32 IrrlichtTexture::d_textureNumber = 0; //----------------------------------------------------------------------------// void IrrlichtTexture::setIrrlichtTexture(irr::video::ITexture* tex) { d_texture = tex; if (d_texture) { d_size = d_dataSize = Sizef( static_cast<float>(d_texture->getSize().Width), static_cast<float>(d_texture->getSize().Height)); updateCachedScaleValues(); } } //----------------------------------------------------------------------------// irr::video::ITexture* IrrlichtTexture::getIrrlichtTexture() const { return d_texture; } //----------------------------------------------------------------------------// const String& IrrlichtTexture::getName() const { return d_name; } //----------------------------------------------------------------------------// const Sizef& IrrlichtTexture::getSize() const { return d_size; } //----------------------------------------------------------------------------// const Sizef& IrrlichtTexture::getOriginalDataSize() const { return d_dataSize; } //----------------------------------------------------------------------------// const Vector2f& IrrlichtTexture::getTexelScaling() const { return d_texelScaling; } //----------------------------------------------------------------------------// void IrrlichtTexture::loadFromFile(const String& filename, const String& resourceGroup) { // get and check existence of CEGUI::System object System* sys = System::getSingletonPtr(); if (!sys) CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: " "CEGUI::System object has not been created!")); // load file to memory via resource provider RawDataContainer texFile; sys->getResourceProvider()->loadRawDataContainer(filename, texFile, resourceGroup); Texture* res = sys->getImageCodec().load(texFile, this); // unload file data buffer sys->getResourceProvider()->unloadRawDataContainer(texFile); // throw exception if data was load loaded to texture. if (!res) CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: " + sys->getImageCodec().getIdentifierString() + " failed to load image '" + filename + "'.")); } //----------------------------------------------------------------------------// void IrrlichtTexture::loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format) { using namespace irr; if (!isPixelFormatSupported(pixel_format)) CEGUI_THROW(InvalidRequestException( "IrrlichtTexture::loadFromMemory: Data was supplied in an " "unsupported pixel format.")); freeIrrlichtTexture(); createIrrlichtTexture(buffer_size); d_size.d_width = static_cast<float>(d_texture->getSize().Width); d_size.d_height = static_cast<float>(d_texture->getSize().Height); d_dataSize = buffer_size; updateCachedScaleValues(); const size_t pix_sz = (pixel_format == PF_RGB) ? 3 : 4; const char* src = static_cast<const char*>(buffer); char* dest = static_cast<char*>(d_texture->lock()); // copy data into texture, swapping red & blue and creating alpha channel // values as needed. for (int j = 0; j < buffer_size.d_height; ++j) { for (int i = 0; i < buffer_size.d_width; ++i) { dest[i * 4 + 0] = src[i * pix_sz + 2]; dest[i * 4 + 1] = src[i * pix_sz + 1]; dest[i * 4 + 2] = src[i * pix_sz + 0]; dest[i * 4 + 3] = (pix_sz == 3) ? 0xFF : src[i * pix_sz + 3]; } src += static_cast<int>(buffer_size.d_width * pix_sz); dest += static_cast<int>(d_size.d_width * 4); } d_texture->unlock(); } //----------------------------------------------------------------------------// void IrrlichtTexture::blitFromMemory(void* sourceData, const Rectf& area) { if (!d_texture) return; const size_t pitch = d_texture->getPitch(); const uint32* src = static_cast<uint32*>(sourceData); uint32* dst = static_cast<uint32*>(d_texture->lock()); if (!dst) CEGUI_THROW(RendererException( "[IrrlichtRenderer] ITexture::lock failed.")); dst += static_cast<size_t>(area.top()) * (pitch / 4) + static_cast<size_t>(area.left()); const Sizef sz(area.getSize()); for (int j = 0; j < sz.d_height; ++j) { for (int i = 0; i < sz.d_width; ++i) { dst[i] = src[i]; } src += static_cast<int>(sz.d_width); dst += pitch / 4; } d_texture->unlock(); } //----------------------------------------------------------------------------// void IrrlichtTexture::blitToMemory(void* targetData) { if (!d_texture) return; const void* src = d_texture->lock(true); if (!src) CEGUI_THROW(RendererException( "[IrrlichtRenderer] ITexture::lock failed.")); memcpy(targetData, src, static_cast<size_t>(d_size.d_width * d_size.d_height) * 4); d_texture->unlock(); } //----------------------------------------------------------------------------// IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner, irr::video::IVideoDriver& driver, const String& name) : d_driver(driver), d_texture(0), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0), d_owner(owner), d_name(name) { } //----------------------------------------------------------------------------// IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner, irr::video::IVideoDriver& driver, const String& name, const String& filename, const String& resourceGroup) : d_driver(driver), d_texture(0), d_owner(owner), d_name(name) { loadFromFile(filename, resourceGroup); } //----------------------------------------------------------------------------// IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner, irr::video::IVideoDriver& driver, const String& name, const Sizef& size) : d_driver(driver), d_dataSize(size), d_owner(owner), d_name(name) { createIrrlichtTexture(size); d_size.d_width = static_cast<float>(d_texture->getSize().Width); d_size.d_height = static_cast<float>(d_texture->getSize().Height); updateCachedScaleValues(); } //----------------------------------------------------------------------------// IrrlichtTexture::~IrrlichtTexture() { freeIrrlichtTexture(); } //----------------------------------------------------------------------------// void IrrlichtTexture::createIrrlichtTexture(const Sizef& sz) { using namespace irr; const Sizef tex_sz(d_owner.getAdjustedTextureSize(sz)); #if CEGUI_IRR_SDK_VERSION >= 16 const core::dimension2d<u32> irr_sz( static_cast<u32>(tex_sz.d_width), static_cast<u32>(tex_sz.d_height)); #else const core::dimension2d<s32> irr_sz( static_cast<s32>(tex_sz.d_width), static_cast<s32>(tex_sz.d_height)); #endif // save texture creation state video::E_TEXTURE_CREATION_FLAG fmtflg; if (d_driver.getTextureCreationFlag(video::ETCF_ALWAYS_32_BIT)) fmtflg = video::ETCF_ALWAYS_32_BIT; else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_QUALITY)) fmtflg = video::ETCF_OPTIMIZED_FOR_QUALITY; else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED)) fmtflg = video::ETCF_OPTIMIZED_FOR_SPEED; else fmtflg = video::ETCF_ALWAYS_16_BIT; const bool tfmips = d_driver.getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS); const bool tfalpha = d_driver.getTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL); const bool tfnpot = d_driver.getTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2); // explicitly set all states to what we want d_driver.setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true); d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false); d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, false); d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, true); d_texture = d_driver.addTexture(irr_sz, getUniqueName().c_str(), irr::video::ECF_A8R8G8B8); // restore previous texture creation state d_driver.setTextureCreationFlag(fmtflg, true); d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, tfmips); d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, tfalpha); d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, tfnpot); // we use ARGB all the time for now, so throw if we gut something else! if(video::ECF_A8R8G8B8 != d_texture->getColorFormat()) CEGUI_THROW(RendererException( "IrrlichtTexture::loadFromMemory: texture did " "not have the correct format (ARGB)")); } //----------------------------------------------------------------------------// void IrrlichtTexture::freeIrrlichtTexture() { if (!d_texture) return; d_driver.removeTexture(d_texture); d_texture = 0; } //----------------------------------------------------------------------------// std::string IrrlichtTexture::getUniqueName() { char tmp[32]; sprintf(tmp, "irr_tex_%d", d_textureNumber++); return std::string(tmp); } //----------------------------------------------------------------------------// void IrrlichtTexture::setOriginalDataSize(const Sizef& sz) { d_dataSize = sz; updateCachedScaleValues(); } //----------------------------------------------------------------------------// void IrrlichtTexture::updateCachedScaleValues() { // // calculate what to use for x scale // const float orgW = d_dataSize.d_width; const float texW = d_size.d_width; // if texture and original data width are the same, scale is based // on the original size. // if texture is wider (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); // // calculate what to use for y scale // const float orgH = d_dataSize.d_height; const float texH = d_size.d_height; // if texture and original data height are the same, scale is based // on the original size. // if texture is taller (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); } //----------------------------------------------------------------------------// bool IrrlichtTexture::isPixelFormatSupported(const PixelFormat fmt) const { return fmt == PF_RGBA || fmt == PF_RGB; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>Fix: add support for building against 1.8 versions of irrlicht. Thanks to Freundlich.<commit_after>/*********************************************************************** filename: CEGUIIrrlichtTexture.cpp created: Tue Mar 3 2009 author: Paul D Turner (based on original code by Thomas Suter) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 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 #include "CEGUI/RendererModules/Irrlicht/Texture.h" #include "CEGUI/System.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodec.h" #include <irrlicht.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// uint32 IrrlichtTexture::d_textureNumber = 0; //----------------------------------------------------------------------------// void IrrlichtTexture::setIrrlichtTexture(irr::video::ITexture* tex) { d_texture = tex; if (d_texture) { d_size = d_dataSize = Sizef( static_cast<float>(d_texture->getSize().Width), static_cast<float>(d_texture->getSize().Height)); updateCachedScaleValues(); } } //----------------------------------------------------------------------------// irr::video::ITexture* IrrlichtTexture::getIrrlichtTexture() const { return d_texture; } //----------------------------------------------------------------------------// const String& IrrlichtTexture::getName() const { return d_name; } //----------------------------------------------------------------------------// const Sizef& IrrlichtTexture::getSize() const { return d_size; } //----------------------------------------------------------------------------// const Sizef& IrrlichtTexture::getOriginalDataSize() const { return d_dataSize; } //----------------------------------------------------------------------------// const Vector2f& IrrlichtTexture::getTexelScaling() const { return d_texelScaling; } //----------------------------------------------------------------------------// void IrrlichtTexture::loadFromFile(const String& filename, const String& resourceGroup) { // get and check existence of CEGUI::System object System* sys = System::getSingletonPtr(); if (!sys) CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: " "CEGUI::System object has not been created!")); // load file to memory via resource provider RawDataContainer texFile; sys->getResourceProvider()->loadRawDataContainer(filename, texFile, resourceGroup); Texture* res = sys->getImageCodec().load(texFile, this); // unload file data buffer sys->getResourceProvider()->unloadRawDataContainer(texFile); // throw exception if data was load loaded to texture. if (!res) CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: " + sys->getImageCodec().getIdentifierString() + " failed to load image '" + filename + "'.")); } //----------------------------------------------------------------------------// void IrrlichtTexture::loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format) { using namespace irr; if (!isPixelFormatSupported(pixel_format)) CEGUI_THROW(InvalidRequestException( "IrrlichtTexture::loadFromMemory: Data was supplied in an " "unsupported pixel format.")); freeIrrlichtTexture(); createIrrlichtTexture(buffer_size); d_size.d_width = static_cast<float>(d_texture->getSize().Width); d_size.d_height = static_cast<float>(d_texture->getSize().Height); d_dataSize = buffer_size; updateCachedScaleValues(); const size_t pix_sz = (pixel_format == PF_RGB) ? 3 : 4; const char* src = static_cast<const char*>(buffer); char* dest = static_cast<char*>(d_texture->lock()); // copy data into texture, swapping red & blue and creating alpha channel // values as needed. for (int j = 0; j < buffer_size.d_height; ++j) { for (int i = 0; i < buffer_size.d_width; ++i) { dest[i * 4 + 0] = src[i * pix_sz + 2]; dest[i * 4 + 1] = src[i * pix_sz + 1]; dest[i * 4 + 2] = src[i * pix_sz + 0]; dest[i * 4 + 3] = (pix_sz == 3) ? 0xFF : src[i * pix_sz + 3]; } src += static_cast<int>(buffer_size.d_width * pix_sz); dest += static_cast<int>(d_size.d_width * 4); } d_texture->unlock(); } //----------------------------------------------------------------------------// void IrrlichtTexture::blitFromMemory(void* sourceData, const Rectf& area) { if (!d_texture) return; const size_t pitch = d_texture->getPitch(); const uint32* src = static_cast<uint32*>(sourceData); uint32* dst = static_cast<uint32*>(d_texture->lock()); if (!dst) CEGUI_THROW(RendererException( "[IrrlichtRenderer] ITexture::lock failed.")); dst += static_cast<size_t>(area.top()) * (pitch / 4) + static_cast<size_t>(area.left()); const Sizef sz(area.getSize()); for (int j = 0; j < sz.d_height; ++j) { for (int i = 0; i < sz.d_width; ++i) { dst[i] = src[i]; } src += static_cast<int>(sz.d_width); dst += pitch / 4; } d_texture->unlock(); } //----------------------------------------------------------------------------// void IrrlichtTexture::blitToMemory(void* targetData) { if (!d_texture) return; #if (IRRLICHT_VERSION_MAJOR <= 1) && (IRRLICHT_VERSION_MINOR < 8) const void* src = d_texture->lock(true); #else const void* src = d_texture->lock(irr::video::ETLM_WRITE_ONLY); #endif if (!src) CEGUI_THROW(RendererException( "[IrrlichtRenderer] ITexture::lock failed.")); memcpy(targetData, src, static_cast<size_t>(d_size.d_width * d_size.d_height) * 4); d_texture->unlock(); } //----------------------------------------------------------------------------// IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner, irr::video::IVideoDriver& driver, const String& name) : d_driver(driver), d_texture(0), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0), d_owner(owner), d_name(name) { } //----------------------------------------------------------------------------// IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner, irr::video::IVideoDriver& driver, const String& name, const String& filename, const String& resourceGroup) : d_driver(driver), d_texture(0), d_owner(owner), d_name(name) { loadFromFile(filename, resourceGroup); } //----------------------------------------------------------------------------// IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner, irr::video::IVideoDriver& driver, const String& name, const Sizef& size) : d_driver(driver), d_dataSize(size), d_owner(owner), d_name(name) { createIrrlichtTexture(size); d_size.d_width = static_cast<float>(d_texture->getSize().Width); d_size.d_height = static_cast<float>(d_texture->getSize().Height); updateCachedScaleValues(); } //----------------------------------------------------------------------------// IrrlichtTexture::~IrrlichtTexture() { freeIrrlichtTexture(); } //----------------------------------------------------------------------------// void IrrlichtTexture::createIrrlichtTexture(const Sizef& sz) { using namespace irr; const Sizef tex_sz(d_owner.getAdjustedTextureSize(sz)); #if CEGUI_IRR_SDK_VERSION >= 16 const core::dimension2d<u32> irr_sz( static_cast<u32>(tex_sz.d_width), static_cast<u32>(tex_sz.d_height)); #else const core::dimension2d<s32> irr_sz( static_cast<s32>(tex_sz.d_width), static_cast<s32>(tex_sz.d_height)); #endif // save texture creation state video::E_TEXTURE_CREATION_FLAG fmtflg; if (d_driver.getTextureCreationFlag(video::ETCF_ALWAYS_32_BIT)) fmtflg = video::ETCF_ALWAYS_32_BIT; else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_QUALITY)) fmtflg = video::ETCF_OPTIMIZED_FOR_QUALITY; else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED)) fmtflg = video::ETCF_OPTIMIZED_FOR_SPEED; else fmtflg = video::ETCF_ALWAYS_16_BIT; const bool tfmips = d_driver.getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS); const bool tfalpha = d_driver.getTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL); const bool tfnpot = d_driver.getTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2); // explicitly set all states to what we want d_driver.setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true); d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false); d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, false); d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, true); d_texture = d_driver.addTexture(irr_sz, getUniqueName().c_str(), irr::video::ECF_A8R8G8B8); // restore previous texture creation state d_driver.setTextureCreationFlag(fmtflg, true); d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, tfmips); d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, tfalpha); d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, tfnpot); // we use ARGB all the time for now, so throw if we gut something else! if(video::ECF_A8R8G8B8 != d_texture->getColorFormat()) CEGUI_THROW(RendererException( "IrrlichtTexture::loadFromMemory: texture did " "not have the correct format (ARGB)")); } //----------------------------------------------------------------------------// void IrrlichtTexture::freeIrrlichtTexture() { if (!d_texture) return; d_driver.removeTexture(d_texture); d_texture = 0; } //----------------------------------------------------------------------------// std::string IrrlichtTexture::getUniqueName() { char tmp[32]; sprintf(tmp, "irr_tex_%d", d_textureNumber++); return std::string(tmp); } //----------------------------------------------------------------------------// void IrrlichtTexture::setOriginalDataSize(const Sizef& sz) { d_dataSize = sz; updateCachedScaleValues(); } //----------------------------------------------------------------------------// void IrrlichtTexture::updateCachedScaleValues() { // // calculate what to use for x scale // const float orgW = d_dataSize.d_width; const float texW = d_size.d_width; // if texture and original data width are the same, scale is based // on the original size. // if texture is wider (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); // // calculate what to use for y scale // const float orgH = d_dataSize.d_height; const float texH = d_size.d_height; // if texture and original data height are the same, scale is based // on the original size. // if texture is taller (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); } //----------------------------------------------------------------------------// bool IrrlichtTexture::isPixelFormatSupported(const PixelFormat fmt) const { return fmt == PF_RGBA || fmt == PF_RGB; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>// // Copyright (C) 2018 University of Amsterdam // // 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 "fsbmosf.h" #include <QGridLayout> #include <QLabel> #include <QNetworkAccessManager> #include <QUrl> #include <QNetworkRequest> #include <QNetworkReply> #include <QJsonDocument> #include <QJsonObject> #include <QJsonParseError> #include <QJsonArray> #include <QFile> #include "fsentry.h" #include "onlinedatamanager.h" #include "simplecrypt.h" #include "settings.h" const QString FSBMOSF::rootelementname = "Projects"; FSBMOSF::FSBMOSF(QObject *parent, QString root) :FSBModel (parent) { _dataManager = NULL; _manager = NULL; _isAuthenticated = false; _rootPath = _path = root; } FSBMOSF::~FSBMOSF() { } void FSBMOSF::setOnlineDataManager(OnlineDataManager *odm) { _dataManager = odm; _manager = odm->getNetworkAccessManager(OnlineDataManager::OSF); } void FSBMOSF::attemptToConnect() { QString password = _dataManager->getPassword(OnlineDataManager::OSF); QString username = _dataManager->getUsername(OnlineDataManager::OSF); if ( username=="" || password =="" ) { emit stopProcessing(); return; } if ( _isAuthenticated == false && _dataManager != NULL ) { emit hideAuthentication(); emit processingEntries(); bool authsuccess = _dataManager->authenticationSuccessful(OnlineDataManager::OSF); setAuthenticated(authsuccess); if (!authsuccess) emit entriesChanged(); } emit stopProcessing(); } bool FSBMOSF::requiresAuthentication() const { return true; } void FSBMOSF::authenticate(const QString &username, const QString &password) { bool success = false; if (_dataManager && username!="") { _dataManager->saveUsername(OnlineDataManager::OSF, username); _dataManager->setAuthentication(OnlineDataManager::OSF, username, password); success = _dataManager->authenticationSuccessful(OnlineDataManager::OSF); if (success) _dataManager->savePassword(OnlineDataManager::OSF, password); else _dataManager->removePassword(OnlineDataManager::OSF); } Settings::sync(); setAuthenticated(success); } void FSBMOSF::setAuthenticated(bool value) { if (value) { _isAuthenticated = true; emit authenticationSuccess(); refresh(); } else { _isAuthenticated = false; emit authenticationFail("Username and/or password are not correct. Please try again."); } } bool FSBMOSF::isAuthenticated() const { return _isAuthenticated; } void FSBMOSF::clearAuthentication() { _isAuthenticated = false; _dataManager->clearAuthentication(OnlineDataManager::OSF); _entries.clear(); _pathUrls.clear(); setPath(_rootPath); emit entriesChanged(); emit authenticationClear(); } void FSBMOSF::refresh() { if (_manager == NULL || _isAuthenticated == false) return; emit processingEntries(); _entries.clear(); if (_path == "Projects") loadProjects(); else { OnlineNodeData nodeData = _pathUrls[_path]; if (nodeData.isFolder) loadFilesAndFolders(QUrl(nodeData.contentsPath), nodeData.level + 1); if (nodeData.isComponent) loadFilesAndFolders(QUrl(nodeData.childrenPath), nodeData.level + 1); } } FSBMOSF::OnlineNodeData FSBMOSF::currentNodeData() { return _pathUrls[_path]; } void FSBMOSF::loadProjects() { QUrl url("https://api.osf.io/v2/users/me/nodes/"); parseProjects(url); } void FSBMOSF::parseProjects(QUrl url, bool recursive) { _isProjectPaginationCall = recursive; QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/vnd.api+json"); request.setRawHeader("Accept", "application/vnd.api+json"); QNetworkReply* reply = _manager->get(request); connect(reply, SIGNAL(finished()), this, SLOT(gotProjects())); } void FSBMOSF::gotProjects() { QNetworkReply *reply = (QNetworkReply*)this->sender(); if (reply->error() == QNetworkReply::NoError) { QByteArray data = reply->readAll(); QString dataString = (QString) data; QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(dataString.toUtf8(), &error); QJsonObject json = doc.object(); QJsonArray dataArray = json.value("data").toArray(); if ( dataArray.size() > 0 && !_isProjectPaginationCall) _entries.clear(); foreach (const QJsonValue & value, dataArray) { QJsonObject nodeObject = value.toObject(); QJsonObject attrObj = nodeObject.value("attributes").toObject(); QString category = attrObj.value("category").toString(); if (category != "project") continue; OnlineNodeData nodeData; nodeData.name = attrObj.value("title").toString(); nodeData.isFolder = true; nodeData.isComponent = true; nodeData.contentsPath = getRelationshipUrl(nodeObject, "files"); nodeData.childrenPath = getRelationshipUrl(nodeObject, "children"); QJsonObject topLinksObj = nodeObject.value("links").toObject(); nodeData.nodePath = topLinksObj.value("self").toString(); nodeData.level = 1; nodeData.canCreateFolders = false; nodeData.canCreateFiles = false; QString path = _path + "/" + nodeData.name; _entries.append(createEntry(path, FSEntry::Folder)); _pathUrls[path] = nodeData; } QJsonObject links = json.value("links").toObject(); QJsonValue nextProjects = links.value("next"); if (nextProjects.isNull() == false) parseProjects(QUrl(nextProjects.toString()), true); else emit entriesChanged(); } reply->deleteLater(); } void FSBMOSF::loadFilesAndFolders(QUrl url, int level) { parseFilesAndFolders(url, level); } void FSBMOSF::parseFilesAndFolders(QUrl url, int level, bool recursive) { _level = level; _isPaginationCall = recursive; QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/vnd.api+json"); request.setRawHeader("Accept", "application/vnd.api+json"); QNetworkReply* reply = _manager->get(request); connect(reply, SIGNAL(finished()), this, SLOT(gotFilesAndFolders())); } void FSBMOSF::gotFilesAndFolders() { QNetworkReply *reply = (QNetworkReply*)this->sender(); bool finished = false; if (reply->error() == QNetworkReply::NoError) { QByteArray data = reply->readAll(); QString dataString = (QString) data; QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(dataString.toUtf8(), &error); QJsonObject json = doc.object(); QJsonArray dataArray = json.value("data").toArray(); if ( dataArray.size() > 0 && !_isPaginationCall) _entries.clear(); foreach (const QJsonValue & value, dataArray) { QJsonObject nodeObject = value.toObject(); OnlineNodeData nodeData; nodeData.isComponent = nodeObject.value("type").toString() == "nodes"; FSEntry::EntryType entryType = FSEntry::Other; QJsonObject attrObj = nodeObject.value("attributes").toObject(); if (nodeData.isComponent == false) { QString kind = attrObj.value("kind").toString(); if (kind != "folder" && kind != "file") continue; nodeData.name = attrObj.value("name").toString(); if (kind == "folder") entryType = FSEntry::Folder; else if (nodeData.name.endsWith(".jasp", Qt::CaseInsensitive)) entryType = FSEntry::JASP; else if (nodeData.name.endsWith(".csv", Qt::CaseInsensitive) || nodeData.name.endsWith(".txt", Qt::CaseInsensitive)) entryType = FSEntry::CSV; else if (nodeData.name.endsWith(".html", Qt::CaseInsensitive) || nodeData.name.endsWith(".pdf", Qt::CaseInsensitive)) entryType = FSEntry::Other; else if (nodeData.name.endsWith(".spss", Qt::CaseInsensitive)) entryType = FSEntry::SPSS; else continue; } else { entryType = FSEntry::Folder; nodeData.name = attrObj.value("title").toString(); } if (entryType == FSEntry::Folder) { nodeData.contentsPath = getRelationshipUrl(nodeObject, "files"); nodeData.childrenPath = getRelationshipUrl(nodeObject, "children"); QJsonObject topLinksObj = nodeObject.value("links").toObject(); if (nodeData.isComponent) nodeData.nodePath = topLinksObj.value("self").toString(); else nodeData.nodePath = topLinksObj.value("info").toString(); nodeData.uploadPath = topLinksObj.value("upload").toString(); nodeData.isFolder = true; nodeData.canCreateFolders = topLinksObj.contains("new_folder"); nodeData.canCreateFiles = topLinksObj.contains("upload"); if (nodeData.nodePath == "") nodeData.nodePath = reply->url().toString() + "#folder://" + nodeData.name; } else { QJsonObject linksObj = nodeObject.value("links").toObject(); nodeData.isFolder = false; nodeData.uploadPath = linksObj.value("upload").toString(); nodeData.downloadPath = linksObj.value("download").toString(); nodeData.nodePath = linksObj.value("info").toString(); nodeData.canCreateFolders = false; nodeData.canCreateFiles = false; } QString path = _path + "/" + nodeData.name; nodeData.level = _level; _entries.append(createEntry(path, entryType)); _pathUrls[path] = nodeData; } QJsonObject contentLevelLinks = json.value("links").toObject(); QJsonValue nextContentList = contentLevelLinks.value("next"); if (nextContentList.isNull() == false) parseFilesAndFolders(QUrl(nextContentList.toString()), _level + 1, true); else finished = true; } if (finished) emit entriesChanged(); reply->deleteLater(); } QString FSBMOSF::getRelationshipUrl(QJsonObject nodeObject, QString name) { QJsonObject relationshipsObj = nodeObject.value("relationships").toObject(); if (relationshipsObj.contains(name) == false) return ""; QJsonObject filesObj = relationshipsObj.value(name).toObject(); QJsonObject linksObj = filesObj.value("links").toObject(); QJsonObject relatedObj = linksObj.value("related").toObject(); return relatedObj.value("href").toString(); } FSBMOSF::OnlineNodeData FSBMOSF::getNodeData(QString key) { return _pathUrls[key]; } <commit_msg>Add sav files in OSF<commit_after>// // Copyright (C) 2018 University of Amsterdam // // 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 "fsbmosf.h" #include <QGridLayout> #include <QLabel> #include <QNetworkAccessManager> #include <QUrl> #include <QNetworkRequest> #include <QNetworkReply> #include <QJsonDocument> #include <QJsonObject> #include <QJsonParseError> #include <QJsonArray> #include <QFile> #include "fsentry.h" #include "onlinedatamanager.h" #include "simplecrypt.h" #include "settings.h" const QString FSBMOSF::rootelementname = "Projects"; FSBMOSF::FSBMOSF(QObject *parent, QString root) :FSBModel (parent) { _dataManager = NULL; _manager = NULL; _isAuthenticated = false; _rootPath = _path = root; } FSBMOSF::~FSBMOSF() { } void FSBMOSF::setOnlineDataManager(OnlineDataManager *odm) { _dataManager = odm; _manager = odm->getNetworkAccessManager(OnlineDataManager::OSF); } void FSBMOSF::attemptToConnect() { QString password = _dataManager->getPassword(OnlineDataManager::OSF); QString username = _dataManager->getUsername(OnlineDataManager::OSF); if ( username=="" || password =="" ) { emit stopProcessing(); return; } if ( _isAuthenticated == false && _dataManager != NULL ) { emit hideAuthentication(); emit processingEntries(); bool authsuccess = _dataManager->authenticationSuccessful(OnlineDataManager::OSF); setAuthenticated(authsuccess); if (!authsuccess) emit entriesChanged(); } emit stopProcessing(); } bool FSBMOSF::requiresAuthentication() const { return true; } void FSBMOSF::authenticate(const QString &username, const QString &password) { bool success = false; if (_dataManager && username!="") { _dataManager->saveUsername(OnlineDataManager::OSF, username); _dataManager->setAuthentication(OnlineDataManager::OSF, username, password); success = _dataManager->authenticationSuccessful(OnlineDataManager::OSF); if (success) _dataManager->savePassword(OnlineDataManager::OSF, password); else _dataManager->removePassword(OnlineDataManager::OSF); } Settings::sync(); setAuthenticated(success); } void FSBMOSF::setAuthenticated(bool value) { if (value) { _isAuthenticated = true; emit authenticationSuccess(); refresh(); } else { _isAuthenticated = false; emit authenticationFail("Username and/or password are not correct. Please try again."); } } bool FSBMOSF::isAuthenticated() const { return _isAuthenticated; } void FSBMOSF::clearAuthentication() { _isAuthenticated = false; _dataManager->clearAuthentication(OnlineDataManager::OSF); _entries.clear(); _pathUrls.clear(); setPath(_rootPath); emit entriesChanged(); emit authenticationClear(); } void FSBMOSF::refresh() { if (_manager == NULL || _isAuthenticated == false) return; emit processingEntries(); _entries.clear(); if (_path == "Projects") loadProjects(); else { OnlineNodeData nodeData = _pathUrls[_path]; if (nodeData.isFolder) loadFilesAndFolders(QUrl(nodeData.contentsPath), nodeData.level + 1); if (nodeData.isComponent) loadFilesAndFolders(QUrl(nodeData.childrenPath), nodeData.level + 1); } } FSBMOSF::OnlineNodeData FSBMOSF::currentNodeData() { return _pathUrls[_path]; } void FSBMOSF::loadProjects() { QUrl url("https://api.osf.io/v2/users/me/nodes/"); parseProjects(url); } void FSBMOSF::parseProjects(QUrl url, bool recursive) { _isProjectPaginationCall = recursive; QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/vnd.api+json"); request.setRawHeader("Accept", "application/vnd.api+json"); QNetworkReply* reply = _manager->get(request); connect(reply, SIGNAL(finished()), this, SLOT(gotProjects())); } void FSBMOSF::gotProjects() { QNetworkReply *reply = (QNetworkReply*)this->sender(); if (reply->error() == QNetworkReply::NoError) { QByteArray data = reply->readAll(); QString dataString = (QString) data; QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(dataString.toUtf8(), &error); QJsonObject json = doc.object(); QJsonArray dataArray = json.value("data").toArray(); if ( dataArray.size() > 0 && !_isProjectPaginationCall) _entries.clear(); foreach (const QJsonValue & value, dataArray) { QJsonObject nodeObject = value.toObject(); QJsonObject attrObj = nodeObject.value("attributes").toObject(); QString category = attrObj.value("category").toString(); if (category != "project") continue; OnlineNodeData nodeData; nodeData.name = attrObj.value("title").toString(); nodeData.isFolder = true; nodeData.isComponent = true; nodeData.contentsPath = getRelationshipUrl(nodeObject, "files"); nodeData.childrenPath = getRelationshipUrl(nodeObject, "children"); QJsonObject topLinksObj = nodeObject.value("links").toObject(); nodeData.nodePath = topLinksObj.value("self").toString(); nodeData.level = 1; nodeData.canCreateFolders = false; nodeData.canCreateFiles = false; QString path = _path + "/" + nodeData.name; _entries.append(createEntry(path, FSEntry::Folder)); _pathUrls[path] = nodeData; } QJsonObject links = json.value("links").toObject(); QJsonValue nextProjects = links.value("next"); if (nextProjects.isNull() == false) parseProjects(QUrl(nextProjects.toString()), true); else emit entriesChanged(); } reply->deleteLater(); } void FSBMOSF::loadFilesAndFolders(QUrl url, int level) { parseFilesAndFolders(url, level); } void FSBMOSF::parseFilesAndFolders(QUrl url, int level, bool recursive) { _level = level; _isPaginationCall = recursive; QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/vnd.api+json"); request.setRawHeader("Accept", "application/vnd.api+json"); QNetworkReply* reply = _manager->get(request); connect(reply, SIGNAL(finished()), this, SLOT(gotFilesAndFolders())); } void FSBMOSF::gotFilesAndFolders() { QNetworkReply *reply = (QNetworkReply*)this->sender(); bool finished = false; if (reply->error() == QNetworkReply::NoError) { QByteArray data = reply->readAll(); QString dataString = (QString) data; QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(dataString.toUtf8(), &error); QJsonObject json = doc.object(); QJsonArray dataArray = json.value("data").toArray(); if ( dataArray.size() > 0 && !_isPaginationCall) _entries.clear(); foreach (const QJsonValue & value, dataArray) { QJsonObject nodeObject = value.toObject(); OnlineNodeData nodeData; nodeData.isComponent = nodeObject.value("type").toString() == "nodes"; FSEntry::EntryType entryType = FSEntry::Other; QJsonObject attrObj = nodeObject.value("attributes").toObject(); if (nodeData.isComponent == false) { QString kind = attrObj.value("kind").toString(); if (kind != "folder" && kind != "file") continue; nodeData.name = attrObj.value("name").toString(); if (kind == "folder") entryType = FSEntry::Folder; else if (nodeData.name.endsWith(".jasp", Qt::CaseInsensitive)) entryType = FSEntry::JASP; else if (nodeData.name.endsWith(".csv", Qt::CaseInsensitive) || nodeData.name.endsWith(".txt", Qt::CaseInsensitive)) entryType = FSEntry::CSV; else if (nodeData.name.endsWith(".html", Qt::CaseInsensitive) || nodeData.name.endsWith(".pdf", Qt::CaseInsensitive)) entryType = FSEntry::Other; else if (nodeData.name.endsWith(".spss", Qt::CaseInsensitive) || nodeData.name.endsWith(".sav", Qt::CaseInsensitive)) entryType = FSEntry::SPSS; else continue; } else { entryType = FSEntry::Folder; nodeData.name = attrObj.value("title").toString(); } if (entryType == FSEntry::Folder) { nodeData.contentsPath = getRelationshipUrl(nodeObject, "files"); nodeData.childrenPath = getRelationshipUrl(nodeObject, "children"); QJsonObject topLinksObj = nodeObject.value("links").toObject(); if (nodeData.isComponent) nodeData.nodePath = topLinksObj.value("self").toString(); else nodeData.nodePath = topLinksObj.value("info").toString(); nodeData.uploadPath = topLinksObj.value("upload").toString(); nodeData.isFolder = true; nodeData.canCreateFolders = topLinksObj.contains("new_folder"); nodeData.canCreateFiles = topLinksObj.contains("upload"); if (nodeData.nodePath == "") nodeData.nodePath = reply->url().toString() + "#folder://" + nodeData.name; } else { QJsonObject linksObj = nodeObject.value("links").toObject(); nodeData.isFolder = false; nodeData.uploadPath = linksObj.value("upload").toString(); nodeData.downloadPath = linksObj.value("download").toString(); nodeData.nodePath = linksObj.value("info").toString(); nodeData.canCreateFolders = false; nodeData.canCreateFiles = false; } QString path = _path + "/" + nodeData.name; nodeData.level = _level; _entries.append(createEntry(path, entryType)); _pathUrls[path] = nodeData; } QJsonObject contentLevelLinks = json.value("links").toObject(); QJsonValue nextContentList = contentLevelLinks.value("next"); if (nextContentList.isNull() == false) parseFilesAndFolders(QUrl(nextContentList.toString()), _level + 1, true); else finished = true; } if (finished) emit entriesChanged(); reply->deleteLater(); } QString FSBMOSF::getRelationshipUrl(QJsonObject nodeObject, QString name) { QJsonObject relationshipsObj = nodeObject.value("relationships").toObject(); if (relationshipsObj.contains(name) == false) return ""; QJsonObject filesObj = relationshipsObj.value(name).toObject(); QJsonObject linksObj = filesObj.value("links").toObject(); QJsonObject relatedObj = linksObj.value("related").toObject(); return relatedObj.value("href").toString(); } FSBMOSF::OnlineNodeData FSBMOSF::getNodeData(QString key) { return _pathUrls[key]; } <|endoftext|>
<commit_before>// // RewardedAdSceneTester.cpp // ee_x_test_mobile // // Created by eps on 10/7/20. // #include "RewardedAdSceneTester.hpp" #include <cocos2d.h> #include <ui/CocosGUI.h> #include <ee/Cpp.hpp> namespace eetest { namespace config { #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID constexpr auto iron_source_app = "d8d36e59"; constexpr auto unity_ads_app = "3843671"; constexpr auto admob_rewarded_ad = "ca-app-pub-2101587572072038/4784852460"; constexpr auto facebook_ads_rewarded_ad = "1095721240884103_1095725130883714"; #else // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID constexpr auto iron_source_app = "d8d2fb49"; constexpr auto unity_ads_app = "3843670"; constexpr auto admob_rewarded_ad = "ca-app-pub-2101587572072038/7027872422"; constexpr auto facebook_ads_rewarded_ad = "1095721240884103_1095724794217081"; #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID constexpr auto unity_ads_rewarded_ad = "rewardedVideo"; constexpr auto iron_source_rewarded_ad = "DefaultRewardedVideo"; } // namespace config using Self = RewardedAdSceneTester; Self::RewardedAdSceneTester() : scene_(nullptr) {} void Self::initialize() { adMob_ = ee::PluginManager::createPlugin<ee::IAdMob>(); facebookAds_ = ee::PluginManager::createPlugin<ee::IFacebookAds>(); ironSource_ = ee::PluginManager::createPlugin<ee::IIronSource>(); unityAds_ = ee::PluginManager::createPlugin<ee::IUnityAds>(); ee::noAwait([this]() -> ee::Task<> { co_await adMob_->initialize(); co_await ironSource_->initialize(config::iron_source_app); co_await unityAds_->initialize(config::unity_ads_app, false); }); handle_ = std::make_unique<ee::ObserverHandle>(); scene_ = cocos2d::Scene::create(); scene_->retain(); auto ad = std::make_shared<ee::MultiRewardedAd>(); (*ad) .addItem(adMob_->createRewardedAd(config::admob_rewarded_ad)) .addItem( facebookAds_->createRewardedAd(config::facebook_ads_rewarded_ad)) .addItem(ironSource_->createRewardedAd(config::iron_source_rewarded_ad)) .addItem(unityAds_->createRewardedAd(config::unity_ads_rewarded_ad)); rewardedAd_ = ad; auto winSize = cocos2d::Director::getInstance()->getWinSize(); auto statusLabel = cocos2d::ui::Text::create(); statusLabel->setContentSize(cocos2d::Size(200, 60)); statusLabel->setPosition( cocos2d::Point(winSize.width / 2, winSize.height / 2 + 100)); statusLabel->setString("---"); auto loadButton = cocos2d::ui::Button::create(); loadButton->setContentSize(cocos2d::Size(150, 80)); loadButton->setPosition( cocos2d::Point(winSize.width / 2, winSize.height / 2 + 50)); loadButton->setTitleText("Load"); loadButton->addClickEventListener(std::bind([ad, statusLabel] { // if (ad->isLoaded()) { statusLabel->setString("Loaded"); } else { ee::noAwait(ad->load()); } })); auto resultLabel = cocos2d::ui::Text::create(); resultLabel->setContentSize(cocos2d::Size(200, 60)); resultLabel->setPosition( cocos2d::Point(winSize.width / 2, winSize.height / 2 - 0)); resultLabel->setString("---"); auto watchButton = cocos2d::ui::Button::create(); watchButton->setContentSize(cocos2d::Size(150, 80)); watchButton->setPosition( cocos2d::Point(winSize.width / 2, winSize.height / 2 - 50)); watchButton->setTitleText("Watch"); watchButton->addClickEventListener( std::bind([ad, statusLabel, resultLabel] { // ee::noAwait([ad, statusLabel, resultLabel]() -> ee::Task<> { statusLabel->setString("---"); auto result = co_await ad->show(); switch (result) { case ee::IRewardedAdResult::Canceled: { resultLabel->setString("Canceled"); break; } case ee::IRewardedAdResult::Completed: { resultLabel->setString("Completed"); break; } case ee::IRewardedAdResult::Failed: { resultLabel->setString("Failed"); break; } } if (ad->isLoaded()) { statusLabel->setString("Loaded"); } }); })); scene_->addChild(statusLabel); scene_->addChild(loadButton); scene_->addChild(resultLabel); scene_->addChild(watchButton); handle_->bind(*ad).addObserver({ .onLoaded = [statusLabel] { // statusLabel->setString("Loaded"); }, }); } void Self::destroy() { scene_->release(); scene_ = nullptr; } void Self::start() { cocos2d::Director::getInstance()->pushScene(scene_); } void Self::stop() { cocos2d::Director::getInstance()->popScene(); } } // namespace eetest <commit_msg>Fix test scene.<commit_after>// // RewardedAdSceneTester.cpp // ee_x_test_mobile // // Created by eps on 10/7/20. // #include "RewardedAdSceneTester.hpp" #include <cocos2d.h> #include <ui/CocosGUI.h> #include <ee/Cpp.hpp> namespace eetest { namespace config { #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID constexpr auto iron_source_app = "d8d36e59"; constexpr auto unity_ads_app = "3843671"; constexpr auto admob_rewarded_ad = "ca-app-pub-2101587572072038/4784852460"; constexpr auto facebook_ads_rewarded_ad = "1095721240884103_1095725130883714"; #else // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID constexpr auto iron_source_app = "d8d2fb49"; constexpr auto unity_ads_app = "3843670"; constexpr auto admob_rewarded_ad = "ca-app-pub-2101587572072038/7027872422"; constexpr auto facebook_ads_rewarded_ad = "1095721240884103_1095724794217081"; #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID constexpr auto unity_ads_rewarded_ad = "rewardedVideo"; constexpr auto iron_source_rewarded_ad = "DefaultRewardedVideo"; } // namespace config using Self = RewardedAdSceneTester; Self::RewardedAdSceneTester() : scene_(nullptr) {} void Self::initialize() { adMob_ = ee::PluginManager::createPlugin<ee::IAdMob>(); facebookAds_ = ee::PluginManager::createPlugin<ee::IFacebookAds>(); ironSource_ = ee::PluginManager::createPlugin<ee::IIronSource>(); unityAds_ = ee::PluginManager::createPlugin<ee::IUnityAds>(); handle_ = std::make_unique<ee::ObserverHandle>(); scene_ = cocos2d::Scene::create(); scene_->retain(); auto winSize = cocos2d::Director::getInstance()->getWinSize(); auto statusLabel = cocos2d::ui::Text::create(); statusLabel->setContentSize(cocos2d::Size(200, 60)); statusLabel->setPosition( cocos2d::Point(winSize.width / 2, winSize.height / 2 + 100)); statusLabel->setString("---"); auto loadButton = cocos2d::ui::Button::create(); loadButton->setContentSize(cocos2d::Size(150, 80)); loadButton->setPosition( cocos2d::Point(winSize.width / 2, winSize.height / 2 + 50)); loadButton->setTitleText("Load"); loadButton->addClickEventListener(std::bind([this, statusLabel] { // if (rewardedAd_->isLoaded()) { statusLabel->setString("Loaded"); } else { ee::noAwait(rewardedAd_->load()); } })); auto resultLabel = cocos2d::ui::Text::create(); resultLabel->setContentSize(cocos2d::Size(200, 60)); resultLabel->setPosition( cocos2d::Point(winSize.width / 2, winSize.height / 2 - 0)); resultLabel->setString("---"); auto watchButton = cocos2d::ui::Button::create(); watchButton->setContentSize(cocos2d::Size(150, 80)); watchButton->setPosition( cocos2d::Point(winSize.width / 2, winSize.height / 2 - 50)); watchButton->setTitleText("Watch"); watchButton->addClickEventListener( std::bind([this, statusLabel, resultLabel] { // ee::noAwait([this, statusLabel, resultLabel]() -> ee::Task<> { statusLabel->setString("---"); auto result = co_await rewardedAd_->show(); switch (result) { case ee::IRewardedAdResult::Canceled: { resultLabel->setString("Canceled"); break; } case ee::IRewardedAdResult::Completed: { resultLabel->setString("Completed"); break; } case ee::IRewardedAdResult::Failed: { resultLabel->setString("Failed"); break; } } if (rewardedAd_->isLoaded()) { statusLabel->setString("Loaded"); } }); })); scene_->addChild(statusLabel); scene_->addChild(loadButton); scene_->addChild(resultLabel); scene_->addChild(watchButton); ee::noAwait([this, statusLabel]() -> ee::Task<> { co_await adMob_->initialize(); co_await facebookAds_->initialize(); co_await ironSource_->initialize(config::iron_source_app); co_await unityAds_->initialize(config::unity_ads_app, false); auto ad = std::make_shared<ee::MultiRewardedAd>(); (*ad) .addItem(adMob_->createRewardedAd(config::admob_rewarded_ad)) .addItem(facebookAds_->createRewardedAd( config::facebook_ads_rewarded_ad)) .addItem( ironSource_->createRewardedAd(config::iron_source_rewarded_ad)) .addItem( unityAds_->createRewardedAd(config::unity_ads_rewarded_ad)); handle_->bind(*ad).addObserver({ .onLoaded = [statusLabel] { // statusLabel->setString("Loaded"); }, }); rewardedAd_ = ad; }); } void Self::destroy() { scene_->release(); scene_ = nullptr; } void Self::start() { cocos2d::Director::getInstance()->pushScene(scene_); } void Self::stop() { cocos2d::Director::getInstance()->popScene(); } } // namespace eetest <|endoftext|>
<commit_before>/* Copyright (C) 2014 The gtkmm Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ // This test case is a result of https://bugzilla.gnome.org/show_bug.cgi?id=731444 // Bug 731444 - gtkmm::builder - derived widget's destructor is not called -> memory leaks #include <iostream> #include <cstring> #include <gtkmm.h> namespace { const char gladefile[] = "<?xml version='1.0' encoding='UTF-8'?>" "<!-- Generated with glade 3.16.1 -->" "<interface>" "<requires lib='gtk+' version='3.10'/>" "<object class='GtkWindow' id='main_window'>" "<property name='can_focus'>False</property>" "<property name='title' translatable='yes'>Gtk::Builder ref count</property>" "<property name='default_width'>440</property>" "<property name='default_height'>150</property>" "<child>" "<object class='GtkBox' id='vbox'>" "<property name='visible'>True</property>" "<property name='can_focus'>False</property>" "<property name='orientation'>vertical</property>" "<child>" "<object class='GtkButton' id='derived_button'>" "<property name='label' translatable='yes'>DerivedButton</property>" "<property name='visible'>True</property>" "<property name='can_focus'>True</property>" "<property name='receives_default'>True</property>" "</object>" "<packing>" "<property name='expand'>False</property>" "<property name='fill'>True</property>" "<property name='position'>0</property>" "</packing>" "</child>" "<child>" "<object class='GtkButton' id='standard_button'>" "<property name='label' translatable='yes'>Gtk::Button</property>" "<property name='visible'>True</property>" "<property name='can_focus'>True</property>" "<property name='receives_default'>True</property>" "</object>" "<packing>" "<property name='expand'>False</property>" "<property name='fill'>True</property>" "<property name='position'>1</property>" "</packing>" "</child>" "</object>" "</child>" "</object>" "<object class='GtkButton' id='orphaned_button'>" "<property name='label' translatable='yes'>Gtk::Button</property>" "<property name='visible'>True</property>" "<property name='can_focus'>True</property>" "<property name='receives_default'>True</property>" "</object>" "</interface>"; void on_managed_button_deleted(sigc::notifiable* /* data */) { std::cout << "Gtk::Button in window deleted" << std::endl; } void on_orphaned_button_deleted(sigc::notifiable* /* data */) { std::cout << "Orphaned Gtk::Button deleted" << std::endl; } class DerivedButton : public Gtk::Button { public: DerivedButton(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& /* refBuilder */, const Glib::ustring icon_name = Glib::ustring()) : Gtk::Button(cobject) { std::cout << "DerivedButton::ctor" << std::endl; if (!icon_name.empty()) set_icon_name(icon_name); } virtual ~DerivedButton() { std::cout << "DerivedButton::dtor" << std::endl; } }; class MainWindow : public Gtk::Window { public: MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refBuilder) : Gtk::Window(cobject), m_pDerivedButton(nullptr), m_pStandardButton(nullptr) { std::cout << "MainWindow::ctor" << std::endl; // Called twice just to see if two calls affect the ref count. Gtk::Builder::get_widget_derived(refBuilder, "derived_button", m_pDerivedButton, "face-smile"); Gtk::Builder::get_widget_derived(refBuilder, "derived_button", m_pDerivedButton); refBuilder->get_widget("standard_button", m_pStandardButton); refBuilder->get_widget("standard_button", m_pStandardButton); m_pStandardButton->add_destroy_notify_callback(nullptr, on_managed_button_deleted); } virtual ~MainWindow() { std::cout << "MainWindow::dtor" << std::endl; } const DerivedButton* get_derived_button() const { return m_pDerivedButton; } const Gtk::Button* get_standard_button() const { return m_pStandardButton; } private: DerivedButton* m_pDerivedButton; Gtk::Button* m_pStandardButton; }; } // end of anonymous namespace int main(int argc, char* argv[]) { // With the command-line parameter --p-a-d, ref counts are printed // after the widgets have been deleted. This means accesses to deallocated // memory, possibly with bad side effects. bool print_after_deletion = false; int argc1 = argc; if (argc > 1 && std::strcmp(argv[1], "--p-a-d") == 0) { print_after_deletion = true; argc1 = 1; // Don't give the command line arguments to Gtk::Application. } auto app = Gtk::Application::create(); auto builder = Gtk::Builder::create_from_string(gladefile); MainWindow* main_win = nullptr; Gtk::Builder::get_widget_derived(builder, "main_window", main_win); Gtk::Button* orph_button = nullptr; builder->get_widget("orphaned_button", orph_button); orph_button->add_destroy_notify_callback(nullptr, on_orphaned_button_deleted); const GObject* const window = (GObject*)main_win->gobj(); const GObject* const orphaned_button = (GObject*)orph_button->gobj(); const GObject* const derived_button = (GObject*)main_win->get_derived_button()->gobj(); const GObject* const standard_button = (GObject*)main_win->get_standard_button()->gobj(); std::cout << "Before app->run(*main_win, argc1, argv)" << std::endl << " ref_count(MainWindow)=" << window->ref_count << std::endl << " ref_count(DerivedButton)=" << derived_button->ref_count << std::endl << " ref_count(Gtk::Button)=" << standard_button->ref_count << std::endl << " ref_count(orphaned_button)=" << orphaned_button->ref_count << std::endl; const int result = app->run(*main_win, argc1, argv); std::cout << "After app->run(*main_win, argc1, argv)" << std::endl << " ref_count(MainWindow)=" << window->ref_count << std::endl << " ref_count(DerivedButton)=" << derived_button->ref_count << std::endl << " ref_count(Gtk::Button)=" << standard_button->ref_count << std::endl << " ref_count(orphaned_button)=" << orphaned_button->ref_count << std::endl; delete main_win; std::cout << "After delete main_win" << std::endl << " ref_count(MainWindow)=" << window->ref_count << std::endl << " ref_count(DerivedButton)=" << derived_button->ref_count << std::endl << " ref_count(Gtk::Button)=" << standard_button->ref_count << std::endl << " ref_count(orphaned_button)=" << orphaned_button->ref_count << std::endl; builder.reset(); if (print_after_deletion) { // If Builder is correct, this code will access deallocated memory. std::cout << "After builder.reset()" << std::endl << " ref_count(MainWindow)=" << window->ref_count << std::endl << " ref_count(DerivedButton)=" << derived_button->ref_count << std::endl << " ref_count(Gtk::Button)=" << standard_button->ref_count << std::endl << " ref_count(orphaned_button)=" << orphaned_button->ref_count << std::endl; } return result; } <commit_msg>tests/builder: Drop .ui properties gone in GTK 4<commit_after>/* Copyright (C) 2014 The gtkmm Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ // This test case is a result of https://bugzilla.gnome.org/show_bug.cgi?id=731444 // Bug 731444 - gtkmm::builder - derived widget's destructor is not called -> memory leaks #include <iostream> #include <cstring> #include <gtkmm.h> namespace { const char gladefile[] = "<?xml version='1.0' encoding='UTF-8'?>" "<!-- Generated with glade 3.16.1 -->" "<interface>" "<requires lib='gtk+' version='3.10'/>" "<object class='GtkWindow' id='main_window'>" "<property name='can_focus'>False</property>" "<property name='title' translatable='yes'>Gtk::Builder ref count</property>" "<property name='default_width'>440</property>" "<property name='default_height'>150</property>" "<child>" "<object class='GtkBox' id='vbox'>" "<property name='can_focus'>False</property>" "<property name='orientation'>vertical</property>" "<child>" "<object class='GtkButton' id='derived_button'>" "<property name='label' translatable='yes'>DerivedButton</property>" "<property name='can_focus'>True</property>" "<property name='receives_default'>True</property>" "</object>" "<packing>" "<property name='position'>0</property>" "</packing>" "</child>" "<child>" "<object class='GtkButton' id='standard_button'>" "<property name='label' translatable='yes'>Gtk::Button</property>" "<property name='can_focus'>True</property>" "<property name='receives_default'>True</property>" "</object>" "<packing>" "<property name='position'>1</property>" "</packing>" "</child>" "</object>" "</child>" "</object>" "<object class='GtkButton' id='orphaned_button'>" "<property name='label' translatable='yes'>Gtk::Button</property>" "<property name='can_focus'>True</property>" "<property name='receives_default'>True</property>" "</object>" "</interface>"; void on_managed_button_deleted(sigc::notifiable* /* data */) { std::cout << "Gtk::Button in window deleted" << std::endl; } void on_orphaned_button_deleted(sigc::notifiable* /* data */) { std::cout << "Orphaned Gtk::Button deleted" << std::endl; } class DerivedButton : public Gtk::Button { public: DerivedButton(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& /* refBuilder */, const Glib::ustring icon_name = Glib::ustring()) : Gtk::Button(cobject) { std::cout << "DerivedButton::ctor" << std::endl; if (!icon_name.empty()) set_icon_name(icon_name); } virtual ~DerivedButton() { std::cout << "DerivedButton::dtor" << std::endl; } }; class MainWindow : public Gtk::Window { public: MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refBuilder) : Gtk::Window(cobject), m_pDerivedButton(nullptr), m_pStandardButton(nullptr) { std::cout << "MainWindow::ctor" << std::endl; // Called twice just to see if two calls affect the ref count. Gtk::Builder::get_widget_derived(refBuilder, "derived_button", m_pDerivedButton, "face-smile"); Gtk::Builder::get_widget_derived(refBuilder, "derived_button", m_pDerivedButton); refBuilder->get_widget("standard_button", m_pStandardButton); refBuilder->get_widget("standard_button", m_pStandardButton); m_pStandardButton->add_destroy_notify_callback(nullptr, on_managed_button_deleted); } virtual ~MainWindow() { std::cout << "MainWindow::dtor" << std::endl; } const DerivedButton* get_derived_button() const { return m_pDerivedButton; } const Gtk::Button* get_standard_button() const { return m_pStandardButton; } private: DerivedButton* m_pDerivedButton; Gtk::Button* m_pStandardButton; }; } // end of anonymous namespace int main(int argc, char* argv[]) { // With the command-line parameter --p-a-d, ref counts are printed // after the widgets have been deleted. This means accesses to deallocated // memory, possibly with bad side effects. bool print_after_deletion = false; int argc1 = argc; if (argc > 1 && std::strcmp(argv[1], "--p-a-d") == 0) { print_after_deletion = true; argc1 = 1; // Don't give the command line arguments to Gtk::Application. } auto app = Gtk::Application::create(); auto builder = Gtk::Builder::create_from_string(gladefile); MainWindow* main_win = nullptr; Gtk::Builder::get_widget_derived(builder, "main_window", main_win); Gtk::Button* orph_button = nullptr; builder->get_widget("orphaned_button", orph_button); orph_button->add_destroy_notify_callback(nullptr, on_orphaned_button_deleted); const GObject* const window = (GObject*)main_win->gobj(); const GObject* const orphaned_button = (GObject*)orph_button->gobj(); const GObject* const derived_button = (GObject*)main_win->get_derived_button()->gobj(); const GObject* const standard_button = (GObject*)main_win->get_standard_button()->gobj(); std::cout << "Before app->run(*main_win, argc1, argv)" << std::endl << " ref_count(MainWindow)=" << window->ref_count << std::endl << " ref_count(DerivedButton)=" << derived_button->ref_count << std::endl << " ref_count(Gtk::Button)=" << standard_button->ref_count << std::endl << " ref_count(orphaned_button)=" << orphaned_button->ref_count << std::endl; const int result = app->run(*main_win, argc1, argv); std::cout << "After app->run(*main_win, argc1, argv)" << std::endl << " ref_count(MainWindow)=" << window->ref_count << std::endl << " ref_count(DerivedButton)=" << derived_button->ref_count << std::endl << " ref_count(Gtk::Button)=" << standard_button->ref_count << std::endl << " ref_count(orphaned_button)=" << orphaned_button->ref_count << std::endl; delete main_win; std::cout << "After delete main_win" << std::endl << " ref_count(MainWindow)=" << window->ref_count << std::endl << " ref_count(DerivedButton)=" << derived_button->ref_count << std::endl << " ref_count(Gtk::Button)=" << standard_button->ref_count << std::endl << " ref_count(orphaned_button)=" << orphaned_button->ref_count << std::endl; builder.reset(); if (print_after_deletion) { // If Builder is correct, this code will access deallocated memory. std::cout << "After builder.reset()" << std::endl << " ref_count(MainWindow)=" << window->ref_count << std::endl << " ref_count(DerivedButton)=" << derived_button->ref_count << std::endl << " ref_count(Gtk::Button)=" << standard_button->ref_count << std::endl << " ref_count(orphaned_button)=" << orphaned_button->ref_count << std::endl; } return result; } <|endoftext|>
<commit_before>#define _WINSOCKAPI_ #include <httpserv.h> #include <comdef.h> class StripHeadersModule : public CHttpModule { private: IAppHostAdminManager * pMgr; IAppHostElement * pParentElem; IAppHostElementCollection * pElemColl; IAppHostElement * pElem; IAppHostPropertyCollection * pElemProps; IAppHostProperty * pElemProp; HRESULT hr; BSTR bstrConfigCommitPath; BSTR bstrSectionName; BSTR bstrPropertyName; DWORD dwElementCount; VARIANT vtValue; VARIANT vtPropertyName; void cleanup() { if ( pElemProp != NULL ) { pElemProp->Release(); pElemProp = NULL; } if ( pElemProps != NULL ) { pElemProps->Release(); pElemProps = NULL; } if ( pElem != NULL ) { pElem->Release(); pElem = NULL; } if ( pElemColl != NULL ) { pElemColl->Release(); pElemColl = NULL; } if ( pParentElem != NULL ) { pParentElem->Release(); pParentElem = NULL; } if ( pMgr != NULL ) { pMgr->Release(); pMgr = NULL; } SysFreeString( bstrConfigCommitPath ); SysFreeString( bstrSectionName ); SysFreeString( bstrPropertyName ); CoUninitialize(); } public: REQUEST_NOTIFICATION_STATUS OnEndRequest( IN IHttpContext * pHttpContext, IN IHttpEventProvider * pProvider ) { UNREFERENCED_PARAMETER( pProvider ); pMgr = NULL; pParentElem = NULL; pElemColl = NULL; pElem = NULL; pElemProps = NULL; pElemProp = NULL; hr = S_OK; bstrConfigCommitPath = SysAllocString( L"MACHINE/WEBROOT/APPHOST" ); bstrSectionName = SysAllocString( L"system.webServer/stripHeaders" ); bstrPropertyName = SysAllocString( L"name" ); dwElementCount = 0; vtPropertyName.vt = VT_BSTR; vtPropertyName.bstrVal = bstrPropertyName; // Initialize hr = CoInitializeEx( NULL, COINIT_MULTITHREADED ); if ( FAILED( hr ) ) { // Set the error status. pProvider->SetErrorStatus( hr ); // cleanup cleanup(); // End additional processing. return RQ_NOTIFICATION_FINISH_REQUEST; } // Create hr = CoCreateInstance( __uuidof( AppHostAdminManager ), NULL, CLSCTX_INPROC_SERVER, __uuidof( IAppHostAdminManager ), (void**) &pMgr ); if( FAILED( hr ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } // Get the admin section hr = pMgr->GetAdminSection( bstrSectionName, bstrConfigCommitPath, &pParentElem ); if ( FAILED( hr ) || ( &pParentElem == NULL ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } // Get the site collection hr = pParentElem->get_Collection( &pElemColl ); if ( FAILED ( hr ) || ( &pElemColl == NULL ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } // Get the elements hr = pElemColl->get_Count( &dwElementCount ); for ( USHORT i = 0; i < dwElementCount; i++ ) { VARIANT vtItemIndex; vtItemIndex.vt = VT_I2; vtItemIndex.iVal = i; // Add a new section group hr = pElemColl->get_Item( vtItemIndex, &pElem ); if ( FAILED( hr ) || ( &pElem == NULL ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } // Get the child elements hr = pElem->get_Properties( &pElemProps ); if ( FAILED( hr ) || ( &pElemProps == NULL ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } hr = pElemProps->get_Item( vtPropertyName, &pElemProp ); if ( FAILED( hr ) || ( pElemProp == NULL ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } hr = pElemProp->get_Value( &vtValue ); if ( FAILED( hr ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } // Retrieve a pointer to the response. IHttpResponse * pHttpResponse = pHttpContext->GetResponse(); // Test for an error. if ( pHttpResponse != NULL ) { // convert bstr to string in order to delete header _bstr_t header( vtValue.bstrVal ); // delete header hr = pHttpResponse->DeleteHeader( (char *)header ); // Test for an error. if ( FAILED( hr ) ) { // Set the error status. pProvider->SetErrorStatus( hr ); // cleanup cleanup(); // End additional processing. return RQ_NOTIFICATION_FINISH_REQUEST; } } // loop_cleanup if ( pElem != NULL ) { pElem->Release(); pElem = NULL; } } cleanup(); // Return processing to the pipeline. return RQ_NOTIFICATION_CONTINUE; } }; // Create the module's class factory. class StripHeadersModuleFactory : public IHttpModuleFactory { public: HRESULT GetHttpModule( OUT CHttpModule ** ppModule, IN IModuleAllocator * pAllocator ) { UNREFERENCED_PARAMETER( pAllocator ); // Create a new instance. StripHeadersModule * pModule = new StripHeadersModule; // Test for an error. if ( !pModule ) { // Return an error if the factory cannot create the instance. return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); } else { // Return a pointer to the module. *ppModule = pModule; pModule = NULL; // Return a success status. return S_OK; } } void Terminate() { // Remove the class from memory. delete this; } }; // Create the module's exported registration function. HRESULT __stdcall RegisterModule( DWORD dwServerVersion, IHttpModuleRegistrationInfo * pModuleInfo, IHttpServer * pGlobalInfo ) { UNREFERENCED_PARAMETER( dwServerVersion ); UNREFERENCED_PARAMETER( pGlobalInfo ); // Set the request notifications and exit. return pModuleInfo->SetRequestNotifications( new StripHeadersModuleFactory, RQ_END_REQUEST, 0 ); }<commit_msg>change event from OnEndRequest to OnSendResponse to allow removal of headers set by ProtocolSupportModule such as X-Powered-By<commit_after>#define _WINSOCKAPI_ #include <httpserv.h> #include <comdef.h> class StripHeadersModule : public CHttpModule { private: IAppHostAdminManager * pMgr; IAppHostElement * pParentElem; IAppHostElementCollection * pElemColl; IAppHostElement * pElem; IAppHostPropertyCollection * pElemProps; IAppHostProperty * pElemProp; HRESULT hr; BSTR bstrConfigCommitPath; BSTR bstrSectionName; BSTR bstrPropertyName; DWORD dwElementCount; VARIANT vtValue; VARIANT vtPropertyName; void cleanup() { if ( pElemProp != NULL ) { pElemProp->Release(); pElemProp = NULL; } if ( pElemProps != NULL ) { pElemProps->Release(); pElemProps = NULL; } if ( pElem != NULL ) { pElem->Release(); pElem = NULL; } if ( pElemColl != NULL ) { pElemColl->Release(); pElemColl = NULL; } if ( pParentElem != NULL ) { pParentElem->Release(); pParentElem = NULL; } if ( pMgr != NULL ) { pMgr->Release(); pMgr = NULL; } SysFreeString( bstrConfigCommitPath ); SysFreeString( bstrSectionName ); SysFreeString( bstrPropertyName ); CoUninitialize(); } public: REQUEST_NOTIFICATION_STATUS OnSendResponse( IN IHttpContext * pHttpContext, IN ISendResponseProvider * pProvider ) { UNREFERENCED_PARAMETER( pProvider ); pMgr = NULL; pParentElem = NULL; pElemColl = NULL; pElem = NULL; pElemProps = NULL; pElemProp = NULL; hr = S_OK; bstrConfigCommitPath = SysAllocString( L"MACHINE/WEBROOT/APPHOST" ); bstrSectionName = SysAllocString( L"system.webServer/stripHeaders" ); bstrPropertyName = SysAllocString( L"name" ); dwElementCount = 0; vtPropertyName.vt = VT_BSTR; vtPropertyName.bstrVal = bstrPropertyName; // Initialize hr = CoInitializeEx( NULL, COINIT_MULTITHREADED ); if ( FAILED( hr ) ) { // Set the error status. pProvider->SetErrorStatus( hr ); // cleanup cleanup(); // End additional processing. return RQ_NOTIFICATION_FINISH_REQUEST; } // Create hr = CoCreateInstance( __uuidof( AppHostAdminManager ), NULL, CLSCTX_INPROC_SERVER, __uuidof( IAppHostAdminManager ), (void**) &pMgr ); if( FAILED( hr ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } // Get the admin section hr = pMgr->GetAdminSection( bstrSectionName, bstrConfigCommitPath, &pParentElem ); if ( FAILED( hr ) || ( &pParentElem == NULL ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } // Get the site collection hr = pParentElem->get_Collection( &pElemColl ); if ( FAILED ( hr ) || ( &pElemColl == NULL ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } // Get the elements hr = pElemColl->get_Count( &dwElementCount ); for ( USHORT i = 0; i < dwElementCount; i++ ) { VARIANT vtItemIndex; vtItemIndex.vt = VT_I2; vtItemIndex.iVal = i; // Add a new section group hr = pElemColl->get_Item( vtItemIndex, &pElem ); if ( FAILED( hr ) || ( &pElem == NULL ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } // Get the child elements hr = pElem->get_Properties( &pElemProps ); if ( FAILED( hr ) || ( &pElemProps == NULL ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } hr = pElemProps->get_Item( vtPropertyName, &pElemProp ); if ( FAILED( hr ) || ( pElemProp == NULL ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } hr = pElemProp->get_Value( &vtValue ); if ( FAILED( hr ) ) { pProvider->SetErrorStatus( hr ); cleanup(); return RQ_NOTIFICATION_FINISH_REQUEST; } // Retrieve a pointer to the response. IHttpResponse * pHttpResponse = pHttpContext->GetResponse(); // Test for an error. if ( pHttpResponse != NULL ) { // convert bstr to string in order to delete header _bstr_t header( vtValue.bstrVal ); // delete header hr = pHttpResponse->DeleteHeader( (char *)header ); // Test for an error. if ( FAILED( hr ) ) { // Set the error status. pProvider->SetErrorStatus( hr ); // cleanup cleanup(); // End additional processing. return RQ_NOTIFICATION_FINISH_REQUEST; } } // loop_cleanup if ( pElem != NULL ) { pElem->Release(); pElem = NULL; } } cleanup(); // Return processing to the pipeline. return RQ_NOTIFICATION_CONTINUE; } }; // Create the module's class factory. class StripHeadersModuleFactory : public IHttpModuleFactory { public: HRESULT GetHttpModule( OUT CHttpModule ** ppModule, IN IModuleAllocator * pAllocator ) { UNREFERENCED_PARAMETER( pAllocator ); // Create a new instance. StripHeadersModule * pModule = new StripHeadersModule; // Test for an error. if ( !pModule ) { // Return an error if the factory cannot create the instance. return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); } else { // Return a pointer to the module. *ppModule = pModule; pModule = NULL; // Return a success status. return S_OK; } } void Terminate() { // Remove the class from memory. delete this; } }; // Create the module's exported registration function. HRESULT __stdcall RegisterModule( DWORD dwServerVersion, IHttpModuleRegistrationInfo * pModuleInfo, IHttpServer * pGlobalInfo ) { UNREFERENCED_PARAMETER( dwServerVersion ); UNREFERENCED_PARAMETER( pGlobalInfo ); // Set the request notifications and exit. return pModuleInfo->SetRequestNotifications( new StripHeadersModuleFactory, RQ_SEND_RESPONSE, 0 ); }<|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/core_options_handler.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/webui/web_ui_browsertest.h" #include "googleurl/src/gurl.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::StrictMock; using ::testing::_; MATCHER_P(Eq_ListValue, inList, "") { return arg->Equals(inList); } class MockCoreOptionsHandler : public CoreOptionsHandler { public: MOCK_METHOD1(HandleInitialize, void(const ListValue* args)); MOCK_METHOD1(HandleFetchPrefs, void(const ListValue* args)); MOCK_METHOD1(HandleObservePrefs, void(const ListValue* args)); MOCK_METHOD1(HandleSetBooleanPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetIntegerPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetDoublePref, void(const ListValue* args)); MOCK_METHOD1(HandleSetStringPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetObjectPref, void(const ListValue* args)); MOCK_METHOD1(HandleClearPref, void(const ListValue* args)); MOCK_METHOD1(HandleUserMetricsAction, void(const ListValue* args)); virtual void RegisterMessages() { web_ui_->RegisterMessageCallback("coreOptionsInitialize", NewCallback(this, &MockCoreOptionsHandler ::HandleInitialize)); web_ui_->RegisterMessageCallback("fetchPrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleFetchPrefs)); web_ui_->RegisterMessageCallback("observePrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleObservePrefs)); web_ui_->RegisterMessageCallback("setBooleanPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetBooleanPref)); web_ui_->RegisterMessageCallback("setIntegerPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetIntegerPref)); web_ui_->RegisterMessageCallback("setDoublePref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetDoublePref)); web_ui_->RegisterMessageCallback("setStringPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetStringPref)); web_ui_->RegisterMessageCallback("setObjectPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetObjectPref)); web_ui_->RegisterMessageCallback("clearPref", NewCallback(this, &MockCoreOptionsHandler ::HandleClearPref)); web_ui_->RegisterMessageCallback("coreOptionsUserMetricsAction", NewCallback(this, &MockCoreOptionsHandler ::HandleUserMetricsAction)); } }; class SettingsWebUITest : public WebUIBrowserTest { protected: virtual void SetUpInProcessBrowserTestFixture() { WebUIBrowserTest::SetUpInProcessBrowserTestFixture(); AddLibrary(FILE_PATH_LITERAL("settings.js")); } virtual WebUIMessageHandler* GetMockMessageHandler() { return &mock_core_options_handler_; } StrictMock<MockCoreOptionsHandler> mock_core_options_handler_; }; // Crashes on Mac only. http://crbug.com/77764 #if defined(OS_MACOSX) #define MAYBE_TestSetBooleanPrefTriggers DISABLED_TestSetBooleanPrefTriggers #else #define MAYBE_TestSetBooleanPrefTriggers TestSetBooleanPrefTriggers #endif // Test the end to end js to WebUI handler code path for // the message setBooleanPref. // TODO(dtseng): add more EXPECT_CALL's when updating js test. IN_PROC_BROWSER_TEST_F(SettingsWebUITest, MAYBE_TestSetBooleanPrefTriggers) { // This serves as an example of a very constrained test. ListValue true_list_value; true_list_value.Append(Value::CreateStringValue("browser.show_home_button")); true_list_value.Append(Value::CreateBooleanValue(true)); true_list_value.Append( Value::CreateStringValue("Options_Homepage_HomeButton")); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUISettingsURL)); EXPECT_CALL(mock_core_options_handler_, HandleSetBooleanPref(Eq_ListValue(&true_list_value))); ASSERT_TRUE(RunJavascriptTest("testSetBooleanPrefTriggers")); } <commit_msg>Reenable passing test SettingsWebUITest.SetBooleanPrefTriggers. BUG=77764 TEST=repeated runs on try bots. Passing for the past two days on Win, Mac, and Linux. TBR=jam Review URL: http://codereview.chromium.org/6735073<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/core_options_handler.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/webui/web_ui_browsertest.h" #include "googleurl/src/gurl.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::StrictMock; using ::testing::_; MATCHER_P(Eq_ListValue, inList, "") { return arg->Equals(inList); } class MockCoreOptionsHandler : public CoreOptionsHandler { public: MOCK_METHOD1(HandleInitialize, void(const ListValue* args)); MOCK_METHOD1(HandleFetchPrefs, void(const ListValue* args)); MOCK_METHOD1(HandleObservePrefs, void(const ListValue* args)); MOCK_METHOD1(HandleSetBooleanPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetIntegerPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetDoublePref, void(const ListValue* args)); MOCK_METHOD1(HandleSetStringPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetObjectPref, void(const ListValue* args)); MOCK_METHOD1(HandleClearPref, void(const ListValue* args)); MOCK_METHOD1(HandleUserMetricsAction, void(const ListValue* args)); virtual void RegisterMessages() { web_ui_->RegisterMessageCallback("coreOptionsInitialize", NewCallback(this, &MockCoreOptionsHandler ::HandleInitialize)); web_ui_->RegisterMessageCallback("fetchPrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleFetchPrefs)); web_ui_->RegisterMessageCallback("observePrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleObservePrefs)); web_ui_->RegisterMessageCallback("setBooleanPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetBooleanPref)); web_ui_->RegisterMessageCallback("setIntegerPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetIntegerPref)); web_ui_->RegisterMessageCallback("setDoublePref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetDoublePref)); web_ui_->RegisterMessageCallback("setStringPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetStringPref)); web_ui_->RegisterMessageCallback("setObjectPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetObjectPref)); web_ui_->RegisterMessageCallback("clearPref", NewCallback(this, &MockCoreOptionsHandler ::HandleClearPref)); web_ui_->RegisterMessageCallback("coreOptionsUserMetricsAction", NewCallback(this, &MockCoreOptionsHandler ::HandleUserMetricsAction)); } }; class SettingsWebUITest : public WebUIBrowserTest { protected: virtual void SetUpInProcessBrowserTestFixture() { WebUIBrowserTest::SetUpInProcessBrowserTestFixture(); AddLibrary(FILE_PATH_LITERAL("settings.js")); } virtual WebUIMessageHandler* GetMockMessageHandler() { return &mock_core_options_handler_; } StrictMock<MockCoreOptionsHandler> mock_core_options_handler_; }; // Test the end to end js to WebUI handler code path for // the message setBooleanPref. // TODO(dtseng): add more EXPECT_CALL's when updating js test. IN_PROC_BROWSER_TEST_F(SettingsWebUITest, TestSetBooleanPrefTriggers) { // This serves as an example of a very constrained test. ListValue true_list_value; true_list_value.Append(Value::CreateStringValue("browser.show_home_button")); true_list_value.Append(Value::CreateBooleanValue(true)); true_list_value.Append( Value::CreateStringValue("Options_Homepage_HomeButton")); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUISettingsURL)); EXPECT_CALL(mock_core_options_handler_, HandleSetBooleanPref(Eq_ListValue(&true_list_value))); ASSERT_TRUE(RunJavascriptTest("testSetBooleanPrefTriggers")); } <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE "test_implicit_membrane_potential" #ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST #include <boost/test/unit_test.hpp> #else #define BOOST_TEST_NO_LIB #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/potential/external/ImplicitMembranePotential.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/util/make_unique.hpp> #include <fstream> BOOST_AUTO_TEST_CASE(IM_double) { typedef mjolnir::SimulatorTraitsBase<double, mjolnir::UnlimitedBoundary> traits; constexpr static std::size_t N = 10000; constexpr static traits::real_type h = 1e-6; constexpr static traits::real_type tolerance = 1e-5; mjolnir::ImplicitMembranePotential<traits> im; const traits::real_type thickness = 10.0; const traits::real_type interaction_magnitude = 1.0; const traits::real_type bend = 1.5; const std::vector<traits::real_type> hydrophobicities{1., 0.}; im.half_thick() = thickness * 0.5; im.interaction_magnitude() = interaction_magnitude; im.bend() = bend; im.set_hydrophobicities(hydrophobicities); const traits::real_type cutoff_length = im.max_cutoff_length(); const traits::real_type z_min = -1 * cutoff_length; const traits::real_type z_max = cutoff_length; const traits::real_type dz = (z_max - z_min) / N; std::ofstream ofs("testlog.dat"); traits::real_type z = z_min; for(std::size_t i = 0; i < N; ++i) { const traits::real_type pot1 = im.potential(0, z + h); const traits::real_type pot2 = im.potential(0, z - h); const traits::real_type dpot = (pot1 - pot2) / (2 * h); const traits::real_type deri = im.derivative(0, z); ofs << z << " " << dz << " " << dpot << " " << deri << std::endl; if(std::abs(z) > h) { if(std::abs(deri) > tolerance) BOOST_CHECK_CLOSE_FRACTION(dpot, deri, tolerance); else BOOST_CHECK_SMALL(deri, tolerance); } const traits::real_type pot0 = im.potential(1, z); const traits::real_type deri0 = im.derivative(1, z); BOOST_CHECK_SMALL(pot0, h); BOOST_CHECK_SMALL(deri0, h); z += dz; } ofs.close(); } /* BOOST_AUTO_TEST_CASE(IM_float) { typedef mjolnir::SimulatorTraitsBase<float, mjolnir::UnlimitedBoundary> traits; constexpr static std::size_t N = 10000; constexpr static traits::real_type h = 1e-6; constexpr static traits::real_type tolerance = 1e-5; mjolnir::ImplicitMembranePotential<traits> im; const traits::real_type thickness = 10.0; const traits::real_type interaction_magnitude = 1.0; const traits::real_type bend = 1.5; const std::vector<traits::real_type> hydrophobicities{1., 0.}; im.half_thick() = thickness * 0.5; im.interaction_magnitude() = interaction_magnitude; im.bend() = bend; im.set_hydrophobicities(hydrophobicities); const traits::real_type cutoff_length = im.max_cutoff_length(); const traits::real_type z_min = -1 * cutoff_length; const traits::real_type z_max = cutoff_length; const traits::real_type dz = (z_max - z_min) / N; std::ofstream ofs("testlog.dat"); traits::real_type z = z_min; for(std::size_t i = 0; i < N; ++i) { const traits::real_type pot1 = im.potential(0, z + h); const traits::real_type pot2 = im.potential(0, z - h); const traits::real_type dpot = (pot1 - pot2) / (2 * h); const traits::real_type deri = im.derivative(0, z); ofs << z << " " << dz << " " << dpot << " " << deri << std::endl; if(std::abs(z) > h) { if(std::abs(deri) > tolerance) BOOST_CHECK_CLOSE_FRACTION(dpot, deri, tolerance); else BOOST_CHECK_SMALL(deri, tolerance); } const traits::real_type pot0 = im.potential(1, z); const traits::real_type deri0 = im.derivative(1, z); BOOST_CHECK_SMALL(pot0, h); BOOST_CHECK_SMALL(deri0, h); z += dz; } ofs.close(); } */ <commit_msg>nit: fix indentations<commit_after>#define BOOST_TEST_MODULE "test_implicit_membrane_potential" #ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST #include <boost/test/unit_test.hpp> #else #define BOOST_TEST_NO_LIB #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/potential/external/ImplicitMembranePotential.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/util/make_unique.hpp> BOOST_AUTO_TEST_CASE(ImplicitMembranePotential_double) { typedef mjolnir::SimulatorTraitsBase<double, mjolnir::UnlimitedBoundary> traits; constexpr static std::size_t N = 10000; constexpr static traits::real_type h = 1e-6; constexpr static traits::real_type tolerance = 1e-5; const traits::real_type thickness = 10.0; const traits::real_type interaction_magnitude = 1.0; const traits::real_type bend = 1.5; const std::vector<traits::real_type> hydrophobicities{1., 0.}; mjolnir::ImplicitMembranePotential<traits> im(thickness, interaction_magnitude, bend, hydrophobicities); const traits::real_type cutoff_length = im.max_cutoff_length(); const traits::real_type z_min = -1 * cutoff_length; const traits::real_type z_max = cutoff_length; const traits::real_type dz = (z_max - z_min) / N; traits::real_type z = z_min; for(std::size_t i = 0; i < N; ++i) { const traits::real_type pot1 = im.potential(0, z + h); const traits::real_type pot2 = im.potential(0, z - h); const traits::real_type dpot = (pot1 - pot2) / (2 * h); const traits::real_type deri = im.derivative(0, z); if(std::abs(z) > h) { if(std::abs(deri) > tolerance) { BOOST_CHECK_CLOSE_FRACTION(dpot, deri, tolerance); } else { BOOST_CHECK_SMALL(deri, tolerance); } } const traits::real_type pot0 = im.potential(1, z); const traits::real_type deri0 = im.derivative(1, z); BOOST_CHECK_SMALL(pot0, h); BOOST_CHECK_SMALL(deri0, h); z += dz; } } <|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/extensions/extension_constants.h" namespace extension_manifest_keys { const wchar_t* kAllFrames = L"all_frames"; const wchar_t* kApp = L"app"; const wchar_t* kAppExtent = L"extent"; const wchar_t* kAppLaunchUrl = L"launch.url"; const wchar_t* kAppLaunchWindowType = L"launch.window_type"; const wchar_t* kBackground = L"background_page"; const wchar_t* kBrowserAction = L"browser_action"; const wchar_t* kChromeURLOverrides = L"chrome_url_overrides"; const wchar_t* kContentScripts = L"content_scripts"; const wchar_t* kConvertedFromUserScript = L"converted_from_user_script"; const wchar_t* kCss = L"css"; const wchar_t* kCurrentLocale = L"current_locale"; const wchar_t* kDefaultLocale = L"default_locale"; const wchar_t* kDescription = L"description"; const wchar_t* kIcons = L"icons"; const wchar_t* kJs = L"js"; const wchar_t* kMatches = L"matches"; const wchar_t* kMinimumChromeVersion = L"minimum_chrome_version"; const wchar_t* kIncludeGlobs = L"include_globs"; const wchar_t* kExcludeGlobs = L"exclude_globs"; const wchar_t* kName = L"name"; const wchar_t* kPageActionId = L"id"; const wchar_t* kPageAction = L"page_action"; const wchar_t* kPageActions = L"page_actions"; const wchar_t* kPageActionIcons = L"icons"; const wchar_t* kPageActionDefaultIcon = L"default_icon"; const wchar_t* kPageActionDefaultPopup = L"default_popup"; const wchar_t* kPageActionDefaultTitle = L"default_title"; const wchar_t* kPageActionPopup = L"popup"; const wchar_t* kPageActionPopupHeight = L"height"; const wchar_t* kPageActionPopupPath = L"path"; const wchar_t* kPermissions = L"permissions"; const wchar_t* kPlugins = L"plugins"; const wchar_t* kPluginsPath = L"path"; const wchar_t* kPluginsPublic = L"public"; const wchar_t* kPublicKey = L"key"; const wchar_t* kRunAt = L"run_at"; const wchar_t* kSignature = L"signature"; const wchar_t* kTheme = L"theme"; const wchar_t* kThemeImages = L"images"; const wchar_t* kThemeColors = L"colors"; const wchar_t* kThemeTints = L"tints"; const wchar_t* kThemeDisplayProperties = L"properties"; const wchar_t* kToolstripMoleHeight = L"mole_height"; const wchar_t* kToolstripMolePath = L"mole"; const wchar_t* kToolstripPath = L"path"; const wchar_t* kToolstrips = L"toolstrips"; const wchar_t* kType = L"type"; const wchar_t* kVersion = L"version"; const wchar_t* kUpdateURL = L"update_url"; const wchar_t* kOptionsPage = L"options_page"; } // namespace extension_manifest_keys namespace extension_manifest_values { const char* kRunAtDocumentStart = "document_start"; const char* kRunAtDocumentEnd = "document_end"; const char* kRunAtDocumentIdle = "document_idle"; const char* kPageActionTypeTab = "tab"; const char* kPageActionTypePermanent = "permanent"; const char* kWindowTypeApp = "app"; const char* kWindowTypePanel = "panel"; } // namespace extension_manifest_values // Extension-related error messages. Some of these are simple patterns, where a // '*' is replaced at runtime with a specific value. This is used instead of // printf because we want to unit test them and scanf is hard to make // cross-platform. namespace extension_manifest_errors { const char* kChromeVersionTooLow = "This extension requires * version * or greater."; const char* kInvalidAllFrames = "Invalid value for 'content_scripts[*].all_frames'."; const char* kInvalidApp = "Invalid app."; const char* kInvalidAppExtent = "Invalid value for app.extent."; const char* kInvalidAppExtentPattern = "Invalid value for app.extent[*]."; const char* kInvalidAppLaunchUrl = "Required value 'app.launch.url' is missing or invalid."; const char* kInvalidAppLaunchWindowType = "Invalid value for 'app.launch.window_type'."; const char* kInvalidBrowserAction = "Invalid value for 'browser_action'."; const char* kInvalidChromeURLOverrides = "Invalid value for 'chrome_url_overrides'."; const char* kInvalidContentScript = "Invalid value for 'content_scripts[*]'."; const char* kInvalidContentScriptsList = "Invalid value for 'content_scripts'."; const char* kInvalidCss = "Invalid value for 'content_scripts[*].css[*]'."; const char* kInvalidCssList = "Required value 'content_scripts[*].css' is invalid."; const char* kInvalidDescription = "Invalid value for 'description'."; const char* kInvalidGlobList = "Invalid value for 'content_scripts[*].*'."; const char* kInvalidGlob = "Invalid value for 'content_scripts[*].*[*]'."; const char* kInvalidIcons = "Invalid value for 'icons'."; const char* kInvalidIconPath = "Invalid value for 'icons[\"*\"]'."; const char* kInvalidJs = "Invalid value for 'content_scripts[*].js[*]'."; const char* kInvalidJsList = "Required value 'content_scripts[*].js' is invalid."; const char* kInvalidKey = "Value 'key' is missing or invalid."; const char* kInvalidManifest = "Manifest file is invalid."; const char* kInvalidMatchCount = "Invalid value for 'content_scripts[*].matches'. There must be at least" "one match specified."; const char* kInvalidMatch = "Invalid value for 'content_scripts[*].matches[*]'."; const char* kInvalidMatches = "Required value 'content_scripts[*].matches' is missing or invalid."; const char* kInvalidMinimumChromeVersion = "Invalid value for 'minimum_chrome_version'."; const char* kInvalidName = "Required value 'name' is missing or invalid."; const char* kInvalidPageAction = "Invalid value for 'page_action'."; const char* kInvalidPageActionName = "Invalid value for 'page_action.name'."; const char* kInvalidPageActionIconPath = "Invalid value for 'page_action.default_icon'."; const char* kInvalidPageActionsList = "Invalid value for 'page_actions'."; const char* kInvalidPageActionsListSize = "Invalid value for 'page_actions'. There can be at most one page action."; const char* kInvalidPageActionId = "Required value 'id' is missing or invalid."; const char* kInvalidPageActionDefaultTitle = "Invalid value for 'default_title'."; const char* kInvalidPageActionOldAndNewKeys = "Key \"*\" is deprecated. Key \"*\" has the same meaning. You can not " "use both."; const char* kInvalidPageActionPopup = "Invalid type for page action popup."; const char* kInvalidPageActionPopupHeight = "Invalid value for page action popup height [*]."; const char* kInvalidPageActionPopupPath = "Invalid value for page action popup path [*]."; const char* kInvalidPageActionTypeValue = "Invalid value for 'page_actions[*].type', expected 'tab' or 'permanent'."; const char* kInvalidPermissions = "Required value 'permissions' is missing or invalid."; const char* kInvalidPermission = "Invalid value for 'permissions[*]'."; const char* kInvalidPermissionScheme = "Invalid scheme for 'permissions[*]'. Only 'http' and 'https' are " "allowed."; const char* kInvalidPlugins = "Invalid value for 'plugins'."; const char* kInvalidPluginsPath = "Invalid value for 'plugins[*].path'."; const char* kInvalidPluginsPublic = "Invalid value for 'plugins[*].public'."; const char* kInvalidBackground = "Invalid value for 'background_page'."; const char* kInvalidRunAt = "Invalid value for 'content_scripts[*].run_at'."; const char* kInvalidSignature = "Value 'signature' is missing or invalid."; const char* kInvalidToolstrip = "Invalid value for 'toolstrips[*]'"; const char* kInvalidToolstrips = "Invalid value for 'toolstrips'."; const char* kInvalidVersion = "Required value 'version' is missing or invalid. It must be between 1-4 " "dot-separated integers."; const char* kInvalidZipHash = "Required key 'zip_hash' is missing or invalid."; const char* kManifestParseError = "Manifest is not valid JSON."; const char* kManifestUnreadable = "Manifest file is missing or unreadable."; const char* kMissingFile = "At least one js or css file is required for 'content_scripts[*]'."; const char* kInvalidTheme = "Invalid value for 'theme'."; const char* kInvalidThemeImages = "Invalid value for theme images - images must be strings."; const char* kInvalidThemeImagesMissing = "Am image specified in the theme is missing."; const char* kInvalidThemeColors = "Invalid value for theme colors - colors must be integers"; const char* kInvalidThemeTints = "Invalid value for theme images - tints must be decimal numbers."; const char* kInvalidUpdateURL = "Invalid value for update url: '[*]'."; const char* kInvalidDefaultLocale = "Invalid value for default locale - locale name must be a string."; const char* kOneUISurfaceOnly = "An extension cannot have both a page action and a browser action."; const char* kThemesCannotContainExtensions = "A theme cannot contain extensions code."; const char* kLocalesNoDefaultLocaleSpecified = "Localization used, but default_locale wasn't specified in the manifest."; const char* kLocalesNoDefaultMessages = "Default locale is defined but default data couldn't be loaded."; const char* kLocalesNoValidLocaleNamesListed = "No valid locale name could be found in _locales directory."; const char* kLocalesTreeMissing = "Default locale was specified, but _locales subtree is missing."; const char* kLocalesMessagesFileMissing = "Messages file is missing for locale."; const char* kInvalidOptionsPage = "Invalid value for 'options_page'."; const char* kReservedMessageFound = "Reserved key * found in message catalog."; const char* kCannotAccessPage = "Cannot access contents of url \"*\". " "Extension manifest must request permission to access this host."; const char* kCannotScriptGallery = "The extensions gallery cannot be scripted."; } // namespace extension_manifest_errors namespace extension_urls { const char* kGalleryBrowsePrefix = "https://chrome.google.com/extensions"; const char* kGalleryDownloadPrefix = "https://clients2.googleusercontent.com/crx/download"; const char* kMiniGalleryBrowsePrefix = "https://tools.google.com/chrome/"; const char* kMiniGalleryDownloadPrefix = "https://dl-ssl.google.com/chrome/"; } <commit_msg>Make the invalid version error a bit more specific; the previous text led me to believe each component of the version string could be a 32-bit integer.<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/extensions/extension_constants.h" namespace extension_manifest_keys { const wchar_t* kAllFrames = L"all_frames"; const wchar_t* kApp = L"app"; const wchar_t* kAppExtent = L"extent"; const wchar_t* kAppLaunchUrl = L"launch.url"; const wchar_t* kAppLaunchWindowType = L"launch.window_type"; const wchar_t* kBackground = L"background_page"; const wchar_t* kBrowserAction = L"browser_action"; const wchar_t* kChromeURLOverrides = L"chrome_url_overrides"; const wchar_t* kContentScripts = L"content_scripts"; const wchar_t* kConvertedFromUserScript = L"converted_from_user_script"; const wchar_t* kCss = L"css"; const wchar_t* kCurrentLocale = L"current_locale"; const wchar_t* kDefaultLocale = L"default_locale"; const wchar_t* kDescription = L"description"; const wchar_t* kIcons = L"icons"; const wchar_t* kJs = L"js"; const wchar_t* kMatches = L"matches"; const wchar_t* kMinimumChromeVersion = L"minimum_chrome_version"; const wchar_t* kIncludeGlobs = L"include_globs"; const wchar_t* kExcludeGlobs = L"exclude_globs"; const wchar_t* kName = L"name"; const wchar_t* kPageActionId = L"id"; const wchar_t* kPageAction = L"page_action"; const wchar_t* kPageActions = L"page_actions"; const wchar_t* kPageActionIcons = L"icons"; const wchar_t* kPageActionDefaultIcon = L"default_icon"; const wchar_t* kPageActionDefaultPopup = L"default_popup"; const wchar_t* kPageActionDefaultTitle = L"default_title"; const wchar_t* kPageActionPopup = L"popup"; const wchar_t* kPageActionPopupHeight = L"height"; const wchar_t* kPageActionPopupPath = L"path"; const wchar_t* kPermissions = L"permissions"; const wchar_t* kPlugins = L"plugins"; const wchar_t* kPluginsPath = L"path"; const wchar_t* kPluginsPublic = L"public"; const wchar_t* kPublicKey = L"key"; const wchar_t* kRunAt = L"run_at"; const wchar_t* kSignature = L"signature"; const wchar_t* kTheme = L"theme"; const wchar_t* kThemeImages = L"images"; const wchar_t* kThemeColors = L"colors"; const wchar_t* kThemeTints = L"tints"; const wchar_t* kThemeDisplayProperties = L"properties"; const wchar_t* kToolstripMoleHeight = L"mole_height"; const wchar_t* kToolstripMolePath = L"mole"; const wchar_t* kToolstripPath = L"path"; const wchar_t* kToolstrips = L"toolstrips"; const wchar_t* kType = L"type"; const wchar_t* kVersion = L"version"; const wchar_t* kUpdateURL = L"update_url"; const wchar_t* kOptionsPage = L"options_page"; } // namespace extension_manifest_keys namespace extension_manifest_values { const char* kRunAtDocumentStart = "document_start"; const char* kRunAtDocumentEnd = "document_end"; const char* kRunAtDocumentIdle = "document_idle"; const char* kPageActionTypeTab = "tab"; const char* kPageActionTypePermanent = "permanent"; const char* kWindowTypeApp = "app"; const char* kWindowTypePanel = "panel"; } // namespace extension_manifest_values // Extension-related error messages. Some of these are simple patterns, where a // '*' is replaced at runtime with a specific value. This is used instead of // printf because we want to unit test them and scanf is hard to make // cross-platform. namespace extension_manifest_errors { const char* kChromeVersionTooLow = "This extension requires * version * or greater."; const char* kInvalidAllFrames = "Invalid value for 'content_scripts[*].all_frames'."; const char* kInvalidApp = "Invalid app."; const char* kInvalidAppExtent = "Invalid value for app.extent."; const char* kInvalidAppExtentPattern = "Invalid value for app.extent[*]."; const char* kInvalidAppLaunchUrl = "Required value 'app.launch.url' is missing or invalid."; const char* kInvalidAppLaunchWindowType = "Invalid value for 'app.launch.window_type'."; const char* kInvalidBrowserAction = "Invalid value for 'browser_action'."; const char* kInvalidChromeURLOverrides = "Invalid value for 'chrome_url_overrides'."; const char* kInvalidContentScript = "Invalid value for 'content_scripts[*]'."; const char* kInvalidContentScriptsList = "Invalid value for 'content_scripts'."; const char* kInvalidCss = "Invalid value for 'content_scripts[*].css[*]'."; const char* kInvalidCssList = "Required value 'content_scripts[*].css' is invalid."; const char* kInvalidDescription = "Invalid value for 'description'."; const char* kInvalidGlobList = "Invalid value for 'content_scripts[*].*'."; const char* kInvalidGlob = "Invalid value for 'content_scripts[*].*[*]'."; const char* kInvalidIcons = "Invalid value for 'icons'."; const char* kInvalidIconPath = "Invalid value for 'icons[\"*\"]'."; const char* kInvalidJs = "Invalid value for 'content_scripts[*].js[*]'."; const char* kInvalidJsList = "Required value 'content_scripts[*].js' is invalid."; const char* kInvalidKey = "Value 'key' is missing or invalid."; const char* kInvalidManifest = "Manifest file is invalid."; const char* kInvalidMatchCount = "Invalid value for 'content_scripts[*].matches'. There must be at least" "one match specified."; const char* kInvalidMatch = "Invalid value for 'content_scripts[*].matches[*]'."; const char* kInvalidMatches = "Required value 'content_scripts[*].matches' is missing or invalid."; const char* kInvalidMinimumChromeVersion = "Invalid value for 'minimum_chrome_version'."; const char* kInvalidName = "Required value 'name' is missing or invalid."; const char* kInvalidPageAction = "Invalid value for 'page_action'."; const char* kInvalidPageActionName = "Invalid value for 'page_action.name'."; const char* kInvalidPageActionIconPath = "Invalid value for 'page_action.default_icon'."; const char* kInvalidPageActionsList = "Invalid value for 'page_actions'."; const char* kInvalidPageActionsListSize = "Invalid value for 'page_actions'. There can be at most one page action."; const char* kInvalidPageActionId = "Required value 'id' is missing or invalid."; const char* kInvalidPageActionDefaultTitle = "Invalid value for 'default_title'."; const char* kInvalidPageActionOldAndNewKeys = "Key \"*\" is deprecated. Key \"*\" has the same meaning. You can not " "use both."; const char* kInvalidPageActionPopup = "Invalid type for page action popup."; const char* kInvalidPageActionPopupHeight = "Invalid value for page action popup height [*]."; const char* kInvalidPageActionPopupPath = "Invalid value for page action popup path [*]."; const char* kInvalidPageActionTypeValue = "Invalid value for 'page_actions[*].type', expected 'tab' or 'permanent'."; const char* kInvalidPermissions = "Required value 'permissions' is missing or invalid."; const char* kInvalidPermission = "Invalid value for 'permissions[*]'."; const char* kInvalidPermissionScheme = "Invalid scheme for 'permissions[*]'. Only 'http' and 'https' are " "allowed."; const char* kInvalidPlugins = "Invalid value for 'plugins'."; const char* kInvalidPluginsPath = "Invalid value for 'plugins[*].path'."; const char* kInvalidPluginsPublic = "Invalid value for 'plugins[*].public'."; const char* kInvalidBackground = "Invalid value for 'background_page'."; const char* kInvalidRunAt = "Invalid value for 'content_scripts[*].run_at'."; const char* kInvalidSignature = "Value 'signature' is missing or invalid."; const char* kInvalidToolstrip = "Invalid value for 'toolstrips[*]'"; const char* kInvalidToolstrips = "Invalid value for 'toolstrips'."; const char* kInvalidVersion = "Required value 'version' is missing or invalid. It must be between 1-4 " "dot-separated integers each between 0 and 65536."; const char* kInvalidZipHash = "Required key 'zip_hash' is missing or invalid."; const char* kManifestParseError = "Manifest is not valid JSON."; const char* kManifestUnreadable = "Manifest file is missing or unreadable."; const char* kMissingFile = "At least one js or css file is required for 'content_scripts[*]'."; const char* kInvalidTheme = "Invalid value for 'theme'."; const char* kInvalidThemeImages = "Invalid value for theme images - images must be strings."; const char* kInvalidThemeImagesMissing = "Am image specified in the theme is missing."; const char* kInvalidThemeColors = "Invalid value for theme colors - colors must be integers"; const char* kInvalidThemeTints = "Invalid value for theme images - tints must be decimal numbers."; const char* kInvalidUpdateURL = "Invalid value for update url: '[*]'."; const char* kInvalidDefaultLocale = "Invalid value for default locale - locale name must be a string."; const char* kOneUISurfaceOnly = "An extension cannot have both a page action and a browser action."; const char* kThemesCannotContainExtensions = "A theme cannot contain extensions code."; const char* kLocalesNoDefaultLocaleSpecified = "Localization used, but default_locale wasn't specified in the manifest."; const char* kLocalesNoDefaultMessages = "Default locale is defined but default data couldn't be loaded."; const char* kLocalesNoValidLocaleNamesListed = "No valid locale name could be found in _locales directory."; const char* kLocalesTreeMissing = "Default locale was specified, but _locales subtree is missing."; const char* kLocalesMessagesFileMissing = "Messages file is missing for locale."; const char* kInvalidOptionsPage = "Invalid value for 'options_page'."; const char* kReservedMessageFound = "Reserved key * found in message catalog."; const char* kCannotAccessPage = "Cannot access contents of url \"*\". " "Extension manifest must request permission to access this host."; const char* kCannotScriptGallery = "The extensions gallery cannot be scripted."; } // namespace extension_manifest_errors namespace extension_urls { const char* kGalleryBrowsePrefix = "https://chrome.google.com/extensions"; const char* kGalleryDownloadPrefix = "https://clients2.googleusercontent.com/crx/download"; const char* kMiniGalleryBrowsePrefix = "https://tools.google.com/chrome/"; const char* kMiniGalleryDownloadPrefix = "https://dl-ssl.google.com/chrome/"; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Implementation of the installation validator. #include "chrome/installer/util/installation_validator.h" #include <algorithm> #include "base/logging.h" #include "base/version.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/helper.h" #include "chrome/installer/util/installation_state.h" namespace installer { BrowserDistribution::Type InstallationValidator::ChromeRules::distribution_type() const { return BrowserDistribution::CHROME_BROWSER; } void InstallationValidator::ChromeRules::AddProductSwitchExpectations( const InstallationState& machine_state, bool system_install, const ProductState& product_state, SwitchExpectations* expectations) const { const bool is_multi_install = product_state.uninstall_command().HasSwitch(switches::kMultiInstall); // --chrome should be present iff --multi-install. expectations->push_back(std::make_pair(std::string(switches::kChrome), is_multi_install)); // --chrome-frame --ready-mode should be present iff CF in ready mode. const ProductState* cf_state = machine_state.GetProductState(system_install, BrowserDistribution::CHROME_FRAME); const bool ready_mode = cf_state != NULL && cf_state->uninstall_command().HasSwitch(switches::kChromeFrameReadyMode); expectations->push_back(std::make_pair(std::string(switches::kChromeFrame), ready_mode)); expectations->push_back( std::make_pair(std::string(switches::kChromeFrameReadyMode), ready_mode)); } BrowserDistribution::Type InstallationValidator::ChromeFrameRules::distribution_type() const { return BrowserDistribution::CHROME_FRAME; } void InstallationValidator::ChromeFrameRules::AddProductSwitchExpectations( const InstallationState& machine_state, bool system_install, const ProductState& product_state, SwitchExpectations* expectations) const { // --chrome-frame must be present. expectations->push_back(std::make_pair(std::string(switches::kChromeFrame), true)); // --chrome must not be present. expectations->push_back(std::make_pair(std::string(switches::kChrome), false)); } // static const InstallationValidator::InstallationType InstallationValidator::kInstallationTypes[] = { NO_PRODUCTS, CHROME_SINGLE, CHROME_MULTI, CHROME_FRAME_SINGLE, CHROME_FRAME_SINGLE_CHROME_SINGLE, CHROME_FRAME_SINGLE_CHROME_MULTI, CHROME_FRAME_MULTI, CHROME_FRAME_MULTI_CHROME_MULTI, CHROME_FRAME_READY_MODE_CHROME_MULTI }; // Validates the multi-install binaries at level |system_level|. void InstallationValidator::ValidateBinaries( const InstallationState& machine_state, bool system_install, const ProductState& binaries_state, bool* is_valid) { const ChannelInfo& channel = binaries_state.channel(); // ap must have -multi if (!channel.IsMultiInstall()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are missing \"-multi\" in channel name: \"" << channel.value() << "\""; } // ap must have -chrome iff Chrome is installed const ProductState* chrome_state = machine_state.GetProductState( system_install, BrowserDistribution::CHROME_BROWSER); if (chrome_state != NULL) { if (!channel.IsChrome()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are missing \"chrome\" in channel name:" << " \"" << channel.value() << "\""; } } else if (channel.IsChrome()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries have \"-chrome\" in channel name, yet Chrome" " is not installed: \"" << channel.value() << "\""; } // ap must have -chromeframe iff Chrome Frame is installed multi const ProductState* cf_state = machine_state.GetProductState( system_install, BrowserDistribution::CHROME_FRAME); if (cf_state != NULL && cf_state->is_multi_install()) { if (!channel.IsChromeFrame()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are missing \"-chromeframe\" in channel" " name: \"" << channel.value() << "\""; } } else if (channel.IsChromeFrame()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries have \"-chromeframe\" in channel name, yet " "Chrome Frame is not installed multi: \"" << channel.value() << "\""; } // ap must have -readymode iff Chrome Frame is installed in ready-mode if (cf_state != NULL && cf_state->uninstall_command().HasSwitch( installer::switches::kChromeFrameReadyMode)) { if (!channel.IsReadyMode()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are missing \"-readymode\" in channel" " name: \"" << channel.value() << "\""; } } else if (channel.IsReadyMode()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries have \"-readymode\" in channel name, yet " "Chrome Frame is not in ready mode: \"" << channel.value() << "\""; } // Chrome or Chrome Frame must be present if (chrome_state == NULL && cf_state == NULL) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are present with no other products."; } // Chrome must be multi-install if present. if (chrome_state != NULL && !chrome_state->is_multi_install()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are present yet Chrome is not multi-install."; } // Chrome Frame must be multi-install if Chrome is not present. if (cf_state != NULL && chrome_state == NULL && !cf_state->is_multi_install()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are present without Chrome yet Chrome Frame " "is not multi-install."; } } // Validates the path to |setup_exe| for the product described by |ctx|. void InstallationValidator::ValidateSetupPath(const ProductContext& ctx, const FilePath& setup_exe, const char* purpose, bool* is_valid) { DCHECK(is_valid); BrowserDistribution* bins_dist = ctx.dist; if (ctx.state.is_multi_install()) { bins_dist = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_BINARIES); } FilePath expected_path = installer::GetChromeInstallPath(ctx.system_install, bins_dist); expected_path = expected_path .AppendASCII(ctx.state.version().GetString()) .Append(installer::kInstallerDir) .Append(installer::kSetupExe); if (!FilePath::CompareEqualIgnoreCase(expected_path.value(), setup_exe.value())) { *is_valid = false; LOG(ERROR) << ctx.dist->GetApplicationName() << " path to " << purpose << " is not " << expected_path.value() << ": " << setup_exe.value(); } } // Validates that |command| meets the expectations described in |expected|. void InstallationValidator::ValidateCommandExpectations( const ProductContext& ctx, const CommandLine& command, const SwitchExpectations& expected, const char* source, bool* is_valid) { for (SwitchExpectations::size_type i = 0, size = expected.size(); i < size; ++i) { const SwitchExpectations::value_type& expectation = expected[i]; if (command.HasSwitch(expectation.first) != expectation.second) { *is_valid = false; LOG(ERROR) << ctx.dist->GetApplicationName() << " " << source << (expectation.second ? " is missing" : " has") << " \"" << expectation.first << "\"" << (expectation.second ? "" : " but shouldn't") << ": " << command.command_line_string(); } } } // Validates that |command|, originating from |source|, is formed properly for // the product described by |ctx| void InstallationValidator::ValidateUninstallCommand(const ProductContext& ctx, const CommandLine& command, const char* source, bool* is_valid) { DCHECK(is_valid); ValidateSetupPath(ctx, command.GetProgram(), "uninstaller", is_valid); const bool is_multi_install = ctx.state.is_multi_install(); SwitchExpectations expected; expected.push_back(std::make_pair(std::string(switches::kUninstall), true)); expected.push_back(std::make_pair(std::string(switches::kSystemLevel), ctx.system_install)); expected.push_back(std::make_pair(std::string(switches::kMultiInstall), is_multi_install)); ctx.rules.AddProductSwitchExpectations(ctx.machine_state, ctx.system_install, ctx.state, &expected); ValidateCommandExpectations(ctx, command, expected, source, is_valid); } // Validates the rename command for the product described by |ctx|. void InstallationValidator::ValidateRenameCommand(const ProductContext& ctx, bool* is_valid) { DCHECK(is_valid); DCHECK(!ctx.state.rename_cmd().empty()); CommandLine command = CommandLine::FromString(ctx.state.rename_cmd()); ValidateSetupPath(ctx, command.GetProgram(), "in-use renamer", is_valid); SwitchExpectations expected; expected.push_back(std::make_pair(std::string(switches::kRenameChromeExe), true)); expected.push_back(std::make_pair(std::string(switches::kSystemLevel), ctx.system_install)); expected.push_back(std::make_pair(std::string(switches::kMultiInstall), ctx.state.is_multi_install())); ctx.rules.AddProductSwitchExpectations(ctx.machine_state, ctx.system_install, ctx.state, &expected); ValidateCommandExpectations(ctx, command, expected, "in-use renamer", is_valid); } // Validates the "opv" and "cmd" values for the product described in |ctx|. void InstallationValidator::ValidateOldVersionValues( const ProductContext& ctx, bool* is_valid) { DCHECK(is_valid); // opv and cmd must both be present or both absent if (ctx.state.old_version() == NULL) { if (!ctx.state.rename_cmd().empty()) { *is_valid = false; LOG(ERROR) << ctx.dist->GetApplicationName() << " has a rename command but no opv: " << ctx.state.rename_cmd(); } } else { if (ctx.state.rename_cmd().empty()) { *is_valid = false; LOG(ERROR) << ctx.dist->GetApplicationName() << " has an opv but no rename command: " << ctx.state.old_version()->GetString(); } else { ValidateRenameCommand(ctx, is_valid); } } } // Validates the multi-install state of the product described in |ctx|. void InstallationValidator::ValidateMultiInstallProduct( const ProductContext& ctx, bool* is_valid) { DCHECK(is_valid); const ProductState* binaries = ctx.machine_state.GetProductState(ctx.system_install, BrowserDistribution::CHROME_BINARIES); DCHECK(binaries); // Version must match that of binaries. if (ctx.state.version().CompareTo(binaries->version()) != 0) { *is_valid = false; LOG(ERROR) << "Version of " << ctx.dist->GetApplicationName() << " (" << ctx.state.version().GetString() << ") does not " "match that of Chrome Binaries (" << binaries->version().GetString() << ")."; } // Channel value must match that of binaries. if (!ctx.state.channel().Equals(binaries->channel())) { *is_valid = false; LOG(ERROR) << "Channel name of " << ctx.dist->GetApplicationName() << " (" << ctx.state.channel().value() << ") does not match that of Chrome Binaries (" << binaries->channel().value() << ")."; } } // Validates the product described in |product_state| according to |rules|. void InstallationValidator::ValidateProduct( const InstallationState& machine_state, bool system_install, const ProductState& product_state, const ProductRules& rules, bool* is_valid) { DCHECK(is_valid); ProductContext ctx = { machine_state, system_install, BrowserDistribution::GetSpecificDistribution(rules.distribution_type()), product_state, rules }; ValidateUninstallCommand(ctx, product_state.uninstall_command(), "Google Update uninstall command", is_valid); ValidateOldVersionValues(ctx, is_valid); if (product_state.is_multi_install()) ValidateMultiInstallProduct(ctx, is_valid); } // static bool InstallationValidator::ValidateInstallationTypeForState( const InstallationState& machine_state, bool system_level, InstallationType* type) { DCHECK(type); bool rock_on = true; *type = NO_PRODUCTS; // Does the system have any multi-installed products? const ProductState* multi_state = machine_state.GetProductState(system_level, BrowserDistribution::CHROME_BINARIES); if (multi_state != NULL) ValidateBinaries(machine_state, system_level, *multi_state, &rock_on); // Is Chrome installed? const ProductState* product_state = machine_state.GetProductState(system_level, BrowserDistribution::CHROME_BROWSER); if (product_state != NULL) { ChromeRules chrome_rules; ValidateProduct(machine_state, system_level, *product_state, chrome_rules, &rock_on); *type = static_cast<InstallationType>( *type | (product_state->is_multi_install() ? ProductBits::CHROME_MULTI : ProductBits::CHROME_SINGLE)); } // Is Chrome Frame installed? product_state = machine_state.GetProductState(system_level, BrowserDistribution::CHROME_FRAME); if (product_state != NULL) { ChromeFrameRules chrome_frame_rules; ValidateProduct(machine_state, system_level, *product_state, chrome_frame_rules, &rock_on); int cf_bit = !product_state->is_multi_install() ? ProductBits::CHROME_FRAME_SINGLE : (product_state->uninstall_command().HasSwitch( switches::kChromeFrameReadyMode) ? ProductBits::CHROME_FRAME_READY_MODE : ProductBits::CHROME_FRAME_MULTI); *type = static_cast<InstallationType>(*type | cf_bit); } DCHECK_NE(std::find(&kInstallationTypes[0], &kInstallationTypes[arraysize(kInstallationTypes)], *type), &kInstallationTypes[arraysize(kInstallationTypes)]) << "Invalid combination of products found on system (" << *type << ")"; return rock_on; } // static bool InstallationValidator::ValidateInstallationType(bool system_level, InstallationType* type) { DCHECK(type); InstallationState machine_state; machine_state.Initialize(); return ValidateInstallationTypeForState(machine_state, system_level, type); } } // namespace installer <commit_msg>Allow --chrome in a single-install's uninstall and rename commands so that mini installer tests don't cry when they evaluate M10 builds.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Implementation of the installation validator. #include "chrome/installer/util/installation_validator.h" #include <algorithm> #include "base/logging.h" #include "base/version.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/helper.h" #include "chrome/installer/util/installation_state.h" namespace installer { BrowserDistribution::Type InstallationValidator::ChromeRules::distribution_type() const { return BrowserDistribution::CHROME_BROWSER; } void InstallationValidator::ChromeRules::AddProductSwitchExpectations( const InstallationState& machine_state, bool system_install, const ProductState& product_state, SwitchExpectations* expectations) const { const bool is_multi_install = product_state.uninstall_command().HasSwitch(switches::kMultiInstall); // --chrome should be present iff --multi-install. This wasn't the case in // Chrome 10 (between r68996 and r72497), though, so consider it optional. // --chrome-frame --ready-mode should be present iff CF in ready mode. const ProductState* cf_state = machine_state.GetProductState(system_install, BrowserDistribution::CHROME_FRAME); const bool ready_mode = cf_state != NULL && cf_state->uninstall_command().HasSwitch(switches::kChromeFrameReadyMode); expectations->push_back(std::make_pair(std::string(switches::kChromeFrame), ready_mode)); expectations->push_back( std::make_pair(std::string(switches::kChromeFrameReadyMode), ready_mode)); } BrowserDistribution::Type InstallationValidator::ChromeFrameRules::distribution_type() const { return BrowserDistribution::CHROME_FRAME; } void InstallationValidator::ChromeFrameRules::AddProductSwitchExpectations( const InstallationState& machine_state, bool system_install, const ProductState& product_state, SwitchExpectations* expectations) const { // --chrome-frame must be present. expectations->push_back(std::make_pair(std::string(switches::kChromeFrame), true)); // --chrome must not be present. expectations->push_back(std::make_pair(std::string(switches::kChrome), false)); } // static const InstallationValidator::InstallationType InstallationValidator::kInstallationTypes[] = { NO_PRODUCTS, CHROME_SINGLE, CHROME_MULTI, CHROME_FRAME_SINGLE, CHROME_FRAME_SINGLE_CHROME_SINGLE, CHROME_FRAME_SINGLE_CHROME_MULTI, CHROME_FRAME_MULTI, CHROME_FRAME_MULTI_CHROME_MULTI, CHROME_FRAME_READY_MODE_CHROME_MULTI }; // Validates the multi-install binaries at level |system_level|. void InstallationValidator::ValidateBinaries( const InstallationState& machine_state, bool system_install, const ProductState& binaries_state, bool* is_valid) { const ChannelInfo& channel = binaries_state.channel(); // ap must have -multi if (!channel.IsMultiInstall()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are missing \"-multi\" in channel name: \"" << channel.value() << "\""; } // ap must have -chrome iff Chrome is installed const ProductState* chrome_state = machine_state.GetProductState( system_install, BrowserDistribution::CHROME_BROWSER); if (chrome_state != NULL) { if (!channel.IsChrome()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are missing \"chrome\" in channel name:" << " \"" << channel.value() << "\""; } } else if (channel.IsChrome()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries have \"-chrome\" in channel name, yet Chrome" " is not installed: \"" << channel.value() << "\""; } // ap must have -chromeframe iff Chrome Frame is installed multi const ProductState* cf_state = machine_state.GetProductState( system_install, BrowserDistribution::CHROME_FRAME); if (cf_state != NULL && cf_state->is_multi_install()) { if (!channel.IsChromeFrame()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are missing \"-chromeframe\" in channel" " name: \"" << channel.value() << "\""; } } else if (channel.IsChromeFrame()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries have \"-chromeframe\" in channel name, yet " "Chrome Frame is not installed multi: \"" << channel.value() << "\""; } // ap must have -readymode iff Chrome Frame is installed in ready-mode if (cf_state != NULL && cf_state->uninstall_command().HasSwitch( installer::switches::kChromeFrameReadyMode)) { if (!channel.IsReadyMode()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are missing \"-readymode\" in channel" " name: \"" << channel.value() << "\""; } } else if (channel.IsReadyMode()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries have \"-readymode\" in channel name, yet " "Chrome Frame is not in ready mode: \"" << channel.value() << "\""; } // Chrome or Chrome Frame must be present if (chrome_state == NULL && cf_state == NULL) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are present with no other products."; } // Chrome must be multi-install if present. if (chrome_state != NULL && !chrome_state->is_multi_install()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are present yet Chrome is not multi-install."; } // Chrome Frame must be multi-install if Chrome is not present. if (cf_state != NULL && chrome_state == NULL && !cf_state->is_multi_install()) { *is_valid = false; LOG(ERROR) << "Chrome Binaries are present without Chrome yet Chrome Frame " "is not multi-install."; } } // Validates the path to |setup_exe| for the product described by |ctx|. void InstallationValidator::ValidateSetupPath(const ProductContext& ctx, const FilePath& setup_exe, const char* purpose, bool* is_valid) { DCHECK(is_valid); BrowserDistribution* bins_dist = ctx.dist; if (ctx.state.is_multi_install()) { bins_dist = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_BINARIES); } FilePath expected_path = installer::GetChromeInstallPath(ctx.system_install, bins_dist); expected_path = expected_path .AppendASCII(ctx.state.version().GetString()) .Append(installer::kInstallerDir) .Append(installer::kSetupExe); if (!FilePath::CompareEqualIgnoreCase(expected_path.value(), setup_exe.value())) { *is_valid = false; LOG(ERROR) << ctx.dist->GetApplicationName() << " path to " << purpose << " is not " << expected_path.value() << ": " << setup_exe.value(); } } // Validates that |command| meets the expectations described in |expected|. void InstallationValidator::ValidateCommandExpectations( const ProductContext& ctx, const CommandLine& command, const SwitchExpectations& expected, const char* source, bool* is_valid) { for (SwitchExpectations::size_type i = 0, size = expected.size(); i < size; ++i) { const SwitchExpectations::value_type& expectation = expected[i]; if (command.HasSwitch(expectation.first) != expectation.second) { *is_valid = false; LOG(ERROR) << ctx.dist->GetApplicationName() << " " << source << (expectation.second ? " is missing" : " has") << " \"" << expectation.first << "\"" << (expectation.second ? "" : " but shouldn't") << ": " << command.command_line_string(); } } } // Validates that |command|, originating from |source|, is formed properly for // the product described by |ctx| void InstallationValidator::ValidateUninstallCommand(const ProductContext& ctx, const CommandLine& command, const char* source, bool* is_valid) { DCHECK(is_valid); ValidateSetupPath(ctx, command.GetProgram(), "uninstaller", is_valid); const bool is_multi_install = ctx.state.is_multi_install(); SwitchExpectations expected; expected.push_back(std::make_pair(std::string(switches::kUninstall), true)); expected.push_back(std::make_pair(std::string(switches::kSystemLevel), ctx.system_install)); expected.push_back(std::make_pair(std::string(switches::kMultiInstall), is_multi_install)); ctx.rules.AddProductSwitchExpectations(ctx.machine_state, ctx.system_install, ctx.state, &expected); ValidateCommandExpectations(ctx, command, expected, source, is_valid); } // Validates the rename command for the product described by |ctx|. void InstallationValidator::ValidateRenameCommand(const ProductContext& ctx, bool* is_valid) { DCHECK(is_valid); DCHECK(!ctx.state.rename_cmd().empty()); CommandLine command = CommandLine::FromString(ctx.state.rename_cmd()); ValidateSetupPath(ctx, command.GetProgram(), "in-use renamer", is_valid); SwitchExpectations expected; expected.push_back(std::make_pair(std::string(switches::kRenameChromeExe), true)); expected.push_back(std::make_pair(std::string(switches::kSystemLevel), ctx.system_install)); expected.push_back(std::make_pair(std::string(switches::kMultiInstall), ctx.state.is_multi_install())); ctx.rules.AddProductSwitchExpectations(ctx.machine_state, ctx.system_install, ctx.state, &expected); ValidateCommandExpectations(ctx, command, expected, "in-use renamer", is_valid); } // Validates the "opv" and "cmd" values for the product described in |ctx|. void InstallationValidator::ValidateOldVersionValues( const ProductContext& ctx, bool* is_valid) { DCHECK(is_valid); // opv and cmd must both be present or both absent if (ctx.state.old_version() == NULL) { if (!ctx.state.rename_cmd().empty()) { *is_valid = false; LOG(ERROR) << ctx.dist->GetApplicationName() << " has a rename command but no opv: " << ctx.state.rename_cmd(); } } else { if (ctx.state.rename_cmd().empty()) { *is_valid = false; LOG(ERROR) << ctx.dist->GetApplicationName() << " has an opv but no rename command: " << ctx.state.old_version()->GetString(); } else { ValidateRenameCommand(ctx, is_valid); } } } // Validates the multi-install state of the product described in |ctx|. void InstallationValidator::ValidateMultiInstallProduct( const ProductContext& ctx, bool* is_valid) { DCHECK(is_valid); const ProductState* binaries = ctx.machine_state.GetProductState(ctx.system_install, BrowserDistribution::CHROME_BINARIES); DCHECK(binaries); // Version must match that of binaries. if (ctx.state.version().CompareTo(binaries->version()) != 0) { *is_valid = false; LOG(ERROR) << "Version of " << ctx.dist->GetApplicationName() << " (" << ctx.state.version().GetString() << ") does not " "match that of Chrome Binaries (" << binaries->version().GetString() << ")."; } // Channel value must match that of binaries. if (!ctx.state.channel().Equals(binaries->channel())) { *is_valid = false; LOG(ERROR) << "Channel name of " << ctx.dist->GetApplicationName() << " (" << ctx.state.channel().value() << ") does not match that of Chrome Binaries (" << binaries->channel().value() << ")."; } } // Validates the product described in |product_state| according to |rules|. void InstallationValidator::ValidateProduct( const InstallationState& machine_state, bool system_install, const ProductState& product_state, const ProductRules& rules, bool* is_valid) { DCHECK(is_valid); ProductContext ctx = { machine_state, system_install, BrowserDistribution::GetSpecificDistribution(rules.distribution_type()), product_state, rules }; ValidateUninstallCommand(ctx, product_state.uninstall_command(), "Google Update uninstall command", is_valid); ValidateOldVersionValues(ctx, is_valid); if (product_state.is_multi_install()) ValidateMultiInstallProduct(ctx, is_valid); } // static bool InstallationValidator::ValidateInstallationTypeForState( const InstallationState& machine_state, bool system_level, InstallationType* type) { DCHECK(type); bool rock_on = true; *type = NO_PRODUCTS; // Does the system have any multi-installed products? const ProductState* multi_state = machine_state.GetProductState(system_level, BrowserDistribution::CHROME_BINARIES); if (multi_state != NULL) ValidateBinaries(machine_state, system_level, *multi_state, &rock_on); // Is Chrome installed? const ProductState* product_state = machine_state.GetProductState(system_level, BrowserDistribution::CHROME_BROWSER); if (product_state != NULL) { ChromeRules chrome_rules; ValidateProduct(machine_state, system_level, *product_state, chrome_rules, &rock_on); *type = static_cast<InstallationType>( *type | (product_state->is_multi_install() ? ProductBits::CHROME_MULTI : ProductBits::CHROME_SINGLE)); } // Is Chrome Frame installed? product_state = machine_state.GetProductState(system_level, BrowserDistribution::CHROME_FRAME); if (product_state != NULL) { ChromeFrameRules chrome_frame_rules; ValidateProduct(machine_state, system_level, *product_state, chrome_frame_rules, &rock_on); int cf_bit = !product_state->is_multi_install() ? ProductBits::CHROME_FRAME_SINGLE : (product_state->uninstall_command().HasSwitch( switches::kChromeFrameReadyMode) ? ProductBits::CHROME_FRAME_READY_MODE : ProductBits::CHROME_FRAME_MULTI); *type = static_cast<InstallationType>(*type | cf_bit); } DCHECK_NE(std::find(&kInstallationTypes[0], &kInstallationTypes[arraysize(kInstallationTypes)], *type), &kInstallationTypes[arraysize(kInstallationTypes)]) << "Invalid combination of products found on system (" << *type << ")"; return rock_on; } // static bool InstallationValidator::ValidateInstallationType(bool system_level, InstallationType* type) { DCHECK(type); InstallationState machine_state; machine_state.Initialize(); return ValidateInstallationTypeForState(machine_state, system_level, type); } } // namespace installer <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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/test/chrome_plugin/test_chrome_plugin.h" #include "base/at_exit.h" #include "base/basictypes.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/string_util.h" #include "chrome/common/chrome_plugin_api.h" #include "googleurl/src/gurl.h" static CPID g_cpid; static CPBrowserFuncs g_cpbrowser_funcs; static CPRequestFuncs g_cprequest_funcs; static CPResponseFuncs g_cpresponse_funcs; static TestFuncParams::BrowserFuncs g_cptest_funcs; // Create a global AtExitManager so that our code can use code from base that // uses Singletons, for example. We don't care about static constructors here. static base::AtExitManager global_at_exit_manager; const TestResponsePayload* FindPayload(const char* url) { for (int i = 0; i < arraysize(kChromeTestPluginPayloads); ++i) { if (strcmp(kChromeTestPluginPayloads[i].url, url) == 0) return &kChromeTestPluginPayloads[i]; } return NULL; } std::string GetPayloadHeaders(const TestResponsePayload* payload) { return StringPrintf( "HTTP/1.1 200 OK%c" "Content-type: %s%c" "%c", 0, payload->mime_type, 0, 0); } void STDCALL InvokeLaterCallback(void* data) { Task* task = static_cast<Task*>(data); task->Run(); delete task; } // ResponseStream: Manages the streaming of the payload data. class ResponseStream : public base::RefCounted<ResponseStream> { public: ResponseStream(const TestResponsePayload* payload, CPRequest* request); ~ResponseStream() { request_->pdata = NULL; } void Init(); int GetResponseInfo(CPResponseInfoType type, void* buf, uint32 buf_size); int ReadData(void* buf, uint32 buf_size); private: // Called asynchronously via InvokeLater. void ResponseStarted(); int ReadCompleted(void* buf, uint32 buf_size); enum ReadyStates { READY_INVALID = 0, READY_WAITING = 1, READY_GOT_HEADERS = 2, READY_GOT_DATA = 3, }; const TestResponsePayload* payload_; uint32 offset_; int ready_state_; CPRequest* request_; }; ResponseStream::ResponseStream(const TestResponsePayload* payload, CPRequest* request) : payload_(payload), offset_(0), request_(request), ready_state_(READY_INVALID) { } void ResponseStream::Init() { if (payload_->async) { // simulate an asynchronous start complete ready_state_ = READY_WAITING; g_cptest_funcs.invoke_later( InvokeLaterCallback, // downcast to Task before void, since we upcast from void to Task. static_cast<Task*>( NewRunnableMethod(this, &ResponseStream::ResponseStarted)), 500); } else { ready_state_ = READY_GOT_DATA; } } int ResponseStream::GetResponseInfo(CPResponseInfoType type, void* buf, uint32 buf_size) { if (ready_state_ < READY_GOT_HEADERS) return CPERR_FAILURE; switch (type) { case CPRESPONSEINFO_HTTP_STATUS: if (buf) { int status = payload_->status; memcpy(buf, &payload_->status, buf_size); } break; case CPRESPONSEINFO_HTTP_RAW_HEADERS: { std::string headers = GetPayloadHeaders(payload_); if (buf_size < headers.size()+1) return static_cast<int>(headers.size()+1); if (buf) memcpy(buf, headers.c_str(), headers.size()+1); break; } default: return CPERR_INVALID_VERSION; } return CPERR_SUCCESS; } int ResponseStream::ReadData(void* buf, uint32 buf_size) { if (ready_state_ < READY_GOT_DATA) { // simulate an asynchronous read complete g_cptest_funcs.invoke_later( InvokeLaterCallback, // downcast to Task before void, since we upcast from void to Task. static_cast<Task*>( NewRunnableMethod(this, &ResponseStream::ReadCompleted, buf, buf_size)), 500); return CPERR_IO_PENDING; } // synchronously complete the read return ReadCompleted(buf, buf_size); } void ResponseStream::ResponseStarted() { ready_state_ = READY_GOT_HEADERS; g_cpresponse_funcs.start_completed(request_, CPERR_SUCCESS); } int ResponseStream::ReadCompleted(void* buf, uint32 buf_size) { uint32 size = static_cast<uint32>(strlen(payload_->body)); uint32 avail = size - offset_; uint32 count = buf_size; if (count > avail) count = avail; if (count) { memcpy(buf, payload_->body + offset_, count); } offset_ += count; if (ready_state_ < READY_GOT_DATA) { ready_state_ = READY_GOT_DATA; g_cpresponse_funcs.read_completed(request_, static_cast<int>(count)); } return count; } // CPP Funcs CPError STDCALL CPP_Shutdown() { return CPERR_SUCCESS; } CPBool STDCALL CPP_ShouldInterceptRequest(CPRequest* request) { DCHECK(StrNCaseCmp(request->url, kChromeTestPluginProtocol, arraysize(kChromeTestPluginProtocol) - 1) == 0); return FindPayload(request->url) != NULL; } CPError STDCALL CPR_StartRequest(CPRequest* request) { const TestResponsePayload* payload = FindPayload(request->url); DCHECK(payload); ResponseStream* stream = new ResponseStream(payload, request); stream->AddRef(); // Released in CPR_EndRequest stream->Init(); request->pdata = stream; return payload->async ? CPERR_IO_PENDING : CPERR_SUCCESS; } void STDCALL CPR_EndRequest(CPRequest* request, CPError reason) { ResponseStream* stream = static_cast<ResponseStream*>(request->pdata); request->pdata = NULL; stream->Release(); // balances AddRef in CPR_StartRequest } void STDCALL CPR_SetExtraRequestHeaders(CPRequest* request, const char* headers) { // doesn't affect us } void STDCALL CPR_SetRequestLoadFlags(CPRequest* request, uint32 flags) { // doesn't affect us } void STDCALL CPR_AppendDataToUpload(CPRequest* request, const char* bytes, int bytes_len) { // doesn't affect us } CPError STDCALL CPR_AppendFileToUpload(CPRequest* request, const char* filepath, uint64 offset, uint64 length) { // doesn't affect us return CPERR_FAILURE; } int STDCALL CPR_GetResponseInfo(CPRequest* request, CPResponseInfoType type, void* buf, uint32 buf_size) { ResponseStream* stream = static_cast<ResponseStream*>(request->pdata); return stream->GetResponseInfo(type, buf, buf_size); } int STDCALL CPR_Read(CPRequest* request, void* buf, uint32 buf_size) { ResponseStream* stream = static_cast<ResponseStream*>(request->pdata); return stream->ReadData(buf, buf_size); } // RequestResponse: manages the retrieval of response data from the host class RequestResponse { public: RequestResponse(const std::string& raw_headers) : raw_headers_(raw_headers), offset_(0) {} void StartReading(CPRequest* request); void ReadCompleted(CPRequest* request, int bytes_read); private: std::string raw_headers_; std::string body_; int offset_; }; void RequestResponse::StartReading(CPRequest* request) { int rv = 0; const uint32 kReadSize = 4096; do { body_.resize(offset_ + kReadSize); rv = g_cprequest_funcs.read(request, &body_[offset_], kReadSize); if (rv > 0) offset_ += rv; } while (rv > 0); if (rv != CPERR_IO_PENDING) { // Either an error occurred, or we are done. ReadCompleted(request, rv); } } void RequestResponse::ReadCompleted(CPRequest* request, int bytes_read) { if (bytes_read > 0) { offset_ += bytes_read; StartReading(request); return; } body_.resize(offset_); bool success = (bytes_read == 0); g_cptest_funcs.test_complete(request, success, raw_headers_, body_); g_cprequest_funcs.end_request(request, CPERR_CANCELLED); delete this; } void STDCALL CPRR_ReceivedRedirect(CPRequest* request, const char* new_url) { } void STDCALL CPRR_StartCompleted(CPRequest* request, CPError result) { DCHECK(!request->pdata); std::string raw_headers; int size = g_cprequest_funcs.get_response_info( request, CPRESPONSEINFO_HTTP_RAW_HEADERS, NULL, 0); int rv = size < 0 ? size : g_cprequest_funcs.get_response_info( request, CPRESPONSEINFO_HTTP_RAW_HEADERS, WriteInto(&raw_headers, size+1), size); if (rv != CPERR_SUCCESS) { g_cptest_funcs.test_complete(request, false, std::string(), std::string()); g_cprequest_funcs.end_request(request, CPERR_CANCELLED); return; } RequestResponse* response = new RequestResponse(raw_headers); request->pdata = response; response->StartReading(request); } void STDCALL CPRR_ReadCompleted(CPRequest* request, int bytes_read) { RequestResponse* response = reinterpret_cast<RequestResponse*>(request->pdata); response->ReadCompleted(request, bytes_read); } int STDCALL CPT_MakeRequest(const char* method, const GURL& url) { CPRequest* request = NULL; if (g_cpbrowser_funcs.create_request(g_cpid, NULL, method, url.spec().c_str(), &request) != CPERR_SUCCESS || !request) { return CPERR_FAILURE; } g_cprequest_funcs.set_request_load_flags(request, CPREQUESTLOAD_DISABLE_INTERCEPT); if (strcmp(method, "POST") == 0) { g_cprequest_funcs.set_extra_request_headers( request, "Content-Type: text/plain"); g_cprequest_funcs.append_data_to_upload( request, kChromeTestPluginPostData, arraysize(kChromeTestPluginPostData) - 1); } int rv = g_cprequest_funcs.start_request(request); if (rv == CPERR_SUCCESS) { CPRR_StartCompleted(request, CPERR_SUCCESS); } else if (rv != CPERR_IO_PENDING) { g_cprequest_funcs.end_request(request, CPERR_CANCELLED); return CPERR_FAILURE; } return CPERR_SUCCESS; } // DLL entry points CPError STDCALL CP_Initialize(CPID id, const CPBrowserFuncs* bfuncs, CPPluginFuncs* pfuncs) { if (bfuncs == NULL || pfuncs == NULL) return CPERR_FAILURE; if (CP_GET_MAJOR_VERSION(bfuncs->version) > CP_MAJOR_VERSION) return CPERR_INVALID_VERSION; if (bfuncs->size < sizeof(CPBrowserFuncs) || pfuncs->size < sizeof(CPPluginFuncs)) return CPERR_INVALID_VERSION; pfuncs->version = CP_VERSION; pfuncs->shutdown = CPP_Shutdown; pfuncs->should_intercept_request = CPP_ShouldInterceptRequest; static CPRequestFuncs request_funcs; request_funcs.start_request = CPR_StartRequest; request_funcs.end_request = CPR_EndRequest; request_funcs.set_extra_request_headers = CPR_SetExtraRequestHeaders; request_funcs.set_request_load_flags = CPR_SetRequestLoadFlags; request_funcs.append_data_to_upload = CPR_AppendDataToUpload; request_funcs.get_response_info = CPR_GetResponseInfo; request_funcs.read = CPR_Read; request_funcs.append_file_to_upload = CPR_AppendFileToUpload; pfuncs->request_funcs = &request_funcs; static CPResponseFuncs response_funcs; response_funcs.received_redirect = CPRR_ReceivedRedirect; response_funcs.start_completed = CPRR_StartCompleted; response_funcs.read_completed = CPRR_ReadCompleted; pfuncs->response_funcs = &response_funcs; g_cpid = id; g_cpbrowser_funcs = *bfuncs; g_cprequest_funcs = *bfuncs->request_funcs; g_cpresponse_funcs = *bfuncs->response_funcs; g_cpbrowser_funcs = *bfuncs; const char* protocols[] = {kChromeTestPluginProtocol}; g_cpbrowser_funcs.enable_request_intercept(g_cpid, protocols, 1); return CPERR_SUCCESS; } int STDCALL CP_Test(void* vparam) { TestFuncParams* param = reinterpret_cast<TestFuncParams*>(vparam); param->pfuncs.test_make_request = CPT_MakeRequest; g_cptest_funcs = param->bfuncs; return CPERR_SUCCESS; } <commit_msg>Some cleanups for gcc warnings:<commit_after>// Copyright (c) 2006-2008 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/test/chrome_plugin/test_chrome_plugin.h" #include "base/at_exit.h" #include "base/basictypes.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/string_util.h" #include "chrome/common/chrome_plugin_api.h" #include "googleurl/src/gurl.h" static CPID g_cpid; static CPBrowserFuncs g_cpbrowser_funcs; static CPRequestFuncs g_cprequest_funcs; static CPResponseFuncs g_cpresponse_funcs; static TestFuncParams::BrowserFuncs g_cptest_funcs; // Create a global AtExitManager so that our code can use code from base that // uses Singletons, for example. We don't care about static constructors here. static base::AtExitManager global_at_exit_manager; const TestResponsePayload* FindPayload(const char* url) { for (size_t i = 0; i < arraysize(kChromeTestPluginPayloads); ++i) { if (strcmp(kChromeTestPluginPayloads[i].url, url) == 0) return &kChromeTestPluginPayloads[i]; } return NULL; } std::string GetPayloadHeaders(const TestResponsePayload* payload) { return StringPrintf( "HTTP/1.1 200 OK%c" "Content-type: %s%c" "%c", 0, payload->mime_type, 0, 0); } void STDCALL InvokeLaterCallback(void* data) { Task* task = static_cast<Task*>(data); task->Run(); delete task; } // ResponseStream: Manages the streaming of the payload data. class ResponseStream : public base::RefCounted<ResponseStream> { public: ResponseStream(const TestResponsePayload* payload, CPRequest* request); ~ResponseStream() { request_->pdata = NULL; } void Init(); int GetResponseInfo(CPResponseInfoType type, void* buf, uint32 buf_size); int ReadData(void* buf, uint32 buf_size); private: // Called asynchronously via InvokeLater. void ResponseStarted(); int ReadCompleted(void* buf, uint32 buf_size); enum ReadyStates { READY_INVALID = 0, READY_WAITING = 1, READY_GOT_HEADERS = 2, READY_GOT_DATA = 3, }; const TestResponsePayload* payload_; uint32 offset_; int ready_state_; CPRequest* request_; }; ResponseStream::ResponseStream(const TestResponsePayload* payload, CPRequest* request) : payload_(payload), offset_(0), ready_state_(READY_INVALID), request_(request) { } void ResponseStream::Init() { if (payload_->async) { // simulate an asynchronous start complete ready_state_ = READY_WAITING; g_cptest_funcs.invoke_later( InvokeLaterCallback, // downcast to Task before void, since we upcast from void to Task. static_cast<Task*>( NewRunnableMethod(this, &ResponseStream::ResponseStarted)), 500); } else { ready_state_ = READY_GOT_DATA; } } int ResponseStream::GetResponseInfo(CPResponseInfoType type, void* buf, uint32 buf_size) { if (ready_state_ < READY_GOT_HEADERS) return CPERR_FAILURE; switch (type) { case CPRESPONSEINFO_HTTP_STATUS: if (buf) memcpy(buf, &payload_->status, buf_size); break; case CPRESPONSEINFO_HTTP_RAW_HEADERS: { std::string headers = GetPayloadHeaders(payload_); if (buf_size < headers.size()+1) return static_cast<int>(headers.size()+1); if (buf) memcpy(buf, headers.c_str(), headers.size()+1); break; } default: return CPERR_INVALID_VERSION; } return CPERR_SUCCESS; } int ResponseStream::ReadData(void* buf, uint32 buf_size) { if (ready_state_ < READY_GOT_DATA) { // simulate an asynchronous read complete g_cptest_funcs.invoke_later( InvokeLaterCallback, // downcast to Task before void, since we upcast from void to Task. static_cast<Task*>( NewRunnableMethod(this, &ResponseStream::ReadCompleted, buf, buf_size)), 500); return CPERR_IO_PENDING; } // synchronously complete the read return ReadCompleted(buf, buf_size); } void ResponseStream::ResponseStarted() { ready_state_ = READY_GOT_HEADERS; g_cpresponse_funcs.start_completed(request_, CPERR_SUCCESS); } int ResponseStream::ReadCompleted(void* buf, uint32 buf_size) { uint32 size = static_cast<uint32>(strlen(payload_->body)); uint32 avail = size - offset_; uint32 count = buf_size; if (count > avail) count = avail; if (count) { memcpy(buf, payload_->body + offset_, count); } offset_ += count; if (ready_state_ < READY_GOT_DATA) { ready_state_ = READY_GOT_DATA; g_cpresponse_funcs.read_completed(request_, static_cast<int>(count)); } return count; } // CPP Funcs CPError STDCALL CPP_Shutdown() { return CPERR_SUCCESS; } CPBool STDCALL CPP_ShouldInterceptRequest(CPRequest* request) { DCHECK(StrNCaseCmp(request->url, kChromeTestPluginProtocol, arraysize(kChromeTestPluginProtocol) - 1) == 0); return FindPayload(request->url) != NULL; } CPError STDCALL CPR_StartRequest(CPRequest* request) { const TestResponsePayload* payload = FindPayload(request->url); DCHECK(payload); ResponseStream* stream = new ResponseStream(payload, request); stream->AddRef(); // Released in CPR_EndRequest stream->Init(); request->pdata = stream; return payload->async ? CPERR_IO_PENDING : CPERR_SUCCESS; } void STDCALL CPR_EndRequest(CPRequest* request, CPError reason) { ResponseStream* stream = static_cast<ResponseStream*>(request->pdata); request->pdata = NULL; stream->Release(); // balances AddRef in CPR_StartRequest } void STDCALL CPR_SetExtraRequestHeaders(CPRequest* request, const char* headers) { // doesn't affect us } void STDCALL CPR_SetRequestLoadFlags(CPRequest* request, uint32 flags) { // doesn't affect us } void STDCALL CPR_AppendDataToUpload(CPRequest* request, const char* bytes, int bytes_len) { // doesn't affect us } CPError STDCALL CPR_AppendFileToUpload(CPRequest* request, const char* filepath, uint64 offset, uint64 length) { // doesn't affect us return CPERR_FAILURE; } int STDCALL CPR_GetResponseInfo(CPRequest* request, CPResponseInfoType type, void* buf, uint32 buf_size) { ResponseStream* stream = static_cast<ResponseStream*>(request->pdata); return stream->GetResponseInfo(type, buf, buf_size); } int STDCALL CPR_Read(CPRequest* request, void* buf, uint32 buf_size) { ResponseStream* stream = static_cast<ResponseStream*>(request->pdata); return stream->ReadData(buf, buf_size); } // RequestResponse: manages the retrieval of response data from the host class RequestResponse { public: RequestResponse(const std::string& raw_headers) : raw_headers_(raw_headers), offset_(0) {} void StartReading(CPRequest* request); void ReadCompleted(CPRequest* request, int bytes_read); private: std::string raw_headers_; std::string body_; int offset_; }; void RequestResponse::StartReading(CPRequest* request) { int rv = 0; const uint32 kReadSize = 4096; do { body_.resize(offset_ + kReadSize); rv = g_cprequest_funcs.read(request, &body_[offset_], kReadSize); if (rv > 0) offset_ += rv; } while (rv > 0); if (rv != CPERR_IO_PENDING) { // Either an error occurred, or we are done. ReadCompleted(request, rv); } } void RequestResponse::ReadCompleted(CPRequest* request, int bytes_read) { if (bytes_read > 0) { offset_ += bytes_read; StartReading(request); return; } body_.resize(offset_); bool success = (bytes_read == 0); g_cptest_funcs.test_complete(request, success, raw_headers_, body_); g_cprequest_funcs.end_request(request, CPERR_CANCELLED); delete this; } void STDCALL CPRR_ReceivedRedirect(CPRequest* request, const char* new_url) { } void STDCALL CPRR_StartCompleted(CPRequest* request, CPError result) { DCHECK(!request->pdata); std::string raw_headers; int size = g_cprequest_funcs.get_response_info( request, CPRESPONSEINFO_HTTP_RAW_HEADERS, NULL, 0); int rv = size < 0 ? size : g_cprequest_funcs.get_response_info( request, CPRESPONSEINFO_HTTP_RAW_HEADERS, WriteInto(&raw_headers, size+1), size); if (rv != CPERR_SUCCESS) { g_cptest_funcs.test_complete(request, false, std::string(), std::string()); g_cprequest_funcs.end_request(request, CPERR_CANCELLED); return; } RequestResponse* response = new RequestResponse(raw_headers); request->pdata = response; response->StartReading(request); } void STDCALL CPRR_ReadCompleted(CPRequest* request, int bytes_read) { RequestResponse* response = reinterpret_cast<RequestResponse*>(request->pdata); response->ReadCompleted(request, bytes_read); } int STDCALL CPT_MakeRequest(const char* method, const GURL& url) { CPRequest* request = NULL; if (g_cpbrowser_funcs.create_request(g_cpid, NULL, method, url.spec().c_str(), &request) != CPERR_SUCCESS || !request) { return CPERR_FAILURE; } g_cprequest_funcs.set_request_load_flags(request, CPREQUESTLOAD_DISABLE_INTERCEPT); if (strcmp(method, "POST") == 0) { g_cprequest_funcs.set_extra_request_headers( request, "Content-Type: text/plain"); g_cprequest_funcs.append_data_to_upload( request, kChromeTestPluginPostData, arraysize(kChromeTestPluginPostData) - 1); } int rv = g_cprequest_funcs.start_request(request); if (rv == CPERR_SUCCESS) { CPRR_StartCompleted(request, CPERR_SUCCESS); } else if (rv != CPERR_IO_PENDING) { g_cprequest_funcs.end_request(request, CPERR_CANCELLED); return CPERR_FAILURE; } return CPERR_SUCCESS; } // DLL entry points CPError STDCALL CP_Initialize(CPID id, const CPBrowserFuncs* bfuncs, CPPluginFuncs* pfuncs) { if (bfuncs == NULL || pfuncs == NULL) return CPERR_FAILURE; if (CP_GET_MAJOR_VERSION(bfuncs->version) > CP_MAJOR_VERSION) return CPERR_INVALID_VERSION; if (bfuncs->size < sizeof(CPBrowserFuncs) || pfuncs->size < sizeof(CPPluginFuncs)) return CPERR_INVALID_VERSION; pfuncs->version = CP_VERSION; pfuncs->shutdown = CPP_Shutdown; pfuncs->should_intercept_request = CPP_ShouldInterceptRequest; static CPRequestFuncs request_funcs; request_funcs.start_request = CPR_StartRequest; request_funcs.end_request = CPR_EndRequest; request_funcs.set_extra_request_headers = CPR_SetExtraRequestHeaders; request_funcs.set_request_load_flags = CPR_SetRequestLoadFlags; request_funcs.append_data_to_upload = CPR_AppendDataToUpload; request_funcs.get_response_info = CPR_GetResponseInfo; request_funcs.read = CPR_Read; request_funcs.append_file_to_upload = CPR_AppendFileToUpload; pfuncs->request_funcs = &request_funcs; static CPResponseFuncs response_funcs; response_funcs.received_redirect = CPRR_ReceivedRedirect; response_funcs.start_completed = CPRR_StartCompleted; response_funcs.read_completed = CPRR_ReadCompleted; pfuncs->response_funcs = &response_funcs; g_cpid = id; g_cpbrowser_funcs = *bfuncs; g_cprequest_funcs = *bfuncs->request_funcs; g_cpresponse_funcs = *bfuncs->response_funcs; g_cpbrowser_funcs = *bfuncs; const char* protocols[] = {kChromeTestPluginProtocol}; g_cpbrowser_funcs.enable_request_intercept(g_cpid, protocols, 1); return CPERR_SUCCESS; } int STDCALL CP_Test(void* vparam) { TestFuncParams* param = reinterpret_cast<TestFuncParams*>(vparam); param->pfuncs.test_make_request = CPT_MakeRequest; g_cptest_funcs = param->bfuncs; return CPERR_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ItemConverter.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2008-02-18 15:53:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART_ITEMCONVERTER_HXX #define CHART_ITEMCONVERTER_HXX #ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_ #include <unotools/eventlisteneradapter.hxx> #endif #ifndef _SFXITEMPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif // for pair #include <utility> struct SfxItemPropertyMap; namespace comphelper { /** This class serves for conversion between properties of an XPropertySet and SfxItems in SfxItemSets. With this helper classes, you can feed dialogs with XPropertySets and let those modify by the dialogs. You must implement GetWhichPairs() such that an SfxItemSet created with CreateEmptyItemSet() is able to hold all items that may be mapped. You also have to implement GetItemProperty(), in order to return the property name for a given which-id together with the corresponding member-id that has to be used for conversion in QueryValue/PutValue. FillSpecialItem and ApplySpecialItem may be used for special handling of individual item, e.g. if you need member-ids in QueryValue/PutValue A typical use could be the following: ::comphelper::ChartTypeItemConverter aItemConverter( xPropertySet, GetItemPool() ); SfxItemSet aItemSet = aItemConverter.CreateEmptyItemSet(); aItemConverter.FillItemSet( aItemSet ); bool bChanged = false; MyDialog aDlg( aItemSet ); if( aDlg.Execute() == RET_OK ) { const SfxItemSet* pOutItemSet = aDlg.GetOutputItemSet(); if( pOutItemSet ) bChanged = aItemConverter.ApplyItemSet( *pOutItemSet ); } if( bChanged ) { [ apply model changes to view ] } */ class ItemConverter : public ::utl::OEventListenerAdapter { public: /** Construct an item converter that uses the given property set for reading/writing converted items */ ItemConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & rPropertySet , SfxItemPool& rItemPool ); virtual ~ItemConverter(); // typedefs ------------------------------- typedef USHORT tWhichIdType; typedef ::rtl::OUString tPropertyNameType; typedef BYTE tMemberIdType; typedef ::std::pair< tPropertyNameType, tMemberIdType > tPropertyNameWithMemberId; // ---------------------------------------- /** applies all properties that can be mapped to items into the given item set. Call this method before opening a dialog. @param rOutItemSet the SfxItemSet is filled with all items that are a result of a conversion from a property of the internal XPropertySet. */ virtual void FillItemSet( SfxItemSet & rOutItemSet ) const; /** applies all properties that are results of a conversion from all items in rItemSet to the internal XPropertySet. Call this method after a dialog was closed with OK @return true, if any properties have been changed, false otherwise. */ virtual bool ApplyItemSet( const SfxItemSet & rItemSet ); /** creates an empty item set using the given pool or a common pool if empty (see GetItemPool) and allowing all items given in the ranges returned by GetWhichPairs. */ SfxItemSet CreateEmptyItemSet() const; /** States whether conversion is still likely to work. In particular, it is checked if the XPropertySet given in the CTOR is still valid, i.e. not disposed. It is assumed that the XPropertySet is valid when the converter is constructed. This only works if the XPropertySet given in the CTOR supports the interface ::com::sun::star::lang::XComponent. */ bool IsValid() const; /** Invalidates all items in rDestSet, that are set (state SFX_ITEM_SET) in both item sets (rDestSet and rSourceSet) and have differing content. */ static void InvalidateUnequalItems( SfxItemSet &rDestSet, const SfxItemSet &rSourceSet ); protected: // ________ /** implement this method to provide an array of which-ranges of the form: const USHORT aMyPairs[] = { from_1, to_1, from_2, to_2, ... from_n, to_n, 0 }; */ virtual const USHORT * GetWhichPairs() const = 0; /** implement this method to return a Property object for a given which id. @param rOutProperty If true is returned, this contains the property name and the corresponding Member-Id. @return true, if the item can be mapped to a property. */ virtual bool GetItemProperty( tWhichIdType nWhichId, tPropertyNameWithMemberId & rOutProperty ) const = 0; /** for items that can not be mapped directly to a property. This method is called from FillItemSet(), if GetItemProperty() returns false. The default implementation does nothing except showing an assertion */ virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const throw( ::com::sun::star::uno::Exception ); /** for items that can not be mapped directly to a property. This method is called from ApplyItemSet(), if GetItemProperty() returns false. The default implementation returns just false and shows an assertion @return true if the item changed a property, false otherwise. */ virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet ) throw( ::com::sun::star::uno::Exception ); // ________ /// Returns the pool SfxItemPool & GetItemPool() const; /** Returns the XPropertySet that was given in the CTOR and is used to apply items in ApplyItemSet(). */ ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > GetPropertySet() const; // ____ ::utl::OEventListenerAdapter ____ virtual void _disposing( const ::com::sun::star::lang::EventObject& rSource ); protected: /** sets a new property set, that you get with GetPropertySet(). It should not be necessary to use this method. It is introduced to allow changing the regression type of a regression curve which changes the object identity. */ void resetPropertySet( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & xPropSet ); private: ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xPropertySet; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > m_xPropertySetInfo; SfxItemPool& m_rItemPool; bool m_bIsValid; }; } // namespace comphelper // CHART_ITEMCONVERTER_HXX #endif <commit_msg>INTEGRATION: CWS changefileheader (1.9.34); FILE MERGED 2008/04/01 15:04:06 thb 1.9.34.3: #i85898# Stripping all external header guards 2008/04/01 10:50:22 thb 1.9.34.2: #i85898# Stripping all external header guards 2008/03/28 16:43:44 rt 1.9.34.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ItemConverter.hxx,v $ * $Revision: 1.10 $ * * 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 CHART_ITEMCONVERTER_HXX #define CHART_ITEMCONVERTER_HXX #include <unotools/eventlisteneradapter.hxx> #include <svtools/itempool.hxx> #include <svtools/itemset.hxx> #include <com/sun/star/beans/XPropertySet.hpp> // for pair #include <utility> struct SfxItemPropertyMap; namespace comphelper { /** This class serves for conversion between properties of an XPropertySet and SfxItems in SfxItemSets. With this helper classes, you can feed dialogs with XPropertySets and let those modify by the dialogs. You must implement GetWhichPairs() such that an SfxItemSet created with CreateEmptyItemSet() is able to hold all items that may be mapped. You also have to implement GetItemProperty(), in order to return the property name for a given which-id together with the corresponding member-id that has to be used for conversion in QueryValue/PutValue. FillSpecialItem and ApplySpecialItem may be used for special handling of individual item, e.g. if you need member-ids in QueryValue/PutValue A typical use could be the following: ::comphelper::ChartTypeItemConverter aItemConverter( xPropertySet, GetItemPool() ); SfxItemSet aItemSet = aItemConverter.CreateEmptyItemSet(); aItemConverter.FillItemSet( aItemSet ); bool bChanged = false; MyDialog aDlg( aItemSet ); if( aDlg.Execute() == RET_OK ) { const SfxItemSet* pOutItemSet = aDlg.GetOutputItemSet(); if( pOutItemSet ) bChanged = aItemConverter.ApplyItemSet( *pOutItemSet ); } if( bChanged ) { [ apply model changes to view ] } */ class ItemConverter : public ::utl::OEventListenerAdapter { public: /** Construct an item converter that uses the given property set for reading/writing converted items */ ItemConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & rPropertySet , SfxItemPool& rItemPool ); virtual ~ItemConverter(); // typedefs ------------------------------- typedef USHORT tWhichIdType; typedef ::rtl::OUString tPropertyNameType; typedef BYTE tMemberIdType; typedef ::std::pair< tPropertyNameType, tMemberIdType > tPropertyNameWithMemberId; // ---------------------------------------- /** applies all properties that can be mapped to items into the given item set. Call this method before opening a dialog. @param rOutItemSet the SfxItemSet is filled with all items that are a result of a conversion from a property of the internal XPropertySet. */ virtual void FillItemSet( SfxItemSet & rOutItemSet ) const; /** applies all properties that are results of a conversion from all items in rItemSet to the internal XPropertySet. Call this method after a dialog was closed with OK @return true, if any properties have been changed, false otherwise. */ virtual bool ApplyItemSet( const SfxItemSet & rItemSet ); /** creates an empty item set using the given pool or a common pool if empty (see GetItemPool) and allowing all items given in the ranges returned by GetWhichPairs. */ SfxItemSet CreateEmptyItemSet() const; /** States whether conversion is still likely to work. In particular, it is checked if the XPropertySet given in the CTOR is still valid, i.e. not disposed. It is assumed that the XPropertySet is valid when the converter is constructed. This only works if the XPropertySet given in the CTOR supports the interface ::com::sun::star::lang::XComponent. */ bool IsValid() const; /** Invalidates all items in rDestSet, that are set (state SFX_ITEM_SET) in both item sets (rDestSet and rSourceSet) and have differing content. */ static void InvalidateUnequalItems( SfxItemSet &rDestSet, const SfxItemSet &rSourceSet ); protected: // ________ /** implement this method to provide an array of which-ranges of the form: const USHORT aMyPairs[] = { from_1, to_1, from_2, to_2, ... from_n, to_n, 0 }; */ virtual const USHORT * GetWhichPairs() const = 0; /** implement this method to return a Property object for a given which id. @param rOutProperty If true is returned, this contains the property name and the corresponding Member-Id. @return true, if the item can be mapped to a property. */ virtual bool GetItemProperty( tWhichIdType nWhichId, tPropertyNameWithMemberId & rOutProperty ) const = 0; /** for items that can not be mapped directly to a property. This method is called from FillItemSet(), if GetItemProperty() returns false. The default implementation does nothing except showing an assertion */ virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const throw( ::com::sun::star::uno::Exception ); /** for items that can not be mapped directly to a property. This method is called from ApplyItemSet(), if GetItemProperty() returns false. The default implementation returns just false and shows an assertion @return true if the item changed a property, false otherwise. */ virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet ) throw( ::com::sun::star::uno::Exception ); // ________ /// Returns the pool SfxItemPool & GetItemPool() const; /** Returns the XPropertySet that was given in the CTOR and is used to apply items in ApplyItemSet(). */ ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > GetPropertySet() const; // ____ ::utl::OEventListenerAdapter ____ virtual void _disposing( const ::com::sun::star::lang::EventObject& rSource ); protected: /** sets a new property set, that you get with GetPropertySet(). It should not be necessary to use this method. It is introduced to allow changing the regression type of a regression curve which changes the object identity. */ void resetPropertySet( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & xPropSet ); private: ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xPropertySet; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > m_xPropertySetInfo; SfxItemPool& m_rItemPool; bool m_bIsValid; }; } // namespace comphelper // CHART_ITEMCONVERTER_HXX #endif <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/platform_thread.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/ui/ui_test.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" #define NUMBER_OF_ITERATIONS 5 namespace { // This Automated UI test opens static files in different tabs in a proxy // browser. After all the tabs have opened, it switches between tabs, and notes // time taken for each switch. It then prints out the times on the console, // with the aim that the page cycler parser can interpret these numbers to // draw graphs for page cycler Tab Switching Performance. // Usage Flags: -enable-logging -dump-histograms-on-exit -log-level=0 class TabSwitchingUITest : public UITest { public: TabSwitchingUITest() { PathService::Get(base::DIR_SOURCE_ROOT, &path_prefix_); path_prefix_ = path_prefix_.AppendASCII("data"); path_prefix_ = path_prefix_.AppendASCII("tab_switching"); show_window_ = true; } void RunTabSwitchingUITest() { // Create a browser proxy. browser_proxy_ = automation()->GetBrowserWindow(0); // Open all the tabs. int initial_tab_count = 0; ASSERT_TRUE(browser_proxy_->GetTabCount(&initial_tab_count)); int new_tab_count = OpenTabs(); ASSERT_TRUE(browser_proxy_->WaitForTabCountToBecome( initial_tab_count + new_tab_count, 10000)); // Switch linearly between tabs. browser_proxy_->ActivateTab(0); int final_tab_count = 0; ASSERT_TRUE(browser_proxy_->GetTabCount(&final_tab_count)); for (int i = initial_tab_count; i < final_tab_count; ++i) { browser_proxy_->ActivateTab(i); ASSERT_TRUE(browser_proxy_->WaitForTabToBecomeActive(i, 10000)); } // Close the browser to force a dump of log. bool application_closed = false; EXPECT_TRUE(CloseBrowser(browser_proxy_.get(), &application_closed)); // Now open the corresponding log file and collect average and std dev from // the histogram stats generated for RenderWidgetHostHWND_WhiteoutDuration FilePath log_file_name; ASSERT_TRUE(PathService::Get(chrome::DIR_LOGS, &log_file_name)); log_file_name = log_file_name.AppendASCII("chrome_debug.log"); bool log_has_been_dumped = false; std::string contents; int max_tries = 20; do { log_has_been_dumped = file_util::ReadFileToString(log_file_name, &contents); if (!log_has_been_dumped) PlatformThread::Sleep(100); } while (!log_has_been_dumped && max_tries--); ASSERT_TRUE(log_has_been_dumped) << "Failed to read the log file"; // Parse the contents to get average and std deviation. std::string average("0.0"), std_dev("0.0"); const std::string average_str("average = "); const std::string std_dev_str("standard deviation = "); std::string::size_type pos = contents.find( "Histogram: MPArch.RWHH_WhiteoutDuration", 0); std::string::size_type comma_pos; std::string::size_type number_length; if (pos != std::string::npos) { // Get the average. pos = contents.find(average_str, pos); comma_pos = contents.find(",", pos); pos += average_str.length(); number_length = comma_pos - pos; average = contents.substr(pos, number_length); // Get the std dev. pos = contents.find(std_dev_str, pos); pos += std_dev_str.length(); comma_pos = contents.find(" ", pos); number_length = comma_pos - pos; std_dev = contents.substr(pos, number_length); } else { LOG(WARNING) << "Histogram: MPArch.RWHH_WhiteoutDuration wasn't found"; } // Print the average and standard deviation. PrintResultMeanAndError("tab_switch", "", "t", average + ", " + std_dev, "ms", true /* important */); } protected: // Opens new tabs. Returns the number of tabs opened. int OpenTabs() { // Add tabs. static const char* files[] = { "espn.go.com", "bugzilla.mozilla.org", "news.cnet.com", "www.amazon.com", "kannada.chakradeo.net", "allegro.pl", "ml.wikipedia.org", "www.bbc.co.uk", "126.com", "www.altavista.com"}; int number_of_new_tabs_opened = 0; FilePath file_name; for (size_t i = 0; i < arraysize(files); ++i) { file_name = path_prefix_; file_name = file_name.AppendASCII(files[i]); file_name = file_name.AppendASCII("index.html"); browser_proxy_->AppendTab(net::FilePathToFileURL(file_name)); number_of_new_tabs_opened++; } return number_of_new_tabs_opened; } FilePath path_prefix_; int number_of_tabs_to_open_; scoped_refptr<BrowserProxy> browser_proxy_; private: DISALLOW_EVIL_CONSTRUCTORS(TabSwitchingUITest); }; TEST_F(TabSwitchingUITest, GenerateTabSwitchStats) { RunTabSwitchingUITest(); } } // namespace <commit_msg>Coverity: Remove an unused variable.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/platform_thread.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/ui/ui_test.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" #define NUMBER_OF_ITERATIONS 5 namespace { // This Automated UI test opens static files in different tabs in a proxy // browser. After all the tabs have opened, it switches between tabs, and notes // time taken for each switch. It then prints out the times on the console, // with the aim that the page cycler parser can interpret these numbers to // draw graphs for page cycler Tab Switching Performance. // Usage Flags: -enable-logging -dump-histograms-on-exit -log-level=0 class TabSwitchingUITest : public UITest { public: TabSwitchingUITest() { PathService::Get(base::DIR_SOURCE_ROOT, &path_prefix_); path_prefix_ = path_prefix_.AppendASCII("data"); path_prefix_ = path_prefix_.AppendASCII("tab_switching"); show_window_ = true; } void RunTabSwitchingUITest() { // Create a browser proxy. browser_proxy_ = automation()->GetBrowserWindow(0); // Open all the tabs. int initial_tab_count = 0; ASSERT_TRUE(browser_proxy_->GetTabCount(&initial_tab_count)); int new_tab_count = OpenTabs(); ASSERT_TRUE(browser_proxy_->WaitForTabCountToBecome( initial_tab_count + new_tab_count, 10000)); // Switch linearly between tabs. browser_proxy_->ActivateTab(0); int final_tab_count = 0; ASSERT_TRUE(browser_proxy_->GetTabCount(&final_tab_count)); for (int i = initial_tab_count; i < final_tab_count; ++i) { browser_proxy_->ActivateTab(i); ASSERT_TRUE(browser_proxy_->WaitForTabToBecomeActive(i, 10000)); } // Close the browser to force a dump of log. bool application_closed = false; EXPECT_TRUE(CloseBrowser(browser_proxy_.get(), &application_closed)); // Now open the corresponding log file and collect average and std dev from // the histogram stats generated for RenderWidgetHostHWND_WhiteoutDuration FilePath log_file_name; ASSERT_TRUE(PathService::Get(chrome::DIR_LOGS, &log_file_name)); log_file_name = log_file_name.AppendASCII("chrome_debug.log"); bool log_has_been_dumped = false; std::string contents; int max_tries = 20; do { log_has_been_dumped = file_util::ReadFileToString(log_file_name, &contents); if (!log_has_been_dumped) PlatformThread::Sleep(100); } while (!log_has_been_dumped && max_tries--); ASSERT_TRUE(log_has_been_dumped) << "Failed to read the log file"; // Parse the contents to get average and std deviation. std::string average("0.0"), std_dev("0.0"); const std::string average_str("average = "); const std::string std_dev_str("standard deviation = "); std::string::size_type pos = contents.find( "Histogram: MPArch.RWHH_WhiteoutDuration", 0); std::string::size_type comma_pos; std::string::size_type number_length; if (pos != std::string::npos) { // Get the average. pos = contents.find(average_str, pos); comma_pos = contents.find(",", pos); pos += average_str.length(); number_length = comma_pos - pos; average = contents.substr(pos, number_length); // Get the std dev. pos = contents.find(std_dev_str, pos); pos += std_dev_str.length(); comma_pos = contents.find(" ", pos); number_length = comma_pos - pos; std_dev = contents.substr(pos, number_length); } else { LOG(WARNING) << "Histogram: MPArch.RWHH_WhiteoutDuration wasn't found"; } // Print the average and standard deviation. PrintResultMeanAndError("tab_switch", "", "t", average + ", " + std_dev, "ms", true /* important */); } protected: // Opens new tabs. Returns the number of tabs opened. int OpenTabs() { // Add tabs. static const char* files[] = { "espn.go.com", "bugzilla.mozilla.org", "news.cnet.com", "www.amazon.com", "kannada.chakradeo.net", "allegro.pl", "ml.wikipedia.org", "www.bbc.co.uk", "126.com", "www.altavista.com"}; int number_of_new_tabs_opened = 0; FilePath file_name; for (size_t i = 0; i < arraysize(files); ++i) { file_name = path_prefix_; file_name = file_name.AppendASCII(files[i]); file_name = file_name.AppendASCII("index.html"); browser_proxy_->AppendTab(net::FilePathToFileURL(file_name)); number_of_new_tabs_opened++; } return number_of_new_tabs_opened; } FilePath path_prefix_; scoped_refptr<BrowserProxy> browser_proxy_; private: DISALLOW_COPY_AND_ASSIGN(TabSwitchingUITest); }; TEST_F(TabSwitchingUITest, GenerateTabSwitchStats) { RunTabSwitchingUITest(); } } // namespace <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: LineChartType.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: bm $ $Date: 2004-01-26 09:12:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2003 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CHART_LINECHARTTYPE_HXX #define CHART_LINECHARTTYPE_HXX #include "ChartType.hxx" #ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_ #include <com/sun/star/chart2/CurveStyle.hpp> #endif namespace chart { class LineChartType : public ChartType { public: LineChartType( sal_Int32 nDim = 2, ::com::sun::star::chart2::CurveStyle eCurveStyle = ::com::sun::star::chart2::CurveStyle_LINES, sal_Int32 nResolution = 20, sal_Int32 nOrder = 3 ); virtual ~LineChartType(); protected: // ____ XChartType ____ virtual ::rtl::OUString SAL_CALL getChartType() throw (::com::sun::star::uno::RuntimeException); // ____ OPropertySet ____ virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const throw(::com::sun::star::beans::UnknownPropertyException); // ____ OPropertySet ____ virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); // ____ XPropertySet ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); }; } // namespace chart // CHART_LINECHARTTYPE_HXX #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.5.110); FILE MERGED 2005/09/05 18:43:22 rt 1.5.110.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LineChartType.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 01:21:13 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART_LINECHARTTYPE_HXX #define CHART_LINECHARTTYPE_HXX #include "ChartType.hxx" #ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_ #include <com/sun/star/chart2/CurveStyle.hpp> #endif namespace chart { class LineChartType : public ChartType { public: LineChartType( sal_Int32 nDim = 2, ::com::sun::star::chart2::CurveStyle eCurveStyle = ::com::sun::star::chart2::CurveStyle_LINES, sal_Int32 nResolution = 20, sal_Int32 nOrder = 3 ); virtual ~LineChartType(); protected: // ____ XChartType ____ virtual ::rtl::OUString SAL_CALL getChartType() throw (::com::sun::star::uno::RuntimeException); // ____ OPropertySet ____ virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const throw(::com::sun::star::beans::UnknownPropertyException); // ____ OPropertySet ____ virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); // ____ XPropertySet ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); }; } // namespace chart // CHART_LINECHARTTYPE_HXX #endif <|endoftext|>
<commit_before>__mmask16 FORCE_INLINE zero_byte_mask(const __m512i v) { const __m512i v01 = _mm512_set1_epi32(0x01010101u); const __m512i v80 = _mm512_set1_epi32(0x80808080u); const __m512i v1 = _mm512_sub_epi32(v, v01); const __m512i tmp1 = _mm512_ternarylogic_epi32(v1, v, v80, 0x20); return _mm512_test_epi32_mask(tmp1, tmp1); } int avx512f_strcmp(const char* s1, const char* s2) { char* c1 = const_cast<char*>(s1); char* c2 = const_cast<char*>(s2); __mmask16 zero1; __mmask16 zero2; __mmask16 diff; while (true) { const __m512i v1 = _mm512_loadu_si512(c1); const __m512i v2 = _mm512_loadu_si512(c2); // locate in s1 dwords having '\0' zero1 = zero_byte_mask(v1); // locate in s1 dwords having '\0' zero2 = zero_byte_mask(v2); // locate differences between s1 and s2 diff = _mm512_cmpneq_epi32_mask(_mm512_xor_si512(v1, v2), _mm512_setzero_si512()); if (zero1 != 0 || zero2 != 0 || diff != 0) { break; } c1 += 64; c2 += 64; } // get result const uint16_t zeros = zero1 | zero2; if (zeros == 0) { // no zeros within current chunk const size_t n = __builtin_ctz(diff); // move pointers to the first dword with diff c1 += n * 4; c2 += n * 4; goto locate_diff; } else if (diff == 0) { // no explicit diff, but one string might be shorter const size_t k = __builtin_ctz(zeros); c1 += k * 4; c2 += k * 4; goto locate_diff_or_eos; } else { // there is diff and zeros const size_t n = __builtin_ctz(diff); const size_t k = __builtin_ctz(zeros); if (n < k) { // first difference is located in dword preceeding dword with zeros // move pointers to that dword c1 += n * 4; c2 += n * 4; goto locate_diff; } else if (k > n) { // first difference is past zeros (strings are equal, but garbage after EOS differs) return 0; } else /* n == k */ { c1 += k * 4; c2 += k * 4; goto locate_diff_or_eos; } } assert(false); locate_diff: for (int i=0; i < 4; i++) { int a = c1[i]; int b = c2[i]; if (a != b) { return a - b; } } assert(false); locate_diff_or_eos: for (int i=0; i < 4; i++) { int a = c1[i]; int b = c2[i]; if (a == 0 && b == 0) { return 0; } if (a != b) { return a - b; } } assert(false); } <commit_msg>remove zero2 from cmp loop simplify bytewise comparison<commit_after>__mmask16 FORCE_INLINE zero_byte_mask(const __m512i v) { const __m512i v01 = _mm512_set1_epi32(0x01010101u); const __m512i v80 = _mm512_set1_epi32(0x80808080u); const __m512i v1 = _mm512_sub_epi32(v, v01); const __m512i tmp1 = _mm512_ternarylogic_epi32(v1, v, v80, 0x20); return _mm512_test_epi32_mask(tmp1, tmp1); } int avx512f_strcmp(const char* s1, const char* s2) { char* c1 = const_cast<char*>(s1); char* c2 = const_cast<char*>(s2); __mmask16 zero1; __mmask16 diff; __mmask16 either; while (true) { const __m512i v1 = _mm512_loadu_si512(c1); const __m512i v2 = _mm512_loadu_si512(c2); // locate in s1 dwords having '\0' zero1 = zero_byte_mask(v1); // a '\0' in v2 will trigger a diff or a 1 bit in zero1 diff = _mm512_cmpneq_epi32_mask(v1, v2); // use lowest order 1 bit of either/both ops either = zero1 | diff; if (either) { break; } c1 += 64; c2 += 64; } const size_t n = __builtin_ctz(either); // move pointers to the first dword with diff and/or eos c1 += n * 4; c2 += n * 4; // strncmp resolves which byte wins for (int i=0; i < 4; i++) { int a = c1[i]; int b = c2[i]; if (a != b || !a) { return a - b; } } assert(false); } <|endoftext|>
<commit_before>#include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkGeometry.h" // http://code.google.com/p/skia/issues/detail?id=32 static void test_cubic() { SkPoint src[4] = { { 556.25000, 523.03003 }, { 556.23999, 522.96002 }, { 556.21997, 522.89001 }, { 556.21997, 522.82001 } }; SkPoint dst[11]; dst[10].set(42, -42); // one past the end, that we don't clobber these SkScalar tval[] = { 0.33333334f, 0.99999994f }; SkChopCubicAt(src, dst, tval, 2); #if 0 for (int i = 0; i < 11; i++) { SkDebugf("--- %d [%g %g]\n", i, dst[i].fX, dst[i].fY); } #endif } class PathView : public SkView { public: int fDStroke, fStroke, fMinStroke, fMaxStroke; SkPath fPath[6]; bool fShowHairline; PathView() { test_cubic(); fShowHairline = false; fDStroke = 1; fStroke = 10; fMinStroke = 10; fMaxStroke = 180; const int V = 85; fPath[0].moveTo(SkIntToScalar(40), SkIntToScalar(70)); fPath[0].lineTo(SkIntToScalar(70), SkIntToScalar(70) + SK_Scalar1/1); fPath[0].lineTo(SkIntToScalar(110), SkIntToScalar(70)); fPath[1].moveTo(SkIntToScalar(40), SkIntToScalar(70)); fPath[1].lineTo(SkIntToScalar(70), SkIntToScalar(70) - SK_Scalar1/1); fPath[1].lineTo(SkIntToScalar(110), SkIntToScalar(70)); fPath[2].moveTo(SkIntToScalar(V), SkIntToScalar(V)); fPath[2].lineTo(SkIntToScalar(50), SkIntToScalar(V)); fPath[2].lineTo(SkIntToScalar(50), SkIntToScalar(50)); fPath[3].moveTo(SkIntToScalar(50), SkIntToScalar(50)); fPath[3].lineTo(SkIntToScalar(50), SkIntToScalar(V)); fPath[3].lineTo(SkIntToScalar(V), SkIntToScalar(V)); fPath[4].moveTo(SkIntToScalar(50), SkIntToScalar(50)); fPath[4].lineTo(SkIntToScalar(50), SkIntToScalar(V)); fPath[4].lineTo(SkIntToScalar(52), SkIntToScalar(50)); fPath[5].moveTo(SkIntToScalar(52), SkIntToScalar(50)); fPath[5].lineTo(SkIntToScalar(50), SkIntToScalar(V)); fPath[5].lineTo(SkIntToScalar(50), SkIntToScalar(50)); } virtual ~PathView() { } void nextStroke() { fStroke += fDStroke; if (fStroke > fMaxStroke || fStroke < fMinStroke) fDStroke = -fDStroke; } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "Paths"); return true; } return this->INHERITED::onQuery(evt); } void drawBG(SkCanvas* canvas) { canvas->drawColor(0xFFDDDDDD); // canvas->drawColor(SK_ColorWHITE); } void drawPath(SkCanvas* canvas, const SkPath& path, SkPaint::Join j) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeJoin(j); paint.setStrokeWidth(SkIntToScalar(fStroke)); if (fShowHairline) { SkPath fill; paint.getFillPath(path, &fill); paint.setStrokeWidth(0); canvas->drawPath(fill, paint); } else canvas->drawPath(path, paint); paint.setColor(SK_ColorRED); paint.setStrokeWidth(0); canvas->drawPath(path, paint); } virtual void onDraw(SkCanvas* canvas) { this->drawBG(canvas); canvas->translate(SkIntToScalar(50), SkIntToScalar(50)); static const SkPaint::Join gJoins[] = { SkPaint::kBevel_Join, SkPaint::kMiter_Join, SkPaint::kRound_Join }; for (int i = 0; i < SK_ARRAY_COUNT(gJoins); i++) { canvas->save(); for (int j = 0; j < SK_ARRAY_COUNT(fPath); j++) { this->drawPath(canvas, fPath[j], gJoins[i]); canvas->translate(SkIntToScalar(200), 0); } canvas->restore(); canvas->translate(0, SkIntToScalar(200)); } this->nextStroke(); this->inval(NULL); } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) { fShowHairline = !fShowHairline; this->inval(NULL); return this->INHERITED::onFindClickHandler(x, y); } virtual bool onClick(Click* click) { return this->INHERITED::onClick(click); } private: typedef SkView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new PathView; } static SkViewRegister reg(MyFactory); <commit_msg>add new cubic test for overflow<commit_after>#include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkParsePath.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkGeometry.h" // http://code.google.com/p/skia/issues/detail?id=32 static void test_cubic() { SkPoint src[4] = { { 556.25000, 523.03003 }, { 556.23999, 522.96002 }, { 556.21997, 522.89001 }, { 556.21997, 522.82001 } }; SkPoint dst[11]; dst[10].set(42, -42); // one past the end, that we don't clobber these SkScalar tval[] = { 0.33333334f, 0.99999994f }; SkChopCubicAt(src, dst, tval, 2); #if 0 for (int i = 0; i < 11; i++) { SkDebugf("--- %d [%g %g]\n", i, dst[i].fX, dst[i].fY); } #endif } static void test_cubic2() { const char* str = "M2242 -590088L-377758 9.94099e+07L-377758 9.94099e+07L2242 -590088Z"; SkPath path; SkParsePath::FromSVGString(str, &path); { float x = strtof("9.94099e+07", NULL); int ix = (int)x; int fx = (int)(x * 65536); int ffx = SkScalarToFixed(x); printf("%g %x %x %x\n", x, ix, fx, ffx); SkRect r = path.getBounds(); SkIRect ir; r.round(&ir); printf("[%g %g %g %g] [%x %x %x %x]\n", r.fLeft, r.fTop, r.fRight, r.fBottom, ir.fLeft, ir.fTop, ir.fRight, ir.fBottom); } SkBitmap bitmap; bitmap.setConfig(SkBitmap::kARGB_8888_Config, 300, 200); bitmap.allocPixels(); SkCanvas canvas(bitmap); SkPaint paint; paint.setAntiAlias(true); canvas.drawPath(path, paint); } class PathView : public SkView { public: int fDStroke, fStroke, fMinStroke, fMaxStroke; SkPath fPath[6]; bool fShowHairline; PathView() { test_cubic(); test_cubic2(); fShowHairline = false; fDStroke = 1; fStroke = 10; fMinStroke = 10; fMaxStroke = 180; const int V = 85; fPath[0].moveTo(SkIntToScalar(40), SkIntToScalar(70)); fPath[0].lineTo(SkIntToScalar(70), SkIntToScalar(70) + SK_Scalar1/1); fPath[0].lineTo(SkIntToScalar(110), SkIntToScalar(70)); fPath[1].moveTo(SkIntToScalar(40), SkIntToScalar(70)); fPath[1].lineTo(SkIntToScalar(70), SkIntToScalar(70) - SK_Scalar1/1); fPath[1].lineTo(SkIntToScalar(110), SkIntToScalar(70)); fPath[2].moveTo(SkIntToScalar(V), SkIntToScalar(V)); fPath[2].lineTo(SkIntToScalar(50), SkIntToScalar(V)); fPath[2].lineTo(SkIntToScalar(50), SkIntToScalar(50)); fPath[3].moveTo(SkIntToScalar(50), SkIntToScalar(50)); fPath[3].lineTo(SkIntToScalar(50), SkIntToScalar(V)); fPath[3].lineTo(SkIntToScalar(V), SkIntToScalar(V)); fPath[4].moveTo(SkIntToScalar(50), SkIntToScalar(50)); fPath[4].lineTo(SkIntToScalar(50), SkIntToScalar(V)); fPath[4].lineTo(SkIntToScalar(52), SkIntToScalar(50)); fPath[5].moveTo(SkIntToScalar(52), SkIntToScalar(50)); fPath[5].lineTo(SkIntToScalar(50), SkIntToScalar(V)); fPath[5].lineTo(SkIntToScalar(50), SkIntToScalar(50)); } virtual ~PathView() { } void nextStroke() { fStroke += fDStroke; if (fStroke > fMaxStroke || fStroke < fMinStroke) fDStroke = -fDStroke; } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "Paths"); return true; } return this->INHERITED::onQuery(evt); } void drawBG(SkCanvas* canvas) { canvas->drawColor(0xFFDDDDDD); // canvas->drawColor(SK_ColorWHITE); } void drawPath(SkCanvas* canvas, const SkPath& path, SkPaint::Join j) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeJoin(j); paint.setStrokeWidth(SkIntToScalar(fStroke)); if (fShowHairline) { SkPath fill; paint.getFillPath(path, &fill); paint.setStrokeWidth(0); canvas->drawPath(fill, paint); } else canvas->drawPath(path, paint); paint.setColor(SK_ColorRED); paint.setStrokeWidth(0); canvas->drawPath(path, paint); } virtual void onDraw(SkCanvas* canvas) { this->drawBG(canvas); canvas->translate(SkIntToScalar(50), SkIntToScalar(50)); static const SkPaint::Join gJoins[] = { SkPaint::kBevel_Join, SkPaint::kMiter_Join, SkPaint::kRound_Join }; for (int i = 0; i < SK_ARRAY_COUNT(gJoins); i++) { canvas->save(); for (int j = 0; j < SK_ARRAY_COUNT(fPath); j++) { this->drawPath(canvas, fPath[j], gJoins[i]); canvas->translate(SkIntToScalar(200), 0); } canvas->restore(); canvas->translate(0, SkIntToScalar(200)); } this->nextStroke(); this->inval(NULL); } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) { fShowHairline = !fShowHairline; this->inval(NULL); return this->INHERITED::onFindClickHandler(x, y); } virtual bool onClick(Click* click) { return this->INHERITED::onClick(click); } private: typedef SkView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new PathView; } static SkViewRegister reg(MyFactory); <|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/bookmarks/bookmark_drag_data.h" #include "app/clipboard/scoped_clipboard_writer.h" #include "base/basictypes.h" #include "base/pickle.h" #include "base/string_util.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/profile.h" #include "chrome/common/url_constants.h" #include "chrome/browser/browser_process.h" #include "net/base/escape.h" const char* BookmarkDragData::kClipboardFormatString = "chromium/x-bookmark-entries"; BookmarkDragData::Element::Element(const BookmarkNode* node) : is_url(node->is_url()), url(node->GetURL()), title(node->GetTitle()), id_(node->id()) { for (int i = 0; i < node->GetChildCount(); ++i) children.push_back(Element(node->GetChild(i))); } void BookmarkDragData::Element::WriteToPickle(Pickle* pickle) const { pickle->WriteBool(is_url); pickle->WriteString(url.spec()); pickle->WriteWString(title); pickle->WriteInt64(id_); if (!is_url) { pickle->WriteSize(children.size()); for (std::vector<Element>::const_iterator i = children.begin(); i != children.end(); ++i) { i->WriteToPickle(pickle); } } } bool BookmarkDragData::Element::ReadFromPickle(Pickle* pickle, void** iterator) { std::string url_spec; if (!pickle->ReadBool(iterator, &is_url) || !pickle->ReadString(iterator, &url_spec) || !pickle->ReadWString(iterator, &title) || !pickle->ReadInt64(iterator, &id_)) { return false; } url = GURL(url_spec); children.clear(); if (!is_url) { size_t children_count; if (!pickle->ReadSize(iterator, &children_count)) return false; children.resize(children_count); for (std::vector<Element>::iterator i = children.begin(); i != children.end(); ++i) { if (!i->ReadFromPickle(pickle, iterator)) return false; } } return true; } #if defined(TOOLKIT_VIEWS) // static OSExchangeData::CustomFormat BookmarkDragData::GetBookmarkCustomFormat() { static OSExchangeData::CustomFormat format; static bool format_valid = false; if (!format_valid) { format_valid = true; format = OSExchangeData::RegisterCustomFormat( BookmarkDragData::kClipboardFormatString); } return format; } #endif BookmarkDragData::BookmarkDragData(const BookmarkNode* node) { elements.push_back(Element(node)); } BookmarkDragData::BookmarkDragData( const std::vector<const BookmarkNode*>& nodes) { for (size_t i = 0; i < nodes.size(); ++i) elements.push_back(Element(nodes[i])); } #if !defined(OS_MACOSX) void BookmarkDragData::WriteToClipboard(Profile* profile) const { ScopedClipboardWriter scw(g_browser_process->clipboard()); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { string16 title = WideToUTF16Hack(elements[0].title); std::string url = elements[0].url.spec(); scw.WriteBookmark(title, url); scw.WriteHyperlink(EscapeForHTML(UTF16ToUTF8(title)), url); } Pickle pickle; WriteToPickle(profile, &pickle); scw.WritePickledData(pickle, kClipboardFormatString); } bool BookmarkDragData::ReadFromClipboard() { std::string data; Clipboard* clipboard = g_browser_process->clipboard(); clipboard->ReadData(kClipboardFormatString, &data); if (!data.empty()) { Pickle pickle(data.data(), data.size()); if (ReadFromPickle(&pickle)) return true; } string16 title; std::string url; clipboard->ReadBookmark(&title, &url); if (!url.empty()) { Element element; element.is_url = true; element.url = GURL(url); element.title = UTF16ToWideHack(title); elements.clear(); elements.push_back(element); return true; } return false; } #endif // !defined(OS_MACOSX) #if defined(TOOLKIT_VIEWS) void BookmarkDragData::Write(Profile* profile, OSExchangeData* data) const { DCHECK(data); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { if (elements[0].url.SchemeIs(chrome::kJavaScriptScheme)) { data->SetString(ASCIIToWide(elements[0].url.spec())); } else { data->SetURL(elements[0].url, elements[0].title); } } Pickle data_pickle; WriteToPickle(profile, &data_pickle); data->SetPickledData(GetBookmarkCustomFormat(), data_pickle); } bool BookmarkDragData::Read(const OSExchangeData& data) { elements.clear(); profile_path_.clear(); if (data.HasCustomFormat(GetBookmarkCustomFormat())) { Pickle drag_data_pickle; if (data.GetPickledData(GetBookmarkCustomFormat(), &drag_data_pickle)) { if (!ReadFromPickle(&drag_data_pickle)) return false; } } else { // See if there is a URL on the clipboard. Element element; if (data.GetURLAndTitle(&element.url, &element.title) && element.url.is_valid()) { element.is_url = true; elements.push_back(element); } } return is_valid(); } #endif void BookmarkDragData::WriteToPickle(Profile* profile, Pickle* pickle) const { #if defined(WCHAR_T_IS_UTF16) pickle->WriteWString( profile ? profile->GetPath().ToWStringHack() : std::wstring()); #elif defined(WCHAR_T_IS_UTF32) pickle->WriteString( profile ? profile->GetPath().value() : std::string()); #else NOTIMPLEMENTED() << "Impossible encoding situation!"; #endif pickle->WriteSize(elements.size()); for (size_t i = 0; i < elements.size(); ++i) elements[i].WriteToPickle(pickle); } bool BookmarkDragData::ReadFromPickle(Pickle* pickle) { void* data_iterator = NULL; size_t element_count; #if defined(WCHAR_T_IS_UTF16) if (pickle->ReadWString(&data_iterator, &profile_path_) && #elif defined(WCHAR_T_IS_UTF32) if (pickle->ReadString(&data_iterator, &profile_path_) && #else NOTIMPLEMENTED() << "Impossible encoding situation!"; if (false && #endif pickle->ReadSize(&data_iterator, &element_count)) { std::vector<Element> tmp_elements; tmp_elements.resize(element_count); for (size_t i = 0; i < element_count; ++i) { if (!tmp_elements[i].ReadFromPickle(pickle, &data_iterator)) { return false; } } elements.swap(tmp_elements); } return true; } std::vector<const BookmarkNode*> BookmarkDragData::GetNodes( Profile* profile) const { std::vector<const BookmarkNode*> nodes; if (!IsFromProfile(profile)) return nodes; for (size_t i = 0; i < elements.size(); ++i) { const BookmarkNode* node = profile->GetBookmarkModel()->GetNodeByID(elements[i].id_); if (!node) { nodes.clear(); return nodes; } nodes.push_back(node); } return nodes; } const BookmarkNode* BookmarkDragData::GetFirstNode(Profile* profile) const { std::vector<const BookmarkNode*> nodes = GetNodes(profile); return nodes.size() == 1 ? nodes[0] : NULL; } bool BookmarkDragData::IsFromProfile(Profile* profile) const { // An empty path means the data is not associated with any profile. return (!profile_path_.empty() && #if defined(WCHAR_T_IS_UTF16) profile->GetPath().ToWStringHack() == profile_path_); #elif defined(WCHAR_T_IS_UTF32) profile->GetPath().value() == profile_path_); #endif } <commit_msg>Lands http://codereview.chromium.org/527033 for bryenug:<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/bookmarks/bookmark_drag_data.h" #include "app/clipboard/scoped_clipboard_writer.h" #include "base/basictypes.h" #include "base/pickle.h" #include "base/string_util.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/profile.h" #include "chrome/common/url_constants.h" #include "chrome/browser/browser_process.h" #include "net/base/escape.h" const char* BookmarkDragData::kClipboardFormatString = "chromium/x-bookmark-entries"; BookmarkDragData::Element::Element(const BookmarkNode* node) : is_url(node->is_url()), url(node->GetURL()), title(node->GetTitle()), id_(node->id()) { for (int i = 0; i < node->GetChildCount(); ++i) children.push_back(Element(node->GetChild(i))); } void BookmarkDragData::Element::WriteToPickle(Pickle* pickle) const { pickle->WriteBool(is_url); pickle->WriteString(url.spec()); pickle->WriteWString(title); pickle->WriteInt64(id_); if (!is_url) { pickle->WriteSize(children.size()); for (std::vector<Element>::const_iterator i = children.begin(); i != children.end(); ++i) { i->WriteToPickle(pickle); } } } bool BookmarkDragData::Element::ReadFromPickle(Pickle* pickle, void** iterator) { std::string url_spec; if (!pickle->ReadBool(iterator, &is_url) || !pickle->ReadString(iterator, &url_spec) || !pickle->ReadWString(iterator, &title) || !pickle->ReadInt64(iterator, &id_)) { return false; } url = GURL(url_spec); children.clear(); if (!is_url) { size_t children_count; if (!pickle->ReadSize(iterator, &children_count)) return false; children.resize(children_count); for (std::vector<Element>::iterator i = children.begin(); i != children.end(); ++i) { if (!i->ReadFromPickle(pickle, iterator)) return false; } } return true; } #if defined(TOOLKIT_VIEWS) // static OSExchangeData::CustomFormat BookmarkDragData::GetBookmarkCustomFormat() { static OSExchangeData::CustomFormat format; static bool format_valid = false; if (!format_valid) { format_valid = true; format = OSExchangeData::RegisterCustomFormat( BookmarkDragData::kClipboardFormatString); } return format; } #endif BookmarkDragData::BookmarkDragData(const BookmarkNode* node) { elements.push_back(Element(node)); } BookmarkDragData::BookmarkDragData( const std::vector<const BookmarkNode*>& nodes) { for (size_t i = 0; i < nodes.size(); ++i) elements.push_back(Element(nodes[i])); } #if !defined(OS_MACOSX) void BookmarkDragData::WriteToClipboard(Profile* profile) const { ScopedClipboardWriter scw(g_browser_process->clipboard()); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { string16 title = WideToUTF16Hack(elements[0].title); std::string url = elements[0].url.spec(); scw.WriteBookmark(title, url); scw.WriteHyperlink(EscapeForHTML(UTF16ToUTF8(title)), url); // Also write the URL to the clipboard as text so that it can be pasted // into text fields scw.WriteURL(UTF8ToUTF16(url)); } Pickle pickle; WriteToPickle(profile, &pickle); scw.WritePickledData(pickle, kClipboardFormatString); } bool BookmarkDragData::ReadFromClipboard() { std::string data; Clipboard* clipboard = g_browser_process->clipboard(); clipboard->ReadData(kClipboardFormatString, &data); if (!data.empty()) { Pickle pickle(data.data(), data.size()); if (ReadFromPickle(&pickle)) return true; } string16 title; std::string url; clipboard->ReadBookmark(&title, &url); if (!url.empty()) { Element element; element.is_url = true; element.url = GURL(url); element.title = UTF16ToWideHack(title); elements.clear(); elements.push_back(element); return true; } return false; } #endif // !defined(OS_MACOSX) #if defined(TOOLKIT_VIEWS) void BookmarkDragData::Write(Profile* profile, OSExchangeData* data) const { DCHECK(data); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { if (elements[0].url.SchemeIs(chrome::kJavaScriptScheme)) { data->SetString(ASCIIToWide(elements[0].url.spec())); } else { data->SetURL(elements[0].url, elements[0].title); } } Pickle data_pickle; WriteToPickle(profile, &data_pickle); data->SetPickledData(GetBookmarkCustomFormat(), data_pickle); } bool BookmarkDragData::Read(const OSExchangeData& data) { elements.clear(); profile_path_.clear(); if (data.HasCustomFormat(GetBookmarkCustomFormat())) { Pickle drag_data_pickle; if (data.GetPickledData(GetBookmarkCustomFormat(), &drag_data_pickle)) { if (!ReadFromPickle(&drag_data_pickle)) return false; } } else { // See if there is a URL on the clipboard. Element element; if (data.GetURLAndTitle(&element.url, &element.title) && element.url.is_valid()) { element.is_url = true; elements.push_back(element); } } return is_valid(); } #endif void BookmarkDragData::WriteToPickle(Profile* profile, Pickle* pickle) const { #if defined(WCHAR_T_IS_UTF16) pickle->WriteWString( profile ? profile->GetPath().ToWStringHack() : std::wstring()); #elif defined(WCHAR_T_IS_UTF32) pickle->WriteString( profile ? profile->GetPath().value() : std::string()); #else NOTIMPLEMENTED() << "Impossible encoding situation!"; #endif pickle->WriteSize(elements.size()); for (size_t i = 0; i < elements.size(); ++i) elements[i].WriteToPickle(pickle); } bool BookmarkDragData::ReadFromPickle(Pickle* pickle) { void* data_iterator = NULL; size_t element_count; #if defined(WCHAR_T_IS_UTF16) if (pickle->ReadWString(&data_iterator, &profile_path_) && #elif defined(WCHAR_T_IS_UTF32) if (pickle->ReadString(&data_iterator, &profile_path_) && #else NOTIMPLEMENTED() << "Impossible encoding situation!"; if (false && #endif pickle->ReadSize(&data_iterator, &element_count)) { std::vector<Element> tmp_elements; tmp_elements.resize(element_count); for (size_t i = 0; i < element_count; ++i) { if (!tmp_elements[i].ReadFromPickle(pickle, &data_iterator)) { return false; } } elements.swap(tmp_elements); } return true; } std::vector<const BookmarkNode*> BookmarkDragData::GetNodes( Profile* profile) const { std::vector<const BookmarkNode*> nodes; if (!IsFromProfile(profile)) return nodes; for (size_t i = 0; i < elements.size(); ++i) { const BookmarkNode* node = profile->GetBookmarkModel()->GetNodeByID(elements[i].id_); if (!node) { nodes.clear(); return nodes; } nodes.push_back(node); } return nodes; } const BookmarkNode* BookmarkDragData::GetFirstNode(Profile* profile) const { std::vector<const BookmarkNode*> nodes = GetNodes(profile); return nodes.size() == 1 ? nodes[0] : NULL; } bool BookmarkDragData::IsFromProfile(Profile* profile) const { // An empty path means the data is not associated with any profile. return (!profile_path_.empty() && #if defined(WCHAR_T_IS_UTF16) profile->GetPath().ToWStringHack() == profile_path_); #elif defined(WCHAR_T_IS_UTF32) profile->GetPath().value() == profile_path_); #endif } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "ExecutionContext.h" #include "cling/Interpreter/Value.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace cling; namespace { class JITtedFunctionCollector : public llvm::JITEventListener { private: llvm::SmallVector<llvm::Function*, 24> m_functions; llvm::ExecutionEngine *m_engine; public: JITtedFunctionCollector(): m_functions(), m_engine(0) { } virtual ~JITtedFunctionCollector() { } virtual void NotifyFunctionEmitted(const llvm::Function& F, void *, size_t, const JITEventListener::EmittedFunctionDetails&) { m_functions.push_back(const_cast<llvm::Function *>(&F)); } virtual void NotifyFreeingMachineCode(void* /*OldPtr*/) {} void UnregisterFunctionMapping(llvm::ExecutionEngine&); }; } void JITtedFunctionCollector::UnregisterFunctionMapping( llvm::ExecutionEngine &engine) { for (std::vector<llvm::Function *>::reverse_iterator it = m_functions.rbegin(), et = m_functions.rend(); it != et; ++it) { llvm::Function *ff = *it; engine.freeMachineCodeForFunction(ff); engine.updateGlobalMapping(ff, 0); } m_functions.clear(); } std::set<std::string> ExecutionContext::m_unresolvedSymbols; std::vector<ExecutionContext::LazyFunctionCreatorFunc_t> ExecutionContext::m_lazyFuncCreator; ExecutionContext::ExecutionContext(): m_engine(0), m_RunningStaticInits(false), m_CxaAtExitRemapped(false) { } void ExecutionContext::InitializeBuilder(llvm::Module* m) { // // Create an execution engine to use. // // Note: Engine takes ownership of the module. assert(m && "Module cannot be null"); llvm::EngineBuilder builder(m); builder.setOptLevel(llvm::CodeGenOpt::Less); std::string errMsg; builder.setErrorStr(&errMsg); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); m_engine = builder.create(); assert(m_engine && "Cannot initialize builder without module!"); //m_engine->addModule(m); // Note: The engine takes ownership of the module. // install lazy function m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } ExecutionContext::~ExecutionContext() { } void unresolvedSymbol() { // throw exception? llvm::errs() << "ExecutionContext: calling unresolved symbol (should never happen)!\n"; } void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols m_unresolvedSymbols.insert(mangled_name); // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } return HandleMissingFunction(mangled_name); } void ExecutionContext::executeFunction(llvm::StringRef funcname, llvm::GenericValue* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below if (!m_CxaAtExitRemapped) { // Rewire atexit: llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); if (atExit && clingAtExit) { void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } } // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.data()); if (!f) { llvm::errs() << "ExecutionContext::executeFunction: could not find function named " << funcname << '\n'; return; } JITtedFunctionCollector listener; // register the listener m_engine->RegisterJITEventListener(&listener); m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::executeFunction: symbol \'" << *i << "\' unresolved!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); m_engine->updateGlobalMapping(ff, 0); m_engine->freeMachineCodeForFunction(ff); } m_unresolvedSymbols.clear(); // cleanup functions listener.UnregisterFunctionMapping(*m_engine); m_engine->UnregisterJITEventListener(&listener); return; } // cleanup list and unregister our listener m_engine->UnregisterJITEventListener(&listener); std::vector<llvm::GenericValue> args; bool wantReturn = (returnValue); if (f->hasStructRetAttr()) { // Function expects to receive the storage for the returned aggregate as // first argument. Make sure returnValue is able to receive it, i.e. // that it has the pointer set: assert(returnValue && GVTOP(*returnValue) && \ "must call function returning aggregate with returnValue pointing " \ "to the storage space for return value!"); args.push_back(*returnValue); // will get set as arg0, must not assign. wantReturn = false; } if (wantReturn) { *returnValue = m_engine->runFunction(f, args); } else { m_engine->runFunction(f, args); } m_engine->freeMachineCodeForFunction(f); } void ExecutionContext::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); if (!m_engine) InitializeBuilder(m); assert(m_engine && "Code generation did not create an engine!"); if (!m_RunningStaticInits) { m_RunningStaticInits = true; llvm::GlobalVariable* gctors = m->getGlobalVariable("llvm.global_ctors", true); if (gctors) { m_engine->runStaticConstructorsDestructors(false); gctors->eraseFromParent(); } m_RunningStaticInits = false; } } void ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* gdtors = m->getGlobalVariable("llvm.global_dtors", true); if (gdtors) { m_engine->runStaticConstructorsDestructors(true); } } int ExecutionContext::verifyModule(llvm::Module* m) { // // Verify generated module. // bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction); if (mod_has_errs) { return 1; } return 0; } void ExecutionContext::printModule(llvm::Module* m) { // // Print module LLVM code in human-readable form. // llvm::PassManager PM; PM.add(llvm::createPrintModulePass(&llvm::outs())); PM.run(*m); } void ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress){ void* actualAdress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAdress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } <commit_msg>That is why we need auto...: use the proper iterator<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "ExecutionContext.h" #include "cling/Interpreter/Value.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace cling; namespace { class JITtedFunctionCollector : public llvm::JITEventListener { private: llvm::SmallVector<llvm::Function*, 24> m_functions; llvm::ExecutionEngine *m_engine; public: JITtedFunctionCollector(): m_functions(), m_engine(0) { } virtual ~JITtedFunctionCollector() { } virtual void NotifyFunctionEmitted(const llvm::Function& F, void *, size_t, const JITEventListener::EmittedFunctionDetails&) { m_functions.push_back(const_cast<llvm::Function *>(&F)); } virtual void NotifyFreeingMachineCode(void* /*OldPtr*/) {} void UnregisterFunctionMapping(llvm::ExecutionEngine&); }; } void JITtedFunctionCollector::UnregisterFunctionMapping( llvm::ExecutionEngine &engine) { for (llvm::SmallVectorImpl<llvm::Function *>::reverse_iterator it = m_functions.rbegin(), et = m_functions.rend(); it != et; ++it) { llvm::Function *ff = *it; engine.freeMachineCodeForFunction(ff); engine.updateGlobalMapping(ff, 0); } m_functions.clear(); } std::set<std::string> ExecutionContext::m_unresolvedSymbols; std::vector<ExecutionContext::LazyFunctionCreatorFunc_t> ExecutionContext::m_lazyFuncCreator; ExecutionContext::ExecutionContext(): m_engine(0), m_RunningStaticInits(false), m_CxaAtExitRemapped(false) { } void ExecutionContext::InitializeBuilder(llvm::Module* m) { // // Create an execution engine to use. // // Note: Engine takes ownership of the module. assert(m && "Module cannot be null"); llvm::EngineBuilder builder(m); builder.setOptLevel(llvm::CodeGenOpt::Less); std::string errMsg; builder.setErrorStr(&errMsg); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); m_engine = builder.create(); assert(m_engine && "Cannot initialize builder without module!"); //m_engine->addModule(m); // Note: The engine takes ownership of the module. // install lazy function m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } ExecutionContext::~ExecutionContext() { } void unresolvedSymbol() { // throw exception? llvm::errs() << "ExecutionContext: calling unresolved symbol (should never happen)!\n"; } void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols m_unresolvedSymbols.insert(mangled_name); // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } return HandleMissingFunction(mangled_name); } void ExecutionContext::executeFunction(llvm::StringRef funcname, llvm::GenericValue* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below if (!m_CxaAtExitRemapped) { // Rewire atexit: llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); if (atExit && clingAtExit) { void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } } // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.data()); if (!f) { llvm::errs() << "ExecutionContext::executeFunction: could not find function named " << funcname << '\n'; return; } JITtedFunctionCollector listener; // register the listener m_engine->RegisterJITEventListener(&listener); m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::executeFunction: symbol \'" << *i << "\' unresolved!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); m_engine->updateGlobalMapping(ff, 0); m_engine->freeMachineCodeForFunction(ff); } m_unresolvedSymbols.clear(); // cleanup functions listener.UnregisterFunctionMapping(*m_engine); m_engine->UnregisterJITEventListener(&listener); return; } // cleanup list and unregister our listener m_engine->UnregisterJITEventListener(&listener); std::vector<llvm::GenericValue> args; bool wantReturn = (returnValue); if (f->hasStructRetAttr()) { // Function expects to receive the storage for the returned aggregate as // first argument. Make sure returnValue is able to receive it, i.e. // that it has the pointer set: assert(returnValue && GVTOP(*returnValue) && \ "must call function returning aggregate with returnValue pointing " \ "to the storage space for return value!"); args.push_back(*returnValue); // will get set as arg0, must not assign. wantReturn = false; } if (wantReturn) { *returnValue = m_engine->runFunction(f, args); } else { m_engine->runFunction(f, args); } m_engine->freeMachineCodeForFunction(f); } void ExecutionContext::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); if (!m_engine) InitializeBuilder(m); assert(m_engine && "Code generation did not create an engine!"); if (!m_RunningStaticInits) { m_RunningStaticInits = true; llvm::GlobalVariable* gctors = m->getGlobalVariable("llvm.global_ctors", true); if (gctors) { m_engine->runStaticConstructorsDestructors(false); gctors->eraseFromParent(); } m_RunningStaticInits = false; } } void ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* gdtors = m->getGlobalVariable("llvm.global_dtors", true); if (gdtors) { m_engine->runStaticConstructorsDestructors(true); } } int ExecutionContext::verifyModule(llvm::Module* m) { // // Verify generated module. // bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction); if (mod_has_errs) { return 1; } return 0; } void ExecutionContext::printModule(llvm::Module* m) { // // Print module LLVM code in human-readable form. // llvm::PassManager PM; PM.add(llvm::createPrintModulePass(&llvm::outs())); PM.run(*m); } void ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress){ void* actualAdress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAdress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * 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 <qmdnsengine/message.h> #include <qmdnsengine/query.h> #include "util.h" bool queryReceived(TestServer *server, const QByteArray &name, quint16 type) { const auto messages = server->receivedMessages(); for (const QMdnsEngine::Message &message, messages) { if (!message.isResponse()) { const auto queries = message.queries(); for (const QMdnsEngine::Query &query, queries) { if (query.name() == name && query.type() == type) { return true; } } } } return false; } <commit_msg>Fix another typo in libcommon test suite.<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * 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 <qmdnsengine/message.h> #include <qmdnsengine/query.h> #include "util.h" bool queryReceived(TestServer *server, const QByteArray &name, quint16 type) { const auto messages = server->receivedMessages(); for (const QMdnsEngine::Message &message : messages) { if (!message.isResponse()) { const auto queries = message.queries(); for (const QMdnsEngine::Query &query : queries) { if (query.name() == name && query.type() == type) { return true; } } } } return false; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/file_util.h" #include "base/scoped_temp_dir.h" #include "chrome/browser/character_encoding.h" #include "chrome/browser/net/url_request_mock_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/web_contents.h" #include "content/test/net/url_request_mock_http_job.h" #include "content/test/test_navigation_observer.h" using content::BrowserThread; static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("encoding_tests"); class BrowserEncodingTest : public InProcessBrowserTest { protected: BrowserEncodingTest() {} // Saves the current page and verifies that the output matches the expected // result. void SaveAndCompare(const char* filename_to_write, const FilePath& expected) { // Dump the page, the content of dump page should be identical to the // expected result file. FilePath full_file_name = save_dir_.AppendASCII(filename_to_write); // We save the page as way of complete HTML file, which requires a directory // name to save sub resources in it. Although this test file does not have // sub resources, but the directory name is still required. ui_test_utils::WindowedNotificationObserver observer( content::NOTIFICATION_SAVE_PACKAGE_SUCCESSFULLY_FINISHED, content::NotificationService::AllSources()); browser()->GetSelectedWebContents()->SavePage( full_file_name, temp_sub_resource_dir_, content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML); observer.Wait(); FilePath expected_file_name = ui_test_utils::GetTestFilePath( FilePath(kTestDir), expected); EXPECT_TRUE(file_util::ContentsEqual(full_file_name, expected_file_name)); } void SetUpOnMainThread() OVERRIDE { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); save_dir_ = temp_dir_.path(); temp_sub_resource_dir_ = save_dir_.AppendASCII("sub_resource_files"); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true)); } ScopedTempDir temp_dir_; FilePath save_dir_; FilePath temp_sub_resource_dir_; }; // TODO(jnd): 1. Some encodings are missing here. It'll be added later. See // http://crbug.com/13306. // 2. Add more files with multiple encoding name variants for each canonical // encoding name). Webkit layout tests cover some, but testing in the UI test is // also necessary. // This test fails frequently on the win_rel trybot. See http://crbug.com/122053 #if defined(OS_WIN) #define MAYBE_TestEncodingAliasMapping DISABLED_TestEncodingAliasMapping #else #define MAYBE_TestEncodingAliasMapping TestEncodingAliasMapping #endif IN_PROC_BROWSER_TEST_F(BrowserEncodingTest, MAYBE_TestEncodingAliasMapping) { struct EncodingTestData { const char* file_name; const char* encoding_name; }; const EncodingTestData kEncodingTestDatas[] = { { "Big5.html", "Big5" }, { "EUC-JP.html", "EUC-JP" }, { "gb18030.html", "gb18030" }, { "iso-8859-1.html", "ISO-8859-1" }, { "ISO-8859-2.html", "ISO-8859-2" }, { "ISO-8859-4.html", "ISO-8859-4" }, { "ISO-8859-5.html", "ISO-8859-5" }, { "ISO-8859-6.html", "ISO-8859-6" }, { "ISO-8859-7.html", "ISO-8859-7" }, { "ISO-8859-8.html", "ISO-8859-8" }, { "ISO-8859-13.html", "ISO-8859-13" }, { "ISO-8859-15.html", "ISO-8859-15" }, { "KOI8-R.html", "KOI8-R" }, { "KOI8-U.html", "KOI8-U" }, { "macintosh.html", "macintosh" }, { "Shift-JIS.html", "Shift_JIS" }, { "US-ASCII.html", "ISO-8859-1" }, // http://crbug.com/15801 { "UTF-8.html", "UTF-8" }, { "UTF-16LE.html", "UTF-16LE" }, { "windows-874.html", "windows-874" }, // http://crbug.com/95963 // { "windows-949.html", "windows-949" }, { "windows-1250.html", "windows-1250" }, { "windows-1251.html", "windows-1251" }, { "windows-1252.html", "windows-1252" }, { "windows-1253.html", "windows-1253" }, { "windows-1254.html", "windows-1254" }, { "windows-1255.html", "windows-1255" }, { "windows-1256.html", "windows-1256" }, { "windows-1257.html", "windows-1257" }, { "windows-1258.html", "windows-1258" } }; const char* const kAliasTestDir = "alias_mapping"; FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAliasTestDir); for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kEncodingTestDatas); ++i) { FilePath test_file_path(test_dir_path); test_file_path = test_file_path.AppendASCII( kEncodingTestDatas[i].file_name); GURL url = URLRequestMockHTTPJob::GetMockUrl(test_file_path); ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ(kEncodingTestDatas[i].encoding_name, browser()->GetSelectedWebContents()->GetEncoding()); } } // Marked as flaky: see http://crbug.com/44668 IN_PROC_BROWSER_TEST_F(BrowserEncodingTest, TestOverrideEncoding) { const char* const kTestFileName = "gb18030_with_iso88591_meta.html"; const char* const kExpectedFileName = "expected_gb18030_saved_from_iso88591_meta.html"; const char* const kOverrideTestDir = "user_override"; FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kOverrideTestDir); test_dir_path = test_dir_path.AppendASCII(kTestFileName); GURL url = URLRequestMockHTTPJob::GetMockUrl(test_dir_path); ui_test_utils::NavigateToURL(browser(), url); content::WebContents* web_contents = browser()->GetSelectedWebContents(); EXPECT_EQ("ISO-8859-1", web_contents->GetEncoding()); // Override the encoding to "gb18030". const std::string selected_encoding = CharacterEncoding::GetCanonicalEncodingNameByAliasName("gb18030"); TestNavigationObserver navigation_observer( content::Source<content::NavigationController>( &web_contents->GetController())); web_contents->SetOverrideEncoding(selected_encoding); navigation_observer.Wait(); EXPECT_EQ("gb18030", web_contents->GetEncoding()); FilePath expected_filename = FilePath().AppendASCII(kOverrideTestDir).AppendASCII(kExpectedFileName); SaveAndCompare(kTestFileName, expected_filename); } // The following encodings are excluded from the auto-detection test because // it's a known issue that the current encoding detector does not detect them: // ISO-8859-4 // ISO-8859-13 // KOI8-U // macintosh // windows-874 // windows-1252 // windows-1253 // windows-1257 // windows-1258 // For Hebrew, the expected encoding value is ISO-8859-8-I. See // http://crbug.com/2927 for more details. // // This test fails frequently on the win_rel trybot. See http://crbug.com/122053 #if defined(OS_WIN) #define MAYBE_TestEncodingAutoDetect DISABLED_TestEncodingAutoDetect #else #define MAYBE_TestEncodingAutoDetect TestEncodingAutoDetect #endif IN_PROC_BROWSER_TEST_F(BrowserEncodingTest, MAYBE_TestEncodingAutoDetect) { struct EncodingAutoDetectTestData { const char* test_file_name; // File name of test data. const char* expected_result; // File name of expected results. const char* expected_encoding; // expected encoding. }; const EncodingAutoDetectTestData kTestDatas[] = { { "Big5_with_no_encoding_specified.html", "expected_Big5_saved_from_no_encoding_specified.html", "Big5" }, { "gb18030_with_no_encoding_specified.html", "expected_gb18030_saved_from_no_encoding_specified.html", "gb18030" }, { "iso-8859-1_with_no_encoding_specified.html", "expected_iso-8859-1_saved_from_no_encoding_specified.html", "ISO-8859-1" }, { "ISO-8859-5_with_no_encoding_specified.html", "expected_ISO-8859-5_saved_from_no_encoding_specified.html", "ISO-8859-5" }, { "ISO-8859-6_with_no_encoding_specified.html", "expected_ISO-8859-6_saved_from_no_encoding_specified.html", "ISO-8859-6" }, { "ISO-8859-7_with_no_encoding_specified.html", "expected_ISO-8859-7_saved_from_no_encoding_specified.html", "ISO-8859-7" }, { "ISO-8859-8_with_no_encoding_specified.html", "expected_ISO-8859-8_saved_from_no_encoding_specified.html", "ISO-8859-8-I" }, { "KOI8-R_with_no_encoding_specified.html", "expected_KOI8-R_saved_from_no_encoding_specified.html", "KOI8-R" }, { "Shift-JIS_with_no_encoding_specified.html", "expected_Shift-JIS_saved_from_no_encoding_specified.html", "Shift_JIS" }, { "UTF-8_with_no_encoding_specified.html", "expected_UTF-8_saved_from_no_encoding_specified.html", "UTF-8" }, { "windows-949_with_no_encoding_specified.html", "expected_windows-949_saved_from_no_encoding_specified.html", "windows-949-2000" }, { "windows-1251_with_no_encoding_specified.html", "expected_windows-1251_saved_from_no_encoding_specified.html", "windows-1251" }, { "windows-1254_with_no_encoding_specified.html", "expected_windows-1254_saved_from_no_encoding_specified.html", "windows-1254" }, { "windows-1255_with_no_encoding_specified.html", "expected_windows-1255_saved_from_no_encoding_specified.html", "windows-1255" }, { "windows-1256_with_no_encoding_specified.html", "expected_windows-1256_saved_from_no_encoding_specified.html", "windows-1256" } }; const char* const kAutoDetectDir = "auto_detect"; // Directory of the files of expected results. const char* const kExpectedResultDir = "expected_results"; FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAutoDetectDir); // Set the default charset to one of encodings not supported by the current // auto-detector (Please refer to the above comments) to make sure we // incorrectly decode the page. Now we use ISO-8859-4. browser()->profile()->GetPrefs()->SetString( prefs::kGlobalDefaultCharset, "ISO-8859-4"); content::WebContents* web_contents = browser()->GetSelectedWebContents(); for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestDatas); ++i) { // Disable auto detect if it is on. browser()->profile()->GetPrefs()->SetBoolean( prefs::kWebKitUsesUniversalDetector, false); FilePath test_file_path(test_dir_path); test_file_path = test_file_path.AppendASCII(kTestDatas[i].test_file_name); GURL url = URLRequestMockHTTPJob::GetMockUrl(test_file_path); ui_test_utils::NavigateToURL(browser(), url); // Get the encoding used for the page, it must be the default charset we // just set. EXPECT_EQ("ISO-8859-4", web_contents->GetEncoding()); // Enable the encoding auto detection. browser()->profile()->GetPrefs()->SetBoolean( prefs::kWebKitUsesUniversalDetector, true); TestNavigationObserver observer( content::Source<content::NavigationController>( &web_contents->GetController())); browser()->Reload(CURRENT_TAB); observer.Wait(); // Re-get the encoding of page. It should return the real encoding now. EXPECT_EQ(kTestDatas[i].expected_encoding, web_contents->GetEncoding()); // Dump the page, the content of dump page should be equal with our expect // result file. FilePath expected_result_file_name = FilePath().AppendASCII(kAutoDetectDir).AppendASCII(kExpectedResultDir). AppendASCII(kTestDatas[i].expected_result); SaveAndCompare(kTestDatas[i].test_file_name, expected_result_file_name); } } <commit_msg>Load every testcase of BrowserEncodingTest.TestEncodingAliasMapping in a new tab to avoid the race condition where the previous encoding is seen.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/file_util.h" #include "base/scoped_temp_dir.h" #include "chrome/browser/character_encoding.h" #include "chrome/browser/net/url_request_mock_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/web_contents.h" #include "content/test/net/url_request_mock_http_job.h" #include "content/test/test_navigation_observer.h" using content::BrowserThread; static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("encoding_tests"); class BrowserEncodingTest : public InProcessBrowserTest { protected: BrowserEncodingTest() {} // Saves the current page and verifies that the output matches the expected // result. void SaveAndCompare(const char* filename_to_write, const FilePath& expected) { // Dump the page, the content of dump page should be identical to the // expected result file. FilePath full_file_name = save_dir_.AppendASCII(filename_to_write); // We save the page as way of complete HTML file, which requires a directory // name to save sub resources in it. Although this test file does not have // sub resources, but the directory name is still required. ui_test_utils::WindowedNotificationObserver observer( content::NOTIFICATION_SAVE_PACKAGE_SUCCESSFULLY_FINISHED, content::NotificationService::AllSources()); browser()->GetSelectedWebContents()->SavePage( full_file_name, temp_sub_resource_dir_, content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML); observer.Wait(); FilePath expected_file_name = ui_test_utils::GetTestFilePath( FilePath(kTestDir), expected); EXPECT_TRUE(file_util::ContentsEqual(full_file_name, expected_file_name)); } void SetUpOnMainThread() OVERRIDE { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); save_dir_ = temp_dir_.path(); temp_sub_resource_dir_ = save_dir_.AppendASCII("sub_resource_files"); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true)); } ScopedTempDir temp_dir_; FilePath save_dir_; FilePath temp_sub_resource_dir_; }; // TODO(jnd): 1. Some encodings are missing here. It'll be added later. See // http://crbug.com/13306. // 2. Add more files with multiple encoding name variants for each canonical // encoding name). Webkit layout tests cover some, but testing in the UI test is // also necessary. // SLOW_ is added for XP debug bots. These tests should really be unittests... IN_PROC_BROWSER_TEST_F(BrowserEncodingTest, SLOW_TestEncodingAliasMapping) { struct EncodingTestData { const char* file_name; const char* encoding_name; }; const EncodingTestData kEncodingTestDatas[] = { { "Big5.html", "Big5" }, { "EUC-JP.html", "EUC-JP" }, { "gb18030.html", "gb18030" }, { "iso-8859-1.html", "ISO-8859-1" }, { "ISO-8859-2.html", "ISO-8859-2" }, { "ISO-8859-4.html", "ISO-8859-4" }, { "ISO-8859-5.html", "ISO-8859-5" }, { "ISO-8859-6.html", "ISO-8859-6" }, { "ISO-8859-7.html", "ISO-8859-7" }, { "ISO-8859-8.html", "ISO-8859-8" }, { "ISO-8859-13.html", "ISO-8859-13" }, { "ISO-8859-15.html", "ISO-8859-15" }, { "KOI8-R.html", "KOI8-R" }, { "KOI8-U.html", "KOI8-U" }, { "macintosh.html", "macintosh" }, { "Shift-JIS.html", "Shift_JIS" }, { "US-ASCII.html", "ISO-8859-1" }, // http://crbug.com/15801 { "UTF-8.html", "UTF-8" }, { "UTF-16LE.html", "UTF-16LE" }, { "windows-874.html", "windows-874" }, // http://crbug.com/95963 // { "windows-949.html", "windows-949" }, { "windows-1250.html", "windows-1250" }, { "windows-1251.html", "windows-1251" }, { "windows-1252.html", "windows-1252" }, { "windows-1253.html", "windows-1253" }, { "windows-1254.html", "windows-1254" }, { "windows-1255.html", "windows-1255" }, { "windows-1256.html", "windows-1256" }, { "windows-1257.html", "windows-1257" }, { "windows-1258.html", "windows-1258" } }; const char* const kAliasTestDir = "alias_mapping"; FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAliasTestDir); for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kEncodingTestDatas); ++i) { FilePath test_file_path(test_dir_path); test_file_path = test_file_path.AppendASCII( kEncodingTestDatas[i].file_name); GURL url = URLRequestMockHTTPJob::GetMockUrl(test_file_path); // When looping through all the above files in one WebContents, there's a // race condition on Windows trybots that causes the previous encoding to be // seen sometimes. Create a new tab for each one. http://crbug.com/122053 ui_test_utils::NavigateToURLWithDisposition( browser(), url, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); EXPECT_EQ(kEncodingTestDatas[i].encoding_name, browser()->GetSelectedWebContents()->GetEncoding()); browser()->CloseTab(); } } // Marked as flaky: see http://crbug.com/44668 IN_PROC_BROWSER_TEST_F(BrowserEncodingTest, TestOverrideEncoding) { const char* const kTestFileName = "gb18030_with_iso88591_meta.html"; const char* const kExpectedFileName = "expected_gb18030_saved_from_iso88591_meta.html"; const char* const kOverrideTestDir = "user_override"; FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kOverrideTestDir); test_dir_path = test_dir_path.AppendASCII(kTestFileName); GURL url = URLRequestMockHTTPJob::GetMockUrl(test_dir_path); ui_test_utils::NavigateToURL(browser(), url); content::WebContents* web_contents = browser()->GetSelectedWebContents(); EXPECT_EQ("ISO-8859-1", web_contents->GetEncoding()); // Override the encoding to "gb18030". const std::string selected_encoding = CharacterEncoding::GetCanonicalEncodingNameByAliasName("gb18030"); TestNavigationObserver navigation_observer( content::Source<content::NavigationController>( &web_contents->GetController())); web_contents->SetOverrideEncoding(selected_encoding); navigation_observer.Wait(); EXPECT_EQ("gb18030", web_contents->GetEncoding()); FilePath expected_filename = FilePath().AppendASCII(kOverrideTestDir).AppendASCII(kExpectedFileName); SaveAndCompare(kTestFileName, expected_filename); } // The following encodings are excluded from the auto-detection test because // it's a known issue that the current encoding detector does not detect them: // ISO-8859-4 // ISO-8859-13 // KOI8-U // macintosh // windows-874 // windows-1252 // windows-1253 // windows-1257 // windows-1258 // For Hebrew, the expected encoding value is ISO-8859-8-I. See // http://crbug.com/2927 for more details. // // This test fails frequently on the win_rel trybot. See http://crbug.com/122053 #if defined(OS_WIN) #define MAYBE_TestEncodingAutoDetect DISABLED_TestEncodingAutoDetect #else #define MAYBE_TestEncodingAutoDetect TestEncodingAutoDetect #endif IN_PROC_BROWSER_TEST_F(BrowserEncodingTest, MAYBE_TestEncodingAutoDetect) { struct EncodingAutoDetectTestData { const char* test_file_name; // File name of test data. const char* expected_result; // File name of expected results. const char* expected_encoding; // expected encoding. }; const EncodingAutoDetectTestData kTestDatas[] = { { "Big5_with_no_encoding_specified.html", "expected_Big5_saved_from_no_encoding_specified.html", "Big5" }, { "gb18030_with_no_encoding_specified.html", "expected_gb18030_saved_from_no_encoding_specified.html", "gb18030" }, { "iso-8859-1_with_no_encoding_specified.html", "expected_iso-8859-1_saved_from_no_encoding_specified.html", "ISO-8859-1" }, { "ISO-8859-5_with_no_encoding_specified.html", "expected_ISO-8859-5_saved_from_no_encoding_specified.html", "ISO-8859-5" }, { "ISO-8859-6_with_no_encoding_specified.html", "expected_ISO-8859-6_saved_from_no_encoding_specified.html", "ISO-8859-6" }, { "ISO-8859-7_with_no_encoding_specified.html", "expected_ISO-8859-7_saved_from_no_encoding_specified.html", "ISO-8859-7" }, { "ISO-8859-8_with_no_encoding_specified.html", "expected_ISO-8859-8_saved_from_no_encoding_specified.html", "ISO-8859-8-I" }, { "KOI8-R_with_no_encoding_specified.html", "expected_KOI8-R_saved_from_no_encoding_specified.html", "KOI8-R" }, { "Shift-JIS_with_no_encoding_specified.html", "expected_Shift-JIS_saved_from_no_encoding_specified.html", "Shift_JIS" }, { "UTF-8_with_no_encoding_specified.html", "expected_UTF-8_saved_from_no_encoding_specified.html", "UTF-8" }, { "windows-949_with_no_encoding_specified.html", "expected_windows-949_saved_from_no_encoding_specified.html", "windows-949-2000" }, { "windows-1251_with_no_encoding_specified.html", "expected_windows-1251_saved_from_no_encoding_specified.html", "windows-1251" }, { "windows-1254_with_no_encoding_specified.html", "expected_windows-1254_saved_from_no_encoding_specified.html", "windows-1254" }, { "windows-1255_with_no_encoding_specified.html", "expected_windows-1255_saved_from_no_encoding_specified.html", "windows-1255" }, { "windows-1256_with_no_encoding_specified.html", "expected_windows-1256_saved_from_no_encoding_specified.html", "windows-1256" } }; const char* const kAutoDetectDir = "auto_detect"; // Directory of the files of expected results. const char* const kExpectedResultDir = "expected_results"; FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAutoDetectDir); // Set the default charset to one of encodings not supported by the current // auto-detector (Please refer to the above comments) to make sure we // incorrectly decode the page. Now we use ISO-8859-4. browser()->profile()->GetPrefs()->SetString( prefs::kGlobalDefaultCharset, "ISO-8859-4"); content::WebContents* web_contents = browser()->GetSelectedWebContents(); for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestDatas); ++i) { // Disable auto detect if it is on. browser()->profile()->GetPrefs()->SetBoolean( prefs::kWebKitUsesUniversalDetector, false); FilePath test_file_path(test_dir_path); test_file_path = test_file_path.AppendASCII(kTestDatas[i].test_file_name); GURL url = URLRequestMockHTTPJob::GetMockUrl(test_file_path); ui_test_utils::NavigateToURL(browser(), url); // Get the encoding used for the page, it must be the default charset we // just set. EXPECT_EQ("ISO-8859-4", web_contents->GetEncoding()); // Enable the encoding auto detection. browser()->profile()->GetPrefs()->SetBoolean( prefs::kWebKitUsesUniversalDetector, true); TestNavigationObserver observer( content::Source<content::NavigationController>( &web_contents->GetController())); browser()->Reload(CURRENT_TAB); observer.Wait(); // Re-get the encoding of page. It should return the real encoding now. EXPECT_EQ(kTestDatas[i].expected_encoding, web_contents->GetEncoding()); // Dump the page, the content of dump page should be equal with our expect // result file. FilePath expected_result_file_name = FilePath().AppendASCII(kAutoDetectDir).AppendASCII(kExpectedResultDir). AppendASCII(kTestDatas[i].expected_result); SaveAndCompare(kTestDatas[i].test_file_name, expected_result_file_name); } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/cros/network_parser.h" #include "base/json/json_writer.h" // for debug output only. #include "base/stringprintf.h" // Needed only for debug output (ConnectionTypeToString). #include "chrome/browser/chromeos/cros/native_network_constants.h" namespace chromeos { namespace { Network* CreateNewNetwork( ConnectionType type, const std::string& service_path) { switch (type) { case TYPE_ETHERNET: { EthernetNetwork* ethernet = new EthernetNetwork(service_path); return ethernet; } case TYPE_WIFI: { WifiNetwork* wifi = new WifiNetwork(service_path); return wifi; } case TYPE_CELLULAR: { CellularNetwork* cellular = new CellularNetwork(service_path); return cellular; } case TYPE_VPN: { VirtualNetwork* vpn = new VirtualNetwork(service_path); return vpn; } default: { // If we try and create a service for which we have an unknown // type, then that's a bug, and we will crash. LOG(FATAL) << "Unknown service type: " << type; return NULL; } } } } // namespace NetworkDeviceParser::NetworkDeviceParser( const EnumMapper<PropertyIndex>* mapper) : mapper_(mapper) { CHECK(mapper); } NetworkDeviceParser::~NetworkDeviceParser() { } NetworkDevice* NetworkDeviceParser::CreateDeviceFromInfo( const std::string& device_path, const DictionaryValue& info) { scoped_ptr<NetworkDevice> device(new NetworkDevice(device_path)); if (!UpdateDeviceFromInfo(info, device.get())) { NOTREACHED() << "Unable to create new device"; return NULL; } VLOG(2) << "Created device for path " << device_path; return device.release(); } bool NetworkDeviceParser::UpdateDeviceFromInfo(const DictionaryValue& info, NetworkDevice* device) { for (DictionaryValue::key_iterator iter = info.begin_keys(); iter != info.end_keys(); ++iter) { const std::string& key = *iter; Value* value; bool result = info.GetWithoutPathExpansion(key, &value); DCHECK(result); if (result) UpdateStatus(key, *value, device, NULL); } if (VLOG_IS_ON(2)) { std::string json; base::JSONWriter::Write(&info, true, &json); VLOG(2) << "Updated device for path " << device->device_path() << ": " << json; } return true; } bool NetworkDeviceParser::UpdateStatus(const std::string& key, const Value& value, NetworkDevice* device, PropertyIndex* index) { PropertyIndex found_index = mapper().Get(key); if (index) *index = found_index; if (!ParseValue(found_index, value, device)) { VLOG(1) << "NetworkDeviceParser: Unhandled key: " << key; return false; } if (VLOG_IS_ON(2)) { std::string value_json; base::JSONWriter::Write(&value, true, &value_json); VLOG(2) << "Updated value on device: " << device->device_path() << "[" << key << "] = " << value_json; } return true; } //----------- Network Parser ----------------- NetworkParser::NetworkParser(const EnumMapper<PropertyIndex>* mapper) : mapper_(mapper) { CHECK(mapper); } NetworkParser::~NetworkParser() { } Network* NetworkParser::CreateNetworkFromInfo( const std::string& service_path, const DictionaryValue& info) { ConnectionType type = ParseTypeFromDictionary(info); scoped_ptr<Network> network(CreateNewNetwork(type, service_path)); if (network.get()) UpdateNetworkFromInfo(info, network.get()); VLOG(2) << "Created Network '" << network->name() << "' from info. Path:" << service_path << " Type:" << ConnectionTypeToString(type); return network.release(); } bool NetworkParser::UpdateNetworkFromInfo(const DictionaryValue& info, Network* network) { network->set_unique_id(""); for (DictionaryValue::key_iterator iter = info.begin_keys(); iter != info.end_keys(); ++iter) { const std::string& key = *iter; Value* value; bool res = info.GetWithoutPathExpansion(key, &value); DCHECK(res); if (res) UpdateStatus(key, *value, network, NULL); } if (network->unique_id().empty()) network->CalculateUniqueId(); VLOG(2) << "Updated network '" << network->name() << "' Path:" << network->service_path() << " Type:" << ConnectionTypeToString(network->type()); return true; } bool NetworkParser::UpdateStatus(const std::string& key, const Value& value, Network* network, PropertyIndex* index) { PropertyIndex found_index = mapper().Get(key); if (index) *index = found_index; if (!ParseValue(found_index, value, network)) { VLOG(1) << "Unhandled key '" << key << "' in Network: " << network->name() << " ID: " << network->unique_id() << " Type: " << ConnectionTypeToString(network->type()); return false; } if (VLOG_IS_ON(2)) { std::string value_json; base::JSONWriter::Write(&value, true, &value_json); VLOG(2) << "Updated value on network: " << network->unique_id() << "[" << key << "] = " << value_json; } return true; } bool NetworkParser::ParseValue(PropertyIndex index, const Value& value, Network* network) { switch (index) { case PROPERTY_INDEX_TYPE: { std::string type_string; if (value.GetAsString(&type_string)) { ConnectionType type = ParseType(type_string); LOG_IF(ERROR, type != network->type()) << "Network with mismatched type: " << network->service_path() << " " << type << " != " << network->type(); return true; } break; } case PROPERTY_INDEX_DEVICE: { std::string device_path; if (!value.GetAsString(&device_path)) break; network->set_device_path(device_path); return true; } case PROPERTY_INDEX_NAME: { std::string name; if (value.GetAsString(&name)) { network->SetName(name); return true; } break; } case PROPERTY_INDEX_GUID: { std::string unique_id; if (!value.GetAsString(&unique_id)) break; network->set_unique_id(unique_id); return true; } case PROPERTY_INDEX_PROFILE: { // Note: currently this is only provided for non remembered networks. std::string profile_path; if (!value.GetAsString(&profile_path)) break; network->set_profile_path(profile_path); return true; } case PROPERTY_INDEX_STATE: { std::string state_string; if (value.GetAsString(&state_string)) { network->SetState(ParseState(state_string)); return true; } break; } case PROPERTY_INDEX_MODE: { std::string mode_string; if (value.GetAsString(&mode_string)) { network->mode_ = ParseMode(mode_string); return true; } break; } case PROPERTY_INDEX_ERROR: { std::string error_string; if (value.GetAsString(&error_string)) { network->error_ = ParseError(error_string); return true; } break; } case PROPERTY_INDEX_CONNECTABLE: { bool connectable; if (!value.GetAsBoolean(&connectable)) break; network->set_connectable(connectable); return true; } case PROPERTY_INDEX_IS_ACTIVE: { bool is_active; if (!value.GetAsBoolean(&is_active)) break; network->set_is_active(is_active); return true; } case PROPERTY_INDEX_AUTO_CONNECT: { bool auto_connect; if (!value.GetAsBoolean(&auto_connect)) break; network->set_auto_connect(auto_connect); return true; } case PROPERTY_INDEX_SAVE_CREDENTIALS: { bool save_credentials; if (!value.GetAsBoolean(&save_credentials)) break; network->set_save_credentials(save_credentials); return true; } default: break; } return false; } } // namespace chromeos <commit_msg>Chrome OS: Invoke the correct virtual ParseValue method when creating networks.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/cros/network_parser.h" #include "base/json/json_writer.h" // for debug output only. #include "base/stringprintf.h" // Needed only for debug output (ConnectionTypeToString). #include "chrome/browser/chromeos/cros/native_network_constants.h" namespace chromeos { namespace { Network* CreateNewNetwork( ConnectionType type, const std::string& service_path) { switch (type) { case TYPE_ETHERNET: { EthernetNetwork* ethernet = new EthernetNetwork(service_path); return ethernet; } case TYPE_WIFI: { WifiNetwork* wifi = new WifiNetwork(service_path); return wifi; } case TYPE_CELLULAR: { CellularNetwork* cellular = new CellularNetwork(service_path); return cellular; } case TYPE_VPN: { VirtualNetwork* vpn = new VirtualNetwork(service_path); return vpn; } default: { // If we try and create a service for which we have an unknown // type, then that's a bug, and we will crash. LOG(FATAL) << "Unknown service type: " << type; return NULL; } } } } // namespace NetworkDeviceParser::NetworkDeviceParser( const EnumMapper<PropertyIndex>* mapper) : mapper_(mapper) { CHECK(mapper); } NetworkDeviceParser::~NetworkDeviceParser() { } NetworkDevice* NetworkDeviceParser::CreateDeviceFromInfo( const std::string& device_path, const DictionaryValue& info) { scoped_ptr<NetworkDevice> device(new NetworkDevice(device_path)); if (!UpdateDeviceFromInfo(info, device.get())) { NOTREACHED() << "Unable to create new device"; return NULL; } VLOG(2) << "Created device for path " << device_path; return device.release(); } bool NetworkDeviceParser::UpdateDeviceFromInfo(const DictionaryValue& info, NetworkDevice* device) { for (DictionaryValue::key_iterator iter = info.begin_keys(); iter != info.end_keys(); ++iter) { const std::string& key = *iter; Value* value; bool result = info.GetWithoutPathExpansion(key, &value); DCHECK(result); if (result) UpdateStatus(key, *value, device, NULL); } if (VLOG_IS_ON(2)) { std::string json; base::JSONWriter::Write(&info, true, &json); VLOG(2) << "Updated device for path " << device->device_path() << ": " << json; } return true; } bool NetworkDeviceParser::UpdateStatus(const std::string& key, const Value& value, NetworkDevice* device, PropertyIndex* index) { PropertyIndex found_index = mapper().Get(key); if (index) *index = found_index; if (!ParseValue(found_index, value, device)) { VLOG(1) << "NetworkDeviceParser: Unhandled key: " << key; return false; } if (VLOG_IS_ON(2)) { std::string value_json; base::JSONWriter::Write(&value, true, &value_json); VLOG(2) << "Updated value on device: " << device->device_path() << "[" << key << "] = " << value_json; } return true; } //----------- Network Parser ----------------- NetworkParser::NetworkParser(const EnumMapper<PropertyIndex>* mapper) : mapper_(mapper) { CHECK(mapper); } NetworkParser::~NetworkParser() { } Network* NetworkParser::CreateNetworkFromInfo( const std::string& service_path, const DictionaryValue& info) { ConnectionType type = ParseTypeFromDictionary(info); scoped_ptr<Network> network(CreateNewNetwork(type, service_path)); if (network.get()) UpdateNetworkFromInfo(info, network.get()); VLOG(2) << "Created Network '" << network->name() << "' from info. Path:" << service_path << " Type:" << ConnectionTypeToString(type); return network.release(); } bool NetworkParser::UpdateNetworkFromInfo(const DictionaryValue& info, Network* network) { network->set_unique_id(""); for (DictionaryValue::key_iterator iter = info.begin_keys(); iter != info.end_keys(); ++iter) { const std::string& key = *iter; Value* value; bool res = info.GetWithoutPathExpansion(key, &value); DCHECK(res); if (res) network->UpdateStatus(key, *value, NULL); } if (network->unique_id().empty()) network->CalculateUniqueId(); VLOG(2) << "Updated network '" << network->name() << "' Path:" << network->service_path() << " Type:" << ConnectionTypeToString(network->type()); return true; } bool NetworkParser::UpdateStatus(const std::string& key, const Value& value, Network* network, PropertyIndex* index) { PropertyIndex found_index = mapper().Get(key); if (index) *index = found_index; if (!ParseValue(found_index, value, network)) { VLOG(1) << "Unhandled key '" << key << "' in Network: " << network->name() << " ID: " << network->unique_id() << " Type: " << ConnectionTypeToString(network->type()); return false; } if (VLOG_IS_ON(2)) { std::string value_json; base::JSONWriter::Write(&value, true, &value_json); VLOG(2) << "Updated value on network: " << network->unique_id() << "[" << key << "] = " << value_json; } return true; } bool NetworkParser::ParseValue(PropertyIndex index, const Value& value, Network* network) { switch (index) { case PROPERTY_INDEX_TYPE: { std::string type_string; if (value.GetAsString(&type_string)) { ConnectionType type = ParseType(type_string); LOG_IF(ERROR, type != network->type()) << "Network with mismatched type: " << network->service_path() << " " << type << " != " << network->type(); return true; } break; } case PROPERTY_INDEX_DEVICE: { std::string device_path; if (!value.GetAsString(&device_path)) break; network->set_device_path(device_path); return true; } case PROPERTY_INDEX_NAME: { std::string name; if (value.GetAsString(&name)) { network->SetName(name); return true; } break; } case PROPERTY_INDEX_GUID: { std::string unique_id; if (!value.GetAsString(&unique_id)) break; network->set_unique_id(unique_id); return true; } case PROPERTY_INDEX_PROFILE: { // Note: currently this is only provided for non remembered networks. std::string profile_path; if (!value.GetAsString(&profile_path)) break; network->set_profile_path(profile_path); return true; } case PROPERTY_INDEX_STATE: { std::string state_string; if (value.GetAsString(&state_string)) { network->SetState(ParseState(state_string)); return true; } break; } case PROPERTY_INDEX_MODE: { std::string mode_string; if (value.GetAsString(&mode_string)) { network->mode_ = ParseMode(mode_string); return true; } break; } case PROPERTY_INDEX_ERROR: { std::string error_string; if (value.GetAsString(&error_string)) { network->error_ = ParseError(error_string); return true; } break; } case PROPERTY_INDEX_CONNECTABLE: { bool connectable; if (!value.GetAsBoolean(&connectable)) break; network->set_connectable(connectable); return true; } case PROPERTY_INDEX_IS_ACTIVE: { bool is_active; if (!value.GetAsBoolean(&is_active)) break; network->set_is_active(is_active); return true; } case PROPERTY_INDEX_AUTO_CONNECT: { bool auto_connect; if (!value.GetAsBoolean(&auto_connect)) break; network->set_auto_connect(auto_connect); return true; } case PROPERTY_INDEX_SAVE_CREDENTIALS: { bool save_credentials; if (!value.GetAsBoolean(&save_credentials)) break; network->set_save_credentials(save_credentials); return true; } default: break; } return false; } } // namespace chromeos <|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/chromeos/frame/bubble_window.h" #include <gtk/gtk.h> #include "chrome/browser/chromeos/frame/bubble_frame_view.h" #include "chrome/browser/chromeos/wm_ipc.h" #include "cros/chromeos_wm_ipc_enums.h" #include "gfx/skia_utils_gtk.h" #include "views/window/non_client_view.h" namespace chromeos { // static const SkColor BubbleWindow::kBackgroundColor = SK_ColorWHITE; BubbleWindow::BubbleWindow(views::WindowDelegate* window_delegate) : views::WindowGtk(window_delegate) { MakeTransparent(); } void BubbleWindow::Init(GtkWindow* parent, const gfx::Rect& bounds) { views::WindowGtk::Init(parent, bounds); GdkColor background_color = gfx::SkColorToGdkColor(kBackgroundColor); gtk_widget_modify_bg(GetNativeView(), GTK_STATE_NORMAL, &background_color); } views::Window* BubbleWindow::Create( gfx::NativeWindow parent, const gfx::Rect& bounds, Style style, views::WindowDelegate* window_delegate) { BubbleWindow* window = new BubbleWindow(window_delegate); window->GetNonClientView()->SetFrameView(new BubbleFrameView(window, style)); window->Init(parent, bounds); chromeos::WmIpc::instance()->SetWindowType( window->GetNativeView(), chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE, NULL); return window; } } // namespace chromeos <commit_msg>[ChromeOS] Remove CHROME_INFO_BUBBLE type from BubbleWindow.<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/chromeos/frame/bubble_window.h" #include <gtk/gtk.h> #include "chrome/browser/chromeos/frame/bubble_frame_view.h" #include "chrome/browser/chromeos/wm_ipc.h" #include "cros/chromeos_wm_ipc_enums.h" #include "gfx/skia_utils_gtk.h" #include "views/window/non_client_view.h" namespace chromeos { // static const SkColor BubbleWindow::kBackgroundColor = SK_ColorWHITE; BubbleWindow::BubbleWindow(views::WindowDelegate* window_delegate) : views::WindowGtk(window_delegate) { MakeTransparent(); } void BubbleWindow::Init(GtkWindow* parent, const gfx::Rect& bounds) { views::WindowGtk::Init(parent, bounds); GdkColor background_color = gfx::SkColorToGdkColor(kBackgroundColor); gtk_widget_modify_bg(GetNativeView(), GTK_STATE_NORMAL, &background_color); } views::Window* BubbleWindow::Create( gfx::NativeWindow parent, const gfx::Rect& bounds, Style style, views::WindowDelegate* window_delegate) { BubbleWindow* window = new BubbleWindow(window_delegate); window->GetNonClientView()->SetFrameView(new BubbleFrameView(window, style)); window->Init(parent, bounds); return window; } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/desktop_notification_handler.h" #include "chrome/browser/notifications/desktop_notification_service.h" #include "chrome/browser/notifications/desktop_notification_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "content/browser/renderer_host/render_process_host.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/renderer_host/render_view_host_delegate.h" #include "content/common/desktop_notification_messages.h" DesktopNotificationHandler::DesktopNotificationHandler( RenderViewHost* render_view_host) : RenderViewHostObserver(render_view_host) { } DesktopNotificationHandler::~DesktopNotificationHandler() { } bool DesktopNotificationHandler::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(DesktopNotificationHandler, message) IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Show, OnShow) IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Cancel, OnCancel) IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_RequestPermission, OnRequestPermission) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void DesktopNotificationHandler::OnShow( const DesktopNotificationHostMsg_Show_Params& params) { // Disallow HTML notifications from unwanted schemes. javascript: // in particular allows unwanted cross-domain access. GURL url = params.contents_url; if (!url.SchemeIs(chrome::kHttpScheme) && !url.SchemeIs(chrome::kHttpsScheme) && !url.SchemeIs(chrome::kExtensionScheme) && !url.SchemeIs(chrome::kDataScheme)) { return; } RenderProcessHost* process = render_view_host()->process(); DesktopNotificationService* service = DesktopNotificationServiceFactory::GetForProfile(process->profile()); service->ShowDesktopNotification( params, process->id(), routing_id(), DesktopNotificationService::PageNotification); } void DesktopNotificationHandler::OnCancel(int notification_id) { RenderProcessHost* process = render_view_host()->process(); DesktopNotificationService* service = DesktopNotificationServiceFactory::GetForProfile(process->profile()); service->CancelDesktopNotification( process->id(), routing_id(), notification_id); } void DesktopNotificationHandler::OnRequestPermission( const GURL& source_origin, int callback_context) { if (render_view_host()->delegate()->RequestDesktopNotificationPermission( source_origin, callback_context)) { return; } RenderProcessHost* process = render_view_host()->process(); DesktopNotificationService* service = DesktopNotificationServiceFactory::GetForProfile(process->profile()); service->RequestPermission( source_origin, process->id(), routing_id(), callback_context, NULL); } <commit_msg>Fix bug notifications bug<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/desktop_notification_handler.h" #include "chrome/browser/notifications/desktop_notification_service.h" #include "chrome/browser/notifications/desktop_notification_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "content/browser/renderer_host/render_process_host.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/renderer_host/render_view_host_delegate.h" #include "content/common/desktop_notification_messages.h" DesktopNotificationHandler::DesktopNotificationHandler( RenderViewHost* render_view_host) : RenderViewHostObserver(render_view_host) { } DesktopNotificationHandler::~DesktopNotificationHandler() { } bool DesktopNotificationHandler::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(DesktopNotificationHandler, message) IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Show, OnShow) IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Cancel, OnCancel) IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_RequestPermission, OnRequestPermission) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void DesktopNotificationHandler::OnShow( const DesktopNotificationHostMsg_Show_Params& params) { // Disallow HTML notifications from unwanted schemes. javascript: // in particular allows unwanted cross-domain access. GURL url = params.contents_url; if (params.is_html && !url.SchemeIs(chrome::kHttpScheme) && !url.SchemeIs(chrome::kHttpsScheme) && !url.SchemeIs(chrome::kExtensionScheme) && !url.SchemeIs(chrome::kDataScheme)) { return; } RenderProcessHost* process = render_view_host()->process(); DesktopNotificationService* service = DesktopNotificationServiceFactory::GetForProfile(process->profile()); service->ShowDesktopNotification( params, process->id(), routing_id(), DesktopNotificationService::PageNotification); } void DesktopNotificationHandler::OnCancel(int notification_id) { RenderProcessHost* process = render_view_host()->process(); DesktopNotificationService* service = DesktopNotificationServiceFactory::GetForProfile(process->profile()); service->CancelDesktopNotification( process->id(), routing_id(), notification_id); } void DesktopNotificationHandler::OnRequestPermission( const GURL& source_origin, int callback_context) { if (render_view_host()->delegate()->RequestDesktopNotificationPermission( source_origin, callback_context)) { return; } RenderProcessHost* process = render_view_host()->process(); DesktopNotificationService* service = DesktopNotificationServiceFactory::GetForProfile(process->profile()); service->RequestPermission( source_origin, process->id(), routing_id(), callback_context, NULL); } <|endoftext|>
<commit_before>#include "chainerx/dynamic_lib.h" #include <string> #include "chainerx/platform.h" namespace chainerx { void* DlOpen(const std::string& filename, int flags) { return platform::DlOpen(filename, flags); } void DlClose(void* handle) { platform::DlClose(handle); } void* DlSym(void* handle, const char* name) { platform::DlSym(handle, name); } } // namespace chainerx <commit_msg>fixed a compiling error<commit_after>#include "chainerx/dynamic_lib.h" #include <string> #include "chainerx/platform.h" namespace chainerx { void* DlOpen(const std::string& filename, int flags) { return platform::DlOpen(filename, flags); } void DlClose(void* handle) { platform::DlClose(handle); } void* DlSym(void* handle, const char* name) { return platform::DlSym(handle, name); } } // namespace chainerx <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/signin_manager.h" #include "chrome/browser/net/gaia/token_service.h" #include "chrome/browser/net/gaia/token_service_unittest.h" #include "chrome/browser/password_manager/encryptor.h" #include "chrome/browser/sync/util/oauth.h" #include "chrome/browser/webdata/web_data_service.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/net/gaia/gaia_urls.h" #include "chrome/test/base/signaling_task.h" #include "chrome/test/base/testing_profile.h" #include "content/test/test_url_fetcher_factory.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_status.h" #include "testing/gtest/include/gtest/gtest.h" class SigninManagerTest : public TokenServiceTestHarness { public: virtual void SetUp() OVERRIDE { TokenServiceTestHarness::SetUp(); manager_.reset(new SigninManager()); google_login_success_.ListenFor( chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL, Source<Profile>(profile_.get())); google_login_failure_.ListenFor(chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED, Source<Profile>(profile_.get())); originally_using_oauth_ = browser_sync::IsUsingOAuth(); } virtual void TearDown() OVERRIDE { browser_sync::SetIsUsingOAuthForTest(originally_using_oauth_); } void SimulateValidResponseClientLogin() { DCHECK(!browser_sync::IsUsingOAuth()); // Simulate the correct ClientLogin response. TestURLFetcher* fetcher = factory_.GetFetcherByID(0); DCHECK(fetcher); DCHECK(fetcher->delegate()); fetcher->delegate()->OnURLFetchComplete( fetcher, GURL(GaiaUrls::GetInstance()->client_login_url()), net::URLRequestStatus(), 200, net::ResponseCookies(), "SID=sid\nLSID=lsid\nAuth=auth"); // Then simulate the correct GetUserInfo response for the canonical email. // A new URL fetcher is used for each call. fetcher = factory_.GetFetcherByID(0); DCHECK(fetcher); DCHECK(fetcher->delegate()); fetcher->delegate()->OnURLFetchComplete( fetcher, GURL(GaiaUrls::GetInstance()->get_user_info_url()), net::URLRequestStatus(), 200, net::ResponseCookies(), "email=user@gmail.com"); } void SimulateSigninStartOAuth() { DCHECK(browser_sync::IsUsingOAuth()); // Simulate a valid OAuth-based signin manager_->OnGetOAuthTokenSuccess("oauth_token-Ev1Vu1hv"); manager_->OnOAuthGetAccessTokenSuccess("oauth1_access_token-qOAmlrSM", "secret-NKKn1DuR"); manager_->OnOAuthWrapBridgeSuccess(browser_sync::SyncServiceName(), "oauth2_wrap_access_token-R0Z3nRtw", "3600"); } void SimulateOAuthUserInfoSuccess() { manager_->OnUserInfoSuccess("user-xZIuqTKu@gmail.com"); } void SimulateValidSigninOAuth() { SimulateSigninStartOAuth(); SimulateOAuthUserInfoSuccess(); } TestURLFetcherFactory factory_; scoped_ptr<SigninManager> manager_; TestNotificationTracker google_login_success_; TestNotificationTracker google_login_failure_; bool originally_using_oauth_; }; // NOTE: ClientLogin's "StartSignin" is called after collecting credentials // from the user. See also SigninManagerTest::SignInOAuth. TEST_F(SigninManagerTest, SignInClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); manager_->StartSignIn("username", "password", "", ""); EXPECT_FALSE(manager_->GetUsername().empty()); SimulateValidResponseClientLogin(); // Should go into token service and stop. EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); // Should persist across resets. manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_EQ("user@gmail.com", manager_->GetUsername()); } // NOTE: OAuth's "StartOAuthSignIn" is called before collecting credentials // from the user. See also SigninManagerTest::SignInClientLogin. TEST_F(SigninManagerTest, SignInOAuth) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); SimulateValidSigninOAuth(); EXPECT_FALSE(manager_->GetUsername().empty()); // Should go into token service and stop. EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); // Should persist across resets. manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_EQ("user-xZIuqTKu@gmail.com", manager_->GetUsername()); } TEST_F(SigninManagerTest, SignOutClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); SimulateValidResponseClientLogin(); manager_->OnClientLoginSuccess(credentials_); EXPECT_EQ("user@gmail.com", manager_->GetUsername()); manager_->SignOut(); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted anymore manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutOAuth) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); SimulateValidSigninOAuth(); EXPECT_FALSE(manager_->GetUsername().empty()); EXPECT_EQ("user-xZIuqTKu@gmail.com", manager_->GetUsername()); manager_->SignOut(); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted anymore manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignInFailureClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error(GoogleServiceAuthError::REQUEST_CANCELED); manager_->OnClientLoginFailure(error); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, ProvideSecondFactorSuccess) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error(GoogleServiceAuthError::TWO_FACTOR); manager_->OnClientLoginFailure(error); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("access"); SimulateValidResponseClientLogin(); EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); } TEST_F(SigninManagerTest, ProvideSecondFactorFailure) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error1(GoogleServiceAuthError::TWO_FACTOR); manager_->OnClientLoginFailure(error1); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("badaccess"); GoogleServiceAuthError error2( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); manager_->OnClientLoginFailure(error2); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(2U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("badaccess"); GoogleServiceAuthError error3(GoogleServiceAuthError::CONNECTION_FAILED); manager_->OnClientLoginFailure(error3); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(3U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutMidConnect) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); manager_->SignOut(); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutOnUserInfoSucessRaceTest) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); SimulateSigninStartOAuth(); manager_->SignOut(); SimulateOAuthUserInfoSuccess(); EXPECT_TRUE(manager_->GetUsername().empty()); } <commit_msg>Sync/Valgrind: Fix a leak in SigninManagerTest.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/signin_manager.h" #include "chrome/browser/net/gaia/token_service.h" #include "chrome/browser/net/gaia/token_service_unittest.h" #include "chrome/browser/password_manager/encryptor.h" #include "chrome/browser/sync/util/oauth.h" #include "chrome/browser/webdata/web_data_service.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/net/gaia/gaia_urls.h" #include "chrome/test/base/signaling_task.h" #include "chrome/test/base/testing_profile.h" #include "content/test/test_url_fetcher_factory.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_status.h" #include "testing/gtest/include/gtest/gtest.h" class SigninManagerTest : public TokenServiceTestHarness { public: virtual void SetUp() OVERRIDE { TokenServiceTestHarness::SetUp(); manager_.reset(new SigninManager()); google_login_success_.ListenFor( chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL, Source<Profile>(profile_.get())); google_login_failure_.ListenFor(chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED, Source<Profile>(profile_.get())); originally_using_oauth_ = browser_sync::IsUsingOAuth(); } virtual void TearDown() OVERRIDE { TokenServiceTestHarness::TearDown(); browser_sync::SetIsUsingOAuthForTest(originally_using_oauth_); } void SimulateValidResponseClientLogin() { DCHECK(!browser_sync::IsUsingOAuth()); // Simulate the correct ClientLogin response. TestURLFetcher* fetcher = factory_.GetFetcherByID(0); DCHECK(fetcher); DCHECK(fetcher->delegate()); fetcher->delegate()->OnURLFetchComplete( fetcher, GURL(GaiaUrls::GetInstance()->client_login_url()), net::URLRequestStatus(), 200, net::ResponseCookies(), "SID=sid\nLSID=lsid\nAuth=auth"); // Then simulate the correct GetUserInfo response for the canonical email. // A new URL fetcher is used for each call. fetcher = factory_.GetFetcherByID(0); DCHECK(fetcher); DCHECK(fetcher->delegate()); fetcher->delegate()->OnURLFetchComplete( fetcher, GURL(GaiaUrls::GetInstance()->get_user_info_url()), net::URLRequestStatus(), 200, net::ResponseCookies(), "email=user@gmail.com"); } void SimulateSigninStartOAuth() { DCHECK(browser_sync::IsUsingOAuth()); // Simulate a valid OAuth-based signin manager_->OnGetOAuthTokenSuccess("oauth_token-Ev1Vu1hv"); manager_->OnOAuthGetAccessTokenSuccess("oauth1_access_token-qOAmlrSM", "secret-NKKn1DuR"); manager_->OnOAuthWrapBridgeSuccess(browser_sync::SyncServiceName(), "oauth2_wrap_access_token-R0Z3nRtw", "3600"); } void SimulateOAuthUserInfoSuccess() { manager_->OnUserInfoSuccess("user-xZIuqTKu@gmail.com"); } void SimulateValidSigninOAuth() { SimulateSigninStartOAuth(); SimulateOAuthUserInfoSuccess(); } TestURLFetcherFactory factory_; scoped_ptr<SigninManager> manager_; TestNotificationTracker google_login_success_; TestNotificationTracker google_login_failure_; bool originally_using_oauth_; }; // NOTE: ClientLogin's "StartSignin" is called after collecting credentials // from the user. See also SigninManagerTest::SignInOAuth. TEST_F(SigninManagerTest, SignInClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); manager_->StartSignIn("username", "password", "", ""); EXPECT_FALSE(manager_->GetUsername().empty()); SimulateValidResponseClientLogin(); // Should go into token service and stop. EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); // Should persist across resets. manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_EQ("user@gmail.com", manager_->GetUsername()); } // NOTE: OAuth's "StartOAuthSignIn" is called before collecting credentials // from the user. See also SigninManagerTest::SignInClientLogin. TEST_F(SigninManagerTest, SignInOAuth) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); SimulateValidSigninOAuth(); EXPECT_FALSE(manager_->GetUsername().empty()); // Should go into token service and stop. EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); // Should persist across resets. manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_EQ("user-xZIuqTKu@gmail.com", manager_->GetUsername()); } TEST_F(SigninManagerTest, SignOutClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); SimulateValidResponseClientLogin(); manager_->OnClientLoginSuccess(credentials_); EXPECT_EQ("user@gmail.com", manager_->GetUsername()); manager_->SignOut(); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted anymore manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutOAuth) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); SimulateValidSigninOAuth(); EXPECT_FALSE(manager_->GetUsername().empty()); EXPECT_EQ("user-xZIuqTKu@gmail.com", manager_->GetUsername()); manager_->SignOut(); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted anymore manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignInFailureClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error(GoogleServiceAuthError::REQUEST_CANCELED); manager_->OnClientLoginFailure(error); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, ProvideSecondFactorSuccess) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error(GoogleServiceAuthError::TWO_FACTOR); manager_->OnClientLoginFailure(error); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("access"); SimulateValidResponseClientLogin(); EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); } TEST_F(SigninManagerTest, ProvideSecondFactorFailure) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error1(GoogleServiceAuthError::TWO_FACTOR); manager_->OnClientLoginFailure(error1); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("badaccess"); GoogleServiceAuthError error2( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); manager_->OnClientLoginFailure(error2); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(2U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("badaccess"); GoogleServiceAuthError error3(GoogleServiceAuthError::CONNECTION_FAILED); manager_->OnClientLoginFailure(error3); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(3U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutMidConnect) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); manager_->SignOut(); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutOnUserInfoSucessRaceTest) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); SimulateSigninStartOAuth(); manager_->SignOut(); SimulateOAuthUserInfoSuccess(); EXPECT_TRUE(manager_->GetUsername().empty()); } <|endoftext|>
<commit_before>#include <stddef.h> #include <stdio.h> #include <stdlib.h> extern "C" { char* __cxa_demangle(const char* mangled_name, char* buf, size_t* n, int* status); typedef void* (*malloc_func_t)(size_t); typedef void (*free_func_t)(void*); char* __unDName(char* buffer, const char* mangled, int buflen, malloc_func_t memget, free_func_t memfree, unsigned short int flags); } int main(int argc, char* argv[]) { for (int i = 1; i < argc; ++i) { int status; char* itanum_demangled = __cxa_demangle(argv[i], NULL, NULL, &status); if (status == 0) printf("itanum: %s\n", itanum_demangled); free(itanum_demangled); char* ms_demangled = __unDName(NULL, argv[i], 0, &malloc, &free, 0); if (ms_demangled) printf("ms: %s\n", ms_demangled); free(ms_demangled); } } <commit_msg>spelling<commit_after>#include <stddef.h> #include <stdio.h> #include <stdlib.h> extern "C" { char* __cxa_demangle(const char* mangled_name, char* buf, size_t* n, int* status); typedef void* (*malloc_func_t)(size_t); typedef void (*free_func_t)(void*); char* __unDName(char* buffer, const char* mangled, int buflen, malloc_func_t memget, free_func_t memfree, unsigned short int flags); } int main(int argc, char* argv[]) { for (int i = 1; i < argc; ++i) { int status; char* itanium_demangled = __cxa_demangle(argv[i], NULL, NULL, &status); if (status == 0) printf("%s\n", itanium_demangled); free(itanium_demangled); char* ms_demangled = __unDName(NULL, argv[i], 0, &malloc, &free, 0); if (ms_demangled) printf("%s\n", ms_demangled); free(ms_demangled); } } <|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 <pwd.h> #include <string.h> #include "base/port.h" #include "chrome/browser/sync/util/path_helpers.h" #include "strings/strutil.h" #if ((!defined(OS_LINUX)) && (!defined(OS_MACOSX))) #error Compile this file on Mac OS X or Linux only. #endif PathString ExpandTilde(const PathString& path) { if (path.empty()) return path; if ('~' != path[0]) return path; PathString ret; // TODO(sync): Consider using getpwuid_r. ret.insert(0, getpwuid(getuid())->pw_dir); ret.append(++path.begin(), path.end()); return ret; } namespace { // TODO(sync): We really should use char[]. string cache_dir_; } void set_cache_dir(string cache_dir) { CHECK(cache_dir_.empty()); cache_dir_ = cache_dir; } string get_cache_dir() { CHECK(!cache_dir_.empty()); return cache_dir_; } // On Posix, PathStrings are UTF-8, not UTF-16 as they are on Windows. // Thus, this function is different from the Windows version. PathString TruncatePathString(const PathString& original, int length) { if (original.size() <= length) return original; if (length <= 0) return original; PathString ret(original.begin(), original.begin() + length); COMPILE_ASSERT(sizeof(PathChar) == sizeof(uint8), PathStringNotUTF8); PathString::reverse_iterator last_char = ret.rbegin(); // Values taken from // http://en.wikipedia.org/w/index.php?title=UTF-8&oldid=252875566 if (0 == (*last_char & 0x80)) return ret; for (; last_char != ret.rend(); ++last_char) { if (0 == (*last_char & 0x80)) { // got malformed UTF-8; bail return ret; } if (0 == (*last_char & 0x40)) { // got another trailing byte continue; } break; } if (ret.rend() == last_char) { // We hit the beginning of the string. bail. return ret; } int last_codepoint_len = last_char - ret.rbegin() + 1; if (((0xC0 == (*last_char & 0xE0)) && (2 == last_codepoint_len)) || ((0xE0 == (*last_char & 0xF0)) && (3 == last_codepoint_len)) || ((0xF0 == (*last_char & 0xF8)) && (4 == last_codepoint_len))) { // Valid utf-8. return ret; } // Invalid utf-8. chop off last "codepoint" and return. ret.resize(ret.size() - last_codepoint_len); return ret; } // Convert /s to :s . PathString MakePathComponentOSLegal(const PathString& component) { if (PathString::npos == component.find("/")) return PSTR(""); PathString new_name; new_name.reserve(component.size()); StringReplace(component, "/", ":", true, &new_name); return new_name; } <commit_msg>Fix one more checkdeps path. Left this out of the last change.<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 <pwd.h> #include <string.h> #include "chrome/browser/sync/util/path_helpers.h" #if ((!defined(OS_LINUX)) && (!defined(OS_MACOSX))) #error Compile this file on Mac OS X or Linux only. #endif PathString ExpandTilde(const PathString& path) { if (path.empty()) return path; if ('~' != path[0]) return path; PathString ret; // TODO(sync): Consider using getpwuid_r. ret.insert(0, getpwuid(getuid())->pw_dir); ret.append(++path.begin(), path.end()); return ret; } namespace { // TODO(sync): We really should use char[]. string cache_dir_; } void set_cache_dir(string cache_dir) { CHECK(cache_dir_.empty()); cache_dir_ = cache_dir; } string get_cache_dir() { CHECK(!cache_dir_.empty()); return cache_dir_; } // On Posix, PathStrings are UTF-8, not UTF-16 as they are on Windows. // Thus, this function is different from the Windows version. PathString TruncatePathString(const PathString& original, int length) { if (original.size() <= length) return original; if (length <= 0) return original; PathString ret(original.begin(), original.begin() + length); COMPILE_ASSERT(sizeof(PathChar) == sizeof(uint8), PathStringNotUTF8); PathString::reverse_iterator last_char = ret.rbegin(); // Values taken from // http://en.wikipedia.org/w/index.php?title=UTF-8&oldid=252875566 if (0 == (*last_char & 0x80)) return ret; for (; last_char != ret.rend(); ++last_char) { if (0 == (*last_char & 0x80)) { // got malformed UTF-8; bail return ret; } if (0 == (*last_char & 0x40)) { // got another trailing byte continue; } break; } if (ret.rend() == last_char) { // We hit the beginning of the string. bail. return ret; } int last_codepoint_len = last_char - ret.rbegin() + 1; if (((0xC0 == (*last_char & 0xE0)) && (2 == last_codepoint_len)) || ((0xE0 == (*last_char & 0xF0)) && (3 == last_codepoint_len)) || ((0xF0 == (*last_char & 0xF8)) && (4 == last_codepoint_len))) { // Valid utf-8. return ret; } // Invalid utf-8. chop off last "codepoint" and return. ret.resize(ret.size() - last_codepoint_len); return ret; } // Convert /s to :s . PathString MakePathComponentOSLegal(const PathString& component) { if (PathString::npos == component.find("/")) return PSTR(""); PathString new_name; new_name.reserve(component.size()); StringReplace(component, "/", ":", true, &new_name); return new_name; } <|endoftext|>
<commit_before>#include "catch.hpp" #include <mapnik/image_reader.hpp> #include <mapnik/image_util.hpp> #include <mapnik/util/file_io.hpp> #include <mapnik/tiff_io.hpp> #include "../../src/tiff_reader.cpp" std::unique_ptr<mapnik::image_reader> open(std::string const& filename) { return std::unique_ptr<mapnik::image_reader>(mapnik::get_image_reader(filename,"tiff")); } #define TIFF_ASSERT(filename) \ mapnik::tiff_reader<boost::iostreams::file_source> tiff_reader(filename); \ REQUIRE( tiff_reader.width() == 256 ); \ REQUIRE( tiff_reader.height() == 256 ); \ auto reader = open(filename); \ REQUIRE( reader->width() == 256 ); \ REQUIRE( reader->height() == 256 ); \ #define TIFF_ASSERT_ALPHA \ REQUIRE( tiff_reader.has_alpha() == true ); \ REQUIRE( tiff_reader.premultiplied_alpha() == false ); \ REQUIRE( reader->has_alpha() == true ); \ REQUIRE( reader->premultiplied_alpha() == false ); \ #define TIFF_ASSERT_NO_ALPHA \ REQUIRE( tiff_reader.has_alpha() == false ); \ REQUIRE( tiff_reader.premultiplied_alpha() == false ); \ REQUIRE( reader->has_alpha() == false ); \ REQUIRE( reader->premultiplied_alpha() == false ); \ TEST_CASE("tiff io") { SECTION("rgba8 striped") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_rgba8_striped.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == false ); REQUIRE( tiff_reader.tile_width() == 0 ); REQUIRE( tiff_reader.tile_height() == 0 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_RGB ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_rgba8>() == true ); TIFF_ASSERT_ALPHA } SECTION("rgba8 tiled") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_rgba8_tiled.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == true ); REQUIRE( tiff_reader.tile_width() == 256 ); REQUIRE( tiff_reader.tile_height() == 256 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_RGB ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_rgba8>() == true ); TIFF_ASSERT_ALPHA } SECTION("rgb8 striped") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_rgb8_striped.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == false ); REQUIRE( tiff_reader.tile_width() == 0 ); REQUIRE( tiff_reader.tile_height() == 0 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_RGB ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_rgba8>() == true ); TIFF_ASSERT_NO_ALPHA } SECTION("rgb8 tiled") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_rgb8_tiled.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == true ); REQUIRE( tiff_reader.tile_width() == 256 ); REQUIRE( tiff_reader.tile_height() == 256 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_RGB ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_rgba8>() == true ); TIFF_ASSERT_NO_ALPHA } SECTION("gray8 striped") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray8_striped.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == false ); REQUIRE( tiff_reader.tile_width() == 0 ); REQUIRE( tiff_reader.tile_height() == 0 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray8>() == true ); TIFF_ASSERT_NO_ALPHA } SECTION("gray8 tiled") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray8_tiled.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == true ); REQUIRE( tiff_reader.tile_width() == 256 ); REQUIRE( tiff_reader.tile_height() == 256 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray8>() == true ); TIFF_ASSERT_NO_ALPHA } SECTION("gray16 striped") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray16_striped.tif") REQUIRE( tiff_reader.bits_per_sample() == 16 ); REQUIRE( tiff_reader.is_tiled() == false ); REQUIRE( tiff_reader.tile_width() == 0 ); REQUIRE( tiff_reader.tile_height() == 0 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray16>() == true ); TIFF_ASSERT_NO_ALPHA } SECTION("gray16 tiled") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray16_tiled.tif") REQUIRE( tiff_reader.bits_per_sample() == 16 ); REQUIRE( tiff_reader.is_tiled() == true ); REQUIRE( tiff_reader.tile_width() == 256 ); REQUIRE( tiff_reader.tile_height() == 256 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray16>() == true ); TIFF_ASSERT_NO_ALPHA } SECTION("gray32f striped") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray32f_striped.tif") REQUIRE( tiff_reader.bits_per_sample() == 32 ); REQUIRE( tiff_reader.is_tiled() == false ); REQUIRE( tiff_reader.tile_width() == 0 ); REQUIRE( tiff_reader.tile_height() == 0 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray32f>() == true ); TIFF_ASSERT_NO_ALPHA } SECTION("gray32f tiled") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray32f_tiled.tif") REQUIRE( tiff_reader.bits_per_sample() == 32 ); REQUIRE( tiff_reader.is_tiled() == true ); REQUIRE( tiff_reader.tile_width() == 256 ); REQUIRE( tiff_reader.tile_height() == 256 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray32f>() == true ); TIFF_ASSERT_NO_ALPHA } }<commit_msg>test reading<commit_after>#include "catch.hpp" #include <mapnik/image_reader.hpp> #include <mapnik/image_util.hpp> #include <mapnik/util/file_io.hpp> #include <mapnik/tiff_io.hpp> #include "../../src/tiff_reader.cpp" std::unique_ptr<mapnik::image_reader> open(std::string const& filename) { return std::unique_ptr<mapnik::image_reader>(mapnik::get_image_reader(filename,"tiff")); } #define TIFF_ASSERT(filename) \ mapnik::tiff_reader<boost::iostreams::file_source> tiff_reader(filename); \ REQUIRE( tiff_reader.width() == 256 ); \ REQUIRE( tiff_reader.height() == 256 ); \ auto reader = open(filename); \ REQUIRE( reader->width() == 256 ); \ REQUIRE( reader->height() == 256 ); \ #define TIFF_ASSERT_ALPHA \ REQUIRE( tiff_reader.has_alpha() == true ); \ REQUIRE( tiff_reader.premultiplied_alpha() == false ); \ REQUIRE( reader->has_alpha() == true ); \ REQUIRE( reader->premultiplied_alpha() == false ); \ #define TIFF_ASSERT_NO_ALPHA \ REQUIRE( tiff_reader.has_alpha() == false ); \ REQUIRE( tiff_reader.premultiplied_alpha() == false ); \ REQUIRE( reader->has_alpha() == false ); \ REQUIRE( reader->premultiplied_alpha() == false ); \ #define TIFF_ASSERT_SIZE( data,reader ) \ REQUIRE( data.width() == reader->width() ); \ REQUIRE( data.height() == reader->height() ); \ #define TIFF_READ_ONE_PIXEL \ mapnik::image_data_any subimage = reader->read(1, 1, 1, 1); \ REQUIRE( subimage.width() == 1 ); \ REQUIRE( subimage.height() == 1 ); \ TEST_CASE("tiff io") { SECTION("rgba8 striped") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_rgba8_striped.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == false ); REQUIRE( tiff_reader.tile_width() == 0 ); REQUIRE( tiff_reader.tile_height() == 0 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_RGB ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_rgba8>() == true ); TIFF_ASSERT_SIZE( data,reader ); TIFF_ASSERT_ALPHA TIFF_READ_ONE_PIXEL } SECTION("rgba8 tiled") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_rgba8_tiled.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == true ); REQUIRE( tiff_reader.tile_width() == 256 ); REQUIRE( tiff_reader.tile_height() == 256 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_RGB ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_rgba8>() == true ); TIFF_ASSERT_SIZE( data,reader ); TIFF_ASSERT_ALPHA TIFF_READ_ONE_PIXEL } SECTION("rgb8 striped") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_rgb8_striped.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == false ); REQUIRE( tiff_reader.tile_width() == 0 ); REQUIRE( tiff_reader.tile_height() == 0 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_RGB ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_rgba8>() == true ); TIFF_ASSERT_SIZE( data,reader ); TIFF_ASSERT_NO_ALPHA TIFF_READ_ONE_PIXEL } SECTION("rgb8 tiled") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_rgb8_tiled.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == true ); REQUIRE( tiff_reader.tile_width() == 256 ); REQUIRE( tiff_reader.tile_height() == 256 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_RGB ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_rgba8>() == true ); TIFF_ASSERT_SIZE( data,reader ); TIFF_ASSERT_NO_ALPHA TIFF_READ_ONE_PIXEL } SECTION("gray8 striped") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray8_striped.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == false ); REQUIRE( tiff_reader.tile_width() == 0 ); REQUIRE( tiff_reader.tile_height() == 0 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray8>() == true ); TIFF_ASSERT_SIZE( data,reader ); TIFF_ASSERT_NO_ALPHA TIFF_READ_ONE_PIXEL } SECTION("gray8 tiled") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray8_tiled.tif") REQUIRE( tiff_reader.bits_per_sample() == 8 ); REQUIRE( tiff_reader.is_tiled() == true ); REQUIRE( tiff_reader.tile_width() == 256 ); REQUIRE( tiff_reader.tile_height() == 256 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray8>() == true ); TIFF_ASSERT_SIZE( data,reader ); TIFF_ASSERT_NO_ALPHA TIFF_READ_ONE_PIXEL } SECTION("gray16 striped") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray16_striped.tif") REQUIRE( tiff_reader.bits_per_sample() == 16 ); REQUIRE( tiff_reader.is_tiled() == false ); REQUIRE( tiff_reader.tile_width() == 0 ); REQUIRE( tiff_reader.tile_height() == 0 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray16>() == true ); TIFF_ASSERT_SIZE( data,reader ); TIFF_ASSERT_NO_ALPHA TIFF_READ_ONE_PIXEL } SECTION("gray16 tiled") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray16_tiled.tif") REQUIRE( tiff_reader.bits_per_sample() == 16 ); REQUIRE( tiff_reader.is_tiled() == true ); REQUIRE( tiff_reader.tile_width() == 256 ); REQUIRE( tiff_reader.tile_height() == 256 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray16>() == true ); TIFF_ASSERT_SIZE( data,reader ); TIFF_ASSERT_NO_ALPHA TIFF_READ_ONE_PIXEL } SECTION("gray32f striped") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray32f_striped.tif") REQUIRE( tiff_reader.bits_per_sample() == 32 ); REQUIRE( tiff_reader.is_tiled() == false ); REQUIRE( tiff_reader.tile_width() == 0 ); REQUIRE( tiff_reader.tile_height() == 0 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray32f>() == true ); TIFF_ASSERT_SIZE( data,reader ); TIFF_ASSERT_NO_ALPHA TIFF_READ_ONE_PIXEL } SECTION("gray32f tiled") { TIFF_ASSERT("./tests/data/tiff/ndvi_256x256_gray32f_tiled.tif") REQUIRE( tiff_reader.bits_per_sample() == 32 ); REQUIRE( tiff_reader.is_tiled() == true ); REQUIRE( tiff_reader.tile_width() == 256 ); REQUIRE( tiff_reader.tile_height() == 256 ); REQUIRE( tiff_reader.photometric() == PHOTOMETRIC_MINISBLACK ); mapnik::image_data_any data = reader->read(0, 0, reader->width(), reader->height()); REQUIRE( data.is<mapnik::image_data_gray32f>() == true ); TIFF_ASSERT_SIZE( data,reader ); TIFF_ASSERT_NO_ALPHA TIFF_READ_ONE_PIXEL } }<|endoftext|>
<commit_before>/***************************************************************************** * Media.hpp: Media API ***************************************************************************** * Copyright © 2015 libvlcpp authors & VideoLAN * * Authors: Alexey Sokolov <alexey+vlc@asokolov.org> * Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef LIBVLC_CXX_MEDIA_H #define LIBVLC_CXX_MEDIA_H #include "common.hpp" #include <vector> #include <stdexcept> namespace VLC { class MediaPlayer; class MediaEventManager; class Instance; class MediaList; class Media : public Internal<libvlc_media_t> { public: enum class FromType { /** * Create a media for a certain file path. */ FromPath, /** * Create a media with a certain given media resource location, * for instance a valid URL. * * \note To refer to a local file with this function, * the file://... URI syntax <b>must</b> be used (see IETF RFC3986). * We recommend using FromPath instead when dealing with * local files. */ FromLocation, /** * Create a media as an empty node with a given name. */ AsNode, }; // To be able to write Media::FromLocation #if !defined(_MSC_VER) || _MSC_VER >= 1900 constexpr static FromType FromPath = FromType::FromPath; constexpr static FromType FromLocation = FromType::FromLocation; constexpr static FromType AsNode = FromType::AsNode; #else static const FromType FromPath = FromType::FromPath; static const FromType FromLocation = FromType::FromLocation; static const FromType AsNode = FromType::AsNode; #endif /** * @brief Media Constructs a libvlc Media instance * @param instance A libvlc instance * @param mrl A path, location, or node name, depending on the 3rd parameter * @param type The type of the 2nd argument. \sa{FromType} */ Media(Instance& instance, const std::string& mrl, FromType type) : Internal{ libvlc_media_release } { InternalPtr ptr = nullptr; switch (type) { case FromLocation: ptr = libvlc_media_new_location( getInternalPtr<libvlc_instance_t>( instance ), mrl.c_str() ); break; case FromPath: ptr = libvlc_media_new_path( getInternalPtr<libvlc_instance_t>( instance ), mrl.c_str() ); break; case AsNode: ptr = libvlc_media_new_as_node( getInternalPtr<libvlc_instance_t>( instance ), mrl.c_str() ); break; default: break; } if ( ptr == nullptr ) throw std::runtime_error("Failed to construct a media"); m_obj.reset( ptr, libvlc_media_release ); } /** * Create a media for an already open file descriptor. * The file descriptor shall be open for reading (or reading and writing). * * Regular file descriptors, pipe read descriptors and character device * descriptors (including TTYs) are supported on all platforms. * Block device descriptors are supported where available. * Directory descriptors are supported on systems that provide fdopendir(). * Sockets are supported on all platforms where they are file descriptors, * i.e. all except Windows. * * \note This library will <b>not</b> automatically close the file descriptor * under any circumstance. Nevertheless, a file descriptor can usually only be * rendered once in a media player. To render it a second time, the file * descriptor should probably be rewound to the beginning with lseek(). * * \param p_instance the instance * \param fd open file descriptor * \return the newly created media or NULL on error */ Media(Instance& instance, int fd) : Internal { libvlc_media_new_fd( getInternalPtr<libvlc_instance_t>( instance ), fd ), libvlc_media_release } { } /** * Get media instance from this media list instance. This action will increase * the refcount on the media instance. * The libvlc_media_list_lock should NOT be held upon entering this function. * * \param p_ml a media list instance * \return media instance */ Media(MediaList& list) : Internal{ libvlc_media_list_media( getInternalPtr<libvlc_media_list_t>( list ) ), libvlc_media_release } { } explicit Media( Internal::InternalPtr ptr, bool incrementRefCount) : Internal{ ptr, libvlc_media_release } { if (incrementRefCount) retain(); } /** * Create an empty VLC Media instance. * * Calling any method on such an instance is undefined. */ Media() = default; /** * Check if 2 Media objects contain the same libvlc_media_t. * \param another another Media * \return true if they contain the same libvlc_media_t */ bool operator==(const Media& another) const { return m_obj == another.m_obj; } /** * Add an option to the media. * * This option will be used to determine how the media_player will read * the media. This allows to use VLC's advanced reading/streaming options * on a per-media basis. * * \note The options are listed in 'vlc long-help' from the command line, * e.g. "-sout-all". Keep in mind that available options and their * semantics vary across LibVLC versions and builds. * * \warning Not all options affects libvlc_media_t objects: Specifically, * due to architectural issues most audio and video options, such as text * renderer options, have no effects on an individual media. These * options must be set through Instance::Instance() instead. * * \param psz_options the options (as a string) */ void addOption(const std::string& psz_options) { libvlc_media_add_option(*this,psz_options.c_str()); } /** * Add an option to the media with configurable flags. * * This option will be used to determine how the media_player will read * the media. This allows to use VLC's advanced reading/streaming options * on a per-media basis. * * The options are detailed in vlc long-help, for instance "--sout-all". * Note that all options are not usable on medias: specifically, due to * architectural issues, video-related options such as text renderer * options cannot be set on a single media. They must be set on the whole * libvlc instance instead. * * \param psz_options the options (as a string) * * \param i_flags the flags for this option */ void addOptionFlag(const std::string& psz_options, unsigned i_flags) { libvlc_media_add_option_flag(*this,psz_options.c_str(), i_flags); } /** * Get the media resource locator (mrl) from a media descriptor object * * \return string with mrl of media descriptor object */ std::string mrl() { auto str = wrapCStr( libvlc_media_get_mrl(*this) ); if ( str == nullptr ) return {}; return str.get(); } /** * Duplicate a media descriptor object. */ MediaPtr duplicate() { auto obj = libvlc_media_duplicate(*this); return std::make_shared<Media>( obj, false ); } /** * Read the meta of the media. * * If the media has not yet been parsed this will return NULL. * * This methods automatically calls parseAsync() , so after * calling it you may receive a libvlc_MediaMetaChanged event. If you * prefer a synchronous version ensure that you call parse() * before get_meta(). * * \see parse() * * \see parseAsync() * * \see libvlc_MediaMetaChanged * * \param e_meta the meta to read * * \return the media's meta */ std::string meta(libvlc_meta_t e_meta) { auto str = wrapCStr(libvlc_media_get_meta(*this, e_meta) ); if ( str == nullptr ) return {}; return str.get(); } /** * Set the meta of the media (this function will not save the meta, call * libvlc_media_save_meta in order to save the meta) * * \param e_meta the meta to write * * \param psz_value the media's meta */ void setMeta(libvlc_meta_t e_meta, const std::string& psz_value) { libvlc_media_set_meta(*this, e_meta, psz_value.c_str()); } /** * Save the meta previously set * * \return true if the write operation was successful */ int saveMeta() { return libvlc_media_save_meta(*this); } /** * Get current state of media descriptor object. Possible media states * are defined in libvlc_structures.c ( libvlc_NothingSpecial=0, * libvlc_Opening, libvlc_Buffering, libvlc_Playing, libvlc_Paused, * libvlc_Stopped, libvlc_Ended, libvlc_Error). * * \see libvlc_state_t * * \return state of media descriptor object */ libvlc_state_t state() { return libvlc_media_get_state(*this); } /** * Get the current statistics about the media * * \param p_stats structure that contain the statistics about the media * (this structure must be allocated by the caller) * * \return true if the statistics are available, false otherwise */ bool stats(libvlc_media_stats_t * p_stats) { return libvlc_media_get_stats(*this, p_stats) != 0; } /** * Get event manager from media descriptor object. NOTE: this function * doesn't increment reference counting. * * \return event manager object */ MediaEventManager& eventManager() { if ( m_eventManager == NULL ) { libvlc_event_manager_t* obj = libvlc_media_event_manager(*this); m_eventManager = std::make_shared<MediaEventManager>( obj ); } return *m_eventManager; } /** * Get duration (in ms) of media descriptor object item. * * \return duration of media item or -1 on error */ libvlc_time_t duration() { return libvlc_media_get_duration(*this); } /** * Parse a media. * * This fetches (local) meta data and tracks information. The method is * synchronous. * * \see parseAsync() * * \see meta() * * \see tracksInfo() */ void parse() { libvlc_media_parse(*this); } /** * Parse a media. * * This fetches (local) meta data and tracks information. The method is * the asynchronous of parse() . * * To track when this is over you can listen to libvlc_MediaParsedChanged * event. However if the media was already parsed you will not receive * this event. * * \see parse() * * \see libvlc_MediaParsedChanged * * \see meta() * * \see tracks() */ void parseAsync() { libvlc_media_parse_async(*this); } /** * Get Parsed status for media descriptor object. * * \see libvlc_MediaParsedChanged * * \return true if media object has been parsed otherwise it returns * false */ bool isParsed() { return libvlc_media_is_parsed(*this) != 0; } /** * Sets media descriptor's user_data. user_data is specialized data * accessed by the host application, VLC.framework uses it as a pointer * to an native object that references a libvlc_media_t pointer * * \param p_new_user_data pointer to user data */ void setUserData(void * p_new_user_data) { libvlc_media_set_user_data(*this, p_new_user_data); } /** * Get media descriptor's user_data. user_data is specialized data * accessed by the host application, VLC.framework uses it as a pointer * to an native object that references a libvlc_media_t pointer */ void* userData() { return libvlc_media_get_user_data(*this); } /** * Get media descriptor's elementary streams description * * Note, you need to call parse() or play the media at least once * before calling this function. Not doing this will result in an empty * array. * * \version LibVLC 2.1.0 and later. * * \return a vector containing all tracks */ std::vector<MediaTrack> tracks() { libvlc_media_track_t** tracks; uint32_t nbTracks = libvlc_media_tracks_get(*this, &tracks); std::vector<MediaTrack> res; if ( nbTracks == 0 ) return res; for ( uint32_t i = 0; i < nbTracks; ++i ) res.emplace_back( tracks[i] ); libvlc_media_tracks_release( tracks, nbTracks ); return res; } private: /** * Retain a reference to a media descriptor object (libvlc_media_t). Use * release() to decrement the reference count of a media * descriptor object. */ void retain() { if ( isValid() ) libvlc_media_retain(*this); } private: std::shared_ptr<MediaEventManager> m_eventManager; }; } // namespace VLC #endif <commit_msg>Media: Don't retain a nullptr instance<commit_after>/***************************************************************************** * Media.hpp: Media API ***************************************************************************** * Copyright © 2015 libvlcpp authors & VideoLAN * * Authors: Alexey Sokolov <alexey+vlc@asokolov.org> * Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef LIBVLC_CXX_MEDIA_H #define LIBVLC_CXX_MEDIA_H #include "common.hpp" #include <vector> #include <stdexcept> namespace VLC { class MediaPlayer; class MediaEventManager; class Instance; class MediaList; class Media : public Internal<libvlc_media_t> { public: enum class FromType { /** * Create a media for a certain file path. */ FromPath, /** * Create a media with a certain given media resource location, * for instance a valid URL. * * \note To refer to a local file with this function, * the file://... URI syntax <b>must</b> be used (see IETF RFC3986). * We recommend using FromPath instead when dealing with * local files. */ FromLocation, /** * Create a media as an empty node with a given name. */ AsNode, }; // To be able to write Media::FromLocation #if !defined(_MSC_VER) || _MSC_VER >= 1900 constexpr static FromType FromPath = FromType::FromPath; constexpr static FromType FromLocation = FromType::FromLocation; constexpr static FromType AsNode = FromType::AsNode; #else static const FromType FromPath = FromType::FromPath; static const FromType FromLocation = FromType::FromLocation; static const FromType AsNode = FromType::AsNode; #endif /** * @brief Media Constructs a libvlc Media instance * @param instance A libvlc instance * @param mrl A path, location, or node name, depending on the 3rd parameter * @param type The type of the 2nd argument. \sa{FromType} */ Media(Instance& instance, const std::string& mrl, FromType type) : Internal{ libvlc_media_release } { InternalPtr ptr = nullptr; switch (type) { case FromLocation: ptr = libvlc_media_new_location( getInternalPtr<libvlc_instance_t>( instance ), mrl.c_str() ); break; case FromPath: ptr = libvlc_media_new_path( getInternalPtr<libvlc_instance_t>( instance ), mrl.c_str() ); break; case AsNode: ptr = libvlc_media_new_as_node( getInternalPtr<libvlc_instance_t>( instance ), mrl.c_str() ); break; default: break; } if ( ptr == nullptr ) throw std::runtime_error("Failed to construct a media"); m_obj.reset( ptr, libvlc_media_release ); } /** * Create a media for an already open file descriptor. * The file descriptor shall be open for reading (or reading and writing). * * Regular file descriptors, pipe read descriptors and character device * descriptors (including TTYs) are supported on all platforms. * Block device descriptors are supported where available. * Directory descriptors are supported on systems that provide fdopendir(). * Sockets are supported on all platforms where they are file descriptors, * i.e. all except Windows. * * \note This library will <b>not</b> automatically close the file descriptor * under any circumstance. Nevertheless, a file descriptor can usually only be * rendered once in a media player. To render it a second time, the file * descriptor should probably be rewound to the beginning with lseek(). * * \param p_instance the instance * \param fd open file descriptor * \return the newly created media or NULL on error */ Media(Instance& instance, int fd) : Internal { libvlc_media_new_fd( getInternalPtr<libvlc_instance_t>( instance ), fd ), libvlc_media_release } { } /** * Get media instance from this media list instance. This action will increase * the refcount on the media instance. * The libvlc_media_list_lock should NOT be held upon entering this function. * * \param p_ml a media list instance * \return media instance */ Media(MediaList& list) : Internal{ libvlc_media_list_media( getInternalPtr<libvlc_media_list_t>( list ) ), libvlc_media_release } { } explicit Media( Internal::InternalPtr ptr, bool incrementRefCount) : Internal{ ptr, libvlc_media_release } { if ( incrementRefCount && ptr != nullptr ) retain(); } /** * Create an empty VLC Media instance. * * Calling any method on such an instance is undefined. */ Media() = default; /** * Check if 2 Media objects contain the same libvlc_media_t. * \param another another Media * \return true if they contain the same libvlc_media_t */ bool operator==(const Media& another) const { return m_obj == another.m_obj; } /** * Add an option to the media. * * This option will be used to determine how the media_player will read * the media. This allows to use VLC's advanced reading/streaming options * on a per-media basis. * * \note The options are listed in 'vlc long-help' from the command line, * e.g. "-sout-all". Keep in mind that available options and their * semantics vary across LibVLC versions and builds. * * \warning Not all options affects libvlc_media_t objects: Specifically, * due to architectural issues most audio and video options, such as text * renderer options, have no effects on an individual media. These * options must be set through Instance::Instance() instead. * * \param psz_options the options (as a string) */ void addOption(const std::string& psz_options) { libvlc_media_add_option(*this,psz_options.c_str()); } /** * Add an option to the media with configurable flags. * * This option will be used to determine how the media_player will read * the media. This allows to use VLC's advanced reading/streaming options * on a per-media basis. * * The options are detailed in vlc long-help, for instance "--sout-all". * Note that all options are not usable on medias: specifically, due to * architectural issues, video-related options such as text renderer * options cannot be set on a single media. They must be set on the whole * libvlc instance instead. * * \param psz_options the options (as a string) * * \param i_flags the flags for this option */ void addOptionFlag(const std::string& psz_options, unsigned i_flags) { libvlc_media_add_option_flag(*this,psz_options.c_str(), i_flags); } /** * Get the media resource locator (mrl) from a media descriptor object * * \return string with mrl of media descriptor object */ std::string mrl() { auto str = wrapCStr( libvlc_media_get_mrl(*this) ); if ( str == nullptr ) return {}; return str.get(); } /** * Duplicate a media descriptor object. */ MediaPtr duplicate() { auto obj = libvlc_media_duplicate(*this); return std::make_shared<Media>( obj, false ); } /** * Read the meta of the media. * * If the media has not yet been parsed this will return NULL. * * This methods automatically calls parseAsync() , so after * calling it you may receive a libvlc_MediaMetaChanged event. If you * prefer a synchronous version ensure that you call parse() * before get_meta(). * * \see parse() * * \see parseAsync() * * \see libvlc_MediaMetaChanged * * \param e_meta the meta to read * * \return the media's meta */ std::string meta(libvlc_meta_t e_meta) { auto str = wrapCStr(libvlc_media_get_meta(*this, e_meta) ); if ( str == nullptr ) return {}; return str.get(); } /** * Set the meta of the media (this function will not save the meta, call * libvlc_media_save_meta in order to save the meta) * * \param e_meta the meta to write * * \param psz_value the media's meta */ void setMeta(libvlc_meta_t e_meta, const std::string& psz_value) { libvlc_media_set_meta(*this, e_meta, psz_value.c_str()); } /** * Save the meta previously set * * \return true if the write operation was successful */ int saveMeta() { return libvlc_media_save_meta(*this); } /** * Get current state of media descriptor object. Possible media states * are defined in libvlc_structures.c ( libvlc_NothingSpecial=0, * libvlc_Opening, libvlc_Buffering, libvlc_Playing, libvlc_Paused, * libvlc_Stopped, libvlc_Ended, libvlc_Error). * * \see libvlc_state_t * * \return state of media descriptor object */ libvlc_state_t state() { return libvlc_media_get_state(*this); } /** * Get the current statistics about the media * * \param p_stats structure that contain the statistics about the media * (this structure must be allocated by the caller) * * \return true if the statistics are available, false otherwise */ bool stats(libvlc_media_stats_t * p_stats) { return libvlc_media_get_stats(*this, p_stats) != 0; } /** * Get event manager from media descriptor object. NOTE: this function * doesn't increment reference counting. * * \return event manager object */ MediaEventManager& eventManager() { if ( m_eventManager == NULL ) { libvlc_event_manager_t* obj = libvlc_media_event_manager(*this); m_eventManager = std::make_shared<MediaEventManager>( obj ); } return *m_eventManager; } /** * Get duration (in ms) of media descriptor object item. * * \return duration of media item or -1 on error */ libvlc_time_t duration() { return libvlc_media_get_duration(*this); } /** * Parse a media. * * This fetches (local) meta data and tracks information. The method is * synchronous. * * \see parseAsync() * * \see meta() * * \see tracksInfo() */ void parse() { libvlc_media_parse(*this); } /** * Parse a media. * * This fetches (local) meta data and tracks information. The method is * the asynchronous of parse() . * * To track when this is over you can listen to libvlc_MediaParsedChanged * event. However if the media was already parsed you will not receive * this event. * * \see parse() * * \see libvlc_MediaParsedChanged * * \see meta() * * \see tracks() */ void parseAsync() { libvlc_media_parse_async(*this); } /** * Get Parsed status for media descriptor object. * * \see libvlc_MediaParsedChanged * * \return true if media object has been parsed otherwise it returns * false */ bool isParsed() { return libvlc_media_is_parsed(*this) != 0; } /** * Sets media descriptor's user_data. user_data is specialized data * accessed by the host application, VLC.framework uses it as a pointer * to an native object that references a libvlc_media_t pointer * * \param p_new_user_data pointer to user data */ void setUserData(void * p_new_user_data) { libvlc_media_set_user_data(*this, p_new_user_data); } /** * Get media descriptor's user_data. user_data is specialized data * accessed by the host application, VLC.framework uses it as a pointer * to an native object that references a libvlc_media_t pointer */ void* userData() { return libvlc_media_get_user_data(*this); } /** * Get media descriptor's elementary streams description * * Note, you need to call parse() or play the media at least once * before calling this function. Not doing this will result in an empty * array. * * \version LibVLC 2.1.0 and later. * * \return a vector containing all tracks */ std::vector<MediaTrack> tracks() { libvlc_media_track_t** tracks; uint32_t nbTracks = libvlc_media_tracks_get(*this, &tracks); std::vector<MediaTrack> res; if ( nbTracks == 0 ) return res; for ( uint32_t i = 0; i < nbTracks; ++i ) res.emplace_back( tracks[i] ); libvlc_media_tracks_release( tracks, nbTracks ); return res; } private: /** * Retain a reference to a media descriptor object (libvlc_media_t). Use * release() to decrement the reference count of a media * descriptor object. */ void retain() { if ( isValid() ) libvlc_media_retain(*this); } private: std::shared_ptr<MediaEventManager> m_eventManager; }; } // namespace VLC #endif <|endoftext|>
<commit_before>#include <cstdlib> #include <iostream> #include "gc/baker.hpp" #include "objectmemory.hpp" #include "object_utils.hpp" #include "builtin/tuple.hpp" #include "builtin/class.hpp" #include "builtin/io.hpp" #include "instruments/stats.hpp" #include "call_frame.hpp" #include "gc/gc.hpp" #include "capi/handle.hpp" namespace rubinius { BakerGC::BakerGC(ObjectMemory *om, size_t bytes) : GarbageCollector(om) , eden(bytes) , heap_a(bytes / 2) , heap_b(bytes / 2) , total_objects(0) , copy_spills_(0) , autotune_(false) , tune_threshold_(0) , original_lifetime_(1) , lifetime_(1) , promoted_(0) { current = &heap_a; next = &heap_b; } BakerGC::~BakerGC() { } Object* BakerGC::saw_object(Object* obj) { Object* copy; if(watched_p(obj)) { std::cout << "detected " << obj << " during baker collection\n"; } if(!obj->reference_p()) return obj; if(obj->zone() != YoungObjectZone) return obj; if(obj->forwarded_p()) return obj->forward(); // This object is already in the next space, we don't want to // copy it again! // TODO test this! if(next->contains_p(obj)) return obj; if(unlikely(obj->inc_age() >= lifetime_)) { copy = object_memory_->promote_object(obj); promoted_push(copy); } else if(likely(next->enough_space_p(obj->size_in_bytes(object_memory_->state)))) { copy = next->copy_object(object_memory_->state, obj); total_objects++; } else { copy_spills_++; copy = object_memory_->promote_object(obj); promoted_push(copy); } if(watched_p(copy)) { std::cout << "detected " << copy << " during baker collection (2)\n"; } obj->set_forward(copy); return copy; } void BakerGC::copy_unscanned() { Object* iobj = next->next_unscanned(object_memory_->state); while(iobj) { assert(iobj->zone() == YoungObjectZone); if(!iobj->forwarded_p()) scan_object(iobj); iobj = next->next_unscanned(object_memory_->state); } } bool BakerGC::fully_scanned_p() { return next->fully_scanned_p(); } const static double cOverFullThreshold = 95.0; const static int cOverFullTimes = 3; const static size_t cMinimumLifetime = 1; const static double cUnderFullThreshold = 20.0; const static int cUnderFullTimes = -3; const static size_t cMaximumLifetime = 6; /* Perform garbage collection on the young objects. */ void BakerGC::collect(GCData& data, YoungCollectStats* stats) { #ifdef RBX_GC_STATS stats::GCStats::get()->bytes_copied.start(); stats::GCStats::get()->objects_copied.start(); stats::GCStats::get()->objects_promoted.start(); stats::GCStats::get()->collect_young.start(); #endif Object* tmp; ObjectArray *current_rs = object_memory_->swap_remember_set(); total_objects = 0; copy_spills_ = 0; reset_promoted(); for(ObjectArray::iterator oi = current_rs->begin(); oi != current_rs->end(); ++oi) { tmp = *oi; // unremember_object throws a NULL in to remove an object // so we don't have to compact the set in unremember if(tmp) { // assert(tmp->zone == MatureObjectZone); // assert(!tmp->forwarded_p()); // Remove the Remember bit, since we're clearing the set. tmp->clear_remember(); scan_object(tmp); } } delete current_rs; for(Roots::Iterator i(data.roots()); i.more(); i.advance()) { i->set(saw_object(i->get())); } if(data.threads()) { for(std::list<ManagedThread*>::iterator i = data.threads()->begin(); i != data.threads()->end(); i++) { for(Roots::Iterator ri((*i)->roots()); ri.more(); ri.advance()) { ri->set(saw_object(ri->get())); } } } for(capi::Handles::Iterator i(*data.handles()); i.more(); i.advance()) { if(!i->weak_p() && i->object()->young_object_p()) { i->set_object(saw_object(i->object())); assert(i->object()->inflated_header_p()); } assert(i->object()->type_id() != InvalidType); } for(capi::Handles::Iterator i(*data.cached_handles()); i.more(); i.advance()) { if(!i->weak_p() && i->object()->young_object_p()) { i->set_object(saw_object(i->object())); assert(i->object()->inflated_header_p()); } assert(i->object()->type_id() != InvalidType); } for(VariableRootBuffers::Iterator i(data.variable_buffers()); i.more(); i.advance()) { Object*** buffer = i->buffer(); for(int idx = 0; idx < i->size(); idx++) { Object** var = buffer[idx]; Object* tmp = *var; if(tmp->reference_p() && tmp->young_object_p()) { *var = saw_object(tmp); } } } // Walk all the call frames for(CallFrameLocationList::iterator i = data.call_frames().begin(); i != data.call_frames().end(); i++) { CallFrame** loc = *i; walk_call_frame(*loc); } // Handle all promotions to non-young space that occured. handle_promotions(); clear_promotion(); assert(fully_scanned_p()); // We're now done seeing the entire object graph of normal, live references. // Now we get to handle the unusual references, like finalizers and such. // reset_promoted(); /* Update finalizers. Doing so can cause objects that would have just died * to continue life until we can get around to running the finalizer. That * more promoted objects, etc. */ check_finalize(); // Run promotions again, because checking finalizers can keep more objects // alive (and thus promoted). handle_promotions(); clear_promotion(); assert(fully_scanned_p()); #ifdef RBX_GC_STATS // Lost souls just tracks the ages of objects, so we know how old they // were when they died. // find_lost_souls(); #endif /* Check any weakrefs and replace dead objects with nil*/ clean_weakrefs(true); /* Swap the 2 halves */ Heap *x = next; next = current; current = x; next->reset(); // Reset eden to empty eden.reset(); if(stats) { stats->lifetime = lifetime_; stats->percentage_used = current->percentage_used(); stats->promoted_objects = promoted_objects_; stats->excess_objects = copy_spills_; } if(autotune_) { double used = current->percentage_used(); if(used > cOverFullThreshold) { if(tune_threshold_ >= cOverFullTimes) { if(lifetime_ > cMinimumLifetime) lifetime_--; } else { tune_threshold_++; } } else if(used < cUnderFullThreshold) { if(tune_threshold_ <= cUnderFullTimes) { if(lifetime_ < cMaximumLifetime) lifetime_++; } else { tune_threshold_--; } } else if(tune_threshold_ > 0) { tune_threshold_--; } else if(tune_threshold_ < 0) { tune_threshold_++; } else if(tune_threshold_ == 0) { if(lifetime_ < original_lifetime_) { lifetime_++; } else if(lifetime_ > original_lifetime_) { lifetime_--; } } } #ifdef RBX_GC_STATS stats::GCStats::get()->collect_young.stop(); stats::GCStats::get()->objects_copied.stop(); stats::GCStats::get()->objects_promoted.stop(); stats::GCStats::get()->bytes_copied.stop(); #endif } void BakerGC::handle_promotions() { /* Ok, now handle all promoted objects. This is setup a little weird * so I should explain. * * We want to scan each promoted object. But this scanning will likely * cause more objects to be promoted. Adding to an ObjectArray that your * iterating over blows up the iterators, so instead we rotate the * current promoted set out as we iterator over it, and stick an * empty ObjectArray in. * * This way, when there are no more objects that are promoted, the last * ObjectArray will be empty. * */ promoted_current_ = promoted_insert_ = promoted_->begin(); while(promoted_->size() > 0 || !fully_scanned_p()) { if(promoted_->size() > 0) { for(;promoted_current_ != promoted_->end(); ++promoted_current_) { Object* tmp = *promoted_current_; assert(tmp->zone() == MatureObjectZone); scan_object(tmp); if(watched_p(tmp)) { std::cout << "detected " << tmp << " during scan of promoted objects.\n"; } } promoted_->resize(promoted_insert_ - promoted_->begin()); promoted_current_ = promoted_insert_ = promoted_->begin(); } /* As we're handling promoted objects, also handle unscanned objects. * Scanning these unscanned objects (via the scan pointer) will * cause more promotions. */ copy_unscanned(); } } inline Object *BakerGC::next_object(Object * obj) { return reinterpret_cast<Object*>(reinterpret_cast<uintptr_t>(obj) + obj->size_in_bytes(object_memory_->state)); } void BakerGC::clear_marks() { Object* obj = current->first_object(); while(obj < current->current()) { obj->clear_mark(); obj = next_object(obj); } obj = next->first_object(); while(obj < next->current()) { obj->clear_mark(); obj = next_object(obj); } obj = eden.first_object(); while(obj < eden.current()) { obj->clear_mark(); obj = next_object(obj); } } void BakerGC::find_lost_souls() { Object* obj = current->first_object(); while(obj < current->current()) { if(!obj->forwarded_p()) { #ifdef RBX_GC_STATS stats::GCStats::get()->lifetimes[obj->age()]++; #endif } obj = next_object(obj); } obj = eden.first_object(); while(obj < eden.current()) { if(!obj->forwarded_p()) { #ifdef RBX_GC_STATS stats::GCStats::get()->lifetimes[obj->age()]++; #endif } obj = next_object(obj); } } void BakerGC::check_finalize() { for(std::list<FinalizeObject>::iterator i = object_memory_->finalize().begin(); i != object_memory_->finalize().end(); ) { FinalizeObject& fi = *i; if(!i->object->young_object_p()) { i++; continue; } switch(i->status) { case FinalizeObject::eLive: if(!i->object->forwarded_p()) { i->status = FinalizeObject::eQueued; // We have to still keep it alive though until we finish with it. i->object = saw_object(i->object); object_memory_->to_finalize().push_back(&fi); } else { i->object = i->object->forward(); } break; case FinalizeObject::eQueued: // Nothing, we haven't gotten to it yet. // Keep waiting and keep i->object updated. if(i->object->forwarded_p()) { i->object = i->object->forward(); } else { i->object = saw_object(i->object); } break; case FinalizeObject::eFinalized: if(!i->object->forwarded_p()) { // finalized and done with. i = object_memory_->finalize().erase(i); continue; } else { // RESURECTION! i->status = FinalizeObject::eQueued; } break; } i++; } } bool BakerGC::in_current_p(Object* obj) { return current->contains_p(obj); } ObjectPosition BakerGC::validate_object(Object* obj) { if(current->in_current_p(obj) || eden.in_current_p(obj)) { return cValid; } else if(next->contains_p(obj)) { return cInWrongYoungHalf; } else { return cUnknown; } } } <commit_msg>Don't reset promotions, we loose stats.<commit_after>#include <cstdlib> #include <iostream> #include "gc/baker.hpp" #include "objectmemory.hpp" #include "object_utils.hpp" #include "builtin/tuple.hpp" #include "builtin/class.hpp" #include "builtin/io.hpp" #include "instruments/stats.hpp" #include "call_frame.hpp" #include "gc/gc.hpp" #include "capi/handle.hpp" namespace rubinius { BakerGC::BakerGC(ObjectMemory *om, size_t bytes) : GarbageCollector(om) , eden(bytes) , heap_a(bytes / 2) , heap_b(bytes / 2) , total_objects(0) , copy_spills_(0) , autotune_(false) , tune_threshold_(0) , original_lifetime_(1) , lifetime_(1) , promoted_(0) { current = &heap_a; next = &heap_b; } BakerGC::~BakerGC() { } Object* BakerGC::saw_object(Object* obj) { Object* copy; if(watched_p(obj)) { std::cout << "detected " << obj << " during baker collection\n"; } if(!obj->reference_p()) return obj; if(obj->zone() != YoungObjectZone) return obj; if(obj->forwarded_p()) return obj->forward(); // This object is already in the next space, we don't want to // copy it again! // TODO test this! if(next->contains_p(obj)) return obj; if(unlikely(obj->inc_age() >= lifetime_)) { copy = object_memory_->promote_object(obj); promoted_push(copy); } else if(likely(next->enough_space_p(obj->size_in_bytes(object_memory_->state)))) { copy = next->copy_object(object_memory_->state, obj); total_objects++; } else { copy_spills_++; copy = object_memory_->promote_object(obj); promoted_push(copy); } if(watched_p(copy)) { std::cout << "detected " << copy << " during baker collection (2)\n"; } obj->set_forward(copy); return copy; } void BakerGC::copy_unscanned() { Object* iobj = next->next_unscanned(object_memory_->state); while(iobj) { assert(iobj->zone() == YoungObjectZone); if(!iobj->forwarded_p()) scan_object(iobj); iobj = next->next_unscanned(object_memory_->state); } } bool BakerGC::fully_scanned_p() { return next->fully_scanned_p(); } const static double cOverFullThreshold = 95.0; const static int cOverFullTimes = 3; const static size_t cMinimumLifetime = 1; const static double cUnderFullThreshold = 20.0; const static int cUnderFullTimes = -3; const static size_t cMaximumLifetime = 6; /* Perform garbage collection on the young objects. */ void BakerGC::collect(GCData& data, YoungCollectStats* stats) { #ifdef RBX_GC_STATS stats::GCStats::get()->bytes_copied.start(); stats::GCStats::get()->objects_copied.start(); stats::GCStats::get()->objects_promoted.start(); stats::GCStats::get()->collect_young.start(); #endif Object* tmp; ObjectArray *current_rs = object_memory_->swap_remember_set(); total_objects = 0; copy_spills_ = 0; reset_promoted(); for(ObjectArray::iterator oi = current_rs->begin(); oi != current_rs->end(); ++oi) { tmp = *oi; // unremember_object throws a NULL in to remove an object // so we don't have to compact the set in unremember if(tmp) { // assert(tmp->zone == MatureObjectZone); // assert(!tmp->forwarded_p()); // Remove the Remember bit, since we're clearing the set. tmp->clear_remember(); scan_object(tmp); } } delete current_rs; for(Roots::Iterator i(data.roots()); i.more(); i.advance()) { i->set(saw_object(i->get())); } if(data.threads()) { for(std::list<ManagedThread*>::iterator i = data.threads()->begin(); i != data.threads()->end(); i++) { for(Roots::Iterator ri((*i)->roots()); ri.more(); ri.advance()) { ri->set(saw_object(ri->get())); } } } for(capi::Handles::Iterator i(*data.handles()); i.more(); i.advance()) { if(!i->weak_p() && i->object()->young_object_p()) { i->set_object(saw_object(i->object())); assert(i->object()->inflated_header_p()); } assert(i->object()->type_id() != InvalidType); } for(capi::Handles::Iterator i(*data.cached_handles()); i.more(); i.advance()) { if(!i->weak_p() && i->object()->young_object_p()) { i->set_object(saw_object(i->object())); assert(i->object()->inflated_header_p()); } assert(i->object()->type_id() != InvalidType); } for(VariableRootBuffers::Iterator i(data.variable_buffers()); i.more(); i.advance()) { Object*** buffer = i->buffer(); for(int idx = 0; idx < i->size(); idx++) { Object** var = buffer[idx]; Object* tmp = *var; if(tmp->reference_p() && tmp->young_object_p()) { *var = saw_object(tmp); } } } // Walk all the call frames for(CallFrameLocationList::iterator i = data.call_frames().begin(); i != data.call_frames().end(); i++) { CallFrame** loc = *i; walk_call_frame(*loc); } // Handle all promotions to non-young space that occured. handle_promotions(); assert(fully_scanned_p()); // We're now done seeing the entire object graph of normal, live references. // Now we get to handle the unusual references, like finalizers and such. // /* Update finalizers. Doing so can cause objects that would have just died * to continue life until we can get around to running the finalizer. That * more promoted objects, etc. */ check_finalize(); // Run promotions again, because checking finalizers can keep more objects // alive (and thus promoted). handle_promotions(); clear_promotion(); assert(fully_scanned_p()); #ifdef RBX_GC_STATS // Lost souls just tracks the ages of objects, so we know how old they // were when they died. // find_lost_souls(); #endif /* Check any weakrefs and replace dead objects with nil*/ clean_weakrefs(true); /* Swap the 2 halves */ Heap *x = next; next = current; current = x; next->reset(); // Reset eden to empty eden.reset(); if(stats) { stats->lifetime = lifetime_; stats->percentage_used = current->percentage_used(); stats->promoted_objects = promoted_objects_; stats->excess_objects = copy_spills_; } if(autotune_) { double used = current->percentage_used(); if(used > cOverFullThreshold) { if(tune_threshold_ >= cOverFullTimes) { if(lifetime_ > cMinimumLifetime) lifetime_--; } else { tune_threshold_++; } } else if(used < cUnderFullThreshold) { if(tune_threshold_ <= cUnderFullTimes) { if(lifetime_ < cMaximumLifetime) lifetime_++; } else { tune_threshold_--; } } else if(tune_threshold_ > 0) { tune_threshold_--; } else if(tune_threshold_ < 0) { tune_threshold_++; } else if(tune_threshold_ == 0) { if(lifetime_ < original_lifetime_) { lifetime_++; } else if(lifetime_ > original_lifetime_) { lifetime_--; } } } #ifdef RBX_GC_STATS stats::GCStats::get()->collect_young.stop(); stats::GCStats::get()->objects_copied.stop(); stats::GCStats::get()->objects_promoted.stop(); stats::GCStats::get()->bytes_copied.stop(); #endif } void BakerGC::handle_promotions() { /* Ok, now handle all promoted objects. This is setup a little weird * so I should explain. * * We want to scan each promoted object. But this scanning will likely * cause more objects to be promoted. Adding to an ObjectArray that your * iterating over blows up the iterators, so instead we rotate the * current promoted set out as we iterator over it, and stick an * empty ObjectArray in. * * This way, when there are no more objects that are promoted, the last * ObjectArray will be empty. * */ promoted_current_ = promoted_insert_ = promoted_->begin(); while(promoted_->size() > 0 || !fully_scanned_p()) { if(promoted_->size() > 0) { for(;promoted_current_ != promoted_->end(); ++promoted_current_) { Object* tmp = *promoted_current_; assert(tmp->zone() == MatureObjectZone); scan_object(tmp); if(watched_p(tmp)) { std::cout << "detected " << tmp << " during scan of promoted objects.\n"; } } promoted_->resize(promoted_insert_ - promoted_->begin()); promoted_current_ = promoted_insert_ = promoted_->begin(); } /* As we're handling promoted objects, also handle unscanned objects. * Scanning these unscanned objects (via the scan pointer) will * cause more promotions. */ copy_unscanned(); } } inline Object *BakerGC::next_object(Object * obj) { return reinterpret_cast<Object*>(reinterpret_cast<uintptr_t>(obj) + obj->size_in_bytes(object_memory_->state)); } void BakerGC::clear_marks() { Object* obj = current->first_object(); while(obj < current->current()) { obj->clear_mark(); obj = next_object(obj); } obj = next->first_object(); while(obj < next->current()) { obj->clear_mark(); obj = next_object(obj); } obj = eden.first_object(); while(obj < eden.current()) { obj->clear_mark(); obj = next_object(obj); } } void BakerGC::find_lost_souls() { Object* obj = current->first_object(); while(obj < current->current()) { if(!obj->forwarded_p()) { #ifdef RBX_GC_STATS stats::GCStats::get()->lifetimes[obj->age()]++; #endif } obj = next_object(obj); } obj = eden.first_object(); while(obj < eden.current()) { if(!obj->forwarded_p()) { #ifdef RBX_GC_STATS stats::GCStats::get()->lifetimes[obj->age()]++; #endif } obj = next_object(obj); } } void BakerGC::check_finalize() { for(std::list<FinalizeObject>::iterator i = object_memory_->finalize().begin(); i != object_memory_->finalize().end(); ) { FinalizeObject& fi = *i; if(!i->object->young_object_p()) { i++; continue; } switch(i->status) { case FinalizeObject::eLive: if(!i->object->forwarded_p()) { i->status = FinalizeObject::eQueued; // We have to still keep it alive though until we finish with it. i->object = saw_object(i->object); object_memory_->to_finalize().push_back(&fi); } else { i->object = i->object->forward(); } break; case FinalizeObject::eQueued: // Nothing, we haven't gotten to it yet. // Keep waiting and keep i->object updated. if(i->object->forwarded_p()) { i->object = i->object->forward(); } else { i->object = saw_object(i->object); } break; case FinalizeObject::eFinalized: if(!i->object->forwarded_p()) { // finalized and done with. i = object_memory_->finalize().erase(i); continue; } else { // RESURECTION! i->status = FinalizeObject::eQueued; } break; } i++; } } bool BakerGC::in_current_p(Object* obj) { return current->contains_p(obj); } ObjectPosition BakerGC::validate_object(Object* obj) { if(current->in_current_p(obj) || eden.in_current_p(obj)) { return cValid; } else if(next->contains_p(obj)) { return cInWrongYoungHalf; } else { return cUnknown; } } } <|endoftext|>
<commit_before>#include "test_function.h" #define _USE_MATH_DEFINES #include <math.h> #include <k52/optimization/params/continuous_parameters_array.h> #include "test_objective_functions.h" using ::k52::optimization::IObjectiveFunction; using ::k52::optimization::IContinuousParameters; using ::k52::optimization::ContinuousParametersArray; namespace k52 { namespace optimization_tests { bool TestFunction::was_initialized_ = false; std::vector<TestFunction::shared_ptr> TestFunction::test_functions_; const IObjectiveFunction& TestFunction::get_objective_function() const { return *function_.get(); } const IContinuousParameters* TestFunction::get_solution() const { return solution_.get(); } const IContinuousParameters* TestFunction::get_start_point() const { return start_point_.get(); } std::string TestFunction::get_analitical_form() const { return analitical_form_; } bool TestFunction::maximize() const { return maximize_; } void TestFunction::Register(IObjectiveFunction::shared_ptr function, IContinuousParameters::shared_ptr solution, IContinuousParameters::shared_ptr start_point, std::string analitical_form, bool maximize) { TestFunction::shared_ptr test_function( new TestFunction(function, solution, start_point, analitical_form, maximize) ); test_functions_.push_back(test_function); } std::vector<TestFunction::shared_ptr> TestFunction::get_test_functions() { if(!was_initialized_) { Initialize(); } return test_functions_; } TestFunction::TestFunction(IObjectiveFunction::shared_ptr function, IContinuousParameters::shared_ptr solution, IContinuousParameters::shared_ptr start_point, std::string analitical_form, bool maximize): function_(function), solution_(solution), start_point_(start_point), analitical_form_(analitical_form), maximize_(maximize) { } void TestFunction::Initialize() { IObjectiveFunction::shared_ptr square_objective_function( new SquareObjectiveFunction() ); std::vector<double> square_solution_values(2); square_solution_values[0] = M_SQRT2; square_solution_values[1] = M_SQRT2; IContinuousParameters::shared_ptr square_solution( new ContinuousParametersArray(square_solution_values)); std::vector<double> square_start_point_values(2); square_start_point_values[0] = 11; square_start_point_values[1] = 7; IContinuousParameters::shared_ptr square_start_point( new ContinuousParametersArray(square_start_point_values)); Register(square_objective_function, square_solution, square_start_point, "square_root(x)", false); } }/* namespace optimization_tests */ }/* namespace k52 */ <commit_msg>Unnecessary define removed<commit_after>#include "test_function.h" #include <math.h> #include <k52/optimization/params/continuous_parameters_array.h> #include "test_objective_functions.h" using ::k52::optimization::IObjectiveFunction; using ::k52::optimization::IContinuousParameters; using ::k52::optimization::ContinuousParametersArray; namespace k52 { namespace optimization_tests { bool TestFunction::was_initialized_ = false; std::vector<TestFunction::shared_ptr> TestFunction::test_functions_; const IObjectiveFunction& TestFunction::get_objective_function() const { return *function_.get(); } const IContinuousParameters* TestFunction::get_solution() const { return solution_.get(); } const IContinuousParameters* TestFunction::get_start_point() const { return start_point_.get(); } std::string TestFunction::get_analitical_form() const { return analitical_form_; } bool TestFunction::maximize() const { return maximize_; } void TestFunction::Register(IObjectiveFunction::shared_ptr function, IContinuousParameters::shared_ptr solution, IContinuousParameters::shared_ptr start_point, std::string analitical_form, bool maximize) { TestFunction::shared_ptr test_function( new TestFunction(function, solution, start_point, analitical_form, maximize) ); test_functions_.push_back(test_function); } std::vector<TestFunction::shared_ptr> TestFunction::get_test_functions() { if(!was_initialized_) { Initialize(); } return test_functions_; } TestFunction::TestFunction(IObjectiveFunction::shared_ptr function, IContinuousParameters::shared_ptr solution, IContinuousParameters::shared_ptr start_point, std::string analitical_form, bool maximize): function_(function), solution_(solution), start_point_(start_point), analitical_form_(analitical_form), maximize_(maximize) { } void TestFunction::Initialize() { IObjectiveFunction::shared_ptr square_objective_function( new SquareObjectiveFunction() ); std::vector<double> square_solution_values(2); square_solution_values[0] = M_SQRT2; square_solution_values[1] = M_SQRT2; IContinuousParameters::shared_ptr square_solution( new ContinuousParametersArray(square_solution_values)); std::vector<double> square_start_point_values(2); square_start_point_values[0] = 11; square_start_point_values[1] = 7; IContinuousParameters::shared_ptr square_start_point( new ContinuousParametersArray(square_start_point_values)); Register(square_objective_function, square_solution, square_start_point, "square_root(x)", false); } }/* namespace optimization_tests */ }/* namespace k52 */ <|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 "base/platform_thread.h" #include "testing/gtest/include/gtest/gtest.h" typedef testing::Test PlatformThreadTest; // Trivial tests that thread runs and doesn't crash on create and join --------- class TrivialThread : public PlatformThread::Delegate { public: TrivialThread() : did_run_(false) {} virtual void ThreadMain() { did_run_ = true; } bool did_run() const { return did_run_; } private: bool did_run_; DISALLOW_COPY_AND_ASSIGN(TrivialThread); }; TEST_F(PlatformThreadTest, Trivial) { TrivialThread thread; PlatformThreadHandle handle = kNullThreadHandle; ASSERT_FALSE(thread.did_run()); ASSERT_TRUE(PlatformThread::Create(0, &thread, &handle)); PlatformThread::Join(handle); ASSERT_TRUE(thread.did_run()); } TEST_F(PlatformThreadTest, TrivialTimesTen) { TrivialThread thread[10]; PlatformThreadHandle handle[arraysize(thread)]; for (size_t n = 0; n < arraysize(thread); n++) ASSERT_FALSE(thread[n].did_run()); for (size_t n = 0; n < arraysize(thread); n++) ASSERT_TRUE(PlatformThread::Create(0, &thread[n], &handle[n])); for (size_t n = 0; n < arraysize(thread); n++) PlatformThread::Join(handle[n]); for (size_t n = 0; n < arraysize(thread); n++) ASSERT_TRUE(thread[n].did_run()); } // Tests of basic thread functions --------------------------------------------- class FunctionTestThread : public TrivialThread { public: FunctionTestThread() {} virtual void ThreadMain() { thread_id_ = PlatformThread::CurrentId(); PlatformThread::YieldCurrentThread(); PlatformThread::Sleep(50); TrivialThread::ThreadMain(); } PlatformThreadId thread_id() const { return thread_id_; } private: PlatformThreadId thread_id_; DISALLOW_COPY_AND_ASSIGN(FunctionTestThread); }; TEST_F(PlatformThreadTest, Function) { PlatformThreadId main_thread_id = PlatformThread::CurrentId(); FunctionTestThread thread; PlatformThreadHandle handle = kNullThreadHandle; ASSERT_FALSE(thread.did_run()); ASSERT_TRUE(PlatformThread::Create(0, &thread, &handle)); PlatformThread::Join(handle); ASSERT_TRUE(thread.did_run()); EXPECT_NE(thread.thread_id(), main_thread_id); } TEST_F(PlatformThreadTest, FunctionTimesTen) { PlatformThreadId main_thread_id = PlatformThread::CurrentId(); FunctionTestThread thread[10]; PlatformThreadHandle handle[arraysize(thread)]; for (size_t n = 0; n < arraysize(thread); n++) ASSERT_FALSE(thread[n].did_run()); for (size_t n = 0; n < arraysize(thread); n++) ASSERT_TRUE(PlatformThread::Create(0, &thread[n], &handle[n])); for (size_t n = 0; n < arraysize(thread); n++) PlatformThread::Join(handle[n]); for (size_t n = 0; n < arraysize(thread); n++) { ASSERT_TRUE(thread[n].did_run()); EXPECT_NE(thread[n].thread_id(), main_thread_id); } } <commit_msg>Uninitialized member variable.<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 "base/platform_thread.h" #include "testing/gtest/include/gtest/gtest.h" typedef testing::Test PlatformThreadTest; // Trivial tests that thread runs and doesn't crash on create and join --------- class TrivialThread : public PlatformThread::Delegate { public: TrivialThread() : did_run_(false) {} virtual void ThreadMain() { did_run_ = true; } bool did_run() const { return did_run_; } private: bool did_run_; DISALLOW_COPY_AND_ASSIGN(TrivialThread); }; TEST_F(PlatformThreadTest, Trivial) { TrivialThread thread; PlatformThreadHandle handle = kNullThreadHandle; ASSERT_FALSE(thread.did_run()); ASSERT_TRUE(PlatformThread::Create(0, &thread, &handle)); PlatformThread::Join(handle); ASSERT_TRUE(thread.did_run()); } TEST_F(PlatformThreadTest, TrivialTimesTen) { TrivialThread thread[10]; PlatformThreadHandle handle[arraysize(thread)]; for (size_t n = 0; n < arraysize(thread); n++) ASSERT_FALSE(thread[n].did_run()); for (size_t n = 0; n < arraysize(thread); n++) ASSERT_TRUE(PlatformThread::Create(0, &thread[n], &handle[n])); for (size_t n = 0; n < arraysize(thread); n++) PlatformThread::Join(handle[n]); for (size_t n = 0; n < arraysize(thread); n++) ASSERT_TRUE(thread[n].did_run()); } // Tests of basic thread functions --------------------------------------------- class FunctionTestThread : public TrivialThread { public: FunctionTestThread() : thread_id_(0) {} virtual void ThreadMain() { thread_id_ = PlatformThread::CurrentId(); PlatformThread::YieldCurrentThread(); PlatformThread::Sleep(50); TrivialThread::ThreadMain(); } PlatformThreadId thread_id() const { return thread_id_; } private: PlatformThreadId thread_id_; DISALLOW_COPY_AND_ASSIGN(FunctionTestThread); }; TEST_F(PlatformThreadTest, Function) { PlatformThreadId main_thread_id = PlatformThread::CurrentId(); FunctionTestThread thread; PlatformThreadHandle handle = kNullThreadHandle; ASSERT_FALSE(thread.did_run()); ASSERT_TRUE(PlatformThread::Create(0, &thread, &handle)); PlatformThread::Join(handle); ASSERT_TRUE(thread.did_run()); EXPECT_NE(thread.thread_id(), main_thread_id); } TEST_F(PlatformThreadTest, FunctionTimesTen) { PlatformThreadId main_thread_id = PlatformThread::CurrentId(); FunctionTestThread thread[10]; PlatformThreadHandle handle[arraysize(thread)]; for (size_t n = 0; n < arraysize(thread); n++) ASSERT_FALSE(thread[n].did_run()); for (size_t n = 0; n < arraysize(thread); n++) ASSERT_TRUE(PlatformThread::Create(0, &thread[n], &handle[n])); for (size_t n = 0; n < arraysize(thread); n++) PlatformThread::Join(handle[n]); for (size_t n = 0; n < arraysize(thread); n++) { ASSERT_TRUE(thread[n].did_run()); EXPECT_NE(thread[n].thread_id(), main_thread_id); } } <|endoftext|>
<commit_before>/* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> * * Permission to use, copy, modify, and/or distribute this software for any purpose with * or without fee is hereby granted, provided that the above copyright notice and this * permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../Base.hpp" #ifdef DGL_OS_WINDOWS # include <windows.h> #else # include <unistd.h> #endif START_NAMESPACE_DGL // ----------------------------------------------------------------------- void sleep(unsigned int secs) { #ifdef DGL_OS_WINDOWS ::Sleep(secs * 1000); #else ::sleep(secs); #endif } void msleep(unsigned int msecs) { #ifdef DGL_OS_WINDOWS ::Sleep(msecs); #else ::usleep(msecs * 1000); #endif } // ----------------------------------------------------------------------- END_NAMESPACE_DGL <commit_msg>Remove useless file<commit_after><|endoftext|>
<commit_before>#ifndef SM_PYTHON_ID_HPP #define SM_PYTHON_ID_HPP #include <numpy_eigen/boost_python_headers.hpp> #include <boost/python/to_python_converter.hpp> #include <Python.h> #include <boost/cstdint.hpp> namespace sm { namespace python { // to use: sm::python::Id_python_converter<FrameId>::register_converter(); // adapted from http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/ template<typename ID_T> struct Id_python_converter { typedef ID_T id_t; // The "Convert from C to Python" API static PyObject * convert(id_t const & id){ PyObject * i = PyInt_FromLong(id.getId()); return boost::python::incref(i); } // The "Convert from Python to C" API // Two functions: convertible() and construct() static void * convertible(PyObject* obj_ptr) { if (!(PyInt_Check(obj_ptr) || PyLong_Check(obj_ptr))) return 0; return obj_ptr; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) { // Get the value. boost::uint64_t value = PyInt_AS_LONG(obj_ptr); void* storage = ((boost::python::converter::rvalue_from_python_storage<id_t>*) data)->storage.bytes; new (storage) id_t(value); // Stash the memory chunk pointer for later use by boost.python data->convertible = storage; } // The registration function. static void register_converter() { // This code checks if the type has already been registered. // http://stackoverflow.com/questions/9888289/checking-whether-a-converter-has-already-been-registered boost::python::type_info info = boost::python::type_id<id_t>(); const boost::python::converter::registration* reg = boost::python::converter::registry::query(info); if (reg == NULL || reg->m_to_python == NULL) { // This is the code to register the type. boost::python::to_python_converter<id_t,Id_python_converter>(); boost::python::converter::registry::push_back( &convertible, &construct, boost::python::type_id<id_t>()); } } }; }} #endif /* SM_PYTHON_ID_HPP */ <commit_msg>Fixed a subtle bug in the ID conversion<commit_after>#ifndef SM_PYTHON_ID_HPP #define SM_PYTHON_ID_HPP #include <numpy_eigen/boost_python_headers.hpp> #include <boost/python/to_python_converter.hpp> #include <Python.h> #include <boost/cstdint.hpp> namespace sm { namespace python { // to use: sm::python::Id_python_converter<FrameId>::register_converter(); // adapted from http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/ template<typename ID_T> struct Id_python_converter { typedef ID_T id_t; // The "Convert from C to Python" API static PyObject * convert(id_t const & id){ PyObject * i = PyInt_FromLong(id.getId()); return boost::python::incref(i); } // The "Convert from Python to C" API // Two functions: convertible() and construct() static void * convertible(PyObject* obj_ptr) { if (!(PyInt_Check(obj_ptr) || PyLong_Check(obj_ptr))) return 0; return obj_ptr; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) { // Get the value. boost::uint64_t value; if ( PyInt_Check(obj_ptr) ) { value = PyInt_AsUnsignedLongLongMask(obj_ptr); } else { value = PyLong_AsUnsignedLongLong(obj_ptr); } void* storage = ((boost::python::converter::rvalue_from_python_storage<id_t>*) data)->storage.bytes; new (storage) id_t(value); // Stash the memory chunk pointer for later use by boost.python data->convertible = storage; } // The registration function. static void register_converter() { // This code checks if the type has already been registered. // http://stackoverflow.com/questions/9888289/checking-whether-a-converter-has-already-been-registered boost::python::type_info info = boost::python::type_id<id_t>(); const boost::python::converter::registration* reg = boost::python::converter::registry::query(info); if (reg == NULL || reg->m_to_python == NULL) { // This is the code to register the type. boost::python::to_python_converter<id_t,Id_python_converter>(); boost::python::converter::registry::push_back( &convertible, &construct, boost::python::type_id<id_t>()); } } }; }} #endif /* SM_PYTHON_ID_HPP */ <|endoftext|>
<commit_before>#include <stdexcept> #include <vector> #include "all_algorithms.hpp" #include "common.hpp" #include "mkl.h" // Run a single benchmark for multiplying m x k x n with num_steps of recursion. // To just call GEMM, set num_steps to zero. // The median of five trials is printed to std::cout. // If run_check is true, then it also void SingleBenchmark(int m, int k, int n, int num_steps, int algorithm) { Matrix<double> A = RandomMatrix<double>(m, k); Matrix<double> B = RandomMatrix<double>(k, n); Matrix<double> C1(m, n); // Run a set number of trials and pick the median time. int num_trials = 5; std::vector<double> times(num_trials); for (int trial = 0; trial < num_trials; ++trial) { times[trial] = Time([&] { RunAlgorithm(algorithm, A, B, C1, num_steps); }); } // Spit out the median time std::sort(times.begin(), times.end()); size_t ind = num_trials / 2 + 1; std::cout << " " << m << " " << k << " " << n << " " << num_steps << " " << times[ind] << " " << "; "; } // Runs a set of benchmarks. void BenchmarkSet(std::vector<int>& m_vals, std::vector<int>& k_vals, std::vector<int>& n_vals, std::vector<int>& num_steps, int algorithm) { assert(m_vals.size() == k_vals.size() && k_vals.size() == n_vals.size()); for (int i = 0; i < m_vals.size(); ++i) { for (int curr_num_steps : num_steps) { std::cout << Alg2Str(algorithm) << "_" << curr_num_steps << std::endl; SingleBenchmark(m_vals[i], k_vals[i], n_vals[i], curr_num_steps, algorithm); } } std::cout << std::endl << std::endl; } // Outer product benchmark set. void OuterProductBenchmark() { std::vector<int> m_vals; for (int i = 1600; i <= 12000; i += 400) { m_vals.push_back(i); } std::vector<int> k_vals(m_vals.size(), 1600); std::vector<int> num_levels = {0}; BenchmarkSet(m_vals, k_vals, m_vals, num_levels, MKL); num_levels = {1, 2}; BenchmarkSet(m_vals, k_vals, m_vals, num_levels, STRASSEN); } void InnerSquareBenchmark() { return; } void SquareBenchmark() { return; } int main(int argc, char **argv) { auto opts = GetOpts(argc, argv); if (OptExists(opts, "square")) { SquareBenchmark(); } if (OptExists(opts, "outer_prod")) { OuterProductBenchmark(); } if (OptExists(opts, "inner_square")) { InnerSquareBenchmark(); } return 0; } <commit_msg>Re-order includes<commit_after>#include "all_algorithms.hpp" #include "common.hpp" #include "mkl.h" #include <algorithm> #include <stdexcept> #include <vector> // Run a single benchmark for multiplying m x k x n with num_steps of recursion. // To just call GEMM, set num_steps to zero. // The median of five trials is printed to std::cout. // If run_check is true, then it also void SingleBenchmark(int m, int k, int n, int num_steps, int algorithm) { Matrix<double> A = RandomMatrix<double>(m, k); Matrix<double> B = RandomMatrix<double>(k, n); Matrix<double> C1(m, n); // Run a set number of trials and pick the median time. int num_trials = 5; std::vector<double> times(num_trials); for (int trial = 0; trial < num_trials; ++trial) { times[trial] = Time([&] { RunAlgorithm(algorithm, A, B, C1, num_steps); }); } // Spit out the median time std::sort(times.begin(), times.end()); size_t ind = num_trials / 2 + 1; std::cout << " " << m << " " << k << " " << n << " " << num_steps << " " << times[ind] << " " << "; "; } // Runs a set of benchmarks. void BenchmarkSet(std::vector<int>& m_vals, std::vector<int>& k_vals, std::vector<int>& n_vals, std::vector<int>& num_steps, int algorithm) { assert(m_vals.size() == k_vals.size() && k_vals.size() == n_vals.size()); for (int i = 0; i < m_vals.size(); ++i) { for (int curr_num_steps : num_steps) { std::cout << Alg2Str(algorithm) << "_" << curr_num_steps << std::endl; SingleBenchmark(m_vals[i], k_vals[i], n_vals[i], curr_num_steps, algorithm); } } std::cout << std::endl << std::endl; } // Outer product benchmark set. void OuterProductBenchmark() { std::vector<int> m_vals; for (int i = 1600; i <= 12000; i += 400) { m_vals.push_back(i); } std::vector<int> k_vals(m_vals.size(), 1600); std::vector<int> num_levels = {0}; BenchmarkSet(m_vals, k_vals, m_vals, num_levels, MKL); num_levels = {1, 2}; BenchmarkSet(m_vals, k_vals, m_vals, num_levels, STRASSEN); } void InnerSquareBenchmark() { return; } void SquareBenchmark() { return; } int main(int argc, char **argv) { auto opts = GetOpts(argc, argv); if (OptExists(opts, "square")) { SquareBenchmark(); } if (OptExists(opts, "outer_prod")) { OuterProductBenchmark(); } if (OptExists(opts, "inner_square")) { InnerSquareBenchmark(); } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <boost/bind.hpp> #include <libport/unit-test.hh> #include <libport/path.hh> using boost::bind; using libport::path; using libport::test_suite; void path_ctor(const std::string& path, const std::string& WIN32_IF(volume, /* nothing */), bool valid) { if (valid) { BOOST_CHECK_NO_THROW(libport::path p(path)); #ifdef WIN32 libport::path p(path); BOOST_CHECK_EQUAL(p.volume_get(), volume); #endif } else BOOST_CHECK_THROW(libport::path p(path), path::invalid_path); } void path_absolute(const std::string& path, bool expected = true) { libport::path p(path); BOOST_CHECK_EQUAL(p.absolute_get(), expected); } void path_name(const std::string& spath, const std::string& dir, const std::string& base) { path path(spath); BOOST_CHECK_EQUAL(path.dirname(), dir); BOOST_CHECK_EQUAL(path.basename(), base); } void concat(const std::string& lhs, const std::string& rhs, const std::string& res) { BOOST_CHECK(path(lhs) / path(rhs) == res); } void invalid_concat(const std::string& lhs, const std::string& rhs) { BOOST_CHECK_THROW(path(lhs) / path(rhs), path::invalid_path); } void exist(const path& p, bool expected = true) { BOOST_CHECK_EQUAL(p.exists(), expected); } void create(const path& p) { // If the file exists, remove it. if (p.exists()) BOOST_CHECK(p.remove()); exist(p, false); p.create(); exist(p, true); BOOST_CHECK(p.remove()); exist(p, false); } void equal(const path& lhs, const path& rhs) { BOOST_CHECK_EQUAL(lhs, rhs); } void not_equal(const path& lhs, const path& rhs) { BOOST_CHECK_NE(lhs, rhs); } void to_string(const path& in, const std::string& out) { BOOST_CHECK_EQUAL(in.to_string(), out); } test_suite* init_test_suite() { test_suite* suite = BOOST_TEST_SUITE("libport::path test suite"); // Test constructors test_suite* ctor_suite = BOOST_TEST_SUITE("Construction test suite"); suite->add(ctor_suite); # define def(Path, Vol, Valid) \ ctor_suite->add(BOOST_TEST_CASE(bind(path_ctor, Path, Vol, Valid))); def("urbi.u", "", true); def("foo/bar.cc", "", true); def("/usr/local", "", true); def("", "", false); #ifdef WIN32 def("C:\\Documents and Settings", "C:", true); def("c:", "c:", true); def("\\\\shared_volume\\subdir", "\\\\shared_volume", true); #endif #undef def // Test absoluteness test_suite* abs_suite = BOOST_TEST_SUITE("Absolute path detection test suite"); suite->add(abs_suite); #define def(Path, Abs) \ abs_suite->add(BOOST_TEST_CASE(bind(path_absolute, Path, Abs))); def("relative", false); def("relative/with/directories", false); def("relative/with/trailing/slash/", false); def("/", true); def("/absolute", true); def("/absolute/but/longer", true); def("/absolute/with/trailing/slash/", true); def("/./still/../absolute", true); #ifdef WIN32 def("c:", false); def("C:", false); def("C:\\", true); def("C:\\absolute", true); def("C:\\absolute\\but\\on\\stupid\\OS", true); def("\\\\shared_volume\\subdir", true); #endif #undef def // Test printing. test_suite* to_string_suite = BOOST_TEST_SUITE("to_string"); suite->add(to_string_suite); # define def(In) \ to_string_suite->add(BOOST_TEST_CASE(bind(to_string, In, In))); #ifdef WIN32 def("C:\\Documents and Settings"); def("c:"); def("\\\\shared_volume\\subdir"); #else def("."); def("/"); def("urbi.u"); def("foo/bar.cc"); def("/usr/local"); #endif #undef def // Test equality operator test_suite* eq_suite = BOOST_TEST_SUITE("Comparison test suite"); suite->add(eq_suite); #define def(lhs, rhs) \ eq_suite->add(BOOST_TEST_CASE(bind(equal, lhs, rhs))); def("foo", "foo"); def("foo/bar/baz/quux", "foo/bar/baz/quux"); def("/foo/bar/baz/quux", "/foo/bar/baz/quux"); def("just/stay", "./just/././stay/./"); def("foo", "foo/"); // def("in/is/fun", // "in/and/out/../../is/fun/too/.."); def("in/and/out/../../is/fun/too/..", "in/and/out/../../is/fun/too/.."); #undef def #define def(lhs, rhs) \ eq_suite->add(BOOST_TEST_CASE(bind(not_equal, lhs, rhs))); def("foo", "/foo"); #undef def // Test basename/dirname test_suite* name_suite = BOOST_TEST_SUITE("Basename/dirname test suite"); suite->add(name_suite); #define def(path, dir, base) \ name_suite->add(BOOST_TEST_CASE(bind(path_name, path, dir, base))); def("dirname/basename", "dirname", "basename"); def("foo", ".", "foo"); def("../../bar", "../..", "bar"); def("/usr/local/gostai", "/usr/local", "gostai"); // Standard (and somehow logical) GNU coreutils behavior: def("/", "/", "/"); def(".", ".", "."); #undef def // Test concatenation test_suite* concat_suite = BOOST_TEST_SUITE("Concatenation test suite"); suite->add(concat_suite); #define def(lhs, rhs, res) \ concat_suite->add(BOOST_TEST_CASE(bind(concat, lhs, rhs, res))); def("foo", "bar", "foo/bar"); def("foo/bar", "baz/quux", "foo/bar/baz/quux"); def("foo/bar", ".", "foo/bar"); // def("foo/bar", "../..", "."); def("foo/bar", "../..", "foo/bar/../.."); def("/foo", "bar", "/foo/bar"); def("/", "foo", "/foo"); def("/", ".", "/"); #ifdef WIN32 def("\\\\share\\foo", "bar", "\\\\share\\foo\\bar"); def("c:\\", "foo", "c:\\foo"); def("c:", "bar", "c:bar"); #endif #undef def #define def(lhs, rhs) \ concat_suite->add(BOOST_TEST_CASE(bind(invalid_concat, lhs, rhs))); def("/", "/"); def("foo", "/bar"); #ifdef WIN32 def("\\\\share\\foo", "\\\\share\\bar"); def("c:", "d:"); #endif #undef def test_suite* exist_suite = BOOST_TEST_SUITE("File existence test suite"); suite->add(exist_suite); #define def(path, res) \ exist_suite->add(BOOST_TEST_CASE(bind(exist, path, res))); def("/", true); def("/this/directory/does/not/exist", false); #undef def test_suite* create_suite = BOOST_TEST_SUITE("File creation test suite"); suite->add(create_suite); #define def(path) \ create_suite->add(BOOST_TEST_CASE(bind(create, path))); def("tests/libport/creation_test"); #undef def return suite; } <commit_msg>Path: fix test under windows.<commit_after>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <boost/bind.hpp> #include <libport/unit-test.hh> #include <libport/path.hh> using boost::bind; using libport::path; using libport::test_suite; void path_ctor(const std::string& path, const std::string& WIN32_IF(volume, /* nothing */), bool valid) { if (valid) { BOOST_CHECK_NO_THROW(libport::path p(path)); #ifdef WIN32 libport::path p(path); BOOST_CHECK_EQUAL(p.volume_get(), volume); #endif } else BOOST_CHECK_THROW(libport::path p(path), path::invalid_path); } void path_absolute(const std::string& path, bool expected = true) { libport::path p(path); BOOST_CHECK_EQUAL(p.absolute_get(), expected); } void path_name(const std::string& spath, const std::string& dir, const std::string& base) { path path(spath); BOOST_CHECK_EQUAL(path.dirname(), dir); BOOST_CHECK_EQUAL(path.basename(), base); } void concat(const std::string& lhs, const std::string& rhs, const std::string& res) { BOOST_CHECK(path(lhs) / path(rhs) == res); } void invalid_concat(const std::string& lhs, const std::string& rhs) { BOOST_CHECK_THROW(path(lhs) / path(rhs), path::invalid_path); } void exist(const path& p, bool expected = true) { BOOST_CHECK_EQUAL(p.exists(), expected); } void create(const path& p) { // If the file exists, remove it. if (p.exists()) BOOST_CHECK(p.remove()); exist(p, false); p.create(); exist(p, true); BOOST_CHECK(p.remove()); exist(p, false); } void equal(const path& lhs, const path& rhs) { BOOST_CHECK_EQUAL(lhs, rhs); } void not_equal(const path& lhs, const path& rhs) { BOOST_CHECK_NE(lhs, rhs); } void to_string(const path& in, const std::string& out) { BOOST_CHECK_EQUAL(in.to_string(), out); } test_suite* init_test_suite() { test_suite* suite = BOOST_TEST_SUITE("libport::path test suite"); // Test constructors test_suite* ctor_suite = BOOST_TEST_SUITE("Construction test suite"); suite->add(ctor_suite); # define def(Path, Vol, Valid) \ ctor_suite->add(BOOST_TEST_CASE(bind(path_ctor, Path, Vol, Valid))); def("urbi.u", "", true); def("foo/bar.cc", "", true); def("/usr/local", "", true); def("", "", false); #ifdef WIN32 def("C:\\Documents and Settings", "C:", true); def("c:", "c:", true); def("\\\\shared_volume\\subdir", "\\\\shared_volume", true); #endif #undef def // Test absoluteness test_suite* abs_suite = BOOST_TEST_SUITE("Absolute path detection test suite"); suite->add(abs_suite); #define def(Path, Abs) \ abs_suite->add(BOOST_TEST_CASE(bind(path_absolute, Path, Abs))); def("relative", false); def("relative/with/directories", false); def("relative/with/trailing/slash/", false); def("/", true); def("/absolute", true); def("/absolute/but/longer", true); def("/absolute/with/trailing/slash/", true); def("/./still/../absolute", true); #ifdef WIN32 def("c:", false); def("C:", false); def("C:\\", true); def("C:\\absolute", true); def("C:\\absolute\\but\\on\\stupid\\OS", true); def("\\\\shared_volume\\subdir", true); #endif #undef def // Test printing. test_suite* to_string_suite = BOOST_TEST_SUITE("to_string"); suite->add(to_string_suite); # define def(In) \ to_string_suite->add(BOOST_TEST_CASE(bind(to_string, In, In))); #ifdef WIN32 def("C:\\Documents and Settings"); def("c:"); def("\\\\shared_volume\\subdir"); #else def("."); def("/"); def("urbi.u"); def("foo/bar.cc"); def("/usr/local"); #endif #undef def // Test equality operator test_suite* eq_suite = BOOST_TEST_SUITE("Comparison test suite"); suite->add(eq_suite); #define def(lhs, rhs) \ eq_suite->add(BOOST_TEST_CASE(bind(equal, lhs, rhs))); def("foo", "foo"); def("foo/bar/baz/quux", "foo/bar/baz/quux"); def("/foo/bar/baz/quux", "/foo/bar/baz/quux"); def("just/stay", "./just/././stay/./"); def("foo", "foo/"); // def("in/is/fun", // "in/and/out/../../is/fun/too/.."); def("in/and/out/../../is/fun/too/..", "in/and/out/../../is/fun/too/.."); #undef def #define def(lhs, rhs) \ eq_suite->add(BOOST_TEST_CASE(bind(not_equal, lhs, rhs))); def("foo", "/foo"); #undef def // Test basename/dirname test_suite* name_suite = BOOST_TEST_SUITE("Basename/dirname test suite"); suite->add(name_suite); #define def(path, dir, base) \ name_suite->add(BOOST_TEST_CASE(bind(path_name, path, dir, base))); def("dirname/basename", "dirname", "basename"); def("foo", ".", "foo"); def("../../bar", "../..", "bar"); def("/usr/local/gostai", "/usr/local", "gostai"); // Standard (and somehow logical) GNU coreutils behavior: #ifndef WIN32 def("/", "/", "/"); #else def("/", "\\", "\\"); #endif def(".", ".", "."); #undef def // Test concatenation test_suite* concat_suite = BOOST_TEST_SUITE("Concatenation test suite"); suite->add(concat_suite); #define def(lhs, rhs, res) \ concat_suite->add(BOOST_TEST_CASE(bind(concat, lhs, rhs, res))); def("foo", "bar", "foo/bar"); def("foo/bar", "baz/quux", "foo/bar/baz/quux"); def("foo/bar", ".", "foo/bar"); // def("foo/bar", "../..", "."); def("foo/bar", "../..", "foo/bar/../.."); def("/foo", "bar", "/foo/bar"); def("/", "foo", "/foo"); def("/", ".", "/"); #ifdef WIN32 def("\\\\share\\foo", "bar", "\\\\share\\foo\\bar"); def("c:\\", "foo", "c:\\foo"); def("c:", "bar", "c:bar"); #endif #undef def #define def(lhs, rhs) \ concat_suite->add(BOOST_TEST_CASE(bind(invalid_concat, lhs, rhs))); def("/", "/"); def("foo", "/bar"); #ifdef WIN32 def("\\\\share\\foo", "\\\\share\\bar"); def("c:", "d:"); #endif #undef def test_suite* exist_suite = BOOST_TEST_SUITE("File existence test suite"); suite->add(exist_suite); #define def(path, res) \ exist_suite->add(BOOST_TEST_CASE(bind(exist, path, res))); def("/", true); def("/this/directory/does/not/exist", false); #undef def test_suite* create_suite = BOOST_TEST_SUITE("File creation test suite"); suite->add(create_suite); #define def(path) \ create_suite->add(BOOST_TEST_CASE(bind(create, path))); def("tests/libport/creation_test"); #undef def return suite; } <|endoftext|>
<commit_before>/* Sirikata Transfer -- Content Transfer mediation * TransferMediator.hpp * * Copyright (c) 2010, Jeff Terrace * 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. */ /* Created on: Jan 15, 2010 */ #ifndef SIRIKATA_TransferMediator_HPP__ #define SIRIKATA_TransferMediator_HPP__ #include "SimplePriorityAggregation.hpp" #include <iostream> #include <map> #include <vector> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/identity.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/format.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/lambda/if.hpp> #include <boost/lambda/loops.hpp> #include <boost/lambda/switch.hpp> #include <boost/lambda/construct.hpp> #include <boost/lambda/casts.hpp> #include <boost/lambda/exceptions.hpp> #include <boost/lambda/algorithm.hpp> #include <boost/lambda/numeric.hpp> #include <boost/asio.hpp> #include <sirikata/core/network/IOService.hpp> #include <sirikata/core/network/Asio.hpp> #include <sirikata/core/util/Thread.hpp> #include <sirikata/core/util/Singleton.hpp> #include <sirikata/core/task/EventManager.hpp> namespace Sirikata { namespace Transfer { using namespace boost::multi_index; /* * Mediates requests for files */ class SIRIKATA_EXPORT TransferMediator : public AutoSingleton<TransferMediator>{ class AggregateRequest { public: TransferRequest::PriorityType mPriority; private: std::map<std::string, std::tr1::shared_ptr<TransferRequest> > mTransferReqs; const std::string mIdentifier; void updateAggregatePriority() { TransferRequest::PriorityType newPriority = SimplePriorityAggregation::aggregate(mTransferReqs); mPriority = newPriority; } public: const std::map<std::string, std::tr1::shared_ptr<TransferRequest> > & getTransferRequests() const { return mTransferReqs; } std::tr1::shared_ptr<TransferRequest> getSingleRequest() { std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::iterator it = mTransferReqs.begin(); return it->second; } void setClientPriority(std::tr1::shared_ptr<TransferRequest> req) { const std::string& clientID = req->getClientID();http://www.facebook.com/ std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::iterator findClient = mTransferReqs.find(clientID); if(findClient == mTransferReqs.end()) { mTransferReqs[clientID] = req; updateAggregatePriority(); } else if(findClient->second->getPriority() != req->getPriority()) { findClient->second = req; updateAggregatePriority(); } else { findClient->second = req; } } const std::string & getIdentifier() const { return mIdentifier; } TransferRequest::PriorityType getPriority() const { return mPriority; } AggregateRequest(std::tr1::shared_ptr<TransferRequest> req) : mIdentifier(req->getIdentifier()) { setClientPriority(req); } }; boost::mutex mAggMutex; //lock this to access mAggregatedList //tags struct tagID{}; struct tagPriority{}; typedef multi_index_container< std::tr1::shared_ptr<AggregateRequest>, indexed_by< hashed_unique<tag<tagID>, const_mem_fun<AggregateRequest,const std::string &,&AggregateRequest::getIdentifier> >, ordered_non_unique<tag<tagPriority>, member<AggregateRequest,TransferRequest::PriorityType,&AggregateRequest::mPriority> > > > AggregateList; AggregateList mAggregateList; //access iterators typedef AggregateList::index<tagID>::type AggregateListByID; typedef AggregateList::index<tagPriority>::type AggregateListByPriority; class PoolWorker { std::tr1::shared_ptr<TransferPool> mTransferPool; Thread * mWorkerThread; bool mCleanup; TransferMediator * mParent; public: PoolWorker(std::tr1::shared_ptr<TransferPool> transferPool, TransferMediator * parent) : mTransferPool(transferPool), mCleanup(false), mParent(parent) { mWorkerThread = new Thread(std::tr1::bind(&PoolWorker::run, this)); } PoolWorker(const PoolWorker & other) : mTransferPool(other.mTransferPool), mWorkerThread(other.mWorkerThread), mCleanup(other.mCleanup), mParent(other.mParent) { } std::tr1::shared_ptr<TransferPool> getTransferPool() const { return mTransferPool; } Thread * getThread() const { return mWorkerThread; } void cleanup() { mCleanup = true; } void run() { while(!mCleanup) { std::tr1::shared_ptr<TransferRequest> req = mTransferPool->getRequest(); if(req == NULL) { continue; } //SILOG(transfer, debug, "worker got one!"); boost::unique_lock<boost::mutex> lock(mParent->mAggMutex); AggregateListByID::iterator findID = mParent->mAggregateList.get<tagID>().find(req->getIdentifier()); //Check if this request already exists if(findID != mParent->mAggregateList.end()) { //store original aggregated priority for later TransferRequest::PriorityType oldAggPriority = (*findID)->getPriority(); //Update the priority of this client (*findID)->setClientPriority(req); //And check if it's changed, we need to update the index TransferRequest::PriorityType newAggPriority = (*findID)->getPriority(); if(oldAggPriority != newAggPriority) { using boost::lambda::_1; //Convert the iterator to the priority one and update AggregateListByPriority::iterator byPriority = mParent->mAggregateList.project<tagPriority>(findID); AggregateListByPriority & priorityIndex = mParent->mAggregateList.get<tagPriority>(); priorityIndex.modify_key(byPriority, _1=newAggPriority); } } else { //Make a new one and insert it //SILOG(transfer, debug, "worker id " << mTransferPool->getClientID() << " adding url " << req->getIdentifier()); std::tr1::shared_ptr<AggregateRequest> newAggReq(new AggregateRequest(req)); mParent->mAggregateList.insert(newAggReq); } } } }; Task::GenEventManager* mEventSystem; Network::IOService* mIOService; typedef std::map<std::string, std::tr1::shared_ptr<PoolWorker> > PoolType; PoolType mPools; boost::shared_mutex mPoolMutex; //lock this to access mPools bool mCleanup; uint32 mNumOutstanding; public: static TransferMediator& getSingleton(); static void destroy(); Thread *thread; /* * Initializes the transfer mediator with the components it needs to fulfill requests */ void initialize(Task::GenEventManager* eventSystem, Network::IOService* io) { mEventSystem = eventSystem; mIOService = io; mCleanup = false; mNumOutstanding = 0; thread = new Thread(std::tr1::bind(&TransferMediator::mediatorThread, this)); } /* * Used to register a client that has a pool of requests it needs serviced by the transfer mediator * @param clientID Should be a string that uniquely identifies the client * @param listener An EventListener to receive a TransferEventPtr with the retrieved data. */ std::tr1::shared_ptr<TransferPool> registerClient(const std::string clientID) { std::tr1::shared_ptr<TransferPool> ret(new TransferPool(clientID)); //Lock exclusive to access map boost::upgrade_lock<boost::shared_mutex> lock(mPoolMutex); boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock); //ensure client id doesnt already exist, they should be unique PoolType::iterator findClientId = mPools.find(clientID); assert(findClientId == mPools.end()); std::tr1::shared_ptr<PoolWorker> worker(new PoolWorker(ret, this)); mPools.insert(PoolType::value_type(clientID, worker)); return ret; } /* * Call when system should be shut down */ void cleanup() { mCleanup = true; } void execute_finished(std::tr1::shared_ptr<TransferRequest> req, std::string id) { boost::unique_lock<boost::mutex> lock(mAggMutex, boost::defer_lock_t()); lock.lock(); AggregateListByID& idIndex = mAggregateList.get<tagID>(); AggregateListByID::iterator findID = idIndex.find(id); if(findID == idIndex.end()) { SILOG(transfer, error, "Got a callback in TransferMediator from a TransferRequest with no associated ID"); mNumOutstanding--; lock.unlock(); return; } const std::map<std::string, std::tr1::shared_ptr<TransferRequest> >& allReqs = (*findID)->getTransferRequests(); for(std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::const_iterator it = allReqs.begin(); it != allReqs.end(); it++) { SILOG(transfer, debug, "Notifying a caller that TransferRequest is complete"); it->second->notifyCaller(req); } mAggregateList.erase(findID); mNumOutstanding--; lock.unlock(); SILOG(transfer, debug, "done transfer mediator execute_finished"); checkQueue(); } void checkQueue() { boost::unique_lock<boost::mutex> lock(mAggMutex, boost::defer_lock_t()); lock.lock(); AggregateListByPriority & priorityIndex = mAggregateList.get<tagPriority>(); AggregateListByPriority::iterator findTop = priorityIndex.begin(); if(findTop != priorityIndex.end()) { std::string topId = (*findTop)->getIdentifier(); SILOG(transfer, debug, priorityIndex.size() << " length agg list, top priority " << (*findTop)->getPriority() << " id " << topId); std::tr1::shared_ptr<TransferRequest> req = (*findTop)->getSingleRequest(); if(mNumOutstanding == 0) { mNumOutstanding++; req->execute(req, std::tr1::bind(&TransferMediator::execute_finished, this, req, topId)); } } else { //SILOG(transfer, debug, priorityIndex.size() << " length agg list"); } lock.unlock(); } /* * Main thread that handles the input pools */ void mediatorThread() { while(!mCleanup) { checkQueue(); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); } for(PoolType::iterator pool = mPools.begin(); pool != mPools.end(); pool++) { pool->second->cleanup(); pool->second->getTransferPool()->addRequest(std::tr1::shared_ptr<TransferRequest>()); } for(PoolType::iterator pool = mPools.begin(); pool != mPools.end(); pool++) { pool->second->getThread()->join(); } } }; } } #endif /* SIRIKATA_TransferMediator_HPP__ */ <commit_msg>Remove accidental url-based label and comment.<commit_after>/* Sirikata Transfer -- Content Transfer mediation * TransferMediator.hpp * * Copyright (c) 2010, Jeff Terrace * 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. */ /* Created on: Jan 15, 2010 */ #ifndef SIRIKATA_TransferMediator_HPP__ #define SIRIKATA_TransferMediator_HPP__ #include "SimplePriorityAggregation.hpp" #include <iostream> #include <map> #include <vector> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/identity.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/format.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/lambda/if.hpp> #include <boost/lambda/loops.hpp> #include <boost/lambda/switch.hpp> #include <boost/lambda/construct.hpp> #include <boost/lambda/casts.hpp> #include <boost/lambda/exceptions.hpp> #include <boost/lambda/algorithm.hpp> #include <boost/lambda/numeric.hpp> #include <boost/asio.hpp> #include <sirikata/core/network/IOService.hpp> #include <sirikata/core/network/Asio.hpp> #include <sirikata/core/util/Thread.hpp> #include <sirikata/core/util/Singleton.hpp> #include <sirikata/core/task/EventManager.hpp> namespace Sirikata { namespace Transfer { using namespace boost::multi_index; /* * Mediates requests for files */ class SIRIKATA_EXPORT TransferMediator : public AutoSingleton<TransferMediator>{ class AggregateRequest { public: TransferRequest::PriorityType mPriority; private: std::map<std::string, std::tr1::shared_ptr<TransferRequest> > mTransferReqs; const std::string mIdentifier; void updateAggregatePriority() { TransferRequest::PriorityType newPriority = SimplePriorityAggregation::aggregate(mTransferReqs); mPriority = newPriority; } public: const std::map<std::string, std::tr1::shared_ptr<TransferRequest> > & getTransferRequests() const { return mTransferReqs; } std::tr1::shared_ptr<TransferRequest> getSingleRequest() { std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::iterator it = mTransferReqs.begin(); return it->second; } void setClientPriority(std::tr1::shared_ptr<TransferRequest> req) { const std::string& clientID = req->getClientID(); std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::iterator findClient = mTransferReqs.find(clientID); if(findClient == mTransferReqs.end()) { mTransferReqs[clientID] = req; updateAggregatePriority(); } else if(findClient->second->getPriority() != req->getPriority()) { findClient->second = req; updateAggregatePriority(); } else { findClient->second = req; } } const std::string & getIdentifier() const { return mIdentifier; } TransferRequest::PriorityType getPriority() const { return mPriority; } AggregateRequest(std::tr1::shared_ptr<TransferRequest> req) : mIdentifier(req->getIdentifier()) { setClientPriority(req); } }; boost::mutex mAggMutex; //lock this to access mAggregatedList //tags struct tagID{}; struct tagPriority{}; typedef multi_index_container< std::tr1::shared_ptr<AggregateRequest>, indexed_by< hashed_unique<tag<tagID>, const_mem_fun<AggregateRequest,const std::string &,&AggregateRequest::getIdentifier> >, ordered_non_unique<tag<tagPriority>, member<AggregateRequest,TransferRequest::PriorityType,&AggregateRequest::mPriority> > > > AggregateList; AggregateList mAggregateList; //access iterators typedef AggregateList::index<tagID>::type AggregateListByID; typedef AggregateList::index<tagPriority>::type AggregateListByPriority; class PoolWorker { std::tr1::shared_ptr<TransferPool> mTransferPool; Thread * mWorkerThread; bool mCleanup; TransferMediator * mParent; public: PoolWorker(std::tr1::shared_ptr<TransferPool> transferPool, TransferMediator * parent) : mTransferPool(transferPool), mCleanup(false), mParent(parent) { mWorkerThread = new Thread(std::tr1::bind(&PoolWorker::run, this)); } PoolWorker(const PoolWorker & other) : mTransferPool(other.mTransferPool), mWorkerThread(other.mWorkerThread), mCleanup(other.mCleanup), mParent(other.mParent) { } std::tr1::shared_ptr<TransferPool> getTransferPool() const { return mTransferPool; } Thread * getThread() const { return mWorkerThread; } void cleanup() { mCleanup = true; } void run() { while(!mCleanup) { std::tr1::shared_ptr<TransferRequest> req = mTransferPool->getRequest(); if(req == NULL) { continue; } //SILOG(transfer, debug, "worker got one!"); boost::unique_lock<boost::mutex> lock(mParent->mAggMutex); AggregateListByID::iterator findID = mParent->mAggregateList.get<tagID>().find(req->getIdentifier()); //Check if this request already exists if(findID != mParent->mAggregateList.end()) { //store original aggregated priority for later TransferRequest::PriorityType oldAggPriority = (*findID)->getPriority(); //Update the priority of this client (*findID)->setClientPriority(req); //And check if it's changed, we need to update the index TransferRequest::PriorityType newAggPriority = (*findID)->getPriority(); if(oldAggPriority != newAggPriority) { using boost::lambda::_1; //Convert the iterator to the priority one and update AggregateListByPriority::iterator byPriority = mParent->mAggregateList.project<tagPriority>(findID); AggregateListByPriority & priorityIndex = mParent->mAggregateList.get<tagPriority>(); priorityIndex.modify_key(byPriority, _1=newAggPriority); } } else { //Make a new one and insert it //SILOG(transfer, debug, "worker id " << mTransferPool->getClientID() << " adding url " << req->getIdentifier()); std::tr1::shared_ptr<AggregateRequest> newAggReq(new AggregateRequest(req)); mParent->mAggregateList.insert(newAggReq); } } } }; Task::GenEventManager* mEventSystem; Network::IOService* mIOService; typedef std::map<std::string, std::tr1::shared_ptr<PoolWorker> > PoolType; PoolType mPools; boost::shared_mutex mPoolMutex; //lock this to access mPools bool mCleanup; uint32 mNumOutstanding; public: static TransferMediator& getSingleton(); static void destroy(); Thread *thread; /* * Initializes the transfer mediator with the components it needs to fulfill requests */ void initialize(Task::GenEventManager* eventSystem, Network::IOService* io) { mEventSystem = eventSystem; mIOService = io; mCleanup = false; mNumOutstanding = 0; thread = new Thread(std::tr1::bind(&TransferMediator::mediatorThread, this)); } /* * Used to register a client that has a pool of requests it needs serviced by the transfer mediator * @param clientID Should be a string that uniquely identifies the client * @param listener An EventListener to receive a TransferEventPtr with the retrieved data. */ std::tr1::shared_ptr<TransferPool> registerClient(const std::string clientID) { std::tr1::shared_ptr<TransferPool> ret(new TransferPool(clientID)); //Lock exclusive to access map boost::upgrade_lock<boost::shared_mutex> lock(mPoolMutex); boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock); //ensure client id doesnt already exist, they should be unique PoolType::iterator findClientId = mPools.find(clientID); assert(findClientId == mPools.end()); std::tr1::shared_ptr<PoolWorker> worker(new PoolWorker(ret, this)); mPools.insert(PoolType::value_type(clientID, worker)); return ret; } /* * Call when system should be shut down */ void cleanup() { mCleanup = true; } void execute_finished(std::tr1::shared_ptr<TransferRequest> req, std::string id) { boost::unique_lock<boost::mutex> lock(mAggMutex, boost::defer_lock_t()); lock.lock(); AggregateListByID& idIndex = mAggregateList.get<tagID>(); AggregateListByID::iterator findID = idIndex.find(id); if(findID == idIndex.end()) { SILOG(transfer, error, "Got a callback in TransferMediator from a TransferRequest with no associated ID"); mNumOutstanding--; lock.unlock(); return; } const std::map<std::string, std::tr1::shared_ptr<TransferRequest> >& allReqs = (*findID)->getTransferRequests(); for(std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::const_iterator it = allReqs.begin(); it != allReqs.end(); it++) { SILOG(transfer, debug, "Notifying a caller that TransferRequest is complete"); it->second->notifyCaller(req); } mAggregateList.erase(findID); mNumOutstanding--; lock.unlock(); SILOG(transfer, debug, "done transfer mediator execute_finished"); checkQueue(); } void checkQueue() { boost::unique_lock<boost::mutex> lock(mAggMutex, boost::defer_lock_t()); lock.lock(); AggregateListByPriority & priorityIndex = mAggregateList.get<tagPriority>(); AggregateListByPriority::iterator findTop = priorityIndex.begin(); if(findTop != priorityIndex.end()) { std::string topId = (*findTop)->getIdentifier(); SILOG(transfer, debug, priorityIndex.size() << " length agg list, top priority " << (*findTop)->getPriority() << " id " << topId); std::tr1::shared_ptr<TransferRequest> req = (*findTop)->getSingleRequest(); if(mNumOutstanding == 0) { mNumOutstanding++; req->execute(req, std::tr1::bind(&TransferMediator::execute_finished, this, req, topId)); } } else { //SILOG(transfer, debug, priorityIndex.size() << " length agg list"); } lock.unlock(); } /* * Main thread that handles the input pools */ void mediatorThread() { while(!mCleanup) { checkQueue(); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); } for(PoolType::iterator pool = mPools.begin(); pool != mPools.end(); pool++) { pool->second->cleanup(); pool->second->getTransferPool()->addRequest(std::tr1::shared_ptr<TransferRequest>()); } for(PoolType::iterator pool = mPools.begin(); pool != mPools.end(); pool++) { pool->second->getThread()->join(); } } }; } } #endif /* SIRIKATA_TransferMediator_HPP__ */ <|endoftext|>
<commit_before>/* * Copyright (C) 2013-2016 Alexander Saprykin <xelfium@gmail.com> * * 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. */ #ifndef PLIB_TESTS_STATIC # define BOOST_TEST_DYN_LINK #endif #define BOOST_TEST_MODULE pmutex_test #include "plib.h" #ifdef PLIB_TESTS_STATIC # include <boost/test/included/unit_test.hpp> #else # include <boost/test/unit_test.hpp> #endif static pint mutex_test_val = 10; static PMutex *global_mutex = NULL; static void * mutex_test_thread (void *) { pint i; for (i = 0; i < 1000; ++i) { if (!p_mutex_trylock (global_mutex)) { if (!p_mutex_lock (global_mutex)) p_uthread_exit (1); } if (mutex_test_val == 10) --mutex_test_val; else { p_uthread_sleep (1); ++mutex_test_val; } if (!p_mutex_unlock (global_mutex)) p_uthread_exit (1); } p_uthread_exit (0); } BOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE) BOOST_AUTO_TEST_CASE (pmutex_general_test) { PUThread *thr1, *thr2; p_lib_init (); BOOST_REQUIRE (p_mutex_lock (global_mutex) == FALSE); BOOST_REQUIRE (p_mutex_unlock (global_mutex) == FALSE); BOOST_REQUIRE (p_mutex_trylock (global_mutex) == FALSE); p_mutex_free (global_mutex); mutex_test_val = 10; global_mutex = p_mutex_new (); BOOST_REQUIRE (global_mutex != NULL); thr1 = p_uthread_create ((PUThreadFunc) mutex_test_thread, NULL, true); BOOST_REQUIRE (thr1 != NULL); thr2 = p_uthread_create ((PUThreadFunc) mutex_test_thread, NULL, true); BOOST_REQUIRE (thr2 != NULL); BOOST_CHECK (p_uthread_join (thr1) == 0); BOOST_CHECK (p_uthread_join (thr2) == 0); BOOST_REQUIRE (mutex_test_val == 10); p_uthread_free (thr1); p_uthread_free (thr2); p_mutex_free (global_mutex); p_lib_shutdown (); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>tests: Add out of memory checks for PMutex<commit_after>/* * Copyright (C) 2013-2016 Alexander Saprykin <xelfium@gmail.com> * * 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. */ #ifndef PLIB_TESTS_STATIC # define BOOST_TEST_DYN_LINK #endif #define BOOST_TEST_MODULE pmutex_test #include "plib.h" #ifdef PLIB_TESTS_STATIC # include <boost/test/included/unit_test.hpp> #else # include <boost/test/unit_test.hpp> #endif static pint mutex_test_val = 10; static PMutex *global_mutex = NULL; extern "C" ppointer pmem_alloc (psize nbytes) { P_UNUSED (nbytes); return (ppointer) NULL; } extern "C" ppointer pmem_realloc (ppointer block, psize nbytes) { P_UNUSED (block); P_UNUSED (nbytes); return (ppointer) NULL; } extern "C" void pmem_free (ppointer block) { P_UNUSED (block); } static void * mutex_test_thread (void *) { pint i; for (i = 0; i < 1000; ++i) { if (!p_mutex_trylock (global_mutex)) { if (!p_mutex_lock (global_mutex)) p_uthread_exit (1); } if (mutex_test_val == 10) --mutex_test_val; else { p_uthread_sleep (1); ++mutex_test_val; } if (!p_mutex_unlock (global_mutex)) p_uthread_exit (1); } p_uthread_exit (0); } BOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE) BOOST_AUTO_TEST_CASE (pmutex_nomem_test) { p_lib_init (); PMemVTable vtable; vtable.free = pmem_free; vtable.malloc = pmem_alloc; vtable.realloc = pmem_realloc; BOOST_CHECK (p_mem_set_vtable (&vtable) == TRUE); BOOST_CHECK (p_mutex_new () == NULL); vtable.malloc = (ppointer (*)(psize)) malloc; vtable.realloc = (ppointer (*)(ppointer, psize)) realloc; vtable.free = (void (*)(ppointer)) free; BOOST_CHECK (p_mem_set_vtable (&vtable) == TRUE); p_lib_shutdown (); } BOOST_AUTO_TEST_CASE (pmutex_general_test) { PUThread *thr1, *thr2; p_lib_init (); BOOST_REQUIRE (p_mutex_lock (global_mutex) == FALSE); BOOST_REQUIRE (p_mutex_unlock (global_mutex) == FALSE); BOOST_REQUIRE (p_mutex_trylock (global_mutex) == FALSE); p_mutex_free (global_mutex); mutex_test_val = 10; global_mutex = p_mutex_new (); BOOST_REQUIRE (global_mutex != NULL); thr1 = p_uthread_create ((PUThreadFunc) mutex_test_thread, NULL, true); BOOST_REQUIRE (thr1 != NULL); thr2 = p_uthread_create ((PUThreadFunc) mutex_test_thread, NULL, true); BOOST_REQUIRE (thr2 != NULL); BOOST_CHECK (p_uthread_join (thr1) == 0); BOOST_CHECK (p_uthread_join (thr2) == 0); BOOST_REQUIRE (mutex_test_val == 10); p_uthread_free (thr1); p_uthread_free (thr2); p_mutex_free (global_mutex); p_lib_shutdown (); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* Copyright (c) 2013, Taiga Nomi 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 <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include "tiny_cnn/tiny_cnn.h" using namespace tiny_cnn; using namespace tiny_cnn::activation; void construct_net(network<sequential>& nn) { // connection table [Y.Lecun, 1998 Table.1] #define O true #define X false static const bool tbl[] = { O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O, O, X, X, X, O, O, O, X, X, O, X, O, O, O, X, O, O, O, X, X, O, O, O, O, X, X, O, X, O, O, X, X, O, O, O, X, X, O, O, O, O, X, O, O, X, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O }; #undef O #undef X // construct nets nn << deconvolutional_layer<tan_h>(32, 32, 5, 1, 6) // D1, 1@32x32-in, 6@28x28-out << average_pooling_layer<tan_h>(28, 28, 6, 2) // S2, 6@28x28-in, 6@14x14-out << average_unpooling_layer<tan_h>(14, 14, 6, 2) // U3, 6@14x14-in, 6@28x28-out << average_pooling_layer<tan_h>(28, 28, 6, 2) // S4, 6@28x28-in, 6@14x14-out << deconvolutional_layer<tan_h>(14, 14, 5, 6, 16, connection_table(tbl, 6, 16)) // D5, 6@14x14-in, 16@18x18-out << average_pooling_layer<tan_h>(18, 18, 16, 2) // S6, 16@18x18-in, 16@9x9-out << deconvolutional_layer<tan_h>(9, 9, 9, 16, 120) // D7, 16@9x9-in, 120@1x1-out << fully_connected_layer<tan_h>(120, 10); // F8, 120-in, 10-out } void train_lenet(std::string data_dir_path) { // specify loss-function and learning strategy network<sequential> nn; adagrad optimizer; construct_net(nn); std::cout << "load models..." << std::endl; // load MNIST dataset std::vector<label_t> train_labels, test_labels; std::vector<vec_t> train_images, test_images; parse_mnist_labels(data_dir_path+"/train-labels.idx1-ubyte", &train_labels); parse_mnist_images(data_dir_path+"/train-images.idx3-ubyte", &train_images, -1.0, 1.0, 2, 2); parse_mnist_labels(data_dir_path+"/t10k-labels.idx1-ubyte", &test_labels); parse_mnist_images(data_dir_path+"/t10k-images.idx3-ubyte", &test_images, -1.0, 1.0, 2, 2); std::cout << "start training" << std::endl; progress_display disp(train_images.size()); timer t; int minibatch_size = 10; int num_epochs = 30; optimizer.alpha *= std::sqrt(minibatch_size); // create callback auto on_enumerate_epoch = [&](){ std::cout << t.elapsed() << "s elapsed." << std::endl; tiny_cnn::result res = nn.test(test_images, test_labels); std::cout << res.num_success << "/" << res.num_total << std::endl; disp.restart(train_images.size()); t.restart(); }; auto on_enumerate_minibatch = [&](){ disp += minibatch_size; }; // training nn.train<mse>(optimizer, train_images, train_labels, minibatch_size, num_epochs, on_enumerate_minibatch, on_enumerate_epoch); std::cout << "end training." << std::endl; // test and show results nn.test(test_images, test_labels).print_detail(std::cout); // save networks std::ofstream ofs("LeNet-weights"); ofs << nn; } int main(int argc, char **argv) { if (argc != 2) { std::cerr << "Usage : " << argv[0] << " path_to_data (example:../data)" << std::endl; return -1; } train_lenet(argv[1]); } <commit_msg>modify example<commit_after>/* Copyright (c) 2013, Taiga Nomi 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 <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include "tiny_cnn/tiny_cnn.h" using namespace tiny_cnn; using namespace tiny_cnn::activation; void construct_net(network<sequential>& nn) { // connection table [Y.Lecun, 1998 Table.1] #define O true #define X false static const bool tbl[] = { O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O, O, X, X, X, O, O, O, X, X, O, X, O, O, O, X, O, O, O, X, X, O, O, O, O, X, X, O, X, O, O, X, X, O, O, O, X, X, O, O, O, O, X, O, O, X, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O }; #undef O #undef X // construct nets nn << convolutional_layer<tan_h>(32, 32, 5, 1, 6) // D1, 1@32x32-in, 6@28x28-out << average_pooling_layer<tan_h>(28, 28, 6, 2) // S2, 6@28x28-in, 6@14x14-out << average_unpooling_layer<tan_h>(14, 14, 6, 2) // U3, 6@14x14-in, 6@28x28-out << average_pooling_layer<tan_h>(28, 28, 6, 2) // S4, 6@28x28-in, 6@14x14-out << deconvolutional_layer<tan_h>(14, 14, 5, 6, 16, connection_table(tbl, 6, 16)) // D5, 6@14x14-in, 16@18x18-out << average_pooling_layer<tan_h>(18, 18, 16, 2) // S6, 16@18x18-in, 16@9x9-out << convolutional_layer<tan_h>(9, 9, 9, 16, 120) // D7, 16@9x9-in, 120@1x1-out << fully_connected_layer<tan_h>(120, 10); // F8, 120-in, 10-out } void train_lenet(std::string data_dir_path) { // specify loss-function and learning strategy network<sequential> nn; adagrad optimizer; construct_net(nn); std::cout << "load models..." << std::endl; // load MNIST dataset std::vector<label_t> train_labels, test_labels; std::vector<vec_t> train_images, test_images; parse_mnist_labels(data_dir_path+"/train-labels.idx1-ubyte", &train_labels); parse_mnist_images(data_dir_path+"/train-images.idx3-ubyte", &train_images, -1.0, 1.0, 2, 2); parse_mnist_labels(data_dir_path+"/t10k-labels.idx1-ubyte", &test_labels); parse_mnist_images(data_dir_path+"/t10k-images.idx3-ubyte", &test_images, -1.0, 1.0, 2, 2); std::cout << "start training" << std::endl; progress_display disp(train_images.size()); timer t; int minibatch_size = 10; int num_epochs = 30; optimizer.alpha *= std::sqrt(minibatch_size); // create callback auto on_enumerate_epoch = [&](){ std::cout << t.elapsed() << "s elapsed." << std::endl; tiny_cnn::result res = nn.test(test_images, test_labels); std::cout << res.num_success << "/" << res.num_total << std::endl; disp.restart(train_images.size()); t.restart(); }; auto on_enumerate_minibatch = [&](){ disp += minibatch_size; }; // training nn.train<mse>(optimizer, train_images, train_labels, minibatch_size, num_epochs, on_enumerate_minibatch, on_enumerate_epoch); std::cout << "end training." << std::endl; // test and show results nn.test(test_images, test_labels).print_detail(std::cout); // save networks std::ofstream ofs("LeNet-weights"); ofs << nn; } int main(int argc, char **argv) { if (argc != 2) { std::cerr << "Usage : " << argv[0] << " path_to_data (example:../data)" << std::endl; return -1; } train_lenet(argv[1]); } <|endoftext|>
<commit_before>// -*- c-basic-offset: 2 -*- /* * This file is part of the KDE libraries * Copyright (C) 1999-2001 Harri Porten (porten@kde.org) * Copyright (C) 2001 Peter Kelly (pmk@post.com) * Copyright (C) 2003 Apple Computer, Inc. * * 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 Steet, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "interpreter.h" #include <assert.h> #include <math.h> #include <stdio.h> #include "collector.h" #include "context.h" #include "error_object.h" #include "internal.h" #include "nodes.h" #include "object.h" #include "operations.h" #include "runtime.h" #include "types.h" #include "value.h" namespace KJS { // ------------------------------ Context -------------------------------------- const ScopeChain &Context::scopeChain() const { return rep->scopeChain(); } JSObject *Context::variableObject() const { return rep->variableObject(); } JSObject *Context::thisValue() const { return rep->thisValue(); } const Context Context::callingContext() const { return rep->callingContext(); } // ------------------------------ Interpreter ---------------------------------- Interpreter::Interpreter(JSObject *global) : rep(0) , m_argumentsPropertyName(&argumentsPropertyName) , m_specialPrototypePropertyName(&specialPrototypePropertyName) { rep = new InterpreterImp(this, global); } Interpreter::Interpreter() : rep(0) , m_argumentsPropertyName(&argumentsPropertyName) , m_specialPrototypePropertyName(&specialPrototypePropertyName) { rep = new InterpreterImp(this, new JSObject); } Interpreter::~Interpreter() { delete rep; } JSObject *Interpreter::globalObject() const { return rep->globalObject(); } void Interpreter::initGlobalObject() { rep->initGlobalObject(); } ExecState *Interpreter::globalExec() { return rep->globalExec(); } bool Interpreter::checkSyntax(const UString &code) { return rep->checkSyntax(code); } Completion Interpreter::evaluate(const UString& sourceURL, int startingLineNumber, const UString& code, JSValue* thisV) { return evaluate(sourceURL, startingLineNumber, code.data(), code.size()); } Completion Interpreter::evaluate(const UString& sourceURL, int startingLineNumber, const UChar* code, int codeLength, JSValue* thisV) { Completion comp = rep->evaluate(code, codeLength, thisV, sourceURL, startingLineNumber); if (shouldPrintExceptions() && comp.complType() == Throw) { JSLock lock; ExecState *exec = rep->globalExec(); CString f = sourceURL.UTF8String(); CString message = comp.value()->toObject(exec)->toString(exec).UTF8String(); #ifdef WIN32 printf("%s:%s\n", f.c_str(), message.c_str()); #else printf("[%d] %s:%s\n", getpid(), f.c_str(), message.c_str()); #endif } return comp; } JSObject *Interpreter::builtinObject() const { return rep->builtinObject(); } JSObject *Interpreter::builtinFunction() const { return rep->builtinFunction(); } JSObject *Interpreter::builtinArray() const { return rep->builtinArray(); } JSObject *Interpreter::builtinBoolean() const { return rep->builtinBoolean(); } JSObject *Interpreter::builtinString() const { return rep->builtinString(); } JSObject *Interpreter::builtinNumber() const { return rep->builtinNumber(); } JSObject *Interpreter::builtinDate() const { return rep->builtinDate(); } JSObject *Interpreter::builtinRegExp() const { return rep->builtinRegExp(); } JSObject *Interpreter::builtinError() const { return rep->builtinError(); } JSObject *Interpreter::builtinObjectPrototype() const { return rep->builtinObjectPrototype(); } JSObject *Interpreter::builtinFunctionPrototype() const { return rep->builtinFunctionPrototype(); } JSObject *Interpreter::builtinArrayPrototype() const { return rep->builtinArrayPrototype(); } JSObject *Interpreter::builtinBooleanPrototype() const { return rep->builtinBooleanPrototype(); } JSObject *Interpreter::builtinStringPrototype() const { return rep->builtinStringPrototype(); } JSObject *Interpreter::builtinNumberPrototype() const { return rep->builtinNumberPrototype(); } JSObject *Interpreter::builtinDatePrototype() const { return rep->builtinDatePrototype(); } JSObject *Interpreter::builtinRegExpPrototype() const { return rep->builtinRegExpPrototype(); } JSObject *Interpreter::builtinErrorPrototype() const { return rep->builtinErrorPrototype(); } JSObject *Interpreter::builtinEvalError() const { return rep->builtinEvalError(); } JSObject *Interpreter::builtinRangeError() const { return rep->builtinRangeError(); } JSObject *Interpreter::builtinReferenceError() const { return rep->builtinReferenceError(); } JSObject *Interpreter::builtinSyntaxError() const { return rep->builtinSyntaxError(); } JSObject *Interpreter::builtinTypeError() const { return rep->builtinTypeError(); } JSObject *Interpreter::builtinURIError() const { return rep->builtinURIError(); } JSObject *Interpreter::builtinEvalErrorPrototype() const { return rep->builtinEvalErrorPrototype(); } JSObject *Interpreter::builtinRangeErrorPrototype() const { return rep->builtinRangeErrorPrototype(); } JSObject *Interpreter::builtinReferenceErrorPrototype() const { return rep->builtinReferenceErrorPrototype(); } JSObject *Interpreter::builtinSyntaxErrorPrototype() const { return rep->builtinSyntaxErrorPrototype(); } JSObject *Interpreter::builtinTypeErrorPrototype() const { return rep->builtinTypeErrorPrototype(); } JSObject *Interpreter::builtinURIErrorPrototype() const { return rep->builtinURIErrorPrototype(); } void Interpreter::setCompatMode(CompatMode mode) { rep->setCompatMode(mode); } Interpreter::CompatMode Interpreter::compatMode() const { return rep->compatMode(); } bool Interpreter::collect() { return Collector::collect(); } #ifdef KJS_DEBUG_MEM #include "lexer.h" void Interpreter::finalCheck() { fprintf(stderr,"Interpreter::finalCheck()\n"); Collector::collect(); Node::finalCheck(); Collector::finalCheck(); Lexer::globalClear(); UString::globalClear(); } #endif static bool printExceptions = false; bool Interpreter::shouldPrintExceptions() { return printExceptions; } void Interpreter::setShouldPrintExceptions(bool print) { printExceptions = print; } #if __APPLE__ void *Interpreter::createLanguageInstanceForValue(ExecState *exec, int language, JSObject *value, const Bindings::RootObject *origin, const Bindings::RootObject *current) { return Bindings::Instance::createLanguageInstanceForValue (exec, (Bindings::Instance::BindingLanguage)language, value, origin, current); } #endif void Interpreter::saveBuiltins (SavedBuiltins &builtins) const { rep->saveBuiltins(builtins); } void Interpreter::restoreBuiltins (const SavedBuiltins &builtins) { rep->restoreBuiltins(builtins); } SavedBuiltins::SavedBuiltins() : _internal(0) { } SavedBuiltins::~SavedBuiltins() { delete _internal; } void Interpreter::virtual_hook( int, void* ) { /*BASE::virtual_hook( id, data );*/ } Interpreter *ExecState::lexicalInterpreter() const { if (!_context) { return dynamicInterpreter(); } InterpreterImp *result = InterpreterImp::interpreterWithGlobalObject(_context->scopeChain().bottom()); if (!result) { return dynamicInterpreter(); } return result->interpreter(); } } <commit_msg>Fix win32 build bustage in interpreter.cpp<commit_after>// -*- c-basic-offset: 2 -*- /* * This file is part of the KDE libraries * Copyright (C) 1999-2001 Harri Porten (porten@kde.org) * Copyright (C) 2001 Peter Kelly (pmk@post.com) * Copyright (C) 2003 Apple Computer, Inc. * * 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 Steet, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "interpreter.h" #include <assert.h> #include <math.h> #include <stdio.h> #include "collector.h" #include "context.h" #include "error_object.h" #include "internal.h" #include "nodes.h" #include "object.h" #include "operations.h" #if !WIN32 #include "runtime.h" #endif #include "types.h" #include "value.h" namespace KJS { // ------------------------------ Context -------------------------------------- const ScopeChain &Context::scopeChain() const { return rep->scopeChain(); } JSObject *Context::variableObject() const { return rep->variableObject(); } JSObject *Context::thisValue() const { return rep->thisValue(); } const Context Context::callingContext() const { return rep->callingContext(); } // ------------------------------ Interpreter ---------------------------------- Interpreter::Interpreter(JSObject *global) : rep(0) , m_argumentsPropertyName(&argumentsPropertyName) , m_specialPrototypePropertyName(&specialPrototypePropertyName) { rep = new InterpreterImp(this, global); } Interpreter::Interpreter() : rep(0) , m_argumentsPropertyName(&argumentsPropertyName) , m_specialPrototypePropertyName(&specialPrototypePropertyName) { rep = new InterpreterImp(this, new JSObject); } Interpreter::~Interpreter() { delete rep; } JSObject *Interpreter::globalObject() const { return rep->globalObject(); } void Interpreter::initGlobalObject() { rep->initGlobalObject(); } ExecState *Interpreter::globalExec() { return rep->globalExec(); } bool Interpreter::checkSyntax(const UString &code) { return rep->checkSyntax(code); } Completion Interpreter::evaluate(const UString& sourceURL, int startingLineNumber, const UString& code, JSValue* thisV) { return evaluate(sourceURL, startingLineNumber, code.data(), code.size()); } Completion Interpreter::evaluate(const UString& sourceURL, int startingLineNumber, const UChar* code, int codeLength, JSValue* thisV) { Completion comp = rep->evaluate(code, codeLength, thisV, sourceURL, startingLineNumber); if (shouldPrintExceptions() && comp.complType() == Throw) { JSLock lock; ExecState *exec = rep->globalExec(); CString f = sourceURL.UTF8String(); CString message = comp.value()->toObject(exec)->toString(exec).UTF8String(); #ifdef WIN32 printf("%s:%s\n", f.c_str(), message.c_str()); #else printf("[%d] %s:%s\n", getpid(), f.c_str(), message.c_str()); #endif } return comp; } JSObject *Interpreter::builtinObject() const { return rep->builtinObject(); } JSObject *Interpreter::builtinFunction() const { return rep->builtinFunction(); } JSObject *Interpreter::builtinArray() const { return rep->builtinArray(); } JSObject *Interpreter::builtinBoolean() const { return rep->builtinBoolean(); } JSObject *Interpreter::builtinString() const { return rep->builtinString(); } JSObject *Interpreter::builtinNumber() const { return rep->builtinNumber(); } JSObject *Interpreter::builtinDate() const { return rep->builtinDate(); } JSObject *Interpreter::builtinRegExp() const { return rep->builtinRegExp(); } JSObject *Interpreter::builtinError() const { return rep->builtinError(); } JSObject *Interpreter::builtinObjectPrototype() const { return rep->builtinObjectPrototype(); } JSObject *Interpreter::builtinFunctionPrototype() const { return rep->builtinFunctionPrototype(); } JSObject *Interpreter::builtinArrayPrototype() const { return rep->builtinArrayPrototype(); } JSObject *Interpreter::builtinBooleanPrototype() const { return rep->builtinBooleanPrototype(); } JSObject *Interpreter::builtinStringPrototype() const { return rep->builtinStringPrototype(); } JSObject *Interpreter::builtinNumberPrototype() const { return rep->builtinNumberPrototype(); } JSObject *Interpreter::builtinDatePrototype() const { return rep->builtinDatePrototype(); } JSObject *Interpreter::builtinRegExpPrototype() const { return rep->builtinRegExpPrototype(); } JSObject *Interpreter::builtinErrorPrototype() const { return rep->builtinErrorPrototype(); } JSObject *Interpreter::builtinEvalError() const { return rep->builtinEvalError(); } JSObject *Interpreter::builtinRangeError() const { return rep->builtinRangeError(); } JSObject *Interpreter::builtinReferenceError() const { return rep->builtinReferenceError(); } JSObject *Interpreter::builtinSyntaxError() const { return rep->builtinSyntaxError(); } JSObject *Interpreter::builtinTypeError() const { return rep->builtinTypeError(); } JSObject *Interpreter::builtinURIError() const { return rep->builtinURIError(); } JSObject *Interpreter::builtinEvalErrorPrototype() const { return rep->builtinEvalErrorPrototype(); } JSObject *Interpreter::builtinRangeErrorPrototype() const { return rep->builtinRangeErrorPrototype(); } JSObject *Interpreter::builtinReferenceErrorPrototype() const { return rep->builtinReferenceErrorPrototype(); } JSObject *Interpreter::builtinSyntaxErrorPrototype() const { return rep->builtinSyntaxErrorPrototype(); } JSObject *Interpreter::builtinTypeErrorPrototype() const { return rep->builtinTypeErrorPrototype(); } JSObject *Interpreter::builtinURIErrorPrototype() const { return rep->builtinURIErrorPrototype(); } void Interpreter::setCompatMode(CompatMode mode) { rep->setCompatMode(mode); } Interpreter::CompatMode Interpreter::compatMode() const { return rep->compatMode(); } bool Interpreter::collect() { return Collector::collect(); } #ifdef KJS_DEBUG_MEM #include "lexer.h" void Interpreter::finalCheck() { fprintf(stderr,"Interpreter::finalCheck()\n"); Collector::collect(); Node::finalCheck(); Collector::finalCheck(); Lexer::globalClear(); UString::globalClear(); } #endif static bool printExceptions = false; bool Interpreter::shouldPrintExceptions() { return printExceptions; } void Interpreter::setShouldPrintExceptions(bool print) { printExceptions = print; } #if __APPLE__ void *Interpreter::createLanguageInstanceForValue(ExecState *exec, int language, JSObject *value, const Bindings::RootObject *origin, const Bindings::RootObject *current) { return Bindings::Instance::createLanguageInstanceForValue (exec, (Bindings::Instance::BindingLanguage)language, value, origin, current); } #endif void Interpreter::saveBuiltins (SavedBuiltins &builtins) const { rep->saveBuiltins(builtins); } void Interpreter::restoreBuiltins (const SavedBuiltins &builtins) { rep->restoreBuiltins(builtins); } SavedBuiltins::SavedBuiltins() : _internal(0) { } SavedBuiltins::~SavedBuiltins() { delete _internal; } void Interpreter::virtual_hook( int, void* ) { /*BASE::virtual_hook( id, data );*/ } Interpreter *ExecState::lexicalInterpreter() const { if (!_context) { return dynamicInterpreter(); } InterpreterImp *result = InterpreterImp::interpreterWithGlobalObject(_context->scopeChain().bottom()); if (!result) { return dynamicInterpreter(); } return result->interpreter(); } } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include "node_pointer.h" #include <nn.h> #include <pubsub.h> #include <pipeline.h> #include <bus.h> #include <pair.h> #include <reqrep.h> #include <survey.h> #include <inproc.h> #include <ipc.h> #include <tcp.h> using v8::Array; using v8::Function; using v8::FunctionTemplate; using v8::Handle; using v8::Local; using v8::Number; using v8::Object; using v8::String; using v8::Value; #define ret NanReturnValue #define utf8 v8::String::Utf8Value #define integer As<Number>()->IntegerValue() #define S args[0].integer NAN_METHOD(Socket) { NanScope(); int domain = args[0]->Uint32Value(); int protocol = args[1]->Uint32Value(); // Invoke nanomsg function. int ret = nn_socket(domain, protocol); NanReturnValue(NanNew<Number>(ret)); } NAN_METHOD(Close) { NanScope(); int s = args[0]->Uint32Value(); // Invoke nanomsg function. int ret = nn_close(s); NanReturnValue(NanNew<Number>(ret)); } NAN_METHOD(Setopt) { NanScope(); int level = args[1].integer; int option = args[2].integer; int optval = args[3].integer; ret(NanNew<Number>(nn_setsockopt(S, level, option, &optval, sizeof(optval)))); } NAN_METHOD(Getopt) { NanScope(); int optval[1]; int option = args[2].integer; size_t optsize = sizeof(optval); // check if the function succeeds if (nn_getsockopt(S, args[1].integer, option, optval, &optsize) == 0) { ret(NanNew<Number>(optval[0])); } else { // pass the error back as an undefined return NanReturnUndefined(); } } NAN_METHOD(Chan) { NanScope(); int level = NN_SUB; int option = args[1].integer; utf8 str(args[2]); ret(NanNew<Number>(nn_setsockopt(S, level, option, *str, str.length()))); } NAN_METHOD(Bind) { NanScope(); int s = args[0]->Uint32Value(); String::Utf8Value addr(args[1]); // Invoke nanomsg function. int ret = nn_bind(s, *addr); NanReturnValue(NanNew<Number>(ret)); } NAN_METHOD(Connect) { NanScope(); int s = args[0]->Uint32Value(); String::Utf8Value addr(args[1]); // Invoke nanomsg function. int ret = nn_connect(s, *addr); NanReturnValue(NanNew<Number>(ret)); } NAN_METHOD(Shutdown) { NanScope(); int s = args[0]->Uint32Value(); int how = args[1]->Uint32Value(); // Invoke nanomsg function. int ret = nn_shutdown(s, how); NanReturnValue(NanNew<Number>(ret)); } NAN_METHOD(Send) { NanScope(); int flags = args[2].integer; if (node::Buffer::HasInstance(args[1])) { ret(NanNew<Number>(nn_send(S, node::Buffer::Data(args[1]), node::Buffer::Length(args[1]), flags))); } else { utf8 str(args[1]->ToString()); ret(NanNew<Number>(nn_send(S, *str, str.length(), flags))); } } NAN_METHOD(Recv) { NanScope(); int s = args[0]->Uint32Value(); int flags = args[1]->Uint32Value(); // Invoke nanomsg function. char *buf = NULL; int len = nn_recv(s, &buf, NN_MSG, flags); if (len > -1) { v8::Local<v8::Value> h = NanNewBufferHandle(len); memcpy(node::Buffer::Data(h), buf, len); // dont memory leak nn_freemsg(buf); ret(h); } else { ret(NanNew<Number>(len)); } } NAN_METHOD(SymbolInfo) { NanScope(); int s = args[0]->Uint32Value(); struct nn_symbol_properties prop; int ret = nn_symbol_info(s, &prop, sizeof(prop)); if (ret > 0) { Local<Object> obj = NanNew<Object>(); obj->Set(NanNew("value"), NanNew<Number>(prop.value)); obj->Set(NanNew("ns"), NanNew<Number>(prop.ns)); obj->Set(NanNew("type"), NanNew<Number>(prop.type)); obj->Set(NanNew("unit"), NanNew<Number>(prop.unit)); obj->Set(NanNew("name"), NanNew<String>(prop.name)); NanReturnValue(obj); } else if (ret == 0) { // symbol index out of range NanReturnUndefined(); } else { NanThrowError(nn_strerror(nn_errno())); NanReturnUndefined(); } } NAN_METHOD(Symbol) { NanScope(); int s = args[0]->Uint32Value(); int val; const char *ret = nn_symbol(s, &val); if (ret) { Local<Object> obj = NanNew<Object>(); obj->Set(NanNew("value"), NanNew<Number>(val)); obj->Set(NanNew("name"), NanNew<String>(ret)); NanReturnValue(obj); } else { // symbol index out of range // this behaviour seems inconsistent with SymbolInfo() above // but we are faithfully following the libnanomsg API, warta and all NanThrowError(nn_strerror(nn_errno())); // EINVAL NanReturnUndefined(); } } NAN_METHOD(Term) { NanScope(); nn_term(); NanReturnUndefined(); } // Pass in two sockets, or (socket, -1) or (-1, socket) for loopback NAN_METHOD(Device) { NanScope(); int s1 = args[0]->Uint32Value(); int s2 = args[1]->Uint32Value(); // nn_device only returns when it encounters an error nn_device(s1, s2); NanThrowError(nn_strerror(nn_errno())); NanReturnUndefined(); } NAN_METHOD(Errno) { NanScope(); // Invoke nanomsg function. int ret = nn_errno(); NanReturnValue(NanNew<Number>(ret)); } NAN_METHOD(Err) { NanScope(); ret(NanNew<String>(nn_strerror(nn_errno()))); } typedef struct nanomsg_socket_s { uv_poll_t poll_handle; uv_os_sock_t sockfd; NanCallback *callback; } nanomsg_socket_t; void NanomsgReadable(uv_poll_t *req, int status, int events) { NanScope(); nanomsg_socket_t *context; context = reinterpret_cast<nanomsg_socket_t *>(req); if (events & UV_READABLE) { Local<Value> argv[] = { NanNew<Number>(events) }; context->callback->Call(1, argv); } } NAN_METHOD(PollSendSocket) { NanScope(); int s = args[0]->Uint32Value(); NanCallback *callback = new NanCallback(args[1].As<Function>()); nanomsg_socket_t *context; size_t siz = sizeof(uv_os_sock_t); context = reinterpret_cast<nanomsg_socket_t *>(calloc(1, sizeof *context)); context->poll_handle.data = context; context->callback = callback; nn_getsockopt(s, NN_SOL_SOCKET, NN_SNDFD, &context->sockfd, &siz); if (context->sockfd != 0) { uv_poll_init_socket(uv_default_loop(), &context->poll_handle, context->sockfd); uv_poll_start(&context->poll_handle, UV_READABLE, NanomsgReadable); NanReturnValue(WrapPointer(context, 8)); } else { NanReturnUndefined(); } } NAN_METHOD(PollReceiveSocket) { NanScope(); int s = args[0]->Uint32Value(); NanCallback *callback = new NanCallback(args[1].As<Function>()); nanomsg_socket_t *context; size_t siz = sizeof(uv_os_sock_t); context = reinterpret_cast<nanomsg_socket_t *>(calloc(1, sizeof *context)); context->poll_handle.data = context; context->callback = callback; nn_getsockopt(s, NN_SOL_SOCKET, NN_RCVFD, &context->sockfd, &siz); if (context->sockfd != 0) { uv_poll_init_socket(uv_default_loop(), &context->poll_handle, context->sockfd); uv_poll_start(&context->poll_handle, UV_READABLE, NanomsgReadable); NanReturnValue(WrapPointer(context, 8)); } else { NanReturnUndefined(); } } NAN_METHOD(PollStop) { NanScope(); nanomsg_socket_t *context = UnwrapPointer<nanomsg_socket_t *>(args[0]); int r = uv_poll_stop(&context->poll_handle); NanReturnValue(NanNew<Number>(r)); } class NanomsgDeviceWorker : public NanAsyncWorker { public: NanomsgDeviceWorker(NanCallback *callback, int s1, int s2) : NanAsyncWorker(callback), s1(s1), s2(s2) {} ~NanomsgDeviceWorker() {} // Executed inside the worker-thread. // It is not safe to access V8, or V8 data structures // here, so everything we need for input and output // should go on `this`. void Execute() { // nn_errno() only returns on error nn_device(s1, s2); err = nn_errno(); } // Executed when the async work is complete // this function will be run inside the main event loop // so it is safe to use V8 again void HandleOKCallback() { NanScope(); Local<Value> argv[] = { NanNew<Number>(err) }; callback->Call(1, argv); }; private: int s1; int s2; int err; }; // Asynchronous access to the `nn_device()` function NAN_METHOD(DeviceWorker) { NanScope(); int s1 = args[0]->Uint32Value(); int s2 = args[1]->Uint32Value(); NanCallback *callback = new NanCallback(args[2].As<Function>()); NanAsyncQueueWorker(new NanomsgDeviceWorker(callback, s1, s2)); NanReturnUndefined(); } #define EXPORT_METHOD(C, S) \ C->Set(NanNew(#S), NanNew<FunctionTemplate>(S)->GetFunction()); void InitAll(Handle<Object> exports) { NanScope(); // Export functions. EXPORT_METHOD(exports, Socket); EXPORT_METHOD(exports, Close); EXPORT_METHOD(exports, Chan); EXPORT_METHOD(exports, Bind); EXPORT_METHOD(exports, Connect); EXPORT_METHOD(exports, Shutdown); EXPORT_METHOD(exports, Send); EXPORT_METHOD(exports, Recv); EXPORT_METHOD(exports, Errno); EXPORT_METHOD(exports, PollSendSocket); EXPORT_METHOD(exports, PollReceiveSocket); EXPORT_METHOD(exports, PollStop); EXPORT_METHOD(exports, DeviceWorker); EXPORT_METHOD(exports, SymbolInfo); EXPORT_METHOD(exports, Symbol); EXPORT_METHOD(exports, Term); EXPORT_METHOD(exports, Getopt); EXPORT_METHOD(exports, Setopt); EXPORT_METHOD(exports, Err); // Export symbols. for (int i = 0;; ++i) { int value; const char *symbol_name = nn_symbol(i, &value); if (symbol_name == NULL) { break; } exports->Set(NanNew(symbol_name), NanNew<Number>(value)); } } NODE_MODULE(node_nanomsg, InitAll) <commit_msg>remove macros • use proper casts • Fixes: #84 • PR: #85<commit_after>#include <stdio.h> #include <stdlib.h> #include "node_pointer.h" #include <nn.h> #include <pubsub.h> #include <pipeline.h> #include <bus.h> #include <pair.h> #include <reqrep.h> #include <survey.h> #include <inproc.h> #include <ipc.h> #include <tcp.h> using v8::Array; using v8::Function; using v8::FunctionTemplate; using v8::Handle; using v8::Local; using v8::Number; using v8::Object; using v8::String; using v8::Value; NAN_METHOD(Socket) { NanScope(); int domain = args[0]->Int32Value(); int protocol = args[1]->Int32Value(); NanReturnValue(NanNew<Number>(nn_socket(domain, protocol))); } NAN_METHOD(Close) { NanScope(); int s = args[0]->Int32Value(); NanReturnValue(NanNew<Number>(nn_close(s))); } NAN_METHOD(Setopt) { NanScope(); int s = args[0]->Int32Value(); int level = args[1]->Int32Value(); int option = args[2]->Int32Value(); int optval = args[3]->Int32Value(); NanReturnValue( NanNew<Number>(nn_setsockopt(s, level, option, &optval, sizeof(optval)))); } NAN_METHOD(Getopt) { NanScope(); int s = args[0]->Int32Value(); int level = args[1]->Int32Value(); int option = args[2]->Int32Value(); int optval; size_t optsize = sizeof(optval); // check if the function succeeds if (nn_getsockopt(s, level, option, &optval, &optsize) == 0) { NanReturnValue(NanNew<Number>(optval)); } else { // pass the error back as an undefined return NanReturnUndefined(); } } NAN_METHOD(Chan) { NanScope(); int s = args[0]->Int32Value(); int level = NN_SUB; int option = args[1]->Int32Value(); v8::String::Utf8Value str(args[2]); NanReturnValue( NanNew<Number>(nn_setsockopt(s, level, option, *str, str.length()))); } NAN_METHOD(Bind) { NanScope(); int s = args[0]->Int32Value(); String::Utf8Value addr(args[1]); NanReturnValue(NanNew<Number>(nn_bind(s, *addr))); } NAN_METHOD(Connect) { NanScope(); int s = args[0]->Int32Value(); String::Utf8Value addr(args[1]); NanReturnValue(NanNew<Number>(nn_connect(s, *addr))); } NAN_METHOD(Shutdown) { NanScope(); int s = args[0]->Int32Value(); int how = args[1]->Int32Value(); NanReturnValue(NanNew<Number>(nn_shutdown(s, how))); } NAN_METHOD(Send) { NanScope(); int s = args[0]->Int32Value(); int flags = args[2]->Int32Value(); if (node::Buffer::HasInstance(args[1])) { NanReturnValue(NanNew<Number>(nn_send( s, node::Buffer::Data(args[1]), node::Buffer::Length(args[1]), flags))); } else { v8::String::Utf8Value str(args[1]->ToString()); NanReturnValue(NanNew<Number>(nn_send(s, *str, str.length(), flags))); } } NAN_METHOD(Recv) { NanScope(); int s = args[0]->Int32Value(); int flags = args[1]->Int32Value(); // Invoke nanomsg function. char *buf = NULL; int len = nn_recv(s, &buf, NN_MSG, flags); if (len > -1) { v8::Local<v8::Value> h = NanNewBufferHandle(len); memcpy(node::Buffer::Data(h), buf, len); // dont memory leak nn_freemsg(buf); NanReturnValue(h); } else { NanReturnValue(NanNew<Number>(len)); } } NAN_METHOD(SymbolInfo) { NanScope(); int s = args[0]->Int32Value(); struct nn_symbol_properties prop; int ret = nn_symbol_info(s, &prop, sizeof(prop)); if (ret > 0) { Local<Object> obj = NanNew<Object>(); obj->Set(NanNew("value"), NanNew<Number>(prop.value)); obj->Set(NanNew("ns"), NanNew<Number>(prop.ns)); obj->Set(NanNew("type"), NanNew<Number>(prop.type)); obj->Set(NanNew("unit"), NanNew<Number>(prop.unit)); obj->Set(NanNew("name"), NanNew<String>(prop.name)); NanReturnValue(obj); } else if (ret == 0) { // symbol index out of range NanReturnUndefined(); } else { NanThrowError(nn_strerror(nn_errno())); NanReturnUndefined(); } } NAN_METHOD(Symbol) { NanScope(); int s = args[0]->Int32Value(); int val; const char *ret = nn_symbol(s, &val); if (ret) { Local<Object> obj = NanNew<Object>(); obj->Set(NanNew("value"), NanNew<Number>(val)); obj->Set(NanNew("name"), NanNew<String>(ret)); NanReturnValue(obj); } else { // symbol index out of range // this behaviour seems inconsistent with SymbolInfo() above // but we are faithfully following the libnanomsg API, warta and all NanThrowError(nn_strerror(nn_errno())); // EINVAL NanReturnUndefined(); } } NAN_METHOD(Term) { NanScope(); nn_term(); NanReturnUndefined(); } // Pass in two sockets, or (socket, -1) or (-1, socket) for loopback NAN_METHOD(Device) { NanScope(); int s1 = args[0]->Int32Value(); int s2 = args[1]->Int32Value(); // nn_device only returns when it encounters an error nn_device(s1, s2); NanThrowError(nn_strerror(nn_errno())); NanReturnUndefined(); } NAN_METHOD(Errno) { NanScope(); NanReturnValue(NanNew<Number>(nn_errno())); } NAN_METHOD(Err) { NanScope(); NanReturnValue(NanNew<String>(nn_strerror(nn_errno()))); } typedef struct nanomsg_socket_s { uv_poll_t poll_handle; uv_os_sock_t sockfd; NanCallback *callback; } nanomsg_socket_t; void NanomsgReadable(uv_poll_t *req, int status, int events) { NanScope(); nanomsg_socket_t *context; context = reinterpret_cast<nanomsg_socket_t *>(req); if (events & UV_READABLE) { Local<Value> argv[] = { NanNew<Number>(events) }; context->callback->Call(1, argv); } } NAN_METHOD(PollSendSocket) { NanScope(); int s = args[0]->Int32Value(); NanCallback *callback = new NanCallback(args[1].As<Function>()); nanomsg_socket_t *context; size_t siz = sizeof(uv_os_sock_t); context = reinterpret_cast<nanomsg_socket_t *>(calloc(1, sizeof *context)); context->poll_handle.data = context; context->callback = callback; nn_getsockopt(s, NN_SOL_SOCKET, NN_SNDFD, &context->sockfd, &siz); if (context->sockfd != 0) { uv_poll_init_socket(uv_default_loop(), &context->poll_handle, context->sockfd); uv_poll_start(&context->poll_handle, UV_READABLE, NanomsgReadable); NanReturnValue(WrapPointer(context, 8)); } else { NanReturnUndefined(); } } NAN_METHOD(PollReceiveSocket) { NanScope(); int s = args[0]->Int32Value(); NanCallback *callback = new NanCallback(args[1].As<Function>()); nanomsg_socket_t *context; size_t siz = sizeof(uv_os_sock_t); context = reinterpret_cast<nanomsg_socket_t *>(calloc(1, sizeof *context)); context->poll_handle.data = context; context->callback = callback; nn_getsockopt(s, NN_SOL_SOCKET, NN_RCVFD, &context->sockfd, &siz); if (context->sockfd != 0) { uv_poll_init_socket(uv_default_loop(), &context->poll_handle, context->sockfd); uv_poll_start(&context->poll_handle, UV_READABLE, NanomsgReadable); NanReturnValue(WrapPointer(context, 8)); } else { NanReturnUndefined(); } } NAN_METHOD(PollStop) { NanScope(); nanomsg_socket_t *context = UnwrapPointer<nanomsg_socket_t *>(args[0]); int r = uv_poll_stop(&context->poll_handle); NanReturnValue(NanNew<Number>(r)); } class NanomsgDeviceWorker : public NanAsyncWorker { public: NanomsgDeviceWorker(NanCallback *callback, int s1, int s2) : NanAsyncWorker(callback), s1(s1), s2(s2) {} ~NanomsgDeviceWorker() {} // Executed inside the worker-thread. // It is not safe to access V8, or V8 data structures // here, so everything we need for input and output // should go on `this`. void Execute() { // nn_errno() only returns on error nn_device(s1, s2); err = nn_errno(); } // Executed when the async work is complete // this function will be run inside the main event loop // so it is safe to use V8 again void HandleOKCallback() { NanScope(); Local<Value> argv[] = { NanNew<Number>(err) }; callback->Call(1, argv); }; private: int s1; int s2; int err; }; // Asynchronous access to the `nn_device()` function NAN_METHOD(DeviceWorker) { NanScope(); int s1 = args[0]->Int32Value(); int s2 = args[1]->Int32Value(); NanCallback *callback = new NanCallback(args[2].As<Function>()); NanAsyncQueueWorker(new NanomsgDeviceWorker(callback, s1, s2)); NanReturnUndefined(); } #define EXPORT_METHOD(C, S) \ C->Set(NanNew(#S), NanNew<FunctionTemplate>(S)->GetFunction()); void InitAll(Handle<Object> exports) { NanScope(); // Export functions. EXPORT_METHOD(exports, Socket); EXPORT_METHOD(exports, Close); EXPORT_METHOD(exports, Chan); EXPORT_METHOD(exports, Bind); EXPORT_METHOD(exports, Connect); EXPORT_METHOD(exports, Shutdown); EXPORT_METHOD(exports, Send); EXPORT_METHOD(exports, Recv); EXPORT_METHOD(exports, Errno); EXPORT_METHOD(exports, PollSendSocket); EXPORT_METHOD(exports, PollReceiveSocket); EXPORT_METHOD(exports, PollStop); EXPORT_METHOD(exports, DeviceWorker); EXPORT_METHOD(exports, SymbolInfo); EXPORT_METHOD(exports, Symbol); EXPORT_METHOD(exports, Term); EXPORT_METHOD(exports, Getopt); EXPORT_METHOD(exports, Setopt); EXPORT_METHOD(exports, Err); // Export symbols. for (int i = 0;; ++i) { int value; const char *symbol_name = nn_symbol(i, &value); if (symbol_name == NULL) { break; } exports->Set(NanNew(symbol_name), NanNew<Number>(value)); } } NODE_MODULE(node_nanomsg, InitAll) <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <miopen/lrn.hpp> #include <miopen/mlo_internal.hpp> #include <miopen/float_equal.hpp> #include <miopen/visit_float.hpp> namespace miopen { miopenStatus_t LRNDescriptor::Forward(Handle& handle, const void* /*alpha*/, const TensorDescriptor& xDesc, ConstData_t x, const void* /*beta*/, const TensorDescriptor& yDesc, Data_t y, bool do_backward, Data_t workSpace) const { miopenStatus_t status = miopenStatusSuccess; mlo_construct_norm construct_params(1); // forward construct_params.setStream(&handle); int nOut; int cOut; int hOut; int wOut; int nOutStride; int cOutStride; int hOutStride; int wOutStride; std::tie(nOut, cOut, hOut, wOut) = tien<4>(yDesc.GetLengths()); std::tie(nOutStride, cOutStride, hOutStride, wOutStride) = tien<4>(yDesc.GetStrides()); construct_params.setTopDescFromMLDesc(yDesc); int nIn; int cIn; int hIn; int wIn; int nInStride; int cInStride; int hInStride; int wInStride; std::tie(nIn, cIn, hIn, wIn) = tien<4>(xDesc.GetLengths()); std::tie(nInStride, cInStride, hInStride, wInStride) = tien<4>(xDesc.GetStrides()); construct_params.setBotDescFromMLDesc(xDesc); int norm_reg = GetMode(); int local_area = GetN(); double lrn_alpha = GetAlpha(); double lrn_beta = GetBeta(); double lrn_K = GetK(); construct_params.doBackward(do_backward); construct_params.setNormDescr(norm_reg, local_area, lrn_alpha, lrn_beta, lrn_K); mloConstruct(construct_params); int norm_region; int local_ar; // whithin channel alphaoverarea is going to be culculate based on actual areal size (cut by // borders). double norm_alpha; double norm_beta; double norm_K; double norm_alphaoverarea; construct_params.getNormDescr( norm_region, local_ar, norm_alpha, norm_beta, norm_K, norm_alphaoverarea); auto f_norm_alpha = static_cast<float>(norm_alpha); auto f_norm_beta = static_cast<float>(norm_beta); auto f_norm_K = static_cast<float>(norm_K); auto f_norm_alphaoverarea = static_cast<float>(norm_alphaoverarea); if(float_equal(f_norm_K, 0.0)) MIOPEN_THROW("Expect non-zero bias/K"); std::string algo_name = "miopenLRNForward"; std::string network_config = std::to_string(f_norm_alpha) + std::to_string(f_norm_beta) + std::to_string(f_norm_K) + std::to_string(f_norm_alphaoverarea) + std::to_string(local_ar) + std::to_string(norm_region) + std::to_string(do_backward) + std::to_string(xDesc.GetType()) + std::to_string(nInStride) + std::to_string(nOutStride) + std::to_string(nIn) + std::to_string(nOut) + std::to_string(nInStride) + std::to_string(nOutStride) + std::to_string(cIn) + std::to_string(cOut) + std::to_string(cInStride) + std::to_string(cOutStride) + std::to_string(hIn) + std::to_string(hOut); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { if(do_backward) { kernels.front()( x, y, workSpace, f_norm_alphaoverarea, f_norm_alpha, f_norm_beta, f_norm_K); } else { kernels.front()(x, y, f_norm_alphaoverarea, f_norm_alpha, f_norm_beta, f_norm_K); } } else { std::string program_name = construct_params.getKernelFile(); // CL kernel filename std::string kernel_name = construct_params.getKernelName(); // kernel name const std::string& compiler_parms = construct_params.getCompilerOptions(); // kernel parameters const std::vector<size_t>& vld = construct_params.getLocalWkSize(); const std::vector<size_t>& vgd = construct_params.getGlobalWkSize(); KernelInvoke obj = handle.AddKernel( algo_name, network_config, program_name, kernel_name, vld, vgd, compiler_parms); if(do_backward) { obj(x, y, workSpace, f_norm_alphaoverarea, f_norm_alpha, f_norm_beta, f_norm_K); } else { obj(x, y, f_norm_alphaoverarea, f_norm_alpha, f_norm_beta, f_norm_K); } } return (status); } miopenStatus_t LRNDescriptor::Backward(Handle& handle, const void* /*alpha*/, const TensorDescriptor& yDesc, ConstData_t y, const TensorDescriptor& dyDesc, ConstData_t dy, const TensorDescriptor& xDesc, ConstData_t x, const void* /*beta*/, const TensorDescriptor& dxDesc, Data_t dx, ConstData_t workSpace) const { miopenStatus_t status = miopenStatusSuccess; mlo_construct_norm construct_params(0); // backward construct_params.setStream(&handle); int ndOut; int cdOut; int hdOut; int wdOut; int ndOutStride; int cdOutStride; int hdOutStride; int wdOutStride; std::tie(ndOut, cdOut, hdOut, wdOut) = tien<4>(dyDesc.GetLengths()); std::tie(ndOutStride, cdOutStride, hdOutStride, wdOutStride) = tien<4>(dyDesc.GetStrides()); construct_params.setTopDfDescFromMLDesc(dyDesc); int nOut; int cOut; int hOut; int wOut; int nOutStride; int cOutStride; int hOutStride; int wOutStride; std::tie(nOut, cOut, hOut, wOut) = tien<4>(yDesc.GetLengths()); std::tie(nOutStride, cOutStride, hOutStride, wOutStride) = tien<4>(yDesc.GetStrides()); construct_params.setTopDescFromMLDesc(yDesc); int ndIn; int cdIn; int hdIn; int wdIn; int ndInStride; int cdInStride; int hdInStride; int wdInStride; std::tie(ndIn, cdIn, hdIn, wdIn) = tien<4>(dxDesc.GetLengths()); std::tie(ndInStride, cdInStride, hdInStride, wdInStride) = tien<4>(dxDesc.GetStrides()); construct_params.setBotDfDescFromMLDesc(dxDesc); int nIn; int cIn; int hIn; int wIn; int nInStride; int cInStride; int hInStride; int wInStride; std::tie(nIn, cIn, hIn, wIn) = tien<4>(xDesc.GetLengths()); std::tie(nInStride, cInStride, hInStride, wInStride) = tien<4>(xDesc.GetStrides()); construct_params.setBotDescFromMLDesc(xDesc); int norm_reg = GetMode(); int local_area = GetN(); double lrn_alpha = GetAlpha(); double lrn_beta = GetBeta(); double lrn_K = GetK(); construct_params.setNormDescr(norm_reg, local_area, lrn_alpha, lrn_beta, lrn_K); mloConstruct(construct_params); int norm_region; int local_ar; // whithin channel alphaoverarea is going to be culculate based on actual areal size (cut by // borders). double norm_alpha; double norm_beta; double norm_K; double norm_alphaoverarea; construct_params.getNormDescr( norm_region, local_ar, norm_alpha, norm_beta, norm_K, norm_alphaoverarea); auto f_norm_alpha = static_cast<float>(norm_alpha); auto f_norm_beta = static_cast<float>(norm_beta); auto f_norm_ratio = static_cast<float>(2. * norm_alpha * norm_beta / static_cast<double>(local_ar)); if(float_equal(norm_K, 0.0)) MIOPEN_THROW("Expect non-zero bias/K"); std::string algo_name = "miopenLRNBackward"; std::string network_config = std::to_string(f_norm_alpha) + std::to_string(f_norm_beta) + std::to_string(norm_K) + std::to_string(norm_alphaoverarea) + std::to_string(local_ar) + std::to_string(norm_region) + std::to_string(f_norm_ratio) + std::to_string(xDesc.GetType()) + std::to_string(nInStride) + std::to_string(nOutStride) + std::to_string(nIn) + std::to_string(nOut) + std::to_string(nInStride) + std::to_string(nOutStride) + std::to_string(cIn) + std::to_string(cOut) + std::to_string(cInStride) + std::to_string(cOutStride) + std::to_string(hIn) + std::to_string(hOut); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { kernels.front()(y, x, dy, workSpace, dx, f_norm_ratio, f_norm_alpha, f_norm_beta); } else { std::string program_name = construct_params.getKernelFile(); // CL kernel filename std::string kernel_name = construct_params.getKernelName(); // kernel name std::string compiler_parms = construct_params.getCompilerOptions(); // kernel parameters const std::vector<size_t>& vld = construct_params.getLocalWkSize(); const std::vector<size_t>& vgd = construct_params.getGlobalWkSize(); handle.AddKernel( algo_name, network_config, program_name, kernel_name, vld, vgd, compiler_parms)( y, x, dy, workSpace, dx, f_norm_ratio, f_norm_alpha, f_norm_beta); } return (status); } } // namespace miopen <commit_msg>Re-inserted lambdas for LRN.<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <miopen/lrn.hpp> #include <miopen/mlo_internal.hpp> #include <miopen/float_equal.hpp> #include <miopen/visit_float.hpp> namespace miopen { miopenStatus_t LRNDescriptor::Forward(Handle& handle, const void* /*alpha*/, const TensorDescriptor& xDesc, ConstData_t x, const void* /*beta*/, const TensorDescriptor& yDesc, Data_t y, bool do_backward, Data_t workSpace) const { miopenStatus_t status = miopenStatusSuccess; mlo_construct_norm construct_params(1); // forward construct_params.setStream(&handle); int nOut; int cOut; int hOut; int wOut; int nOutStride; int cOutStride; int hOutStride; int wOutStride; std::tie(nOut, cOut, hOut, wOut) = tien<4>(yDesc.GetLengths()); std::tie(nOutStride, cOutStride, hOutStride, wOutStride) = tien<4>(yDesc.GetStrides()); construct_params.setTopDescFromMLDesc(yDesc); int nIn; int cIn; int hIn; int wIn; int nInStride; int cInStride; int hInStride; int wInStride; std::tie(nIn, cIn, hIn, wIn) = tien<4>(xDesc.GetLengths()); std::tie(nInStride, cInStride, hInStride, wInStride) = tien<4>(xDesc.GetStrides()); construct_params.setBotDescFromMLDesc(xDesc); int norm_reg = GetMode(); int local_area = GetN(); double lrn_alpha = GetAlpha(); double lrn_beta = GetBeta(); double lrn_K = GetK(); construct_params.doBackward(do_backward); construct_params.setNormDescr(norm_reg, local_area, lrn_alpha, lrn_beta, lrn_K); mloConstruct(construct_params); int norm_region; int local_ar; // whithin channel alphaoverarea is going to be culculate based on actual areal size (cut by // borders). double norm_alpha; double norm_beta; double norm_K; double norm_alphaoverarea; construct_params.getNormDescr( norm_region, local_ar, norm_alpha, norm_beta, norm_K, norm_alphaoverarea); auto f_norm_alpha = static_cast<float>(norm_alpha); auto f_norm_beta = static_cast<float>(norm_beta); auto f_norm_K = static_cast<float>(norm_K); auto f_norm_alphaoverarea = static_cast<float>(norm_alphaoverarea); if(float_equal(f_norm_K, 0.0)) MIOPEN_THROW("Expect non-zero bias/K"); std::string algo_name = "miopenLRNForward"; std::string network_config = std::to_string(f_norm_alpha) + std::to_string(f_norm_beta) + std::to_string(f_norm_K) + std::to_string(f_norm_alphaoverarea) + std::to_string(local_ar) + std::to_string(norm_region) + std::to_string(do_backward) + std::to_string(xDesc.GetType()) + std::to_string(nInStride) + std::to_string(nOutStride) + std::to_string(nIn) + std::to_string(nOut) + std::to_string(nInStride) + std::to_string(nOutStride) + std::to_string(cIn) + std::to_string(cOut) + std::to_string(cInStride) + std::to_string(cOutStride) + std::to_string(hIn) + std::to_string(hOut); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { visit_float(xDesc.GetType(), [&](auto as_float) { if(do_backward) { kernels.front()(x, y, workSpace, as_float(f_norm_alphaoverarea), as_float(f_norm_alpha), as_float(f_norm_beta), as_float(f_norm_K)); } else { kernels.front()(x, y, as_float(f_norm_alphaoverarea), as_float(f_norm_alpha), as_float(f_norm_beta), as_float(f_norm_K)); } }); } else { const std::string program_name = construct_params.getKernelFile(); // CL kernel filename const std::string kernel_name = construct_params.getKernelName(); // kernel name const std::string& compiler_parms = construct_params.getCompilerOptions(); // kernel parameters const std::vector<size_t>& vld = construct_params.getLocalWkSize(); const std::vector<size_t>& vgd = construct_params.getGlobalWkSize(); KernelInvoke obj = handle.AddKernel( algo_name, network_config, program_name, kernel_name, vld, vgd, compiler_parms); visit_float(xDesc.GetType(), [&](auto as_float) { if(do_backward) { obj(x, y, workSpace, as_float(f_norm_alphaoverarea), as_float(f_norm_alpha), as_float(f_norm_beta), as_float(f_norm_K)); } else { obj(x, y, as_float(f_norm_alphaoverarea), as_float(f_norm_alpha), as_float(f_norm_beta), as_float(f_norm_K)); } }); } return (status); } miopenStatus_t LRNDescriptor::Backward(Handle& handle, const void* /*alpha*/, const TensorDescriptor& yDesc, ConstData_t y, const TensorDescriptor& dyDesc, ConstData_t dy, const TensorDescriptor& xDesc, ConstData_t x, const void* /*beta*/, const TensorDescriptor& dxDesc, Data_t dx, ConstData_t workSpace) const { miopenStatus_t status = miopenStatusSuccess; mlo_construct_norm construct_params(0); // backward construct_params.setStream(&handle); int ndOut; int cdOut; int hdOut; int wdOut; int ndOutStride; int cdOutStride; int hdOutStride; int wdOutStride; std::tie(ndOut, cdOut, hdOut, wdOut) = tien<4>(dyDesc.GetLengths()); std::tie(ndOutStride, cdOutStride, hdOutStride, wdOutStride) = tien<4>(dyDesc.GetStrides()); construct_params.setTopDfDescFromMLDesc(dyDesc); int nOut; int cOut; int hOut; int wOut; int nOutStride; int cOutStride; int hOutStride; int wOutStride; std::tie(nOut, cOut, hOut, wOut) = tien<4>(yDesc.GetLengths()); std::tie(nOutStride, cOutStride, hOutStride, wOutStride) = tien<4>(yDesc.GetStrides()); construct_params.setTopDescFromMLDesc(yDesc); int ndIn; int cdIn; int hdIn; int wdIn; int ndInStride; int cdInStride; int hdInStride; int wdInStride; std::tie(ndIn, cdIn, hdIn, wdIn) = tien<4>(dxDesc.GetLengths()); std::tie(ndInStride, cdInStride, hdInStride, wdInStride) = tien<4>(dxDesc.GetStrides()); construct_params.setBotDfDescFromMLDesc(dxDesc); int nIn; int cIn; int hIn; int wIn; int nInStride; int cInStride; int hInStride; int wInStride; std::tie(nIn, cIn, hIn, wIn) = tien<4>(xDesc.GetLengths()); std::tie(nInStride, cInStride, hInStride, wInStride) = tien<4>(xDesc.GetStrides()); construct_params.setBotDescFromMLDesc(xDesc); int norm_reg = GetMode(); int local_area = GetN(); double lrn_alpha = GetAlpha(); double lrn_beta = GetBeta(); double lrn_K = GetK(); construct_params.setNormDescr(norm_reg, local_area, lrn_alpha, lrn_beta, lrn_K); mloConstruct(construct_params); int norm_region; int local_ar; // whithin channel alphaoverarea is going to be culculate based on actual areal size (cut by // borders). double norm_alpha; double norm_beta; double norm_K; double norm_alphaoverarea; construct_params.getNormDescr( norm_region, local_ar, norm_alpha, norm_beta, norm_K, norm_alphaoverarea); auto f_norm_alpha = static_cast<float>(norm_alpha); auto f_norm_beta = static_cast<float>(norm_beta); auto f_norm_ratio = static_cast<float>(2. * norm_alpha * norm_beta / static_cast<double>(local_ar)); if(float_equal(norm_K, 0.0)) MIOPEN_THROW("Expect non-zero bias/K"); std::string algo_name = "miopenLRNBackward"; std::string network_config = std::to_string(f_norm_alpha) + std::to_string(f_norm_beta) + std::to_string(norm_K) + std::to_string(norm_alphaoverarea) + std::to_string(local_ar) + std::to_string(norm_region) + std::to_string(f_norm_ratio) + std::to_string(xDesc.GetType()) + std::to_string(nInStride) + std::to_string(nOutStride) + std::to_string(nIn) + std::to_string(nOut) + std::to_string(nInStride) + std::to_string(nOutStride) + std::to_string(cIn) + std::to_string(cOut) + std::to_string(cInStride) + std::to_string(cOutStride) + std::to_string(hIn) + std::to_string(hOut); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { visit_float(xDesc.GetType(), [&](auto as_float) { kernels.front()(y, x, dy, workSpace, dx, as_float(f_norm_ratio), as_float(f_norm_alpha), as_float(f_norm_beta)); }); } else { const std::string program_name = construct_params.getKernelFile(); // CL kernel filename const std::string kernel_name = construct_params.getKernelName(); // kernel name const std::string& compiler_parms = construct_params.getCompilerOptions(); // kernel parameters const std::vector<size_t>& vld = construct_params.getLocalWkSize(); const std::vector<size_t>& vgd = construct_params.getGlobalWkSize(); visit_float(xDesc.GetType(), [&](auto as_float) { handle.AddKernel( algo_name, network_config, program_name, kernel_name, vld, vgd, compiler_parms)( y, x, dy, workSpace, dx, as_float(f_norm_ratio), as_float(f_norm_alpha), as_float(f_norm_beta)); }); } return (status); } } // namespace miopen <|endoftext|>
<commit_before>/* * SessionDiagnosticsTests.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 <tests/TestThat.hpp> #include "SessionDiagnostics.hpp" #include <iostream> #include <core/collection/Tree.hpp> #include <core/FilePath.hpp> #include <core/system/FileScanner.hpp> #include <core/FileUtils.hpp> #include <boost/algorithm/string.hpp> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <session/SessionOptions.hpp> #include "SessionRParser.hpp" namespace rstudio { namespace session { namespace modules { namespace diagnostics { using namespace rparser; static const ParseOptions s_parseOptions(true); using namespace core; using namespace core::r_util; // We use macros so that the test output gives // meaningful line numbers. #define EXPECT_ERRORS(__STRING__) \ do \ { \ ParseResults results = parse(__STRING__, s_parseOptions); \ expect_true(results.lint().hasErrors()); \ } while (0) #define EXPECT_NO_ERRORS(__STRING__) \ do \ { \ ParseResults results = parse(__STRING__, s_parseOptions); \ if (results.lint().hasErrors()) \ results.lint().dump(); \ expect_false(results.lint().hasErrors()); \ } while (0) #define EXPECT_LINT(__STRING__) \ do \ { \ ParseResults results = parse(__STRING__, s_parseOptions); \ expect_false(results.lint().get().empty()); \ } while (0) #define EXPECT_NO_LINT(__STRING__) \ do \ { \ ParseResults results = parse(__STRING__, s_parseOptions); \ expect_true(results.lint().get().empty()); \ } while (0) bool isRFile(const FileInfo& info) { std::string ext = string_utils::getExtension(info.absolutePath()); return string_utils::toLower(ext) == ".r"; } void lintRFilesInSubdirectory(const FilePath& path) { tree<core::FileInfo> fileTree; core::system::FileScannerOptions fsOptions; fsOptions.recursive = true; fsOptions.yield = true; core::system::scanFiles(core::toFileInfo(path), fsOptions, &fileTree); tree<core::FileInfo>::leaf_iterator it = fileTree.begin_leaf(); for (; fileTree.is_valid(it); ++it) { const FileInfo& info = *it; if (info.isDirectory()) continue; if (!isRFile(info)) continue; std::string content = file_utils::readFile(core::toFilePath(info)); ParseResults results = parse(content); if (results.lint().hasErrors()) { FAIL("Lint errors: '" + info.absolutePath() + "'"); } } } void lintRStudioRFiles() { lintRFilesInSubdirectory(options().coreRSourcePath()); lintRFilesInSubdirectory(options().modulesRSourcePath()); } context("Diagnostics") { test_that("valid expressions generate no lint") { EXPECT_NO_ERRORS("print(1)"); EXPECT_NO_ERRORS("1 + 1"); EXPECT_NO_ERRORS("1; 2; 3; 4; 5"); EXPECT_NO_ERRORS("(1)(1, 2, 3)"); EXPECT_NO_ERRORS("{{{}}}"); EXPECT_NO_ERRORS("for (i in 1) 1"); EXPECT_NO_ERRORS("(for (i in 1:10) i)"); EXPECT_NO_ERRORS("for (i in 10) {}"); EXPECT_NO_ERRORS("(1) * (2)"); EXPECT_NO_ERRORS("while ((for (i in 10) {})) 1"); EXPECT_NO_ERRORS("while (for (i in 0) 0) 0"); EXPECT_NO_ERRORS("({while(1){}})"); EXPECT_NO_ERRORS("if (foo) bar"); EXPECT_NO_ERRORS("if (foo) bar else baz"); EXPECT_NO_ERRORS("if (foo) bar else if (baz) bam"); EXPECT_NO_ERRORS("if (foo) bar else if (baz) bam else bat"); EXPECT_NO_ERRORS("if (foo) {} else if (bar) {}"); EXPECT_NO_ERRORS("if (foo) {(1)} else {(1)}"); EXPECT_ERRORS("if (foo) {()} else {()}"); // () with no contents invalid if not function EXPECT_NO_ERRORS("if(foo){bar}else{baz}"); EXPECT_NO_ERRORS("if (a) a() else if (b()) b"); EXPECT_NO_ERRORS("if(1)if(2)if(3)if(4)if(5)5"); EXPECT_NO_ERRORS("if(1)if(2)if(3)if(4)if(5)5 else 6"); EXPECT_NO_ERRORS("a(b()); b"); EXPECT_NO_ERRORS("a(x = b()); b"); EXPECT_NO_ERRORS("a({a();})"); EXPECT_NO_ERRORS("a({a(); if (b) c})"); EXPECT_NO_ERRORS("{a()\nb()}"); EXPECT_NO_ERRORS("a()[[1]]"); EXPECT_NO_ERRORS("a[,a]"); EXPECT_NO_ERRORS("a[,,]"); EXPECT_NO_ERRORS("a(,,1,,,{{}},)"); EXPECT_NO_ERRORS("x[x,,a]"); EXPECT_NO_ERRORS("x(x,,a)"); EXPECT_NO_ERRORS("x[1,,]"); EXPECT_NO_ERRORS("x(1,,)"); EXPECT_NO_ERRORS("a=1 #\nb"); EXPECT_ERRORS("foo(a = 1 b = 2)"); EXPECT_ERRORS("foo(a = 1\nb = 2)"); EXPECT_NO_ERRORS("c(a=function()a,)"); EXPECT_NO_ERRORS("function(a) a"); EXPECT_NO_ERRORS("function(a)\nwhile (1) 1\n"); EXPECT_NO_ERRORS("function(a)\nfor (i in 1) 1\n"); EXPECT_NO_ERRORS("{if(!(a)){};if(b){}}"); EXPECT_NO_ERRORS("if (1) foo(1) <- 1 else 2; 1 + 2"); EXPECT_NO_ERRORS("if (1)\nfoo(1) <- 1\nelse 2; 4 + 8"); EXPECT_NO_ERRORS("if (1) (foo(1) <- {{1}})\n2 + 1"); EXPECT_NO_ERRORS("if (1) function() 1 else 2"); EXPECT_NO_ERRORS("if (1) function() b()() else 2"); EXPECT_NO_ERRORS("if (1) if (2) function() a() else 3 else 4"); EXPECT_NO_ERRORS("if(1)while(2) 2 else 3"); EXPECT_NO_ERRORS("if(1)if(2)while(3)while(4)if(5) 6 else 7 else 8 else 9"); EXPECT_NO_ERRORS("if(1)if(2)while(3)while(4)if(5) foo()[]() else bar() else 8 else 9"); EXPECT_ERRORS("if(1)while(2)function(3)repeat(4)if(5)(function())() else 6"); // function body cannot be empty paren list; in general, '()' not allowed // at 'start' scope EXPECT_ERRORS("(function() ())()"); EXPECT_NO_ERRORS("(function() (1))()"); // EXPECT_ERRORS("if (1) (1)\nelse (2)"); EXPECT_NO_ERRORS("{if (1) (1)\nelse (2)}"); EXPECT_NO_ERRORS("if (a)\nF(b) <- 'c'\nelse if (d) e"); EXPECT_NO_ERRORS("lapply(x, `[[`, 1)"); EXPECT_NO_ERRORS("a((function() {})())"); EXPECT_NO_ERRORS("function(a=1,b=2) {}"); EXPECT_ERRORS("for {i in 1:10}"); EXPECT_ERRORS("((()})"); EXPECT_ERRORS("(a +)"); EXPECT_ERRORS("{a +}"); EXPECT_ERRORS("foo[[bar][baz]]"); EXPECT_NO_ERRORS("myvar <- con; readLines(con = stdin())"); EXPECT_NO_LINT("(function(a) a)"); EXPECT_LINT("a <- 1\nb <- 2\na+b"); EXPECT_NO_LINT("a <- 1\nb <- 2\na +\nb"); EXPECT_NO_LINT("a <- 1\nb <- 2\na()$'b'"); EXPECT_LINT("a <- 1\na$1"); EXPECT_LINT("- 1"); EXPECT_LINT("foo <- 1 + foo"); EXPECT_NO_LINT("foo <- 1 + foo()"); EXPECT_LINT("foo <- rnorm(n = foo)"); EXPECT_LINT("rnorm (1)"); EXPECT_NO_LINT("n <- 1; rnorm(n = n)"); EXPECT_NO_LINT("n <- 1 ## a comment\nprint(n)"); } lintRStudioRFiles(); } } // namespace linter } // namespace modules } // namespace session } // namespace rstudio <commit_msg>add (failing) tests that need fixes<commit_after>/* * SessionDiagnosticsTests.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 <tests/TestThat.hpp> #include "SessionDiagnostics.hpp" #include <iostream> #include <core/collection/Tree.hpp> #include <core/FilePath.hpp> #include <core/system/FileScanner.hpp> #include <core/FileUtils.hpp> #include <boost/algorithm/string.hpp> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <session/SessionOptions.hpp> #include "SessionRParser.hpp" namespace rstudio { namespace session { namespace modules { namespace diagnostics { using namespace rparser; static const ParseOptions s_parseOptions(true); using namespace core; using namespace core::r_util; // We use macros so that the test output gives // meaningful line numbers. #define EXPECT_ERRORS(__STRING__) \ do \ { \ ParseResults results = parse(__STRING__, s_parseOptions); \ expect_true(results.lint().hasErrors()); \ } while (0) #define EXPECT_NO_ERRORS(__STRING__) \ do \ { \ ParseResults results = parse(__STRING__, s_parseOptions); \ if (results.lint().hasErrors()) \ results.lint().dump(); \ expect_false(results.lint().hasErrors()); \ } while (0) #define EXPECT_LINT(__STRING__) \ do \ { \ ParseResults results = parse(__STRING__, s_parseOptions); \ expect_false(results.lint().get().empty()); \ } while (0) #define EXPECT_NO_LINT(__STRING__) \ do \ { \ ParseResults results = parse(__STRING__, s_parseOptions); \ expect_true(results.lint().get().empty()); \ } while (0) bool isRFile(const FileInfo& info) { std::string ext = string_utils::getExtension(info.absolutePath()); return string_utils::toLower(ext) == ".r"; } void lintRFilesInSubdirectory(const FilePath& path) { tree<core::FileInfo> fileTree; core::system::FileScannerOptions fsOptions; fsOptions.recursive = true; fsOptions.yield = true; core::system::scanFiles(core::toFileInfo(path), fsOptions, &fileTree); tree<core::FileInfo>::leaf_iterator it = fileTree.begin_leaf(); for (; fileTree.is_valid(it); ++it) { const FileInfo& info = *it; if (info.isDirectory()) continue; if (!isRFile(info)) continue; std::string content = file_utils::readFile(core::toFilePath(info)); ParseResults results = parse(content); if (results.lint().hasErrors()) { FAIL("Lint errors: '" + info.absolutePath() + "'"); } } } void lintRStudioRFiles() { lintRFilesInSubdirectory(options().coreRSourcePath()); lintRFilesInSubdirectory(options().modulesRSourcePath()); } context("Diagnostics") { test_that("valid expressions generate no lint") { EXPECT_NO_ERRORS("print(1)"); EXPECT_NO_ERRORS("1 + 1"); EXPECT_NO_ERRORS("1; 2; 3; 4; 5"); EXPECT_NO_ERRORS("(1)(1, 2, 3)"); EXPECT_NO_ERRORS("{{{}}}"); EXPECT_NO_ERRORS("for (i in 1) 1"); EXPECT_NO_ERRORS("(for (i in 1:10) i)"); EXPECT_NO_ERRORS("for (i in 10) {}"); EXPECT_NO_ERRORS("(1) * (2)"); EXPECT_NO_ERRORS("while ((for (i in 10) {})) 1"); EXPECT_NO_ERRORS("while (for (i in 0) 0) 0"); EXPECT_NO_ERRORS("({while(1){}})"); EXPECT_NO_ERRORS("if (foo) bar"); EXPECT_NO_ERRORS("if (foo) bar else baz"); EXPECT_NO_ERRORS("if (foo) bar else if (baz) bam"); EXPECT_NO_ERRORS("if (foo) bar else if (baz) bam else bat"); EXPECT_NO_ERRORS("if (foo) {} else if (bar) {}"); EXPECT_NO_ERRORS("if (foo) {(1)} else {(1)}"); EXPECT_ERRORS("if (foo) {()} else {()}"); // () with no contents invalid if not function EXPECT_NO_ERRORS("if(foo){bar}else{baz}"); EXPECT_NO_ERRORS("if (a) a() else if (b()) b"); EXPECT_NO_ERRORS("if(1)if(2)if(3)if(4)if(5)5"); EXPECT_NO_ERRORS("if(1)if(2)if(3)if(4)if(5)5 else 6"); EXPECT_NO_ERRORS("a(b()); b"); EXPECT_NO_ERRORS("a(x = b()); b"); EXPECT_NO_ERRORS("a({a();})"); EXPECT_NO_ERRORS("a({a(); if (b) c})"); EXPECT_NO_ERRORS("{a()\nb()}"); EXPECT_NO_ERRORS("a()[[1]]"); EXPECT_NO_ERRORS("a[,a]"); EXPECT_NO_ERRORS("a[,,]"); EXPECT_NO_ERRORS("a(,,1,,,{{}},)"); EXPECT_NO_ERRORS("x[x,,a]"); EXPECT_NO_ERRORS("x(x,,a)"); EXPECT_NO_ERRORS("x[1,,]"); EXPECT_NO_ERRORS("x(1,,)"); EXPECT_NO_ERRORS("a=1 #\nb"); EXPECT_ERRORS("foo(a = 1 b = 2)"); EXPECT_ERRORS("foo(a = 1\nb = 2)"); EXPECT_NO_ERRORS("c(a=function()a,)"); EXPECT_NO_ERRORS("function(a) a"); EXPECT_NO_ERRORS("function(a)\nwhile (1) 1\n"); EXPECT_NO_ERRORS("function(a)\nfor (i in 1) 1\n"); EXPECT_NO_ERRORS("{if(!(a)){};if(b){}}"); EXPECT_NO_ERRORS("if (1) foo(1) <- 1 else 2; 1 + 2"); EXPECT_NO_ERRORS("if (1)\nfoo(1) <- 1\nelse 2; 4 + 8"); EXPECT_NO_ERRORS("if (1) (foo(1) <- {{1}})\n2 + 1"); EXPECT_NO_ERRORS("if (1) function() 1 else 2"); EXPECT_NO_ERRORS("if (1) function() b()() else 2"); EXPECT_NO_ERRORS("if (1) if (2) function() a() else 3 else 4"); EXPECT_NO_ERRORS("if(1)while(2) 2 else 3"); EXPECT_NO_ERRORS("if(1)if(2)while(3)while(4)if(5) 6 else 7 else 8 else 9"); EXPECT_NO_ERRORS("if(1)if(2)while(3)while(4)if(5) foo()[]() else bar() else 8 else 9"); EXPECT_ERRORS("if(1)while(2)function(3)repeat(4)if(5)(function())() else 6"); EXPECT_NO_ERRORS("if(1)function(){}else 2"); EXPECT_NO_ERRORS("if(1){}\n{}"); EXPECT_NO_ERRORS("foo(1, x=,y=,,,z=1,,,,)"); // function body cannot be empty paren list; in general, '()' not allowed // at 'start' scope EXPECT_ERRORS("(function() ())()"); // EXPECT_ERRORS("if (1) (1)\nelse (2)"); EXPECT_NO_ERRORS("{if (1) (1)\nelse (2)}"); EXPECT_NO_ERRORS("if (a)\nF(b) <- 'c'\nelse if (d) e"); EXPECT_NO_ERRORS("lapply(x, `[[`, 1)"); EXPECT_NO_ERRORS("a((function() {})())"); EXPECT_NO_ERRORS("function(a=1,b=2) {}"); EXPECT_ERRORS("for {i in 1:10}"); EXPECT_ERRORS("((()})"); EXPECT_ERRORS("(a +)"); EXPECT_ERRORS("{a +}"); EXPECT_ERRORS("foo[[bar][baz]]"); EXPECT_NO_ERRORS("myvar <- con; readLines(con = stdin())"); EXPECT_NO_LINT("(function(a) a)"); EXPECT_LINT("a <- 1\nb <- 2\na+b"); EXPECT_NO_LINT("a <- 1\nb <- 2\na +\nb"); EXPECT_NO_LINT("a <- 1\nb <- 2\na()$'b'"); EXPECT_LINT("a <- 1\na$1"); EXPECT_LINT("- 1"); EXPECT_LINT("foo <- 1 + foo"); EXPECT_NO_LINT("foo <- 1 + foo()"); EXPECT_LINT("foo <- rnorm(n = foo)"); EXPECT_LINT("rnorm (1)"); EXPECT_NO_LINT("n <- 1; rnorm(n = n)"); EXPECT_NO_LINT("n <- 1 ## a comment\nprint(n)"); } lintRStudioRFiles(); } } // namespace linter } // namespace modules } // namespace session } // namespace rstudio <|endoftext|>
<commit_before>#ifndef option_types_hh_INCLUDED #define option_types_hh_INCLUDED #include "array_view.hh" #include "coord.hh" #include "containers.hh" #include "exception.hh" #include "flags.hh" #include "hash_map.hh" #include "option.hh" #include "string.hh" #include "units.hh" #include <tuple> #include <vector> namespace Kakoune { template<typename T> constexpr decltype(T::option_type_name) option_type_name(Meta::Type<T>) { return T::option_type_name; } template<typename Enum> typename std::enable_if<std::is_enum<Enum>::value, String>::type option_type_name(Meta::Type<Enum>) { return format("{}({})", with_bit_ops(Meta::Type<Enum>{}) ? "flags" : "enum", join(enum_desc(Meta::Type<Enum>{}) | transform(std::mem_fn(&EnumDesc<Enum>::name)), '|')); } inline String option_to_string(int opt) { return to_string(opt); } inline void option_from_string(StringView str, int& opt) { opt = str_to_int(str); } inline bool option_add(int& opt, StringView str) { auto val = str_to_int(str); opt += val; return val != 0; } constexpr StringView option_type_name(Meta::Type<int>) { return "int"; } inline String option_to_string(size_t opt) { return to_string(opt); } inline void option_from_string(StringView str, size_t& opt) { opt = str_to_int(str); } inline String option_to_string(bool opt) { return opt ? "true" : "false"; } inline void option_from_string(StringView str, bool& opt) { if (str == "true" or str == "yes") opt = true; else if (str == "false" or str == "no") opt = false; else throw runtime_error("boolean values are either true, yes, false or no"); } constexpr StringView option_type_name(Meta::Type<bool>) { return "bool"; } constexpr char list_separator = ':'; template<typename T, MemoryDomain domain> String option_to_string(const Vector<T, domain>& opt) { String res; for (size_t i = 0; i < opt.size(); ++i) { res += escape(option_to_string(opt[i]), list_separator, '\\'); if (i != opt.size() - 1) res += list_separator; } return res; } template<typename T, MemoryDomain domain> void option_from_string(StringView str, Vector<T, domain>& opt) { opt.clear(); Vector<String> elems = split(str, list_separator, '\\'); for (auto& elem: elems) { T opt_elem; option_from_string(elem, opt_elem); opt.push_back(opt_elem); } } template<typename T, MemoryDomain domain> bool option_add(Vector<T, domain>& opt, StringView str) { Vector<T, domain> vec; option_from_string(str, vec); std::copy(std::make_move_iterator(vec.begin()), std::make_move_iterator(vec.end()), back_inserter(opt)); return not vec.empty(); } template<typename T, MemoryDomain D> String option_type_name(Meta::Type<Vector<T, D>>) { return option_type_name(Meta::Type<T>{}) + StringView{"-list"}; } template<typename Key, typename Value, MemoryDomain domain> String option_to_string(const HashMap<Key, Value, domain>& opt) { String res; for (auto it = begin(opt); it != end(opt); ++it) { if (it != begin(opt)) res += list_separator; String elem = escape(option_to_string(it->key), '=', '\\') + "=" + escape(option_to_string(it->value), '=', '\\'); res += escape(elem, list_separator, '\\'); } return res; } template<typename Key, typename Value, MemoryDomain domain> void option_from_string(StringView str, HashMap<Key, Value, domain>& opt) { opt.clear(); for (auto& elem : split(str, list_separator, '\\')) { Vector<String> pair_str = split(elem, '=', '\\'); if (pair_str.size() != 2) throw runtime_error("map option expects key=value"); Key key; Value value; option_from_string(pair_str[0], key); option_from_string(pair_str[1], value); opt.insert({ std::move(key), std::move(value) }); } } template<typename K, typename V, MemoryDomain D> String option_type_name(Meta::Type<HashMap<K, V, D>>) { return format("{}-to-{}-map", option_type_name(Meta::Type<K>{}), option_type_name(Meta::Type<V>{})); } constexpr char tuple_separator = '|'; template<size_t I, typename... Types> struct TupleOptionDetail { static String to_string(const std::tuple<Types...>& opt) { return TupleOptionDetail<I-1, Types...>::to_string(opt) + tuple_separator + escape(option_to_string(std::get<I>(opt)), tuple_separator, '\\'); } static void from_string(ConstArrayView<String> elems, std::tuple<Types...>& opt) { option_from_string(elems[I], std::get<I>(opt)); TupleOptionDetail<I-1, Types...>::from_string(elems, opt); } }; template<typename... Types> struct TupleOptionDetail<0, Types...> { static String to_string(const std::tuple<Types...>& opt) { return option_to_string(std::get<0>(opt)); } static void from_string(ConstArrayView<String> elems, std::tuple<Types...>& opt) { option_from_string(elems[0], std::get<0>(opt)); } }; template<typename... Types> String option_to_string(const std::tuple<Types...>& opt) { return TupleOptionDetail<sizeof...(Types)-1, Types...>::to_string(opt); } template<typename... Types> void option_from_string(StringView str, std::tuple<Types...>& opt) { auto elems = split(str, tuple_separator, '\\'); if (elems.size() != sizeof...(Types)) throw runtime_error(elems.size() < sizeof...(Types) ? "not enough elements in tuple" : "to many elements in tuple"); TupleOptionDetail<sizeof...(Types)-1, Types...>::from_string(elems, opt); } template<typename RealType, typename ValueType> inline String option_to_string(const StronglyTypedNumber<RealType, ValueType>& opt) { return to_string(opt); } template<typename RealType, typename ValueType> inline void option_from_string(StringView str, StronglyTypedNumber<RealType, ValueType>& opt) { opt = StronglyTypedNumber<RealType, ValueType>{str_to_int(str)}; } template<typename RealType, typename ValueType> inline bool option_add(StronglyTypedNumber<RealType, ValueType>& opt, StringView str) { int val = str_to_int(str); opt += val; return val != 0; } struct WorstMatch { template<typename T> WorstMatch(T&&) {} }; inline bool option_add(WorstMatch, StringView) { throw runtime_error("no add operation supported for this option type"); } inline void option_update(WorstMatch, const Context&) { throw runtime_error("no update operation supported for this option type"); } template<typename EffectiveType, typename LineType, typename ColumnType> inline void option_from_string(StringView str, LineAndColumn<EffectiveType, LineType, ColumnType>& opt) { auto vals = split(str, ','); if (vals.size() != 2) throw runtime_error("expected <line>,<column>"); opt.line = str_to_int(vals[0]); opt.column = str_to_int(vals[1]); } template<typename EffectiveType, typename LineType, typename ColumnType> inline String option_to_string(const LineAndColumn<EffectiveType, LineType, ColumnType>& opt) { return format("{},{}", opt.line, opt.column); } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags, String> option_to_string(Flags flags) { constexpr auto desc = enum_desc(Meta::Type<Flags>{}); String res; for (int i = 0; i < desc.size(); ++i) { if (not (flags & desc[i].value)) continue; if (not res.empty()) res += "|"; res += desc[i].name; } return res; } template<typename Enum, typename = decltype(enum_desc(Meta::Type<Enum>{}))> EnableIfWithoutBitOps<Enum, String> option_to_string(Enum e) { constexpr auto desc = enum_desc(Meta::Type<Enum>{}); auto it = find_if(desc, [e](const EnumDesc<Enum>& d) { return d.value == e; }); if (it != desc.end()) return it->name.str(); kak_assert(false); return {}; } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags> option_from_string(StringView str, Flags& flags) { constexpr auto desc = enum_desc(Meta::Type<Flags>{}); flags = Flags{}; for (auto s : str | split<StringView>('|')) { auto it = find_if(desc, [s](const EnumDesc<Flags>& d) { return d.name == s; }); if (it == desc.end()) throw runtime_error(format("invalid flag value '{}'", s)); flags |= it->value; } } template<typename Enum, typename = decltype(enum_desc(Meta::Type<Enum>{}))> EnableIfWithoutBitOps<Enum> option_from_string(StringView str, Enum& e) { constexpr auto desc = enum_desc(Meta::Type<Enum>{}); auto it = find_if(desc, [str](const EnumDesc<Enum>& d) { return d.name == str; }); if (it == desc.end()) throw runtime_error(format("invalid enum value '{}'", str)); e = it->value; } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags, bool> option_add(Flags& opt, StringView str) { Flags res = Flags{}; option_from_string(str, res); opt |= res; return res != (Flags)0; } template<typename P, typename T> inline String option_to_string(const PrefixedList<P, T>& opt) { return format("{}:{}", opt.prefix, option_to_string(opt.list)); } template<typename P, typename T> inline void option_from_string(StringView str, PrefixedList<P, T>& opt) { auto it = find(str, ':'); option_from_string(StringView{str.begin(), it}, opt.prefix); if (it != str.end()) option_from_string({it+1, str.end()}, opt.list); } template<typename P, typename T> inline bool option_add(PrefixedList<P, T>& opt, StringView str) { return option_add(opt.list, str); } } #endif // option_types_hh_INCLUDED <commit_msg>Support option_add for HashMap options<commit_after>#ifndef option_types_hh_INCLUDED #define option_types_hh_INCLUDED #include "array_view.hh" #include "coord.hh" #include "containers.hh" #include "exception.hh" #include "flags.hh" #include "hash_map.hh" #include "option.hh" #include "string.hh" #include "units.hh" #include <tuple> #include <vector> namespace Kakoune { template<typename T> constexpr decltype(T::option_type_name) option_type_name(Meta::Type<T>) { return T::option_type_name; } template<typename Enum> typename std::enable_if<std::is_enum<Enum>::value, String>::type option_type_name(Meta::Type<Enum>) { return format("{}({})", with_bit_ops(Meta::Type<Enum>{}) ? "flags" : "enum", join(enum_desc(Meta::Type<Enum>{}) | transform(std::mem_fn(&EnumDesc<Enum>::name)), '|')); } inline String option_to_string(int opt) { return to_string(opt); } inline void option_from_string(StringView str, int& opt) { opt = str_to_int(str); } inline bool option_add(int& opt, StringView str) { auto val = str_to_int(str); opt += val; return val != 0; } constexpr StringView option_type_name(Meta::Type<int>) { return "int"; } inline String option_to_string(size_t opt) { return to_string(opt); } inline void option_from_string(StringView str, size_t& opt) { opt = str_to_int(str); } inline String option_to_string(bool opt) { return opt ? "true" : "false"; } inline void option_from_string(StringView str, bool& opt) { if (str == "true" or str == "yes") opt = true; else if (str == "false" or str == "no") opt = false; else throw runtime_error("boolean values are either true, yes, false or no"); } constexpr StringView option_type_name(Meta::Type<bool>) { return "bool"; } constexpr char list_separator = ':'; template<typename T, MemoryDomain domain> String option_to_string(const Vector<T, domain>& opt) { String res; for (size_t i = 0; i < opt.size(); ++i) { res += escape(option_to_string(opt[i]), list_separator, '\\'); if (i != opt.size() - 1) res += list_separator; } return res; } template<typename T, MemoryDomain domain> void option_from_string(StringView str, Vector<T, domain>& opt) { opt.clear(); Vector<String> elems = split(str, list_separator, '\\'); for (auto& elem: elems) { T opt_elem; option_from_string(elem, opt_elem); opt.push_back(opt_elem); } } template<typename T, MemoryDomain domain> bool option_add(Vector<T, domain>& opt, StringView str) { Vector<T, domain> vec; option_from_string(str, vec); std::copy(std::make_move_iterator(vec.begin()), std::make_move_iterator(vec.end()), back_inserter(opt)); return not vec.empty(); } template<typename T, MemoryDomain D> String option_type_name(Meta::Type<Vector<T, D>>) { return option_type_name(Meta::Type<T>{}) + StringView{"-list"}; } template<typename Key, typename Value, MemoryDomain domain> String option_to_string(const HashMap<Key, Value, domain>& opt) { String res; for (auto it = begin(opt); it != end(opt); ++it) { if (it != begin(opt)) res += list_separator; String elem = escape(option_to_string(it->key), '=', '\\') + "=" + escape(option_to_string(it->value), '=', '\\'); res += escape(elem, list_separator, '\\'); } return res; } template<typename Key, typename Value, MemoryDomain domain> bool option_add(HashMap<Key, Value, domain>& opt, StringView str) { bool changed = false; for (auto& elem : split(str, list_separator, '\\')) { Vector<String> pair_str = split(elem, '=', '\\'); if (pair_str.size() != 2) throw runtime_error("map option expects key=value"); Key key; Value value; option_from_string(pair_str[0], key); option_from_string(pair_str[1], value); opt.insert({ std::move(key), std::move(value) }); changed = true; } return changed; } template<typename Key, typename Value, MemoryDomain domain> void option_from_string(StringView str, HashMap<Key, Value, domain>& opt) { opt.clear(); option_add(opt, str); } template<typename K, typename V, MemoryDomain D> String option_type_name(Meta::Type<HashMap<K, V, D>>) { return format("{}-to-{}-map", option_type_name(Meta::Type<K>{}), option_type_name(Meta::Type<V>{})); } constexpr char tuple_separator = '|'; template<size_t I, typename... Types> struct TupleOptionDetail { static String to_string(const std::tuple<Types...>& opt) { return TupleOptionDetail<I-1, Types...>::to_string(opt) + tuple_separator + escape(option_to_string(std::get<I>(opt)), tuple_separator, '\\'); } static void from_string(ConstArrayView<String> elems, std::tuple<Types...>& opt) { option_from_string(elems[I], std::get<I>(opt)); TupleOptionDetail<I-1, Types...>::from_string(elems, opt); } }; template<typename... Types> struct TupleOptionDetail<0, Types...> { static String to_string(const std::tuple<Types...>& opt) { return option_to_string(std::get<0>(opt)); } static void from_string(ConstArrayView<String> elems, std::tuple<Types...>& opt) { option_from_string(elems[0], std::get<0>(opt)); } }; template<typename... Types> String option_to_string(const std::tuple<Types...>& opt) { return TupleOptionDetail<sizeof...(Types)-1, Types...>::to_string(opt); } template<typename... Types> void option_from_string(StringView str, std::tuple<Types...>& opt) { auto elems = split(str, tuple_separator, '\\'); if (elems.size() != sizeof...(Types)) throw runtime_error(elems.size() < sizeof...(Types) ? "not enough elements in tuple" : "to many elements in tuple"); TupleOptionDetail<sizeof...(Types)-1, Types...>::from_string(elems, opt); } template<typename RealType, typename ValueType> inline String option_to_string(const StronglyTypedNumber<RealType, ValueType>& opt) { return to_string(opt); } template<typename RealType, typename ValueType> inline void option_from_string(StringView str, StronglyTypedNumber<RealType, ValueType>& opt) { opt = StronglyTypedNumber<RealType, ValueType>{str_to_int(str)}; } template<typename RealType, typename ValueType> inline bool option_add(StronglyTypedNumber<RealType, ValueType>& opt, StringView str) { int val = str_to_int(str); opt += val; return val != 0; } struct WorstMatch { template<typename T> WorstMatch(T&&) {} }; inline bool option_add(WorstMatch, StringView) { throw runtime_error("no add operation supported for this option type"); } inline void option_update(WorstMatch, const Context&) { throw runtime_error("no update operation supported for this option type"); } template<typename EffectiveType, typename LineType, typename ColumnType> inline void option_from_string(StringView str, LineAndColumn<EffectiveType, LineType, ColumnType>& opt) { auto vals = split(str, ','); if (vals.size() != 2) throw runtime_error("expected <line>,<column>"); opt.line = str_to_int(vals[0]); opt.column = str_to_int(vals[1]); } template<typename EffectiveType, typename LineType, typename ColumnType> inline String option_to_string(const LineAndColumn<EffectiveType, LineType, ColumnType>& opt) { return format("{},{}", opt.line, opt.column); } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags, String> option_to_string(Flags flags) { constexpr auto desc = enum_desc(Meta::Type<Flags>{}); String res; for (int i = 0; i < desc.size(); ++i) { if (not (flags & desc[i].value)) continue; if (not res.empty()) res += "|"; res += desc[i].name; } return res; } template<typename Enum, typename = decltype(enum_desc(Meta::Type<Enum>{}))> EnableIfWithoutBitOps<Enum, String> option_to_string(Enum e) { constexpr auto desc = enum_desc(Meta::Type<Enum>{}); auto it = find_if(desc, [e](const EnumDesc<Enum>& d) { return d.value == e; }); if (it != desc.end()) return it->name.str(); kak_assert(false); return {}; } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags> option_from_string(StringView str, Flags& flags) { constexpr auto desc = enum_desc(Meta::Type<Flags>{}); flags = Flags{}; for (auto s : str | split<StringView>('|')) { auto it = find_if(desc, [s](const EnumDesc<Flags>& d) { return d.name == s; }); if (it == desc.end()) throw runtime_error(format("invalid flag value '{}'", s)); flags |= it->value; } } template<typename Enum, typename = decltype(enum_desc(Meta::Type<Enum>{}))> EnableIfWithoutBitOps<Enum> option_from_string(StringView str, Enum& e) { constexpr auto desc = enum_desc(Meta::Type<Enum>{}); auto it = find_if(desc, [str](const EnumDesc<Enum>& d) { return d.name == str; }); if (it == desc.end()) throw runtime_error(format("invalid enum value '{}'", str)); e = it->value; } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags, bool> option_add(Flags& opt, StringView str) { Flags res = Flags{}; option_from_string(str, res); opt |= res; return res != (Flags)0; } template<typename P, typename T> inline String option_to_string(const PrefixedList<P, T>& opt) { return format("{}:{}", opt.prefix, option_to_string(opt.list)); } template<typename P, typename T> inline void option_from_string(StringView str, PrefixedList<P, T>& opt) { auto it = find(str, ':'); option_from_string(StringView{str.begin(), it}, opt.prefix); if (it != str.end()) option_from_string({it+1, str.end()}, opt.list); } template<typename P, typename T> inline bool option_add(PrefixedList<P, T>& opt, StringView str) { return option_add(opt.list, str); } } #endif // option_types_hh_INCLUDED <|endoftext|>
<commit_before>#ifndef option_types_hh_INCLUDED #define option_types_hh_INCLUDED #include "array_view.hh" #include "coord.hh" #include "exception.hh" #include "flags.hh" #include "hash_map.hh" #include "option.hh" #include "ranges.hh" #include "string.hh" #include "string_utils.hh" #include "units.hh" #include <tuple> #include <vector> namespace Kakoune { template<typename T> constexpr decltype(T::option_type_name) option_type_name(Meta::Type<T>) { return T::option_type_name; } template<typename Enum> std::enable_if_t<std::is_enum<Enum>::value, String> option_type_name(Meta::Type<Enum>) { return format("{}({})", with_bit_ops(Meta::Type<Enum>{}) ? "flags" : "enum", join(enum_desc(Meta::Type<Enum>{}) | transform(std::mem_fn(&EnumDesc<Enum>::name)), '|')); } inline String option_to_string(int opt) { return to_string(opt); } inline void option_from_string(StringView str, int& opt) { opt = str_to_int(str); } inline bool option_add(int& opt, StringView str) { auto val = str_to_int(str); opt += val; return val != 0; } constexpr StringView option_type_name(Meta::Type<int>) { return "int"; } inline String option_to_string(size_t opt) { return to_string(opt); } inline void option_from_string(StringView str, size_t& opt) { opt = str_to_int(str); } inline String option_to_string(bool opt) { return opt ? "true" : "false"; } inline void option_from_string(StringView str, bool& opt) { if (str == "true" or str == "yes") opt = true; else if (str == "false" or str == "no") opt = false; else throw runtime_error("boolean values are either true, yes, false or no"); } constexpr StringView option_type_name(Meta::Type<bool>) { return "bool"; } inline String option_to_string(Codepoint opt) { return to_string(opt); } inline void option_from_string(StringView str, Codepoint& opt) { if (str.char_length() != 1) throw runtime_error{format("'{}' is not a single codepoint", str)}; opt = str[0_char]; } constexpr StringView option_type_name(Meta::Type<Codepoint>) { return "codepoint"; } constexpr char list_separator = ':'; template<typename T, MemoryDomain domain> String option_to_string(const Vector<T, domain>& opt) { return join(opt | transform([](const T& t) { return option_to_string(t); }), list_separator); } template<typename T, MemoryDomain domain> void option_list_postprocess(Vector<T, domain>& opt) {} template<typename T, MemoryDomain domain> void option_from_string(StringView str, Vector<T, domain>& opt) { opt.clear(); for (auto& elem : split(str, list_separator, '\\')) { T opt_elem; option_from_string(elem, opt_elem); opt.push_back(opt_elem); } option_list_postprocess(opt); } template<typename T, MemoryDomain domain> bool option_add(Vector<T, domain>& opt, StringView str) { Vector<T, domain> vec; option_from_string(str, vec); opt.insert(opt.end(), std::make_move_iterator(vec.begin()), std::make_move_iterator(vec.end())); option_list_postprocess(opt); return not vec.empty(); } template<typename T, MemoryDomain D> String option_type_name(Meta::Type<Vector<T, D>>) { return option_type_name(Meta::Type<T>{}) + StringView{"-list"}; } template<typename Key, typename Value, MemoryDomain domain> String option_to_string(const HashMap<Key, Value, domain>& opt) { String res; for (auto it = opt.begin(); it != opt.end(); ++it) { if (it != opt.begin()) res += list_separator; String elem = escape(option_to_string(it->key), '=', '\\') + "=" + escape(option_to_string(it->value), '=', '\\'); res += escape(elem, list_separator, '\\'); } return res; } template<typename Key, typename Value, MemoryDomain domain> bool option_add(HashMap<Key, Value, domain>& opt, StringView str) { bool changed = false; for (auto& elem : split(str, list_separator, '\\')) { Vector<String> pair_str = split(elem, '=', '\\'); if (pair_str.size() != 2) throw runtime_error("map option expects key=value"); Key key; Value value; option_from_string(pair_str[0], key); option_from_string(pair_str[1], value); opt.insert({ std::move(key), std::move(value) }); changed = true; } return changed; } template<typename Key, typename Value, MemoryDomain domain> void option_from_string(StringView str, HashMap<Key, Value, domain>& opt) { opt.clear(); option_add(opt, str); } template<typename K, typename V, MemoryDomain D> String option_type_name(Meta::Type<HashMap<K, V, D>>) { return format("{}-to-{}-map", option_type_name(Meta::Type<K>{}), option_type_name(Meta::Type<V>{})); } constexpr char tuple_separator = '|'; template<size_t I, typename... Types> struct TupleOptionDetail { static String to_string(const std::tuple<Types...>& opt) { return TupleOptionDetail<I-1, Types...>::to_string(opt) + tuple_separator + escape(option_to_string(std::get<I>(opt)), tuple_separator, '\\'); } static void from_string(ConstArrayView<String> elems, std::tuple<Types...>& opt) { option_from_string(elems[I], std::get<I>(opt)); TupleOptionDetail<I-1, Types...>::from_string(elems, opt); } }; template<typename... Types> struct TupleOptionDetail<0, Types...> { static String to_string(const std::tuple<Types...>& opt) { return option_to_string(std::get<0>(opt)); } static void from_string(ConstArrayView<String> elems, std::tuple<Types...>& opt) { option_from_string(elems[0], std::get<0>(opt)); } }; template<typename... Types> String option_to_string(const std::tuple<Types...>& opt) { return TupleOptionDetail<sizeof...(Types)-1, Types...>::to_string(opt); } template<typename... Types> void option_from_string(StringView str, std::tuple<Types...>& opt) { auto elems = split(str, tuple_separator, '\\'); if (elems.size() != sizeof...(Types)) throw runtime_error(elems.size() < sizeof...(Types) ? "not enough elements in tuple" : "too many elements in tuple"); TupleOptionDetail<sizeof...(Types)-1, Types...>::from_string(elems, opt); } template<typename RealType, typename ValueType> inline String option_to_string(const StronglyTypedNumber<RealType, ValueType>& opt) { return to_string(opt); } template<typename RealType, typename ValueType> inline void option_from_string(StringView str, StronglyTypedNumber<RealType, ValueType>& opt) { opt = StronglyTypedNumber<RealType, ValueType>{str_to_int(str)}; } template<typename RealType, typename ValueType> inline bool option_add(StronglyTypedNumber<RealType, ValueType>& opt, StringView str) { int val = str_to_int(str); opt += val; return val != 0; } struct WorstMatch { template<typename T> WorstMatch(T&&) {} }; inline bool option_add(WorstMatch, StringView) { throw runtime_error("no add operation supported for this option type"); } class Context; inline void option_update(WorstMatch, const Context&) { throw runtime_error("no update operation supported for this option type"); } template<typename EffectiveType, typename LineType, typename ColumnType> inline void option_from_string(StringView str, LineAndColumn<EffectiveType, LineType, ColumnType>& opt) { auto vals = split(str, ','); if (vals.size() != 2) throw runtime_error("expected <line>,<column>"); opt.line = str_to_int(vals[0]); opt.column = str_to_int(vals[1]); } template<typename EffectiveType, typename LineType, typename ColumnType> inline String option_to_string(const LineAndColumn<EffectiveType, LineType, ColumnType>& opt) { return format("{},{}", opt.line, opt.column); } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags, String> option_to_string(Flags flags) { constexpr auto desc = enum_desc(Meta::Type<Flags>{}); String res; for (int i = 0; i < desc.size(); ++i) { if (not (flags & desc[i].value)) continue; if (not res.empty()) res += "|"; res += desc[i].name; } return res; } template<typename Enum, typename = decltype(enum_desc(Meta::Type<Enum>{}))> EnableIfWithoutBitOps<Enum, String> option_to_string(Enum e) { constexpr auto desc = enum_desc(Meta::Type<Enum>{}); auto it = find_if(desc, [e](const EnumDesc<Enum>& d) { return d.value == e; }); if (it != desc.end()) return it->name.str(); kak_assert(false); return {}; } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags> option_from_string(StringView str, Flags& flags) { constexpr auto desc = enum_desc(Meta::Type<Flags>{}); flags = Flags{}; for (auto s : str | split<StringView>('|')) { auto it = find_if(desc, [s](const EnumDesc<Flags>& d) { return d.name == s; }); if (it == desc.end()) throw runtime_error(format("invalid flag value '{}'", s)); flags |= it->value; } } template<typename Enum, typename = decltype(enum_desc(Meta::Type<Enum>{}))> EnableIfWithoutBitOps<Enum> option_from_string(StringView str, Enum& e) { constexpr auto desc = enum_desc(Meta::Type<Enum>{}); auto it = find_if(desc, [str](const EnumDesc<Enum>& d) { return d.name == str; }); if (it == desc.end()) throw runtime_error(format("invalid enum value '{}'", str)); e = it->value; } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags, bool> option_add(Flags& opt, StringView str) { Flags res = Flags{}; option_from_string(str, res); opt |= res; return res != (Flags)0; } template<typename P, typename T> inline String option_to_string(const PrefixedList<P, T>& opt) { return format("{}:{}", opt.prefix, option_to_string(opt.list)); } template<typename P, typename T> inline void option_from_string(StringView str, PrefixedList<P, T>& opt) { auto it = find(str, ':'); option_from_string(StringView{str.begin(), it}, opt.prefix); if (it != str.end()) option_from_string({it+1, str.end()}, opt.list); } template<typename P, typename T> inline bool option_add(PrefixedList<P, T>& opt, StringView str) { return option_add(opt.list, str); } } #endif // option_types_hh_INCLUDED <commit_msg>Options: rework conversion to string of prefixed lists<commit_after>#ifndef option_types_hh_INCLUDED #define option_types_hh_INCLUDED #include "array_view.hh" #include "coord.hh" #include "exception.hh" #include "flags.hh" #include "hash_map.hh" #include "option.hh" #include "ranges.hh" #include "string.hh" #include "string_utils.hh" #include "units.hh" #include <tuple> #include <vector> namespace Kakoune { template<typename T> constexpr decltype(T::option_type_name) option_type_name(Meta::Type<T>) { return T::option_type_name; } template<typename Enum> std::enable_if_t<std::is_enum<Enum>::value, String> option_type_name(Meta::Type<Enum>) { return format("{}({})", with_bit_ops(Meta::Type<Enum>{}) ? "flags" : "enum", join(enum_desc(Meta::Type<Enum>{}) | transform(std::mem_fn(&EnumDesc<Enum>::name)), '|')); } inline String option_to_string(int opt) { return to_string(opt); } inline void option_from_string(StringView str, int& opt) { opt = str_to_int(str); } inline bool option_add(int& opt, StringView str) { auto val = str_to_int(str); opt += val; return val != 0; } constexpr StringView option_type_name(Meta::Type<int>) { return "int"; } inline String option_to_string(size_t opt) { return to_string(opt); } inline void option_from_string(StringView str, size_t& opt) { opt = str_to_int(str); } inline String option_to_string(bool opt) { return opt ? "true" : "false"; } inline void option_from_string(StringView str, bool& opt) { if (str == "true" or str == "yes") opt = true; else if (str == "false" or str == "no") opt = false; else throw runtime_error("boolean values are either true, yes, false or no"); } constexpr StringView option_type_name(Meta::Type<bool>) { return "bool"; } inline String option_to_string(Codepoint opt) { return to_string(opt); } inline void option_from_string(StringView str, Codepoint& opt) { if (str.char_length() != 1) throw runtime_error{format("'{}' is not a single codepoint", str)}; opt = str[0_char]; } constexpr StringView option_type_name(Meta::Type<Codepoint>) { return "codepoint"; } constexpr char list_separator = ':'; template<typename T, MemoryDomain domain> String option_to_string(const Vector<T, domain>& opt) { return join(opt | transform([](const T& t) { return option_to_string(t); }), list_separator); } template<typename T, MemoryDomain domain> void option_list_postprocess(Vector<T, domain>& opt) {} template<typename T, MemoryDomain domain> void option_from_string(StringView str, Vector<T, domain>& opt) { opt.clear(); for (auto& elem : split(str, list_separator, '\\')) { T opt_elem; option_from_string(elem, opt_elem); opt.push_back(opt_elem); } option_list_postprocess(opt); } template<typename T, MemoryDomain domain> bool option_add(Vector<T, domain>& opt, StringView str) { Vector<T, domain> vec; option_from_string(str, vec); opt.insert(opt.end(), std::make_move_iterator(vec.begin()), std::make_move_iterator(vec.end())); option_list_postprocess(opt); return not vec.empty(); } template<typename T, MemoryDomain D> String option_type_name(Meta::Type<Vector<T, D>>) { return option_type_name(Meta::Type<T>{}) + StringView{"-list"}; } template<typename Key, typename Value, MemoryDomain domain> String option_to_string(const HashMap<Key, Value, domain>& opt) { String res; for (auto it = opt.begin(); it != opt.end(); ++it) { if (it != opt.begin()) res += list_separator; String elem = escape(option_to_string(it->key), '=', '\\') + "=" + escape(option_to_string(it->value), '=', '\\'); res += escape(elem, list_separator, '\\'); } return res; } template<typename Key, typename Value, MemoryDomain domain> bool option_add(HashMap<Key, Value, domain>& opt, StringView str) { bool changed = false; for (auto& elem : split(str, list_separator, '\\')) { Vector<String> pair_str = split(elem, '=', '\\'); if (pair_str.size() != 2) throw runtime_error("map option expects key=value"); Key key; Value value; option_from_string(pair_str[0], key); option_from_string(pair_str[1], value); opt.insert({ std::move(key), std::move(value) }); changed = true; } return changed; } template<typename Key, typename Value, MemoryDomain domain> void option_from_string(StringView str, HashMap<Key, Value, domain>& opt) { opt.clear(); option_add(opt, str); } template<typename K, typename V, MemoryDomain D> String option_type_name(Meta::Type<HashMap<K, V, D>>) { return format("{}-to-{}-map", option_type_name(Meta::Type<K>{}), option_type_name(Meta::Type<V>{})); } constexpr char tuple_separator = '|'; template<size_t I, typename... Types> struct TupleOptionDetail { static String to_string(const std::tuple<Types...>& opt) { return TupleOptionDetail<I-1, Types...>::to_string(opt) + tuple_separator + escape(option_to_string(std::get<I>(opt)), tuple_separator, '\\'); } static void from_string(ConstArrayView<String> elems, std::tuple<Types...>& opt) { option_from_string(elems[I], std::get<I>(opt)); TupleOptionDetail<I-1, Types...>::from_string(elems, opt); } }; template<typename... Types> struct TupleOptionDetail<0, Types...> { static String to_string(const std::tuple<Types...>& opt) { return option_to_string(std::get<0>(opt)); } static void from_string(ConstArrayView<String> elems, std::tuple<Types...>& opt) { option_from_string(elems[0], std::get<0>(opt)); } }; template<typename... Types> String option_to_string(const std::tuple<Types...>& opt) { return TupleOptionDetail<sizeof...(Types)-1, Types...>::to_string(opt); } template<typename... Types> void option_from_string(StringView str, std::tuple<Types...>& opt) { auto elems = split(str, tuple_separator, '\\'); if (elems.size() != sizeof...(Types)) throw runtime_error(elems.size() < sizeof...(Types) ? "not enough elements in tuple" : "too many elements in tuple"); TupleOptionDetail<sizeof...(Types)-1, Types...>::from_string(elems, opt); } template<typename RealType, typename ValueType> inline String option_to_string(const StronglyTypedNumber<RealType, ValueType>& opt) { return to_string(opt); } template<typename RealType, typename ValueType> inline void option_from_string(StringView str, StronglyTypedNumber<RealType, ValueType>& opt) { opt = StronglyTypedNumber<RealType, ValueType>{str_to_int(str)}; } template<typename RealType, typename ValueType> inline bool option_add(StronglyTypedNumber<RealType, ValueType>& opt, StringView str) { int val = str_to_int(str); opt += val; return val != 0; } struct WorstMatch { template<typename T> WorstMatch(T&&) {} }; inline bool option_add(WorstMatch, StringView) { throw runtime_error("no add operation supported for this option type"); } class Context; inline void option_update(WorstMatch, const Context&) { throw runtime_error("no update operation supported for this option type"); } template<typename EffectiveType, typename LineType, typename ColumnType> inline void option_from_string(StringView str, LineAndColumn<EffectiveType, LineType, ColumnType>& opt) { auto vals = split(str, ','); if (vals.size() != 2) throw runtime_error("expected <line>,<column>"); opt.line = str_to_int(vals[0]); opt.column = str_to_int(vals[1]); } template<typename EffectiveType, typename LineType, typename ColumnType> inline String option_to_string(const LineAndColumn<EffectiveType, LineType, ColumnType>& opt) { return format("{},{}", opt.line, opt.column); } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags, String> option_to_string(Flags flags) { constexpr auto desc = enum_desc(Meta::Type<Flags>{}); String res; for (int i = 0; i < desc.size(); ++i) { if (not (flags & desc[i].value)) continue; if (not res.empty()) res += "|"; res += desc[i].name; } return res; } template<typename Enum, typename = decltype(enum_desc(Meta::Type<Enum>{}))> EnableIfWithoutBitOps<Enum, String> option_to_string(Enum e) { constexpr auto desc = enum_desc(Meta::Type<Enum>{}); auto it = find_if(desc, [e](const EnumDesc<Enum>& d) { return d.value == e; }); if (it != desc.end()) return it->name.str(); kak_assert(false); return {}; } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags> option_from_string(StringView str, Flags& flags) { constexpr auto desc = enum_desc(Meta::Type<Flags>{}); flags = Flags{}; for (auto s : str | split<StringView>('|')) { auto it = find_if(desc, [s](const EnumDesc<Flags>& d) { return d.name == s; }); if (it == desc.end()) throw runtime_error(format("invalid flag value '{}'", s)); flags |= it->value; } } template<typename Enum, typename = decltype(enum_desc(Meta::Type<Enum>{}))> EnableIfWithoutBitOps<Enum> option_from_string(StringView str, Enum& e) { constexpr auto desc = enum_desc(Meta::Type<Enum>{}); auto it = find_if(desc, [str](const EnumDesc<Enum>& d) { return d.name == str; }); if (it == desc.end()) throw runtime_error(format("invalid enum value '{}'", str)); e = it->value; } template<typename Flags, typename = decltype(enum_desc(Meta::Type<Flags>{}))> EnableIfWithBitOps<Flags, bool> option_add(Flags& opt, StringView str) { Flags res = Flags{}; option_from_string(str, res); opt |= res; return res != (Flags)0; } template<typename P, typename T> inline String option_to_string(const PrefixedList<P, T>& opt) { if (opt.list.empty()) return format("{}", escape(option_to_string(opt.prefix), list_separator, '\\')); else return format("{}{}{}", escape(option_to_string(opt.prefix), list_separator, '\\'), list_separator, option_to_string(opt.list)); } template<typename P, typename T> inline void option_from_string(StringView str, PrefixedList<P, T>& opt) { auto it = find(str, list_separator); option_from_string(StringView{str.begin(), it}, opt.prefix); if (it != str.end()) option_from_string({it+1, str.end()}, opt.list); } template<typename P, typename T> inline bool option_add(PrefixedList<P, T>& opt, StringView str) { return option_add(opt.list, str); } } #endif // option_types_hh_INCLUDED <|endoftext|>
<commit_before>// // THIS CONTAINS THE IMPLEMENTATION FOR PUBLISHING ON-BOARD CAMERA IMAGES // ON CRAZYFLIE USING THE CAMERA PUBLISHER CLASS // // COPYRIGHT BELONGS TO THE AUTHOR OF THIS CODE // // AUTHOR : LAKSHMAN KUMAR // AFFILIATION : UNIVERSITY OF MARYLAND, MARYLAND ROBOTICS CENTER // EMAIL : LKUMAR93@UMD.EDU // LINKEDIN : WWW.LINKEDIN.COM/IN/LAKSHMANKUMAR1993 // // THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THE MIT LICENSE // THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF // THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. // // BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO // BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS // CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND // CONDITIONS. // /////////////////////////////////////////// // // LIBRARIES // /////////////////////////////////////////// #include <ros/ros.h> #include <cv_bridge/cv_bridge.h> #include <string> #include <iostream> #include <opencv2/highgui/highgui.hpp> #include <sensor_msgs/image_encodings.h> #include <image_transport/image_transport.h> #include <camera_info_manager/camera_info_manager.h> #include <deep_learning_crazyflie/bottom_camera_parameters.h> #include <deep_learning_crazyflie/front_camera_parameters.h> #include <opencv2/videostab.hpp> using namespace cv; using namespace std; /////////////////////////////////////////// // // CLASSES // /////////////////////////////////////////// class CameraPublisher { //Declare all the necessary variables string camera_position; int camera_input_id ; VideoCapture cap; Mat InputImage; Mat UndistortedImage; Mat DeNoisedImage; image_transport::CameraPublisher camera_pub; string prefix = "crazyflie/cameras/"; string postfix = "/image" ; string camera_topic_name ; sensor_msgs::CameraInfo* camera_info; sensor_msgs::CameraInfoPtr camera_info_ptr; cv::Mat_<float> camera_matrix; cv::Mat_<float> distortion_params; public: //Use the constructor to initialize variables CameraPublisher(string position, int id, image_transport::ImageTransport ImageTransporter, double FL_X ,double PP_X ,double FL_Y, double PP_Y, double* DistArray) :camera_matrix(3,3), distortion_params(1,5) { camera_position = position ; camera_input_id = id ; camera_topic_name = prefix + camera_position + postfix ; camera_pub = ImageTransporter.advertiseCamera(camera_topic_name, 1); camera_info = new sensor_msgs::CameraInfo (); camera_info_ptr = sensor_msgs::CameraInfoPtr (camera_info); camera_info_ptr->header.frame_id = camera_position+"_camera"; camera_info->header.frame_id = camera_position+"_camera"; camera_info->width = 640; camera_info->height = 480; camera_info->K.at(0) = FL_X; camera_info->K.at(2) = PP_X; camera_info->K.at(4) = FL_Y; camera_info->K.at(5) = PP_Y; camera_info->K.at(8) = 1; camera_info->P.at(0) = camera_info->K.at(0); camera_info->P.at(1) = 0; camera_info->P.at(2) = camera_info->K.at(2); camera_info->P.at(3) = 0; camera_info->P.at(4) = 0; camera_info->P.at(5) = camera_info->K.at(4); camera_info->P.at(6) = camera_info->K.at(5); camera_info->P.at(7) = 0; camera_info->P.at(8) = 0; camera_info->P.at(9) = 0; camera_info->P.at(10) = 1; camera_info->P.at(11) = 0; camera_info->distortion_model = "plumb_bob"; // Make Rotation Matrix an identity matrix camera_info->R.at(0) = (double) 1; camera_info->R.at(1) = (double) 0; camera_info->R.at(2) = (double) 0; camera_info->R.at(3) = (double) 0; camera_info->R.at(4) = (double) 1; camera_info->R.at(5) = (double) 0; camera_info->R.at(6) = (double) 0; camera_info->R.at(7) = (double) 0; camera_info->R.at(8) = (double) 1; for (int i = 0; i < 5; i++) camera_info->D.push_back (DistArray[i]); camera_matrix << FL_X, 0, PP_X, 0, FL_Y, PP_Y, 0, 0, 1 ; distortion_params << DistArray[0],DistArray[1],DistArray[2],DistArray[3],DistArray[4]; } // Initialize the camera bool Initialize() { cap.open(camera_input_id); cap.set(CV_CAP_PROP_FRAME_WIDTH , 480); cap.set(CV_CAP_PROP_FRAME_HEIGHT , 640); if( !cap.isOpened() ) { ROS_ERROR("Could not initialize camera with id : %d ",camera_input_id); return false; } ROS_INFO("Camera with id : %d initialized",camera_input_id); return true; } // Publish the image from the camera to the corresponding topic void Publish() { ROS_INFO("Publishing image from camera with id : %d ",camera_input_id); cap >> InputImage; if( InputImage.empty() ) { ROS_INFO("Empty image from camera with id : %d ",camera_input_id); } else { sensor_msgs::ImagePtr msg; //undistort(InputImage, UndistortedImage, camera_matrix, distortion_params); GaussianBlur(InputImage,InputImage, Size(5,5),0,0); medianBlur(InputImage,DeNoisedImage,5); //fastNlMeansDenoisingColored(InputImage,DeNoisedImage,3,3,5,11); msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", DeNoisedImage).toImageMsg(); msg->header.stamp = ros::Time::now() ; msg->header.frame_id = camera_position+"_camera"; camera_info->header.stamp = ros::Time::now(); camera_pub.publish(msg, camera_info_ptr) ; } } }; /////////////////////////////////////////// // // MAIN FUNCTION // /////////////////////////////////////////// int main( int argc, char** argv ) { //Initialize the Crazyflie Camera Publisher Node ros::init(argc, argv, "crazyflie_camera_node"); ros::NodeHandle nh; int bottom_camera_id,front_camera_id; image_transport::ImageTransport it(nh); try { bottom_camera_id = atoi(argv[1]); front_camera_id = atoi(argv[2]); } catch (...) { cout << "Camera ID missing in Command Line"; exit(0); } ROS_INFO(" Front Camera = %d Bottom Camera = %d ", front_camera_id, bottom_camera_id); //Create a publisher for the bottom facing camera CameraPublisher bottom_camera_pub("bottom", bottom_camera_id, it, FocalLength_X_Bottom, FocalLength_Y_Bottom, PrincipalPoint_X_Bottom, PrincipalPoint_Y_Bottom, Distortion_Bottom); //Create a publisher for the front facing camera CameraPublisher front_camera_pub("front", front_camera_id, it, FocalLength_X_Front, FocalLength_Y_Front, PrincipalPoint_X_Front, PrincipalPoint_Y_Front, Distortion_Front); //Initialize the cameras and check for errors bool Initialized = bottom_camera_pub.Initialize() && front_camera_pub.Initialize(); //If the camera has been initialized and everything is ok , publish the images from the cameras while(nh.ok() && Initialized) { bottom_camera_pub.Publish() ; front_camera_pub.Publish(); } return 0; } <commit_msg>Change camera publisher queue size to 3<commit_after>// // THIS CONTAINS THE IMPLEMENTATION FOR PUBLISHING ON-BOARD CAMERA IMAGES // ON CRAZYFLIE USING THE CAMERA PUBLISHER CLASS // // COPYRIGHT BELONGS TO THE AUTHOR OF THIS CODE // // AUTHOR : LAKSHMAN KUMAR // AFFILIATION : UNIVERSITY OF MARYLAND, MARYLAND ROBOTICS CENTER // EMAIL : LKUMAR93@UMD.EDU // LINKEDIN : WWW.LINKEDIN.COM/IN/LAKSHMANKUMAR1993 // // THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THE MIT LICENSE // THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF // THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. // // BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO // BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS // CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND // CONDITIONS. // /////////////////////////////////////////// // // LIBRARIES // /////////////////////////////////////////// #include <ros/ros.h> #include <cv_bridge/cv_bridge.h> #include <string> #include <iostream> #include <opencv2/highgui/highgui.hpp> #include <sensor_msgs/image_encodings.h> #include <image_transport/image_transport.h> #include <camera_info_manager/camera_info_manager.h> #include <deep_learning_crazyflie/bottom_camera_parameters.h> #include <deep_learning_crazyflie/front_camera_parameters.h> #include <opencv2/videostab.hpp> using namespace cv; using namespace std; /////////////////////////////////////////// // // CLASSES // /////////////////////////////////////////// class CameraPublisher { //Declare all the necessary variables string camera_position; int camera_input_id ; VideoCapture cap; Mat InputImage; Mat UndistortedImage; Mat DeNoisedImage; image_transport::CameraPublisher camera_pub; string prefix = "crazyflie/cameras/"; string postfix = "/image" ; string camera_topic_name ; sensor_msgs::CameraInfo* camera_info; sensor_msgs::CameraInfoPtr camera_info_ptr; cv::Mat_<float> camera_matrix; cv::Mat_<float> distortion_params; public: //Use the constructor to initialize variables CameraPublisher(string position, int id, image_transport::ImageTransport ImageTransporter, double FL_X ,double PP_X ,double FL_Y, double PP_Y, double* DistArray) :camera_matrix(3,3), distortion_params(1,5) { camera_position = position ; camera_input_id = id ; camera_topic_name = prefix + camera_position + postfix ; camera_pub = ImageTransporter.advertiseCamera(camera_topic_name, 3); camera_info = new sensor_msgs::CameraInfo (); camera_info_ptr = sensor_msgs::CameraInfoPtr (camera_info); camera_info_ptr->header.frame_id = camera_position+"_camera"; camera_info->header.frame_id = camera_position+"_camera"; camera_info->width = 640; camera_info->height = 480; camera_info->K.at(0) = FL_X; camera_info->K.at(2) = PP_X; camera_info->K.at(4) = FL_Y; camera_info->K.at(5) = PP_Y; camera_info->K.at(8) = 1; camera_info->P.at(0) = camera_info->K.at(0); camera_info->P.at(1) = 0; camera_info->P.at(2) = camera_info->K.at(2); camera_info->P.at(3) = 0; camera_info->P.at(4) = 0; camera_info->P.at(5) = camera_info->K.at(4); camera_info->P.at(6) = camera_info->K.at(5); camera_info->P.at(7) = 0; camera_info->P.at(8) = 0; camera_info->P.at(9) = 0; camera_info->P.at(10) = 1; camera_info->P.at(11) = 0; camera_info->distortion_model = "plumb_bob"; // Make Rotation Matrix an identity matrix camera_info->R.at(0) = (double) 1; camera_info->R.at(1) = (double) 0; camera_info->R.at(2) = (double) 0; camera_info->R.at(3) = (double) 0; camera_info->R.at(4) = (double) 1; camera_info->R.at(5) = (double) 0; camera_info->R.at(6) = (double) 0; camera_info->R.at(7) = (double) 0; camera_info->R.at(8) = (double) 1; for (int i = 0; i < 5; i++) camera_info->D.push_back (DistArray[i]); camera_matrix << FL_X, 0, PP_X, 0, FL_Y, PP_Y, 0, 0, 1 ; distortion_params << DistArray[0],DistArray[1],DistArray[2],DistArray[3],DistArray[4]; } // Initialize the camera bool Initialize() { cap.open(camera_input_id); cap.set(CV_CAP_PROP_FRAME_WIDTH , 480); cap.set(CV_CAP_PROP_FRAME_HEIGHT , 640); if( !cap.isOpened() ) { ROS_ERROR("Could not initialize camera with id : %d ",camera_input_id); return false; } ROS_INFO("Camera with id : %d initialized",camera_input_id); return true; } // Publish the image from the camera to the corresponding topic void Publish() { ROS_INFO("Publishing image from camera with id : %d ",camera_input_id); cap >> InputImage; if( InputImage.empty() ) { ROS_INFO("Empty image from camera with id : %d ",camera_input_id); } else { sensor_msgs::ImagePtr msg; //undistort(InputImage, UndistortedImage, camera_matrix, distortion_params); DeNoisedImage = InputImage; //GaussianBlur(InputImage,InputImage, Size(5,5),0,0); //medianBlur(InputImage,DeNoisedImage,5); //fastNlMeansDenoisingColored(InputImage,DeNoisedImage,3,3,5,11); msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", DeNoisedImage).toImageMsg(); msg->header.stamp = ros::Time::now() ; msg->header.frame_id = camera_position+"_camera"; camera_info->header.stamp = ros::Time::now(); camera_pub.publish(msg, camera_info_ptr) ; } } }; /////////////////////////////////////////// // // MAIN FUNCTION // /////////////////////////////////////////// int main( int argc, char** argv ) { //Initialize the Crazyflie Camera Publisher Node ros::init(argc, argv, "crazyflie_camera_node"); ros::NodeHandle nh; int bottom_camera_id,front_camera_id; image_transport::ImageTransport it(nh); try { bottom_camera_id = atoi(argv[1]); front_camera_id = atoi(argv[2]); } catch (...) { cout << "Camera ID missing in Command Line"; exit(0); } ROS_INFO(" Front Camera = %d Bottom Camera = %d ", front_camera_id, bottom_camera_id); //Create a publisher for the bottom facing camera CameraPublisher bottom_camera_pub("bottom", bottom_camera_id, it, FocalLength_X_Bottom, FocalLength_Y_Bottom, PrincipalPoint_X_Bottom, PrincipalPoint_Y_Bottom, Distortion_Bottom); //Create a publisher for the front facing camera CameraPublisher front_camera_pub("front", front_camera_id, it, FocalLength_X_Front, FocalLength_Y_Front, PrincipalPoint_X_Front, PrincipalPoint_Y_Front, Distortion_Front); //Initialize the cameras and check for errors bool Initialized = bottom_camera_pub.Initialize() && front_camera_pub.Initialize(); //If the camera has been initialized and everything is ok , publish the images from the cameras while(nh.ok() && Initialized) { bottom_camera_pub.Publish() ; front_camera_pub.Publish(); } return 0; } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <ros/package.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <image_geometry/stereo_camera_model.h> #include <image_transport/image_transport.h> #include <sensor_msgs/Image.h> #include <stereo_msgs/DisparityImage.h> #include <std_msgs/Int32.h> #include <sensor_msgs/fill_image.h> #include <camera_info_manager/camera_info_manager.h> #include <sstream> #include <pcl_conversions/pcl_conversions.h> //! #include <signal.h> #include <errno.h> #include <fcntl.h> #include <linux/videodev2.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <unistd.h> #include "../include/orsens.h" using namespace cv; using namespace sensor_msgs; ros::Publisher pub_left; ros::Publisher pub_right; ros::Publisher pub_disp; ros::Publisher pub_depth; ros::Publisher pub_disp_filtered; ros::Publisher pub_info; ros::Publisher pub_cloud; Orsens orsens; bool working = false; void sigint_handler(int sig) { working = false; orsens.stop(); ros::shutdown(); } int main (int argc, char** argv) { // Initialize ROS ros::init (argc, argv, "orsens_node"); ros::NodeHandle nh; string capture_mode_string; string data_path; int color_width, depth_width; int color_rate, depth_rate; bool compress_color, compress_depth; bool publish_color, publish_disp, publish_depth; nh.param<string>("/orsens/capture_mode", capture_mode_string, "depth_only"); nh.param<string>("/orsens/data_path", data_path, "../data"); nh.param<int>("/orsens/color_width", color_width, 640); nh.param<int>("/orsens/depth_width", depth_width, 640); nh.param<int>("/orsens/color_rate", color_rate, 15); nh.param<int>("/orsens/depth_rate", depth_rate, 15); nh.param<bool>("/orsens/compress_color", compress_color, false); nh.param<bool>("/orsens/compress_depth", compress_depth, false); nh.param<bool>("/orsens/publish_color", publish_color, true); nh.param<bool>("/orsens/publish_disp", publish_disp, true); nh.param<bool>("/orsens/publish_depth", publish_depth, true); Orsens::CaptureMode capture_mode = Orsens::captureModeFromString(capture_mode_string); printf("params: %d %s\n", color_width, capture_mode_string.c_str()); if (!orsens.start(capture_mode, data_path, color_width, depth_width, color_rate, depth_rate, compress_color, compress_depth)) { ROS_ERROR("unable to start OrSens device, check connection\n"); return -1; } // Create a ROS publishers for the output messages pub_left = nh.advertise<sensor_msgs::Image> ("/orsens/left", 1); pub_right = nh.advertise<sensor_msgs::Image> ("/orsens/right", 1); pub_disp = nh.advertise<sensor_msgs::Image> ("/orsens/disparity", 1); // 0-255 pub_depth = nh.advertise<sensor_msgs::Image> ("/orsens/depth", 1); // uint16 in mm // pub_info = nh.advertise<sensor_msgs::CameraInfo>("/orsens/camera_info", 1); // pub_cloud = nh.advertise<pcl::PCLPointCloud2>("cloud", 1);orsens.getRate() ros::Rate loop_rate(15); working = true; sensor_msgs::Image ros_left, ros_disp, ros_depth; while (nh.ok() && working) { ros::Time time = ros::Time::now(); orsens.grabSensorData(); Mat color = orsens.getLeft(); Mat disp = orsens.getDisp(); Mat depth = orsens.getDepth(); if (publish_color && !color.empty()) { fillImage(ros_left, "rgb8", color.rows, color.cols, 3 * color.cols, color.data); ros_left.header.stamp = time; ros_left.header.frame_id = "orsens_camera"; pub_left.publish(ros_left); //l_info_msg.header.stamp = time; // l_info_msg.header.frame_id = "stereo_camera"; // pub_info.publish(l_info_msg); } if (publish_disp && !disp.empty()) { fillImage(ros_disp, "mono8", disp.rows, disp.cols, disp.cols, disp.data); ros_disp.header.stamp = time; pub_disp.publish(ros_disp); } if (publish_depth && !depth.empty()) { fillImage(ros_depth, "mono16", depth.rows, depth.cols, 2*depth.cols, depth.data); ros_depth.header.stamp = time; pub_depth.publish(ros_depth); } ros::spinOnce(); loop_rate.sleep(); } sigint_handler(0); } <commit_msg>getting correct param name<commit_after>#include <ros/ros.h> #include <ros/package.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <image_geometry/stereo_camera_model.h> #include <image_transport/image_transport.h> #include <sensor_msgs/Image.h> #include <stereo_msgs/DisparityImage.h> #include <std_msgs/Int32.h> #include <sensor_msgs/fill_image.h> #include <camera_info_manager/camera_info_manager.h> #include <sstream> #include <pcl_conversions/pcl_conversions.h> //! #include <signal.h> #include <errno.h> #include <fcntl.h> #include <linux/videodev2.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <unistd.h> #include "../include/orsens.h" using namespace cv; using namespace sensor_msgs; ros::Publisher pub_left; ros::Publisher pub_right; ros::Publisher pub_disp; ros::Publisher pub_depth; ros::Publisher pub_disp_filtered; ros::Publisher pub_info; ros::Publisher pub_cloud; Orsens orsens; bool working = false; void sigint_handler(int sig) { working = false; orsens.stop(); ros::shutdown(); } int main (int argc, char** argv) { // Initialize ROS ros::init (argc, argv, "orsens_node"); ros::NodeHandle nh; string capture_mode_string; string data_path; int color_width, depth_width; int color_rate, depth_rate; bool compress_color, compress_depth; bool publish_color, publish_disp, publish_depth; std::string node_name = ros::this_node::getName(); nh.param<string>(node_name+"/capture_mode", capture_mode_string, "depth_only"); nh.param<string>(node_name+"/data_path", data_path, "../data"); nh.param<int>(node_name+"/color_width", color_width, 640); nh.param<int>(node_name+"/depth_width", depth_width, 640); nh.param<int>(node_name+"/color_rate", color_rate, 15); nh.param<int>(node_name+"/depth_rate", depth_rate, 15); nh.param<bool>(node_name+"/compress_color", compress_color, false); nh.param<bool>(node_name+"/compress_depth", compress_depth, false); nh.param<bool>(node_name+"/publish_color", publish_color, true); nh.param<bool>(node_name+"/publish_disp", publish_disp, true); nh.param<bool>(node_name+"/publish_depth", publish_depth, true); Orsens::CaptureMode capture_mode = Orsens::captureModeFromString(capture_mode_string); printf("params: %d %s\n", color_width, capture_mode_string.c_str()); if (!orsens.start(capture_mode, data_path, color_width, depth_width, color_rate, depth_rate, compress_color, compress_depth)) { ROS_ERROR("unable to start OrSens device, check connection\n"); return -1; } // Create a ROS publishers for the output messages pub_left = nh.advertise<sensor_msgs::Image> ("/orsens/left", 1); pub_right = nh.advertise<sensor_msgs::Image> ("/orsens/right", 1); pub_disp = nh.advertise<sensor_msgs::Image> ("/orsens/disparity", 1); // 0-255 pub_depth = nh.advertise<sensor_msgs::Image> ("/orsens/depth", 1); // uint16 in mm // pub_info = nh.advertise<sensor_msgs::CameraInfo>("/orsens/camera_info", 1); // pub_cloud = nh.advertise<pcl::PCLPointCloud2>("cloud", 1);orsens.getRate() ros::Rate loop_rate(15); working = true; sensor_msgs::Image ros_left, ros_disp, ros_depth; while (nh.ok() && working) { ros::Time time = ros::Time::now(); orsens.grabSensorData(); Mat color = orsens.getLeft(); Mat disp = orsens.getDisp(); Mat depth = orsens.getDepth(); if (publish_color && !color.empty()) { fillImage(ros_left, "rgb8", color.rows, color.cols, 3 * color.cols, color.data); ros_left.header.stamp = time; ros_left.header.frame_id = "orsens_camera"; pub_left.publish(ros_left); //l_info_msg.header.stamp = time; // l_info_msg.header.frame_id = "stereo_camera"; // pub_info.publish(l_info_msg); } if (publish_disp && !disp.empty()) { fillImage(ros_disp, "mono8", disp.rows, disp.cols, disp.cols, disp.data); ros_disp.header.stamp = time; pub_disp.publish(ros_disp); } if (publish_depth && !depth.empty()) { fillImage(ros_depth, "mono16", depth.rows, depth.cols, 2*depth.cols, depth.data); ros_depth.header.stamp = time; pub_depth.publish(ros_depth); } ros::spinOnce(); loop_rate.sleep(); } sigint_handler(0); } <|endoftext|>
<commit_before>#include "phash.h" namespace ys { phash::phash() { first = new unsigned short[F_LENGTH]; second = new unsigned int[S_LENGTH]; third = new unsigned long[T_LENGTH]; } phash::~phash() { delete[] first; delete[] second; delete[] third; } long phash::getpHash(unsigned int key) { int i1 = key >> 21; int i2 = key >> 6; int i3 = key; return first[i1]+second[i2]+third[i3]; } } <commit_msg>Delete phash.cpp<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2014 liblcf authors * This file is released under the MIT License * http://opensource.org/licenses/MIT */ #include "reader_options.h" #ifdef LCF_SUPPORT_ICU # include "unicode/ucsdet.h" # include "unicode/ucnv.h" #else # ifdef _WIN32 # include <cstdio> # define WIN32_LEAN_AND_MEAN # ifndef NOMINMAX # define NOMINMAX # endif # include <windows.h> # endif #endif #ifndef _WIN32 # include <locale> #endif #include <cstdlib> #include <sstream> #include <vector> #include "data.h" #include "inireader.h" #include "ldb_reader.h" #include "reader_util.h" namespace ReaderUtil { } std::string ReaderUtil::CodepageToEncoding(int codepage) { if (codepage == 0) return std::string(); #ifndef LCF_SUPPORT_ICU # ifdef _WIN32 if (codepage > 0) { // Looks like a valid codepage return std::string(codepage); } # endif #endif if (codepage == 932) { #ifdef LCF_SUPPORT_ICU return "cp943"; #else return "SHIFT_JIS"; #endif } if (codepage == 949) { #ifdef LCF_SUPPORT_ICU return "cp949"; #else return "cp1361"; #endif } std::ostringstream out; #ifdef LCF_SUPPORT_ICU out << "windows-" << codepage; #else out << "CP" << codepage; #endif // Check at first if the ini value is a codepage if (!out.str().empty()) { // Looks like a valid codepage return out.str(); } return std::string(); } std::string ReaderUtil::DetectEncoding(const std::string& database_file) { #ifdef LCF_SUPPORT_ICU std::ostringstream text; std::string encoding; //Populate Data::terms or will empty by default even if load fails LDB_Reader::Load(database_file, ""); text << Data::terms.menu_save << " " << Data::terms.menu_quit << " " << Data::terms.new_game << " " << Data::terms.load_game << " " << Data::terms.exit_game << " " << Data::terms.status << " " << Data::terms.row << " " << Data::terms.order << " " << Data::terms.wait_on << " " << Data::terms.wait_off << " " << Data::terms.level << " " << Data::terms.health_points << " " << Data::terms.spirit_points << " " << Data::terms.normal_status << " " << Data::terms.exp_short << " " << Data::terms.lvl_short << " " << Data::terms.hp_short << " " << Data::terms.sp_short << " " << Data::terms.sp_cost << " " << Data::terms.attack << " " << Data::terms.defense << " " << Data::terms.spirit << " " << Data::terms.agility << " " << Data::terms.weapon << " " << Data::terms.shield << " " << Data::terms.armor << " " << Data::terms.helmet << " " << Data::terms.accessory << " " << Data::terms.save_game_message << " " << Data::terms.load_game_message << " " << Data::terms.file << " " << Data::terms.exit_game_message << " " << Data::terms.yes << " " << Data::terms.no; // Checks if there are more than the above 33 spaces (no data) if (text.str().size() > 33) { UErrorCode status = U_ZERO_ERROR; UCharsetDetector* detector = ucsdet_open(&status); ucsdet_setText(detector, text.str().data(), text.str().length(), &status); const UCharsetMatch* match = ucsdet_detect(detector, &status); if (match != NULL) { encoding = ucsdet_getName(match, &status); } ucsdet_close(detector); // Fixes to ensure proper Windows encodings if (encoding == "Shift_JIS") { encoding = "cp943"; // Japanese } else if (encoding == "EUC-KR") { encoding = "cp949"; // Korean } else if (encoding == "ISO-8859-1") { encoding = "windows-1252"; // Occidental } else if (encoding == "ISO-8859-2") { encoding = "windows-1250"; // Central Europe } else if (encoding == "ISO-8859-5") { encoding = "windows-1251"; // Cyrillic } else if (encoding == "ISO-8859-6") { encoding = "windows-1256"; // Arabic } else if (encoding == "ISO-8859-7") { encoding = "windows-1253"; // Greek } else if (encoding == "ISO-8859-8") { encoding = "windows-1255"; // Hebrew } } #endif return encoding; } std::string ReaderUtil::GetEncoding(const std::string& ini_file) { INIReader ini(ini_file); if (ini.ParseError() != -1) { std::string encoding = ini.Get("EasyRPG", "Encoding", std::string()); if (!encoding.empty()) { return ReaderUtil::CodepageToEncoding(atoi(encoding.c_str())); } } return std::string(); } std::string ReaderUtil::GetLocaleEncoding() { #ifdef _WIN32 // On Windows means current system locale. int codepage = 0; #else int codepage = 1252; std::locale loc = std::locale(""); // Gets the language and culture part only std::string loc_full = loc.name().substr(0, loc.name().find_first_of("@.")); // Gets the language part only std::string loc_lang = loc.name().substr(0, loc.name().find_first_of("_")); if (loc_lang == "th") codepage = 874; else if (loc_lang == "ja") codepage = 932; else if (loc_full == "zh_CN" || loc_full == "zh_SG") codepage = 936; else if (loc_lang == "ko") codepage = 949; else if (loc_full == "zh_TW" || loc_full == "zh_HK") codepage = 950; else if (loc_lang == "cs" || loc_lang == "hu" || loc_lang == "pl" || loc_lang == "ro" || loc_lang == "hr" || loc_lang == "sk" || loc_lang == "sl") codepage = 1250; else if (loc_lang == "ru") codepage = 1251; else if (loc_lang == "ca" || loc_lang == "da" || loc_lang == "de" || loc_lang == "en" || loc_lang == "es" || loc_lang == "fi" || loc_lang == "fr" || loc_lang == "it" || loc_lang == "nl" || loc_lang == "nb" || loc_lang == "pt" || loc_lang == "sv" || loc_lang == "eu") codepage = 1252; else if (loc_lang == "el") codepage = 1253; else if (loc_lang == "tr") codepage = 1254; else if (loc_lang == "he") codepage = 1255; else if (loc_lang == "ar") codepage = 1256; else if (loc_lang == "et" || loc_lang == "lt" || loc_lang == "lv") codepage = 1257; else if (loc_lang == "vi") codepage = 1258; #endif return CodepageToEncoding(codepage); } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& source_encoding) { #ifdef _WIN32 return ReaderUtil::Recode(str_to_encode, source_encoding, "65001"); #else return ReaderUtil::Recode(str_to_encode, source_encoding, "UTF-8"); #endif } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& src_enc, const std::string& dst_enc) { std::string encoding_str = src_enc; if (src_enc.empty()) { return str_to_encode; } if (atoi(src_enc.c_str()) > 0) { encoding_str = ReaderUtil::CodepageToEncoding(atoi(src_enc.c_str())); } #ifdef LCF_SUPPORT_ICU UErrorCode status = U_ZERO_ERROR; int size = str_to_encode.size() * 4; UChar unicode_str[size]; // FIXME UConverter *conv; int length; conv = ucnv_open(encoding_str.c_str(), &status); length = ucnv_toUChars(conv, unicode_str, size, str_to_encode.c_str(), -1, &status); ucnv_close(conv); char result[length]; // FIXME conv = ucnv_open(dst_enc.c_str(), &status); ucnv_fromUChars(conv, result, length * 4, unicode_str, -1, &status); ucnv_close(conv); if (status != 0) return std::string(); return std::string(&result[0]); #else # ifdef _WIN32 size_t strsize = str_to_encode.size(); wchar_t* widechar = new wchar_t[strsize * 5 + 1]; // To UTF-16 // Default codepage is 0, so we dont need a check here int res = MultiByteToWideChar(atoi(encoding_str.c_str()), 0, str_to_encode.c_str(), strsize, widechar, strsize * 5 + 1); if (res == 0) { // Invalid codepage delete [] widechar; return str_to_encode; } widechar[res] = '\0'; // Back to UTF-8... char* utf8char = new char[strsize * 5 + 1]; res = WideCharToMultiByte(atoi(dst_enc.c_str()), 0, widechar, res, utf8char, strsize * 5 + 1, NULL, NULL); utf8char[res] = '\0'; // Result in str std::string str = std::string(utf8char, res); delete [] widechar; delete [] utf8char; return str; # else iconv_t cd = iconv_open(dst_enc.c_str(), encoding_str.c_str()); if (cd == (iconv_t)-1) return str_to_encode; char *src = const_cast<char *>(str_to_encode.c_str()); size_t src_left = str_to_encode.size(); size_t dst_size = str_to_encode.size() * 5 + 10; char *dst = new char[dst_size]; size_t dst_left = dst_size; # ifdef ICONV_CONST char ICONV_CONST *p = src; # else char *p = src; # endif char *q = dst; size_t status = iconv(cd, &p, &src_left, &q, &dst_left); iconv_close(cd); if (status == (size_t) -1 || src_left > 0) { delete[] dst; return std::string(); } *q++ = '\0'; std::string result(dst); delete[] dst; return result; # endif #endif } <commit_msg>ICU: Fix warnings and check for errors on first conversion<commit_after>/* * Copyright (c) 2014 liblcf authors * This file is released under the MIT License * http://opensource.org/licenses/MIT */ #include "reader_options.h" #ifdef LCF_SUPPORT_ICU # include "unicode/ucsdet.h" # include "unicode/ucnv.h" #else # ifdef _WIN32 # include <cstdio> # define WIN32_LEAN_AND_MEAN # ifndef NOMINMAX # define NOMINMAX # endif # include <windows.h> # endif #endif #ifndef _WIN32 # include <locale> #endif #include <cstdlib> #include <sstream> #include <vector> #include "data.h" #include "inireader.h" #include "ldb_reader.h" #include "reader_util.h" namespace ReaderUtil { } std::string ReaderUtil::CodepageToEncoding(int codepage) { if (codepage == 0) return std::string(); #ifndef LCF_SUPPORT_ICU # ifdef _WIN32 if (codepage > 0) { // Looks like a valid codepage return std::string(codepage); } # endif #endif if (codepage == 932) { #ifdef LCF_SUPPORT_ICU return "cp943"; #else return "SHIFT_JIS"; #endif } if (codepage == 949) { #ifdef LCF_SUPPORT_ICU return "cp949"; #else return "cp1361"; #endif } std::ostringstream out; #ifdef LCF_SUPPORT_ICU out << "windows-" << codepage; #else out << "CP" << codepage; #endif // Check at first if the ini value is a codepage if (!out.str().empty()) { // Looks like a valid codepage return out.str(); } return std::string(); } std::string ReaderUtil::DetectEncoding(const std::string& database_file) { #ifdef LCF_SUPPORT_ICU std::ostringstream text; std::string encoding; //Populate Data::terms or will empty by default even if load fails LDB_Reader::Load(database_file, ""); text << Data::terms.menu_save << " " << Data::terms.menu_quit << " " << Data::terms.new_game << " " << Data::terms.load_game << " " << Data::terms.exit_game << " " << Data::terms.status << " " << Data::terms.row << " " << Data::terms.order << " " << Data::terms.wait_on << " " << Data::terms.wait_off << " " << Data::terms.level << " " << Data::terms.health_points << " " << Data::terms.spirit_points << " " << Data::terms.normal_status << " " << Data::terms.exp_short << " " << Data::terms.lvl_short << " " << Data::terms.hp_short << " " << Data::terms.sp_short << " " << Data::terms.sp_cost << " " << Data::terms.attack << " " << Data::terms.defense << " " << Data::terms.spirit << " " << Data::terms.agility << " " << Data::terms.weapon << " " << Data::terms.shield << " " << Data::terms.armor << " " << Data::terms.helmet << " " << Data::terms.accessory << " " << Data::terms.save_game_message << " " << Data::terms.load_game_message << " " << Data::terms.file << " " << Data::terms.exit_game_message << " " << Data::terms.yes << " " << Data::terms.no; // Checks if there are more than the above 33 spaces (no data) if (text.str().size() > 33) { UErrorCode status = U_ZERO_ERROR; UCharsetDetector* detector = ucsdet_open(&status); ucsdet_setText(detector, text.str().data(), text.str().length(), &status); const UCharsetMatch* match = ucsdet_detect(detector, &status); if (match != NULL) { encoding = ucsdet_getName(match, &status); } ucsdet_close(detector); // Fixes to ensure proper Windows encodings if (encoding == "Shift_JIS") { encoding = "cp943"; // Japanese } else if (encoding == "EUC-KR") { encoding = "cp949"; // Korean } else if (encoding == "ISO-8859-1") { encoding = "windows-1252"; // Occidental } else if (encoding == "ISO-8859-2") { encoding = "windows-1250"; // Central Europe } else if (encoding == "ISO-8859-5") { encoding = "windows-1251"; // Cyrillic } else if (encoding == "ISO-8859-6") { encoding = "windows-1256"; // Arabic } else if (encoding == "ISO-8859-7") { encoding = "windows-1253"; // Greek } else if (encoding == "ISO-8859-8") { encoding = "windows-1255"; // Hebrew } } #endif return encoding; } std::string ReaderUtil::GetEncoding(const std::string& ini_file) { INIReader ini(ini_file); if (ini.ParseError() != -1) { std::string encoding = ini.Get("EasyRPG", "Encoding", std::string()); if (!encoding.empty()) { return ReaderUtil::CodepageToEncoding(atoi(encoding.c_str())); } } return std::string(); } std::string ReaderUtil::GetLocaleEncoding() { #ifdef _WIN32 // On Windows means current system locale. int codepage = 0; #else int codepage = 1252; std::locale loc = std::locale(""); // Gets the language and culture part only std::string loc_full = loc.name().substr(0, loc.name().find_first_of("@.")); // Gets the language part only std::string loc_lang = loc.name().substr(0, loc.name().find_first_of("_")); if (loc_lang == "th") codepage = 874; else if (loc_lang == "ja") codepage = 932; else if (loc_full == "zh_CN" || loc_full == "zh_SG") codepage = 936; else if (loc_lang == "ko") codepage = 949; else if (loc_full == "zh_TW" || loc_full == "zh_HK") codepage = 950; else if (loc_lang == "cs" || loc_lang == "hu" || loc_lang == "pl" || loc_lang == "ro" || loc_lang == "hr" || loc_lang == "sk" || loc_lang == "sl") codepage = 1250; else if (loc_lang == "ru") codepage = 1251; else if (loc_lang == "ca" || loc_lang == "da" || loc_lang == "de" || loc_lang == "en" || loc_lang == "es" || loc_lang == "fi" || loc_lang == "fr" || loc_lang == "it" || loc_lang == "nl" || loc_lang == "nb" || loc_lang == "pt" || loc_lang == "sv" || loc_lang == "eu") codepage = 1252; else if (loc_lang == "el") codepage = 1253; else if (loc_lang == "tr") codepage = 1254; else if (loc_lang == "he") codepage = 1255; else if (loc_lang == "ar") codepage = 1256; else if (loc_lang == "et" || loc_lang == "lt" || loc_lang == "lv") codepage = 1257; else if (loc_lang == "vi") codepage = 1258; #endif return CodepageToEncoding(codepage); } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& source_encoding) { #ifdef _WIN32 return ReaderUtil::Recode(str_to_encode, source_encoding, "65001"); #else return ReaderUtil::Recode(str_to_encode, source_encoding, "UTF-8"); #endif } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& src_enc, const std::string& dst_enc) { std::string encoding_str = src_enc; if (src_enc.empty()) { return str_to_encode; } if (atoi(src_enc.c_str()) > 0) { encoding_str = ReaderUtil::CodepageToEncoding(atoi(src_enc.c_str())); } #ifdef LCF_SUPPORT_ICU UErrorCode status = U_ZERO_ERROR; int size = str_to_encode.size() * 4; UChar* unicode_str = new UChar[size]; UConverter *conv; int length; conv = ucnv_open(encoding_str.c_str(), &status); length = ucnv_toUChars(conv, unicode_str, size, str_to_encode.c_str(), -1, &status); ucnv_close(conv); if (status != U_ZERO_ERROR) return std::string(); char* result = new char[length * 4]; conv = ucnv_open(dst_enc.c_str(), &status); ucnv_fromUChars(conv, result, length * 4, unicode_str, -1, &status); ucnv_close(conv); if (status != U_ZERO_ERROR) return std::string(); return std::string(&result[0]); #else # ifdef _WIN32 size_t strsize = str_to_encode.size(); wchar_t* widechar = new wchar_t[strsize * 5 + 1]; // To UTF-16 // Default codepage is 0, so we dont need a check here int res = MultiByteToWideChar(atoi(encoding_str.c_str()), 0, str_to_encode.c_str(), strsize, widechar, strsize * 5 + 1); if (res == 0) { // Invalid codepage delete [] widechar; return str_to_encode; } widechar[res] = '\0'; // Back to UTF-8... char* utf8char = new char[strsize * 5 + 1]; res = WideCharToMultiByte(atoi(dst_enc.c_str()), 0, widechar, res, utf8char, strsize * 5 + 1, NULL, NULL); utf8char[res] = '\0'; // Result in str std::string str = std::string(utf8char, res); delete [] widechar; delete [] utf8char; return str; # else iconv_t cd = iconv_open(dst_enc.c_str(), encoding_str.c_str()); if (cd == (iconv_t)-1) return str_to_encode; char *src = const_cast<char *>(str_to_encode.c_str()); size_t src_left = str_to_encode.size(); size_t dst_size = str_to_encode.size() * 5 + 10; char *dst = new char[dst_size]; size_t dst_left = dst_size; # ifdef ICONV_CONST char ICONV_CONST *p = src; # else char *p = src; # endif char *q = dst; size_t status = iconv(cd, &p, &src_left, &q, &dst_left); iconv_close(cd); if (status == (size_t) -1 || src_left > 0) { delete[] dst; return std::string(); } *q++ = '\0'; std::string result(dst); delete[] dst; return result; # endif #endif } <|endoftext|>
<commit_before>#include "BAGame.h" #include "BAGlobal.h" #include "BACharacterSelectionHelper.h" #include "BAVersusScreen.h" #include "ABMapSprites.h" #include "BAUI.h" // -------------------------------------------------- // Helper // -------------------------------------------------- void drawSelection(ABPoint offset, byte animator); void drawTriangles(ABPoint offset, byte animator); // -------------------------------------------------- // GAME CLASS // -------------------------------------------------- BAGame::BAGame(){ player = NULL; enemyPlayer = NULL; } bool BAGame::start(){ // Main game Loop while(true){ // reset game reset(); // Show character selection if(showCharSelect() == BAGamesCommandBack){ playSoundBack(); return true; // return to menu if user wants } if(showVersusScreenWithPlayerAndEnemy(player->getCharacterData(), enemyPlayer->getCharacterData()) == BAGamesCommandBack){ continue; } if(showPositionShips()){ continue; } } return true; } void BAGame::reset(){ delete player; delete enemyPlayer; player = NULL; enemyPlayer = NULL; } // -------------------------------------------------- // CHAR SELECTION // -------------------------------------------------- BAGamesCommand BAGame::showCharSelect(){ BACharacterData availableCharacters[4]; // make char data // name, spriteID, #OfShots per round, small ships, medium ships, large ships, difficulty availableCharacters[0] = BACharacterDataMake("Matt", CharacterIDMatt, 1, 3, 2, 1, CharDifficultyEasy); availableCharacters[1] = BACharacterDataMake("Mimi", CharacterIDMimi, 1, 5, 2, 1, CharDifficultyHard); availableCharacters[2] = BACharacterDataMake("Kenji", CharacterIDKenji, 1, 2, 2, 2, CharDifficultyHard); availableCharacters[3] = BACharacterDataMake("Naru", CharacterIDNaru, 2, 2, 2, 0, CharDifficultyHard); // helper byte selectedCharIndex = 0; byte bgAnimator = 0; byte selectionAnimator = 0; // Screenloop while(true){ if (!arduboy.nextFrame()) continue; // update input globalInput.updateInput(); // check input if(globalInput.pressed(RIGHT_BUTTON)){ selectedCharIndex = (selectedCharIndex+1)%4; } if(globalInput.pressed(LEFT_BUTTON)){ selectedCharIndex = (selectedCharIndex-1)%4; } if(globalInput.pressed(UP_BUTTON)){ selectedCharIndex = (selectedCharIndex-2)%4; } if(globalInput.pressed(DOWN_BUTTON)){ selectedCharIndex = (selectedCharIndex+2)%4; } if(globalInput.pressed(A_BUTTON)){ playSoundBack(); return BAGamesCommandBack; } if(globalInput.pressed(B_BUTTON)){ player = new BAPlayer(availableCharacters[selectedCharIndex]); // get random enemy but not itself byte enemyCharIndex = random(4); while(enemyCharIndex == selectedCharIndex) enemyCharIndex = random(4); enemyPlayer = new BAPlayer(availableCharacters[enemyCharIndex]); return BAGamesCommandNext; } if (arduboy.everyXFrames(3)){ bgAnimator++; bgAnimator = bgAnimator%3; } if (arduboy.everyXFrames(15)){ selectionAnimator++; selectionAnimator = selectionAnimator%2; } ABPoint offset; offset.x = ( ((selectedCharIndex%2) == 0)?0:64); offset.y = ( (selectedCharIndex > 1)?32:0); // clear screen arduboy.clear(); // draw stuff drawSelection(offset, selectionAnimator); drawTriangles(offset, bgAnimator); // draw chars for(size_t i = 0; i < 4; i++){ ABPoint charOffset; charOffset.x = 64 * (i%2); charOffset.y = ((i>1)?32:0); drawCharacterSelectionAsset(availableCharacters[i], charOffset); } arduboy.display(); } return BAGamesCommandErr; } // -------------------------------------------------- // POSITION SHIPS // -------------------------------------------------- BAGamesCommand BAGame::showPositionShips(){ // store information ABPoint playerCursor = ABPointMake(6, 4); bool cursorFlip = true; byte numberOfPlacedShips = 0; bool orienteationHorizontal = true; while(true){ if (!arduboy.nextFrame()) continue; if (arduboy.everyXFrames(10)) cursorFlip = !cursorFlip; // handle input globalInput.updateInput(); if(globalInput.pressed(RIGHT_BUTTON)){ playerCursor.x++; // limit playerCursor.x = ((playerCursor.x >= GAME_BOARD_SIZE_WIDTH)? (GAME_BOARD_SIZE_WIDTH-1) : playerCursor.x); } if(globalInput.pressed(LEFT_BUTTON)){ playerCursor.x--; // limit playerCursor.x = ((playerCursor.x < 0)? -1 : playerCursor.x); // -1 is okay for menu } if(globalInput.pressed(UP_BUTTON)){ playerCursor.y--; // limit playerCursor.y = ((playerCursor.y < 0)? 0 : playerCursor.y); } if(globalInput.pressed(DOWN_BUTTON)){ playerCursor.y++; // limit playerCursor.y = ((playerCursor.y >= GAME_BOARD_SIZE_HEIGHT)? (GAME_BOARD_SIZE_HEIGHT-1) : playerCursor.y); } if(globalInput.pressed(A_BUTTON)){ // Flip orientation orienteationHorizontal = !orienteationHorizontal; } if(globalInput.pressed(B_BUTTON)){ // Check if cancel was pressed if(playerCursor.x < 0){ playSoundBack(); return BAGamesCommandBack; } else{ // check if ship collides with other ship or mountain if (player->playerBoard[playerCursor.y][playerCursor.x] >= 0 || player->playerBoard[playerCursor.y][playerCursor.x] == BAMapTileTypeMountain){ // play error sound and ignore playSoundErr(); } else{ // nope, place ship! playSoundSuccess(); } } } // clear screen arduboy.clear(); // Draw map for player drawMap(player); //======================================= // draw menu //arduboy.drawFastVLine(MENU_WIDTH-1, 0, HEIGHT, WHITE); arduboy.setCursor(1,1); arduboy.print(player->getCharacterData().name); // Info fields arduboy.drawBitmap(0, 28, BAUI_a_rotate, 30, 8, WHITE); arduboy.drawBitmap(0, 40, BAUI_b_place, 30, 8, WHITE); //======================================= // Draw cursor // only draw cursor if index is inside map if(playerCursor.x >= 0){ ABRect cursorFrame; cursorFrame.origin.x = MENU_WIDTH + playerCursor.x*8 + (cursorFlip ? 1:0); cursorFrame.origin.y = playerCursor.y*8 + (cursorFlip ? 1:0); cursorFrame.size.width = cursorFlip ? 6 : 8; cursorFrame.size.height = cursorFlip ? 6 : 8; arduboy.drawRect(cursorFrame.origin.x, cursorFrame.origin.y, cursorFrame.size.width, cursorFrame.size.height, WHITE); // Draw cancle button arduboy.drawBitmap(0, 55, BAUI_cancel, 30, 8, WHITE); } else{ // Draw cancel button arduboy.drawBitmap(0, 55, BAUI_cancel_selected, 30, 8, WHITE); } arduboy.display(); } return BAGamesCommandErr; } <commit_msg>visible ship on map place<commit_after>#include "BAGame.h" #include "BAGlobal.h" #include "BACharacterSelectionHelper.h" #include "BAVersusScreen.h" #include "ABMapSprites.h" #include "BAUI.h" #include "BAShip.h" // -------------------------------------------------- // Helper // -------------------------------------------------- void drawSelection(ABPoint offset, byte animator); void drawTriangles(ABPoint offset, byte animator); // -------------------------------------------------- // GAME CLASS // -------------------------------------------------- BAGame::BAGame(){ player = NULL; enemyPlayer = NULL; } bool BAGame::start(){ // Main game Loop while(true){ // reset game reset(); // Show character selection if(showCharSelect() == BAGamesCommandBack){ playSoundBack(); return true; // return to menu if user wants } if(showVersusScreenWithPlayerAndEnemy(player->getCharacterData(), enemyPlayer->getCharacterData()) == BAGamesCommandBack){ continue; } if(showPositionShips()){ continue; } } return true; } void BAGame::reset(){ delete player; delete enemyPlayer; player = NULL; enemyPlayer = NULL; } // -------------------------------------------------- // CHAR SELECTION // -------------------------------------------------- BAGamesCommand BAGame::showCharSelect(){ BACharacterData availableCharacters[4]; // make char data // name, spriteID, #OfShots per round, small ships, medium ships, large ships, difficulty availableCharacters[0] = BACharacterDataMake("Matt", CharacterIDMatt, 1, 3, 2, 1, CharDifficultyEasy); availableCharacters[1] = BACharacterDataMake("Mimi", CharacterIDMimi, 1, 5, 2, 1, CharDifficultyHard); availableCharacters[2] = BACharacterDataMake("Kenji", CharacterIDKenji, 1, 2, 2, 2, CharDifficultyHard); availableCharacters[3] = BACharacterDataMake("Naru", CharacterIDNaru, 2, 2, 2, 0, CharDifficultyHard); // helper byte selectedCharIndex = 0; byte bgAnimator = 0; byte selectionAnimator = 0; // Screenloop while(true){ if (!arduboy.nextFrame()) continue; // update input globalInput.updateInput(); // check input if(globalInput.pressed(RIGHT_BUTTON)){ selectedCharIndex = (selectedCharIndex+1)%4; } if(globalInput.pressed(LEFT_BUTTON)){ selectedCharIndex = (selectedCharIndex-1)%4; } if(globalInput.pressed(UP_BUTTON)){ selectedCharIndex = (selectedCharIndex-2)%4; } if(globalInput.pressed(DOWN_BUTTON)){ selectedCharIndex = (selectedCharIndex+2)%4; } if(globalInput.pressed(A_BUTTON)){ playSoundBack(); return BAGamesCommandBack; } if(globalInput.pressed(B_BUTTON)){ player = new BAPlayer(availableCharacters[selectedCharIndex]); // get random enemy but not itself byte enemyCharIndex = random(4); while(enemyCharIndex == selectedCharIndex) enemyCharIndex = random(4); enemyPlayer = new BAPlayer(availableCharacters[enemyCharIndex]); return BAGamesCommandNext; } if (arduboy.everyXFrames(3)){ bgAnimator++; bgAnimator = bgAnimator%3; } if (arduboy.everyXFrames(15)){ selectionAnimator++; selectionAnimator = selectionAnimator%2; } ABPoint offset; offset.x = ( ((selectedCharIndex%2) == 0)?0:64); offset.y = ( (selectedCharIndex > 1)?32:0); // clear screen arduboy.clear(); // draw stuff drawSelection(offset, selectionAnimator); drawTriangles(offset, bgAnimator); // draw chars for(size_t i = 0; i < 4; i++){ ABPoint charOffset; charOffset.x = 64 * (i%2); charOffset.y = ((i>1)?32:0); drawCharacterSelectionAsset(availableCharacters[i], charOffset); } arduboy.display(); } return BAGamesCommandErr; } // -------------------------------------------------- // POSITION SHIPS // -------------------------------------------------- BAGamesCommand BAGame::showPositionShips(){ // store information ABPoint playerCursor = ABPointMake(6, 4); bool cursorFlip = true; byte numberOfPlacedShips = 0; bool orienteationHorizontal = true; while(true){ if (!arduboy.nextFrame()) continue; if (arduboy.everyXFrames(10)) cursorFlip = !cursorFlip; // get current ship BAShip currentShip = player->shipAtIndex(numberOfPlacedShips); // handle input globalInput.updateInput(); if(globalInput.pressed(RIGHT_BUTTON)){ playerCursor.x++; } if(globalInput.pressed(LEFT_BUTTON)){ playerCursor.x--; // limit playerCursor.x = ((playerCursor.x < 0)? -1 : playerCursor.x); // -1 is okay for menu } if(globalInput.pressed(UP_BUTTON)){ playerCursor.y--; // limit playerCursor.y = ((playerCursor.y < 0)? 0 : playerCursor.y); } if(globalInput.pressed(DOWN_BUTTON)){ playerCursor.y++; } if(globalInput.pressed(A_BUTTON)){ // Flip orientation orienteationHorizontal = !orienteationHorizontal; } // move cursor inside bounds if ship gets longer int maxX = GAME_BOARD_SIZE_WIDTH - ( orienteationHorizontal ? currentShip.fullLength : 1); int maxY = GAME_BOARD_SIZE_HEIGHT - ( !orienteationHorizontal ? currentShip.fullLength : 1); playerCursor.y = ((playerCursor.y > maxY)? maxY : playerCursor.y); playerCursor.x = ((playerCursor.x > maxX)? maxX : playerCursor.x); if(globalInput.pressed(B_BUTTON)){ // Check if cancel was pressed if(playerCursor.x < 0){ playSoundBack(); return BAGamesCommandBack; } else{ // check if ship collides with other ship or mountain if (player->playerBoard[playerCursor.y][playerCursor.x] >= 0 || player->playerBoard[playerCursor.y][playerCursor.x] == BAMapTileTypeMountain){ // play error sound and ignore playSoundErr(); } else{ // nope, place ship! playSoundSuccess(); numberOfPlacedShips++; // check if done if(numberOfPlacedShips == player->numberOfShips){ // show done? } } } } // clear screen arduboy.clear(); // Draw map for player drawMap(player); //======================================= // draw menu arduboy.setCursor(1,1); arduboy.println(player->getCharacterData().name); arduboy.println(player->numberOfShips); // Info fields arduboy.drawBitmap(0, 28, BAUI_a_rotate, 30, 8, WHITE); arduboy.drawBitmap(0, 40, BAUI_b_place, 30, 8, WHITE); //======================================= // Draw cursor // only draw cursor if index is inside map if(playerCursor.x >= 0){ ABPoint shipPos; shipPos.x = MENU_WIDTH + playerCursor.x*8; shipPos.y = playerCursor.y*8; // draw current ship if(orienteationHorizontal){ drawHorizontalShip(shipPos, currentShip.fullLength, WHITE); } else{ drawVerticalShip(shipPos, currentShip.fullLength, WHITE); } ABRect cursorFrame; cursorFrame.origin.x = shipPos.x + (cursorFlip ? 1:0); cursorFrame.origin.y = shipPos.y + (cursorFlip ? 1:0); cursorFrame.size.width = cursorFlip ? 6 : 8; cursorFrame.size.height = cursorFlip ? 6 : 8; arduboy.drawRect(cursorFrame.origin.x, cursorFrame.origin.y, cursorFrame.size.width, cursorFrame.size.height, WHITE); // Draw cancle button arduboy.drawBitmap(0, 55, BAUI_cancel, 30, 8, WHITE); } else{ // Draw cancel button arduboy.drawBitmap(0, 55, BAUI_cancel_selected, 30, 8, WHITE); } arduboy.display(); } return BAGamesCommandErr; } <|endoftext|>
<commit_before>/* * opencog/atoms/execution/EvaluationLink.cc * * Copyright (C) 2009, 2013, 2014, 2015 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atomspace/atom_types.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/SimpleTruthValue.h> #include <opencog/atoms/NumberNode.h> #include <opencog/cython/PythonEval.h> #include <opencog/guile/SchemeEval.h> #include "EvaluationLink.h" #include "ExecutionOutputLink.h" using namespace opencog; EvaluationLink::EvaluationLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FreeLink(EVALUATION_LINK, oset, tv, av) { if ((2 != oset.size()) or (LIST_LINK != oset[1]->getType())) { throw RuntimeException(TRACE_INFO, "EvaluationLink must have predicate and args!"); } } EvaluationLink::EvaluationLink(Handle schema, Handle args, TruthValuePtr tv, AttentionValuePtr av) : FreeLink(EVALUATION_LINK, schema, args, tv, av) { if (LIST_LINK != args->getType()) { throw RuntimeException(TRACE_INFO, "EvaluationLink must have args in a ListLink!"); } } EvaluationLink::EvaluationLink(Link& l) : FreeLink(l) { Type tscope = l.getType(); if (EVALUATION_LINK != tscope) { throw RuntimeException(TRACE_INFO, "Expecting an EvaluationLink"); } } // Perform a GreaterThan check static TruthValuePtr greater(AtomSpace* as, LinkPtr ll) { if (2 != ll->getArity()) throw RuntimeException(TRACE_INFO, "GreaterThankLink expects two arguments"); Handle h1(ll->getOutgoingAtom(0)); Handle h2(ll->getOutgoingAtom(1)); if (NUMBER_NODE != h1->getType()) h1 = ExecutionOutputLink::do_execute(as, h1); if (NUMBER_NODE != h2->getType()) h2 = ExecutionOutputLink::do_execute(as, h2); NumberNodePtr n1(NumberNodeCast(h1)); NumberNodePtr n2(NumberNodeCast(h2)); if (NULL == n1 or NULL == n2) throw RuntimeException(TRACE_INFO, "Expecting c++:greater arguments to be NumberNode's!"); if (n1->getValue() > n2->getValue()) return TruthValue::TRUE_TV(); else return TruthValue::FALSE_TV(); } static TruthValuePtr equal(AtomSpace* as, LinkPtr ll) { const HandleSeq& oset = ll->getOutgoingSet(); if (2 != oset.size()) throw RuntimeException(TRACE_INFO, "EqualLink expects two arguments"); if (oset[0] == oset[1]) return TruthValue::TRUE_TV(); else return TruthValue::FALSE_TV(); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects the argument to be an EvaluationLink, which should have the /// following structure: /// /// EvaluationLink /// GroundedPredicateNode "lang: func_name" /// ListLink /// SomeAtom /// OtherAtom /// /// The "lang:" should be either "scm:" for scheme, or "py:" for python. /// This method will then invoke "func_name" on the provided ListLink /// of arguments to the function. /// TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, Handle execlnk) { Type t = execlnk->getType(); if (EVALUATION_LINK == t) { LinkPtr l(LinkCast(execlnk)); return do_evaluate(as, l->getOutgoingSet()); } else if (EQUAL_LINK == t) { return equal(as, LinkCast(execlnk)); } else if (GREATER_THAN_LINK == t) { return greater(as, LinkCast(execlnk)); } else if (NOT_LINK == t) { LinkPtr l(LinkCast(execlnk)); TruthValuePtr tv(do_evaluate(as, l->getOutgoingAtom(0))); return SimpleTruthValue::createTV( 1.0 - tv->getMean(), tv->getCount()); } throw RuntimeException(TRACE_INFO, "Expecting to get an EvaluationLink!"); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects the sequence to be exactly two atoms long. /// Expects the first handle of the sequence to be a GroundedPredicateNode /// Expects the second handle of the sequence to be a ListLink /// Executes the GroundedPredicateNode, supplying the second handle as argument /// TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, const HandleSeq& sna) { if (2 != sna.size()) { throw RuntimeException(TRACE_INFO, "Incorrect arity for an EvaluationLink!"); } return do_evaluate(as, sna[0], sna[1]); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects "gsn" to be a GroundedPredicateNode /// Expects "args" to be a ListLink /// Executes the GroundedPredicateNode, supplying the args as argument /// TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, Handle gsn, Handle args) { if (GROUNDED_PREDICATE_NODE != gsn->getType()) { throw RuntimeException(TRACE_INFO, "Expecting GroundedPredicateNode!"); } if (LIST_LINK != args->getType()) { throw RuntimeException(TRACE_INFO, "Expecting arguments to EvaluationLink!"); } // Get the schema name. const std::string& schema = NodeCast(gsn)->getName(); // printf ("Grounded schema name: %s\n", schema.c_str()); // A very special-case C++ comparison. // This compares two NumberNodes, by their numeric value. // Hard-coded in C++ for speed. (well, and for convenience ...) if (0 == schema.compare("c++:greater")) { return greater(as, LinkCast(args)); } // A very special-case C++ comparison. // This compares a set of atoms, verifying that they are all different. // Hard-coded in C++ for speed. (well, and for convenience ...) if (0 == schema.compare("c++:exclusive")) { LinkPtr ll(LinkCast(args)); Arity sz = ll->getArity(); for (Arity i=0; i<sz-1; i++) { Handle h1(ll->getOutgoingAtom(i)); for (Arity j=i+1; j<sz; j++) { Handle h2(ll->getOutgoingAtom(j)); if (h1 == h2) return TruthValue::FALSE_TV(); } } return TruthValue::TRUE_TV(); } // At this point, we only run scheme and python schemas. if (0 == schema.compare(0,4,"scm:", 4)) { #ifdef HAVE_GUILE // Be friendly, and strip leading white-space, if any. size_t pos = 4; while (' ' == schema[pos]) pos++; SchemeEval* applier = get_evaluator(as); return applier->apply_tv(schema.substr(pos), args); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate scheme GroundedPredicateNode!"); #endif /* HAVE_GUILE */ } if (0 == schema.compare(0, 3,"py:", 3)) { #ifdef HAVE_CYTHON // Be friendly, and strip leading white-space, if any. size_t pos = 3; while (' ' == schema[pos]) pos++; PythonEval &applier = PythonEval::instance(); // std::string rc = applier.apply(schema.substr(pos), args); // if (rc.compare("None") or rc.compare("False")) return false; return applier.apply_tv(schema.substr(pos), args); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate python GroundedPredicateNode!"); #endif /* HAVE_CYTHON */ } // Unkown proceedure type. throw RuntimeException(TRACE_INFO, "Cannot evaluate unknown GroundedPredicateNode: %s", schema.c_str()); } <commit_msg>minor printing fix<commit_after>/* * opencog/atoms/execution/EvaluationLink.cc * * Copyright (C) 2009, 2013, 2014, 2015 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atomspace/atom_types.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/SimpleTruthValue.h> #include <opencog/atoms/NumberNode.h> #include <opencog/cython/PythonEval.h> #include <opencog/guile/SchemeEval.h> #include "EvaluationLink.h" #include "ExecutionOutputLink.h" using namespace opencog; EvaluationLink::EvaluationLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FreeLink(EVALUATION_LINK, oset, tv, av) { if ((2 != oset.size()) or (LIST_LINK != oset[1]->getType())) { throw RuntimeException(TRACE_INFO, "EvaluationLink must have predicate and args!"); } } EvaluationLink::EvaluationLink(Handle schema, Handle args, TruthValuePtr tv, AttentionValuePtr av) : FreeLink(EVALUATION_LINK, schema, args, tv, av) { if (LIST_LINK != args->getType()) { throw RuntimeException(TRACE_INFO, "EvaluationLink must have args in a ListLink!"); } } EvaluationLink::EvaluationLink(Link& l) : FreeLink(l) { Type tscope = l.getType(); if (EVALUATION_LINK != tscope) { throw RuntimeException(TRACE_INFO, "Expecting an EvaluationLink"); } } // Perform a GreaterThan check static TruthValuePtr greater(AtomSpace* as, LinkPtr ll) { if (2 != ll->getArity()) throw RuntimeException(TRACE_INFO, "GreaterThankLink expects two arguments"); Handle h1(ll->getOutgoingAtom(0)); Handle h2(ll->getOutgoingAtom(1)); if (NUMBER_NODE != h1->getType()) h1 = ExecutionOutputLink::do_execute(as, h1); if (NUMBER_NODE != h2->getType()) h2 = ExecutionOutputLink::do_execute(as, h2); NumberNodePtr n1(NumberNodeCast(h1)); NumberNodePtr n2(NumberNodeCast(h2)); if (NULL == n1 or NULL == n2) throw RuntimeException(TRACE_INFO, "Expecting c++:greater arguments to be NumberNode's! Got:\n%s\n", (h1==NULL)? "(invalid handle)" : h1->toShortString().c_str(), (h2==NULL)? "(invalid handle)" : h2->toShortString().c_str()); if (n1->getValue() > n2->getValue()) return TruthValue::TRUE_TV(); else return TruthValue::FALSE_TV(); } static TruthValuePtr equal(AtomSpace* as, LinkPtr ll) { const HandleSeq& oset = ll->getOutgoingSet(); if (2 != oset.size()) throw RuntimeException(TRACE_INFO, "EqualLink expects two arguments"); if (oset[0] == oset[1]) return TruthValue::TRUE_TV(); else return TruthValue::FALSE_TV(); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects the argument to be an EvaluationLink, which should have the /// following structure: /// /// EvaluationLink /// GroundedPredicateNode "lang: func_name" /// ListLink /// SomeAtom /// OtherAtom /// /// The "lang:" should be either "scm:" for scheme, or "py:" for python. /// This method will then invoke "func_name" on the provided ListLink /// of arguments to the function. /// TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, Handle execlnk) { Type t = execlnk->getType(); if (EVALUATION_LINK == t) { LinkPtr l(LinkCast(execlnk)); return do_evaluate(as, l->getOutgoingSet()); } else if (EQUAL_LINK == t) { return equal(as, LinkCast(execlnk)); } else if (GREATER_THAN_LINK == t) { return greater(as, LinkCast(execlnk)); } else if (NOT_LINK == t) { LinkPtr l(LinkCast(execlnk)); TruthValuePtr tv(do_evaluate(as, l->getOutgoingAtom(0))); return SimpleTruthValue::createTV( 1.0 - tv->getMean(), tv->getCount()); } throw RuntimeException(TRACE_INFO, "Expecting to get an EvaluationLink!"); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects the sequence to be exactly two atoms long. /// Expects the first handle of the sequence to be a GroundedPredicateNode /// Expects the second handle of the sequence to be a ListLink /// Executes the GroundedPredicateNode, supplying the second handle as argument /// TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, const HandleSeq& sna) { if (2 != sna.size()) { throw RuntimeException(TRACE_INFO, "Incorrect arity for an EvaluationLink!"); } return do_evaluate(as, sna[0], sna[1]); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects "gsn" to be a GroundedPredicateNode /// Expects "args" to be a ListLink /// Executes the GroundedPredicateNode, supplying the args as argument /// TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, Handle gsn, Handle args) { if (GROUNDED_PREDICATE_NODE != gsn->getType()) { throw RuntimeException(TRACE_INFO, "Expecting GroundedPredicateNode!"); } if (LIST_LINK != args->getType()) { throw RuntimeException(TRACE_INFO, "Expecting arguments to EvaluationLink!"); } // Get the schema name. const std::string& schema = NodeCast(gsn)->getName(); // printf ("Grounded schema name: %s\n", schema.c_str()); // A very special-case C++ comparison. // This compares two NumberNodes, by their numeric value. // Hard-coded in C++ for speed. (well, and for convenience ...) if (0 == schema.compare("c++:greater")) { return greater(as, LinkCast(args)); } // A very special-case C++ comparison. // This compares a set of atoms, verifying that they are all different. // Hard-coded in C++ for speed. (well, and for convenience ...) if (0 == schema.compare("c++:exclusive")) { LinkPtr ll(LinkCast(args)); Arity sz = ll->getArity(); for (Arity i=0; i<sz-1; i++) { Handle h1(ll->getOutgoingAtom(i)); for (Arity j=i+1; j<sz; j++) { Handle h2(ll->getOutgoingAtom(j)); if (h1 == h2) return TruthValue::FALSE_TV(); } } return TruthValue::TRUE_TV(); } // At this point, we only run scheme and python schemas. if (0 == schema.compare(0,4,"scm:", 4)) { #ifdef HAVE_GUILE // Be friendly, and strip leading white-space, if any. size_t pos = 4; while (' ' == schema[pos]) pos++; SchemeEval* applier = get_evaluator(as); return applier->apply_tv(schema.substr(pos), args); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate scheme GroundedPredicateNode!"); #endif /* HAVE_GUILE */ } if (0 == schema.compare(0, 3,"py:", 3)) { #ifdef HAVE_CYTHON // Be friendly, and strip leading white-space, if any. size_t pos = 3; while (' ' == schema[pos]) pos++; PythonEval &applier = PythonEval::instance(); // std::string rc = applier.apply(schema.substr(pos), args); // if (rc.compare("None") or rc.compare("False")) return false; return applier.apply_tv(schema.substr(pos), args); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate python GroundedPredicateNode!"); #endif /* HAVE_CYTHON */ } // Unkown proceedure type. throw RuntimeException(TRACE_INFO, "Cannot evaluate unknown GroundedPredicateNode: %s", schema.c_str()); } <|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 <> struct RunnableMethodTraits<Touchpad> { void RetainCallee(Touchpad*) {} void ReleaseCallee(Touchpad*) {} }; // 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); } <commit_msg>Tweak touchpad settings for better performance. TEST=none BUG=23996 Review URL: http://codereview.chromium.org/242164<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 <> struct RunnableMethodTraits<Touchpad> { void RetainCallee(Touchpad*) {} void ReleaseCallee(Touchpad*) {} }; // 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 MaxSpeed. MinSpeed is set to 0.2. // MaxSpeed can go from 0.2 to 1.1. The preference is an integer between // 1 and 10, so we divide that by 10 and add 0.1 for the value of MaxSpeed. int value = speed_factor_.GetValue(); if (value < 1) value = 1; if (value > 10) value = 10; // Convert from 1-10 to 0.2-1.1 double d = static_cast<double>(value) / 10.0 + 0.1; SetSynclientParam("MaxSpeed", 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>/** * The MIT License (MIT) * * Copyright © 2018 Ruben Van Boxem * * 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 "css/test_rule.h++" #include <css/grammar/property_symbols_table.h++> namespace { using skui::core::string; enum class Enum { one, two }; const string inherit = "inherit"; const string initial = "initial"; const string one = "one"; const string two = "two"; struct enum_table : skui::css::grammar::property_symbols_table<Enum> { enum_table() { add("one", Enum::one) ("two", Enum::two) ; } } const enum_parser; using namespace boost::spirit::x3; const auto enum_rule = rule<struct enum_rule, skui::css::property<Enum>>{"enum rule"} = enum_parser; } int main() { using skui::test::check_rule_success; check_rule_success(enum_rule, inherit, skui::css::inherit); check_rule_success(enum_rule, initial, skui::css::initial); check_rule_success(enum_rule, one, Enum::one); check_rule_success(enum_rule, two, Enum::two); return skui::test::exit_code; } <commit_msg>Fix test for Clang.<commit_after>/** * The MIT License (MIT) * * Copyright © 2018 Ruben Van Boxem * * 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 "css/test_rule.h++" #include <css/grammar/property_symbols_table.h++> enum class Enum { one, two }; std::ostream& operator<<(std::ostream& os, skui::css::property<Enum>) { return os; } namespace { using skui::core::string; const string inherit = "inherit"; const string initial = "initial"; const string one = "one"; const string two = "two"; struct enum_table : skui::css::grammar::property_symbols_table<Enum> { enum_table() { add("one", Enum::one) ("two", Enum::two) ; } } const enum_parser; using namespace boost::spirit::x3; const auto enum_rule = rule<struct enum_rule, skui::css::property<Enum>>{"enum rule"} = enum_parser; } int main() { using skui::test::check_rule_success; check_rule_success(enum_rule, inherit, skui::css::inherit); check_rule_success(enum_rule, initial, skui::css::initial); check_rule_success(enum_rule, one, Enum::one); check_rule_success(enum_rule, two, Enum::two); return skui::test::exit_code; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewcontactoftextobj.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:46:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _SDR_CONTACT_VIEWCONTACTOFTEXTOBJ_HXX #include <svx/sdr/contact/viewcontactoftextobj.hxx> #endif #ifndef _SVDOTEXT_HXX #include <svx/svdotext.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { ViewContactOfTextObj::ViewContactOfTextObj(SdrTextObj& rTextObj) : ViewContactOfSdrObj(rTextObj) { } ViewContactOfTextObj::~ViewContactOfTextObj() { } } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS changefileheader (1.5.368); FILE MERGED 2008/04/01 12:49:32 thb 1.5.368.2: #i85898# Stripping all external header guards 2008/03/31 14:23:11 rt 1.5.368.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewcontactoftextobj.cxx,v $ * $Revision: 1.6 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <svx/sdr/contact/viewcontactoftextobj.hxx> #include <svx/svdotext.hxx> ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { ViewContactOfTextObj::ViewContactOfTextObj(SdrTextObj& rTextObj) : ViewContactOfSdrObj(rTextObj) { } ViewContactOfTextObj::~ViewContactOfTextObj() { } } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>/* * 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 Library 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. * * ola-recorder.cpp * A simple tool to record & playback shows. * Copyright (C) 2011 Simon Newton */ #include <errno.h> #include <getopt.h> #include <string.h> #include <sysexits.h> #include <ola/DmxBuffer.h> #include <ola/Logging.h> #include <ola/StringUtils.h> #include <iostream> #include <map> #include <string> #include <vector> #include "examples/ShowPlayer.h" #include "examples/ShowLoader.h" #include "examples/ShowRecorder.h" using std::cout; using std::endl; using std::map; using std::vector; using std::string; using ola::OlaUniverse; using ola::SimpleClient; typedef struct { ola::log_level level; bool help; // show the help string cmd; // argv[0] bool playback; bool record; bool verify; // 0 means infinite looping unsigned int loop_iterations; unsigned int loop_delay; string file; string universes; } options; /* * Parse our cmd line options. */ int ParseOptions(int argc, char *argv[], options *opts) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"delay", required_argument, 0, 'd'}, {"iterations", required_argument, 0, 'i'}, {"log-level", required_argument, 0, 'l'}, {"playback", required_argument, 0, 'p'}, {"record", required_argument, 0, 'r'}, {"universes", required_argument, 0, 'u'}, {"verify", required_argument, 0, 'v'}, {0, 0, 0, 0} }; opts->help = false; opts->level = ola::OLA_LOG_INFO; opts->playback = false; opts->loop_iterations = 1; opts->loop_delay = 0; opts->record = false; opts->verify = false; int c, ll; int option_index = 0; while (1) { c = getopt_long(argc, argv, "d:hi:l:p:r:u:v:", long_options, &option_index); if (c == -1) break; switch (c) { case 0: break; case 'd': opts->loop_delay = atoi(optarg); break; case 'h': opts->help = true; break; case 'i': opts->loop_iterations = atoi(optarg); break; case 'l': ll = atoi(optarg); switch (ll) { case 0: // nothing is written at this level // so this turns logging off opts->level = ola::OLA_LOG_NONE; break; case 1: opts->level = ola::OLA_LOG_FATAL; break; case 2: opts->level = ola::OLA_LOG_WARN; break; case 3: opts->level = ola::OLA_LOG_INFO; break; case 4: opts->level = ola::OLA_LOG_DEBUG; break; default : break; } break; case 'p': opts->file = optarg; opts->playback = true; break; case 'r': opts->file = optarg; opts->record = true; break; case 'u': opts->universes = optarg; break; case 'v': opts->file = optarg; opts->verify = true; break; case '?': break; default: break; } } return 0; } /* * Display the help message */ void DisplayHelpAndExit(const options &opts) { cout << "Usage: " << opts.cmd << " --universes <universe_list> [--record <file>] [--playback <file>]\n" "\n" "Record a series of universes, or playback a previously recorded show.\n" "\n" " -h, --help Display this help message and exit.\n" " -l, --log-level <level> Set the logging level 0 .. 4 .\n" " -r, --record <file> Path to a file to record data\n" " -p, --playback <file> Path to a file from which to playback data\n" " -u, --universes <list> Comma separated list of universes to record.\n" " -v, --verify <file> Path to a file to verify\n" "\n" "Additional Playback Options:\n" " -d, --delay Delay in ms between successive iterations.\n" " -i, --iterations Number of times to repeat the show, 0: unlimited." "\n" << endl; exit(0); } /** * Record a show */ int RecordShow(const options &opts) { if (opts.universes.empty()) { OLA_FATAL << "No universes specified, use -u"; exit(EX_USAGE); } vector<string> universe_strs; vector<unsigned int> universes; ola::StringSplit(opts.universes, universe_strs, ","); vector<string>::const_iterator iter = universe_strs.begin(); for (; iter != universe_strs.end(); ++iter) { unsigned int universe; if (!ola::StringToInt(*iter, &universe)) { OLA_FATAL << *iter << " isn't a valid universe number"; exit(EX_USAGE); } universes.push_back(universe); } ShowRecorder recorder(opts.file, universes); int status = recorder.Init(); if (status) return status; recorder.Record(); return EX_OK; } /** * Verify a show file is valid */ int VerifyShow(const string &filename) { ShowLoader loader(filename); if (!loader.Load()) return EX_NOINPUT; map<unsigned int, unsigned int> frames_by_universe; uint64_t total_time = 0; unsigned int universe; ola::DmxBuffer buffer; unsigned int timeout; ShowLoader::State state; while (true) { state = loader.NextFrame(&universe, &buffer); if (state != ShowLoader::OK) break; frames_by_universe[universe]++; state = loader.NextTimeout(&timeout); if (state != ShowLoader::OK) break; total_time += timeout; } map<unsigned int, unsigned int>::const_iterator iter; unsigned int total = 0; cout << "------------ Summary ----------" << endl; for (iter = frames_by_universe.begin(); iter != frames_by_universe.end(); ++iter) { cout << "Universe " << iter->first << ": " << iter->second << " frames" << endl; total += iter->second; } cout << "Total frames: " << total << endl; cout << "Playback time: " << total_time / 1000 << "." << total_time % 10 << " seconds" << endl; return EX_OK; } /* * Main */ int main(int argc, char *argv[]) { options opts; ParseOptions(argc, argv, &opts); ola::InitLogging(opts.level, ola::OLA_LOG_STDERR); if (opts.help) DisplayHelpAndExit(opts); int check = (opts.playback ? 1 : 0) + (opts.record ? 1 : 0) + (opts.verify ? 1 : 0); if (check == 0) { DisplayHelpAndExit(opts); } if (check != 1) { OLA_FATAL << "Only one of --record or --playback must be provided"; exit(EX_USAGE); } else if (opts.record) { return RecordShow(opts); } else if (opts.playback) { ShowPlayer player(opts.file); int status = player.Init(); if (!status) status = player.Playback(opts.loop_iterations, opts.loop_delay); return status; } else if (opts.verify) { return VerifyShow(opts.file); } return EX_OK; } <commit_msg>finish the help change<commit_after>/* * 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 Library 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. * * ola-recorder.cpp * A simple tool to record & playback shows. * Copyright (C) 2011 Simon Newton */ #include <errno.h> #include <getopt.h> #include <string.h> #include <sysexits.h> #include <ola/DmxBuffer.h> #include <ola/Logging.h> #include <ola/StringUtils.h> #include <iostream> #include <map> #include <string> #include <vector> #include "examples/ShowPlayer.h" #include "examples/ShowLoader.h" #include "examples/ShowRecorder.h" using std::cout; using std::endl; using std::map; using std::vector; using std::string; using ola::OlaUniverse; using ola::SimpleClient; typedef struct { ola::log_level level; bool help; // show the help string cmd; // argv[0] bool playback; bool record; bool verify; // 0 means infinite looping unsigned int loop_iterations; unsigned int loop_delay; string file; string universes; } options; /* * Parse our cmd line options. */ int ParseOptions(int argc, char *argv[], options *opts) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"delay", required_argument, 0, 'd'}, {"iterations", required_argument, 0, 'i'}, {"log-level", required_argument, 0, 'l'}, {"playback", required_argument, 0, 'p'}, {"record", required_argument, 0, 'r'}, {"universes", required_argument, 0, 'u'}, {"verify", required_argument, 0, 'v'}, {0, 0, 0, 0} }; opts->help = false; opts->level = ola::OLA_LOG_INFO; opts->playback = false; opts->loop_iterations = 1; opts->loop_delay = 0; opts->record = false; opts->verify = false; int c, ll; int option_index = 0; while (1) { c = getopt_long(argc, argv, "d:hi:l:p:r:u:v:", long_options, &option_index); if (c == -1) break; switch (c) { case 0: break; case 'd': opts->loop_delay = atoi(optarg); break; case 'h': opts->help = true; break; case 'i': opts->loop_iterations = atoi(optarg); break; case 'l': ll = atoi(optarg); switch (ll) { case 0: // nothing is written at this level // so this turns logging off opts->level = ola::OLA_LOG_NONE; break; case 1: opts->level = ola::OLA_LOG_FATAL; break; case 2: opts->level = ola::OLA_LOG_WARN; break; case 3: opts->level = ola::OLA_LOG_INFO; break; case 4: opts->level = ola::OLA_LOG_DEBUG; break; default : break; } break; case 'p': opts->file = optarg; opts->playback = true; break; case 'r': opts->file = optarg; opts->record = true; break; case 'u': opts->universes = optarg; break; case 'v': opts->file = optarg; opts->verify = true; break; case '?': break; default: break; } } return 0; } /* * Display the help message */ void DisplayHelpAndExit(const options &opts) { cout << "Usage: " << opts.cmd << " --universes <universe_list> [--record <file>] [--playback <file>]\n" "\n" "Record a series of universes, or playback a previously recorded show.\n" "\n" " -h, --help Display this help message and exit.\n" " -l, --log-level <level> Set the logging level 0 .. 4 .\n" " -r, --record <file> Path to a file to record data\n" " -p, --playback <file> Path to a file from which to playback data\n" " -u, --universes <list> Comma separated list of universes to record.\n" " -v, --verify <file> Path to a file to verify\n" "\n" "Additional Playback Options:\n" " -d, --delay Delay in ms between successive iterations.\n" " -i, --iterations Number of times to repeat the show, 0: unlimited." "\n" << endl; exit(0); } /** * Record a show */ int RecordShow(const options &opts) { if (opts.universes.empty()) { OLA_FATAL << "No universes specified, use -u"; exit(EX_USAGE); } vector<string> universe_strs; vector<unsigned int> universes; ola::StringSplit(opts.universes, universe_strs, ","); vector<string>::const_iterator iter = universe_strs.begin(); for (; iter != universe_strs.end(); ++iter) { unsigned int universe; if (!ola::StringToInt(*iter, &universe)) { OLA_FATAL << *iter << " isn't a valid universe number"; exit(EX_USAGE); } universes.push_back(universe); } ShowRecorder recorder(opts.file, universes); int status = recorder.Init(); if (status) return status; recorder.Record(); return EX_OK; } /** * Verify a show file is valid */ int VerifyShow(const string &filename) { ShowLoader loader(filename); if (!loader.Load()) return EX_NOINPUT; map<unsigned int, unsigned int> frames_by_universe; uint64_t total_time = 0; unsigned int universe; ola::DmxBuffer buffer; unsigned int timeout; ShowLoader::State state; while (true) { state = loader.NextFrame(&universe, &buffer); if (state != ShowLoader::OK) break; frames_by_universe[universe]++; state = loader.NextTimeout(&timeout); if (state != ShowLoader::OK) break; total_time += timeout; } map<unsigned int, unsigned int>::const_iterator iter; unsigned int total = 0; cout << "------------ Summary ----------" << endl; for (iter = frames_by_universe.begin(); iter != frames_by_universe.end(); ++iter) { cout << "Universe " << iter->first << ": " << iter->second << " frames" << endl; total += iter->second; } cout << "Total frames: " << total << endl; cout << "Playback time: " << total_time / 1000 << "." << total_time % 10 << " seconds" << endl; return EX_OK; } /* * Main */ int main(int argc, char *argv[]) { options opts; ParseOptions(argc, argv, &opts); ola::InitLogging(opts.level, ola::OLA_LOG_STDERR); if (opts.help) DisplayHelpAndExit(opts); int check = (opts.playback ? 1 : 0) + (opts.record ? 1 : 0) + (opts.verify ? 1 : 0); if (check != 1) { OLA_FATAL << "One of --record or --playback must be provided"; DisplayHelpAndExit(opts); } else if (opts.record) { return RecordShow(opts); } else if (opts.playback) { ShowPlayer player(opts.file); int status = player.Init(); if (!status) status = player.Playback(opts.loop_iterations, opts.loop_delay); return status; } else if (opts.verify) { return VerifyShow(opts.file); } return EX_OK; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: graphicproperties.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2003-11-24 16:50:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SDR_PROPERTIES_GRAPHICPROPERTIES_HXX #include <svx/sdr/properties/graphicproperties.hxx> #endif #ifndef _SFXSTYLE_HXX #include <svtools/style.hxx> #endif #ifndef _SVDDEF_HXX #include <svddef.hxx> #endif #ifndef _EEITEM_HXX #include <eeitem.hxx> #endif #ifndef _SVDOGRAF_HXX #include <svdograf.hxx> #endif #define ITEMID_GRF_CROP 0 #ifndef _SDGCPITM_HXX #include <sdgcpitm.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { // create a new itemset SfxItemSet& GraphicProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool) { return *(new SfxItemSet(rPool, // range from SdrAttrObj SDRATTR_START, SDRATTRSET_SHADOW, SDRATTRSET_OUTLINER, SDRATTRSET_MISC, SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION, // range from SdrGrafObj SDRATTR_GRAF_FIRST, SDRATTRSET_GRAF, // range from SdrTextObj EE_ITEMS_START, EE_ITEMS_END, // end 0, 0)); } GraphicProperties::GraphicProperties(SdrObject& rObj) : RectangleProperties(rObj) { } GraphicProperties::GraphicProperties(const GraphicProperties& rProps, SdrObject& rObj) : RectangleProperties(rProps, rObj) { } GraphicProperties::~GraphicProperties() { } BaseProperties& GraphicProperties::Clone(SdrObject& rObj) const { return *(new GraphicProperties(*this, rObj)); } void GraphicProperties::ItemSetChanged(const SfxItemSet& rSet) { SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject(); // local changes rObj.SetXPolyDirty(); // call parent RectangleProperties::ItemSetChanged(rSet); } void GraphicProperties::SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr) { SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject(); // local changes rObj.SetXPolyDirty(); // call parent RectangleProperties::SetStyleSheet(pNewStyleSheet, bDontRemoveHardAttr); // local changes rObj.ImpSetAttrToGrafInfo(); } void GraphicProperties::PreProcessSave() { // call parent RectangleProperties::PreProcessSave(); // prepare SetItems for storage const SfxItemSet& rSet = *mpItemSet; const SfxItemSet* pParent = mpStyleSheet ? &(mpStyleSheet->GetItemSet()) : 0L; SdrGrafSetItem aGrafAttr(rSet.GetPool()); aGrafAttr.GetItemSet().Put(rSet); aGrafAttr.GetItemSet().SetParent(pParent); mpItemSet->Put(aGrafAttr); } void GraphicProperties::PostProcessSave() { // call parent RectangleProperties::PostProcessSave(); // remove SetItems from local itemset if(mpItemSet) { mpItemSet->ClearItem(SDRATTRSET_GRAF); } } void GraphicProperties::ForceDefaultAttributes() { // call parent RectangleProperties::ForceDefaultAttributes(); GetObjectItemSet(); mpItemSet->Put( SdrGrafLuminanceItem( 0 ) ); mpItemSet->Put( SdrGrafContrastItem( 0 ) ); mpItemSet->Put( SdrGrafRedItem( 0 ) ); mpItemSet->Put( SdrGrafGreenItem( 0 ) ); mpItemSet->Put( SdrGrafBlueItem( 0 ) ); mpItemSet->Put( SdrGrafGamma100Item( 100 ) ); mpItemSet->Put( SdrGrafTransparenceItem( 0 ) ); mpItemSet->Put( SdrGrafInvertItem( FALSE ) ); mpItemSet->Put( SdrGrafModeItem( GRAPHICDRAWMODE_STANDARD ) ); mpItemSet->Put( SdrGrafCropItem( 0, 0, 0, 0 ) ); } } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS aw007 (1.2.20); FILE MERGED 2003/12/10 09:50:47 aw 1.2.20.1: #114265# I made some places more secure which use the mpItemSet inside the properties implementations<commit_after>/************************************************************************* * * $RCSfile: graphicproperties.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2003-12-16 13:10:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SDR_PROPERTIES_GRAPHICPROPERTIES_HXX #include <svx/sdr/properties/graphicproperties.hxx> #endif #ifndef _SFXSTYLE_HXX #include <svtools/style.hxx> #endif #ifndef _SVDDEF_HXX #include <svddef.hxx> #endif #ifndef _EEITEM_HXX #include <eeitem.hxx> #endif #ifndef _SVDOGRAF_HXX #include <svdograf.hxx> #endif #define ITEMID_GRF_CROP 0 #ifndef _SDGCPITM_HXX #include <sdgcpitm.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { // create a new itemset SfxItemSet& GraphicProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool) { return *(new SfxItemSet(rPool, // range from SdrAttrObj SDRATTR_START, SDRATTRSET_SHADOW, SDRATTRSET_OUTLINER, SDRATTRSET_MISC, SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION, // range from SdrGrafObj SDRATTR_GRAF_FIRST, SDRATTRSET_GRAF, // range from SdrTextObj EE_ITEMS_START, EE_ITEMS_END, // end 0, 0)); } GraphicProperties::GraphicProperties(SdrObject& rObj) : RectangleProperties(rObj) { } GraphicProperties::GraphicProperties(const GraphicProperties& rProps, SdrObject& rObj) : RectangleProperties(rProps, rObj) { } GraphicProperties::~GraphicProperties() { } BaseProperties& GraphicProperties::Clone(SdrObject& rObj) const { return *(new GraphicProperties(*this, rObj)); } void GraphicProperties::ItemSetChanged(const SfxItemSet& rSet) { SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject(); // local changes rObj.SetXPolyDirty(); // call parent RectangleProperties::ItemSetChanged(rSet); } void GraphicProperties::SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr) { SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject(); // local changes rObj.SetXPolyDirty(); // call parent RectangleProperties::SetStyleSheet(pNewStyleSheet, bDontRemoveHardAttr); // local changes rObj.ImpSetAttrToGrafInfo(); } void GraphicProperties::PreProcessSave() { // call parent RectangleProperties::PreProcessSave(); // force ItemSet GetObjectItemSet(); // prepare SetItems for storage const SfxItemSet& rSet = *mpItemSet; const SfxItemSet* pParent = mpStyleSheet ? &(mpStyleSheet->GetItemSet()) : 0L; SdrGrafSetItem aGrafAttr(rSet.GetPool()); aGrafAttr.GetItemSet().Put(rSet); aGrafAttr.GetItemSet().SetParent(pParent); mpItemSet->Put(aGrafAttr); } void GraphicProperties::PostProcessSave() { // call parent RectangleProperties::PostProcessSave(); // remove SetItems from local itemset if(mpItemSet) { mpItemSet->ClearItem(SDRATTRSET_GRAF); } } void GraphicProperties::ForceDefaultAttributes() { // call parent RectangleProperties::ForceDefaultAttributes(); // force ItemSet GetObjectItemSet(); mpItemSet->Put( SdrGrafLuminanceItem( 0 ) ); mpItemSet->Put( SdrGrafContrastItem( 0 ) ); mpItemSet->Put( SdrGrafRedItem( 0 ) ); mpItemSet->Put( SdrGrafGreenItem( 0 ) ); mpItemSet->Put( SdrGrafBlueItem( 0 ) ); mpItemSet->Put( SdrGrafGamma100Item( 100 ) ); mpItemSet->Put( SdrGrafTransparenceItem( 0 ) ); mpItemSet->Put( SdrGrafInvertItem( FALSE ) ); mpItemSet->Put( SdrGrafModeItem( GRAPHICDRAWMODE_STANDARD ) ); mpItemSet->Put( SdrGrafCropItem( 0, 0, 0, 0 ) ); } } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 <cassert> #include <fstream> #include <iostream> #include <map> #include <unordered_map> #include "../fast_simple_lcsk/lcsk.h" #include "../fast_simple_lcsk/match_pair.h" #include "../fast_simple_lcsk/rolling_hasher.h" using namespace std; #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) #define TRACE(x) cout << #x << " = " << x << endl #define _ << " _ " << long long CountMatchPairs(const string& s, const int k) { vector<char> char_to_id(256); char_to_id['A'] = 0; char_to_id['C'] = 1; char_to_id['T'] = 2; char_to_id['G'] = 3; RollingHasher rolling_hasher(s, k, char_to_id, /*alphabet_size=*/4); unordered_map<unsigned long long, long long> kmer_counts; for (unsigned long long hash = -1; rolling_hasher.Next(&hash);) { ++kmer_counts[hash]; } long long num_match_pairs = 0; for (const auto& kmer_count : kmer_counts) { num_match_pairs += kmer_count.second * kmer_count.second; } return num_match_pairs; } int main(int argc, char** argv) { if (argc != 3) { printf( "Example: ./stats_fasta 4 input.fa\n" "outputs lcskpplen, number of matchpair objects created, max number of matchpair objects alive\n" ); return 0; }; int k = stoi(argv[1]); ifstream infile(argv[2]); vector<string> sequences; string line; string current_seq; bool first = true; while (getline(infile, line)) { if (!line.size()) continue; if (line[0] == '>') { if (!first) { sequences.push_back(current_seq); } current_seq = ""; first = false; } else if (line[0] == ',') { continue; } else { current_seq += line; } } sequences.push_back(current_seq); string input = ""; for (string& sequence : sequences) { for (char c : sequence) { if (c == 'A' || c == 'G' || c == 'T' || c == 'C') input.push_back(c); } } { const long long num_match_pairs = CountMatchPairs(input, k); cout << "num_match_pairs=" << num_match_pairs << endl; } const int n = input.size(); cout << "input.size()=" << n << endl; vector<pair<int, int>> recon; LcsKSparseFast(input, input, k, &recon); const int length = recon.size(); cout << n << " " << length << " " << ObjectCounter<MatchPair>::objects_created << " " << ObjectCounter<MatchPair>::max_objects_alive << endl; return 0; } <commit_msg>Add an assert to check that num_match_pairs + 1 == number of created MatchPairs objects.<commit_after>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 <cassert> #include <fstream> #include <iostream> #include <map> #include <unordered_map> #include "../fast_simple_lcsk/lcsk.h" #include "../fast_simple_lcsk/match_pair.h" #include "../fast_simple_lcsk/rolling_hasher.h" using namespace std; #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) #define TRACE(x) cout << #x << " = " << x << endl #define _ << " _ " << long long CountMatchPairs(const string& s, const int k) { vector<char> char_to_id(256); char_to_id['A'] = 0; char_to_id['C'] = 1; char_to_id['T'] = 2; char_to_id['G'] = 3; RollingHasher rolling_hasher(s, k, char_to_id, /*alphabet_size=*/4); unordered_map<unsigned long long, long long> kmer_counts; for (unsigned long long hash = -1; rolling_hasher.Next(&hash);) { ++kmer_counts[hash]; } long long num_match_pairs = 0; for (const auto& kmer_count : kmer_counts) { num_match_pairs += kmer_count.second * kmer_count.second; } return num_match_pairs; } int main(int argc, char** argv) { if (argc != 3) { printf( "Example: ./stats_fasta 4 input.fa\n" "outputs lcskpplen, number of matchpair objects created, max number of matchpair objects alive\n" ); return 0; }; int k = stoi(argv[1]); ifstream infile(argv[2]); vector<string> sequences; string line; string current_seq; bool first = true; while (getline(infile, line)) { if (!line.size()) continue; if (line[0] == '>') { if (!first) { sequences.push_back(current_seq); } current_seq = ""; first = false; } else if (line[0] == ',') { continue; } else { current_seq += line; } } sequences.push_back(current_seq); string input = ""; for (string& sequence : sequences) { for (char c : sequence) { if (c == 'A' || c == 'G' || c == 'T' || c == 'C') input.push_back(c); } } const int n = input.size(); cerr << "input.size()=" << n << endl; const long long num_match_pairs = CountMatchPairs(input, k); vector<pair<int, int>> recon; LcsKSparseFast(input, input, k, &recon); // '+1' comes from a single dummy MatchPair object in the first row of the // compressed table. assert(num_match_pairs + 1 == ObjectCounter<MatchPair>::objects_created); const int length = recon.size(); cout << n << " " << length << " " << num_match_pairs << " " << ObjectCounter<MatchPair>::max_objects_alive << endl; return 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: hexmode.cpp // Purpose: Implementation of class wxExHexModeLine // Author: Anton van Wezenbeek // Copyright: (c) 2012 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/extension/hexmode.h> #include <wx/extension/stc.h> const wxFileOffset bytes_per_line = 16; const wxFileOffset each_hex_field = 3; const wxFileOffset space_between_fields = 1; const wxFileOffset start_hex_field = 9; const wxFileOffset start_ascii_field = start_hex_field + each_hex_field * bytes_per_line + space_between_fields; wxExHexModeLine::wxExHexModeLine(wxExSTC* stc) : m_Line(stc->GetCurLine()) , m_LineNo(stc->GetCurrentLine()) , m_Index(stc->GetColumn(stc->GetCurrentPos())) , m_STC(stc) { } wxExHexModeLine::wxExHexModeLine(wxExSTC* stc, int pos_or_offset, bool is_position) : m_STC(stc) { if (is_position) { Set(pos_or_offset != -1 ? pos_or_offset: stc->GetCurrentPos()); } else { char field_offset[start_hex_field]; sprintf(field_offset, "%08lx", (unsigned long)(pos_or_offset & ~0x0f)); if (m_STC->FindNext(field_offset, 0)) { m_LineNo = m_STC->GetCurrentLine(); m_Line = m_STC->GetLine(m_LineNo); m_Index = (pos_or_offset & 0x0f); m_STC->SetSelection(m_STC->GetCurrentPos(), m_STC->GetCurrentPos()); } else { m_LineNo = -1; m_Line.clear(); m_Index = -1; } } } void wxExHexModeLine::AppendText(const wxCharBuffer& buffer) { wxFileOffset start = m_STC->m_HexBuffer.length(); m_STC->m_HexBuffer += buffer; const wxFileOffset mid_in_hex_field = 7; wxString text; // Allocate space for the string. text.Alloc( // offset: (9 + 1 + 1) * length / 16 bytes, (start_hex_field + 1 + 1) * buffer.length() / bytes_per_line + // hex field: 3 * length each_hex_field * buffer.length() + // ascii field: just the length buffer.length()); // Using wxString::Format here asserts (wxWidgets-2.9.1). char field_offset[start_hex_field]; for ( wxFileOffset offset = 0; offset < buffer.length(); offset += bytes_per_line) { long count = buffer.length() - offset; count = (bytes_per_line < count ? bytes_per_line : count); wxString field_hex, field_ascii; for (register wxFileOffset byte = 0; byte < count; byte++) { const unsigned char c = buffer.data()[offset + byte]; field_hex += wxString::Format("%02x ", c); // Print an extra space. if (byte == mid_in_hex_field) { field_hex += ' '; } field_ascii += Printable(c); } // The extra space if we ended too soon. if (count <= mid_in_hex_field) { field_hex += ' '; } sprintf(field_offset, "%08lx ", (unsigned long)start + (unsigned long)offset); const wxString field_spaces = wxString( ' ', (bytes_per_line - count)* each_hex_field); text += field_offset + field_hex + field_spaces + field_ascii; if (buffer.length() - offset > bytes_per_line) { text += m_STC->GetEOL(); } } m_STC->AppendText(text); } int wxExHexModeLine::Convert(int offset) const { const wxString address(m_Line.Mid(0, start_hex_field)); long val; if (sscanf(address.c_str(), "%lx", &val)) { return val + offset; } wxLogError("Cannot convert hex: " + address + " to number"); return 0; } int wxExHexModeLine::GetAsciiField() const { if (m_Line.GetChar(m_Index) != ' ') { int space = 0; if (m_Index >= start_hex_field + space_between_fields + (bytes_per_line * each_hex_field) / 2) { space++; } const int offset = (m_Index - (start_hex_field + space)) / each_hex_field; return start_ascii_field + offset; } return wxSTC_INVALID_POSITION; } int wxExHexModeLine::GetByte() const { if (m_Index > start_ascii_field + bytes_per_line) { return wxSTC_INVALID_POSITION; } else if (m_Index >= start_ascii_field) { return Convert(m_Index - start_ascii_field); } else if (m_Index >= start_hex_field) { if (m_Line.GetChar(m_Index) != ' ') { int space = 0; if (m_Index >= start_hex_field + space_between_fields + (bytes_per_line * each_hex_field) / 2) { space++; } return Convert((m_Index - (start_hex_field + space)) / each_hex_field); } } return wxSTC_INVALID_POSITION; } const wxString wxExHexModeLine::GetInfo() const { if (IsHexField() || IsOffsetField()) { const wxString word = m_STC->GetWordAtPos(m_STC->GetCurrentPos()); if (!word.empty()) { long base16_val; const bool base16_ok = word.ToLong(&base16_val, 16); if (base16_ok) { if (IsOffsetField()) { return wxString::Format("%ld", base16_val); } else { return wxString::Format("byte: %ld %ld", GetByte(), base16_val); } } } } else if (IsAsciiField()) { return wxString::Format("byte: %ld", GetByte()); } return wxEmptyString; } int wxExHexModeLine::GetHexField() const { const int offset = m_Index - start_ascii_field; int space = 0; if (m_Index == start_ascii_field + bytes_per_line) { space--; } else if (m_Index >= start_ascii_field + bytes_per_line / 2) { space++; } return start_hex_field + each_hex_field * offset + space; } bool wxExHexModeLine::Goto() const { if (m_LineNo < 0 || m_Index < 0) { return false; } const int start = m_STC->PositionFromLine(m_LineNo); m_STC->SetFocus(); m_STC->SetCurrentPos(start + start_ascii_field + m_Index); m_STC->SetSelection(m_STC->GetCurrentPos(), m_STC->GetCurrentPos()); return true; } bool wxExHexModeLine::IsAsciiField() const { return m_Index >= start_ascii_field && m_Index < start_ascii_field + bytes_per_line; } bool wxExHexModeLine::IsHexField() const { return m_Index >= start_hex_field && m_Index < start_ascii_field; } bool wxExHexModeLine::IsOffsetField() const { return m_Index >= 0 && m_Index < start_hex_field; } bool wxExHexModeLine::IsReadOnly() const { if (IsAsciiField()) { return false; } else if (IsHexField()) { if (m_Line.GetChar(m_Index) != ' ') { return false; } } return true; } int wxExHexModeLine::OtherField() const { if (IsAsciiField()) { return GetHexField(); } else if (IsHexField()) { return GetAsciiField(); } else { return wxSTC_INVALID_POSITION; } } wxUniChar wxExHexModeLine::Printable(unsigned int c) const { // We do not want control chars (\n etc.) to be printed, // as that disturbs the hex view field. if (c <= 255 && !iscntrl(c)) { return c; } else { // If we already defined our own symbol, use that one, // otherwise print an ordinary ascii char. const int symbol = m_STC->GetControlCharSymbol(); if (symbol == 0) { return '.'; } else { return symbol; } } } bool wxExHexModeLine::Replace(const wxUniChar& c) { if (IsReadOnly() || m_LineNo < 0 || m_Index < 0) { return false; } const int byte = GetByte(); if (byte == wxSTC_INVALID_POSITION) { return false; } const int pos = m_STC->PositionFromLine(m_LineNo); wxUniChar val = c; if (IsAsciiField()) { // replace ascii field with value m_STC->wxStyledTextCtrl::Replace( pos + m_Index, pos + m_Index + 1, c); // replace hex field with code const wxString code = wxString::Format("%02x", c); m_STC->wxStyledTextCtrl::Replace( pos + OtherField(), pos + OtherField() + 2, code); } else if (IsHexField()) { // hex text should be entered. if (!isxdigit(c)) { return false; } // replace hex field with value m_STC->wxStyledTextCtrl::Replace( pos + m_Index, pos + m_Index + 1, c); // replace ascii field with code char str[3]; if (m_Line[m_Index + 1] == ' ') { str[0] = m_Line[m_Index - 1]; str[1] = c; } else { str[0] = c; str[1] = m_Line[m_Index]; } str[2] = '\0'; unsigned int code; sscanf(str, "%x", &code); m_STC->wxStyledTextCtrl::Replace( pos + OtherField(), pos + OtherField() + 1, Printable(code)); val = code; } else { return false; } m_STC->m_HexBuffer[byte] = val; return true; } void wxExHexModeLine::Set(int pos) { m_LineNo = m_STC->LineFromPosition(pos); m_Line = m_STC->GetLine(m_LineNo); m_Index = m_STC->GetColumn(pos); } <commit_msg>use isascii and begin and end undo action<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: hexmode.cpp // Purpose: Implementation of class wxExHexModeLine // Author: Anton van Wezenbeek // Copyright: (c) 2012 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/extension/hexmode.h> #include <wx/extension/stc.h> const wxFileOffset bytes_per_line = 16; const wxFileOffset each_hex_field = 3; const wxFileOffset space_between_fields = 1; const wxFileOffset start_hex_field = 9; const wxFileOffset start_ascii_field = start_hex_field + each_hex_field * bytes_per_line + space_between_fields; wxExHexModeLine::wxExHexModeLine(wxExSTC* stc) : m_Line(stc->GetCurLine()) , m_LineNo(stc->GetCurrentLine()) , m_Index(stc->GetColumn(stc->GetCurrentPos())) , m_STC(stc) { } wxExHexModeLine::wxExHexModeLine(wxExSTC* stc, int pos_or_offset, bool is_position) : m_STC(stc) { if (is_position) { Set(pos_or_offset != -1 ? pos_or_offset: stc->GetCurrentPos()); } else { char field_offset[start_hex_field]; sprintf(field_offset, "%08lx", (unsigned long)(pos_or_offset & ~0x0f)); if (m_STC->FindNext(field_offset, 0)) { m_LineNo = m_STC->GetCurrentLine(); m_Line = m_STC->GetLine(m_LineNo); m_Index = (pos_or_offset & 0x0f); m_STC->SetSelection(m_STC->GetCurrentPos(), m_STC->GetCurrentPos()); } else { m_LineNo = -1; m_Line.clear(); m_Index = -1; } } } void wxExHexModeLine::AppendText(const wxCharBuffer& buffer) { wxFileOffset start = m_STC->m_HexBuffer.length(); m_STC->m_HexBuffer += buffer; const wxFileOffset mid_in_hex_field = 7; wxString text; // Allocate space for the string. text.Alloc( // offset: (9 + 1 + 1) * length / 16 bytes, (start_hex_field + 1 + 1) * buffer.length() / bytes_per_line + // hex field: 3 * length each_hex_field * buffer.length() + // ascii field: just the length buffer.length()); // Using wxString::Format here asserts (wxWidgets-2.9.1). char field_offset[start_hex_field]; for ( wxFileOffset offset = 0; offset < buffer.length(); offset += bytes_per_line) { long count = buffer.length() - offset; count = (bytes_per_line < count ? bytes_per_line : count); wxString field_hex, field_ascii; for (register wxFileOffset byte = 0; byte < count; byte++) { const unsigned char c = buffer.data()[offset + byte]; field_hex += wxString::Format("%02x ", c); // Print an extra space. if (byte == mid_in_hex_field) { field_hex += ' '; } field_ascii += Printable(c); } // The extra space if we ended too soon. if (count <= mid_in_hex_field) { field_hex += ' '; } sprintf(field_offset, "%08lx ", (unsigned long)start + (unsigned long)offset); const wxString field_spaces = wxString( ' ', (bytes_per_line - count)* each_hex_field); text += field_offset + field_hex + field_spaces + field_ascii; if (buffer.length() - offset > bytes_per_line) { text += m_STC->GetEOL(); } } m_STC->AppendText(text); } int wxExHexModeLine::Convert(int offset) const { const wxString address(m_Line.Mid(0, start_hex_field)); long val; if (sscanf(address.c_str(), "%lx", &val)) { return val + offset; } wxLogError("Cannot convert hex: " + address + " to number"); return 0; } int wxExHexModeLine::GetAsciiField() const { if (m_Line.GetChar(m_Index) != ' ') { int space = 0; if (m_Index >= start_hex_field + space_between_fields + (bytes_per_line * each_hex_field) / 2) { space++; } const int offset = (m_Index - (start_hex_field + space)) / each_hex_field; return start_ascii_field + offset; } return wxSTC_INVALID_POSITION; } int wxExHexModeLine::GetByte() const { if (m_Index > start_ascii_field + bytes_per_line) { return wxSTC_INVALID_POSITION; } else if (m_Index >= start_ascii_field) { return Convert(m_Index - start_ascii_field); } else if (m_Index >= start_hex_field) { if (m_Line.GetChar(m_Index) != ' ') { int space = 0; if (m_Index >= start_hex_field + space_between_fields + (bytes_per_line * each_hex_field) / 2) { space++; } return Convert((m_Index - (start_hex_field + space)) / each_hex_field); } } return wxSTC_INVALID_POSITION; } const wxString wxExHexModeLine::GetInfo() const { if (IsHexField() || IsOffsetField()) { const wxString word = m_STC->GetWordAtPos(m_STC->GetCurrentPos()); if (!word.empty()) { long base16_val; const bool base16_ok = word.ToLong(&base16_val, 16); if (base16_ok) { if (IsOffsetField()) { return wxString::Format("%ld", base16_val); } else { return wxString::Format("byte: %ld %ld", GetByte(), base16_val); } } } } else if (IsAsciiField()) { return wxString::Format("byte: %ld", GetByte()); } return wxEmptyString; } int wxExHexModeLine::GetHexField() const { const int offset = m_Index - start_ascii_field; int space = 0; if (m_Index == start_ascii_field + bytes_per_line) { space--; } else if (m_Index >= start_ascii_field + bytes_per_line / 2) { space++; } return start_hex_field + each_hex_field * offset + space; } bool wxExHexModeLine::Goto() const { if (m_LineNo < 0 || m_Index < 0) { return false; } const int start = m_STC->PositionFromLine(m_LineNo); m_STC->SetFocus(); m_STC->SetCurrentPos(start + start_ascii_field + m_Index); m_STC->SetSelection(m_STC->GetCurrentPos(), m_STC->GetCurrentPos()); return true; } bool wxExHexModeLine::IsAsciiField() const { return m_Index >= start_ascii_field && m_Index < start_ascii_field + bytes_per_line; } bool wxExHexModeLine::IsHexField() const { return m_Index >= start_hex_field && m_Index < start_ascii_field; } bool wxExHexModeLine::IsOffsetField() const { return m_Index >= 0 && m_Index < start_hex_field; } bool wxExHexModeLine::IsReadOnly() const { if (IsAsciiField()) { return false; } else if (IsHexField()) { if (m_Line.GetChar(m_Index) != ' ') { return false; } } return true; } int wxExHexModeLine::OtherField() const { if (IsAsciiField()) { return GetHexField(); } else if (IsHexField()) { return GetAsciiField(); } else { return wxSTC_INVALID_POSITION; } } wxUniChar wxExHexModeLine::Printable(unsigned int c) const { // We do not want control chars (\n etc.) to be printed, // as that disturbs the hex view field. if (isascii(c) && !iscntrl(c)) { return c; } else { // If we already defined our own symbol, use that one, // otherwise print an ordinary ascii char. const int symbol = m_STC->GetControlCharSymbol(); if (symbol == 0) { return '.'; } else { return symbol; } } } bool wxExHexModeLine::Replace(const wxUniChar& c) { if (IsReadOnly() || m_LineNo < 0 || m_Index < 0) { return false; } const int byte = GetByte(); if (byte == wxSTC_INVALID_POSITION) { return false; } const int pos = m_STC->PositionFromLine(m_LineNo); wxUniChar val = c; if (IsAsciiField()) { m_STC->BeginUndoAction(); // replace ascii field with value m_STC->wxStyledTextCtrl::Replace( pos + m_Index, pos + m_Index + 1, c); // replace hex field with code const wxString code = wxString::Format("%02x", c); m_STC->wxStyledTextCtrl::Replace( pos + OtherField(), pos + OtherField() + 2, code); m_STC->EndUndoAction(); } else if (IsHexField()) { // hex text should be entered. if (!isxdigit(c)) { return false; } m_STC->BeginUndoAction(); // replace hex field with value m_STC->wxStyledTextCtrl::Replace( pos + m_Index, pos + m_Index + 1, c); // replace ascii field with code char str[3]; if (m_Line[m_Index + 1] == ' ') { str[0] = m_Line[m_Index - 1]; str[1] = c; } else { str[0] = c; str[1] = m_Line[m_Index]; } str[2] = '\0'; unsigned int code; sscanf(str, "%x", &code); m_STC->wxStyledTextCtrl::Replace( pos + OtherField(), pos + OtherField() + 1, Printable(code)); m_STC->EndUndoAction(); val = code; } else { return false; } m_STC->m_HexBuffer[byte] = val; return true; } void wxExHexModeLine::Set(int pos) { m_LineNo = m_STC->LineFromPosition(pos); m_Line = m_STC->GetLine(m_LineNo); m_Index = m_STC->GetColumn(pos); } <|endoftext|>
<commit_before>/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <string> #include <map> #include <stdlib.h> #include <unistd.h> #include <boost/algorithm/string/trim.hpp> #include <osquery/core.h> #include <osquery/tables.h> #include <osquery/filesystem.h> #include <osquery/logger.h> namespace osquery { namespace tables { inline std::string getProcAttr(const std::string& attr, const std::string& pid) { return "/proc/" + pid + "/" + attr; } inline std::string readProcCMDLine(const std::string& pid) { auto attr = getProcAttr("cmdline", pid); std::string content; readFile(attr, content); // Remove \0 delimiters. std::replace_if(content.begin(), content.end(), [](const char& c) { return c == 0; }, ' '); // Remove trailing delimiter. boost::algorithm::trim(content); return content; } inline std::string readProcLink(const std::string& attr, const std::string& pid) { // The exe is a symlink to the binary on-disk. auto attr_path = getProcAttr(attr, pid); std::string result; char link_path[PATH_MAX] = {0}; auto bytes = readlink(attr_path.c_str(), link_path, sizeof(link_path) - 1); if (bytes >= 0) { result = std::string(link_path); } return result; } std::set<std::string> getProcList(const QueryContext& context) { std::set<std::string> pidlist; if (context.constraints.count("pid") > 0 && context.constraints.at("pid").exists(EQUALS)) { for (const auto& pid : context.constraints.at("pid").getAll(EQUALS)) { if (isDirectory("/proc/" + pid)) { pidlist.insert(pid); } } } else { osquery::procProcesses(pidlist); } return pidlist; } void genProcessEnvironment(const std::string& pid, QueryData& results) { auto attr = getProcAttr("environ", pid); std::string content; readFile(attr, content); const char* variable = content.c_str(); // Stop at the end of nul-delimited string content. while (*variable > 0) { auto buf = std::string(variable); size_t idx = buf.find_first_of("="); Row r; r["pid"] = pid; r["key"] = buf.substr(0, idx); r["value"] = buf.substr(idx + 1); results.push_back(r); variable += buf.size() + 1; } } void genProcessMap(const std::string& pid, QueryData& results) { auto map = getProcAttr("maps", pid); std::string content; readFile(map, content); for (auto& line : osquery::split(content, "\n")) { auto fields = osquery::split(line, " "); Row r; r["pid"] = pid; // If can't read address, not sure. if (fields.size() < 5) { continue; } if (fields[0].size() > 0) { auto addresses = osquery::split(fields[0], "-"); r["start"] = "0x" + addresses[0]; r["end"] = "0x" + addresses[1]; } r["permissions"] = fields[1]; auto offset = std::stoll(fields[2], nullptr, 16); r["offset"] = (offset != 0) ? BIGINT(offset) : r["start"]; r["device"] = fields[3]; r["inode"] = fields[4]; // Path name must be trimmed. if (fields.size() > 5) { boost::trim(fields[5]); r["path"] = fields[5]; } // BSS with name in pathname. r["pseudo"] = (fields[4] == "0" && r["path"].size() > 0) ? "1" : "0"; results.push_back(r); } } struct SimpleProcStat { // Output from string parsing /proc/<pid>/status. std::string name; // Name: std::string real_uid; // Uid: * - - - std::string real_gid; // Gid: * - - - std::string effective_uid; // Uid: - * - - std::string effective_gid; // Gid: - * - - std::string resident_size; // VmRSS: std::string phys_footprint; // VmSize: // Output from sring parsing /proc/<pid>/stat. std::string state; std::string parent; std::string group; std::string nice; std::string user_time; std::string system_time; std::string start_time; }; static inline SimpleProcStat getProcStat(const std::string& pid) { SimpleProcStat stat; std::string content; if (readFile(getProcAttr("stat", pid), content).ok()) { auto start = content.find_last_of(")"); // Start parsing stats from ") <MODE>..." if (start == std::string::npos || content.size() <= start + 2) { return stat; } auto details = osquery::split(content.substr(start + 2), " "); if (details.size() <= 19) { return stat; } stat.state = details.at(0); stat.parent = details.at(1); stat.group = details.at(2); stat.user_time = details.at(11); stat.system_time = details.at(12); stat.nice = details.at(16); try { stat.start_time = TEXT(AS_LITERAL(BIGINT_LITERAL, details.at(19)) / 100); } catch (const boost::bad_lexical_cast& e) { stat.start_time = "-1"; } } if (readFile(getProcAttr("status", pid), content).ok()) { for (const auto& line : osquery::split(content, "\n")) { // Status lines are formatted: Key: Value....\n. auto detail = osquery::split(line, ":", 1); if (detail.size() != 2) { continue; } // There are specific fields from each detail. if (detail.at(0) == "Name") { stat.name = detail.at(1); } else if (detail.at(0) == "VmRSS") { detail[1].erase(detail.at(1).end() - 3, detail.at(1).end()); // Memory is reported in kB. stat.resident_size = detail.at(1) + "000"; } else if (detail.at(0) == "VmSize") { detail[1].erase(detail.at(1).end() - 3, detail.at(1).end()); // Memory is reported in kB. stat.phys_footprint = detail.at(1) + "000"; } else if (detail.at(0) == "Gid") { // Format is: R E - - auto gid_detail = osquery::split(detail.at(1), "\t"); if (gid_detail.size() == 4) { stat.real_gid = gid_detail.at(0); stat.effective_gid = gid_detail.at(1); } } else if (detail.at(0) == "Uid") { auto uid_detail = osquery::split(detail.at(1), "\t"); if (uid_detail.size() == 4) { stat.real_uid = uid_detail.at(0); stat.effective_uid = uid_detail.at(1); } } } } return stat; } void genProcess(const std::string& pid, QueryData& results) { // Parse the process stat and status. auto proc_stat = getProcStat(pid); Row r; r["pid"] = pid; r["parent"] = proc_stat.parent; r["path"] = readProcLink("exe", pid); r["name"] = proc_stat.name; r["group"] = proc_stat.group; r["state"] = proc_stat.state; r["nice"] = proc_stat.nice; // Read/parse cmdline arguments. r["cmdline"] = readProcCMDLine(pid); r["cwd"] = readProcLink("cwd", pid); r["root"] = readProcLink("root", pid); r["uid"] = proc_stat.real_uid; r["euid"] = proc_stat.effective_uid; r["gid"] = proc_stat.real_gid; r["egid"] = proc_stat.effective_gid; // If the path of the executable that started the process is available and // the path exists on disk, set on_disk to 1. If the path is not // available, set on_disk to -1. If, and only if, the path of the // executable is available and the file does NOT exist on disk, set on_disk // to 0. r["on_disk"] = osquery::pathExists(r["path"]).toString(); // size/memory information r["wired_size"] = "0"; // No support for unpagable counters in linux. r["resident_size"] = proc_stat.resident_size; r["phys_footprint"] = proc_stat.phys_footprint; // time information r["user_time"] = proc_stat.user_time; r["system_time"] = proc_stat.system_time; r["start_time"] = proc_stat.start_time; results.push_back(r); } QueryData genProcesses(QueryContext& context) { QueryData results; auto pidlist = getProcList(context); for (const auto& pid : pidlist) { genProcess(pid, results); } return results; } QueryData genProcessEnvs(QueryContext& context) { QueryData results; auto pidlist = getProcList(context); for (const auto& pid : pidlist) { genProcessEnvironment(pid, results); } return results; } QueryData genProcessMemoryMap(QueryContext& context) { QueryData results; auto pidlist = getProcList(context); for (const auto& pid : pidlist) { genProcessMap(pid, results); } return results; } } } <commit_msg>[Fix #1580] Handle exceptions in linux process_memory_map<commit_after>/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <string> #include <map> #include <stdlib.h> #include <unistd.h> #include <boost/algorithm/string/trim.hpp> #include <osquery/core.h> #include <osquery/tables.h> #include <osquery/filesystem.h> #include <osquery/logger.h> namespace osquery { namespace tables { inline std::string getProcAttr(const std::string& attr, const std::string& pid) { return "/proc/" + pid + "/" + attr; } inline std::string readProcCMDLine(const std::string& pid) { auto attr = getProcAttr("cmdline", pid); std::string content; readFile(attr, content); // Remove \0 delimiters. std::replace_if(content.begin(), content.end(), [](const char& c) { return c == 0; }, ' '); // Remove trailing delimiter. boost::algorithm::trim(content); return content; } inline std::string readProcLink(const std::string& attr, const std::string& pid) { // The exe is a symlink to the binary on-disk. auto attr_path = getProcAttr(attr, pid); std::string result; char link_path[PATH_MAX] = {0}; auto bytes = readlink(attr_path.c_str(), link_path, sizeof(link_path) - 1); if (bytes >= 0) { result = std::string(link_path); } return result; } std::set<std::string> getProcList(const QueryContext& context) { std::set<std::string> pidlist; if (context.constraints.count("pid") > 0 && context.constraints.at("pid").exists(EQUALS)) { for (const auto& pid : context.constraints.at("pid").getAll(EQUALS)) { if (isDirectory("/proc/" + pid)) { pidlist.insert(pid); } } } else { osquery::procProcesses(pidlist); } return pidlist; } void genProcessEnvironment(const std::string& pid, QueryData& results) { auto attr = getProcAttr("environ", pid); std::string content; readFile(attr, content); const char* variable = content.c_str(); // Stop at the end of nul-delimited string content. while (*variable > 0) { auto buf = std::string(variable); size_t idx = buf.find_first_of("="); Row r; r["pid"] = pid; r["key"] = buf.substr(0, idx); r["value"] = buf.substr(idx + 1); results.push_back(r); variable += buf.size() + 1; } } void genProcessMap(const std::string& pid, QueryData& results) { auto map = getProcAttr("maps", pid); std::string content; readFile(map, content); for (auto& line : osquery::split(content, "\n")) { auto fields = osquery::split(line, " "); // If can't read address, not sure. if (fields.size() < 5) { continue; } Row r; r["pid"] = pid; if (!fields[0].empty()) { auto addresses = osquery::split(fields[0], "-"); if (addresses.size() >= 2) { r["start"] = "0x" + addresses[0]; r["end"] = "0x" + addresses[1]; } else { // Problem with the address format. continue; } } r["permissions"] = fields[1]; try { auto offset = std::stoll(fields[2], nullptr, 16); r["offset"] = (offset != 0) ? BIGINT(offset) : r["start"]; } catch (const std::exception& e) { // Value was out of range or could not be interpreted as a hex long long. r["offset"] = "-1"; } r["device"] = fields[3]; r["inode"] = fields[4]; // Path name must be trimmed. if (fields.size() > 5) { boost::trim(fields[5]); r["path"] = fields[5]; } // BSS with name in pathname. r["pseudo"] = (fields[4] == "0" && !r["path"].empty()) ? "1" : "0"; results.push_back(r); } } struct SimpleProcStat { // Output from string parsing /proc/<pid>/status. std::string name; // Name: std::string real_uid; // Uid: * - - - std::string real_gid; // Gid: * - - - std::string effective_uid; // Uid: - * - - std::string effective_gid; // Gid: - * - - std::string resident_size; // VmRSS: std::string phys_footprint; // VmSize: // Output from sring parsing /proc/<pid>/stat. std::string state; std::string parent; std::string group; std::string nice; std::string user_time; std::string system_time; std::string start_time; }; static inline SimpleProcStat getProcStat(const std::string& pid) { SimpleProcStat stat; std::string content; if (readFile(getProcAttr("stat", pid), content).ok()) { auto start = content.find_last_of(")"); // Start parsing stats from ") <MODE>..." if (start == std::string::npos || content.size() <= start + 2) { return stat; } auto details = osquery::split(content.substr(start + 2), " "); if (details.size() <= 19) { return stat; } stat.state = details.at(0); stat.parent = details.at(1); stat.group = details.at(2); stat.user_time = details.at(11); stat.system_time = details.at(12); stat.nice = details.at(16); try { stat.start_time = TEXT(AS_LITERAL(BIGINT_LITERAL, details.at(19)) / 100); } catch (const boost::bad_lexical_cast& e) { stat.start_time = "-1"; } } if (readFile(getProcAttr("status", pid), content).ok()) { for (const auto& line : osquery::split(content, "\n")) { // Status lines are formatted: Key: Value....\n. auto detail = osquery::split(line, ":", 1); if (detail.size() != 2) { continue; } // There are specific fields from each detail. if (detail.at(0) == "Name") { stat.name = detail.at(1); } else if (detail.at(0) == "VmRSS") { detail[1].erase(detail.at(1).end() - 3, detail.at(1).end()); // Memory is reported in kB. stat.resident_size = detail.at(1) + "000"; } else if (detail.at(0) == "VmSize") { detail[1].erase(detail.at(1).end() - 3, detail.at(1).end()); // Memory is reported in kB. stat.phys_footprint = detail.at(1) + "000"; } else if (detail.at(0) == "Gid") { // Format is: R E - - auto gid_detail = osquery::split(detail.at(1), "\t"); if (gid_detail.size() == 4) { stat.real_gid = gid_detail.at(0); stat.effective_gid = gid_detail.at(1); } } else if (detail.at(0) == "Uid") { auto uid_detail = osquery::split(detail.at(1), "\t"); if (uid_detail.size() == 4) { stat.real_uid = uid_detail.at(0); stat.effective_uid = uid_detail.at(1); } } } } return stat; } void genProcess(const std::string& pid, QueryData& results) { // Parse the process stat and status. auto proc_stat = getProcStat(pid); Row r; r["pid"] = pid; r["parent"] = proc_stat.parent; r["path"] = readProcLink("exe", pid); r["name"] = proc_stat.name; r["group"] = proc_stat.group; r["state"] = proc_stat.state; r["nice"] = proc_stat.nice; // Read/parse cmdline arguments. r["cmdline"] = readProcCMDLine(pid); r["cwd"] = readProcLink("cwd", pid); r["root"] = readProcLink("root", pid); r["uid"] = proc_stat.real_uid; r["euid"] = proc_stat.effective_uid; r["gid"] = proc_stat.real_gid; r["egid"] = proc_stat.effective_gid; // If the path of the executable that started the process is available and // the path exists on disk, set on_disk to 1. If the path is not // available, set on_disk to -1. If, and only if, the path of the // executable is available and the file does NOT exist on disk, set on_disk // to 0. r["on_disk"] = osquery::pathExists(r["path"]).toString(); // size/memory information r["wired_size"] = "0"; // No support for unpagable counters in linux. r["resident_size"] = proc_stat.resident_size; r["phys_footprint"] = proc_stat.phys_footprint; // time information r["user_time"] = proc_stat.user_time; r["system_time"] = proc_stat.system_time; r["start_time"] = proc_stat.start_time; results.push_back(r); } QueryData genProcesses(QueryContext& context) { QueryData results; auto pidlist = getProcList(context); for (const auto& pid : pidlist) { genProcess(pid, results); } return results; } QueryData genProcessEnvs(QueryContext& context) { QueryData results; auto pidlist = getProcList(context); for (const auto& pid : pidlist) { genProcessEnvironment(pid, results); } return results; } QueryData genProcessMemoryMap(QueryContext& context) { QueryData results; auto pidlist = getProcList(context); for (const auto& pid : pidlist) { genProcessMap(pid, results); } return results; } } } <|endoftext|>
<commit_before>// Author: Christophe.Delaere@cern.ch 25/04/04 /////////////////////////////////////////////////////////////////////////// // // TMLPAnalyzer // // This utility class contains a set of tests usefull when developing // a neural network. // It allows you to check for unneeded variables, and to control // the network structure. // /////////////////////////////////////////////////////////////////////////// #include "TSynapse.h" #include "TNeuron.h" #include "TMultiLayerPerceptron.h" #include "TMLPAnalyzer.h" #include "TTree.h" #include "TTreeFormula.h" #include "TEventList.h" #include "TH1D.h" #include "THStack.h" #include "TLegend.h" #include "TPad.h" #include "Riostream.h" ClassImp(TMLPAnalyzer) //______________________________________________________________________________ TMLPAnalyzer::~TMLPAnalyzer() { if(analysisTree) delete analysisTree; } //______________________________________________________________________________ Int_t TMLPAnalyzer::GetLayers() { // Returns the number of layers TString fStructure = network->GetStructure(); return fStructure.CountChar(':')+1; } //______________________________________________________________________________ Int_t TMLPAnalyzer::GetNeurons(Int_t layer) { // Returns the number of neurons in given layer if(layer==1) { TString fStructure = network->GetStructure(); TString input = TString(fStructure(0, fStructure.First(':'))); return input.CountChar(',')+1; } else if(layer==GetLayers()) { TString fStructure = network->GetStructure(); TString output = TString(fStructure(fStructure.Last(':') + 1, fStructure.Length() - fStructure.Last(':'))); return output.CountChar(',')+1; } else { Int_t cnt=1; TString fStructure = network->GetStructure(); TString hidden = TString(fStructure(fStructure.First(':') + 1, fStructure.Last(':') - fStructure.First(':') - 1)); Int_t beg = 0; Int_t end = hidden.Index(":", beg + 1); Int_t num = 0; while (end != -1) { num = atoi(TString(hidden(beg, end - beg)).Data()); cnt++; beg = end + 1; end = hidden.Index(":", beg + 1); if(layer==cnt) return num; } num = atoi(TString(hidden(beg, hidden.Length() - beg)).Data()); cnt++; if(layer==cnt) return num; } return -1; } //______________________________________________________________________________ TString TMLPAnalyzer::GetNeuronFormula(Int_t idx) { // returns the formula used as input for neuron (idx) in // the first layer. TString fStructure = network->GetStructure(); TString input = TString(fStructure(0, fStructure.First(':'))); Int_t beg = 0; Int_t end = input.Index(",", beg + 1); TString brName; Int_t cnt = 0; while (end != -1) { brName = TString(input(beg, end - beg)); beg = end + 1; end = input.Index(",", beg + 1); if(cnt==idx) return brName; cnt++; } brName = TString(input(beg, input.Length() - beg)); return brName; } //______________________________________________________________________________ void TMLPAnalyzer::CheckNetwork() { // gives some information about the network in the terminal. TString fStructure = network->GetStructure(); cout << "Network with structure: " << fStructure.Data() << endl; cout << "an input with lower values may not be needed" << endl; // Checks if some input variable is not needed for(Int_t i=0;i<GetNeurons(1);i++) { analysisTree->Draw(Form("Diff>>tmp%i",i),Form("InNeuron==%i",i),"goff"); TH1F* tmp = (TH1F*)gDirectory->Get(Form("tmp%i",i)); cout << GetNeuronFormula(i) << " -> " << tmp->GetMean() << " +/- " << tmp->GetRMS() << endl; } } //______________________________________________________________________________ void TMLPAnalyzer::GatherInformations() { // Collect informations about what is usefull in the network. // This method as to be called first when analyzing a network. #define shift 0.1 TTree* data = network->fData; TEventList* test = network->fTest; Int_t nEvents = test->GetN(); Int_t NN = GetNeurons(1); Double_t* params = new Double_t[NN]; Double_t* rms = new Double_t[NN]; TTreeFormula** formulas = new TTreeFormula*[NN]; TString formula; Int_t i(0), j(0), k(0), l(0); for(i=0; i<NN; i++){ formula = GetNeuronFormula(i); formulas[i] = new TTreeFormula(Form("NF%d",this),formula,data); TH1D tmp("tmpb", "tmpb", 1, -FLT_MAX, FLT_MAX); data->Draw(Form("%s>>tmpb",formula.Data()),"","goff"); rms[i] = tmp.GetRMS(); } Int_t InNeuron = 0; Double_t Diff = 0.; if(analysisTree) delete analysisTree; analysisTree = new TTree("result","analysis"); analysisTree->SetDirectory(0); analysisTree->Branch("InNeuron",&InNeuron,"InNeuron/I"); analysisTree->Branch("Diff",&Diff,"Diff/D"); // Loop on the input neurons Double_t v1 = 0.; Double_t v2 = 0.; for(i=0; i<GetNeurons(1); i++){ InNeuron = i; // Loop on the events in the test sample for(j=0; j< nEvents; j++) { network->GetEntry(test->GetEntry(j)); // Loop on the neurons to evaluate for(k=0; k<GetNeurons(1); k++) { params[k] = formulas[k]->EvalInstance(); } // Loop on the neurons in the output layer Diff = 0; for(l=0; l<GetNeurons(GetLayers()); l++){ params[i] += shift*rms[i]; v1 = network->Evaluate(l,params); params[i] -= 2*shift*rms[i]; v2 = network->Evaluate(l,params); Diff += (v1-v2)*(v1-v2); } Diff = TMath::Sqrt(Diff); analysisTree->Fill(); } } delete[] params; delete[] rms; for(i=0; i<GetNeurons(1); i++) delete formulas[i]; delete [] formulas; } //______________________________________________________________________________ void TMLPAnalyzer::DrawDInput(Int_t i) { // Draws the distribution (on the test sample) of the // impact on the network output of a small variation of // the ith input. analysisTree->Draw("Diff",Form("InNeuron==%i",i)); } //______________________________________________________________________________ void TMLPAnalyzer::DrawDInputs() { // Draws the distribution (on the test sample) of the // impact on the network output of a small variation of // each input. THStack* stack = new THStack("differences","differences"); TLegend* legend = new TLegend(0.75,0.75,0.95,0.95); TH1F* tmp = NULL; for(Int_t i=0;i<GetNeurons(1);i++) { analysisTree->Draw(Form("Diff>>tmp%i",i),Form("InNeuron==%i",i),"goff"); tmp = (TH1F*)gDirectory->Get(Form("tmp%i",i)); tmp->SetDirectory(0); tmp->SetLineColor(i+1); stack->Add(tmp); legend->AddEntry(tmp,GetNeuronFormula(i),"l"); } stack->Draw("nostack"); legend->Draw(); gPad->SetLogy(); } //______________________________________________________________________________ void TMLPAnalyzer::DrawNetwork(Int_t neuron, const char* signal, const char* bg) { // Draws the distribution of the neural network (using ith neuron). // Two distributions are drawn, for events passing respectively the "signal" // and "background" cuts. // Only the test sample is used. TTree* data = network->fData; TEventList* test = network->fTest; TEventList* current = data->GetEventList(); data->SetEventList(test); THStack* stack = new THStack("__NNout_TMLPA",Form("Neural net output (neuron %i)",neuron)); TH1F *bgh = new TH1F("__bgh_TMLPA", "NN output", 50, 0, -1); TH1F *sigh = new TH1F("__sigh_TMLPA", "NN output", 50, 0, -1); bgh->SetDirectory(0); sigh->SetDirectory(0); Int_t nEvents = 0; Int_t j=0; // build event lists for signal and background TEventList* signal_list = new TEventList("__tmpSig_MLPA"); TEventList* bg_list = new TEventList("__tmpBkg_MLPA"); data->Draw(">>__tmpSig_MLPA",signal,"goff"); data->Draw(">>__tmpBkg_MLPA",bg,"goff"); // fill the background nEvents = bg_list->GetN(); for(j=0; j< nEvents; j++) { bgh->Fill(network->Result(bg_list->GetEntry(j),neuron)); } // fill the signal nEvents = signal_list->GetN(); for(j=0; j< nEvents; j++) { sigh->Fill(network->Result(signal_list->GetEntry(j),neuron)); } // draws the result bgh->SetLineColor(kBlue); bgh->SetFillStyle(3008); bgh->SetFillColor(kBlue); sigh->SetLineColor(kRed); sigh->SetFillStyle(3003); sigh->SetFillColor(kRed); bgh->SetStats(0); sigh->SetStats(0); stack->Add(bgh); stack->Add(sigh); TLegend *legend = new TLegend(.75, .80, .95, .95); legend->AddEntry(bgh, "Background"); legend->AddEntry(sigh,"Signal"); stack->Draw("nostack"); legend->Draw(); // restore the default event list data->SetEventList(current); delete signal_list; delete bg_list; } <commit_msg>In TMLPAnalyzer::CheckNetwork replace the two Form in the same statement by simple printf.<commit_after>// Author: Christophe.Delaere@cern.ch 25/04/04 /////////////////////////////////////////////////////////////////////////// // // TMLPAnalyzer // // This utility class contains a set of tests usefull when developing // a neural network. // It allows you to check for unneeded variables, and to control // the network structure. // /////////////////////////////////////////////////////////////////////////// #include "TSynapse.h" #include "TNeuron.h" #include "TMultiLayerPerceptron.h" #include "TMLPAnalyzer.h" #include "TTree.h" #include "TTreeFormula.h" #include "TEventList.h" #include "TH1D.h" #include "THStack.h" #include "TLegend.h" #include "TPad.h" #include "Riostream.h" ClassImp(TMLPAnalyzer) //______________________________________________________________________________ TMLPAnalyzer::~TMLPAnalyzer() { if(analysisTree) delete analysisTree; } //______________________________________________________________________________ Int_t TMLPAnalyzer::GetLayers() { // Returns the number of layers TString fStructure = network->GetStructure(); return fStructure.CountChar(':')+1; } //______________________________________________________________________________ Int_t TMLPAnalyzer::GetNeurons(Int_t layer) { // Returns the number of neurons in given layer if(layer==1) { TString fStructure = network->GetStructure(); TString input = TString(fStructure(0, fStructure.First(':'))); return input.CountChar(',')+1; } else if(layer==GetLayers()) { TString fStructure = network->GetStructure(); TString output = TString(fStructure(fStructure.Last(':') + 1, fStructure.Length() - fStructure.Last(':'))); return output.CountChar(',')+1; } else { Int_t cnt=1; TString fStructure = network->GetStructure(); TString hidden = TString(fStructure(fStructure.First(':') + 1, fStructure.Last(':') - fStructure.First(':') - 1)); Int_t beg = 0; Int_t end = hidden.Index(":", beg + 1); Int_t num = 0; while (end != -1) { num = atoi(TString(hidden(beg, end - beg)).Data()); cnt++; beg = end + 1; end = hidden.Index(":", beg + 1); if(layer==cnt) return num; } num = atoi(TString(hidden(beg, hidden.Length() - beg)).Data()); cnt++; if(layer==cnt) return num; } return -1; } //______________________________________________________________________________ TString TMLPAnalyzer::GetNeuronFormula(Int_t idx) { // returns the formula used as input for neuron (idx) in // the first layer. TString fStructure = network->GetStructure(); TString input = TString(fStructure(0, fStructure.First(':'))); Int_t beg = 0; Int_t end = input.Index(",", beg + 1); TString brName; Int_t cnt = 0; while (end != -1) { brName = TString(input(beg, end - beg)); beg = end + 1; end = input.Index(",", beg + 1); if(cnt==idx) return brName; cnt++; } brName = TString(input(beg, input.Length() - beg)); return brName; } //______________________________________________________________________________ void TMLPAnalyzer::CheckNetwork() { // gives some information about the network in the terminal. TString fStructure = network->GetStructure(); cout << "Network with structure: " << fStructure.Data() << endl; cout << "an input with lower values may not be needed" << endl; // Checks if some input variable is not needed char var[20],sel[20]; for(Int_t i=0;i<GetNeurons(1);i++) { sprintf(var,"Diff>>tmp%d",i); sprintf(sel,"InNeuron==%d",i); analysisTree->Draw(var,sel,"goff"); TH1F* tmp = (TH1F*)gDirectory->Get(Form("tmp%i",i)); cout << GetNeuronFormula(i) << " -> " << tmp->GetMean() << " +/- " << tmp->GetRMS() << endl; } } //______________________________________________________________________________ void TMLPAnalyzer::GatherInformations() { // Collect informations about what is usefull in the network. // This method as to be called first when analyzing a network. #define shift 0.1 TTree* data = network->fData; TEventList* test = network->fTest; Int_t nEvents = test->GetN(); Int_t NN = GetNeurons(1); Double_t* params = new Double_t[NN]; Double_t* rms = new Double_t[NN]; TTreeFormula** formulas = new TTreeFormula*[NN]; TString formula; Int_t i(0), j(0), k(0), l(0); for(i=0; i<NN; i++){ formula = GetNeuronFormula(i); formulas[i] = new TTreeFormula(Form("NF%d",this),formula,data); TH1D tmp("tmpb", "tmpb", 1, -FLT_MAX, FLT_MAX); data->Draw(Form("%s>>tmpb",formula.Data()),"","goff"); rms[i] = tmp.GetRMS(); } Int_t InNeuron = 0; Double_t Diff = 0.; if(analysisTree) delete analysisTree; analysisTree = new TTree("result","analysis"); analysisTree->SetDirectory(0); analysisTree->Branch("InNeuron",&InNeuron,"InNeuron/I"); analysisTree->Branch("Diff",&Diff,"Diff/D"); // Loop on the input neurons Double_t v1 = 0.; Double_t v2 = 0.; for(i=0; i<GetNeurons(1); i++){ InNeuron = i; // Loop on the events in the test sample for(j=0; j< nEvents; j++) { network->GetEntry(test->GetEntry(j)); // Loop on the neurons to evaluate for(k=0; k<GetNeurons(1); k++) { params[k] = formulas[k]->EvalInstance(); } // Loop on the neurons in the output layer Diff = 0; for(l=0; l<GetNeurons(GetLayers()); l++){ params[i] += shift*rms[i]; v1 = network->Evaluate(l,params); params[i] -= 2*shift*rms[i]; v2 = network->Evaluate(l,params); Diff += (v1-v2)*(v1-v2); } Diff = TMath::Sqrt(Diff); analysisTree->Fill(); } } delete[] params; delete[] rms; for(i=0; i<GetNeurons(1); i++) delete formulas[i]; delete [] formulas; } //______________________________________________________________________________ void TMLPAnalyzer::DrawDInput(Int_t i) { // Draws the distribution (on the test sample) of the // impact on the network output of a small variation of // the ith input. analysisTree->Draw("Diff",Form("InNeuron==%i",i)); } //______________________________________________________________________________ void TMLPAnalyzer::DrawDInputs() { // Draws the distribution (on the test sample) of the // impact on the network output of a small variation of // each input. THStack* stack = new THStack("differences","differences"); TLegend* legend = new TLegend(0.75,0.75,0.95,0.95); TH1F* tmp = NULL; for(Int_t i=0;i<GetNeurons(1);i++) { analysisTree->Draw(Form("Diff>>tmp%i",i),Form("InNeuron==%i",i),"goff"); tmp = (TH1F*)gDirectory->Get(Form("tmp%i",i)); tmp->SetDirectory(0); tmp->SetLineColor(i+1); stack->Add(tmp); legend->AddEntry(tmp,GetNeuronFormula(i),"l"); } stack->Draw("nostack"); legend->Draw(); gPad->SetLogy(); } //______________________________________________________________________________ void TMLPAnalyzer::DrawNetwork(Int_t neuron, const char* signal, const char* bg) { // Draws the distribution of the neural network (using ith neuron). // Two distributions are drawn, for events passing respectively the "signal" // and "background" cuts. // Only the test sample is used. TTree* data = network->fData; TEventList* test = network->fTest; TEventList* current = data->GetEventList(); data->SetEventList(test); THStack* stack = new THStack("__NNout_TMLPA",Form("Neural net output (neuron %i)",neuron)); TH1F *bgh = new TH1F("__bgh_TMLPA", "NN output", 50, 0, -1); TH1F *sigh = new TH1F("__sigh_TMLPA", "NN output", 50, 0, -1); bgh->SetDirectory(0); sigh->SetDirectory(0); Int_t nEvents = 0; Int_t j=0; // build event lists for signal and background TEventList* signal_list = new TEventList("__tmpSig_MLPA"); TEventList* bg_list = new TEventList("__tmpBkg_MLPA"); data->Draw(">>__tmpSig_MLPA",signal,"goff"); data->Draw(">>__tmpBkg_MLPA",bg,"goff"); // fill the background nEvents = bg_list->GetN(); for(j=0; j< nEvents; j++) { bgh->Fill(network->Result(bg_list->GetEntry(j),neuron)); } // fill the signal nEvents = signal_list->GetN(); for(j=0; j< nEvents; j++) { sigh->Fill(network->Result(signal_list->GetEntry(j),neuron)); } // draws the result bgh->SetLineColor(kBlue); bgh->SetFillStyle(3008); bgh->SetFillColor(kBlue); sigh->SetLineColor(kRed); sigh->SetFillStyle(3003); sigh->SetFillColor(kRed); bgh->SetStats(0); sigh->SetStats(0); stack->Add(bgh); stack->Add(sigh); TLegend *legend = new TLegend(.75, .80, .95, .95); legend->AddEntry(bgh, "Background"); legend->AddEntry(sigh,"Signal"); stack->Draw("nostack"); legend->Draw(); // restore the default event list data->SetEventList(current); delete signal_list; delete bg_list; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/embed/ElementModes.hpp> #include <com/sun/star/embed/XHierarchicalStorageAccess2.hpp> #include <com/sun/star/embed/XTransactedObject.hpp> #include <com/sun/star/embed/XTransactionBroadcaster.hpp> #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp> #include "ohierarchyholder.hxx" using namespace ::com::sun::star; // OHierarchyHolder_Impl uno::Reference< embed::XExtendedStorageStream > OHierarchyHolder_Impl::GetStreamHierarchically( sal_Int32 nStorageMode, OStringList_Impl& aListPath, sal_Int32 nStreamMode, const ::comphelper::SequenceAsHashMap& aEncryptionData ) { uno::Reference< embed::XStorage > xOwnStor( m_xWeakOwnStorage.get(), uno::UNO_QUERY_THROW ); if ( !( nStorageMode & embed::ElementModes::WRITE ) && ( nStreamMode & embed::ElementModes::WRITE ) ) throw io::IOException(); uno::Reference< embed::XExtendedStorageStream > xResult = m_xChild->GetStreamHierarchically( nStorageMode, aListPath, nStreamMode, aEncryptionData ); if ( !xResult.is() ) throw uno::RuntimeException(); return xResult; } void OHierarchyHolder_Impl::RemoveStreamHierarchically( OStringList_Impl& aListPath ) { uno::Reference< embed::XStorage > xOwnStor( m_xWeakOwnStorage.get(), uno::UNO_QUERY_THROW ); m_xChild->RemoveStreamHierarchically( aListPath ); } // static OStringList_Impl OHierarchyHolder_Impl::GetListPathFromString( const OUString& aPath ) { OStringList_Impl aResult; sal_Int32 nIndex = 0; do { OUString aName = aPath.getToken( 0, '/', nIndex ); if ( aName.isEmpty() ) throw lang::IllegalArgumentException(); aResult.push_back( aName ); } while ( nIndex >= 0 ); return aResult; } // OHierarchyElement_Impl uno::Reference< embed::XExtendedStorageStream > OHierarchyElement_Impl::GetStreamHierarchically( sal_Int32 nStorageMode, OStringList_Impl& aListPath, sal_Int32 nStreamMode, const ::comphelper::SequenceAsHashMap& aEncryptionData ) { ::osl::MutexGuard aGuard( m_aMutex ); if ( !( nStorageMode & embed::ElementModes::WRITE ) && ( nStreamMode & embed::ElementModes::WRITE ) ) throw io::IOException(); if ( !aListPath.size() ) throw uno::RuntimeException(); OUString aNextName = *(aListPath.begin()); aListPath.erase( aListPath.begin() ); uno::Reference< embed::XExtendedStorageStream > xResult; uno::Reference< embed::XStorage > xOwnStor; xOwnStor = m_xOwnStorage.is() ? m_xOwnStorage : uno::Reference< embed::XStorage >( m_xWeakOwnStorage.get(), uno::UNO_QUERY ); if ( !xOwnStor.is() ) throw uno::RuntimeException(); if ( !aListPath.size() ) { if ( !aEncryptionData.size() ) { uno::Reference< embed::XHierarchicalStorageAccess > xHStorage( xOwnStor, uno::UNO_QUERY_THROW ); xResult = xHStorage->openStreamElementByHierarchicalName( aNextName, nStreamMode ); } else { uno::Reference< embed::XHierarchicalStorageAccess2 > xHStorage( xOwnStor, uno::UNO_QUERY_THROW ); xResult = xHStorage->openEncryptedStreamByHierarchicalName( aNextName, nStreamMode, aEncryptionData.getAsConstNamedValueList() ); } uno::Reference< embed::XTransactedObject > xTransact( xResult, uno::UNO_QUERY ); if ( xTransact.is() ) { // the existance of the transacted object means that the stream is opened for writing also // so the whole chain must be commited uno::Reference< embed::XTransactionBroadcaster > xTrBroadcast( xTransact, uno::UNO_QUERY_THROW ); xTrBroadcast->addTransactionListener( static_cast< embed::XTransactionListener* >( this ) ); } else { uno::Reference< lang::XComponent > xStreamComp( xResult, uno::UNO_QUERY_THROW ); xStreamComp->addEventListener( static_cast< lang::XEventListener* >( this ) ); } m_aOpenStreams.push_back( uno::WeakReference< embed::XExtendedStorageStream >( xResult ) ); } else { sal_Bool bNewElement = sal_False; ::rtl::Reference< OHierarchyElement_Impl > aElement; OHierarchyElementList_Impl::iterator aIter = m_aChildren.find( aNextName ); if ( aIter != m_aChildren.end() ) aElement = aIter->second; if ( !aElement.is() ) { bNewElement = sal_True; uno::Reference< embed::XStorage > xChildStorage = xOwnStor->openStorageElement( aNextName, nStorageMode ); if ( !xChildStorage.is() ) throw uno::RuntimeException(); aElement = new OHierarchyElement_Impl( NULL, xChildStorage ); } xResult = aElement->GetStreamHierarchically( nStorageMode, aListPath, nStreamMode, aEncryptionData ); if ( !xResult.is() ) throw uno::RuntimeException(); if ( bNewElement ) { m_aChildren[aNextName] = aElement; aElement->SetParent( this ); } } // the subelement was opened successfully, remember the storage to let it be locked m_xOwnStorage = xOwnStor; return xResult; } void OHierarchyElement_Impl::RemoveStreamHierarchically( OStringList_Impl& aListPath ) { ::osl::MutexGuard aGuard( m_aMutex ); if ( !aListPath.size() ) throw uno::RuntimeException(); OUString aNextName = *(aListPath.begin()); aListPath.erase( aListPath.begin() ); uno::Reference< embed::XExtendedStorageStream > xResult; uno::Reference< embed::XStorage > xOwnStor; xOwnStor = m_xOwnStorage.is() ? m_xOwnStorage : uno::Reference< embed::XStorage >( m_xWeakOwnStorage.get(), uno::UNO_QUERY ); if ( !xOwnStor.is() ) throw uno::RuntimeException(); if ( !aListPath.size() ) { xOwnStor->removeElement( aNextName ); } else { ::rtl::Reference< OHierarchyElement_Impl > aElement; OHierarchyElementList_Impl::iterator aIter = m_aChildren.find( aNextName ); if ( aIter != m_aChildren.end() ) aElement = aIter->second; if ( !aElement.is() ) { uno::Reference< embed::XStorage > xChildStorage = xOwnStor->openStorageElement( aNextName, embed::ElementModes::READWRITE ); if ( !xChildStorage.is() ) throw uno::RuntimeException(); aElement = new OHierarchyElement_Impl( NULL, xChildStorage ); } aElement->RemoveStreamHierarchically( aListPath ); } uno::Reference< embed::XTransactedObject > xTransact( xOwnStor, uno::UNO_QUERY ); if ( xTransact.is() ) xTransact->commit(); TestForClosing(); } void OHierarchyElement_Impl::Commit() { ::rtl::Reference< OHierarchyElement_Impl > aLocker( this ); ::rtl::Reference< OHierarchyElement_Impl > aParent; uno::Reference< embed::XStorage > xOwnStor; { ::osl::MutexGuard aGuard( m_aMutex ); aParent = m_rParent; xOwnStor = m_xOwnStorage; } if ( xOwnStor.is() ) { uno::Reference< embed::XTransactedObject > xTransact( xOwnStor, uno::UNO_QUERY_THROW ); xTransact->commit(); if ( aParent.is() ) aParent->Commit(); } } void OHierarchyElement_Impl::TestForClosing() { ::rtl::Reference< OHierarchyElement_Impl > aLocker( this ); { ::osl::MutexGuard aGuard( m_aMutex ); if ( !m_aOpenStreams.size() && !m_aChildren.size() ) { if ( m_rParent.is() ) { // only the root storage should not be disposed, other storages can be disposed if ( m_xOwnStorage.is() ) { try { m_xOwnStorage->dispose(); } catch( uno::Exception& ) {} } m_rParent->RemoveElement( this ); } m_xOwnStorage = uno::Reference< embed::XStorage >(); } } } void SAL_CALL OHierarchyElement_Impl::disposing( const lang::EventObject& Source ) throw ( uno::RuntimeException ) { uno::Sequence< embed::XStorage > aStoragesToCommit; try { ::osl::ClearableMutexGuard aGuard( m_aMutex ); uno::Reference< embed::XExtendedStorageStream > xStream( Source.Source, uno::UNO_QUERY ); for ( OWeakStorRefList_Impl::iterator pStorageIter = m_aOpenStreams.begin(); pStorageIter != m_aOpenStreams.end(); ) { OWeakStorRefList_Impl::iterator pTmp = pStorageIter++; if ( !pTmp->get().is() || pTmp->get() == xStream ) m_aOpenStreams.erase( pTmp ); } aGuard.clear(); TestForClosing(); } catch( uno::Exception& ) { throw uno::RuntimeException(); // no exception must happen here, usually an exception means disaster } } void OHierarchyElement_Impl::RemoveElement( const ::rtl::Reference< OHierarchyElement_Impl >& aRef ) { { ::osl::MutexGuard aGuard( m_aMutex ); OHierarchyElementList_Impl::iterator aIter = m_aChildren.begin(); const OHierarchyElementList_Impl::const_iterator aEnd = m_aChildren.end(); while (aIter != aEnd) { if (aIter->second == aRef ) aIter = m_aChildren.erase(aIter); else ++aIter; } } TestForClosing(); } // XTransactionListener void SAL_CALL OHierarchyElement_Impl::preCommit( const ::com::sun::star::lang::EventObject& /*aEvent*/ ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) { } void SAL_CALL OHierarchyElement_Impl::commited( const ::com::sun::star::lang::EventObject& /*aEvent*/ ) throw (::com::sun::star::uno::RuntimeException) { try { Commit(); } catch( const uno::Exception& e ) { throw lang::WrappedTargetRuntimeException( "Can not commit storage sequence!", uno::Reference< uno::XInterface >(), uno::makeAny( e ) ); } } void SAL_CALL OHierarchyElement_Impl::preRevert( const ::com::sun::star::lang::EventObject& /*aEvent*/ ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) { } void SAL_CALL OHierarchyElement_Impl::reverted( const ::com::sun::star::lang::EventObject& /*aEvent*/ ) throw (::com::sun::star::uno::RuntimeException) { } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>End iterator might not be const<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/embed/ElementModes.hpp> #include <com/sun/star/embed/XHierarchicalStorageAccess2.hpp> #include <com/sun/star/embed/XTransactedObject.hpp> #include <com/sun/star/embed/XTransactionBroadcaster.hpp> #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp> #include "ohierarchyholder.hxx" using namespace ::com::sun::star; // OHierarchyHolder_Impl uno::Reference< embed::XExtendedStorageStream > OHierarchyHolder_Impl::GetStreamHierarchically( sal_Int32 nStorageMode, OStringList_Impl& aListPath, sal_Int32 nStreamMode, const ::comphelper::SequenceAsHashMap& aEncryptionData ) { uno::Reference< embed::XStorage > xOwnStor( m_xWeakOwnStorage.get(), uno::UNO_QUERY_THROW ); if ( !( nStorageMode & embed::ElementModes::WRITE ) && ( nStreamMode & embed::ElementModes::WRITE ) ) throw io::IOException(); uno::Reference< embed::XExtendedStorageStream > xResult = m_xChild->GetStreamHierarchically( nStorageMode, aListPath, nStreamMode, aEncryptionData ); if ( !xResult.is() ) throw uno::RuntimeException(); return xResult; } void OHierarchyHolder_Impl::RemoveStreamHierarchically( OStringList_Impl& aListPath ) { uno::Reference< embed::XStorage > xOwnStor( m_xWeakOwnStorage.get(), uno::UNO_QUERY_THROW ); m_xChild->RemoveStreamHierarchically( aListPath ); } // static OStringList_Impl OHierarchyHolder_Impl::GetListPathFromString( const OUString& aPath ) { OStringList_Impl aResult; sal_Int32 nIndex = 0; do { OUString aName = aPath.getToken( 0, '/', nIndex ); if ( aName.isEmpty() ) throw lang::IllegalArgumentException(); aResult.push_back( aName ); } while ( nIndex >= 0 ); return aResult; } // OHierarchyElement_Impl uno::Reference< embed::XExtendedStorageStream > OHierarchyElement_Impl::GetStreamHierarchically( sal_Int32 nStorageMode, OStringList_Impl& aListPath, sal_Int32 nStreamMode, const ::comphelper::SequenceAsHashMap& aEncryptionData ) { ::osl::MutexGuard aGuard( m_aMutex ); if ( !( nStorageMode & embed::ElementModes::WRITE ) && ( nStreamMode & embed::ElementModes::WRITE ) ) throw io::IOException(); if ( !aListPath.size() ) throw uno::RuntimeException(); OUString aNextName = *(aListPath.begin()); aListPath.erase( aListPath.begin() ); uno::Reference< embed::XExtendedStorageStream > xResult; uno::Reference< embed::XStorage > xOwnStor; xOwnStor = m_xOwnStorage.is() ? m_xOwnStorage : uno::Reference< embed::XStorage >( m_xWeakOwnStorage.get(), uno::UNO_QUERY ); if ( !xOwnStor.is() ) throw uno::RuntimeException(); if ( !aListPath.size() ) { if ( !aEncryptionData.size() ) { uno::Reference< embed::XHierarchicalStorageAccess > xHStorage( xOwnStor, uno::UNO_QUERY_THROW ); xResult = xHStorage->openStreamElementByHierarchicalName( aNextName, nStreamMode ); } else { uno::Reference< embed::XHierarchicalStorageAccess2 > xHStorage( xOwnStor, uno::UNO_QUERY_THROW ); xResult = xHStorage->openEncryptedStreamByHierarchicalName( aNextName, nStreamMode, aEncryptionData.getAsConstNamedValueList() ); } uno::Reference< embed::XTransactedObject > xTransact( xResult, uno::UNO_QUERY ); if ( xTransact.is() ) { // the existance of the transacted object means that the stream is opened for writing also // so the whole chain must be commited uno::Reference< embed::XTransactionBroadcaster > xTrBroadcast( xTransact, uno::UNO_QUERY_THROW ); xTrBroadcast->addTransactionListener( static_cast< embed::XTransactionListener* >( this ) ); } else { uno::Reference< lang::XComponent > xStreamComp( xResult, uno::UNO_QUERY_THROW ); xStreamComp->addEventListener( static_cast< lang::XEventListener* >( this ) ); } m_aOpenStreams.push_back( uno::WeakReference< embed::XExtendedStorageStream >( xResult ) ); } else { sal_Bool bNewElement = sal_False; ::rtl::Reference< OHierarchyElement_Impl > aElement; OHierarchyElementList_Impl::iterator aIter = m_aChildren.find( aNextName ); if ( aIter != m_aChildren.end() ) aElement = aIter->second; if ( !aElement.is() ) { bNewElement = sal_True; uno::Reference< embed::XStorage > xChildStorage = xOwnStor->openStorageElement( aNextName, nStorageMode ); if ( !xChildStorage.is() ) throw uno::RuntimeException(); aElement = new OHierarchyElement_Impl( NULL, xChildStorage ); } xResult = aElement->GetStreamHierarchically( nStorageMode, aListPath, nStreamMode, aEncryptionData ); if ( !xResult.is() ) throw uno::RuntimeException(); if ( bNewElement ) { m_aChildren[aNextName] = aElement; aElement->SetParent( this ); } } // the subelement was opened successfully, remember the storage to let it be locked m_xOwnStorage = xOwnStor; return xResult; } void OHierarchyElement_Impl::RemoveStreamHierarchically( OStringList_Impl& aListPath ) { ::osl::MutexGuard aGuard( m_aMutex ); if ( !aListPath.size() ) throw uno::RuntimeException(); OUString aNextName = *(aListPath.begin()); aListPath.erase( aListPath.begin() ); uno::Reference< embed::XExtendedStorageStream > xResult; uno::Reference< embed::XStorage > xOwnStor; xOwnStor = m_xOwnStorage.is() ? m_xOwnStorage : uno::Reference< embed::XStorage >( m_xWeakOwnStorage.get(), uno::UNO_QUERY ); if ( !xOwnStor.is() ) throw uno::RuntimeException(); if ( !aListPath.size() ) { xOwnStor->removeElement( aNextName ); } else { ::rtl::Reference< OHierarchyElement_Impl > aElement; OHierarchyElementList_Impl::iterator aIter = m_aChildren.find( aNextName ); if ( aIter != m_aChildren.end() ) aElement = aIter->second; if ( !aElement.is() ) { uno::Reference< embed::XStorage > xChildStorage = xOwnStor->openStorageElement( aNextName, embed::ElementModes::READWRITE ); if ( !xChildStorage.is() ) throw uno::RuntimeException(); aElement = new OHierarchyElement_Impl( NULL, xChildStorage ); } aElement->RemoveStreamHierarchically( aListPath ); } uno::Reference< embed::XTransactedObject > xTransact( xOwnStor, uno::UNO_QUERY ); if ( xTransact.is() ) xTransact->commit(); TestForClosing(); } void OHierarchyElement_Impl::Commit() { ::rtl::Reference< OHierarchyElement_Impl > aLocker( this ); ::rtl::Reference< OHierarchyElement_Impl > aParent; uno::Reference< embed::XStorage > xOwnStor; { ::osl::MutexGuard aGuard( m_aMutex ); aParent = m_rParent; xOwnStor = m_xOwnStorage; } if ( xOwnStor.is() ) { uno::Reference< embed::XTransactedObject > xTransact( xOwnStor, uno::UNO_QUERY_THROW ); xTransact->commit(); if ( aParent.is() ) aParent->Commit(); } } void OHierarchyElement_Impl::TestForClosing() { ::rtl::Reference< OHierarchyElement_Impl > aLocker( this ); { ::osl::MutexGuard aGuard( m_aMutex ); if ( !m_aOpenStreams.size() && !m_aChildren.size() ) { if ( m_rParent.is() ) { // only the root storage should not be disposed, other storages can be disposed if ( m_xOwnStorage.is() ) { try { m_xOwnStorage->dispose(); } catch( uno::Exception& ) {} } m_rParent->RemoveElement( this ); } m_xOwnStorage = uno::Reference< embed::XStorage >(); } } } void SAL_CALL OHierarchyElement_Impl::disposing( const lang::EventObject& Source ) throw ( uno::RuntimeException ) { uno::Sequence< embed::XStorage > aStoragesToCommit; try { ::osl::ClearableMutexGuard aGuard( m_aMutex ); uno::Reference< embed::XExtendedStorageStream > xStream( Source.Source, uno::UNO_QUERY ); for ( OWeakStorRefList_Impl::iterator pStorageIter = m_aOpenStreams.begin(); pStorageIter != m_aOpenStreams.end(); ) { OWeakStorRefList_Impl::iterator pTmp = pStorageIter++; if ( !pTmp->get().is() || pTmp->get() == xStream ) m_aOpenStreams.erase( pTmp ); } aGuard.clear(); TestForClosing(); } catch( uno::Exception& ) { throw uno::RuntimeException(); // no exception must happen here, usually an exception means disaster } } void OHierarchyElement_Impl::RemoveElement( const ::rtl::Reference< OHierarchyElement_Impl >& aRef ) { { ::osl::MutexGuard aGuard( m_aMutex ); OHierarchyElementList_Impl::iterator aIter = m_aChildren.begin(); while (aIter != m_aChildren.end()) { if (aIter->second == aRef ) aIter = m_aChildren.erase(aIter); else ++aIter; } } TestForClosing(); } // XTransactionListener void SAL_CALL OHierarchyElement_Impl::preCommit( const ::com::sun::star::lang::EventObject& /*aEvent*/ ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) { } void SAL_CALL OHierarchyElement_Impl::commited( const ::com::sun::star::lang::EventObject& /*aEvent*/ ) throw (::com::sun::star::uno::RuntimeException) { try { Commit(); } catch( const uno::Exception& e ) { throw lang::WrappedTargetRuntimeException( "Can not commit storage sequence!", uno::Reference< uno::XInterface >(), uno::makeAny( e ) ); } } void SAL_CALL OHierarchyElement_Impl::preRevert( const ::com::sun::star::lang::EventObject& /*aEvent*/ ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) { } void SAL_CALL OHierarchyElement_Impl::reverted( const ::com::sun::star::lang::EventObject& /*aEvent*/ ) throw (::com::sun::star::uno::RuntimeException) { } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/String2Int.h" #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Execution/CommandLine.h" #include "Stroika/Foundation/Execution/Module.h" #include "Stroika/Foundation/Execution/SignalHandlers.h" #include "Stroika/Foundation/Execution/TimeOutException.h" #include "Stroika/Foundation/Execution/WaitableEvent.h" #include "Stroika/Foundation/IO/Network/HTTP/Exception.h" #include "Stroika/Foundation/IO/Network/HTTP/Headers.h" #include "Stroika/Foundation/Streams/TextReader.h" #include "Stroika/Frameworks/WebServer/ConnectionManager.h" #include "Stroika/Frameworks/WebServer/FileSystemRouter.h" #include "Stroika/Frameworks/WebServer/Router.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks::WebServer; using Characters::String; using Memory::BLOB; /* * To test this example: (make sure you run with 'current directory == top level directory of this sample else you wont find sample-html-folder) * * o Run the service (under the debugger if you wish) * o curl http://localhost:8080/ OR * o curl http://localhost:8080/FRED OR (to see error handling) * o curl -H "Content-Type: application/json" -X POST -d '{"AppState":"Start"}' http://localhost:8080/SetAppState * o curl http://localhost:8080/Files/foo.html -v */ namespace { /* * It's often helpful to structure together, routes, special interceptors, with your connection manager, to package up * all the logic /options for HTTP interface. * * This particular organization also makes it easy to save instance variables with the webserver (like a pointer to a handler) * and accesss them from the Route handler functions. */ struct MyWebServer_ { const Router kRouter_; ConnectionManager fConnectionMgr_; MyWebServer_ (uint16_t portNumber) : kRouter_{ Sequence<Route>{ Route{RegularExpression (L""), DefaultPage_}, Route{RegularExpression (L"POST"), RegularExpression (L"SetAppState"), SetAppState_}, Route{ RegularExpression (L"Files/.*"), FileSystemRouter{Execution::GetEXEDir () + L"html", String (L"Files"), Sequence<String>{L"index.html"}}, }, }} , fConnectionMgr_{SocketAddresses (InternetAddresses_Any (), portNumber), kRouter_, ConnectionManager::Options{{}, Socket::BindFlags{}, String{L"Stroika-Sample-WebServer/1.0"}}} { } // Can declare arguments as Request*,Response* static void DefaultPage_ (Request*, Response* response) { response->writeln (L"<html><body>"); response->writeln (L"<p>Hi Mom</p>"); response->writeln (L"<ul>"); response->writeln (L"Run the service (under the debugger if you wish)"); response->writeln (L"<li>curl http://localhost:8080/ OR</li>"); response->writeln (L"<li>curl http://localhost:8080/FRED OR (to see error handling)</li>"); response->writeln (L"<li>curl -H \"Content-Type: application/json\" -X POST -d '{\"AppState\":\"Start\"}' http://localhost:8080/SetAppState</li>"); response->writeln (L"<li>curl http://localhost:8080/Files/foo.html -v</li>"); response->writeln (L"</ul>"); response->writeln (L"</body></html>"); response->SetContentType (DataExchange::PredefinedInternetMediaType::kText_HTML); } // Can declare arguments as Message* message static void SetAppState_ (Message* message) { String argsAsString = Streams::TextReader::New (message->PeekRequest ()->GetBody ()).ReadAll (); message->PeekResponse ()->writeln (L"<html><body><p>Hi SetAppState (" + argsAsString.As<wstring> () + L")</p></body></html>"); message->PeekResponse ()->SetContentType (DataExchange::PredefinedInternetMediaType::kText_HTML); } }; } int main (int argc, const char* argv[]) { Execution::SignalHandlerRegistry::SafeSignalsManager safeSignals; #if qPlatform_POSIX Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED); #endif uint16_t portNumber = 8080; Time::DurationSecondsType quitAfter = numeric_limits<Time::DurationSecondsType>::max (); Sequence<String> args = Execution::ParseCommandLine (argc, argv); for (auto argi = args.begin (); argi != args.end (); ++argi) { if (Execution::MatchesCommandLineArgument (*argi, L"port")) { ++argi; if (argi != args.end ()) { portNumber = Characters::String2Int<uint16_t> (*argi); } else { cerr << "Expected arg to -port" << endl; return EXIT_FAILURE; } } else if (Execution::MatchesCommandLineArgument (*argi, L"quit-after")) { ++argi; if (argi != args.end ()) { quitAfter = Characters::String2Float<Time::DurationSecondsType> (*argi); } else { cerr << "Expected arg to -quit-after" << endl; return EXIT_FAILURE; } } } try { MyWebServer_ myWebServer{portNumber}; // listen and dispatch while this object exists Execution::WaitableEvent{}.Wait (quitAfter); // wait forever - til user hits ctrl-c } catch (const Execution::TimeOutException&) { cerr << "Timed out - so - terminating..." << endl; return EXIT_FAILURE; } catch (...) { cerr << "Error encountered: " << Characters::ToString (current_exception ()).AsNarrowSDKString () << " - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>fixed name of sample html file in WebServer sample<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/String2Int.h" #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Execution/CommandLine.h" #include "Stroika/Foundation/Execution/Module.h" #include "Stroika/Foundation/Execution/SignalHandlers.h" #include "Stroika/Foundation/Execution/TimeOutException.h" #include "Stroika/Foundation/Execution/WaitableEvent.h" #include "Stroika/Foundation/IO/Network/HTTP/Exception.h" #include "Stroika/Foundation/IO/Network/HTTP/Headers.h" #include "Stroika/Foundation/Streams/TextReader.h" #include "Stroika/Frameworks/WebServer/ConnectionManager.h" #include "Stroika/Frameworks/WebServer/FileSystemRouter.h" #include "Stroika/Frameworks/WebServer/Router.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks::WebServer; using Characters::String; using Memory::BLOB; /* * To test this example: (make sure you run with 'current directory == top level directory of this sample else you wont find sample-html-folder) * * o Run the service (under the debugger if you wish) * o curl http://localhost:8080/ OR * o curl http://localhost:8080/FRED OR (to see error handling) * o curl -H "Content-Type: application/json" -X POST -d '{"AppState":"Start"}' http://localhost:8080/SetAppState * o curl http://localhost:8080/Files/foo.html -v */ namespace { /* * It's often helpful to structure together, routes, special interceptors, with your connection manager, to package up * all the logic /options for HTTP interface. * * This particular organization also makes it easy to save instance variables with the webserver (like a pointer to a handler) * and accesss them from the Route handler functions. */ struct MyWebServer_ { const Router kRouter_; ConnectionManager fConnectionMgr_; MyWebServer_ (uint16_t portNumber) : kRouter_{ Sequence<Route>{ Route{RegularExpression (L""), DefaultPage_}, Route{RegularExpression (L"POST"), RegularExpression (L"SetAppState"), SetAppState_}, Route{ RegularExpression (L"Files/.*"), FileSystemRouter{Execution::GetEXEDir () + L"html", String (L"Files"), Sequence<String>{L"index.html"}}, }, }} , fConnectionMgr_{SocketAddresses (InternetAddresses_Any (), portNumber), kRouter_, ConnectionManager::Options{{}, Socket::BindFlags{}, String{L"Stroika-Sample-WebServer/1.0"}}} { } // Can declare arguments as Request*,Response* static void DefaultPage_ (Request*, Response* response) { response->writeln (L"<html><body>"); response->writeln (L"<p>Hi Mom</p>"); response->writeln (L"<ul>"); response->writeln (L"Run the service (under the debugger if you wish)"); response->writeln (L"<li>curl http://localhost:8080/ OR</li>"); response->writeln (L"<li>curl http://localhost:8080/FRED OR (to see error handling)</li>"); response->writeln (L"<li>curl -H \"Content-Type: application/json\" -X POST -d '{\"AppState\":\"Start\"}' http://localhost:8080/SetAppState</li>"); response->writeln (L"<li>curl http://localhost:8080/Files/index.html -v</li>"); response->writeln (L"</ul>"); response->writeln (L"</body></html>"); response->SetContentType (DataExchange::PredefinedInternetMediaType::kText_HTML); } // Can declare arguments as Message* message static void SetAppState_ (Message* message) { String argsAsString = Streams::TextReader::New (message->PeekRequest ()->GetBody ()).ReadAll (); message->PeekResponse ()->writeln (L"<html><body><p>Hi SetAppState (" + argsAsString.As<wstring> () + L")</p></body></html>"); message->PeekResponse ()->SetContentType (DataExchange::PredefinedInternetMediaType::kText_HTML); } }; } int main (int argc, const char* argv[]) { Execution::SignalHandlerRegistry::SafeSignalsManager safeSignals; #if qPlatform_POSIX Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED); #endif uint16_t portNumber = 8080; Time::DurationSecondsType quitAfter = numeric_limits<Time::DurationSecondsType>::max (); Sequence<String> args = Execution::ParseCommandLine (argc, argv); for (auto argi = args.begin (); argi != args.end (); ++argi) { if (Execution::MatchesCommandLineArgument (*argi, L"port")) { ++argi; if (argi != args.end ()) { portNumber = Characters::String2Int<uint16_t> (*argi); } else { cerr << "Expected arg to -port" << endl; return EXIT_FAILURE; } } else if (Execution::MatchesCommandLineArgument (*argi, L"quit-after")) { ++argi; if (argi != args.end ()) { quitAfter = Characters::String2Float<Time::DurationSecondsType> (*argi); } else { cerr << "Expected arg to -quit-after" << endl; return EXIT_FAILURE; } } } try { MyWebServer_ myWebServer{portNumber}; // listen and dispatch while this object exists Execution::WaitableEvent{}.Wait (quitAfter); // wait forever - til user hits ctrl-c } catch (const Execution::TimeOutException&) { cerr << "Timed out - so - terminating..." << endl; return EXIT_FAILURE; } catch (...) { cerr << "Error encountered: " << Characters::ToString (current_exception ()).AsNarrowSDKString () << " - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <stack> #include <vector> #include <sstream> #include "Constants.h" #include "ExpressionUtil.h" std::string FormatInfix(const std::string& infix) { std::string::const_iterator bos = infix.begin(); std::string::const_iterator eos = infix.end(); std::string formatted; for (std::string::const_iterator it = bos; it != eos; ++it) { if (std::find(operators.begin(), operators.end(), std::string(1, *it)) != operators.end() || *it == '(' || *it == ')') { if (it != bos && *(it - 1) != ' ' && *(formatted.end() - 1) != ' ' ) { formatted.append(1, ' '); } formatted.append(1, *it); if ((it + 1) != eos && *(it + 1) != ' ') { formatted.append(1, ' '); } } // sin, cos, tan else if (it < eos - 3 && std::find(operators.begin(), operators.end(), std::string(it, it + 3)) != operators.end()) { if (it != bos && *(it - 1) != ' ' && *(formatted.end() - 1) != ' ') { formatted.append(1, ' '); } formatted.append(it, it + 3); it += 2; if ((it + 1) != eos && *(it + 1) != ' ') { formatted.append(1, ' '); } } else { if (*it != ' ') { formatted.append(1, *it); } else if (it != bos && *(it - 1) != ' ') { formatted.append(1, *it); } } } return formatted; } std::string InfixToPostfix(const std::string& infix) { std::stack<std::string> operatorStack; std::string token; std::string previousToken = ""; int parenCount = 0; bool isUnary = true; std::istringstream is(FormatInfix(infix)); std::string postfix; while (is >> token) { if (token != "(" && std::find(operators.begin(), operators.end(), token) != operators.end()) { if (previousToken == "(") { throw InfixError("Operator can't evaluate with invalid operands"); } if (isUnary && token == "-") { token = "u" + token; } else { while (!operatorStack.empty() && input_priority.find(token)->second <= stack_priority.find(operatorStack.top())->second) { postfix += operatorStack.top() + ' '; operatorStack.pop(); } } operatorStack.push(token); isUnary = true; } else if (token == "(") { operatorStack.push(token); ++parenCount; } else if (token == ")") { if (parenCount == 0) { throw InfixError("Invalid Paren"); } if (previousToken == "(" && !postfix.empty()) { throw InfixError("Invalid Paren"); } while (!operatorStack.empty() && operatorStack.top() != "(") { postfix += operatorStack.top() + ' '; operatorStack.pop(); } operatorStack.pop(); --parenCount; } else if (token.find_first_not_of(operand_chars) == std::string::npos) { if (previousToken == ")") { throw InfixError("Operator can't evaluate with invalid operands"); } postfix += token + ' '; isUnary = false; } else { throw InfixError("Undefined Symbol"); } previousToken = token; } if (parenCount > 0) { throw InfixError("Invalid Paren"); } while (!operatorStack.empty()) { postfix += operatorStack.top() + ' '; operatorStack.pop(); } if (!postfix.empty()) { postfix.erase(postfix.size() - 1); } size_t equalPos = infix.find("="); if (equalPos != std::string::npos) { if (infix.substr(0, equalPos).find_first_not_of(identifier_chars + " " + "\t") != std::string::npos) { throw InfixError("Invalid Variable"); } if (equalPos != infix.rfind("=")) { throw InfixError("Invalid Variable"); } } return postfix; } <commit_msg>fix eos-3 error if infix.size() is less than 3<commit_after>#include <stack> #include <vector> #include <sstream> #include "Constants.h" #include "ExpressionUtil.h" std::string FormatInfix(const std::string& infix) { std::string::const_iterator bos = infix.begin(); std::string::const_iterator eos = infix.end(); std::string formatted; for (std::string::const_iterator it = bos; it != eos; ++it) { if (std::find(operators.begin(), operators.end(), std::string(1, *it)) != operators.end() || *it == '(' || *it == ')') { if (it != bos && *(it - 1) != ' ' && *(formatted.end() - 1) != ' ' ) { formatted.append(1, ' '); } formatted.append(1, *it); if ((it + 1) != eos && *(it + 1) != ' ') { formatted.append(1, ' '); } } // sin, cos, tan else if (infix.size() > 3 && it < eos - 3 && std::find(operators.begin(), operators.end(), std::string(it, it + 3)) != operators.end()) { if (it != bos && *(it - 1) != ' ' && *(formatted.end() - 1) != ' ') { formatted.append(1, ' '); } formatted.append(it, it + 3); it += 2; if ((it + 1) != eos && *(it + 1) != ' ') { formatted.append(1, ' '); } } else { if (*it != ' ') { formatted.append(1, *it); } else if (it != bos && *(it - 1) != ' ') { formatted.append(1, *it); } } } return formatted; } std::string InfixToPostfix(const std::string& infix) { std::stack<std::string> operatorStack; std::string token; std::string previousToken = ""; int parenCount = 0; bool isUnary = true; std::istringstream is(FormatInfix(infix)); std::string postfix; while (is >> token) { if (token != "(" && std::find(operators.begin(), operators.end(), token) != operators.end()) { if (previousToken == "(") { throw InfixError("Operator can't evaluate with invalid operands"); } if (isUnary && token == "-") { token = "u" + token; } else { while (!operatorStack.empty() && input_priority.find(token)->second <= stack_priority.find(operatorStack.top())->second) { postfix += operatorStack.top() + ' '; operatorStack.pop(); } } operatorStack.push(token); isUnary = true; } else if (token == "(") { operatorStack.push(token); ++parenCount; } else if (token == ")") { if (parenCount == 0) { throw InfixError("Invalid Paren"); } if (previousToken == "(" && !postfix.empty()) { throw InfixError("Invalid Paren"); } while (!operatorStack.empty() && operatorStack.top() != "(") { postfix += operatorStack.top() + ' '; operatorStack.pop(); } operatorStack.pop(); --parenCount; } else if (token.find_first_not_of(operand_chars) == std::string::npos) { if (previousToken == ")") { throw InfixError("Operator can't evaluate with invalid operands"); } postfix += token + ' '; isUnary = false; } else { throw InfixError("Undefined Symbol"); } previousToken = token; } if (parenCount > 0) { throw InfixError("Invalid Paren"); } while (!operatorStack.empty()) { postfix += operatorStack.top() + ' '; operatorStack.pop(); } if (!postfix.empty()) { postfix.erase(postfix.size() - 1); } size_t equalPos = infix.find("="); if (equalPos != std::string::npos) { if (infix.substr(0, equalPos).find_first_not_of(identifier_chars + " " + "\t") != std::string::npos) { throw InfixError("Invalid Variable"); } if (equalPos != infix.rfind("=")) { throw InfixError("Invalid Variable"); } } return postfix; } <|endoftext|>