text
stringlengths 54
60.6k
|
|---|
<commit_before>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/data/smart_buffer.h>
using namespace vespalib;
void checkMemory(const vespalib::string &expect, const Memory &mem) {
EXPECT_EQUAL(expect, vespalib::string(mem.data, mem.size));
}
void checkBuffer(const vespalib::string &expect, SmartBuffer &buf) {
TEST_DO(checkMemory(expect, buf.obtain()));
}
void write_buf(const vespalib::string &str, SmartBuffer &buf) {
WritableMemory mem = buf.reserve(str.size());
for (size_t i = 0; i < str.size(); ++i) {
mem.data[i] = str.data()[i];
}
buf.commit(str.size());
}
TEST("require that basic read/write works") {
SmartBuffer buf(3);
TEST_DO(checkBuffer("", buf));
{ // read from empty buffer
EXPECT_EQUAL(0u, buf.obtain().size);
}
{ // write to buffer
WritableMemory mem = buf.reserve(10);
TEST_DO(checkBuffer("", buf));
EXPECT_LESS_EQUAL(10u, mem.size);
mem.data[0] = 'a';
mem.data[1] = 'b';
mem.data[2] = 'c';
EXPECT_EQUAL(&buf, &buf.commit(3));
mem = buf.reserve(0);
TEST_DO(checkBuffer("abc", buf));
EXPECT_LESS_EQUAL(0u, mem.size);
}
{ // read without evicting last byte
Memory mem = buf.obtain();
TEST_DO(checkBuffer("abc", buf));
TEST_DO(checkMemory("abc", mem));
EXPECT_EQUAL(&buf, &buf.evict(2));
mem = buf.obtain();
TEST_DO(checkBuffer("c", buf));
TEST_DO(checkMemory("c", mem));
mem = buf.obtain();
TEST_DO(checkBuffer("c", buf));
TEST_DO(checkMemory("c", mem));
}
{ // write more to buffer
WritableMemory mem = buf.reserve(10);
EXPECT_LESS_EQUAL(10u, mem.size);
TEST_DO(checkBuffer("c", buf));
mem.data[0] = 'd';
EXPECT_EQUAL(&buf, &buf.commit(1));
mem = buf.reserve(5);
TEST_DO(checkBuffer("cd", buf));
EXPECT_LESS_EQUAL(5u, mem.size);
}
{ // read until end
Memory mem = buf.obtain();
TEST_DO(checkBuffer("cd", buf));
TEST_DO(checkMemory("cd", mem));
EXPECT_EQUAL(&buf, &buf.evict(1));
mem = buf.obtain();
TEST_DO(checkBuffer("d", buf));
TEST_DO(checkMemory("d", mem));
EXPECT_EQUAL(&buf, &buf.evict(1));
mem = buf.obtain();
TEST_DO(checkBuffer("", buf));
TEST_DO(checkMemory("", mem));
}
}
TEST("require that requested initial size is not adjusted") {
SmartBuffer buf(400);
EXPECT_EQUAL(buf.capacity(), 400u);
}
TEST("require that buffer auto-resets when empty") {
SmartBuffer buf(64);
EXPECT_EQUAL(buf.reserve(10).size, 64u);
write_buf("abc", buf);
EXPECT_EQUAL(buf.reserve(10).size, 61u);
buf.evict(3);
EXPECT_EQUAL(buf.reserve(10).size, 64u);
}
TEST("require that buffer can grow") {
SmartBuffer buf(64);
EXPECT_EQUAL(buf.capacity(), 64u);
write_buf("abc", buf);
write_buf("abc", buf);
buf.evict(3);
EXPECT_EQUAL(buf.reserve(70).size, size_t(128 - 3));
TEST_DO(checkBuffer("abc", buf));
EXPECT_EQUAL(buf.capacity(), 128u);
}
TEST("require that buffer can grow more than 2x") {
SmartBuffer buf(64);
EXPECT_EQUAL(buf.capacity(), 64u);
write_buf("abc", buf);
write_buf("abc", buf);
buf.evict(3);
EXPECT_EQUAL(buf.reserve(170).size, 170u);
TEST_DO(checkBuffer("abc", buf));
EXPECT_EQUAL(buf.capacity(), 173u);
}
TEST("require that buffer can be compacted") {
SmartBuffer buf(16);
EXPECT_EQUAL(buf.capacity(), 16u);
write_buf("abc", buf);
write_buf("abc", buf);
buf.evict(3);
write_buf("abc", buf);
buf.evict(3);
write_buf("abc", buf);
buf.evict(3);
write_buf("abc", buf);
buf.evict(3);
EXPECT_EQUAL(buf.reserve(0).size, 1u);
write_buf("abc", buf);
TEST_DO(checkBuffer("abcabc", buf));
EXPECT_EQUAL(buf.capacity(), 16u);
EXPECT_EQUAL(buf.reserve(0).size, 10u);
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>test empty smart buffer<commit_after>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/data/smart_buffer.h>
using namespace vespalib;
void checkMemory(const vespalib::string &expect, const Memory &mem) {
EXPECT_EQUAL(expect, vespalib::string(mem.data, mem.size));
}
void checkBuffer(const vespalib::string &expect, SmartBuffer &buf) {
TEST_DO(checkMemory(expect, buf.obtain()));
}
void write_buf(const vespalib::string &str, SmartBuffer &buf) {
WritableMemory mem = buf.reserve(str.size());
for (size_t i = 0; i < str.size(); ++i) {
mem.data[i] = str.data()[i];
}
buf.commit(str.size());
}
TEST("require that basic read/write works") {
SmartBuffer buf(3);
TEST_DO(checkBuffer("", buf));
{ // read from empty buffer
EXPECT_EQUAL(0u, buf.obtain().size);
}
{ // write to buffer
WritableMemory mem = buf.reserve(10);
TEST_DO(checkBuffer("", buf));
EXPECT_LESS_EQUAL(10u, mem.size);
mem.data[0] = 'a';
mem.data[1] = 'b';
mem.data[2] = 'c';
EXPECT_EQUAL(&buf, &buf.commit(3));
mem = buf.reserve(0);
TEST_DO(checkBuffer("abc", buf));
EXPECT_LESS_EQUAL(0u, mem.size);
}
{ // read without evicting last byte
Memory mem = buf.obtain();
TEST_DO(checkBuffer("abc", buf));
TEST_DO(checkMemory("abc", mem));
EXPECT_EQUAL(&buf, &buf.evict(2));
mem = buf.obtain();
TEST_DO(checkBuffer("c", buf));
TEST_DO(checkMemory("c", mem));
mem = buf.obtain();
TEST_DO(checkBuffer("c", buf));
TEST_DO(checkMemory("c", mem));
}
{ // write more to buffer
WritableMemory mem = buf.reserve(10);
EXPECT_LESS_EQUAL(10u, mem.size);
TEST_DO(checkBuffer("c", buf));
mem.data[0] = 'd';
EXPECT_EQUAL(&buf, &buf.commit(1));
mem = buf.reserve(5);
TEST_DO(checkBuffer("cd", buf));
EXPECT_LESS_EQUAL(5u, mem.size);
}
{ // read until end
Memory mem = buf.obtain();
TEST_DO(checkBuffer("cd", buf));
TEST_DO(checkMemory("cd", mem));
EXPECT_EQUAL(&buf, &buf.evict(1));
mem = buf.obtain();
TEST_DO(checkBuffer("d", buf));
TEST_DO(checkMemory("d", mem));
EXPECT_EQUAL(&buf, &buf.evict(1));
mem = buf.obtain();
TEST_DO(checkBuffer("", buf));
TEST_DO(checkMemory("", mem));
}
}
TEST("require that requested initial size is not adjusted") {
SmartBuffer buf(400);
EXPECT_EQUAL(buf.capacity(), 400u);
}
TEST("require that buffer auto-resets when empty") {
SmartBuffer buf(64);
EXPECT_EQUAL(buf.reserve(10).size, 64u);
write_buf("abc", buf);
EXPECT_EQUAL(buf.reserve(10).size, 61u);
buf.evict(3);
EXPECT_EQUAL(buf.reserve(10).size, 64u);
}
TEST("require that buffer can grow") {
SmartBuffer buf(64);
EXPECT_EQUAL(buf.capacity(), 64u);
write_buf("abc", buf);
write_buf("abc", buf);
buf.evict(3);
EXPECT_EQUAL(buf.reserve(70).size, size_t(128 - 3));
TEST_DO(checkBuffer("abc", buf));
EXPECT_EQUAL(buf.capacity(), 128u);
}
TEST("require that buffer can grow more than 2x") {
SmartBuffer buf(64);
EXPECT_EQUAL(buf.capacity(), 64u);
write_buf("abc", buf);
write_buf("abc", buf);
buf.evict(3);
EXPECT_EQUAL(buf.reserve(170).size, 170u);
TEST_DO(checkBuffer("abc", buf));
EXPECT_EQUAL(buf.capacity(), 173u);
}
TEST("require that buffer can be compacted") {
SmartBuffer buf(16);
EXPECT_EQUAL(buf.capacity(), 16u);
write_buf("abc", buf);
write_buf("abc", buf);
buf.evict(3);
write_buf("abc", buf);
buf.evict(3);
write_buf("abc", buf);
buf.evict(3);
write_buf("abc", buf);
buf.evict(3);
EXPECT_EQUAL(buf.reserve(0).size, 1u);
write_buf("abc", buf);
TEST_DO(checkBuffer("abcabc", buf));
EXPECT_EQUAL(buf.capacity(), 16u);
EXPECT_EQUAL(buf.reserve(0).size, 10u);
}
TEST("require that a completely empty buffer can be created") {
SmartBuffer buf(0);
EXPECT_EQUAL(buf.capacity(), 0u);
EXPECT_TRUE(buf.obtain().data == nullptr);
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2008-2016 the Urho3D project.
//
// 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 "../Precompiled.h"
#include "../Core/Context.h"
#include "../Scene/Component.h"
#include "../Scene/ReplicationState.h"
#include "../Scene/Scene.h"
#include "../Scene/SceneEvents.h"
#ifdef URHO3D_PHYSICS
#include "../Physics/PhysicsWorld.h"
#endif
#ifdef URHO3D_URHO2D
#include "../Urho2D/PhysicsWorld2D.h"
#endif
#include "../DebugNew.h"
#include "../Resource/JSONValue.h"
#ifdef _MSC_VER
#pragma warning(disable:6293)
#endif
namespace Urho3D
{
Component::Component(Context* context) :
Animatable(context),
node_(0),
id_(0),
networkUpdate_(false),
enabled_(true)
{
}
Component::~Component()
{
}
bool Component::Save(Serializer& dest) const
{
// Write type and ID
if (!dest.WriteStringHash(GetType()))
return false;
if (!dest.WriteUInt(id_))
return false;
// Write attributes
return Animatable::Save(dest);
}
bool Component::SaveXML(XMLElement& dest) const
{
// Write type and ID
if (!dest.SetString("type", GetTypeName()))
return false;
if (!dest.SetUInt("id", id_))
return false;
// Write attributes
return Animatable::SaveXML(dest);
}
bool Component::SaveJSON(JSONValue& dest) const
{
// Write type and ID
dest.Set("type", GetTypeName());
dest.Set("id", id_);
// Write attributes
return Animatable::SaveJSON(dest);
}
void Component::MarkNetworkUpdate()
{
if (!networkUpdate_ && id_ < FIRST_LOCAL_ID)
{
Scene* scene = GetScene();
if (scene)
{
scene->MarkNetworkUpdate(this);
networkUpdate_ = true;
}
}
}
void Component::GetDependencyNodes(PODVector<Node*>& dest)
{
}
void Component::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
{
}
void Component::SetEnabled(bool enable)
{
if (enable != enabled_)
{
enabled_ = enable;
OnSetEnabled();
MarkNetworkUpdate();
// Send change event for the component
Scene* scene = GetScene();
if (scene)
{
using namespace ComponentEnabledChanged;
VariantMap& eventData = GetEventDataMap();
eventData[P_SCENE] = scene;
eventData[P_NODE] = node_;
eventData[P_COMPONENT] = this;
scene->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
}
}
}
void Component::Remove()
{
if (node_)
node_->RemoveComponent(this);
}
Scene* Component::GetScene() const
{
return node_ ? node_->GetScene() : 0;
}
void Component::AddReplicationState(ComponentReplicationState* state)
{
if (!networkState_)
AllocateNetworkState();
networkState_->replicationStates_.Push(state);
}
void Component::PrepareNetworkUpdate()
{
if (!networkState_)
AllocateNetworkState();
const Vector<AttributeInfo>* attributes = networkState_->attributes_;
if (!attributes)
return;
unsigned numAttributes = attributes->Size();
if (networkState_->currentValues_.Size() != numAttributes)
{
networkState_->currentValues_.Resize(numAttributes);
networkState_->previousValues_.Resize(numAttributes);
// Copy the default attribute values to the previous state as a starting point
for (unsigned i = 0; i < numAttributes; ++i)
networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
}
// Check for attribute changes
for (unsigned i = 0; i < numAttributes; ++i)
{
const AttributeInfo& attr = attributes->At(i);
if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
continue;
OnGetAttribute(attr, networkState_->currentValues_[i]);
if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
{
networkState_->previousValues_[i] = networkState_->currentValues_[i];
// Mark the attribute dirty in all replication states that are tracking this component
for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
j != networkState_->replicationStates_.End(); ++j)
{
ComponentReplicationState* compState = static_cast<ComponentReplicationState*>(*j);
compState->dirtyAttributes_.Set(i);
// Add component's parent node to the dirty set if not added yet
NodeReplicationState* nodeState = compState->nodeState_;
if (!nodeState->markedDirty_)
{
nodeState->markedDirty_ = true;
nodeState->sceneState_->dirtyNodes_.Insert(node_->GetID());
}
}
}
}
networkUpdate_ = false;
}
void Component::CleanupConnection(Connection* connection)
{
if (networkState_)
{
for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
{
if (networkState_->replicationStates_[i]->connection_ == connection)
networkState_->replicationStates_.Erase(i);
}
}
}
void Component::OnAttributeAnimationAdded()
{
if (attributeAnimationInfos_.Size() == 1)
SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Component, HandleAttributeAnimationUpdate));
}
void Component::OnAttributeAnimationRemoved()
{
if (attributeAnimationInfos_.Empty())
UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
}
void Component::OnNodeSet(Node* node)
{
}
void Component::OnSceneSet(Scene* scene)
{
}
void Component::OnMarkedDirty(Node* node)
{
}
void Component::OnNodeSetEnabled(Node* node)
{
}
void Component::SetID(unsigned id)
{
id_ = id;
}
void Component::SetNode(Node* node)
{
node_ = node;
OnNodeSet(node_);
}
Component* Component::GetComponent(StringHash type) const
{
return node_ ? node_->GetComponent(type) : 0;
}
bool Component::IsEnabledEffective() const
{
return enabled_ && node_ && node_->IsEnabled();
}
void Component::GetComponents(PODVector<Component*>& dest, StringHash type) const
{
if (node_)
node_->GetComponents(dest, type);
else
dest.Clear();
}
void Component::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace AttributeAnimationUpdate;
UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
}
Component* Component::GetFixedUpdateSource()
{
Component* ret = 0;
Scene* scene = GetScene();
if (scene)
{
#ifdef URHO3D_PHYSICS
ret = scene->GetComponent<PhysicsWorld>();
#endif
#ifdef URHO3D_URHO2D
if (!ret)
ret = scene->GetComponent<PhysicsWorld2D>();
#endif
}
return ret;
}
}
<commit_msg>Include DebugNew.h last in Component.cpp to match convention used elsewhere.<commit_after>//
// Copyright (c) 2008-2016 the Urho3D project.
//
// 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 "../Precompiled.h"
#include "../Core/Context.h"
#include "../Resource/JSONValue.h"
#include "../Scene/Component.h"
#include "../Scene/ReplicationState.h"
#include "../Scene/Scene.h"
#include "../Scene/SceneEvents.h"
#ifdef URHO3D_PHYSICS
#include "../Physics/PhysicsWorld.h"
#endif
#ifdef URHO3D_URHO2D
#include "../Urho2D/PhysicsWorld2D.h"
#endif
#include "../DebugNew.h"
#ifdef _MSC_VER
#pragma warning(disable:6293)
#endif
namespace Urho3D
{
Component::Component(Context* context) :
Animatable(context),
node_(0),
id_(0),
networkUpdate_(false),
enabled_(true)
{
}
Component::~Component()
{
}
bool Component::Save(Serializer& dest) const
{
// Write type and ID
if (!dest.WriteStringHash(GetType()))
return false;
if (!dest.WriteUInt(id_))
return false;
// Write attributes
return Animatable::Save(dest);
}
bool Component::SaveXML(XMLElement& dest) const
{
// Write type and ID
if (!dest.SetString("type", GetTypeName()))
return false;
if (!dest.SetUInt("id", id_))
return false;
// Write attributes
return Animatable::SaveXML(dest);
}
bool Component::SaveJSON(JSONValue& dest) const
{
// Write type and ID
dest.Set("type", GetTypeName());
dest.Set("id", id_);
// Write attributes
return Animatable::SaveJSON(dest);
}
void Component::MarkNetworkUpdate()
{
if (!networkUpdate_ && id_ < FIRST_LOCAL_ID)
{
Scene* scene = GetScene();
if (scene)
{
scene->MarkNetworkUpdate(this);
networkUpdate_ = true;
}
}
}
void Component::GetDependencyNodes(PODVector<Node*>& dest)
{
}
void Component::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
{
}
void Component::SetEnabled(bool enable)
{
if (enable != enabled_)
{
enabled_ = enable;
OnSetEnabled();
MarkNetworkUpdate();
// Send change event for the component
Scene* scene = GetScene();
if (scene)
{
using namespace ComponentEnabledChanged;
VariantMap& eventData = GetEventDataMap();
eventData[P_SCENE] = scene;
eventData[P_NODE] = node_;
eventData[P_COMPONENT] = this;
scene->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
}
}
}
void Component::Remove()
{
if (node_)
node_->RemoveComponent(this);
}
Scene* Component::GetScene() const
{
return node_ ? node_->GetScene() : 0;
}
void Component::AddReplicationState(ComponentReplicationState* state)
{
if (!networkState_)
AllocateNetworkState();
networkState_->replicationStates_.Push(state);
}
void Component::PrepareNetworkUpdate()
{
if (!networkState_)
AllocateNetworkState();
const Vector<AttributeInfo>* attributes = networkState_->attributes_;
if (!attributes)
return;
unsigned numAttributes = attributes->Size();
if (networkState_->currentValues_.Size() != numAttributes)
{
networkState_->currentValues_.Resize(numAttributes);
networkState_->previousValues_.Resize(numAttributes);
// Copy the default attribute values to the previous state as a starting point
for (unsigned i = 0; i < numAttributes; ++i)
networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
}
// Check for attribute changes
for (unsigned i = 0; i < numAttributes; ++i)
{
const AttributeInfo& attr = attributes->At(i);
if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
continue;
OnGetAttribute(attr, networkState_->currentValues_[i]);
if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
{
networkState_->previousValues_[i] = networkState_->currentValues_[i];
// Mark the attribute dirty in all replication states that are tracking this component
for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
j != networkState_->replicationStates_.End(); ++j)
{
ComponentReplicationState* compState = static_cast<ComponentReplicationState*>(*j);
compState->dirtyAttributes_.Set(i);
// Add component's parent node to the dirty set if not added yet
NodeReplicationState* nodeState = compState->nodeState_;
if (!nodeState->markedDirty_)
{
nodeState->markedDirty_ = true;
nodeState->sceneState_->dirtyNodes_.Insert(node_->GetID());
}
}
}
}
networkUpdate_ = false;
}
void Component::CleanupConnection(Connection* connection)
{
if (networkState_)
{
for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
{
if (networkState_->replicationStates_[i]->connection_ == connection)
networkState_->replicationStates_.Erase(i);
}
}
}
void Component::OnAttributeAnimationAdded()
{
if (attributeAnimationInfos_.Size() == 1)
SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Component, HandleAttributeAnimationUpdate));
}
void Component::OnAttributeAnimationRemoved()
{
if (attributeAnimationInfos_.Empty())
UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
}
void Component::OnNodeSet(Node* node)
{
}
void Component::OnSceneSet(Scene* scene)
{
}
void Component::OnMarkedDirty(Node* node)
{
}
void Component::OnNodeSetEnabled(Node* node)
{
}
void Component::SetID(unsigned id)
{
id_ = id;
}
void Component::SetNode(Node* node)
{
node_ = node;
OnNodeSet(node_);
}
Component* Component::GetComponent(StringHash type) const
{
return node_ ? node_->GetComponent(type) : 0;
}
bool Component::IsEnabledEffective() const
{
return enabled_ && node_ && node_->IsEnabled();
}
void Component::GetComponents(PODVector<Component*>& dest, StringHash type) const
{
if (node_)
node_->GetComponents(dest, type);
else
dest.Clear();
}
void Component::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace AttributeAnimationUpdate;
UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
}
Component* Component::GetFixedUpdateSource()
{
Component* ret = 0;
Scene* scene = GetScene();
if (scene)
{
#ifdef URHO3D_PHYSICS
ret = scene->GetComponent<PhysicsWorld>();
#endif
#ifdef URHO3D_URHO2D
if (!ret)
ret = scene->GetComponent<PhysicsWorld2D>();
#endif
}
return ret;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest_android.h"
#include <android/log.h>
#include <stdio.h>
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest_defines.h"
int ViEAutoTestAndroid::RunAutotest(int testSelection, int subTestSelection,
void* window1, void* window2,
JavaVM* javaVM, void* env, void* context) {
ViEAutoTest vieAutoTest(window1, window2);
ViETest::Log("RunAutoTest(%d, %d)", testSelection, subTestSelection);
webrtc::VideoEngine::SetAndroidObjects(javaVM, context);
#ifndef WEBRTC_ANDROID_OPENSLES
// voice engine calls into ADM directly
webrtc::VoiceEngine::SetAndroidObjects(javaVM, env, context);
#endif
if (subTestSelection == 0) {
// Run all selected test
switch (testSelection) {
case 0:
vieAutoTest.ViEStandardTest();
break;
case 1:
vieAutoTest.ViEAPITest();
break;
case 2:
vieAutoTest.ViEExtendedTest();
break;
case 3:
vieAutoTest.ViELoopbackCall();
break;
default:
break;
}
}
switch (testSelection) {
case 0: // Specific standard test
switch (subTestSelection) {
case 1: // base
vieAutoTest.ViEBaseStandardTest();
break;
case 2: // capture
vieAutoTest.ViECaptureStandardTest();
break;
case 3: // codec
vieAutoTest.ViECodecStandardTest();
break;
case 6: // image process
vieAutoTest.ViEImageProcessStandardTest();
break;
#if 0 // vie_autotest_network.cc isn't actually pulled into the build at all!
case 7: // network
vieAutoTest.ViENetworkStandardTest();
break;
#endif
case 8: // Render
vieAutoTest.ViERenderStandardTest();
break;
case 9: // RTP/RTCP
vieAutoTest.ViERtpRtcpStandardTest();
break;
default:
break;
}
break;
case 1:// specific API
switch (subTestSelection) {
case 1: // base
vieAutoTest.ViEBaseAPITest();
break;
case 2: // capture
vieAutoTest.ViECaptureAPITest();
break;
case 3: // codec
vieAutoTest.ViECodecAPITest();
break;
case 6: // image process
vieAutoTest.ViEImageProcessAPITest();
break;
#if 0 // vie_autotest_network.cc isn't actually pulled into the build at all!
case 7: // network
vieAutoTest.ViENetworkAPITest();
break;
#endif
case 8: // Render
vieAutoTest.ViERenderAPITest();
break;
case 9: // RTP/RTCP
vieAutoTest.ViERtpRtcpAPITest();
break;
case 10:
break;
default:
break;
}
break;
case 2:// specific extended
switch (subTestSelection) {
case 1: // base
vieAutoTest.ViEBaseExtendedTest();
break;
case 2: // capture
vieAutoTest.ViECaptureExtendedTest();
break;
case 3: // codec
vieAutoTest.ViECodecExtendedTest();
break;
case 6: // image process
vieAutoTest.ViEImageProcessExtendedTest();
break;
case 7: // Render
vieAutoTest.ViERenderExtendedTest();
break;
case 8: // RTP/RTCP
vieAutoTest.ViERtpRtcpExtendedTest();
break;
default:
break;
}
break;
case 3:
vieAutoTest.ViELoopbackCall();
break;
default:
break;
}
return 0;
}
int main(int argc, char** argv) {
// TODO(leozwang): Add real tests here
return 0;
}
<commit_msg>ViEAutoTestAndroid: Unbreak compile by casting void* to jobject.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest_android.h"
#include <android/log.h>
#include <stdio.h>
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest_defines.h"
int ViEAutoTestAndroid::RunAutotest(int testSelection, int subTestSelection,
void* window1, void* window2,
JavaVM* javaVM, void* env, void* context) {
ViEAutoTest vieAutoTest(window1, window2);
ViETest::Log("RunAutoTest(%d, %d)", testSelection, subTestSelection);
webrtc::VideoEngine::SetAndroidObjects(javaVM, static_cast<jobject>(context));
#ifndef WEBRTC_ANDROID_OPENSLES
// voice engine calls into ADM directly
webrtc::VoiceEngine::SetAndroidObjects(javaVM, env, context);
#endif
if (subTestSelection == 0) {
// Run all selected test
switch (testSelection) {
case 0:
vieAutoTest.ViEStandardTest();
break;
case 1:
vieAutoTest.ViEAPITest();
break;
case 2:
vieAutoTest.ViEExtendedTest();
break;
case 3:
vieAutoTest.ViELoopbackCall();
break;
default:
break;
}
}
switch (testSelection) {
case 0: // Specific standard test
switch (subTestSelection) {
case 1: // base
vieAutoTest.ViEBaseStandardTest();
break;
case 2: // capture
vieAutoTest.ViECaptureStandardTest();
break;
case 3: // codec
vieAutoTest.ViECodecStandardTest();
break;
case 6: // image process
vieAutoTest.ViEImageProcessStandardTest();
break;
#if 0 // vie_autotest_network.cc isn't actually pulled into the build at all!
case 7: // network
vieAutoTest.ViENetworkStandardTest();
break;
#endif
case 8: // Render
vieAutoTest.ViERenderStandardTest();
break;
case 9: // RTP/RTCP
vieAutoTest.ViERtpRtcpStandardTest();
break;
default:
break;
}
break;
case 1:// specific API
switch (subTestSelection) {
case 1: // base
vieAutoTest.ViEBaseAPITest();
break;
case 2: // capture
vieAutoTest.ViECaptureAPITest();
break;
case 3: // codec
vieAutoTest.ViECodecAPITest();
break;
case 6: // image process
vieAutoTest.ViEImageProcessAPITest();
break;
#if 0 // vie_autotest_network.cc isn't actually pulled into the build at all!
case 7: // network
vieAutoTest.ViENetworkAPITest();
break;
#endif
case 8: // Render
vieAutoTest.ViERenderAPITest();
break;
case 9: // RTP/RTCP
vieAutoTest.ViERtpRtcpAPITest();
break;
case 10:
break;
default:
break;
}
break;
case 2:// specific extended
switch (subTestSelection) {
case 1: // base
vieAutoTest.ViEBaseExtendedTest();
break;
case 2: // capture
vieAutoTest.ViECaptureExtendedTest();
break;
case 3: // codec
vieAutoTest.ViECodecExtendedTest();
break;
case 6: // image process
vieAutoTest.ViEImageProcessExtendedTest();
break;
case 7: // Render
vieAutoTest.ViERenderExtendedTest();
break;
case 8: // RTP/RTCP
vieAutoTest.ViERtpRtcpExtendedTest();
break;
default:
break;
}
break;
case 3:
vieAutoTest.ViELoopbackCall();
break;
default:
break;
}
return 0;
}
int main(int argc, char** argv) {
// TODO(leozwang): Add real tests here
return 0;
}
<|endoftext|>
|
<commit_before>/* -*- c++ -*-
passphrasedialog.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004 Klarlvdalens Datakonsult AB
Libkleopatra 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.
Libkleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
Based on kpgpui.cpp
Copyright (C) 2001,2002 the KPGP authors
See file libkdenetwork/AUTHORS.kpgp for details
This file is part of KPGP, the KDE PGP/GnuPG support library.
KPGP 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.
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
*/
#ifndef HAVE_CONFIG_H
#include <config.h>
#endif
#include "passphrasedialog.h"
#include <kpassdlg.h>
#include <kiconloader.h>
#include <klocale.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qfontmetrics.h>
struct Kleo::PassphraseDialog::Private {
KPasswordEdit * lineedit;
};
Kleo::PassphraseDialog::PassphraseDialog( const QString & msg, const QString & caption,
QWidget * parent, const char * name, bool modal )
: KDialogBase( parent, name, modal, caption, Ok|Cancel, Ok ), d( 0 )
{
d = new Private();
QWidget * w = new QWidget( this );
setMainWidget( w );
QHBoxLayout * hlay = new QHBoxLayout( w, marginHint(), spacingHint() );
QLabel * label = new QLabel( w );
label->setPixmap( BarIcon( "pgp-keys" ) );
hlay->addWidget( label, 0, AlignTop );
QVBoxLayout * vlay = new QVBoxLayout( hlay ); // inherits spacing
vlay->addWidget( new QLabel( msg.isEmpty() ? i18n("Please enter your passphrase:") : msg, w ) );
d->lineedit = new KPasswordEdit( KPasswordEdit::OneStar, w, "d->lineedit" );
d->lineedit->setMinimumWidth( fontMetrics().width("*") * 20 );
d->lineedit->setFocus();
vlay->addWidget( d->lineedit );
connect( d->lineedit, SIGNAL(returnPressed()), SLOT(slotOk()) );
disableResize();
}
Kleo::PassphraseDialog::~PassphraseDialog() {
delete d; d = 0;
}
const char * Kleo::PassphraseDialog::passphrase() const {
return d->lineedit->password();
}
void Kleo::PassphraseDialog::slotOk() {
const char * pass = passphrase();
emit finished( pass ? pass : "" );
KDialogBase::slotOk();
}
void Kleo::PassphraseDialog::slotCancel() {
emit canceled();
KDialogBase::slotCancel();
}
void Kleo::PassphraseDialog::virtual_hook( int id, void * data ) {
return KDialogBase::virtual_hook( id, data );
}
#include "passphrasedialog.moc"
<commit_msg>* Add a label for the passphrase lineedit * Use a bigger icon size * Fix margin<commit_after>/* -*- c++ -*-
passphrasedialog.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004 Klarlvdalens Datakonsult AB
Libkleopatra 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.
Libkleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
Based on kpgpui.cpp
Copyright (C) 2001,2002 the KPGP authors
See file libkdenetwork/AUTHORS.kpgp for details
This file is part of KPGP, the KDE PGP/GnuPG support library.
KPGP 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.
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
*/
#ifndef HAVE_CONFIG_H
#include <config.h>
#endif
#include "passphrasedialog.h"
#include <kpassdlg.h>
#include <kiconloader.h>
#include <klocale.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qfontmetrics.h>
struct Kleo::PassphraseDialog::Private {
KPasswordEdit * lineedit;
};
Kleo::PassphraseDialog::PassphraseDialog( const QString & msg, const QString & caption,
QWidget * parent, const char * name, bool modal )
: KDialogBase( parent, name, modal, caption, Ok|Cancel, Ok ), d( 0 )
{
d = new Private();
QWidget * w = new QWidget( this );
setMainWidget( w );
QHBoxLayout * hlay = new QHBoxLayout( w, 0, spacingHint() );
QLabel * label = new QLabel( w );
label->setPixmap( DesktopIcon( "pgp-keys", KIcon::SizeMedium ) );
hlay->addWidget( label, 0, AlignTop );
QVBoxLayout * vlay = new QVBoxLayout( hlay ); // inherits spacing
vlay->addWidget( new QLabel( msg.isEmpty() ? i18n("Please enter your passphrase:") : msg, w ) );
vlay->addWidget( new QLabel( i18n( "Enter passphrase:" ), w ) );
d->lineedit = new KPasswordEdit( KPasswordEdit::OneStar, w, "d->lineedit" );
d->lineedit->setMinimumWidth( fontMetrics().width("*") * 20 );
d->lineedit->setFocus();
vlay->addWidget( d->lineedit );
connect( d->lineedit, SIGNAL(returnPressed()), SLOT(slotOk()) );
disableResize();
}
Kleo::PassphraseDialog::~PassphraseDialog() {
delete d; d = 0;
}
const char * Kleo::PassphraseDialog::passphrase() const {
return d->lineedit->password();
}
void Kleo::PassphraseDialog::slotOk() {
const char * pass = passphrase();
emit finished( pass ? pass : "" );
KDialogBase::slotOk();
}
void Kleo::PassphraseDialog::slotCancel() {
emit canceled();
KDialogBase::slotCancel();
}
void Kleo::PassphraseDialog::virtual_hook( int id, void * data ) {
return KDialogBase::virtual_hook( id, data );
}
#include "passphrasedialog.moc"
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/dom/CharacterData.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/Document.h"
#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/MutationEvent.h"
#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
#include "core/dom/Text.h"
#include "core/editing/FrameSelection.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/platform/text/TextBreakIterator.h"
using namespace std;
namespace WebCore {
void CharacterData::atomize()
{
m_data = AtomicString(m_data);
}
void CharacterData::setData(const String& data)
{
const String& nonNullData = !data.isNull() ? data : emptyString();
if (m_data == nonNullData)
return;
RefPtr<CharacterData> protect = this;
unsigned oldLength = length();
setDataAndUpdate(nonNullData, 0, oldLength, nonNullData.length());
document()->textRemoved(this, 0, oldLength);
}
String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& es)
{
if (offset > length()) {
es.throwDOMException(IndexSizeError);
return String();
}
return m_data.substring(offset, count);
}
unsigned CharacterData::parserAppendData(const String& string, unsigned offset, unsigned lengthLimit)
{
unsigned oldLength = m_data.length();
ASSERT(lengthLimit >= oldLength);
unsigned characterLength = string.length() - offset;
unsigned characterLengthLimit = min(characterLength, lengthLimit - oldLength);
// Check that we are not on an unbreakable boundary.
// Some text break iterator implementations work best if the passed buffer is as small as possible,
// see <https://bugs.webkit.org/show_bug.cgi?id=29092>.
// We need at least two characters look-ahead to account for UTF-16 surrogates.
ASSERT(!string.is8Bit() || string.containsOnlyLatin1()); // Latin-1 doesn't have unbreakable boundaries.
if (characterLengthLimit < characterLength && !string.is8Bit()) {
NonSharedCharacterBreakIterator it(string.characters16() + offset, (characterLengthLimit + 2 > characterLength) ? characterLength : characterLengthLimit + 2);
if (!it.isBreak(characterLengthLimit))
characterLengthLimit = it.preceding(characterLengthLimit);
}
if (!characterLengthLimit)
return 0;
if (string.is8Bit())
m_data.append(string.characters8() + offset, characterLengthLimit);
else
m_data.append(string.characters16() + offset, characterLengthLimit);
ASSERT(!renderer() || isTextNode());
if (isTextNode())
toText(this)->updateTextRenderer(oldLength, 0);
document()->incDOMTreeVersion();
if (parentNode())
parentNode()->childrenChanged();
return characterLengthLimit;
}
void CharacterData::appendData(const String& data)
{
String newStr = m_data;
newStr.append(data);
setDataAndUpdate(newStr, m_data.length(), 0, data.length());
// FIXME: Should we call textInserted here?
}
void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es)
{
if (offset > length()) {
es.throwDOMException(IndexSizeError);
return;
}
String newStr = m_data;
newStr.insert(data, offset);
setDataAndUpdate(newStr, offset, 0, data.length());
document()->textInserted(this, offset, data.length());
}
void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es)
{
if (offset > length()) {
es.throwDOMException(IndexSizeError);
return;
}
unsigned realCount;
if (offset + count > length())
realCount = length() - offset;
else
realCount = count;
String newStr = m_data;
newStr.remove(offset, realCount);
setDataAndUpdate(newStr, offset, count, 0);
document()->textRemoved(this, offset, realCount);
}
void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& es)
{
if (offset > length()) {
es.throwDOMException(IndexSizeError);
return;
}
unsigned realCount;
if (offset + count > length())
realCount = length() - offset;
else
realCount = count;
String newStr = m_data;
newStr.remove(offset, realCount);
newStr.insert(data, offset);
setDataAndUpdate(newStr, offset, count, data.length());
// update the markers for spell checking and grammar checking
document()->textRemoved(this, offset, realCount);
document()->textInserted(this, offset, data.length());
}
String CharacterData::nodeValue() const
{
return m_data;
}
bool CharacterData::containsOnlyWhitespace() const
{
return m_data.containsOnlyWhitespace();
}
void CharacterData::setNodeValue(const String& nodeValue)
{
setData(nodeValue);
}
void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength)
{
String oldData = m_data;
m_data = newData;
ASSERT(!renderer() || isTextNode());
if (isTextNode())
toText(this)->updateTextRenderer(offsetOfReplacedData, oldLength);
if (document()->frame())
document()->frame()->selection()->textWasReplaced(this, offsetOfReplacedData, oldLength, newLength);
document()->incDOMTreeVersion();
didModifyData(oldData);
}
void CharacterData::didModifyData(const String& oldData)
{
if (OwnPtr<MutationObserverInterestGroup> mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(this))
mutationRecipients->enqueueMutationRecord(MutationRecord::createCharacterData(this, oldData));
if (parentNode())
parentNode()->childrenChanged();
if (!isInShadowTree()) {
if (document()->hasListenerType(Document::DOMCHARACTERDATAMODIFIED_LISTENER))
dispatchScopedEvent(MutationEvent::create(eventNames().DOMCharacterDataModifiedEvent, true, 0, oldData, m_data));
dispatchSubtreeModifiedEvent();
}
InspectorInstrumentation::characterDataModified(document(), this);
}
int CharacterData::maxCharacterOffset() const
{
return static_cast<int>(length());
}
bool CharacterData::offsetInCharacters() const
{
return true;
}
} // namespace WebCore
<commit_msg>Remove 'String::append' from 'Source/core/dom/CharacterData.cpp'.<commit_after>/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/dom/CharacterData.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/Document.h"
#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/MutationEvent.h"
#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
#include "core/dom/Text.h"
#include "core/editing/FrameSelection.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/platform/text/TextBreakIterator.h"
using namespace std;
namespace WebCore {
void CharacterData::atomize()
{
m_data = AtomicString(m_data);
}
void CharacterData::setData(const String& data)
{
const String& nonNullData = !data.isNull() ? data : emptyString();
if (m_data == nonNullData)
return;
RefPtr<CharacterData> protect = this;
unsigned oldLength = length();
setDataAndUpdate(nonNullData, 0, oldLength, nonNullData.length());
document()->textRemoved(this, 0, oldLength);
}
String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& es)
{
if (offset > length()) {
es.throwDOMException(IndexSizeError);
return String();
}
return m_data.substring(offset, count);
}
unsigned CharacterData::parserAppendData(const String& string, unsigned offset, unsigned lengthLimit)
{
unsigned oldLength = m_data.length();
ASSERT(lengthLimit >= oldLength);
unsigned characterLength = string.length() - offset;
unsigned characterLengthLimit = min(characterLength, lengthLimit - oldLength);
// Check that we are not on an unbreakable boundary.
// Some text break iterator implementations work best if the passed buffer is as small as possible,
// see <https://bugs.webkit.org/show_bug.cgi?id=29092>.
// We need at least two characters look-ahead to account for UTF-16 surrogates.
ASSERT(!string.is8Bit() || string.containsOnlyLatin1()); // Latin-1 doesn't have unbreakable boundaries.
if (characterLengthLimit < characterLength && !string.is8Bit()) {
NonSharedCharacterBreakIterator it(string.characters16() + offset, (characterLengthLimit + 2 > characterLength) ? characterLength : characterLengthLimit + 2);
if (!it.isBreak(characterLengthLimit))
characterLengthLimit = it.preceding(characterLengthLimit);
}
if (!characterLengthLimit)
return 0;
if (string.is8Bit())
m_data.append(string.characters8() + offset, characterLengthLimit);
else
m_data.append(string.characters16() + offset, characterLengthLimit);
ASSERT(!renderer() || isTextNode());
if (isTextNode())
toText(this)->updateTextRenderer(oldLength, 0);
document()->incDOMTreeVersion();
if (parentNode())
parentNode()->childrenChanged();
return characterLengthLimit;
}
void CharacterData::appendData(const String& data)
{
String newStr = m_data + data;
setDataAndUpdate(newStr, m_data.length(), 0, data.length());
// FIXME: Should we call textInserted here?
}
void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es)
{
if (offset > length()) {
es.throwDOMException(IndexSizeError);
return;
}
String newStr = m_data;
newStr.insert(data, offset);
setDataAndUpdate(newStr, offset, 0, data.length());
document()->textInserted(this, offset, data.length());
}
void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es)
{
if (offset > length()) {
es.throwDOMException(IndexSizeError);
return;
}
unsigned realCount;
if (offset + count > length())
realCount = length() - offset;
else
realCount = count;
String newStr = m_data;
newStr.remove(offset, realCount);
setDataAndUpdate(newStr, offset, count, 0);
document()->textRemoved(this, offset, realCount);
}
void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& es)
{
if (offset > length()) {
es.throwDOMException(IndexSizeError);
return;
}
unsigned realCount;
if (offset + count > length())
realCount = length() - offset;
else
realCount = count;
String newStr = m_data;
newStr.remove(offset, realCount);
newStr.insert(data, offset);
setDataAndUpdate(newStr, offset, count, data.length());
// update the markers for spell checking and grammar checking
document()->textRemoved(this, offset, realCount);
document()->textInserted(this, offset, data.length());
}
String CharacterData::nodeValue() const
{
return m_data;
}
bool CharacterData::containsOnlyWhitespace() const
{
return m_data.containsOnlyWhitespace();
}
void CharacterData::setNodeValue(const String& nodeValue)
{
setData(nodeValue);
}
void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength)
{
String oldData = m_data;
m_data = newData;
ASSERT(!renderer() || isTextNode());
if (isTextNode())
toText(this)->updateTextRenderer(offsetOfReplacedData, oldLength);
if (document()->frame())
document()->frame()->selection()->textWasReplaced(this, offsetOfReplacedData, oldLength, newLength);
document()->incDOMTreeVersion();
didModifyData(oldData);
}
void CharacterData::didModifyData(const String& oldData)
{
if (OwnPtr<MutationObserverInterestGroup> mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(this))
mutationRecipients->enqueueMutationRecord(MutationRecord::createCharacterData(this, oldData));
if (parentNode())
parentNode()->childrenChanged();
if (!isInShadowTree()) {
if (document()->hasListenerType(Document::DOMCHARACTERDATAMODIFIED_LISTENER))
dispatchScopedEvent(MutationEvent::create(eventNames().DOMCharacterDataModifiedEvent, true, 0, oldData, m_data));
dispatchSubtreeModifiedEvent();
}
InspectorInstrumentation::characterDataModified(document(), this);
}
int CharacterData::maxCharacterOffset() const
{
return static_cast<int>(length());
}
bool CharacterData::offsetInCharacters() const
{
return true;
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>// Copyright (c) 2014, Ruslan Baratov
// All rights reserved.
#include <sober/sober.hpp>
class Delegate : public sober::network::api::OpenWeatherMap {
public:
using Base = sober::network::api::OpenWeatherMap;
using StatusCode = sober::network::http::response::attribute::StatusCode;
using ErrorCode = boost::system::error_code;
Delegate(sober::network::http::Stream& stream):
Base(stream),
max_count_(10) {
}
virtual void on_start() override;
virtual boost::posix_time::time_duration watchdog_period() override {
return boost::posix_time::milliseconds(1000);
}
virtual bool force_stop() override {
++counter_;
std::cout << "Count " << counter_ << "/" << max_count_ << std::endl;
bool stop = (counter_ >= max_count_);
if (stop) {
std::cerr << "Timeout reached" << std::endl;
}
return stop;
}
virtual void on_success() override {
try {
Base::on_success();
}
catch (const std::exception& exc) {
std::cerr << "Parse failed: " << exc.what() << std::endl;
return;
}
const Attribute& attr = attribute();
std::cout << "Success..." << std::endl;
std::cout << " longitude: " << attr.longitude << std::endl;
std::cout << " latitude: " << attr.latitude << std::endl;
std::cout << " temperature: " << attr.temperature << std::endl;
std::cout << " temperature(human): " << attr.temperature_human
<< std::endl;
std::cout << " description: " << attr.description << std::endl;
std::cout << " icon: " << attr.icon << std::endl;
}
virtual bool restart_on_error(const ErrorCode& error) override {
std::cerr << "Error: " << error.message() << std::endl;
return false;
}
virtual bool restart_on_error(const StatusCode& status_code) override {
std::cerr << "Error(bad status code): " << status_code << std::endl;
return false;
}
private:
const int max_count_;
int counter_;
};
void Delegate::on_start() {
counter_ = 0;
}
int main() {
try {
const bool debug = sober::utils::always();
if (debug) {
sober::log::Logger::init_logs_for_testing(true, true);
}
else {
sober::log::Logger::init_logs_for_testing(false, false);
}
namespace net = sober::network;
net::Engine engine;
net::http::Stream stream(engine);
Delegate delegate(stream);
const char* city = "Madrid";
std::cout << "City: " << city << std::endl;
delegate.async_get_city(city);
engine.run();
return sober::Exit::OK;
}
catch (std::exception& exc) {
std::cerr << "Exception: " << exc.what() << std::endl;
return sober::Exit::FAIL;
}
}
<commit_msg>Suppress logging on example<commit_after>// Copyright (c) 2014, Ruslan Baratov
// All rights reserved.
#include <sober/sober.hpp>
class Delegate : public sober::network::api::OpenWeatherMap {
public:
using Base = sober::network::api::OpenWeatherMap;
using StatusCode = sober::network::http::response::attribute::StatusCode;
using ErrorCode = boost::system::error_code;
Delegate(sober::network::http::Stream& stream):
Base(stream),
max_count_(10) {
}
virtual void on_start() override;
virtual boost::posix_time::time_duration watchdog_period() override {
return boost::posix_time::milliseconds(1000);
}
virtual bool force_stop() override {
++counter_;
std::cout << "Count " << counter_ << "/" << max_count_ << std::endl;
bool stop = (counter_ >= max_count_);
if (stop) {
std::cerr << "Timeout reached" << std::endl;
}
return stop;
}
virtual void on_success() override {
try {
Base::on_success();
}
catch (const std::exception& exc) {
std::cerr << "Parse failed: " << exc.what() << std::endl;
return;
}
const Attribute& attr = attribute();
std::cout << "Success..." << std::endl;
std::cout << " longitude: " << attr.longitude << std::endl;
std::cout << " latitude: " << attr.latitude << std::endl;
std::cout << " temperature: " << attr.temperature << std::endl;
std::cout << " temperature(human): " << attr.temperature_human
<< std::endl;
std::cout << " description: " << attr.description << std::endl;
std::cout << " icon: " << attr.icon << std::endl;
}
virtual bool restart_on_error(const ErrorCode& error) override {
std::cerr << "Error: " << error.message() << std::endl;
return false;
}
virtual bool restart_on_error(const StatusCode& status_code) override {
std::cerr << "Error(bad status code): " << status_code << std::endl;
return false;
}
private:
const int max_count_;
int counter_;
};
void Delegate::on_start() {
counter_ = 0;
}
int main() {
try {
const bool debug = !sober::utils::always();
if (debug) {
sober::log::Logger::init_logs_for_testing(true, true);
}
else {
sober::log::Logger::init_logs_for_testing(false, false);
}
namespace net = sober::network;
net::Engine engine;
net::http::Stream stream(engine);
Delegate delegate(stream);
const char* city = "Madrid";
std::cout << "City: " << city << std::endl;
delegate.async_get_city(city);
engine.run();
return sober::Exit::OK;
}
catch (std::exception& exc) {
std::cerr << "Exception: " << exc.what() << std::endl;
return sober::Exit::FAIL;
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of HadesMem.
Copyright (C) 2010 Joshua Boyce (aka RaptorFactor, Cypherjb, Cypher, Chazwazza).
<http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>
HadesMem is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
HadesMem 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 HadesMem. If not, see <http://www.gnu.org/licenses/>.
*/
// Windows API
#include <tchar.h>
#include <crtdbg.h>
#include <Windows.h>
// C++ Standard Library
#include <limits>
#include <vector>
#include <string>
#include <iterator>
#include <iostream>
#include <exception>
// Boost
#pragma warning(push, 1)
#include <boost/timer.hpp>
#include <boost/python.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#pragma warning(pop)
// Hades
#include "HadesMemory/Memory.hpp"
bool GetInput(boost::python::object const& PythonNamespace)
{
// Prompt for input
std::cout << ">";
// Get command from user
std::string Input;
while (!std::getline(std::cin, Input) || Input.empty())
{
std::cout << "Invalid command." << std::endl;
std::cout << ">";
// Reset input stream if necessary
if (!std::cin)
{
std::cin.clear();
std::cin.ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
}
}
// Check for quit request
if (Input == "quit" || Input == "exit")
{
return false;
}
try
{
// Run script
boost::python::exec(Input.c_str(), PythonNamespace, PythonNamespace);
}
catch (...)
{
// Handle exceptions
boost::python::handle_exception();
// Print error string
PyErr_Print();
}
return true;
}
// Program entry-point.
int wmain(int argc, wchar_t *argv[ ], wchar_t* /*envp*/[])
{
// Program timer
boost::timer ProgTimer;
try
{
// Attempt to detect memory leaks in debug mode
#ifdef _DEBUG
int CurrentFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
int NewFlags = (_CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_LEAK_CHECK_DF |
_CRTDBG_CHECK_ALWAYS_DF);
_CrtSetDbgFlag(CurrentFlags | NewFlags);
#endif
// Get default heap
HANDLE ProcHeap = GetProcessHeap();
if (!ProcHeap)
{
std::error_code const LastError = Hades::GetLastErrorCode();
BOOST_THROW_EXCEPTION(Hades::HadesError() <<
Hades::ErrorFunction("wmain") <<
Hades::ErrorString("Could not get process heap.") <<
Hades::ErrorCode(LastError));
}
// Detect heap corruption
if (!HeapSetInformation(ProcHeap, HeapEnableTerminationOnCorruption,
NULL, 0))
{
std::error_code const LastError = Hades::GetLastErrorCode();
BOOST_THROW_EXCEPTION(Hades::HadesError() <<
Hades::ErrorFunction("wmain") <<
Hades::ErrorString("Could not set heap information.") <<
Hades::ErrorCode(LastError));
}
// Hades version number
std::wstring const VerNum(L"TRUNK");
// Version and copyright output
#if defined(_M_X64)
std::wcout << "MemSandbox AMD64 [Version " << VerNum << "]\n";
#elif defined(_M_IX86)
std::wcout << "MemSandbox IA32 [Version " << VerNum << "]\n";
#else
#error "[HadesMem] Unsupported architecture."
#endif
std::wcout << "Copyright (C) 2010 RaptorFactor. All rights reserved." <<
std::endl;
std::wcout << "Website: http://www.raptorfactor.com/, "
"Email: raptorfactor@raptorfactor.com." << std::endl;
std::wcout << "Built on " << __DATE__ << " at " << __TIME__ << "." <<
std::endl << std::endl;
// Auto-close flag (Set by Boost.ProgramOptions)
bool KeepOpen = false;
// Path to script file (Set by Boost.ProgramOptions)
std::wstring FilePath;
// Script string (Set by Boost.ProgramOptions)
std::string ScriptStr;
// Set program option descriptions
boost::program_options::options_description OptsDesc("Allowed options");
OptsDesc.add_options()
("help", "display help")
("keep-open", boost::program_options::wvalue<bool>(&KeepOpen)->
zero_tokens(), "keep console window open")
("file", boost::program_options::wvalue<std::wstring>(&FilePath),
"file to execute")
("string", boost::program_options::value<std::string>(&ScriptStr),
"string to execute")
;
// Parse program options
boost::program_options::variables_map Opts;
boost::program_options::store(boost::program_options::parse_command_line(
argc, argv, OptsDesc), Opts);
boost::program_options::notify(Opts);
// Print help if requested
if (Opts.count("help"))
{
// Print help
std::cout << OptsDesc << std::endl;
// Stop window from automatically closing if required
if (KeepOpen)
{
std::wcin.clear();
std::wcin.sync();
std::wcin.get();
}
// Quit
return 1;
}
// Initialize Python
Py_Initialize();
// Debug output
std::wcout << "Python " << Py_GetVersion() << "\n" << std::endl;
// Retrieve the main module.
boost::python::object PythonMain(boost::python::import("__main__"));
// Retrieve the main module's namespace
boost::python::object PythonGlobal(PythonMain.attr("__dict__"));
try
{
// Import PyHadesMem
boost::python::exec("import PyHadesMem", PythonGlobal, PythonGlobal);
}
catch (...)
{
// Print error string
PyErr_Print();
// Throw exception
BOOST_THROW_EXCEPTION(Hades::HadesError() <<
Hades::ErrorFunction("_tmain") <<
Hades::ErrorString("Failed to load PyHadesMem."));
}
// If user has passed in a file-name then run it
if (!FilePath.empty())
{
// Get file
boost::filesystem::path const FilePathReal(FilePath);
if (!boost::filesystem::exists(FilePathReal))
{
BOOST_THROW_EXCEPTION(Hades::HadesError() <<
Hades::ErrorFunction("_tmain") <<
Hades::ErrorString("Requested file could not be found."));
}
try
{
// Run file
boost::python::exec_file(FilePathReal.string().c_str(), PythonGlobal,
PythonGlobal);
}
catch (...)
{
// Handle exceptions
boost::python::handle_exception();
// Print error string
PyErr_Print();
}
}
// If user has passed in a string then run it
else if (!ScriptStr.empty())
{
try
{
// Run script
boost::python::exec(ScriptStr.c_str(), PythonGlobal, PythonGlobal);
}
catch (...)
{
// Handle exceptions
boost::python::handle_exception();
// Print error string
PyErr_Print();
}
}
// Otherwise process commands from user
else
{
for (;;)
{
try
{
if (!GetInput(PythonGlobal))
{
break;
}
}
catch (std::exception const& e)
{
// Dump error information
std::cout << boost::diagnostic_information(e);
}
}
}
// Print elapsed time
std::wcout << "\nElapsed Time: " << ProgTimer.elapsed() << "." <<
std::endl;
// Stop window from automatically closing if required
if (KeepOpen)
{
std::wcin.clear();
std::wcin.sync();
std::wcin.get();
}
}
catch (std::exception const& e)
{
// Dump error information
std::cout << boost::diagnostic_information(e);
// Print elapsed time
std::wcout << "\nElapsed Time: " << ProgTimer.elapsed() << "." <<
std::endl;
// Always keep window open in case of an error
std::wcin.clear();
std::wcin.sync();
std::wcin.get();
}
}
<commit_msg>* Output fix.<commit_after>/*
This file is part of HadesMem.
Copyright (C) 2010 Joshua Boyce (aka RaptorFactor, Cypherjb, Cypher, Chazwazza).
<http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>
HadesMem is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
HadesMem 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 HadesMem. If not, see <http://www.gnu.org/licenses/>.
*/
// Windows API
#include <tchar.h>
#include <crtdbg.h>
#include <Windows.h>
// C++ Standard Library
#include <limits>
#include <vector>
#include <string>
#include <iterator>
#include <iostream>
#include <exception>
// Boost
#pragma warning(push, 1)
#include <boost/timer.hpp>
#include <boost/python.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#pragma warning(pop)
// Hades
#include "HadesMemory/Memory.hpp"
bool GetInput(boost::python::object const& PythonNamespace)
{
// Prompt for input
std::cout << ">";
// Get command from user
std::string Input;
while (!std::getline(std::cin, Input) || Input.empty())
{
std::cout << "Invalid command." << std::endl;
std::cout << ">";
// Reset input stream if necessary
if (!std::cin)
{
std::cin.clear();
std::cin.ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
}
}
// Check for quit request
if (Input == "quit" || Input == "exit")
{
return false;
}
try
{
// Run script
boost::python::exec(Input.c_str(), PythonNamespace, PythonNamespace);
}
catch (...)
{
// Handle exceptions
boost::python::handle_exception();
// Print error string
PyErr_Print();
}
return true;
}
// Program entry-point.
int wmain(int argc, wchar_t *argv[ ], wchar_t* /*envp*/[])
{
// Program timer
boost::timer ProgTimer;
try
{
// Attempt to detect memory leaks in debug mode
#ifdef _DEBUG
int CurrentFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
int NewFlags = (_CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_LEAK_CHECK_DF |
_CRTDBG_CHECK_ALWAYS_DF);
_CrtSetDbgFlag(CurrentFlags | NewFlags);
#endif
// Get default heap
HANDLE ProcHeap = GetProcessHeap();
if (!ProcHeap)
{
std::error_code const LastError = Hades::GetLastErrorCode();
BOOST_THROW_EXCEPTION(Hades::HadesError() <<
Hades::ErrorFunction("wmain") <<
Hades::ErrorString("Could not get process heap.") <<
Hades::ErrorCode(LastError));
}
// Detect heap corruption
if (!HeapSetInformation(ProcHeap, HeapEnableTerminationOnCorruption,
NULL, 0))
{
std::error_code const LastError = Hades::GetLastErrorCode();
BOOST_THROW_EXCEPTION(Hades::HadesError() <<
Hades::ErrorFunction("wmain") <<
Hades::ErrorString("Could not set heap information.") <<
Hades::ErrorCode(LastError));
}
// Hades version number
std::wstring const VerNum(L"TRUNK");
// Version and copyright output
#if defined(_M_X64)
std::wcout << "Hades MemSandbox AMD64 [Version " << VerNum << "]\n";
#elif defined(_M_IX86)
std::wcout << "Hades MemSandbox IA32 [Version " << VerNum << "]\n";
#else
#error "[HadesMem] Unsupported architecture."
#endif
std::wcout << "Copyright (C) 2010 RaptorFactor. All rights reserved." <<
std::endl;
std::wcout << "Website: http://www.raptorfactor.com/, "
"Email: raptorfactor@raptorfactor.com." << std::endl;
std::wcout << "Built on " << __DATE__ << " at " << __TIME__ << "." <<
std::endl << std::endl;
// Auto-close flag (Set by Boost.ProgramOptions)
bool KeepOpen = false;
// Path to script file (Set by Boost.ProgramOptions)
std::wstring FilePath;
// Script string (Set by Boost.ProgramOptions)
std::string ScriptStr;
// Set program option descriptions
boost::program_options::options_description OptsDesc("Allowed options");
OptsDesc.add_options()
("help", "display help")
("keep-open", boost::program_options::wvalue<bool>(&KeepOpen)->
zero_tokens(), "keep console window open")
("file", boost::program_options::wvalue<std::wstring>(&FilePath),
"file to execute")
("string", boost::program_options::value<std::string>(&ScriptStr),
"string to execute")
;
// Parse program options
boost::program_options::variables_map Opts;
boost::program_options::store(boost::program_options::parse_command_line(
argc, argv, OptsDesc), Opts);
boost::program_options::notify(Opts);
// Print help if requested
if (Opts.count("help"))
{
// Print help
std::cout << OptsDesc << std::endl;
// Stop window from automatically closing if required
if (KeepOpen)
{
std::wcin.clear();
std::wcin.sync();
std::wcin.get();
}
// Quit
return 1;
}
// Initialize Python
Py_Initialize();
// Debug output
std::wcout << "Python " << Py_GetVersion() << "\n" << std::endl;
// Retrieve the main module.
boost::python::object PythonMain(boost::python::import("__main__"));
// Retrieve the main module's namespace
boost::python::object PythonGlobal(PythonMain.attr("__dict__"));
try
{
// Import PyHadesMem
boost::python::exec("import PyHadesMem", PythonGlobal, PythonGlobal);
}
catch (...)
{
// Print error string
PyErr_Print();
// Throw exception
BOOST_THROW_EXCEPTION(Hades::HadesError() <<
Hades::ErrorFunction("_tmain") <<
Hades::ErrorString("Failed to load PyHadesMem."));
}
// If user has passed in a file-name then run it
if (!FilePath.empty())
{
// Get file
boost::filesystem::path const FilePathReal(FilePath);
if (!boost::filesystem::exists(FilePathReal))
{
BOOST_THROW_EXCEPTION(Hades::HadesError() <<
Hades::ErrorFunction("_tmain") <<
Hades::ErrorString("Requested file could not be found."));
}
try
{
// Run file
boost::python::exec_file(FilePathReal.string().c_str(), PythonGlobal,
PythonGlobal);
}
catch (...)
{
// Handle exceptions
boost::python::handle_exception();
// Print error string
PyErr_Print();
}
}
// If user has passed in a string then run it
else if (!ScriptStr.empty())
{
try
{
// Run script
boost::python::exec(ScriptStr.c_str(), PythonGlobal, PythonGlobal);
}
catch (...)
{
// Handle exceptions
boost::python::handle_exception();
// Print error string
PyErr_Print();
}
}
// Otherwise process commands from user
else
{
for (;;)
{
try
{
if (!GetInput(PythonGlobal))
{
break;
}
}
catch (std::exception const& e)
{
// Dump error information
std::cout << boost::diagnostic_information(e);
}
}
}
// Print elapsed time
std::wcout << "\nElapsed Time: " << ProgTimer.elapsed() << "." <<
std::endl;
// Stop window from automatically closing if required
if (KeepOpen)
{
std::wcin.clear();
std::wcin.sync();
std::wcin.get();
}
}
catch (std::exception const& e)
{
// Dump error information
std::cout << boost::diagnostic_information(e);
// Print elapsed time
std::wcout << "\nElapsed Time: " << ProgTimer.elapsed() << "." <<
std::endl;
// Always keep window open in case of an error
std::wcin.clear();
std::wcin.sync();
std::wcin.get();
}
}
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include "stan/prob/distributions/multivariate/continuous/multi_normal_cholesky.hpp"
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <stan/agrad/rev.hpp>
using Eigen::Dynamic;
using Eigen::Matrix;
using std::vector;
TEST(ProbDistributionsMultiNormalCholesky,NotVectorized) {
Matrix<double,Dynamic,1> y(3,1);
y << 2.0, -2.0, 11.0;
Matrix<double,Dynamic,1> mu(3,1);
mu << 1.0, -1.0, 3.0;
Matrix<double,Dynamic,Dynamic> Sigma(3,3);
Sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 0.0,
0.0, 0.0, 5.0;
Matrix<double,Dynamic,Dynamic> L = Sigma.llt().matrixL();
EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L));
}
TEST(ProbDistributionsMultiNormal,Vectorized) {
vector< Matrix<double,Dynamic,1> > vec_y(2);
vector< Matrix<double,1,Dynamic> > vec_y_t(2);
Matrix<double,Dynamic,1> y(3);
Matrix<double,1,Dynamic> y_t(3);
y << 2.0, -2.0, 11.0;
vec_y[0] = y;
vec_y_t[0] = y;
y << 4.0, -2.0, 1.0;
vec_y[1] = y;
vec_y_t[1] = y;
y_t = y;
vector< Matrix<double,Dynamic,1> > vec_mu(2);
vector< Matrix<double,1,Dynamic> > vec_mu_t(2);
Matrix<double,Dynamic,1> mu(3);
Matrix<double,1,Dynamic> mu_t(3);
mu << 1.0, -1.0, 3.0;
vec_mu[0] = mu;
vec_mu_t[0] = mu;
mu << 2.0, -1.0, 4.0;
vec_mu[1] = mu;
vec_mu_t[1] = mu;
mu_t = mu;
Matrix<double,Dynamic,Dynamic> Sigma(3,3);
Sigma << 10.0, -3.0, 0.0,
-3.0, 5.0, 0.0,
0.0, 0.0, 5.0;
Sigma = Sigma.llt().matrixL();
//y and mu vectorized
EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y,vec_mu,Sigma));
EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y_t,vec_mu,Sigma));
EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y,vec_mu_t,Sigma));
EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y_t,vec_mu_t,Sigma));
//y vectorized
EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y,mu,Sigma));
EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y_t,mu,Sigma));
EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y,mu_t,Sigma));
EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y_t,mu_t,Sigma));
//mu vectorized
EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y,vec_mu,Sigma));
EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y_t,vec_mu,Sigma));
EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y,vec_mu_t,Sigma));
EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y_t,vec_mu_t,Sigma));
}
TEST(ProbDistributionsMultiNormalCholesky,MultiNormalVar) {
using stan::agrad::var;
Matrix<var,Dynamic,1> y(3,1);
y << 2.0, -2.0, 11.0;
Matrix<var,Dynamic,1> mu(3,1);
mu << 1.0, -1.0, 3.0;
Matrix<var,Dynamic,Dynamic> Sigma(3,3);
Sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 0.0,
0.0, 0.0, 5.0;
Matrix<var,Dynamic,Dynamic> L = Sigma.llt().matrixL();
EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L).val());
}
TEST(ProbDistributionsMultiNormalCholesky,MultiNormalOneRow) {
Matrix<double,Dynamic,Dynamic> y(1,3);
y << 2.0, -2.0, 11.0;
Matrix<double,Dynamic,1> mu(3,1);
mu << 1.0, -1.0, 3.0;
Matrix<double,Dynamic,Dynamic> Sigma(3,3);
Sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 0.0,
0.0, 0.0, 5.0;
Matrix<double,Dynamic,Dynamic> L = Sigma.llt().matrixL();
EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L));
}
TEST(ProbDistributionsMultiNormalCholesky, error_check) {
boost::random::mt19937 rng;
Matrix<double,Dynamic,Dynamic> mu(3,1);
mu << 2.0,
-2.0,
11.0;
Matrix<double,Dynamic,Dynamic> sigma(3,3);
sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 1.0,
0.0, 1.0, 3.0;
sigma = sigma.llt().matrixL();
EXPECT_NO_THROW(stan::prob::multi_normal_cholesky_rng(mu, sigma,rng));
mu << stan::math::positive_infinity(),
-2.0,
11.0;
EXPECT_THROW(stan::prob::multi_normal_cholesky_rng(mu,sigma,rng),std::domain_error);
}
TEST(ProbDistributionsMultiNormalCholesky, marginalOneChiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
Matrix<double,Dynamic,Dynamic> sigma(3,3);
sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 1.0,
0.0, 1.0, 3.0;
sigma = sigma.llt().matrixL();
Matrix<double,Dynamic,Dynamic> mu(3,1);
mu << 2.0,
-2.0,
11.0;
int N = 10000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::normal_distribution<>dist (2.0,3.0);
boost::math::chi_squared mydist(K-1);
double loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));
int count = 0;
int bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N / K;
}
Eigen::VectorXd a(mu.rows());
while (count < N) {
a = stan::prob::multi_normal_cholesky_rng(mu,sigma,rng);
int i = 0;
while (i < K-1 && a(0) > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsMultiNormalCholesky, marginalTwoChiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
Matrix<double,Dynamic,Dynamic> sigma(3,3);
sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 1.0,
0.0, 1.0, 3.0;
sigma = sigma.llt().matrixL();
Matrix<double,Dynamic,Dynamic> mu(3,1);
mu << 2.0,
-2.0,
11.0;
int N = 10000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::normal_distribution<>dist (-2.0,2.0);
boost::math::chi_squared mydist(K-1);
double loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));
int count = 0;
int bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N / K;
}
Eigen::VectorXd a(mu.rows());
while (count < N) {
a = stan::prob::multi_normal_cholesky_rng(mu,sigma,rng);
int i = 0;
while (i < K-1 && a(1) > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsMultiNormalCholesky, marginalThreeChiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
Matrix<double,Dynamic,Dynamic> sigma(3,3);
sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 1.0,
0.0, 1.0, 16.0;
sigma = sigma.llt().matrixL();
Matrix<double,Dynamic,Dynamic> mu(3,1);
mu << 2.0,
-2.0,
11.0;
int N = 10000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::normal_distribution<>dist (11.0,4.0);
boost::math::chi_squared mydist(K-1);
double loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));
int count = 0;
int bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N / K;
}
Eigen::VectorXd a(mu.rows());
while (count < N) {
a = stan::prob::multi_normal_cholesky_rng(mu,sigma,rng);
int i = 0;
while (i < K-1 && a(2) > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
<commit_msg>use dedicated variable for Cholesky factor in tests<commit_after>#include <gtest/gtest.h>
#include "stan/prob/distributions/multivariate/continuous/multi_normal_cholesky.hpp"
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <stan/agrad/rev.hpp>
using Eigen::Dynamic;
using Eigen::Matrix;
using std::vector;
TEST(ProbDistributionsMultiNormalCholesky,NotVectorized) {
Matrix<double,Dynamic,1> y(3,1);
y << 2.0, -2.0, 11.0;
Matrix<double,Dynamic,1> mu(3,1);
mu << 1.0, -1.0, 3.0;
Matrix<double,Dynamic,Dynamic> Sigma(3,3);
Sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 0.0,
0.0, 0.0, 5.0;
Matrix<double,Dynamic,Dynamic> L = Sigma.llt().matrixL();
EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L));
}
TEST(ProbDistributionsMultiNormal,Vectorized) {
vector< Matrix<double,Dynamic,1> > vec_y(2);
vector< Matrix<double,1,Dynamic> > vec_y_t(2);
Matrix<double,Dynamic,1> y(3);
Matrix<double,1,Dynamic> y_t(3);
y << 2.0, -2.0, 11.0;
vec_y[0] = y;
vec_y_t[0] = y;
y << 4.0, -2.0, 1.0;
vec_y[1] = y;
vec_y_t[1] = y;
y_t = y;
vector< Matrix<double,Dynamic,1> > vec_mu(2);
vector< Matrix<double,1,Dynamic> > vec_mu_t(2);
Matrix<double,Dynamic,1> mu(3);
Matrix<double,1,Dynamic> mu_t(3);
mu << 1.0, -1.0, 3.0;
vec_mu[0] = mu;
vec_mu_t[0] = mu;
mu << 2.0, -1.0, 4.0;
vec_mu[1] = mu;
vec_mu_t[1] = mu;
mu_t = mu;
Matrix<double,Dynamic,Dynamic> Sigma(3,3);
Sigma << 10.0, -3.0, 0.0,
-3.0, 5.0, 0.0,
0.0, 0.0, 5.0;
Matrix<double,Dynamic,Dynamic> L = Sigma.llt().matrixL();
//y and mu vectorized
EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y,vec_mu,L));
EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y_t,vec_mu,L));
EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y,vec_mu_t,L));
EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y_t,vec_mu_t,L));
//y vectorized
EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y,mu,L));
EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y_t,mu,L));
EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y,mu_t,L));
EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y_t,mu_t,L));
//mu vectorized
EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y,vec_mu,L));
EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y_t,vec_mu,L));
EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y,vec_mu_t,L));
EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y_t,vec_mu_t,L));
}
TEST(ProbDistributionsMultiNormalCholesky,MultiNormalVar) {
using stan::agrad::var;
Matrix<var,Dynamic,1> y(3,1);
y << 2.0, -2.0, 11.0;
Matrix<var,Dynamic,1> mu(3,1);
mu << 1.0, -1.0, 3.0;
Matrix<var,Dynamic,Dynamic> Sigma(3,3);
Sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 0.0,
0.0, 0.0, 5.0;
Matrix<var,Dynamic,Dynamic> L = Sigma.llt().matrixL();
EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L).val());
}
TEST(ProbDistributionsMultiNormalCholesky,MultiNormalOneRow) {
Matrix<double,Dynamic,Dynamic> y(1,3);
y << 2.0, -2.0, 11.0;
Matrix<double,Dynamic,1> mu(3,1);
mu << 1.0, -1.0, 3.0;
Matrix<double,Dynamic,Dynamic> Sigma(3,3);
Sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 0.0,
0.0, 0.0, 5.0;
Matrix<double,Dynamic,Dynamic> L = Sigma.llt().matrixL();
EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L));
}
TEST(ProbDistributionsMultiNormalCholesky, error_check) {
boost::random::mt19937 rng;
Matrix<double,Dynamic,Dynamic> mu(3,1);
mu << 2.0,
-2.0,
11.0;
Matrix<double,Dynamic,Dynamic> sigma(3,3);
sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 1.0,
0.0, 1.0, 3.0;
Matrix<double,Dynamic,Dynamic> L = sigma.llt().matrixL();
EXPECT_NO_THROW(stan::prob::multi_normal_cholesky_rng(mu, L, rng));
mu << stan::math::positive_infinity(),
-2.0,
11.0;
EXPECT_THROW(stan::prob::multi_normal_cholesky_rng(mu,sigma,rng),std::domain_error);
}
TEST(ProbDistributionsMultiNormalCholesky, marginalOneChiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
Matrix<double,Dynamic,Dynamic> sigma(3,3);
sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 1.0,
0.0, 1.0, 3.0;
Matrix<double,Dynamic,Dynamic> L = sigma.llt().matrixL();
Matrix<double,Dynamic,Dynamic> mu(3,1);
mu << 2.0,
-2.0,
11.0;
int N = 10000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::normal_distribution<>dist (2.0,3.0);
boost::math::chi_squared mydist(K-1);
double loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));
int count = 0;
int bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N / K;
}
Eigen::VectorXd a(mu.rows());
while (count < N) {
a = stan::prob::multi_normal_cholesky_rng(mu,L,rng);
int i = 0;
while (i < K-1 && a(0) > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsMultiNormalCholesky, marginalTwoChiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
Matrix<double,Dynamic,Dynamic> sigma(3,3);
sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 1.0,
0.0, 1.0, 3.0;
Matrix<double,Dynamic,Dynamic> L = sigma.llt().matrixL();
Matrix<double,Dynamic,Dynamic> mu(3,1);
mu << 2.0,
-2.0,
11.0;
int N = 10000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::normal_distribution<>dist (-2.0,2.0);
boost::math::chi_squared mydist(K-1);
double loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));
int count = 0;
int bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N / K;
}
Eigen::VectorXd a(mu.rows());
while (count < N) {
a = stan::prob::multi_normal_cholesky_rng(mu,L,rng);
int i = 0;
while (i < K-1 && a(1) > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsMultiNormalCholesky, marginalThreeChiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
Matrix<double,Dynamic,Dynamic> sigma(3,3);
sigma << 9.0, -3.0, 0.0,
-3.0, 4.0, 1.0,
0.0, 1.0, 16.0;
Matrix<double,Dynamic,Dynamic> L = sigma.llt().matrixL();
Matrix<double,Dynamic,Dynamic> mu(3,1);
mu << 2.0,
-2.0,
11.0;
int N = 10000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::normal_distribution<>dist (11.0,4.0);
boost::math::chi_squared mydist(K-1);
double loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));
int count = 0;
int bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N / K;
}
Eigen::VectorXd a(mu.rows());
while (count < N) {
a = stan::prob::multi_normal_cholesky_rng(mu,L,rng);
int i = 0;
while (i < K-1 && a(2) > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <stdexcept>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
#include <bh.h>
#include "bh_fuse.h"
using namespace std;
namespace bohrium {
/* The possible fuse models */
enum fuse_model
{
/* The broadest possible model. I.e. a SIMD machine can
* theoretically execute the two instructions in a single operation,
* thus accepts broadcast, reduction, extension methods, etc. */
BROADEST,
/* A very simple mode that only fuses same shaped arrays thus no
* broadcast, reduction, extension methods, etc. */
SAME_SHAPE,
/* The sentinel */
NONE
};
/* The default fuse model */
static const fuse_model default_fuse_model = BROADEST;
/* The current selected fuse model */
static fuse_model selected_fuse_model = NONE;
/************************************************************************/
/*************** Specific fuse model implementations ********************/
/************************************************************************/
static bool fuse_broadest(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
&& not bh_view_aligned(&b->operand[0], &a->operand[i]))
return false;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
&& not bh_view_aligned(&a->operand[0], &b->operand[i]))
return false;
}
return true;
}
static bool fuse_same_shape(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
if(!bh_opcode_is_elementwise(a->opcode) || !bh_opcode_is_elementwise(b->opcode))
return false;
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
&& not bh_view_aligned_and_same_shape(&b->operand[0], &a->operand[i]))
return false;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
&& not bh_view_aligned_and_same_shape(&a->operand[0], &b->operand[i]))
return false;
}
return true;
}
/************************************************************************/
/*************** The public interface implementation ********************/
/************************************************************************/
/* Get the selected fuse model by reading the environment
* variable 'BH_FUSE_MODEL' */
static fuse_model get_selected_fuse_model()
{
using namespace boost;
//Check enviroment variable
const char *env = getenv("BH_FUSE_MODEL");
if(env != NULL)
{
string e(env);
if(iequals(e, string("broadest")))
{
//cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
return BROADEST;
}
else if(iequals(e, string("same_shape")))
{
//cout << "[FUSE] info: selected fuse model: 'SAME_SHAPE'" << endl;
return SAME_SHAPE;
}
else
{
cerr << "[FUSE] WARNING: unknown fuse model: '" << e;
cerr << "', using the default model instead" << endl;
}
}
//cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
return default_fuse_model;
}
/* Determines whether it is legal to fuse two instructions into one
* kernel using the 'selected_fuse_model'.
*
* @a The first instruction
* @b The second instruction
* @return The boolean answer
*/
bool check_fusible(const bh_instruction *a, const bh_instruction *b)
{
switch(selected_fuse_model)
{
case NONE:
selected_fuse_model = get_selected_fuse_model();
return check_fusible(a, b);
case BROADEST:
return fuse_broadest(a,b);
case SAME_SHAPE:
return fuse_same_shape(a,b);
default:
throw runtime_error("No fuse module is selected!");
}
}
} //namespace bohrium
<commit_msg>fuse: now all instructions must have same shape in fuse_same_shape()<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <stdexcept>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
#include <bh.h>
#include "bh_fuse.h"
using namespace std;
namespace bohrium {
/* The possible fuse models */
enum fuse_model
{
/* The broadest possible model. I.e. a SIMD machine can
* theoretically execute the two instructions in a single operation,
* thus accepts broadcast, reduction, extension methods, etc. */
BROADEST,
/* A very simple mode that only fuses same shaped arrays thus no
* broadcast, reduction, extension methods, etc. */
SAME_SHAPE,
/* The sentinel */
NONE
};
/* The default fuse model */
static const fuse_model default_fuse_model = BROADEST;
/* The current selected fuse model */
static fuse_model selected_fuse_model = NONE;
/************************************************************************/
/*************** Specific fuse model implementations ********************/
/************************************************************************/
static bool fuse_broadest(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
&& not bh_view_aligned(&b->operand[0], &a->operand[i]))
return false;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
&& not bh_view_aligned(&a->operand[0], &b->operand[i]))
return false;
}
return true;
}
static bool fuse_same_shape(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
if(!bh_opcode_is_elementwise(a->opcode) || !bh_opcode_is_elementwise(b->opcode))
return false;
const int a_nop = bh_operands(a->opcode);
const int b_nop = bh_operands(b->opcode);
const bh_intp *shape = a->operand[0].shape;
const bh_intp ndim = a->operand[0].ndim;
for(int i=1; i<a_nop; ++i)
{
if(bh_is_constant(&a->operand[i]))
continue;
if(ndim != a->operand[i].ndim)
return false;
for(bh_intp j=0; j<ndim; ++j)
{
if(a->operand[i].shape[j] != shape[j])
return false;
}
}
for(int i=0; i<b_nop; ++i)
{
if(bh_is_constant(&b->operand[i]))
continue;
if(ndim != b->operand[i].ndim)
return false;
for(bh_intp j=0; j<ndim; ++j)
{
if(b->operand[i].shape[j] != shape[j])
return false;
}
}
return fuse_broadest(a, b);
}
/************************************************************************/
/*************** The public interface implementation ********************/
/************************************************************************/
/* Get the selected fuse model by reading the environment
* variable 'BH_FUSE_MODEL' */
static fuse_model get_selected_fuse_model()
{
using namespace boost;
//Check enviroment variable
const char *env = getenv("BH_FUSE_MODEL");
if(env != NULL)
{
string e(env);
if(iequals(e, string("broadest")))
{
//cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
return BROADEST;
}
else if(iequals(e, string("same_shape")))
{
//cout << "[FUSE] info: selected fuse model: 'SAME_SHAPE'" << endl;
return SAME_SHAPE;
}
else
{
cerr << "[FUSE] WARNING: unknown fuse model: '" << e;
cerr << "', using the default model instead" << endl;
}
}
//cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
return default_fuse_model;
}
/* Determines whether it is legal to fuse two instructions into one
* kernel using the 'selected_fuse_model'.
*
* @a The first instruction
* @b The second instruction
* @return The boolean answer
*/
bool check_fusible(const bh_instruction *a, const bh_instruction *b)
{
switch(selected_fuse_model)
{
case NONE:
selected_fuse_model = get_selected_fuse_model();
return check_fusible(a, b);
case BROADEST:
return fuse_broadest(a,b);
case SAME_SHAPE:
return fuse_same_shape(a,b);
default:
throw runtime_error("No fuse module is selected!");
}
}
} //namespace bohrium
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tp_SeriesToAxis.cxx,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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "tp_SeriesToAxis.hxx"
#include "ResId.hxx"
#include "TabPages.hrc"
#include "chartview/ChartSfxItemIds.hxx"
#include "NoWarningThisInCTOR.hxx"
// header for class SfxBoolItem
#include <svtools/eitem.hxx>
// header for SfxInt32Item
#include <svtools/intitem.hxx>
//.............................................................................
namespace chart
{
//.............................................................................
SchOptionTabPage::SchOptionTabPage(Window* pWindow,const SfxItemSet& rInAttrs) :
SfxTabPage(pWindow, SchResId(TP_OPTIONS), rInAttrs),
aGrpAxis(this, SchResId(GRP_OPT_AXIS)),
aRbtAxis1(this,SchResId(RBT_OPT_AXIS_1)),
aRbtAxis2(this,SchResId(RBT_OPT_AXIS_2)),
aGrpBar(this, SchResId(GB_BAR)),
aFTGap(this,SchResId(FT_GAP)),
aMTGap(this,SchResId(MT_GAP)),
aFTOverlap(this,SchResId(FT_OVERLAP)),
aMTOverlap(this,SchResId(MT_OVERLAP)),
aCBConnect(this,SchResId(CB_CONNECTOR)),
aCBAxisSideBySide(this,SchResId(CB_BARS_SIDE_BY_SIDE))
{
FreeResource();
aRbtAxis1.SetClickHdl( LINK( this, SchOptionTabPage, EnableHdl ));
aRbtAxis2.SetClickHdl( LINK( this, SchOptionTabPage, EnableHdl ));
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
SchOptionTabPage::~SchOptionTabPage()
{
}
IMPL_LINK( SchOptionTabPage, EnableHdl, RadioButton *, EMPTYARG )
{
if( m_nAllSeriesAxisIndex == 0 )
aCBAxisSideBySide.Enable( aRbtAxis2.IsChecked());
else if( m_nAllSeriesAxisIndex == 1 )
aCBAxisSideBySide.Enable( aRbtAxis1.IsChecked());
return 0;
}
/*************************************************************************
|*
|* Erzeugung
|*
\*************************************************************************/
SfxTabPage* SchOptionTabPage::Create(Window* pWindow,const SfxItemSet& rOutAttrs)
{
return new SchOptionTabPage(pWindow, rOutAttrs);
}
/*************************************************************************
|*
|* Fuellt uebergebenen Item-Set mit Dialogbox-Attributen
|*
\*************************************************************************/
BOOL SchOptionTabPage::FillItemSet(SfxItemSet& rOutAttrs)
{
if(aRbtAxis2.IsChecked())
rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_SECONDARY_Y));
else
rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_PRIMARY_Y));
if(aMTGap.IsVisible())
rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_GAPWIDTH,static_cast< sal_Int32 >( aMTGap.GetValue())));
if(aMTOverlap.IsVisible())
rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_OVERLAP,static_cast< sal_Int32 >( aMTOverlap.GetValue())));
if(aCBConnect.IsVisible())
rOutAttrs.Put(SfxBoolItem(SCHATTR_BAR_CONNECT,aCBConnect.IsChecked()));
// model property is "group bars per axis", UI feature is the other way
// round: "show bars side by side"
if(aCBAxisSideBySide.IsVisible())
rOutAttrs.Put(SfxBoolItem(SCHATTR_GROUP_BARS_PER_AXIS, ! aCBAxisSideBySide.IsChecked()));
return TRUE;
}
/*************************************************************************
|*
|* Initialisierung
|*
\*************************************************************************/
void SchOptionTabPage::Reset(const SfxItemSet& rInAttrs)
{
const SfxPoolItem *pPoolItem = NULL;
aRbtAxis1.Check(TRUE);
aRbtAxis2.Check(FALSE);
if (rInAttrs.GetItemState(SCHATTR_AXIS,TRUE, &pPoolItem) == SFX_ITEM_SET)
{
long nVal=((const SfxInt32Item*)pPoolItem)->GetValue();
if(nVal==CHART_AXIS_SECONDARY_Y)
{
aRbtAxis2.Check(TRUE);
aRbtAxis1.Check(FALSE);
}
}
long nTmp;
if (rInAttrs.GetItemState(SCHATTR_BAR_GAPWIDTH, TRUE, &pPoolItem) == SFX_ITEM_SET)
{
nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue();
aMTGap.SetValue(nTmp);
}
else
{
aMTGap.Show(FALSE);
aFTGap.Show(FALSE);
}
if (rInAttrs.GetItemState(SCHATTR_BAR_OVERLAP, TRUE, &pPoolItem) == SFX_ITEM_SET)
{
nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue();
aMTOverlap.SetValue(nTmp);
}
else
{
aMTOverlap.Show(FALSE);
aFTOverlap.Show(FALSE);
}
if (rInAttrs.GetItemState(SCHATTR_BAR_CONNECT, TRUE, &pPoolItem) == SFX_ITEM_SET)
{
BOOL bCheck = static_cast< const SfxBoolItem * >( pPoolItem )->GetValue();
aCBConnect.Check(bCheck);
}
else
{
aCBConnect.Show(FALSE);
}
if (rInAttrs.GetItemState(SCHATTR_AXIS_FOR_ALL_SERIES, TRUE, &pPoolItem) == SFX_ITEM_SET)
{
m_nAllSeriesAxisIndex = static_cast< const SfxInt32Item * >( pPoolItem )->GetValue();
aCBAxisSideBySide.Disable();
}
if (rInAttrs.GetItemState(SCHATTR_GROUP_BARS_PER_AXIS, TRUE, &pPoolItem) == SFX_ITEM_SET)
{
// model property is "group bars per axis", UI feature is the other way
// round: "show bars side by side"
BOOL bCheck = ! static_cast< const SfxBoolItem * >( pPoolItem )->GetValue();
aCBAxisSideBySide.Check( bCheck );
}
else
{
aCBAxisSideBySide.Show(FALSE);
}
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS chart22 (1.9.46); FILE MERGED 2008/04/17 11:29:35 iha 1.9.46.2: RESYNC: (1.9-1.10); FILE MERGED 2008/02/21 17:13:32 iha 1.9.46.1: #i65549# Plotting of missing values + cleanuo<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: tp_SeriesToAxis.cxx,v $
* $Revision: 1.11 $
*
* 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_chart2.hxx"
#include "tp_SeriesToAxis.hxx"
#include "ResId.hxx"
#include "TabPages.hrc"
#include "chartview/ChartSfxItemIds.hxx"
#include "NoWarningThisInCTOR.hxx"
// header for class SfxBoolItem
#include <svtools/eitem.hxx>
// header for SfxInt32Item
#include <svtools/intitem.hxx>
//SfxIntegerListItem
#include <svtools/ilstitem.hxx>
#include <com/sun/star/chart/MissingValueTreatment.hpp>
//.............................................................................
namespace chart
{
//.............................................................................
SchOptionTabPage::SchOptionTabPage(Window* pWindow,const SfxItemSet& rInAttrs) :
SfxTabPage(pWindow, SchResId(TP_OPTIONS), rInAttrs),
aGrpAxis(this, SchResId(GRP_OPT_AXIS)),
aRbtAxis1(this,SchResId(RBT_OPT_AXIS_1)),
aRbtAxis2(this,SchResId(RBT_OPT_AXIS_2)),
aGrpBar(this, SchResId(GB_BAR)),
aFTGap(this,SchResId(FT_GAP)),
aMTGap(this,SchResId(MT_GAP)),
aFTOverlap(this,SchResId(FT_OVERLAP)),
aMTOverlap(this,SchResId(MT_OVERLAP)),
aCBConnect(this,SchResId(CB_CONNECTOR)),
aCBAxisSideBySide(this,SchResId(CB_BARS_SIDE_BY_SIDE)),
m_aFL_EmptyCells(this,SchResId(FL_PLOT_MISSING_VALUES)),
m_aRB_DontPaint(this,SchResId(RB_DONT_PAINT)),
m_aRB_AssumeZero(this,SchResId(RB_ASSUME_ZERO)),
m_aRB_ContinueLine(this,SchResId(RB_CONTINUE_LINE)),
m_bProvidesSecondaryYAxis(true),
m_bProvidesOverlapAndGapWidth(false)
{
FreeResource();
aRbtAxis1.SetClickHdl( LINK( this, SchOptionTabPage, EnableHdl ));
aRbtAxis2.SetClickHdl( LINK( this, SchOptionTabPage, EnableHdl ));
}
SchOptionTabPage::~SchOptionTabPage()
{
}
IMPL_LINK( SchOptionTabPage, EnableHdl, RadioButton *, EMPTYARG )
{
if( m_nAllSeriesAxisIndex == 0 )
aCBAxisSideBySide.Enable( aRbtAxis2.IsChecked());
else if( m_nAllSeriesAxisIndex == 1 )
aCBAxisSideBySide.Enable( aRbtAxis1.IsChecked());
return 0;
}
SfxTabPage* SchOptionTabPage::Create(Window* pWindow,const SfxItemSet& rOutAttrs)
{
return new SchOptionTabPage(pWindow, rOutAttrs);
}
BOOL SchOptionTabPage::FillItemSet(SfxItemSet& rOutAttrs)
{
if(aRbtAxis2.IsChecked())
rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_SECONDARY_Y));
else
rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_PRIMARY_Y));
if(aMTGap.IsVisible())
rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_GAPWIDTH,static_cast< sal_Int32 >( aMTGap.GetValue())));
if(aMTOverlap.IsVisible())
rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_OVERLAP,static_cast< sal_Int32 >( aMTOverlap.GetValue())));
if(aCBConnect.IsVisible())
rOutAttrs.Put(SfxBoolItem(SCHATTR_BAR_CONNECT,aCBConnect.IsChecked()));
// model property is "group bars per axis", UI feature is the other way
// round: "show bars side by side"
if(aCBAxisSideBySide.IsVisible())
rOutAttrs.Put(SfxBoolItem(SCHATTR_GROUP_BARS_PER_AXIS, ! aCBAxisSideBySide.IsChecked()));
if(m_aRB_DontPaint.IsChecked())
rOutAttrs.Put(SfxInt32Item(SCHATTR_MISSING_VALUE_TREATMENT,::com::sun::star::chart::MissingValueTreatment::LEAVE_GAP));
else if(m_aRB_AssumeZero.IsChecked())
rOutAttrs.Put(SfxInt32Item(SCHATTR_MISSING_VALUE_TREATMENT,::com::sun::star::chart::MissingValueTreatment::USE_ZERO));
else if(m_aRB_ContinueLine.IsChecked())
rOutAttrs.Put(SfxInt32Item(SCHATTR_MISSING_VALUE_TREATMENT,::com::sun::star::chart::MissingValueTreatment::CONTINUE));
return TRUE;
}
void SchOptionTabPage::Reset(const SfxItemSet& rInAttrs)
{
const SfxPoolItem *pPoolItem = NULL;
aRbtAxis1.Check(TRUE);
aRbtAxis2.Check(FALSE);
if (rInAttrs.GetItemState(SCHATTR_AXIS,TRUE, &pPoolItem) == SFX_ITEM_SET)
{
long nVal=((const SfxInt32Item*)pPoolItem)->GetValue();
if(nVal==CHART_AXIS_SECONDARY_Y)
{
aRbtAxis2.Check(TRUE);
aRbtAxis1.Check(FALSE);
}
}
long nTmp;
if (rInAttrs.GetItemState(SCHATTR_BAR_GAPWIDTH, TRUE, &pPoolItem) == SFX_ITEM_SET)
{
nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue();
aMTGap.SetValue(nTmp);
}
if (rInAttrs.GetItemState(SCHATTR_BAR_OVERLAP, TRUE, &pPoolItem) == SFX_ITEM_SET)
{
nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue();
aMTOverlap.SetValue(nTmp);
}
if (rInAttrs.GetItemState(SCHATTR_BAR_CONNECT, TRUE, &pPoolItem) == SFX_ITEM_SET)
{
BOOL bCheck = static_cast< const SfxBoolItem * >( pPoolItem )->GetValue();
aCBConnect.Check(bCheck);
}
if (rInAttrs.GetItemState(SCHATTR_AXIS_FOR_ALL_SERIES, TRUE, &pPoolItem) == SFX_ITEM_SET)
{
m_nAllSeriesAxisIndex = static_cast< const SfxInt32Item * >( pPoolItem )->GetValue();
aCBAxisSideBySide.Disable();
}
if (rInAttrs.GetItemState(SCHATTR_GROUP_BARS_PER_AXIS, TRUE, &pPoolItem) == SFX_ITEM_SET)
{
// model property is "group bars per axis", UI feature is the other way
// round: "show bars side by side"
BOOL bCheck = ! static_cast< const SfxBoolItem * >( pPoolItem )->GetValue();
aCBAxisSideBySide.Check( bCheck );
}
else
{
aCBAxisSideBySide.Show(FALSE);
}
//missing value treatment
{
::com::sun::star::uno::Sequence < sal_Int32 > aMissingValueTreatments;
if( rInAttrs.GetItemState(SCHATTR_AVAILABLE_MISSING_VALUE_TREATMENTS, TRUE, &pPoolItem) == SFX_ITEM_SET )
aMissingValueTreatments =((const SfxIntegerListItem*)pPoolItem)->GetConstSequence();
if ( aMissingValueTreatments.getLength()>1 && rInAttrs.GetItemState(SCHATTR_MISSING_VALUE_TREATMENT,TRUE, &pPoolItem) == SFX_ITEM_SET)
{
m_aRB_DontPaint.Enable(FALSE);
m_aRB_AssumeZero.Enable(FALSE);
m_aRB_ContinueLine.Enable(FALSE);
for( sal_Int32 nN =0; nN<aMissingValueTreatments.getLength(); nN++ )
{
sal_Int32 nVal = aMissingValueTreatments[nN];
if(nVal==::com::sun::star::chart::MissingValueTreatment::LEAVE_GAP)
m_aRB_DontPaint.Enable(TRUE);
else if(nVal==::com::sun::star::chart::MissingValueTreatment::USE_ZERO)
m_aRB_AssumeZero.Enable(TRUE);
else if(nVal==::com::sun::star::chart::MissingValueTreatment::CONTINUE)
m_aRB_ContinueLine.Enable(TRUE);
}
long nVal=((const SfxInt32Item*)pPoolItem)->GetValue();
if(nVal==::com::sun::star::chart::MissingValueTreatment::LEAVE_GAP)
m_aRB_DontPaint.Check(TRUE);
else if(nVal==::com::sun::star::chart::MissingValueTreatment::USE_ZERO)
m_aRB_AssumeZero.Check(TRUE);
else if(nVal==::com::sun::star::chart::MissingValueTreatment::CONTINUE)
m_aRB_ContinueLine.Check(TRUE);
}
else
{
m_aRB_DontPaint.Show(FALSE);
m_aRB_AssumeZero.Show(FALSE);
m_aRB_ContinueLine.Show(FALSE);
m_aFL_EmptyCells.Show(FALSE);
}
}
AdaptControlPositionsAndVisibility();
}
void SchOptionTabPage::Init( bool bProvidesSecondaryYAxis, bool bProvidesOverlapAndGapWidth, bool bProvidesBarConnectors )
{
m_bProvidesSecondaryYAxis = bProvidesSecondaryYAxis;
m_bProvidesOverlapAndGapWidth = bProvidesOverlapAndGapWidth;
m_bProvidesBarConnectors = bProvidesBarConnectors;
AdaptControlPositionsAndVisibility();
}
void SchOptionTabPage::AdaptControlPositionsAndVisibility()
{
aRbtAxis1.Show(m_bProvidesSecondaryYAxis);
aRbtAxis2.Show(m_bProvidesSecondaryYAxis);
aGrpAxis.Show(m_bProvidesSecondaryYAxis);
aMTGap.Show(m_bProvidesOverlapAndGapWidth);
aFTGap.Show(m_bProvidesOverlapAndGapWidth);
aMTOverlap.Show(m_bProvidesOverlapAndGapWidth);
aFTOverlap.Show(m_bProvidesOverlapAndGapWidth);
aCBConnect.Show(m_bProvidesBarConnectors);
if( !aMTGap.IsVisible() && !aMTOverlap.IsVisible() )
{
aGrpBar.Show(FALSE);
Point aPos;
if( !aRbtAxis1.IsVisible() && !aRbtAxis2.IsVisible() )
aPos = aGrpAxis.GetPosPixel();
else
aPos = aGrpBar.GetPosPixel();
long nDiffX = aRbtAxis1.GetPosPixel().getX() - aGrpAxis.GetPosPixel().getX();
long nDiffY = aRbtAxis1.GetPosPixel().getY() - aGrpAxis.GetPosPixel().getY();
long nDiffY1 = aRbtAxis2.GetPosPixel().getY() - aRbtAxis1.GetPosPixel().getY();
m_aFL_EmptyCells.SetPosPixel( aPos );
m_aRB_DontPaint.SetPosPixel( Point( aPos.getX() + nDiffX, aPos.getY() + nDiffY ) );
m_aRB_AssumeZero.SetPosPixel( Point( aPos.getX() + nDiffX, aPos.getY() + nDiffY + nDiffY1 ) );
m_aRB_ContinueLine.SetPosPixel( Point( aPos.getX() + nDiffX, aPos.getY() + nDiffY + nDiffY1 * 2 ) );
}
if( !m_aRB_DontPaint.IsVisible() )
{
m_aRB_ContinueLine.SetPosPixel( m_aRB_AssumeZero.GetPosPixel() );
m_aRB_AssumeZero.SetPosPixel( m_aRB_DontPaint.GetPosPixel() );
}
}
//.............................................................................
} //namespace chart
//.............................................................................
<|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/status/status_area_button.h"
#include "grit/theme_resources.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/skbitmap_operations.h"
#include "views/border.h"
#include "views/view.h"
namespace chromeos {
// A 0.7 black to decorate status text. Same color is used for icon borders.
static const SkColor kStatusTextHaloColor = SkColorSetARGB(0xB3, 0, 0, 0);
////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton
StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
: MenuButton(NULL, std::wstring(), menu_delegate, false),
use_menu_button_paint_(false), active_(true) {
set_border(NULL);
// Use an offset that is top aligned with toolbar.
set_menu_offset(0, 2);
// Use a halo for status text as the icons.
SetTextHaloColor(kStatusTextHaloColor);
}
void StatusAreaButton::OnPaint(gfx::Canvas* canvas, bool for_drag) {
if (state() == BS_PUSHED) {
// Apply 10% white when pushed down.
canvas->FillRectInt(SkColorSetARGB(0x19, 0xFF, 0xFF, 0xFF),
0, 0, width(), height());
}
if (use_menu_button_paint_) {
views::MenuButton::Paint(canvas, for_drag);
} else {
DrawIcon(canvas);
OnPaintFocusBorder(canvas);
}
}
gfx::Size StatusAreaButton::GetPreferredSize() {
gfx::Insets insets = views::MenuButton::GetInsets();
gfx::Size prefsize(icon_width() + insets.width(),
icon_height() + insets.height());
// Adjusts size when use menu button paint.
if (use_menu_button_paint_) {
gfx::Size menu_button_size = views::MenuButton::GetPreferredSize();
prefsize.SetSize(
std::max(prefsize.width(), menu_button_size.width()),
std::max(prefsize.height(), menu_button_size.height())
);
// Shift 1-pixel down for odd number of pixels in vertical space.
if ((prefsize.height() - menu_button_size.height()) % 2) {
insets_.Set(insets.top() + 1, insets.left(),
insets.bottom(), insets.right());
}
}
// Add padding.
prefsize.Enlarge(2 * horizontal_padding(), 0);
return prefsize;
}
gfx::Insets StatusAreaButton::GetInsets() const {
return insets_;
}
void StatusAreaButton::SetText(const std::wstring& text) {
// TextButtons normally remember the max text size, so the button's preferred
// size will always be as large as the largest text ever put in it.
// We clear that max text size, so we can adjust the size to fit the text.
ClearMaxTextSize();
views::MenuButton::SetText(text);
}
void StatusAreaButton::DrawIcon(gfx::Canvas* canvas) {
canvas->DrawBitmapInt(icon(), horizontal_padding(), 0);
}
bool StatusAreaButton::Activate() {
if (active_) {
return views::MenuButton::Activate();
} else {
return true;
}
}
} // namespace chromeos
<commit_msg>Fix resizing behavior of the input method button in the chromeos status bar.<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/status/status_area_button.h"
#include "grit/theme_resources.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/skbitmap_operations.h"
#include "views/border.h"
#include "views/view.h"
namespace chromeos {
// A 0.7 black to decorate status text. Same color is used for icon borders.
static const SkColor kStatusTextHaloColor = SkColorSetARGB(0xB3, 0, 0, 0);
////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton
StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
: MenuButton(NULL, std::wstring(), menu_delegate, false),
use_menu_button_paint_(false), active_(true) {
set_border(NULL);
// Use an offset that is top aligned with toolbar.
set_menu_offset(0, 2);
// Use a halo for status text as the icons.
SetTextHaloColor(kStatusTextHaloColor);
}
void StatusAreaButton::OnPaint(gfx::Canvas* canvas, bool for_drag) {
if (state() == BS_PUSHED) {
// Apply 10% white when pushed down.
canvas->FillRectInt(SkColorSetARGB(0x19, 0xFF, 0xFF, 0xFF),
0, 0, width(), height());
}
if (use_menu_button_paint_) {
views::MenuButton::Paint(canvas, for_drag);
} else {
DrawIcon(canvas);
OnPaintFocusBorder(canvas);
}
}
gfx::Size StatusAreaButton::GetPreferredSize() {
gfx::Insets insets = views::MenuButton::GetInsets();
gfx::Size prefsize(icon_width() + insets.width(),
icon_height() + insets.height());
// Adjusts size when use menu button paint.
if (use_menu_button_paint_) {
gfx::Size menu_button_size = views::MenuButton::GetPreferredSize();
prefsize.SetSize(
std::max(prefsize.width(), menu_button_size.width()),
std::max(prefsize.height(), menu_button_size.height())
);
// Shift 1-pixel down for odd number of pixels in vertical space.
if ((prefsize.height() - menu_button_size.height()) % 2) {
insets_.Set(insets.top() + 1, insets.left(),
insets.bottom(), insets.right());
}
}
// Add padding.
prefsize.Enlarge(2 * horizontal_padding(), 0);
return prefsize;
}
gfx::Insets StatusAreaButton::GetInsets() const {
return insets_;
}
void StatusAreaButton::SetText(const std::wstring& text) {
// TextButtons normally remember the max text size, so the button's preferred
// size will always be as large as the largest text ever put in it.
// We clear that max text size, so we can adjust the size to fit the text.
// The order is important. ClearMaxTextSize sets the size to that of the
// current text, so it must be called after SetText.
views::MenuButton::SetText(text);
ClearMaxTextSize();
PreferredSizeChanged();
}
void StatusAreaButton::DrawIcon(gfx::Canvas* canvas) {
canvas->DrawBitmapInt(icon(), horizontal_padding(), 0);
}
bool StatusAreaButton::Activate() {
if (active_) {
return views::MenuButton::Activate();
} else {
return true;
}
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Johannes Zellner <webmaster@nebulon.de>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "volumepopup.h"
#include "pulseaudiodevice.h"
#include <qtxdg/xdgicon.h>
#include <QtGui/QSlider>
#include <QtGui/QToolButton>
#include <QtGui/QVBoxLayout>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
VolumePopup::VolumePopup(QWidget* parent):
QWidget(parent, Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::X11BypassWindowManagerHint),
m_pos(0,0),
m_anchor(Qt::TopLeftCorner)
{
m_volumeSlider = new QSlider(Qt::Vertical, this);
m_mixerButton = new QToolButton(this);
m_mixerButton->setIcon(XdgIcon::fromTheme(QStringList() << "kmix"));
QVBoxLayout *l = new QVBoxLayout(this);
l->setSpacing(0);
l->setMargin(0);
l->addWidget(m_volumeSlider, 0, Qt::AlignHCenter);
l->addWidget(m_mixerButton);
setLayout(new QVBoxLayout(this));
connect(m_mixerButton, SIGNAL(clicked()), this, SLOT(launchMixer()));
connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int)));
}
VolumePopup::~VolumePopup()
{
}
void VolumePopup::enterEvent(QEvent *event)
{
emit mouseEnter();
}
void VolumePopup::leaveEvent(QEvent *event)
{
emit mouseExit();
}
void VolumePopup::launchMixer()
{
qWarning("try to launch mixer.");
}
void VolumePopup::handleSliderValueChanged(int value)
{
if (!m_device)
return;
m_device->setVolume(value);
}
void VolumePopup::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
realign();
}
void VolumePopup::open(QPoint pos, Qt::Corner anchor)
{
m_pos = pos;
m_anchor = anchor;
realign();
show();
}
void VolumePopup::handleWheelEvent(QWheelEvent *event)
{
m_volumeSlider->event(reinterpret_cast<QEvent*>(event));
}
void VolumePopup::setDevice(PulseAudioDevice *device)
{
if (device == m_device)
return;
// disconnect old device
disconnect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int)));
disconnect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int)));
m_device = device;
connect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int)));
connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int)));
}
void VolumePopup::realign()
{
QRect rect;
rect.setSize(sizeHint());
switch (m_anchor)
{
case Qt::TopLeftCorner:
rect.moveTopLeft(m_pos);
break;
case Qt::TopRightCorner:
rect.moveTopRight(m_pos);
break;
case Qt::BottomLeftCorner:
rect.moveBottomLeft(m_pos);
break;
case Qt::BottomRightCorner:
rect.moveBottomRight(m_pos);
break;
}
QRect screen = QApplication::desktop()->availableGeometry(m_pos);
if (rect.right() > screen.right())
rect.moveRight(screen.right());
if (rect.bottom() > screen.bottom())
rect.moveBottom(screen.bottom());
move(rect.topLeft());
}
<commit_msg>panel-volume: Fix segfault<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Johannes Zellner <webmaster@nebulon.de>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "volumepopup.h"
#include "pulseaudiodevice.h"
#include <qtxdg/xdgicon.h>
#include <QtGui/QSlider>
#include <QtGui/QToolButton>
#include <QtGui/QVBoxLayout>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
VolumePopup::VolumePopup(QWidget* parent):
QWidget(parent, Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::X11BypassWindowManagerHint),
m_pos(0,0),
m_anchor(Qt::TopLeftCorner),
m_device(0)
{
m_volumeSlider = new QSlider(Qt::Vertical, this);
m_mixerButton = new QToolButton(this);
m_mixerButton->setIcon(XdgIcon::fromTheme(QStringList() << "kmix"));
QVBoxLayout *l = new QVBoxLayout(this);
l->setSpacing(0);
l->setMargin(0);
l->addWidget(m_volumeSlider, 0, Qt::AlignHCenter);
l->addWidget(m_mixerButton);
setLayout(new QVBoxLayout(this));
connect(m_mixerButton, SIGNAL(clicked()), this, SLOT(launchMixer()));
connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int)));
}
VolumePopup::~VolumePopup()
{
}
void VolumePopup::enterEvent(QEvent *event)
{
emit mouseEnter();
}
void VolumePopup::leaveEvent(QEvent *event)
{
emit mouseExit();
}
void VolumePopup::launchMixer()
{
qWarning("try to launch mixer.");
}
void VolumePopup::handleSliderValueChanged(int value)
{
if (!m_device)
return;
m_device->setVolume(value);
}
void VolumePopup::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
realign();
}
void VolumePopup::open(QPoint pos, Qt::Corner anchor)
{
m_pos = pos;
m_anchor = anchor;
realign();
show();
}
void VolumePopup::handleWheelEvent(QWheelEvent *event)
{
m_volumeSlider->event(reinterpret_cast<QEvent*>(event));
}
void VolumePopup::setDevice(PulseAudioDevice *device)
{
if (device == m_device)
return;
// disconnect old device
if (m_device) {
disconnect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int)));
disconnect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int)));
}
m_device = device;
connect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int)));
connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int)));
}
void VolumePopup::realign()
{
QRect rect;
rect.setSize(sizeHint());
switch (m_anchor)
{
case Qt::TopLeftCorner:
rect.moveTopLeft(m_pos);
break;
case Qt::TopRightCorner:
rect.moveTopRight(m_pos);
break;
case Qt::BottomLeftCorner:
rect.moveBottomLeft(m_pos);
break;
case Qt::BottomRightCorner:
rect.moveBottomRight(m_pos);
break;
}
QRect screen = QApplication::desktop()->availableGeometry(m_pos);
if (rect.right() > screen.right())
rect.moveRight(screen.right());
if (rect.bottom() > screen.bottom())
rect.moveBottom(screen.bottom());
move(rect.topLeft());
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2000-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.
*/
///
/// @file sim/main.cc
///
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <signal.h>
#include <list>
#include <string>
#include <vector>
#include "base/copyright.hh"
#include "base/embedfile.hh"
#include "base/inifile.hh"
#include "base/misc.hh"
#include "base/pollevent.hh"
#include "base/statistics.hh"
#include "base/str.hh"
#include "base/time.hh"
#include "cpu/base_cpu.hh"
#include "cpu/full_cpu/smt.hh"
#include "sim/async.hh"
#include "sim/builder.hh"
#include "sim/configfile.hh"
#include "sim/host.hh"
#include "sim/sim_events.hh"
#include "sim/sim_exit.hh"
#include "sim/sim_object.hh"
#include "sim/stat_control.hh"
#include "sim/stats.hh"
#include "sim/universe.hh"
#include "sim/pyconfig/pyconfig.hh"
using namespace std;
// See async.h.
volatile bool async_event = false;
volatile bool async_dump = false;
volatile bool async_dumpreset = false;
volatile bool async_exit = false;
volatile bool async_io = false;
volatile bool async_alarm = false;
/// Stats signal handler.
void
dumpStatsHandler(int sigtype)
{
async_event = true;
async_dump = true;
}
void
dumprstStatsHandler(int sigtype)
{
async_event = true;
async_dumpreset = true;
}
/// Exit signal handler.
void
exitNowHandler(int sigtype)
{
async_event = true;
async_exit = true;
}
/// Abort signal handler.
void
abortHandler(int sigtype)
{
cerr << "Program aborted at cycle " << curTick << endl;
#if TRACING_ON
// dump trace buffer, if there is one
Trace::theLog.dump(cerr);
#endif
}
/// Simulator executable name
const char *myProgName = "";
/// Show brief help message.
static void
showBriefHelp(ostream &out)
{
out << "Usage: " << myProgName
<< " [-hnu] [-Dname[=def]] [-Uname] [-I[dir]] "
<< "<config-spec> [<config-spec> ...]\n"
<< "[] [<config file> ...]\n"
<< " -h: print long help (including parameter listing)\n"
<< " -u: don't quit on unreferenced parameters\n"
<< " -D,-U,-I: passed to cpp for preprocessing .ini files\n"
<< " <config-spec>: config file name (.ini or .py) or\n"
<< " single param (--<section>:<param>=<value>)"
<< endl;
}
/// Show verbose help message. Includes parameter listing from
/// showBriefHelp(), plus an exhaustive list of ini-file parameters
/// and SimObjects (with their parameters).
static void
showLongHelp(ostream &out)
{
showBriefHelp(out);
out << endl
<< endl
<< "-----------------" << endl
<< "Global Parameters" << endl
<< "-----------------" << endl
<< endl;
ParamContext::describeAllContexts(out);
out << endl
<< endl
<< "-----------------" << endl
<< "Simulator Objects" << endl
<< "-----------------" << endl
<< endl;
SimObjectClass::describeAllClasses(out);
}
/// Print welcome message.
static void
sayHello(ostream &out)
{
extern const char *compileDate; // from date.cc
ccprintf(out, "M5 Simulator System\n");
// display copyright
ccprintf(out, "%s\n", briefCopyright);
ccprintf(out, "M5 compiled on %d\n", compileDate);
char *host = getenv("HOSTNAME");
if (!host)
host = getenv("HOST");
if (host)
ccprintf(out, "M5 executing on %s\n", host);
ccprintf(out, "M5 simulation started %s\n", Time::start);
}
///
/// Echo the command line for posterity in such a way that it can be
/// used to rerun the same simulation (given the same .ini files).
///
static void
echoCommandLine(int argc, char **argv, ostream &out)
{
out << "command line: " << argv[0];
for (int i = 1; i < argc; i++) {
string arg(argv[i]);
out << ' ';
// If the arg contains spaces, we need to quote it.
// The rest of this is overkill to make it look purty.
// print dashes first outside quotes
int non_dash_pos = arg.find_first_not_of("-");
out << arg.substr(0, non_dash_pos); // print dashes
string body = arg.substr(non_dash_pos); // the rest
// if it's an assignment, handle the lhs & rhs separately
int eq_pos = body.find("=");
if (eq_pos == string::npos) {
out << quote(body);
}
else {
string lhs(body.substr(0, eq_pos));
string rhs(body.substr(eq_pos + 1));
out << quote(lhs) << "=" << quote(rhs);
}
}
out << endl << endl;
}
///
/// The simulator configuration database. This is the union of all
/// specified .ini files. This shouldn't need to be visible outside
/// this file, as it is passed as a parameter to all the param-parsing
/// routines.
///
static IniFile simConfigDB;
/// M5 entry point.
int
main(int argc, char **argv)
{
// Save off program name
myProgName = argv[0];
signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths
signal(SIGTRAP, SIG_IGN);
signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats
signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats
signal(SIGINT, exitNowHandler); // dump final stats and exit
signal(SIGABRT, abortHandler);
sayHello(cerr);
// Initialize statistics database
Stats::InitSimStats();
vector<char *> cppArgs;
// Should we quit if there are unreferenced parameters? By
// default, yes... it's a good way of catching typos in
// section/parameter names (which otherwise go by silently). Use
// -u to override.
bool quitOnUnreferenced = true;
bool python_initialized = false;
// Parse command-line options.
// Since most of the complex options are handled through the
// config database, we don't mess with getopts, and just parse
// manually.
for (int i = 1; i < argc; ++i) {
char *arg_str = argv[i];
// if arg starts with '-', parse as option,
// else treat it as a configuration file name and load it
if (arg_str[0] == '-') {
// switch on second char
switch (arg_str[1]) {
case 'X': {
list<EmbedFile> lst;
EmbedMap::all(lst);
list<EmbedFile>::iterator i = lst.begin();
list<EmbedFile>::iterator end = lst.end();
while (i != end) {
cprintf("Embedded File: %s\n", i->name);
cout.write(i->data, i->length);
++i;
}
return 0;
}
case 'h':
// -h: show help
showLongHelp(cerr);
exit(1);
case 'u':
// -u: don't quit on unreferenced parameters
quitOnUnreferenced = false;
break;
case 'D':
case 'U':
// cpp options: record & pass to cpp. Note that these
// cannot have spaces, i.e., '-Dname=val' is OK, but
// '-D name=val' is not. I don't consider this a
// problem, since even though gnu cpp accepts the
// latter, other cpp implementations do not (Tru64,
// for one).
cppArgs.push_back(arg_str);
break;
case 'I': {
// We push -I as an argument to cpp
cppArgs.push_back(arg_str);
string arg = arg_str + 2;
eat_white(arg);
// Send this as the python path
addPythonPath(arg);
} break;
case 'P':
if (!python_initialized) {
initPythonConfig();
python_initialized = true;
}
writePythonString(arg_str + 2);
writePythonString("\n");
case 'E':
if (putenv(arg_str + 2) == -1)
panic("putenv: %s\n", strerror(errno));
break;
case '-':
// command-line configuration parameter:
// '--<section>:<parameter>=<value>'
if (!simConfigDB.add(arg_str + 2)) {
// parse error
ccprintf(cerr,
"Could not parse configuration argument '%s'\n"
"Expecting --<section>:<parameter>=<value>\n",
arg_str);
exit(0);
}
break;
default:
showBriefHelp(cerr);
ccprintf(cerr, "Fatal: invalid argument '%s'\n", arg_str);
exit(0);
}
}
else {
// no '-', treat as config file name
// make STL string out of file name
string filename(arg_str);
int ext_loc = filename.rfind(".");
string ext =
(ext_loc != string::npos) ? filename.substr(ext_loc) : "";
if (ext == ".ini") {
if (!simConfigDB.loadCPP(filename, cppArgs)) {
cprintf("Error processing file %s\n", filename);
exit(1);
}
} else if (ext == ".py" || ext == ".mpy") {
if (!python_initialized) {
initPythonConfig();
python_initialized = true;
}
loadPythonConfig(filename);
}
else {
cprintf("Config file name '%s' must end in '.py' or '.ini'.\n",
filename);
exit(1);
}
}
}
if (python_initialized && finishPythonConfig(simConfigDB)) {
cprintf("Error processing python code\n");
exit(1);
}
// The configuration database is now complete; start processing it.
// Parse and check all non-config-hierarchy parameters.
ParamContext::parseAllContexts(simConfigDB);
ParamContext::checkAllContexts();
// Print header info into stats file. Can't do this sooner since
// the stat file name is set via a .ini param... thus it just got
// opened above during ParamContext::checkAllContexts().
// Now process the configuration hierarchy and create the SimObjects.
ConfigHierarchy configHierarchy(simConfigDB);
configHierarchy.build();
configHierarchy.createSimObjects();
// Print hello message to stats file if it's actually a file. If
// it's not (i.e. it's cout or cerr) then we already did it above.
if (outputStream != &cout && outputStream != &cerr)
sayHello(*outputStream);
// Echo command line and all parameter settings to stats file as well.
echoCommandLine(argc, argv, *outputStream);
ParamContext::showAllContexts(*configStream);
// Do a second pass to finish initializing the sim objects
SimObject::initAll();
// Restore checkpointed state, if any.
configHierarchy.unserializeSimObjects();
// Done processing the configuration database.
// Check for unreferenced entries.
if (simConfigDB.printUnreferenced() && quitOnUnreferenced) {
cerr << "Fatal: unreferenced .ini sections/entries." << endl
<< "If this is not an error, add 'unref_section_ok=y' or "
<< "'unref_entries_ok=y' to the appropriate sections "
<< "to suppress this message." << endl;
exit(1);
}
SimObject::regAllStats();
// uncomment the following to get PC-based execution-time profile
#ifdef DO_PROFILE
init_profile((char *)&_init, (char *)&_fini);
#endif
// Check to make sure that the stats package is properly initialized
Stats::check();
// Reset to put the stats in a consistent state.
Stats::reset();
// Nothing to simulate if we don't have at least one CPU somewhere.
if (BaseCPU::numSimulatedCPUs() == 0) {
cerr << "Fatal: no CPUs to simulate." << endl;
exit(1);
}
warn("Entering event queue. Starting simulation...\n");
SimStartup();
while (!mainEventQueue.empty()) {
assert(curTick <= mainEventQueue.nextTick() &&
"event scheduled in the past");
// forward current cycle to the time of the first event on the
// queue
curTick = mainEventQueue.nextTick();
mainEventQueue.serviceOne();
if (async_event) {
async_event = false;
if (async_dump) {
async_dump = false;
using namespace Stats;
SetupEvent(Dump, curTick);
}
if (async_dumpreset) {
async_dumpreset = false;
using namespace Stats;
SetupEvent(Dump | Reset, curTick);
}
if (async_exit) {
async_exit = false;
new SimExitEvent("User requested STOP");
}
if (async_io || async_alarm) {
async_io = false;
async_alarm = false;
pollQueue.service();
}
}
}
// This should never happen... every conceivable way for the
// simulation to terminate (hit max cycles/insts, signal,
// simulated system halts/exits) generates an exit event, so we
// should never run out of events on the queue.
exitNow("no events on event loop! All CPUs must be idle.", 1);
return 0;
}
<commit_msg>get the exit condition for the python code right<commit_after>/*
* Copyright (c) 2000-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.
*/
///
/// @file sim/main.cc
///
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <signal.h>
#include <list>
#include <string>
#include <vector>
#include "base/copyright.hh"
#include "base/embedfile.hh"
#include "base/inifile.hh"
#include "base/misc.hh"
#include "base/pollevent.hh"
#include "base/statistics.hh"
#include "base/str.hh"
#include "base/time.hh"
#include "cpu/base_cpu.hh"
#include "cpu/full_cpu/smt.hh"
#include "sim/async.hh"
#include "sim/builder.hh"
#include "sim/configfile.hh"
#include "sim/host.hh"
#include "sim/sim_events.hh"
#include "sim/sim_exit.hh"
#include "sim/sim_object.hh"
#include "sim/stat_control.hh"
#include "sim/stats.hh"
#include "sim/universe.hh"
#include "sim/pyconfig/pyconfig.hh"
using namespace std;
// See async.h.
volatile bool async_event = false;
volatile bool async_dump = false;
volatile bool async_dumpreset = false;
volatile bool async_exit = false;
volatile bool async_io = false;
volatile bool async_alarm = false;
/// Stats signal handler.
void
dumpStatsHandler(int sigtype)
{
async_event = true;
async_dump = true;
}
void
dumprstStatsHandler(int sigtype)
{
async_event = true;
async_dumpreset = true;
}
/// Exit signal handler.
void
exitNowHandler(int sigtype)
{
async_event = true;
async_exit = true;
}
/// Abort signal handler.
void
abortHandler(int sigtype)
{
cerr << "Program aborted at cycle " << curTick << endl;
#if TRACING_ON
// dump trace buffer, if there is one
Trace::theLog.dump(cerr);
#endif
}
/// Simulator executable name
const char *myProgName = "";
/// Show brief help message.
static void
showBriefHelp(ostream &out)
{
out << "Usage: " << myProgName
<< " [-hnu] [-Dname[=def]] [-Uname] [-I[dir]] "
<< "<config-spec> [<config-spec> ...]\n"
<< "[] [<config file> ...]\n"
<< " -h: print long help (including parameter listing)\n"
<< " -u: don't quit on unreferenced parameters\n"
<< " -D,-U,-I: passed to cpp for preprocessing .ini files\n"
<< " <config-spec>: config file name (.ini or .py) or\n"
<< " single param (--<section>:<param>=<value>)"
<< endl;
}
/// Show verbose help message. Includes parameter listing from
/// showBriefHelp(), plus an exhaustive list of ini-file parameters
/// and SimObjects (with their parameters).
static void
showLongHelp(ostream &out)
{
showBriefHelp(out);
out << endl
<< endl
<< "-----------------" << endl
<< "Global Parameters" << endl
<< "-----------------" << endl
<< endl;
ParamContext::describeAllContexts(out);
out << endl
<< endl
<< "-----------------" << endl
<< "Simulator Objects" << endl
<< "-----------------" << endl
<< endl;
SimObjectClass::describeAllClasses(out);
}
/// Print welcome message.
static void
sayHello(ostream &out)
{
extern const char *compileDate; // from date.cc
ccprintf(out, "M5 Simulator System\n");
// display copyright
ccprintf(out, "%s\n", briefCopyright);
ccprintf(out, "M5 compiled on %d\n", compileDate);
char *host = getenv("HOSTNAME");
if (!host)
host = getenv("HOST");
if (host)
ccprintf(out, "M5 executing on %s\n", host);
ccprintf(out, "M5 simulation started %s\n", Time::start);
}
///
/// Echo the command line for posterity in such a way that it can be
/// used to rerun the same simulation (given the same .ini files).
///
static void
echoCommandLine(int argc, char **argv, ostream &out)
{
out << "command line: " << argv[0];
for (int i = 1; i < argc; i++) {
string arg(argv[i]);
out << ' ';
// If the arg contains spaces, we need to quote it.
// The rest of this is overkill to make it look purty.
// print dashes first outside quotes
int non_dash_pos = arg.find_first_not_of("-");
out << arg.substr(0, non_dash_pos); // print dashes
string body = arg.substr(non_dash_pos); // the rest
// if it's an assignment, handle the lhs & rhs separately
int eq_pos = body.find("=");
if (eq_pos == string::npos) {
out << quote(body);
}
else {
string lhs(body.substr(0, eq_pos));
string rhs(body.substr(eq_pos + 1));
out << quote(lhs) << "=" << quote(rhs);
}
}
out << endl << endl;
}
///
/// The simulator configuration database. This is the union of all
/// specified .ini files. This shouldn't need to be visible outside
/// this file, as it is passed as a parameter to all the param-parsing
/// routines.
///
static IniFile simConfigDB;
/// M5 entry point.
int
main(int argc, char **argv)
{
// Save off program name
myProgName = argv[0];
signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths
signal(SIGTRAP, SIG_IGN);
signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats
signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats
signal(SIGINT, exitNowHandler); // dump final stats and exit
signal(SIGABRT, abortHandler);
sayHello(cerr);
// Initialize statistics database
Stats::InitSimStats();
vector<char *> cppArgs;
// Should we quit if there are unreferenced parameters? By
// default, yes... it's a good way of catching typos in
// section/parameter names (which otherwise go by silently). Use
// -u to override.
bool quitOnUnreferenced = true;
bool python_initialized = false;
// Parse command-line options.
// Since most of the complex options are handled through the
// config database, we don't mess with getopts, and just parse
// manually.
for (int i = 1; i < argc; ++i) {
char *arg_str = argv[i];
// if arg starts with '-', parse as option,
// else treat it as a configuration file name and load it
if (arg_str[0] == '-') {
// switch on second char
switch (arg_str[1]) {
case 'X': {
list<EmbedFile> lst;
EmbedMap::all(lst);
list<EmbedFile>::iterator i = lst.begin();
list<EmbedFile>::iterator end = lst.end();
while (i != end) {
cprintf("Embedded File: %s\n", i->name);
cout.write(i->data, i->length);
++i;
}
return 0;
}
case 'h':
// -h: show help
showLongHelp(cerr);
exit(1);
case 'u':
// -u: don't quit on unreferenced parameters
quitOnUnreferenced = false;
break;
case 'D':
case 'U':
// cpp options: record & pass to cpp. Note that these
// cannot have spaces, i.e., '-Dname=val' is OK, but
// '-D name=val' is not. I don't consider this a
// problem, since even though gnu cpp accepts the
// latter, other cpp implementations do not (Tru64,
// for one).
cppArgs.push_back(arg_str);
break;
case 'I': {
// We push -I as an argument to cpp
cppArgs.push_back(arg_str);
string arg = arg_str + 2;
eat_white(arg);
// Send this as the python path
addPythonPath(arg);
} break;
case 'P':
if (!python_initialized) {
initPythonConfig();
python_initialized = true;
}
writePythonString(arg_str + 2);
writePythonString("\n");
case 'E':
if (putenv(arg_str + 2) == -1)
panic("putenv: %s\n", strerror(errno));
break;
case '-':
// command-line configuration parameter:
// '--<section>:<parameter>=<value>'
if (!simConfigDB.add(arg_str + 2)) {
// parse error
ccprintf(cerr,
"Could not parse configuration argument '%s'\n"
"Expecting --<section>:<parameter>=<value>\n",
arg_str);
exit(0);
}
break;
default:
showBriefHelp(cerr);
ccprintf(cerr, "Fatal: invalid argument '%s'\n", arg_str);
exit(0);
}
}
else {
// no '-', treat as config file name
// make STL string out of file name
string filename(arg_str);
int ext_loc = filename.rfind(".");
string ext =
(ext_loc != string::npos) ? filename.substr(ext_loc) : "";
if (ext == ".ini") {
if (!simConfigDB.loadCPP(filename, cppArgs)) {
cprintf("Error processing file %s\n", filename);
exit(1);
}
} else if (ext == ".py" || ext == ".mpy") {
if (!python_initialized) {
initPythonConfig();
python_initialized = true;
}
loadPythonConfig(filename);
}
else {
cprintf("Config file name '%s' must end in '.py' or '.ini'.\n",
filename);
exit(1);
}
}
}
if (python_initialized && !finishPythonConfig(simConfigDB)) {
cprintf("Error processing python code\n");
exit(1);
}
// The configuration database is now complete; start processing it.
// Parse and check all non-config-hierarchy parameters.
ParamContext::parseAllContexts(simConfigDB);
ParamContext::checkAllContexts();
// Print header info into stats file. Can't do this sooner since
// the stat file name is set via a .ini param... thus it just got
// opened above during ParamContext::checkAllContexts().
// Now process the configuration hierarchy and create the SimObjects.
ConfigHierarchy configHierarchy(simConfigDB);
configHierarchy.build();
configHierarchy.createSimObjects();
// Print hello message to stats file if it's actually a file. If
// it's not (i.e. it's cout or cerr) then we already did it above.
if (outputStream != &cout && outputStream != &cerr)
sayHello(*outputStream);
// Echo command line and all parameter settings to stats file as well.
echoCommandLine(argc, argv, *outputStream);
ParamContext::showAllContexts(*configStream);
// Do a second pass to finish initializing the sim objects
SimObject::initAll();
// Restore checkpointed state, if any.
configHierarchy.unserializeSimObjects();
// Done processing the configuration database.
// Check for unreferenced entries.
if (simConfigDB.printUnreferenced() && quitOnUnreferenced) {
cerr << "Fatal: unreferenced .ini sections/entries." << endl
<< "If this is not an error, add 'unref_section_ok=y' or "
<< "'unref_entries_ok=y' to the appropriate sections "
<< "to suppress this message." << endl;
exit(1);
}
SimObject::regAllStats();
// uncomment the following to get PC-based execution-time profile
#ifdef DO_PROFILE
init_profile((char *)&_init, (char *)&_fini);
#endif
// Check to make sure that the stats package is properly initialized
Stats::check();
// Reset to put the stats in a consistent state.
Stats::reset();
// Nothing to simulate if we don't have at least one CPU somewhere.
if (BaseCPU::numSimulatedCPUs() == 0) {
cerr << "Fatal: no CPUs to simulate." << endl;
exit(1);
}
warn("Entering event queue. Starting simulation...\n");
SimStartup();
while (!mainEventQueue.empty()) {
assert(curTick <= mainEventQueue.nextTick() &&
"event scheduled in the past");
// forward current cycle to the time of the first event on the
// queue
curTick = mainEventQueue.nextTick();
mainEventQueue.serviceOne();
if (async_event) {
async_event = false;
if (async_dump) {
async_dump = false;
using namespace Stats;
SetupEvent(Dump, curTick);
}
if (async_dumpreset) {
async_dumpreset = false;
using namespace Stats;
SetupEvent(Dump | Reset, curTick);
}
if (async_exit) {
async_exit = false;
new SimExitEvent("User requested STOP");
}
if (async_io || async_alarm) {
async_io = false;
async_alarm = false;
pollQueue.service();
}
}
}
// This should never happen... every conceivable way for the
// simulation to terminate (hit max cycles/insts, signal,
// simulated system halts/exits) generates an exit event, so we
// should never run out of events on the queue.
exitNow("no events on event loop! All CPUs must be idle.", 1);
return 0;
}
<|endoftext|>
|
<commit_before>#include "global_state_annotation.h"
namespace fish_annotator {
GlobalStateAnnotation::GlobalStateAnnotation(
std::map<std::string, bool> states)
: states_(states) {
}
GlobalStateAnnotation::GlobalStateAnnotation()
: states_() {
}
pt::ptree GlobalStateAnnotation::write() const {
pt::ptree arr;
for(auto state : states_) {
pt::ptree tree;
tree.put("state", state.first);
tree.put("value", state.second);
tree.put("type", "bool");
arr.push_back(std::make_pair("", tree));
}
return arr;
}
void GlobalStateAnnotation::read(const pt::ptree &tree) {
states_.clear();
for(auto val : tree) {
pt::ptree elem = val.second.get_child("");
states_.insert(std::pair<std::string, bool>(
elem.get<std::string>("state"),
elem.get<std::string>("value") == "true"));
}
}
std::string GlobalStateAnnotation::writeCsvHeader() {
std::string header;
for(auto state : states_) {
header += ",";
header += state.first;
}
return header;
}
std::string GlobalStateAnnotation::writeCsvValues() {
std::string values;
for (auto state : states_) {
values += ",";
values += state.second ? "1" : "0";
}
return values;
}
} // namespace fish_annotator
<commit_msg>Deserialize directly into bool<commit_after>#include "global_state_annotation.h"
namespace fish_annotator {
GlobalStateAnnotation::GlobalStateAnnotation(
std::map<std::string, bool> states)
: states_(states) {
}
GlobalStateAnnotation::GlobalStateAnnotation()
: states_() {
}
pt::ptree GlobalStateAnnotation::write() const {
pt::ptree arr;
for(auto state : states_) {
pt::ptree tree;
tree.put("state", state.first);
tree.put("value", state.second);
tree.put("type", "bool");
arr.push_back(std::make_pair("", tree));
}
return arr;
}
void GlobalStateAnnotation::read(const pt::ptree &tree) {
states_.clear();
for(auto val : tree) {
pt::ptree elem = val.second.get_child("");
states_.insert(std::pair<std::string, bool>(
elem.get<std::string>("state"),
elem.get<bool>("value")));
}
}
std::string GlobalStateAnnotation::writeCsvHeader() {
std::string header;
for(auto state : states_) {
header += ",";
header += state.first;
}
return header;
}
std::string GlobalStateAnnotation::writeCsvValues() {
std::string values;
for (auto state : states_) {
values += ",";
values += state.second ? "1" : "0";
}
return values;
}
} // namespace fish_annotator
<|endoftext|>
|
<commit_before>// include google test
#include <gtest/gtest.h>
// include files to test
#include <common/PackedString.hpp>
#include <common/alphabets.hpp>
#include <common/AlphabetTraits.hpp>
class PackingTest : public ::testing::Test
{
public:
std::vector<std::string> dna_seqs = {"", "A", "T", "C", "AC", "AAAAAAAA",
"TTTTTT", "GG", "CACACACA", "ACTGGGCCATAATCTCTCATGGATGCTACGAGCTGATCGTAGCTGACTAGTCGA"};
};
TEST_F(PackingTest, TestPackedString1) {
for (std::string dna : dna_seqs)
{
// first step: translate (in place)
AlphabetTraits<DNA>::translateFromAscii(dna.begin(), dna.end(), dna.begin());
// check that every letter's value is smaller than the total alphabet size
for (char c : dna)
{
EXPECT_LT(static_cast<unsigned int>(c), AlphabetTraits<DNA>::getSize()) << "The value of the translated chars must be smaller than the size of the alphabet";
}
// then pack it
PackedString<DNA> packedStr(dna);
ASSERT_EQ(packedStr.size(), dna.size()) << "The packed sequence should be of same length as the original string.";
// unpack it
std::vector<DNA> unpacked_dna(packedStr.size());
packedStr.unpackSequence(unpacked_dna.begin());
// compare the vector and the given string
for (unsigned int i = 0; i < dna.size(); ++i)
{
EXPECT_EQ(dna[i], unpacked_dna[i]) << "The unpacked char was not the same as the original char.";
}
}
}
TEST_F(PackingTest, TestPackedString2) {
for (std::string dna : dna_seqs)
{
// translate into different container
std::vector<char> dna_vec(dna.size());
AlphabetTraits<DNA>::translateFromAscii(dna.begin(), dna.end(), dna_vec.begin());
// check that every letter's value is smaller than the total alphabet size
for (char c : dna_vec)
{
EXPECT_LT(static_cast<unsigned int>(c), AlphabetTraits<DNA>::getSize()) << "The value of the translated chars must be smaller than the size of the alphabet";
}
// then pack it
PackedString<DNA> packedStr(dna_vec.begin(), dna_vec.end());
ASSERT_EQ(packedStr.size(), dna.size()) << "The packed sequence should be of same length as the original string.";
ASSERT_EQ(packedStr.size(), dna_vec.size()) << "The packed sequence should be of same length as the original string.";
// unpack it
std::string unpacked_dna(packedStr.size(),'X');
packedStr.unpackSequence(unpacked_dna.begin());
// translate back to ASCII (in place)
AlphabetTraits<DNA>::translateToAscii(unpacked_dna.begin(), unpacked_dna.end(), unpacked_dna.begin());
// compare the vector and the given string
for (unsigned int i = 0; i < dna.size(); ++i)
{
EXPECT_EQ(dna[i], unpacked_dna[i]) << "The unpacked char was not the same as the original char.";
}
}
}<commit_msg>even more testing<commit_after>// include google test
#include <gtest/gtest.h>
// include files to test
#include <common/PackedString.hpp>
#include <common/alphabets.hpp>
#include <common/AlphabetTraits.hpp>
class PackingTest : public ::testing::Test
{
public:
std::vector<std::string> dna_seqs = {"", "A", "T", "C", "AC", "AAAAAAAA",
"TTTTTT", "GG", "CACACACA", "ACTGGGCCATAATCTCTCATGGATGCTACGAGCTGATCGTAGCTGACTAGTCGA",
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACTCTGCTCGTGATCGATCGATCGATCGATCGATCGACTAGCTAGCTACGTACGTACGTACGATCGATCGTACGATCGATCGATCGATCGATCGTACGTACGTACGTCAGCTAGCTCGATCGATATGCTAGATACACACACTACATACTCACATACACATCAACTCATACTTCATCAGACGATCGATCGATCTCGCTGATCGACTGTCGATCGTCGATCGTAGCTCGTAGCTCGTAGCTCG"
};
};
TEST_F(PackingTest, TestPackedString1) {
for (std::string dna : dna_seqs)
{
// first step: translate (in place)
AlphabetTraits<DNA>::translateFromAscii(dna.begin(), dna.end(), dna.begin());
// check that every letter's value is smaller than the total alphabet size
for (char c : dna)
{
EXPECT_LT(static_cast<unsigned int>(c), AlphabetTraits<DNA>::getSize()) << "The value of the translated chars must be smaller than the size of the alphabet";
}
// then pack it
PackedString<DNA> packedStr(dna);
ASSERT_EQ(packedStr.size(), dna.size()) << "The packed sequence should be of same length as the original string.";
// unpack it
std::vector<DNA> unpacked_dna(packedStr.size());
packedStr.unpackSequence(unpacked_dna.begin());
// compare the vector and the given string
for (unsigned int i = 0; i < dna.size(); ++i)
{
EXPECT_EQ(dna[i], unpacked_dna[i]) << "The unpacked char was not the same as the original char.";
}
}
}
TEST_F(PackingTest, TestPackedString2) {
for (std::string dna : dna_seqs)
{
// translate into different container
std::vector<char> dna_vec(dna.size());
AlphabetTraits<DNA>::translateFromAscii(dna.begin(), dna.end(), dna_vec.begin());
// check that every letter's value is smaller than the total alphabet size
for (char c : dna_vec)
{
EXPECT_LT(static_cast<unsigned int>(c), AlphabetTraits<DNA>::getSize()) << "The value of the translated chars must be smaller than the size of the alphabet";
}
// then pack it
PackedString<DNA> packedStr(dna_vec.begin(), dna_vec.end());
ASSERT_EQ(packedStr.size(), dna.size()) << "The packed sequence should be of same length as the original string.";
ASSERT_EQ(packedStr.size(), dna_vec.size()) << "The packed sequence should be of same length as the original string.";
// unpack it into a basic_string<DNA> container
std::basic_string<DNA> unpacked_dna(packedStr.size(),'X');
packedStr.unpackSequence(unpacked_dna.begin());
// compare the values using the [] operator
for (unsigned int i = 0; i < packedStr.size(); ++i)
{
EXPECT_EQ(packedStr[i], unpacked_dna[i]) << "packed and unpacked strings have to compare equal";
}
// translate back to ASCII (in place)
AlphabetTraits<DNA>::translateToAscii(unpacked_dna.begin(), unpacked_dna.end(), unpacked_dna.begin());
// compare the vector and the given string
for (unsigned int i = 0; i < dna.size(); ++i)
{
EXPECT_EQ(dna[i], unpacked_dna[i]) << "The unpacked char was not the same as the original char.";
}
}
}<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <map>
#include <sstream>
#include "src/compiler/config.h"
#include "src/compiler/objective_c_generator.h"
#include "src/compiler/objective_c_generator_helpers.h"
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
using ::google::protobuf::compiler::objectivec::ClassName;
using ::grpc::protobuf::io::Printer;
using ::grpc::protobuf::MethodDescriptor;
using ::grpc::protobuf::ServiceDescriptor;
using ::std::map;
namespace grpc_objective_c_generator {
namespace {
void PrintProtoRpcDeclarationAsPragma(Printer *printer,
const MethodDescriptor *method,
map< ::grpc::string, ::grpc::string> vars) {
vars["client_stream"] = method->client_streaming() ? "stream " : "";
vars["server_stream"] = method->server_streaming() ? "stream " : "";
printer->Print(vars,
"#pragma mark $method_name$($client_stream$$request_type$)"
" returns ($server_stream$$response_type$)\n\n");
}
void PrintMethodSignature(Printer *printer, const MethodDescriptor *method,
const map< ::grpc::string, ::grpc::string> &vars) {
// TODO(jcanizales): Print method comments.
printer->Print(vars, "- ($return_type$)$method_name$With");
if (method->client_streaming()) {
printer->Print("RequestsWriter:(GRXWriter *)requestWriter");
} else {
printer->Print(vars, "Request:($request_class$ *)request");
}
// TODO(jcanizales): Put this on a new line and align colons.
if (method->server_streaming()) {
printer->Print(vars,
" eventHandler:(void(^)(BOOL done, "
"$response_class$ *_Nullable response, NSError *_Nullable error))eventHandler");
} else {
printer->Print(vars,
" handler:(void(^)($response_class$ *_Nullable response, "
"NSError *_Nullable error))handler");
}
}
void PrintSimpleSignature(Printer *printer, const MethodDescriptor *method,
map< ::grpc::string, ::grpc::string> vars) {
vars["method_name"] =
grpc_generator::LowercaseFirstLetter(vars["method_name"]);
vars["return_type"] = "void";
PrintMethodSignature(printer, method, vars);
}
void PrintAdvancedSignature(Printer *printer, const MethodDescriptor *method,
map< ::grpc::string, ::grpc::string> vars) {
vars["method_name"] = "RPCTo" + vars["method_name"];
vars["return_type"] = "GRPCProtoCall *";
PrintMethodSignature(printer, method, vars);
}
inline map< ::grpc::string, ::grpc::string> GetMethodVars(const MethodDescriptor *method) {
map< ::grpc::string, ::grpc::string> res;
res["method_name"] = method->name();
res["request_type"] = method->input_type()->name();
res["response_type"] = method->output_type()->name();
res["request_class"] = ClassName(method->input_type());
res["response_class"] = ClassName(method->output_type());
return res;
}
void PrintMethodDeclarations(Printer *printer, const MethodDescriptor *method) {
map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);
PrintProtoRpcDeclarationAsPragma(printer, method, vars);
PrintSimpleSignature(printer, method, vars);
printer->Print(";\n\n");
PrintAdvancedSignature(printer, method, vars);
printer->Print(";\n\n\n");
}
void PrintSimpleImplementation(Printer *printer, const MethodDescriptor *method,
map< ::grpc::string, ::grpc::string> vars) {
printer->Print("{\n");
printer->Print(vars, " [[self RPCTo$method_name$With");
if (method->client_streaming()) {
printer->Print("RequestsWriter:requestWriter");
} else {
printer->Print("Request:request");
}
if (method->server_streaming()) {
printer->Print(" eventHandler:eventHandler] start];\n");
} else {
printer->Print(" handler:handler] start];\n");
}
printer->Print("}\n");
}
void PrintAdvancedImplementation(Printer *printer,
const MethodDescriptor *method,
map< ::grpc::string, ::grpc::string> vars) {
printer->Print("{\n");
printer->Print(vars, " return [self RPCToMethod:@\"$method_name$\"\n");
printer->Print(" requestsWriter:");
if (method->client_streaming()) {
printer->Print("requestWriter\n");
} else {
printer->Print("[GRXWriter writerWithValue:request]\n");
}
printer->Print(vars, " responseClass:[$response_class$ class]\n");
printer->Print(" responsesWriteable:[GRXWriteable ");
if (method->server_streaming()) {
printer->Print("writeableWithEventHandler:eventHandler]];\n");
} else {
printer->Print("writeableWithSingleHandler:handler]];\n");
}
printer->Print("}\n");
}
void PrintMethodImplementations(Printer *printer,
const MethodDescriptor *method) {
map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);
PrintProtoRpcDeclarationAsPragma(printer, method, vars);
// TODO(jcanizales): Print documentation from the method.
PrintSimpleSignature(printer, method, vars);
PrintSimpleImplementation(printer, method, vars);
printer->Print("// Returns a not-yet-started RPC object.\n");
PrintAdvancedSignature(printer, method, vars);
PrintAdvancedImplementation(printer, method, vars);
}
} // namespace
::grpc::string GetHeader(const ServiceDescriptor *service) {
::grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
grpc::protobuf::io::StringOutputStream output_stream(&output);
Printer printer(&output_stream, '$');
map< ::grpc::string, ::grpc::string> vars = {{"service_class", ServiceClassName(service)}};
printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n");
for (int i = 0; i < service->method_count(); i++) {
PrintMethodDeclarations(&printer, service->method(i));
}
printer.Print("@end\n\n");
printer.Print(
"// Basic service implementation, over gRPC, that only does"
" marshalling and parsing.\n");
printer.Print(vars,
"@interface $service_class$ :"
" GRPCProtoService<$service_class$>\n");
printer.Print(
"- (instancetype)initWithHost:(NSString *)host"
" NS_DESIGNATED_INITIALIZER;\n");
printer.Print("+ (instancetype)serviceWithHost:(NSString *)host;\n");
printer.Print("@end\n");
}
return output;
}
::grpc::string GetSource(const ServiceDescriptor *service) {
::grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
grpc::protobuf::io::StringOutputStream output_stream(&output);
Printer printer(&output_stream, '$');
map< ::grpc::string,::grpc::string> vars = {{"service_name", service->name()},
{"service_class", ServiceClassName(service)},
{"package", service->file()->package()}};
printer.Print(vars,
"static NSString *const kPackageName = @\"$package$\";\n");
printer.Print(
vars, "static NSString *const kServiceName = @\"$service_name$\";\n\n");
printer.Print(vars, "@implementation $service_class$\n\n");
printer.Print("// Designated initializer\n");
printer.Print("- (instancetype)initWithHost:(NSString *)host {\n");
printer.Print(
" return (self = [super initWithHost:host"
" packageName:kPackageName serviceName:kServiceName]);\n");
printer.Print("}\n\n");
printer.Print(
"// Override superclass initializer to disallow different"
" package and service names.\n");
printer.Print("- (instancetype)initWithHost:(NSString *)host\n");
printer.Print(" packageName:(NSString *)packageName\n");
printer.Print(" serviceName:(NSString *)serviceName {\n");
printer.Print(" return [self initWithHost:host];\n");
printer.Print("}\n\n");
printer.Print("+ (instancetype)serviceWithHost:(NSString *)host {\n");
printer.Print(" return [[self alloc] initWithHost:host];\n");
printer.Print("}\n\n\n");
for (int i = 0; i < service->method_count(); i++) {
PrintMethodImplementations(&printer, service->method(i));
}
printer.Print("@end\n");
}
return output;
}
} // namespace grpc_objective_c_generator
<commit_msg>fix for #6834<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <map>
#include <sstream>
#include "src/compiler/config.h"
#include "src/compiler/objective_c_generator.h"
#include "src/compiler/objective_c_generator_helpers.h"
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
using ::google::protobuf::compiler::objectivec::ClassName;
using ::grpc::protobuf::io::Printer;
using ::grpc::protobuf::MethodDescriptor;
using ::grpc::protobuf::ServiceDescriptor;
using ::std::map;
namespace grpc_objective_c_generator {
namespace {
void PrintProtoRpcDeclarationAsPragma(Printer *printer,
const MethodDescriptor *method,
map< ::grpc::string, ::grpc::string> vars) {
vars["client_stream"] = method->client_streaming() ? "stream " : "";
vars["server_stream"] = method->server_streaming() ? "stream " : "";
printer->Print(vars,
"#pragma mark $method_name$($client_stream$$request_type$)"
" returns ($server_stream$$response_type$)\n\n");
}
void PrintMethodSignature(Printer *printer, const MethodDescriptor *method,
const map< ::grpc::string, ::grpc::string> &vars) {
// TODO(jcanizales): Print method comments.
printer->Print(vars, "- ($return_type$)$method_name$With");
if (method->client_streaming()) {
printer->Print("RequestsWriter:(GRXWriter *)requestWriter");
} else {
printer->Print(vars, "Request:($request_class$ *)request");
}
// TODO(jcanizales): Put this on a new line and align colons.
if (method->server_streaming()) {
printer->Print(vars,
" eventHandler:(void(^)(BOOL done, "
"$response_class$ *_Nullable response, NSError *_Nullable error))eventHandler");
} else {
printer->Print(vars,
" handler:(void(^)($response_class$ *_Nullable response, "
"NSError *_Nullable error))handler");
}
}
void PrintSimpleSignature(Printer *printer, const MethodDescriptor *method,
map< ::grpc::string, ::grpc::string> vars) {
vars["method_name"] =
grpc_generator::LowercaseFirstLetter(vars["method_name"]);
vars["return_type"] = "void";
PrintMethodSignature(printer, method, vars);
}
void PrintAdvancedSignature(Printer *printer, const MethodDescriptor *method,
map< ::grpc::string, ::grpc::string> vars) {
vars["method_name"] = "RPCTo" + vars["method_name"];
vars["return_type"] = "GRPCProtoCall *";
PrintMethodSignature(printer, method, vars);
}
inline map< ::grpc::string, ::grpc::string> GetMethodVars(const MethodDescriptor *method) {
map< ::grpc::string, ::grpc::string> res;
res["method_name"] = method->name();
res["request_type"] = method->input_type()->name();
res["response_type"] = method->output_type()->name();
res["request_class"] = ClassName(method->input_type());
res["response_class"] = ClassName(method->output_type());
return res;
}
void PrintMethodDeclarations(Printer *printer, const MethodDescriptor *method) {
map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);
PrintProtoRpcDeclarationAsPragma(printer, method, vars);
PrintSimpleSignature(printer, method, vars);
printer->Print(";\n\n");
PrintAdvancedSignature(printer, method, vars);
printer->Print(";\n\n\n");
}
void PrintSimpleImplementation(Printer *printer, const MethodDescriptor *method,
map< ::grpc::string, ::grpc::string> vars) {
printer->Print("{\n");
printer->Print(vars, " [[self RPCTo$method_name$With");
if (method->client_streaming()) {
printer->Print("RequestsWriter:requestWriter");
} else {
printer->Print("Request:request");
}
if (method->server_streaming()) {
printer->Print(" eventHandler:eventHandler] start];\n");
} else {
printer->Print(" handler:handler] start];\n");
}
printer->Print("}\n");
}
void PrintAdvancedImplementation(Printer *printer,
const MethodDescriptor *method,
map< ::grpc::string, ::grpc::string> vars) {
printer->Print("{\n");
printer->Print(vars, " return [self RPCToMethod:@\"$method_name$\"\n");
printer->Print(" requestsWriter:");
if (method->client_streaming()) {
printer->Print("requestWriter\n");
} else {
printer->Print("[GRXWriter writerWithValue:request]\n");
}
printer->Print(vars, " responseClass:[$response_class$ class]\n");
printer->Print(" responsesWriteable:[GRXWriteable ");
if (method->server_streaming()) {
printer->Print("writeableWithEventHandler:eventHandler]];\n");
} else {
printer->Print("writeableWithSingleHandler:handler]];\n");
}
printer->Print("}\n");
}
void PrintMethodImplementations(Printer *printer,
const MethodDescriptor *method) {
map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);
PrintProtoRpcDeclarationAsPragma(printer, method, vars);
// TODO(jcanizales): Print documentation from the method.
PrintSimpleSignature(printer, method, vars);
PrintSimpleImplementation(printer, method, vars);
printer->Print("// Returns a not-yet-started RPC object.\n");
PrintAdvancedSignature(printer, method, vars);
PrintAdvancedImplementation(printer, method, vars);
}
} // namespace
::grpc::string GetHeader(const ServiceDescriptor *service) {
::grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
grpc::protobuf::io::StringOutputStream output_stream(&output);
Printer printer(&output_stream, '$');
map< ::grpc::string, ::grpc::string> vars = {{"service_class", ServiceClassName(service)}};
printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n");
for (int i = 0; i < service->method_count(); i++) {
PrintMethodDeclarations(&printer, service->method(i));
}
printer.Print("@end\n\n");
printer.Print(
"// Basic service implementation, over gRPC, that only does"
" marshalling and parsing.\n");
printer.Print(vars,
"@interface $service_class$ :"
" GRPCProtoService<$service_class$>\n");
printer.Print(
"- (instancetype)initWithHost:(NSString *)host"
" NS_DESIGNATED_INITIALIZER;\n");
printer.Print("+ (instancetype)serviceWithHost:(NSString *)host;\n");
printer.Print("@end\n");
}
return output;
}
::grpc::string GetSource(const ServiceDescriptor *service) {
::grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
grpc::protobuf::io::StringOutputStream output_stream(&output);
Printer printer(&output_stream, '$');
map< ::grpc::string,::grpc::string> vars = {{"service_name", service->name()},
{"service_class", ServiceClassName(service)},
{"package", service->file()->package()}};
printer.Print(vars, "@implementation $service_class$\n\n");
printer.Print("// Designated initializer\n");
printer.Print("- (instancetype)initWithHost:(NSString *)host {\n");
printer.Print(vars,
" return (self = [super initWithHost:host"
" packageName:@\"$package$\" serviceName:@\"$service_name$\"]);\n");
printer.Print("}\n\n");
printer.Print(
"// Override superclass initializer to disallow different"
" package and service names.\n");
printer.Print("- (instancetype)initWithHost:(NSString *)host\n");
printer.Print(" packageName:(NSString *)packageName\n");
printer.Print(" serviceName:(NSString *)serviceName {\n");
printer.Print(" return [self initWithHost:host];\n");
printer.Print("}\n\n");
printer.Print("+ (instancetype)serviceWithHost:(NSString *)host {\n");
printer.Print(" return [[self alloc] initWithHost:host];\n");
printer.Print("}\n\n\n");
for (int i = 0; i < service->method_count(); i++) {
PrintMethodImplementations(&printer, service->method(i));
}
printer.Print("@end\n");
}
return output;
}
} // namespace grpc_objective_c_generator
<|endoftext|>
|
<commit_before>/* rapicorn-zintern - small C source compression utility
* Copyright (C) 2003-2006 Tim Janik
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* A copy of the GNU Lesser General Public License should ship along
* with this library; if not, see http://www.gnu.org/copyleft/.
*/
#include <rapicorn-core/rapicorn-core.hh>
#include <glib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <zlib.h>
namespace Rapicorn {
static void zintern_error (const char *format,
...) RAPICORN_PRINTF (1, 2);
static void
zintern_error (const char *format,
...)
{
gchar *buffer;
va_list args;
va_start (args, format);
buffer = g_strdup_vprintf (format, args);
va_end (args);
g_printerr ("\nERROR: %s", buffer);
_exit (1);
g_free (buffer);
}
static bool use_compression = FALSE;
static bool use_base_name = FALSE;
typedef struct {
uint pos;
bool pad;
} Config;
static Config config_init = { 0, 0 };
static inline void
print_uchar (Config *config,
uint8 d)
{
if (config->pos > 70)
{
printf ("\"\n \"");
config->pos = 3;
config->pad = FALSE;
}
if (d < 33 || d > 126 || d == '?')
{
printf ("\\%o", d);
config->pos += 1 + 1 + (d > 7) + (d > 63);
config->pad = d < 64;
return;
}
if (d == '\\')
{
printf ("\\\\");
config->pos += 2;
}
else if (d == '"')
{
printf ("\\\"");
config->pos += 2;
}
else if (config->pad && d >= '0' && d <= '9')
{
printf ("\"\"");
printf ("%c", d);
config->pos += 3;
}
else
{
printf ("%c", d);
config->pos += 1;
}
config->pad = FALSE;
return;
}
#define to_upper(c) ((c) >='a' && (c) <='z' ? (c) - 'a' + 'A' : (c))
#define is_alnum(c) (((c) >='A' && (c) <='Z') || ((c) >='a' && (c) <='z') || ((c) >='0' && (c) <='9'))
static String
to_cupper (const String &str)
{
String s (str);
for (uint i = 0; i < s.size(); i++)
if (is_alnum (s[i]))
s[i] = to_upper (s[i]);
else
s[i] = '_';
return s;
}
static void
gen_zfile (const char *name,
const char *file)
{
FILE *f = fopen (file, "r");
uint8 *data = NULL;
uint i, dlen = 0, mlen = 0;
Bytef *cdata;
uLongf clen;
gchar *basefile = g_path_get_basename (file);
String fname = use_base_name ? basefile : file;
g_free (basefile); basefile = NULL;
Config config;
if (!f)
zintern_error ("failed to open \"%s\": %s", file, g_strerror (errno));
do
{
if (mlen <= dlen + 1024)
{
mlen += 8192;
data = g_renew (uint8, data, mlen);
}
dlen += fread (data + dlen, 1, mlen - dlen, f);
}
while (!feof (f));
if (ferror (f))
zintern_error ("failed to read from \"%s\": %s", file, g_strerror (errno));
if (use_compression)
{
int result;
const char *err;
clen = dlen + dlen / 100 + 64;
cdata = g_new (uint8, clen);
result = compress2 (cdata, &clen, data, dlen, Z_BEST_COMPRESSION);
switch (result)
{
case Z_OK:
err = NULL;
break;
case Z_MEM_ERROR:
err = "out of memory";
break;
case Z_BUF_ERROR:
err = "insufficient buffer size";
break;
default:
err = "unknown error";
break;
}
if (err)
zintern_error ("while compressing \"%s\": %s", file, err);
}
else
{
clen = dlen;
cdata = data;
}
g_print ("/* rapicorn-zintern file dump of %s */\n", file);
config = config_init;
printf ("#define %s_NAME \"", to_cupper (name).c_str());
for (i = 0; i < fname.size(); i++)
print_uchar (&config, fname[i]);
printf ("\"\n");
printf ("#define %s_SIZE (%u)\n", to_cupper (name).c_str(), dlen);
config = config_init;
printf ("static const unsigned char %s_DATA[%lu + 1] =\n", to_cupper (name).c_str(), clen);
printf ("( \"");
for (i = 0; i < clen; i++)
print_uchar (&config, cdata[i]);
printf ("\");\n");
fclose (f);
g_free (data);
if (cdata != data)
g_free (cdata);
}
static int
help (char *arg)
{
g_printerr ("usage: rapicorn-zintern [-h] [-b] [-z] [[name file]...]\n");
g_printerr (" -h Print usage information\n");
g_printerr (" -b Strip directories from file names\n");
g_printerr (" -z Compress data blocks with libz\n");
g_printerr ("Parse (name, file) pairs and generate C source\n");
g_printerr ("containing inlined data blocks of the files given.\n");
return arg != NULL;
}
extern "C" int
main (int argc,
char *argv[])
{
GSList *plist = NULL;
InitValue ivalues[] = {
{ "stand-alone", "true" },
{ NULL }
};
// rapicorn_init_core (&argc, &argv, NULL, ivalues);
for (int i = 1; i < argc; i++)
{
if (strcmp ("-z", argv[i]) == 0)
{
use_compression = TRUE;
}
else if (strcmp ("-b", argv[i]) == 0)
{
use_base_name = TRUE;
}
else if (strcmp ("-h", argv[i]) == 0)
{
return help (NULL);
}
else
plist = g_slist_append (plist, argv[i]);
}
if (argc <= 1)
return help (NULL);
while (plist && plist->next)
{
const char *name = (char*) plist->data;
GSList *tmp = plist;
plist = tmp->next;
g_slist_free_1 (tmp);
const char *file = (char*) plist->data;
tmp = plist;
plist = tmp->next;
g_slist_free_1 (tmp);
gen_zfile (name, file);
}
return 0;
}
} // Rapicorn
<commit_msg>rapicorn-zintern.cc: namespace fixes and cleanups.<commit_after>/* rapicorn-zintern - small C source compression utility
* Copyright (C) 2003-2006 Tim Janik
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* A copy of the GNU Lesser General Public License should ship along
* with this library; if not, see http://www.gnu.org/copyleft/.
*/
#include <rapicorn-core.hh>
#include <glib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <zlib.h>
namespace {
using namespace Rapicorn;
static void zintern_error (const char *format,
...) RAPICORN_PRINTF (1, 2);
static void
zintern_error (const char *format,
...)
{
gchar *buffer;
va_list args;
va_start (args, format);
buffer = g_strdup_vprintf (format, args);
va_end (args);
g_printerr ("\nERROR: %s", buffer);
_exit (1);
g_free (buffer);
}
static bool use_compression = FALSE;
static bool use_base_name = FALSE;
typedef struct {
uint pos;
bool pad;
} Config;
static Config config_init = { 0, 0 };
static inline void
print_uchar (Config *config,
uint8 d)
{
if (config->pos > 70)
{
printf ("\"\n \"");
config->pos = 3;
config->pad = FALSE;
}
if (d < 33 || d > 126 || d == '?')
{
printf ("\\%o", d);
config->pos += 1 + 1 + (d > 7) + (d > 63);
config->pad = d < 64;
return;
}
if (d == '\\')
{
printf ("\\\\");
config->pos += 2;
}
else if (d == '"')
{
printf ("\\\"");
config->pos += 2;
}
else if (config->pad && d >= '0' && d <= '9')
{
printf ("\"\"");
printf ("%c", d);
config->pos += 3;
}
else
{
printf ("%c", d);
config->pos += 1;
}
config->pad = FALSE;
return;
}
#define to_upper(c) ((c) >='a' && (c) <='z' ? (c) - 'a' + 'A' : (c))
#define is_alnum(c) (((c) >='A' && (c) <='Z') || ((c) >='a' && (c) <='z') || ((c) >='0' && (c) <='9'))
static String
to_cupper (const String &str)
{
String s (str);
for (uint i = 0; i < s.size(); i++)
if (is_alnum (s[i]))
s[i] = to_upper (s[i]);
else
s[i] = '_';
return s;
}
static void
gen_zfile (const char *name,
const char *file)
{
FILE *f = fopen (file, "r");
uint8 *data = NULL;
uint i, dlen = 0, mlen = 0;
Bytef *cdata;
uLongf clen;
gchar *basefile = g_path_get_basename (file);
String fname = use_base_name ? basefile : file;
g_free (basefile); basefile = NULL;
Config config;
if (!f)
zintern_error ("failed to open \"%s\": %s", file, g_strerror (errno));
do
{
if (mlen <= dlen + 1024)
{
mlen += 8192;
data = g_renew (uint8, data, mlen);
}
dlen += fread (data + dlen, 1, mlen - dlen, f);
}
while (!feof (f));
if (ferror (f))
zintern_error ("failed to read from \"%s\": %s", file, g_strerror (errno));
if (use_compression)
{
int result;
const char *err;
clen = dlen + dlen / 100 + 64;
cdata = g_new (uint8, clen);
result = compress2 (cdata, &clen, data, dlen, Z_BEST_COMPRESSION);
switch (result)
{
case Z_OK:
err = NULL;
break;
case Z_MEM_ERROR:
err = "out of memory";
break;
case Z_BUF_ERROR:
err = "insufficient buffer size";
break;
default:
err = "unknown error";
break;
}
if (err)
zintern_error ("while compressing \"%s\": %s", file, err);
}
else
{
clen = dlen;
cdata = data;
}
g_print ("/* rapicorn-zintern file dump of %s */\n", file);
config = config_init;
printf ("#define %s_NAME \"", to_cupper (name).c_str());
for (i = 0; i < fname.size(); i++)
print_uchar (&config, fname[i]);
printf ("\"\n");
printf ("#define %s_SIZE (%u)\n", to_cupper (name).c_str(), dlen);
config = config_init;
printf ("static const unsigned char %s_DATA[%lu + 1] =\n", to_cupper (name).c_str(), clen);
printf ("( \"");
for (i = 0; i < clen; i++)
print_uchar (&config, cdata[i]);
printf ("\");\n");
fclose (f);
g_free (data);
if (cdata != data)
g_free (cdata);
}
static int
help (char *arg)
{
g_printerr ("usage: rapicorn-zintern [-h] [-b] [-z] [[name file]...]\n");
g_printerr (" -h Print usage information\n");
g_printerr (" -b Strip directories from file names\n");
g_printerr (" -z Compress data blocks with libz\n");
g_printerr ("Parse (name, file) pairs and generate C source\n");
g_printerr ("containing inlined data blocks of the files given.\n");
return arg != NULL;
}
extern "C" int
main (int argc,
char *argv[])
{
GSList *plist = NULL;
for (int i = 1; i < argc; i++)
{
if (strcmp ("-z", argv[i]) == 0)
{
use_compression = TRUE;
}
else if (strcmp ("-b", argv[i]) == 0)
{
use_base_name = TRUE;
}
else if (strcmp ("-h", argv[i]) == 0)
{
return help (NULL);
}
else
plist = g_slist_append (plist, argv[i]);
}
if (argc <= 1)
return help (NULL);
while (plist && plist->next)
{
const char *name = (char*) plist->data;
GSList *tmp = plist;
plist = tmp->next;
g_slist_free_1 (tmp);
const char *file = (char*) plist->data;
tmp = plist;
plist = tmp->next;
g_slist_free_1 (tmp);
gen_zfile (name, file);
}
return 0;
}
} // anon
<|endoftext|>
|
<commit_before>#include "Analog.h"
#include "..\sysex\SysEx.h"
#include "..\eeprom\Configuration.h"
#include "..\interface\settings\AnalogSettings.h"
Analog::Analog() {
//def const
}
void Analog::init() {
const subtype analogEnabledSubtype = { MAX_NUMBER_OF_ANALOG, 0, 1 };
const subtype analogInvertedSubtype = { MAX_NUMBER_OF_ANALOG, 0, 1 };
const subtype analogTypeSubtype = { MAX_NUMBER_OF_ANALOG, 0, ANALOG_TYPES-1 };
const subtype analogMIDIidSubtype = { MAX_NUMBER_OF_ANALOG, 0, 127 };
const subtype analogCClowerLimitSubtype = { MAX_NUMBER_OF_ANALOG, 0, 127 };
const subtype analogCCupperLimitSubtype = { MAX_NUMBER_OF_ANALOG, 0, 127 };
const subtype *analogSubtypeArray[] = {
&analogEnabledSubtype,
&analogTypeSubtype,
&analogInvertedSubtype,
&analogMIDIidSubtype,
&analogCClowerLimitSubtype,
&analogCCupperLimitSubtype
};
//define message for sysex configuration
sysEx.addMessageType(CONF_ENCODER_BLOCK, ANALOG_SUBTYPES);
for (int i=0; i<ANALOG_SUBTYPES; i++) {
//define subtype messages
sysEx.addMessageSubType(CONF_ENCODER_BLOCK, i, analogSubtypeArray[i]->parameters, analogSubtypeArray[i]->lowValue, analogSubtypeArray[i]->highValue);
}
}
void Analog::update() {
if (!board.analogDataAvailable()) return;
int16_t analogData;
//check values
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++) {
analogData = board.getAnalogValue(i); //get raw analog reading
if (!getAnalogEnabled(i)) continue; //don't process component if it's not enabled
addAnalogSample(i, analogData);
if (!analogValueSampled(i)) continue; //three samples are needed
analogData = getMedianValue(i); //get median value from three analog samples for better accuracy
analogType type = getAnalogType(i);
switch(type) {
case potentiometer:
checkPotentiometerValue(i, analogData);
break;
case fsr:
checkFSRvalue(i, analogData);
break;
case ldr:
break;
default:
return;
}
}
}
void Analog::addAnalogSample(uint8_t analogID, int16_t sample) {
uint8_t sampleIndex = analogDebounceCounter[analogID];
analogSample[analogID][sampleIndex] = sample;
analogDebounceCounter[analogID]++;
}
bool Analog::analogValueSampled(uint8_t analogID) {
if (analogDebounceCounter[analogID] == NUMBER_OF_SAMPLES) {
analogDebounceCounter[analogID] = 0;
return true;
} return false;
}
int16_t Analog::getMedianValue(uint8_t analogID) {
int16_t medianValue = 0;
if ((analogSample[analogID][0] <= analogSample[analogID][1]) && (analogSample[analogID][0] <= analogSample[analogID][2]))
medianValue = (analogSample[analogID][1] <= analogSample[analogID][2]) ? analogSample[analogID][1] : analogSample[analogID][2];
else if ((analogSample[analogID][1] <= analogSample[analogID][0]) && (analogSample[analogID][1] <= analogSample[analogID][2]))
medianValue = (analogSample[analogID][0] <= analogSample[analogID][2]) ? analogSample[analogID][0] : analogSample[analogID][2];
else
medianValue = (analogSample[analogID][0] <= analogSample[analogID][1]) ? analogSample[analogID][0] : analogSample[analogID][1];
return medianValue;
}
bool Analog::getAnalogEnabled(uint8_t analogID) {
return configuration.readParameter(CONF_ANALOG_BLOCK, analogEnabledSection, analogID);
}
bool Analog::getAnalogInvertState(uint8_t analogID) {
return configuration.readParameter(CONF_ANALOG_BLOCK, analogInvertedSection, analogID);
}
analogType Analog::getAnalogType(uint8_t analogID) {
return (analogType)configuration.readParameter(CONF_ANALOG_BLOCK, analogTypeSection, analogID);
}
uint8_t Analog::getMIDIid(uint8_t analogID) {
return configuration.readParameter(CONF_ANALOG_BLOCK, analogMIDIidSection, analogID);
}
uint8_t Analog::getCClimit(uint8_t analogID, ccLimitType type) {
switch(type) {
case ccLimitLow:
return configuration.readParameter(CONF_ANALOG_BLOCK, analogCClowerLimitSection, analogID);
break;
case ccLimitHigh:
return configuration.readParameter(CONF_ANALOG_BLOCK, analogCCupperLimitSection, analogID);
break;
} return 0;
}
uint8_t Analog::getParameter(uint8_t messageType, uint8_t parameter) {
switch(messageType) {
case analogEnabledConf:
return getAnalogEnabled(parameter);
break;
case analogInvertedConf:
return getAnalogInvertState(parameter);
break;
case analogTypeConf:
return getAnalogType(parameter);
break;
case analogMIDIidConf:
return getMIDIid(parameter);
break;
case analogCClowerLimitConf:
return getCClimit(parameter, ccLimitLow);
break;
case analogCCupperLimitConf:
return getCClimit(parameter, ccLimitHigh);
break;
} return 0;
}
bool Analog::setAnalogEnabled(uint8_t analogID, uint8_t state) {
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogEnabledSection, analogID, state);
}
bool Analog::setAnalogInvertState(uint8_t analogID, uint8_t state) {
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogInvertedSection, analogID, state);
}
bool Analog::setAnalogType(uint8_t analogID, uint8_t type) {
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogTypeSection, analogID, type);
}
bool Analog::setMIDIid(uint8_t analogID, uint8_t midiID) {
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogMIDIidSection, analogID, midiID);
}
bool Analog::setCClimit(ccLimitType type, uint8_t analogID, uint8_t limit) {
switch (limit) {
case ccLimitLow:
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogCClowerLimitSection, analogID, limit);
break;
case ccLimitHigh:
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogCCupperLimitSection, analogID, limit);
break;
default:
return false;
break;
}
}
bool Analog::setParameter(uint8_t messageType, uint8_t parameter, uint8_t newParameter) {
switch(messageType) {
case analogEnabledConf:
return setAnalogEnabled(parameter, newParameter);
break;
case analogInvertedConf:
return setAnalogInvertState(parameter, newParameter);
break;
case analogTypeConf:
return setAnalogType(parameter, newParameter);
break;
case analogMIDIidConf:
return setMIDIid(parameter, newParameter);
break;
case analogCClowerLimitConf:
return setCClimit(ccLimitLow, parameter, newParameter);
break;
case analogCCupperLimitConf:
return setCClimit(ccLimitLow, parameter, newParameter);
break;
} return false;
}
Analog analog;<commit_msg>fix potential bug when changing from fsr to pot<commit_after>#include "Analog.h"
#include "..\sysex\SysEx.h"
#include "..\eeprom\Configuration.h"
#include "..\interface\settings\AnalogSettings.h"
Analog::Analog() {
//def const
}
void Analog::init() {
const subtype analogEnabledSubtype = { MAX_NUMBER_OF_ANALOG, 0, 1 };
const subtype analogInvertedSubtype = { MAX_NUMBER_OF_ANALOG, 0, 1 };
const subtype analogTypeSubtype = { MAX_NUMBER_OF_ANALOG, 0, ANALOG_TYPES-1 };
const subtype analogMIDIidSubtype = { MAX_NUMBER_OF_ANALOG, 0, 127 };
const subtype analogCClowerLimitSubtype = { MAX_NUMBER_OF_ANALOG, 0, 127 };
const subtype analogCCupperLimitSubtype = { MAX_NUMBER_OF_ANALOG, 0, 127 };
const subtype *analogSubtypeArray[] = {
&analogEnabledSubtype,
&analogTypeSubtype,
&analogInvertedSubtype,
&analogMIDIidSubtype,
&analogCClowerLimitSubtype,
&analogCCupperLimitSubtype
};
//define message for sysex configuration
sysEx.addMessageType(CONF_ENCODER_BLOCK, ANALOG_SUBTYPES);
for (int i=0; i<ANALOG_SUBTYPES; i++) {
//define subtype messages
sysEx.addMessageSubType(CONF_ENCODER_BLOCK, i, analogSubtypeArray[i]->parameters, analogSubtypeArray[i]->lowValue, analogSubtypeArray[i]->highValue);
}
}
void Analog::update() {
if (!board.analogDataAvailable()) return;
int16_t analogData;
//check values
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++) {
analogData = board.getAnalogValue(i); //get raw analog reading
if (!getAnalogEnabled(i)) continue; //don't process component if it's not enabled
addAnalogSample(i, analogData);
if (!analogValueSampled(i)) continue; //three samples are needed
analogData = getMedianValue(i); //get median value from three analog samples for better accuracy
analogType type = getAnalogType(i);
switch(type) {
case potentiometer:
checkPotentiometerValue(i, analogData);
break;
case fsr:
checkFSRvalue(i, analogData);
break;
case ldr:
break;
default:
return;
}
}
}
void Analog::addAnalogSample(uint8_t analogID, int16_t sample) {
uint8_t sampleIndex = analogDebounceCounter[analogID];
analogSample[analogID][sampleIndex] = sample;
analogDebounceCounter[analogID]++;
}
bool Analog::analogValueSampled(uint8_t analogID) {
if (analogDebounceCounter[analogID] == NUMBER_OF_SAMPLES) {
analogDebounceCounter[analogID] = 0;
return true;
} return false;
}
int16_t Analog::getMedianValue(uint8_t analogID) {
int16_t medianValue = 0;
if ((analogSample[analogID][0] <= analogSample[analogID][1]) && (analogSample[analogID][0] <= analogSample[analogID][2]))
medianValue = (analogSample[analogID][1] <= analogSample[analogID][2]) ? analogSample[analogID][1] : analogSample[analogID][2];
else if ((analogSample[analogID][1] <= analogSample[analogID][0]) && (analogSample[analogID][1] <= analogSample[analogID][2]))
medianValue = (analogSample[analogID][0] <= analogSample[analogID][2]) ? analogSample[analogID][0] : analogSample[analogID][2];
else
medianValue = (analogSample[analogID][0] <= analogSample[analogID][1]) ? analogSample[analogID][0] : analogSample[analogID][1];
return medianValue;
}
bool Analog::getAnalogEnabled(uint8_t analogID) {
return configuration.readParameter(CONF_ANALOG_BLOCK, analogEnabledSection, analogID);
}
bool Analog::getAnalogInvertState(uint8_t analogID) {
return configuration.readParameter(CONF_ANALOG_BLOCK, analogInvertedSection, analogID);
}
analogType Analog::getAnalogType(uint8_t analogID) {
return (analogType)configuration.readParameter(CONF_ANALOG_BLOCK, analogTypeSection, analogID);
}
uint8_t Analog::getMIDIid(uint8_t analogID) {
return configuration.readParameter(CONF_ANALOG_BLOCK, analogMIDIidSection, analogID);
}
uint8_t Analog::getCClimit(uint8_t analogID, ccLimitType type) {
switch(type) {
case ccLimitLow:
return configuration.readParameter(CONF_ANALOG_BLOCK, analogCClowerLimitSection, analogID);
break;
case ccLimitHigh:
return configuration.readParameter(CONF_ANALOG_BLOCK, analogCCupperLimitSection, analogID);
break;
} return 0;
}
uint8_t Analog::getParameter(uint8_t messageType, uint8_t parameter) {
switch(messageType) {
case analogEnabledConf:
return getAnalogEnabled(parameter);
break;
case analogInvertedConf:
return getAnalogInvertState(parameter);
break;
case analogTypeConf:
return getAnalogType(parameter);
break;
case analogMIDIidConf:
return getMIDIid(parameter);
break;
case analogCClowerLimitConf:
return getCClimit(parameter, ccLimitLow);
break;
case analogCCupperLimitConf:
return getCClimit(parameter, ccLimitHigh);
break;
} return 0;
}
bool Analog::setAnalogEnabled(uint8_t analogID, uint8_t state) {
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogEnabledSection, analogID, state);
}
bool Analog::setAnalogInvertState(uint8_t analogID, uint8_t state) {
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogInvertedSection, analogID, state);
}
bool Analog::setAnalogType(uint8_t analogID, uint8_t type) {
lastAnalogueValue[analogID] = 0;
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogTypeSection, analogID, type);
}
bool Analog::setMIDIid(uint8_t analogID, uint8_t midiID) {
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogMIDIidSection, analogID, midiID);
}
bool Analog::setCClimit(ccLimitType type, uint8_t analogID, uint8_t limit) {
switch (limit) {
case ccLimitLow:
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogCClowerLimitSection, analogID, limit);
break;
case ccLimitHigh:
return configuration.writeParameter(CONF_ANALOG_BLOCK, analogCCupperLimitSection, analogID, limit);
break;
default:
return false;
break;
}
}
bool Analog::setParameter(uint8_t messageType, uint8_t parameter, uint8_t newParameter) {
switch(messageType) {
case analogEnabledConf:
return setAnalogEnabled(parameter, newParameter);
break;
case analogInvertedConf:
return setAnalogInvertState(parameter, newParameter);
break;
case analogTypeConf:
return setAnalogType(parameter, newParameter);
break;
case analogMIDIidConf:
return setMIDIid(parameter, newParameter);
break;
case analogCClowerLimitConf:
return setCClimit(ccLimitLow, parameter, newParameter);
break;
case analogCCupperLimitConf:
return setCClimit(ccLimitLow, parameter, newParameter);
break;
} return false;
}
Analog analog;<|endoftext|>
|
<commit_before>#include "ImageStreamer.hpp"
#include "ImageImporter.hpp"
#include "DeviceManager.hpp"
#include "Exception.hpp"
using namespace fast;
/**
* Dummy function to get into the class again
*/
inline void stubStreamThread(ImageStreamer * streamer) {
streamer->producerStream();
}
DynamicImage::pointer ImageStreamer::getOutput() {
mOutput->setSource(mPtr.lock());
mOutput->setStreamer(mPtr.lock());
return mOutput;
}
ImageStreamer::ImageStreamer() {
mOutput = DynamicImage::New();
mStreamIsStarted = false;
mIsModified = true;
thread = NULL;
mFirstFrameIsInserted = false;
mHasReachedEnd = false;
mDevice = DeviceManager::getInstance().getDefaultComputationDevice();
mFilenameFormat = "";
}
void ImageStreamer::execute() {
mOutput->setSource(mPtr.lock());
mOutput->setStreamer(mPtr.lock());
if(mFilenameFormat == "")
throw Exception("No filename format was given to the ImageStreamer");
if(!mStreamIsStarted) {
mStreamIsStarted = true;
thread = new boost::thread(&stubStreamThread, this);
}
// Wait here for first frame
// TODO use condition variable instead
while(!mFirstFrameIsInserted);
}
void ImageStreamer::setFilenameFormat(std::string str) {
if(str.find("#") == std::string::npos)
throw Exception("Filename format must include a hash tag # which will be replaced by a integer starting from 0.");
mFilenameFormat = str;
}
void ImageStreamer::setDevice(ExecutionDevice::pointer device) {
mDevice = device;
}
inline std::string intToString(int number) {
std::stringstream ss;//create a stringstream
ss << number;//add number to the stream
return ss.str();//return a string with the contents of the stream
}
void ImageStreamer::producerStream() {
int i = 0;
while(true) {
std::string filename = mFilenameFormat;
filename.replace(
filename.find("#"),
1,
intToString(i));
try {
ImageImporter::pointer importer = ImageImporter::New();
importer->setFilename(filename);
importer->setDevice(mDevice);
Image::pointer image = importer->getOutput();
image->update();
DynamicImage::pointer ptr = mOutput;
if(ptr.isValid()) {
ptr->addFrame(image);
mFirstFrameIsInserted = true;
} else {
std::cout << "DynamicImage object destroyed, stream can stop." << std::endl;
break;
}
i++;
} catch(FileNotFoundException &e) {
std::cout << "Reached end of stream" << std::endl;
mHasReachedEnd = true;
// Reached end of stream
break;
}
}
}
ImageStreamer::~ImageStreamer() {
if(mStreamIsStarted) {
std::cout << "Joining the thread" << std::endl;
// TODO stop thread as well
thread->join();
delete thread;
}
}
bool ImageStreamer::hasReachedEnd() const {
return mHasReachedEnd;
}
<commit_msg>avoid deadlock when destroying streamer<commit_after>#include "ImageStreamer.hpp"
#include "ImageImporter.hpp"
#include "DeviceManager.hpp"
#include "Exception.hpp"
using namespace fast;
/**
* Dummy function to get into the class again
*/
inline void stubStreamThread(ImageStreamer * streamer) {
streamer->producerStream();
}
DynamicImage::pointer ImageStreamer::getOutput() {
mOutput->setSource(mPtr.lock());
mOutput->setStreamer(mPtr.lock());
return mOutput;
}
ImageStreamer::ImageStreamer() {
mOutput = DynamicImage::New();
mStreamIsStarted = false;
mIsModified = true;
thread = NULL;
mFirstFrameIsInserted = false;
mHasReachedEnd = false;
mDevice = DeviceManager::getInstance().getDefaultComputationDevice();
mFilenameFormat = "";
}
void ImageStreamer::execute() {
mOutput->setSource(mPtr.lock());
mOutput->setStreamer(mPtr.lock());
if(mFilenameFormat == "")
throw Exception("No filename format was given to the ImageStreamer");
if(!mStreamIsStarted) {
mStreamIsStarted = true;
thread = new boost::thread(&stubStreamThread, this);
}
// Wait here for first frame
// TODO use condition variable instead
while(!mFirstFrameIsInserted);
}
void ImageStreamer::setFilenameFormat(std::string str) {
if(str.find("#") == std::string::npos)
throw Exception("Filename format must include a hash tag # which will be replaced by a integer starting from 0.");
mFilenameFormat = str;
}
void ImageStreamer::setDevice(ExecutionDevice::pointer device) {
mDevice = device;
}
inline std::string intToString(int number) {
std::stringstream ss;//create a stringstream
ss << number;//add number to the stream
return ss.str();//return a string with the contents of the stream
}
void ImageStreamer::producerStream() {
int i = 0;
while(true) {
std::string filename = mFilenameFormat;
filename.replace(
filename.find("#"),
1,
intToString(i));
try {
ImageImporter::pointer importer = ImageImporter::New();
importer->setFilename(filename);
importer->setDevice(mDevice);
Image::pointer image = importer->getOutput();
image->update();
DynamicImage::pointer ptr = mOutput;
if(ptr.isValid()) {
ptr->addFrame(image);
mFirstFrameIsInserted = true;
} else {
std::cout << "DynamicImage object destroyed, stream can stop." << std::endl;
break;
}
i++;
} catch(FileNotFoundException &e) {
std::cout << "Reached end of stream" << std::endl;
mHasReachedEnd = true;
// Reached end of stream
break;
}
}
}
ImageStreamer::~ImageStreamer() {
if(mStreamIsStarted) {
if(thread->get_id() != boost::this_thread::get_id()) { // avoid deadlock
thread->join();
}
delete thread;
}
}
bool ImageStreamer::hasReachedEnd() const {
return mHasReachedEnd;
}
<|endoftext|>
|
<commit_before>/*
* BatteryTech
* Copyright (c) 2010 Battery Powered Games LLC.
*
* This code is a component of BatteryTech and is subject to the 'BatteryTech
* End User License Agreement'. Among other important provisions, this
* license prohibits the distribution of source code to anyone other than
* authorized parties. If you have any questions or would like an additional
* copy of the license, please contact: support@batterypoweredgames.com
*/
//============================================================================
// Name : boot.cpp
// Description : Android bootstrap and JNI linkage
//============================================================================
#ifdef ANDROID_NDK
#include "androidtypes.h"
#include "../platformgeneral.h"
#include "../../batterytech.h"
#include "../../render/GraphicsConfiguration.h"
#include "importgl.h"
#include <jni.h>
#include <android/log.h>
#include "../../util/strx.h"
#include "../opengles.h"
#include "../../audio/AudioManager.h"
using namespace BatteryTech;
#ifdef __cplusplus
extern "C" {
#endif
// the current env for the call
JNIEnv *jnienv;
jobject javaBoot;
extern AudioManager *_andSndMgr; // from androidgeneral
GraphicsConfiguration *gConfig;
void determineGPUCapabilities();
BatteryTech::SpecialKey getSpecialKey(int keyCode);
void Java_com_batterypoweredgames_batterytech_Boot_init(JNIEnv* env, jobject thiz, jint width, jint height, jboolean usingGLES2) {
jnienv = env;
javaBoot = thiz;
importGLInit(usingGLES2);
gConfig = new GraphicsConfiguration;
determineGPUCapabilities();
btInit(gConfig, width, height);
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_setScreenSize(JNIEnv* env, jobject thiz, jint width, jint height) {
jnienv = env;
javaBoot = thiz;
btSetScreenSize(width, height);
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_release(JNIEnv* env, jobject thiz) {
jnienv = env;
javaBoot = thiz;
btRelease();
delete gConfig;
importGLDeinit();
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_update(JNIEnv* env, jobject thiz, jfloat delta) {
//__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech Boot", "delta is %f", delta);
jnienv = env;
javaBoot = thiz;
btUpdate((F32)delta);
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_draw(JNIEnv* env, jobject thiz) {
jnienv = env;
javaBoot = thiz;
btDraw();
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_suspend(JNIEnv* env, jobject thiz) {
jnienv = env;
javaBoot = thiz;
btSuspend();
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_resume(JNIEnv* env, jobject thiz) {
jnienv = env;
javaBoot = thiz;
btResume();
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_setPointerState(JNIEnv* env, jobject thiz, jint pointerId, jboolean down, jint x, jint y) {
jnienv = env;
javaBoot = thiz;
btSetPointerState(pointerId, down, x, y);
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_keyUp(JNIEnv* env, jobject thiz, jint keyChar, jint keyCode) {
jnienv = env;
javaBoot = thiz;
btKeyUp(keyChar, getSpecialKey(keyCode));
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_keyDown(JNIEnv* env, jobject thiz, jint keyChar, jint keyCode) {
jnienv = env;
javaBoot = thiz;
btKeyDown(keyChar, getSpecialKey(keyCode));
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_keyPressed(JNIEnv* env, jobject thiz, jint keyChar, jint keyCode) {
jnienv = env;
javaBoot = thiz;
btKeyPressed(keyChar, getSpecialKey(keyCode));
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_accelerometerChanged(JNIEnv* env, jobject thiz, jfloat x, jfloat y, jfloat z) {
//__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech Boot", "delta is %f", delta);
jnienv = env;
javaBoot = thiz;
btAccelerometerChanged(x,y,z);
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_fillAudioBuffer(JNIEnv* env, jobject thiz, jshortArray jPCMData, jint length) {
if (_andSndMgr) {
signed short *buf = new signed short[length / 2];
_andSndMgr->fillBuffer(buf, length);
env->SetShortArrayRegion(jPCMData, 0, length / 2, buf);
delete [] buf;
}
}
jboolean Java_com_batterypoweredgames_batterytech_Boot_callback(JNIEnv* env, jobject thiz, jstring data) {
jnienv = env;
javaBoot = thiz;
jboolean ret = FALSE;
if (data) {
jboolean isCopy;
const char *jnibuf = jnienv->GetStringUTFChars(data, &isCopy);
ret = btCallback(jnibuf);
jnienv->ReleaseStringUTFChars(data, jnibuf);
}
jnienv = 0;
javaBoot = 0;
return ret;
}
void determineGPUCapabilities() {
const char *vendor = (const char*)glGetString(GL_VENDOR);
const char *renderer = (const char*)glGetString(GL_RENDERER);
const char *version = (const char*)glGetString(GL_VERSION);
const char *extensions = (const char*)glGetString(GL_EXTENSIONS);
// 1.0 = 0, 1.1 = 1, 2.0 = 2
int ver = 0;
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL Vendor %s", vendor);
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL Renderer %s", renderer);
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL Version %s", version);
if (strstr(version, "2.0")) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL ES Version 2.0 found");
ver = 2;
gConfig->supportsShaders = TRUE;
gConfig->supportsFBOs = TRUE;
} else if (strstr(version, "1.1")) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL ES Version 1.1 found");
ver = 1;
}
if (ver == 0) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL ES Version 1.0 found");
}
if ((ver > 0) || gles_checkExtension(GLES_EXT_GENERATE_MIPMAP)) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "HW MipMap Gen Supported");
gConfig->supportsHWmipmapgen = TRUE;
}
if (gles_checkExtension(GLES_EXT_TEXTURE_FLOAT)) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "Float textures supported");
gConfig->supportsFloatTextures = TRUE;
}
if (gles_checkExtension(GLES_EXT_DEPTH_TEXTURE)) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "Depth textures supported");
gConfig->supportsDepthTextures = TRUE;
}
if ((ver > 0) || gles_checkExtension(GLES_EXT_VERTEX_BUFFER_OBJECT)) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "VBOs Supported");
gConfig->supportsVBOs = TRUE;
}
if (strstr(renderer, "MSM7500")) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "HW UV Transform not supported");
gConfig->supportsUVTransform = FALSE;
} else {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "HW UV Transform supported");
gConfig->supportsUVTransform = TRUE;
}
if (strstr(renderer, ANDROID_RENDERER_PIXELFLINGER)) {
gConfig->softGPU = TRUE;
}
}
BatteryTech::SpecialKey getSpecialKey(int keyCode) {
if (keyCode == 82) {
return BatteryTech::SKEY_MENU;
} else if (keyCode == 4) {
return BatteryTech::SKEY_BACK;
} else if (keyCode == 27) {
return BatteryTech::SKEY_CAMERA;
} else {
return BatteryTech::SKEY_NULL;
}
}
void Java_com_batterypoweredgames_batterytech_Boot_setGraphicsContextLost(JNIEnv* env, jobject thiz, jboolean wasLost) {
jnienv = env;
javaBoot = thiz;
btSetGraphicsContextLost(wasLost);
jnienv = 0;
javaBoot = 0;
}
#ifdef __cplusplus
}
#endif
#endif /* _ANDROID */
<commit_msg>BatteryTech - Fixed Android OpenGL ES 3.0+<commit_after>/*
* BatteryTech
* Copyright (c) 2010 Battery Powered Games LLC.
*
* This code is a component of BatteryTech and is subject to the 'BatteryTech
* End User License Agreement'. Among other important provisions, this
* license prohibits the distribution of source code to anyone other than
* authorized parties. If you have any questions or would like an additional
* copy of the license, please contact: support@batterypoweredgames.com
*/
//============================================================================
// Name : boot.cpp
// Description : Android bootstrap and JNI linkage
//============================================================================
#ifdef ANDROID_NDK
#include "androidtypes.h"
#include "../platformgeneral.h"
#include "../../batterytech.h"
#include "../../render/GraphicsConfiguration.h"
#include "importgl.h"
#include <jni.h>
#include <android/log.h>
#include "../../util/strx.h"
#include "../opengles.h"
#include "../../audio/AudioManager.h"
using namespace BatteryTech;
#ifdef __cplusplus
extern "C" {
#endif
// the current env for the call
JNIEnv *jnienv;
jobject javaBoot;
extern AudioManager *_andSndMgr; // from androidgeneral
GraphicsConfiguration *gConfig;
void determineGPUCapabilities();
BatteryTech::SpecialKey getSpecialKey(int keyCode);
void Java_com_batterypoweredgames_batterytech_Boot_init(JNIEnv* env, jobject thiz, jint width, jint height, jboolean usingGLES2) {
jnienv = env;
javaBoot = thiz;
importGLInit(usingGLES2);
gConfig = new GraphicsConfiguration;
determineGPUCapabilities();
btInit(gConfig, width, height);
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_setScreenSize(JNIEnv* env, jobject thiz, jint width, jint height) {
jnienv = env;
javaBoot = thiz;
btSetScreenSize(width, height);
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_release(JNIEnv* env, jobject thiz) {
jnienv = env;
javaBoot = thiz;
btRelease();
delete gConfig;
importGLDeinit();
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_update(JNIEnv* env, jobject thiz, jfloat delta) {
//__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech Boot", "delta is %f", delta);
jnienv = env;
javaBoot = thiz;
btUpdate((F32)delta);
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_draw(JNIEnv* env, jobject thiz) {
jnienv = env;
javaBoot = thiz;
btDraw();
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_suspend(JNIEnv* env, jobject thiz) {
jnienv = env;
javaBoot = thiz;
btSuspend();
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_resume(JNIEnv* env, jobject thiz) {
jnienv = env;
javaBoot = thiz;
btResume();
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_setPointerState(JNIEnv* env, jobject thiz, jint pointerId, jboolean down, jint x, jint y) {
jnienv = env;
javaBoot = thiz;
btSetPointerState(pointerId, down, x, y);
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_keyUp(JNIEnv* env, jobject thiz, jint keyChar, jint keyCode) {
jnienv = env;
javaBoot = thiz;
btKeyUp(keyChar, getSpecialKey(keyCode));
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_keyDown(JNIEnv* env, jobject thiz, jint keyChar, jint keyCode) {
jnienv = env;
javaBoot = thiz;
btKeyDown(keyChar, getSpecialKey(keyCode));
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_keyPressed(JNIEnv* env, jobject thiz, jint keyChar, jint keyCode) {
jnienv = env;
javaBoot = thiz;
btKeyPressed(keyChar, getSpecialKey(keyCode));
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_accelerometerChanged(JNIEnv* env, jobject thiz, jfloat x, jfloat y, jfloat z) {
//__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech Boot", "delta is %f", delta);
jnienv = env;
javaBoot = thiz;
btAccelerometerChanged(x,y,z);
jnienv = 0;
javaBoot = 0;
}
void Java_com_batterypoweredgames_batterytech_Boot_fillAudioBuffer(JNIEnv* env, jobject thiz, jshortArray jPCMData, jint length) {
if (_andSndMgr) {
signed short *buf = new signed short[length / 2];
_andSndMgr->fillBuffer(buf, length);
env->SetShortArrayRegion(jPCMData, 0, length / 2, buf);
delete [] buf;
}
}
jboolean Java_com_batterypoweredgames_batterytech_Boot_callback(JNIEnv* env, jobject thiz, jstring data) {
jnienv = env;
javaBoot = thiz;
jboolean ret = FALSE;
if (data) {
jboolean isCopy;
const char *jnibuf = jnienv->GetStringUTFChars(data, &isCopy);
ret = btCallback(jnibuf);
jnienv->ReleaseStringUTFChars(data, jnibuf);
}
jnienv = 0;
javaBoot = 0;
return ret;
}
void determineGPUCapabilities() {
const char *vendor = (const char*)glGetString(GL_VENDOR);
const char *renderer = (const char*)glGetString(GL_RENDERER);
const char *version = (const char*)glGetString(GL_VERSION);
const char *extensions = (const char*)glGetString(GL_EXTENSIONS);
// 1.0 = 0, 1.1 = 1, 2.0/3.0 = 2
int ver = 0;
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL Vendor %s", vendor);
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL Renderer %s", renderer);
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL Version %s", version);
if ((strstr(version, "1.0") || strstr(version, "1.1")) && !(strstr(version, "2.0") || strstr(version, "3.0"))) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL ES Version 1.0/1.1 found");
if (!strstr(version, "1.0")) {
ver = 1;
}
} else {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "OpenGL ES Version 2.0/3.0 found");
gConfig->supportsShaders = TRUE;
gConfig->supportsFBOs = TRUE;
ver = 2;
}
if ((ver > 0) || gles_checkExtension(GLES_EXT_GENERATE_MIPMAP)) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "HW MipMap Gen Supported");
gConfig->supportsHWmipmapgen = TRUE;
}
if (gles_checkExtension(GLES_EXT_TEXTURE_FLOAT)) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "Float textures supported");
gConfig->supportsFloatTextures = TRUE;
}
if (gles_checkExtension(GLES_EXT_DEPTH_TEXTURE)) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "Depth textures supported");
gConfig->supportsDepthTextures = TRUE;
}
if ((ver > 0) || gles_checkExtension(GLES_EXT_VERTEX_BUFFER_OBJECT)) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "VBOs Supported");
gConfig->supportsVBOs = TRUE;
}
if (strstr(renderer, "MSM7500")) {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "HW UV Transform not supported");
gConfig->supportsUVTransform = FALSE;
} else {
__android_log_print(ANDROID_LOG_DEBUG, "BatteryTech", "HW UV Transform supported");
gConfig->supportsUVTransform = TRUE;
}
if (strstr(renderer, ANDROID_RENDERER_PIXELFLINGER)) {
gConfig->softGPU = TRUE;
}
}
BatteryTech::SpecialKey getSpecialKey(int keyCode) {
if (keyCode == 82) {
return BatteryTech::SKEY_MENU;
} else if (keyCode == 4) {
return BatteryTech::SKEY_BACK;
} else if (keyCode == 27) {
return BatteryTech::SKEY_CAMERA;
} else {
return BatteryTech::SKEY_NULL;
}
}
void Java_com_batterypoweredgames_batterytech_Boot_setGraphicsContextLost(JNIEnv* env, jobject thiz, jboolean wasLost) {
jnienv = env;
javaBoot = thiz;
btSetGraphicsContextLost(wasLost);
jnienv = 0;
javaBoot = 0;
}
#ifdef __cplusplus
}
#endif
#endif /* _ANDROID */
<|endoftext|>
|
<commit_before>/**
* @file
*
* Includes all external headers.
*/
#pragma once
#include <algorithm>
#include <numeric>
#include <limits>
#include <utility>
#include <functional>
#include <vector>
#include <memory>
#include <string>
#include <sstream>
#include <iomanip>
#include <initializer_list>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cstddef>
#include <cmath>
#include <unistd.h>
#include <getopt.h>
#include <dlfcn.h>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Sparse>
#ifdef HAVE_OMP_H
#include <omp.h>
#endif
<commit_msg>Removed Eigen header include for sparse matrices.<commit_after>/**
* @file
*
* Includes all external headers.
*/
#pragma once
#include <algorithm>
#include <numeric>
#include <limits>
#include <utility>
#include <functional>
#include <vector>
#include <memory>
#include <string>
#include <sstream>
#include <iomanip>
#include <initializer_list>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cstddef>
#include <cmath>
#include <unistd.h>
#include <getopt.h>
#include <dlfcn.h>
#include <eigen3/Eigen/Dense>
#ifdef HAVE_OMP_H
#include <omp.h>
#endif
<|endoftext|>
|
<commit_before>/* Sirikata Utilities -- Sirikata Utilities
* Singleton.hpp
*
* Copyright (c) 2009, Daniel Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _SIRIKATA_SINGLETON_HPP_
#define _SIRIKATA_SINGLETON_HPP_
namespace Sirikata {
template <class T> class AutoSingleton {
static std::auto_ptr<T>sInstance;
public:
static T&getSingleton() {
if (sInstance.get()==NULL) {
std::auto_ptr<T> tmp(new T);
sInstance = tmp;
}
return *static_cast<T*>(sInstance.get());
}
AutoSingleton() {
if (sInstance.get()==NULL) {
std::auto_ptr<T> tmp(static_cast<T*>(this));
sInstance=tmp;
}
}
virtual ~AutoSingleton() {
if (sInstance.get()==this)
sInstance.release();
}
static void destroy() {
sInstance.reset();
}
};
}
#define AUTO_SINGLETON_INSTANCE(ClassName) template<>std::auto_ptr<ClassName>Sirikata::AutoSingleton<ClassName>::sInstance= std::auto_ptr<ClassName>()
#endif
<commit_msg>fixed options memory leak due to autoptr being inited twice<commit_after>/* Sirikata Utilities -- Sirikata Utilities
* Singleton.hpp
*
* Copyright (c) 2009, Daniel Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _SIRIKATA_SINGLETON_HPP_
#define _SIRIKATA_SINGLETON_HPP_
namespace Sirikata {
template <class T> class AutoSingleton {
static std::auto_ptr<T>sInstance;
public:
static T&getSingleton() {
if (sInstance.get()==NULL) {
std::auto_ptr<T> tmp(new T);
sInstance = tmp;
}
return *static_cast<T*>(sInstance.get());
}
AutoSingleton() {
if (sInstance.get()==NULL) {
std::auto_ptr<T> tmp(static_cast<T*>(this));
sInstance=tmp;
}
}
virtual ~AutoSingleton() {
if (sInstance.get()==this)
sInstance.release();
}
static void destroy() {
sInstance.reset();
}
};
}
#define AUTO_SINGLETON_INSTANCE(ClassName) template std::auto_ptr<ClassName> Sirikata::AutoSingleton<ClassName>::sInstance; template<>std::auto_ptr<ClassName>Sirikata::AutoSingleton<ClassName>::sInstance
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "core/posix.hh"
#include "core/vla.hh"
#include "core/reactor.hh"
#include "core/future-util.hh"
#include "core/stream.hh"
#include "core/circular_buffer.hh"
#include "core/align.hh"
#include <atomic>
#include <list>
#include <queue>
#include <fcntl.h>
#include <linux/if_tun.h>
#include "ip.hh"
#include <xen/xen.h>
#include <xen/memory.h>
#include <xen/sys/gntalloc.h>
#include "core/xen/xenstore.hh"
#include "core/xen/evtchn.hh"
#include "xenfront.hh"
#include <unordered_set>
using namespace net;
namespace xen {
using phys = uint64_t;
class xenfront_net_device : public net::device {
private:
bool _userspace;
stream<packet> _rx_stream;
net::hw_features _hw_features;
std::string _device_str;
xenstore* _xenstore = xenstore::instance();
unsigned _otherend;
std::string _backend;
gntalloc *_gntalloc;
evtchn *_evtchn;
port _tx_evtchn;
port _rx_evtchn;
front_ring<tx> _tx_ring;
front_ring<rx> _rx_ring;
grant_head *_tx_refs;
grant_head *_rx_refs;
std::list<std::pair<std::string, std::string>> _features;
static std::unordered_set<std::string> _supported_features;
ethernet_address _hw_address;
port bind_tx_evtchn();
port bind_rx_evtchn();
future<> alloc_rx_references();
future<> handle_tx_completions();
future<> queue_rx_packet();
void alloc_one_rx_reference(unsigned id);
std::string path(std::string s) { return _device_str + "/" + s; }
public:
explicit xenfront_net_device(boost::program_options::variables_map opts, bool userspace);
~xenfront_net_device();
virtual subscription<packet> receive(std::function<future<> (packet)> next) override;
virtual future<> send(packet p) override;
ethernet_address hw_address();
net::hw_features hw_features();
};
std::unordered_set<std::string>
xenfront_net_device::_supported_features = {
"feature-split-event-channels",
"feature-rx-copy",
};
subscription<packet>
xenfront_net_device::receive(std::function<future<> (packet)> next) {
auto sub = _rx_stream.listen(std::move(next));
keep_doing([this] {
return _rx_evtchn.pending().then([this] {
return queue_rx_packet();
});
});
return std::move(sub);
}
future<>
xenfront_net_device::send(packet _p) {
uint32_t frag = 0;
// There doesn't seem to be a way to tell xen, when using the userspace
// drivers, to map a particular page. Therefore, the only alternative
// here is to copy. All pages shared must come from the gntalloc mmap.
//
// A better solution could be to change the packet allocation path to
// use a pre-determined page for data.
//
// In-kernel should be fine
// FIXME: negotiate and use scatter/gather
_p.linearize();
return _tx_ring.entries.get_index().then([this, p = std::move(_p), frag] (unsigned idx) mutable {
auto req_prod = _tx_ring._sring->req_prod;
auto f = p.frag(frag);
auto ref = _tx_refs->new_ref(f.base, f.size);
assert(!_tx_ring.entries[idx]);
_tx_ring.entries[idx] = ref;
auto req = &_tx_ring._sring->_ring[idx].req;
req->gref = ref.xen_id;
req->offset = 0;
req->flags = {};
if (p.offload_info().protocol != ip_protocol_num::unused) {
req->flags.csum_blank = true;
req->flags.data_validated = true;
} else {
req->flags.data_validated = true;
}
req->id = idx;
req->size = f.size;
_tx_ring.req_prod_pvt = idx;
_tx_ring._sring->req_prod = req_prod + 1;
_tx_ring._sring->req_event++;
if ((frag + 1) == p.nr_frags()) {
_tx_evtchn.notify();
return make_ready_future<>();
} else {
return make_ready_future<>();
}
});
// FIXME: Don't forget to clear all grant refs when frontend closes. Or is it automatic?
}
#define rmb() asm volatile("lfence":::"memory");
#define wmb() asm volatile("":::"memory");
template <typename T>
future<unsigned> front_ring<T>::entries::get_index() {
return _available.wait().then([this] {
auto ret = _ids.front();
_ids.pop();
return make_ready_future<unsigned>(ret);
});
}
template <typename T>
void front_ring<T>::entries::free_index(unsigned id) {
_ids.push(id);
_available.signal();
}
future<> xenfront_net_device::queue_rx_packet() {
auto rsp_cons = _rx_ring.rsp_cons;
rmb();
auto rsp_prod = _rx_ring._sring->rsp_prod;
while (rsp_cons < rsp_prod) {
auto rsp = _rx_ring[rsp_cons].rsp;
auto& entry = _rx_ring.entries[rsp.id];
rsp_cons++;
_rx_ring.rsp_cons = rsp_cons;
if (rsp.status < 0) {
printf("Packet error: Handle it\n");
continue;
}
auto rsp_size = rsp.status;
packet p(static_cast<char *>(entry.page) + rsp.offset, rsp_size);
_rx_stream.produce(std::move(p));
_rx_ring._sring->rsp_event = rsp_cons + 1;
rsp_prod = _rx_ring._sring->rsp_prod;
_rx_refs->free_ref(entry);
_rx_ring.entries.free_index(rsp.id);
}
// FIXME: Queue_rx maybe should not be a future then
return make_ready_future<>();
}
void xenfront_net_device::alloc_one_rx_reference(unsigned index) {
_rx_ring.entries[index] = _rx_refs->new_ref();
// This is how the backend knows where to put data.
auto req = &_rx_ring._sring->_ring[index].req;
req->id = index;
req->gref = _rx_ring.entries[index].xen_id;
}
future<> xenfront_net_device::alloc_rx_references() {
return _rx_ring.entries.get_index().then([this] (unsigned i) {
auto req_prod = _rx_ring.req_prod_pvt;
alloc_one_rx_reference(i);
++req_prod;
_rx_ring.req_prod_pvt = req_prod;
wmb();
_rx_ring._sring->req_prod = req_prod;
/* ready */
_rx_evtchn.notify();
});
}
future<> xenfront_net_device::handle_tx_completions() {
auto prod = _tx_ring._sring->rsp_prod;
rmb();
for (unsigned i = _tx_ring.rsp_cons; i != prod; i++) {
auto rsp = _tx_ring[i].rsp;
if (rsp.status == 1) {
continue;
}
if (rsp.status != 0) {
printf("Packet error: Handle it\n");
continue;
}
auto& entry = _tx_ring.entries[rsp.id];
_tx_refs->free_ref(entry);
_tx_ring.entries.free_index(rsp.id);
}
_tx_ring.rsp_cons = prod;
_tx_ring._sring->rsp_event = prod + 1;
return make_ready_future<>();
}
ethernet_address xenfront_net_device::hw_address() {
return _hw_address;
}
net::hw_features xenfront_net_device::hw_features() {
return _hw_features;
}
port xenfront_net_device::bind_tx_evtchn() {
return _evtchn->bind();
}
port xenfront_net_device::bind_rx_evtchn() {
auto split = _xenstore->read_or_default<int>(_backend + "/feature-split-event-channels");
if (split) {
return _evtchn->bind();
}
return _evtchn->bind(_tx_evtchn.number());
}
xenfront_net_device::xenfront_net_device(boost::program_options::variables_map opts, bool userspace)
: _userspace(userspace)
, _rx_stream()
, _device_str("device/vif/" + std::to_string(opts["vif"].as<unsigned>()))
, _otherend(_xenstore->read<int>(path("backend-id")))
, _backend(_xenstore->read(path("backend")))
, _gntalloc(gntalloc::instance(_userspace, _otherend))
, _evtchn(evtchn::instance(_userspace, _otherend))
, _tx_evtchn(bind_tx_evtchn())
, _rx_evtchn(bind_rx_evtchn())
, _tx_ring(_gntalloc->alloc_ref())
, _rx_ring(_gntalloc->alloc_ref())
, _tx_refs(_gntalloc->alloc_ref(front_ring<tx>::nr_ents))
, _rx_refs(_gntalloc->alloc_ref(front_ring<rx>::nr_ents))
, _hw_address(net::parse_ethernet_address(_xenstore->read(path("mac")))) {
_rx_stream.started();
auto all_features = _xenstore->ls(_backend);
std::unordered_map<std::string, int> features_nack;
for (auto&& feat : all_features) {
if (feat.compare(0, 8, "feature-") == 0 && !_supported_features.count(feat)) {
features_nack[feat] = 0;
}
}
if (!opts["split-event-channels"].as<bool>()) {
features_nack["feature-split-event-channels"] = 0;
}
_hw_features.rx_csum_offload = true;
_hw_features.tx_csum_offload = true;
for (auto&s : all_features) {
auto value = _xenstore->read(_backend + "/" + s);
_features.push_back(std::make_pair(s, value));
}
{
auto t = xenstore::xenstore_transaction();
for (auto&& f: features_nack) {
_xenstore->write(path(f.first), f.second, t);
}
_xenstore->write<int>(path("event-channel-tx"), _tx_evtchn.number(), t);
_xenstore->write<int>(path("event-channel-rx"), _rx_evtchn.number(), t);
_xenstore->write<int>(path("tx-ring-ref"), _tx_ring.ref, t);
_xenstore->write<int>(path("rx-ring-ref"), _rx_ring.ref, t);
_xenstore->write<int>(path("state"), 4, t);
}
keep_doing([this] {
return alloc_rx_references();
});
keep_doing([this] () {
return _tx_evtchn.pending().then([this] {
handle_tx_completions();
});
});
}
xenfront_net_device::~xenfront_net_device() {
{
auto t = xenstore::xenstore_transaction();
for (auto& f: _features) {
_xenstore->remove(path(f.first), t);
}
_xenstore->remove(path("event-channel-tx"), t);
_xenstore->remove(path("event-channel-rx"), t);
_xenstore->remove(path("tx-ring-ref"), t);
_xenstore->remove(path("rx-ring-ref"), t);
_xenstore->write<int>(path("state"), 6, t);
}
_xenstore->write<int>(path("state"), 1);
}
boost::program_options::options_description
get_xenfront_net_options_description() {
boost::program_options::options_description opts(
"xenfront net options");
opts.add_options()
("vif",
boost::program_options::value<unsigned>()->default_value(0),
"vif number to hijack")
("split-event-channels",
boost::program_options::value<bool>()->default_value(true),
"Split event channel support")
;
return opts;
}
std::unique_ptr<net::device> create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace) {
auto ptr = std::make_unique<xenfront_net_device>(opts, userspace);
// This assumes only one device per cpu. Will need to be fixed when
// this assumption will no longer hold.
dev = ptr.get();
return std::move(ptr);
}
}
<commit_msg>xen: positively acknowledge supported features<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "core/posix.hh"
#include "core/vla.hh"
#include "core/reactor.hh"
#include "core/future-util.hh"
#include "core/stream.hh"
#include "core/circular_buffer.hh"
#include "core/align.hh"
#include <atomic>
#include <list>
#include <queue>
#include <fcntl.h>
#include <linux/if_tun.h>
#include "ip.hh"
#include <xen/xen.h>
#include <xen/memory.h>
#include <xen/sys/gntalloc.h>
#include "core/xen/xenstore.hh"
#include "core/xen/evtchn.hh"
#include "xenfront.hh"
#include <unordered_set>
using namespace net;
namespace xen {
using phys = uint64_t;
class xenfront_net_device : public net::device {
private:
bool _userspace;
stream<packet> _rx_stream;
net::hw_features _hw_features;
std::string _device_str;
xenstore* _xenstore = xenstore::instance();
unsigned _otherend;
std::string _backend;
gntalloc *_gntalloc;
evtchn *_evtchn;
port _tx_evtchn;
port _rx_evtchn;
front_ring<tx> _tx_ring;
front_ring<rx> _rx_ring;
grant_head *_tx_refs;
grant_head *_rx_refs;
std::list<std::pair<std::string, std::string>> _features;
static std::unordered_set<std::string> _supported_features;
ethernet_address _hw_address;
port bind_tx_evtchn();
port bind_rx_evtchn();
future<> alloc_rx_references();
future<> handle_tx_completions();
future<> queue_rx_packet();
void alloc_one_rx_reference(unsigned id);
std::string path(std::string s) { return _device_str + "/" + s; }
public:
explicit xenfront_net_device(boost::program_options::variables_map opts, bool userspace);
~xenfront_net_device();
virtual subscription<packet> receive(std::function<future<> (packet)> next) override;
virtual future<> send(packet p) override;
ethernet_address hw_address();
net::hw_features hw_features();
};
std::unordered_set<std::string>
xenfront_net_device::_supported_features = {
"feature-split-event-channels",
"feature-rx-copy",
};
subscription<packet>
xenfront_net_device::receive(std::function<future<> (packet)> next) {
auto sub = _rx_stream.listen(std::move(next));
keep_doing([this] {
return _rx_evtchn.pending().then([this] {
return queue_rx_packet();
});
});
return std::move(sub);
}
future<>
xenfront_net_device::send(packet _p) {
uint32_t frag = 0;
// There doesn't seem to be a way to tell xen, when using the userspace
// drivers, to map a particular page. Therefore, the only alternative
// here is to copy. All pages shared must come from the gntalloc mmap.
//
// A better solution could be to change the packet allocation path to
// use a pre-determined page for data.
//
// In-kernel should be fine
// FIXME: negotiate and use scatter/gather
_p.linearize();
return _tx_ring.entries.get_index().then([this, p = std::move(_p), frag] (unsigned idx) mutable {
auto req_prod = _tx_ring._sring->req_prod;
auto f = p.frag(frag);
auto ref = _tx_refs->new_ref(f.base, f.size);
assert(!_tx_ring.entries[idx]);
_tx_ring.entries[idx] = ref;
auto req = &_tx_ring._sring->_ring[idx].req;
req->gref = ref.xen_id;
req->offset = 0;
req->flags = {};
if (p.offload_info().protocol != ip_protocol_num::unused) {
req->flags.csum_blank = true;
req->flags.data_validated = true;
} else {
req->flags.data_validated = true;
}
req->id = idx;
req->size = f.size;
_tx_ring.req_prod_pvt = idx;
_tx_ring._sring->req_prod = req_prod + 1;
_tx_ring._sring->req_event++;
if ((frag + 1) == p.nr_frags()) {
_tx_evtchn.notify();
return make_ready_future<>();
} else {
return make_ready_future<>();
}
});
// FIXME: Don't forget to clear all grant refs when frontend closes. Or is it automatic?
}
#define rmb() asm volatile("lfence":::"memory");
#define wmb() asm volatile("":::"memory");
template <typename T>
future<unsigned> front_ring<T>::entries::get_index() {
return _available.wait().then([this] {
auto ret = _ids.front();
_ids.pop();
return make_ready_future<unsigned>(ret);
});
}
template <typename T>
void front_ring<T>::entries::free_index(unsigned id) {
_ids.push(id);
_available.signal();
}
future<> xenfront_net_device::queue_rx_packet() {
auto rsp_cons = _rx_ring.rsp_cons;
rmb();
auto rsp_prod = _rx_ring._sring->rsp_prod;
while (rsp_cons < rsp_prod) {
auto rsp = _rx_ring[rsp_cons].rsp;
auto& entry = _rx_ring.entries[rsp.id];
rsp_cons++;
_rx_ring.rsp_cons = rsp_cons;
if (rsp.status < 0) {
printf("Packet error: Handle it\n");
continue;
}
auto rsp_size = rsp.status;
packet p(static_cast<char *>(entry.page) + rsp.offset, rsp_size);
_rx_stream.produce(std::move(p));
_rx_ring._sring->rsp_event = rsp_cons + 1;
rsp_prod = _rx_ring._sring->rsp_prod;
_rx_refs->free_ref(entry);
_rx_ring.entries.free_index(rsp.id);
}
// FIXME: Queue_rx maybe should not be a future then
return make_ready_future<>();
}
void xenfront_net_device::alloc_one_rx_reference(unsigned index) {
_rx_ring.entries[index] = _rx_refs->new_ref();
// This is how the backend knows where to put data.
auto req = &_rx_ring._sring->_ring[index].req;
req->id = index;
req->gref = _rx_ring.entries[index].xen_id;
}
future<> xenfront_net_device::alloc_rx_references() {
return _rx_ring.entries.get_index().then([this] (unsigned i) {
auto req_prod = _rx_ring.req_prod_pvt;
alloc_one_rx_reference(i);
++req_prod;
_rx_ring.req_prod_pvt = req_prod;
wmb();
_rx_ring._sring->req_prod = req_prod;
/* ready */
_rx_evtchn.notify();
});
}
future<> xenfront_net_device::handle_tx_completions() {
auto prod = _tx_ring._sring->rsp_prod;
rmb();
for (unsigned i = _tx_ring.rsp_cons; i != prod; i++) {
auto rsp = _tx_ring[i].rsp;
if (rsp.status == 1) {
continue;
}
if (rsp.status != 0) {
printf("Packet error: Handle it\n");
continue;
}
auto& entry = _tx_ring.entries[rsp.id];
_tx_refs->free_ref(entry);
_tx_ring.entries.free_index(rsp.id);
}
_tx_ring.rsp_cons = prod;
_tx_ring._sring->rsp_event = prod + 1;
return make_ready_future<>();
}
ethernet_address xenfront_net_device::hw_address() {
return _hw_address;
}
net::hw_features xenfront_net_device::hw_features() {
return _hw_features;
}
port xenfront_net_device::bind_tx_evtchn() {
return _evtchn->bind();
}
port xenfront_net_device::bind_rx_evtchn() {
auto split = _xenstore->read_or_default<int>(_backend + "/feature-split-event-channels");
if (split) {
return _evtchn->bind();
}
return _evtchn->bind(_tx_evtchn.number());
}
xenfront_net_device::xenfront_net_device(boost::program_options::variables_map opts, bool userspace)
: _userspace(userspace)
, _rx_stream()
, _device_str("device/vif/" + std::to_string(opts["vif"].as<unsigned>()))
, _otherend(_xenstore->read<int>(path("backend-id")))
, _backend(_xenstore->read(path("backend")))
, _gntalloc(gntalloc::instance(_userspace, _otherend))
, _evtchn(evtchn::instance(_userspace, _otherend))
, _tx_evtchn(bind_tx_evtchn())
, _rx_evtchn(bind_rx_evtchn())
, _tx_ring(_gntalloc->alloc_ref())
, _rx_ring(_gntalloc->alloc_ref())
, _tx_refs(_gntalloc->alloc_ref(front_ring<tx>::nr_ents))
, _rx_refs(_gntalloc->alloc_ref(front_ring<rx>::nr_ents))
, _hw_address(net::parse_ethernet_address(_xenstore->read(path("mac")))) {
_rx_stream.started();
auto all_features = _xenstore->ls(_backend);
std::unordered_map<std::string, int> features_nack;
for (auto&& feat : all_features) {
if (feat.compare(0, 8, "feature-") == 0) {
auto val = _xenstore->read<int>(_backend + "/" + feat);
features_nack[feat] = val && _supported_features.count(feat);
}
}
if (!opts["split-event-channels"].as<bool>()) {
features_nack["feature-split-event-channels"] = 0;
}
_hw_features.rx_csum_offload = true;
_hw_features.tx_csum_offload = true;
for (auto&s : all_features) {
auto value = _xenstore->read(_backend + "/" + s);
_features.push_back(std::make_pair(s, value));
}
{
auto t = xenstore::xenstore_transaction();
for (auto&& f: features_nack) {
_xenstore->write(path(f.first), f.second, t);
}
_xenstore->write<int>(path("event-channel-tx"), _tx_evtchn.number(), t);
_xenstore->write<int>(path("event-channel-rx"), _rx_evtchn.number(), t);
_xenstore->write<int>(path("tx-ring-ref"), _tx_ring.ref, t);
_xenstore->write<int>(path("rx-ring-ref"), _rx_ring.ref, t);
_xenstore->write<int>(path("state"), 4, t);
}
keep_doing([this] {
return alloc_rx_references();
});
keep_doing([this] () {
return _tx_evtchn.pending().then([this] {
handle_tx_completions();
});
});
}
xenfront_net_device::~xenfront_net_device() {
{
auto t = xenstore::xenstore_transaction();
for (auto& f: _features) {
_xenstore->remove(path(f.first), t);
}
_xenstore->remove(path("event-channel-tx"), t);
_xenstore->remove(path("event-channel-rx"), t);
_xenstore->remove(path("tx-ring-ref"), t);
_xenstore->remove(path("rx-ring-ref"), t);
_xenstore->write<int>(path("state"), 6, t);
}
_xenstore->write<int>(path("state"), 1);
}
boost::program_options::options_description
get_xenfront_net_options_description() {
boost::program_options::options_description opts(
"xenfront net options");
opts.add_options()
("vif",
boost::program_options::value<unsigned>()->default_value(0),
"vif number to hijack")
("split-event-channels",
boost::program_options::value<bool>()->default_value(true),
"Split event channel support")
;
return opts;
}
std::unique_ptr<net::device> create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace) {
auto ptr = std::make_unique<xenfront_net_device>(opts, userspace);
// This assumes only one device per cpu. Will need to be fixed when
// this assumption will no longer hold.
dev = ptr.get();
return std::move(ptr);
}
}
<|endoftext|>
|
<commit_before>#ifndef TEST_NOTCH_IO_HPP
#define TEST_NOTCH_IO_HPP
#include <sstream>
#include "catch.hpp"
#include "notch_io.hpp"
using namespace std;
TEST_CASE("Array plain-text I/O", "[io]") {
Array a = {0.5, 1.0, 2.0, 4.0};
// output
ostringstream sout;
sout << a;
CHECK(sout.str() == "0.5 1 2 4");
// input
Array b(4);
istringstream sin(sout.str());
sin >> b;
REQUIRE(b.size() == a.size());
for (size_t i = 0; i < a.size(); ++i) {
CHECK(b[i] == a[i]);
}
}
#endif
<commit_msg>tests for FANNReader and FANNFormat<commit_after>#ifndef TEST_NOTCH_IO_HPP
#define TEST_NOTCH_IO_HPP
#include <sstream>
#include <iterator>
#include "catch.hpp"
#include "notch_io.hpp"
using namespace std;
TEST_CASE("Array plain-text I/O", "[io]") {
Array a = {0.5, 1.0, 2.0, 4.0};
// output
ostringstream sout;
sout << a;
CHECK(sout.str() == "0.5 1 2 4");
// input
Array b(4);
istringstream sin(sout.str());
sin >> b;
REQUIRE(b.size() == a.size());
for (size_t i = 0; i < a.size(); ++i) {
CHECK(b[i] == a[i]);
}
}
TEST_CASE("Dataset FANN-format reader", "[io]") {
stringstream ss("4 2 1\n0.0 0\n0\n0.0 1.0\n1.0\n1.0 0.0\n1\n1 1\n0.0");
LabeledDataset d = FANNReader::read(ss);
CHECK(d.size() == 4);
CHECK(d.inputDim() == 2);
CHECK(d.outputDim() == 1);
LabeledDataset good {{{0,0},{0}},
{{0,1},{1}},
{{1,0},{1}},
{{1,1},{0}}};
auto d_it = begin(d);
auto d_end = end(d);
auto good_it = begin(good);
auto good_end = end(good);
for (; good_it != good_end; ++d_it, ++good_it) {
for (size_t i = 0; i < good.inputDim(); ++i) {
CHECK((*good_it).data[i] == (*d_it).data[i]);
}
for (size_t i = 0; i < good.outputDim(); ++i) {
CHECK((*good_it).label[i] == (*d_it).label[i]);
}
}
}
TEST_CASE("Dataset FANN-format writer", "[io]") {
LabeledDataset xorD {{{0,0},{0}}, {{0,1},{1}}, {{1,0},{1}}, {{1,1},{0}}};
ostringstream ss;
ss << FANNFormat(xorD);
CHECK(ss.str() == "4 2 1\n0 0\n0\n0 1\n1\n1 0\n1\n1 1\n0\n");
}
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <mapnik/geom_util.hpp>
// boost
#include <boost/version.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#if BOOST_VERSION < 103600
#include <boost/filesystem/convenience.hpp>
#endif
#include "shape_featureset.hpp"
#include "shape_index_featureset.hpp"
#include "shape.hpp"
DATASOURCE_PLUGIN(shape_datasource)
using mapnik::String;
using mapnik::Double;
using mapnik::Integer;
using mapnik::datasource_exception;
using mapnik::filter_in_box;
using mapnik::filter_at_point;
using mapnik::attribute_descriptor;
shape_datasource::shape_datasource(const parameters ¶ms)
: datasource (params),
type_(datasource::Vector),
file_length_(0),
indexed_(false),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8"))
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw datasource_exception("missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
shape_name_ = *base + "/" + *file;
else
shape_name_ = *file;
boost::filesystem::path path(shape_name_);
#if BOOST_VERSION >= 103600
path.replace_extension("");
#else
path = boost::filesystem::change_extension(path,"");
#endif
shape_name_ = path.string();
if (!boost::filesystem::exists(shape_name_ + ".shp")) throw datasource_exception(shape_name_ + ".shp does not exist");
try
{
shape_io shape(shape_name_);
init(shape);
for (int i=0;i<shape.dbf().num_fields();++i)
{
field_descriptor const& fd=shape.dbf().descriptor(i);
std::string fld_name=fd.name_;
switch (fd.type_)
{
case 'C':
case 'D':
case 'M':
case 'L':
desc_.add_descriptor(attribute_descriptor(fld_name, String));
break;
case 'N':
case 'F':
{
if (fd.dec_>0)
{
desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8));
}
else
{
desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4));
}
break;
}
default:
#ifdef MAPNIK_DEBUG
std::clog << "unknown type "<<fd.type_<<"\n";
#endif
break;
}
}
}
catch (datasource_exception& ex)
{
std::clog<<ex.what()<<std::endl;
throw;
}
catch (...)
{
std::clog << " got exception ... \n";
throw;
}
}
shape_datasource::~shape_datasource() {}
const std::string shape_datasource::name_="shape";
void shape_datasource::init(shape_io& shape)
{
//first read header from *.shp
int file_code=shape.shp().read_xdr_integer();
if (file_code!=9994)
{
//invalid file code
throw datasource_exception((boost::format("wrong file code : %d") % file_code).str());
}
shape.shp().skip(5*4);
file_length_=shape.shp().read_xdr_integer();
int version=shape.shp().read_ndr_integer();
if (version!=1000)
{
//invalid version number
throw datasource_exception((boost::format("invalid version number: %d") % version).str());
}
#ifdef MAPNIK_DEBUG
int shape_type = shape.shp().read_ndr_integer();
#else
shape.shp().skip(4);
#endif
shape.shp().read_envelope(extent_);
shape.shp().skip(4*8);
// check if we have an index file around
std::string index_name(shape_name_+".index");
std::ifstream file(index_name.c_str(),std::ios::in | std::ios::binary);
if (file)
{
indexed_=true;
file.close();
}
#ifdef MAPNIK_DEBUG
std::clog << extent_ << std::endl;
std::clog << "file_length=" << file_length_ << std::endl;
std::clog << "shape_type=" << shape_type << std::endl;
#endif
}
int shape_datasource::type() const
{
return type_;
}
layer_descriptor shape_datasource::get_descriptor() const
{
return desc_;
}
std::string shape_datasource::name()
{
return name_;
}
featureset_ptr shape_datasource::features(const query& q) const
{
filter_in_box filter(q.get_bbox());
if (indexed_)
{
return featureset_ptr
(new shape_index_featureset<filter_in_box>(filter,
shape_name_,
q.property_names(),
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_in_box>(filter,
shape_name_,
q.property_names(),
desc_.get_encoding(),
file_length_));
}
}
featureset_ptr shape_datasource::features_at_point(coord2d const& pt) const
{
filter_at_point filter(pt);
// collect all attribute names
std::vector<attribute_descriptor> const& desc_vector = desc_.get_descriptors();
std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_vector.end();
std::set<std::string> names;
while (itr != end)
{
names.insert(itr->get_name());
++itr;
}
if (indexed_)
{
return featureset_ptr
(new shape_index_featureset<filter_at_point>(filter,
shape_name_,
names,
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_at_point>(filter,
shape_name_,
names,
desc_.get_encoding(),
file_length_));
}
}
Envelope<double> shape_datasource::envelope() const
{
return extent_;
}
<commit_msg>shape plugin: only trim the '.shp' extension (restores behavior added in r1046 and later changed in r1170) - closes #413<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <mapnik/geom_util.hpp>
// boost
#include <boost/version.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#include "shape_featureset.hpp"
#include "shape_index_featureset.hpp"
#include "shape.hpp"
DATASOURCE_PLUGIN(shape_datasource)
using mapnik::String;
using mapnik::Double;
using mapnik::Integer;
using mapnik::datasource_exception;
using mapnik::filter_in_box;
using mapnik::filter_at_point;
using mapnik::attribute_descriptor;
shape_datasource::shape_datasource(const parameters ¶ms)
: datasource (params),
type_(datasource::Vector),
file_length_(0),
indexed_(false),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8"))
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw datasource_exception("missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
shape_name_ = *base + "/" + *file;
else
shape_name_ = *file;
boost::algorithm::ireplace_last(shape_name_,".shp","");
if (!boost::filesystem::exists(shape_name_ + ".shp"))
{
throw datasource_exception(shape_name_ + " does not exist");
}
try
{
shape_io shape(shape_name_);
init(shape);
for (int i=0;i<shape.dbf().num_fields();++i)
{
field_descriptor const& fd=shape.dbf().descriptor(i);
std::string fld_name=fd.name_;
switch (fd.type_)
{
case 'C':
case 'D':
case 'M':
case 'L':
desc_.add_descriptor(attribute_descriptor(fld_name, String));
break;
case 'N':
case 'F':
{
if (fd.dec_>0)
{
desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8));
}
else
{
desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4));
}
break;
}
default:
#ifdef MAPNIK_DEBUG
std::clog << "unknown type "<<fd.type_<<"\n";
#endif
break;
}
}
}
catch (datasource_exception& ex)
{
std::clog<<ex.what()<<std::endl;
throw;
}
catch (...)
{
std::clog << " got exception ... \n";
throw;
}
}
shape_datasource::~shape_datasource() {}
const std::string shape_datasource::name_="shape";
void shape_datasource::init(shape_io& shape)
{
//first read header from *.shp
int file_code=shape.shp().read_xdr_integer();
if (file_code!=9994)
{
//invalid file code
throw datasource_exception((boost::format("wrong file code : %d") % file_code).str());
}
shape.shp().skip(5*4);
file_length_=shape.shp().read_xdr_integer();
int version=shape.shp().read_ndr_integer();
if (version!=1000)
{
//invalid version number
throw datasource_exception((boost::format("invalid version number: %d") % version).str());
}
#ifdef MAPNIK_DEBUG
int shape_type = shape.shp().read_ndr_integer();
#else
shape.shp().skip(4);
#endif
shape.shp().read_envelope(extent_);
shape.shp().skip(4*8);
// check if we have an index file around
std::string index_name(shape_name_+".index");
std::ifstream file(index_name.c_str(),std::ios::in | std::ios::binary);
if (file)
{
indexed_=true;
file.close();
}
#ifdef MAPNIK_DEBUG
std::clog << extent_ << std::endl;
std::clog << "file_length=" << file_length_ << std::endl;
std::clog << "shape_type=" << shape_type << std::endl;
#endif
}
int shape_datasource::type() const
{
return type_;
}
layer_descriptor shape_datasource::get_descriptor() const
{
return desc_;
}
std::string shape_datasource::name()
{
return name_;
}
featureset_ptr shape_datasource::features(const query& q) const
{
filter_in_box filter(q.get_bbox());
if (indexed_)
{
return featureset_ptr
(new shape_index_featureset<filter_in_box>(filter,
shape_name_,
q.property_names(),
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_in_box>(filter,
shape_name_,
q.property_names(),
desc_.get_encoding(),
file_length_));
}
}
featureset_ptr shape_datasource::features_at_point(coord2d const& pt) const
{
filter_at_point filter(pt);
// collect all attribute names
std::vector<attribute_descriptor> const& desc_vector = desc_.get_descriptors();
std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_vector.end();
std::set<std::string> names;
while (itr != end)
{
names.insert(itr->get_name());
++itr;
}
if (indexed_)
{
return featureset_ptr
(new shape_index_featureset<filter_at_point>(filter,
shape_name_,
names,
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_at_point>(filter,
shape_name_,
names,
desc_.get_encoding(),
file_length_));
}
}
Envelope<double> shape_datasource::envelope() const
{
return extent_;
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D/Common.hpp>
# include <Siv3D/Common/OpenGL.hpp>
# include <Siv3D/PointVector.hpp>
# include <Siv3D/ResizeMode.hpp>
# include <Siv3D/Scene.hpp>
# include <Siv3D/Graphics.hpp>
# include <Siv3D/FloatRect.hpp>
# include <Siv3D/Image.hpp>
# include <ThirdParty/EnumBitmask/EnumBitmask.hpp>
# include "GLES3InternalTexture2D.hpp"
namespace s3d
{
enum class GLES3ClearTarget
{
BackBuffer = 1 << 0,
Scene = 1 << 1,
All = (BackBuffer | Scene),
};
DEFINE_BITMASK_OPERATORS(GLES3ClearTarget);
class CRenderer2D_GLES3;
class GLES3BackBuffer
{
private:
CRenderer2D_GLES3* pRenderer2D = nullptr;
uint32 m_sampleCount = Graphics::DefaultSampleCount;
ResizeMode m_sceneResizeMode = Scene::DefaultResizeMode;
Size m_backBufferSize = Window::DefaultClientSize;
Size m_sceneSize = Scene::DefaultSceneSize;
struct SceneBuffer
{
std::unique_ptr<GLES3InternalTexture2D> scene;
std::unique_ptr<GLES3InternalTexture2D> resolved;
} m_sceneBuffers;
ColorF m_letterboxColor = Scene::DefaultLetterBoxColor;
ColorF m_backgroundColor = Scene::DefaultBackgroundColor;
TextureFilter m_sceneTextureFilter = Scene::DefaultTextureFilter;
Image m_screenCaptureImage;
public:
GLES3BackBuffer();
~GLES3BackBuffer();
void clear(GLES3ClearTarget clearTargets);
void bindSceneToContext(bool useDepth);
void bindToScene(GLuint frameBuffer);
void unbind();
void updateFromSceneBuffer();
void capture();
const Image& getScreenCapture() const;
//////////////////////////////////////////////////
//
// LetterboxColor
//
//////////////////////////////////////////////////
void setLetterboxColor(const ColorF& color) noexcept;
[[nodiscard]]
const ColorF& getLetterBoxColor() const noexcept;
//////////////////////////////////////////////////
//
// BackgroundColor
//
//////////////////////////////////////////////////
void setBackgroundColor(const ColorF& color) noexcept;
[[nodiscard]]
const ColorF& getBackgroundColor() const noexcept;
//////////////////////////////////////////////////
//
// SceneTextureFilter
//
//////////////////////////////////////////////////
void setSceneTextureFilter(TextureFilter textureFilter) noexcept;
[[nodiscard]]
TextureFilter getSceneTextureFilter() const noexcept;
//////////////////////////////////////////////////
//
// SceneResizeMode
//
//////////////////////////////////////////////////
void setSceneResizeMode(ResizeMode resizeMode);
[[nodiscard]]
ResizeMode getSceneResizeMode() const noexcept;
//////////////////////////////////////////////////
//
// BackBuffer
//
//////////////////////////////////////////////////
void setBackBufferSize(Size backBufferSize);
[[nodiscard]]
const Size& getBackBufferSize() const noexcept;
void updateSceneSize();
[[nodiscard]]
std::pair<float, RectF> getLetterboxComposition() const noexcept;
//////////////////////////////////////////////////
//
// SceneBuffer
//
//////////////////////////////////////////////////
void setSceneBufferSize(Size size);
[[nodiscard]]
const Size& getSceneBufferSize() const noexcept;
};
}
<commit_msg>[Web] reduce scene buffer sampling number to 1<commit_after>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D/Common.hpp>
# include <Siv3D/Common/OpenGL.hpp>
# include <Siv3D/PointVector.hpp>
# include <Siv3D/ResizeMode.hpp>
# include <Siv3D/Scene.hpp>
# include <Siv3D/Graphics.hpp>
# include <Siv3D/FloatRect.hpp>
# include <Siv3D/Image.hpp>
# include <ThirdParty/EnumBitmask/EnumBitmask.hpp>
# include "GLES3InternalTexture2D.hpp"
namespace s3d
{
enum class GLES3ClearTarget
{
BackBuffer = 1 << 0,
Scene = 1 << 1,
All = (BackBuffer | Scene),
};
DEFINE_BITMASK_OPERATORS(GLES3ClearTarget);
class CRenderer2D_GLES3;
class GLES3BackBuffer
{
private:
CRenderer2D_GLES3* pRenderer2D = nullptr;
uint32 m_sampleCount = 1; // Graphics::DefaultSampleCount;
ResizeMode m_sceneResizeMode = Scene::DefaultResizeMode;
Size m_backBufferSize = Window::DefaultClientSize;
Size m_sceneSize = Scene::DefaultSceneSize;
struct SceneBuffer
{
std::unique_ptr<GLES3InternalTexture2D> scene;
std::unique_ptr<GLES3InternalTexture2D> resolved;
} m_sceneBuffers;
ColorF m_letterboxColor = Scene::DefaultLetterBoxColor;
ColorF m_backgroundColor = Scene::DefaultBackgroundColor;
TextureFilter m_sceneTextureFilter = Scene::DefaultTextureFilter;
Image m_screenCaptureImage;
public:
GLES3BackBuffer();
~GLES3BackBuffer();
void clear(GLES3ClearTarget clearTargets);
void bindSceneToContext(bool useDepth);
void bindToScene(GLuint frameBuffer);
void unbind();
void updateFromSceneBuffer();
void capture();
const Image& getScreenCapture() const;
//////////////////////////////////////////////////
//
// LetterboxColor
//
//////////////////////////////////////////////////
void setLetterboxColor(const ColorF& color) noexcept;
[[nodiscard]]
const ColorF& getLetterBoxColor() const noexcept;
//////////////////////////////////////////////////
//
// BackgroundColor
//
//////////////////////////////////////////////////
void setBackgroundColor(const ColorF& color) noexcept;
[[nodiscard]]
const ColorF& getBackgroundColor() const noexcept;
//////////////////////////////////////////////////
//
// SceneTextureFilter
//
//////////////////////////////////////////////////
void setSceneTextureFilter(TextureFilter textureFilter) noexcept;
[[nodiscard]]
TextureFilter getSceneTextureFilter() const noexcept;
//////////////////////////////////////////////////
//
// SceneResizeMode
//
//////////////////////////////////////////////////
void setSceneResizeMode(ResizeMode resizeMode);
[[nodiscard]]
ResizeMode getSceneResizeMode() const noexcept;
//////////////////////////////////////////////////
//
// BackBuffer
//
//////////////////////////////////////////////////
void setBackBufferSize(Size backBufferSize);
[[nodiscard]]
const Size& getBackBufferSize() const noexcept;
void updateSceneSize();
[[nodiscard]]
std::pair<float, RectF> getLetterboxComposition() const noexcept;
//////////////////////////////////////////////////
//
// SceneBuffer
//
//////////////////////////////////////////////////
void setSceneBufferSize(Size size);
[[nodiscard]]
const Size& getSceneBufferSize() const noexcept;
};
}
<|endoftext|>
|
<commit_before>#pragma once
#include "crow/core.hpp" // -lcrow
#include <map>
#include <stdexcept>
#include <string>
namespace Unicorn {
namespace UnicornDetail {
struct UnicodeVersionTable {
std::map<Crow::Version, char32_t> table;
UnicodeVersionTable();
};
const UnicodeVersionTable& unicode_version_table();
}
// Imports
using Crow::basic_string; // std::basic_string
using Crow::string; // std::string
using Crow::u8string; // std::string
using Crow::u16string; // std::u16string
using Crow::u32string; // std::u32string
using Crow::wstring; // std::wstring
using Crow::ascii_whitespace; // "\t\n\v\f\r "
using Crow::npos; // std::string::npos
// Exceptions
class EncodingError:
public std::runtime_error {
public:
EncodingError():
std::runtime_error(prefix({}, 0)), enc(), ofs(0) {}
explicit EncodingError(const u8string& encoding, size_t offset = 0):
std::runtime_error(prefix(encoding, offset)), enc(encoding), ofs(offset) {}
template <typename C>
EncodingError(const u8string& encoding, size_t offset, const C* ptr, size_t n = 1):
std::runtime_error(prefix(encoding, offset) + hexcode(ptr, n)), enc(encoding), ofs(offset) {}
u8string encoding() const { return enc; }
size_t offset() const noexcept { return ofs; }
private:
u8string enc;
size_t ofs;
static u8string prefix(const u8string& encoding, size_t offset);
template <typename C> static u8string hexcode(const C* ptr, size_t n);
};
template <typename C>
u8string EncodingError::hexcode(const C* ptr, size_t n) {
using utype = std::make_unsigned_t<C>;
if (! ptr || ! n)
return {};
u8string s = "; hex";
auto uptr = reinterpret_cast<const utype*>(ptr);
for (size_t i = 0; i < n; ++i) {
s += ' ';
s += Crow::hex(uptr[i]);
}
return s;
}
// Basic character types
#if defined(_XOPEN_SOURCE)
using NativeCharacter = char;
#else
#define UNICORN_NATIVE_WCHAR 1
using NativeCharacter = wchar_t;
#endif
#if WCHAR_MAX < 0x7fffffff
#define UNICORN_WCHAR_UTF16 1
using WcharEquivalent = char16_t;
#else
#define UNICORN_WCHAR_UTF32 1
using WcharEquivalent = char32_t;
#endif
using NativeString = basic_string<NativeCharacter>;
using WstringEquivalent = basic_string<WcharEquivalent>;
namespace Literals {
NativeString operator"" _nat(const char* s, size_t n);
}
// Version information
Crow::Version unicorn_version() noexcept;
Crow::Version unicode_version() noexcept;
}
<commit_msg>Change ldlib detection scheme<commit_after>#pragma once
#include "crow/core.hpp"
#include <map>
#include <stdexcept>
#include <string>
namespace Unicorn {
namespace UnicornDetail {
struct UnicodeVersionTable {
std::map<Crow::Version, char32_t> table;
UnicodeVersionTable();
};
const UnicodeVersionTable& unicode_version_table();
}
// Imports
using Crow::basic_string; // std::basic_string
using Crow::string; // std::string
using Crow::u8string; // std::string
using Crow::u16string; // std::u16string
using Crow::u32string; // std::u32string
using Crow::wstring; // std::wstring
using Crow::ascii_whitespace; // "\t\n\v\f\r "
using Crow::npos; // std::string::npos
// Exceptions
class EncodingError:
public std::runtime_error {
public:
EncodingError():
std::runtime_error(prefix({}, 0)), enc(), ofs(0) {}
explicit EncodingError(const u8string& encoding, size_t offset = 0):
std::runtime_error(prefix(encoding, offset)), enc(encoding), ofs(offset) {}
template <typename C>
EncodingError(const u8string& encoding, size_t offset, const C* ptr, size_t n = 1):
std::runtime_error(prefix(encoding, offset) + hexcode(ptr, n)), enc(encoding), ofs(offset) {}
u8string encoding() const { return enc; }
size_t offset() const noexcept { return ofs; }
private:
u8string enc;
size_t ofs;
static u8string prefix(const u8string& encoding, size_t offset);
template <typename C> static u8string hexcode(const C* ptr, size_t n);
};
template <typename C>
u8string EncodingError::hexcode(const C* ptr, size_t n) {
using utype = std::make_unsigned_t<C>;
if (! ptr || ! n)
return {};
u8string s = "; hex";
auto uptr = reinterpret_cast<const utype*>(ptr);
for (size_t i = 0; i < n; ++i) {
s += ' ';
s += Crow::hex(uptr[i]);
}
return s;
}
// Basic character types
#if defined(_XOPEN_SOURCE)
using NativeCharacter = char;
#else
#define UNICORN_NATIVE_WCHAR 1
using NativeCharacter = wchar_t;
#endif
#if WCHAR_MAX < 0x7fffffff
#define UNICORN_WCHAR_UTF16 1
using WcharEquivalent = char16_t;
#else
#define UNICORN_WCHAR_UTF32 1
using WcharEquivalent = char32_t;
#endif
using NativeString = basic_string<NativeCharacter>;
using WstringEquivalent = basic_string<WcharEquivalent>;
namespace Literals {
NativeString operator"" _nat(const char* s, size_t n);
}
// Version information
Crow::Version unicorn_version() noexcept;
Crow::Version unicode_version() noexcept;
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, 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 <assert.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include "P4TopIndication.h"
#include "P4TopRequest.h"
#include "GeneratedTypes.h"
#include "utils.h"
#ifndef le32
#define le32 int32_t
#endif
#ifndef u32
#define u32 u_int32_t
#endif
#ifndef u16
#define u16 u_int16_t
#endif
#ifndef s32
#define s32 int32_t
#endif
#define DATA_WIDTH 128
struct pcap_file_header {
u32 magic;
u16 version_major;
u16 version_minor;
s32 thiszone; /* gmt to local correction */
u32 sigfigs; /* accuracy of timL1 cache bytes userspaceestamps */
u32 snaplen; /* max length saved portion of each pkt */
u32 linktype; /* data link type (LINKTYPE_*) */
} __attribute__((packed));
struct pcap_pkthdr_ts {
le32 hts_sec;
le32 hts_usec;
} __attribute__((packed));
struct pcap_pkthdr {
struct pcap_pkthdr_ts ts; /* time stamp */
le32 caplen; /* length of portion present */
le32 length; /* length this packet (off wire) */
} __attribute__((packed));
void mem_copy(const void *buff, int length);
static P4TopRequestProxy *device = 0;
class P4TopIndication : public P4TopIndicationWrapper
{
public:
virtual void sonic_read_version_resp(uint32_t a) {
fprintf(stderr, "version %d\n", a);
}
virtual void cam_search_result(uint32_t a) {
fprintf(stderr, "cam search %x\n", a);
}
virtual void read_setram_result(uint64_t a) {
fprintf(stderr, "setram %lx\n", a);
}
virtual void match_table_resp(uint32_t a) {
fprintf(stderr, "match table");
}
virtual void matchTableResponse(uint32_t key, uint32_t value) {
fprintf(stderr, "GET : key = %u value = %u\n", key, value);
}
P4TopIndication(unsigned int id) : P4TopIndicationWrapper(id) {}
};
void mem_copy(const void *buff, int packet_size) {
int i, sop, eop;
uint64_t data[2];
int numBeats;
numBeats = packet_size / 8; // 16 bytes per beat for 128-bit datawidth;
if (packet_size % 8) numBeats++;
PRINT_INFO("nBeats=%d, packetSize=%d\n", numBeats, packet_size);
for (i=0; i<numBeats; i++) {
data[i%2] = *(static_cast<const uint64_t *>(buff) + i);
sop = (i/2 == 0);
eop = (i/2 == (numBeats-1)/2);
if (i%2) {
device->writePacketData(data, sop, eop);
PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop);
}
// last beat, padding with zero
if ((numBeats%2!=0) && (i==numBeats-1)) {
sop = (i/2 == 0) ? 1 : 0;
eop = 1;
data[1] = 0;
device->writePacketData(data, sop, eop);
PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop);
}
}
}
/**
* Send packet on quick_tx device
* @param qtx pointer to a quick_tx structure
* @param buffer full packet data starting at the ETH frame
* @param length length of packet (must be over 0)
* @return length of packet if it was successfully queued, QTX_E_EXIT if a critical error occurred
* and close needs to be called
*/
static inline int quick_tx_send_packet(const void* buffer, int length) {
assert(buffer);
assert(length > 0);
#ifdef EXTRA_DEBUG
printf("[quick_tx] Copying data from %p buffer, length = %d\n",
(buffer, length);
#endif
mem_copy(buffer, length);
return length;
}
bool read_pcap_file(char* filename, void** buffer, long *length) {
FILE *infile;
long length_read;
infile = fopen(filename, "r");
if(infile == NULL) {
printf("File does not exist!\n");
return false;
}
fseek(infile, 0L, SEEK_END);
*length = ftell(infile);
fseek(infile, 0L, SEEK_SET);
*buffer = (char*)calloc(*length, sizeof(char));
/* memory error */
if(*buffer == NULL) {
printf("Could not allocate %ld bytes of memory!\n", *length);
return false;
}
length_read = fread(*buffer, sizeof(char), *length, infile);
*length = length_read;
fclose(infile);
return true;
}
void test_setram(P4TopRequestProxy *device) {
device->writeSetRam(0x11, 0xff);
device->readSetRam(0x11);
}
void test_bcam(P4TopRequestProxy *device) {
device->camInsert(0x302, 0x24);
device->camSearch(0x24);
//device->camInsert(0x303, 0x24);
}
void test_matchtable(P4TopRequestProxy *device) {
device->matchTableRequest(10, 15, 1); //PUT(10,15)
device->matchTableRequest(10, 0, 0); //GET(10) should print k=10 v=15
device->matchTableRequest(10, 20, 2); //UPDATE(10,20)
device->matchTableRequest(29, 0, 3); //REMOVE(29)
device->matchTableRequest(10, 0, 0); //GET(10) should print k=10 v=20
device->matchTableRequest(10, 0, 3); //REMOVE(10)
device->matchTableRequest(10, 0, 0); //GET(10) should not print anything
device->matchTableRequest(10, 30, 2); //UPDATE(10,30) should not update
device->matchTableRequest(10, 0, 0); //GET(10) should not print anything
device->matchTableRequest(10, 45, 1); //PUT(10,45)
device->matchTableRequest(10, 0, 0); //GET(10) should print k=10 v=45
device->matchTableRequest(20, 15, 1); //PUT(20,15)
device->matchTableRequest(20, 0, 3); //REMOVE(20)
device->matchTableRequest(20, 0, 0); //GET(20) should not print anyting
device->matchTableRequest(20, 15, 1); //PUT(20,15)
device->matchTableRequest(20, 0, 3); //REMOVE(20)
device->matchTableRequest(20, 60, 1); //PUT(20,15)
device->matchTableRequest(20, 0, 0); //GET(20) should print k=20 v=60
}
int main(int argc, char **argv)
{
void *buffer;
long length;
struct pcap_pkthdr* pcap_hdr;
int i;
int loops = 1;
P4TopIndication echoIndication(IfcNames_P4TopIndicationH2S);
device = new P4TopRequestProxy(IfcNames_P4TopRequestS2H);
device->sonic_read_version();
// test_setram(device);
// test_matchtable(device);
test_bcam(device);
while(1) sleep(1);
fprintf(stderr, "Attempts to read pcap file %s\n", argv[1]);
if (!read_pcap_file(argv[1], &buffer, &length)) {
perror("Failed to read file!");
exit(-1);
}
for (i = 0; i < loops; i++) {
void* offset = static_cast<char *>(buffer) + sizeof(struct pcap_file_header);
while(offset < static_cast<char *>(buffer) + length) {
pcap_hdr = (struct pcap_pkthdr*) offset;
offset = static_cast<char *>(offset) + sizeof(struct pcap_pkthdr);
if ((quick_tx_send_packet((const void*)offset, pcap_hdr->caplen)) < 0) {
printf("An error occurred while trying to send a packet\n");
exit(-1);
}
offset = static_cast<char *>(offset) + pcap_hdr->caplen;
}
}
return 0;
}
<commit_msg>update testcase<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, 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 <assert.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include "P4TopIndication.h"
#include "P4TopRequest.h"
#include "GeneratedTypes.h"
#include "utils.h"
#ifndef le32
#define le32 int32_t
#endif
#ifndef u32
#define u32 u_int32_t
#endif
#ifndef u16
#define u16 u_int16_t
#endif
#ifndef s32
#define s32 int32_t
#endif
#define DATA_WIDTH 128
struct pcap_file_header {
u32 magic;
u16 version_major;
u16 version_minor;
s32 thiszone; /* gmt to local correction */
u32 sigfigs; /* accuracy of timL1 cache bytes userspaceestamps */
u32 snaplen; /* max length saved portion of each pkt */
u32 linktype; /* data link type (LINKTYPE_*) */
} __attribute__((packed));
struct pcap_pkthdr_ts {
le32 hts_sec;
le32 hts_usec;
} __attribute__((packed));
struct pcap_pkthdr {
struct pcap_pkthdr_ts ts; /* time stamp */
le32 caplen; /* length of portion present */
le32 length; /* length this packet (off wire) */
} __attribute__((packed));
void mem_copy(const void *buff, int length);
static P4TopRequestProxy *device = 0;
class P4TopIndication : public P4TopIndicationWrapper
{
public:
virtual void sonic_read_version_resp(uint32_t a) {
fprintf(stderr, "version %d\n", a);
}
virtual void cam_search_result(uint32_t a) {
fprintf(stderr, "cam search %x\n", a);
}
virtual void read_setram_result(uint64_t a) {
fprintf(stderr, "setram %lx\n", a);
}
virtual void match_table_resp(uint32_t a) {
fprintf(stderr, "match table");
}
virtual void matchTableResponse(uint32_t key, uint32_t value) {
fprintf(stderr, "GET : key = %u value = %u\n", key, value);
}
P4TopIndication(unsigned int id) : P4TopIndicationWrapper(id) {}
};
void mem_copy(const void *buff, int packet_size) {
int i, sop, eop;
uint64_t data[2];
int numBeats;
numBeats = packet_size / 8; // 16 bytes per beat for 128-bit datawidth;
if (packet_size % 8) numBeats++;
PRINT_INFO("nBeats=%d, packetSize=%d\n", numBeats, packet_size);
for (i=0; i<numBeats; i++) {
data[i%2] = *(static_cast<const uint64_t *>(buff) + i);
sop = (i/2 == 0);
eop = (i/2 == (numBeats-1)/2);
if (i%2) {
device->writePacketData(data, sop, eop);
PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop);
}
// last beat, padding with zero
if ((numBeats%2!=0) && (i==numBeats-1)) {
sop = (i/2 == 0) ? 1 : 0;
eop = 1;
data[1] = 0;
device->writePacketData(data, sop, eop);
PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop);
}
}
}
/**
* Send packet on quick_tx device
* @param qtx pointer to a quick_tx structure
* @param buffer full packet data starting at the ETH frame
* @param length length of packet (must be over 0)
* @return length of packet if it was successfully queued, QTX_E_EXIT if a critical error occurred
* and close needs to be called
*/
static inline int quick_tx_send_packet(const void* buffer, int length) {
assert(buffer);
assert(length > 0);
#ifdef EXTRA_DEBUG
printf("[quick_tx] Copying data from %p buffer, length = %d\n",
(buffer, length);
#endif
mem_copy(buffer, length);
return length;
}
bool read_pcap_file(char* filename, void** buffer, long *length) {
FILE *infile;
long length_read;
infile = fopen(filename, "r");
if(infile == NULL) {
printf("File does not exist!\n");
return false;
}
fseek(infile, 0L, SEEK_END);
*length = ftell(infile);
fseek(infile, 0L, SEEK_SET);
*buffer = (char*)calloc(*length, sizeof(char));
/* memory error */
if(*buffer == NULL) {
printf("Could not allocate %ld bytes of memory!\n", *length);
return false;
}
length_read = fread(*buffer, sizeof(char), *length, infile);
*length = length_read;
fclose(infile);
return true;
}
void test_setram(P4TopRequestProxy *device) {
device->writeSetRam(0x11, 0xff);
device->readSetRam(0x11);
}
void test_bcam(P4TopRequestProxy *device) {
fprintf(stderr, "Insert CAM\n");
device->camInsert(0x0, 0x0);
device->camInsert(0x1, 0x1);
device->camInsert(0x2, 0x2);
device->camInsert(0x3, 0x3);
device->camSearch(0x0);
device->camSearch(0x1);
device->camSearch(0x2);
device->camSearch(0x3);
//device->camInsert(0x303, 0x24);
}
void test_matchtable(P4TopRequestProxy *device) {
device->matchTableRequest(10, 15, 1); //PUT(10,15)
device->matchTableRequest(10, 0, 0); //GET(10) should print k=10 v=15
device->matchTableRequest(10, 20, 2); //UPDATE(10,20)
device->matchTableRequest(29, 0, 3); //REMOVE(29)
device->matchTableRequest(10, 0, 0); //GET(10) should print k=10 v=20
device->matchTableRequest(10, 0, 3); //REMOVE(10)
device->matchTableRequest(10, 0, 0); //GET(10) should not print anything
device->matchTableRequest(10, 30, 2); //UPDATE(10,30) should not update
device->matchTableRequest(10, 0, 0); //GET(10) should not print anything
device->matchTableRequest(10, 45, 1); //PUT(10,45)
device->matchTableRequest(10, 0, 0); //GET(10) should print k=10 v=45
device->matchTableRequest(20, 15, 1); //PUT(20,15)
device->matchTableRequest(20, 0, 3); //REMOVE(20)
device->matchTableRequest(20, 0, 0); //GET(20) should not print anyting
device->matchTableRequest(20, 15, 1); //PUT(20,15)
device->matchTableRequest(20, 0, 3); //REMOVE(20)
device->matchTableRequest(20, 60, 1); //PUT(20,15)
device->matchTableRequest(20, 0, 0); //GET(20) should print k=20 v=60
}
int main(int argc, char **argv)
{
void *buffer;
long length;
struct pcap_pkthdr* pcap_hdr;
int i;
int loops = 1;
P4TopIndication echoIndication(IfcNames_P4TopIndicationH2S);
device = new P4TopRequestProxy(IfcNames_P4TopRequestS2H);
device->sonic_read_version();
// test_setram(device);
// test_matchtable(device);
test_bcam(device);
while(1) sleep(1);
fprintf(stderr, "Attempts to read pcap file %s\n", argv[1]);
if (!read_pcap_file(argv[1], &buffer, &length)) {
perror("Failed to read file!");
exit(-1);
}
for (i = 0; i < loops; i++) {
void* offset = static_cast<char *>(buffer) + sizeof(struct pcap_file_header);
while(offset < static_cast<char *>(buffer) + length) {
pcap_hdr = (struct pcap_pkthdr*) offset;
offset = static_cast<char *>(offset) + sizeof(struct pcap_pkthdr);
if ((quick_tx_send_packet((const void*)offset, pcap_hdr->caplen)) < 0) {
printf("An error occurred while trying to send a packet\n");
exit(-1);
}
offset = static_cast<char *>(offset) + pcap_hdr->caplen;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "UICurve.h"
#include "../resource/ResManager.h"
using namespace Gear::Res;
UICurve::UICurve()
#ifdef USE_D2D_RENDER_MODE
:m_pColorBrush(nullptr)
, m_pStrokeStyle(nullptr)
#else
#endif
{
InitAttrMap();
InitEventMap();
InitAttrValuePatternMap();
InitAttrValueParserMap();
}
void UICurve::InitAttrMap()
{
ADD_ATTR("color", "FFFFFF")
ADD_ATTR("hline", "0")
ADD_ATTR("vline", "0")
ADD_ATTR("linewidth", "1")
ADD_ATTR("style", "solid")
ADD_ATTR("cap", "flat")
ADD_ATTR("dashes", "")//ֻstyle == customʱŻõ
}
void UICurve::InitEventMap()
{
}
void UICurve::InitAttrValuePatternMap()
{
ADD_ATTR_PATTERN("color", R_CHECK_COLOR_VALUE)
ADD_ATTR_PATTERN("hline", R_CHECK_BOOL)
ADD_ATTR_PATTERN("vline", R_CHECK_BOOL)
ADD_ATTR_PATTERN("linewidth", R_CHECK_INT)
}
void UICurve::InitAttrValueParserMap()
{
auto ParseDashes = [&](const string& sAttrName)->bool {
string dashes = m_attrMap[sAttrName];
if (dashes.empty()){
return false;
}
EraseSpace(dashes);
string item = "";
for (std::size_t i=0; i<dashes.length(); ++i)
{
char num = dashes[i];
if (num >= '0' && num <= '9')
{
item += num;
} else if(num == ','){
float dash = (float)atoi(item.c_str());
item = "";
m_dashesVec.push_back(dash);
continue;
} else {
ERR("ParseDashes error: illegal character");
return false;
}
}
if (!item.empty())
{
float dash = (float)atoi(item.c_str());
m_dashesVec.push_back(dash);
}
return true;
};
ADD_ATTR_PARSER("dashes", ParseDashes)
}
///////////////////////////////////////Direct2DȾģʽش///////////////////////////////////
#ifdef USE_D2D_RENDER_MODE
HRESULT UICurve::OnDrawImpl(ID2D1RenderTarget* pRenderTarget, const D2D1_RECT_F& rcWndPos)
{
HRESULT hr = S_OK;
D2D1_POINT_2F pA, pB;
int lineWidth = atoi(m_attrMap["linewidth"].c_str());
if (m_attrMap["hline"] == "1") {
pA.x = rcWndPos.left;
pA.y = rcWndPos.top;
pB.x = rcWndPos.right;
pB.y = rcWndPos.top;
pRenderTarget->DrawLine(pA, pB, m_pColorBrush, (FLOAT)lineWidth, m_pStrokeStyle);
} else if (m_attrMap["vline"] == "1") {
pA.x = rcWndPos.left;
pA.y = rcWndPos.top;
pB.x = rcWndPos.left;
pB.y = rcWndPos.bottom;
pRenderTarget->DrawLine(pA, pB, m_pColorBrush, (FLOAT)lineWidth, m_pStrokeStyle);
} else {//if(m_gdiPointsVer.size() > 0)
m_pointsVer.push_back(D2D1_POINT_2F{ 0, 0 });
m_pointsVer.push_back(D2D1_POINT_2F{ 15, 5 });
m_pointsVer.push_back(D2D1_POINT_2F{ 70, 9 });
m_pointsVer.push_back(D2D1_POINT_2F{ 11, 50 });
std::size_t length = m_pointsVer.size();
for (std::size_t i = 0; i < length - 1; ++i) {
pA = m_pointsVer[i];
pB = m_pointsVer[i + 1];
pRenderTarget->DrawLine(pA, pB, m_pColorBrush, (FLOAT)lineWidth, m_pStrokeStyle);
}
}
return hr;
}
HRESULT UICurve::CreateDeviceDependentResources(ID2D1RenderTarget* pRenderTarget)
{
if (m_pColorBrush) return S_OK;
if (!pRenderTarget) {
ERR("fatal error in CreateDeviceDependentResources, nullptr! OnDrawImpl will abort");
return S_FALSE;
}
D2D1::ColorF curveColor = ResManager::GetInstance().GetColorObject(m_attrMap["color"])->GetD2D1ColorF();
HRESULT hr = pRenderTarget->CreateSolidColorBrush(curveColor, &m_pColorBrush);
if (FAILED(hr)) {
ERR("fatal error in CreateSolidColorBrush, nullptr! hr:{}", hr);
return hr;
}
//Ĭsolid(ʵ)
D2D1_STROKE_STYLE_PROPERTIES prop = StrokeStyleProperties();
auto style = m_attrMap["style"];
auto cap = m_attrMap["cap"];
int length = 0;
FLOAT* floatVec = nullptr;
if (style == "solid") {
prop.dashStyle = D2D1_DASH_STYLE_SOLID;
}else if (style == "dash") {
prop.dashStyle = D2D1_DASH_STYLE_DASH;
} else if (style == "dot") {
prop.dashStyle = D2D1_DASH_STYLE_DOT;
} else if (style == "dashdot") {
prop.dashStyle = D2D1_DASH_STYLE_DASH_DOT;
} else if (style == "dashdotdot") {
prop.dashStyle = D2D1_DASH_STYLE_DASH_DOT_DOT;
} else if (style == "custom" && m_dashesVec.size() > 0) {
prop.dashStyle = D2D1_DASH_STYLE_CUSTOM;
length = m_dashesVec.size();
floatVec = new FLOAT[length];
for (auto i=0; i<length; ++i)
{
floatVec[i] = m_dashesVec[i];
}
}
if (cap == "flat") {
prop.dashCap = D2D1_CAP_STYLE_FLAT;
} else if (cap == "square") {
prop.dashCap = D2D1_CAP_STYLE_SQUARE;
} else if (cap == "round") {
prop.dashCap = D2D1_CAP_STYLE_ROUND;
} else if (cap == "triangle") {
prop.dashCap = D2D1_CAP_STYLE_TRIANGLE;
}
hr = RenderManager::m_pD2DFactory->CreateStrokeStyle(prop, floatVec, length,&m_pStrokeStyle);
if (FAILED(hr)) {
ERR("fatal error in m_pStrokeStyle, nullptr! hr:{}", hr);
return hr;
}
return hr;
}
HRESULT UICurve::DiscardDeviceDependentResources()
{
HRESULT hr = S_OK;
SafeRelease(&m_pColorBrush);
SafeRelease(&m_pStrokeStyle);
return hr;
}
/////////////////////////////////////////GDI+Ⱦģʽش/////////////////////////////////////
#else
HRESULT UICurve::OnDrawImpl(Graphics& graphics, const UIPos& rcWndPos)
{
auto SetStyle = [&](Pen& pen) {
auto style = m_attrMap["style"];
if (style == "solid") {
pen.SetDashStyle(DashStyleSolid);
} else if (style == "dash") {
pen.SetDashStyle(DashStyleDash);
} else if (style == "dot") {
pen.SetDashStyle(DashStyleDot);
} else if (style == "dashdot") {
pen.SetDashStyle(DashStyleDashDot);
} else if (style == "dashdotdot") {
pen.SetDashStyle(DashStyleDashDotDot);
} else if (style == "custom") {
pen.SetDashStyle(DashStyleCustom);
int length = (int)m_dashesVec.size();
REAL* floatVec = new REAL[length];
for (auto i = 0; i < length; ++i)
{
floatVec[i] = m_dashesVec[i];
}
pen.SetDashPattern(floatVec, length);
}
};
auto SetCap = [&](Pen& pen) {
auto cap = m_attrMap["cap"];
if (cap == "flat") {
pen.SetDashCap(Gdiplus::DashCapFlat);
} else if (cap == "round") {
pen.SetDashCap(Gdiplus::DashCapRound);
} else if (cap == "triangle") {
pen.SetDashCap(Gdiplus::DashCapTriangle);
}
};
ResColor* resColorObj = ResManager::GetInstance().GetColorObject(m_attrMap["color"]);
Color color = resColorObj->GetGdiplusColor();
int lineWidth = atoi(m_attrMap["linewidth"].c_str());
Gdiplus::Pen pen(color, (REAL)lineWidth);
SetStyle(pen);
SetCap(pen);
Status status = GenericError;
if (m_attrMap["hline"] == "1"){
Gdiplus::Point pA(rcWndPos.left, rcWndPos.top);
Gdiplus::Point pB(rcWndPos.left + rcWndPos.width, rcWndPos.top);
status = graphics.DrawLine(&pen, pA, pB);
} else if(m_attrMap["vline"] == "1") {
Gdiplus::Point pA(rcWndPos.left, rcWndPos.top);
Gdiplus::Point pB(rcWndPos.left, rcWndPos.top + rcWndPos.height);
status = graphics.DrawLine(&pen, pA, pB);
} else {//if(m_gdiPointsVer.size() > 0)
m_pointsVer.push_back(PointF(0, 0));
m_pointsVer.push_back(PointF(15, 5));
m_pointsVer.push_back(PointF(70, 9));
m_pointsVer.push_back(PointF(11, 50));
std::size_t length = m_pointsVer.size();
Gdiplus::PointF* points = new Gdiplus::PointF[length];
for (std::size_t i=0; i<length; ++i){
points[i] = m_pointsVer[i];
}
status = graphics.DrawLines(&pen, points, length);
}
return status == Ok ? S_OK : S_FALSE;
}
#endif<commit_msg>去掉测试代码<commit_after>#include "stdafx.h"
#include "UICurve.h"
#include "../resource/ResManager.h"
using namespace Gear::Res;
UICurve::UICurve()
#ifdef USE_D2D_RENDER_MODE
:m_pColorBrush(nullptr)
, m_pStrokeStyle(nullptr)
#else
#endif
{
InitAttrMap();
InitEventMap();
InitAttrValuePatternMap();
InitAttrValueParserMap();
}
void UICurve::InitAttrMap()
{
ADD_ATTR("color", "FFFFFF")
ADD_ATTR("hline", "0")
ADD_ATTR("vline", "0")
ADD_ATTR("linewidth", "1")
ADD_ATTR("style", "solid")
ADD_ATTR("cap", "flat")
ADD_ATTR("dashes", "")//ֻstyle == customʱŻõ
}
void UICurve::InitEventMap()
{
}
void UICurve::InitAttrValuePatternMap()
{
ADD_ATTR_PATTERN("color", R_CHECK_COLOR_VALUE)
ADD_ATTR_PATTERN("hline", R_CHECK_BOOL)
ADD_ATTR_PATTERN("vline", R_CHECK_BOOL)
ADD_ATTR_PATTERN("linewidth", R_CHECK_INT)
}
void UICurve::InitAttrValueParserMap()
{
auto ParseDashes = [&](const string& sAttrName)->bool {
string dashes = m_attrMap[sAttrName];
if (dashes.empty()){
return false;
}
EraseSpace(dashes);
string item = "";
for (std::size_t i=0; i<dashes.length(); ++i)
{
char num = dashes[i];
if (num >= '0' && num <= '9')
{
item += num;
} else if(num == ','){
float dash = (float)atoi(item.c_str());
item = "";
m_dashesVec.push_back(dash);
continue;
} else {
ERR("ParseDashes error: illegal character");
return false;
}
}
if (!item.empty())
{
float dash = (float)atoi(item.c_str());
m_dashesVec.push_back(dash);
}
return true;
};
ADD_ATTR_PARSER("dashes", ParseDashes)
}
///////////////////////////////////////Direct2DȾģʽش///////////////////////////////////
#ifdef USE_D2D_RENDER_MODE
HRESULT UICurve::OnDrawImpl(ID2D1RenderTarget* pRenderTarget, const D2D1_RECT_F& rcWndPos)
{
HRESULT hr = S_OK;
D2D1_POINT_2F pA, pB;
int lineWidth = atoi(m_attrMap["linewidth"].c_str());
if (m_attrMap["hline"] == "1") {
pA.x = rcWndPos.left;
pA.y = rcWndPos.top;
pB.x = rcWndPos.right;
pB.y = rcWndPos.top;
pRenderTarget->DrawLine(pA, pB, m_pColorBrush, (FLOAT)lineWidth, m_pStrokeStyle);
} else if (m_attrMap["vline"] == "1") {
pA.x = rcWndPos.left;
pA.y = rcWndPos.top;
pB.x = rcWndPos.left;
pB.y = rcWndPos.bottom;
pRenderTarget->DrawLine(pA, pB, m_pColorBrush, (FLOAT)lineWidth, m_pStrokeStyle);
} else if (m_pointsVer.size() > 0) {//
std::size_t length = m_pointsVer.size();
for (std::size_t i = 0; i < length - 1; ++i) {
pA = m_pointsVer[i];
pB = m_pointsVer[i + 1];
pRenderTarget->DrawLine(pA, pB, m_pColorBrush, (FLOAT)lineWidth, m_pStrokeStyle);
}
}
return hr;
}
HRESULT UICurve::CreateDeviceDependentResources(ID2D1RenderTarget* pRenderTarget)
{
if (m_pColorBrush) return S_OK;
if (!pRenderTarget) {
ERR("fatal error in CreateDeviceDependentResources, nullptr! OnDrawImpl will abort");
return S_FALSE;
}
D2D1::ColorF curveColor = ResManager::GetInstance().GetColorObject(m_attrMap["color"])->GetD2D1ColorF();
HRESULT hr = pRenderTarget->CreateSolidColorBrush(curveColor, &m_pColorBrush);
if (FAILED(hr)) {
ERR("fatal error in CreateSolidColorBrush, nullptr! hr:{}", hr);
return hr;
}
//Ĭsolid(ʵ)
D2D1_STROKE_STYLE_PROPERTIES prop = StrokeStyleProperties();
auto style = m_attrMap["style"];
auto cap = m_attrMap["cap"];
int length = 0;
FLOAT* floatVec = nullptr;
if (style == "solid") {
prop.dashStyle = D2D1_DASH_STYLE_SOLID;
}else if (style == "dash") {
prop.dashStyle = D2D1_DASH_STYLE_DASH;
} else if (style == "dot") {
prop.dashStyle = D2D1_DASH_STYLE_DOT;
} else if (style == "dashdot") {
prop.dashStyle = D2D1_DASH_STYLE_DASH_DOT;
} else if (style == "dashdotdot") {
prop.dashStyle = D2D1_DASH_STYLE_DASH_DOT_DOT;
} else if (style == "custom" && m_dashesVec.size() > 0) {
prop.dashStyle = D2D1_DASH_STYLE_CUSTOM;
length = m_dashesVec.size();
floatVec = new FLOAT[length];
for (auto i=0; i<length; ++i)
{
floatVec[i] = m_dashesVec[i];
}
}
if (cap == "flat") {
prop.dashCap = D2D1_CAP_STYLE_FLAT;
} else if (cap == "square") {
prop.dashCap = D2D1_CAP_STYLE_SQUARE;
} else if (cap == "round") {
prop.dashCap = D2D1_CAP_STYLE_ROUND;
} else if (cap == "triangle") {
prop.dashCap = D2D1_CAP_STYLE_TRIANGLE;
}
hr = RenderManager::m_pD2DFactory->CreateStrokeStyle(prop, floatVec, length,&m_pStrokeStyle);
if (FAILED(hr)) {
ERR("fatal error in m_pStrokeStyle, nullptr! hr:{}", hr);
return hr;
}
return hr;
}
HRESULT UICurve::DiscardDeviceDependentResources()
{
HRESULT hr = S_OK;
SafeRelease(&m_pColorBrush);
SafeRelease(&m_pStrokeStyle);
return hr;
}
/////////////////////////////////////////GDI+Ⱦģʽش/////////////////////////////////////
#else
HRESULT UICurve::OnDrawImpl(Graphics& graphics, const UIPos& rcWndPos)
{
auto SetStyle = [&](Pen& pen) {
auto style = m_attrMap["style"];
if (style == "solid") {
pen.SetDashStyle(DashStyleSolid);
} else if (style == "dash") {
pen.SetDashStyle(DashStyleDash);
} else if (style == "dot") {
pen.SetDashStyle(DashStyleDot);
} else if (style == "dashdot") {
pen.SetDashStyle(DashStyleDashDot);
} else if (style == "dashdotdot") {
pen.SetDashStyle(DashStyleDashDotDot);
} else if (style == "custom") {
pen.SetDashStyle(DashStyleCustom);
int length = (int)m_dashesVec.size();
REAL* floatVec = new REAL[length];
for (auto i = 0; i < length; ++i)
{
floatVec[i] = m_dashesVec[i];
}
pen.SetDashPattern(floatVec, length);
}
};
auto SetCap = [&](Pen& pen) {
auto cap = m_attrMap["cap"];
if (cap == "flat") {
pen.SetDashCap(Gdiplus::DashCapFlat);
} else if (cap == "round") {
pen.SetDashCap(Gdiplus::DashCapRound);
} else if (cap == "triangle") {
pen.SetDashCap(Gdiplus::DashCapTriangle);
}
};
ResColor* resColorObj = ResManager::GetInstance().GetColorObject(m_attrMap["color"]);
Color color = resColorObj->GetGdiplusColor();
int lineWidth = atoi(m_attrMap["linewidth"].c_str());
Gdiplus::Pen pen(color, (REAL)lineWidth);
SetStyle(pen);
SetCap(pen);
Status status = GenericError;
if (m_attrMap["hline"] == "1"){
Gdiplus::Point pA(rcWndPos.left, rcWndPos.top);
Gdiplus::Point pB(rcWndPos.left + rcWndPos.width, rcWndPos.top);
status = graphics.DrawLine(&pen, pA, pB);
} else if(m_attrMap["vline"] == "1") {
Gdiplus::Point pA(rcWndPos.left, rcWndPos.top);
Gdiplus::Point pB(rcWndPos.left, rcWndPos.top + rcWndPos.height);
status = graphics.DrawLine(&pen, pA, pB);
} else if (m_pointsVer.size() > 0) {//
std::size_t length = m_pointsVer.size();
Gdiplus::PointF* points = new Gdiplus::PointF[length];
for (std::size_t i=0; i<length; ++i){
points[i] = m_pointsVer[i];
}
status = graphics.DrawLines(&pen, points, length);
}
return status == Ok ? S_OK : S_FALSE;
}
#endif<|endoftext|>
|
<commit_before>#ifndef DATAMANAGER_H
#define DATAMANAGER_H
#include "StdIncl.hpp"
#include "types/Data.hpp"
#include "InvalidConfigException.hpp"
namespace uipf{
using namespace std;
// Provides and controls access to Parameters, Input and Outputdata
class DataManager
{
public:
DataManager(std::map < std::string, Data::ptr& >& input, std::map < std::string,std::string >& params, std::map < std::string, Data::ptr >& output)
:input_(input),params_(params),output_(output)
{}
~DataManager(){}
//returns a typesafe readonly smartpointer to input/output data by name if it is available
template <typename T>
const T* getInputData( const std::string& strName) const;
//returns a typesafe smartpointer to input/output data by name if it is available
template <typename T>
T* getOutputData( const std::string& strName) const;
//returns a typesafe smartpointer to input/output data by name if it is available
template <typename T>
void setOutputData( const std::string& strName, T*) ;
//returns a typesafe parameter by name if it is available. otherwise a defaultValue is used
template <typename T>
T getParam(const std::string& strName, T defaultValue) const;
//print given parameters
void listParams( ) const;
private:
std::map < std::string, Data::ptr& >& input_;
std::map < std::string, std::string >& params_;
std::map < std::string, Data::ptr >& output_;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//templates need to be implemented in headers
template <typename T>
const T* DataManager::getInputData( const std::string& strName) const
{
if (input_.find(strName) != input_.end())
{
//do downcasting..
Data::ptr& ptr = input_.find(strName)->second;
return dynamic_cast<T*>(ptr.get());
}
else
{
throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!"));
}
}
template <typename T>
T* DataManager::getOutputData( const std::string& strName) const
{
if (output_.find(strName) != output_.end())
{
//do downcasting..
Data::ptr& ptr = output_.find(strName)->second;
return dynamic_cast<T*>(ptr.get());
}
else
{
throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!"));
}
}
template <typename T>
void DataManager::setOutputData( const std::string& strName, T* outputData)
{
output_.insert (pair < string, Data::ptr >(strName, typename T::ptr(outputData)));
}
//2DO other type specialisations e.g. float with atof() etc.
template <typename T>
T DataManager::getParam( const std::string& strName, T defaultValue) const
{
if (params_.find(strName) != params_.end())
{
return static_cast<T>(params_[strName]);
}
else
{
return defaultValue;
}
}
template <>
inline int DataManager::getParam( const std::string& strName, int defaultValue) const
{
if (params_.find(strName) != params_.end())
{
return atoi(params_[strName].c_str());
}
else
{
return defaultValue;
}
}
template <>
inline float DataManager::getParam(const std::string& strName, float defaultValue) const
{
if (params_.find(strName) != params_.end())
{
return atof(params_[strName].c_str());
}
else
{
return defaultValue;
}
}
template <>
inline double DataManager::getParam( const std::string& strName, double defaultValue) const
{
if (params_.find(strName) != params_.end())
{
return atof(params_[strName].c_str());
}
else
{
return defaultValue;
}
}
} //namespace
#endif // DATAMANAGER_H
<commit_msg>parsing for bools from yaml<commit_after>#ifndef DATAMANAGER_H
#define DATAMANAGER_H
#include "StdIncl.hpp"
#include "types/Data.hpp"
#include "InvalidConfigException.hpp"
#include "Utils.hpp"
namespace uipf{
using namespace std;
// Provides and controls access to Parameters, Input and Outputdata
class DataManager
{
public:
DataManager(std::map < std::string, Data::ptr& >& input, std::map < std::string,std::string >& params, std::map < std::string, Data::ptr >& output)
:input_(input),params_(params),output_(output)
{}
~DataManager(){}
//returns a typesafe readonly smartpointer to input/output data by name if it is available
template <typename T>
const T* getInputData( const std::string& strName) const;
//returns a typesafe smartpointer to input/output data by name if it is available
template <typename T>
T* getOutputData( const std::string& strName) const;
//returns a typesafe smartpointer to input/output data by name if it is available
template <typename T>
void setOutputData( const std::string& strName, T*) ;
//returns a typesafe parameter by name if it is available. otherwise a defaultValue is used
template <typename T>
T getParam(const std::string& strName, T defaultValue) const;
//print given parameters
void listParams( ) const;
private:
std::map < std::string, Data::ptr& >& input_;
std::map < std::string, std::string >& params_;
std::map < std::string, Data::ptr >& output_;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//templates need to be implemented in headers
template <typename T>
const T* DataManager::getInputData( const std::string& strName) const
{
if (input_.find(strName) != input_.end())
{
//do downcasting..
Data::ptr& ptr = input_.find(strName)->second;
return dynamic_cast<T*>(ptr.get());
}
else
{
throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!"));
}
}
template <typename T>
T* DataManager::getOutputData( const std::string& strName) const
{
if (output_.find(strName) != output_.end())
{
//do downcasting..
Data::ptr& ptr = output_.find(strName)->second;
return dynamic_cast<T*>(ptr.get());
}
else
{
throw InvalidConfigException(std::string("input data '") + strName + std::string("' not found!"));
}
}
template <typename T>
void DataManager::setOutputData( const std::string& strName, T* outputData)
{
output_.insert (pair < string, Data::ptr >(strName, typename T::ptr(outputData)));
}
//2DO other type specialisations e.g. float with atof() etc.
template <typename T>
T DataManager::getParam( const std::string& strName, T defaultValue) const
{
if (params_.find(strName) != params_.end())
{
return static_cast<T>(params_[strName]);
}
else
{
return defaultValue;
}
}
template <>
inline int DataManager::getParam( const std::string& strName, int defaultValue) const
{
if (params_.find(strName) != params_.end())
{
return atoi(params_[strName].c_str());
}
else
{
return defaultValue;
}
}
template <>
inline float DataManager::getParam(const std::string& strName, float defaultValue) const
{
if (params_.find(strName) != params_.end())
{
return atof(params_[strName].c_str());
}
else
{
return defaultValue;
}
}
template <>
inline double DataManager::getParam( const std::string& strName, double defaultValue) const
{
if (params_.find(strName) != params_.end())
{
return atof(params_[strName].c_str());
}
else
{
return defaultValue;
}
}
template <>
inline bool DataManager::getParam( const std::string& strName, bool defaultValue) const
{
if (params_.find(strName) != params_.end())
{
return (utils::toLower(params_[strName]).compare("true")==0);
}
else
{
return defaultValue;
}
}
} //namespace
#endif // DATAMANAGER_H
<|endoftext|>
|
<commit_before>// Copyright (c) 2021 The Orbit 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 "SessionSetup/RetrieveInstancesWidget.h"
#include <QCoreApplication>
#include <QLineEdit>
#include <QMessageBox>
#include <QObject>
#include <QPointer>
#include <QPushButton>
#include <QSettings>
#include <QVariant>
#include <memory>
#include <optional>
#include "MetricsUploader/ScopedMetric.h"
#include "MetricsUploader/orbit_log_event.pb.h"
#include "OrbitBase/Result.h"
#include "OrbitGgp/Client.h"
#include "QtUtils/MainThreadExecutorImpl.h"
#include "SessionSetup/PersistentStorage.h"
#include "SessionSetup/RetrieveInstances.h"
#include "ui_RetrieveInstancesWidget.h"
namespace orbit_session_setup {
using orbit_ggp::Instance;
using orbit_ggp::Project;
using LoadProjectsAndInstancesResult = RetrieveInstances::LoadProjectsAndInstancesResult;
using InstanceListScope = orbit_ggp::Client::InstanceListScope;
using orbit_metrics_uploader::OrbitLogEvent;
using orbit_metrics_uploader::ScopedMetric;
RetrieveInstancesWidget::~RetrieveInstancesWidget() = default;
RetrieveInstancesWidget::RetrieveInstancesWidget(QWidget* parent)
: QWidget(parent),
ui_(std::make_unique<Ui::RetrieveInstancesWidget>()),
main_thread_executor_(orbit_qt_utils::MainThreadExecutorImpl::Create()),
s_idle_(&state_machine_),
s_loading_(&state_machine_),
s_initial_loading_failed_(&state_machine_) {
ui_->setupUi(this);
SetupStateMachine();
QObject::connect(ui_->filterLineEdit, &QLineEdit::textChanged, this,
&RetrieveInstancesWidget::FilterTextChanged);
QObject::connect(ui_->reloadButton, &QPushButton::clicked, this,
&RetrieveInstancesWidget::OnReloadButtonClicked);
QObject::connect(ui_->projectComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
&RetrieveInstancesWidget::OnProjectComboBoxCurrentIndexChanged);
QObject::connect(ui_->allCheckBox, &QCheckBox::clicked, this,
&RetrieveInstancesWidget::OnAllCheckboxClicked);
}
void RetrieveInstancesWidget::SetupStateMachine() {
state_machine_.setGlobalRestorePolicy(QStateMachine::RestoreProperties);
s_idle_.assignProperty(ui_->projectComboBox, "enabled", true);
s_idle_.assignProperty(ui_->filterLineEdit, "enabled", true);
s_idle_.assignProperty(ui_->allCheckBox, "enabled", true);
s_idle_.assignProperty(ui_->reloadButton, "enabled", true);
s_idle_.addTransition(this, &RetrieveInstancesWidget::LoadingStarted, &s_loading_);
s_loading_.assignProperty(ui_->projectComboBox, "enabled", false);
s_loading_.assignProperty(ui_->filterLineEdit, "enabled", false);
s_loading_.assignProperty(ui_->allCheckBox, "enabled", false);
s_loading_.assignProperty(ui_->reloadButton, "enabled", false);
s_loading_.addTransition(this, &RetrieveInstancesWidget::LoadingSuccessful, &s_idle_);
s_loading_.addTransition(this, &RetrieveInstancesWidget::LoadingFailed, &s_idle_);
s_loading_.addTransition(this, &RetrieveInstancesWidget::InitialLoadingFailed,
&s_initial_loading_failed_);
s_initial_loading_failed_.assignProperty(ui_->projectComboBox, "enabled", false);
s_initial_loading_failed_.assignProperty(ui_->filterLineEdit, "enabled", false);
s_initial_loading_failed_.assignProperty(ui_->allCheckBox, "enabled", false);
s_initial_loading_failed_.assignProperty(ui_->reloadButton, "enabled", true);
s_initial_loading_failed_.addTransition(this, &RetrieveInstancesWidget::LoadingStarted,
&s_loading_);
}
void RetrieveInstancesWidget::Start() {
ORBIT_CHECK(retrieve_instances_ != nullptr);
state_machine_.setInitialState(&s_loading_);
state_machine_.start();
ui_->allCheckBox->setChecked(LoadInstancesScopeFromPersistentStorage() ==
InstanceListScope::kAllReservedInstances);
InitialLoad(LoadLastSelectedProjectFromPersistentStorage());
}
InstanceListScope RetrieveInstancesWidget::GetSelectedInstanceListScope() const {
return ui_->allCheckBox->isChecked() ? InstanceListScope::kAllReservedInstances
: InstanceListScope::kOnlyOwnInstances;
}
void RetrieveInstancesWidget::InitialLoad(const std::optional<Project>& remembered_project) {
ORBIT_CHECK(ui_->projectComboBox->count() == 0);
emit LoadingStarted();
ScopedMetric metric{metrics_uploader_, OrbitLogEvent::ORBIT_INSTANCES_INITIAL_LOAD};
retrieve_instances_->LoadProjectsAndInstances(remembered_project, GetSelectedInstanceListScope())
.Then(main_thread_executor_.get(),
// The metric gets its own future continuation, so the time measured is only the
// time that the call took.
[metric = std::move(metric)](auto loading_result) mutable {
if (loading_result.has_error()) metric.SetStatusCode(OrbitLogEvent::INTERNAL_ERROR);
return loading_result;
})
.Then(main_thread_executor_.get(),
[this](ErrorMessageOr<LoadProjectsAndInstancesResult> loading_result) {
// `this` still exists when this lambda is executed. This is enforced, because
// main_thread_executor_ is a member of `this`. When `this` is destroyed,
// main_thread_executor_ is destroyed and the lambda is not executed. Check
// Future::Then for details about the lambda not being executed.
if (loading_result.has_error()) {
emit InitialLoadingFailed();
OnInstancesLoadingReturned(loading_result.error());
return;
}
OnInitialLoadingReturnedSuccess(loading_result.value());
});
}
void RetrieveInstancesWidget::OnInitialLoadingReturnedSuccess(
LoadProjectsAndInstancesResult initial_load_result) {
ORBIT_CHECK(ui_->projectComboBox->count() == 0);
// From here on the projectComboBox is filled. To not trigger currentIndexChanged signals, the
// signals of projectComboBox are blocked until the end of this function.
ui_->projectComboBox->blockSignals(true);
QString default_project_text =
QString("Default Project (%1)").arg(initial_load_result.default_project.display_name);
ui_->projectComboBox->addItem(default_project_text);
QVector<Project>& projects{initial_load_result.projects};
std::sort(projects.begin(), projects.end(),
[](const Project& p1, const Project& p2) { return p1.display_name < p2.display_name; });
for (const Project& project : initial_load_result.projects) {
QString text = project.display_name;
if (project == initial_load_result.default_project) {
text.append(" (default)");
}
ui_->projectComboBox->addItem(text, QVariant::fromValue(project));
// initial_load_result.instances is the list for a specific project, which is
// initial_load_result.project_of_instances. (This can be different than the remembered project
// which was used in InitialLoad.) Since the initial_load_result.instances will be shown by
// ConnectToStadiaWidget, the combobox should have the project selected that belongs to this
// list. This selection is done here.
if (project == initial_load_result.project_of_instances) {
// last added item
ui_->projectComboBox->setCurrentIndex(ui_->projectComboBox->count() - 1);
}
}
ui_->projectComboBox->blockSignals(false);
OnInstancesLoadingReturned(initial_load_result.instances);
}
void RetrieveInstancesWidget::OnInstancesLoadingReturned(
const ErrorMessageOr<QVector<Instance>>& loading_result) {
if (loading_result.has_error()) {
ORBIT_ERROR("instance loading returned with error: %s", loading_result.error().message());
QMessageBox::critical(this, QCoreApplication::applicationName(),
QString::fromStdString(loading_result.error().message()));
emit LoadingFailed();
return;
}
emit LoadingSuccessful(loading_result.value());
}
void RetrieveInstancesWidget::OnReloadButtonClicked() {
// Initial loading failed
if (ui_->projectComboBox->count() == 0) {
InitialLoad(std::nullopt);
return;
}
std::optional<Project> selected_project;
if (ui_->projectComboBox->currentData().canConvert<Project>()) {
selected_project = ui_->projectComboBox->currentData().value<Project>();
}
emit LoadingStarted();
retrieve_instances_->LoadInstancesWithoutCache(selected_project, GetSelectedInstanceListScope())
.Then(main_thread_executor_.get(),
[this](const ErrorMessageOr<QVector<Instance>>& load_result) {
// `this` still exists when this lambda is executed. This is enforced, because
// main_thread_executor_ is a member of `this`. When `this` is destroyed,
// main_thread_executor_ is destroyed and the lambda is not executed. Check
// Future::Then for details about the lambda not being executed.
OnInstancesLoadingReturned(load_result);
});
}
std::optional<orbit_ggp::Project> RetrieveInstancesWidget::GetSelectedProject() const {
std::optional<Project> project;
if (ui_->projectComboBox->currentData().canConvert<Project>()) {
project = ui_->projectComboBox->currentData().value<Project>();
}
return project;
}
void RetrieveInstancesWidget::OnProjectComboBoxCurrentIndexChanged() {
std::optional<Project> selected_project = GetSelectedProject();
if (metrics_uploader_ != nullptr) {
metrics_uploader_->SendLogEvent(OrbitLogEvent::ORBIT_PROJECT_CHANGED);
}
emit LoadingStarted();
retrieve_instances_->LoadInstances(selected_project, GetSelectedInstanceListScope())
.Then(main_thread_executor_.get(),
[this, selected_project](const ErrorMessageOr<QVector<Instance>>& load_result) {
// `this` still exists when this lambda is executed. This is enforced, because
// main_thread_executor_ is a member of `this`. When `this` is destroyed,
// main_thread_executor_ is destroyed and the lambda is not executed. Check
// Future::Then for details about the lambda not being executed.
if (load_result.has_value()) {
SaveProjectToPersistentStorage(selected_project);
} else {
std::optional<Project> previously_selected =
LoadLastSelectedProjectFromPersistentStorage();
// The upcoming call to setCurrentIndex is not user action, but only resetting to
// previous values. Hence the signals are temporarily blocked.
ui_->projectComboBox->blockSignals(true);
if (previously_selected == std::nullopt) {
// If previously_selected is nullopt, that means QSettings contained either the
// default project or nothing (in which case selecting the default project is also
// correct). The first entry of the combobox (index 0) is the default project.
ui_->projectComboBox->setCurrentIndex(0);
} else {
int index = ui_->projectComboBox->findData(
QVariant::fromValue(previously_selected.value()));
ui_->projectComboBox->setCurrentIndex(index);
}
ui_->projectComboBox->blockSignals(false);
}
OnInstancesLoadingReturned(load_result);
});
}
void RetrieveInstancesWidget::OnAllCheckboxClicked() {
InstanceListScope selected_scope = GetSelectedInstanceListScope();
emit LoadingStarted();
retrieve_instances_->LoadInstances(GetSelectedProject(), selected_scope)
.Then(main_thread_executor_.get(),
[widget = QPointer<RetrieveInstancesWidget>(this),
selected_scope](const ErrorMessageOr<QVector<Instance>>& load_result) {
if (widget == nullptr) return;
if (load_result.has_value()) {
SaveInstancesScopeToPersistentStorage(selected_scope);
} else {
// reset to the value before (value saved in PersistenStorage)
widget->ui_->allCheckBox->setChecked(LoadInstancesScopeFromPersistentStorage() ==
InstanceListScope::kAllReservedInstances);
}
widget->OnInstancesLoadingReturned(load_result);
});
}
} // namespace orbit_session_setup<commit_msg>Fix use of wrong vector in RetrieveInstancesWidget (#3942)<commit_after>// Copyright (c) 2021 The Orbit 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 "SessionSetup/RetrieveInstancesWidget.h"
#include <QCoreApplication>
#include <QLineEdit>
#include <QMessageBox>
#include <QObject>
#include <QPointer>
#include <QPushButton>
#include <QSettings>
#include <QVariant>
#include <memory>
#include <optional>
#include "MetricsUploader/ScopedMetric.h"
#include "MetricsUploader/orbit_log_event.pb.h"
#include "OrbitBase/Result.h"
#include "OrbitGgp/Client.h"
#include "QtUtils/MainThreadExecutorImpl.h"
#include "SessionSetup/PersistentStorage.h"
#include "SessionSetup/RetrieveInstances.h"
#include "ui_RetrieveInstancesWidget.h"
namespace orbit_session_setup {
using orbit_ggp::Instance;
using orbit_ggp::Project;
using LoadProjectsAndInstancesResult = RetrieveInstances::LoadProjectsAndInstancesResult;
using InstanceListScope = orbit_ggp::Client::InstanceListScope;
using orbit_metrics_uploader::OrbitLogEvent;
using orbit_metrics_uploader::ScopedMetric;
RetrieveInstancesWidget::~RetrieveInstancesWidget() = default;
RetrieveInstancesWidget::RetrieveInstancesWidget(QWidget* parent)
: QWidget(parent),
ui_(std::make_unique<Ui::RetrieveInstancesWidget>()),
main_thread_executor_(orbit_qt_utils::MainThreadExecutorImpl::Create()),
s_idle_(&state_machine_),
s_loading_(&state_machine_),
s_initial_loading_failed_(&state_machine_) {
ui_->setupUi(this);
SetupStateMachine();
QObject::connect(ui_->filterLineEdit, &QLineEdit::textChanged, this,
&RetrieveInstancesWidget::FilterTextChanged);
QObject::connect(ui_->reloadButton, &QPushButton::clicked, this,
&RetrieveInstancesWidget::OnReloadButtonClicked);
QObject::connect(ui_->projectComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
&RetrieveInstancesWidget::OnProjectComboBoxCurrentIndexChanged);
QObject::connect(ui_->allCheckBox, &QCheckBox::clicked, this,
&RetrieveInstancesWidget::OnAllCheckboxClicked);
}
void RetrieveInstancesWidget::SetupStateMachine() {
state_machine_.setGlobalRestorePolicy(QStateMachine::RestoreProperties);
s_idle_.assignProperty(ui_->projectComboBox, "enabled", true);
s_idle_.assignProperty(ui_->filterLineEdit, "enabled", true);
s_idle_.assignProperty(ui_->allCheckBox, "enabled", true);
s_idle_.assignProperty(ui_->reloadButton, "enabled", true);
s_idle_.addTransition(this, &RetrieveInstancesWidget::LoadingStarted, &s_loading_);
s_loading_.assignProperty(ui_->projectComboBox, "enabled", false);
s_loading_.assignProperty(ui_->filterLineEdit, "enabled", false);
s_loading_.assignProperty(ui_->allCheckBox, "enabled", false);
s_loading_.assignProperty(ui_->reloadButton, "enabled", false);
s_loading_.addTransition(this, &RetrieveInstancesWidget::LoadingSuccessful, &s_idle_);
s_loading_.addTransition(this, &RetrieveInstancesWidget::LoadingFailed, &s_idle_);
s_loading_.addTransition(this, &RetrieveInstancesWidget::InitialLoadingFailed,
&s_initial_loading_failed_);
s_initial_loading_failed_.assignProperty(ui_->projectComboBox, "enabled", false);
s_initial_loading_failed_.assignProperty(ui_->filterLineEdit, "enabled", false);
s_initial_loading_failed_.assignProperty(ui_->allCheckBox, "enabled", false);
s_initial_loading_failed_.assignProperty(ui_->reloadButton, "enabled", true);
s_initial_loading_failed_.addTransition(this, &RetrieveInstancesWidget::LoadingStarted,
&s_loading_);
}
void RetrieveInstancesWidget::Start() {
ORBIT_CHECK(retrieve_instances_ != nullptr);
state_machine_.setInitialState(&s_loading_);
state_machine_.start();
ui_->allCheckBox->setChecked(LoadInstancesScopeFromPersistentStorage() ==
InstanceListScope::kAllReservedInstances);
InitialLoad(LoadLastSelectedProjectFromPersistentStorage());
}
InstanceListScope RetrieveInstancesWidget::GetSelectedInstanceListScope() const {
return ui_->allCheckBox->isChecked() ? InstanceListScope::kAllReservedInstances
: InstanceListScope::kOnlyOwnInstances;
}
void RetrieveInstancesWidget::InitialLoad(const std::optional<Project>& remembered_project) {
ORBIT_CHECK(ui_->projectComboBox->count() == 0);
emit LoadingStarted();
ScopedMetric metric{metrics_uploader_, OrbitLogEvent::ORBIT_INSTANCES_INITIAL_LOAD};
retrieve_instances_->LoadProjectsAndInstances(remembered_project, GetSelectedInstanceListScope())
.Then(main_thread_executor_.get(),
// The metric gets its own future continuation, so the time measured is only the
// time that the call took.
[metric = std::move(metric)](auto loading_result) mutable {
if (loading_result.has_error()) metric.SetStatusCode(OrbitLogEvent::INTERNAL_ERROR);
return loading_result;
})
.Then(main_thread_executor_.get(),
[this](ErrorMessageOr<LoadProjectsAndInstancesResult> loading_result) {
// `this` still exists when this lambda is executed. This is enforced, because
// main_thread_executor_ is a member of `this`. When `this` is destroyed,
// main_thread_executor_ is destroyed and the lambda is not executed. Check
// Future::Then for details about the lambda not being executed.
if (loading_result.has_error()) {
emit InitialLoadingFailed();
OnInstancesLoadingReturned(loading_result.error());
return;
}
OnInitialLoadingReturnedSuccess(loading_result.value());
});
}
void RetrieveInstancesWidget::OnInitialLoadingReturnedSuccess(
LoadProjectsAndInstancesResult initial_load_result) {
ORBIT_CHECK(ui_->projectComboBox->count() == 0);
// From here on the projectComboBox is filled. To not trigger currentIndexChanged signals, the
// signals of projectComboBox are blocked until the end of this function.
ui_->projectComboBox->blockSignals(true);
QString default_project_text =
QString("Default Project (%1)").arg(initial_load_result.default_project.display_name);
ui_->projectComboBox->addItem(default_project_text);
QVector<Project>& projects{initial_load_result.projects};
std::sort(projects.begin(), projects.end(),
[](const Project& p1, const Project& p2) { return p1.display_name < p2.display_name; });
for (const Project& project : projects) {
QString text = project.display_name;
if (project == initial_load_result.default_project) {
text.append(" (default)");
}
ui_->projectComboBox->addItem(text, QVariant::fromValue(project));
// initial_load_result.instances is the list for a specific project, which is
// initial_load_result.project_of_instances. (This can be different than the remembered project
// which was used in InitialLoad.) Since the initial_load_result.instances will be shown by
// ConnectToStadiaWidget, the combobox should have the project selected that belongs to this
// list. This selection is done here.
if (project == initial_load_result.project_of_instances) {
// last added item
ui_->projectComboBox->setCurrentIndex(ui_->projectComboBox->count() - 1);
}
}
ui_->projectComboBox->blockSignals(false);
OnInstancesLoadingReturned(initial_load_result.instances);
}
void RetrieveInstancesWidget::OnInstancesLoadingReturned(
const ErrorMessageOr<QVector<Instance>>& loading_result) {
if (loading_result.has_error()) {
ORBIT_ERROR("instance loading returned with error: %s", loading_result.error().message());
QMessageBox::critical(this, QCoreApplication::applicationName(),
QString::fromStdString(loading_result.error().message()));
emit LoadingFailed();
return;
}
emit LoadingSuccessful(loading_result.value());
}
void RetrieveInstancesWidget::OnReloadButtonClicked() {
// Initial loading failed
if (ui_->projectComboBox->count() == 0) {
InitialLoad(std::nullopt);
return;
}
std::optional<Project> selected_project;
if (ui_->projectComboBox->currentData().canConvert<Project>()) {
selected_project = ui_->projectComboBox->currentData().value<Project>();
}
emit LoadingStarted();
retrieve_instances_->LoadInstancesWithoutCache(selected_project, GetSelectedInstanceListScope())
.Then(main_thread_executor_.get(),
[this](const ErrorMessageOr<QVector<Instance>>& load_result) {
// `this` still exists when this lambda is executed. This is enforced, because
// main_thread_executor_ is a member of `this`. When `this` is destroyed,
// main_thread_executor_ is destroyed and the lambda is not executed. Check
// Future::Then for details about the lambda not being executed.
OnInstancesLoadingReturned(load_result);
});
}
std::optional<orbit_ggp::Project> RetrieveInstancesWidget::GetSelectedProject() const {
std::optional<Project> project;
if (ui_->projectComboBox->currentData().canConvert<Project>()) {
project = ui_->projectComboBox->currentData().value<Project>();
}
return project;
}
void RetrieveInstancesWidget::OnProjectComboBoxCurrentIndexChanged() {
std::optional<Project> selected_project = GetSelectedProject();
if (metrics_uploader_ != nullptr) {
metrics_uploader_->SendLogEvent(OrbitLogEvent::ORBIT_PROJECT_CHANGED);
}
emit LoadingStarted();
retrieve_instances_->LoadInstances(selected_project, GetSelectedInstanceListScope())
.Then(main_thread_executor_.get(),
[this, selected_project](const ErrorMessageOr<QVector<Instance>>& load_result) {
// `this` still exists when this lambda is executed. This is enforced, because
// main_thread_executor_ is a member of `this`. When `this` is destroyed,
// main_thread_executor_ is destroyed and the lambda is not executed. Check
// Future::Then for details about the lambda not being executed.
if (load_result.has_value()) {
SaveProjectToPersistentStorage(selected_project);
} else {
std::optional<Project> previously_selected =
LoadLastSelectedProjectFromPersistentStorage();
// The upcoming call to setCurrentIndex is not user action, but only resetting to
// previous values. Hence the signals are temporarily blocked.
ui_->projectComboBox->blockSignals(true);
if (previously_selected == std::nullopt) {
// If previously_selected is nullopt, that means QSettings contained either the
// default project or nothing (in which case selecting the default project is also
// correct). The first entry of the combobox (index 0) is the default project.
ui_->projectComboBox->setCurrentIndex(0);
} else {
int index = ui_->projectComboBox->findData(
QVariant::fromValue(previously_selected.value()));
ui_->projectComboBox->setCurrentIndex(index);
}
ui_->projectComboBox->blockSignals(false);
}
OnInstancesLoadingReturned(load_result);
});
}
void RetrieveInstancesWidget::OnAllCheckboxClicked() {
InstanceListScope selected_scope = GetSelectedInstanceListScope();
emit LoadingStarted();
retrieve_instances_->LoadInstances(GetSelectedProject(), selected_scope)
.Then(main_thread_executor_.get(),
[widget = QPointer<RetrieveInstancesWidget>(this),
selected_scope](const ErrorMessageOr<QVector<Instance>>& load_result) {
if (widget == nullptr) return;
if (load_result.has_value()) {
SaveInstancesScopeToPersistentStorage(selected_scope);
} else {
// reset to the value before (value saved in PersistenStorage)
widget->ui_->allCheckBox->setChecked(LoadInstancesScopeFromPersistentStorage() ==
InstanceListScope::kAllReservedInstances);
}
widget->OnInstancesLoadingReturned(load_result);
});
}
} // namespace orbit_session_setup<|endoftext|>
|
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/mlir_gpu/experimental/conv_emitter/conv_emitter.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/IR/AffineExpr.h" // TF:local_config_mlir
#include "mlir/IR/AffineMap.h" // TF:local_config_mlir
#include "mlir/IR/Builders.h" // TF:local_config_mlir
#include "mlir/IR/Function.h" // TF:local_config_mlir
#include "mlir/IR/Location.h" // TF:local_config_mlir
#include "mlir/IR/MLIRContext.h" // TF:local_config_mlir
#include "mlir/IR/Module.h" // TF:local_config_mlir
#include "mlir/IR/StandardTypes.h" // TF:local_config_mlir
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include "tensorflow/compiler/xla/tests/filecheck.h"
#include "tensorflow/core/platform/test.h"
namespace xla {
namespace gpu_mlir {
namespace {
mlir::Type ShapeToMlirType(const xla::Shape& shape, mlir::Builder* builder) {
CHECK(shape.IsArray());
mlir::Type element_type = [&] {
switch (shape.element_type()) {
case xla::F16:
return builder->getF16Type();
case xla::F32:
return builder->getF32Type();
default:
break;
}
CHECK(false);
}();
std::vector<int64_t> physical_layout;
std::vector<mlir::AffineExpr> major_to_minor;
for (int i = shape.layout().minor_to_major_size() - 1; i >= 0; i--) {
major_to_minor.push_back(
builder->getAffineDimExpr(shape.layout().minor_to_major(i)));
physical_layout.push_back(
shape.dimensions(shape.layout().minor_to_major(i)));
}
return builder->getMemRefType(
physical_layout, element_type,
{builder->getAffineMap(major_to_minor.size(), 0, major_to_minor)});
}
std::string CompileHloConvAndGetMlir(absl::string_view hlo_text) {
xla::HloModuleConfig hlo_config;
xla::HloModule hlo_module("Conv", hlo_config);
TF_CHECK_OK(xla::ParseHloString(hlo_text, &hlo_module));
xla::HloInstruction* conv =
hlo_module.entry_computation()->root_instruction();
mlir::MLIRContext context;
mlir::Location location = mlir::UnknownLoc::get(&context);
auto mlir_module = mlir::ModuleOp::create(location);
mlir::OpBuilder builder(&context);
xla::Shape input_shape = conv->operand(0)->shape();
xla::Shape filter_shape = conv->operand(1)->shape();
xla::Shape output_shape = conv->shape().tuple_shapes(0);
auto function = mlir::FuncOp::create(
location, "Conv",
builder.getFunctionType({ShapeToMlirType(output_shape, &builder),
ShapeToMlirType(input_shape, &builder),
ShapeToMlirType(filter_shape, &builder)},
{builder.getNoneType()}));
mlir_module.push_back(function);
auto* entry_block = function.addEntryBlock();
builder.setInsertionPointToStart(entry_block);
TF_CHECK_OK(xla::mlir_gpu::EmitConvolutionForwardAsMlir(
conv, entry_block->getArgument(1), entry_block->getArgument(2),
entry_block->getArgument(0), builder));
mlir_module.verify();
std::string mlir_text;
llvm::raw_string_ostream strstream(mlir_text);
function.print(strstream);
return mlir_text;
}
// TODO(timshen): integrate this with mlir_gpu's testing infrastructure.
TEST(ConvEmtiterTest, TestDefault) {
std::string hlo_text = R"(HloModule TestModule
ENTRY %TestComputation {
%param_0 = f16[128,4,224,224]{1,3,2,0} parameter(0)
%param_1 = f16[7,7,64,4]{3,1,0,2} parameter(1)
ROOT %custom-call.1 = (f16[128,64,112,112]{1,3,2,0}, u8[0]{0}) custom-call(%param_0, %param_1), window={size=7x7 stride=2x2 pad=3_3x3_3}, dim_labels=bf01_01oi->bf01, custom_call_target="__cudnn$convForward", backend_config="{conv_result_scale:1}"
})";
std::string expected_mlir_pattern =
R"(
CHECK: func @Conv(%arg0: memref<128x112x112x64xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>, %arg1: memref<128x224x224x4xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>, %arg2: memref<64x7x7x4xf16, (d0, d1, d2, d3) -> (d2, d0, d1, d3)>) -> none {
CHECK-NEXT: %0 = memref_cast %arg2 : memref<64x7x7x4xf16, (d0, d1, d2, d3) -> (d2, d0, d1, d3)> to memref<64x7x7x4xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg3: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg4: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg5: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg6: index):
CHECK-NEXT: %1 = alloc() : memref<32x16xf32>
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg7: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg8: index):
CHECK-NEXT: %cst = constant 0.000000e+00 : f32
CHECK-NEXT: "affine.store"(%cst, %1, %arg7, %arg8) {map = (d0, d1) -> (d0, d1)} : (f32, memref<32x16xf32>, index, index) -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (16)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (32)} : () -> ()
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg7: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg8: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg9: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg10: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg11: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg12: index):
CHECK-NEXT: %2 = "affine.load"(%arg1, %arg3, %arg9, %arg5, %arg6, %arg10, %arg11, %arg12, %arg8) {map = (d0, d1, d2, d3, d4, d5, d6, d7) -> (d0, d1 * 4 + d6, d2 * 2 + d4 - 3, (d3 * 16 + d7) * 2 + d5 - 3)} : (memref<128x224x224x4xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>, index, index, index, index, index, index, index, index) -> f16
CHECK-NEXT: %3 = "affine.load"(%0, %arg4, %arg9, %arg10, %arg11, %arg12, %arg7) {map = (d0, d1, d2, d3, d4, d5) -> (d0 * 32 + d5, d1 * 4 + d4, d2, d3)} : (memref<64x7x7x4xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>, index, index, index, index, index, index) -> f16
CHECK-NEXT: %4 = "affine.load"(%1, %arg7, %arg8) {map = (d0, d1) -> (d0, d1)} : (memref<32x16xf32>, index, index) -> f32
CHECK-NEXT: %5 = mulf %2, %3 : f16
CHECK-NEXT: %6 = "std.addf"(%4, %5) : (f32, f16) -> f32
CHECK-NEXT: "affine.store"(%6, %1, %arg7, %arg8) {map = (d0, d1) -> (d0, d1)} : (f32, memref<32x16xf32>, index, index) -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (4)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (7)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (7)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (1)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (16)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (32)} : () -> ()
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg7: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg8: index):
CHECK-NEXT: %2 = "affine.load"(%1, %arg7, %arg8) {map = (d0, d1) -> (d0, d1)} : (memref<32x16xf32>, index, index) -> f32
CHECK-NEXT: "affine.store"(%2, %arg0, %arg3, %arg4, %arg5, %arg6, %arg7, %arg8) {map = (d0, d1, d2, d3, d4, d5) -> (d0, d1 * 32 + d4, d2, d3 * 16 + d5)} : (f32, memref<128x112x112x64xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>, index, index, index, index, index, index) -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (16)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (32)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (7)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (112)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (2)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (128)} : () -> ()
CHECK-NEXT: }
)";
EXPECT_TRUE(
RunFileCheck(CompileHloConvAndGetMlir(hlo_text), expected_mlir_pattern)
.ValueOrDie());
}
} // namespace
} // namespace gpu_mlir
} // namespace xla
<commit_msg>[XLA/MLIR_GPU] Plug leak in ConvEmitterTest<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/mlir_gpu/experimental/conv_emitter/conv_emitter.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/IR/AffineExpr.h" // TF:local_config_mlir
#include "mlir/IR/AffineMap.h" // TF:local_config_mlir
#include "mlir/IR/Builders.h" // TF:local_config_mlir
#include "mlir/IR/Function.h" // TF:local_config_mlir
#include "mlir/IR/Location.h" // TF:local_config_mlir
#include "mlir/IR/MLIRContext.h" // TF:local_config_mlir
#include "mlir/IR/Module.h" // TF:local_config_mlir
#include "mlir/IR/StandardTypes.h" // TF:local_config_mlir
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include "tensorflow/compiler/xla/tests/filecheck.h"
#include "tensorflow/core/platform/test.h"
namespace xla {
namespace gpu_mlir {
namespace {
mlir::Type ShapeToMlirType(const xla::Shape& shape, mlir::Builder* builder) {
CHECK(shape.IsArray());
mlir::Type element_type = [&] {
switch (shape.element_type()) {
case xla::F16:
return builder->getF16Type();
case xla::F32:
return builder->getF32Type();
default:
break;
}
CHECK(false);
}();
std::vector<int64_t> physical_layout;
std::vector<mlir::AffineExpr> major_to_minor;
for (int i = shape.layout().minor_to_major_size() - 1; i >= 0; i--) {
major_to_minor.push_back(
builder->getAffineDimExpr(shape.layout().minor_to_major(i)));
physical_layout.push_back(
shape.dimensions(shape.layout().minor_to_major(i)));
}
return builder->getMemRefType(
physical_layout, element_type,
{builder->getAffineMap(major_to_minor.size(), 0, major_to_minor)});
}
std::string CompileHloConvAndGetMlir(absl::string_view hlo_text) {
xla::HloModuleConfig hlo_config;
xla::HloModule hlo_module("Conv", hlo_config);
TF_CHECK_OK(xla::ParseHloString(hlo_text, &hlo_module));
xla::HloInstruction* conv =
hlo_module.entry_computation()->root_instruction();
mlir::MLIRContext context;
mlir::Location location = mlir::UnknownLoc::get(&context);
mlir::OwningModuleRef mlir_module(mlir::ModuleOp::create(location));
mlir::OpBuilder builder(&context);
xla::Shape input_shape = conv->operand(0)->shape();
xla::Shape filter_shape = conv->operand(1)->shape();
xla::Shape output_shape = conv->shape().tuple_shapes(0);
auto function = mlir::FuncOp::create(
location, "Conv",
builder.getFunctionType({ShapeToMlirType(output_shape, &builder),
ShapeToMlirType(input_shape, &builder),
ShapeToMlirType(filter_shape, &builder)},
{builder.getNoneType()}));
mlir_module->push_back(function);
auto* entry_block = function.addEntryBlock();
builder.setInsertionPointToStart(entry_block);
TF_CHECK_OK(xla::mlir_gpu::EmitConvolutionForwardAsMlir(
conv, entry_block->getArgument(1), entry_block->getArgument(2),
entry_block->getArgument(0), builder));
mlir_module->verify();
std::string mlir_text;
llvm::raw_string_ostream strstream(mlir_text);
function.print(strstream);
return mlir_text;
}
// TODO(timshen): integrate this with mlir_gpu's testing infrastructure.
TEST(ConvEmitterTest, TestDefault) {
std::string hlo_text = R"(HloModule TestModule
ENTRY %TestComputation {
%param_0 = f16[128,4,224,224]{1,3,2,0} parameter(0)
%param_1 = f16[7,7,64,4]{3,1,0,2} parameter(1)
ROOT %custom-call.1 = (f16[128,64,112,112]{1,3,2,0}, u8[0]{0}) custom-call(%param_0, %param_1), window={size=7x7 stride=2x2 pad=3_3x3_3}, dim_labels=bf01_01oi->bf01, custom_call_target="__cudnn$convForward", backend_config="{conv_result_scale:1}"
})";
std::string expected_mlir_pattern =
R"(
CHECK: func @Conv(%arg0: memref<128x112x112x64xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>, %arg1: memref<128x224x224x4xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>, %arg2: memref<64x7x7x4xf16, (d0, d1, d2, d3) -> (d2, d0, d1, d3)>) -> none {
CHECK-NEXT: %0 = memref_cast %arg2 : memref<64x7x7x4xf16, (d0, d1, d2, d3) -> (d2, d0, d1, d3)> to memref<64x7x7x4xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg3: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg4: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg5: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg6: index):
CHECK-NEXT: %1 = alloc() : memref<32x16xf32>
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg7: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg8: index):
CHECK-NEXT: %cst = constant 0.000000e+00 : f32
CHECK-NEXT: "affine.store"(%cst, %1, %arg7, %arg8) {map = (d0, d1) -> (d0, d1)} : (f32, memref<32x16xf32>, index, index) -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (16)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (32)} : () -> ()
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg7: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg8: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg9: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg10: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg11: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg12: index):
CHECK-NEXT: %2 = "affine.load"(%arg1, %arg3, %arg9, %arg5, %arg6, %arg10, %arg11, %arg12, %arg8) {map = (d0, d1, d2, d3, d4, d5, d6, d7) -> (d0, d1 * 4 + d6, d2 * 2 + d4 - 3, (d3 * 16 + d7) * 2 + d5 - 3)} : (memref<128x224x224x4xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>, index, index, index, index, index, index, index, index) -> f16
CHECK-NEXT: %3 = "affine.load"(%0, %arg4, %arg9, %arg10, %arg11, %arg12, %arg7) {map = (d0, d1, d2, d3, d4, d5) -> (d0 * 32 + d5, d1 * 4 + d4, d2, d3)} : (memref<64x7x7x4xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>, index, index, index, index, index, index) -> f16
CHECK-NEXT: %4 = "affine.load"(%1, %arg7, %arg8) {map = (d0, d1) -> (d0, d1)} : (memref<32x16xf32>, index, index) -> f32
CHECK-NEXT: %5 = mulf %2, %3 : f16
CHECK-NEXT: %6 = "std.addf"(%4, %5) : (f32, f16) -> f32
CHECK-NEXT: "affine.store"(%6, %1, %arg7, %arg8) {map = (d0, d1) -> (d0, d1)} : (f32, memref<32x16xf32>, index, index) -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (4)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (7)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (7)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (1)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (16)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (32)} : () -> ()
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg7: index):
CHECK-NEXT: "affine.for"() ( {
CHECK-NEXT: ^bb0(%arg8: index):
CHECK-NEXT: %2 = "affine.load"(%1, %arg7, %arg8) {map = (d0, d1) -> (d0, d1)} : (memref<32x16xf32>, index, index) -> f32
CHECK-NEXT: "affine.store"(%2, %arg0, %arg3, %arg4, %arg5, %arg6, %arg7, %arg8) {map = (d0, d1, d2, d3, d4, d5) -> (d0, d1 * 32 + d4, d2, d3 * 16 + d5)} : (f32, memref<128x112x112x64xf16, (d0, d1, d2, d3) -> (d0, d2, d3, d1)>, index, index, index, index, index, index) -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (16)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (32)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (7)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (112)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (2)} : () -> ()
CHECK-NEXT: "affine.terminator"() : () -> ()
CHECK-NEXT: }) {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (128)} : () -> ()
CHECK-NEXT: }
)";
EXPECT_TRUE(
RunFileCheck(CompileHloConvAndGetMlir(hlo_text), expected_mlir_pattern)
.ValueOrDie());
}
} // namespace
} // namespace gpu_mlir
} // namespace xla
<|endoftext|>
|
<commit_before>// RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
#include <stdint.h>
#include <stdio.h>
#include <sys/mman.h>
int main() {
const size_t kLog2Size = 40;
const uintptr_t kLocation = 0x40ULL << kLog2Size;
void *p = mmap(
reinterpret_cast<void*>(kLocation),
1ULL << kLog2Size,
PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
-1, 0);
fprintf(stderr, "DONE %p\n", p);
return p == MAP_FAILED;
}
// CHECK: DONE
<commit_msg>tsan: fix test<commit_after>// RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
#include <stdint.h>
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>
int main() {
const size_t kLog2Size = 39;
const uintptr_t kLocation = 0x40ULL << kLog2Size;
void *p = mmap(
reinterpret_cast<void*>(kLocation),
1ULL << kLog2Size,
PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
-1, 0);
fprintf(stderr, "DONE %p %d\n", p, errno);
return p == MAP_FAILED;
}
// CHECK: DONE
<|endoftext|>
|
<commit_before>#include "ComplexSymLoader.h"
#include "FilepathHelper.h"
#include "SpriteFactory.h"
#include "SprTransLoader.h"
#include <sprite2/ComplexSymbol.h>
#include <simp/NodeComplex.h>
#include <fstream>
namespace gum
{
ComplexSymLoader::ComplexSymLoader(s2::ComplexSymbol* sym)
: m_sym(sym)
{
if (m_sym) {
m_sym->AddReference();
}
}
ComplexSymLoader::~ComplexSymLoader()
{
if (m_sym) {
m_sym->RemoveReference();
}
}
void ComplexSymLoader::LoadJson(const std::string& filepath)
{
if (!m_sym) {
return;
}
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
sm::rect scissor;
scissor.xmin = static_cast<float>(value["xmin"].asInt());
scissor.xmax = static_cast<float>(value["xmax"].asInt());
scissor.ymin = static_cast<float>(value["ymin"].asInt());
scissor.ymax = static_cast<float>(value["ymax"].asInt());
m_sym->SetScissor(scissor);
std::string dir = FilepathHelper::Dir(filepath);
m_sym->Clear();
for (int i = 0, n = value["sprite"].size(); i < n; ++i) {
s2::Sprite* spr = SpriteFactory::Instance()->Create(value["sprite"][i], dir);
m_sym->Add(spr);
}
LoadJsonAction(value, m_sym);
}
void ComplexSymLoader::LoadBin(const simp::NodeComplex* node)
{
sm::rect scissor;
scissor.xmin = node->scissor[0];
scissor.ymin = node->scissor[1];
scissor.xmax = node->scissor[2];
scissor.ymax = node->scissor[3];
m_sym->SetScissor(scissor);
m_sym->Clear();
for (int i = 0; i < node->sprs_n; ++i) {
s2::Sprite* spr = SpriteFactory::Instance()->Create(node->sprs[i]);
SprTransLoader::Load(spr, node->trans[i]);
m_sym->Add(spr);
}
const std::vector<s2::Sprite*>& children = m_sym->GetChildren();
std::vector<s2::ComplexSymbol::Action> dst;
dst.reserve(node->actions_n);
for (int i = 0; i < node->actions_n; ++i) {
const simp::NodeComplex::Action& src_action = node->actions[i];
s2::ComplexSymbol::Action dst_action;
dst_action.name = src_action.name;
dst_action.sprs.reserve(src_action.n);
for (int j = 0; j < src_action.n; ++j) {
dst_action.sprs.push_back(children[src_action.idx[j]]);
}
dst.push_back(dst_action);
}
m_sym->SetActions(dst);
}
void ComplexSymLoader::LoadJsonAction(const Json::Value& val, s2::ComplexSymbol* sym)
{
const std::vector<s2::Sprite*>& children = sym->GetChildren();
std::vector<Action> src;
LoadJsonAction(val, src);
std::vector<s2::ComplexSymbol::Action> dst;
dst.reserve(src.size());
for (int i = 0, n = src.size(); i < n; ++i) {
const Action& src_action = src[i];
s2::ComplexSymbol::Action dst_action;
dst_action.name = src_action.name;
dst_action.sprs.reserve(src_action.idx.size());
for (int j = 0, m = src_action.idx.size(); j < m; ++j) {
int idx = src_action.idx[j];
if (idx >= 0) {
dst_action.sprs.push_back(children[idx]);
}
}
dst.push_back(dst_action);
}
sym->SetActions(dst);
}
void ComplexSymLoader::LoadJsonAction(const Json::Value& val, std::vector<Action>& actions)
{
if (!val.isMember("action")) {
return;
}
const Json::Value& actions_val = val["action"];
for (int i = 0, n = actions_val.size(); i < n; ++i) {
const Json::Value& src = actions_val[i];
Action dst;
dst.name = src["name"].asString();
dst.idx.reserve(src["sprite"].size());
for (int j = 0, m = src["sprite"].size(); j < m; ++j) {
dst.idx.push_back(src["sprite"][j].asInt());
}
actions.push_back(dst);
}
}
}<commit_msg>[FIXED] complex load<commit_after>#include "ComplexSymLoader.h"
#include "FilepathHelper.h"
#include "SpriteFactory.h"
#include "SprTransLoader.h"
#include <sprite2/S2_Sprite.h>
#include <sprite2/ComplexSymbol.h>
#include <simp/NodeComplex.h>
#include <fstream>
namespace gum
{
ComplexSymLoader::ComplexSymLoader(s2::ComplexSymbol* sym)
: m_sym(sym)
{
if (m_sym) {
m_sym->AddReference();
}
}
ComplexSymLoader::~ComplexSymLoader()
{
if (m_sym) {
m_sym->RemoveReference();
}
}
void ComplexSymLoader::LoadJson(const std::string& filepath)
{
if (!m_sym) {
return;
}
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
sm::rect scissor;
scissor.xmin = static_cast<float>(value["xmin"].asInt());
scissor.xmax = static_cast<float>(value["xmax"].asInt());
scissor.ymin = static_cast<float>(value["ymin"].asInt());
scissor.ymax = static_cast<float>(value["ymax"].asInt());
m_sym->SetScissor(scissor);
std::string dir = FilepathHelper::Dir(filepath);
m_sym->Clear();
for (int i = 0, n = value["sprite"].size(); i < n; ++i) {
s2::Sprite* spr = SpriteFactory::Instance()->Create(value["sprite"][i], dir);
m_sym->Add(spr);
spr->RemoveReference();
}
LoadJsonAction(value, m_sym);
}
void ComplexSymLoader::LoadBin(const simp::NodeComplex* node)
{
sm::rect scissor;
scissor.xmin = node->scissor[0];
scissor.ymin = node->scissor[1];
scissor.xmax = node->scissor[2];
scissor.ymax = node->scissor[3];
m_sym->SetScissor(scissor);
m_sym->Clear();
for (int i = 0; i < node->sprs_n; ++i) {
s2::Sprite* spr = SpriteFactory::Instance()->Create(node->sprs[i]);
SprTransLoader::Load(spr, node->trans[i]);
m_sym->Add(spr);
spr->RemoveReference();
}
const std::vector<s2::Sprite*>& children = m_sym->GetChildren();
std::vector<s2::ComplexSymbol::Action> dst;
dst.reserve(node->actions_n);
for (int i = 0; i < node->actions_n; ++i) {
const simp::NodeComplex::Action& src_action = node->actions[i];
s2::ComplexSymbol::Action dst_action;
dst_action.name = src_action.name;
dst_action.sprs.reserve(src_action.n);
for (int j = 0; j < src_action.n; ++j) {
dst_action.sprs.push_back(children[src_action.idx[j]]);
}
dst.push_back(dst_action);
}
m_sym->SetActions(dst);
}
void ComplexSymLoader::LoadJsonAction(const Json::Value& val, s2::ComplexSymbol* sym)
{
const std::vector<s2::Sprite*>& children = sym->GetChildren();
std::vector<Action> src;
LoadJsonAction(val, src);
std::vector<s2::ComplexSymbol::Action> dst;
dst.reserve(src.size());
for (int i = 0, n = src.size(); i < n; ++i) {
const Action& src_action = src[i];
s2::ComplexSymbol::Action dst_action;
dst_action.name = src_action.name;
dst_action.sprs.reserve(src_action.idx.size());
for (int j = 0, m = src_action.idx.size(); j < m; ++j) {
int idx = src_action.idx[j];
if (idx >= 0) {
dst_action.sprs.push_back(children[idx]);
}
}
dst.push_back(dst_action);
}
sym->SetActions(dst);
}
void ComplexSymLoader::LoadJsonAction(const Json::Value& val, std::vector<Action>& actions)
{
if (!val.isMember("action")) {
return;
}
const Json::Value& actions_val = val["action"];
for (int i = 0, n = actions_val.size(); i < n; ++i) {
const Json::Value& src = actions_val[i];
Action dst;
dst.name = src["name"].asString();
dst.idx.reserve(src["sprite"].size());
for (int j = 0, m = src["sprite"].size(); j < m; ++j) {
dst.idx.push_back(src["sprite"][j].asInt());
}
actions.push_back(dst);
}
}
}<|endoftext|>
|
<commit_before>#include <LinearizedTree.h>
#include <algorithm>
LinearizedTree::LinearizedTree()
: _tree(nullptr)
, _strategy(None)
, _nextIndex(0)
{
}
LinearizedTree::LinearizedTree(const Tree* tree, Algorithm strategy)
: _tree(tree)
, _strategy(strategy)
, _nodes(tree->size())
, _nextIndex(0)
{
linearize();
}
const Tree* LinearizedTree::tree() const
{
return _tree;
}
void LinearizedTree::setTree(const Tree* tree)
{
if (_tree == tree) return;
_tree = tree;
}
void LinearizedTree::setAlgorithm(Algorithm strategy)
{
if (_strategy == strategy) return;
_strategy = strategy;
}
unsigned LinearizedTree::size() const
{
return _tree ? _tree->size() : 0;
}
int LinearizedTree::maxId() const
{
return _tree ? _tree->maxId() : -1;
}
const Node* LinearizedTree::root() const
{
return _tree ? _tree->root() : nullptr;
}
int LinearizedTree::indexOf(const Node* node) const
{
if (!_indices.count(node))
{
return -1;
}
return _indices.at(node);
}
int LinearizedTree::indexOf(int id) const
{
return indexOf(getNode(id));
}
const Node* LinearizedTree::at(int index) const
{
return _nodes[index];
}
const Node* LinearizedTree::operator[](int index) const
{
return _nodes[index];
}
const Node* LinearizedTree::getNode(int id) const
{
return _tree->getNode(id);
}
const std::vector<std::pair<int, int>>& LinearizedTree::thresholds() const
{
return _treeDepthTresholds;
}
void LinearizedTree::treeLayerRangesDo(std::function<void(int, int)> callback) const
{
if (_strategy == BreadthFirst || _strategy == OptimizedBreadthFirst)
{
for (const std::pair<int, int>& pair : _treeDepthTresholds)
{
callback(pair.first, pair.second);
}
}
}
std::vector<const Node*>::const_iterator LinearizedTree::begin() const
{
return _nodes.begin();
}
std::vector<const Node*>::const_iterator LinearizedTree::end() const
{
return _nodes.end();
}
void LinearizedTree::linearize()
{
clear();
if (!_tree)
{
return;
}
switch (_strategy)
{
case DepthFirst:
linearizeDepthFirst();
break;
case BreadthFirst:
linearizeBreadthFirst();
break;
case OptimizedBreadthFirst:
linearizeOptimizedBreadthFirst();
break;
}
}
void LinearizedTree::clear()
{
_nextIndex = 0;
_nodes.clear();
_indices.clear();
_treeDepthTresholds.clear();
if (_tree)
{
_nodes.resize(_tree->size());
}
}
void LinearizedTree::add(const Node* node)
{
int index = _nextIndex++;
_nodes[index] = node;
_indices[node] = index;
}
void LinearizedTree::linearizeDepthFirst()
{
_tree->nodesDo([this](const Node* node) { add(node); });
}
void LinearizedTree::linearizeBreadthFirst()
{
_tree->nodesOrderedByDepthDo([this](const Node* node) {
add(node);
if (_treeDepthTresholds.size() < node->depth()+1)
{
_treeDepthTresholds.emplace_back(indexOf(node), indexOf(node));
}
else
{
_treeDepthTresholds.back().second = indexOf(node);
}
});
}
void LinearizedTree::linearizeOptimizedBreadthFirst()
{
std::vector<const Node*> currentLevel;
_tree->nodesOrderedByDepthDo([this, ¤tLevel](const Node* node)
{
if (!currentLevel.empty() && node->depth() > currentLevel.back()->depth())
{
std::sort(currentLevel.begin(), currentLevel.end(), [](const Node* node1, const Node* node2) {
return (node1->isLeaf() ? 0 : 1) < (node2->isLeaf() ? 0 : 1);
});
for (const Node* child : currentLevel)
{
add(child);
}
for (const Node* child : currentLevel)
{
if (child->isLeaf())
{
continue;
}
_treeDepthTresholds.emplace_back(indexOf(child), indexOf(currentLevel.back()));
break;
}
currentLevel.clear();
}
currentLevel.push_back(node);
});
// only add the remaining nodes because they are all leafs
for (const Node* child : currentLevel)
{
add(child);
}
}
<commit_msg>Fix segfault in LinearizedTree constructor<commit_after>#include <LinearizedTree.h>
#include <algorithm>
LinearizedTree::LinearizedTree()
: _tree(nullptr)
, _strategy(None)
, _nextIndex(0)
{
}
LinearizedTree::LinearizedTree(const Tree* tree, Algorithm strategy)
: _tree(tree)
, _strategy(strategy)
, _nodes(tree ? tree->size() : 0)
, _nextIndex(0)
{
linearize();
}
const Tree* LinearizedTree::tree() const
{
return _tree;
}
void LinearizedTree::setTree(const Tree* tree)
{
if (_tree == tree) return;
_tree = tree;
}
void LinearizedTree::setAlgorithm(Algorithm strategy)
{
if (_strategy == strategy) return;
_strategy = strategy;
}
unsigned LinearizedTree::size() const
{
return _tree ? _tree->size() : 0;
}
int LinearizedTree::maxId() const
{
return _tree ? _tree->maxId() : -1;
}
const Node* LinearizedTree::root() const
{
return _tree ? _tree->root() : nullptr;
}
int LinearizedTree::indexOf(const Node* node) const
{
if (!_indices.count(node))
{
return -1;
}
return _indices.at(node);
}
int LinearizedTree::indexOf(int id) const
{
return indexOf(getNode(id));
}
const Node* LinearizedTree::at(int index) const
{
return _nodes[index];
}
const Node* LinearizedTree::operator[](int index) const
{
return _nodes[index];
}
const Node* LinearizedTree::getNode(int id) const
{
return _tree->getNode(id);
}
const std::vector<std::pair<int, int>>& LinearizedTree::thresholds() const
{
return _treeDepthTresholds;
}
void LinearizedTree::treeLayerRangesDo(std::function<void(int, int)> callback) const
{
if (_strategy == BreadthFirst || _strategy == OptimizedBreadthFirst)
{
for (const std::pair<int, int>& pair : _treeDepthTresholds)
{
callback(pair.first, pair.second);
}
}
}
std::vector<const Node*>::const_iterator LinearizedTree::begin() const
{
return _nodes.begin();
}
std::vector<const Node*>::const_iterator LinearizedTree::end() const
{
return _nodes.end();
}
void LinearizedTree::linearize()
{
clear();
if (!_tree)
{
return;
}
switch (_strategy)
{
case DepthFirst:
linearizeDepthFirst();
break;
case BreadthFirst:
linearizeBreadthFirst();
break;
case OptimizedBreadthFirst:
linearizeOptimizedBreadthFirst();
break;
}
}
void LinearizedTree::clear()
{
_nextIndex = 0;
_nodes.clear();
_indices.clear();
_treeDepthTresholds.clear();
if (_tree)
{
_nodes.resize(_tree->size());
}
}
void LinearizedTree::add(const Node* node)
{
int index = _nextIndex++;
_nodes[index] = node;
_indices[node] = index;
}
void LinearizedTree::linearizeDepthFirst()
{
_tree->nodesDo([this](const Node* node) { add(node); });
}
void LinearizedTree::linearizeBreadthFirst()
{
_tree->nodesOrderedByDepthDo([this](const Node* node) {
add(node);
if (_treeDepthTresholds.size() < node->depth()+1)
{
_treeDepthTresholds.emplace_back(indexOf(node), indexOf(node));
}
else
{
_treeDepthTresholds.back().second = indexOf(node);
}
});
}
void LinearizedTree::linearizeOptimizedBreadthFirst()
{
std::vector<const Node*> currentLevel;
_tree->nodesOrderedByDepthDo([this, ¤tLevel](const Node* node)
{
if (!currentLevel.empty() && node->depth() > currentLevel.back()->depth())
{
std::sort(currentLevel.begin(), currentLevel.end(), [](const Node* node1, const Node* node2) {
return (node1->isLeaf() ? 0 : 1) < (node2->isLeaf() ? 0 : 1);
});
for (const Node* child : currentLevel)
{
add(child);
}
for (const Node* child : currentLevel)
{
if (child->isLeaf())
{
continue;
}
_treeDepthTresholds.emplace_back(indexOf(child), indexOf(currentLevel.back()));
break;
}
currentLevel.clear();
}
currentLevel.push_back(node);
});
// only add the remaining nodes because they are all leafs
for (const Node* child : currentLevel)
{
add(child);
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2005 by Jorrit Tyberghein
(C) 2005 by Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csgeom/math.h"
#include "csutil/sysfunc.h"
#include "csutil/threadjobqueue.h"
namespace CS
{
namespace Threading
{
ThreadedJobQueue::ThreadedJobQueue (size_t numWorkers, ThreadPriority priority)
: scfImplementationType (this),
numWorkerThreads (numWorkers),
shutdownQueue (false), outstandingJobs (0)
{
allThreadState = new ThreadState*[numWorkers];
// Start up the threads
for (size_t i = 0; i < numWorkerThreads; ++i)
{
allThreadState[i] = new ThreadState (this);
allThreadState[i]->threadObject->SetPriority(priority);
allThreads.Add (allThreadState[i]->threadObject);
}
allThreads.StartAll ();
}
ThreadedJobQueue::~ThreadedJobQueue ()
{
{
// Empty the queue for new jobs
MutexScopedLock lock (jobMutex);
jobQueue.DeleteAll ();
}
// Wait for all threads to finish their current job
shutdownQueue = true;
newJob.NotifyAll ();
allThreads.WaitAll ();
// Deallocate
for (size_t i = 0; i < numWorkerThreads; ++i)
{
delete allThreadState[i];
}
delete allThreadState;
}
void ThreadedJobQueue::Enqueue (iJob* job)
{
if (!job)
return;
MutexScopedLock lock (jobMutex);
jobQueue.Push (job);
CS::Threading::AtomicOperations::Increment (&outstandingJobs);
newJob.NotifyOne ();
}
void ThreadedJobQueue::PullAndRun (iJob* job)
{
bool jobUnqued = false;
{
MutexScopedLock lock (jobMutex);
// Check if in queue
jobUnqued = jobQueue.Delete (job);
}
if (jobUnqued)
{
job->Run ();
CS::Threading::AtomicOperations::Decrement (&outstandingJobs);
return;
}
// Now we have to check the active jobs, just wait until it is done
{
MutexScopedLock lock (threadStateMutex);
bool isRunning = false;
size_t index;
for (size_t i = 0; i < numWorkerThreads; ++i)
{
if (allThreadState[i]->currentJob == job)
{
isRunning = true;
index = i;
break;
}
}
if (isRunning)
{
while (allThreadState[index]->currentJob == job)
allThreadState[index]->jobFinished.Wait (threadStateMutex);
}
}
}
void ThreadedJobQueue::Unqueue (iJob* job, bool waitIfCurrent)
{
{
MutexScopedLock lock (jobMutex);
// Check if in queue
bool jobUnqued = jobQueue.Delete (job);
if (jobUnqued)
return;
}
{
// Check the running threads
MutexScopedLock lock (threadStateMutex);
bool isRunning = false;
size_t index;
for (size_t i = 0; i < numWorkerThreads; ++i)
{
if (allThreadState[i]->currentJob == job)
{
isRunning = true;
index = i;
break;
}
}
if (isRunning && waitIfCurrent)
{
while (allThreadState[index]->currentJob == job)
allThreadState[index]->jobFinished.Wait (threadStateMutex);
}
}
}
void ThreadedJobQueue::Wait (iJob* job)
{
while (true)
{
{
// Check the running threads
MutexScopedLock lock (threadStateMutex);
bool isRunning = false;
size_t index;
for (size_t i = 0; i < numWorkerThreads; ++i)
{
if (allThreadState[i]->currentJob == job)
{
isRunning = true;
index = i;
break;
}
}
if (isRunning)
{
/* The job is currently running, so wait until it finished */
while (allThreadState[index]->currentJob == job)
allThreadState[index]->jobFinished.Wait (threadStateMutex);
return;
}
}
{
MutexScopedLock lock (jobMutex);
// Check if in queue
bool jobUnqued = jobQueue.Contains (job);
if (!jobUnqued)
// Not queued or running at all (any more)
return;
}
/* The job is somewhere in a queue.
* Just wait for any job to finish and check everything again...
*/
if (!IsFinished())
{
jobFinished.Wait (jobFinishedMutex);
}
}
}
bool ThreadedJobQueue::IsFinished ()
{
int32 c = CS::Threading::AtomicOperations::Read (&outstandingJobs);
return c == 0;
}
ThreadedJobQueue::QueueRunnable::QueueRunnable (ThreadedJobQueue* queue,
ThreadState* ts)
: ownerQueue (queue), threadState (ts)
{
}
void ThreadedJobQueue::QueueRunnable::Run ()
{
while (true)
{
// Get a job
{
MutexScopedLock lock (ownerQueue->jobMutex);
while (ownerQueue->jobQueue.GetSize () == 0)
{
if (ownerQueue->shutdownQueue)
return;
ownerQueue->newJob.Wait (ownerQueue->jobMutex);
}
{
MutexScopedLock lock2 (ownerQueue->threadStateMutex);
threadState->currentJob = ownerQueue->jobQueue.PopTop ();
}
}
// Execute it
if (threadState->currentJob)
{
threadState->currentJob->Run ();
CS::Threading::AtomicOperations::Decrement (&(ownerQueue->outstandingJobs));
}
// Clean up
{
MutexScopedLock lock (ownerQueue->threadStateMutex);
threadState->currentJob = 0;
threadState->jobFinished.NotifyAll ();
}
{
ownerQueue->jobFinished.NotifyAll ();
}
}
}
int32 ThreadedJobQueue::GetQueueCount()
{
return CS::Threading::AtomicOperations::Read(&outstandingJobs);
}
}
}
<commit_msg>Fixed a delete that should be a delete[].<commit_after>/*
Copyright (C) 2005 by Jorrit Tyberghein
(C) 2005 by Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csgeom/math.h"
#include "csutil/sysfunc.h"
#include "csutil/threadjobqueue.h"
namespace CS
{
namespace Threading
{
ThreadedJobQueue::ThreadedJobQueue (size_t numWorkers, ThreadPriority priority)
: scfImplementationType (this),
numWorkerThreads (numWorkers),
shutdownQueue (false), outstandingJobs (0)
{
allThreadState = new ThreadState*[numWorkers];
// Start up the threads
for (size_t i = 0; i < numWorkerThreads; ++i)
{
allThreadState[i] = new ThreadState (this);
allThreadState[i]->threadObject->SetPriority(priority);
allThreads.Add (allThreadState[i]->threadObject);
}
allThreads.StartAll ();
}
ThreadedJobQueue::~ThreadedJobQueue ()
{
{
// Empty the queue for new jobs
MutexScopedLock lock (jobMutex);
jobQueue.DeleteAll ();
}
// Wait for all threads to finish their current job
shutdownQueue = true;
newJob.NotifyAll ();
allThreads.WaitAll ();
// Deallocate
for (size_t i = 0; i < numWorkerThreads; ++i)
{
delete allThreadState[i];
}
delete[] allThreadState;
}
void ThreadedJobQueue::Enqueue (iJob* job)
{
if (!job)
return;
MutexScopedLock lock (jobMutex);
jobQueue.Push (job);
CS::Threading::AtomicOperations::Increment (&outstandingJobs);
newJob.NotifyOne ();
}
void ThreadedJobQueue::PullAndRun (iJob* job)
{
bool jobUnqued = false;
{
MutexScopedLock lock (jobMutex);
// Check if in queue
jobUnqued = jobQueue.Delete (job);
}
if (jobUnqued)
{
job->Run ();
CS::Threading::AtomicOperations::Decrement (&outstandingJobs);
return;
}
// Now we have to check the active jobs, just wait until it is done
{
MutexScopedLock lock (threadStateMutex);
bool isRunning = false;
size_t index;
for (size_t i = 0; i < numWorkerThreads; ++i)
{
if (allThreadState[i]->currentJob == job)
{
isRunning = true;
index = i;
break;
}
}
if (isRunning)
{
while (allThreadState[index]->currentJob == job)
allThreadState[index]->jobFinished.Wait (threadStateMutex);
}
}
}
void ThreadedJobQueue::Unqueue (iJob* job, bool waitIfCurrent)
{
{
MutexScopedLock lock (jobMutex);
// Check if in queue
bool jobUnqued = jobQueue.Delete (job);
if (jobUnqued)
return;
}
{
// Check the running threads
MutexScopedLock lock (threadStateMutex);
bool isRunning = false;
size_t index;
for (size_t i = 0; i < numWorkerThreads; ++i)
{
if (allThreadState[i]->currentJob == job)
{
isRunning = true;
index = i;
break;
}
}
if (isRunning && waitIfCurrent)
{
while (allThreadState[index]->currentJob == job)
allThreadState[index]->jobFinished.Wait (threadStateMutex);
}
}
}
void ThreadedJobQueue::Wait (iJob* job)
{
while (true)
{
{
// Check the running threads
MutexScopedLock lock (threadStateMutex);
bool isRunning = false;
size_t index;
for (size_t i = 0; i < numWorkerThreads; ++i)
{
if (allThreadState[i]->currentJob == job)
{
isRunning = true;
index = i;
break;
}
}
if (isRunning)
{
/* The job is currently running, so wait until it finished */
while (allThreadState[index]->currentJob == job)
allThreadState[index]->jobFinished.Wait (threadStateMutex);
return;
}
}
{
MutexScopedLock lock (jobMutex);
// Check if in queue
bool jobUnqued = jobQueue.Contains (job);
if (!jobUnqued)
// Not queued or running at all (any more)
return;
}
/* The job is somewhere in a queue.
* Just wait for any job to finish and check everything again...
*/
if (!IsFinished())
{
jobFinished.Wait (jobFinishedMutex);
}
}
}
bool ThreadedJobQueue::IsFinished ()
{
int32 c = CS::Threading::AtomicOperations::Read (&outstandingJobs);
return c == 0;
}
ThreadedJobQueue::QueueRunnable::QueueRunnable (ThreadedJobQueue* queue,
ThreadState* ts)
: ownerQueue (queue), threadState (ts)
{
}
void ThreadedJobQueue::QueueRunnable::Run ()
{
while (true)
{
// Get a job
{
MutexScopedLock lock (ownerQueue->jobMutex);
while (ownerQueue->jobQueue.GetSize () == 0)
{
if (ownerQueue->shutdownQueue)
return;
ownerQueue->newJob.Wait (ownerQueue->jobMutex);
}
{
MutexScopedLock lock2 (ownerQueue->threadStateMutex);
threadState->currentJob = ownerQueue->jobQueue.PopTop ();
}
}
// Execute it
if (threadState->currentJob)
{
threadState->currentJob->Run ();
CS::Threading::AtomicOperations::Decrement (&(ownerQueue->outstandingJobs));
}
// Clean up
{
MutexScopedLock lock (ownerQueue->threadStateMutex);
threadState->currentJob = 0;
threadState->jobFinished.NotifyAll ();
}
{
ownerQueue->jobFinished.NotifyAll ();
}
}
}
int32 ThreadedJobQueue::GetQueueCount()
{
return CS::Threading::AtomicOperations::Read(&outstandingJobs);
}
}
}
<|endoftext|>
|
<commit_before>// tinygettext - A gettext replacement that works directly on .po files
// Copyright (C) 2009 Ingo Ruhnke <grumbel@gmx.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "po_parser.hpp"
#include <iostream>
#include <ctype.h>
#include <string>
#include <istream>
#include <string.h>
#include <map>
#include <stddef.h> // for size_t
#include <stdlib.h>
#include "language.hpp"
#include "log_stream.hpp"
#include "iconv.hpp"
#include "dictionary.hpp"
#include "plural_forms.hpp"
namespace tinygettext {
bool POParser::pedantic = true;
void
POParser::parse(const std::string& filename, std::istream& in, Dictionary& dict)
{
POParser parser(filename, in, dict);
parser.parse();
}
class POParserError {};
POParser::POParser(const std::string& filename_, std::istream& in_, Dictionary& dict_, bool use_fuzzy_) :
filename(filename_),
in(in_),
dict(dict_),
use_fuzzy(use_fuzzy_),
running(false),
eof(false),
big5(false),
line_number(0),
current_line(),
conv()
{
}
POParser::~POParser()
{
}
void
POParser::warning(const std::string& msg)
{
log_warning << filename << ":" << line_number << ": warning: " << msg << ": " << current_line << std::endl;
//log_warning << "Line: " << current_line << std::endl;
}
void
POParser::error(const std::string& msg)
{
log_error << filename << ":" << line_number << ": error: " << msg << ": " << current_line << std::endl;
// Try to recover from an error by searching for start of another entry
do
next_line();
while(!eof && !is_empty_line());
throw POParserError();
}
void
POParser::next_line()
{
line_number += 1;
if (!std::getline(in, current_line))
eof = true;
}
void
POParser::get_string_line(std::ostringstream& out,unsigned int skip)
{
if (skip+1 >= static_cast<unsigned int>(current_line.size()))
error("unexpected end of line");
if (current_line[skip] != '"')
error("expected start of string '\"'");
std::string::size_type i;
for(i = skip+1; current_line[i] != '\"'; ++i)
{
if (big5 && static_cast<unsigned char>(current_line[i]) >= 0x81 && static_cast<unsigned char>(current_line[i]) <= 0xfe)
{
out << current_line[i];
i += 1;
if (i >= current_line.size())
error("invalid big5 encoding");
out << current_line[i];
}
else if (i >= current_line.size())
{
error("unexpected end of string");
}
else if (current_line[i] == '\\')
{
i += 1;
if (i >= current_line.size())
error("unexpected end of string in handling '\\'");
switch (current_line[i])
{
case 'a': out << '\a'; break;
case 'b': out << '\b'; break;
case 'v': out << '\v'; break;
case 'n': out << '\n'; break;
case 't': out << '\t'; break;
case 'r': out << '\r'; break;
case '"': out << '"'; break;
case '\\': out << '\\'; break;
default:
std::ostringstream err;
err << "unhandled escape '\\" << current_line[i] << "'";
warning(err.str());
out << current_line[i-1] << current_line[i];
break;
}
}
else
{
out << current_line[i];
}
}
// process trailing garbage in line and warn if there is any
for(i = i+1; i < current_line.size(); ++i)
if (!isspace(current_line[i]))
{
warning("unexpected garbage after string ignoren");
break;
}
}
std::string
POParser::get_string(unsigned int skip)
{
std::ostringstream out;
if (skip+1 >= static_cast<unsigned int>(current_line.size()))
error("unexpected end of line");
if (current_line[skip] == ' ' && current_line[skip+1] == '"')
{
get_string_line(out, skip+1);
}
else
{
if (pedantic)
warning("keyword and string must be seperated by a single space");
for(;;)
{
if (skip >= static_cast<unsigned int>(current_line.size()))
error("unexpected end of line");
else if (current_line[skip] == '\"')
{
get_string_line(out, skip);
break;
}
else if (!isspace(current_line[skip]))
{
error("string must start with '\"'");
}
else
{
// skip space
}
skip += 1;
}
}
next:
next_line();
for(std::string::size_type i = 0; i < current_line.size(); ++i)
{
if (current_line[i] == '"')
{
if (i == 1)
if (pedantic)
warning("leading whitespace before string");
get_string_line(out, i);
goto next;
}
else if (isspace(current_line[i]))
{
// skip
}
else
{
break;
}
}
return out.str();
}
static bool has_prefix(const std::string& lhs, const std::string rhs)
{
if (lhs.length() < rhs.length())
return false;
else
return lhs.compare(0, rhs.length(), rhs) == 0;
}
void
POParser::parse_header(const std::string& header)
{
std::string from_charset;
std::string::size_type start = 0;
for(std::string::size_type i = 0; i < header.length(); ++i)
{
if (header[i] == '\n')
{
std::string line = header.substr(start, i - start);
if (has_prefix(line, "Content-Type:"))
{
// from_charset = line.substr(len);
size_t len = strlen("Content-Type: text/plain; charset=");
if (line.compare(0, len, "Content-Type: text/plain; charset=") == 0)
{
from_charset = line.substr(len);
for(std::string::iterator ch = from_charset.begin(); ch != from_charset.end(); ++ch)
*ch = static_cast<char>(toupper(*ch));
}
else
{
warning("malformed Content-Type header");
}
}
else if (has_prefix(line, "Plural-Forms:"))
{
PluralForms plural_forms = PluralForms::from_string(line);
if (!plural_forms)
{
warning("unknown Plural-Forms given");
}
else
{
if (!dict.get_plural_forms())
{
dict.set_plural_forms(plural_forms);
}
else
{
if (dict.get_plural_forms() != plural_forms)
{
warning("Plural-Forms missmatch between .po file and dictionary");
}
}
}
}
start = i+1;
}
}
if (from_charset.empty() || from_charset == "CHARSET")
{
warning("charset not specified for .po, fallback to utf-8");
from_charset = "UTF-8";
}
else if (from_charset == "BIG5")
{
big5 = true;
}
conv.set_charsets(from_charset, dict.get_charset());
}
bool
POParser::is_empty_line()
{
if (current_line.empty())
{
return true;
}
else if (current_line[0] == '#')
{ // handle comments as empty lines
if (current_line.size() == 1 || (current_line.size() >= 2 && isspace(current_line[1])))
return true;
else
return false;
}
else
{
for(std::string::iterator i = current_line.begin(); i != current_line.end(); ++i)
{
if (!isspace(*i))
return false;
}
}
return true;
}
bool
POParser::prefix(const char* prefix_str)
{
return current_line.compare(0, strlen(prefix_str), prefix_str) == 0;
}
void
POParser::parse()
{
next_line();
// skip UTF-8 intro that some text editors produce
// see http://en.wikipedia.org/wiki/Byte-order_mark
if (current_line.size() >= 3 &&
current_line[0] == '\xef' &&
current_line[1] == '\xbb' &&
current_line[2] == '\xbf')
{
current_line = current_line.substr(3);
}
// Parser structure
while(!eof)
{
try
{
bool fuzzy = false;
bool has_msgctxt = false;
std::string msgctxt;
std::string msgid;
while(prefix("#"))
{
if (current_line.size() >= 2 && current_line[1] == ',')
{
// FIXME: Rather simplistic hunt for fuzzy flag
if (current_line.find("fuzzy", 2) != std::string::npos)
fuzzy = true;
}
next_line();
}
if (!is_empty_line())
{
if (prefix("msgctxt"))
{
has_msgctxt = true;
msgctxt = get_string(7);
}
if (prefix("msgid"))
msgid = get_string(5);
else
error("expected 'msgid'");
if (prefix("msgid_plural"))
{
std::string msgid_plural = get_string(12);
std::vector<std::string> msgstr_num;
bool saw_nonempty_msgstr = false;
next:
if (is_empty_line())
{
if (msgstr_num.empty())
error("expected 'msgstr[N] (0 <= N <= 9)'");
}
else if (prefix("msgstr[") &&
current_line.size() > 8 &&
isdigit(current_line[7]) && current_line[8] == ']')
{
unsigned int number = static_cast<unsigned int>(current_line[7] - '0');
std::string msgstr = get_string(9);
if(!msgstr.empty())
saw_nonempty_msgstr = true;
if (number >= msgstr_num.size())
msgstr_num.resize(number+1);
msgstr_num[number] = conv.convert(msgstr);
goto next;
}
else
{
error("expected 'msgstr[N]'");
}
if (!is_empty_line())
error("expected 'msgstr[N]' or empty line");
if (saw_nonempty_msgstr)
{
if (use_fuzzy || !fuzzy)
{
if (!dict.get_plural_forms())
{
warning("msgstr[N] seen, but no Plural-Forms given");
}
else
{
if (msgstr_num.size() != dict.get_plural_forms().get_nplural())
{
warning("msgstr[N] count doesn't match Plural-Forms.nplural");
}
}
if (has_msgctxt)
dict.add_translation(msgctxt, msgid, msgid_plural, msgstr_num);
else
dict.add_translation(msgid, msgid_plural, msgstr_num);
}
if (0)
{
std::cout << (fuzzy?"fuzzy":"not-fuzzy") << std::endl;
std::cout << "msgid \"" << msgid << "\"" << std::endl;
std::cout << "msgid_plural \"" << msgid_plural << "\"" << std::endl;
for(std::vector<std::string>::size_type i = 0; i < msgstr_num.size(); ++i)
std::cout << "msgstr[" << i << "] \"" << conv.convert(msgstr_num[i]) << "\"" << std::endl;
std::cout << std::endl;
}
}
}
else if (prefix("msgstr"))
{
std::string msgstr = get_string(6);
if (msgid.empty())
{
parse_header(msgstr);
}
else if(!msgstr.empty())
{
if (use_fuzzy || !fuzzy)
{
if (has_msgctxt)
dict.add_translation(msgctxt, msgid, conv.convert(msgstr));
else
dict.add_translation(msgid, conv.convert(msgstr));
}
if (0)
{
std::cout << (fuzzy?"fuzzy":"not-fuzzy") << std::endl;
std::cout << "msgid \"" << msgid << "\"" << std::endl;
std::cout << "msgstr \"" << conv.convert(msgstr) << "\"" << std::endl;
std::cout << std::endl;
}
}
}
else
{
error("expected 'msgstr' or 'msgid_plural'");
}
}
if (!is_empty_line())
error("expected empty line");
next_line();
}
catch(POParserError&)
{
}
}
}
} // namespace tinygettext
/* EOF */
<commit_msg>[tinygettext] Precache string length in loop (DEBUG builds optimization)<commit_after>// tinygettext - A gettext replacement that works directly on .po files
// Copyright (C) 2009 Ingo Ruhnke <grumbel@gmx.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "po_parser.hpp"
#include <iostream>
#include <ctype.h>
#include <string>
#include <istream>
#include <string.h>
#include <map>
#include <stddef.h> // for size_t
#include <stdlib.h>
#include "language.hpp"
#include "log_stream.hpp"
#include "iconv.hpp"
#include "dictionary.hpp"
#include "plural_forms.hpp"
namespace tinygettext {
bool POParser::pedantic = true;
void
POParser::parse(const std::string& filename, std::istream& in, Dictionary& dict)
{
POParser parser(filename, in, dict);
parser.parse();
}
class POParserError {};
POParser::POParser(const std::string& filename_, std::istream& in_, Dictionary& dict_, bool use_fuzzy_) :
filename(filename_),
in(in_),
dict(dict_),
use_fuzzy(use_fuzzy_),
running(false),
eof(false),
big5(false),
line_number(0),
current_line(),
conv()
{
}
POParser::~POParser()
{
}
void
POParser::warning(const std::string& msg)
{
log_warning << filename << ":" << line_number << ": warning: " << msg << ": " << current_line << std::endl;
//log_warning << "Line: " << current_line << std::endl;
}
void
POParser::error(const std::string& msg)
{
log_error << filename << ":" << line_number << ": error: " << msg << ": " << current_line << std::endl;
// Try to recover from an error by searching for start of another entry
do
next_line();
while(!eof && !is_empty_line());
throw POParserError();
}
void
POParser::next_line()
{
line_number += 1;
if (!std::getline(in, current_line))
eof = true;
}
void
POParser::get_string_line(std::ostringstream& out,unsigned int skip)
{
if (skip+1 >= static_cast<unsigned int>(current_line.size()))
error("unexpected end of line");
if (current_line[skip] != '"')
error("expected start of string '\"'");
std::string::size_type i;
for(i = skip+1; current_line[i] != '\"'; ++i)
{
if (big5 && static_cast<unsigned char>(current_line[i]) >= 0x81 && static_cast<unsigned char>(current_line[i]) <= 0xfe)
{
out << current_line[i];
i += 1;
if (i >= current_line.size())
error("invalid big5 encoding");
out << current_line[i];
}
else if (i >= current_line.size())
{
error("unexpected end of string");
}
else if (current_line[i] == '\\')
{
i += 1;
if (i >= current_line.size())
error("unexpected end of string in handling '\\'");
switch (current_line[i])
{
case 'a': out << '\a'; break;
case 'b': out << '\b'; break;
case 'v': out << '\v'; break;
case 'n': out << '\n'; break;
case 't': out << '\t'; break;
case 'r': out << '\r'; break;
case '"': out << '"'; break;
case '\\': out << '\\'; break;
default:
std::ostringstream err;
err << "unhandled escape '\\" << current_line[i] << "'";
warning(err.str());
out << current_line[i-1] << current_line[i];
break;
}
}
else
{
out << current_line[i];
}
}
// process trailing garbage in line and warn if there is any
for(i = i+1; i < current_line.size(); ++i)
if (!isspace(current_line[i]))
{
warning("unexpected garbage after string ignoren");
break;
}
}
std::string
POParser::get_string(unsigned int skip)
{
std::ostringstream out;
if (skip+1 >= static_cast<unsigned int>(current_line.size()))
error("unexpected end of line");
if (current_line[skip] == ' ' && current_line[skip+1] == '"')
{
get_string_line(out, skip+1);
}
else
{
if (pedantic)
warning("keyword and string must be seperated by a single space");
for(;;)
{
if (skip >= static_cast<unsigned int>(current_line.size()))
error("unexpected end of line");
else if (current_line[skip] == '\"')
{
get_string_line(out, skip);
break;
}
else if (!isspace(current_line[skip]))
{
error("string must start with '\"'");
}
else
{
// skip space
}
skip += 1;
}
}
next:
next_line();
for(std::string::size_type i = 0; i < current_line.size(); ++i)
{
if (current_line[i] == '"')
{
if (i == 1)
if (pedantic)
warning("leading whitespace before string");
get_string_line(out, i);
goto next;
}
else if (isspace(current_line[i]))
{
// skip
}
else
{
break;
}
}
return out.str();
}
static bool has_prefix(const std::string& lhs, const std::string rhs)
{
if (lhs.length() < rhs.length())
return false;
else
return lhs.compare(0, rhs.length(), rhs) == 0;
}
void
POParser::parse_header(const std::string& header)
{
std::string from_charset;
std::string::size_type start = 0;
const char content_type[] = "Content-Type: text/plain; charset=";
const size_t content_type_len = strlen(content_type);
for(std::string::size_type i = 0; i < header.length(); ++i)
{
if (header[i] == '\n')
{
std::string line = header.substr(start, i - start);
if (has_prefix(line, "Content-Type:"))
{
// from_charset = line.substr(len);
if (line.compare(0, content_type_len, content_type) == 0)
{
from_charset = line.substr(content_type_len);
for(std::string::iterator ch = from_charset.begin(); ch != from_charset.end(); ++ch)
*ch = static_cast<char>(toupper(*ch));
}
else
{
warning("malformed Content-Type header");
}
}
else if (has_prefix(line, "Plural-Forms:"))
{
PluralForms plural_forms = PluralForms::from_string(line);
if (!plural_forms)
{
warning("unknown Plural-Forms given");
}
else
{
if (!dict.get_plural_forms())
{
dict.set_plural_forms(plural_forms);
}
else
{
if (dict.get_plural_forms() != plural_forms)
{
warning("Plural-Forms missmatch between .po file and dictionary");
}
}
}
}
start = i+1;
}
}
if (from_charset.empty() || from_charset == "CHARSET")
{
warning("charset not specified for .po, fallback to utf-8");
from_charset = "UTF-8";
}
else if (from_charset == "BIG5")
{
big5 = true;
}
conv.set_charsets(from_charset, dict.get_charset());
}
bool
POParser::is_empty_line()
{
if (current_line.empty())
{
return true;
}
else if (current_line[0] == '#')
{ // handle comments as empty lines
if (current_line.size() == 1 || (current_line.size() >= 2 && isspace(current_line[1])))
return true;
else
return false;
}
else
{
for(std::string::iterator i = current_line.begin(); i != current_line.end(); ++i)
{
if (!isspace(*i))
return false;
}
}
return true;
}
bool
POParser::prefix(const char* prefix_str)
{
return current_line.compare(0, strlen(prefix_str), prefix_str) == 0;
}
void
POParser::parse()
{
next_line();
// skip UTF-8 intro that some text editors produce
// see http://en.wikipedia.org/wiki/Byte-order_mark
if (current_line.size() >= 3 &&
current_line[0] == '\xef' &&
current_line[1] == '\xbb' &&
current_line[2] == '\xbf')
{
current_line = current_line.substr(3);
}
// Parser structure
while(!eof)
{
try
{
bool fuzzy = false;
bool has_msgctxt = false;
std::string msgctxt;
std::string msgid;
while(prefix("#"))
{
if (current_line.size() >= 2 && current_line[1] == ',')
{
// FIXME: Rather simplistic hunt for fuzzy flag
if (current_line.find("fuzzy", 2) != std::string::npos)
fuzzy = true;
}
next_line();
}
if (!is_empty_line())
{
if (prefix("msgctxt"))
{
has_msgctxt = true;
msgctxt = get_string(7);
}
if (prefix("msgid"))
msgid = get_string(5);
else
error("expected 'msgid'");
if (prefix("msgid_plural"))
{
std::string msgid_plural = get_string(12);
std::vector<std::string> msgstr_num;
bool saw_nonempty_msgstr = false;
next:
if (is_empty_line())
{
if (msgstr_num.empty())
error("expected 'msgstr[N] (0 <= N <= 9)'");
}
else if (prefix("msgstr[") &&
current_line.size() > 8 &&
isdigit(current_line[7]) && current_line[8] == ']')
{
unsigned int number = static_cast<unsigned int>(current_line[7] - '0');
std::string msgstr = get_string(9);
if(!msgstr.empty())
saw_nonempty_msgstr = true;
if (number >= msgstr_num.size())
msgstr_num.resize(number+1);
msgstr_num[number] = conv.convert(msgstr);
goto next;
}
else
{
error("expected 'msgstr[N]'");
}
if (!is_empty_line())
error("expected 'msgstr[N]' or empty line");
if (saw_nonempty_msgstr)
{
if (use_fuzzy || !fuzzy)
{
if (!dict.get_plural_forms())
{
warning("msgstr[N] seen, but no Plural-Forms given");
}
else
{
if (msgstr_num.size() != dict.get_plural_forms().get_nplural())
{
warning("msgstr[N] count doesn't match Plural-Forms.nplural");
}
}
if (has_msgctxt)
dict.add_translation(msgctxt, msgid, msgid_plural, msgstr_num);
else
dict.add_translation(msgid, msgid_plural, msgstr_num);
}
if (0)
{
std::cout << (fuzzy?"fuzzy":"not-fuzzy") << std::endl;
std::cout << "msgid \"" << msgid << "\"" << std::endl;
std::cout << "msgid_plural \"" << msgid_plural << "\"" << std::endl;
for(std::vector<std::string>::size_type i = 0; i < msgstr_num.size(); ++i)
std::cout << "msgstr[" << i << "] \"" << conv.convert(msgstr_num[i]) << "\"" << std::endl;
std::cout << std::endl;
}
}
}
else if (prefix("msgstr"))
{
std::string msgstr = get_string(6);
if (msgid.empty())
{
parse_header(msgstr);
}
else if(!msgstr.empty())
{
if (use_fuzzy || !fuzzy)
{
if (has_msgctxt)
dict.add_translation(msgctxt, msgid, conv.convert(msgstr));
else
dict.add_translation(msgid, conv.convert(msgstr));
}
if (0)
{
std::cout << (fuzzy?"fuzzy":"not-fuzzy") << std::endl;
std::cout << "msgid \"" << msgid << "\"" << std::endl;
std::cout << "msgstr \"" << conv.convert(msgstr) << "\"" << std::endl;
std::cout << std::endl;
}
}
}
else
{
error("expected 'msgstr' or 'msgid_plural'");
}
}
if (!is_empty_line())
error("expected empty line");
next_line();
}
catch(POParserError&)
{
}
}
}
} // namespace tinygettext
/* EOF */
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: chips/p9/procedures/hwp/initfiles/p9_fbc_cd_hp_scom.C $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_fbc_cd_hp_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
#include <attribute_ids.H>
#include <target_types.H>
#include <fapi2_attribute_service.H>
using namespace fapi2;
fapi2::ReturnCode p9_fbc_cd_hp_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
fapi2::ReturnCode l_rc = 0;
do
{
}
while(0);
return l_rc;
}
<commit_msg>initCompiler: update all initfile procedures with latest initCompiler<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: chips/p9/procedures/hwp/initfiles/p9_fbc_cd_hp_scom.C $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_fbc_cd_hp_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
fapi2::ReturnCode p9_fbc_cd_hp_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
fapi2::ReturnCode l_rc = 0;
do
{
fapi2::buffer<uint64_t> l_scom_buffer;
}
while (0);
return l_rc;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_cppm.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
// *INDENT-OFF*
///
/// @file p9_pm_recovery_ffdc_cppm.C
/// @brief PPM FFDC collection of PM complex
///
/// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner: Prasad Bg Ranganath <prasadbgr@in.ibm.com>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_quad_scom_addresses.H>
#include <p9_pm_recovery_ffdc_cppm.H>
#include <collect_reg_ffdc.H>
#include <stddef.h>
#include <endian.h>
namespace p9_stop_recov_ffdc
{
CppmRegs::CppmRegs( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt )
: PlatPmComplex ( i_procChipTgt, PLAT_CPPM )
{ }
//----------------------------------------------------------------------
void CppmRegs::initRegList()
{
std::vector < uint32_t> l_scomRegList;
l_scomRegList.push_back( C_PPM_SSHSRC );
l_scomRegList.push_back( C_PPM_VDMCR );
PlatPmComplex::updateSummaryList( l_scomRegList );
}
//----------------------------------------------------------------------
fapi2::ReturnCode CppmRegs::init ( void* i_pHomerBuf )
{
FAPI_DBG (">> CppmRegs::init" );
FAPI_TRY ( collectFfdc( i_pHomerBuf, INIT),
"Failed To Init CPPM REGS FFDC" );
fapi_try_exit:
FAPI_DBG ("<< CppmRegs::init" );
return fapi2::current_err;
}
//----------------------------------------------------------------------
fapi2::ReturnCode CppmRegs::collectFfdc( void* i_pHomerBuf,
uint8_t i_ffdcType )
{
FAPI_DBG(">> CppmRegs::collectFfdc");
fapi2::ReturnCode l_rc = fapi2::FAPI2_RC_SUCCESS;
uint8_t l_quadPos = 0;
uint8_t l_corePos = 0;
uint8_t* l_pCppmFfdcLoc = NULL;
uint8_t* l_pQuadFfdcLoc = NULL;
uint16_t l_cppmFfdcValid = 0;
uint16_t l_quadFfdcValid = 0;
HomerFfdcRegion * l_pHomerFfdc =
( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET );
auto l_quadList = getProcChip().getChildren<fapi2::TARGET_TYPE_EQ> (fapi2::TARGET_STATE_PRESENT);
for (auto& quad : l_quadList)
{
// @TODO via RTC 153978: define bitsets for quad sub-section validity
l_quadFfdcValid = 0;
FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, quad, l_quadPos),
"FAPI_ATTR_GET Failed To Read QUAD Position" );
l_pQuadFfdcLoc = &l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadFfdcHeader[0];
// @note: INIT applies to all present units, and is handled as default flow
// @note: CPPM headers for EQs that are not functionals will not be initialized
if (quad.isFunctional())
{
l_quadFfdcValid = 1;
auto l_coreList =
quad.getChildren< fapi2::TARGET_TYPE_CORE > ( fapi2::TARGET_STATE_PRESENT );
for (auto& core : l_coreList)
{
FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, core, l_corePos ),
"FAPI_ATTR_GET Failed To Read CORE Position" );
l_cppmFfdcValid = 0;
l_pCppmFfdcLoc = &l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadCppmRegion[l_corePos%MAX_CORES_PER_QUAD][0];
// Note: ( i_ffdcType & INIT ) is the default case, for all present cores
if( core.isFunctional() )
{
FAPI_INF("CPPM FFDC: Quad#%d Core#%d ", l_quadPos, (l_corePos%MAX_CORES_PER_QUAD));
if (i_ffdcType & SCOM_REG)
{
l_rc = collectRegisterData <fapi2::TARGET_TYPE_CORE> (core,
l_pCppmFfdcLoc + sizeof (PpmFfdcHeader),
fapi2::CPPM_FFDC_REGISTERS);
if (l_rc == fapi2::FAPI2_RC_SUCCESS)
{
l_cppmFfdcValid = 1;
}
}
}
FAPI_TRY( updateCppmFfdcHeader( l_pCppmFfdcLoc, l_corePos, l_cppmFfdcValid),
"Failed To Update CPPM FFDC Header for QUAD#%d CORE#%d", l_quadPos, (l_corePos%MAX_CORES_PER_QUAD));
}
}
FAPI_TRY( updateQuadFfdcHeader( l_pQuadFfdcLoc,l_quadPos, l_quadFfdcValid),
"Failed To Update Quad FFDC Header for EQ 0x%0d", l_quadPos );
setPmFfdcSectionValid ( i_pHomerBuf, (PM_FFDC_QUAD0_VALID << l_quadPos), l_quadFfdcValid);
}
if( !(i_ffdcType & INIT) )
{
generateSummary( i_pHomerBuf );
}
fapi_try_exit:
FAPI_DBG("<< CppmRegs::collectFfdc");
return fapi2::current_err;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode CppmRegs::updateCppmFfdcHeader( uint8_t * i_pHomerBuf,
const uint8_t i_corePos,
const uint16_t i_ffdcValid)
{
FAPI_DBG(">> updateCppmFfdcHeader" );
PpmFfdcHeader * l_CppmFfdcHdr = (PpmFfdcHeader *) i_pHomerBuf ;
l_CppmFfdcHdr->iv_ppmMagicWord = htobe32(FFDC_CPPM_MAGIC_NUM);
l_CppmFfdcHdr->iv_versionMajor = 1;
l_CppmFfdcHdr->iv_versionMinor = 0;
l_CppmFfdcHdr->iv_Instance = i_corePos; // CHIP_UNIT_POS
l_CppmFfdcHdr->iv_ppmHeaderSize = htobe16 (sizeof(PpmFfdcHeader));
l_CppmFfdcHdr->iv_sectionSize = htobe16 (FFDC_CPPM_REGION_SIZE);
l_CppmFfdcHdr->iv_ffdcValid = htobe16 (i_ffdcValid);
FAPI_DBG("<< updateCppmFfdcHeader" );
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode CppmRegs::updateQuadFfdcHeader( uint8_t* i_pHomerBuf,
const uint8_t i_eqPos,
const uint16_t i_ffdcValid)
{
FAPI_DBG(">> updateQuadFfdcHeader" );
QuadFfdcHeader* l_QuadFfdcHdr = (QuadFfdcHeader*) i_pHomerBuf ;
l_QuadFfdcHdr->iv_quadMagicWord = htobe32(FFDC_QUAD_MAGIC_NUM);
l_QuadFfdcHdr->iv_versionMajor = 1;
l_QuadFfdcHdr->iv_versionMinor = 0;
l_QuadFfdcHdr->iv_quadInstance = i_eqPos;
l_QuadFfdcHdr->iv_quadHeaderSize = htobe16 (sizeof(QuadFfdcHeader));
l_QuadFfdcHdr->iv_sectionSize = htobe16 (sizeof(HomerQuadFfdcRegion));
l_QuadFfdcHdr->iv_offsetCppm0 = htobe16(offsetof (struct HomerQuadFfdcRegion,
iv_quadCppmRegion[0][0]));
l_QuadFfdcHdr->iv_offsetCppm1 = htobe16(offsetof (struct HomerQuadFfdcRegion,
iv_quadCppmRegion[1][0]));
l_QuadFfdcHdr->iv_offsetCppm2 = htobe16(offsetof (struct HomerQuadFfdcRegion,
iv_quadCppmRegion[2][0]));
l_QuadFfdcHdr->iv_offsetCppm3 = htobe16(offsetof (struct HomerQuadFfdcRegion,
iv_quadCppmRegion[3][0]));
l_QuadFfdcHdr->iv_offsetCme0 = htobe16(offsetof(struct HomerQuadFfdcRegion,
iv_quadCmeBlock[0][0]));
l_QuadFfdcHdr->iv_offsetCme1 = htobe16(offsetof(struct HomerQuadFfdcRegion,
iv_quadCmeBlock[1][0]));
l_QuadFfdcHdr->iv_offsetQppm = htobe16(offsetof(struct HomerQuadFfdcRegion,
iv_quadQppmRegion[0]));
l_QuadFfdcHdr->iv_sectionsValid = htobe16 (i_ffdcValid);
FAPI_DBG("<< updateQuadFfdcHeader" );
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode CppmRegs::generateSummary( void * i_pHomer )
{
HomerFfdcRegion * l_pHomerFfdc =
( HomerFfdcRegion *)( (uint8_t *)i_pHomer + FFDC_REGION_HOMER_BASE_OFFSET );
uint8_t* l_pCppmFfdcLoc = NULL;
PpmFfdcHeader * l_pCppmHdr = NULL;
uint8_t * l_pCppmSummary = NULL;
uint8_t l_quadPos = 0;
uint8_t l_relCorePos = 0;
initRegList();
uint32_t l_sizeLimit = FFDC_CPPM_REGION_SIZE - sizeof( PpmFfdcHeader );
for( uint8_t l_ppmPos = 0; l_ppmPos < MAX_CORES_PER_CHIP; l_ppmPos++ )
{
l_relCorePos = l_ppmPos % MAX_CORES_PER_QUAD;
l_quadPos = l_ppmPos >> 2;
l_pCppmFfdcLoc =
&l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadCppmRegion[l_relCorePos][0];
l_pCppmSummary = &l_pHomerFfdc->iv_ffdcSummaryRegion.iv_cpmmRegSummary[l_ppmPos][FFDC_SUMMARY_SEC_HDR_SIZE];
l_pCppmHdr = ( PpmFfdcHeader *) &l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadCppmRegion[l_relCorePos][0];
FfdcSummSubSectHdr * l_pCppmSummaryHdr =
(FfdcSummSubSectHdr *)&l_pHomerFfdc->iv_ffdcSummaryRegion.iv_cpmmRegSummary[l_ppmPos][0];
l_pCppmSummaryHdr->iv_subSectnId = PLAT_CPPM;
l_pCppmSummaryHdr->iv_majorNum = 1;
l_pCppmSummaryHdr->iv_minorNum = 0;
l_pCppmSummaryHdr->iv_secValid = htobe16( l_pCppmHdr->iv_ffdcValid );
if( !l_pCppmSummaryHdr->iv_secValid )
{
continue;
}
PlatPmComplex::extractScomSummaryReg( l_pCppmFfdcLoc + sizeof(PpmFfdcHeader),
l_sizeLimit, l_pCppmSummary );
}
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
extern "C"
{
fapi2::ReturnCode p9_pm_recovery_ffdc_cppm( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip, void * i_pFfdcBuf )
{
FAPI_IMP(">> p9_pm_recovery_ffdc_cppm" );
CppmRegs l_cppmFfdc( i_procChip );
FAPI_TRY( l_cppmFfdc.collectFfdc( i_pFfdcBuf, SCOM_REG ),
"Failed To Collect CPPM FFDC" );
fapi_try_exit:
FAPI_IMP("<< p9_pm_recovery_ffdc_cppm" );
return fapi2::current_err;
}
}
}//namespace p9_stop_recov_ffdc ends
<commit_msg>Extend PM Reset flow to collect PM FFDC to HOMER<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_cppm.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
// *INDENT-OFF*
///
/// @file p9_pm_recovery_ffdc_cppm.C
/// @brief PPM FFDC collection of PM complex
///
/// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner: Prasad Bg Ranganath <prasadbgr@in.ibm.com>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_quad_scom_addresses.H>
#include <p9_pm_recovery_ffdc_cppm.H>
#include <collect_reg_ffdc.H>
#include <stddef.h>
#include <endian.h>
namespace p9_stop_recov_ffdc
{
CppmRegs::CppmRegs( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt )
: PlatPmComplex ( i_procChipTgt, PLAT_CPPM )
{ }
//----------------------------------------------------------------------
void CppmRegs::initRegList()
{
std::vector < uint32_t> l_scomRegList;
l_scomRegList.push_back( C_PPM_SSHSRC );
l_scomRegList.push_back( C_PPM_VDMCR );
PlatPmComplex::updateSummaryList( l_scomRegList );
}
//----------------------------------------------------------------------
fapi2::ReturnCode CppmRegs::init ( void* i_pHomerBuf )
{
FAPI_DBG (">> CppmRegs::init" );
FAPI_TRY ( collectFfdc( i_pHomerBuf, INIT),
"Failed To Init CPPM REGS FFDC" );
fapi_try_exit:
FAPI_DBG ("<< CppmRegs::init" );
return fapi2::current_err;
}
//----------------------------------------------------------------------
fapi2::ReturnCode CppmRegs::collectFfdc( void* i_pHomerBuf,
uint8_t i_ffdcType )
{
FAPI_DBG(">> CppmRegs::collectFfdc");
fapi2::ReturnCode l_rc = fapi2::FAPI2_RC_SUCCESS;
uint8_t l_quadPos = 0;
uint8_t l_corePos = 0;
uint8_t* l_pCppmFfdcLoc = NULL;
uint8_t* l_pQuadFfdcLoc = NULL;
uint16_t l_cppmFfdcValid = 0;
uint16_t l_quadFfdcValid = 0;
HomerFfdcRegion * l_pHomerFfdc =
( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET );
auto l_quadList = getProcChip().getChildren<fapi2::TARGET_TYPE_EQ> (fapi2::TARGET_STATE_PRESENT);
for (auto& quad : l_quadList)
{
// @TODO via RTC 153978: define bitsets for quad sub-section validity
l_quadFfdcValid = 0;
FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, quad, l_quadPos),
"FAPI_ATTR_GET Failed To Read QUAD Position" );
l_pQuadFfdcLoc = &l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadFfdcHeader[0];
// @note: INIT applies to all present units, and is handled as default flow
// @note: CPPM headers for EQs that are not functionals will not be initialized
if (quad.isFunctional())
{
l_quadFfdcValid = 1;
auto l_coreList =
quad.getChildren< fapi2::TARGET_TYPE_CORE > ( fapi2::TARGET_STATE_PRESENT );
for (auto& core : l_coreList)
{
FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, core, l_corePos ),
"FAPI_ATTR_GET Failed To Read CORE Position" );
l_cppmFfdcValid = 0;
l_pCppmFfdcLoc = &l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadCppmRegion[l_corePos%MAX_CORES_PER_QUAD][0];
// Note: ( i_ffdcType & INIT ) is the default case, for all present cores
if( core.isFunctional() )
{
FAPI_INF("CPPM FFDC: Quad#%d Core#%d ", l_quadPos, (l_corePos%MAX_CORES_PER_QUAD));
if (i_ffdcType & SCOM_REG)
{
l_rc = collectRegisterData <fapi2::TARGET_TYPE_CORE> (core,
l_pCppmFfdcLoc + sizeof (PpmFfdcHeader),
fapi2::CPPM_FFDC_REGISTERS);
if (l_rc == fapi2::FAPI2_RC_SUCCESS)
{
l_cppmFfdcValid = 1;
}
}
}
FAPI_TRY( updateCppmFfdcHeader( l_pCppmFfdcLoc, l_corePos, l_cppmFfdcValid),
"Failed To Update CPPM FFDC Header for QUAD#%d CORE#%d", l_quadPos, (l_corePos%MAX_CORES_PER_QUAD));
}
}
FAPI_TRY( updateQuadFfdcHeader( l_pQuadFfdcLoc,l_quadPos, l_quadFfdcValid),
"Failed To Update Quad FFDC Header for EQ 0x%0d", l_quadPos );
setPmFfdcSectionValid ( i_pHomerBuf, (PM_FFDC_QUAD0_VALID << l_quadPos), l_quadFfdcValid);
}
if( !(i_ffdcType & INIT) )
{
generateSummary( i_pHomerBuf );
}
fapi_try_exit:
logPmResetPhase (i_pHomerBuf);
FAPI_DBG("<< CppmRegs::collectFfdc");
return fapi2::current_err;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode CppmRegs::updateCppmFfdcHeader( uint8_t * i_pHomerBuf,
const uint8_t i_corePos,
const uint16_t i_ffdcValid)
{
FAPI_DBG(">> updateCppmFfdcHeader" );
PpmFfdcHeader * l_CppmFfdcHdr = (PpmFfdcHeader *) i_pHomerBuf ;
l_CppmFfdcHdr->iv_ppmMagicWord = htobe32(FFDC_CPPM_MAGIC_NUM);
l_CppmFfdcHdr->iv_versionMajor = 1;
l_CppmFfdcHdr->iv_versionMinor = 0;
l_CppmFfdcHdr->iv_Instance = i_corePos; // CHIP_UNIT_POS
l_CppmFfdcHdr->iv_ppmHeaderSize = htobe16 (sizeof(PpmFfdcHeader));
l_CppmFfdcHdr->iv_sectionSize = htobe16 (FFDC_CPPM_REGION_SIZE);
l_CppmFfdcHdr->iv_ffdcValid = htobe16 (i_ffdcValid);
FAPI_DBG("<< updateCppmFfdcHeader" );
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode CppmRegs::updateQuadFfdcHeader( uint8_t* i_pHomerBuf,
const uint8_t i_eqPos,
const uint16_t i_ffdcValid)
{
FAPI_DBG(">> updateQuadFfdcHeader" );
QuadFfdcHeader* l_QuadFfdcHdr = (QuadFfdcHeader*) i_pHomerBuf ;
l_QuadFfdcHdr->iv_quadMagicWord = htobe32(FFDC_QUAD_MAGIC_NUM);
l_QuadFfdcHdr->iv_versionMajor = 1;
l_QuadFfdcHdr->iv_versionMinor = 0;
l_QuadFfdcHdr->iv_quadInstance = i_eqPos;
l_QuadFfdcHdr->iv_quadHeaderSize = htobe16 (sizeof(QuadFfdcHeader));
l_QuadFfdcHdr->iv_sectionSize = htobe16 (sizeof(HomerQuadFfdcRegion));
l_QuadFfdcHdr->iv_offsetCppm0 = htobe16(offsetof (struct HomerQuadFfdcRegion,
iv_quadCppmRegion[0][0]));
l_QuadFfdcHdr->iv_offsetCppm1 = htobe16(offsetof (struct HomerQuadFfdcRegion,
iv_quadCppmRegion[1][0]));
l_QuadFfdcHdr->iv_offsetCppm2 = htobe16(offsetof (struct HomerQuadFfdcRegion,
iv_quadCppmRegion[2][0]));
l_QuadFfdcHdr->iv_offsetCppm3 = htobe16(offsetof (struct HomerQuadFfdcRegion,
iv_quadCppmRegion[3][0]));
l_QuadFfdcHdr->iv_offsetCme0 = htobe16(offsetof(struct HomerQuadFfdcRegion,
iv_quadCmeBlock[0][0]));
l_QuadFfdcHdr->iv_offsetCme1 = htobe16(offsetof(struct HomerQuadFfdcRegion,
iv_quadCmeBlock[1][0]));
l_QuadFfdcHdr->iv_offsetQppm = htobe16(offsetof(struct HomerQuadFfdcRegion,
iv_quadQppmRegion[0]));
l_QuadFfdcHdr->iv_sectionsValid = htobe16 (i_ffdcValid);
FAPI_DBG("<< updateQuadFfdcHeader" );
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode CppmRegs::generateSummary( void * i_pHomer )
{
HomerFfdcRegion * l_pHomerFfdc =
( HomerFfdcRegion *)( (uint8_t *)i_pHomer + FFDC_REGION_HOMER_BASE_OFFSET );
uint8_t* l_pCppmFfdcLoc = NULL;
PpmFfdcHeader * l_pCppmHdr = NULL;
uint8_t * l_pCppmSummary = NULL;
uint8_t l_quadPos = 0;
uint8_t l_relCorePos = 0;
initRegList();
uint32_t l_sizeLimit = FFDC_CPPM_REGION_SIZE - sizeof( PpmFfdcHeader );
for( uint8_t l_ppmPos = 0; l_ppmPos < MAX_CORES_PER_CHIP; l_ppmPos++ )
{
l_relCorePos = l_ppmPos % MAX_CORES_PER_QUAD;
l_quadPos = l_ppmPos >> 2;
l_pCppmFfdcLoc =
&l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadCppmRegion[l_relCorePos][0];
l_pCppmSummary = &l_pHomerFfdc->iv_ffdcSummaryRegion.iv_cpmmRegSummary[l_ppmPos][FFDC_SUMMARY_SEC_HDR_SIZE];
l_pCppmHdr = ( PpmFfdcHeader *) &l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadCppmRegion[l_relCorePos][0];
FfdcSummSubSectHdr * l_pCppmSummaryHdr =
(FfdcSummSubSectHdr *)&l_pHomerFfdc->iv_ffdcSummaryRegion.iv_cpmmRegSummary[l_ppmPos][0];
l_pCppmSummaryHdr->iv_subSectnId = PLAT_CPPM;
l_pCppmSummaryHdr->iv_majorNum = 1;
l_pCppmSummaryHdr->iv_minorNum = 0;
l_pCppmSummaryHdr->iv_secValid = htobe16( l_pCppmHdr->iv_ffdcValid );
if( !l_pCppmSummaryHdr->iv_secValid )
{
continue;
}
PlatPmComplex::extractScomSummaryReg( l_pCppmFfdcLoc + sizeof(PpmFfdcHeader),
l_sizeLimit, l_pCppmSummary );
}
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
extern "C"
{
fapi2::ReturnCode p9_pm_recovery_ffdc_cppm( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip, void * i_pFfdcBuf )
{
FAPI_IMP(">> p9_pm_recovery_ffdc_cppm" );
CppmRegs l_cppmFfdc( i_procChip );
FAPI_TRY( l_cppmFfdc.collectFfdc( i_pFfdcBuf, SCOM_REG ),
"Failed To Collect CPPM FFDC" );
fapi_try_exit:
FAPI_IMP("<< p9_pm_recovery_ffdc_cppm" );
return fapi2::current_err;
}
}
}//namespace p9_stop_recov_ffdc ends
<|endoftext|>
|
<commit_before>/// \file ConfigureAndGetEventTriggerMaskAndCaloTriggerString.C
/// \ingroup CaloTrackCorrMacros
/// \brief Configuration of the event trigger
///
/// Configuration macro of the task event trigger, depending on trigger name,
/// specially for EMCal triggers.
/// The trigger event settings depend on special trigger names:
/// * default: Min bias like triggers, kMB or kINT7
/// * EMCAL_L0, DCAL_L0: EMCAL or DCAL L0 triggers kEMC7, kEMC8, kEMC1
/// * EMCAL_L1, DCAL_L1: EMCAL or DCAL L1 triggers, kEMCEGA, with name EG1 or EGA
/// * EMCAL_L2, DCAL_L2: EMCAL or DCAL L2 triggers, kEMCEGA, with name EG2
///
/// \author Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TString.h>
#include "AliVEvent.h"
#endif
///
/// Main method
///
/// The options that can be passed to the macro are:
/// \param trigger : name of the desired trigger. Special names depending on Calo triggers.
/// \param year : year
/// \param triggerString : specific trigger name string to select at analysis level
///
UInt_t ConfigureAndGetEventTriggerMaskAndCaloTriggerString
(TString trigger, Int_t year, TString & triggerString)
{
//printf("ConfigureAndGetEventTriggerCaloTrackCorr - Set event trigger class for %s in year %d\n",
// trigger.Data(),year);
triggerString = "";
if( trigger.Contains("INT") || trigger.Contains("MB") || trigger.Contains("default") )
{
return ( AliVEvent::kINT7 | AliVEvent::kMB );
}
else if(trigger.Contains("EMCAL_L0"))
{
triggerString = "EMC";
return ( AliVEvent::kEMC7 | AliVEvent::kEMC8 | AliVEvent::kEMC1 );
}
else if(trigger.Contains("DCAL_L0"))
{
triggerString = "DMC";
return ( AliVEvent::kEMC7 | AliVEvent::kEMC8 | AliVEvent::kEMC1 );
}
else if(trigger.Contains("EMCAL_L1"))
{
if(year > 2012) triggerString = "EG1";
// before 2013 only one kind of L1 trigger
return ( AliVEvent::kEMCEGA );
}
else if(trigger.Contains("DCAL_L1"))
{
triggerString = "DG1";
return ( AliVEvent::kEMCEGA );
}
else if(trigger.Contains("EMCAL_L2"))
{
triggerString = "EG2";
return ( AliVEvent::kEMCEGA );
}
else if(trigger.Contains("DCAL_L2"))
{
triggerString = "DG2";
return ( AliVEvent::kEMCEGA );
}
return 0;
}
<commit_msg>fix comment<commit_after>/// \file ConfigureAndGetEventTriggerMaskAndCaloTriggerString.C
/// \ingroup CaloTrackCorrMacros
/// \brief Configuration of the event trigger
///
/// Configuration macro of the task event trigger, depending on trigger name,
/// specially for EMCal triggers.
/// The trigger event settings depend on special trigger names:
/// * default: Min bias like triggers, kMB or kINT7
/// * EMCAL_L0, DCAL_L0: EMCal or DCal L0 triggers kEMC7, kEMC8, kEMC1
/// * EMCAL_L1, DCAL_L1: EMCal or DCal L1 triggers, kEMCEGA, with name EG1 or EGA
/// * EMCAL_L2, DCAL_L2: EMCal or DCal L1 triggers, kEMCEGA, with name EG2
///
/// \author Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TString.h>
#include "AliVEvent.h"
#endif
///
/// Main method
///
/// The options that can be passed to the macro are:
/// \param trigger : name of the desired trigger. Special names depending on Calo triggers.
/// \param year : year
/// \param triggerString : specific trigger name string to select at analysis level
///
UInt_t ConfigureAndGetEventTriggerMaskAndCaloTriggerString
(TString trigger, Int_t year, TString & triggerString)
{
//printf("ConfigureAndGetEventTriggerCaloTrackCorr - Set event trigger class for %s in year %d\n",
// trigger.Data(),year);
triggerString = "";
if( trigger.Contains("INT") || trigger.Contains("MB") || trigger.Contains("default") )
{
return ( AliVEvent::kINT7 | AliVEvent::kMB );
}
else if(trigger.Contains("EMCAL_L0"))
{
triggerString = "EMC";
return ( AliVEvent::kEMC7 | AliVEvent::kEMC8 | AliVEvent::kEMC1 );
}
else if(trigger.Contains("DCAL_L0"))
{
triggerString = "DMC";
return ( AliVEvent::kEMC7 | AliVEvent::kEMC8 | AliVEvent::kEMC1 );
}
else if(trigger.Contains("EMCAL_L1"))
{
if(year > 2012) triggerString = "EG1";
// before 2013 only one kind of L1 trigger
return ( AliVEvent::kEMCEGA );
}
else if(trigger.Contains("DCAL_L1"))
{
triggerString = "DG1";
return ( AliVEvent::kEMCEGA );
}
else if(trigger.Contains("EMCAL_L2"))
{
triggerString = "EG2";
return ( AliVEvent::kEMCEGA );
}
else if(trigger.Contains("DCAL_L2"))
{
triggerString = "DG2";
return ( AliVEvent::kEMCEGA );
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
/*
* Simple command shell designed as a more versatile replacement to the ChibiOS embedded shell.
*/
#pragma once
#include <ch.hpp>
#include <chprintf.h>
#include <memstreams.h>
#include <cstring>
#include <cstdint>
#include <cstdarg>
#include <cassert>
#include <zubax_chibios/os.hpp>
namespace os
{
namespace shell
{
/**
* This class wraps the underlying OS primitive used to access the shell communication channel.
*/
class BaseChannelWrapper
{
BaseChannel* channel_;
std::size_t writeExpandingCrLf(unsigned character_timeout_msec, const char* str)
{
std::size_t ret = 0;
for (const char* pc = str; *pc != '\0'; pc++)
{
if (*pc == '\n')
{
if (MSG_OK != chnPutTimeout(channel_, '\r', MS2ST(character_timeout_msec)))
{
break;
}
ret++;
}
if (MSG_OK != chnPutTimeout(channel_, *pc, MS2ST(character_timeout_msec)))
{
break;
}
ret++;
}
return ret;
}
public:
static constexpr unsigned DefaultWriteCharacterTimeoutMSec = 2;
BaseChannelWrapper(BaseChannel* chan) :
channel_(chan)
{ }
BaseChannel* getChannel() const { return channel_; }
void setChannel(BaseChannel* chan) { channel_ = chan; }
template <unsigned BufferSize = 200, unsigned CharacterTimeoutMSec = DefaultWriteCharacterTimeoutMSec>
std::size_t vprint(const char* format, va_list vl)
{
MemoryStream ms;
char buffer[BufferSize];
msObjectInit(&ms, reinterpret_cast<std::uint8_t*>(buffer), BufferSize, 0);
auto chp = reinterpret_cast<::BaseSequentialStream*>(&ms);
chvprintf(chp, format, vl);
chSequentialStreamPut(chp, 0);
return writeExpandingCrLf(CharacterTimeoutMSec, buffer);
}
template <typename... ReferToVPrintForArgs>
std::size_t print(const char* format, ...)
{
va_list vl;
va_start(vl, format);
const auto ret = vprint<ReferToVPrintForArgs...>(format, vl);
va_end(vl);
return ret;
}
int getChar(unsigned timeout_msec)
{
return chnGetTimeout(channel_, MS2ST(timeout_msec));
}
int putChar(char chr, unsigned timeout_msec = DefaultWriteCharacterTimeoutMSec)
{
return chnPutTimeout(channel_, chr, MS2ST(timeout_msec));
}
// More methods may be added in the future
};
/**
* Inherit this interface to implement a command handler.
*/
class ICommandHandler
{
ICommandHandler(const ICommandHandler&) = delete;
ICommandHandler& operator=(const ICommandHandler&) = delete;
protected:
ICommandHandler() { }
public:
virtual ~ICommandHandler() { }
virtual const char* getName() const = 0;
virtual void execute(BaseChannelWrapper& ios, int argc, char** argv) = 0;
};
/**
* Implementation details, do not use directly.
*/
namespace impl_
{
class Tokenizer // A la strtok()
{
char* token_ptr_ = nullptr;
public:
char* tokenize(char* str)
{
if (str)
{
token_ptr_ = str;
}
char* token = token_ptr_;
if (!token)
{
return NULL;
}
static const char* const Delims = " \t";
token += std::strspn(token, Delims);
token_ptr_ = std::strpbrk(token, Delims);
if (token_ptr_)
{
*token_ptr_++ = '\0';
}
return *token ? token : NULL;
}
};
class HelpCommandHandler : public ICommandHandler
{
const ICommandHandler* const* const command_handlers_;
const unsigned max_handlers_;
const char* getName() const override { return "help"; }
void execute(BaseChannelWrapper& ios, int, char**) override
{
ios.print("Available commands:\n");
auto x = command_handlers_;
for (unsigned i = 0; i < max_handlers_; i++)
{
if (*x != nullptr)
{
ios.print("\t%s\n", (*x)->getName());
}
x++;
}
}
public:
HelpCommandHandler(const ICommandHandler* const* handlers, unsigned max_handlers) :
command_handlers_(handlers),
max_handlers_(max_handlers)
{ }
};
}
/**
* Operating mode of the shell.
*/
enum class Mode
{
Normal, //!< Normal mode, regular shell behavior
Silent //!< No echo unless the command is recognized; no prompt. Useful for bootloaders etc.
};
/**
* Shell command processor class.
*/
template <unsigned MaxCommandHandlers = 10,
unsigned MaxLineLength = 200,
unsigned MaxCommandArguments = 8>
class Shell
{
ICommandHandler* command_handlers_[MaxCommandHandlers] = {};
char line_buffer_[MaxLineLength + 1] = {};
unsigned pos_ = 0;
bool need_prompt_ = true;
Mode mode_;
impl_::HelpCommandHandler help_command_handler_;
void echo(BaseChannelWrapper& ios, char chr) const
{
if (mode_ != Mode::Silent)
{
(void)ios.putChar(chr);
}
}
void processCommand(BaseChannelWrapper& ios, const char* line) const
{
// Creating a mutable copy of the line, as the original needs to be retained for silent mode
char mutable_copy_of_line[MaxLineLength + 1];
std::strncpy(mutable_copy_of_line, line, sizeof(mutable_copy_of_line));
// Tokenizing
char* argv[MaxCommandArguments] = {};
std::uint8_t argc = 0;
impl_::Tokenizer tokenizer;
{
char* token = tokenizer.tokenize(mutable_copy_of_line);
while (token != nullptr)
{
argv[argc++] = token;
if (argc >= MaxCommandArguments)
{
break;
}
token = tokenizer.tokenize(nullptr);
}
}
if (argc == 0)
{
return; // No command provided, ignore
}
// Command lookup, exit on success
for (auto x : command_handlers_)
{
if ((x != nullptr) && (std::strcmp(x->getName(), argv[0]) == 0))
{
// In silent mode we only echo if the command is recognized
if (mode_ == Mode::Silent)
{
(void)ios.print("%s\n", line);
}
x->execute(ios, argc, argv);
return;
}
}
// No such command
if (mode_ != Mode::Silent)
{
(void)ios.print("! ERROR: \"%s\"?\n", argv[0]);
}
}
public:
Shell(Mode mode = Mode::Normal) :
mode_(mode),
help_command_handler_(command_handlers_, MaxCommandHandlers)
{
addCommandHandler(&help_command_handler_);
}
Mode getMode() const { return mode_; }
void setMode(Mode mode) { mode_ = mode; }
bool addCommandHandler(ICommandHandler* chr)
{
for (auto& x : command_handlers_)
{
if (x == nullptr)
{
x = chr;
return true;
}
}
return false;
}
void runFor(BaseChannelWrapper& ios, unsigned run_duration_msec)
{
const auto run_duration_st = MS2ST(run_duration_msec);
const auto started_at_st = chVTGetSystemTime();
do
{
if (need_prompt_)
{
need_prompt_ = false;
if (mode_ != Mode::Silent)
{
(void)ios.print("> ");
}
}
// Reading new character
const auto elapsed = chVTTimeElapsedSinceX(started_at_st);
const auto read_timeout_st = (run_duration_st > elapsed) ? (run_duration_st - elapsed) : 1;
const auto chr = ios.getChar(std::max(1U, unsigned(ST2MS(read_timeout_st))));
if (chr < 0)
{
continue;
}
// Processing the character
if (chr == '\r') // End of command
{
echo(ios, '\r');
echo(ios, '\n');
line_buffer_[pos_] = '\0';
if (pos_ > 0)
{
processCommand(ios, line_buffer_);
}
reset();
}
else if (chr == 8 || chr == 127) // DEL or BS (backspace)
{
if (pos_ > 0)
{
echo(ios, 8); // Erase last char and move caret back
echo(ios, ' '); // Put space on top of the erased character
echo(ios, 8); // Move the caret back again
pos_ -= 1;
}
}
else if (chr >= 32) // Normal printable ASCII character and everything above ASCII
{
if (pos_ < MaxLineLength)
{
echo(ios, chr);
line_buffer_[pos_++] = char(chr);
}
}
else // This also includes Ctrl+C, Ctrl+D, and LF
{
; // Invalid byte - ignore
}
// Invariants
assert(pos_ <= MaxLineLength);
}
while (chVTTimeElapsedSinceX(started_at_st) <= run_duration_st);
}
void reset()
{
assert(pos_ <= MaxLineLength);
pos_ = 0;
need_prompt_ = true;
}
};
}
}
<commit_msg>Warning fix in CLI<commit_after>/*
* Copyright (c) 2016 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
/*
* Simple command shell designed as a more versatile replacement to the ChibiOS embedded shell.
*/
#pragma once
#include <ch.hpp>
#include <chprintf.h>
#include <memstreams.h>
#include <cstring>
#include <cstdint>
#include <cstdarg>
#include <cassert>
#include <zubax_chibios/os.hpp>
namespace os
{
namespace shell
{
/**
* This class wraps the underlying OS primitive used to access the shell communication channel.
*/
class BaseChannelWrapper
{
BaseChannel* channel_;
std::size_t writeExpandingCrLf(unsigned character_timeout_msec, const char* str)
{
std::size_t ret = 0;
for (const char* pc = str; *pc != '\0'; pc++)
{
if (*pc == '\n')
{
if (MSG_OK != chnPutTimeout(channel_, '\r', MS2ST(character_timeout_msec)))
{
break;
}
ret++;
}
if (MSG_OK != chnPutTimeout(channel_, *pc, MS2ST(character_timeout_msec)))
{
break;
}
ret++;
}
return ret;
}
public:
static constexpr unsigned DefaultWriteCharacterTimeoutMSec = 2;
BaseChannelWrapper(BaseChannel* chan) :
channel_(chan)
{ }
BaseChannel* getChannel() const { return channel_; }
void setChannel(BaseChannel* chan) { channel_ = chan; }
template <unsigned BufferSize = 200, unsigned CharacterTimeoutMSec = DefaultWriteCharacterTimeoutMSec>
std::size_t vprint(const char* format, va_list vl)
{
MemoryStream ms;
char buffer[BufferSize];
msObjectInit(&ms, reinterpret_cast<std::uint8_t*>(buffer), BufferSize, 0);
auto chp = reinterpret_cast<::BaseSequentialStream*>(&ms);
chvprintf(chp, format, vl);
chSequentialStreamPut(chp, 0);
return writeExpandingCrLf(CharacterTimeoutMSec, buffer);
}
template <typename... ReferToVPrintForArgs>
std::size_t print(const char* format, ...)
{
va_list vl;
va_start(vl, format);
const auto ret = vprint<ReferToVPrintForArgs...>(format, vl);
va_end(vl);
return ret;
}
int getChar(unsigned timeout_msec)
{
return chnGetTimeout(channel_, MS2ST(timeout_msec));
}
int putChar(char chr, unsigned timeout_msec = DefaultWriteCharacterTimeoutMSec)
{
return chnPutTimeout(channel_, chr, MS2ST(timeout_msec));
}
// More methods may be added in the future
};
/**
* Inherit this interface to implement a command handler.
*/
class ICommandHandler
{
ICommandHandler(const ICommandHandler&) = delete;
ICommandHandler& operator=(const ICommandHandler&) = delete;
protected:
ICommandHandler() { }
public:
virtual ~ICommandHandler() { }
virtual const char* getName() const = 0;
virtual void execute(BaseChannelWrapper& ios, int argc, char** argv) = 0;
};
/**
* Implementation details, do not use directly.
*/
namespace impl_
{
class Tokenizer // A la strtok()
{
char* token_ptr_ = nullptr;
public:
char* tokenize(char* str)
{
if (str)
{
token_ptr_ = str;
}
char* token = token_ptr_;
if (!token)
{
return NULL;
}
static const char* const Delims = " \t";
token += std::strspn(token, Delims);
token_ptr_ = std::strpbrk(token, Delims);
if (token_ptr_)
{
*token_ptr_++ = '\0';
}
return *token ? token : NULL;
}
};
class HelpCommandHandler : public ICommandHandler
{
const ICommandHandler* const* const command_handlers_;
const unsigned max_handlers_;
const char* getName() const override { return "help"; }
void execute(BaseChannelWrapper& ios, int, char**) override
{
ios.print("Available commands:\n");
auto x = command_handlers_;
for (unsigned i = 0; i < max_handlers_; i++)
{
if (*x != nullptr)
{
ios.print("\t%s\n", (*x)->getName());
}
x++;
}
}
public:
HelpCommandHandler(const ICommandHandler* const* handlers, unsigned max_handlers) :
command_handlers_(handlers),
max_handlers_(max_handlers)
{ }
};
}
/**
* Operating mode of the shell.
*/
enum class Mode
{
Normal, //!< Normal mode, regular shell behavior
Silent //!< No echo unless the command is recognized; no prompt. Useful for bootloaders etc.
};
/**
* Shell command processor class.
*/
template <unsigned MaxCommandHandlers = 10,
unsigned MaxLineLength = 200,
unsigned MaxCommandArguments = 8>
class Shell
{
ICommandHandler* command_handlers_[MaxCommandHandlers] = {};
char line_buffer_[MaxLineLength + 1] = {};
unsigned pos_ = 0;
bool need_prompt_ = true;
Mode mode_;
impl_::HelpCommandHandler help_command_handler_;
void echo(BaseChannelWrapper& ios, char chr) const
{
if (mode_ != Mode::Silent)
{
(void)ios.putChar(chr);
}
}
void processCommand(BaseChannelWrapper& ios, const char* line) const
{
// Creating a mutable copy of the line, as the original needs to be retained for silent mode
char mutable_copy_of_line[MaxLineLength + 1];
std::strncpy(mutable_copy_of_line, line, sizeof(mutable_copy_of_line));
// Tokenizing
char* argv[MaxCommandArguments] = {};
std::uint8_t argc = 0;
impl_::Tokenizer tokenizer;
{
char* token = tokenizer.tokenize(mutable_copy_of_line);
while (token != nullptr)
{
argv[argc++] = token;
if (argc >= MaxCommandArguments)
{
break;
}
token = tokenizer.tokenize(nullptr);
}
}
if (argc == 0)
{
return; // No command provided, ignore
}
// Command lookup, exit on success
for (auto x : command_handlers_)
{
if ((x != nullptr) && (std::strcmp(x->getName(), argv[0]) == 0))
{
// In silent mode we only echo if the command is recognized
if (mode_ == Mode::Silent)
{
(void)ios.print("%s\n", line);
}
x->execute(ios, argc, argv);
return;
}
}
// No such command
if (mode_ != Mode::Silent)
{
(void)ios.print("! ERROR: \"%s\"?\n", argv[0]);
}
}
public:
Shell(Mode mode = Mode::Normal) :
mode_(mode),
help_command_handler_(command_handlers_, MaxCommandHandlers)
{
addCommandHandler(&help_command_handler_);
}
Mode getMode() const { return mode_; }
void setMode(Mode mode) { mode_ = mode; }
bool addCommandHandler(ICommandHandler* chr)
{
for (auto& x : command_handlers_)
{
if (x == nullptr)
{
x = chr;
return true;
}
}
return false;
}
void runFor(BaseChannelWrapper& ios, unsigned run_duration_msec)
{
const auto run_duration_st = MS2ST(run_duration_msec);
const auto started_at_st = chVTGetSystemTime();
do
{
if (need_prompt_)
{
need_prompt_ = false;
if (mode_ != Mode::Silent)
{
(void)ios.print("> ");
}
}
// Reading new character
const auto elapsed = chVTTimeElapsedSinceX(started_at_st);
const auto read_timeout_st = (run_duration_st > elapsed) ? (run_duration_st - elapsed) : 1;
const auto chr = ios.getChar(std::max(1U, unsigned(ST2MS(read_timeout_st))));
if (chr < 0)
{
continue;
}
// Processing the character
if (chr == '\r') // End of command
{
echo(ios, '\r');
echo(ios, '\n');
line_buffer_[pos_] = '\0';
if (pos_ > 0)
{
processCommand(ios, line_buffer_);
}
reset();
}
else if (chr == 8 || chr == 127) // DEL or BS (backspace)
{
if (pos_ > 0)
{
echo(ios, 8); // Erase last char and move caret back
echo(ios, ' '); // Put space on top of the erased character
echo(ios, 8); // Move the caret back again
pos_ -= 1;
}
}
else if (chr >= 32) // Normal printable ASCII character and everything above ASCII
{
if (pos_ < MaxLineLength)
{
echo(ios, char(chr));
line_buffer_[pos_++] = char(chr);
}
}
else // This also includes Ctrl+C, Ctrl+D, and LF
{
; // Invalid byte - ignore
}
// Invariants
assert(pos_ <= MaxLineLength);
}
while (chVTTimeElapsedSinceX(started_at_st) <= run_duration_st);
}
void reset()
{
assert(pos_ <= MaxLineLength);
pos_ = 0;
need_prompt_ = true;
}
};
}
}
<|endoftext|>
|
<commit_before>#include "HelloPolycodeApp.h"
HelloPolycodeApp::HelloPolycodeApp(PolycodeView *view) {
core = new POLYCODE_CORE(view, 640,480,false,false,0,0,90);
CoreServices::getInstance()->getResourceManager()->addArchive("Resources/default.pak");
CoreServices::getInstance()->getResourceManager()->addDirResource("default", false);
scene = new CollisionScene();
ScenePrimitive *ground = new ScenePrimitive(ScenePrimitive::TYPE_PLANE, 10, 10);
ground->loadTexture("Resources/green_texture.png");
scene->addEntity(ground);
box = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 0.5,0.5,0.5);
box->loadTexture("Resources/pink_texture.png");
box->setPosition(0,1,0);
scene->addCollisionChild(box, CollisionSceneEntity::SHAPE_BOX);
bigBox = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 2,2,2);
bigBox->loadTexture("Resources/pink_texture.png");
bigBox->setColor(0.0,1.0,1.0,0.5);
bigBox->setPosition(0,1,0);
scene->addCollisionChild(bigBox, CollisionSceneEntity::SHAPE_BOX);
scene->getDefaultCamera()->setPosition(7,7,7);
scene->getDefaultCamera()->lookAt(Vector3(0,0,0));
swingValue = 0;
}
HelloPolycodeApp::~HelloPolycodeApp() {
}
bool HelloPolycodeApp::Update() {
Number elapsed = core->getElapsed();
swingValue += elapsed;
box->setPosition(sin(swingValue) * 5,1,0);
CollisionResult res = scene->testCollision(box, bigBox);
if(res.collided) {
bigBox->setColor(1.0,1.0,0.0,0.5);
} else {
bigBox->setColor(0.0,1.0,1.0,0.5);
}
return core->updateAndRender();
}
<commit_msg>Rebased 3DPhysics_CollisionOnly on Screenrewrite<commit_after>#include "HelloPolycodeApp.h"
HelloPolycodeApp::HelloPolycodeApp(PolycodeView *view) {
core = new POLYCODE_CORE(view, 640,480,false,false,0,0,90);
CoreServices::getInstance()->getResourceManager()->addArchive("Resources/default.pak");
CoreServices::getInstance()->getResourceManager()->addDirResource("default", false);
scene = new CollisionScene();
ScenePrimitive *ground = new ScenePrimitive(ScenePrimitive::TYPE_PLANE, 10, 10);
ground->loadTexture("Resources/green_texture.png");
scene->addEntity(ground);
box = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 0.5,0.5,0.5);
box->loadTexture("Resources/pink_texture.png");
box->setPosition(0,1,0);
scene->addCollisionChild(box, CollisionEntity::SHAPE_BOX);
bigBox = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 2,2,2);
bigBox->loadTexture("Resources/pink_texture.png");
bigBox->setColor(0.0,1.0,1.0,0.5);
bigBox->setPosition(0,1,0);
scene->addCollisionChild(bigBox, CollisionEntity::SHAPE_BOX);
scene->getDefaultCamera()->setPosition(7,7,7);
scene->getDefaultCamera()->lookAt(Vector3(0,0,0));
swingValue = 0;
}
HelloPolycodeApp::~HelloPolycodeApp() {
}
bool HelloPolycodeApp::Update() {
Number elapsed = core->getElapsed();
swingValue += elapsed;
box->setPosition(sin(swingValue) * 5,1,0);
CollisionResult res = scene->testCollision(box, bigBox);
if(res.collided) {
bigBox->setColor(1.0,1.0,0.0,0.5);
} else {
bigBox->setColor(0.0,1.0,1.0,0.5);
}
return core->updateAndRender();
}
<|endoftext|>
|
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich 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 "QueryResultVisualizer.h"
#include "ModelBase/src/nodes/Node.h"
#include "OOModel/src/declarations/Declaration.h"
#include "VisualizationBase/src/Scene.h"
#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/overlays/ArrowOverlay.h"
#include "VisualizationBase/src/VisualizationManager.h"
#include "VisualizationBase/src/views/MainView.h"
#include "VisualizationBase/src/items/WebBrowserItem.h"
#include "HighlightOverlay.h"
#include "QueryRegistry.h"
#include "QueryExecutor.h"
namespace InformationScripting {
const QString QueryResultVisualizer::HIGHLIGHT_OVERLAY_GROUP = {"default graph highlight"};
const QString QueryResultVisualizer::ARROW_OVERLAY_GROUP = {"default arrow"};
const QStringList QueryResultVisualizer::INFO_ARGUMENT_NAMES{"i", "info"};
const QStringList QueryResultVisualizer::SORT_ARGUMENT_NAMES{"s", "sort"};
QueryResultVisualizer::QueryResultVisualizer(Model::Node* target, QStringList args, QueryExecutor* executor)
: LinearQuery{target}, arguments_{{
{INFO_ARGUMENT_NAMES, "Name of info values to be printed", INFO_ARGUMENT_NAMES[1]},
{SORT_ARGUMENT_NAMES, "Name of info sort key for infos", SORT_ARGUMENT_NAMES[1]}
}, args}, executor_{executor}
{}
Optional<TupleSet> QueryResultVisualizer::executeLinear(TupleSet input)
{
auto result = visualize(input);
if (result.hasErrors())
return {result.errors()[0]};
Q_ASSERT(executor_);
executor_->setVisualizationExecuted();
return input;
}
void QueryResultVisualizer::registerDefaultQueries()
{
QueryRegistry::registerQuery<QueryResultVisualizer, QueryRegistry::ExtraArguments::QueryExecutor>("show");
QueryRegistry::registerAlias("info", "show", [](QStringList& args) {args.prepend("-info");});
}
Optional<int> QueryResultVisualizer::visualize(const TupleSet& ts)
{
cleanScene();
showASTRelation(ts, "calls");
auto colors = extractColors(ts);
auto infoOptional = extractInfo(ts);
if (infoOptional.hasErrors())
return {infoOptional.errors()[0]};
auto infos = infoOptional.value();
auto astTuples = ts.tuples("ast");
// Set default color for non covered ast nodes.
for (const auto& astTuple : astTuples)
{
auto& color = colors[astTuple["ast"]];
if (color.isNull()) color = "red";
}
for (auto it = infos.begin(); it != infos.end(); ++it)
{
auto& color = colors[it.key()];
if (color.isNull()) color = "red";
}
for (auto it = colors.begin(); it != colors.end(); ++it)
{
Model::Node* node = it.key();
Q_ASSERT(node);
QString info = infos[node];
auto nodeVisualizationIt = Visualization::Item::nodeItemsMap().find(node);
if (nodeVisualizationIt == Visualization::Item::nodeItemsMap().end())
qWarning() << "no visualization for" << node->typeName();
while (nodeVisualizationIt != Visualization::Item::nodeItemsMap().end() && nodeVisualizationIt.key() == node)
{
auto item = *nodeVisualizationIt++;
auto overlay = new HighlightOverlay{item};
overlay->setText(info);
setColor(overlay, it.value());
item->addOverlay(overlay, HIGHLIGHT_OVERLAY_GROUP);
}
}
auto htmlTuples = ts.tuples("html");
if (htmlTuples.size()) {
QString htmlContent = (*htmlTuples.begin())["html"];
// TODO an overlay or something would probably be better for this:
// TODO position it a bit better? right now it is just centered.
auto browser = new Visualization::WebBrowserItem{nullptr, htmlContent,
Visualization::WebBrowserItem::itemStyles().get("frame")};
browser->setZValue(Visualization::Item::LAYER_OVERLAY_Z);
auto mainScene = Visualization::VisualizationManager::instance().mainScene();
for (auto view : mainScene->views())
if (auto mainView = dynamic_cast<Visualization::MainView*>(view))
browser->setPos(mainView->sceneRect().center());
mainScene->addTopLevelItem(browser);
}
return {1};
}
void QueryResultVisualizer::cleanScene()
{
for (auto scene : Visualization::Scene::allScenes())
{
scene->removeOverlayGroup(HIGHLIGHT_OVERLAY_GROUP);
scene->removeOverlayGroup(ARROW_OVERLAY_GROUP);
}
}
void QueryResultVisualizer::showASTRelation(const TupleSet& ts, const QString& relationName)
{
auto relationTuples = ts.tuples(relationName);
for (auto t : relationTuples)
{
auto allAsts = t.valuesOfType<Model::Node*>();
if (allAsts.size() > 1)
{
Model::Node* fromNode = allAsts[0];
Model::Node* toNode = allAsts[1];
auto fromVisualization = Visualization::Item::nodeItemsMap().find(fromNode);
Q_ASSERT(fromVisualization != Visualization::Item::nodeItemsMap().end());
auto toVisualization = Visualization::Item::nodeItemsMap().find(toNode);
Q_ASSERT(toVisualization != Visualization::Item::nodeItemsMap().end());
auto fromVisualizationItem = *fromVisualization;
auto overlay = new Visualization::ArrowOverlay{
fromVisualizationItem, *toVisualization, Visualization::ArrowOverlay::itemStyles().get()};
fromVisualizationItem->addOverlay(overlay, ARROW_OVERLAY_GROUP);
}
}
}
QHash<Model::Node*, QString> QueryResultVisualizer::extractColors(const TupleSet& ts)
{
QHash<Model::Node*, QString> colors;
for (const auto& colorTuple : ts.tuples("color"))
{
auto it = colorTuple.find("ast");
if (it != colorTuple.end())
{
QString color = colorTuple["color"];
colors[it->second] = color;
}
}
return colors;
}
Optional<QHash<Model::Node*, QString>> QueryResultVisualizer::extractInfo(const TupleSet& ts)
{
QHash<Model::Node*, QList<Tuple>> infos;
auto infoValues = infoArgumentValues();
if (infoValues.hasErrors()) return infoValues.errors()[0];
auto values = infoValues.value();
if (values.empty()) return QHash<Model::Node*, QString>();
const auto tag = values[0].first;
bool allSame = std::all_of(values.begin(), values.end(), [&tag](const auto& values) {return values.first == tag;});
if (!allSame) return {"Info values have to have same tag"};
for (const auto& infoTuple : ts.tuples(tag))
{
auto allAsts = infoTuple.valuesOfType<Model::Node*>();
if (allAsts.isEmpty() || allAsts.size() > 1) return {"Infotuple has to have a value which refers to an AST node"};
auto astNode = allAsts[0];
QList<NamedProperty> tupleValues;
for (const auto& taggedVal : values)
{
auto valIt = infoTuple.find(taggedVal.second);
if (valIt != infoTuple.end()) tupleValues.push_back(*valIt);
else return {QString{"info: tuple %1 has no entry named %2"}.arg(tag, taggedVal.second)};
}
infos[astNode].append(Tuple{tupleValues});
}
return convertTuplesToString(infos);
}
Optional<QHash<Model::Node*, QString>> QueryResultVisualizer::convertTuplesToString(
const QHash<Model::Node*, QList<Tuple>>& infos)
{
QHash<Model::Node*, QString> result;
auto sortKey = arguments_.argument(SORT_ARGUMENT_NAMES[1]);
for (auto it = infos.begin(); it != infos.end(); ++it)
{
auto values = it.value();
if (!sortKey.isEmpty())
std::sort(values.begin(), values.end(), [sortKey](const Tuple& left, const Tuple& right) {
return left[sortKey] < right[sortKey];}); // TODO check if sortkey is contained
QStringList stringTuples;
for (const auto& tuple : values)
{
QStringList values;
for (const auto& value : tuple)
values << value.second.toString();
stringTuples << values.join(", ");
}
result[it.key()] = stringTuples.join("<br>");
}
return result;
}
Optional<std::vector<QueryResultVisualizer::TaggedValue>> QueryResultVisualizer::infoArgumentValues()
{
std::vector<QueryResultVisualizer::TaggedValue> values;
const QRegularExpression valueMatch{"((\\w+)\\.)?(\\w+)"};
auto valueMatchIt = valueMatch.globalMatch(arguments_.argument(INFO_ARGUMENT_NAMES[1]));
while (valueMatchIt.hasNext())
{
auto match = valueMatchIt.next();
if (!match.hasMatch()) return {"Info values have to be of form: tag.value"};
auto tag = match.captured(2);
auto value = match.captured(3);
values.push_back({tag, value});
}
return values;
}
void QueryResultVisualizer::setColor(HighlightOverlay* overlay, QColor color)
{
color.setAlpha(DEFAULT_ALPHA_);
overlay->setColor(color);
}
}
<commit_msg>Enlarge and center the HTML tuple visualization<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich 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 "QueryResultVisualizer.h"
#include "ModelBase/src/nodes/Node.h"
#include "OOModel/src/declarations/Declaration.h"
#include "VisualizationBase/src/Scene.h"
#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/overlays/ArrowOverlay.h"
#include "VisualizationBase/src/VisualizationManager.h"
#include "VisualizationBase/src/views/MainView.h"
#include "VisualizationBase/src/items/WebBrowserItem.h"
#include "HighlightOverlay.h"
#include "QueryRegistry.h"
#include "QueryExecutor.h"
namespace InformationScripting {
const QString QueryResultVisualizer::HIGHLIGHT_OVERLAY_GROUP = {"default graph highlight"};
const QString QueryResultVisualizer::ARROW_OVERLAY_GROUP = {"default arrow"};
const QStringList QueryResultVisualizer::INFO_ARGUMENT_NAMES{"i", "info"};
const QStringList QueryResultVisualizer::SORT_ARGUMENT_NAMES{"s", "sort"};
QueryResultVisualizer::QueryResultVisualizer(Model::Node* target, QStringList args, QueryExecutor* executor)
: LinearQuery{target}, arguments_{{
{INFO_ARGUMENT_NAMES, "Name of info values to be printed", INFO_ARGUMENT_NAMES[1]},
{SORT_ARGUMENT_NAMES, "Name of info sort key for infos", SORT_ARGUMENT_NAMES[1]}
}, args}, executor_{executor}
{}
Optional<TupleSet> QueryResultVisualizer::executeLinear(TupleSet input)
{
auto result = visualize(input);
if (result.hasErrors())
return {result.errors()[0]};
Q_ASSERT(executor_);
executor_->setVisualizationExecuted();
return input;
}
void QueryResultVisualizer::registerDefaultQueries()
{
QueryRegistry::registerQuery<QueryResultVisualizer, QueryRegistry::ExtraArguments::QueryExecutor>("show");
QueryRegistry::registerAlias("info", "show", [](QStringList& args) {args.prepend("-info");});
}
Optional<int> QueryResultVisualizer::visualize(const TupleSet& ts)
{
cleanScene();
showASTRelation(ts, "calls");
auto colors = extractColors(ts);
auto infoOptional = extractInfo(ts);
if (infoOptional.hasErrors())
return {infoOptional.errors()[0]};
auto infos = infoOptional.value();
auto astTuples = ts.tuples("ast");
// Set default color for non covered ast nodes.
for (const auto& astTuple : astTuples)
{
auto& color = colors[astTuple["ast"]];
if (color.isNull()) color = "red";
}
for (auto it = infos.begin(); it != infos.end(); ++it)
{
auto& color = colors[it.key()];
if (color.isNull()) color = "red";
}
for (auto it = colors.begin(); it != colors.end(); ++it)
{
Model::Node* node = it.key();
Q_ASSERT(node);
QString info = infos[node];
auto nodeVisualizationIt = Visualization::Item::nodeItemsMap().find(node);
if (nodeVisualizationIt == Visualization::Item::nodeItemsMap().end())
qWarning() << "no visualization for" << node->typeName();
while (nodeVisualizationIt != Visualization::Item::nodeItemsMap().end() && nodeVisualizationIt.key() == node)
{
auto item = *nodeVisualizationIt++;
auto overlay = new HighlightOverlay{item};
overlay->setText(info);
setColor(overlay, it.value());
item->addOverlay(overlay, HIGHLIGHT_OVERLAY_GROUP);
}
}
auto htmlTuples = ts.tuples("html");
if (htmlTuples.size()) {
QString htmlContent = (*htmlTuples.begin())["html"];
// TODO an overlay or something would probably be better for this:
// TODO position it a bit better? right now it is just centered.
auto browser = new Visualization::WebBrowserItem{nullptr, htmlContent,
Visualization::WebBrowserItem::itemStyles().get("frame")};
browser->setZValue(Visualization::Item::LAYER_OVERLAY_Z);
browser->updateSize({800, 600});
auto mainScene = Visualization::VisualizationManager::instance().mainScene();
for (auto view : mainScene->views())
if (auto mainView = dynamic_cast<Visualization::MainView*>(view))
browser->setPos(mainView->sceneRect().center() - QPoint{400, 300});
mainScene->addTopLevelItem(browser);
}
return {1};
}
void QueryResultVisualizer::cleanScene()
{
for (auto scene : Visualization::Scene::allScenes())
{
scene->removeOverlayGroup(HIGHLIGHT_OVERLAY_GROUP);
scene->removeOverlayGroup(ARROW_OVERLAY_GROUP);
}
}
void QueryResultVisualizer::showASTRelation(const TupleSet& ts, const QString& relationName)
{
auto relationTuples = ts.tuples(relationName);
for (auto t : relationTuples)
{
auto allAsts = t.valuesOfType<Model::Node*>();
if (allAsts.size() > 1)
{
Model::Node* fromNode = allAsts[0];
Model::Node* toNode = allAsts[1];
auto fromVisualization = Visualization::Item::nodeItemsMap().find(fromNode);
Q_ASSERT(fromVisualization != Visualization::Item::nodeItemsMap().end());
auto toVisualization = Visualization::Item::nodeItemsMap().find(toNode);
Q_ASSERT(toVisualization != Visualization::Item::nodeItemsMap().end());
auto fromVisualizationItem = *fromVisualization;
auto overlay = new Visualization::ArrowOverlay{
fromVisualizationItem, *toVisualization, Visualization::ArrowOverlay::itemStyles().get()};
fromVisualizationItem->addOverlay(overlay, ARROW_OVERLAY_GROUP);
}
}
}
QHash<Model::Node*, QString> QueryResultVisualizer::extractColors(const TupleSet& ts)
{
QHash<Model::Node*, QString> colors;
for (const auto& colorTuple : ts.tuples("color"))
{
auto it = colorTuple.find("ast");
if (it != colorTuple.end())
{
QString color = colorTuple["color"];
colors[it->second] = color;
}
}
return colors;
}
Optional<QHash<Model::Node*, QString>> QueryResultVisualizer::extractInfo(const TupleSet& ts)
{
QHash<Model::Node*, QList<Tuple>> infos;
auto infoValues = infoArgumentValues();
if (infoValues.hasErrors()) return infoValues.errors()[0];
auto values = infoValues.value();
if (values.empty()) return QHash<Model::Node*, QString>();
const auto tag = values[0].first;
bool allSame = std::all_of(values.begin(), values.end(), [&tag](const auto& values) {return values.first == tag;});
if (!allSame) return {"Info values have to have same tag"};
for (const auto& infoTuple : ts.tuples(tag))
{
auto allAsts = infoTuple.valuesOfType<Model::Node*>();
if (allAsts.isEmpty() || allAsts.size() > 1) return {"Infotuple has to have a value which refers to an AST node"};
auto astNode = allAsts[0];
QList<NamedProperty> tupleValues;
for (const auto& taggedVal : values)
{
auto valIt = infoTuple.find(taggedVal.second);
if (valIt != infoTuple.end()) tupleValues.push_back(*valIt);
else return {QString{"info: tuple %1 has no entry named %2"}.arg(tag, taggedVal.second)};
}
infos[astNode].append(Tuple{tupleValues});
}
return convertTuplesToString(infos);
}
Optional<QHash<Model::Node*, QString>> QueryResultVisualizer::convertTuplesToString(
const QHash<Model::Node*, QList<Tuple>>& infos)
{
QHash<Model::Node*, QString> result;
auto sortKey = arguments_.argument(SORT_ARGUMENT_NAMES[1]);
for (auto it = infos.begin(); it != infos.end(); ++it)
{
auto values = it.value();
if (!sortKey.isEmpty())
std::sort(values.begin(), values.end(), [sortKey](const Tuple& left, const Tuple& right) {
return left[sortKey] < right[sortKey];}); // TODO check if sortkey is contained
QStringList stringTuples;
for (const auto& tuple : values)
{
QStringList values;
for (const auto& value : tuple)
values << value.second.toString();
stringTuples << values.join(", ");
}
result[it.key()] = stringTuples.join("<br>");
}
return result;
}
Optional<std::vector<QueryResultVisualizer::TaggedValue>> QueryResultVisualizer::infoArgumentValues()
{
std::vector<QueryResultVisualizer::TaggedValue> values;
const QRegularExpression valueMatch{"((\\w+)\\.)?(\\w+)"};
auto valueMatchIt = valueMatch.globalMatch(arguments_.argument(INFO_ARGUMENT_NAMES[1]));
while (valueMatchIt.hasNext())
{
auto match = valueMatchIt.next();
if (!match.hasMatch()) return {"Info values have to be of form: tag.value"};
auto tag = match.captured(2);
auto value = match.captured(3);
values.push_back({tag, value});
}
return values;
}
void QueryResultVisualizer::setColor(HighlightOverlay* overlay, QColor color)
{
color.setAlpha(DEFAULT_ALPHA_);
overlay->setColor(color);
}
}
<|endoftext|>
|
<commit_before>// This file is part of the ustl library, an STL implementation.
//
// Copyright (C) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
//
// sostream.h
//
#include "mistream.h" // for istream_iterator, referenced in utf8.h
#include "sostream.h"
#include "ustring.h"
#include "utf8.h"
#include "ulimits.h"
#include <stdio.h>
namespace ustl {
/// Default constructor.
ostringstream::ostringstream (void)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
}
/// Creates a stream for writing into \p p of size \p n.
ostringstream::ostringstream (void* p, size_type n)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (p, n);
}
/// Creates a stream for writing into string \p dest.
///
/// dest may be resized by the stream if insufficient space is available.
///
ostringstream::ostringstream (string& dest)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (dest);
}
/// Creates a stream for writing into fixed block \p dest.
ostringstream::ostringstream (memlink& dest)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (dest);
}
/// Writes a single character into the stream.
void ostringstream::iwrite (uint8_t v)
{
if (remaining() >= sizeof(uint8_t) || overflow() >= sizeof(uint8_t))
ostream::iwrite (v);
}
/// Writes \p buf of size \p bufSize through the internal buffer.
void ostringstream::write_buffer (const char* buf, size_type bufSize)
{
size_type btw = 0, written = 0;
while ((written += btw) < bufSize && (remaining() || overflow(bufSize - written)))
write (buf + written, btw = min (remaining(), bufSize - written));
}
/// Simple decimal encoding of \p n into \p fmt.
inline char* ostringstream::encode_dec (char* fmt, uint32_t n) const
{
do {
*fmt++ = '0' + n % 10;
} while (n /= 10);
return (fmt);
}
/// Generates a sprintf format string for the given type.
void ostringstream::fmtstring (char* fmt, const char* typestr, bool bInteger) const
{
*fmt++ = '%';
if (m_Width)
fmt = encode_dec (fmt, m_Width);
if (m_Flags & ios::left)
*fmt++ = '-';
if (!bInteger) {
*fmt++ = '.';
fmt = encode_dec (fmt, m_Precision);
}
while (*typestr)
*fmt++ = *typestr++;
if (bInteger) {
if (m_Base == 16)
fmt[-1] = 'X';
else if (m_Base == 8)
fmt[-1] = 'o';
} else {
if (m_Flags & ios::scientific)
fmt[-1] = 'E';
}
*fmt = 0;
}
template <typename T>
inline void ostringstream::sprintf_iwrite (T v, const char* typestr)
{
const size_type c_BufSize = 64, c_FmtStrSize = 16;
char fmt [c_FmtStrSize], buffer [c_BufSize];
fmtstring (fmt, typestr, numeric_limits<T>::is_integer);
size_type i = snprintf (buffer, c_BufSize, fmt, v);
i = min (i, c_BufSize - 1);
write_buffer (buffer, i);
}
void ostringstream::iwrite (int v) { sprintf_iwrite (v, "d"); }
void ostringstream::iwrite (unsigned int v) { sprintf_iwrite (v, "u"); }
void ostringstream::iwrite (long v) { sprintf_iwrite (v, "ld"); }
void ostringstream::iwrite (unsigned long v) { sprintf_iwrite (v, "lu"); }
void ostringstream::iwrite (float v) { simd::reset_mmx(); sprintf_iwrite (v, "f"); }
void ostringstream::iwrite (double v) { simd::reset_mmx(); sprintf_iwrite (v, "lf"); }
#if HAVE_LONG_LONG
void ostringstream::iwrite (long long v) { sprintf_iwrite (v, "lld"); }
void ostringstream::iwrite (unsigned long long v) { sprintf_iwrite (v, "llu"); }
#endif
/// Writes \p v into the stream as utf8
void ostringstream::iwrite (wchar_t v)
{
char buffer [9];
*utf8out(buffer) = v;
write_buffer (buffer, Utf8Bytes(v));
}
/// Writes value \p v into the stream as text.
void ostringstream::iwrite (bool v)
{
static const char* c_Names[2] = { "false", "true" };
write_buffer (c_Names[v], 5 - v);
}
/// Writes string \p s into the stream.
void ostringstream::iwrite (const char* s)
{
write_buffer (s, strlen(s));
}
/// Writes string \p v into the stream.
void ostringstream::iwrite (const string& v)
{
write_buffer (v.begin(), v.size());
}
/// Equivalent to a vsprintf on the string.
int ostringstream::vformat (const char* fmt, va_list args)
{
#if HAVE_VA_COPY
va_list args2;
__va_copy (args2, args); // Because vsnprintf will iterate over args, changing them.
#else
#define args2 args
#endif
const bool bIsString (m_pResizable);
int rv = vsnprintf (ipos(), remaining() + bIsString, fmt, args);
if (uoff_t(rv) >= remaining() + 0)
rv = vsnprintf (ipos(), overflow(rv) + bIsString, fmt, args2);
skip (min (uoff_t(rv), remaining()));
return (rv);
}
/// Equivalent to a sprintf on the string.
int ostringstream::format (const char* fmt, ...)
{
simd::reset_mmx();
va_list args;
va_start (args, fmt);
const int rv = vformat (fmt, args);
va_end (args);
return (rv);
}
/// Sets the flag \p f in the stream.
void ostringstream::iwrite (ios::fmtflags f)
{
switch (f) {
case ios::oct: set_base (8); break;
case ios::dec: set_base (10); break;
case ios::hex: set_base (16); break;
case ios::left:
m_Flags |= ios::left;
m_Flags &= ~ios::right;
break;
case ios::right:
m_Flags |= ios::right;
m_Flags &= ~ios::left;
break;
default:
m_Flags |= f;
break;
}
}
/// Links to string \p l as resizable.
void ostringstream::link (string& l)
{
if (l.is_linked())
l.reserve (l.capacity());
assert (l.data() && "The output string buffer must not be read-only");
ostream::link (l);
m_pResizable = &l;
}
/// Unlinks the stream from its bound buffer.
void ostringstream::unlink (void)
{
ostream::unlink();
m_pResizable = NULL;
}
/// Writes the contents of \p buffer of \p size into the stream.
void ostringstream::write (const void* buffer, size_type sz)
{
if (remaining() < sz && overflow(sz) < sz)
return;
ostream::write (buffer, sz);
}
/// Writes the contents of \p buf into the stream.
void ostringstream::write (const cmemlink& buf)
{
if (remaining() < buf.size() && overflow(buf.size()) < buf.size())
return;
ostream::write (buf);
}
/// Attempts to create more output space. Returns remaining().
ostringstream::size_type ostringstream::overflow (size_type n)
{
if (m_pResizable && n > remaining()) {
const uoff_t oldPos (pos());
m_pResizable->reserve (oldPos + n, false);
m_pResizable->resize (oldPos + n);
link (*m_pResizable);
seek (oldPos);
}
if (n > remaining())
#ifdef WANT_STREAM_BOUNDS_CHECKING
throw stream_bounds_exception ("write", "text", pos(), n, remaining());
#else
assert (remaining() >= n && "Buffer overrun. Check your stream size calculations.");
#endif
return (remaining());
}
} // namespace ustl
<commit_msg>Reverted incorrectly committed hack<commit_after>// This file is part of the ustl library, an STL implementation.
//
// Copyright (C) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
//
// sostream.h
//
#include "mistream.h" // for istream_iterator, referenced in utf8.h
#include "sostream.h"
#include "ustring.h"
#include "utf8.h"
#include "ulimits.h"
#include <stdio.h>
namespace ustl {
/// Default constructor.
ostringstream::ostringstream (void)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
}
/// Creates a stream for writing into \p p of size \p n.
ostringstream::ostringstream (void* p, size_type n)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (p, n);
}
/// Creates a stream for writing into string \p dest.
///
/// dest may be resized by the stream if insufficient space is available.
///
ostringstream::ostringstream (string& dest)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (dest);
}
/// Creates a stream for writing into fixed block \p dest.
ostringstream::ostringstream (memlink& dest)
: ostream (),
m_pResizable (NULL),
m_Flags (0),
m_Base (10),
m_Precision (2),
m_Width (0),
m_DecimalSeparator ('.'),
m_ThousandSeparator (',')
{
link (dest);
}
/// Writes a single character into the stream.
void ostringstream::iwrite (uint8_t v)
{
if (remaining() >= sizeof(uint8_t) || overflow() >= sizeof(uint8_t))
ostream::iwrite (v);
}
/// Writes \p buf of size \p bufSize through the internal buffer.
void ostringstream::write_buffer (const char* buf, size_type bufSize)
{
size_type btw = 0, written = 0;
while ((written += btw) < bufSize && (remaining() || overflow(bufSize - written)))
write (buf + written, btw = min (remaining(), bufSize - written));
}
/// Simple decimal encoding of \p n into \p fmt.
inline char* ostringstream::encode_dec (char* fmt, uint32_t n) const
{
do {
*fmt++ = '0' + n % 10;
} while (n /= 10);
return (fmt);
}
/// Generates a sprintf format string for the given type.
void ostringstream::fmtstring (char* fmt, const char* typestr, bool bInteger) const
{
*fmt++ = '%';
if (m_Width)
fmt = encode_dec (fmt, m_Width);
if (m_Flags & ios::left)
*fmt++ = '-';
if (!bInteger) {
*fmt++ = '.';
fmt = encode_dec (fmt, m_Precision);
}
while (*typestr)
*fmt++ = *typestr++;
if (bInteger) {
if (m_Base == 16)
fmt[-1] = 'X';
else if (m_Base == 8)
fmt[-1] = 'o';
} else {
if (m_Flags & ios::scientific)
fmt[-1] = 'E';
}
*fmt = 0;
}
template <typename T>
inline void ostringstream::sprintf_iwrite (T v, const char* typestr)
{
const size_type c_BufSize = 64, c_FmtStrSize = 16;
char fmt [c_FmtStrSize], buffer [c_BufSize];
fmtstring (fmt, typestr, numeric_limits<T>::is_integer);
size_type i = snprintf (buffer, c_BufSize, fmt, v);
i = min (i, c_BufSize - 1);
write_buffer (buffer, i);
}
void ostringstream::iwrite (int v) { sprintf_iwrite (v, "d"); }
void ostringstream::iwrite (unsigned int v) { sprintf_iwrite (v, "u"); }
void ostringstream::iwrite (long v) { sprintf_iwrite (v, "ld"); }
void ostringstream::iwrite (unsigned long v) { sprintf_iwrite (v, "lu"); }
void ostringstream::iwrite (float v) { simd::reset_mmx(); sprintf_iwrite (v, "f"); }
void ostringstream::iwrite (double v) { simd::reset_mmx(); sprintf_iwrite (v, "lf"); }
#if HAVE_LONG_LONG
void ostringstream::iwrite (long long v) { sprintf_iwrite (v, "lld"); }
void ostringstream::iwrite (unsigned long long v) { sprintf_iwrite (v, "llu"); }
#endif
/// Writes \p v into the stream as utf8
void ostringstream::iwrite (wchar_t v)
{
char buffer [9];
*utf8out(buffer) = v;
write_buffer (buffer, Utf8Bytes(v));
}
/// Writes value \p v into the stream as text.
void ostringstream::iwrite (bool v)
{
static const char* c_Names[2] = { "false", "true" };
write_buffer (c_Names[v], 5 - v);
}
/// Writes string \p s into the stream.
void ostringstream::iwrite (const char* s)
{
write_buffer (s, strlen(s));
}
/// Writes string \p v into the stream.
void ostringstream::iwrite (const string& v)
{
write_buffer (v.begin(), v.size());
}
/// Equivalent to a vsprintf on the string.
int ostringstream::vformat (const char* fmt, va_list args)
{
#if HAVE_VA_COPY
va_list args2;
__va_copy (args2, args); // Because vsnprintf will iterate over args, changing them.
#else
#define args2 args
#endif
const bool bIsString (m_pResizable);
int rv = vsnprintf (ipos(), remaining() + bIsString, fmt, args);
if (uoff_t(rv) >= remaining() + bIsString)
rv = vsnprintf (ipos(), overflow(rv) + bIsString, fmt, args2);
skip (min (uoff_t(rv), remaining()));
return (rv);
}
/// Equivalent to a sprintf on the string.
int ostringstream::format (const char* fmt, ...)
{
simd::reset_mmx();
va_list args;
va_start (args, fmt);
const int rv = vformat (fmt, args);
va_end (args);
return (rv);
}
/// Sets the flag \p f in the stream.
void ostringstream::iwrite (ios::fmtflags f)
{
switch (f) {
case ios::oct: set_base (8); break;
case ios::dec: set_base (10); break;
case ios::hex: set_base (16); break;
case ios::left:
m_Flags |= ios::left;
m_Flags &= ~ios::right;
break;
case ios::right:
m_Flags |= ios::right;
m_Flags &= ~ios::left;
break;
default:
m_Flags |= f;
break;
}
}
/// Links to string \p l as resizable.
void ostringstream::link (string& l)
{
if (l.is_linked())
l.reserve (l.capacity());
assert (l.data() && "The output string buffer must not be read-only");
ostream::link (l);
m_pResizable = &l;
}
/// Unlinks the stream from its bound buffer.
void ostringstream::unlink (void)
{
ostream::unlink();
m_pResizable = NULL;
}
/// Writes the contents of \p buffer of \p size into the stream.
void ostringstream::write (const void* buffer, size_type sz)
{
if (remaining() < sz && overflow(sz) < sz)
return;
ostream::write (buffer, sz);
}
/// Writes the contents of \p buf into the stream.
void ostringstream::write (const cmemlink& buf)
{
if (remaining() < buf.size() && overflow(buf.size()) < buf.size())
return;
ostream::write (buf);
}
/// Attempts to create more output space. Returns remaining().
ostringstream::size_type ostringstream::overflow (size_type n)
{
if (m_pResizable && n > remaining()) {
const uoff_t oldPos (pos());
m_pResizable->reserve (oldPos + n, false);
m_pResizable->resize (oldPos + n);
link (*m_pResizable);
seek (oldPos);
}
if (n > remaining())
#ifdef WANT_STREAM_BOUNDS_CHECKING
throw stream_bounds_exception ("write", "text", pos(), n, remaining());
#else
assert (remaining() >= n && "Buffer overrun. Check your stream size calculations.");
#endif
return (remaining());
}
} // namespace ustl
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: OptimizationExample.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Samuel R. Hamner, Ajay Seth *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* Example of an OpenSim program that optimizes the performance of a model.
* The main() loads the arm26 model and maximizes the forward velocity of
* the hand during a muscle-driven forward simulation by finding the set
* of (constant) controls.
*/
//==============================================================================
//==============================================================================
#include <OpenSim/OpenSim.h>
#include "OpenSim/Common/STOFileAdapter.h"
#include <ctime> // clock(), clock_t, CLOCKS_PER_SEC
using namespace OpenSim;
using namespace SimTK;
using namespace std;
// Global variables to define integration time window, optimizer step count,
// the best solution.
int stepCount = 0;
double initialTime = 0.0;
double finalTime = 0.25;
double bestSoFar = Infinity;
class ExampleOptimizationSystem : public OptimizerSystem {
public:
/* Constructor class. Parameters passed are accessed in the objectiveFunc() class. */
ExampleOptimizationSystem(int numParameters, State& s, Model& aModel):
OptimizerSystem(numParameters),
numControls(numParameters),
si(s),
osimModel(aModel)
{
// Create the integrator for the simulation.
p_integrator = new RungeKuttaMersonIntegrator(osimModel.getMultibodySystem());
p_integrator->setAccuracy(1.0e-7);
}
int objectiveFunc( const Vector &newControls, bool new_coefficients, Real& f ) const override {
// make a copy of the initial states
State s = si;
// Update the control values
osimModel.updDefaultControls() = newControls;
// Integrate from initial time to final time
Manager manager(osimModel, *p_integrator);
s.setTime(initialTime);
osimModel.getMultibodySystem().realize(s, Stage::Acceleration);
manager.integrate(s, finalTime);
/* Calculate the scalar quantity we want to minimize or maximize.
* In this case, were maximizing forward velocity of the
* forearm/hand mass center, so to maximize, compute velocity
* and multiply it by -1.
*/
const auto& hand = osimModel.getComponent<OpenSim::Body>("r_ulna_radius_hand");
osimModel.getMultibodySystem().realize(s, Stage::Velocity);
Vec3 massCenter = hand.getMassCenter();
Vec3 velocity = hand.findStationVelocityInGround(s, massCenter);
f = -velocity[0];
stepCount++;
// Use an if statement to only store and print the results of an
// optimization step if it is better than a previous result.
if(f < bestSoFar) {
bestSoFar = f;
cout << "\nobjective evaluation #: " << stepCount << " controls = "
<< newControls << " bestSoFar = " << f << std::endl;
}
return 0;
}
private:
int numControls;
State& si;
Model& osimModel;
SimTK::ReferencePtr<RungeKuttaMersonIntegrator> p_integrator;
};
//______________________________________________________________________________
/**
* Define an optimization problem that finds a set of muscle controls to maximize
* the forward velocity of the forearm/hand segment mass center.
*/
int main()
{
try {
std::clock_t startTime = std::clock();
// Use Millard2012Equilibrium muscles with rigid tendons for better
// performance.
Object::renameType("Thelen2003Muscle", "Millard2012EquilibriumMuscle");
// Create a new OpenSim model. This model is similar to the arm26 model,
// but without wrapping surfaces for better performance.
Model osimModel("Arm26_Optimize.osim");
// Initialize the system and get the state representing the state system
State& si = osimModel.initSystem();
// Initialize the starting shoulder angle.
const CoordinateSet& coords = osimModel.getCoordinateSet();
coords.get("r_shoulder_elev").setValue(si, -1.57079633);
// Set the initial muscle activations and make all tendons rigid.
const Set<Muscle> &muscleSet = osimModel.getMuscles();
for(int i=0; i<muscleSet.getSize(); ++i) {
muscleSet[i].setActivation(si, 0.01);
muscleSet[i].setIgnoreTendonCompliance(si, true);
}
// Make sure the muscles states are in equilibrium
osimModel.equilibrateMuscles(si);
// The number of controls will equal the number of muscles in the model!
int numControls = osimModel.getNumControls();
// Initialize the optimizer system we've defined.
ExampleOptimizationSystem sys(numControls, si, osimModel);
Real f = NaN;
/* Define initial values and bounds for the controls to optimize */
Vector controls(numControls, 0.01);
controls[3] = 0.99;
controls[4] = 0.99;
controls[5] = 0.99;
Vector lower_bounds(numControls, 0.01);
Vector upper_bounds(numControls, 0.99);
sys.setParameterLimits( lower_bounds, upper_bounds );
// Create an optimizer. Pass in our OptimizerSystem
// and the name of the optimization algorithm.
Optimizer opt(sys, SimTK::LBFGSB);
//Optimizer opt(sys, InteriorPoint);
// Specify settings for the optimizer
opt.setConvergenceTolerance(0.1);
opt.useNumericalGradient(true, 1e-5);
opt.setMaxIterations(100);
opt.setLimitedMemoryHistory(500);
// Optimize it!
f = opt.optimize(controls);
cout << "Elapsed time = " << (std::clock()-startTime)/CLOCKS_PER_SEC << "s" << endl;
const Set<Actuator>& actuators = osimModel.getActuators();
for(int i=0; i<actuators.getSize(); ++i){
cout << actuators[i].getName() << " control value = " << controls[i] << endl;
}
cout << "\nMaximum hand velocity = " << -f << "m/s" << endl;
cout << "OpenSim example completed successfully." << endl;
// Dump out optimization results to a text file for testing
ofstream ofile;
ofile.open("Arm26_optimization_result");
for(int i=0; i<actuators.getSize(); ++i)
ofile << controls[i] << endl;
ofile << -f <<endl;
ofile.close();
// Re-run simulation with optimal controls.
RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
integrator.setAccuracy(1.0e-7);
Manager manager(osimModel, integrator);
osimModel.updDefaultControls() = controls;
// Integrate from initial time to final time.
si.setTime(initialTime);
osimModel.getMultibodySystem().realize(si, Stage::Acceleration);
manager.integrate(si, finalTime);
auto statesTable = manager.getStatesTable();
STOFileAdapter_<double>::write(statesTable,
"Arm26_optimized_states.sto");
}
catch (const std::exception& ex)
{
std::cout << ex.what() << std::endl;
return 1;
}
// End of main() routine.
return 0;
}
<commit_msg>Speedup optimization example loosening the accuracy from 1e-7 to 1e-5 for numerical integration and for the estimate of the objective function accuracy. Also greatly reduce the maximum number of iterations so if the tests is to fail it should do some more quickly.<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: OptimizationExample.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Samuel R. Hamner, Ajay Seth *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* Example of an OpenSim program that optimizes the performance of a model.
* The main() loads the arm26 model and maximizes the forward velocity of
* the hand during a muscle-driven forward simulation by finding the set
* of (constant) controls.
*/
//==============================================================================
//==============================================================================
#include <OpenSim/OpenSim.h>
#include "OpenSim/Common/STOFileAdapter.h"
#include <ctime> // clock(), clock_t, CLOCKS_PER_SEC
using namespace OpenSim;
using namespace SimTK;
using namespace std;
// Global variables to define integration time window, optimizer step count,
// the best solution.
int stepCount = 0;
const double initialTime = 0.0;
const double finalTime = 0.25;
const double desired_accuracy = 1.0e-5;
double bestSoFar = Infinity;
class ExampleOptimizationSystem : public OptimizerSystem {
public:
/* Constructor class. Parameters passed are accessed in the objectiveFunc() class. */
ExampleOptimizationSystem(int numParameters, State& s, Model& aModel):
OptimizerSystem(numParameters),
numControls(numParameters),
si(s),
osimModel(aModel)
{
// Create the integrator for the simulation.
p_integrator = new RungeKuttaMersonIntegrator(osimModel.getMultibodySystem());
p_integrator->setAccuracy(desired_accuracy);
}
int objectiveFunc(const Vector &newControls,
bool new_coefficients, Real& f) const override {
// make a copy of the initial states
State s = si;
// Update the control values
osimModel.updDefaultControls() = newControls;
// Integrate from initial time to final time
Manager manager(osimModel, *p_integrator);
s.setTime(initialTime);
osimModel.getMultibodySystem().realize(s, Stage::Acceleration);
manager.integrate(s, finalTime);
/* Calculate the scalar quantity we want to minimize or maximize.
* In this case, were maximizing forward velocity of the
* forearm/hand mass center, so to maximize, compute velocity
* and multiply it by -1.
*/
const auto& hand = osimModel.getComponent<OpenSim::Body>("r_ulna_radius_hand");
osimModel.getMultibodySystem().realize(s, Stage::Velocity);
Vec3 massCenter = hand.getMassCenter();
Vec3 velocity = hand.findStationVelocityInGround(s, massCenter);
f = -velocity[0];
stepCount++;
// Use an if statement to only store and print the results of an
// optimization step if it is better than a previous result.
if(f < bestSoFar) {
bestSoFar = f;
cout << "\nobjective evaluation #: " << stepCount << " controls = "
<< newControls << " bestSoFar = " << f << std::endl;
}
return 0;
}
private:
int numControls;
State& si;
Model& osimModel;
SimTK::ReferencePtr<RungeKuttaMersonIntegrator> p_integrator;
};
//______________________________________________________________________________
/**
* Define an optimization problem that finds a set of muscle controls to maximize
* the forward velocity of the forearm/hand segment mass center.
*/
int main()
{
try {
std::clock_t startTime = std::clock();
// Use Millard2012Equilibrium muscles with rigid tendons for better
// performance.
Object::renameType("Thelen2003Muscle", "Millard2012EquilibriumMuscle");
// Create a new OpenSim model. This model is similar to the arm26 model,
// but without wrapping surfaces for better performance.
Model osimModel("Arm26_Optimize.osim");
// Initialize the system and get the state representing the state system
State& si = osimModel.initSystem();
// Initialize the starting shoulder angle.
const CoordinateSet& coords = osimModel.getCoordinateSet();
coords.get("r_shoulder_elev").setValue(si, -1.57079633);
// Set the initial muscle activations and make all tendons rigid.
const Set<Muscle> &muscleSet = osimModel.getMuscles();
for(int i=0; i<muscleSet.getSize(); ++i) {
muscleSet[i].setActivation(si, 0.01);
muscleSet[i].setIgnoreTendonCompliance(si, true);
}
// Make sure the muscles states are in equilibrium
osimModel.equilibrateMuscles(si);
// The number of controls will equal the number of muscles in the model!
int numControls = osimModel.getNumControls();
// Initialize the optimizer system we've defined.
ExampleOptimizationSystem sys(numControls, si, osimModel);
Real f = NaN;
/* Define initial values and bounds for the controls to optimize */
Vector controls(numControls, 0.02);
controls[3] = 0.99;
controls[4] = 0.99;
controls[5] = 0.99;
Vector lower_bounds(numControls, 0.01);
Vector upper_bounds(numControls, 0.99);
sys.setParameterLimits( lower_bounds, upper_bounds );
// Create an optimizer. Pass in our OptimizerSystem
// and the name of the optimization algorithm.
Optimizer opt(sys, SimTK::LBFGSB);
//Optimizer opt(sys, InteriorPoint);
// Specify settings for the optimizer
opt.setConvergenceTolerance(0.1);
opt.useNumericalGradient(true, desired_accuracy);
opt.setMaxIterations(2);
opt.setLimitedMemoryHistory(500);
// Optimize it!
f = opt.optimize(controls);
cout << "Elapsed time = " << (std::clock()-startTime)/CLOCKS_PER_SEC << "s" << endl;
const Set<Actuator>& actuators = osimModel.getActuators();
for(int i=0; i<actuators.getSize(); ++i){
cout << actuators[i].getName() << " control value = " << controls[i] << endl;
}
cout << "\nMaximum hand velocity = " << -f << "m/s" << endl;
cout << "OpenSim example completed successfully." << endl;
// Dump out optimization results to a text file for testing
ofstream ofile;
ofile.open("Arm26_optimization_result");
for(int i=0; i<actuators.getSize(); ++i)
ofile << controls[i] << endl;
ofile << -f <<endl;
ofile.close();
// Re-run simulation with optimal controls.
RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
integrator.setAccuracy(desired_accuracy);
Manager manager(osimModel, integrator);
osimModel.updDefaultControls() = controls;
// Integrate from initial time to final time.
si.setTime(initialTime);
osimModel.getMultibodySystem().realize(si, Stage::Acceleration);
manager.integrate(si, finalTime);
auto statesTable = manager.getStatesTable();
STOFileAdapter_<double>::write(statesTable,
"Arm26_optimized_states.sto");
}
catch (const std::exception& ex)
{
std::cout << ex.what() << std::endl;
return 1;
}
// End of main() routine.
return 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 "ppapi/tests/test_fullscreen.h"
#include <stdio.h>
#include <string.h>
#include <string>
#include "ppapi/c/dev/ppb_testing_dev.h"
#include "ppapi/c/dev/ppb_fullscreen_dev.h"
#include "ppapi/cpp/input_event.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/point.h"
#include "ppapi/tests/test_utils.h"
#include "ppapi/tests/testing_instance.h"
REGISTER_TEST_CASE(Fullscreen);
namespace {
bool HasMidScreen(const pp::Rect& position, const pp::Size& screen_size) {
static int32_t mid_x = screen_size.width() / 2;
static int32_t mid_y = screen_size.height() / 2;
return (position.Contains(mid_x, mid_y));
}
} // namespace
TestFullscreen::TestFullscreen(TestingInstance* instance)
: TestCase(instance),
error_(),
screen_mode_(instance),
fullscreen_pending_(false),
normal_pending_(false),
saw_first_fullscreen_didchangeview(false),
graphics2d_fullscreen_(instance, pp::Size(10, 10), false),
graphics2d_normal_(instance, pp::Size(15, 15), false),
set_fullscreen_true_callback_(instance->pp_instance()),
fullscreen_callback_(instance->pp_instance()),
normal_callback_(instance->pp_instance()) {
screen_mode_.GetScreenSize(&screen_size_);
}
bool TestFullscreen::Init() {
if (graphics2d_fullscreen_.is_null() && graphics2d_normal_.is_null())
return false;
return InitTestingInterface();
}
void TestFullscreen::RunTest() {
RUN_TEST(GetScreenSize);
RUN_TEST(NormalToFullscreenToNormal);
}
bool TestFullscreen::GotError() {
return !error_.empty();
}
std::string TestFullscreen::Error() {
std::string last_error = error_;
error_.clear();
return last_error;
}
std::string TestFullscreen::TestGetScreenSize() {
if (screen_size_.width() < 320 || screen_size_.width() > 2560)
return ReportError("screen_size.width()", screen_size_.width());
if (screen_size_.height() < 200 || screen_size_.height() > 2048)
return ReportError("screen_size.height()", screen_size_.height());
PASS();
}
std::string TestFullscreen::TestNormalToFullscreenToNormal() {
// 0. Start in normal mode.
if (screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() at start", true);
// 1. Switch to fullscreen.
// This is only allowed within a context of a user gesture (e.g. mouse click).
if (screen_mode_.SetFullscreen(true))
return ReportError("SetFullscreen(true) outside of user gesture", true);
// The transition is asynchronous and ends at the next DidChangeView().
// No graphics devices can be bound while in transition.
instance_->RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
// HandleInputEvent() will call SetFullscreen(true).
// DidChangeView() will call the callback once in fullscreen mode.
fullscreen_callback_.WaitForResult();
if (GotError())
return Error();
if (fullscreen_pending_)
return "fullscreen_pending_ has not been reset";
if (!screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() in fullscreen", false);
if (!instance_->BindGraphics(graphics2d_fullscreen_))
return ReportError("BindGraphics() in fullscreen", false);
// 2. Stay in fullscreen. No change.
if (screen_mode_.SetFullscreen(true))
return ReportError("SetFullscreen(true) in fullscreen", true);
if (!screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() in fullscreen^2", false);
// 3. Switch to normal.
// The transition is asynchronous and ends at DidChangeView().
// No graphics devices can be bound while in transition.
normal_pending_ = true;
if (!screen_mode_.SetFullscreen(false))
return ReportError("SetFullscreen(false) in fullscreen", false);
// Normal is now pending, so additional requests should fail.
if (screen_mode_.SetFullscreen(false))
return ReportError("SetFullscreen(false) in normal pending", true);
if (screen_mode_.SetFullscreen(true))
return ReportError("SetFullscreen(true) in normal pending", true);
if (instance_->BindGraphics(graphics2d_normal_))
return ReportError("BindGraphics() in normal transition", true);
if (!screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() in normal transition", false);
// DidChangeView() will call the callback once out of fullscreen mode.
normal_callback_.WaitForResult();
if (normal_pending_)
return "normal_pending_ has not been reset";
if (screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() in normal", true);
if (!instance_->BindGraphics(graphics2d_fullscreen_))
return ReportError("BindGraphics() in normal", false);
// 4. Stay in normal. No change.
if (screen_mode_.SetFullscreen(false))
return ReportError("SetFullscreen(false) in normal", true);
if (screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() in normal^2", true);
PASS();
}
void TestFullscreen::FailFullscreenTest(const std::string& error) {
screen_mode_.SetFullscreen(false);
fullscreen_pending_ = false;
error_ = error;
pp::Module::Get()->core()->CallOnMainThread(0, fullscreen_callback_);
}
// Transition to fullscreen can only happen when processing a user gesture.
bool TestFullscreen::HandleInputEvent(const pp::InputEvent& event) {
// We only let mouse events through and only mouse clicks count.
if (event.GetType() != PP_INPUTEVENT_TYPE_MOUSEDOWN &&
event.GetType() != PP_INPUTEVENT_TYPE_MOUSEUP)
return false;
// We got the gesture. No need to handle any more events.
instance_->ClearInputEventRequest(PP_INPUTEVENT_CLASS_MOUSE);
fullscreen_pending_ = true;
if (!screen_mode_.SetFullscreen(true)) {
FailFullscreenTest(ReportError("SetFullscreen(true) in normal", false));
return false;
}
// Fullscreen is now pending, so additional requests should fail.
if (screen_mode_.SetFullscreen(true)) {
FailFullscreenTest(
ReportError("SetFullscreen(true) in fullscreen pending", true));
return false;
}
if (screen_mode_.SetFullscreen(false)) {
FailFullscreenTest(
ReportError("SetFullscreen(false) in fullscreen pending", true));
}
// No graphics devices can be bound while in transition.
if (instance_->BindGraphics(graphics2d_fullscreen_)) {
FailFullscreenTest(
ReportError("BindGraphics() in fullscreen transition", true));
return false;
}
if (screen_mode_.IsFullscreen()) {
FailFullscreenTest(
ReportError("IsFullscreen() in fullscreen transtion", true));
return false;
}
// DidChangeView() will complete the transition to fullscreen.
return false;
}
// Transitions to/from fullscreen is asynchornous ending at DidChangeView.
// When going to fullscreen, two DidChangeView calls are generated:
// one for moving the plugin to the middle of window and one for stretching
// the window and placing the plugin in the middle of the screen.
// WebKit does not change the plugin size, but Pepper does explicitly set
// it to screen width and height when SetFullscreen(true) is called and
// resets it back when ViewChanged is received indicating that we exited
// fullscreen.
// NOTE: The number of DidChangeView calls for <object> might be different.
void TestFullscreen::DidChangeView(const pp::Rect& position,
const pp::Rect& clip) {
if (normal_position_.IsEmpty())
normal_position_ = position;
if (fullscreen_pending_ && !saw_first_fullscreen_didchangeview) {
saw_first_fullscreen_didchangeview = true;
if (!screen_mode_.IsFullscreen())
FailFullscreenTest("DidChangeView1 is not in fullscreen");
if (position.size() != screen_size_)
FailFullscreenTest("DidChangeView1 does not have screen size");
// Wait for the 2nd DidChangeView.
} else if (fullscreen_pending_) {
fullscreen_pending_ = false;
saw_first_fullscreen_didchangeview = false;
if (!screen_mode_.IsFullscreen())
FailFullscreenTest("DidChangeView2 is not in fullscreen");
else if (!HasMidScreen(position, screen_size_))
FailFullscreenTest("DidChangeView2 is not in the middle of the screen");
else if (position.size() != screen_size_)
FailFullscreenTest("DidChangeView2 does not have screen size");
// NOTE: we cannot reliably test for clip size being equal to the screen
// because it might be affected by JS console, info bars, etc.
else
pp::Module::Get()->core()->CallOnMainThread(0, fullscreen_callback_);
} else if (normal_pending_) {
normal_pending_ = false;
if (screen_mode_.IsFullscreen())
error_ = "DidChangeview is in fullscreen";
else if (position != normal_position_)
error_ = "DidChangeView position is not normal";
pp::Module::Get()->core()->CallOnMainThread(0, normal_callback_);
}
}
<commit_msg>PPAPI Fullscreen: update ppapi_test to match the behavior after RenderWidget::is_fullscreen (used in DidChangeView to detect fullscreen mode) was implemented. Review URL: http://codereview.chromium.org/8301010<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 "ppapi/tests/test_fullscreen.h"
#include <stdio.h>
#include <string.h>
#include <string>
#include "ppapi/c/dev/ppb_testing_dev.h"
#include "ppapi/c/dev/ppb_fullscreen_dev.h"
#include "ppapi/cpp/input_event.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/point.h"
#include "ppapi/tests/test_utils.h"
#include "ppapi/tests/testing_instance.h"
REGISTER_TEST_CASE(Fullscreen);
namespace {
bool HasMidScreen(const pp::Rect& position, const pp::Size& screen_size) {
static int32_t mid_x = screen_size.width() / 2;
static int32_t mid_y = screen_size.height() / 2;
return (position.Contains(mid_x, mid_y));
}
} // namespace
TestFullscreen::TestFullscreen(TestingInstance* instance)
: TestCase(instance),
error_(),
screen_mode_(instance),
fullscreen_pending_(false),
normal_pending_(false),
saw_first_fullscreen_didchangeview(false),
graphics2d_fullscreen_(instance, pp::Size(10, 10), false),
graphics2d_normal_(instance, pp::Size(15, 15), false),
set_fullscreen_true_callback_(instance->pp_instance()),
fullscreen_callback_(instance->pp_instance()),
normal_callback_(instance->pp_instance()) {
screen_mode_.GetScreenSize(&screen_size_);
}
bool TestFullscreen::Init() {
if (graphics2d_fullscreen_.is_null() && graphics2d_normal_.is_null())
return false;
return InitTestingInterface();
}
void TestFullscreen::RunTest() {
RUN_TEST(GetScreenSize);
RUN_TEST(NormalToFullscreenToNormal);
}
bool TestFullscreen::GotError() {
return !error_.empty();
}
std::string TestFullscreen::Error() {
std::string last_error = error_;
error_.clear();
return last_error;
}
std::string TestFullscreen::TestGetScreenSize() {
if (screen_size_.width() < 320 || screen_size_.width() > 2560)
return ReportError("screen_size.width()", screen_size_.width());
if (screen_size_.height() < 200 || screen_size_.height() > 2048)
return ReportError("screen_size.height()", screen_size_.height());
PASS();
}
std::string TestFullscreen::TestNormalToFullscreenToNormal() {
// 0. Start in normal mode.
if (screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() at start", true);
// 1. Switch to fullscreen.
// This is only allowed within a context of a user gesture (e.g. mouse click).
if (screen_mode_.SetFullscreen(true))
return ReportError("SetFullscreen(true) outside of user gesture", true);
// The transition is asynchronous and ends at the next DidChangeView().
// No graphics devices can be bound while in transition.
instance_->RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
// HandleInputEvent() will call SetFullscreen(true).
// DidChangeView() will call the callback once in fullscreen mode.
fullscreen_callback_.WaitForResult();
if (GotError())
return Error();
if (fullscreen_pending_)
return "fullscreen_pending_ has not been reset";
if (!screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() in fullscreen", false);
if (!instance_->BindGraphics(graphics2d_fullscreen_))
return ReportError("BindGraphics() in fullscreen", false);
// 2. Stay in fullscreen. No change.
if (screen_mode_.SetFullscreen(true))
return ReportError("SetFullscreen(true) in fullscreen", true);
if (!screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() in fullscreen^2", false);
// 3. Switch to normal.
// The transition is asynchronous and ends at DidChangeView().
// No graphics devices can be bound while in transition.
normal_pending_ = true;
if (!screen_mode_.SetFullscreen(false))
return ReportError("SetFullscreen(false) in fullscreen", false);
// Normal is now pending, so additional requests should fail.
if (screen_mode_.SetFullscreen(false))
return ReportError("SetFullscreen(false) in normal pending", true);
if (screen_mode_.SetFullscreen(true))
return ReportError("SetFullscreen(true) in normal pending", true);
if (instance_->BindGraphics(graphics2d_normal_))
return ReportError("BindGraphics() in normal transition", true);
if (!screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() in normal transition", false);
// DidChangeView() will call the callback once out of fullscreen mode.
normal_callback_.WaitForResult();
if (normal_pending_)
return "normal_pending_ has not been reset";
if (screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() in normal", true);
if (!instance_->BindGraphics(graphics2d_fullscreen_))
return ReportError("BindGraphics() in normal", false);
// 4. Stay in normal. No change.
if (screen_mode_.SetFullscreen(false))
return ReportError("SetFullscreen(false) in normal", true);
if (screen_mode_.IsFullscreen())
return ReportError("IsFullscreen() in normal^2", true);
PASS();
}
void TestFullscreen::FailFullscreenTest(const std::string& error) {
screen_mode_.SetFullscreen(false);
fullscreen_pending_ = false;
error_ = error;
pp::Module::Get()->core()->CallOnMainThread(0, fullscreen_callback_);
}
// Transition to fullscreen can only happen when processing a user gesture.
bool TestFullscreen::HandleInputEvent(const pp::InputEvent& event) {
// We only let mouse events through and only mouse clicks count.
if (event.GetType() != PP_INPUTEVENT_TYPE_MOUSEDOWN &&
event.GetType() != PP_INPUTEVENT_TYPE_MOUSEUP)
return false;
// We got the gesture. No need to handle any more events.
instance_->ClearInputEventRequest(PP_INPUTEVENT_CLASS_MOUSE);
fullscreen_pending_ = true;
if (!screen_mode_.SetFullscreen(true)) {
FailFullscreenTest(ReportError("SetFullscreen(true) in normal", false));
return false;
}
// Fullscreen is now pending, so additional requests should fail.
if (screen_mode_.SetFullscreen(true)) {
FailFullscreenTest(
ReportError("SetFullscreen(true) in fullscreen pending", true));
return false;
}
if (screen_mode_.SetFullscreen(false)) {
FailFullscreenTest(
ReportError("SetFullscreen(false) in fullscreen pending", true));
}
// No graphics devices can be bound while in transition.
if (instance_->BindGraphics(graphics2d_fullscreen_)) {
FailFullscreenTest(
ReportError("BindGraphics() in fullscreen transition", true));
return false;
}
if (screen_mode_.IsFullscreen()) {
FailFullscreenTest(
ReportError("IsFullscreen() in fullscreen transtion", true));
return false;
}
// DidChangeView() will complete the transition to fullscreen.
return false;
}
// Transitions to/from fullscreen is asynchornous ending at DidChangeView.
// When going to fullscreen, two DidChangeView calls are generated:
// one for moving the plugin to the middle of window and one for stretching
// the window and placing the plugin in the middle of the screen.
// WebKit does not change the plugin size, but Pepper does explicitly set
// it to screen width and height when SetFullscreen(true) is called and
// resets it back when ViewChanged is received indicating that we exited
// fullscreen.
// NOTE: The number of DidChangeView calls for <object> might be different.
void TestFullscreen::DidChangeView(const pp::Rect& position,
const pp::Rect& clip) {
if (normal_position_.IsEmpty())
normal_position_ = position;
if (fullscreen_pending_ && !saw_first_fullscreen_didchangeview) {
saw_first_fullscreen_didchangeview = true;
if (screen_mode_.IsFullscreen())
FailFullscreenTest("DidChangeView1 is in fullscreen");
if (position.size() != screen_size_)
FailFullscreenTest("DidChangeView1 does not have screen size");
// Wait for the 2nd DidChangeView.
} else if (fullscreen_pending_) {
fullscreen_pending_ = false;
saw_first_fullscreen_didchangeview = false;
if (!screen_mode_.IsFullscreen())
FailFullscreenTest("DidChangeView2 is not in fullscreen");
else if (!HasMidScreen(position, screen_size_))
FailFullscreenTest("DidChangeView2 is not in the middle of the screen");
else if (position.size() != screen_size_)
FailFullscreenTest("DidChangeView2 does not have screen size");
// NOTE: we cannot reliably test for clip size being equal to the screen
// because it might be affected by JS console, info bars, etc.
else
pp::Module::Get()->core()->CallOnMainThread(0, fullscreen_callback_);
} else if (normal_pending_) {
normal_pending_ = false;
if (screen_mode_.IsFullscreen())
error_ = "DidChangeview is in fullscreen";
else if (position != normal_position_)
error_ = "DidChangeView position is not normal";
pp::Module::Get()->core()->CallOnMainThread(0, normal_callback_);
}
}
<|endoftext|>
|
<commit_before>#include <mex.h>
#include <stdio.h>
#include <zmq.h>
#include <string.h>
#include <assert.h>
#include "protocol.h"
////////////////////////////////////////////////////////////
// Global variables
uint16_T socket_port;
uint32_T socket_timeout;
void *context;
void *zsocket;
zmq_pollitem_t poll_items [1];
////////////////////////////////////////////////////////////
// Prototypes
static void close_socket();
bool server_init(const mxArray *config);
bool server_recv(const mxArray *config, mxArray *msg_array);
////////////////////////////////////////////////////////////
// Initialise the server
bool server_init(const mxArray *config)
{
if (context != NULL) {
// We have already been initialised
printf("Server: INIT called again\n");
close_socket();
}
// Load config settings
socket_port = getConfigField<uint16_T>(config, "port", "uint16");
socket_timeout = getConfigField<uint32_T>(config, "timeout", "uint32");
// Initialise ZMQ
context = zmq_ctx_new();
zsocket = zmq_socket(context, ZMQ_REP);
if (zsocket == NULL) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:failure",
"Failed to create ZMQ socket:\n%s", zmq_strerror(errno));
}
mexAtExit(close_socket);
int linger = 0;
zmq_setsockopt(zsocket, ZMQ_LINGER, &linger, sizeof(linger));
// Bind the socket
char endpoint [30];
#ifdef _WIN32
// Silly windows defines its own version of this function
_snprintf_s(endpoint, 30, "tcp://*:%i", socket_port);
#else
snprintf(endpoint, 30, "tcp://*:%i", socket_port);
#endif
int rc = zmq_bind(zsocket, endpoint);
if (rc != 0) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:failure",
"Failed to bind ZMQ socket:\n%s", zmq_strerror(errno));
}
// Prepare the poll items (for the RECV call)
poll_items[0].socket = zsocket;
poll_items[0].events = ZMQ_POLLIN;
// Done
printf("Server initialised\n");
return true;
}
////////////////////////////////////////////////////////////
// Receive on the socket, or timeout
bool server_recv(const mxArray *config, mxArray *msg_array)
{
int rc;
if (context == NULL) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:failure",
"RECV called before INIT");
}
// Initialise a zmq_msg_t structure to receive the message
zmq_msg_t zmsg;
rc = zmq_msg_init(&zmsg);
assert(rc == 0);
// Attempt to receive a message
errno = EAGAIN; // On windows, zmq_msg_recv does not seem to set this!
int num_bytes = zmq_msg_recv(&zmsg, zsocket, ZMQ_DONTWAIT);
if (num_bytes == -1) {
// Did not receive a message ...
if (errno == EAGAIN) {
// ... because none were available.
// Wait for a message to be available.
int nevents = zmq_poll(poll_items, 1, socket_timeout);
if (nevents == -1) {
int poll_errno = errno;
zmq_msg_close(&zmsg);
mexErrMsgIdAndTxt( "MATLAB:zmq_communicate:error",
"Failed to poll socket: %s", zmq_strerror(poll_errno));
} else if (nevents == 0) {
// Timeout.
zmq_msg_close(&zmsg);
return false;
} else {
// A message is available
num_bytes = zmq_msg_recv(&zmsg, zsocket, 0);
}
} else {
// ... because receiving failed
int poll_errno = errno;
zmq_msg_close(&zmsg);
mexErrMsgIdAndTxt( "MATLAB:zmq_communicate:error",
"Failed to receive from socket: %s", zmq_strerror(poll_errno));
}
}
//printf("Server received %i bytes\n", num_bytes);
uint8_T *msg_zmq_data = (uint8_T *)zmq_msg_data(&zmsg);
// Allocate memory on the MATLAB side
uint8_T *msg_matlab_data = (uint8_T *)mxCalloc(num_bytes, sizeof(uint8_T));
// Copy the memory
memcpy(msg_matlab_data, msg_zmq_data, num_bytes);
// Link the MATLAB memory to the return value
mxSetData(msg_array, msg_matlab_data);
mxSetM(msg_array, 1);
mxSetN(msg_array, num_bytes);
// Free the message
zmq_msg_close(&zmsg);
return true;
}
////////////////////////////////////////////////////////////
// Send on the socket
bool server_send(const mxArray *data)
{
int rc;
uint8_T *req_data = (uint8_T*) mxGetData(data);
size_t req_size = mxGetNumberOfElements(data);
rc = zmq_send(zsocket, req_data, req_size*sizeof(uint8_T), 0);
//printf("Sent %i bytes.\n", rc);
if (rc != req_size*sizeof(uint8_T)) {
mexErrMsgIdAndTxt( "MATLAB:zmq_communicate:error",
"Failed to send message: %s", zmq_strerror(errno));
}
return true;
}
////////////////////////////////////////////////////////////
// Close the socket
static void close_socket()
{
printf("server: closing ZMQ socket\n");
if (zsocket != NULL) {
zmq_close(zsocket);
zsocket = NULL;
}
if (context != NULL) {
zmq_ctx_destroy(context);
context = NULL;
}
}
////////////////////////////////////////////////////////////
// MATLAB mex function wrapper
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
// Check for the proper number of arguments
if (nrhs != 2) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:invalidNumInputs",
"Usage: [has_msg, msg] = server_communicate(mode, data)");
}
if (nlhs != 2) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:invalidNumOutputs",
"Need two return values.\n"
"Usage: [has_msg, msg] = server_communicate(mode, data)");
}
// Check the mode
if ( (mxGetM(prhs[0]) != 1)
|| (mxGetN(prhs[0]) != 1)
|| !mxIsClass(prhs[0], "uint32") ) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:invalidInputs",
"Usage: server_communicate(mode, data)\n"
"Mode argument must be uint32");
}
// Initialise the data return value
plhs[1] = mxCreateNumericMatrix(0, 0, mxUINT8_CLASS, mxREAL);
// Check the mode, and run the appropriate function
uint32_T *mode = (uint32_T *)mxGetData(prhs[0]);
bool success;
switch (*mode) {
case SERVER_INIT:
success = server_init(prhs[1]);
break;
case SERVER_RECV:
success = server_recv(prhs[1], plhs[1]);
break;
case SERVER_SEND:
success = server_send(prhs[1]);
break;
default:
mexErrMsgIdAndTxt( "MATLAB:server_communicate:invalidInputs",
"Usage: server_communicate(mode, data)\n"
"Invalid mode argument");
}
// Set the success flag
mxLogical *successData = (mxLogical *)mxCalloc(1, sizeof(mxLogical));
*successData = success;
plhs[0] = mxCreateNumericMatrix(0, 0, mxLOGICAL_CLASS, mxREAL);
mxSetData(plhs[0], successData);
mxSetM(plhs[0], 1);
mxSetN(plhs[0], 1);
}
<commit_msg>Squashed '+netsrv/' changes from c497090..ab56df2<commit_after>#include <mex.h>
#include <stdio.h>
#include <zmq.h>
#include <string.h>
#include <assert.h>
#include "protocol.h"
////////////////////////////////////////////////////////////
// Global variables
uint16_T socket_port;
uint32_T socket_timeout;
void *context;
void *zsocket;
zmq_pollitem_t poll_items [1];
////////////////////////////////////////////////////////////
// Prototypes
static void close_socket();
bool server_init(const mxArray *config);
bool server_recv(const mxArray *config, mxArray *msg_array);
////////////////////////////////////////////////////////////
// Initialise the server
bool server_init(const mxArray *config)
{
if (context != NULL) {
// We have already been initialised
printf("Server: INIT called again\n");
close_socket();
}
// Load config settings
socket_port = getConfigField<uint16_T>(config, "port", "uint16");
socket_timeout = getConfigField<uint32_T>(config, "timeout", "uint32");
// Initialise ZMQ
context = zmq_ctx_new();
zsocket = zmq_socket(context, ZMQ_REP);
if (zsocket == NULL) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:failure",
"Failed to create ZMQ socket:\n%s", zmq_strerror(errno));
}
mexAtExit(close_socket);
int linger = 0;
zmq_setsockopt(zsocket, ZMQ_LINGER, &linger, sizeof(linger));
// Bind the socket
char endpoint [30];
#ifdef _WIN32
// Silly windows defines its own version of this function
_snprintf_s(endpoint, 30, "tcp://*:%i", socket_port);
#else
snprintf(endpoint, 30, "tcp://*:%i", socket_port);
#endif
int rc = zmq_bind(zsocket, endpoint);
if (rc != 0) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:failure",
"Failed to bind ZMQ socket:\n%s", zmq_strerror(errno));
}
// Prepare the poll items (for the RECV call)
poll_items[0].socket = zsocket;
poll_items[0].events = ZMQ_POLLIN;
// Done
printf("Server initialised\n");
return true;
}
////////////////////////////////////////////////////////////
// Receive on the socket, or timeout
bool server_recv(const mxArray *config, mxArray *msg_array)
{
int rc;
if (context == NULL) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:failure",
"RECV called before INIT");
}
// Initialise a zmq_msg_t structure to receive the message
zmq_msg_t zmsg;
rc = zmq_msg_init(&zmsg);
assert(rc == 0);
// Attempt to receive a message
errno = EAGAIN; // On windows, zmq_msg_recv does not seem to set this!
int num_bytes = zmq_msg_recv(&zmsg, zsocket, ZMQ_DONTWAIT);
if (num_bytes == -1) {
// Did not receive a message ...
if (errno == EAGAIN) {
// ... because none were available.
// Wait for a message to be available.
int nevents = zmq_poll(poll_items, 1, socket_timeout);
if (nevents == -1) {
if (errno == EINTR) {
// System call was interrupted. Treat this like a timeout.
zmq_msg_close(&zmsg);
return false;
}
int poll_errno = errno;
zmq_msg_close(&zmsg);
mexErrMsgIdAndTxt( "MATLAB:zmq_communicate:error",
"Failed to poll socket: %s", zmq_strerror(poll_errno));
} else if (nevents == 0) {
// Timeout.
zmq_msg_close(&zmsg);
return false;
} else {
// A message is available
num_bytes = zmq_msg_recv(&zmsg, zsocket, 0);
}
} else {
// ... because receiving failed
int poll_errno = errno;
zmq_msg_close(&zmsg);
mexErrMsgIdAndTxt( "MATLAB:zmq_communicate:error",
"Failed to receive from socket: %s", zmq_strerror(poll_errno));
}
}
//printf("Server received %i bytes\n", num_bytes);
uint8_T *msg_zmq_data = (uint8_T *)zmq_msg_data(&zmsg);
// Allocate memory on the MATLAB side
uint8_T *msg_matlab_data = (uint8_T *)mxCalloc(num_bytes, sizeof(uint8_T));
// Copy the memory
memcpy(msg_matlab_data, msg_zmq_data, num_bytes);
// Link the MATLAB memory to the return value
mxSetData(msg_array, msg_matlab_data);
mxSetM(msg_array, 1);
mxSetN(msg_array, num_bytes);
// Free the message
zmq_msg_close(&zmsg);
return true;
}
////////////////////////////////////////////////////////////
// Send on the socket
bool server_send(const mxArray *data)
{
int rc;
uint8_T *req_data = (uint8_T*) mxGetData(data);
size_t req_size = mxGetNumberOfElements(data);
rc = zmq_send(zsocket, req_data, req_size*sizeof(uint8_T), 0);
//printf("Sent %i bytes.\n", rc);
if (rc != req_size*sizeof(uint8_T)) {
mexErrMsgIdAndTxt( "MATLAB:zmq_communicate:error",
"Failed to send message: %s", zmq_strerror(errno));
}
return true;
}
////////////////////////////////////////////////////////////
// Close the socket
static void close_socket()
{
printf("server: closing ZMQ socket\n");
if (zsocket != NULL) {
zmq_close(zsocket);
zsocket = NULL;
}
if (context != NULL) {
zmq_ctx_destroy(context);
context = NULL;
}
}
////////////////////////////////////////////////////////////
// MATLAB mex function wrapper
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
// Check for the proper number of arguments
if (nrhs != 2) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:invalidNumInputs",
"Usage: [has_msg, msg] = server_communicate(mode, data)");
}
if (nlhs != 2) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:invalidNumOutputs",
"Need two return values.\n"
"Usage: [has_msg, msg] = server_communicate(mode, data)");
}
// Check the mode
if ( (mxGetM(prhs[0]) != 1)
|| (mxGetN(prhs[0]) != 1)
|| !mxIsClass(prhs[0], "uint32") ) {
mexErrMsgIdAndTxt( "MATLAB:server_communicate:invalidInputs",
"Usage: server_communicate(mode, data)\n"
"Mode argument must be uint32");
}
// Initialise the data return value
plhs[1] = mxCreateNumericMatrix(0, 0, mxUINT8_CLASS, mxREAL);
// Check the mode, and run the appropriate function
uint32_T *mode = (uint32_T *)mxGetData(prhs[0]);
bool success;
switch (*mode) {
case SERVER_INIT:
success = server_init(prhs[1]);
break;
case SERVER_RECV:
success = server_recv(prhs[1], plhs[1]);
break;
case SERVER_SEND:
success = server_send(prhs[1]);
break;
default:
mexErrMsgIdAndTxt( "MATLAB:server_communicate:invalidInputs",
"Usage: server_communicate(mode, data)\n"
"Invalid mode argument");
}
// Set the success flag
mxLogical *successData = (mxLogical *)mxCalloc(1, sizeof(mxLogical));
*successData = success;
plhs[0] = mxCreateNumericMatrix(0, 0, mxLOGICAL_CLASS, mxREAL);
mxSetData(plhs[0], successData);
mxSetM(plhs[0], 1);
mxSetN(plhs[0], 1);
}
<|endoftext|>
|
<commit_before>#include <leveldb/db.h>
#include <leveldb/slice.h>
#include <leveldb/env.h>
#include <leveldb/write_batch.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include <errno.h>
#include <time.h>
#include <netinet/tcp.h>
#include <list>
using namespace std;
static const int RESULT_GOOD = 1273252631;
static const int RESULT_BAD = 9999;
static const int RESULT_NOTFOUND = 133133;
leveldb::DB* db;
leveldb::WriteOptions write_options;
void error(const char *msg)
{
perror(msg);
exit(1);
}
struct connection_info
{
int fd;
};
int read_fully(int fd, char* buffer, int len)
{
int offset = 0;
while(offset < len)
{
int r = read(fd, buffer + offset, len - offset);
if (r <= 0) return r;
offset += r;
}
return offset;
}
int write_fully(int fd, const char* buffer, int len)
{
int offset = 0;
while(offset < len)
{
int r = write(fd, buffer + offset, len - offset);
if (r < 0) cout << "errno:" << errno << " " << strerror(errno) << endl;
if (r <= 0) return r;
offset += r;
}
return offset;
}
/*
* The data in the slice will need to be freed
*/
int read_slice(int fd, leveldb::Slice &s)
{
int sz;
if(read_fully(fd, (char*)&sz, sizeof(sz)) <= 0) return -1;
sz = ntohl(sz);
char* data= NULL;
if (sz > 0)
{
data = new char[sz];
if(read_fully(fd, data, sz) <= 0)
{
return -1;
}
}
s = leveldb::Slice(data,sz);
//delete data;
return 0;
}
int write_slice(int fd, leveldb::Slice &s)
{
int sz = htonl(s.size());
if (write_fully(fd, (char*)&sz, sizeof(sz)) < 0) return -1;
if (write_fully(fd, s.data(), s.size()) < 0) return -1;
return 0;
}
leveldb::Slice cloneSlice(leveldb::Slice a)
{
char* b = new char[a.size()];
memcpy(b, a.data(), a.size());
return leveldb::Slice(b, a.size());
}
void* handle_connection(void* arg)
{
connection_info* info=(connection_info*)arg;
int fd = info->fd;
//FILE* f = fdopen(fd, "w+");
// [action][options]
// actions
// 1 - get (size = bytes of data) (data = key)
// [size][keydata]
// 2 - put (size = number of keyvalues)
// [key_size][keydata][value_size][valuedata]
// 3 - putall
// [items]
// [key_size][keydata][value_size][valuedata] (item times)
// 4 - getprefix
// [size][keydata]
// Returns for puts: int status code, 0 = no problems
// Return for gets: int status code, 0 = no problems, [size][valuedata]
// Returns for getprefix: int status code
// [items]
// [key_size][keydata][value_size][valuedata] (item times)
bool problems=false;
while(!problems)
{
char action[2];
if (read_fully(fd, action, 2) <= 0) { problems=true; break;}
if (action[0] == 1)
{
leveldb::Slice key;
if (read_slice(fd, key) < 0) { problems=true; break;}
string value;
leveldb::Status db_stat = db->Get(leveldb::ReadOptions(),key, &value);
delete []key.data();
int status=RESULT_GOOD;
if (db_stat.IsNotFound())
{
status=RESULT_NOTFOUND;
}
int net_status=htonl(status);
write_fully(fd, (char*)&net_status, sizeof(net_status));
if (status==RESULT_GOOD)
{
leveldb::Slice s = leveldb::Slice(value);
if (write_slice(fd, s) < 0) { problems=true; break;}
}
fsync(fd);
}
else if (action[0] == 2)
{
leveldb::Slice key;
leveldb::Slice value;
if (read_slice(fd, key) < 0) { problems=true; break;}
if (read_slice(fd, value) < 0) { problems=true; break;}
leveldb::Status db_stat = db->Put(write_options,key, value);
delete[] key.data();
delete[] value.data();
int status=RESULT_BAD;
if (db_stat.ok())
{
status=RESULT_GOOD;
}
else
{
cout << db_stat.ToString() << endl;
if (db_stat.IsCorruption() || db_stat.IsIOError()) exit(10);
}
status=htonl(status);
write_fully(fd, (char*)&status, sizeof(status));
fsync(fd);
}
else if (action[0] == 3)
{
int items;
if(read_fully(fd, (char*)&items, sizeof(items)) <= 0) { problems=true; break;}
items = ntohl(items);
leveldb::WriteBatch write_batch;
list<leveldb::Slice> slices;
for(int i = 0; i<items; i++)
{
leveldb::Slice key;
leveldb::Slice value;
if (read_slice(fd, key) < 0) { problems=true; break;}
if (read_slice(fd, value) < 0) { problems=true; break;}
write_batch.Put(key, value);
slices.push_back(key);
slices.push_back(value);
}
if (problems) break;
leveldb::Status db_stat = db->Write(write_options, &write_batch);
int status=RESULT_BAD;
if (db_stat.ok())
{
status=RESULT_GOOD;
}
else
{
cout << db_stat.ToString() << endl;
if (db_stat.IsCorruption() || db_stat.IsIOError()) exit(10);
}
for(list<leveldb::Slice>::iterator I = slices.begin(); I!=slices.end(); I++)
{
delete[] I->data();
}
status=htonl(status);
write_fully(fd, (char*)&status, sizeof(status));
fsync(fd);
}
else if (action[0] == 4)
{
leveldb::Slice prefix;
if (read_slice(fd, prefix) < 0) { problems=true; break;}
list<leveldb::Slice> slices;
slices.clear();
leveldb::Iterator* I = db->NewIterator(leveldb::ReadOptions());
int items=0;
for(I->Seek(prefix); I->Valid() && I->key().starts_with(prefix) ;I->Next())
{
slices.push_back(cloneSlice(I->key()));
slices.push_back(cloneSlice(I->value()));
items++;
}
int status=RESULT_GOOD;
status=htonl(status);
write_fully(fd, (char*)&status, sizeof(status));
items=htonl(items);
write_fully(fd, (char*)&items, sizeof(items));
for(list<leveldb::Slice>::iterator it = slices.begin(); it!=slices.end(); it++)
{
leveldb::Slice s=*it;
if (write_slice(fd, s) < 0) { problems=true; break;}
delete[] s.data();
}
delete[] prefix.data();
delete I;
}
else
{
problems=true;
}
}
//cout << "Closing socket with problems" << endl;
close(fd);
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
cout << "Params: ./levelnet path_level_db" << endl;
return -1;
}
cout << "LevelDB version " << leveldb::kMajorVersion << "." << leveldb::kMinorVersion << endl;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, argv[1], &db);
//write_options.sync = true;
if (!status.ok()) cerr << status.ToString() << endl;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serv_addr;
int yes=1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(int));
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(8844);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,16);
while(true)
{
socklen_t clilen;
struct sockaddr_in cli_addr;
clilen = sizeof(cli_addr);
int newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
pthread_t pt;
connection_info info;
info.fd = newsockfd;
pthread_create(&pt, NULL, handle_connection, &info);
}
}
<commit_msg>Set read timeout<commit_after>#include <leveldb/db.h>
#include <leveldb/slice.h>
#include <leveldb/env.h>
#include <leveldb/write_batch.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include <errno.h>
#include <time.h>
#include <netinet/tcp.h>
#include <list>
using namespace std;
static const int RESULT_GOOD = 1273252631;
static const int RESULT_BAD = 9999;
static const int RESULT_NOTFOUND = 133133;
leveldb::DB* db;
leveldb::WriteOptions write_options;
void error(const char *msg)
{
perror(msg);
exit(1);
}
struct connection_info
{
int fd;
};
int read_fully(int fd, char* buffer, int len)
{
int offset = 0;
while(offset < len)
{
int r = read(fd, buffer + offset, len - offset);
if (r <= 0) return r;
offset += r;
}
return offset;
}
int write_fully(int fd, const char* buffer, int len)
{
int offset = 0;
while(offset < len)
{
int r = write(fd, buffer + offset, len - offset);
if (r < 0) cout << "errno:" << errno << " " << strerror(errno) << endl;
if (r <= 0) return r;
offset += r;
}
return offset;
}
/*
* The data in the slice will need to be freed
*/
int read_slice(int fd, leveldb::Slice &s)
{
int sz;
if(read_fully(fd, (char*)&sz, sizeof(sz)) <= 0) return -1;
sz = ntohl(sz);
char* data= NULL;
if (sz > 0)
{
data = new char[sz];
if(read_fully(fd, data, sz) <= 0)
{
return -1;
}
}
s = leveldb::Slice(data,sz);
//delete data;
return 0;
}
int write_slice(int fd, leveldb::Slice &s)
{
int sz = htonl(s.size());
if (write_fully(fd, (char*)&sz, sizeof(sz)) < 0) return -1;
if (write_fully(fd, s.data(), s.size()) < 0) return -1;
return 0;
}
leveldb::Slice cloneSlice(leveldb::Slice a)
{
char* b = new char[a.size()];
memcpy(b, a.data(), a.size());
return leveldb::Slice(b, a.size());
}
void* handle_connection(void* arg)
{
connection_info* info=(connection_info*)arg;
int fd = info->fd;
//FILE* f = fdopen(fd, "w+");
// [action][options]
// actions
// 1 - get (size = bytes of data) (data = key)
// [size][keydata]
// 2 - put (size = number of keyvalues)
// [key_size][keydata][value_size][valuedata]
// 3 - putall
// [items]
// [key_size][keydata][value_size][valuedata] (item times)
// 4 - getprefix
// [size][keydata]
// Returns for puts: int status code, 0 = no problems
// Return for gets: int status code, 0 = no problems, [size][valuedata]
// Returns for getprefix: int status code
// [items]
// [key_size][keydata][value_size][valuedata] (item times)
bool problems=false;
while(!problems)
{
char action[2];
if (read_fully(fd, action, 2) <= 0) { problems=true; break;}
if (action[0] == 1)
{
leveldb::Slice key;
if (read_slice(fd, key) < 0) { problems=true; break;}
string value;
leveldb::Status db_stat = db->Get(leveldb::ReadOptions(),key, &value);
delete []key.data();
int status=RESULT_GOOD;
if (db_stat.IsNotFound())
{
status=RESULT_NOTFOUND;
}
int net_status=htonl(status);
write_fully(fd, (char*)&net_status, sizeof(net_status));
if (status==RESULT_GOOD)
{
leveldb::Slice s = leveldb::Slice(value);
if (write_slice(fd, s) < 0) { problems=true; break;}
}
fsync(fd);
}
else if (action[0] == 2)
{
leveldb::Slice key;
leveldb::Slice value;
if (read_slice(fd, key) < 0) { problems=true; break;}
if (read_slice(fd, value) < 0) { problems=true; break;}
leveldb::Status db_stat = db->Put(write_options,key, value);
delete[] key.data();
delete[] value.data();
int status=RESULT_BAD;
if (db_stat.ok())
{
status=RESULT_GOOD;
}
else
{
cout << db_stat.ToString() << endl;
if (db_stat.IsCorruption() || db_stat.IsIOError()) exit(10);
}
status=htonl(status);
write_fully(fd, (char*)&status, sizeof(status));
fsync(fd);
}
else if (action[0] == 3)
{
int items;
if(read_fully(fd, (char*)&items, sizeof(items)) <= 0) { problems=true; break;}
items = ntohl(items);
leveldb::WriteBatch write_batch;
list<leveldb::Slice> slices;
for(int i = 0; i<items; i++)
{
leveldb::Slice key;
leveldb::Slice value;
if (read_slice(fd, key) < 0) { problems=true; break;}
if (read_slice(fd, value) < 0) { problems=true; break;}
write_batch.Put(key, value);
slices.push_back(key);
slices.push_back(value);
}
if (problems) break;
leveldb::Status db_stat = db->Write(write_options, &write_batch);
int status=RESULT_BAD;
if (db_stat.ok())
{
status=RESULT_GOOD;
}
else
{
cout << db_stat.ToString() << endl;
if (db_stat.IsCorruption() || db_stat.IsIOError()) exit(10);
}
for(list<leveldb::Slice>::iterator I = slices.begin(); I!=slices.end(); I++)
{
delete[] I->data();
}
status=htonl(status);
write_fully(fd, (char*)&status, sizeof(status));
fsync(fd);
}
else if (action[0] == 4)
{
leveldb::Slice prefix;
if (read_slice(fd, prefix) < 0) { problems=true; break;}
list<leveldb::Slice> slices;
slices.clear();
leveldb::Iterator* I = db->NewIterator(leveldb::ReadOptions());
int items=0;
for(I->Seek(prefix); I->Valid() && I->key().starts_with(prefix) ;I->Next())
{
slices.push_back(cloneSlice(I->key()));
slices.push_back(cloneSlice(I->value()));
items++;
}
int status=RESULT_GOOD;
status=htonl(status);
write_fully(fd, (char*)&status, sizeof(status));
items=htonl(items);
write_fully(fd, (char*)&items, sizeof(items));
for(list<leveldb::Slice>::iterator it = slices.begin(); it!=slices.end(); it++)
{
leveldb::Slice s=*it;
if (write_slice(fd, s) < 0) { problems=true; break;}
delete[] s.data();
}
delete[] prefix.data();
delete I;
}
else
{
problems=true;
}
}
//cout << "Closing socket with problems" << endl;
close(fd);
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
cout << "Params: ./levelnet path_level_db" << endl;
return -1;
}
cout << "LevelDB version " << leveldb::kMajorVersion << "." << leveldb::kMinorVersion << endl;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, argv[1], &db);
//write_options.sync = true;
if (!status.ok()) cerr << status.ToString() << endl;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serv_addr;
int yes=1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(int));
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(8844);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,16);
while(true)
{
socklen_t clilen;
struct sockaddr_in cli_addr;
clilen = sizeof(cli_addr);
int newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
struct timeval timeout;
timeout.tv_sec = 3600;
timeout.tv_usec = 0;
setsockopt(newsockfd, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout,
sizeof(timeout));
pthread_t pt;
connection_info info;
info.fd = newsockfd;
pthread_create(&pt, NULL, handle_connection, &info);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <graphene/app/application.hpp>
#include <graphene/delayed_node/delayed_node_plugin.hpp>
#include <graphene/account_history/account_history_plugin.hpp>
#include <graphene/market_history/market_history_plugin.hpp>
#include <fc/exception/exception.hpp>
#include <fc/thread/thread.hpp>
#include <fc/interprocess/signals.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <iostream>
#include <fstream>
#ifdef WIN32
# include <signal.h>
#else
# include <csignal>
#endif
using namespace graphene;
namespace bpo = boost::program_options;
void write_default_logging_config_to_stream(std::ostream& out);
fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path& config_ini_filename);
int main(int argc, char** argv) {
try {
app::application node;
bpo::options_description app_options("Graphene Delayed Node");
bpo::options_description cfg_options("Graphene Delayed Node");
app_options.add_options()
("help,h", "Print this help message and exit.")
("data-dir,d", bpo::value<boost::filesystem::path>()->default_value("delayed_node_data_dir"), "Directory containing databases, configuration file, etc.")
("plugins", bpo::value<std::string>()->default_value("delayed_node account_history market_history"),
"Space-separated list of plugins to activate");
;
bpo::variables_map options;
auto delayed_plug = node.register_plugin<delayed_node::delayed_node_plugin>();
auto history_plug = node.register_plugin<account_history::account_history_plugin>();
auto market_history_plug = node.register_plugin<market_history::market_history_plugin>();
try
{
bpo::options_description cli, cfg;
node.set_program_options(cli, cfg);
app_options.add(cli);
cfg_options.add(cfg);
bpo::store(bpo::parse_command_line(argc, argv, app_options), options);
}
catch (const boost::program_options::error& e)
{
std::cerr << "Error parsing command line: " << e.what() << "\n";
return 1;
}
if( options.count("help") )
{
std::cout << app_options << "\n";
return 0;
}
fc::path data_dir;
if( options.count("data-dir") )
{
data_dir = options["data-dir"].as<boost::filesystem::path>();
if( data_dir.is_relative() )
data_dir = fc::current_path() / data_dir;
}
fc::path config_ini_path = data_dir / "config.ini";
// Create config file if not already present
if( !fc::exists(config_ini_path) )
{
ilog("Writing new config file at ${path}", ("path", config_ini_path));
if( !fc::exists(data_dir) )
fc::create_directories(data_dir);
std::ofstream out_cfg(config_ini_path.preferred_string());
for( const boost::shared_ptr<bpo::option_description> od : cfg_options.options() )
{
if( !od->description().empty() )
out_cfg << "# " << od->description() << "\n";
boost::any store;
if( !od->semantic()->apply_default(store) )
out_cfg << "# " << od->long_name() << " = \n";
else {
auto example = od->format_parameter();
if( example.empty() )
// This is a boolean switch
out_cfg << od->long_name() << " = " << "false\n";
else {
// The string is formatted "arg (=<interesting part>)"
example.erase(0, 6);
example.erase(example.length()-1);
out_cfg << od->long_name() << " = " << example << "\n";
}
}
out_cfg << "\n";
}
write_default_logging_config_to_stream(out_cfg);
out_cfg.close();
// read the default logging config we just wrote out to the file and start using it
fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path);
if (logging_config)
fc::configure_logging(*logging_config);
}
// Parse configuration file
try {
bpo::store(bpo::parse_config_file<char>(config_ini_path.preferred_string().c_str(), cfg_options, true), options);
// try to get logging options from the config file.
try
{
fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path);
if (logging_config)
fc::configure_logging(*logging_config);
}
catch (const fc::exception&)
{
wlog("Error parsing logging config from config file ${config}, using default config", ("config", config_ini_path.preferred_string()));
}
bpo::notify(options);
} catch( const boost::program_options::error& e ) {
elog("Error parsing configuration file: ${e}", ("e", e.what()));
return 1;
}
std::set<std::string> plugins;
boost::split(plugins, options.at("plugins").as<std::string>(), [](char c){return c == ' ';});
if(plugins.count("account_history") && plugins.count("elasticsearch")) {
std::cerr << "Plugin conflict: Cannot load both account_history plugin and elasticsearch plugin\n";
return 1;
}
std::for_each(plugins.begin(), plugins.end(), [&](const std::string& plug) mutable {
if (!plug.empty()) {
node.enable_plugin(plug);
}
});
node.initialize(data_dir, options);
node.initialize_plugins( options );
node.startup();
node.startup_plugins();
fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
fc::set_signal_handler([&exit_promise](int signal) {
exit_promise->set_value(signal);
}, SIGINT);
ilog("Started delayed node on a chain with ${h} blocks.", ("h", node.chain_database()->head_block_num()));
ilog("Chain ID is ${id}", ("id", node.chain_database()->get_chain_id()) );
int signal = exit_promise->wait();
ilog("Exiting from signal ${n}", ("n", signal));
node.shutdown_plugins();
return 0;
} catch( const fc::exception& e ) {
elog("Exiting with error:\n${e}", ("e", e.to_detail_string()));
return 1;
}
}
// logging config is too complicated to be parsed by boost::program_options,
// so we do it by hand
//
// Currently, you can only specify the filenames and logging levels, which
// are all most users would want to change. At a later time, options can
// be added to control rotation intervals, compression, and other seldom-
// used features
void write_default_logging_config_to_stream(std::ostream& out)
{
out << "# declare an appender named \"stderr\" that writes messages to the console\n"
"[log.console_appender.stderr]\n"
"stream=std_error\n\n"
"# declare an appender named \"p2p\" that writes messages to p2p.log\n"
"[log.file_appender.p2p]\n"
"filename=logs/p2p/p2p.log\n"
"# filename can be absolute or relative to this config file\n\n"
"# route any messages logged to the default logger to the \"stderr\" logger we\n"
"# declared above, if they are info level are higher\n"
"[logger.default]\n"
"level=info\n"
"appenders=stderr\n\n"
"# route messages sent to the \"p2p\" logger to the p2p appender declared above\n"
"[logger.p2p]\n"
"level=info\n"
"appenders=p2p\n\n";
}
fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path& config_ini_filename)
{
try
{
fc::logging_config logging_config;
bool found_logging_config = false;
boost::property_tree::ptree config_ini_tree;
boost::property_tree::ini_parser::read_ini(config_ini_filename.preferred_string().c_str(), config_ini_tree);
for (const auto& section : config_ini_tree)
{
const std::string& section_name = section.first;
const boost::property_tree::ptree& section_tree = section.second;
const std::string console_appender_section_prefix = "log.console_appender.";
const std::string file_appender_section_prefix = "log.file_appender.";
const std::string logger_section_prefix = "logger.";
if (boost::starts_with(section_name, console_appender_section_prefix))
{
std::string console_appender_name = section_name.substr(console_appender_section_prefix.length());
std::string stream_name = section_tree.get<std::string>("stream");
// construct a default console appender config here
// stdout/stderr will be taken from ini file, everything else hard-coded here
fc::console_appender::config console_appender_config;
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::debug,
fc::console_appender::color::green));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::warn,
fc::console_appender::color::brown));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::error,
fc::console_appender::color::cyan));
console_appender_config.stream = fc::variant(stream_name, 1).as<fc::console_appender::stream::type>(1);
logging_config.appenders.push_back(fc::appender_config(console_appender_name, "console", fc::variant(console_appender_config, GRAPHENE_MAX_NESTED_OBJECTS)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, file_appender_section_prefix))
{
std::string file_appender_name = section_name.substr(file_appender_section_prefix.length());
fc::path file_name = section_tree.get<std::string>("filename");
if (file_name.is_relative())
file_name = fc::absolute(config_ini_filename).parent_path() / file_name;
// construct a default file appender config here
// filename will be taken from ini file, everything else hard-coded here
fc::file_appender::config file_appender_config;
file_appender_config.filename = file_name;
file_appender_config.flush = true;
file_appender_config.rotate = true;
file_appender_config.rotation_interval = fc::hours(1);
file_appender_config.rotation_limit = fc::days(1);
logging_config.appenders.push_back(fc::appender_config(file_appender_name, "file", fc::variant(file_appender_config, GRAPHENE_MAX_NESTED_OBJECTS)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, logger_section_prefix))
{
std::string logger_name = section_name.substr(logger_section_prefix.length());
std::string level_string = section_tree.get<std::string>("level");
std::string appenders_string = section_tree.get<std::string>("appenders");
fc::logger_config logger_config(logger_name);
logger_config.level = fc::variant(level_string, 1).as<fc::log_level>(1);
boost::split(logger_config.appenders, appenders_string,
boost::is_any_of(" ,"),
boost::token_compress_on);
logging_config.loggers.push_back(logger_config);
found_logging_config = true;
}
}
if (found_logging_config)
return logging_config;
else
return fc::optional<fc::logging_config>();
}
FC_RETHROW_EXCEPTIONS(warn, "")
}
<commit_msg>remove useless check<commit_after>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <graphene/app/application.hpp>
#include <graphene/delayed_node/delayed_node_plugin.hpp>
#include <graphene/account_history/account_history_plugin.hpp>
#include <graphene/market_history/market_history_plugin.hpp>
#include <fc/exception/exception.hpp>
#include <fc/thread/thread.hpp>
#include <fc/interprocess/signals.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <iostream>
#include <fstream>
#ifdef WIN32
# include <signal.h>
#else
# include <csignal>
#endif
using namespace graphene;
namespace bpo = boost::program_options;
void write_default_logging_config_to_stream(std::ostream& out);
fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path& config_ini_filename);
int main(int argc, char** argv) {
try {
app::application node;
bpo::options_description app_options("Graphene Delayed Node");
bpo::options_description cfg_options("Graphene Delayed Node");
app_options.add_options()
("help,h", "Print this help message and exit.")
("data-dir,d", bpo::value<boost::filesystem::path>()->default_value("delayed_node_data_dir"), "Directory containing databases, configuration file, etc.")
("plugins", bpo::value<std::string>()->default_value("delayed_node account_history market_history"),
"Space-separated list of plugins to activate");
;
bpo::variables_map options;
auto delayed_plug = node.register_plugin<delayed_node::delayed_node_plugin>();
auto history_plug = node.register_plugin<account_history::account_history_plugin>();
auto market_history_plug = node.register_plugin<market_history::market_history_plugin>();
try
{
bpo::options_description cli, cfg;
node.set_program_options(cli, cfg);
app_options.add(cli);
cfg_options.add(cfg);
bpo::store(bpo::parse_command_line(argc, argv, app_options), options);
}
catch (const boost::program_options::error& e)
{
std::cerr << "Error parsing command line: " << e.what() << "\n";
return 1;
}
if( options.count("help") )
{
std::cout << app_options << "\n";
return 0;
}
fc::path data_dir;
if( options.count("data-dir") )
{
data_dir = options["data-dir"].as<boost::filesystem::path>();
if( data_dir.is_relative() )
data_dir = fc::current_path() / data_dir;
}
fc::path config_ini_path = data_dir / "config.ini";
// Create config file if not already present
if( !fc::exists(config_ini_path) )
{
ilog("Writing new config file at ${path}", ("path", config_ini_path));
if( !fc::exists(data_dir) )
fc::create_directories(data_dir);
std::ofstream out_cfg(config_ini_path.preferred_string());
for( const boost::shared_ptr<bpo::option_description> od : cfg_options.options() )
{
if( !od->description().empty() )
out_cfg << "# " << od->description() << "\n";
boost::any store;
if( !od->semantic()->apply_default(store) )
out_cfg << "# " << od->long_name() << " = \n";
else {
auto example = od->format_parameter();
if( example.empty() )
// This is a boolean switch
out_cfg << od->long_name() << " = " << "false\n";
else {
// The string is formatted "arg (=<interesting part>)"
example.erase(0, 6);
example.erase(example.length()-1);
out_cfg << od->long_name() << " = " << example << "\n";
}
}
out_cfg << "\n";
}
write_default_logging_config_to_stream(out_cfg);
out_cfg.close();
// read the default logging config we just wrote out to the file and start using it
fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path);
if (logging_config)
fc::configure_logging(*logging_config);
}
// Parse configuration file
try {
bpo::store(bpo::parse_config_file<char>(config_ini_path.preferred_string().c_str(), cfg_options, true), options);
// try to get logging options from the config file.
try
{
fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path);
if (logging_config)
fc::configure_logging(*logging_config);
}
catch (const fc::exception&)
{
wlog("Error parsing logging config from config file ${config}, using default config", ("config", config_ini_path.preferred_string()));
}
bpo::notify(options);
} catch( const boost::program_options::error& e ) {
elog("Error parsing configuration file: ${e}", ("e", e.what()));
return 1;
}
std::set<std::string> plugins;
boost::split(plugins, options.at("plugins").as<std::string>(), [](char c){return c == ' ';});
std::for_each(plugins.begin(), plugins.end(), [&](const std::string& plug) mutable {
if (!plug.empty()) {
node.enable_plugin(plug);
}
});
node.initialize(data_dir, options);
node.initialize_plugins( options );
node.startup();
node.startup_plugins();
fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
fc::set_signal_handler([&exit_promise](int signal) {
exit_promise->set_value(signal);
}, SIGINT);
ilog("Started delayed node on a chain with ${h} blocks.", ("h", node.chain_database()->head_block_num()));
ilog("Chain ID is ${id}", ("id", node.chain_database()->get_chain_id()) );
int signal = exit_promise->wait();
ilog("Exiting from signal ${n}", ("n", signal));
node.shutdown_plugins();
return 0;
} catch( const fc::exception& e ) {
elog("Exiting with error:\n${e}", ("e", e.to_detail_string()));
return 1;
}
}
// logging config is too complicated to be parsed by boost::program_options,
// so we do it by hand
//
// Currently, you can only specify the filenames and logging levels, which
// are all most users would want to change. At a later time, options can
// be added to control rotation intervals, compression, and other seldom-
// used features
void write_default_logging_config_to_stream(std::ostream& out)
{
out << "# declare an appender named \"stderr\" that writes messages to the console\n"
"[log.console_appender.stderr]\n"
"stream=std_error\n\n"
"# declare an appender named \"p2p\" that writes messages to p2p.log\n"
"[log.file_appender.p2p]\n"
"filename=logs/p2p/p2p.log\n"
"# filename can be absolute or relative to this config file\n\n"
"# route any messages logged to the default logger to the \"stderr\" logger we\n"
"# declared above, if they are info level are higher\n"
"[logger.default]\n"
"level=info\n"
"appenders=stderr\n\n"
"# route messages sent to the \"p2p\" logger to the p2p appender declared above\n"
"[logger.p2p]\n"
"level=info\n"
"appenders=p2p\n\n";
}
fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path& config_ini_filename)
{
try
{
fc::logging_config logging_config;
bool found_logging_config = false;
boost::property_tree::ptree config_ini_tree;
boost::property_tree::ini_parser::read_ini(config_ini_filename.preferred_string().c_str(), config_ini_tree);
for (const auto& section : config_ini_tree)
{
const std::string& section_name = section.first;
const boost::property_tree::ptree& section_tree = section.second;
const std::string console_appender_section_prefix = "log.console_appender.";
const std::string file_appender_section_prefix = "log.file_appender.";
const std::string logger_section_prefix = "logger.";
if (boost::starts_with(section_name, console_appender_section_prefix))
{
std::string console_appender_name = section_name.substr(console_appender_section_prefix.length());
std::string stream_name = section_tree.get<std::string>("stream");
// construct a default console appender config here
// stdout/stderr will be taken from ini file, everything else hard-coded here
fc::console_appender::config console_appender_config;
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::debug,
fc::console_appender::color::green));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::warn,
fc::console_appender::color::brown));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::error,
fc::console_appender::color::cyan));
console_appender_config.stream = fc::variant(stream_name, 1).as<fc::console_appender::stream::type>(1);
logging_config.appenders.push_back(fc::appender_config(console_appender_name, "console", fc::variant(console_appender_config, GRAPHENE_MAX_NESTED_OBJECTS)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, file_appender_section_prefix))
{
std::string file_appender_name = section_name.substr(file_appender_section_prefix.length());
fc::path file_name = section_tree.get<std::string>("filename");
if (file_name.is_relative())
file_name = fc::absolute(config_ini_filename).parent_path() / file_name;
// construct a default file appender config here
// filename will be taken from ini file, everything else hard-coded here
fc::file_appender::config file_appender_config;
file_appender_config.filename = file_name;
file_appender_config.flush = true;
file_appender_config.rotate = true;
file_appender_config.rotation_interval = fc::hours(1);
file_appender_config.rotation_limit = fc::days(1);
logging_config.appenders.push_back(fc::appender_config(file_appender_name, "file", fc::variant(file_appender_config, GRAPHENE_MAX_NESTED_OBJECTS)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, logger_section_prefix))
{
std::string logger_name = section_name.substr(logger_section_prefix.length());
std::string level_string = section_tree.get<std::string>("level");
std::string appenders_string = section_tree.get<std::string>("appenders");
fc::logger_config logger_config(logger_name);
logger_config.level = fc::variant(level_string, 1).as<fc::log_level>(1);
boost::split(logger_config.appenders, appenders_string,
boost::is_any_of(" ,"),
boost::token_compress_on);
logging_config.loggers.push_back(logger_config);
found_logging_config = true;
}
}
if (found_logging_config)
return logging_config;
else
return fc::optional<fc::logging_config>();
}
FC_RETHROW_EXCEPTIONS(warn, "")
}
<|endoftext|>
|
<commit_before>#include <stdint.h>
#include <assert.h>
/////////////////////////////////////////////////////////////////////////////////////////
class BitArray
{
public:
uint32_t *v;
const uint32_t size;
BitArray(uint32_t size =1)
: size(size)
{
v = new uint32_t [size];
}
~BitArray()
{
delete v;
}
uint32_t * operator[](int n)
{
return getDWord(n);
}
public:
uint32_t * getDWord(uint32_t n)
{
assert(n < size);
return v+n;
}
public:
/////////////////////////////////////
// Bit Operations
//number |= 1 << n; //set bit
//number &= ~(1 << n); //clear a bit
//number ^= 1 << n; //toggle a bit
//bit = (number >> n) & 1; //check a bit
//number ^= (-value ^ number) & (1 << n); //setting the nth bit to either 1 or 0
void setBit(uint32_t n)
{
uint32_t *pByte = getDWord(n/32);
*pByte |= 1 << n%32;
}
void clearBit(uint32_t n)
{
uint32_t *pByte = getDWord(n/32);
*pByte &= ~(1 << n%32);;
}
void toggleBit(uint32_t n)
{
uint32_t *pByte = getDWord(n/32);
*pByte ^= 1 << n%32;
}
uint32_t checkBit(uint32_t n)
{
uint32_t *pByte = getDWord(n/32);
return (*pByte >> n) & 1;
}
void setBit(uint32_t n, uint32_t val)
{
uint32_t *pByte = getDWord(n/32);
*pByte ^= (-val ^ *pByte) & (1 << n%32);
}
/////////////////////////////////////////////////
// DWord operations
void andDWord(uint32_t n, uint32_t val)
{
uint32_t *pByte = getDWord(n);
*pByte &= val;
}
void orDWord(uint32_t n, uint32_t val)
{
uint32_t *pByte = getDWord(n);
*pByte |= val;
}
uint32_t numberOfSetBits(uint32_t n)
{
uint32_t byte = * getDWord(n);
byte = byte - ((byte >> 1) & 0x55555555);
byte = (byte & 0x33333333) + ((byte >> 2) & 0x33333333);
return (((byte + (byte >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
/////////////////////////////////////////////////
// Array operations
void and(const BitArray &rhs)
{
assert(size == rhs.size);
for(uint32_t i=0; i<size; ++i)
andDWord(i, rhs.v[i]);
}
void or(const BitArray &rhs)
{
assert(size == rhs.size);
for(uint32_t i=0; i<size; ++i)
orDWord(i, rhs.v[i]);
}
uint32_t numberOfSetBits()
{
uint32_t ret = 0;
for(uint32_t i=0; i<size; ++i)
ret += numberOfSetBits(i);
return ret;
}
};
template <int L>
class BitArrayT : public BitArray
{
public:
BitArrayT()
: BitArray(L)
{}
};
//int main()
//{
// BitArray ba(2); ba.v[0] = ba.v[1] = 0;
//
// ba.setBit(2); assert(ba.v[0] == 4);
// ba.setBit(32); assert(ba.v[1] == 1);
// ba.clearBit(2); assert(ba.v[0] == 0);
// ba.clearBit(32); assert(ba.v[1] == 0);
// ba.toggleBit(3); assert(ba.v[0] == 8); assert(ba.checkBit(3) == 1);
// ba.toggleBit(63); /*assert(ba.v[0] == 2147483648L);*/ assert(ba.checkBit(63) == 1);
// ba.setBit(3,0); assert(ba.v[0] == 0); assert(ba.checkBit(3) == 0);
// ba.setBit(63,0); assert(ba.v[0] == 0); assert(ba.checkBit(63) == 0);
//
// ba.v[0] = 0x1AB; ba.andDWord(0, 0x100); assert(ba.v[0] == 0x100);
// ba.v[1] = 0x88; ba.andDWord(1, 8); assert(ba.v[1] == 8);
// ba.v[0] = 0x100; ba.orDWord(0, 0x1AB); assert(ba.v[0] == 0x1AB);
// ba.v[1] = 0x80; ba.orDWord(1, 8); assert(ba.v[1] == 0x88);
//
// ba.v[0] = 0x514841; assert(ba.numberOfSetBits(0) == 7);
// ba.v[1] = 0x854052AF; assert(ba.numberOfSetBits(1) == 13);
// assert(ba.numberOfSetBits() == 20);
//
// BitArrayT<2> bm; bm.v[0] = 0xFF00AA; bm.v[1] = 0x00BF00;
// *ba[0] = 0x00FF00; *ba[1] = 0xAA00CC;
// ba.and(bm);
// assert(*ba[0] == 0 && *ba[1] == 0);
//
// *ba[0] = 0x00CD00; *ba[1] = 0x880011;
// ba.or(bm);
// assert(*ba[0] == 0xFFCDAA && *ba[1] == 0x88BF11);
//}
<commit_msg>fix bitarray to uint32_t<commit_after>#include <stdint.h>
#include <assert.h>
/////////////////////////////////////////////////////////////////////////////////////////
class BitArray
{
public:
uint32_t *v;
const uint32_t size;
BitArray(uint32_t size =1)
: size(size)
{
v = new uint32_t [size];
}
~BitArray()
{
delete v;
}
uint32_t * operator[](uint32_t n)
{
return getDWord(n);
}
public:
uint32_t * getDWord(uint32_t n)
{
assert(n < size);
return v+n;
}
public:
/////////////////////////////////////
// Bit Operations
//number |= 1 << n; //set bit
//number &= ~(1 << n); //clear a bit
//number ^= 1 << n; //toggle a bit
//bit = (number >> n) & 1; //check a bit
//number ^= (-value ^ number) & (1 << n); //setting the nth bit to either 1 or 0
void setBit(uint32_t n)
{
uint32_t *pByte = getDWord(n/32);
*pByte |= 1 << n%32;
}
void clearBit(uint32_t n)
{
uint32_t *pByte = getDWord(n/32);
*pByte &= ~(1 << n%32);;
}
void toggleBit(uint32_t n)
{
uint32_t *pByte = getDWord(n/32);
*pByte ^= 1 << n%32;
}
uint32_t checkBit(uint32_t n)
{
uint32_t *pByte = getDWord(n/32);
return (*pByte >> n) & 1;
}
void setBit(uint32_t n, uint32_t val)
{
uint32_t *pByte = getDWord(n/32);
*pByte ^= (-val ^ *pByte) & (1 << n%32);
}
/////////////////////////////////////////////////
// DWord operations
void andDWord(uint32_t n, uint32_t val)
{
uint32_t *pByte = getDWord(n);
*pByte &= val;
}
void orDWord(uint32_t n, uint32_t val)
{
uint32_t *pByte = getDWord(n);
*pByte |= val;
}
uint32_t numberOfSetBits(uint32_t n)
{
uint32_t byte = * getDWord(n);
byte = byte - ((byte >> 1) & 0x55555555);
byte = (byte & 0x33333333) + ((byte >> 2) & 0x33333333);
return (((byte + (byte >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
/////////////////////////////////////////////////
// Array operations
void and(const BitArray &rhs)
{
assert(size == rhs.size);
for(uint32_t i=0; i<size; ++i)
andDWord(i, rhs.v[i]);
}
void or(const BitArray &rhs)
{
assert(size == rhs.size);
for(uint32_t i=0; i<size; ++i)
orDWord(i, rhs.v[i]);
}
uint32_t numberOfSetBits()
{
uint32_t ret = 0;
for(uint32_t i=0; i<size; ++i)
ret += numberOfSetBits(i);
return ret;
}
};
template <uint32_t L>
class BitArrayT : public BitArray
{
public:
BitArrayT()
: BitArray(L)
{}
};
//int main()
//{
// BitArray ba(2); ba.v[0] = ba.v[1] = 0;
//
// ba.setBit(2); assert(ba.v[0] == 4);
// ba.setBit(32); assert(ba.v[1] == 1);
// ba.clearBit(2); assert(ba.v[0] == 0);
// ba.clearBit(32); assert(ba.v[1] == 0);
// ba.toggleBit(3); assert(ba.v[0] == 8); assert(ba.checkBit(3) == 1);
// ba.toggleBit(63); /*assert(ba.v[0] == 2147483648L);*/ assert(ba.checkBit(63) == 1);
// ba.setBit(3,0); assert(ba.v[0] == 0); assert(ba.checkBit(3) == 0);
// ba.setBit(63,0); assert(ba.v[0] == 0); assert(ba.checkBit(63) == 0);
//
// ba.v[0] = 0x1AB; ba.andDWord(0, 0x100); assert(ba.v[0] == 0x100);
// ba.v[1] = 0x88; ba.andDWord(1, 8); assert(ba.v[1] == 8);
// ba.v[0] = 0x100; ba.orDWord(0, 0x1AB); assert(ba.v[0] == 0x1AB);
// ba.v[1] = 0x80; ba.orDWord(1, 8); assert(ba.v[1] == 0x88);
//
// ba.v[0] = 0x514841; assert(ba.numberOfSetBits(0) == 7);
// ba.v[1] = 0x854052AF; assert(ba.numberOfSetBits(1) == 13);
// assert(ba.numberOfSetBits() == 20);
//
// BitArrayT<2> bm; bm.v[0] = 0xFF00AA; bm.v[1] = 0x00BF00;
// *ba[0] = 0x00FF00; *ba[1] = 0xAA00CC;
// ba.and(bm);
// assert(*ba[0] == 0 && *ba[1] == 0);
//
// *ba[0] = 0x00CD00; *ba[1] = 0x880011;
// ba.or(bm);
// assert(*ba[0] == 0xFFCDAA && *ba[1] == 0x88BF11);
//}
<|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.
*/
/*
* Copyright (C) 2015 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <cstddef>
#include <iosfwd>
#include "core/sstring.hh"
#include "seastarx.hh"
namespace cql3 {
class operator_type {
public:
static const operator_type EQ;
static const operator_type LT;
static const operator_type LTE;
static const operator_type GTE;
static const operator_type GT;
static const operator_type IN;
static const operator_type CONTAINS;
static const operator_type CONTAINS_KEY;
static const operator_type NEQ;
static const operator_type IS_NOT;
private:
int32_t _b;
const operator_type& _reverse;
sstring _text;
private:
operator_type(int32_t b, const operator_type& reverse, sstring text)
: _b(b)
, _reverse(reverse)
, _text(std::move(text))
{}
public:
const operator_type& reverse() const { return _reverse; }
bool is_slice() const {
return (*this == LT) || (*this == LTE) || (*this == GT) || (*this == GTE);
}
sstring to_string() const { return _text; }
bool operator==(const operator_type& other) const { return this == &other; }
bool operator!=(const operator_type& other) const { return this != &other; }
#if 0
/**
* Write the serialized version of this <code>Operator</code> to the specified output.
*
* @param output the output to write to
* @throws IOException if an I/O problem occurs while writing to the specified output
*/
public void writeTo(DataOutput output) throws IOException
{
output.writeInt(b);
}
/**
* Deserializes a <code>Operator</code> instance from the specified input.
*
* @param input the input to read from
* @return the <code>Operator</code> instance deserialized
* @throws IOException if a problem occurs while deserializing the <code>Type</code> instance.
*/
public static Operator readFrom(DataInput input) throws IOException
{
int b = input.readInt();
for (Operator operator : values())
if (operator.b == b)
return operator;
throw new IOException(String.format("Cannot resolve Relation.Type from binary representation: %s", b));
}
#endif
};
static inline
std::ostream& operator<<(std::ostream& out, const operator_type& op) {
return out << op.to_string();
}
}
<commit_msg>cql3: Make operator_type class non-copyable<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.
*/
/*
* Copyright (C) 2015 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <cstddef>
#include <iosfwd>
#include "core/sstring.hh"
#include "seastarx.hh"
namespace cql3 {
class operator_type {
public:
static const operator_type EQ;
static const operator_type LT;
static const operator_type LTE;
static const operator_type GTE;
static const operator_type GT;
static const operator_type IN;
static const operator_type CONTAINS;
static const operator_type CONTAINS_KEY;
static const operator_type NEQ;
static const operator_type IS_NOT;
private:
int32_t _b;
const operator_type& _reverse;
sstring _text;
private:
operator_type(int32_t b, const operator_type& reverse, sstring text)
: _b(b)
, _reverse(reverse)
, _text(std::move(text))
{}
public:
operator_type(const operator_type&) = delete;
operator_type& operator=(const operator_type&) = delete;
const operator_type& reverse() const { return _reverse; }
bool is_slice() const {
return (*this == LT) || (*this == LTE) || (*this == GT) || (*this == GTE);
}
sstring to_string() const { return _text; }
bool operator==(const operator_type& other) const { return this == &other; }
bool operator!=(const operator_type& other) const { return this != &other; }
#if 0
/**
* Write the serialized version of this <code>Operator</code> to the specified output.
*
* @param output the output to write to
* @throws IOException if an I/O problem occurs while writing to the specified output
*/
public void writeTo(DataOutput output) throws IOException
{
output.writeInt(b);
}
/**
* Deserializes a <code>Operator</code> instance from the specified input.
*
* @param input the input to read from
* @return the <code>Operator</code> instance deserialized
* @throws IOException if a problem occurs while deserializing the <code>Type</code> instance.
*/
public static Operator readFrom(DataInput input) throws IOException
{
int b = input.readInt();
for (Operator operator : values())
if (operator.b == b)
return operator;
throw new IOException(String.format("Cannot resolve Relation.Type from binary representation: %s", b));
}
#endif
};
static inline
std::ostream& operator<<(std::ostream& out, const operator_type& op) {
return out << op.to_string();
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/api/jsepsessiondescription.h"
#include <memory>
#include "webrtc/base/arraysize.h"
#include "webrtc/base/stringencode.h"
#include "webrtc/pc/mediasession.h"
#include "webrtc/pc/webrtcsdp.h"
using cricket::SessionDescription;
namespace webrtc {
static const char* kSupportedTypes[] = {
JsepSessionDescription::kOffer,
JsepSessionDescription::kPrAnswer,
JsepSessionDescription::kAnswer
};
static bool IsTypeSupported(const std::string& type) {
bool type_supported = false;
for (size_t i = 0; i < arraysize(kSupportedTypes); ++i) {
if (kSupportedTypes[i] == type) {
type_supported = true;
break;
}
}
return type_supported;
}
// RFC 5245
// It is RECOMMENDED that default candidates be chosen based on the
// likelihood of those candidates to work with the peer that is being
// contacted. It is RECOMMENDED that relayed > reflexive > host.
static const int kPreferenceUnknown = 0;
static const int kPreferenceHost = 1;
static const int kPreferenceReflexive = 2;
static const int kPreferenceRelayed = 3;
static const char kDummyAddress[] = "0.0.0.0";
static const int kDummyPort = 9;
static int GetCandidatePreferenceFromType(const std::string& type) {
int preference = kPreferenceUnknown;
if (type == cricket::LOCAL_PORT_TYPE) {
preference = kPreferenceHost;
} else if (type == cricket::STUN_PORT_TYPE) {
preference = kPreferenceReflexive;
} else if (type == cricket::RELAY_PORT_TYPE) {
preference = kPreferenceRelayed;
} else {
RTC_NOTREACHED();
}
return preference;
}
// Update the connection address for the MediaContentDescription based on the
// candidates.
static void UpdateConnectionAddress(
const JsepCandidateCollection& candidate_collection,
cricket::ContentDescription* content_description) {
int port = kDummyPort;
std::string ip = kDummyAddress;
int current_preference = kPreferenceUnknown;
int current_family = AF_UNSPEC;
for (size_t i = 0; i < candidate_collection.count(); ++i) {
const IceCandidateInterface* jsep_candidate = candidate_collection.at(i);
if (jsep_candidate->candidate().component() !=
cricket::ICE_CANDIDATE_COMPONENT_RTP) {
continue;
}
// Default destination should be UDP only.
if (jsep_candidate->candidate().protocol() != cricket::UDP_PROTOCOL_NAME) {
continue;
}
const int preference =
GetCandidatePreferenceFromType(jsep_candidate->candidate().type());
const int family = jsep_candidate->candidate().address().ipaddr().family();
// See if this candidate is more preferable then the current one if it's the
// same family. Or if the current family is IPv4 already so we could safely
// ignore all IPv6 ones. WebRTC bug 4269.
// http://code.google.com/p/webrtc/issues/detail?id=4269
if ((preference <= current_preference && current_family == family) ||
(current_family == AF_INET && family == AF_INET6)) {
continue;
}
current_preference = preference;
current_family = family;
port = jsep_candidate->candidate().address().port();
ip = jsep_candidate->candidate().address().ipaddr().ToString();
}
rtc::SocketAddress connection_addr;
connection_addr.SetIP(ip);
connection_addr.SetPort(port);
static_cast<cricket::MediaContentDescription*>(content_description)
->set_connection_address(connection_addr);
}
const char SessionDescriptionInterface::kOffer[] = "offer";
const char SessionDescriptionInterface::kPrAnswer[] = "pranswer";
const char SessionDescriptionInterface::kAnswer[] = "answer";
const int JsepSessionDescription::kDefaultVideoCodecId = 100;
const char JsepSessionDescription::kDefaultVideoCodecName[] = "VP8";
SessionDescriptionInterface* CreateSessionDescription(const std::string& type,
const std::string& sdp,
SdpParseError* error) {
if (!IsTypeSupported(type)) {
return NULL;
}
JsepSessionDescription* jsep_desc = new JsepSessionDescription(type);
if (!jsep_desc->Initialize(sdp, error)) {
delete jsep_desc;
return NULL;
}
return jsep_desc;
}
JsepSessionDescription::JsepSessionDescription(const std::string& type)
: type_(type) {
}
JsepSessionDescription::~JsepSessionDescription() {}
bool JsepSessionDescription::Initialize(
cricket::SessionDescription* description,
const std::string& session_id,
const std::string& session_version) {
if (!description)
return false;
session_id_ = session_id;
session_version_ = session_version;
description_.reset(description);
candidate_collection_.resize(number_of_mediasections());
return true;
}
bool JsepSessionDescription::Initialize(const std::string& sdp,
SdpParseError* error) {
return SdpDeserialize(sdp, this, error);
}
bool JsepSessionDescription::AddCandidate(
const IceCandidateInterface* candidate) {
if (!candidate || candidate->sdp_mline_index() < 0)
return false;
size_t mediasection_index = 0;
if (!GetMediasectionIndex(candidate, &mediasection_index)) {
return false;
}
if (mediasection_index >= number_of_mediasections())
return false;
const std::string& content_name =
description_->contents()[mediasection_index].name;
const cricket::TransportInfo* transport_info =
description_->GetTransportInfoByName(content_name);
if (!transport_info) {
return false;
}
cricket::Candidate updated_candidate = candidate->candidate();
if (updated_candidate.username().empty()) {
updated_candidate.set_username(transport_info->description.ice_ufrag);
}
if (updated_candidate.password().empty()) {
updated_candidate.set_password(transport_info->description.ice_pwd);
}
std::unique_ptr<JsepIceCandidate> updated_candidate_wrapper(
new JsepIceCandidate(candidate->sdp_mid(),
static_cast<int>(mediasection_index),
updated_candidate));
if (!candidate_collection_[mediasection_index].HasCandidate(
updated_candidate_wrapper.get())) {
candidate_collection_[mediasection_index].add(
updated_candidate_wrapper.release());
UpdateConnectionAddress(
candidate_collection_[mediasection_index],
description_->contents()[mediasection_index].description);
}
return true;
}
size_t JsepSessionDescription::RemoveCandidates(
const std::vector<cricket::Candidate>& candidates) {
size_t num_removed = 0;
for (auto& candidate : candidates) {
int mediasection_index = GetMediasectionIndex(candidate);
if (mediasection_index < 0) {
// Not found.
continue;
}
num_removed += candidate_collection_[mediasection_index].remove(candidate);
UpdateConnectionAddress(
candidate_collection_[mediasection_index],
description_->contents()[mediasection_index].description);
}
return num_removed;
}
size_t JsepSessionDescription::number_of_mediasections() const {
if (!description_)
return 0;
return description_->contents().size();
}
const IceCandidateCollection* JsepSessionDescription::candidates(
size_t mediasection_index) const {
if (mediasection_index >= candidate_collection_.size())
return NULL;
return &candidate_collection_[mediasection_index];
}
bool JsepSessionDescription::ToString(std::string* out) const {
if (!description_ || !out) {
return false;
}
*out = SdpSerialize(*this, false);
return !out->empty();
}
bool JsepSessionDescription::GetMediasectionIndex(
const IceCandidateInterface* candidate,
size_t* index) {
if (!candidate || !index) {
return false;
}
*index = static_cast<size_t>(candidate->sdp_mline_index());
if (description_ && !candidate->sdp_mid().empty()) {
bool found = false;
// Try to match the sdp_mid with content name.
for (size_t i = 0; i < description_->contents().size(); ++i) {
if (candidate->sdp_mid() == description_->contents().at(i).name) {
*index = i;
found = true;
break;
}
}
if (!found) {
// If the sdp_mid is presented but we can't find a match, we consider
// this as an error.
return false;
}
}
return true;
}
int JsepSessionDescription::GetMediasectionIndex(
const cricket::Candidate& candidate) {
// Find the description with a matching transport name of the candidate.
const std::string& transport_name = candidate.transport_name();
for (size_t i = 0; i < description_->contents().size(); ++i) {
if (transport_name == description_->contents().at(i).name) {
return static_cast<int>(i);
}
}
return -1;
}
} // namespace webrtc
<commit_msg>Fix the fuzz test.<commit_after>/*
* Copyright 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/api/jsepsessiondescription.h"
#include <memory>
#include "webrtc/base/arraysize.h"
#include "webrtc/base/stringencode.h"
#include "webrtc/pc/mediasession.h"
#include "webrtc/pc/webrtcsdp.h"
using cricket::SessionDescription;
namespace webrtc {
static const char* kSupportedTypes[] = {
JsepSessionDescription::kOffer,
JsepSessionDescription::kPrAnswer,
JsepSessionDescription::kAnswer
};
static bool IsTypeSupported(const std::string& type) {
bool type_supported = false;
for (size_t i = 0; i < arraysize(kSupportedTypes); ++i) {
if (kSupportedTypes[i] == type) {
type_supported = true;
break;
}
}
return type_supported;
}
// RFC 5245
// It is RECOMMENDED that default candidates be chosen based on the
// likelihood of those candidates to work with the peer that is being
// contacted. It is RECOMMENDED that relayed > reflexive > host.
static const int kPreferenceUnknown = 0;
static const int kPreferenceHost = 1;
static const int kPreferenceReflexive = 2;
static const int kPreferenceRelayed = 3;
static const char kDummyAddress[] = "0.0.0.0";
static const int kDummyPort = 9;
static int GetCandidatePreferenceFromType(const std::string& type) {
int preference = kPreferenceUnknown;
if (type == cricket::LOCAL_PORT_TYPE) {
preference = kPreferenceHost;
} else if (type == cricket::STUN_PORT_TYPE) {
preference = kPreferenceReflexive;
} else if (type == cricket::RELAY_PORT_TYPE) {
preference = kPreferenceRelayed;
} else {
preference = kPreferenceUnknown;
}
return preference;
}
// Update the connection address for the MediaContentDescription based on the
// candidates.
static void UpdateConnectionAddress(
const JsepCandidateCollection& candidate_collection,
cricket::ContentDescription* content_description) {
int port = kDummyPort;
std::string ip = kDummyAddress;
int current_preference = kPreferenceUnknown;
int current_family = AF_UNSPEC;
for (size_t i = 0; i < candidate_collection.count(); ++i) {
const IceCandidateInterface* jsep_candidate = candidate_collection.at(i);
if (jsep_candidate->candidate().component() !=
cricket::ICE_CANDIDATE_COMPONENT_RTP) {
continue;
}
// Default destination should be UDP only.
if (jsep_candidate->candidate().protocol() != cricket::UDP_PROTOCOL_NAME) {
continue;
}
const int preference =
GetCandidatePreferenceFromType(jsep_candidate->candidate().type());
const int family = jsep_candidate->candidate().address().ipaddr().family();
// See if this candidate is more preferable then the current one if it's the
// same family. Or if the current family is IPv4 already so we could safely
// ignore all IPv6 ones. WebRTC bug 4269.
// http://code.google.com/p/webrtc/issues/detail?id=4269
if ((preference <= current_preference && current_family == family) ||
(current_family == AF_INET && family == AF_INET6)) {
continue;
}
current_preference = preference;
current_family = family;
port = jsep_candidate->candidate().address().port();
ip = jsep_candidate->candidate().address().ipaddr().ToString();
}
rtc::SocketAddress connection_addr;
connection_addr.SetIP(ip);
connection_addr.SetPort(port);
static_cast<cricket::MediaContentDescription*>(content_description)
->set_connection_address(connection_addr);
}
const char SessionDescriptionInterface::kOffer[] = "offer";
const char SessionDescriptionInterface::kPrAnswer[] = "pranswer";
const char SessionDescriptionInterface::kAnswer[] = "answer";
const int JsepSessionDescription::kDefaultVideoCodecId = 100;
const char JsepSessionDescription::kDefaultVideoCodecName[] = "VP8";
SessionDescriptionInterface* CreateSessionDescription(const std::string& type,
const std::string& sdp,
SdpParseError* error) {
if (!IsTypeSupported(type)) {
return NULL;
}
JsepSessionDescription* jsep_desc = new JsepSessionDescription(type);
if (!jsep_desc->Initialize(sdp, error)) {
delete jsep_desc;
return NULL;
}
return jsep_desc;
}
JsepSessionDescription::JsepSessionDescription(const std::string& type)
: type_(type) {
}
JsepSessionDescription::~JsepSessionDescription() {}
bool JsepSessionDescription::Initialize(
cricket::SessionDescription* description,
const std::string& session_id,
const std::string& session_version) {
if (!description)
return false;
session_id_ = session_id;
session_version_ = session_version;
description_.reset(description);
candidate_collection_.resize(number_of_mediasections());
return true;
}
bool JsepSessionDescription::Initialize(const std::string& sdp,
SdpParseError* error) {
return SdpDeserialize(sdp, this, error);
}
bool JsepSessionDescription::AddCandidate(
const IceCandidateInterface* candidate) {
if (!candidate || candidate->sdp_mline_index() < 0)
return false;
size_t mediasection_index = 0;
if (!GetMediasectionIndex(candidate, &mediasection_index)) {
return false;
}
if (mediasection_index >= number_of_mediasections())
return false;
const std::string& content_name =
description_->contents()[mediasection_index].name;
const cricket::TransportInfo* transport_info =
description_->GetTransportInfoByName(content_name);
if (!transport_info) {
return false;
}
cricket::Candidate updated_candidate = candidate->candidate();
if (updated_candidate.username().empty()) {
updated_candidate.set_username(transport_info->description.ice_ufrag);
}
if (updated_candidate.password().empty()) {
updated_candidate.set_password(transport_info->description.ice_pwd);
}
std::unique_ptr<JsepIceCandidate> updated_candidate_wrapper(
new JsepIceCandidate(candidate->sdp_mid(),
static_cast<int>(mediasection_index),
updated_candidate));
if (!candidate_collection_[mediasection_index].HasCandidate(
updated_candidate_wrapper.get())) {
candidate_collection_[mediasection_index].add(
updated_candidate_wrapper.release());
UpdateConnectionAddress(
candidate_collection_[mediasection_index],
description_->contents()[mediasection_index].description);
}
return true;
}
size_t JsepSessionDescription::RemoveCandidates(
const std::vector<cricket::Candidate>& candidates) {
size_t num_removed = 0;
for (auto& candidate : candidates) {
int mediasection_index = GetMediasectionIndex(candidate);
if (mediasection_index < 0) {
// Not found.
continue;
}
num_removed += candidate_collection_[mediasection_index].remove(candidate);
UpdateConnectionAddress(
candidate_collection_[mediasection_index],
description_->contents()[mediasection_index].description);
}
return num_removed;
}
size_t JsepSessionDescription::number_of_mediasections() const {
if (!description_)
return 0;
return description_->contents().size();
}
const IceCandidateCollection* JsepSessionDescription::candidates(
size_t mediasection_index) const {
if (mediasection_index >= candidate_collection_.size())
return NULL;
return &candidate_collection_[mediasection_index];
}
bool JsepSessionDescription::ToString(std::string* out) const {
if (!description_ || !out) {
return false;
}
*out = SdpSerialize(*this, false);
return !out->empty();
}
bool JsepSessionDescription::GetMediasectionIndex(
const IceCandidateInterface* candidate,
size_t* index) {
if (!candidate || !index) {
return false;
}
*index = static_cast<size_t>(candidate->sdp_mline_index());
if (description_ && !candidate->sdp_mid().empty()) {
bool found = false;
// Try to match the sdp_mid with content name.
for (size_t i = 0; i < description_->contents().size(); ++i) {
if (candidate->sdp_mid() == description_->contents().at(i).name) {
*index = i;
found = true;
break;
}
}
if (!found) {
// If the sdp_mid is presented but we can't find a match, we consider
// this as an error.
return false;
}
}
return true;
}
int JsepSessionDescription::GetMediasectionIndex(
const cricket::Candidate& candidate) {
// Find the description with a matching transport name of the candidate.
const std::string& transport_name = candidate.transport_name();
for (size_t i = 0; i < description_->contents().size(); ++i) {
if (transport_name == description_->contents().at(i).name) {
return static_cast<int>(i);
}
}
return -1;
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>// ECE556 - Copyright 2014 University of Wisconsin-Madison. All Rights Reserved.
#include "ece556.h"
int main(int argc, char **argv)
{
signal(SIGSEGV, handler);
if(argc!=3){
printf("Usage : ./ROUTE.exe <input_benchmark_name> <output_file_name> \n");
return 1;
}
int status;
char *inputFileName = argv[1];
char *outputFileName = argv[2];
/// create a new routing instance
routingInst *rst = new routingInst;
/// read benchmark
printf("about to enter read Benchmark\n");
status = readBenchmark(inputFileName, rst);
for(int i = 0; i < rst->numEdges; i++)
cout << "edge weight of e" << i << " = " << rst->edgeCaps[i] << "\t";
cout << endl;
if(status==0){
printf("ERROR: reading input file \n");
return 1;
}
/// run actual routing
status = solveRouting(rst);
if(status==0){
printf("ERROR: running routing \n");
release(rst);
return 1;
}
/// write the result
status = writeOutput(outputFileName, rst);
if(status==0){
printf("ERROR: writing the result \n");
release(rst);
return 1;
}
release(rst);
printf("\nDONE!\n\n");
return 0;
}
<commit_msg>got rid of print statements in main<commit_after>// ECE556 - Copyright 2014 University of Wisconsin-Madison. All Rights Reserved.
#include "ece556.h"
int main(int argc, char **argv)
{
signal(SIGSEGV, handler);
if(argc!=3){
printf("Usage : ./ROUTE.exe <input_benchmark_name> <output_file_name> \n");
return 1;
}
int status;
char *inputFileName = argv[1];
char *outputFileName = argv[2];
/// create a new routing instance
routingInst *rst = new routingInst;
/// read benchmark
status = readBenchmark(inputFileName, rst);
if(status==0){
printf("ERROR: reading input file \n");
return 1;
}
/// run actual routing
status = solveRouting(rst);
if(status==0){
printf("ERROR: running routing \n");
release(rst);
return 1;
}
/// write the result
status = writeOutput(outputFileName, rst);
if(status==0){
printf("ERROR: writing the result \n");
release(rst);
return 1;
}
release(rst);
printf("\nDONE!\n\n");
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>linux: abort unless we have the proper version of NSS<commit_after><|endoftext|>
|
<commit_before><commit_msg>Fixing scoped_ptr misusage in base/win_util.cc BUG=24266<commit_after><|endoftext|>
|
<commit_before>//@author A0097630B
#include "stdafx.h"
#include "exceptions/parse_error_exception.h"
#include "query_parser.h"
namespace You {
namespace NLP {
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace phoenix = boost::phoenix;
QUERY QueryParser::parse(const StringType& string) {
QUERY result;
if (parse(string, result)) {
return result;
} else {
throw ParserException();
}
}
bool QueryParser::parse(const StringType& string, QUERY& result) {
return qi::parse(
begin(string),
end(string),
QueryParser(),
result);
}
QueryParser::QueryParser() : QueryParser::base_type(start) {
start %= (
(qi::lit(L'/') > explicitCommand) |
addCommand
) >> qi::eoi;
BOOST_SPIRIT_DEBUG_NODE(start);
explicitCommand %= (
(qi::lit(L"add") >> space >> addCommand) |
(qi::lit(L"show") >> space >> showCommand) |
(qi::lit(L"edit") >> space >> editCommand) |
(qi::lit(L"delete") >> space >> deleteCommand) |
(qi::lit(L"undo") >> undoCommand)
);
BOOST_SPIRIT_DEBUG_NODE(explicitCommand);
#pragma region Adding tasks
addCommand %= (
addCommandDescription
);
BOOST_SPIRIT_DEBUG_NODE(addCommand);
addCommandDescription = (
ParserCharTraits::char_ >> addCommandDescriptionTail
)[qi::_val = phoenix::bind(&constructAddQuery, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(addCommandDescription);
addCommandDescriptionTail %= (
addCommandPriority |
addCommandDescription
);
BOOST_SPIRIT_DEBUG_NODE(addCommandDescriptionTail);
addCommandPriority %= (
(-space >> qi::lit('!') >> addCommandDeadlineOptional)
[qi::_val = phoenix::bind(&constructAddQueryWithPriority, qi::_1)] |
addCommandDeadlineOptional
);
BOOST_SPIRIT_DEBUG_NODE(addCommandPriority);
addCommandDeadline = (
space >> (qi::lit("by") | qi::lit("before")) >>
utilityTime
)[qi::_val = phoenix::bind(&constructAddQueryWithDeadline, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(addCommandDeadline);
addCommandDeadlineOptional = (
addCommandDeadline || qi::eoi
)[qi::_val = phoenix::bind(&constructAddQueryWithOptionalDeadline, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(addCommandDeadlineOptional);
#pragma endregion
#pragma region Showing tasks
showCommand = (
-showCommandFiltering >>
-(-space >> (qi::lit(L"sorted by") | qi::lit(L"order by")) >> space >>
showCommandSorting)
)[qi::_val = phoenix::bind(&constructShowQuery, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(showCommand);
showCommandFiltering %=
showCommandFilteringColumn % (
(-space >> qi::lit(L",") >> -space) |
(space >> qi::lit(L"and") >> space));
BOOST_SPIRIT_DEBUG_NODE(showCommandFiltering);
showCommandFilteringColumn = (
showCommandFields >>
-space >> showCommandFilteringPredicate >> -space >>
utilityValue
)[qi::_val = phoenix::bind(&constructShowQueryFilteringColumn,
qi::_1,
qi::_2,
qi::_3)];
BOOST_SPIRIT_DEBUG_NODE(showCommandFiltering);
showCommandFilteringPredicate.add
(L"=", SHOW_QUERY::Predicate::EQ)
(L"!=", SHOW_QUERY::Predicate::NOT_EQ)
(L"<", SHOW_QUERY::Predicate::LESS_THAN)
(L"<=", SHOW_QUERY::Predicate::LESS_THAN_EQ)
(L">", SHOW_QUERY::Predicate::GREATER_THAN)
(L">=", SHOW_QUERY::Predicate::GREATER_THAN_EQ);
showCommandSorting %= (
showCommandSortingColumn % (
(-space >> qi::lit(L",") >> -space) |
(space >> qi::lit(L"then") >> space)));
BOOST_SPIRIT_DEBUG_NODE(showCommandSorting);
showCommandSortingColumn = (
showCommandFields >> -(space >> showCommandSortingOrders)
)[qi::_val = phoenix::bind(&constructShowQuerySortColumn, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(showCommandSortingColumn);
showCommandSortingOrders.add
(L"asc", SHOW_QUERY::Order::ASCENDING)
(L"ascending", SHOW_QUERY::Order::ASCENDING)
(L"desc", SHOW_QUERY::Order::DESCENDING)
(L"descending", SHOW_QUERY::Order::DESCENDING);
showCommandFields.add
(L"description", TaskField::DESCRIPTION)
(L"deadline", TaskField::DEADLINE)
(L"priority", TaskField::PRIORITY)
(L"done", TaskField::COMPLETE)
(L"complete", TaskField::COMPLETE);
#pragma endregion
#pragma region Editing tasks
editCommand = (
qi::uint_ >> space >> qi::lit(L"set") >> space >> editCommandRule
)[qi::_val = phoenix::bind(&constructEditQuery,
qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(editCommand);
editCommandRule %= (
editCommandRuleNullary |
editCommandRuleUnary |
editCommandRulePriorities
);
BOOST_SPIRIT_DEBUG_NODE(editCommandRule);
editCommandRuleNullary = (
editCommandFieldsNullary
)[qi::_val = phoenix::bind(&constructEditQueryNullary, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRuleNullary);
editCommandRuleUnary = (
editCommandFieldsUnary >>
-space >> qi::lit('=') >> -space >>
utilityValue)
[qi::_val = phoenix::bind(&constructEditQueryUnary, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRuleUnary);
editCommandRulePriorities = (
qi::lit(L"priority") >>
-space >> qi::lit('=') >> -space >>
utilityTaskPriority
)[qi::_val = phoenix::bind(&constructEditQueryPriority, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRulePriorities);
editCommandFieldsUnary.add
(L"description", TaskField::DESCRIPTION)
(L"deadline", TaskField::DEADLINE);
editCommandFieldsNullary.add
(L"done", TaskField::COMPLETE)
(L"complete", TaskField::COMPLETE);
#pragma endregion
#pragma region Deleting tasks
deleteCommand = (
qi::uint_
)[qi::_val = phoenix::bind(&constructDeleteQuery, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(deleteCommand);
#pragma endregion
#pragma region Undoing tasks
undoCommand = (
qi::eps
)[qi::_val = phoenix::construct<UNDO_QUERY>()];
BOOST_SPIRIT_DEBUG_NODE(undoCommand);
#pragma endregion
space = qi::omit[+ParserCharTraits::blank];
utilityValue = (
(qi::int_) |
(qi::bool_) |
utilityTaskPriority |
utilityLexeme
)[qi::_val = phoenix::bind(&constructValue, qi::_1)];
utilityTaskPriority.add
(L"normal", TaskPriority::NORMAL)
(L"high", TaskPriority::HIGH);
utilityTime = (
qi::as_wstring[+ParserCharTraits::char_]
)[qi::_val = phoenix::bind(&constructDateTime, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(utilityTime);
utilityLexeme %= qi::as_wstring[(
qi::lit('\'') > *utilityLexemeContents > qi::lit('\'')
)];
BOOST_SPIRIT_DEBUG_NODE(utilityLexeme);
utilityLexemeContents %= (
qi::lit("\\'")[qi::_val = L'\''] |
qi::lit("\\\\")[qi::_val = L'\\'] |
(ParserCharTraits::char_ - qi::lit('\''))
);
BOOST_SPIRIT_DEBUG_NODE(utilityLexemeContents);
qi::on_error<qi::fail>(start,
phoenix::bind(&onFailure, qi::_1, qi::_2, qi::_3, qi::_4));
}
void QueryParser::onFailure(
ParserIteratorType /*begin*/,
ParserIteratorType end,
ParserIteratorType errorPos,
const spirit::info& message) {
StringType lexeme(errorPos, end);
throw ParseErrorException(message, lexeme);
}
} // namespace NLP
} // namespace You
<commit_msg>Time is the date time parser itself.<commit_after>//@author A0097630B
#include "stdafx.h"
#include "exceptions/parse_error_exception.h"
#include "query_parser.h"
namespace You {
namespace NLP {
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace phoenix = boost::phoenix;
QUERY QueryParser::parse(const StringType& string) {
QUERY result;
if (parse(string, result)) {
return result;
} else {
throw ParserException();
}
}
bool QueryParser::parse(const StringType& string, QUERY& result) {
return qi::parse(
begin(string),
end(string),
QueryParser(),
result);
}
QueryParser::QueryParser() : QueryParser::base_type(start) {
start %= (
(qi::lit(L'/') > explicitCommand) |
addCommand
) >> qi::eoi;
BOOST_SPIRIT_DEBUG_NODE(start);
explicitCommand %= (
(qi::lit(L"add") >> space >> addCommand) |
(qi::lit(L"show") >> space >> showCommand) |
(qi::lit(L"edit") >> space >> editCommand) |
(qi::lit(L"delete") >> space >> deleteCommand) |
(qi::lit(L"undo") >> undoCommand)
);
BOOST_SPIRIT_DEBUG_NODE(explicitCommand);
#pragma region Adding tasks
addCommand %= (
addCommandDescription
);
BOOST_SPIRIT_DEBUG_NODE(addCommand);
addCommandDescription = (
ParserCharTraits::char_ >> addCommandDescriptionTail
)[qi::_val = phoenix::bind(&constructAddQuery, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(addCommandDescription);
addCommandDescriptionTail %= (
addCommandPriority |
addCommandDescription
);
BOOST_SPIRIT_DEBUG_NODE(addCommandDescriptionTail);
addCommandPriority %= (
(-space >> qi::lit('!') >> addCommandDeadlineOptional)
[qi::_val = phoenix::bind(&constructAddQueryWithPriority, qi::_1)] |
addCommandDeadlineOptional
);
BOOST_SPIRIT_DEBUG_NODE(addCommandPriority);
addCommandDeadline = (
space >> (qi::lit("by") | qi::lit("before")) >>
utilityTime
)[qi::_val = phoenix::bind(&constructAddQueryWithDeadline, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(addCommandDeadline);
addCommandDeadlineOptional = (
addCommandDeadline || qi::eoi
)[qi::_val = phoenix::bind(&constructAddQueryWithOptionalDeadline, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(addCommandDeadlineOptional);
#pragma endregion
#pragma region Showing tasks
showCommand = (
-showCommandFiltering >>
-(-space >> (qi::lit(L"sorted by") | qi::lit(L"order by")) >> space >>
showCommandSorting)
)[qi::_val = phoenix::bind(&constructShowQuery, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(showCommand);
showCommandFiltering %=
showCommandFilteringColumn % (
(-space >> qi::lit(L",") >> -space) |
(space >> qi::lit(L"and") >> space));
BOOST_SPIRIT_DEBUG_NODE(showCommandFiltering);
showCommandFilteringColumn = (
showCommandFields >>
-space >> showCommandFilteringPredicate >> -space >>
utilityValue
)[qi::_val = phoenix::bind(&constructShowQueryFilteringColumn,
qi::_1,
qi::_2,
qi::_3)];
BOOST_SPIRIT_DEBUG_NODE(showCommandFiltering);
showCommandFilteringPredicate.add
(L"=", SHOW_QUERY::Predicate::EQ)
(L"!=", SHOW_QUERY::Predicate::NOT_EQ)
(L"<", SHOW_QUERY::Predicate::LESS_THAN)
(L"<=", SHOW_QUERY::Predicate::LESS_THAN_EQ)
(L">", SHOW_QUERY::Predicate::GREATER_THAN)
(L">=", SHOW_QUERY::Predicate::GREATER_THAN_EQ);
showCommandSorting %= (
showCommandSortingColumn % (
(-space >> qi::lit(L",") >> -space) |
(space >> qi::lit(L"then") >> space)));
BOOST_SPIRIT_DEBUG_NODE(showCommandSorting);
showCommandSortingColumn = (
showCommandFields >> -(space >> showCommandSortingOrders)
)[qi::_val = phoenix::bind(&constructShowQuerySortColumn, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(showCommandSortingColumn);
showCommandSortingOrders.add
(L"asc", SHOW_QUERY::Order::ASCENDING)
(L"ascending", SHOW_QUERY::Order::ASCENDING)
(L"desc", SHOW_QUERY::Order::DESCENDING)
(L"descending", SHOW_QUERY::Order::DESCENDING);
showCommandFields.add
(L"description", TaskField::DESCRIPTION)
(L"deadline", TaskField::DEADLINE)
(L"priority", TaskField::PRIORITY)
(L"done", TaskField::COMPLETE)
(L"complete", TaskField::COMPLETE);
#pragma endregion
#pragma region Editing tasks
editCommand = (
qi::uint_ >> space >> qi::lit(L"set") >> space >> editCommandRule
)[qi::_val = phoenix::bind(&constructEditQuery,
qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(editCommand);
editCommandRule %= (
editCommandRuleNullary |
editCommandRuleUnary |
editCommandRulePriorities
);
BOOST_SPIRIT_DEBUG_NODE(editCommandRule);
editCommandRuleNullary = (
editCommandFieldsNullary
)[qi::_val = phoenix::bind(&constructEditQueryNullary, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRuleNullary);
editCommandRuleUnary = (
editCommandFieldsUnary >>
-space >> qi::lit('=') >> -space >>
utilityValue)
[qi::_val = phoenix::bind(&constructEditQueryUnary, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRuleUnary);
editCommandRulePriorities = (
qi::lit(L"priority") >>
-space >> qi::lit('=') >> -space >>
utilityTaskPriority
)[qi::_val = phoenix::bind(&constructEditQueryPriority, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRulePriorities);
editCommandFieldsUnary.add
(L"description", TaskField::DESCRIPTION)
(L"deadline", TaskField::DEADLINE);
editCommandFieldsNullary.add
(L"done", TaskField::COMPLETE)
(L"complete", TaskField::COMPLETE);
#pragma endregion
#pragma region Deleting tasks
deleteCommand = (
qi::uint_
)[qi::_val = phoenix::bind(&constructDeleteQuery, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(deleteCommand);
#pragma endregion
#pragma region Undoing tasks
undoCommand = (
qi::eps
)[qi::_val = phoenix::construct<UNDO_QUERY>()];
BOOST_SPIRIT_DEBUG_NODE(undoCommand);
#pragma endregion
space = qi::omit[+ParserCharTraits::blank];
utilityValue = (
(qi::int_) |
(qi::bool_) |
utilityTaskPriority |
utilityLexeme
)[qi::_val = phoenix::bind(&constructValue, qi::_1)];
utilityTaskPriority.add
(L"normal", TaskPriority::NORMAL)
(L"high", TaskPriority::HIGH);
utilityLexeme %= qi::as_wstring[(
qi::lit('\'') > *utilityLexemeContents > qi::lit('\'')
)];
BOOST_SPIRIT_DEBUG_NODE(utilityLexeme);
utilityLexemeContents %= (
qi::lit("\\'")[qi::_val = L'\''] |
qi::lit("\\\\")[qi::_val = L'\\'] |
(ParserCharTraits::char_ - qi::lit('\''))
);
BOOST_SPIRIT_DEBUG_NODE(utilityLexemeContents);
qi::on_error<qi::fail>(start,
phoenix::bind(&onFailure, qi::_1, qi::_2, qi::_3, qi::_4));
}
void QueryParser::onFailure(
ParserIteratorType /*begin*/,
ParserIteratorType end,
ParserIteratorType errorPos,
const spirit::info& message) {
StringType lexeme(errorPos, end);
throw ParseErrorException(message, lexeme);
}
} // namespace NLP
} // namespace You
<|endoftext|>
|
<commit_before>//@author A0097630B
#include "stdafx.h"
#include "exceptions/parse_error_exception.h"
#include "query_parser.h"
namespace You {
namespace NLP {
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace phoenix = boost::phoenix;
QUERY QueryParser::parse(const StringType& string) {
QUERY result;
if (parse(string, result)) {
return result;
} else {
throw ParserException();
}
}
bool QueryParser::parse(const StringType& string, QUERY& result) {
try {
return qi::parse(
begin(string),
end(string),
QueryParser() > qi::omit[*ParserCharTraits::blank] > qi::eoi,
result);
} catch (ParserExpectationFailure&) {
return false;
}
}
QueryParser::QueryParser() : QueryParser::base_type(start) {
start %= (
(qi::lit('/') > explicitCommand) |
addCommand
);
BOOST_SPIRIT_DEBUG_NODE(start);
explicitCommand %= (
(qi::lit("add") > space > addCommand) |
((qi::lit("show") | qi::lit("find")) > *space > showCommand) |
(qi::lit("edit") > space > editCommand) |
(qi::lit("delete") > space > deleteCommand) |
(qi::lit("undo") > *space > undoCommand)
);
BOOST_SPIRIT_DEBUG_NODE(explicitCommand);
#pragma region Adding tasks
addCommand = (
addCommandDescription >
-(*space >> qi::lit("->") > *space > addCommand) >
-(*space >> qi::lit(':') > *space > addCommandSubtasks)
)[qi::_val = phoenix::bind(
&constructAddQuery,
qi::_1,
qi::_2,
qi::_3)];
BOOST_SPIRIT_DEBUG_NODE(addCommand);
addCommandDescription %= (
addCommandDescriptionQuoted |
addCommandDescriptionUnquoted
);
BOOST_SPIRIT_DEBUG_NODE(addCommandDescription);
addCommandDescriptionQuoted = (
string > addCommandPriority
)[qi::_val = phoenix::bind(
static_cast<ADD_QUERY (*)(StringType, ADD_QUERY)>(
&constructAddQueryFromDescription),
qi::_1,
qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(addCommandDescriptionQuoted);
addCommandDescriptionUnquoted = (
ParserCharTraits::char_ > addCommandDescriptionUnquotedTail
)[qi::_val = phoenix::bind(
static_cast<ADD_QUERY(*)(ParserCharEncoding::char_type, ADD_QUERY)>(
&constructAddQueryFromDescription),
qi::_1,
qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(addCommandDescriptionUnquoted);
addCommandDescriptionUnquotedTail %= (
addCommandPriority |
addCommandDescriptionUnquoted
);
BOOST_SPIRIT_DEBUG_NODE(addCommandDescriptionUnquotedTail);
addCommandPriority %= (
(*space >> qi::lit('!') >> addCommandTimeOptional)
[qi::_val = phoenix::bind(&constructAddQueryWithPriority, qi::_1)] |
addCommandTimeOptional
);
BOOST_SPIRIT_DEBUG_NODE(addCommandPriority);
addCommandTime = (
#ifdef _DEBUG
((addCommandTimeFrom || addCommandTimeTo)
[qi::_val = phoenix::bind(&constructAddQueryWithTime, qi::_1, qi::_2)])
#else
((addCommandTimeFrom >> -addCommandTimeTo)
[qi::_val = phoenix::bind(&constructAddQueryWithTime,
qi::_1,
qi::_2)]) |
((addCommandTimeTo)
[qi::_val = phoenix::bind(&constructAddQueryWithTime,
boost::none,
qi::_1)])
#endif
>> *space
);
BOOST_SPIRIT_DEBUG_NODE(addCommandTime);
addCommandTimeFrom %= (
space >> (qi::lit("from") | qi::lit("after")) >> space >> time);
addCommandTimeTo %= (
(space >> (qi::lit("by") | qi::lit("before") | qi::lit("to")) >>
space >> time));
addCommandTimeOptional = (
addCommandTime || (
*space >> &(qi::char_(":;") | qi::lit("->") | qi::eoi))
)[qi::_val = phoenix::bind(&constructAddQueryWithOptionalTime, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(addCommandTimeOptional);
addCommandSubtasks %= (
addCommand % (*space >> qi::lit(';') >> *space)
);
BOOST_SPIRIT_DEBUG_NODE(addCommandSubtasks);
#pragma endregion
#pragma region Showing tasks
showCommand = (
-showCommandFiltering >
-(-space >> (qi::lit("sorted by") | qi::lit("order by")) > space >
showCommandSorting)
)[qi::_val = phoenix::bind(&constructShowQuery, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(showCommand);
showCommandFiltering %=
showCommandFilteringColumn % (
(-space >> qi::lit(',') >> -space) |
(space >> qi::lit("and") >> space));
BOOST_SPIRIT_DEBUG_NODE(showCommandFiltering);
showCommandFilteringColumn = (
showCommandFields >
-space > showCommandFilteringPredicate > -space >
value
)[qi::_val = phoenix::bind(&constructShowQueryFilteringColumn,
qi::_1,
qi::_2,
qi::_3)];
BOOST_SPIRIT_DEBUG_NODE(showCommandFiltering);
showCommandFilteringPredicate.add
(L"=", SHOW_QUERY::Predicate::EQ)
(L"~", SHOW_QUERY::Predicate::SIMILAR)
(L"!=", SHOW_QUERY::Predicate::NOT_EQ)
(L"<", SHOW_QUERY::Predicate::LESS_THAN)
(L"<=", SHOW_QUERY::Predicate::LESS_THAN_EQ)
(L">", SHOW_QUERY::Predicate::GREATER_THAN)
(L">=", SHOW_QUERY::Predicate::GREATER_THAN_EQ);
showCommandSorting %= (
showCommandSortingColumn % (
(-space >> qi::lit(",") >> -space) |
(space >> qi::lit("then") >> space)));
BOOST_SPIRIT_DEBUG_NODE(showCommandSorting);
showCommandSortingColumn = (
showCommandFields >> -(space >> showCommandSortingOrders)
)[qi::_val = phoenix::bind(&constructShowQuerySortColumn, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(showCommandSortingColumn);
showCommandSortingOrders.add
(L"asc", SHOW_QUERY::Order::ASCENDING)
(L"ascending", SHOW_QUERY::Order::ASCENDING)
(L"desc", SHOW_QUERY::Order::DESCENDING)
(L"descending", SHOW_QUERY::Order::DESCENDING);
showCommandFields.add
(L"description", TaskField::DESCRIPTION)
(L"start", TaskField::START)
(L"deadline", TaskField::DEADLINE)
(L"priority", TaskField::PRIORITY)
(L"done", TaskField::COMPLETE)
(L"complete", TaskField::COMPLETE)
(L"completed", TaskField::COMPLETE);
#pragma endregion
#pragma region Editing tasks
editCommand = (
qi::uint_ > (
(space >> qi::lit("set") > space > editCommandRule) |
(*space >> qi::lit("!") > editSetHighPriority) |
(editSetTimes) |
(*space >> qi::lit(":") > *space > editSetSubtask) |
(*space >> qi::lit("->") > *space > editSetDependent) |
(space >> qi::lit("attach") > space >
editAttachmentCommandRule(true)) |
(space >> qi::lit("detach") > space >
editAttachmentCommandRule(false)))
)[qi::_val = phoenix::bind(&constructEditQuery,
qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(editCommand);
editCommandRule %= (
editCommandRuleNullary |
editCommandRuleUnary |
editCommandRulePriorities
);
BOOST_SPIRIT_DEBUG_NODE(editCommandRule);
editCommandRuleNullary = (
editCommandFieldsNullary
)[qi::_val = phoenix::bind(&constructEditQueryNullary, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRuleNullary);
editCommandRuleUnary = (
editCommandFieldsUnary >
*space > qi::lit('=') > *space >
value)
[qi::_val = phoenix::bind(&constructEditQueryUnary, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRuleUnary);
editCommandRulePriorities = (
qi::lit("priority") >
*space > qi::lit('=') > *space >
taskPriority
)[qi::_val = phoenix::bind(&constructEditQueryPriority, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRulePriorities);
editCommandFieldsUnary.add
(L"description", TaskField::DESCRIPTION)
(L"start", TaskField::START)
(L"deadline", TaskField::DEADLINE);
editCommandFieldsNullary.add
(L"done", TaskField::COMPLETE)
(L"complete", TaskField::COMPLETE)
(L"completed", TaskField::COMPLETE);
editSetHighPriority = (
qi::eps
)[qi::_val = phoenix::bind(&constructEditQueryPriority,
TaskPriority::HIGH)];
BOOST_SPIRIT_DEBUG_NODE(editSetHighPriority);
editSetTimes = (
#ifdef _DEBUG
(editSetTimesFrom || editSetTimesTo)
[qi::_val = phoenix::bind(&constructEditQueryTimes,
qi::_1, qi::_2)]
#else
// Equivalent code for release builds. VC++ generates the wrong program
// with optimisations.
(editSetTimesFrom > -editSetTimesTo)
[qi::_val = phoenix::bind(&constructEditQueryTimes,
qi::_1, qi::_2)] |
(editSetTimesTo)
[qi::_val = phoenix::bind(&constructEditQueryTimes,
boost::none, qi::_1)]
#endif
);
BOOST_SPIRIT_DEBUG_NODE(editSetTimes);
editSetTimesFrom %= (space >>
(qi::lit("from") | qi::lit("after")) > space > time);
editSetTimesTo %= (space >>
(qi::lit("by") | qi::lit("before") | qi::lit("to")) > space >
time);
editSetSubtask = (
qi::int_
)[qi::_val = phoenix::bind(&constructEditQuerySubtask, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editSetSubtask);
editSetDependent = (
qi::int_
)[qi::_val = phoenix::bind(&constructEditQueryDependent, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editSetDependent);
editAttachmentCommandRule = (
string
)[qi::_val = phoenix::bind(&constructEditQueryAttachment, qi::_r1, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editAttachmentCommandRule);
#pragma endregion
#pragma region Deleting tasks
deleteCommand = (
qi::uint_
)[qi::_val = phoenix::bind(&constructDeleteQuery, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(deleteCommand);
#pragma endregion
#pragma region Undoing tasks
undoCommand = (
qi::eps
)[qi::_val = phoenix::construct<UNDO_QUERY>()];
BOOST_SPIRIT_DEBUG_NODE(undoCommand);
#pragma endregion
space = qi::omit[+ParserCharTraits::blank];
value = (
(qi::int_) |
(qi::bool_) |
taskPriority |
string
)[qi::_val = phoenix::bind(&constructValue, qi::_1)];
taskPriority.add
(L"normal", TaskPriority::NORMAL)
(L"high", TaskPriority::HIGH);
string %= qi::as_wstring[(
qi::lit('\'') > *stringContents > qi::lit('\'')
)];
BOOST_SPIRIT_DEBUG_NODE(string);
stringContents %= (
qi::lit("\\'")[qi::_val = '\''] |
qi::lit("\\\\")[qi::_val = '\\'] |
(ParserCharTraits::char_ - qi::lit('\''))
);
BOOST_SPIRIT_DEBUG_NODE(stringContents);
qi::on_error<qi::fail>(start,
phoenix::bind(&onFailure, qi::_1, qi::_2, qi::_3, qi::_4));
}
void QueryParser::onFailure(
ParserIteratorType /*begin*/,
ParserIteratorType end,
ParserIteratorType errorPos,
const spirit::info& message) {
StringType lexeme(errorPos, end);
throw ParseErrorException(message, lexeme);
}
} // namespace NLP
} // namespace You
<commit_msg>Add another comment for where the workaround is used.<commit_after>//@author A0097630B
#include "stdafx.h"
#include "exceptions/parse_error_exception.h"
#include "query_parser.h"
namespace You {
namespace NLP {
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace phoenix = boost::phoenix;
QUERY QueryParser::parse(const StringType& string) {
QUERY result;
if (parse(string, result)) {
return result;
} else {
throw ParserException();
}
}
bool QueryParser::parse(const StringType& string, QUERY& result) {
try {
return qi::parse(
begin(string),
end(string),
QueryParser() > qi::omit[*ParserCharTraits::blank] > qi::eoi,
result);
} catch (ParserExpectationFailure&) {
return false;
}
}
QueryParser::QueryParser() : QueryParser::base_type(start) {
start %= (
(qi::lit('/') > explicitCommand) |
addCommand
);
BOOST_SPIRIT_DEBUG_NODE(start);
explicitCommand %= (
(qi::lit("add") > space > addCommand) |
((qi::lit("show") | qi::lit("find")) > *space > showCommand) |
(qi::lit("edit") > space > editCommand) |
(qi::lit("delete") > space > deleteCommand) |
(qi::lit("undo") > *space > undoCommand)
);
BOOST_SPIRIT_DEBUG_NODE(explicitCommand);
#pragma region Adding tasks
addCommand = (
addCommandDescription >
-(*space >> qi::lit("->") > *space > addCommand) >
-(*space >> qi::lit(':') > *space > addCommandSubtasks)
)[qi::_val = phoenix::bind(
&constructAddQuery,
qi::_1,
qi::_2,
qi::_3)];
BOOST_SPIRIT_DEBUG_NODE(addCommand);
addCommandDescription %= (
addCommandDescriptionQuoted |
addCommandDescriptionUnquoted
);
BOOST_SPIRIT_DEBUG_NODE(addCommandDescription);
addCommandDescriptionQuoted = (
string > addCommandPriority
)[qi::_val = phoenix::bind(
static_cast<ADD_QUERY (*)(StringType, ADD_QUERY)>(
&constructAddQueryFromDescription),
qi::_1,
qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(addCommandDescriptionQuoted);
addCommandDescriptionUnquoted = (
ParserCharTraits::char_ > addCommandDescriptionUnquotedTail
)[qi::_val = phoenix::bind(
static_cast<ADD_QUERY(*)(ParserCharEncoding::char_type, ADD_QUERY)>(
&constructAddQueryFromDescription),
qi::_1,
qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(addCommandDescriptionUnquoted);
addCommandDescriptionUnquotedTail %= (
addCommandPriority |
addCommandDescriptionUnquoted
);
BOOST_SPIRIT_DEBUG_NODE(addCommandDescriptionUnquotedTail);
addCommandPriority %= (
(*space >> qi::lit('!') >> addCommandTimeOptional)
[qi::_val = phoenix::bind(&constructAddQueryWithPriority, qi::_1)] |
addCommandTimeOptional
);
BOOST_SPIRIT_DEBUG_NODE(addCommandPriority);
addCommandTime = (
#ifdef _DEBUG
((addCommandTimeFrom || addCommandTimeTo)
[qi::_val = phoenix::bind(&constructAddQueryWithTime, qi::_1, qi::_2)])
#else
// Equivalent code for release builds. VC++ generates the wrong program
// with optimisations.
((addCommandTimeFrom >> -addCommandTimeTo)
[qi::_val = phoenix::bind(&constructAddQueryWithTime,
qi::_1,
qi::_2)]) |
((addCommandTimeTo)
[qi::_val = phoenix::bind(&constructAddQueryWithTime,
boost::none,
qi::_1)])
#endif
>> *space
);
BOOST_SPIRIT_DEBUG_NODE(addCommandTime);
addCommandTimeFrom %= (
space >> (qi::lit("from") | qi::lit("after")) >> space >> time);
addCommandTimeTo %= (
(space >> (qi::lit("by") | qi::lit("before") | qi::lit("to")) >>
space >> time));
addCommandTimeOptional = (
addCommandTime || (
*space >> &(qi::char_(":;") | qi::lit("->") | qi::eoi))
)[qi::_val = phoenix::bind(&constructAddQueryWithOptionalTime, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(addCommandTimeOptional);
addCommandSubtasks %= (
addCommand % (*space >> qi::lit(';') >> *space)
);
BOOST_SPIRIT_DEBUG_NODE(addCommandSubtasks);
#pragma endregion
#pragma region Showing tasks
showCommand = (
-showCommandFiltering >
-(-space >> (qi::lit("sorted by") | qi::lit("order by")) > space >
showCommandSorting)
)[qi::_val = phoenix::bind(&constructShowQuery, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(showCommand);
showCommandFiltering %=
showCommandFilteringColumn % (
(-space >> qi::lit(',') >> -space) |
(space >> qi::lit("and") >> space));
BOOST_SPIRIT_DEBUG_NODE(showCommandFiltering);
showCommandFilteringColumn = (
showCommandFields >
-space > showCommandFilteringPredicate > -space >
value
)[qi::_val = phoenix::bind(&constructShowQueryFilteringColumn,
qi::_1,
qi::_2,
qi::_3)];
BOOST_SPIRIT_DEBUG_NODE(showCommandFiltering);
showCommandFilteringPredicate.add
(L"=", SHOW_QUERY::Predicate::EQ)
(L"~", SHOW_QUERY::Predicate::SIMILAR)
(L"!=", SHOW_QUERY::Predicate::NOT_EQ)
(L"<", SHOW_QUERY::Predicate::LESS_THAN)
(L"<=", SHOW_QUERY::Predicate::LESS_THAN_EQ)
(L">", SHOW_QUERY::Predicate::GREATER_THAN)
(L">=", SHOW_QUERY::Predicate::GREATER_THAN_EQ);
showCommandSorting %= (
showCommandSortingColumn % (
(-space >> qi::lit(",") >> -space) |
(space >> qi::lit("then") >> space)));
BOOST_SPIRIT_DEBUG_NODE(showCommandSorting);
showCommandSortingColumn = (
showCommandFields >> -(space >> showCommandSortingOrders)
)[qi::_val = phoenix::bind(&constructShowQuerySortColumn, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(showCommandSortingColumn);
showCommandSortingOrders.add
(L"asc", SHOW_QUERY::Order::ASCENDING)
(L"ascending", SHOW_QUERY::Order::ASCENDING)
(L"desc", SHOW_QUERY::Order::DESCENDING)
(L"descending", SHOW_QUERY::Order::DESCENDING);
showCommandFields.add
(L"description", TaskField::DESCRIPTION)
(L"start", TaskField::START)
(L"deadline", TaskField::DEADLINE)
(L"priority", TaskField::PRIORITY)
(L"done", TaskField::COMPLETE)
(L"complete", TaskField::COMPLETE)
(L"completed", TaskField::COMPLETE);
#pragma endregion
#pragma region Editing tasks
editCommand = (
qi::uint_ > (
(space >> qi::lit("set") > space > editCommandRule) |
(*space >> qi::lit("!") > editSetHighPriority) |
(editSetTimes) |
(*space >> qi::lit(":") > *space > editSetSubtask) |
(*space >> qi::lit("->") > *space > editSetDependent) |
(space >> qi::lit("attach") > space >
editAttachmentCommandRule(true)) |
(space >> qi::lit("detach") > space >
editAttachmentCommandRule(false)))
)[qi::_val = phoenix::bind(&constructEditQuery,
qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(editCommand);
editCommandRule %= (
editCommandRuleNullary |
editCommandRuleUnary |
editCommandRulePriorities
);
BOOST_SPIRIT_DEBUG_NODE(editCommandRule);
editCommandRuleNullary = (
editCommandFieldsNullary
)[qi::_val = phoenix::bind(&constructEditQueryNullary, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRuleNullary);
editCommandRuleUnary = (
editCommandFieldsUnary >
*space > qi::lit('=') > *space >
value)
[qi::_val = phoenix::bind(&constructEditQueryUnary, qi::_1, qi::_2)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRuleUnary);
editCommandRulePriorities = (
qi::lit("priority") >
*space > qi::lit('=') > *space >
taskPriority
)[qi::_val = phoenix::bind(&constructEditQueryPriority, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editCommandRulePriorities);
editCommandFieldsUnary.add
(L"description", TaskField::DESCRIPTION)
(L"start", TaskField::START)
(L"deadline", TaskField::DEADLINE);
editCommandFieldsNullary.add
(L"done", TaskField::COMPLETE)
(L"complete", TaskField::COMPLETE)
(L"completed", TaskField::COMPLETE);
editSetHighPriority = (
qi::eps
)[qi::_val = phoenix::bind(&constructEditQueryPriority,
TaskPriority::HIGH)];
BOOST_SPIRIT_DEBUG_NODE(editSetHighPriority);
editSetTimes = (
#ifdef _DEBUG
(editSetTimesFrom || editSetTimesTo)
[qi::_val = phoenix::bind(&constructEditQueryTimes,
qi::_1, qi::_2)]
#else
// Equivalent code for release builds. VC++ generates the wrong program
// with optimisations.
(editSetTimesFrom > -editSetTimesTo)
[qi::_val = phoenix::bind(&constructEditQueryTimes,
qi::_1, qi::_2)] |
(editSetTimesTo)
[qi::_val = phoenix::bind(&constructEditQueryTimes,
boost::none, qi::_1)]
#endif
);
BOOST_SPIRIT_DEBUG_NODE(editSetTimes);
editSetTimesFrom %= (space >>
(qi::lit("from") | qi::lit("after")) > space > time);
editSetTimesTo %= (space >>
(qi::lit("by") | qi::lit("before") | qi::lit("to")) > space >
time);
editSetSubtask = (
qi::int_
)[qi::_val = phoenix::bind(&constructEditQuerySubtask, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editSetSubtask);
editSetDependent = (
qi::int_
)[qi::_val = phoenix::bind(&constructEditQueryDependent, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editSetDependent);
editAttachmentCommandRule = (
string
)[qi::_val = phoenix::bind(&constructEditQueryAttachment, qi::_r1, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(editAttachmentCommandRule);
#pragma endregion
#pragma region Deleting tasks
deleteCommand = (
qi::uint_
)[qi::_val = phoenix::bind(&constructDeleteQuery, qi::_1)];
BOOST_SPIRIT_DEBUG_NODE(deleteCommand);
#pragma endregion
#pragma region Undoing tasks
undoCommand = (
qi::eps
)[qi::_val = phoenix::construct<UNDO_QUERY>()];
BOOST_SPIRIT_DEBUG_NODE(undoCommand);
#pragma endregion
space = qi::omit[+ParserCharTraits::blank];
value = (
(qi::int_) |
(qi::bool_) |
taskPriority |
string
)[qi::_val = phoenix::bind(&constructValue, qi::_1)];
taskPriority.add
(L"normal", TaskPriority::NORMAL)
(L"high", TaskPriority::HIGH);
string %= qi::as_wstring[(
qi::lit('\'') > *stringContents > qi::lit('\'')
)];
BOOST_SPIRIT_DEBUG_NODE(string);
stringContents %= (
qi::lit("\\'")[qi::_val = '\''] |
qi::lit("\\\\")[qi::_val = '\\'] |
(ParserCharTraits::char_ - qi::lit('\''))
);
BOOST_SPIRIT_DEBUG_NODE(stringContents);
qi::on_error<qi::fail>(start,
phoenix::bind(&onFailure, qi::_1, qi::_2, qi::_3, qi::_4));
}
void QueryParser::onFailure(
ParserIteratorType /*begin*/,
ParserIteratorType end,
ParserIteratorType errorPos,
const spirit::info& message) {
StringType lexeme(errorPos, end);
throw ParseErrorException(message, lexeme);
}
} // namespace NLP
} // namespace You
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_bulk_pwr_throttles.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_bulk_pwr_throttles.H
/// @brief Set the throttle attributes based on a power limit for the dimms on the channel pair
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#ifndef __P9_MSS_BULK_PWR_THROTTLES__
#define __P9_MSS_BULK_PWR_THROTTLES__
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_mss_bulk_pwr_throttles_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&);
extern "C"
{
///
/// @brief Set the throttle attributes based on a power limit for the dimms on the channel pair
/// @param[in] i_target controller target
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_bulk_pwr_throttles( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target );
}
#endif
<commit_msg>Modifying ATTRs for memory power thermal<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_bulk_pwr_throttles.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_bulk_pwr_throttles.H
/// @brief Set the throttle attributes based on a power limit for the dimms on the channel pair
///
// *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#ifndef __P9_MSS_BULK_PWR_THROTTLES__
#define __P9_MSS_BULK_PWR_THROTTLES__
#include <fapi2.H>
#include <vector>
typedef fapi2::ReturnCode (*p9_mss_bulk_pwr_throttles_FP_t) (const
std::vector< fapi2::Target< fapi2::TARGET_TYPE_MCS>>&);
extern "C"
{
enum throttle_type : size_t
{
POWER = 0,
THERMAL = 1,
};
///
/// @brief Set ATTR_MSS_PORT_MAXPOWER, ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT, ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_PORT
/// @param[in] i_targets vector of MCS's on the same VDDR domain
/// @param[in] thermal boolean to determine whether to calculate throttles based on the power regulator or thermal limits
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
/// @note Called in p9_mss_bulk_pwr_throttles
/// @note determines the throttle levels based off of the port's power curve,
/// sets the slot throttles to the same
/// @note Enums are POWER for power egulator throttles and THERMAL for thermal throttles
/// @note equalizes the throttles to the lowest of runtime and the lowest slot-throttle value
///
fapi2::ReturnCode p9_mss_bulk_pwr_throttles (const std::vector < fapi2::Target< fapi2::TARGET_TYPE_MCS>>& i_targets,
throttle_type t );
}
#endif
<|endoftext|>
|
<commit_before>#include "np-divs/np_divs.hpp"
#include "np-divs/matrix_io.hpp"
#include "np-divs/div-funcs/div_func.hpp"
#include "np-divs/div_func_from_str.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <boost/program_options.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <flann/util/matrix.h>
using namespace NPDivs;
using namespace std;
using namespace boost;
namespace po = boost::program_options;
typedef struct s_popts {
string x_bags_file;
string y_bags_file;
string results_file;
ptr_vector<DivFunc> div_funcs;
size_t k;
size_t num_threads;
flann::IndexParams index_params;
flann::SearchParams search_params;
} ProgOpts;
bool parse_args(int argc, const char ** argv, ProgOpts& opts);
int main(int argc, const char ** argv) {
typedef flann::Matrix<double> Matrix;
ProgOpts opts;
opts.index_params = flann::KDTreeSingleIndexParams();
opts.search_params = flann::SearchParams(64);
if (!parse_args(argc, argv, opts))
return 1;
size_t num_df = opts.div_funcs.size();
// load input bags
// TODO - gracefully handle nonexisting files
size_t num_x;
Matrix* x_bags;
if (opts.x_bags_file == "-") {
x_bags = matrices_from_csv(cin, num_x);
} else {
ifstream ifs(opts.x_bags_file.c_str(), ifstream::in);
x_bags = matrices_from_csv(ifs, num_x);
}
size_t num_y;
Matrix* y_bags;
if (opts.y_bags_file.empty()) {
y_bags = NULL;
num_y = num_x;
} else if (opts.y_bags_file == "-") {
y_bags = matrices_from_csv(cin, num_y);
} else {
ifstream ifs(opts.y_bags_file.c_str(), ifstream::in);
y_bags = matrices_from_csv(ifs, num_y);
}
Matrix* results = alloc_matrix_array<double>(num_df, num_x, num_y);
try {
np_divs(x_bags, num_x, y_bags, num_y, opts.div_funcs, results, opts.k,
opts.index_params, opts.search_params, opts.num_threads);
} catch (std::exception e) {
cerr << "Error: " << e.what() << endl;
exit(1);
}
if (opts.results_file == "-") {
matrix_array_to_csv(cout, results, num_df);
} else {
ofstream ofs(opts.results_file.c_str());
matrix_array_to_csv(ofs, results, num_df);
}
free_matrix_array(results, num_df);
return 0;
}
void parse_div_funcs(ProgOpts &opts, const vector<string> &names) {
for (size_t i = 0; i < names.size(); i++) {
opts.div_funcs.push_back(div_func_from_str(names[i]));
}
}
// TODO nicer handling of matrix inputs
// TODO optionally support HDF5 inputs
// TODO positional arguments for x_bags, y_bags
// TODO support setting {index,search}_params
bool parse_args(int argc, const char ** argv, ProgOpts& opts) {
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce this help message.")
("x-bags,x",
po::value<string>(&opts.x_bags_file)->default_value("-"),
"CSV-style file containing matrices separated by blank lines; "
"- means stdin.")
("y-bags,y",
po::value<string>(&opts.y_bags_file),
"CSV-style file containing matrices separated by blank lines. "
"If passed, divergences are calculated between the x bags (rows "
"in the output matrix) and the y bags (columns); if not passed, "
"divergences are calculated from the x bags to themselves. Pass "
"- to use stdin; if both x and y are from stdin, x is read first "
"and the two groups must be separated by exactly two blank lines. ")
("results,r",
po::value<string>(&opts.results_file)->default_value("-"),
"Where to write CSV-style matrix of results, where m[i,j] = "
"div(x_i, y_j). Use - for stdout.")
("div-func,f",
po::value< vector<string> >()->composing()->required()
->notifier(boost::bind(&parse_div_funcs, boost::ref(opts), _1)),
"Divergence functions to use; can be specified more than once. At "
"least one is required. Format is name:arg1:arg2:..., where argN "
"refers to the Nth argument to the corresponding DivFunc's "
"constructor. Some support a first argument specifying a "
"parameter: renyi:.99 means the Renyi-.99 divergence. All support "
"a last parameter, which determines the way that large values are "
"normalized: l2:.95 or renyi:.99:.95 means certain calculated "
"intermediate values above the 95th percentile are cut down; 1 "
"means not to do this; default is .99. All extra arguments are "
"optional.")
("num-threads",
po::value<size_t>(&opts.num_threads)->default_value(0),
"Number of threads to use for calculations. 0 means one per core.")
("k",
po::value<size_t>(&opts.k)->default_value(3),
"The k for k-nearest-neighbor calculations.")
;
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
if (vm.count("help")) {
std::cout << desc << "\n";
exit(0);
}
po::notify(vm);
} catch (std::exception &e) {
cerr << "Error: " << e.what() << endl;
return false;
}
return true;
}
<commit_msg>CLI: simple options to choose index type<commit_after>#include "np-divs/np_divs.hpp"
#include "np-divs/matrix_io.hpp"
#include "np-divs/div-funcs/div_func.hpp"
#include "np-divs/div_func_from_str.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <boost/program_options.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/utility.hpp>
#include <flann/util/matrix.h>
using namespace NPDivs;
using namespace std;
using namespace boost;
namespace po = boost::program_options;
typedef struct s_popts : noncopyable {
string x_bags_file;
string y_bags_file;
string results_file;
ptr_vector<DivFunc> div_funcs;
size_t k;
size_t num_threads;
flann::IndexParams index_params;
flann::SearchParams search_params;
void parse_div_funcs(const vector<string> &names) {
for (size_t i = 0; i < names.size(); i++) {
div_funcs.push_back(div_func_from_str(names[i]));
}
}
void parse_index(const string name) {
// TODO: more index types, support arguments
if (name == "linear" || name == "brute") {
index_params = flann::LinearIndexParams();
} else if (name == "kdtree" || name == "kd") {
index_params = flann::KDTreeSingleIndexParams();
} else {
throw domain_error((format("unknown index type %s") % name).str());
}
}
} ProgOpts;
bool parse_args(int argc, const char ** argv, ProgOpts& opts);
int main(int argc, const char ** argv) {
typedef flann::Matrix<double> Matrix;
ProgOpts opts;
opts.search_params = flann::SearchParams(64);
if (!parse_args(argc, argv, opts))
return 1;
size_t num_df = opts.div_funcs.size();
// load input bags
// TODO - gracefully handle nonexisting files
size_t num_x;
Matrix* x_bags;
if (opts.x_bags_file == "-") {
x_bags = matrices_from_csv(cin, num_x);
} else {
ifstream ifs(opts.x_bags_file.c_str(), ifstream::in);
x_bags = matrices_from_csv(ifs, num_x);
}
size_t num_y;
Matrix* y_bags;
if (opts.y_bags_file.empty()) {
y_bags = NULL;
num_y = num_x;
} else if (opts.y_bags_file == "-") {
y_bags = matrices_from_csv(cin, num_y);
} else {
ifstream ifs(opts.y_bags_file.c_str(), ifstream::in);
y_bags = matrices_from_csv(ifs, num_y);
}
Matrix* results = alloc_matrix_array<double>(num_df, num_x, num_y);
try {
np_divs(x_bags, num_x, y_bags, num_y, opts.div_funcs, results, opts.k,
opts.index_params, opts.search_params, opts.num_threads);
} catch (std::exception e) {
cerr << "Error: " << e.what() << endl;
exit(1);
}
if (opts.results_file == "-") {
matrix_array_to_csv(cout, results, num_df);
} else {
ofstream ofs(opts.results_file.c_str());
matrix_array_to_csv(ofs, results, num_df);
}
free_matrix_array(results, num_df);
return 0;
}
// TODO nicer handling of matrix inputs
// TODO optionally support HDF5 inputs
// TODO positional arguments for x_bags, y_bags
// TODO support setting {index,search}_params
bool parse_args(int argc, const char ** argv, ProgOpts& opts) {
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce this help message.")
("x-bags,x",
po::value<string>(&opts.x_bags_file)->default_value("-"),
"CSV-style file containing matrices separated by blank lines; "
"- means stdin.")
("y-bags,y",
po::value<string>(&opts.y_bags_file),
"CSV-style file containing matrices separated by blank lines. "
"If passed, divergences are calculated between the x bags (rows "
"in the output matrix) and the y bags (columns); if not passed, "
"divergences are calculated from the x bags to themselves. Pass "
"- to use stdin; if both x and y are from stdin, x is read first "
"and the two groups must be separated by exactly two blank lines. ")
("results,r",
po::value<string>(&opts.results_file)->default_value("-"),
"Where to write CSV-style matrix of results, where m[i,j] = "
"div(x_i, y_j). Use - for stdout.")
("div-func,f",
po::value< vector<string> >()->composing()->required()
->notifier(bind(&ProgOpts::parse_div_funcs, ref(opts), _1)),
"Divergence functions to use; can be specified more than once. At "
"least one is required. Format is name:arg1:arg2:..., where argN "
"refers to the Nth argument to the corresponding DivFunc's "
"constructor. Some support a first argument specifying a "
"parameter: renyi:.99 means the Renyi-.99 divergence. All support "
"a last parameter, which determines the way that large values are "
"normalized: l2:.95 or renyi:.99:.95 means certain calculated "
"intermediate values above the 95th percentile are cut down; 1 "
"means not to do this; default is .99. All extra arguments are "
"optional.")
("num-threads",
po::value<size_t>(&opts.num_threads)->default_value(0),
"Number of threads to use for calculations. 0 means one per core.")
("k",
po::value<size_t>(&opts.k)->default_value(3),
"The k for k-nearest-neighbor calculations.")
("index,i",
po::value<string>()->default_value("kdtree")
->notifier(bind(&ProgOpts::parse_index, ref(opts), _1)),
"The nearest-neighbor index to use. Options: linear, kdtree.")
;
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
if (vm.count("help")) {
std::cout << desc << "\n";
exit(0);
}
po::notify(vm);
} catch (std::exception &e) {
cerr << "Error: " << e.what() << endl;
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 Oleg Morozenkov
*
* 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 "tgbot/Api.h"
#include "tgbot/TgTypeParser.h"
#include "tgbot/TgException.h"
#include "tgbot/net/HttpClient.h"
using namespace std;
using namespace boost::property_tree;
namespace TgBot {
Api::Api(const string& token) : _token(token) {
}
User::Ptr Api::getMe() const {
return TgTypeParser::getInstance().parseJsonAndGetUser(sendRequest("getMe"));
}
Message::Ptr Api::sendMessage(int32_t chatId, const string& text, bool disableWebPagePreview, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("text", text));
if (disableWebPagePreview) {
args.push_back(HttpReqArg("disable_web_page_preview", disableWebPagePreview));
}
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendMessage", args));
}
Message::Ptr Api::forwardMessage(int32_t chatId, int32_t fromChatId, int32_t messageId) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("from_chat_id", fromChatId));
args.push_back(HttpReqArg("message_id", messageId));
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("forwardMessage", args));
}
Message::Ptr Api::sendPhoto(int32_t chatId, const InputFile::Ptr& photo, const string& caption, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("photo", photo->data, true, photo->mimeType));
if (!caption.empty()) {
args.push_back(HttpReqArg("caption", caption));
}
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendPhoto", args));
}
Message::Ptr Api::sendPhoto(int32_t chatId, const string& photo, const string& caption, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("photo", photo));
if (!caption.empty()) {
args.push_back(HttpReqArg("caption", caption));
}
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendPhoto", args));
}
Message::Ptr Api::sendAudio(int32_t chatId, const InputFile::Ptr& audio, int32_t duration, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("audio", audio->data, true, audio->mimeType));
if (duration) {
args.push_back(HttpReqArg("duration", duration));
}
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendAudio", args));
}
Message::Ptr Api::sendAudio(int32_t chatId, const string& audio, int32_t duration, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("audio", audio));
if (duration) {
args.push_back(HttpReqArg("duration", duration));
}
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendAudio", args));
}
Message::Ptr Api::sendDocument(int32_t chatId, const InputFile::Ptr& document, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("document", document->data, true, document->mimeType));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendDocument", args));
}
Message::Ptr Api::sendDocument(int32_t chatId, const string& document, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("document", document));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendDocument", args));
}
Message::Ptr Api::sendSticker(int32_t chatId, const InputFile::Ptr& sticker, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("sticker", sticker->data, true, sticker->mimeType));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendSticker", args));
}
Message::Ptr Api::sendSticker(int32_t chatId, const string& sticker, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("sticker", sticker));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendSticker", args));
}
Message::Ptr Api::sendVideo(int32_t chatId, const InputFile::Ptr& video, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("video", video->data, true, video->mimeType));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendVideo", args));
}
Message::Ptr Api::sendVideo(int32_t chatId, const string& video, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("video", video));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendVideo", args));
}
Message::Ptr Api::sendLocation(int32_t chatId, float latitude, float longitude, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("latitude", latitude));
args.push_back(HttpReqArg("longitude", longitude));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendLocation", args));
}
void Api::sendChatAction(int32_t chatId, const string& action) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("action", action));
sendRequest("sendChatAction", args);
}
UserProfilePhotos::Ptr Api::getUserProfilePhotos(int32_t userId, int32_t offset, int32_t limit) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("user_id", userId));
if (offset) {
args.push_back(HttpReqArg("offset", offset));
}
limit = max(1, min(100, limit));
args.push_back(HttpReqArg("limit", limit));
return TgTypeParser::getInstance().parseJsonAndGetUserProfilePhotos(sendRequest("getUserProfilePhotos", args));
}
vector<Update::Ptr> Api::getUpdates(int32_t offset, int32_t limit, int32_t timeout) const {
vector<HttpReqArg> args;
if (offset) {
args.push_back(HttpReqArg("offset", offset));
}
limit = max(1, min(100, limit));
args.push_back(HttpReqArg("limit", limit));
if (timeout) {
args.push_back(HttpReqArg("timeout", timeout));
}
return TgTypeParser::getInstance().parseJsonAndGetArray<Update>(&TgTypeParser::parseJsonAndGetUpdate, sendRequest("getUpdates", args), "result");
}
void Api::setWebhook(const string& url) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("url", url));
sendRequest("setWebhook", args);
}
ptree Api::sendRequest(const string& method, const vector<HttpReqArg>& args) const {
string url = "https://api.telegram.org/bot";
url += _token;
url += "/";
url += method;
string serverResponse = HttpClient::getInstance().makeRequest(url, args);
if (serverResponse.find("<html>") != serverResponse.npos) {
throw TgException("Bad request");
}
ptree result = TgTypeParser::getInstance().parseJson(serverResponse);
try {
if (result.get<bool>("ok")) {
return result.find("result")->second;
} else {
throw TgException(result.get("description", ""));
}
} catch (boost::property_tree::ptree_error& e) {
throw TgException("");
}
}
}
<commit_msg>Bug fix: now bot can parse messages correctly<commit_after>/*
* Copyright (c) 2015 Oleg Morozenkov
*
* 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 "tgbot/Api.h"
#include "tgbot/TgTypeParser.h"
#include "tgbot/TgException.h"
#include "tgbot/net/HttpClient.h"
using namespace std;
using namespace boost::property_tree;
namespace TgBot {
Api::Api(const string& token) : _token(token) {
}
User::Ptr Api::getMe() const {
return TgTypeParser::getInstance().parseJsonAndGetUser(sendRequest("getMe"));
}
Message::Ptr Api::sendMessage(int32_t chatId, const string& text, bool disableWebPagePreview, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("text", text));
if (disableWebPagePreview) {
args.push_back(HttpReqArg("disable_web_page_preview", disableWebPagePreview));
}
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendMessage", args));
}
Message::Ptr Api::forwardMessage(int32_t chatId, int32_t fromChatId, int32_t messageId) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("from_chat_id", fromChatId));
args.push_back(HttpReqArg("message_id", messageId));
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("forwardMessage", args));
}
Message::Ptr Api::sendPhoto(int32_t chatId, const InputFile::Ptr& photo, const string& caption, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("photo", photo->data, true, photo->mimeType));
if (!caption.empty()) {
args.push_back(HttpReqArg("caption", caption));
}
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendPhoto", args));
}
Message::Ptr Api::sendPhoto(int32_t chatId, const string& photo, const string& caption, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("photo", photo));
if (!caption.empty()) {
args.push_back(HttpReqArg("caption", caption));
}
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendPhoto", args));
}
Message::Ptr Api::sendAudio(int32_t chatId, const InputFile::Ptr& audio, int32_t duration, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("audio", audio->data, true, audio->mimeType));
if (duration) {
args.push_back(HttpReqArg("duration", duration));
}
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendAudio", args));
}
Message::Ptr Api::sendAudio(int32_t chatId, const string& audio, int32_t duration, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("audio", audio));
if (duration) {
args.push_back(HttpReqArg("duration", duration));
}
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendAudio", args));
}
Message::Ptr Api::sendDocument(int32_t chatId, const InputFile::Ptr& document, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("document", document->data, true, document->mimeType));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendDocument", args));
}
Message::Ptr Api::sendDocument(int32_t chatId, const string& document, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("document", document));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendDocument", args));
}
Message::Ptr Api::sendSticker(int32_t chatId, const InputFile::Ptr& sticker, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("sticker", sticker->data, true, sticker->mimeType));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendSticker", args));
}
Message::Ptr Api::sendSticker(int32_t chatId, const string& sticker, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("sticker", sticker));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendSticker", args));
}
Message::Ptr Api::sendVideo(int32_t chatId, const InputFile::Ptr& video, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("video", video->data, true, video->mimeType));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendVideo", args));
}
Message::Ptr Api::sendVideo(int32_t chatId, const string& video, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("video", video));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendVideo", args));
}
Message::Ptr Api::sendLocation(int32_t chatId, float latitude, float longitude, int32_t replyToMessageId, const GenericReply::Ptr& replyMarkup) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("latitude", latitude));
args.push_back(HttpReqArg("longitude", longitude));
if (replyToMessageId) {
args.push_back(HttpReqArg("reply_to_message_id", replyToMessageId));
}
if (replyMarkup) {
args.push_back(HttpReqArg("reply_markup", TgTypeParser::getInstance().parseGenericReply(replyMarkup)));
}
return TgTypeParser::getInstance().parseJsonAndGetMessage(sendRequest("sendLocation", args));
}
void Api::sendChatAction(int32_t chatId, const string& action) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("chat_id", chatId));
args.push_back(HttpReqArg("action", action));
sendRequest("sendChatAction", args);
}
UserProfilePhotos::Ptr Api::getUserProfilePhotos(int32_t userId, int32_t offset, int32_t limit) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("user_id", userId));
if (offset) {
args.push_back(HttpReqArg("offset", offset));
}
limit = max(1, min(100, limit));
args.push_back(HttpReqArg("limit", limit));
return TgTypeParser::getInstance().parseJsonAndGetUserProfilePhotos(sendRequest("getUserProfilePhotos", args));
}
vector<Update::Ptr> Api::getUpdates(int32_t offset, int32_t limit, int32_t timeout) const {
vector<HttpReqArg> args;
if (offset) {
args.push_back(HttpReqArg("offset", offset));
}
limit = max(1, min(100, limit));
args.push_back(HttpReqArg("limit", limit));
if (timeout) {
args.push_back(HttpReqArg("timeout", timeout));
}
return TgTypeParser::getInstance().parseJsonAndGetArray<Update>(&TgTypeParser::parseJsonAndGetUpdate, sendRequest("getUpdates", args), "result");
}
void Api::setWebhook(const string& url) const {
vector<HttpReqArg> args;
args.push_back(HttpReqArg("url", url));
sendRequest("setWebhook", args);
}
ptree Api::sendRequest(const string& method, const vector<HttpReqArg>& args) const {
string url = "https://api.telegram.org/bot";
url += _token;
url += "/";
url += method;
string serverResponse = HttpClient::getInstance().makeRequest(url, args);
if (serverResponse.find("<html>") != serverResponse.npos) {
throw TgException("Bad request");
}
ptree result = TgTypeParser::getInstance().parseJson(serverResponse);
try {
if (result.get<bool>("ok")) {
if(method != "getMe" && method != "sendMessage")
return result;
else
return result.find("result")->second;
} else {
throw TgException(result.get("description", ""));
}
} catch (boost::property_tree::ptree_error& e) {
throw TgException("");
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: out_node.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-09-18 14:04:03 $
*
* 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
*
************************************************************************/
#include <precomp.h>
#include <toolkit/out_node.hxx>
// NOT FULLY DEFINED SERVICES
#include <algorithm>
namespace output
{
namespace
{
struct Less_NodePtr
{
bool operator()(
Node * p1,
Node * p2 ) const
{ return p1->Name() < p2->Name(); }
};
struct Less_NodePtr C_Less_NodePtr;
Node C_aNullNode(Node::null_object);
} // namepace anonymous
//********************** Node ***************************//
Node::Node()
: sName(),
pParent(0),
aChildren(),
nDepth(0),
nNameRoomId(0)
{
}
Node::Node( E_NullObject )
: sName(),
pParent(0),
aChildren(),
nDepth(-1),
nNameRoomId(0)
{
}
Node::Node( const String & i_name,
Node & i_parent )
: sName(i_name),
pParent(&i_parent),
aChildren(),
nDepth(i_parent.Depth()+1),
nNameRoomId(0)
{
}
Node::~Node()
{
for ( List::iterator it = aChildren.begin();
it != aChildren.end();
++it )
{
delete *it;
}
}
Node &
Node::Provide_Child( const String & i_name )
{
Node * ret = find_Child(i_name);
if (ret != 0)
return *ret;
return add_Child(i_name);
}
void
Node::Get_Path( StreamStr & o_result,
intt i_maxDepth ) const
{
// Intentionally 'i_maxDepth != 0', so max_Depth == -1 sets no limit:
if (i_maxDepth != 0)
{
if (pParent != 0)
pParent->Get_Path(o_result, i_maxDepth-1);
o_result << sName << '/';
}
}
void
Node::Get_Chain( StringVector & o_result,
intt i_maxDepth ) const
{
if (i_maxDepth != 0)
{
// This is called also for the toplevel Node,
// but there happens nothing:
if (pParent != 0)
{
pParent->Get_Chain(o_result, i_maxDepth-1);
o_result.push_back(sName);
}
}
}
Node *
Node::find_Child( const String & i_name )
{
// Trying to optimise search in a vector:
uintt nSize = aChildren.size();
if ( nSize > 0 AND nSize < 20 )
{
List::const_iterator it = aChildren.begin();
List::const_iterator itMiddle = it + nSize/2;
int comp = 0;
if ( i_name < (*itMiddle)->Name() )
{
for ( ;
it != itMiddle
? (comp = csv::compare(i_name, (*it)->Name())) <= 0
: false;
++it )
{
if ( comp == 0 )
return *it;
} // end for
}
else
{
List::const_iterator itEnd = aChildren.end();
for ( it = itMiddle;
it != itEnd
? (comp = csv::compare(i_name, (*it)->Name())) <= 0
: false;
++it )
{
if ( comp == 0 )
return *it;
} // end for
}
}
else if (nSize > 0)
{
Node aSearch;
aSearch.sName = i_name;
List::const_iterator
ret = std::lower_bound( aChildren.begin(),
aChildren.end(),
&aSearch,
C_Less_NodePtr );
if ( ret != aChildren.end() ? (*ret)->Name() == i_name : false )
return *ret;
}
return 0;
}
Node &
Node::add_Child( const String & i_name )
{
DYN Node * pNew = new Node(i_name,*this);
aChildren.insert( std::upper_bound( aChildren.begin(),
aChildren.end(),
pNew,
C_Less_NodePtr ),
pNew );
return *pNew;
}
Node &
Node::provide_Child( StringVector::const_iterator i_next,
StringVector::const_iterator i_end )
{
if (i_next == i_end)
return *this;
return Provide_Child(*i_next).provide_Child(i_next+1,i_end);
}
Node &
Node::Null_()
{
return C_aNullNode;
}
} // namespace output
<commit_msg>INTEGRATION: CWS adc18 (1.5.2); FILE MERGED 2007/10/18 15:23:15 np 1.5.2.1: #i81775#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: out_node.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-11-02 16:42:12 $
*
* 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
*
************************************************************************/
#include <precomp.h>
#include <toolkit/out_node.hxx>
// NOT FULLY DEFINED SERVICES
#include <algorithm>
namespace output
{
namespace
{
struct Less_NodePtr
{
bool operator()(
Node * p1,
Node * p2 ) const
{ return p1->Name() < p2->Name(); }
};
struct Less_NodePtr C_Less_NodePtr;
Node C_aNullNode(Node::null_object);
} // namepace anonymous
//********************** Node ***************************//
Node::Node()
: sName(),
pParent(0),
aChildren(),
nDepth(0),
nNameRoomId(0)
{
}
Node::Node( E_NullObject )
: sName(),
pParent(0),
aChildren(),
nDepth(-1),
nNameRoomId(0)
{
}
Node::Node( const String & i_name,
Node & i_parent )
: sName(i_name),
pParent(&i_parent),
aChildren(),
nDepth(i_parent.Depth()+1),
nNameRoomId(0)
{
}
Node::~Node()
{
for ( List::iterator it = aChildren.begin();
it != aChildren.end();
++it )
{
delete *it;
}
}
Node &
Node::Provide_Child( const String & i_name )
{
Node *
ret = find_Child(i_name);
if (ret != 0)
return *ret;
return add_Child(i_name);
}
void
Node::Get_Path( StreamStr & o_result,
intt i_maxDepth ) const
{
// Intentionally 'i_maxDepth != 0', so max_Depth == -1 sets no limit:
if (i_maxDepth != 0)
{
if (pParent != 0)
pParent->Get_Path(o_result, i_maxDepth-1);
o_result << sName << '/';
}
}
void
Node::Get_Chain( StringVector & o_result,
intt i_maxDepth ) const
{
if (i_maxDepth != 0)
{
// This is called also for the toplevel Node,
// but there happens nothing:
if (pParent != 0)
{
pParent->Get_Chain(o_result, i_maxDepth-1);
o_result.push_back(sName);
}
}
}
Node *
Node::find_Child( const String & i_name )
{
Node aSearch;
aSearch.sName = i_name;
List::const_iterator
ret = std::lower_bound( aChildren.begin(),
aChildren.end(),
&aSearch,
C_Less_NodePtr );
if ( ret != aChildren.end() ? (*ret)->Name() == i_name : false )
return *ret;
return 0;
}
Node &
Node::add_Child( const String & i_name )
{
DYN Node *
pNew = new Node(i_name,*this);
aChildren.insert( std::lower_bound( aChildren.begin(),
aChildren.end(),
pNew,
C_Less_NodePtr ),
pNew );
return *pNew;
}
Node &
Node::provide_Child( StringVector::const_iterator i_next,
StringVector::const_iterator i_end )
{
if (i_next == i_end)
return *this;
return Provide_Child(*i_next).provide_Child(i_next+1,i_end);
}
Node &
Node::Null_()
{
return C_aNullNode;
}
} // namespace output
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: expop2.cxx,v $
*
* $Revision: 1.25 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:57:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------------
#include <svtools/fltrcfg.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docinf.hxx>
#include <svx/svxmsbas.hxx>
#include "scerrors.hxx"
#include "scextopt.hxx"
#include "root.hxx"
#include "exp_op.hxx"
#include "excdoc.hxx"
#include "xcl97esc.hxx"
#include "document.hxx"
#include "rangenam.hxx"
#include "filtopt.hxx"
#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
#ifndef SC_XELINK_HXX
#include "xelink.hxx"
#endif
ExportBiff5::ExportBiff5( XclExpRootData& rExpData ):
ExportTyp( rExpData.mrBookStrm, &rExpData.mrDoc, rExpData.meCharSet ),
XclExpRoot( rExpData )
{
// nur Teil der Root-Daten gebraucht
pExcRoot = &GetOldRoot();
pExcRoot->pER = this; // ExcRoot -> XclExpRoot
pExcRoot->eDateiTyp = Biff5;
pExcDoc = new ExcDocument( *this );
}
ExportBiff5::~ExportBiff5()
{
delete pExcDoc;
}
FltError ExportBiff5::Write()
{
FltError eRet = eERR_OK;
SfxObjectShell* pDocShell = GetDocShell();
DBG_ASSERT( pDocShell, "ExportBiff5::Write - no document shell" );
SotStorageRef xRootStrg = GetRootStorage();
DBG_ASSERT( xRootStrg.Is(), "ExportBiff5::Write - no root storage" );
bool bWriteBasicCode = false;
bool bWriteBasicStrg = false;
if( GetBiff() == EXC_BIFF8 )
{
if( SvtFilterOptions* pFilterOpt = SvtFilterOptions::Get() )
{
bWriteBasicCode = pFilterOpt->IsLoadExcelBasicCode();
bWriteBasicStrg = pFilterOpt->IsLoadExcelBasicStorage();
}
}
if( pDocShell && xRootStrg.Is() && bWriteBasicStrg )
{
SvxImportMSVBasic aBasicImport( *pDocShell, *xRootStrg, bWriteBasicCode, bWriteBasicStrg );
ULONG nErr = aBasicImport.SaveOrDelMSVBAStorage( TRUE, EXC_STORAGE_VBA_PROJECT );
if( nErr != ERRCODE_NONE )
pDocShell->SetError( nErr );
}
pExcDoc->ReadDoc(); // ScDoc -> ExcDoc
pExcDoc->Write( aOut ); // wechstreamen
if( pDocShell && xRootStrg.Is() )
{
SfxDocumentInfo& rInfo = pDocShell->GetDocInfo();
rInfo.SavePropertySet( xRootStrg );
}
//! TODO: separate warnings for columns and sheets
const XclExpAddressConverter& rAddrConv = GetAddressConverter();
if( rAddrConv.IsColTruncated() || rAddrConv.IsRowTruncated() || rAddrConv.IsTabTruncated() )
return SCWARN_EXPORT_MAXROW;
return eERR_OK;
}
ExportBiff8::ExportBiff8( XclExpRootData& rExpData ) :
ExportBiff5( rExpData )
{
pExcRoot->eDateiTyp = Biff8;
pExcRoot->pEscher = new XclEscher( GetDoc().GetTableCount(), *pExcRoot );
}
ExportBiff8::~ExportBiff8()
{
delete pExcRoot->pEscher;
pExcRoot->pEscher = NULL;
}
<commit_msg>INTEGRATION: CWS dr46 (1.25.106); FILE MERGED 2006/02/16 12:55:24 dr 1.25.106.1: new file dumper, remove unused member mrBookStrm from root data<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: expop2.cxx,v $
*
* $Revision: 1.26 $
*
* last change: $Author: obo $ $Date: 2006-03-22 12:00:04 $
*
* 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
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------------
#include <svtools/fltrcfg.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docinf.hxx>
#include <svx/svxmsbas.hxx>
#include "scerrors.hxx"
#include "scextopt.hxx"
#include "root.hxx"
#include "exp_op.hxx"
#include "excdoc.hxx"
#include "xcl97esc.hxx"
#include "document.hxx"
#include "rangenam.hxx"
#include "filtopt.hxx"
#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
#ifndef SC_XELINK_HXX
#include "xelink.hxx"
#endif
ExportBiff5::ExportBiff5( XclExpRootData& rExpData, SvStream& rStrm ):
ExportTyp( rStrm, &rExpData.mrDoc, rExpData.meCharSet ),
XclExpRoot( rExpData )
{
// nur Teil der Root-Daten gebraucht
pExcRoot = &GetOldRoot();
pExcRoot->pER = this; // ExcRoot -> XclExpRoot
pExcRoot->eDateiTyp = Biff5;
pExcDoc = new ExcDocument( *this );
}
ExportBiff5::~ExportBiff5()
{
delete pExcDoc;
}
FltError ExportBiff5::Write()
{
FltError eRet = eERR_OK;
SfxObjectShell* pDocShell = GetDocShell();
DBG_ASSERT( pDocShell, "ExportBiff5::Write - no document shell" );
SotStorageRef xRootStrg = GetRootStorage();
DBG_ASSERT( xRootStrg.Is(), "ExportBiff5::Write - no root storage" );
bool bWriteBasicCode = false;
bool bWriteBasicStrg = false;
if( GetBiff() == EXC_BIFF8 )
{
if( SvtFilterOptions* pFilterOpt = SvtFilterOptions::Get() )
{
bWriteBasicCode = pFilterOpt->IsLoadExcelBasicCode();
bWriteBasicStrg = pFilterOpt->IsLoadExcelBasicStorage();
}
}
if( pDocShell && xRootStrg.Is() && bWriteBasicStrg )
{
SvxImportMSVBasic aBasicImport( *pDocShell, *xRootStrg, bWriteBasicCode, bWriteBasicStrg );
ULONG nErr = aBasicImport.SaveOrDelMSVBAStorage( TRUE, EXC_STORAGE_VBA_PROJECT );
if( nErr != ERRCODE_NONE )
pDocShell->SetError( nErr );
}
pExcDoc->ReadDoc(); // ScDoc -> ExcDoc
pExcDoc->Write( aOut ); // wechstreamen
if( pDocShell && xRootStrg.Is() )
{
SfxDocumentInfo& rInfo = pDocShell->GetDocInfo();
rInfo.SavePropertySet( xRootStrg );
}
//! TODO: separate warnings for columns and sheets
const XclExpAddressConverter& rAddrConv = GetAddressConverter();
if( rAddrConv.IsColTruncated() || rAddrConv.IsRowTruncated() || rAddrConv.IsTabTruncated() )
return SCWARN_EXPORT_MAXROW;
return eERR_OK;
}
ExportBiff8::ExportBiff8( XclExpRootData& rExpData, SvStream& rStrm ) :
ExportBiff5( rExpData, rStrm )
{
pExcRoot->eDateiTyp = Biff8;
pExcRoot->pEscher = new XclEscher( GetDoc().GetTableCount(), *pExcRoot );
}
ExportBiff8::~ExportBiff8()
{
delete pExcRoot->pEscher;
pExcRoot->pEscher = NULL;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xmlnexpi.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2003-06-04 12:36:37 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include <rtl/ustrbuf.hxx>
#include "xmlnexpi.hxx"
#include "xmlimprt.hxx"
#include "xmlcelli.hxx"
#include "docuno.hxx"
#include "global.hxx"
//#include "document.hxx"
#ifndef _SC_XMLCONVERTER_HXX
#include "XMLConverter.hxx"
#endif
#include <xmloff/xmltkmap.hxx>
#include <xmloff/nmspmap.hxx>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/sheet/XNamedRanges.hpp>
#include <com/sun/star/sheet/NamedRangeFlag.hpp>
#ifndef _COM_SUN_STAR_SHEET_XNAMEDRANGE_HPP_
#include <com/sun/star/sheet/XNamedRange.hpp>
#endif
#define SC_NAMEDRANGES "NamedRanges"
#define SC_REPEAT_COLUMN "repeat-column"
#define SC_REPEAT_ROW "repeat-row"
#define SC_FILTER "filter"
#define SC_PRINT_RANGE "print-range"
using namespace com::sun::star;
//------------------------------------------------------------------
ScXMLNamedExpressionsContext::ScXMLNamedExpressionsContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
SvXMLImportContext( rImport, nPrfx, rLName )
{
/* sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
rtl::OUString aLocalName;
USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
rtl::OUString sValue = xAttrList->getValueByIndex( i );
const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedRangeAttrTokenMap();
switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
{
}
}*/
rImport.LockSolarMutex();
}
ScXMLNamedExpressionsContext::~ScXMLNamedExpressionsContext()
{
GetScImport().UnlockSolarMutex();
}
SvXMLImportContext *ScXMLNamedExpressionsContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetScImport().GetNamedExpressionsElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLName ) )
{
case XML_TOK_NAMED_EXPRESSIONS_NAMED_RANGE:
pContext = new ScXMLNamedRangeContext( GetScImport(), nPrefix,
rLName, xAttrList//,
//this
);
break;
case XML_TOK_NAMED_EXPRESSIONS_NAMED_EXPRESSION:
pContext = new ScXMLNamedExpressionContext( GetScImport(), nPrefix,
rLName, xAttrList//,
//this
);
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );
return pContext;
}
sal_Int32 ScXMLNamedExpressionsContext::GetRangeType(const rtl::OUString sRangeType) const
{
sal_Int32 nRangeType = 0;
rtl::OUStringBuffer sBuffer;
sal_Int16 i = 0;
while (i <= sRangeType.getLength())
{
if ((sRangeType[i] == ' ') || (i == sRangeType.getLength()))
{
rtl::OUString sTemp = sBuffer.makeStringAndClear();
if (sTemp.compareToAscii(SC_REPEAT_COLUMN) == 0)
nRangeType |= sheet::NamedRangeFlag::COLUMN_HEADER;
else if (sTemp.compareToAscii(SC_REPEAT_ROW) == 0)
nRangeType |= sheet::NamedRangeFlag::ROW_HEADER;
else if (sTemp.compareToAscii(SC_FILTER) == 0)
nRangeType |= sheet::NamedRangeFlag::FILTER_CRITERIA;
else if (sTemp.compareToAscii(SC_PRINT_RANGE) == 0)
nRangeType |= sheet::NamedRangeFlag::PRINT_AREA;
}
else if (i < sRangeType.getLength())
sBuffer.append(sRangeType[i]);
i++;
}
return nRangeType;
}
void ScXMLNamedExpressionsContext::EndElement()
{
if (GetScImport().GetModel().is())
{
uno::Reference <beans::XPropertySet> xPropertySet (GetScImport().GetModel(), uno::UNO_QUERY);
if (xPropertySet.is())
{
uno::Any aNamedRanges = xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_NAMEDRANGES)));
uno::Reference <sheet::XNamedRanges> xNamedRanges;
if (aNamedRanges >>= xNamedRanges)
{
ScMyNamedExpressions* pNamedExpressions = GetScImport().GetNamedExpressions();
ScMyNamedExpressions::iterator aItr = pNamedExpressions->begin();
ScMyNamedExpressions::const_iterator aEndItr = pNamedExpressions->end();
table::CellAddress aCellAddress;
rtl::OUString sTempContent(RTL_CONSTASCII_USTRINGPARAM("0"));
while (aItr != aEndItr)
{
sal_Int32 nOffset(0);
if (ScXMLConverter::GetAddressFromString(
aCellAddress, (*aItr)->sBaseCellAddress, GetScImport().GetDocument(), nOffset ))
{
try
{
xNamedRanges->addNewByName((*aItr)->sName, sTempContent, aCellAddress, GetRangeType((*aItr)->sRangeType));
}
catch( uno::RuntimeException& r )
{
DBG_ERROR("here are some Named Ranges with the same name");
uno::Reference < container::XIndexAccess > xIndex(xNamedRanges, uno::UNO_QUERY);
if (xIndex.is())
{
sal_Int32 nMax(xIndex->getCount());
sal_Bool bInserted(sal_False);
sal_Int32 nCount(1);
rtl::OUStringBuffer sName((*aItr)->sName);
sName.append(sal_Unicode('_'));
while (!bInserted && nCount <= nMax)
{
rtl::OUStringBuffer sTemp(sName);
sTemp.append(rtl::OUString::valueOf(nCount));
try
{
xNamedRanges->addNewByName(sTemp.makeStringAndClear(), sTempContent, aCellAddress, GetRangeType((*aItr)->sRangeType));
bInserted = sal_True;
}
catch( uno::RuntimeException& rE )
{
++nCount;
}
}
}
}
}
aItr++;
}
aItr = pNamedExpressions->begin();
while (aItr != aEndItr)
{
sal_Int32 nOffset(0);
if (ScXMLConverter::GetAddressFromString(
aCellAddress, (*aItr)->sBaseCellAddress, GetScImport().GetDocument(), nOffset ))
{
sTempContent = (*aItr)->sContent;
ScXMLConverter::ParseFormula(sTempContent, (*aItr)->bIsExpression);
uno::Any aNamedRange = xNamedRanges->getByName((*aItr)->sName);
uno::Reference <sheet::XNamedRange> xNamedRange;
if (aNamedRange >>= xNamedRange)
xNamedRange->setContent(sTempContent);
}
delete *aItr;
aItr = pNamedExpressions->erase(aItr);
}
}
}
}
}
ScXMLNamedRangeContext::ScXMLNamedRangeContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
SvXMLImportContext( rImport, nPrfx, rLName )
{
ScMyNamedExpression* pNamedExpression = new ScMyNamedExpression;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedRangeAttrTokenMap();
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
rtl::OUString aLocalName;
USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
rtl::OUString sValue = xAttrList->getValueByIndex( i );
switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
{
case XML_TOK_NAMED_RANGE_ATTR_NAME :
{
pNamedExpression->sName = sValue;
}
break;
case XML_TOK_NAMED_RANGE_ATTR_CELL_RANGE_ADDRESS :
{
pNamedExpression->sContent = sValue;
}
break;
case XML_TOK_NAMED_RANGE_ATTR_BASE_CELL_ADDRESS :
{
pNamedExpression->sBaseCellAddress = sValue;
}
break;
case XML_TOK_NAMED_RANGE_ATTR_RANGE_USABLE_AS :
{
pNamedExpression->sRangeType = sValue;
}
break;
}
}
pNamedExpression->bIsExpression = sal_False;
GetScImport().AddNamedExpression(pNamedExpression);
}
ScXMLNamedRangeContext::~ScXMLNamedRangeContext()
{
}
SvXMLImportContext *ScXMLNamedRangeContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0;
/* const SvXMLTokenMap& rTokenMap = GetScImport().GetTableElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLName ) )
{
}*/
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );
return pContext;
}
void ScXMLNamedRangeContext::EndElement()
{
}
ScXMLNamedExpressionContext::ScXMLNamedExpressionContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
SvXMLImportContext( rImport, nPrfx, rLName )
{
ScMyNamedExpression* pNamedExpression = new ScMyNamedExpression;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedExpressionAttrTokenMap();
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
rtl::OUString aLocalName;
USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
rtl::OUString sValue = xAttrList->getValueByIndex( i );
switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
{
case XML_TOK_NAMED_EXPRESSION_ATTR_NAME :
{
pNamedExpression->sName = sValue;
}
break;
case XML_TOK_NAMED_EXPRESSION_ATTR_EXPRESSION :
{
pNamedExpression->sContent = sValue;
}
break;
case XML_TOK_NAMED_EXPRESSION_ATTR_BASE_CELL_ADDRESS :
{
pNamedExpression->sBaseCellAddress = sValue;
}
break;
}
}
pNamedExpression->bIsExpression = sal_True;
GetScImport().AddNamedExpression(pNamedExpression);
}
ScXMLNamedExpressionContext::~ScXMLNamedExpressionContext()
{
}
SvXMLImportContext *ScXMLNamedExpressionContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0;
/* const SvXMLTokenMap& rTokenMap = GetScImport().GetTableElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLName ) )
{
}*/
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );
return pContext;
}
void ScXMLNamedExpressionContext::EndElement()
{
}
<commit_msg>INTEGRATION: CWS geordi2q01 (1.11.74); FILE MERGED 2003/08/18 14:01:35 hr 1.11.74.1: #111861#: join changes from CWS sab006<commit_after>/*************************************************************************
*
* $RCSfile: xmlnexpi.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hjs $ $Date: 2003-08-18 14:44:12 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include <rtl/ustrbuf.hxx>
#include "xmlnexpi.hxx"
#include "xmlimprt.hxx"
#include "xmlcelli.hxx"
#include "docuno.hxx"
#include "global.hxx"
#ifndef _SC_XMLCONVERTER_HXX
#include "XMLConverter.hxx"
#endif
#include <xmloff/xmltkmap.hxx>
#include <xmloff/nmspmap.hxx>
using namespace com::sun::star;
//------------------------------------------------------------------
ScXMLNamedExpressionsContext::ScXMLNamedExpressionsContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
SvXMLImportContext( rImport, nPrfx, rLName )
{
/* sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
rtl::OUString aLocalName;
USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
rtl::OUString sValue = xAttrList->getValueByIndex( i );
const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedRangeAttrTokenMap();
switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
{
}
}*/
rImport.LockSolarMutex();
}
ScXMLNamedExpressionsContext::~ScXMLNamedExpressionsContext()
{
GetScImport().UnlockSolarMutex();
}
SvXMLImportContext *ScXMLNamedExpressionsContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetScImport().GetNamedExpressionsElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLName ) )
{
case XML_TOK_NAMED_EXPRESSIONS_NAMED_RANGE:
pContext = new ScXMLNamedRangeContext( GetScImport(), nPrefix,
rLName, xAttrList//,
//this
);
break;
case XML_TOK_NAMED_EXPRESSIONS_NAMED_EXPRESSION:
pContext = new ScXMLNamedExpressionContext( GetScImport(), nPrefix,
rLName, xAttrList//,
//this
);
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );
return pContext;
}
void ScXMLNamedExpressionsContext::EndElement()
{
// happends in ScXMLImport::EndDocument()
// because it has to be set after the Database Ranges
}
ScXMLNamedRangeContext::ScXMLNamedRangeContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
SvXMLImportContext( rImport, nPrfx, rLName )
{
ScMyNamedExpression* pNamedExpression = new ScMyNamedExpression;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedRangeAttrTokenMap();
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
rtl::OUString aLocalName;
USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
rtl::OUString sValue = xAttrList->getValueByIndex( i );
switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
{
case XML_TOK_NAMED_RANGE_ATTR_NAME :
{
pNamedExpression->sName = sValue;
}
break;
case XML_TOK_NAMED_RANGE_ATTR_CELL_RANGE_ADDRESS :
{
pNamedExpression->sContent = sValue;
}
break;
case XML_TOK_NAMED_RANGE_ATTR_BASE_CELL_ADDRESS :
{
pNamedExpression->sBaseCellAddress = sValue;
}
break;
case XML_TOK_NAMED_RANGE_ATTR_RANGE_USABLE_AS :
{
pNamedExpression->sRangeType = sValue;
}
break;
}
}
pNamedExpression->bIsExpression = sal_False;
GetScImport().AddNamedExpression(pNamedExpression);
}
ScXMLNamedRangeContext::~ScXMLNamedRangeContext()
{
}
SvXMLImportContext *ScXMLNamedRangeContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0;
/* const SvXMLTokenMap& rTokenMap = GetScImport().GetTableElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLName ) )
{
}*/
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );
return pContext;
}
void ScXMLNamedRangeContext::EndElement()
{
}
ScXMLNamedExpressionContext::ScXMLNamedExpressionContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
SvXMLImportContext( rImport, nPrfx, rLName )
{
ScMyNamedExpression* pNamedExpression = new ScMyNamedExpression;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedExpressionAttrTokenMap();
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
rtl::OUString aLocalName;
USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
rtl::OUString sValue = xAttrList->getValueByIndex( i );
switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
{
case XML_TOK_NAMED_EXPRESSION_ATTR_NAME :
{
pNamedExpression->sName = sValue;
}
break;
case XML_TOK_NAMED_EXPRESSION_ATTR_EXPRESSION :
{
pNamedExpression->sContent = sValue;
}
break;
case XML_TOK_NAMED_EXPRESSION_ATTR_BASE_CELL_ADDRESS :
{
pNamedExpression->sBaseCellAddress = sValue;
}
break;
}
}
pNamedExpression->bIsExpression = sal_True;
GetScImport().AddNamedExpression(pNamedExpression);
}
ScXMLNamedExpressionContext::~ScXMLNamedExpressionContext()
{
}
SvXMLImportContext *ScXMLNamedExpressionContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0;
/* const SvXMLTokenMap& rTokenMap = GetScImport().GetTableElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLName ) )
{
}*/
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );
return pContext;
}
void ScXMLNamedExpressionContext::EndElement()
{
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: graphsh.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:59: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
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#include <sfx2/app.hxx>
#include <sfx2/objface.hxx>
#include <sfx2/request.hxx>
#include <svtools/whiter.hxx>
#include <svx/svdograf.hxx>
#include <svx/grfflt.hxx>
#include <svx/grafctrl.hxx>
#include "graphsh.hxx"
#include "sc.hrc"
#include "viewdata.hxx"
#include "drawview.hxx"
#include "scresid.hxx"
#define ScGraphicShell
#include "scslots.hxx"
#define ITEMVALUE(ItemSet,Id,Cast) ((const Cast&)(ItemSet).Get(Id)).GetValue()
SFX_IMPL_INTERFACE(ScGraphicShell, ScDrawShell, ScResId(SCSTR_GRAPHICSHELL) )
{
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OBJECT|SFX_VISIBILITY_STANDARD|SFX_VISIBILITY_SERVER,
ScResId(RID_GRAPHIC_OBJECTBAR) );
SFX_POPUPMENU_REGISTRATION( ScResId(RID_POPUP_GRAPHIC) );
SFX_OBJECTMENU_REGISTRATION( SID_OBJECTMENU0, ScResId(RID_OBJECTMENU_DRAW) );
}
TYPEINIT1( ScGraphicShell, ScDrawShell );
ScGraphicShell::ScGraphicShell(ScViewData* pData) :
ScDrawShell(pData)
{
SetHelpId(HID_SCSHELL_GRAPHIC);
SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("GraphicObject")));
}
ScGraphicShell::~ScGraphicShell()
{
}
void ScGraphicShell::GetAttrState( SfxItemSet& rSet )
{
ScDrawView* pView = GetViewData()->GetScDrawView();
if( pView )
SvxGrafAttrHelper::GetGrafAttrState( rSet, *pView );
}
void ScGraphicShell::Execute( SfxRequest& rReq )
{
ScDrawView* pView = GetViewData()->GetScDrawView();
if( pView )
{
SvxGrafAttrHelper::ExecuteGrafAttr( rReq, *pView );
Invalidate();
}
}
void ScGraphicShell::GetFilterState( SfxItemSet& rSet )
{
ScDrawView* pView = GetViewData()->GetScDrawView();
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
BOOL bEnable = FALSE;
if( rMarkList.GetMarkCount() == 1 )
{
SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();
if( pObj && pObj->ISA( SdrGrafObj ) && ( ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP ) )
bEnable = TRUE;
}
if( !bEnable )
SvxGraphicFilter::DisableGraphicFilterSlots( rSet );
}
void ScGraphicShell::ExecuteFilter( SfxRequest& rReq )
{
ScDrawView* pView = GetViewData()->GetScDrawView();
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
{
SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();
if( pObj && pObj->ISA( SdrGrafObj ) && ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP )
{
GraphicObject aFilterObj( ( (SdrGrafObj*) pObj )->GetGraphicObject() );
if( SVX_GRAPHICFILTER_ERRCODE_NONE ==
SvxGraphicFilter::ExecuteGrfFilterSlot( rReq, aFilterObj ) )
{
SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );
if( pPageView )
{
SdrGrafObj* pFilteredObj = (SdrGrafObj*) pObj->Clone();
String aStr( pView->GetDescriptionOfMarkedObjects() );
aStr.Append( sal_Unicode(' ') );
aStr.Append( String( ScResId( SCSTR_UNDO_GRAFFILTER ) ) );
pView->BegUndo( aStr );
pFilteredObj->SetGraphicObject( aFilterObj );
pView->ReplaceObject( pObj, *pPageView, pFilteredObj );
pView->EndUndo();
}
}
}
}
Invalidate();
}
<commit_msg>INTEGRATION: CWS sfxcleanup (1.6.124); FILE MERGED 2006/03/02 10:39:28 mba 1.6.124.2: #132394#: remove superfluous code 2006/03/02 09:26:20 mba 1.6.124.1: #132394#: remove superfluous code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: graphsh.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2006-05-02 15:49:17 $
*
* 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
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#include <sfx2/app.hxx>
#include <sfx2/objface.hxx>
#include <sfx2/request.hxx>
#include <svtools/whiter.hxx>
#include <svx/svdograf.hxx>
#include <svx/grfflt.hxx>
#include <svx/grafctrl.hxx>
#include "graphsh.hxx"
#include "sc.hrc"
#include "viewdata.hxx"
#include "drawview.hxx"
#include "scresid.hxx"
#define ScGraphicShell
#include "scslots.hxx"
#define ITEMVALUE(ItemSet,Id,Cast) ((const Cast&)(ItemSet).Get(Id)).GetValue()
SFX_IMPL_INTERFACE(ScGraphicShell, ScDrawShell, ScResId(SCSTR_GRAPHICSHELL) )
{
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OBJECT|SFX_VISIBILITY_STANDARD|SFX_VISIBILITY_SERVER,
ScResId(RID_GRAPHIC_OBJECTBAR) );
SFX_POPUPMENU_REGISTRATION( ScResId(RID_POPUP_GRAPHIC) );
}
TYPEINIT1( ScGraphicShell, ScDrawShell );
ScGraphicShell::ScGraphicShell(ScViewData* pData) :
ScDrawShell(pData)
{
SetHelpId(HID_SCSHELL_GRAPHIC);
SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("GraphicObject")));
}
ScGraphicShell::~ScGraphicShell()
{
}
void ScGraphicShell::GetAttrState( SfxItemSet& rSet )
{
ScDrawView* pView = GetViewData()->GetScDrawView();
if( pView )
SvxGrafAttrHelper::GetGrafAttrState( rSet, *pView );
}
void ScGraphicShell::Execute( SfxRequest& rReq )
{
ScDrawView* pView = GetViewData()->GetScDrawView();
if( pView )
{
SvxGrafAttrHelper::ExecuteGrafAttr( rReq, *pView );
Invalidate();
}
}
void ScGraphicShell::GetFilterState( SfxItemSet& rSet )
{
ScDrawView* pView = GetViewData()->GetScDrawView();
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
BOOL bEnable = FALSE;
if( rMarkList.GetMarkCount() == 1 )
{
SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();
if( pObj && pObj->ISA( SdrGrafObj ) && ( ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP ) )
bEnable = TRUE;
}
if( !bEnable )
SvxGraphicFilter::DisableGraphicFilterSlots( rSet );
}
void ScGraphicShell::ExecuteFilter( SfxRequest& rReq )
{
ScDrawView* pView = GetViewData()->GetScDrawView();
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
{
SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();
if( pObj && pObj->ISA( SdrGrafObj ) && ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP )
{
GraphicObject aFilterObj( ( (SdrGrafObj*) pObj )->GetGraphicObject() );
if( SVX_GRAPHICFILTER_ERRCODE_NONE ==
SvxGraphicFilter::ExecuteGrfFilterSlot( rReq, aFilterObj ) )
{
SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );
if( pPageView )
{
SdrGrafObj* pFilteredObj = (SdrGrafObj*) pObj->Clone();
String aStr( pView->GetDescriptionOfMarkedObjects() );
aStr.Append( sal_Unicode(' ') );
aStr.Append( String( ScResId( SCSTR_UNDO_GRAFFILTER ) ) );
pView->BegUndo( aStr );
pFilteredObj->SetGraphicObject( aFilterObj );
pView->ReplaceObject( pObj, *pPageView, pFilteredObj );
pView->EndUndo();
}
}
}
}
Invalidate();
}
<|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 "media/base/media.h"
#include <windows.h>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
// Enable timing code by turning on TESTING macro.
//#define TESTING 1
#ifdef TESTING
#include "base/string_util.h"
#include "base/time.h"
namespace {
// Fetch current time as milliseconds.
// Return as double for high duration and precision.
// TODO(fbarchard): integrate into base/time.h
static inline double GetTime() {
return base::TimeTicks::HighResNow().ToInternalValue() * (1.0 / 1000.0);
}
}
#endif
namespace media {
namespace {
enum FFmpegDLLKeys {
FILE_LIBAVCODEC, // full path to libavcodec media decoding library.
FILE_LIBAVFORMAT, // full path to libavformat media parsing library.
FILE_LIBAVUTIL, // full path to libavutil media utility library.
};
// Retrieves the DLLName for the given key.
FilePath::CharType* GetDLLName(FFmpegDLLKeys dll_key) {
// TODO(ajwong): Do we want to lock to a specific ffmpeg version?
switch (dll_key) {
case FILE_LIBAVCODEC:
return FILE_PATH_LITERAL("avcodec-52.dll");
case FILE_LIBAVFORMAT:
return FILE_PATH_LITERAL("avformat-52.dll");
case FILE_LIBAVUTIL:
return FILE_PATH_LITERAL("avutil-50.dll");
default:
LOG(DFATAL) << "Invalid DLL key requested: " << dll_key;
return FILE_PATH_LITERAL("");
}
}
} // namespace
// Attempts to initialize the media library (loading DLLs, DSOs, etc.).
// Returns true if everything was successfully initialized, false otherwise.
bool InitializeMediaLibrary(const FilePath& base_path) {
FFmpegDLLKeys path_keys[] = {
media::FILE_LIBAVCODEC,
media::FILE_LIBAVFORMAT,
media::FILE_LIBAVUTIL
};
HMODULE libs[arraysize(path_keys)] = {NULL};
for (size_t i = 0; i < arraysize(path_keys); ++i) {
FilePath path = base_path.Append(GetDLLName(path_keys[i]));
#ifdef TESTING
double dll_loadtime_start = GetTime();
#endif
const wchar_t* cpath = path.value().c_str();
libs[i] = LoadLibrary(cpath);
if (!libs[i])
break;
#ifdef TESTING
double dll_loadtime_end = GetTime();
std::wstring outputbuf = StringPrintf(L"DLL loadtime %5.2f ms, %ls\n",
dll_loadtime_end - dll_loadtime_start,
cpath);
OutputDebugStringW(outputbuf.c_str());
#endif
}
// Check that we loaded all libraries successfully. We only need to check the
// last array element because the loop above will break without initializing
// it on any prior error.
if (libs[arraysize(libs)-1])
return true;
// Free any loaded libraries if we weren't successful.
for (size_t i = 0; i < arraysize(libs) && libs[i] != NULL; ++i) {
FreeLibrary(libs[i]);
libs[i] = NULL; // Just to be safe.
}
return false;
}
bool InitializeOpenMaxLibrary(const FilePath& module_dir) {
NOTIMPLEMENTED() << "OpenMAX is not used in Windows.";
return false;
}
} // namespace media
<commit_msg>Limit the DLL search path when loading FFmpeg binaries on Windows.<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 "media/base/media.h"
#include <windows.h>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/scoped_ptr.h"
// Enable timing code by turning on TESTING macro.
//#define TESTING 1
#ifdef TESTING
#include "base/string_util.h"
#include "base/time.h"
namespace {
// Fetch current time as milliseconds.
// Return as double for high duration and precision.
// TODO(fbarchard): integrate into base/time.h
static inline double GetTime() {
return base::TimeTicks::HighResNow().ToInternalValue() * (1.0 / 1000.0);
}
}
#endif
namespace media {
namespace {
enum FFmpegDLLKeys {
FILE_LIBAVCODEC, // full path to libavcodec media decoding library.
FILE_LIBAVFORMAT, // full path to libavformat media parsing library.
FILE_LIBAVUTIL, // full path to libavutil media utility library.
};
// Retrieves the DLLName for the given key.
FilePath::CharType* GetDLLName(FFmpegDLLKeys dll_key) {
// TODO(ajwong): Do we want to lock to a specific ffmpeg version?
switch (dll_key) {
case FILE_LIBAVCODEC:
return FILE_PATH_LITERAL("avcodec-52.dll");
case FILE_LIBAVFORMAT:
return FILE_PATH_LITERAL("avformat-52.dll");
case FILE_LIBAVUTIL:
return FILE_PATH_LITERAL("avutil-50.dll");
default:
LOG(DFATAL) << "Invalid DLL key requested: " << dll_key;
return FILE_PATH_LITERAL("");
}
}
} // namespace
// Attempts to initialize the media library (loading DLLs, DSOs, etc.).
// Returns true if everything was successfully initialized, false otherwise.
bool InitializeMediaLibrary(const FilePath& base_path) {
FFmpegDLLKeys path_keys[] = {
media::FILE_LIBAVCODEC,
media::FILE_LIBAVFORMAT,
media::FILE_LIBAVUTIL
};
HMODULE libs[arraysize(path_keys)] = {NULL};
// Limit the DLL search path so we don't load dependencies from the system
// path. Refer to http://crbug.com/35857
scoped_array<wchar_t> previous_dll_directory(new wchar_t[MAX_PATH]);
if (!GetDllDirectory(MAX_PATH, previous_dll_directory.get())) {
previous_dll_directory.reset();
}
SetDllDirectory(base_path.value().c_str());
for (size_t i = 0; i < arraysize(path_keys); ++i) {
FilePath path(GetDLLName(path_keys[i]));
#ifdef TESTING
double dll_loadtime_start = GetTime();
#endif
const wchar_t* cpath = path.value().c_str();
libs[i] = LoadLibrary(cpath);
if (!libs[i])
break;
#ifdef TESTING
double dll_loadtime_end = GetTime();
std::wstring outputbuf = StringPrintf(L"DLL loadtime %5.2f ms, %ls\n",
dll_loadtime_end - dll_loadtime_start,
cpath);
OutputDebugStringW(outputbuf.c_str());
#endif
}
SetDllDirectory(previous_dll_directory.get());
// Check that we loaded all libraries successfully. We only need to check the
// last array element because the loop above will break without initializing
// it on any prior error.
if (libs[arraysize(libs)-1])
return true;
// Free any loaded libraries if we weren't successful.
for (size_t i = 0; i < arraysize(libs) && libs[i] != NULL; ++i) {
FreeLibrary(libs[i]);
libs[i] = NULL; // Just to be safe.
}
return false;
}
bool InitializeOpenMaxLibrary(const FilePath& module_dir) {
NOTIMPLEMENTED() << "OpenMAX is not used in Windows.";
return false;
}
} // namespace media
<|endoftext|>
|
<commit_before>/* -LICENSE-START-
** Copyright (c) 2013 Blackmagic Design
**
** 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.
** -LICENSE-END-
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <csignal>
#include <jni.h>
#include <string>
#include "DeckLinkAPI.h"
#include "Capture.h"
#include "Util.hpp"
#include "us_ihmc_javadecklink_Capture.h"
DeckLinkCaptureDelegate::DeckLinkCaptureDelegate(IDeckLink* decklink, IDeckLinkInput* decklinkInput, JavaVM* vm) :
m_refCount(1),
decklink(decklink),
decklinkInput(decklinkInput),
vm(vm),
initial_video_pts(AV_NOPTS_VALUE)
{
av_register_all();
avcodec_register_all();
oc = avformat_alloc_context();
oc->oformat = av_guess_format("mp4", NULL, NULL);
if(oc->oformat == NULL)
{
fprintf(stderr, "AV Format mp4 not found\n");
exit(1);
}
oc->oformat->video_codec = AV_CODEC_ID_MJPEG;
snprintf(oc->filename, sizeof(oc->filename), "test.mp4");
oc->oformat->audio_codec = AV_CODEC_ID_NONE;
}
ULONG DeckLinkCaptureDelegate::AddRef(void)
{
return __sync_add_and_fetch(&m_refCount, 1);
}
ULONG DeckLinkCaptureDelegate::Release(void)
{
int32_t newRefValue = __sync_sub_and_fetch(&m_refCount, 1);
if (newRefValue == 0)
{
delete this;
return 0;
}
return newRefValue;
}
HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
{
void* frameBytes;
// Handle Video Frame
if (videoFrame)
{
JNIEnv* env = getEnv(vm);
if(env == 0)
{
// Cannot throw a runtime exception because we don't have an env
std::cerr << "Cannot load env" << std::endl;
return S_OK;
}
if (videoFrame->GetFlags() & bmdFrameHasNoInputSource)
{
printf("Frame received - No input signal detected\n");
//env->CallVoidMethod(obj, methodID, false, 0, 0, NULL);
}
else
{
printf("Frame received - Size: %li bytes\n",
videoFrame->GetRowBytes() * videoFrame->GetHeight());
videoFrame->GetBytes(&frameBytes);
//write(g_videoOutputFile, frameBytes, videoFrame->GetRowBytes() * videoFrame->GetHeight());
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
BMDTimeValue frameTime;
BMDTimeValue frameDuration;
videoFrame->GetStreamTime(&frameTime, &frameDuration, video_st->time_base.den);
int64_t pts;
pts = frameTime / video_st->time_base.num;
if (initial_video_pts == AV_NOPTS_VALUE) {
initial_video_pts = pts;
}
pts -= initial_video_pts;
pictureUYVY->pts = pts;
pictureYUV420->pts = pts;
pkt.pts = pkt.dts = pts;
avpicture_fill((AVPicture*)pictureUYVY, (uint8_t*) frameBytes, AV_PIX_FMT_UYVY422, pictureUYVY->width, pictureUYVY->height);
sws_scale(img_convert_ctx, pictureUYVY->data, pictureUYVY->linesize, 0, c->height, pictureYUV420->data, pictureYUV420->linesize);
/* encode the image */
int got_output;
int ret = avcodec_encode_video2(c, &pkt, pictureYUV420, &got_output);
if (ret < 0) {
fprintf(stderr, "error encoding frame\n");
exit(1);
}
if (got_output) {
printf("encoding frame %3d (size=%5d)\n", i, pkt.size);
av_write_frame(oc, &pkt);
av_free_packet(&pkt); //depreacted, use av_packet_unref(&pkt); after Ubuntu 16.04 comes out
}
++i;
}
}
return S_OK;
}
HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags formatFlags)
{
// This only gets called if bmdVideoInputEnableFormatDetection was set
// when enabling video input
HRESULT result;
char* displayModeName = NULL;
BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
JNIEnv* env = getEnv(vm);
if (formatFlags & bmdDetectedVideoInputRGB444)
{
throwRuntimeException(env, "Unsupported input format: RGB444");
goto bail;
}
mode->GetName((const char**)&displayModeName);
printf("Video format changed to %s %s\n", displayModeName, formatFlags & bmdDetectedVideoInputRGB444 ? "RGB" : "YUV");
if (displayModeName)
free(displayModeName);
if (decklinkInput)
{
decklinkInput->StopStreams();
codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
video_st = avformat_new_stream(oc, codec);
if(!video_st)
{
throwRuntimeException(env, "Cannot allocate video stream");
goto bail;
}
c = video_st->codec;
/* put sample parameters */
c->qcompress = 0.80;
/* resolution must be a multiple of two */
c->width = mode->GetWidth();
c->height = mode->GetHeight();
/* frames per second */
BMDTimeValue numerator;
BMDTimeScale denumerator;
mode->GetFrameRate(&numerator, &denumerator);
c->time_base.den = denumerator;
c->time_base.num = numerator;
c->pix_fmt = AV_PIX_FMT_YUVJ420P;
if(oc->oformat->flags & AVFMT_GLOBALHEADER)
{
c->flags |= CODEC_FLAG_GLOBAL_HEADER;
}
/* open it */
if (avcodec_open2(c, codec, NULL) < 0) {
throwRuntimeException(env, "Could not open codec");
goto bail;
}
if(avio_open(&oc->pb, oc->filename, AVIO_FLAG_WRITE) < 0)
{
throwRuntimeException(env, "Could not open file");
goto bail;
}
pictureYUV420 = avcodec_alloc_frame();
int ret = av_image_alloc(pictureYUV420->data, pictureYUV420->linesize, c->width, c->height,
c->pix_fmt, 32);
if (ret < 0) {
throwRuntimeException(env, "could not alloc raw picture buffer\n");
goto bail;
}
pictureYUV420->format = c->pix_fmt;
pictureYUV420->width = c->width;
pictureYUV420->height = c->height;
pictureUYVY = avcodec_alloc_frame();
pictureUYVY->width = c->width;
pictureUYVY->height = c->height;
pictureUYVY->format = AV_PIX_FMT_UYVY422;
img_convert_ctx = sws_getContext(c->width, c->height,
AV_PIX_FMT_UYVY422,
c->width, c->height,
c->pix_fmt,
sws_flags, NULL, NULL, NULL);
avformat_write_header(oc, NULL);
result = decklinkInput->EnableVideoInput(mode->GetDisplayMode(), pixelFormat, bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection);
if (result != S_OK)
{
throwRuntimeException(env, "Failed to switch to new video mode");
goto bail;
}
decklinkInput->StartStreams();
}
bail:
std::cout << "Detected new mode " << mode->GetWidth() << "x" << mode->GetHeight() << std::endl;
return S_OK;
}
void DeckLinkCaptureDelegate::Stop()
{
decklinkInput->StopStreams();
decklinkInput->DisableVideoInput();
if (decklinkInput != NULL)
{
decklinkInput->Release();
decklinkInput = NULL;
}
if (decklink != NULL)
{
decklink->Release();
decklink = NULL;
}
releaseEnv(vm);
avcodec_close(c);
av_free(c);
av_freep(&pictureYUV420->data[0]);
avcodec_free_frame(&pictureYUV420);
av_write_trailer(oc);
avio_close(oc->pb);
}
JNIEXPORT void JNICALL Java_us_ihmc_javadecklink_Capture_stopCaptureNative
(JNIEnv *, jobject, jlong delegatePtr)
{
DeckLinkCaptureDelegate* delegate = (DeckLinkCaptureDelegate*) delegatePtr;
delegate->Stop();
}
JNIEXPORT jlong JNICALL Java_us_ihmc_javadecklink_Capture_startCaptureNative
(JNIEnv *env, jobject obj, jint idx, jint displayModeId)
{
IDeckLinkIterator* deckLinkIterator = NULL;
IDeckLink* deckLink = NULL;
IDeckLinkDisplayModeIterator* displayModeIterator = NULL;
IDeckLinkDisplayMode* displayMode = NULL;
char* displayModeName = NULL;
BMDDisplayModeSupport displayModeSupported;
DeckLinkCaptureDelegate* delegate = NULL;
HRESULT result;
IDeckLinkInput* g_deckLinkInput = NULL;
JavaVM* vm;
JNIassert(env, env->GetJavaVM(&vm) == 0);
// Get the DeckLink device
deckLinkIterator = CreateDeckLinkIteratorInstance();
if (!deckLinkIterator)
{
fprintf(stderr, "This application requires the DeckLink drivers installed.\n");
goto bail;
}
while ((result = deckLinkIterator->Next(&deckLink)) == S_OK)
{
if (idx == 0)
break;
--idx;
deckLink->Release();
}
if (result != S_OK || deckLink == NULL)
{
fprintf(stderr, "Unable to get DeckLink device %u\n", idx);
goto bail;
}
// Get the input (capture) interface of the DeckLink device
result = deckLink->QueryInterface(IID_IDeckLinkInput, (void**)&g_deckLinkInput);
if (result != S_OK)
goto bail;
result = g_deckLinkInput->GetDisplayModeIterator(&displayModeIterator);
if (result != S_OK)
goto bail;
displayModeId = 0;
while ((result = displayModeIterator->Next(&displayMode)) == S_OK)
{
if (displayModeId == 0)
break;
--displayModeId;
displayMode->Release();
}
if (result != S_OK || displayMode == NULL)
{
fprintf(stderr, "Unable to get display mode %d\n", displayModeId);
goto bail;
}
// Get display mode name
result = displayMode->GetName((const char**)&displayModeName);
if (result != S_OK)
{
displayModeName = (char *)malloc(32);
snprintf(displayModeName, 32, "[index %d]", displayModeId);
}
// Check display mode is supported with given options
result = g_deckLinkInput->DoesSupportVideoMode(displayMode->GetDisplayMode(), bmdFormat8BitYUV, bmdVideoInputFlagDefault, &displayModeSupported, NULL);
if (result != S_OK)
goto bail;
if (displayModeSupported == bmdDisplayModeNotSupported)
{
fprintf(stderr, "The display mode %s is not supported with the selected pixel format\n", displayModeName);
goto bail;
}
// Configure the capture callback
delegate = new DeckLinkCaptureDelegate(deckLink, g_deckLinkInput, vm);
g_deckLinkInput->SetCallback(delegate);
// Start capturing
result = g_deckLinkInput->EnableVideoInput(displayMode->GetDisplayMode(), bmdFormat8BitYUV, bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection);
if (result != S_OK)
{
fprintf(stderr, "Failed to enable video input. Is another application using the card?\n");
goto bail;
}
result = g_deckLinkInput->StartStreams();
if (result != S_OK)
goto bail;
bail:
if (displayModeName != NULL)
free(displayModeName);
if (displayMode != NULL)
displayMode->Release();
if (displayModeIterator != NULL)
displayModeIterator->Release();
if (deckLinkIterator != NULL)
deckLinkIterator->Release();
return (jlong) delegate;
}
<commit_msg>Playing with timecodes<commit_after>/* -LICENSE-START-
** Copyright (c) 2013 Blackmagic Design
**
** 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.
** -LICENSE-END-
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <csignal>
#include <jni.h>
#include <string>
#include "DeckLinkAPI.h"
#include "Capture.h"
#include "Util.hpp"
#include "us_ihmc_javadecklink_Capture.h"
DeckLinkCaptureDelegate::DeckLinkCaptureDelegate(IDeckLink* decklink, IDeckLinkInput* decklinkInput, JavaVM* vm) :
m_refCount(1),
decklink(decklink),
decklinkInput(decklinkInput),
vm(vm),
initial_video_pts(AV_NOPTS_VALUE)
{
av_register_all();
avcodec_register_all();
oc = avformat_alloc_context();
oc->oformat = av_guess_format("mp4", NULL, NULL);
if(oc->oformat == NULL)
{
fprintf(stderr, "AV Format mp4 not found\n");
exit(1);
}
oc->oformat->video_codec = AV_CODEC_ID_MJPEG;
snprintf(oc->filename, sizeof(oc->filename), "test.mp4");
oc->oformat->audio_codec = AV_CODEC_ID_NONE;
}
ULONG DeckLinkCaptureDelegate::AddRef(void)
{
return __sync_add_and_fetch(&m_refCount, 1);
}
ULONG DeckLinkCaptureDelegate::Release(void)
{
int32_t newRefValue = __sync_sub_and_fetch(&m_refCount, 1);
if (newRefValue == 0)
{
delete this;
return 0;
}
return newRefValue;
}
HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
{
void* frameBytes;
// Handle Video Frame
if (videoFrame)
{
JNIEnv* env = getEnv(vm);
if(env == 0)
{
// Cannot throw a runtime exception because we don't have an env
std::cerr << "Cannot load env" << std::endl;
return S_OK;
}
if (videoFrame->GetFlags() & bmdFrameHasNoInputSource)
{
printf("Frame received - No input signal detected\n");
//env->CallVoidMethod(obj, methodID, false, 0, 0, NULL);
}
else
{
printf("Frame received - Size: %li bytes\n",
videoFrame->GetRowBytes() * videoFrame->GetHeight());
videoFrame->GetBytes(&frameBytes);
//write(g_videoOutputFile, frameBytes, videoFrame->GetRowBytes() * videoFrame->GetHeight());
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
BMDTimeValue frameTime;
BMDTimeValue frameDuration;
videoFrame->GetStreamTime(&frameTime, &frameDuration, video_st->time_base.den);
int64_t pts;
pts = frameTime / video_st->time_base.num;
videoFrame->GetStreamTime(&frameTime, &frameDuration, 1000000);
printf("Got frame at %ld\n", frameTime);
if (initial_video_pts == AV_NOPTS_VALUE) {
initial_video_pts = pts;
}
pts -= initial_video_pts;
pictureUYVY->pts = pts;
pictureYUV420->pts = pts;
pkt.pts = pkt.dts = pts;
avpicture_fill((AVPicture*)pictureUYVY, (uint8_t*) frameBytes, AV_PIX_FMT_UYVY422, pictureUYVY->width, pictureUYVY->height);
sws_scale(img_convert_ctx, pictureUYVY->data, pictureUYVY->linesize, 0, c->height, pictureYUV420->data, pictureYUV420->linesize);
/* encode the image */
int got_output;
int ret = avcodec_encode_video2(c, &pkt, pictureYUV420, &got_output);
if (ret < 0) {
fprintf(stderr, "error encoding frame\n");
exit(1);
}
if (got_output) {
printf("encoding frame %3d (size=%5d)\n", i, pkt.size);
av_write_frame(oc, &pkt);
av_free_packet(&pkt); //depreacted, use av_packet_unref(&pkt); after Ubuntu 16.04 comes out
}
++i;
}
}
return S_OK;
}
HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags formatFlags)
{
// This only gets called if bmdVideoInputEnableFormatDetection was set
// when enabling video input
HRESULT result;
char* displayModeName = NULL;
BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
JNIEnv* env = getEnv(vm);
if (formatFlags & bmdDetectedVideoInputRGB444)
{
throwRuntimeException(env, "Unsupported input format: RGB444");
goto bail;
}
mode->GetName((const char**)&displayModeName);
printf("Video format changed to %s %s\n", displayModeName, formatFlags & bmdDetectedVideoInputRGB444 ? "RGB" : "YUV");
if (displayModeName)
free(displayModeName);
if (decklinkInput)
{
decklinkInput->StopStreams();
codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
video_st = avformat_new_stream(oc, codec);
if(!video_st)
{
throwRuntimeException(env, "Cannot allocate video stream");
goto bail;
}
c = video_st->codec;
/* put sample parameters */
c->qcompress = 0.80;
/* resolution must be a multiple of two */
c->width = mode->GetWidth();
c->height = mode->GetHeight();
/* frames per second */
BMDTimeValue numerator;
BMDTimeScale denumerator;
mode->GetFrameRate(&numerator, &denumerator);
c->time_base.den = denumerator;
c->time_base.num = numerator;
c->pix_fmt = AV_PIX_FMT_YUVJ420P;
if(oc->oformat->flags & AVFMT_GLOBALHEADER)
{
c->flags |= CODEC_FLAG_GLOBAL_HEADER;
}
/* open it */
if (avcodec_open2(c, codec, NULL) < 0) {
throwRuntimeException(env, "Could not open codec");
goto bail;
}
if(avio_open(&oc->pb, oc->filename, AVIO_FLAG_WRITE) < 0)
{
throwRuntimeException(env, "Could not open file");
goto bail;
}
pictureYUV420 = avcodec_alloc_frame();
int ret = av_image_alloc(pictureYUV420->data, pictureYUV420->linesize, c->width, c->height,
c->pix_fmt, 32);
if (ret < 0) {
throwRuntimeException(env, "could not alloc raw picture buffer\n");
goto bail;
}
pictureYUV420->format = c->pix_fmt;
pictureYUV420->width = c->width;
pictureYUV420->height = c->height;
pictureUYVY = avcodec_alloc_frame();
pictureUYVY->width = c->width;
pictureUYVY->height = c->height;
pictureUYVY->format = AV_PIX_FMT_UYVY422;
img_convert_ctx = sws_getContext(c->width, c->height,
AV_PIX_FMT_UYVY422,
c->width, c->height,
c->pix_fmt,
sws_flags, NULL, NULL, NULL);
avformat_write_header(oc, NULL);
result = decklinkInput->EnableVideoInput(mode->GetDisplayMode(), pixelFormat, bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection);
if (result != S_OK)
{
throwRuntimeException(env, "Failed to switch to new video mode");
goto bail;
}
decklinkInput->StartStreams();
}
bail:
std::cout << "Detected new mode " << mode->GetWidth() << "x" << mode->GetHeight() << std::endl;
return S_OK;
}
void DeckLinkCaptureDelegate::Stop()
{
decklinkInput->StopStreams();
decklinkInput->DisableVideoInput();
if (decklinkInput != NULL)
{
decklinkInput->Release();
decklinkInput = NULL;
}
if (decklink != NULL)
{
decklink->Release();
decklink = NULL;
}
releaseEnv(vm);
avcodec_close(c);
av_free(c);
av_freep(&pictureYUV420->data[0]);
avcodec_free_frame(&pictureYUV420);
av_write_trailer(oc);
avio_close(oc->pb);
}
JNIEXPORT void JNICALL Java_us_ihmc_javadecklink_Capture_stopCaptureNative
(JNIEnv *, jobject, jlong delegatePtr)
{
DeckLinkCaptureDelegate* delegate = (DeckLinkCaptureDelegate*) delegatePtr;
delegate->Stop();
}
JNIEXPORT jlong JNICALL Java_us_ihmc_javadecklink_Capture_startCaptureNative
(JNIEnv *env, jobject obj, jint idx, jint displayModeId)
{
IDeckLinkIterator* deckLinkIterator = NULL;
IDeckLink* deckLink = NULL;
IDeckLinkDisplayModeIterator* displayModeIterator = NULL;
IDeckLinkDisplayMode* displayMode = NULL;
char* displayModeName = NULL;
BMDDisplayModeSupport displayModeSupported;
DeckLinkCaptureDelegate* delegate = NULL;
HRESULT result;
IDeckLinkInput* g_deckLinkInput = NULL;
JavaVM* vm;
JNIassert(env, env->GetJavaVM(&vm) == 0);
// Get the DeckLink device
deckLinkIterator = CreateDeckLinkIteratorInstance();
if (!deckLinkIterator)
{
fprintf(stderr, "This application requires the DeckLink drivers installed.\n");
goto bail;
}
while ((result = deckLinkIterator->Next(&deckLink)) == S_OK)
{
if (idx == 0)
break;
--idx;
deckLink->Release();
}
if (result != S_OK || deckLink == NULL)
{
fprintf(stderr, "Unable to get DeckLink device %u\n", idx);
goto bail;
}
// Get the input (capture) interface of the DeckLink device
result = deckLink->QueryInterface(IID_IDeckLinkInput, (void**)&g_deckLinkInput);
if (result != S_OK)
goto bail;
result = g_deckLinkInput->GetDisplayModeIterator(&displayModeIterator);
if (result != S_OK)
goto bail;
displayModeId = 0;
while ((result = displayModeIterator->Next(&displayMode)) == S_OK)
{
if (displayModeId == 0)
break;
--displayModeId;
displayMode->Release();
}
if (result != S_OK || displayMode == NULL)
{
fprintf(stderr, "Unable to get display mode %d\n", displayModeId);
goto bail;
}
// Get display mode name
result = displayMode->GetName((const char**)&displayModeName);
if (result != S_OK)
{
displayModeName = (char *)malloc(32);
snprintf(displayModeName, 32, "[index %d]", displayModeId);
}
// Check display mode is supported with given options
result = g_deckLinkInput->DoesSupportVideoMode(displayMode->GetDisplayMode(), bmdFormat8BitYUV, bmdVideoInputFlagDefault, &displayModeSupported, NULL);
if (result != S_OK)
goto bail;
if (displayModeSupported == bmdDisplayModeNotSupported)
{
fprintf(stderr, "The display mode %s is not supported with the selected pixel format\n", displayModeName);
goto bail;
}
// Configure the capture callback
delegate = new DeckLinkCaptureDelegate(deckLink, g_deckLinkInput, vm);
g_deckLinkInput->SetCallback(delegate);
// Start capturing
result = g_deckLinkInput->EnableVideoInput(displayMode->GetDisplayMode(), bmdFormat8BitYUV, bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection);
if (result != S_OK)
{
fprintf(stderr, "Failed to enable video input. Is another application using the card?\n");
goto bail;
}
result = g_deckLinkInput->StartStreams();
if (result != S_OK)
goto bail;
bail:
if (displayModeName != NULL)
free(displayModeName);
if (displayMode != NULL)
displayMode->Release();
if (displayModeIterator != NULL)
displayModeIterator->Release();
if (deckLinkIterator != NULL)
deckLinkIterator->Release();
return (jlong) delegate;
}
<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include <chrono>
#include "OSPRayFixture.h"
#include "commandline/Utility.h"
#include "pico_bench/pico_bench.h"
using std::cout;
using std::endl;
using std::string;
// NOTE(jda) - Implement make_unique() as it didn't show up until C++14...
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique(Args&& ...args)
{
return std::unique_ptr<T>(new T( std::forward<Args>(args)... ));
}
void printUsageAndExit()
{
cout << "Usage: ospBenchmark [options] model_file" << endl;
cout << endl << "Args:" << endl;
cout << endl;
cout << " model_file --> Scene used for benchmarking, supported types"
<< " are:" << endl;
cout << " stl, msg, tri, xml, obj, hbp, x3d" << endl;
cout << endl;
cout << "Options:" << endl;
cout << endl;
cout << "**generic rendering options**" << endl;
cout << endl;
cout << " -i | --image --> Specify the base filename to write the"
<< " framebuffer to a file." << endl;
cout << " If ommitted, no file will be written." << endl;
cout << " NOTE: this option adds '.ppm' to the end of the"
<< " filename" << endl;
cout << endl;
cout << " -w | --width --> Specify the width of the benchmark frame"
<< endl;
cout << " default: 1024" << endl;
cout << endl;
cout << " -h | --height --> Specify the height of the benchmark frame"
<< endl;
cout << " default: 1024" << endl;
cout << endl;
cout << " -r | --renderer --> Specify the renderer to be benchmarked."
<< endl;
cout << " Ex: -r pathtracer" << endl;
cout << " default: ao1" << endl;
cout << endl;
cout << " -bg | --background --> Specify the background color: R G B"
<< endl;
cout << endl;
cout << " -wf | --warmup --> Specify the number of warmup frames: N"
<< endl;
cout << " default: 10" << endl;
cout << endl;
cout << " -bf | --bench --> Specify the number of benchmark frames: N"
<< endl;
cout << " default: 100" << endl;
cout << endl;
cout << " -lft | --log-frame-times --> Log frame time in ms for every frame rendered"
<< endl;
cout << endl;
cout << "**camera rendering options**" << endl;
cout << endl;
cout << " -vp | --eye --> Specify the camera eye as: ex ey ez " << endl;
cout << endl;
cout << " -vi | --gaze --> Specify the camera gaze point as: ix iy iz "
<< endl;
cout << endl;
cout << " -vu | --up --> Specify the camera up as: ux uy uz " << endl;
cout << endl;
cout << "**volume rendering options**" << endl;
cout << endl;
cout << " -s | --sampling-rate --> Specify the sampling rate for volumes."
<< endl;
cout << " default: 0.125" << endl;
cout << endl;
cout << " -dr | --data-range --> Specify the data range for volumes."
<< " If not specified, then the min and max data" << endl
<< " values will be used when reading the data into memory." << endl;
cout << " Format: low high" << endl;
cout << endl;
cout << " -tfc | --tf-color --> Specify the next color to in the transfer"
<< " function for volumes. Each entry will add to the total list of"
<< " colors in the order they are specified." << endl;
cout << " Format: R G B A" << endl;
cout << " Value Range: [0,1]" << endl;
cout << " -tfs | --tf-scale --> Specify the opacity the transfer function"
<< " will scale to: [0,x] where x is the input value." << endl;
cout << " default: 1.0" << endl;
cout << " -tff | --tf-file --> Specify the transfer function file to use"
<< endl;
cout << endl;
cout << " -is | --surface --> Specify an isosurface at value: val "
<< endl;
cout << endl;
cout << " --help --> Print this help text" << endl;
exit(0);
}
void parseCommandLine(int argc, const char *argv[])
{
if (argc <= 1) {
printUsageAndExit();
}
for (int i = 1; i < argc; ++i) {
string arg = argv[i];
if (arg == "--help") {
printUsageAndExit();
} else if (arg == "-i" || arg == "--image") {
OSPRayFixture::imageOutputFile = argv[++i];
} else if (arg == "-w" || arg == "--width") {
OSPRayFixture::width = atoi(argv[++i]);
} else if (arg == "-h" || arg == "--height") {
OSPRayFixture::height = atoi(argv[++i]);
} else if (arg == "-wf" || arg == "--warmup") {
OSPRayFixture::numWarmupFrames = atoi(argv[++i]);
} else if (arg == "-bf" || arg == "--bench") {
OSPRayFixture::numBenchFrames = atoi(argv[++i]);
} else if (arg == "-bg" || arg == "--background") {
ospcommon::vec3f &color = OSPRayFixture::bg_color;
color.x = atof(argv[++i]);
color.y = atof(argv[++i]);
color.z = atof(argv[++i]);
} else if (arg == "-lft" || arg == "--log-frame-times") {
OSPRayFixture::logFrameTimes = true;
}
}
auto ospObjs = parseWithDefaultParsers(argc, argv);
ospcommon::box3f bbox;
std::tie(bbox,
*OSPRayFixture::model,
*OSPRayFixture::renderer,
*OSPRayFixture::camera) = ospObjs;
float width = OSPRayFixture::width;
float height = OSPRayFixture::height;
auto &camera = *OSPRayFixture::camera;
camera.set("aspect", width/height);
camera.commit();
}
void allocateFixtureObjects()
{
// NOTE(jda) - Have to allocate objects here, because we can't allocate them
// statically (before ospInit) and can't in the fixture's
// constructor because they need to exist during parseCommandLine.
OSPRayFixture::renderer = make_unique<ospray::cpp::Renderer>();
OSPRayFixture::camera = make_unique<ospray::cpp::Camera>();
OSPRayFixture::model = make_unique<ospray::cpp::Model>();
OSPRayFixture::fb = make_unique<ospray::cpp::FrameBuffer>();
}
int main(int argc, const char *argv[])
{
ospInit(&argc, argv);
allocateFixtureObjects();
parseCommandLine(argc, argv);
using namespace std::chrono;
using Millis = duration<double, std::ratio<1, 1000>>;
auto bencher = pico_bench::Benchmarker<Millis>{OSPRayFixture::numBenchFrames};
OSPRayFixture fixture;
fixture.SetUp();
auto stats = bencher([&]() {
fixture.renderer->renderFrame(*fixture.fb, OSP_FB_COLOR | OSP_FB_ACCUM);
});
stats.time_suffix = "ms";
if (OSPRayFixture::logFrameTimes) {
for (size_t i = 0; i < stats.size(); ++i) {
std::cout << stats[i].count() << stats.time_suffix << "\n";
}
}
std::cout << stats << "\n";
return 0;
}
<commit_msg>Forgot to teardown fixture<commit_after>// ======================================================================== //
// Copyright 2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include <chrono>
#include "OSPRayFixture.h"
#include "commandline/Utility.h"
#include "pico_bench/pico_bench.h"
using std::cout;
using std::endl;
using std::string;
// NOTE(jda) - Implement make_unique() as it didn't show up until C++14...
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique(Args&& ...args)
{
return std::unique_ptr<T>(new T( std::forward<Args>(args)... ));
}
void printUsageAndExit()
{
cout << "Usage: ospBenchmark [options] model_file" << endl;
cout << endl << "Args:" << endl;
cout << endl;
cout << " model_file --> Scene used for benchmarking, supported types"
<< " are:" << endl;
cout << " stl, msg, tri, xml, obj, hbp, x3d" << endl;
cout << endl;
cout << "Options:" << endl;
cout << endl;
cout << "**generic rendering options**" << endl;
cout << endl;
cout << " -i | --image --> Specify the base filename to write the"
<< " framebuffer to a file." << endl;
cout << " If ommitted, no file will be written." << endl;
cout << " NOTE: this option adds '.ppm' to the end of the"
<< " filename" << endl;
cout << endl;
cout << " -w | --width --> Specify the width of the benchmark frame"
<< endl;
cout << " default: 1024" << endl;
cout << endl;
cout << " -h | --height --> Specify the height of the benchmark frame"
<< endl;
cout << " default: 1024" << endl;
cout << endl;
cout << " -r | --renderer --> Specify the renderer to be benchmarked."
<< endl;
cout << " Ex: -r pathtracer" << endl;
cout << " default: ao1" << endl;
cout << endl;
cout << " -bg | --background --> Specify the background color: R G B"
<< endl;
cout << endl;
cout << " -wf | --warmup --> Specify the number of warmup frames: N"
<< endl;
cout << " default: 10" << endl;
cout << endl;
cout << " -bf | --bench --> Specify the number of benchmark frames: N"
<< endl;
cout << " default: 100" << endl;
cout << endl;
cout << " -lft | --log-frame-times --> Log frame time in ms for every frame rendered"
<< endl;
cout << endl;
cout << "**camera rendering options**" << endl;
cout << endl;
cout << " -vp | --eye --> Specify the camera eye as: ex ey ez " << endl;
cout << endl;
cout << " -vi | --gaze --> Specify the camera gaze point as: ix iy iz "
<< endl;
cout << endl;
cout << " -vu | --up --> Specify the camera up as: ux uy uz " << endl;
cout << endl;
cout << "**volume rendering options**" << endl;
cout << endl;
cout << " -s | --sampling-rate --> Specify the sampling rate for volumes."
<< endl;
cout << " default: 0.125" << endl;
cout << endl;
cout << " -dr | --data-range --> Specify the data range for volumes."
<< " If not specified, then the min and max data" << endl
<< " values will be used when reading the data into memory." << endl;
cout << " Format: low high" << endl;
cout << endl;
cout << " -tfc | --tf-color --> Specify the next color to in the transfer"
<< " function for volumes. Each entry will add to the total list of"
<< " colors in the order they are specified." << endl;
cout << " Format: R G B A" << endl;
cout << " Value Range: [0,1]" << endl;
cout << " -tfs | --tf-scale --> Specify the opacity the transfer function"
<< " will scale to: [0,x] where x is the input value." << endl;
cout << " default: 1.0" << endl;
cout << " -tff | --tf-file --> Specify the transfer function file to use"
<< endl;
cout << endl;
cout << " -is | --surface --> Specify an isosurface at value: val "
<< endl;
cout << endl;
cout << " --help --> Print this help text" << endl;
exit(0);
}
void parseCommandLine(int argc, const char *argv[])
{
if (argc <= 1) {
printUsageAndExit();
}
for (int i = 1; i < argc; ++i) {
string arg = argv[i];
if (arg == "--help") {
printUsageAndExit();
} else if (arg == "-i" || arg == "--image") {
OSPRayFixture::imageOutputFile = argv[++i];
} else if (arg == "-w" || arg == "--width") {
OSPRayFixture::width = atoi(argv[++i]);
} else if (arg == "-h" || arg == "--height") {
OSPRayFixture::height = atoi(argv[++i]);
} else if (arg == "-wf" || arg == "--warmup") {
OSPRayFixture::numWarmupFrames = atoi(argv[++i]);
} else if (arg == "-bf" || arg == "--bench") {
OSPRayFixture::numBenchFrames = atoi(argv[++i]);
} else if (arg == "-bg" || arg == "--background") {
ospcommon::vec3f &color = OSPRayFixture::bg_color;
color.x = atof(argv[++i]);
color.y = atof(argv[++i]);
color.z = atof(argv[++i]);
} else if (arg == "-lft" || arg == "--log-frame-times") {
OSPRayFixture::logFrameTimes = true;
}
}
auto ospObjs = parseWithDefaultParsers(argc, argv);
ospcommon::box3f bbox;
std::tie(bbox,
*OSPRayFixture::model,
*OSPRayFixture::renderer,
*OSPRayFixture::camera) = ospObjs;
float width = OSPRayFixture::width;
float height = OSPRayFixture::height;
auto &camera = *OSPRayFixture::camera;
camera.set("aspect", width/height);
camera.commit();
}
void allocateFixtureObjects()
{
// NOTE(jda) - Have to allocate objects here, because we can't allocate them
// statically (before ospInit) and can't in the fixture's
// constructor because they need to exist during parseCommandLine.
OSPRayFixture::renderer = make_unique<ospray::cpp::Renderer>();
OSPRayFixture::camera = make_unique<ospray::cpp::Camera>();
OSPRayFixture::model = make_unique<ospray::cpp::Model>();
OSPRayFixture::fb = make_unique<ospray::cpp::FrameBuffer>();
}
int main(int argc, const char *argv[])
{
ospInit(&argc, argv);
allocateFixtureObjects();
parseCommandLine(argc, argv);
using namespace std::chrono;
using Millis = duration<double, std::ratio<1, 1000>>;
auto bencher = pico_bench::Benchmarker<Millis>{OSPRayFixture::numBenchFrames};
OSPRayFixture fixture;
fixture.SetUp();
auto stats = bencher([&]() {
fixture.renderer->renderFrame(*fixture.fb, OSP_FB_COLOR | OSP_FB_ACCUM);
});
stats.time_suffix = "ms";
if (OSPRayFixture::logFrameTimes) {
for (size_t i = 0; i < stats.size(); ++i) {
std::cout << stats[i].count() << stats.time_suffix << "\n";
}
}
std::cout << stats << "\n";
fixture.TearDown();
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef __SCHEME_MASTER_HPP_INCLUDED
#define __SCHEME_MASTER_HPP_INCLUDED
// Include standard headers
#include <string> // std::string
#include "s7.h"
namespace yli
{
namespace scheme
{
class SchemeMaster
{
public:
// constructor.
SchemeMaster();
// destructor.
~SchemeMaster();
std::string eval_string(const std::string& my_string) const;
private:
s7_scheme* s7;
};
}
}
#endif
<commit_msg>`SchemeMaster`: delete copy constructor and copy assignment.<commit_after>#ifndef __SCHEME_MASTER_HPP_INCLUDED
#define __SCHEME_MASTER_HPP_INCLUDED
// Include standard headers
#include <string> // std::string
#include "s7.h"
namespace yli
{
namespace scheme
{
class SchemeMaster
{
public:
// constructor.
SchemeMaster();
SchemeMaster(const SchemeMaster&) = delete; // Delete copy constructor.
SchemeMaster &operator=(const SchemeMaster&) = delete; // Delete copy assignment.
// destructor.
~SchemeMaster();
std::string eval_string(const std::string& my_string) const;
private:
s7_scheme* s7;
};
}
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: typemanager.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2004-06-04 03:09:24 $
*
* 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 _CODEMAKER_TYPEMANAGER_HXX_
#define _CODEMAKER_TYPEMANAGER_HXX_
#include "codemaker/global.hxx"
#include "registry/registry.hxx"
#include "registry/types.h"
#include <hash_map>
#include <list>
namespace typereg { class Reader; }
typedef ::std::list< Registry* > RegistryList;
#if defined( _MSC_VER ) && ( _MSC_VER < 1200 )
typedef ::std::__hash_map__
<
::rtl::OString, // Typename
RTTypeClass, // TypeClass
HashString,
EqualString,
NewAlloc
> T2TypeClassMap;
#else
typedef ::std::hash_map
<
::rtl::OString, // Typename
RTTypeClass, // TypeClass
HashString,
EqualString
> T2TypeClassMap;
#endif
struct TypeManagerImpl
{
TypeManagerImpl()
: m_refCount(0)
{}
sal_Int32 m_refCount;
};
class TypeManager
{
public:
TypeManager();
~TypeManager();
TypeManager( const TypeManager& value )
: m_pImpl( value.m_pImpl )
{
acquire();
}
TypeManager& operator = ( const TypeManager& value )
{
release();
m_pImpl = value.m_pImpl;
acquire();
return *this;
}
virtual sal_Bool isValidType(const ::rtl::OString& name) const
{ return sal_False; }
virtual RegistryKey getTypeKey(
const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const
{ return RegistryKey(); }
virtual typereg::Reader getTypeReader(
const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const = 0;
virtual RTTypeClass getTypeClass(const ::rtl::OString& name) const
{ return RT_TYPE_INVALID; }
virtual void setBase(const ::rtl::OString& base) {}
virtual ::rtl::OString getBase() const { return ::rtl::OString(); }
virtual sal_Int32 getSize() const { return 0; }
static sal_Bool isBaseType(const ::rtl::OString& name);
protected:
sal_Int32 acquire();
sal_Int32 release();
protected:
TypeManagerImpl* m_pImpl;
};
struct RegistryTypeManagerImpl
{
RegistryTypeManagerImpl()
: m_base("/")
{}
T2TypeClassMap m_t2TypeClass;
RegistryList m_registries;
RegistryList m_extra_registries;
::rtl::OString m_base;
};
class RegistryTypeManager : public TypeManager
{
public:
RegistryTypeManager();
~RegistryTypeManager();
RegistryTypeManager( const RegistryTypeManager& value )
: TypeManager(value)
, m_pImpl( value.m_pImpl )
{
acquire();
}
sal_Bool init(const StringVector& regFiles, const StringVector& extraFiles = StringVector() );
sal_Bool isValidType(const ::rtl::OString& name) const
{ return searchTypeKey(name, 0).isValid(); }
RegistryKey getTypeKey(
const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const
{ return searchTypeKey(name, pIsExtraType); }
typereg::Reader getTypeReader(
const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const;
RTTypeClass getTypeClass(const ::rtl::OString& name) const;
void setBase(const ::rtl::OString& base);
::rtl::OString getBase() const { return m_pImpl->m_base; }
sal_Int32 getSize() const { return m_pImpl->m_t2TypeClass.size(); }
protected:
RegistryKey searchTypeKey(
const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const;
void freeRegistries();
void acquire();
void release();
protected:
RegistryTypeManagerImpl* m_pImpl;
};
#endif // _CODEMAKER_TYPEMANAGER_HXX_
<commit_msg>INTEGRATION: CWS sdksample (1.6.14); FILE MERGED 2004/07/05 11:01:51 jsc 1.6.14.1: #i30954# use registry keys directly instead of typenames<commit_after>/*************************************************************************
*
* $RCSfile: typemanager.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-01-31 15:27:21 $
*
* 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 _CODEMAKER_TYPEMANAGER_HXX_
#define _CODEMAKER_TYPEMANAGER_HXX_
#include "codemaker/global.hxx"
#include "registry/registry.hxx"
#include "registry/types.h"
#include <hash_map>
#include <list>
namespace typereg { class Reader; }
//typedef ::std::list< Registry* > RegistryList;
typedef ::std::vector< Registry* > RegistryList;
typedef ::std::pair< RegistryKey, sal_Bool > KeyPair;
typedef ::std::vector< KeyPair > RegistryKeyList;
#if defined( _MSC_VER ) && ( _MSC_VER < 1200 )
typedef ::std::__hash_map__
<
::rtl::OString, // Typename
RTTypeClass, // TypeClass
HashString,
EqualString,
NewAlloc
> T2TypeClassMap;
#else
typedef ::std::hash_map
<
::rtl::OString, // Typename
RTTypeClass, // TypeClass
HashString,
EqualString
> T2TypeClassMap;
#endif
struct TypeManagerImpl
{
TypeManagerImpl()
: m_refCount(0)
{}
sal_Int32 m_refCount;
};
class TypeManager
{
public:
TypeManager();
~TypeManager();
TypeManager( const TypeManager& value )
: m_pImpl( value.m_pImpl )
{
acquire();
}
TypeManager& operator = ( const TypeManager& value )
{
release();
m_pImpl = value.m_pImpl;
acquire();
return *this;
}
virtual sal_Bool isValidType(const ::rtl::OString& name) const
{ return sal_False; }
virtual ::rtl::OString getTypeName(RegistryKey& rTypeKey) const
{ return ::rtl::OString(); }
virtual RegistryKey getTypeKey(
const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const
{ return RegistryKey(); }
virtual RegistryKeyList getTypeKeys(const ::rtl::OString& name) const
{ return RegistryKeyList(); }
virtual typereg::Reader getTypeReader(
const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const = 0;
virtual typereg::Reader getTypeReader(RegistryKey& rTypeKey) const = 0;
virtual RTTypeClass getTypeClass(const ::rtl::OString& name) const
{ return RT_TYPE_INVALID; }
virtual RTTypeClass getTypeClass(RegistryKey& rTypeKey) const
{ return RT_TYPE_INVALID; }
virtual void setBase(const ::rtl::OString& base) {}
virtual ::rtl::OString getBase() const { return ::rtl::OString(); }
virtual sal_Int32 getSize() const { return 0; }
static sal_Bool isBaseType(const ::rtl::OString& name);
protected:
sal_Int32 acquire();
sal_Int32 release();
protected:
TypeManagerImpl* m_pImpl;
};
struct RegistryTypeManagerImpl
{
RegistryTypeManagerImpl()
: m_base("/")
{}
T2TypeClassMap m_t2TypeClass;
RegistryList m_registries;
RegistryList m_extra_registries;
::rtl::OString m_base;
};
class RegistryTypeManager : public TypeManager
{
public:
RegistryTypeManager();
~RegistryTypeManager();
RegistryTypeManager( const RegistryTypeManager& value )
: TypeManager(value)
, m_pImpl( value.m_pImpl )
{
acquire();
}
sal_Bool init(const StringVector& regFiles, const StringVector& extraFiles = StringVector() );
::rtl::OString getTypeName(RegistryKey& rTypeKey) const;
sal_Bool isValidType(const ::rtl::OString& name) const
{ return searchTypeKey(name, 0).isValid(); }
RegistryKey getTypeKey(
const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const
{ return searchTypeKey(name, pIsExtraType); }
RegistryKeyList getTypeKeys(const ::rtl::OString& name) const;
typereg::Reader getTypeReader(
const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const;
typereg::Reader getTypeReader(RegistryKey& rTypeKey) const;
RTTypeClass getTypeClass(const ::rtl::OString& name) const;
RTTypeClass getTypeClass(RegistryKey& rTypeKey) const;
void setBase(const ::rtl::OString& base);
::rtl::OString getBase() const { return m_pImpl->m_base; }
sal_Int32 getSize() const { return m_pImpl->m_t2TypeClass.size(); }
protected:
RegistryKey searchTypeKey(
const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const;
void freeRegistries();
void acquire();
void release();
protected:
RegistryTypeManagerImpl* m_pImpl;
};
#endif // _CODEMAKER_TYPEMANAGER_HXX_
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: javatype.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2004-06-04 03:14:13 $
*
* 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 INCLUDED_codemaker_source_javamaker_javatype_hxx
#define INCLUDED_codemaker_source_javamaker_javatype_hxx
namespace codemaker { class GeneratedTypeSet; }
namespace rtl { class OString; }
class JavaOptions;
class TypeManager;
bool produceType(
rtl::OString const & type, TypeManager & manager,
codemaker::GeneratedTypeSet & generated, JavaOptions * options);
#endif
<commit_msg>INTEGRATION: CWS sdksample (1.4.14); FILE MERGED 2004/07/05 11:02:56 jsc 1.4.14.1: #i30954# use registry keys directly instead of typenames<commit_after>/*************************************************************************
*
* $RCSfile: javatype.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-01-31 15:30:05 $
*
* 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 INCLUDED_codemaker_source_javamaker_javatype_hxx
#define INCLUDED_codemaker_source_javamaker_javatype_hxx
namespace codemaker { class GeneratedTypeSet; }
namespace rtl { class OString; }
class JavaOptions;
class TypeManager;
class RegistryKey;
bool produceType(
rtl::OString const & type, TypeManager const & manager,
codemaker::GeneratedTypeSet & generated, JavaOptions * pOptions);
bool produceType(RegistryKey& typeName, bool bIsExtraType, TypeManager const & typeMgr,
codemaker::GeneratedTypeSet & generated,
JavaOptions* pOptions);
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "test-harness.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#include <map>
#include <cstring>
#include <testcase.h>
namespace TestHarness
{
typedef std::map<int, TestCase> RunningTestCases;
namespace
{
const char* RED_COLOR="\e[1;31m";
const char* GREEN_COLOR="\e[1;32m";
const char* ASCII_RESET="\e[0m";
const char* ASCII_BOLD="\e[1m";
}
int RunTestCase( struct ::testcase_s& testCase )
{
int result = EXIT_STATUS_TESTCASE_FAILED;
// dont want to catch exception as we want to be able to get
// gdb stack trace from the first error
// by default tests should all always pass with no exceptions
if( testCase.startup )
{
testCase.startup();
}
result = testCase.function();
if( testCase.cleanup )
{
testCase.cleanup();
}
return result;
}
int RunTestCaseInChildProcess( struct ::testcase_s& testCase, bool suppressOutput )
{
int testResult = EXIT_STATUS_TESTCASE_FAILED;
int pid = fork();
if( pid == 0 ) // Child process
{
if( suppressOutput )
{
close(STDOUT_FILENO);
close(STDERR_FILENO);
}
exit( RunTestCase( testCase ) );
}
else if(pid == -1)
{
perror("fork");
exit(EXIT_STATUS_FORK_FAILED);
}
else // Parent process
{
int status = 0;
int childPid = waitpid(-1, &status, 0);
if( childPid == -1 )
{
perror("waitpid");
exit(EXIT_STATUS_WAITPID_FAILED);
}
if( WIFEXITED(status) )
{
if( childPid > 0 )
{
testResult = WEXITSTATUS(status);
if( testResult )
{
printf("Test case %s failed: %d\n", testCase.name, testResult);
}
}
}
else if(WIFSIGNALED(status) )
{
testResult = EXIT_STATUS_TESTCASE_ABORTED;
#ifdef WCOREDUMP
if(WCOREDUMP(status))
{
printf("Test case %s crashed\n", testCase.name);
}
#endif
printf("Test case %s exited with signal %s\n", testCase.name, strsignal(WTERMSIG(status)));
}
else if(WIFSTOPPED(status))
{
printf("Test case %s stopped with signal %s\n", testCase.name, strsignal(WSTOPSIG(status)));
}
}
return testResult;
}
void OutputStatistics( int numPasses, int numFailures )
{
const char* failureColor = GREEN_COLOR;
if( numFailures > 0 )
{
failureColor = RED_COLOR;
}
printf("\rNumber of test passes: %s%4d (%5.2f%%)%s\n", ASCII_BOLD, numPasses, 100.0f * (float)numPasses / (numPasses+numFailures), ASCII_RESET);
printf("%sNumber of test failures:%s %s%4d%s\n", failureColor, ASCII_RESET, ASCII_BOLD, numFailures, ASCII_RESET);
}
int RunAll(const char* processName, ::testcase tc_array[], bool reRunFailed)
{
int numFailures = 0;
int numPasses = 0;
// Run test cases in child process( to kill output/handle signals ), but run serially.
for( unsigned int i=0; tc_array[i].name; i++)
{
int result = RunTestCaseInChildProcess( tc_array[i], true );
if( result == 0 )
{
numPasses++;
}
else
{
numFailures++;
}
}
OutputStatistics(numPasses, numFailures);
return numFailures;
}
// Constantly runs up to MAX_NUM_CHILDREN processes
int RunAllInParallel( const char* processName, ::testcase tc_array[], bool reRunFailed)
{
int numFailures = 0;
int numPasses = 0;
RunningTestCases children;
std::vector<int> failedTestCases;
// Fork up to MAX_NUM_CHILDREN processes, then
// wait. As soon as a proc completes, fork the next.
int nextTestCase = 0;
int numRunningChildren = 0;
while( tc_array[nextTestCase].name || numRunningChildren > 0)
{
// Create more children (up to the max number or til the end of the array)
while( numRunningChildren < MAX_NUM_CHILDREN && tc_array[nextTestCase].name )
{
int pid = fork();
if( pid == 0 ) // Child process
{
close(STDOUT_FILENO);
close(STDERR_FILENO);
exit( RunTestCase( tc_array[nextTestCase] ) );
}
else if(pid == -1)
{
perror("fork");
exit(EXIT_STATUS_FORK_FAILED);
}
else // Parent process
{
TestCase tc(nextTestCase, tc_array[nextTestCase].name);
children[pid] = tc;
nextTestCase++;
numRunningChildren++;
}
}
// Wait for the next child to finish
int status=0;
int childPid = waitpid(-1, &status, 0);
if( childPid == -1 )
{
perror("waitpid");
exit(EXIT_STATUS_WAITPID_FAILED);
}
if( WIFEXITED(status) )
{
if( childPid > 0 )
{
int testResult = WEXITSTATUS(status);
if( testResult )
{
printf("Test case %s failed: %d\n", children[childPid].testCaseName, testResult);
failedTestCases.push_back(children[childPid].testCase);
numFailures++;
}
else
{
numPasses++;
}
numRunningChildren--;
}
}
else if( WIFSIGNALED(status) || WIFSTOPPED(status))
{
status = WIFSIGNALED(status)?WTERMSIG(status):WSTOPSIG(status);
if( childPid > 0 )
{
RunningTestCases::iterator iter = children.find(childPid);
if( iter != children.end() )
{
printf("Test case %s exited with signal %s\n", iter->second.testCaseName, strsignal(status));
failedTestCases.push_back(iter->second.testCase);
}
else
{
printf("Unknown child process: %d signaled %s\n", childPid, strsignal(status));
}
numFailures++;
numRunningChildren--;
}
}
}
OutputStatistics( numPasses, numFailures );
if( reRunFailed )
{
for( unsigned int i=0; i<failedTestCases.size(); i++)
{
char* testCaseStrapline;
int numChars = asprintf(&testCaseStrapline, "Test case %s", tc_array[failedTestCases[i]].name );
printf("\n%s\n", testCaseStrapline);
for(int j=0; j<numChars; j++)
{
printf("=");
}
printf("\n");
RunTestCaseInChildProcess( tc_array[failedTestCases[i] ], false );
}
}
return numFailures;
}
int FindAndRunTestCase(::testcase tc_array[], const char* testCaseName)
{
int result = EXIT_STATUS_TESTCASE_NOT_FOUND;
for( int i = 0; tc_array[i].name; i++ )
{
if( !strcmp(testCaseName, tc_array[i].name) )
{
return RunTestCase( tc_array[i] );
}
}
printf("Unknown testcase name: \"%s\"\n", testCaseName);
return result;
}
void Usage(const char* program)
{
printf("Usage: \n"
" %s <testcase name>\t\t Execute a test case\n"
" %s \t\t Execute all test cases in parallel\n"
" %s -r\t\t Execute all test cases in parallel, rerunning failed test cases\n",
program, program, program);
}
} // namespace
<commit_msg>Harmonize test failures<commit_after>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "test-harness.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#include <map>
#include <cstring>
#include <testcase.h>
namespace TestHarness
{
typedef std::map<int, TestCase> RunningTestCases;
namespace
{
const char* RED_COLOR="\e[1;31m";
const char* GREEN_COLOR="\e[1;32m";
const char* ASCII_RESET="\e[0m";
const char* ASCII_BOLD="\e[1m";
}
int RunTestCase( struct ::testcase_s& testCase )
{
int result = EXIT_STATUS_TESTCASE_FAILED;
// dont want to catch exception as we want to be able to get
// gdb stack trace from the first error
// by default tests should all always pass with no exceptions
if( testCase.startup )
{
testCase.startup();
}
result = testCase.function();
if( testCase.cleanup )
{
testCase.cleanup();
}
return result;
}
int RunTestCaseInChildProcess( struct ::testcase_s& testCase, bool suppressOutput )
{
int testResult = EXIT_STATUS_TESTCASE_FAILED;
int pid = fork();
if( pid == 0 ) // Child process
{
if( suppressOutput )
{
close(STDOUT_FILENO);
close(STDERR_FILENO);
}
exit( RunTestCase( testCase ) );
}
else if(pid == -1)
{
perror("fork");
exit(EXIT_STATUS_FORK_FAILED);
}
else // Parent process
{
int status = 0;
int childPid = waitpid(-1, &status, 0);
if( childPid == -1 )
{
perror("waitpid");
exit(EXIT_STATUS_WAITPID_FAILED);
}
if( WIFEXITED(status) )
{
if( childPid > 0 )
{
testResult = WEXITSTATUS(status);
if( testResult )
{
printf("Test case %s failed: %d\n", testCase.name, testResult);
}
}
}
else if(WIFSIGNALED(status) )
{
testResult = EXIT_STATUS_TESTCASE_ABORTED;
#ifdef WCOREDUMP
if(WCOREDUMP(status))
{
printf("Test case %s failed: due to a crash\n", testCase.name);
}
#endif
printf("Test case %s failed: exit with signal %s\n", testCase.name, strsignal(WTERMSIG(status)));
}
else if(WIFSTOPPED(status))
{
printf("Test case %s failed: stopped with signal %s\n", testCase.name, strsignal(WSTOPSIG(status)));
}
}
return testResult;
}
void OutputStatistics( int numPasses, int numFailures )
{
const char* failureColor = GREEN_COLOR;
if( numFailures > 0 )
{
failureColor = RED_COLOR;
}
printf("\rNumber of test passes: %s%4d (%5.2f%%)%s\n", ASCII_BOLD, numPasses, 100.0f * (float)numPasses / (numPasses+numFailures), ASCII_RESET);
printf("%sNumber of test failures:%s %s%4d%s\n", failureColor, ASCII_RESET, ASCII_BOLD, numFailures, ASCII_RESET);
}
int RunAll(const char* processName, ::testcase tc_array[], bool reRunFailed)
{
int numFailures = 0;
int numPasses = 0;
// Run test cases in child process( to kill output/handle signals ), but run serially.
for( unsigned int i=0; tc_array[i].name; i++)
{
int result = RunTestCaseInChildProcess( tc_array[i], true );
if( result == 0 )
{
numPasses++;
}
else
{
numFailures++;
}
}
OutputStatistics(numPasses, numFailures);
return numFailures;
}
// Constantly runs up to MAX_NUM_CHILDREN processes
int RunAllInParallel( const char* processName, ::testcase tc_array[], bool reRunFailed)
{
int numFailures = 0;
int numPasses = 0;
RunningTestCases children;
std::vector<int> failedTestCases;
// Fork up to MAX_NUM_CHILDREN processes, then
// wait. As soon as a proc completes, fork the next.
int nextTestCase = 0;
int numRunningChildren = 0;
while( tc_array[nextTestCase].name || numRunningChildren > 0)
{
// Create more children (up to the max number or til the end of the array)
while( numRunningChildren < MAX_NUM_CHILDREN && tc_array[nextTestCase].name )
{
int pid = fork();
if( pid == 0 ) // Child process
{
close(STDOUT_FILENO);
close(STDERR_FILENO);
exit( RunTestCase( tc_array[nextTestCase] ) );
}
else if(pid == -1)
{
perror("fork");
exit(EXIT_STATUS_FORK_FAILED);
}
else // Parent process
{
TestCase tc(nextTestCase, tc_array[nextTestCase].name);
children[pid] = tc;
nextTestCase++;
numRunningChildren++;
}
}
// Wait for the next child to finish
int status=0;
int childPid = waitpid(-1, &status, 0);
if( childPid == -1 )
{
perror("waitpid");
exit(EXIT_STATUS_WAITPID_FAILED);
}
if( WIFEXITED(status) )
{
if( childPid > 0 )
{
int testResult = WEXITSTATUS(status);
if( testResult )
{
printf("Test case %s failed: %d\n", children[childPid].testCaseName, testResult);
failedTestCases.push_back(children[childPid].testCase);
numFailures++;
}
else
{
numPasses++;
}
numRunningChildren--;
}
}
else if( WIFSIGNALED(status) || WIFSTOPPED(status))
{
status = WIFSIGNALED(status)?WTERMSIG(status):WSTOPSIG(status);
if( childPid > 0 )
{
RunningTestCases::iterator iter = children.find(childPid);
if( iter != children.end() )
{
printf("Test case %s exited with signal %s\n", iter->second.testCaseName, strsignal(status));
failedTestCases.push_back(iter->second.testCase);
}
else
{
printf("Unknown child process: %d signaled %s\n", childPid, strsignal(status));
}
numFailures++;
numRunningChildren--;
}
}
}
OutputStatistics( numPasses, numFailures );
if( reRunFailed )
{
for( unsigned int i=0; i<failedTestCases.size(); i++)
{
char* testCaseStrapline;
int numChars = asprintf(&testCaseStrapline, "Test case %s", tc_array[failedTestCases[i]].name );
printf("\n%s\n", testCaseStrapline);
for(int j=0; j<numChars; j++)
{
printf("=");
}
printf("\n");
RunTestCaseInChildProcess( tc_array[failedTestCases[i] ], false );
}
}
return numFailures;
}
int FindAndRunTestCase(::testcase tc_array[], const char* testCaseName)
{
int result = EXIT_STATUS_TESTCASE_NOT_FOUND;
for( int i = 0; tc_array[i].name; i++ )
{
if( !strcmp(testCaseName, tc_array[i].name) )
{
return RunTestCase( tc_array[i] );
}
}
printf("Unknown testcase name: \"%s\"\n", testCaseName);
return result;
}
void Usage(const char* program)
{
printf("Usage: \n"
" %s <testcase name>\t\t Execute a test case\n"
" %s \t\t Execute all test cases in parallel\n"
" %s -r\t\t Execute all test cases in parallel, rerunning failed test cases\n",
program, program, program);
}
} // namespace
<|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 "app/resource_bundle.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/status_icons/status_icon_gtk.h"
#include "chrome/browser/gtk/status_icons/status_tray_gtk.h"
#include "grit/browser_resources.h"
#include "grit/theme_resources.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class MockStatusIconObserver : public StatusIcon::Observer {
public:
MOCK_METHOD0(OnClicked, void());
};
TEST(StatusTrayGtkTest, CreateTray) {
// Just tests creation/destruction.
StatusTrayGtk tray;
}
TEST(StatusTrayGtkTest, CreateIcon) {
// Create an icon, set the images and tooltip, then shut it down.
StatusTrayGtk tray;
StatusIcon* icon = tray.GetStatusIcon(ASCIIToUTF16("test"));
SkBitmap* bitmap = ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_STATUS_TRAY_ICON);
icon->SetImage(*bitmap);
icon->SetPressedImage(*bitmap);
icon->SetToolTip(ASCIIToUTF16("tool tip"));
}
TEST(StatusTrayGtkTest, ClickOnIcon) {
// Create an icon, send a fake click event, make sure observer is called.
StatusTrayGtk tray;
StatusIconGtk* icon = static_cast<StatusIconGtk*>(
tray.GetStatusIcon(ASCIIToUTF16("test")));
MockStatusIconObserver observer;
icon->AddObserver(&observer);
EXPECT_CALL(observer, OnClicked());
// Mimic a click.
icon->OnClick(NULL, icon);
icon->RemoveObserver(&observer);
}
} // namespace
<commit_msg>linux: build fix<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 "app/resource_bundle.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/status_icons/status_icon_gtk.h"
#include "chrome/browser/gtk/status_icons/status_tray_gtk.h"
#include "grit/browser_resources.h"
#include "grit/theme_resources.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class MockStatusIconObserver : public StatusIcon::Observer {
public:
MOCK_METHOD0(OnClicked, void());
};
TEST(StatusTrayGtkTest, CreateTray) {
// Just tests creation/destruction.
StatusTrayGtk tray;
}
TEST(StatusTrayGtkTest, CreateIcon) {
// Create an icon, set the images and tooltip, then shut it down.
StatusTrayGtk tray;
StatusIcon* icon = tray.GetStatusIcon(ASCIIToUTF16("test"));
SkBitmap* bitmap = ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_STATUS_TRAY_ICON);
icon->SetImage(*bitmap);
icon->SetPressedImage(*bitmap);
icon->SetToolTip(ASCIIToUTF16("tool tip"));
}
TEST(StatusTrayGtkTest, ClickOnIcon) {
// Create an icon, send a fake click event, make sure observer is called.
StatusTrayGtk tray;
StatusIconGtk* icon = static_cast<StatusIconGtk*>(
tray.GetStatusIcon(ASCIIToUTF16("test")));
MockStatusIconObserver observer;
icon->AddObserver(&observer);
EXPECT_CALL(observer, OnClicked());
// Mimic a click.
icon->OnClick(NULL);
icon->RemoveObserver(&observer);
}
} // namespace
<|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/browser/renderer_host/render_widget_host_view_gtk.h"
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <cairo/cairo.h>
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/native_web_keyboard_event.h"
#include "chrome/common/x11_util.h"
#include "chrome/browser/renderer_host/backing_store.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "third_party/WebKit/WebKit/chromium/public/gtk/WebInputEventFactory.h"
using WebKit::WebInputEventFactory;
namespace {
#include "webkit/glue/webcursor_gtk_data.h"
// This class is a simple convenience wrapper for Gtk functions. It has only
// static methods.
class RenderWidgetHostViewGtkWidget {
public:
static GtkWidget* CreateNewWidget(RenderWidgetHostViewGtk* host_view) {
GtkWidget* widget = gtk_drawing_area_new();
gtk_widget_set_double_buffered(widget, FALSE);
gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
g_signal_connect(widget, "configure-event",
G_CALLBACK(ConfigureEvent), host_view);
g_signal_connect(widget, "expose-event",
G_CALLBACK(ExposeEvent), host_view);
g_signal_connect(widget, "key-press-event",
G_CALLBACK(KeyPressReleaseEvent), host_view);
g_signal_connect(widget, "key-release-event",
G_CALLBACK(KeyPressReleaseEvent), host_view);
g_signal_connect(widget, "focus-in-event",
G_CALLBACK(FocusIn), host_view);
g_signal_connect(widget, "focus-out-event",
G_CALLBACK(FocusOut), host_view);
g_signal_connect(widget, "button-press-event",
G_CALLBACK(ButtonPressReleaseEvent), host_view);
g_signal_connect(widget, "button-release-event",
G_CALLBACK(ButtonPressReleaseEvent), host_view);
g_signal_connect(widget, "motion-notify-event",
G_CALLBACK(MouseMoveEvent), host_view);
g_signal_connect(widget, "scroll-event",
G_CALLBACK(MouseScrollEvent), host_view);
return widget;
}
private:
static gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
RenderWidgetHostViewGtk* host_view) {
host_view->GetRenderWidgetHost()->WasResized();
return FALSE;
}
static gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
RenderWidgetHostViewGtk* host_view) {
const gfx::Rect damage_rect(expose->area);
host_view->Paint(damage_rect);
return FALSE;
}
static gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
RenderWidgetHostViewGtk* host_view) {
NativeWebKeyboardEvent wke(event);
host_view->GetRenderWidgetHost()->ForwardKeyboardEvent(wke);
// We return TRUE because we did handle the event. If it turns out webkit
// can't handle the event, we'll deal with it in
// RenderView::UnhandledKeyboardEvent().
return TRUE;
}
static gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
RenderWidgetHostViewGtk* host_view) {
host_view->GetRenderWidgetHost()->Focus();
return FALSE;
}
static gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
RenderWidgetHostViewGtk* host_view) {
// Whenever we lose focus, set the cursor back to that of our parent window,
// which should be the default arrow.
gdk_window_set_cursor(widget->window, NULL);
host_view->GetRenderWidgetHost()->Blur();
return FALSE;
}
static gboolean ButtonPressReleaseEvent(
GtkWidget* widget, GdkEventButton* event,
RenderWidgetHostViewGtk* host_view) {
host_view->GetRenderWidgetHost()->ForwardMouseEvent(
WebInputEventFactory::mouseEvent(event));
// TODO(evanm): why is this necessary here but not in test shell?
// This logic is the same as GtkButton.
if (event->type == GDK_BUTTON_PRESS && !GTK_WIDGET_HAS_FOCUS(widget))
gtk_widget_grab_focus(widget);
return FALSE;
}
static gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
RenderWidgetHostViewGtk* host_view) {
host_view->GetRenderWidgetHost()->ForwardMouseEvent(
WebInputEventFactory::mouseEvent(event));
return FALSE;
}
static gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
RenderWidgetHostViewGtk* host_view) {
host_view->GetRenderWidgetHost()->ForwardWheelEvent(
WebInputEventFactory::mouseWheelEvent(event));
return FALSE;
}
DISALLOW_IMPLICIT_CONSTRUCTORS(RenderWidgetHostViewGtkWidget);
};
gboolean OnPopupParentFocusOut(GtkWidget* parent, GdkEventFocus* focus,
RenderWidgetHost* host) {
host->Shutdown();
return FALSE;
}
} // namespace
// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
RenderWidgetHost* widget) {
return new RenderWidgetHostViewGtk(widget);
}
RenderWidgetHostViewGtk::RenderWidgetHostViewGtk(RenderWidgetHost* widget_host)
: host_(widget_host),
parent_host_view_(NULL),
parent_(NULL),
popup_signal_id_(0),
activatable_(true),
is_loading_(false) {
host_->set_view(this);
}
RenderWidgetHostViewGtk::~RenderWidgetHostViewGtk() {
}
void RenderWidgetHostViewGtk::InitAsChild() {
view_.Own(RenderWidgetHostViewGtkWidget::CreateNewWidget(this));
gtk_widget_show(view_.get());
}
void RenderWidgetHostViewGtk::InitAsPopup(
RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) {
parent_host_view_ = parent_host_view;
parent_ = parent_host_view->GetPluginNativeView();
GtkWidget* popup = gtk_window_new(GTK_WINDOW_POPUP);
view_.Own(RenderWidgetHostViewGtkWidget::CreateNewWidget(this));
gtk_container_add(GTK_CONTAINER(popup), view_.get());
// If we are not activatable, we don't want to grab keyboard input,
// and webkit will manage our destruction.
if (activatable_) {
// Grab all input for the app. If a click lands outside the bounds of the
// popup, WebKit will notice and destroy us.
gtk_grab_add(view_.get());
// We also destroy ourselves if our parent loses focus.
popup_signal_id_ = g_signal_connect(parent_, "focus-out-event",
G_CALLBACK(OnPopupParentFocusOut), host_);
// Our parent widget actually keeps GTK focus within its window, but we have
// to make the webkit selection box disappear to maintain appearances.
parent_host_view->Blur();
}
gtk_window_set_default_size(GTK_WINDOW(popup),
pos.width(), pos.height());
gtk_widget_show_all(popup);
gtk_window_move(GTK_WINDOW(popup), pos.x(), pos.y());
}
void RenderWidgetHostViewGtk::DidBecomeSelected() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::WasHidden() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::SetSize(const gfx::Size& size) {
// We rely on our parent GTK container to size us.
}
gfx::NativeView RenderWidgetHostViewGtk::GetPluginNativeView() {
// TODO(port): We need to pass some widget pointer out here because the
// renderer echos it back to us when it asks for GetScreenInfo. However, we
// should probably be passing the top-level window or some such instead.
return view_.get();
}
void RenderWidgetHostViewGtk::MovePluginWindows(
const std::vector<WebPluginGeometry>& plugin_window_moves) {
if (plugin_window_moves.empty())
return;
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Focus() {
host_->Focus();
}
void RenderWidgetHostViewGtk::Blur() {
host_->Blur();
}
bool RenderWidgetHostViewGtk::HasFocus() {
NOTIMPLEMENTED();
return false;
}
void RenderWidgetHostViewGtk::Show() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Hide() {
NOTIMPLEMENTED();
}
gfx::Rect RenderWidgetHostViewGtk::GetViewBounds() const {
GtkAllocation* alloc = &view_.get()->allocation;
return gfx::Rect(alloc->x, alloc->y, alloc->width, alloc->height);
}
void RenderWidgetHostViewGtk::UpdateCursor(const WebCursor& cursor) {
// Optimize the common case, where the cursor hasn't changed.
// However, we can switch between different pixmaps, so only on the
// non-pixmap branch.
if (current_cursor_.GetCursorType() != GDK_CURSOR_IS_PIXMAP &&
current_cursor_.GetCursorType() == cursor.GetCursorType())
return;
current_cursor_ = cursor;
ShowCurrentCursor();
}
void RenderWidgetHostViewGtk::SetIsLoading(bool is_loading) {
is_loading_ = is_loading;
// Only call ShowCurrentCursor() when it will actually change the cursor.
if (current_cursor_.GetCursorType() == GDK_LAST_CURSOR)
ShowCurrentCursor();
}
void RenderWidgetHostViewGtk::IMEUpdateStatus(int control,
const gfx::Rect& caret_rect) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::DidPaintRect(const gfx::Rect& rect) {
Paint(rect);
}
void RenderWidgetHostViewGtk::DidScrollRect(const gfx::Rect& rect, int dx,
int dy) {
Paint(rect);
}
void RenderWidgetHostViewGtk::RenderViewGone() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Destroy() {
// If |parent_| is non-null, we are a popup and we must disconnect from our
// parent and destroy the popup window.
if (parent_) {
if (activatable_) {
g_signal_handler_disconnect(parent_, popup_signal_id_);
parent_host_view_->Focus();
}
gtk_widget_destroy(gtk_widget_get_parent(view_.get()));
}
// We need to disconnect ourselves from our parent widget at this time; this
// does the right thing, automatically removing ourselves from our parent
// container.
view_.Destroy();
}
void RenderWidgetHostViewGtk::SetTooltipText(const std::wstring& tooltip_text) {
if (tooltip_text.empty()) {
gtk_widget_set_has_tooltip(view_.get(), FALSE);
} else {
gtk_widget_set_tooltip_text(view_.get(), WideToUTF8(tooltip_text).c_str());
}
}
BackingStore* RenderWidgetHostViewGtk::AllocBackingStore(
const gfx::Size& size) {
Display* display = x11_util::GetXDisplay();
void* visual = x11_util::GetVisualFromGtkWidget(view_.get());
XID root_window = x11_util::GetX11RootWindow();
bool use_render = x11_util::QueryRenderSupport(display);
bool use_shared_memory = x11_util::QuerySharedMemorySupport(display);
int depth = gtk_widget_get_visual(view_.get())->depth;
return new BackingStore(size, display, depth, visual, root_window,
use_render, use_shared_memory);
}
void RenderWidgetHostViewGtk::Paint(const gfx::Rect& damage_rect) {
BackingStore* backing_store = host_->GetBackingStore();
GdkWindow* window = view_.get()->window;
if (backing_store) {
// Only render the widget if it is attached to a window; there's a short
// period where this object isn't attached to a window but hasn't been
// Destroy()ed yet and it receives paint messages...
if (window) {
backing_store->ShowRect(
damage_rect, x11_util::GetX11WindowFromGtkWidget(view_.get()));
}
} else {
if (window)
gdk_window_clear(window);
NOTIMPLEMENTED();
}
}
void RenderWidgetHostViewGtk::ShowCurrentCursor() {
GdkCursor* gdk_cursor;
switch(current_cursor_.GetCursorType()) {
case GDK_CURSOR_IS_PIXMAP:
// TODO(port): WebKit bug https://bugs.webkit.org/show_bug.cgi?id=16388 is
// that calling gdk_window_set_cursor repeatedly is expensive. We should
// avoid it here where possible.
gdk_cursor = current_cursor_.GetCustomCursor();
break;
case GDK_LAST_CURSOR:
if (is_loading_) {
// Use MOZ_CURSOR_SPINNING if we are showing the default cursor and
// the page is loading.
static const GdkColor fg = { 0, 0, 0, 0 };
static const GdkColor bg = { 65535, 65535, 65535, 65535 };
GdkPixmap* source =
gdk_bitmap_create_from_data(NULL, moz_spinning_bits, 32, 32);
GdkPixmap* mask =
gdk_bitmap_create_from_data(NULL, moz_spinning_mask_bits, 32, 32);
gdk_cursor = gdk_cursor_new_from_pixmap(source, mask, &fg, &bg, 2, 2);
g_object_unref(source);
g_object_unref(mask);
} else {
gdk_cursor = NULL;
}
break;
default:
gdk_cursor = gdk_cursor_new(current_cursor_.GetCursorType());
}
gdk_window_set_cursor(view_.get()->window, gdk_cursor);
// The window now owns the cursor.
if (gdk_cursor)
gdk_cursor_unref(gdk_cursor);
}
<commit_msg>Don't try to set the cursor on null windows.<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/browser/renderer_host/render_widget_host_view_gtk.h"
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <cairo/cairo.h>
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/native_web_keyboard_event.h"
#include "chrome/common/x11_util.h"
#include "chrome/browser/renderer_host/backing_store.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "third_party/WebKit/WebKit/chromium/public/gtk/WebInputEventFactory.h"
using WebKit::WebInputEventFactory;
namespace {
#include "webkit/glue/webcursor_gtk_data.h"
// This class is a simple convenience wrapper for Gtk functions. It has only
// static methods.
class RenderWidgetHostViewGtkWidget {
public:
static GtkWidget* CreateNewWidget(RenderWidgetHostViewGtk* host_view) {
GtkWidget* widget = gtk_drawing_area_new();
gtk_widget_set_double_buffered(widget, FALSE);
gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
g_signal_connect(widget, "configure-event",
G_CALLBACK(ConfigureEvent), host_view);
g_signal_connect(widget, "expose-event",
G_CALLBACK(ExposeEvent), host_view);
g_signal_connect(widget, "key-press-event",
G_CALLBACK(KeyPressReleaseEvent), host_view);
g_signal_connect(widget, "key-release-event",
G_CALLBACK(KeyPressReleaseEvent), host_view);
g_signal_connect(widget, "focus-in-event",
G_CALLBACK(FocusIn), host_view);
g_signal_connect(widget, "focus-out-event",
G_CALLBACK(FocusOut), host_view);
g_signal_connect(widget, "button-press-event",
G_CALLBACK(ButtonPressReleaseEvent), host_view);
g_signal_connect(widget, "button-release-event",
G_CALLBACK(ButtonPressReleaseEvent), host_view);
g_signal_connect(widget, "motion-notify-event",
G_CALLBACK(MouseMoveEvent), host_view);
g_signal_connect(widget, "scroll-event",
G_CALLBACK(MouseScrollEvent), host_view);
return widget;
}
private:
static gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
RenderWidgetHostViewGtk* host_view) {
host_view->GetRenderWidgetHost()->WasResized();
return FALSE;
}
static gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
RenderWidgetHostViewGtk* host_view) {
const gfx::Rect damage_rect(expose->area);
host_view->Paint(damage_rect);
return FALSE;
}
static gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
RenderWidgetHostViewGtk* host_view) {
NativeWebKeyboardEvent wke(event);
host_view->GetRenderWidgetHost()->ForwardKeyboardEvent(wke);
// We return TRUE because we did handle the event. If it turns out webkit
// can't handle the event, we'll deal with it in
// RenderView::UnhandledKeyboardEvent().
return TRUE;
}
static gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
RenderWidgetHostViewGtk* host_view) {
host_view->GetRenderWidgetHost()->Focus();
return FALSE;
}
static gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
RenderWidgetHostViewGtk* host_view) {
// Whenever we lose focus, set the cursor back to that of our parent window,
// which should be the default arrow.
gdk_window_set_cursor(widget->window, NULL);
host_view->GetRenderWidgetHost()->Blur();
return FALSE;
}
static gboolean ButtonPressReleaseEvent(
GtkWidget* widget, GdkEventButton* event,
RenderWidgetHostViewGtk* host_view) {
host_view->GetRenderWidgetHost()->ForwardMouseEvent(
WebInputEventFactory::mouseEvent(event));
// TODO(evanm): why is this necessary here but not in test shell?
// This logic is the same as GtkButton.
if (event->type == GDK_BUTTON_PRESS && !GTK_WIDGET_HAS_FOCUS(widget))
gtk_widget_grab_focus(widget);
return FALSE;
}
static gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
RenderWidgetHostViewGtk* host_view) {
host_view->GetRenderWidgetHost()->ForwardMouseEvent(
WebInputEventFactory::mouseEvent(event));
return FALSE;
}
static gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
RenderWidgetHostViewGtk* host_view) {
host_view->GetRenderWidgetHost()->ForwardWheelEvent(
WebInputEventFactory::mouseWheelEvent(event));
return FALSE;
}
DISALLOW_IMPLICIT_CONSTRUCTORS(RenderWidgetHostViewGtkWidget);
};
gboolean OnPopupParentFocusOut(GtkWidget* parent, GdkEventFocus* focus,
RenderWidgetHost* host) {
host->Shutdown();
return FALSE;
}
} // namespace
// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
RenderWidgetHost* widget) {
return new RenderWidgetHostViewGtk(widget);
}
RenderWidgetHostViewGtk::RenderWidgetHostViewGtk(RenderWidgetHost* widget_host)
: host_(widget_host),
parent_host_view_(NULL),
parent_(NULL),
popup_signal_id_(0),
activatable_(true),
is_loading_(false) {
host_->set_view(this);
}
RenderWidgetHostViewGtk::~RenderWidgetHostViewGtk() {
}
void RenderWidgetHostViewGtk::InitAsChild() {
view_.Own(RenderWidgetHostViewGtkWidget::CreateNewWidget(this));
gtk_widget_show(view_.get());
}
void RenderWidgetHostViewGtk::InitAsPopup(
RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) {
parent_host_view_ = parent_host_view;
parent_ = parent_host_view->GetPluginNativeView();
GtkWidget* popup = gtk_window_new(GTK_WINDOW_POPUP);
view_.Own(RenderWidgetHostViewGtkWidget::CreateNewWidget(this));
gtk_container_add(GTK_CONTAINER(popup), view_.get());
// If we are not activatable, we don't want to grab keyboard input,
// and webkit will manage our destruction.
if (activatable_) {
// Grab all input for the app. If a click lands outside the bounds of the
// popup, WebKit will notice and destroy us.
gtk_grab_add(view_.get());
// We also destroy ourselves if our parent loses focus.
popup_signal_id_ = g_signal_connect(parent_, "focus-out-event",
G_CALLBACK(OnPopupParentFocusOut), host_);
// Our parent widget actually keeps GTK focus within its window, but we have
// to make the webkit selection box disappear to maintain appearances.
parent_host_view->Blur();
}
gtk_window_set_default_size(GTK_WINDOW(popup),
pos.width(), pos.height());
gtk_widget_show_all(popup);
gtk_window_move(GTK_WINDOW(popup), pos.x(), pos.y());
}
void RenderWidgetHostViewGtk::DidBecomeSelected() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::WasHidden() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::SetSize(const gfx::Size& size) {
// We rely on our parent GTK container to size us.
}
gfx::NativeView RenderWidgetHostViewGtk::GetPluginNativeView() {
// TODO(port): We need to pass some widget pointer out here because the
// renderer echos it back to us when it asks for GetScreenInfo. However, we
// should probably be passing the top-level window or some such instead.
return view_.get();
}
void RenderWidgetHostViewGtk::MovePluginWindows(
const std::vector<WebPluginGeometry>& plugin_window_moves) {
if (plugin_window_moves.empty())
return;
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Focus() {
host_->Focus();
}
void RenderWidgetHostViewGtk::Blur() {
host_->Blur();
}
bool RenderWidgetHostViewGtk::HasFocus() {
NOTIMPLEMENTED();
return false;
}
void RenderWidgetHostViewGtk::Show() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Hide() {
NOTIMPLEMENTED();
}
gfx::Rect RenderWidgetHostViewGtk::GetViewBounds() const {
GtkAllocation* alloc = &view_.get()->allocation;
return gfx::Rect(alloc->x, alloc->y, alloc->width, alloc->height);
}
void RenderWidgetHostViewGtk::UpdateCursor(const WebCursor& cursor) {
// Optimize the common case, where the cursor hasn't changed.
// However, we can switch between different pixmaps, so only on the
// non-pixmap branch.
if (current_cursor_.GetCursorType() != GDK_CURSOR_IS_PIXMAP &&
current_cursor_.GetCursorType() == cursor.GetCursorType())
return;
current_cursor_ = cursor;
ShowCurrentCursor();
}
void RenderWidgetHostViewGtk::SetIsLoading(bool is_loading) {
is_loading_ = is_loading;
// Only call ShowCurrentCursor() when it will actually change the cursor.
if (current_cursor_.GetCursorType() == GDK_LAST_CURSOR)
ShowCurrentCursor();
}
void RenderWidgetHostViewGtk::IMEUpdateStatus(int control,
const gfx::Rect& caret_rect) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::DidPaintRect(const gfx::Rect& rect) {
Paint(rect);
}
void RenderWidgetHostViewGtk::DidScrollRect(const gfx::Rect& rect, int dx,
int dy) {
Paint(rect);
}
void RenderWidgetHostViewGtk::RenderViewGone() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Destroy() {
// If |parent_| is non-null, we are a popup and we must disconnect from our
// parent and destroy the popup window.
if (parent_) {
if (activatable_) {
g_signal_handler_disconnect(parent_, popup_signal_id_);
parent_host_view_->Focus();
}
gtk_widget_destroy(gtk_widget_get_parent(view_.get()));
}
// We need to disconnect ourselves from our parent widget at this time; this
// does the right thing, automatically removing ourselves from our parent
// container.
view_.Destroy();
}
void RenderWidgetHostViewGtk::SetTooltipText(const std::wstring& tooltip_text) {
if (tooltip_text.empty()) {
gtk_widget_set_has_tooltip(view_.get(), FALSE);
} else {
gtk_widget_set_tooltip_text(view_.get(), WideToUTF8(tooltip_text).c_str());
}
}
BackingStore* RenderWidgetHostViewGtk::AllocBackingStore(
const gfx::Size& size) {
Display* display = x11_util::GetXDisplay();
void* visual = x11_util::GetVisualFromGtkWidget(view_.get());
XID root_window = x11_util::GetX11RootWindow();
bool use_render = x11_util::QueryRenderSupport(display);
bool use_shared_memory = x11_util::QuerySharedMemorySupport(display);
int depth = gtk_widget_get_visual(view_.get())->depth;
return new BackingStore(size, display, depth, visual, root_window,
use_render, use_shared_memory);
}
void RenderWidgetHostViewGtk::Paint(const gfx::Rect& damage_rect) {
BackingStore* backing_store = host_->GetBackingStore();
GdkWindow* window = view_.get()->window;
if (backing_store) {
// Only render the widget if it is attached to a window; there's a short
// period where this object isn't attached to a window but hasn't been
// Destroy()ed yet and it receives paint messages...
if (window) {
backing_store->ShowRect(
damage_rect, x11_util::GetX11WindowFromGtkWidget(view_.get()));
}
} else {
if (window)
gdk_window_clear(window);
NOTIMPLEMENTED();
}
}
void RenderWidgetHostViewGtk::ShowCurrentCursor() {
// The widget may not have a window. If that's the case, abort mission. This
// is the same issue as that explained above in Paint().
if (!view_.get()->window)
return;
GdkCursor* gdk_cursor;
switch(current_cursor_.GetCursorType()) {
case GDK_CURSOR_IS_PIXMAP:
// TODO(port): WebKit bug https://bugs.webkit.org/show_bug.cgi?id=16388 is
// that calling gdk_window_set_cursor repeatedly is expensive. We should
// avoid it here where possible.
gdk_cursor = current_cursor_.GetCustomCursor();
break;
case GDK_LAST_CURSOR:
if (is_loading_) {
// Use MOZ_CURSOR_SPINNING if we are showing the default cursor and
// the page is loading.
static const GdkColor fg = { 0, 0, 0, 0 };
static const GdkColor bg = { 65535, 65535, 65535, 65535 };
GdkPixmap* source =
gdk_bitmap_create_from_data(NULL, moz_spinning_bits, 32, 32);
GdkPixmap* mask =
gdk_bitmap_create_from_data(NULL, moz_spinning_mask_bits, 32, 32);
gdk_cursor = gdk_cursor_new_from_pixmap(source, mask, &fg, &bg, 2, 2);
g_object_unref(source);
g_object_unref(mask);
} else {
gdk_cursor = NULL;
}
break;
default:
gdk_cursor = gdk_cursor_new(current_cursor_.GetCursorType());
}
gdk_window_set_cursor(view_.get()->window, gdk_cursor);
// The window now owns the cursor.
if (gdk_cursor)
gdk_cursor_unref(gdk_cursor);
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// boost
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
// mapnik
#include <mapnik/raster_colorizer.hpp>
using mapnik::raster_colorizer;
using mapnik::raster_colorizer_ptr;
using mapnik::colorizer_stop;
using mapnik::colorizer_stops;
using mapnik::colorizer_mode_enum;
using mapnik::color;
using mapnik::COLORIZER_INHERIT;
using mapnik::COLORIZER_LINEAR;
using mapnik::COLORIZER_DISCRETE;
using mapnik::COLORIZER_EXACT;
namespace {
void add_stop(raster_colorizer_ptr & rc, colorizer_stop & stop)
{
rc->add_stop(stop);
}
void add_stop2(raster_colorizer_ptr & rc, float v) {
colorizer_stop stop(v, rc->get_default_mode(), rc->get_default_color());
rc->add_stop(stop);
}
void add_stop3(raster_colorizer_ptr &rc, float v, color c) {
colorizer_stop stop(v, rc->get_default_mode(), c);
rc->add_stop(stop);
}
void add_stop4(raster_colorizer_ptr &rc, float v, colorizer_mode_enum m) {
colorizer_stop stop(v, m, rc->get_default_color());
rc->add_stop(stop);
}
void add_stop5(raster_colorizer_ptr &rc, float v, colorizer_mode_enum m, color c) {
colorizer_stop stop(v, m, c);
rc->add_stop(stop);
}
colorizer_stops const& get_stops(raster_colorizer_ptr & rc)
{
return rc->get_stops();
}
}
void export_raster_colorizer()
{
using namespace boost::python;
class_<raster_colorizer,raster_colorizer_ptr>("RasterColorizer",
"A Raster Colorizer object.",
init<colorizer_mode_enum, color>(args("default_mode","default_color"))
)
.def(init<>())
.add_property("default_color",
make_function(&raster_colorizer::get_default_color, return_value_policy<reference_existing_object>()),
&raster_colorizer::set_default_color,
"The default color for stops added without a color (mapnik.Color).\n")
.add_property("default_mode",
&raster_colorizer::get_default_mode_enum,
&raster_colorizer::set_default_mode_enum,
"The default mode (mapnik.ColorizerMode).\n"
"\n"
"If a stop is added without a mode, then it will inherit this default mode\n")
.add_property("stops",
make_function(get_stops,return_value_policy<reference_existing_object>()),
"The list of stops this RasterColorizer contains\n")
.add_property("epsilon",
&raster_colorizer::get_epsilon,
&raster_colorizer::set_epsilon,
"Comparison epsilon value for exact mode\n"
"\n"
"When comparing values in exact mode, values need only be within epsilon to match.\n")
.def("add_stop", add_stop,
(arg("ColorizerStop")),
"Add a colorizer stop to the raster colorizer.\n"
"\n"
"Usage:\n"
">>> colorizer = mapnik.RasterColorizer()\n"
">>> color = mapnik.Color(\"#0044cc\")\n"
">>> stop = mapnik.ColorizerStop(3, mapnik.COLORIZER_INHERIT, color)\n"
">>> colorizer.add_stop(stop)\n"
)
.def("add_stop", add_stop2,
(arg("value")),
"Add a colorizer stop to the raster colorizer, using the default mode and color.\n"
"\n"
"Usage:\n"
">>> default_color = mapnik.Color(\"#0044cc\")\n"
">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
">>> colorizer.add_stop(100)\n"
)
.def("add_stop", add_stop3,
(arg("value")),
"Add a colorizer stop to the raster colorizer, using the default mode.\n"
"\n"
"Usage:\n"
">>> default_color = mapnik.Color(\"#0044cc\")\n"
">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
">>> colorizer.add_stop(100, mapnik.Color(\"#123456\"))\n"
)
.def("add_stop", add_stop4,
(arg("value")),
"Add a colorizer stop to the raster colorizer, using the default color.\n"
"\n"
"Usage:\n"
">>> default_color = mapnik.Color(\"#0044cc\")\n"
">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
">>> colorizer.add_stop(100, mapnik.COLORIZER_EXACT)\n"
)
.def("add_stop", add_stop5,
(arg("value")),
"Add a colorizer stop to the raster colorizer.\n"
"\n"
"Usage:\n"
">>> default_color = mapnik.Color(\"#0044cc\")\n"
">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
">>> colorizer.add_stop(100, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#112233\"))\n"
)
.def("get_color", &raster_colorizer::get_color,
"Get the color assigned to a certain value in raster data.\n"
"\n"
"Usage:\n"
">>> colorizer = mapnik.RasterColorizer()\n"
">>> color = mapnik.Color(\"#0044cc\")\n"
">>> colorizer.add_stop(0, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#000000\"))\n"
">>> colorizer.add_stop(100, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#0E0A06\"))\n"
">>> colorizer.get_color(50)\n"
"Color('#070503')\n"
)
;
class_<colorizer_stops>("ColorizerStops",
"A RasterColorizer's collection of ordered color stops.\n"
"This class is not meant to be instantiated from python. However, "
"it can be accessed at a RasterColorizer's \"stops\" attribute for "
"introspection purposes",
no_init)
.def(vector_indexing_suite<colorizer_stops>())
;
enum_<colorizer_mode_enum>("ColorizerMode")
.value("COLORIZER_INHERIT", COLORIZER_INHERIT)
.value("COLORIZER_LINEAR", COLORIZER_LINEAR)
.value("COLORIZER_DISCRETE", COLORIZER_DISCRETE)
.value("COLORIZER_EXACT", COLORIZER_EXACT)
.export_values()
;
class_<colorizer_stop>("ColorizerStop",init<float, colorizer_mode_enum, color const&>(
"A Colorizer Stop object.\n"
"Create with a value, ColorizerMode, and Color\n"
"\n"
"Usage:"
">>> color = mapnik.Color(\"#fff000\")\n"
">>> stop= mapnik.ColorizerStop(42.42, mapnik.COLORIZER_LINEAR, color)\n"
))
.add_property("color",
make_function(&colorizer_stop::get_color, return_value_policy<reference_existing_object>()),
&colorizer_stop::set_color,
"The stop color (mapnik.Color).\n")
.add_property("value",
&colorizer_stop::get_value,
&colorizer_stop::set_value,
"The stop value.\n")
.add_property("label",
make_function(&colorizer_stop::get_label, return_value_policy<copy_const_reference>()),
&colorizer_stop::set_label,
"The stop label.\n")
.add_property("mode",
&colorizer_stop::get_mode_enum,
&colorizer_stop::set_mode_enum,
"The stop mode (mapnik.ColorizerMode).\n"
"\n"
"If this is COLORIZER_INHERIT then it will inherit the default mode\n"
" from the RasterColorizer it is added to.\n")
.def(self == self)
.def("__str__",&colorizer_stop::to_string)
;
}
<commit_msg>fix raster colorizer via python<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// boost
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
// mapnik
#include <mapnik/raster_colorizer.hpp>
using mapnik::raster_colorizer;
using mapnik::raster_colorizer_ptr;
using mapnik::colorizer_stop;
using mapnik::colorizer_stops;
using mapnik::colorizer_mode_enum;
using mapnik::color;
using mapnik::COLORIZER_INHERIT;
using mapnik::COLORIZER_LINEAR;
using mapnik::COLORIZER_DISCRETE;
using mapnik::COLORIZER_EXACT;
namespace {
void add_stop(raster_colorizer_ptr & rc, colorizer_stop & stop)
{
rc->add_stop(stop);
}
void add_stop2(raster_colorizer_ptr & rc, float v) {
colorizer_stop stop(v, rc->get_default_mode(), rc->get_default_color());
rc->add_stop(stop);
}
void add_stop3(raster_colorizer_ptr &rc, float v, color c) {
colorizer_stop stop(v, rc->get_default_mode(), c);
rc->add_stop(stop);
}
void add_stop4(raster_colorizer_ptr &rc, float v, colorizer_mode_enum m) {
colorizer_stop stop(v, m, rc->get_default_color());
rc->add_stop(stop);
}
void add_stop5(raster_colorizer_ptr &rc, float v, colorizer_mode_enum m, color c) {
colorizer_stop stop(v, m, c);
rc->add_stop(stop);
}
mapnik::color get_color(raster_colorizer_ptr &rc, float value) {
unsigned rgba = rc->get_color(value);
unsigned r = (rgba & 0xff);
unsigned g = (rgba >> 8 ) & 0xff;
unsigned b = (rgba >> 16) & 0xff;
unsigned a = (rgba >> 24) & 0xff;
return mapnik::color(r,g,b,a);
}
colorizer_stops const& get_stops(raster_colorizer_ptr & rc)
{
return rc->get_stops();
}
}
void export_raster_colorizer()
{
using namespace boost::python;
class_<raster_colorizer,raster_colorizer_ptr>("RasterColorizer",
"A Raster Colorizer object.",
init<colorizer_mode_enum, color>(args("default_mode","default_color"))
)
.def(init<>())
.add_property("default_color",
make_function(&raster_colorizer::get_default_color, return_value_policy<reference_existing_object>()),
&raster_colorizer::set_default_color,
"The default color for stops added without a color (mapnik.Color).\n")
.add_property("default_mode",
&raster_colorizer::get_default_mode_enum,
&raster_colorizer::set_default_mode_enum,
"The default mode (mapnik.ColorizerMode).\n"
"\n"
"If a stop is added without a mode, then it will inherit this default mode\n")
.add_property("stops",
make_function(get_stops,return_value_policy<reference_existing_object>()),
"The list of stops this RasterColorizer contains\n")
.add_property("epsilon",
&raster_colorizer::get_epsilon,
&raster_colorizer::set_epsilon,
"Comparison epsilon value for exact mode\n"
"\n"
"When comparing values in exact mode, values need only be within epsilon to match.\n")
.def("add_stop", add_stop,
(arg("ColorizerStop")),
"Add a colorizer stop to the raster colorizer.\n"
"\n"
"Usage:\n"
">>> colorizer = mapnik.RasterColorizer()\n"
">>> color = mapnik.Color(\"#0044cc\")\n"
">>> stop = mapnik.ColorizerStop(3, mapnik.COLORIZER_INHERIT, color)\n"
">>> colorizer.add_stop(stop)\n"
)
.def("add_stop", add_stop2,
(arg("value")),
"Add a colorizer stop to the raster colorizer, using the default mode and color.\n"
"\n"
"Usage:\n"
">>> default_color = mapnik.Color(\"#0044cc\")\n"
">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
">>> colorizer.add_stop(100)\n"
)
.def("add_stop", add_stop3,
(arg("value")),
"Add a colorizer stop to the raster colorizer, using the default mode.\n"
"\n"
"Usage:\n"
">>> default_color = mapnik.Color(\"#0044cc\")\n"
">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
">>> colorizer.add_stop(100, mapnik.Color(\"#123456\"))\n"
)
.def("add_stop", add_stop4,
(arg("value")),
"Add a colorizer stop to the raster colorizer, using the default color.\n"
"\n"
"Usage:\n"
">>> default_color = mapnik.Color(\"#0044cc\")\n"
">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
">>> colorizer.add_stop(100, mapnik.COLORIZER_EXACT)\n"
)
.def("add_stop", add_stop5,
(arg("value")),
"Add a colorizer stop to the raster colorizer.\n"
"\n"
"Usage:\n"
">>> default_color = mapnik.Color(\"#0044cc\")\n"
">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
">>> colorizer.add_stop(100, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#112233\"))\n"
)
.def("get_color", get_color,
"Get the color assigned to a certain value in raster data.\n"
"\n"
"Usage:\n"
">>> colorizer = mapnik.RasterColorizer()\n"
">>> color = mapnik.Color(\"#0044cc\")\n"
">>> colorizer.add_stop(0, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#000000\"))\n"
">>> colorizer.add_stop(100, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#0E0A06\"))\n"
">>> colorizer.get_color(50)\n"
"Color('#070503')\n"
)
;
class_<colorizer_stops>("ColorizerStops",
"A RasterColorizer's collection of ordered color stops.\n"
"This class is not meant to be instantiated from python. However, "
"it can be accessed at a RasterColorizer's \"stops\" attribute for "
"introspection purposes",
no_init)
.def(vector_indexing_suite<colorizer_stops>())
;
enum_<colorizer_mode_enum>("ColorizerMode")
.value("COLORIZER_INHERIT", COLORIZER_INHERIT)
.value("COLORIZER_LINEAR", COLORIZER_LINEAR)
.value("COLORIZER_DISCRETE", COLORIZER_DISCRETE)
.value("COLORIZER_EXACT", COLORIZER_EXACT)
.export_values()
;
class_<colorizer_stop>("ColorizerStop",init<float, colorizer_mode_enum, color const&>(
"A Colorizer Stop object.\n"
"Create with a value, ColorizerMode, and Color\n"
"\n"
"Usage:"
">>> color = mapnik.Color(\"#fff000\")\n"
">>> stop= mapnik.ColorizerStop(42.42, mapnik.COLORIZER_LINEAR, color)\n"
))
.add_property("color",
make_function(&colorizer_stop::get_color, return_value_policy<reference_existing_object>()),
&colorizer_stop::set_color,
"The stop color (mapnik.Color).\n")
.add_property("value",
&colorizer_stop::get_value,
&colorizer_stop::set_value,
"The stop value.\n")
.add_property("label",
make_function(&colorizer_stop::get_label, return_value_policy<copy_const_reference>()),
&colorizer_stop::set_label,
"The stop label.\n")
.add_property("mode",
&colorizer_stop::get_mode_enum,
&colorizer_stop::set_mode_enum,
"The stop mode (mapnik.ColorizerMode).\n"
"\n"
"If this is COLORIZER_INHERIT then it will inherit the default mode\n"
" from the RasterColorizer it is added to.\n")
.def(self == self)
.def("__str__",&colorizer_stop::to_string)
;
}
<|endoftext|>
|
<commit_before>/* Copyright 2009 Thomas McGuire <mcguire@kde.org>
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 ) version 3 or, at the discretion of KDE e.V.
( which shall act as a proxy as in section 14 of the GPLv3 ), any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "htmlquotecolorer.h"
#include "csshelper.h"
#include <dom/html_document.h>
#include <dom/dom_element.h>
namespace KMail {
HTMLQuoteColorer::HTMLQuoteColorer( KPIM::CSSHelper *cssHelper )
: mCSSHelper( cssHelper )
{
}
QString HTMLQuoteColorer::process( const QString &htmlSource )
{
// Create a DOM Document from the HTML source
DOM::HTMLDocument doc;
doc.open();
doc.write( htmlSource );
doc.close();
mIsQuotedLine = false;
mIsFirstTextNodeInLine = true;
processNode( doc.documentElement() );
return doc.toString().string();
}
DOM::Node HTMLQuoteColorer::processNode( DOM::Node node )
{
// Below, we determine if the current text node should be quote colored by keeping track of
// linebreaks and wether this text node is the first one.
const QString textContent = node.textContent().string();
const bool isTextNode = !textContent.isEmpty() && !node.hasChildNodes();
if ( isTextNode ) {
if ( mIsFirstTextNodeInLine ) {
if ( textContent.simplified().startsWith( '>' ) ||
textContent.simplified().startsWith( '|' ) ) {
mIsQuotedLine = true;
currentQuoteLength = quoteLength( textContent ) - 1;
}
else {
mIsQuotedLine = false;
}
}
// All subsequent text nodes are not the first ones anymore
mIsFirstTextNodeInLine = false;
}
const QString nodeName = node.nodeName().string().toLower();
QStringList lineBreakNodes;
lineBreakNodes << "br" << "p" << "div" << "ul" << "ol" << "li";
if ( lineBreakNodes.contains( nodeName ) ) {
mIsFirstTextNodeInLine = true;
}
DOM::Node returnNode = node;
bool fontTagAdded = false;
if ( mIsQuotedLine && isTextNode ) {
// Ok, we are in a line that should be quoted, so create a font node for the color and replace
// the current node with it.
DOM::Element font = node.ownerDocument().createElement( QString( "font" ) );
font.setAttribute( QString( "color" ), mCSSHelper->quoteColor( currentQuoteLength ).name() );
node.parentNode().replaceChild( font, node );
font.appendChild( node );
returnNode = font;
fontTagAdded = true;
}
// Process all child nodes, but only if we are didn't add those child nodes itself, as otherwise
// we'll go into an infinite recursion.
if ( !fontTagAdded ) {
DOM::Node childNode = node.firstChild();
while ( !childNode.isNull() ) {
childNode = processNode( childNode );
childNode = childNode.nextSibling();
}
}
return returnNode;
}
int HTMLQuoteColorer::quoteLength( const QString &line ) const
{
QString simplified = line.simplified();
simplified = simplified.replace( QRegExp( QLatin1String( "\\s" ) ), QString() )
.replace( QLatin1Char( '|' ), QLatin1Char( '>' ) );
if ( simplified.startsWith( ">>>" ) ) return 3;
if ( simplified.startsWith( ">>" ) ) return 2;
if ( simplified.startsWith( ">" ) ) return 1;
return 0;
}
}
<commit_msg>Catch DOM exceptions. This should at fix Dmitry's crash, although I couldn't reproduce it.<commit_after>/* Copyright 2009 Thomas McGuire <mcguire@kde.org>
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 ) version 3 or, at the discretion of KDE e.V.
( which shall act as a proxy as in section 14 of the GPLv3 ), any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "htmlquotecolorer.h"
#include "csshelper.h"
#include <dom/html_document.h>
#include <dom/dom_element.h>
#include <dom/dom_exception.h>
namespace KMail {
HTMLQuoteColorer::HTMLQuoteColorer( KPIM::CSSHelper *cssHelper )
: mCSSHelper( cssHelper )
{
}
QString HTMLQuoteColorer::process( const QString &htmlSource )
{
try {
// Create a DOM Document from the HTML source
DOM::HTMLDocument doc;
doc.open();
doc.write( htmlSource );
doc.close();
mIsQuotedLine = false;
mIsFirstTextNodeInLine = true;
processNode( doc.documentElement() );
return doc.toString().string();
}
catch( const DOM::DOMException &exception ) {
kWarning() << "Got a DOM exception with code" << exception.code;
kWarning() << "No quote coloring for you, then.";
return htmlSource;
}
}
DOM::Node HTMLQuoteColorer::processNode( DOM::Node node )
{
// Below, we determine if the current text node should be quote colored by keeping track of
// linebreaks and wether this text node is the first one.
const QString textContent = node.textContent().string();
const bool isTextNode = !textContent.isEmpty() && !node.hasChildNodes();
if ( isTextNode ) {
if ( mIsFirstTextNodeInLine ) {
if ( textContent.simplified().startsWith( '>' ) ||
textContent.simplified().startsWith( '|' ) ) {
mIsQuotedLine = true;
currentQuoteLength = quoteLength( textContent ) - 1;
}
else {
mIsQuotedLine = false;
}
}
// All subsequent text nodes are not the first ones anymore
mIsFirstTextNodeInLine = false;
}
const QString nodeName = node.nodeName().string().toLower();
QStringList lineBreakNodes;
lineBreakNodes << "br" << "p" << "div" << "ul" << "ol" << "li";
if ( lineBreakNodes.contains( nodeName ) ) {
mIsFirstTextNodeInLine = true;
}
DOM::Node returnNode = node;
bool fontTagAdded = false;
if ( mIsQuotedLine && isTextNode ) {
// Ok, we are in a line that should be quoted, so create a font node for the color and replace
// the current node with it.
DOM::Element font = node.ownerDocument().createElement( QString( "font" ) );
font.setAttribute( QString( "color" ), mCSSHelper->quoteColor( currentQuoteLength ).name() );
node.parentNode().replaceChild( font, node );
font.appendChild( node );
returnNode = font;
fontTagAdded = true;
}
// Process all child nodes, but only if we are didn't add those child nodes itself, as otherwise
// we'll go into an infinite recursion.
if ( !fontTagAdded ) {
DOM::Node childNode = node.firstChild();
while ( !childNode.isNull() ) {
childNode = processNode( childNode );
childNode = childNode.nextSibling();
}
}
return returnNode;
}
int HTMLQuoteColorer::quoteLength( const QString &line ) const
{
QString simplified = line.simplified();
simplified = simplified.replace( QRegExp( QLatin1String( "\\s" ) ), QString() )
.replace( QLatin1Char( '|' ), QLatin1Char( '>' ) );
if ( simplified.startsWith( ">>>" ) ) return 3;
if ( simplified.startsWith( ">>" ) ) return 2;
if ( simplified.startsWith( ">" ) ) return 1;
return 0;
}
}
<|endoftext|>
|
<commit_before>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "BeaconEntity.h"
#include "../BlockArea.h"
#include "../Entities/Player.h"
#include "../UI/BeaconWindow.h"
#include "../ClientHandle.h"
cBeaconEntity::cBeaconEntity(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World):
Super(a_BlockType, a_BlockMeta, a_BlockX, a_BlockY, a_BlockZ, 1, 1, a_World),
m_IsActive(false),
m_BeaconLevel(0),
m_PrimaryEffect(cEntityEffect::effNoEffect),
m_SecondaryEffect(cEntityEffect::effNoEffect)
{
ASSERT(a_BlockType == E_BLOCK_BEACON);
UpdateBeacon();
}
char cBeaconEntity::CalculatePyramidLevel(void)
{
cBlockArea Area;
int MinY = std::max(GetPosY() - 4, 0);
int MaxY = std::max(GetPosY() - 1, 0);
Area.Read(
*m_World,
GetPosX() - 4, GetPosX() + 4,
MinY, MaxY,
GetPosZ() - 4, GetPosZ() + 4,
cBlockArea::baTypes
);
int Layer = 1;
int MiddleXZ = 4;
for (int Y = (Area.GetSizeY() - 1); Y >= 0; Y--)
{
for (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++)
{
for (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++)
{
if (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z)))
{
return static_cast<char>(Layer - 1);
}
}
}
Layer++;
}
return static_cast<char>(Layer - 1);
}
bool cBeaconEntity::IsValidEffect(cEntityEffect::eType a_Effect, char a_BeaconLevel)
{
switch (a_Effect)
{
case cEntityEffect::effRegeneration: return (a_BeaconLevel >= 4);
case cEntityEffect::effStrength: return (a_BeaconLevel >= 3);
case cEntityEffect::effResistance: return (a_BeaconLevel >= 2);
case cEntityEffect::effJumpBoost: return (a_BeaconLevel >= 2);
case cEntityEffect::effSpeed: return (a_BeaconLevel >= 1);
case cEntityEffect::effHaste: return (a_BeaconLevel >= 1);
case cEntityEffect::effNoEffect: return true;
default:
{
LOGD("%s: Invalid beacon effect: %d", __FUNCTION__, static_cast<int>(a_Effect));
return false;
}
}
}
bool cBeaconEntity::SetPrimaryEffect(cEntityEffect::eType a_Effect)
{
if (!IsValidEffect(a_Effect, m_BeaconLevel))
{
m_PrimaryEffect = cEntityEffect::effNoEffect;
return false;
}
m_PrimaryEffect = a_Effect;
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(1, m_PrimaryEffect);
}
return true;
}
bool cBeaconEntity::SetSecondaryEffect(cEntityEffect::eType a_Effect)
{
if (!IsValidEffect(a_Effect, m_BeaconLevel))
{
m_SecondaryEffect = cEntityEffect::effNoEffect;
return false;
}
m_SecondaryEffect = a_Effect;
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(2, m_SecondaryEffect);
}
return true;
}
bool cBeaconEntity::IsBeaconBlocked(void)
{
for (int Y = m_PosY; Y < cChunkDef::Height; ++Y)
{
BLOCKTYPE Block = m_World->GetBlock(m_PosX, Y, m_PosZ);
if (!cBlockInfo::IsTransparent(Block))
{
return true;
}
}
return false;
}
bool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType)
{
switch (a_BlockType)
{
case E_BLOCK_DIAMOND_BLOCK:
case E_BLOCK_GOLD_BLOCK:
case E_BLOCK_IRON_BLOCK:
case E_BLOCK_EMERALD_BLOCK:
{
return true;
}
}
return false;
}
void cBeaconEntity::UpdateBeacon(void)
{
int OldBeaconLevel = m_BeaconLevel;
if (IsBeaconBlocked())
{
m_IsActive = false;
m_BeaconLevel = 0;
}
else
{
m_BeaconLevel = CalculatePyramidLevel();
m_IsActive = (m_BeaconLevel > 0);
}
if (m_BeaconLevel != OldBeaconLevel)
{
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(0, m_BeaconLevel);
}
}
// TODO: Add achievement
}
void cBeaconEntity::GiveEffects(void)
{
if (!m_IsActive || (m_BeaconLevel < 0))
{
return;
}
int Radius = m_BeaconLevel * 10 + 10;
short EffectLevel = 0;
if ((m_BeaconLevel >= 4) && (m_PrimaryEffect == m_SecondaryEffect))
{
EffectLevel = 1;
}
cEntityEffect::eType SecondaryEffect = cEntityEffect::effNoEffect;
if ((m_BeaconLevel >= 4) && (m_PrimaryEffect != m_SecondaryEffect) && (m_SecondaryEffect > 0))
{
SecondaryEffect = m_SecondaryEffect;
}
class cPlayerCallback : public cPlayerListCallback
{
int m_Radius;
int m_PosX, m_PosY, m_PosZ;
cEntityEffect::eType m_PrimaryEffect, m_SecondaryEffect;
short m_EffectLevel;
virtual bool Item(cPlayer * a_Player)
{
Vector3d PlayerPosition = Vector3d(a_Player->GetPosition());
if (PlayerPosition.y > static_cast<double>(m_PosY))
{
PlayerPosition.y = static_cast<double>(m_PosY);
}
// TODO: Vanilla minecraft uses an AABB check instead of a radius one
Vector3d BeaconPosition = Vector3d(m_PosX, m_PosY, m_PosZ);
if ((PlayerPosition - BeaconPosition).Length() <= m_Radius)
{
a_Player->AddEntityEffect(m_PrimaryEffect, 180, m_EffectLevel);
if (m_SecondaryEffect != cEntityEffect::effNoEffect)
{
a_Player->AddEntityEffect(m_SecondaryEffect, 180, 0);
}
}
return false;
}
public:
cPlayerCallback(int a_Radius, int a_PosX, int a_PosY, int a_PosZ, cEntityEffect::eType a_PrimaryEffect, cEntityEffect::eType a_SecondaryEffect, short a_EffectLevel):
m_Radius(a_Radius),
m_PosX(a_PosX),
m_PosY(a_PosY),
m_PosZ(a_PosZ),
m_PrimaryEffect(a_PrimaryEffect),
m_SecondaryEffect(a_SecondaryEffect),
m_EffectLevel(a_EffectLevel)
{
}
} PlayerCallback(Radius, m_PosX, m_PosY, m_PosZ, m_PrimaryEffect, SecondaryEffect, EffectLevel);
GetWorld()->ForEachPlayer(PlayerCallback);
}
void cBeaconEntity::CopyFrom(const cBlockEntity & a_Src)
{
Super::CopyFrom(a_Src);
auto & src = reinterpret_cast<const cBeaconEntity &>(a_Src);
m_BeaconLevel = src.m_BeaconLevel;
m_Contents.CopyFrom(src.m_Contents);
m_IsActive = src.m_IsActive;
m_PrimaryEffect = src.m_PrimaryEffect;
m_SecondaryEffect = src.m_SecondaryEffect;
}
void cBeaconEntity::SendTo(cClientHandle & a_Client)
{
a_Client.SendUpdateBlockEntity(*this);
}
bool cBeaconEntity::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
// Update the beacon every 4 seconds
if ((GetWorld()->GetWorldAge() % 80) == 0)
{
UpdateBeacon();
GiveEffects();
}
return false;
}
bool cBeaconEntity::UsedBy(cPlayer * a_Player)
{
cWindow * Window = GetWindow();
if (Window == nullptr)
{
OpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this));
Window = GetWindow();
}
if (Window != nullptr)
{
// if (a_Player->GetWindow() != Window)
// -> Because mojang doesn't send a 'close window' packet when you click the cancel button in the beacon inventory ...
{
a_Player->OpenWindow(*Window);
}
}
return true;
}
<commit_msg>cBeaconEntity fix no world crash<commit_after>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "BeaconEntity.h"
#include "../BlockArea.h"
#include "../Entities/Player.h"
#include "../UI/BeaconWindow.h"
#include "../ClientHandle.h"
cBeaconEntity::cBeaconEntity(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World):
Super(a_BlockType, a_BlockMeta, a_BlockX, a_BlockY, a_BlockZ, 1, 1, a_World),
m_IsActive(false),
m_BeaconLevel(0),
m_PrimaryEffect(cEntityEffect::effNoEffect),
m_SecondaryEffect(cEntityEffect::effNoEffect)
{
ASSERT(a_BlockType == E_BLOCK_BEACON);
if (m_World != nullptr)
{
UpdateBeacon();
}
}
char cBeaconEntity::CalculatePyramidLevel(void)
{
cBlockArea Area;
int MinY = std::max(GetPosY() - 4, 0);
int MaxY = std::max(GetPosY() - 1, 0);
Area.Read(
*m_World,
GetPosX() - 4, GetPosX() + 4,
MinY, MaxY,
GetPosZ() - 4, GetPosZ() + 4,
cBlockArea::baTypes
);
int Layer = 1;
int MiddleXZ = 4;
for (int Y = (Area.GetSizeY() - 1); Y >= 0; Y--)
{
for (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++)
{
for (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++)
{
if (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z)))
{
return static_cast<char>(Layer - 1);
}
}
}
Layer++;
}
return static_cast<char>(Layer - 1);
}
bool cBeaconEntity::IsValidEffect(cEntityEffect::eType a_Effect, char a_BeaconLevel)
{
switch (a_Effect)
{
case cEntityEffect::effRegeneration: return (a_BeaconLevel >= 4);
case cEntityEffect::effStrength: return (a_BeaconLevel >= 3);
case cEntityEffect::effResistance: return (a_BeaconLevel >= 2);
case cEntityEffect::effJumpBoost: return (a_BeaconLevel >= 2);
case cEntityEffect::effSpeed: return (a_BeaconLevel >= 1);
case cEntityEffect::effHaste: return (a_BeaconLevel >= 1);
case cEntityEffect::effNoEffect: return true;
default:
{
LOGD("%s: Invalid beacon effect: %d", __FUNCTION__, static_cast<int>(a_Effect));
return false;
}
}
}
bool cBeaconEntity::SetPrimaryEffect(cEntityEffect::eType a_Effect)
{
if (!IsValidEffect(a_Effect, m_BeaconLevel))
{
m_PrimaryEffect = cEntityEffect::effNoEffect;
return false;
}
m_PrimaryEffect = a_Effect;
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(1, m_PrimaryEffect);
}
return true;
}
bool cBeaconEntity::SetSecondaryEffect(cEntityEffect::eType a_Effect)
{
if (!IsValidEffect(a_Effect, m_BeaconLevel))
{
m_SecondaryEffect = cEntityEffect::effNoEffect;
return false;
}
m_SecondaryEffect = a_Effect;
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(2, m_SecondaryEffect);
}
return true;
}
bool cBeaconEntity::IsBeaconBlocked(void)
{
for (int Y = m_PosY; Y < cChunkDef::Height; ++Y)
{
BLOCKTYPE Block = m_World->GetBlock(m_PosX, Y, m_PosZ);
if (!cBlockInfo::IsTransparent(Block))
{
return true;
}
}
return false;
}
bool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType)
{
switch (a_BlockType)
{
case E_BLOCK_DIAMOND_BLOCK:
case E_BLOCK_GOLD_BLOCK:
case E_BLOCK_IRON_BLOCK:
case E_BLOCK_EMERALD_BLOCK:
{
return true;
}
}
return false;
}
void cBeaconEntity::UpdateBeacon(void)
{
int OldBeaconLevel = m_BeaconLevel;
if (IsBeaconBlocked())
{
m_IsActive = false;
m_BeaconLevel = 0;
}
else
{
m_BeaconLevel = CalculatePyramidLevel();
m_IsActive = (m_BeaconLevel > 0);
}
if (m_BeaconLevel != OldBeaconLevel)
{
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(0, m_BeaconLevel);
}
}
// TODO: Add achievement
}
void cBeaconEntity::GiveEffects(void)
{
if (!m_IsActive || (m_BeaconLevel < 0))
{
return;
}
int Radius = m_BeaconLevel * 10 + 10;
short EffectLevel = 0;
if ((m_BeaconLevel >= 4) && (m_PrimaryEffect == m_SecondaryEffect))
{
EffectLevel = 1;
}
cEntityEffect::eType SecondaryEffect = cEntityEffect::effNoEffect;
if ((m_BeaconLevel >= 4) && (m_PrimaryEffect != m_SecondaryEffect) && (m_SecondaryEffect > 0))
{
SecondaryEffect = m_SecondaryEffect;
}
class cPlayerCallback : public cPlayerListCallback
{
int m_Radius;
int m_PosX, m_PosY, m_PosZ;
cEntityEffect::eType m_PrimaryEffect, m_SecondaryEffect;
short m_EffectLevel;
virtual bool Item(cPlayer * a_Player)
{
Vector3d PlayerPosition = Vector3d(a_Player->GetPosition());
if (PlayerPosition.y > static_cast<double>(m_PosY))
{
PlayerPosition.y = static_cast<double>(m_PosY);
}
// TODO: Vanilla minecraft uses an AABB check instead of a radius one
Vector3d BeaconPosition = Vector3d(m_PosX, m_PosY, m_PosZ);
if ((PlayerPosition - BeaconPosition).Length() <= m_Radius)
{
a_Player->AddEntityEffect(m_PrimaryEffect, 180, m_EffectLevel);
if (m_SecondaryEffect != cEntityEffect::effNoEffect)
{
a_Player->AddEntityEffect(m_SecondaryEffect, 180, 0);
}
}
return false;
}
public:
cPlayerCallback(int a_Radius, int a_PosX, int a_PosY, int a_PosZ, cEntityEffect::eType a_PrimaryEffect, cEntityEffect::eType a_SecondaryEffect, short a_EffectLevel):
m_Radius(a_Radius),
m_PosX(a_PosX),
m_PosY(a_PosY),
m_PosZ(a_PosZ),
m_PrimaryEffect(a_PrimaryEffect),
m_SecondaryEffect(a_SecondaryEffect),
m_EffectLevel(a_EffectLevel)
{
}
} PlayerCallback(Radius, m_PosX, m_PosY, m_PosZ, m_PrimaryEffect, SecondaryEffect, EffectLevel);
GetWorld()->ForEachPlayer(PlayerCallback);
}
void cBeaconEntity::CopyFrom(const cBlockEntity & a_Src)
{
Super::CopyFrom(a_Src);
auto & src = reinterpret_cast<const cBeaconEntity &>(a_Src);
m_BeaconLevel = src.m_BeaconLevel;
m_Contents.CopyFrom(src.m_Contents);
m_IsActive = src.m_IsActive;
m_PrimaryEffect = src.m_PrimaryEffect;
m_SecondaryEffect = src.m_SecondaryEffect;
}
void cBeaconEntity::SendTo(cClientHandle & a_Client)
{
a_Client.SendUpdateBlockEntity(*this);
}
bool cBeaconEntity::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
// Update the beacon every 4 seconds
if ((GetWorld()->GetWorldAge() % 80) == 0)
{
UpdateBeacon();
GiveEffects();
}
return false;
}
bool cBeaconEntity::UsedBy(cPlayer * a_Player)
{
cWindow * Window = GetWindow();
if (Window == nullptr)
{
OpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this));
Window = GetWindow();
}
if (Window != nullptr)
{
// if (a_Player->GetWindow() != Window)
// -> Because mojang doesn't send a 'close window' packet when you click the cancel button in the beacon inventory ...
{
a_Player->OpenWindow(*Window);
}
}
return true;
}
<|endoftext|>
|
<commit_before><commit_msg>use p for momentum threshold of protons<commit_after><|endoftext|>
|
<commit_before>#include "Definitions.h"
#include "Simulator.h"
#include "cpplog/cpplog.hpp"
#include <boost/filesystem.hpp>
#include <boost/make_shared.hpp>
int main(int argc, char **argv)
{
auto logger = boost::make_shared<cpplog::StdErrLogger>();
state state0;
state0.V = -70;
state0.h = 1.0;
state0.n = 0.0;
state0.z = 0.0;
state0.s_AMPA = 0.0;
state0.s_NMDA = 0.0;
state0.x_NMDA = 0.0;
state0.s_GABAA = 0.0;
state0.I_app = 1.0;
auto path = boost::filesystem3::path(CL_SOURCE_DIR);
path /= "/kernels.cl";
Simulator sim = Simulator(
800,
5000,
0.1f,
state0,
false,
true,
path,
logger);
sim.simulate();
exit(0);
}<commit_msg>program options<commit_after>#include "Definitions.h"
#include "Simulator.h"
#include "util.h"
#include "cpplog/cpplog.hpp"
#include <numeric>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
void measureTimes(Logger const& logger, state const& state0, boost::filesystem3::path const& path)
{
const unsigned int start = 0;
const unsigned int powers = 10;
std::vector<const unsigned int> numNeurons;
std::vector<const double> avgTimesCalculations;
std::vector<const double> avgTimesFFTW;
std::vector<const double> avgTimesClFFT;
for(int i = start; i < powers; ++i)
{
auto neurons = static_cast<const unsigned int>(pow(2.f, i));
numNeurons.push_back(neurons);
Simulator sim = Simulator(
neurons,
500,
0.1f,
state0,
Simulator::NO_PLOT,
Simulator::MEASURE,
Simulator::FFTW,
Simulator::CLFFT,
path,
logger);
sim.simulate();
auto timesCalculations = sim.getTimesCalculations();
auto timesFFTW = sim.getTimesFFTW();
auto timesClFFT = sim.getTimesClFFT();
avgTimesCalculations.push_back(
std::accumulate(
timesCalculations.begin(),
timesCalculations.end(), 0.0)
/ timesCalculations.size());
avgTimesFFTW.push_back(
std::accumulate(
timesFFTW.begin(),
timesFFTW.end(), 0.0)
/ timesFFTW.size());
avgTimesClFFT.push_back(
std::accumulate(
timesClFFT.begin(),
timesClFFT.end(), 0.0)
/ timesClFFT.size());
}
for(int i = 0; i < powers - start; ++i)
{
std::cout << static_cast<const unsigned int>(pow(2.f, (int)(i + start))) << "\t" << avgTimesCalculations[i] << "\t" << avgTimesFFTW[i] << "\t" << avgTimesClFFT[i] << std::endl;
}
}
int main(int ac, char **av)
{
float V0, h0, n0, z0, sAMPA0, sNMDA0, xNMDA0, sGABAA0, IApp0, dt;
unsigned int numNeurons, timesteps;
std::string plot, measure, fftw, clfft;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("V", po::value<float>(&V0)->default_value(-70.0), "initial value for membrane potential")
("h", po::value<float>(&h0)->default_value(1.0), "initial value for h")
("n", po::value<float>(&n0)->default_value(0.0), "initial value for n")
("z", po::value<float>(&z0)->default_value(0.0), "initial value for z")
("sAMPA", po::value<float>(&sAMPA0)->default_value(0.0), "initial value for sAMPA")
("sNMDA", po::value<float>(&sNMDA0)->default_value(0.0), "initial value for sNMDA")
("xNMDA", po::value<float>(&xNMDA0)->default_value(0.0), "initial value for xNMDA")
("sGABAA", po::value<float>(&sGABAA0)->default_value(0.0), "initial value for xNMDA")
("IApp", po::value<float>(&IApp0)->default_value(1.0), "initial value for IApp")
("dt", po::value<float>(&dt)->default_value(0.1f), "length of one timestep")
("timesteps", po::value<unsigned int>(×teps)->default_value(500), "number of timesteps")
("neurons", po::value<unsigned int>(&numNeurons)->default_value(1024), "number of neurons in network")
("plot", po::value<std::string>(&plot)->default_value("true"), "plot results")
("measure", po::value<std::string>(&measure)->default_value("true"), "measure execution time")
("fftw", po::value<std::string>(&fftw)->default_value("false"), "compute synaptic fields using fftw")
("clfft", po::value<std::string>(&clfft)->default_value("true"), "compute synaptic fields using clFFT")
;
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
exit(1);
}
auto logger = make_shared<cpplog::StdErrLogger>();
state state0;
state0.V = V0;
state0.h = h0;
state0.n = n0;
state0.z = z0;
state0.s_AMPA = sAMPA0;
state0.s_NMDA = sNMDA0;
state0.x_NMDA = xNMDA0;
state0.s_GABAA = sGABAA0;
state0.I_app = IApp0;
auto path = boost::filesystem3::path(CL_SOURCE_DIR);
path /= "/kernels.cl";
Simulator sim = Simulator(
numNeurons,
timesteps,
dt,
state0,
stringToBool(plot) ? Simulator::PLOT : Simulator::NO_PLOT,
stringToBool(measure) ? Simulator::MEASURE : Simulator::NO_MEASURE,
stringToBool(fftw) ? Simulator::FFTW : Simulator::NO_FFTW,
stringToBool(clfft) ? Simulator::CLFFT : Simulator::NO_CLFFT,
path,
logger);
sim.simulate();
////measureTimes(logger, state0, path);
exit(0);
}<|endoftext|>
|
<commit_before>template <class T> struct F {};
template <class T> class I {
F<T> m;
};
struct C {
typedef short char_type;
typedef F<char_type> f; // commenting this line out fixes it!
typedef I<char_type> i;
};
<commit_msg>minor change<commit_after>template <class T> struct F {};
template <class T> struct I {
F<T> m;
};
struct C {
typedef short char_type;
typedef F<char_type> f; // commenting this line out fixes it!
typedef I<char_type> i;
};
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "maemopackageinstaller.h"
#include "maemoglobal.h"
#include <utils/ssh/sshconnection.h>
#include <utils/ssh/sshremoteprocessrunner.h>
using namespace Utils;
namespace Qt4ProjectManager {
namespace Internal {
AbstractMaemoPackageInstaller::AbstractMaemoPackageInstaller(QObject *parent)
: QObject(parent), m_isRunning(false)
{
}
AbstractMaemoPackageInstaller::~AbstractMaemoPackageInstaller() {}
void AbstractMaemoPackageInstaller::installPackage(const SshConnection::Ptr &connection,
const QString &packageFilePath, bool removePackageFile)
{
Q_ASSERT(connection && connection->state() == SshConnection::Connected);
Q_ASSERT(!m_isRunning);
prepareInstallation();
m_installer = SshRemoteProcessRunner::create(connection);
connect(m_installer.data(), SIGNAL(connectionError(Utils::SshError)),
SLOT(handleConnectionError()));
connect(m_installer.data(), SIGNAL(processOutputAvailable(QByteArray)),
SLOT(handleInstallerOutput(QByteArray)));
connect(m_installer.data(), SIGNAL(processErrorOutputAvailable(QByteArray)),
SLOT(handleInstallerErrorOutput(QByteArray)));
connect(m_installer.data(), SIGNAL(processClosed(int)),
SLOT(handleInstallationFinished(int)));
const QString space = QLatin1String(" ");
QString cmdLine = MaemoGlobal::remoteSudo() + space + installCommand()
+ space + installCommandArguments().join(space) + space
+ packageFilePath;
if (removePackageFile) {
cmdLine += QLatin1String(" && (rm ") + packageFilePath
+ QLatin1String(" || :)");
}
m_installer->run(cmdLine.toUtf8());
m_isRunning = true;
}
void AbstractMaemoPackageInstaller::cancelInstallation()
{
Q_ASSERT(m_isRunning);
const SshRemoteProcessRunner::Ptr killProcess
= SshRemoteProcessRunner::create(m_installer->connection());
killProcess->run("pkill " + installCommand().toUtf8());
setFinished();
}
void AbstractMaemoPackageInstaller::handleConnectionError()
{
if (!m_isRunning)
return;
emit finished(tr("Connection failure: %1")
.arg(m_installer->connection()->errorString()));
setFinished();
}
void AbstractMaemoPackageInstaller::handleInstallationFinished(int exitStatus)
{
if (!m_isRunning)
return;
if (exitStatus != SshRemoteProcess::ExitedNormally
|| m_installer->process()->exitCode() != 0) {
emit finished(tr("Installing package failed."));
} else if (!errorString().isEmpty()) {
emit finished(errorString());
} else {
emit finished();
}
setFinished();
}
void AbstractMaemoPackageInstaller::handleInstallerOutput(const QByteArray &output)
{
emit stdoutData(QString::fromUtf8(output));
}
void AbstractMaemoPackageInstaller::handleInstallerErrorOutput(const QByteArray &output)
{
emit stderrData(QString::fromUtf8(output));
}
void AbstractMaemoPackageInstaller::setFinished()
{
disconnect(m_installer.data(), 0, this, 0);
m_installer.clear();
m_isRunning = false;
}
MaemoDebianPackageInstaller::MaemoDebianPackageInstaller(QObject *parent)
: AbstractMaemoPackageInstaller(parent)
{
connect(this, SIGNAL(stderrData(QString)),
SLOT(handleInstallerErrorOutput(QString)));
}
void MaemoDebianPackageInstaller::prepareInstallation()
{
m_installerStderr.clear();
}
QString MaemoDebianPackageInstaller::installCommand() const
{
return QLatin1String("dpkg");
}
QStringList MaemoDebianPackageInstaller::installCommandArguments() const
{
return QStringList() << QLatin1String("-i")
<< QLatin1String("--no-force-downgrade");
}
void MaemoDebianPackageInstaller::handleInstallerErrorOutput(const QString &output)
{
m_installerStderr += output;
}
QString MaemoDebianPackageInstaller::errorString() const
{
if (m_installerStderr.contains(QLatin1String("Will not downgrade"))) {
return tr("Installation failed: "
"You tried to downgrade a package, which is not allowed.");
} else {
return QString();
}
}
MaemoRpmPackageInstaller::MaemoRpmPackageInstaller(QObject *parent)
: AbstractMaemoPackageInstaller(parent)
{
}
QString MaemoRpmPackageInstaller::installCommand() const
{
return QLatin1String("rpm");
}
QStringList MaemoRpmPackageInstaller::installCommandArguments() const
{
return QStringList() << QLatin1String("-Uhv");
}
MaemoTarPackageInstaller::MaemoTarPackageInstaller(QObject *parent)
: AbstractMaemoPackageInstaller(parent)
{
}
QString MaemoTarPackageInstaller::installCommand() const
{
return QLatin1String("tar");
}
QStringList MaemoTarPackageInstaller::installCommandArguments() const
{
return QStringList() << QLatin1String("xvf");
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Meego: Allow re-installation of package with equal version number.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "maemopackageinstaller.h"
#include "maemoglobal.h"
#include <utils/ssh/sshconnection.h>
#include <utils/ssh/sshremoteprocessrunner.h>
using namespace Utils;
namespace Qt4ProjectManager {
namespace Internal {
AbstractMaemoPackageInstaller::AbstractMaemoPackageInstaller(QObject *parent)
: QObject(parent), m_isRunning(false)
{
}
AbstractMaemoPackageInstaller::~AbstractMaemoPackageInstaller() {}
void AbstractMaemoPackageInstaller::installPackage(const SshConnection::Ptr &connection,
const QString &packageFilePath, bool removePackageFile)
{
Q_ASSERT(connection && connection->state() == SshConnection::Connected);
Q_ASSERT(!m_isRunning);
prepareInstallation();
m_installer = SshRemoteProcessRunner::create(connection);
connect(m_installer.data(), SIGNAL(connectionError(Utils::SshError)),
SLOT(handleConnectionError()));
connect(m_installer.data(), SIGNAL(processOutputAvailable(QByteArray)),
SLOT(handleInstallerOutput(QByteArray)));
connect(m_installer.data(), SIGNAL(processErrorOutputAvailable(QByteArray)),
SLOT(handleInstallerErrorOutput(QByteArray)));
connect(m_installer.data(), SIGNAL(processClosed(int)),
SLOT(handleInstallationFinished(int)));
const QString space = QLatin1String(" ");
QString cmdLine = MaemoGlobal::remoteSudo() + space + installCommand()
+ space + installCommandArguments().join(space) + space
+ packageFilePath;
if (removePackageFile) {
cmdLine += QLatin1String(" && (rm ") + packageFilePath
+ QLatin1String(" || :)");
}
m_installer->run(cmdLine.toUtf8());
m_isRunning = true;
}
void AbstractMaemoPackageInstaller::cancelInstallation()
{
Q_ASSERT(m_isRunning);
const SshRemoteProcessRunner::Ptr killProcess
= SshRemoteProcessRunner::create(m_installer->connection());
killProcess->run("pkill " + installCommand().toUtf8());
setFinished();
}
void AbstractMaemoPackageInstaller::handleConnectionError()
{
if (!m_isRunning)
return;
emit finished(tr("Connection failure: %1")
.arg(m_installer->connection()->errorString()));
setFinished();
}
void AbstractMaemoPackageInstaller::handleInstallationFinished(int exitStatus)
{
if (!m_isRunning)
return;
if (exitStatus != SshRemoteProcess::ExitedNormally
|| m_installer->process()->exitCode() != 0) {
emit finished(tr("Installing package failed."));
} else if (!errorString().isEmpty()) {
emit finished(errorString());
} else {
emit finished();
}
setFinished();
}
void AbstractMaemoPackageInstaller::handleInstallerOutput(const QByteArray &output)
{
emit stdoutData(QString::fromUtf8(output));
}
void AbstractMaemoPackageInstaller::handleInstallerErrorOutput(const QByteArray &output)
{
emit stderrData(QString::fromUtf8(output));
}
void AbstractMaemoPackageInstaller::setFinished()
{
disconnect(m_installer.data(), 0, this, 0);
m_installer.clear();
m_isRunning = false;
}
MaemoDebianPackageInstaller::MaemoDebianPackageInstaller(QObject *parent)
: AbstractMaemoPackageInstaller(parent)
{
connect(this, SIGNAL(stderrData(QString)),
SLOT(handleInstallerErrorOutput(QString)));
}
void MaemoDebianPackageInstaller::prepareInstallation()
{
m_installerStderr.clear();
}
QString MaemoDebianPackageInstaller::installCommand() const
{
return QLatin1String("dpkg");
}
QStringList MaemoDebianPackageInstaller::installCommandArguments() const
{
return QStringList() << QLatin1String("-i")
<< QLatin1String("--no-force-downgrade");
}
void MaemoDebianPackageInstaller::handleInstallerErrorOutput(const QString &output)
{
m_installerStderr += output;
}
QString MaemoDebianPackageInstaller::errorString() const
{
if (m_installerStderr.contains(QLatin1String("Will not downgrade"))) {
return tr("Installation failed: "
"You tried to downgrade a package, which is not allowed.");
} else {
return QString();
}
}
MaemoRpmPackageInstaller::MaemoRpmPackageInstaller(QObject *parent)
: AbstractMaemoPackageInstaller(parent)
{
}
QString MaemoRpmPackageInstaller::installCommand() const
{
return QLatin1String("rpm");
}
QStringList MaemoRpmPackageInstaller::installCommandArguments() const
{
// --replacepkgs to re-install package, even if the same version is already installed
return QStringList() << QLatin1String("-Uhv") << QLatin1String("--replacepkgs");
}
MaemoTarPackageInstaller::MaemoTarPackageInstaller(QObject *parent)
: AbstractMaemoPackageInstaller(parent)
{
}
QString MaemoTarPackageInstaller::installCommand() const
{
return QLatin1String("tar");
}
QStringList MaemoTarPackageInstaller::installCommandArguments() const
{
return QStringList() << QLatin1String("xvf");
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>
|
<commit_before>#include <Kunlaboro/Component.inl>
#include <Kunlaboro/Entity.inl>
#include <Kunlaboro/EntitySystem.inl>
#include <Kunlaboro/Views.inl>
#include "catch.hpp"
#include <atomic>
#include <random>
struct NumberComponent : public Kunlaboro::Component
{
NumberComponent(int i)
: Number(i)
{ }
int Number;
};
struct NameComponent : public Kunlaboro::Component
{
NameComponent(const std::string& name)
: Name(name)
{ }
std::string Name;
};
TEST_CASE("fizzbuzz", "[entity][view]")
{
Kunlaboro::EntitySystem es;
for (int i = 1; i <= 15; ++i)
{
auto ent = es.entityCreate();
if (i % 3 == 0 && i % 5 == 0)
ent.addComponent<NameComponent>("fizzbuzz");
else if (i % 3 == 0)
ent.addComponent<NameComponent>("fizz");
else if (i % 5 == 0)
ent.addComponent<NameComponent>("buzz");
ent.addComponent<NumberComponent>(i);
}
SECTION("Range-based for")
{
std::string result;
auto view = Kunlaboro::EntityView(es);
for (auto& ent : view)
{
if (ent.hasComponent<NameComponent>())
result += ent.getComponent<NameComponent>()->Name + " ";
else if (ent.hasComponent<NumberComponent>())
result += std::to_string(ent.getComponent<NumberComponent>()->Number) + " ";
}
REQUIRE(result == "1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz ");
}
SECTION("forEach - match any")
{
std::string result;
auto view = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_Any, NumberComponent, NameComponent>();
view.forEach([&result](Kunlaboro::Entity&, NumberComponent* number, NameComponent* name) {
if (name)
result += name->Name + " ";
else
result += std::to_string(number->Number) + " ";
});
REQUIRE(result == "1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz ");
}
SECTION("forEach - match all")
{
std::string result;
auto view = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, NumberComponent, NameComponent>();
view.forEach([&result](Kunlaboro::Entity&, NumberComponent& number, NameComponent& name) {
result += std::to_string(number.Number);
result += name.Name + " ";
});
REQUIRE(result == "3fizz 5buzz 6fizz 9fizz 10buzz 12fizz 15fizzbuzz ");
}
}
struct Position : public Kunlaboro::Component
{
Position(float x, float y)
: X(x)
, Y(y)
{ }
volatile float X, Y;
};
struct Velocity : public Kunlaboro::Component
{
Velocity(float x, float y)
: X(x)
, Y(y)
{ }
volatile float X, Y;
};
TEST_CASE("Simple n-body simulation", "[performance][view]")
{
Kunlaboro::EntitySystem es;
SECTION("Creation, 100 particles")
{
const int ParticleCount = 100;
std::random_device rand;
std::uniform_real_distribution<float> ang(0, 3.14159f * 2);
std::uniform_real_distribution<float> mag(0, 100);
for (int i = 0; i < ParticleCount; ++i)
{
auto ent = es.entityCreate();
float angle = ang(rand);
float magnitude = mag(rand);
ent.addComponent<Position>(std::cos(angle) * magnitude, std::sin(angle) * magnitude);
ent.addComponent<Velocity>((mag(rand) - 50) / 5, (mag(rand) - 50) / 5);
}
REQUIRE(es.componentGetPool(Kunlaboro::ComponentFamily<Position>::getFamily()).countBits() == ParticleCount);
REQUIRE(es.componentGetPool(Kunlaboro::ComponentFamily<Velocity>::getFamily()).countBits() == ParticleCount);
SECTION("Iteration, 100 steps, 100 000 calls per step")
{
const int IterationCount = 100;
std::atomic<uint32_t> gravityIterations(0)
, velocityIterations(0);
auto entityView = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position,Velocity>();
auto particleList = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position>();
for (int step = 0; step < IterationCount; ++step)
{
entityView.forEach([&gravityIterations, &velocityIterations, &particleList](Kunlaboro::Entity& ent, Position& pos, Velocity& vel) {
particleList.forEach([&gravityIterations, &ent, &pos, &vel](Kunlaboro::Entity& ent2, Position& pos2) {
if (ent == ent2)
return;
const float xDelta = (pos2.X - pos.X);
const float yDelta = (pos2.Y - pos.Y);
const float deltaSqrt = std::sqrt(xDelta*xDelta + yDelta*yDelta + 1e-9f);
const float invDist = 1 / deltaSqrt;
const float invDist2 = invDist * invDist;
vel.X += xDelta * invDist2;
vel.Y += yDelta * invDist2;
gravityIterations.fetch_add(1);
});
pos.X += vel.X;
pos.Y += vel.Y;
velocityIterations.fetch_add(1);
});
}
REQUIRE(gravityIterations == ParticleCount * (ParticleCount - 1) * IterationCount);
REQUIRE(velocityIterations == ParticleCount * IterationCount);
}
SECTION("Parallel gravity iteration, 100 steps, 100 000 calls per step")
{
const int IterationCount = 100;
std::atomic<uint32_t> gravityIterations(0)
, velocityIterations(0);
Kunlaboro::detail::JobQueue queue;
auto entityView = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position,Velocity>();
auto particleList = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position>().parallel(queue);
for (int step = 0; step < IterationCount; ++step)
{
entityView.forEach([&gravityIterations, &velocityIterations, &particleList](Kunlaboro::Entity& ent, Position& pos, Velocity& vel) {
particleList.forEach([&gravityIterations, &ent, &pos, &vel](Kunlaboro::Entity& ent2, Position& pos2) {
if (ent == ent2)
return;
const float xDelta = (pos2.X - pos.X);
const float yDelta = (pos2.Y - pos.Y);
const float deltaSqrt = std::sqrt(xDelta*xDelta + yDelta*yDelta + 1e-9f);
const float invDist = 1 / deltaSqrt;
const float invDist2 = invDist * invDist;
vel.X += xDelta * invDist2;
vel.Y += yDelta * invDist2;
gravityIterations.fetch_add(1, std::memory_order_relaxed);
});
pos.X += vel.X;
pos.Y += vel.Y;
velocityIterations.fetch_add(1, std::memory_order_relaxed);
});
}
REQUIRE(gravityIterations == ParticleCount * (ParticleCount - 1) * IterationCount);
REQUIRE(velocityIterations == ParticleCount * IterationCount);
}
}
}
<commit_msg>Better result reporting on AppVeyor<commit_after>#include <Kunlaboro/Component.inl>
#include <Kunlaboro/Entity.inl>
#include <Kunlaboro/EntitySystem.inl>
#include <Kunlaboro/Views.inl>
#include "catch.hpp"
#include <atomic>
#include <random>
struct NumberComponent : public Kunlaboro::Component
{
NumberComponent(int i)
: Number(i)
{ }
int Number;
};
struct NameComponent : public Kunlaboro::Component
{
NameComponent(const std::string& name)
: Name(name)
{ }
std::string Name;
};
TEST_CASE("fizzbuzz", "[comprehensive][entity][view]")
{
Kunlaboro::EntitySystem es;
for (int i = 1; i <= 15; ++i)
{
auto ent = es.entityCreate();
if (i % 3 == 0 && i % 5 == 0)
ent.addComponent<NameComponent>("fizzbuzz");
else if (i % 3 == 0)
ent.addComponent<NameComponent>("fizz");
else if (i % 5 == 0)
ent.addComponent<NameComponent>("buzz");
ent.addComponent<NumberComponent>(i);
}
SECTION("Range-based for")
{
std::string result;
auto view = Kunlaboro::EntityView(es);
for (auto& ent : view)
{
if (ent.hasComponent<NameComponent>())
result += ent.getComponent<NameComponent>()->Name + " ";
else if (ent.hasComponent<NumberComponent>())
result += std::to_string(ent.getComponent<NumberComponent>()->Number) + " ";
}
REQUIRE(result == "1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz ");
}
SECTION("forEach - match any")
{
std::string result;
auto view = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_Any, NumberComponent, NameComponent>();
view.forEach([&result](Kunlaboro::Entity&, NumberComponent* number, NameComponent* name) {
if (name)
result += name->Name + " ";
if (number)
result += std::to_string(number->Number) + " ";
});
REQUIRE(result == "1 2 fizz 3 4 buzz 5 fizz 6 7 8 fizz 9 buzz 10 11 fizz 12 13 14 fizzbuzz 15 ");
}
SECTION("forEach - match all")
{
std::string result;
auto view = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, NumberComponent, NameComponent>();
view.forEach([&result](Kunlaboro::Entity&, NumberComponent& number, NameComponent& name) {
result += std::to_string(number.Number);
result += name.Name + " ";
});
REQUIRE(result == "3fizz 5buzz 6fizz 9fizz 10buzz 12fizz 15fizzbuzz ");
}
}
struct Position : public Kunlaboro::Component
{
Position(float x, float y)
: X(x)
, Y(y)
{ }
volatile float X, Y;
};
struct Velocity : public Kunlaboro::Component
{
Velocity(float x, float y)
: X(x)
, Y(y)
{ }
volatile float X, Y;
};
TEST_CASE("Simple n-body simulation - 100 particles", "[comprehensive][performance][view]")
{
Kunlaboro::EntitySystem es;
const int ParticleCount = 100;
std::random_device rand;
std::uniform_real_distribution<float> ang(0, 3.14159f * 2);
std::uniform_real_distribution<float> mag(0, 100);
for (int i = 0; i < ParticleCount; ++i)
{
auto ent = es.entityCreate();
float angle = ang(rand);
float magnitude = mag(rand);
ent.addComponent<Position>(std::cos(angle) * magnitude, std::sin(angle) * magnitude);
ent.addComponent<Velocity>((mag(rand) - 50) / 5, (mag(rand) - 50) / 5);
}
REQUIRE(es.componentGetPool(Kunlaboro::ComponentFamily<Position>::getFamily()).countBits() == ParticleCount);
REQUIRE(es.componentGetPool(Kunlaboro::ComponentFamily<Velocity>::getFamily()).countBits() == ParticleCount);
SECTION("forEach Iteration, 100 steps, 100 000 calls per step")
{
const int IterationCount = 100;
std::atomic<uint32_t> gravityIterations(0)
, velocityIterations(0);
auto entityView = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position,Velocity>();
auto particleList = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position>();
for (int step = 0; step < IterationCount; ++step)
{
entityView.forEach([&gravityIterations, &velocityIterations, &particleList](Kunlaboro::Entity& ent, Position& pos, Velocity& vel) {
particleList.forEach([&gravityIterations, &ent, &pos, &vel](Kunlaboro::Entity& ent2, Position& pos2) {
if (ent == ent2)
return;
const float xDelta = (pos2.X - pos.X);
const float yDelta = (pos2.Y - pos.Y);
const float deltaSqrt = std::sqrt(xDelta*xDelta + yDelta*yDelta + 1e-9f);
const float invDist = 1 / deltaSqrt;
const float invDist2 = invDist * invDist;
vel.X += xDelta * invDist2;
vel.Y += yDelta * invDist2;
gravityIterations.fetch_add(1);
});
pos.X += vel.X;
pos.Y += vel.Y;
velocityIterations.fetch_add(1);
});
}
REQUIRE(gravityIterations == ParticleCount * (ParticleCount - 1) * IterationCount);
REQUIRE(velocityIterations == ParticleCount * IterationCount);
}
SECTION("Parallel gravity iteration, 100 steps, 100 000 calls per step")
{
const int IterationCount = 100;
std::atomic<uint32_t> gravityIterations(0)
, velocityIterations(0);
Kunlaboro::detail::JobQueue queue;
auto entityView = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position,Velocity>();
auto particleList = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position>().parallel(queue);
for (int step = 0; step < IterationCount; ++step)
{
entityView.forEach([&gravityIterations, &velocityIterations, &particleList](Kunlaboro::Entity& ent, Position& pos, Velocity& vel) {
particleList.forEach([&gravityIterations, &ent, &pos, &vel](Kunlaboro::Entity& ent2, Position& pos2) {
if (ent == ent2)
return;
const float xDelta = (pos2.X - pos.X);
const float yDelta = (pos2.Y - pos.Y);
const float deltaSqrt = std::sqrt(xDelta*xDelta + yDelta*yDelta + 1e-9f);
const float invDist = 1 / deltaSqrt;
const float invDist2 = invDist * invDist;
vel.X += xDelta * invDist2;
vel.Y += yDelta * invDist2;
gravityIterations.fetch_add(1, std::memory_order_relaxed);
});
pos.X += vel.X;
pos.Y += vel.Y;
velocityIterations.fetch_add(1, std::memory_order_relaxed);
});
}
REQUIRE(gravityIterations == ParticleCount * (ParticleCount - 1) * IterationCount);
REQUIRE(velocityIterations == ParticleCount * IterationCount);
}
}
<|endoftext|>
|
<commit_before>#include "WrapperGenerator.h"
using namespace std;
void WrapperGenerator::initOpToGenMap() {
shared_ptr<TracingInnerWrapperGenerator> traceGen;
shared_ptr<CachingIPCInnerWrapperGenerator> cachingIPCGen;
shared_ptr<NonCachingIPCInnerWrapperGenerator> nonCachingIPCGen;
traceGen = make_shared<TracingInnerWrapperGenerator>(operationMap);
cachingIPCGen = make_shared<CachingIPCInnerWrapperGenerator>();
nonCachingIPCGen = make_shared<NonCachingIPCInnerWrapperGenerator>();
operationToGenerator = WrapperGenMap({{"MUTEX_LOCK", traceGen},
{"MUTEX_UNLOCK", traceGen},
{"CV_WAIT", traceGen},
{"CV_BROADCAST", traceGen},
{"CV_SIGNAL", traceGen},
{"QUEUE_ENQUEUE", traceGen},
{"QUEUE_DEQUEUE", traceGen},
{"MESSAGE_SEND", traceGen},
{"MESSAGE_RECEIVE", traceGen},
{"MKNOD", cachingIPCGen},
{"OPEN", cachingIPCGen},
{"PIPE", cachingIPCGen},
{"MSGGET", cachingIPCGen},
{"READ", nonCachingIPCGen},
{"WRITE", nonCachingIPCGen},
{"MSGRCV", nonCachingIPCGen},
{"MSGSND", nonCachingIPCGen}});
}
WrapperGenerator::WrapperGenerator(shared_ptr<unordered_map<string,
FunctionPrototype>> _prototypeMap,
std::shared_ptr<std::unordered_map<std::string,
std::string>> _operationMap,
string pathPrefix):
prototypeMap(_prototypeMap),
operationMap(_operationMap) {
initOpToGenMap();
headerFile.open(pathPrefix + "VProfEventWrappers.h");
implementationFile.open(pathPrefix + "VProfEventWrappers.cpp");
const string generatedFileMessage =
" ///////////////////////////////////////////////////// \n"
" // Note that this file was generated by VProfiler. // \n"
" // Please do not change the contents of this file! // \n"
" ///////////////////////////////////////////////////// \n\n";
headerFile << generatedFileMessage;
implementationFile << generatedFileMessage;
}
vector<string> WrapperGenerator::getFilenames() {
vector<string> result;
for (auto kv : *prototypeMap) {
result.push_back(kv.second.filename);
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
void WrapperGenerator::GenerateHeader() {
vector<string> includeNames = getFilenames();
headerFile << "#ifndef VPROFEVENTWRAPPERS_H\n#define VPROFEVENTWRAPPERS_H\n";
for (string &includeName : includeNames) {
headerFile << "#include \"" + includeName + "\"\n";
}
headerFile << "#include \"trace_tool.h\"\n\n"
"#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n";
for (auto kv : *prototypeMap) {
headerFile << kv.second.functionPrototype + ";\n\n";
}
headerFile << "#ifdef __cplusplus\n}\n#endif\n\n#endif";
headerFile.close();
}
void WrapperGenerator::GenerateImplementations() {
string operation;
implementationFile << "#include \"VProfEventWrappers.h\"\n\n";
for (auto kv : *prototypeMap) {
operation = (*operationMap)[kv.first];
implementationFile << kv.second.functionPrototype + " {\n\t";
if (kv.second.returnType != "void") {
implementationFile << kv.second.returnType + " result;\n\t";
}
operationToGenerator[operation]->GenerateWrapperPrologue(kv.first, kv.second);
if (kv.second.returnType != "void") {
implementationFile << "result = ";
}
implementationFile << kv.second.innerCallPrefix + "(";
for (int i = 0, j = kv.second.paramVars.size(); i < j; i++) {
implementationFile << kv.second.paramVars[i];
if (i != (j - 1)) {
implementationFile << ", ";
}
}
implementationFile <<");\n\t";
operationToGenerator[operation]->GenerateWrapperEpilogue(kv.first, kv.second);
if (kv.second.returnType != "void") {
implementationFile << "\treturn result;\n";
}
implementationFile << "}\n\n";
}
implementationFile.close();
}
void WrapperGenerator::GenerateWrappers() {
GenerateHeader();
GenerateImplementations();
}
<commit_msg>Change tab to newline.<commit_after>#include "WrapperGenerator.h"
using namespace std;
void WrapperGenerator::initOpToGenMap() {
shared_ptr<TracingInnerWrapperGenerator> traceGen;
shared_ptr<CachingIPCInnerWrapperGenerator> cachingIPCGen;
shared_ptr<NonCachingIPCInnerWrapperGenerator> nonCachingIPCGen;
traceGen = make_shared<TracingInnerWrapperGenerator>(operationMap);
cachingIPCGen = make_shared<CachingIPCInnerWrapperGenerator>();
nonCachingIPCGen = make_shared<NonCachingIPCInnerWrapperGenerator>();
operationToGenerator = WrapperGenMap({{"MUTEX_LOCK", traceGen},
{"MUTEX_UNLOCK", traceGen},
{"CV_WAIT", traceGen},
{"CV_BROADCAST", traceGen},
{"CV_SIGNAL", traceGen},
{"QUEUE_ENQUEUE", traceGen},
{"QUEUE_DEQUEUE", traceGen},
{"MESSAGE_SEND", traceGen},
{"MESSAGE_RECEIVE", traceGen},
{"MKNOD", cachingIPCGen},
{"OPEN", cachingIPCGen},
{"PIPE", cachingIPCGen},
{"MSGGET", cachingIPCGen},
{"READ", nonCachingIPCGen},
{"WRITE", nonCachingIPCGen},
{"MSGRCV", nonCachingIPCGen},
{"MSGSND", nonCachingIPCGen}});
}
WrapperGenerator::WrapperGenerator(shared_ptr<unordered_map<string,
FunctionPrototype>> _prototypeMap,
std::shared_ptr<std::unordered_map<std::string,
std::string>> _operationMap,
string pathPrefix):
prototypeMap(_prototypeMap),
operationMap(_operationMap) {
initOpToGenMap();
headerFile.open(pathPrefix + "VProfEventWrappers.h");
implementationFile.open(pathPrefix + "VProfEventWrappers.cpp");
const string generatedFileMessage =
" ///////////////////////////////////////////////////// \n"
" // Note that this file was generated by VProfiler. // \n"
" // Please do not change the contents of this file! // \n"
" ///////////////////////////////////////////////////// \n\n";
headerFile << generatedFileMessage;
implementationFile << generatedFileMessage;
}
vector<string> WrapperGenerator::getFilenames() {
vector<string> result;
for (auto kv : *prototypeMap) {
result.push_back(kv.second.filename);
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
void WrapperGenerator::GenerateHeader() {
vector<string> includeNames = getFilenames();
headerFile << "#ifndef VPROFEVENTWRAPPERS_H\n#define VPROFEVENTWRAPPERS_H\n";
for (string &includeName : includeNames) {
headerFile << "#include \"" + includeName + "\"\n";
}
headerFile << "#include \"trace_tool.h\"\n\n"
"#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n";
for (auto kv : *prototypeMap) {
headerFile << kv.second.functionPrototype + ";\n\n";
}
headerFile << "#ifdef __cplusplus\n}\n#endif\n\n#endif";
headerFile.close();
}
void WrapperGenerator::GenerateImplementations() {
string operation;
implementationFile << "#include \"VProfEventWrappers.h\"\n\n";
for (auto kv : *prototypeMap) {
operation = (*operationMap)[kv.first];
implementationFile << kv.second.functionPrototype + " {\n\t";
if (kv.second.returnType != "void") {
implementationFile << kv.second.returnType + " result;\n\t";
}
operationToGenerator[operation]->GenerateWrapperPrologue(kv.first, kv.second);
if (kv.second.returnType != "void") {
implementationFile << "result = ";
}
implementationFile << kv.second.innerCallPrefix + "(";
for (int i = 0, j = kv.second.paramVars.size(); i < j; i++) {
implementationFile << kv.second.paramVars[i];
if (i != (j - 1)) {
implementationFile << ", ";
}
}
implementationFile <<");\n\n";
operationToGenerator[operation]->GenerateWrapperEpilogue(kv.first, kv.second);
if (kv.second.returnType != "void") {
implementationFile << "\treturn result;\n";
}
implementationFile << "}\n\n";
}
implementationFile.close();
}
void WrapperGenerator::GenerateWrappers() {
GenerateHeader();
GenerateImplementations();
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <stdio.h>
#include <tools/fsys.hxx>
#include <comphelper/string.hxx>
#include "export.hxx"
#include <iostream>
using namespace std;
using comphelper::string::getToken;
using comphelper::string::getTokenCount;
namespace
{
static ::rtl::OString lcl_NormalizeFilename(const ::rtl::OString& rFilename)
{
return rFilename.copy(
::std::max(
rFilename.lastIndexOf( "\\" ),
rFilename.lastIndexOf( "/" ))+1);
};
}
extern void ConvertHalfwitdhToFullwidth( String& rString );
//
// class PFormEntrys
//
ByteString PFormEntrys::Dump()
{
ByteString sRet( "PFormEntrys\n" );
ByteString a("sText");
if (sText.size())
Export::DumpMap(a , sText);
return sRet;
}
sal_Bool PFormEntrys::GetTransex3Text( ByteString &rReturn,
sal_uInt16 nTyp, const ByteString &nLangIndex, sal_Bool bDel )
{
sal_Bool rc = GetText( rReturn , nTyp , nLangIndex , bDel );
ByteString test( rReturn );
for( sal_uInt16 idx = 0; idx < rReturn.Len(); idx++ )
{
if( rReturn.GetChar( idx ) == '\"' && ( idx >= 1 ) && rReturn.GetChar( idx-1 ) == '\\' )
{
rReturn.Erase( idx-1 , 1 );
}
}
//if( !rReturn.Equals( test ) )
// printf("*CHANGED******************\n%s\n%s\n",test.GetBuffer(),rReturn.GetBuffer());
return rc;
}
/*****************************************************************************/
sal_Bool PFormEntrys::GetText( ByteString &rReturn,
sal_uInt16 nTyp, const ByteString &nLangIndex, sal_Bool bDel )
{
sal_Bool bReturn=sal_True;
switch ( nTyp ) {
case STRING_TYP_TEXT :
rReturn = sText[ nLangIndex ];
if ( bDel )
sText[ nLangIndex ] = "";
bReturn = bTextFirst[ nLangIndex ];
bTextFirst[ nLangIndex ] = sal_False;
break;
case STRING_TYP_HELPTEXT :
rReturn = sHelpText;
break;
case STRING_TYP_QUICKHELPTEXT :
rReturn = sQuickHelpText[ nLangIndex ];
if ( bDel )
sQuickHelpText[ nLangIndex ] = "";
bReturn = bQuickHelpTextFirst[ nLangIndex ];
bQuickHelpTextFirst[ nLangIndex ] = sal_False;
break;
case STRING_TYP_TITLE :
rReturn = sTitle[ nLangIndex ];
if ( bDel )
sTitle[ nLangIndex ] = "";
bReturn = bTitleFirst[ nLangIndex ];
bTitleFirst[ nLangIndex ] = sal_False;
break;
}
return bReturn;
}
//
// class MergeData
//
MergeData::~MergeData()
{
}
PFormEntrys* MergeData::GetPFormEntries()
{
if( aMap.find( ByteString("HACK") ) != aMap.end() )
return aMap[ ByteString("HACK") ];
return NULL;
}
void MergeData::Insert(PFormEntrys* pfEntrys )
{
aMap.insert( PFormEntrysHashMap::value_type( ByteString("HACK") , pfEntrys ) );
}
rtl::OString MergeData::Dump()
{
printf("MergeData sTyp = %s , sGid = %s , sLid =%s , sFilename = %s\n",
sTyp.getStr(), sGID.getStr(), sLID.getStr(), sFilename.getStr());
PFormEntrysHashMap::const_iterator idbg;
for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg )
{
printf("aMap[ %s ] = " ,idbg->first.getStr());
( (PFormEntrys*)(idbg->second) )->Dump();
printf("\n");
}
printf("\n");
return rtl::OString(RTL_CONSTASCII_STRINGPARAM("MergeData\n"));
}
PFormEntrys* MergeData::GetPFObject( const rtl::OString& rPFO )
{
if( aMap.find( ByteString("HACK") ) != aMap.end() )
return aMap[ rPFO ];
return NULL;
}
sal_Bool MergeData::operator==( ResData *pData )
{
ByteString sResTyp_upper( pData->sResTyp );
sResTyp_upper.ToUpperAscii();
ByteString sTyp_upper( sTyp );
sTyp_upper.ToUpperAscii();
return (( pData->sId == sLID ) &&
( pData->sGId == sGID ) &&
( sResTyp_upper == sTyp_upper )
);
}
//
// class MergeDataFile
//
#define FFORMAT_UNKNOWN 0x0000
#define FFORMAT_NEW 0x0001
#define FFORMAT_OLD 0x0002
MergeDataFile::MergeDataFile(
const ByteString &rFileName,
const ByteString& sFile,
bool bErrLog,
bool bCaseSensitive)
: bErrorLog( bErrLog )
{
SvFileStream aInputStream( String( rFileName, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ );
aInputStream.SetStreamCharSet( RTL_TEXTENCODING_MS_1252 );
rtl::OString sLine;
const ByteString sHACK("HACK");
const ::rtl::OString sFileNormalized(lcl_NormalizeFilename(sFile));
const bool isFileEmpty = !sFileNormalized.isEmpty();
if( !aInputStream.IsOpen() )
{
printf("Warning : Can't open %s\n", rFileName.GetBuffer());
return;
}
while ( !aInputStream.IsEof())
{
xub_StrLen nToks;
aInputStream.ReadLine( sLine );
nToks = getTokenCount(sLine, '\t');
if ( nToks == 15 )
{
// Skip all wrong filenames
const ::rtl::OString filename = lcl_NormalizeFilename(getToken(sLine, 1 , '\t'));
if(isFileEmpty || sFileNormalized.equals("") || (!isFileEmpty && filename.equals(sFileNormalized)) )
{
sal_Int32 rIdx = 0;
const ByteString sTYP = sLine.getToken( 3, '\t', rIdx );
const ByteString sGID = sLine.getToken( 0, '\t', rIdx ); // 4
const ByteString sLID = sLine.getToken( 0, '\t', rIdx ); // 5
ByteString sPFO = sLine.getToken( 1, '\t', rIdx ); // 7
sPFO = sHACK;
ByteString nLANG = sLine.getToken( 1, '\t', rIdx ); // 9
nLANG = comphelper::string::strip(nLANG, ' ');
const ByteString sTEXT = sLine.getToken( 0, '\t', rIdx ); // 10
const ByteString sQHTEXT = sLine.getToken( 1, '\t', rIdx ); // 12
const ByteString sTITLE = sLine.getToken( 0, '\t', rIdx ); // 13
if( !nLANG.EqualsIgnoreCaseAscii("en-US") )
{
aLanguageSet.insert(nLANG);
InsertEntry( sTYP, sGID, sLID, sPFO, nLANG, sTEXT, sQHTEXT, sTITLE, filename, bCaseSensitive );
}
}
}
else if ( nToks == 10 )
{
printf("ERROR: File format is obsolete and no longer supported!\n");
}
}
aInputStream.Close();
}
MergeDataFile::~MergeDataFile()
{
for (MergeDataHashMap::iterator aI = aMap.begin(), aEnd = aMap.end(); aI != aEnd; ++aI)
delete aI->second;
}
ByteString MergeDataFile::Dump(){
ByteString sRet( "MergeDataFile\n" );
printf("MergeDataFile\n");
MergeDataHashMap::const_iterator idbg;
for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg )
{
printf("aMap[ %s ] = ",idbg->first.getStr());
idbg->second->Dump();
printf("\n");
}
printf("\n");
return sRet;
}
std::vector<rtl::OString> MergeDataFile::GetLanguages(){
return std::vector<rtl::OString>(aLanguageSet.begin(),aLanguageSet.end());
}
MergeData *MergeDataFile::GetMergeData( ResData *pResData , bool bCaseSensitive )
{
ByteString sOldG = pResData->sGId;
ByteString sOldL = pResData->sId;
ByteString sGID = pResData->sGId;
ByteString sLID;
if(!sGID.Len())
sGID = pResData->sId;
else
sLID = pResData->sId;
pResData->sGId = sGID;
pResData->sId = sLID;
ByteString sKey = CreateKey( pResData->sResTyp , pResData->sGId , pResData->sId , pResData->sFilename , bCaseSensitive );
if(aMap.find( sKey ) != aMap.end())
{
pResData->sGId = sOldG;
pResData->sId = sOldL;
return aMap[ sKey ];
}
pResData->sGId = sOldG;
pResData->sId = sOldL;
return NULL;
}
PFormEntrys *MergeDataFile::GetPFormEntrys( ResData *pResData )
{
// search for requested PFormEntrys
MergeData *pData = GetMergeData( pResData );
if ( pData )
return pData->GetPFormEntries();
return NULL;
}
PFormEntrys *MergeDataFile::GetPFormEntrysCaseSensitive( ResData *pResData )
{
// search for requested PFormEntrys
MergeData *pData = GetMergeData( pResData , true );
if ( pData )
return pData->GetPFormEntries();
return NULL;
}
void MergeDataFile::InsertEntry(
const ByteString &rTYP, const ByteString &rGID,
const ByteString &rLID, const ByteString &rPFO,
const ByteString &nLANG, const ByteString &rTEXT,
const ByteString &rQHTEXT, const ByteString &rTITLE ,
const ByteString &rInFilename , bool bCaseSensitive
)
{
MergeData *pData;
// search for MergeData
ByteString sKey = CreateKey( rTYP , rGID , rLID , rInFilename , bCaseSensitive );
MergeDataHashMap::const_iterator mit;
mit = aMap.find( sKey );
if( mit != aMap.end() )
{
pData = mit->second;
}
else
{
pData = new MergeData( rTYP, rGID, rLID, rInFilename );
aMap.insert( MergeDataHashMap::value_type( sKey, pData ) );
}
PFormEntrys *pFEntrys = 0;
// search for PFormEntrys
pFEntrys = pData->GetPFObject( rPFO );
if( !pFEntrys )
{
// create new PFormEntrys, cause no one exists with current properties
pFEntrys = new PFormEntrys( rPFO );
pData->Insert( pFEntrys );
}
// finaly insert the cur string
pFEntrys->InsertEntry( nLANG , rTEXT, rQHTEXT, rTITLE );
}
ByteString MergeDataFile::CreateKey( const ByteString& rTYP , const ByteString& rGID , const ByteString& rLID , const ByteString& rFilename , bool bCaseSensitive )
{
static const ::rtl::OString sStroke('-');
::rtl::OString sKey( rTYP );
sKey += sStroke;
sKey += rGID;
sKey += sStroke;
sKey += rLID;
sKey += sStroke;
sKey += lcl_NormalizeFilename(rFilename);
OSL_TRACE("created key: %s", sKey.getStr());
if(bCaseSensitive)
return sKey; // officecfg case sensitive identifier
return sKey.toAsciiUpperCase();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>unused test string<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <stdio.h>
#include <tools/fsys.hxx>
#include <comphelper/string.hxx>
#include "export.hxx"
#include <iostream>
using namespace std;
using comphelper::string::getToken;
using comphelper::string::getTokenCount;
namespace
{
static ::rtl::OString lcl_NormalizeFilename(const ::rtl::OString& rFilename)
{
return rFilename.copy(
::std::max(
rFilename.lastIndexOf( "\\" ),
rFilename.lastIndexOf( "/" ))+1);
};
}
extern void ConvertHalfwitdhToFullwidth( String& rString );
//
// class PFormEntrys
//
ByteString PFormEntrys::Dump()
{
ByteString sRet( "PFormEntrys\n" );
ByteString a("sText");
if (sText.size())
Export::DumpMap(a , sText);
return sRet;
}
sal_Bool PFormEntrys::GetTransex3Text( ByteString &rReturn,
sal_uInt16 nTyp, const ByteString &nLangIndex, sal_Bool bDel )
{
sal_Bool rc = GetText( rReturn , nTyp , nLangIndex , bDel );
for( sal_uInt16 idx = 0; idx < rReturn.Len(); idx++ )
{
if( rReturn.GetChar( idx ) == '\"' && ( idx >= 1 ) && rReturn.GetChar( idx-1 ) == '\\' )
{
rReturn.Erase( idx-1 , 1 );
}
}
return rc;
}
/*****************************************************************************/
sal_Bool PFormEntrys::GetText( ByteString &rReturn,
sal_uInt16 nTyp, const ByteString &nLangIndex, sal_Bool bDel )
{
sal_Bool bReturn=sal_True;
switch ( nTyp ) {
case STRING_TYP_TEXT :
rReturn = sText[ nLangIndex ];
if ( bDel )
sText[ nLangIndex ] = "";
bReturn = bTextFirst[ nLangIndex ];
bTextFirst[ nLangIndex ] = sal_False;
break;
case STRING_TYP_HELPTEXT :
rReturn = sHelpText;
break;
case STRING_TYP_QUICKHELPTEXT :
rReturn = sQuickHelpText[ nLangIndex ];
if ( bDel )
sQuickHelpText[ nLangIndex ] = "";
bReturn = bQuickHelpTextFirst[ nLangIndex ];
bQuickHelpTextFirst[ nLangIndex ] = sal_False;
break;
case STRING_TYP_TITLE :
rReturn = sTitle[ nLangIndex ];
if ( bDel )
sTitle[ nLangIndex ] = "";
bReturn = bTitleFirst[ nLangIndex ];
bTitleFirst[ nLangIndex ] = sal_False;
break;
}
return bReturn;
}
//
// class MergeData
//
MergeData::~MergeData()
{
}
PFormEntrys* MergeData::GetPFormEntries()
{
if( aMap.find( ByteString("HACK") ) != aMap.end() )
return aMap[ ByteString("HACK") ];
return NULL;
}
void MergeData::Insert(PFormEntrys* pfEntrys )
{
aMap.insert( PFormEntrysHashMap::value_type( ByteString("HACK") , pfEntrys ) );
}
rtl::OString MergeData::Dump()
{
printf("MergeData sTyp = %s , sGid = %s , sLid =%s , sFilename = %s\n",
sTyp.getStr(), sGID.getStr(), sLID.getStr(), sFilename.getStr());
PFormEntrysHashMap::const_iterator idbg;
for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg )
{
printf("aMap[ %s ] = " ,idbg->first.getStr());
( (PFormEntrys*)(idbg->second) )->Dump();
printf("\n");
}
printf("\n");
return rtl::OString(RTL_CONSTASCII_STRINGPARAM("MergeData\n"));
}
PFormEntrys* MergeData::GetPFObject( const rtl::OString& rPFO )
{
if( aMap.find( ByteString("HACK") ) != aMap.end() )
return aMap[ rPFO ];
return NULL;
}
sal_Bool MergeData::operator==( ResData *pData )
{
ByteString sResTyp_upper( pData->sResTyp );
sResTyp_upper.ToUpperAscii();
ByteString sTyp_upper( sTyp );
sTyp_upper.ToUpperAscii();
return (( pData->sId == sLID ) &&
( pData->sGId == sGID ) &&
( sResTyp_upper == sTyp_upper )
);
}
//
// class MergeDataFile
//
#define FFORMAT_UNKNOWN 0x0000
#define FFORMAT_NEW 0x0001
#define FFORMAT_OLD 0x0002
MergeDataFile::MergeDataFile(
const ByteString &rFileName,
const ByteString& sFile,
bool bErrLog,
bool bCaseSensitive)
: bErrorLog( bErrLog )
{
SvFileStream aInputStream( String( rFileName, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ );
aInputStream.SetStreamCharSet( RTL_TEXTENCODING_MS_1252 );
rtl::OString sLine;
const ByteString sHACK("HACK");
const ::rtl::OString sFileNormalized(lcl_NormalizeFilename(sFile));
const bool isFileEmpty = !sFileNormalized.isEmpty();
if( !aInputStream.IsOpen() )
{
printf("Warning : Can't open %s\n", rFileName.GetBuffer());
return;
}
while ( !aInputStream.IsEof())
{
xub_StrLen nToks;
aInputStream.ReadLine( sLine );
nToks = getTokenCount(sLine, '\t');
if ( nToks == 15 )
{
// Skip all wrong filenames
const ::rtl::OString filename = lcl_NormalizeFilename(getToken(sLine, 1 , '\t'));
if(isFileEmpty || sFileNormalized.equals("") || (!isFileEmpty && filename.equals(sFileNormalized)) )
{
sal_Int32 rIdx = 0;
const ByteString sTYP = sLine.getToken( 3, '\t', rIdx );
const ByteString sGID = sLine.getToken( 0, '\t', rIdx ); // 4
const ByteString sLID = sLine.getToken( 0, '\t', rIdx ); // 5
ByteString sPFO = sLine.getToken( 1, '\t', rIdx ); // 7
sPFO = sHACK;
ByteString nLANG = sLine.getToken( 1, '\t', rIdx ); // 9
nLANG = comphelper::string::strip(nLANG, ' ');
const ByteString sTEXT = sLine.getToken( 0, '\t', rIdx ); // 10
const ByteString sQHTEXT = sLine.getToken( 1, '\t', rIdx ); // 12
const ByteString sTITLE = sLine.getToken( 0, '\t', rIdx ); // 13
if( !nLANG.EqualsIgnoreCaseAscii("en-US") )
{
aLanguageSet.insert(nLANG);
InsertEntry( sTYP, sGID, sLID, sPFO, nLANG, sTEXT, sQHTEXT, sTITLE, filename, bCaseSensitive );
}
}
}
else if ( nToks == 10 )
{
printf("ERROR: File format is obsolete and no longer supported!\n");
}
}
aInputStream.Close();
}
MergeDataFile::~MergeDataFile()
{
for (MergeDataHashMap::iterator aI = aMap.begin(), aEnd = aMap.end(); aI != aEnd; ++aI)
delete aI->second;
}
ByteString MergeDataFile::Dump(){
ByteString sRet( "MergeDataFile\n" );
printf("MergeDataFile\n");
MergeDataHashMap::const_iterator idbg;
for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg )
{
printf("aMap[ %s ] = ",idbg->first.getStr());
idbg->second->Dump();
printf("\n");
}
printf("\n");
return sRet;
}
std::vector<rtl::OString> MergeDataFile::GetLanguages(){
return std::vector<rtl::OString>(aLanguageSet.begin(),aLanguageSet.end());
}
MergeData *MergeDataFile::GetMergeData( ResData *pResData , bool bCaseSensitive )
{
ByteString sOldG = pResData->sGId;
ByteString sOldL = pResData->sId;
ByteString sGID = pResData->sGId;
ByteString sLID;
if(!sGID.Len())
sGID = pResData->sId;
else
sLID = pResData->sId;
pResData->sGId = sGID;
pResData->sId = sLID;
ByteString sKey = CreateKey( pResData->sResTyp , pResData->sGId , pResData->sId , pResData->sFilename , bCaseSensitive );
if(aMap.find( sKey ) != aMap.end())
{
pResData->sGId = sOldG;
pResData->sId = sOldL;
return aMap[ sKey ];
}
pResData->sGId = sOldG;
pResData->sId = sOldL;
return NULL;
}
PFormEntrys *MergeDataFile::GetPFormEntrys( ResData *pResData )
{
// search for requested PFormEntrys
MergeData *pData = GetMergeData( pResData );
if ( pData )
return pData->GetPFormEntries();
return NULL;
}
PFormEntrys *MergeDataFile::GetPFormEntrysCaseSensitive( ResData *pResData )
{
// search for requested PFormEntrys
MergeData *pData = GetMergeData( pResData , true );
if ( pData )
return pData->GetPFormEntries();
return NULL;
}
void MergeDataFile::InsertEntry(
const ByteString &rTYP, const ByteString &rGID,
const ByteString &rLID, const ByteString &rPFO,
const ByteString &nLANG, const ByteString &rTEXT,
const ByteString &rQHTEXT, const ByteString &rTITLE ,
const ByteString &rInFilename , bool bCaseSensitive
)
{
MergeData *pData;
// search for MergeData
ByteString sKey = CreateKey( rTYP , rGID , rLID , rInFilename , bCaseSensitive );
MergeDataHashMap::const_iterator mit;
mit = aMap.find( sKey );
if( mit != aMap.end() )
{
pData = mit->second;
}
else
{
pData = new MergeData( rTYP, rGID, rLID, rInFilename );
aMap.insert( MergeDataHashMap::value_type( sKey, pData ) );
}
PFormEntrys *pFEntrys = 0;
// search for PFormEntrys
pFEntrys = pData->GetPFObject( rPFO );
if( !pFEntrys )
{
// create new PFormEntrys, cause no one exists with current properties
pFEntrys = new PFormEntrys( rPFO );
pData->Insert( pFEntrys );
}
// finaly insert the cur string
pFEntrys->InsertEntry( nLANG , rTEXT, rQHTEXT, rTITLE );
}
ByteString MergeDataFile::CreateKey( const ByteString& rTYP , const ByteString& rGID , const ByteString& rLID , const ByteString& rFilename , bool bCaseSensitive )
{
static const ::rtl::OString sStroke('-');
::rtl::OString sKey( rTYP );
sKey += sStroke;
sKey += rGID;
sKey += sStroke;
sKey += rLID;
sKey += sStroke;
sKey += lcl_NormalizeFilename(rFilename);
OSL_TRACE("created key: %s", sKey.getStr());
if(bCaseSensitive)
return sKey; // officecfg case sensitive identifier
return sKey.toAsciiUpperCase();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: sdxmlwrp.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: cl $ $Date: 2000-11-17 11:13:31 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef _SDXMLWRP_HXX
#include "sdxmlwrp.hxx"
#endif
#ifndef _SDXMLIMP_HXX
#include <xmloff/sdxmlimp.hxx>
#endif
#ifndef _SDXMLEXP_HXX
#include <xmloff/sdxmlexp.hxx>
#endif
#ifndef _DRAWDOC_HXX
#include "drawdoc.hxx"
#endif
#ifndef _UNO_MAPPING_HXX_
#include <uno/mapping.hxx> //! only necessary until SfxMedium has a uno3 DataSource / DataSink
#endif
#include <com/sun/star/xml/sax/XErrorHandler.hpp>
#include <com/sun/star/xml/sax/XEntityResolver.hpp>
#include <com/sun/star/xml/sax/InputSource.hpp>
#include <com/sun/star/xml/sax/XDTDHandler.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include "pkgurl.hxx"
using namespace com::sun::star;
using namespace rtl;
//////////////////////////////////////////////////////////////////////////////
char __READONLY_DATA sXML_drawing[] = "drawing";
char __READONLY_DATA sXML_impress[] = "presentation";
//////////////////////////////////////////////////////////////////////////////
SdXMLWrapper::SdXMLWrapper(
uno::Reference<frame::XModel>& xRef,
SfxMedium& rMedium,
BOOL bIsDraw, BOOL bShowProg)
: mxLocalModel(xRef),
mrMedium(rMedium),
mbIsDraw(bIsDraw),
mbShowProgress(bShowProg)
{
}
BOOL SdXMLWrapper::Import()
{
if(!mxLocalModel.is())
{
DBG_ERROR("Got NO Model in XMLImport");
return FALSE;
}
uno::Reference<lang::XServiceInfo> xServiceInfo(mxLocalModel, uno::UNO_QUERY);
if(!xServiceInfo.is() || !xServiceInfo->supportsService(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocument"))))
{
DBG_ERROR("Model is no DrawingDocument in XMLImport");
return FALSE;
}
uno::Reference<lang::XMultiServiceFactory> xServiceFactory(::comphelper::getProcessServiceFactory());
if(!xServiceFactory.is())
{
DBG_ERROR("XMLReader::Read: got no service manager");
return FALSE;
}
// Get data source ...
uno::Reference<io::XActiveDataSource> xSource = mrMedium.GetDataSource();
if(!xSource.is())
{
// // If we didn't get a data source from a medium, we have to create one
// XInterfaceRef xFactory = xServiceFactory->createInstance(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.DataSourceFactory"));
// if(xFactory.is())
// {
// XMultiServiceFactoryRef xMFactory(xFactory, USR_QUERY);
//
// if(xMFactory.is())
// {
// UString sURL(S2WS(mrMedium.GetName()));
// Sequence<Any> aArgs(1);
// Any* pArgs = aArgs.getArray();
//
// pArgs->setString(sURL);
//
// XInterfaceRef xSrc = xMFactory->createInstanceWithArguments(sURL, aArgs);
//
// if(xSrc.is())
// {
// xSrc->queryInterface(XActiveDataSource::getSmartUik(), xSource);
// }
// }
// }
}
// get data source
if(!xSource.is())
{
DBG_ERROR("XMLReader::Read: data source missing");
return FALSE;
}
// get parser
uno::Reference<uno::XInterface> xXMLParser(xServiceFactory->createInstance(
OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser"))));
if(!xXMLParser.is())
{
DBG_ERROR("com.sun.star.xml.sax.Parser service missing");
return FALSE;
}
// get a pipe for connecting the data source to the parser
uno::Reference<uno::XInterface> xPipe(xServiceFactory->createInstance(
OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.Pipe"))));
if(!xPipe.is())
{
DBG_ERROR("com.sun.star.io.Pipe service missing");
return FALSE;
}
UINT16 nStyleFamilyMask(0);
BOOL bLoadDoc(TRUE);
// this is stuff for loading only styles or add-load documents, needed later
// USHORT nStyleFamilyMask = SFX_STYLE_FAMILY_ALL;
// BOOL bInsert;
// if( aOpt.IsFmtsOnly() )
// {
// bLoadDoc = FALSE;
// bInsert = aOpt.IsMerge();
// nStyleFamilyMask = 0U;
// if( aOpt.IsFrmFmts() )
// nStyleFamilyMask |= SFX_STYLE_FAMILY_FRAME;
// if( aOpt.IsPageDescs() )
// nStyleFamilyMask |= SFX_STYLE_FAMILY_PAGE;
// if( aOpt.IsTxtFmts() )
// nStyleFamilyMask |= (SFX_STYLE_FAMILY_CHAR|SFX_STYLE_FAMILY_PARA);
// if( aOpt.IsNumRules() )
// nStyleFamilyMask |= SFX_STYLE_FAMILY_PSEUDO;
// }
// else
// {
// bLoadDoc = TRUE;
// bInsert = bInsertMode;
// nStyleFamilyMask = SFX_STYLE_FAMILY_ALL;
// }
// aOpt.ResetAllFmtsOnly();
// get filter
uno::Reference<xml::sax::XDocumentHandler> xFilter =
new SdXMLImport(mxLocalModel, bLoadDoc, nStyleFamilyMask, mbShowProgress, IsDraw());
// connect pipe's output stream to the data source
uno::Reference<io::XOutputStream> xPipeOutput(xPipe, uno::UNO_QUERY);
xSource->setOutputStream(xPipeOutput);
// connect pipe's input stream to the parser
xml::sax::InputSource aParserInput;
uno::Reference<io::XInputStream> xPipeInput(xPipe, uno::UNO_QUERY);
aParserInput.aInputStream = xPipeInput;
aParserInput.sSystemId = mrMedium.GetName();
OUString sFileName = mrMedium.GetName();
// connect parser and filter
uno::Reference<xml::sax::XParser> xParser(xXMLParser, uno::UNO_QUERY);
// uno::Reference<xml::sax::XDocumentHandler> xPacker =
// new URLPacker(sFileName, xFilter, sal_True, sal_False);
// xParser->setDocumentHandler(xPacker);
xParser->setDocumentHandler(xFilter);
// parse
uno::Reference<io::XActiveDataControl> xSourceControl(xSource, uno::UNO_QUERY);
xSourceControl->start();
BOOL bRetval(TRUE);
try
{
xParser->parseStream(aParserInput);
}
catch(xml::sax::SAXParseException)
{
bRetval = FALSE;
}
catch(xml::sax::SAXException)
{
bRetval = FALSE;
}
catch(io::IOException)
{
bRetval = FALSE;
}
return bRetval;
}
BOOL SdXMLWrapper::Export()
{
if(!mxLocalModel.is())
{
DBG_ERROR("Got NO Model in XMLExport");
return FALSE;
}
uno::Reference<lang::XServiceInfo> xServiceInfo(mxLocalModel, uno::UNO_QUERY);
if(!xServiceInfo.is() || !xServiceInfo->supportsService(
OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocument"))))
{
DBG_ERROR("Model is no DrawingDocument in XMLExport");
return FALSE;
}
uno::Reference<lang::XMultiServiceFactory> xServiceFactory(::comphelper::getProcessServiceFactory());
if(!xServiceFactory.is())
{
DBG_ERROR("got no service manager");
return FALSE;
}
uno::Reference<uno::XInterface> xWriter(xServiceFactory->createInstance(
OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer"))));
if(!xWriter.is())
{
DBG_ERROR("com.sun.star.xml.sax.Writer service missing");
return FALSE;
}
// smart -> uno3 conversion only until SfxMedium has a uno3 DataSink
uno::Reference<io::XOutputStream> xOut = mrMedium.GetDataSink();
uno::Reference<io::XActiveDataSource> xSrc(xWriter, uno::UNO_QUERY);
xSrc->setOutputStream(xOut);
uno::Reference<xml::sax::XDocumentHandler> xHandler(xWriter, uno::UNO_QUERY);
OUString sFileName = mrMedium.GetName();
#ifdef XMLTESTBIN
uno::Reference<xml::sax::XDocumentHandler> xPacker =
new URLPacker(sFileName, xHandler, sal_False, sal_True);
SdXMLExport aExp(mxLocalModel, sFileName, xPacker, mbShowProgress, IsDraw());
#else
SdXMLExport aExp(mxLocalModel, sFileName, xHandler, mbShowProgress, IsDraw());
#endif
// give string descriptor as parameter for doc type
BOOL bRet = (0 == aExp.exportDoc( IsDraw() ? sXML_drawing : sXML_impress ));
return bRet;
}
<commit_msg>#80795#: new package concept/added SvxXMLGraphicHelper<commit_after>/*************************************************************************
*
* $RCSfile: sdxmlwrp.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: ka $ $Date: 2000-12-02 10:13:02 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef _SDXMLIMP_HXX
#include <xmloff/sdxmlimp.hxx>
#endif
#ifndef _SDXMLEXP_HXX
#include <xmloff/sdxmlexp.hxx>
#endif
#ifndef _DRAWDOC_HXX
#include "drawdoc.hxx"
#endif
#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif
#ifndef _XMLGRHLP_HXX
#include <svx/xmlgrhlp.hxx>
#endif
#include <com/sun/star/xml/sax/XErrorHandler.hpp>
#include <com/sun/star/xml/sax/XEntityResolver.hpp>
#include <com/sun/star/xml/sax/InputSource.hpp>
#include <com/sun/star/xml/sax/XDTDHandler.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include "sdxmlwrp.hxx"
#include "pkgurl.hxx"
using namespace com::sun::star;
using namespace rtl;
//////////////////////////////////////////////////////////////////////////////
char __READONLY_DATA sXML_drawing[] = "drawing";
char __READONLY_DATA sXML_impress[] = "presentation";
char __READONLY_DATA sXML_content[] = "Content";
// ----------------
// - SdXMLWrapper -
// ----------------
SdXMLWrapper::SdXMLWrapper( uno::Reference<frame::XModel>& xRef,
SfxMedium& rMedium, BOOL bIsDraw, BOOL bShowProg ) :
mxLocalModel ( xRef ),
mrMedium ( rMedium ),
mbIsDraw ( bIsDraw ),
mbShowProgress ( bShowProg )
{
}
// -----------------------------------------------------------------------------
BOOL SdXMLWrapper::Import()
{
if( !mxLocalModel.is() )
{
DBG_ERROR("Got NO Model in XMLImport");
return FALSE;
}
uno::Reference<lang::XServiceInfo> xServiceInfo(mxLocalModel, uno::UNO_QUERY);
if( !xServiceInfo.is() || !xServiceInfo->supportsService( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) ) )
{
DBG_ERROR( "Model is no DrawingDocument in XMLImport" );
return FALSE;
}
uno::Reference<lang::XMultiServiceFactory> xServiceFactory( ::comphelper::getProcessServiceFactory() );
if( !xServiceFactory.is() )
{
DBG_ERROR( "XMLReader::Read: got no service manager" );
return FALSE;
}
uno::Reference< uno::XInterface> xXMLParser( xServiceFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" ) ) ) );
if( !xXMLParser.is() )
{
DBG_ERROR( "com.sun.star.xml.sax.Parser service missing" );
return FALSE;
}
UINT16 nStyleFamilyMask = 0;
BOOL bLoadDoc = TRUE, bRet = FALSE;
// this is stuff for loading only styles or add-load documents, needed later
// USHORT nStyleFamilyMask = SFX_STYLE_FAMILY_ALL;
// BOOL bInsert;
// if( aOpt.IsFmtsOnly() )
// {
// bLoadDoc = FALSE;
// bInsert = aOpt.IsMerge();
// nStyleFamilyMask = 0U;
// if( aOpt.IsFrmFmts() )
// nStyleFamilyMask |= SFX_STYLE_FAMILY_FRAME;
// if( aOpt.IsPageDescs() )
// nStyleFamilyMask |= SFX_STYLE_FAMILY_PAGE;
// if( aOpt.IsTxtFmts() )
// nStyleFamilyMask |= (SFX_STYLE_FAMILY_CHAR|SFX_STYLE_FAMILY_PARA);
// if( aOpt.IsNumRules() )
// nStyleFamilyMask |= SFX_STYLE_FAMILY_PSEUDO;
// }
// else
// {
// bLoadDoc = TRUE;
// bInsert = bInsertMode;
// nStyleFamilyMask = SFX_STYLE_FAMILY_ALL;
// }
// aOpt.ResetAllFmtsOnly();
try
{
xml::sax::InputSource aParserInput;
SvStorageStreamRef xIStm;
SvStorage* pStorage = mrMedium.GetStorage();
uno::Reference< io::XActiveDataSource > xSource;
aParserInput.sSystemId = mrMedium.GetName();
if( pStorage )
{
static const String aContentStmName( RTL_CONSTASCII_USTRINGPARAM( sXML_content ) );
xIStm = pStorage->OpenStream( aContentStmName, STREAM_READ | STREAM_NOCREATE );
if( xIStm.Is() )
{
xIStm->SetBufferSize( 16 * 1024 );
aParserInput.aInputStream = new utl::OInputStreamWrapper( *xIStm );
}
else
{
DBG_ERROR( "could not open Content stream" );
return FALSE;
}
}
else
{
uno::Reference< uno::XInterface > xPipe;
mrMedium.GetInStream()->Seek( 0 );
xSource = mrMedium.GetDataSource();
DBG_ASSERT( xSource.is(), "got no data source from medium" );
if( !xSource.is() )
return sal_False;
xPipe = xServiceFactory->createInstance( OUString::createFromAscii( "com.sun.star.io.Pipe" ) );
DBG_ASSERT( xPipe.is(), "com.sun.star.io.Pipe service missing" );
if( !xPipe.is() )
return sal_False;
xSource->setOutputStream( uno::Reference< io::XOutputStream >( xPipe, uno::UNO_QUERY ) );
aParserInput.aInputStream = uno::Reference< io::XInputStream >( xPipe, uno::UNO_QUERY );
}
if( aParserInput.aInputStream.is() )
{
SvXMLGraphicHelper* pGraphicHelper;
uno::Reference< container::XIndexContainer > xGrfContainer;
uno::Reference< xml::sax::XParser > xParser( xXMLParser, uno::UNO_QUERY );
if( pStorage )
{
pGraphicHelper = SvXMLGraphicHelper::Create( *pStorage, GRAPHICHELPER_MODE_READ );
xGrfContainer = pGraphicHelper;
}
xParser->setDocumentHandler( new SdXMLImport( mxLocalModel, xGrfContainer,
bLoadDoc, nStyleFamilyMask,
mbShowProgress, IsDraw() ) );
if( !pStorage )
uno::Reference< io::XActiveDataControl >( xSource, uno::UNO_QUERY )->start();
xParser->parseStream( aParserInput );
if( pStorage )
SvXMLGraphicHelper::Destroy( pGraphicHelper );
bRet = TRUE;
}
}
catch( xml::sax::SAXParseException )
{
}
catch( xml::sax::SAXException )
{
}
catch( io::IOException )
{
}
return bRet;
}
// -----------------------------------------------------------------------------
BOOL SdXMLWrapper::Export()
{
BOOL bRet = FALSE;
if( !mxLocalModel.is() )
{
DBG_ERROR("Got NO Model in XMLExport");
return FALSE;
}
uno::Reference< lang::XServiceInfo > xServiceInfo( mxLocalModel, uno::UNO_QUERY );
if( !xServiceInfo.is() || !xServiceInfo->supportsService( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) ) )
{
DBG_ERROR( "Model is no DrawingDocument in XMLExport" );
return FALSE;
}
uno::Reference< lang::XMultiServiceFactory> xServiceFactory( ::comphelper::getProcessServiceFactory() );
if( !xServiceFactory.is() )
{
DBG_ERROR( "got no service manager" );
return FALSE;
}
uno::Reference< uno::XInterface > xWriter( xServiceFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Writer" ) ) ) );
if( !xWriter.is() )
{
DBG_ERROR( "com.sun.star.xml.sax.Writer service missing" );
return FALSE;
}
SvStorage* pStorage = mrMedium.GetOutputStorage();
if( pStorage )
{
SvStorageStreamRef xOStm( pStorage->OpenStream( String( RTL_CONSTASCII_USTRINGPARAM( "Content" ) ),
STREAM_READ | STREAM_WRITE | STREAM_TRUNC ) );
if( !xOStm.Is() || xOStm->GetError() )
{
DBG_ERROR( "Could not create output stream" );
return FALSE;
}
uno::Reference< io::XActiveDataSource > xSrc( xWriter, uno::UNO_QUERY );
uno::Reference<xml::sax::XDocumentHandler> xHandler( xWriter, uno::UNO_QUERY );
xSrc->setOutputStream( new ::utl::OOutputStreamWrapper( *xOStm ) );
try
{
SvXMLGraphicHelper* pGraphicHelper = SvXMLGraphicHelper::Create( *pStorage, GRAPHICHELPER_MODE_WRITE, FALSE );
SdXMLExport aExp( mxLocalModel, mrMedium.GetName(), xHandler, pGraphicHelper, mbShowProgress, IsDraw() );
bRet = ( 0 == aExp.exportDoc( IsDraw() ? sXML_drawing : sXML_impress ) );
SvXMLGraphicHelper::Destroy( pGraphicHelper );
}
catch( xml::sax::SAXParseException )
{
}
catch( xml::sax::SAXException )
{
}
catch( io::IOException )
{
}
}
return bRet;
}
<|endoftext|>
|
<commit_before>/// \file libuobject/main.cc
#include <libport/cstdio>
#include <libport/unistd.h>
#include <cerrno>
#include <iostream>
#include <list>
#include <sstream>
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <libport/lexical-cast.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <urbi/package-info.hh>
#include <urbi/uexternal.hh>
#include <urbi/umain.hh>
#include <urbi/uobject.hh>
#include <urbi/usyncclient.hh>
#include <libuobject/remoteucontextimpl.hh>
using libport::program_name;
namespace urbi
{
static impl::RemoteUContextImpl* defaultContext;
UCallbackAction
debug(const UMessage& msg)
{
msg.client.printf("DEBUG: got a message: %s\n",
string_cast(msg).c_str());
return URBI_CONTINUE;
}
UCallbackAction
static
endProgram(const UMessage& msg)
{
msg.client.printf("ERROR: got a disconnection message: %s\n",
string_cast(msg).c_str());
exit(1);
return URBI_CONTINUE; //stupid gcc
}
static
void
usage()
{
std::cout <<
"usage:\n" << libport::program_name() << " [OPTION]...\n"
"\n"
"Options:\n"
" -b, --buffer SIZE input buffer size"
<< " [" << UAbstractClient::URBI_BUFLEN << "]\n"
" -h, --help display this message and exit\n"
" -H, --host ADDR server host name"
<< " [" << UClient::DEFAULT_HOST << "]\n"
" --server put remote in server mode\n"
" -p, --port PORT tcp port URBI will listen to"
<< " [" << UAbstractClient::URBI_PORT << "]\n"
" -r, --port-file FILE file containing the port to listen to\n"
" -v, --version print version information and exit\n"
" -d, --disconnect exit program if disconnected(defaults)\n"
" -s, --stay-alive do not exit program if disconnected\n"
<< libport::exit (EX_OK);
}
static
void
version()
{
std::cout << urbi::package_info() << std::endl
<< libport::exit (EX_OK);
}
int
initialize(const std::string& host, int port, size_t buflen,
bool exitOnDisconnect, bool server)
{
std::cerr << program_name()
<< ": " << urbi::package_info() << std::endl
<< program_name()
<< ": Remote Component Running on "
<< host << " " << port << std::endl;
USyncClient::options o;
o.server(server);
new USyncClient(host, port, buflen, o);
defaultContext = new impl::RemoteUContextImpl(
dynamic_cast<USyncClient*>(getDefaultClient()));
if (exitOnDisconnect)
{
if (!getDefaultClient() || getDefaultClient()->error())
std::cerr << "ERROR: failed to connect, exiting..." << std::endl
<< libport::exit(1);
getDefaultClient()->setClientErrorCallback(callback(&endProgram));
}
if (!getDefaultClient() || getDefaultClient()->error())
return 1;
#ifdef LIBURBIDEBUG
getDefaultClient()->setWildcardCallback(callback(&debug));
#else
getDefaultClient()->setErrorCallback(callback(&debug));
#endif
// Wait for client to be connected if in server mode.
while (getDefaultClient()
&& !getDefaultClient()->error()
&& !getDefaultClient()->init())
usleep(20000);
// Waiting for connectionID.
while (getDefaultClient()
&& getDefaultClient()->connectionID() == "")
usleep(5000);
defaultContext->init();
//baseURBIStarter::init();
// Send a ';' since UObject likely sent a serie of piped commands.
URBI_SEND_COMMAND("");
return 0;
}
namespace
{
static
void
argument_with_option(const char* longopt,
char shortopt,
const std::string& val)
{
std::cerr
<< program_name()
<< ": warning: arguments without options are deprecated"
<< std::endl
<< "use `-" << shortopt << ' ' << val << '\''
<< " or `--" << longopt << ' ' << val << "' instead"
<< std::endl
<< "Try `" << program_name() << " --help' for more information."
<< std::endl;
}
}
int
main(const libport::cli_args_type& args, bool block, bool)
{
std::string host = UClient::DEFAULT_HOST;
bool exitOnDisconnect = true;
int port = UAbstractClient::URBI_PORT;
bool server = false;
size_t buflen = UAbstractClient::URBI_BUFLEN;
// The number of the next (non-option) argument.
unsigned argp = 1;
for (unsigned i = 1; i < args.size(); ++i)
{
const std::string& arg = args[i];
if (arg == "--buffer" || arg == "-b")
buflen = libport::convert_argument<size_t>(args, i++);
else if (arg == "--disconnect" || arg == "-d")
exitOnDisconnect = true;
else if (arg == "--stay-alive" || arg == "-s")
exitOnDisconnect = false;
else if (arg == "--help" || arg == "-h")
usage();
else if (arg == "--host" || arg == "-H")
host = libport::convert_argument<std::string>(args, i++);
else if (arg == "--port" || arg == "-p")
port = libport::convert_argument<unsigned>(args, i++);
else if (arg == "--port-file" || arg == "-r")
port =
(libport::file_contents_get<int>
(libport::convert_argument<const char*>(args, i++)));
else if (arg == "--server")
server = true;
else if (arg == "--version" || arg == "-v")
version();
else if (arg[0] == '-')
libport::invalid_option(arg);
else
// A genuine argument.
switch (argp++)
{
case 1:
argument_with_option("host", 'H', args[i]);
host = args[i];
break;
case 2:
argument_with_option("port", 'p', args[i]);
port = libport::convert_argument<unsigned> ("port", args[i].c_str());
break;
default:
std::cerr << "unexpected argument: " << arg << std::endl
<< libport::exit(EX_USAGE);
}
}
initialize(host, port, buflen, exitOnDisconnect, server);
if (block)
while (true)
usleep(30000000);
return 0;
}
}
<commit_msg>Urbi-launch: accept --file in remote mode.<commit_after>/// \file libuobject/main.cc
#include <libport/cstdio>
#include <libport/unistd.h>
#include <cerrno>
#include <iostream>
#include <list>
#include <sstream>
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <libport/lexical-cast.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <urbi/package-info.hh>
#include <urbi/uexternal.hh>
#include <urbi/umain.hh>
#include <urbi/uobject.hh>
#include <urbi/usyncclient.hh>
#include <libuobject/remoteucontextimpl.hh>
using libport::program_name;
namespace urbi
{
static impl::RemoteUContextImpl* defaultContext;
UCallbackAction
debug(const UMessage& msg)
{
msg.client.printf("DEBUG: got a message: %s\n",
string_cast(msg).c_str());
return URBI_CONTINUE;
}
UCallbackAction
static
endProgram(const UMessage& msg)
{
msg.client.printf("ERROR: got a disconnection message: %s\n",
string_cast(msg).c_str());
exit(1);
return URBI_CONTINUE; //stupid gcc
}
static
void
usage()
{
std::cout <<
"usage:\n" << libport::program_name() << " [OPTION]...\n"
"\n"
"Options:\n"
" -b, --buffer SIZE input buffer size"
<< " [" << UAbstractClient::URBI_BUFLEN << "]\n"
" -h, --help display this message and exit\n"
" -H, --host ADDR server host name"
<< " [" << UClient::DEFAULT_HOST << "]\n"
" --server put remote in server mode\n"
" -p, --port PORT tcp port URBI will listen to"
<< " [" << UAbstractClient::URBI_PORT << "]\n"
" -r, --port-file FILE file containing the port to listen to\n"
" -v, --version print version information and exit\n"
" -d, --disconnect exit program if disconnected(defaults)\n"
" -s, --stay-alive do not exit program if disconnected\n"
<< libport::exit (EX_OK);
}
static
void
version()
{
std::cout << urbi::package_info() << std::endl
<< libport::exit (EX_OK);
}
typedef std::vector<std::string> files_type;
int
initialize(const std::string& host, int port, size_t buflen,
bool exitOnDisconnect, bool server, const files_type& files)
{
std::cerr << program_name()
<< ": " << urbi::package_info() << std::endl
<< program_name()
<< ": Remote Component Running on "
<< host << " " << port << std::endl;
USyncClient::options o;
o.server(server);
new USyncClient(host, port, buflen, o);
defaultContext = new impl::RemoteUContextImpl(
dynamic_cast<USyncClient*>(getDefaultClient()));
if (exitOnDisconnect)
{
if (!getDefaultClient() || getDefaultClient()->error())
std::cerr << "ERROR: failed to connect, exiting..." << std::endl
<< libport::exit(1);
getDefaultClient()->setClientErrorCallback(callback(&endProgram));
}
if (!getDefaultClient() || getDefaultClient()->error())
return 1;
#ifdef LIBURBIDEBUG
getDefaultClient()->setWildcardCallback(callback(&debug));
#else
getDefaultClient()->setErrorCallback(callback(&debug));
#endif
// Wait for client to be connected if in server mode.
while (getDefaultClient()
&& !getDefaultClient()->error()
&& !getDefaultClient()->init())
usleep(20000);
// Waiting for connectionID.
while (getDefaultClient()
&& getDefaultClient()->connectionID() == "")
usleep(5000);
defaultContext->init();
//baseURBIStarter::init();
// Send a ';' since UObject likely sent a serie of piped commands.
URBI_SEND_COMMAND("");
// Load initialization files.
foreach (const std::string& file, files)
getDefaultClient()->sendFile(file);
return 0;
}
namespace
{
static
void
argument_with_option(const char* longopt,
char shortopt,
const std::string& val)
{
std::cerr
<< program_name()
<< ": warning: arguments without options are deprecated"
<< std::endl
<< "use `-" << shortopt << ' ' << val << '\''
<< " or `--" << longopt << ' ' << val << "' instead"
<< std::endl
<< "Try `" << program_name() << " --help' for more information."
<< std::endl;
}
}
int
main(const libport::cli_args_type& args, bool block, bool)
{
std::string host = UClient::DEFAULT_HOST;
bool exitOnDisconnect = true;
int port = UAbstractClient::URBI_PORT;
bool server = false;
size_t buflen = UAbstractClient::URBI_BUFLEN;
// Files to load
files_type files;
// The number of the next (non-option) argument.
unsigned argp = 1;
for (unsigned i = 1; i < args.size(); ++i)
{
const std::string& arg = args[i];
if (arg == "--buffer" || arg == "-b")
buflen = libport::convert_argument<size_t>(args, i++);
else if (arg == "--disconnect" || arg == "-d")
exitOnDisconnect = true;
else if (arg == "--file" || arg == "-f")
files.push_back(libport::convert_argument<const char*>(args, i++));
else if (arg == "--stay-alive" || arg == "-s")
exitOnDisconnect = false;
else if (arg == "--help" || arg == "-h")
usage();
else if (arg == "--host" || arg == "-H")
host = libport::convert_argument<std::string>(args, i++);
else if (arg == "--port" || arg == "-p")
port = libport::convert_argument<unsigned>(args, i++);
else if (arg == "--port-file" || arg == "-r")
port =
(libport::file_contents_get<int>
(libport::convert_argument<const char*>(args, i++)));
else if (arg == "--server")
server = true;
else if (arg == "--version" || arg == "-v")
version();
else if (arg[0] == '-')
libport::invalid_option(arg);
else
// A genuine argument.
switch (argp++)
{
case 1:
argument_with_option("host", 'H', args[i]);
host = args[i];
break;
case 2:
argument_with_option("port", 'p', args[i]);
port = libport::convert_argument<unsigned> ("port", args[i].c_str());
break;
default:
std::cerr << "unexpected argument: " << arg << std::endl
<< libport::exit(EX_USAGE);
}
}
initialize(host, port, buflen, exitOnDisconnect, server, files);
if (block)
while (true)
usleep(30000000);
return 0;
}
}
<|endoftext|>
|
<commit_before>#include "Phantom_vrepHW.h"
#include "../v_repLib.h"
#include <string>
#include <iostream>
namespace MR
{
std::string Phantom_vrepHW::sm_jointsName[MR_JOINTS_NUM] = {
"PhantomXPincher_joint1",
"PhantomXPincher_joint2",
"PhantomXPincher_joint3",
"PhantomXPincher_joint4"
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Phantom_vrepHW::Phantom_vrepHW() :
hardware_interface::RobotHW()
{
// Init arrays m_cmd[], m_pos[], m_vel[], m_eff[].
for (int i = 0; i < MR_JOINTS_NUM; ++i)
{
m_pos_cmd[i] = 0.0;
m_vel_cmd[i] = 0.0;
m_pos[i] = 0.0;
m_vel[i] = 0.0;
m_eff[i] = 0.0;
}
// Init and get handles of the joints to control.
for (int i = 0; i < MR_JOINTS_NUM; ++i)
m_vrepJointsHandle[i] = -1;
// Register joint interfaces.
registerHardwareInterfaces();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::init()
{
// Get joint handles.
for (int i = 0; i < MR_JOINTS_NUM; ++i)
{
int vrepJointsHandle = simGetObjectHandle(sm_jointsName[i].c_str());
if (vrepJointsHandle == -1)
{
ROS_ERROR_STREAM("MR robot interface not able to get handle for '" << sm_jointsName[i] << "'." << std::endl);
return false;
}
m_vrepJointsHandle[i] = vrepJointsHandle;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Phantom_vrepHW::registerHardwareInterfaces()
{
for (int i = 0; i < MR_JOINTS_NUM; ++i)
{
// Joint state interface.
hardware_interface::JointStateHandle jointStateHandle(sm_jointsName[i], &m_pos[i], &m_vel[i], &m_eff[i]);
m_jointState_interface.registerHandle(jointStateHandle);
// Joint velocity command interface
hardware_interface::JointHandle jointVelocityHandle(jointStateHandle, &m_vel_cmd[i]);
m_jointVelocity_interface.registerHandle(jointVelocityHandle);
//Joint position command interface
hardware_interface::JointHandle jointPositionHandle(jointStateHandle, &m_pos_cmd[i]);
m_jointPosition_interface.registerHandle(jointPositionHandle);
}
registerInterface(&m_jointState_interface);
registerInterface(&m_jointVelocity_interface);
registerInterface(&m_jointPosition_interface);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::read()
{
for (int i = 0; i < MR_JOINTS_NUM; ++i)
{
float pos,
vel,
eff;
if (simGetJointPosition(m_vrepJointsHandle[i], &pos) == -1 ||
simGetObjectFloatParameter(m_vrepJointsHandle[i], 2012, &vel) == -1 || // Velocity.
simGetJointForce(m_vrepJointsHandle[i], &eff) == -1)
{
ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);
return false;
}
m_pos[i] = pos;
m_vel[i] = vel;
m_eff[i] = eff;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::write()
{
for (int i = 0; i < MR_JOINTS_NUM; ++i){
//====== Velocity Control =========
/*if (simSetJointTargetVelocity(m_vrepJointsHandle[i], m_vel_cmd[i]) == -1) {
ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);
return false;
}
*/
//===== Position Control =======
if (simSetJointTargetPosition(m_vrepJointsHandle[i], m_pos_cmd[i]) == -1) {
ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);
return false;
}
}
return true;
}
} // namespace MR.
<commit_msg>Added gripper controller - forgot a file<commit_after>#include "Phantom_vrepHW.h"
#include "../v_repLib.h"
#include <string>
#include <iostream>
namespace MR
{
std::string Phantom_vrepHW::sm_jointsName[MR_JOINTS_NUM] = {
"PhantomXPincher_joint1",
"PhantomXPincher_joint2",
"PhantomXPincher_joint3",
"PhantomXPincher_joint4",
"PhantomXPincher_gripperClose_joint"
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Phantom_vrepHW::Phantom_vrepHW() :
hardware_interface::RobotHW()
{
// Init arrays m_cmd[], m_pos[], m_vel[], m_eff[].
for (int i = 0; i < MR_JOINTS_NUM; ++i)
{
m_pos_cmd[i] = 0.0;
m_vel_cmd[i] = 0.0;
m_pos[i] = 0.0;
m_vel[i] = 0.0;
m_eff[i] = 0.0;
}
// Init and get handles of the joints to control.
for (int i = 0; i < MR_JOINTS_NUM; ++i)
m_vrepJointsHandle[i] = -1;
// Register joint interfaces.
registerHardwareInterfaces();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::init()
{
// Get joint handles.
for (int i = 0; i < MR_JOINTS_NUM; ++i)
{
int vrepJointsHandle = simGetObjectHandle(sm_jointsName[i].c_str());
if (vrepJointsHandle == -1)
{
ROS_ERROR_STREAM("MR robot interface not able to get handle for '" << sm_jointsName[i] << "'." << std::endl);
return false;
}
m_vrepJointsHandle[i] = vrepJointsHandle;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Phantom_vrepHW::registerHardwareInterfaces()
{
for (int i = 0; i < MR_JOINTS_NUM; ++i)
{
// Joint state interface.
hardware_interface::JointStateHandle jointStateHandle(sm_jointsName[i], &m_pos[i], &m_vel[i], &m_eff[i]);
m_jointState_interface.registerHandle(jointStateHandle);
// Joint velocity command interface
hardware_interface::JointHandle jointVelocityHandle(jointStateHandle, &m_vel_cmd[i]);
m_jointVelocity_interface.registerHandle(jointVelocityHandle);
//Joint position command interface
hardware_interface::JointHandle jointPositionHandle(jointStateHandle, &m_pos_cmd[i]);
m_jointPosition_interface.registerHandle(jointPositionHandle);
}
registerInterface(&m_jointState_interface);
registerInterface(&m_jointVelocity_interface);
registerInterface(&m_jointPosition_interface);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::read()
{
for (int i = 0; i < MR_JOINTS_NUM; ++i)
{
float pos,
vel,
eff;
if (simGetJointPosition(m_vrepJointsHandle[i], &pos) == -1 ||
simGetObjectFloatParameter(m_vrepJointsHandle[i], 2012, &vel) == -1 || // Velocity.
simGetJointForce(m_vrepJointsHandle[i], &eff) == -1)
{
ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);
return false;
}
m_pos[i] = pos;
m_vel[i] = vel;
m_eff[i] = eff;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Phantom_vrepHW::write()
{
for (int i = 0; i < MR_JOINTS_NUM; ++i){
//====== Velocity Control =========
/*if (simSetJointTargetVelocity(m_vrepJointsHandle[i], m_vel_cmd[i]) == -1) {
ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);
return false;
}
*/
//===== Position Control =======
if (simSetJointTargetPosition(m_vrepJointsHandle[i], m_pos_cmd[i]) == -1) {
ROS_ERROR_STREAM("MR robot interface not able to get state for '" << sm_jointsName[i] << "'." << std::endl);
return false;
}
}
return true;
}
} // namespace MR.
<|endoftext|>
|
<commit_before>/*
Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open
Source Software License
Copyright (c) 2008 Ames Laboratory Iowa State University
All rights reserved.
Redistribution and use of HOOMD, 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 holder nor the names HOOMD's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND
CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
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.
*/
// $Id$
// $URL$
/*! \file LJForceComputeGPU.cc
\brief Defines the LJForceComputeGPU class
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include "LJForceComputeGPU.h"
#include "cuda_runtime.h"
#include <stdexcept>
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
using namespace std;
/*! \param sysdef System to compute forces on
\param nlist Neighborlist to use for computing the forces
\param r_cut Cuttoff radius beyond which the force is 0
\param slj Determines if Diameter Shifted LJ potential is being used
\post memory is allocated and all parameters lj1 and lj2 are set to 0.0
\note The LJForceComputeGPU does not own the Neighborlist, the caller should
delete the neighborlist when done.
*/
LJForceComputeGPU::LJForceComputeGPU(boost::shared_ptr<SystemDefinition> sysdef, boost::shared_ptr<NeighborList> nlist, Scalar r_cut)
: LJForceCompute(sysdef, nlist, r_cut)
{
// can't run on the GPU if there aren't any GPUs in the execution configuration
if (exec_conf.gpu.size() == 0)
{
cerr << endl << "***Error! Creating a LJForceComputeGPU with no GPU in the execution configuration" << endl << endl;
throw std::runtime_error("Error initializing LJForceComputeGPU");
}
if (m_ntypes > 44)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle " << m_ntypes << " types" << endl << endl;
throw runtime_error("Error initializing LJForceComputeGPU");
}
// default block size is the highest performance in testing on different hardware
// choose based on compute capability of the device
cudaDeviceProp deviceProp;
int dev;
exec_conf.gpu[0]->call(bind(cudaGetDevice, &dev));
exec_conf.gpu[0]->call(bind(cudaGetDeviceProperties, &deviceProp, dev));
if (deviceProp.major == 1 && deviceProp.minor == 0)
m_block_size = 320;
else if (deviceProp.major == 1 && deviceProp.minor == 1)
m_block_size = 256;
else if (deviceProp.major == 1 && deviceProp.minor < 4)
m_block_size = 384;
else
{
cout << "***Warning! Unknown compute " << deviceProp.major << "." << deviceProp.minor << " when tuning block size for LJForceComputeGPU" << endl;
m_block_size = 64;
}
// ulf workaround setup
#ifndef DISABLE_ULF_WORKAROUND
// the ULF workaround is needed on GTX280 and older GPUS
// it is not needed on C1060, S1070, GTX285, GTX295, and (hopefully) newer ones
m_ulf_workaround = true;
if (deviceProp.major == 1 && deviceProp.minor >= 3)
m_ulf_workaround = false;
if (string(deviceProp.name) == "GTX 280")
m_ulf_workaround = true;
if (m_ulf_workaround)
cout << "Notice: ULF bug workaround enabled for LJForceComputeGPU" << endl;
#else
m_ulf_workaround = false;
#endif
/*
if (m_slj) cout << "Notice: Using Diameter-Shifted LJ Pair Potential for LJForceComputeGPU" << endl;
else cout << "Diameter-Shifted LJ Pair Potential is NOT set for LJForceComputeGPU" << endl;
*/
// allocate the coeff data on the GPU
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
d_coeffs.resize(exec_conf.gpu.size());
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
exec_conf.gpu[cur_gpu]->setTag(__FILE__, __LINE__);
exec_conf.gpu[cur_gpu]->call(bind(cudaMalloc, (void **)((void *)&d_coeffs[cur_gpu]), nbytes));
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaMemset, (void *)d_coeffs[cur_gpu], 0, nbytes));
}
// allocate the coeff data on the CPU
h_coeffs = new float2[m_pdata->getNTypes()*m_pdata->getNTypes()];
}
LJForceComputeGPU::~LJForceComputeGPU()
{
// free the coefficients on the GPU
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaFree, (void *)d_coeffs[cur_gpu]));
}
delete[] h_coeffs;
}
/*! \param block_size Size of the block to run on the device
Performance of the code may be dependant on the block size run
on the GPU. \a block_size should be set to be a multiple of 32.
*/
void LJForceComputeGPU::setBlockSize(int block_size)
{
m_block_size = block_size;
}
/*! \post The parameters \a lj1 and \a lj2 are set for the pairs \a typ1, \a typ2 and \a typ2, \a typ1.
\note \a lj? are low level parameters used in the calculation. In order to specify
these for a normal lennard jones formula (with alpha), they should be set to the following.
- \a lj1 = 4.0 * epsilon * pow(sigma,12.0)
- \a lj2 = alpha * 4.0 * epsilon * pow(sigma,6.0);
Setting the parameters for typ1,typ2 automatically sets the same parameters for typ2,typ1: there
is no need to call this funciton for symmetric pairs. Any pairs that this function is not called
for will have lj1 and lj2 set to 0.0.
\param typ1 Specifies one type of the pair
\param typ2 Specifies the second type of the pair
\param lj1 First parameter used to calcluate forces
\param lj2 Second parameter used to calculate forces
*/
void LJForceComputeGPU::setParams(unsigned int typ1, unsigned int typ2, Scalar lj1, Scalar lj2)
{
assert(h_coeffs);
if (typ1 >= m_ntypes || typ2 >= m_ntypes)
{
cerr << endl << "***Error! Trying to set LJ params for a non existant type! " << typ1 << "," << typ2 << endl << endl;
throw runtime_error("LJForceComputeGpu::setParams argument error");
}
// set coeffs in both symmetric positions in the matrix
h_coeffs[typ1*m_pdata->getNTypes() + typ2] = make_float2(lj1, lj2);
h_coeffs[typ2*m_pdata->getNTypes() + typ1] = make_float2(lj1, lj2);
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->call(bind(cudaMemcpy, d_coeffs[cur_gpu], h_coeffs, nbytes, cudaMemcpyHostToDevice));
}
/*! \post The lennard jones forces are computed for the given timestep on the GPU.
The neighborlist's compute method is called to ensure that it is up to date
before forces are computed.
\param timestep Current time step of the simulation
Calls gpu_compute_lj_forces to do the dirty work.
*/
void LJForceComputeGPU::computeForces(unsigned int timestep)
{
// start by updating the neighborlist
m_nlist->compute(timestep);
// start the profile
if (m_prof) m_prof->push(exec_conf, "LJ pair");
// The GPU implementation CANNOT handle a half neighborlist, error out now
bool third_law = m_nlist->getStorageMode() == NeighborList::half;
if (third_law)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle a half neighborlist" << endl << endl;
throw runtime_error("Error computing forces in LJForceComputeGPU");
}
// access the neighbor list, which just selects the neighborlist into the device's memory, copying
// it there if needed
vector<gpu_nlist_array>& nlist = m_nlist->getListGPU();
// access the particle data
vector<gpu_pdata_arrays>& pdata = m_pdata->acquireReadOnlyGPU();
gpu_boxsize box = m_pdata->getBoxGPU();
// run the kernel on all GPUs in parallel
exec_conf.tagAll(__FILE__, __LINE__);
lj_options opt;
opt.r_cutsq = m_r_cut * m_r_cut;
opt.block_size = m_block_size;
opt.xplor_fraction = m_xplor_fraction;
opt.ulf_workaround = m_ulf_workaround;
opt.shift_mode = m_shift_mode;
opt.slj = m_slj;
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->callAsync(bind(gpu_compute_lj_forces, m_gpu_forces[cur_gpu].d_data, pdata[cur_gpu], box, nlist[cur_gpu], d_coeffs[cur_gpu], m_pdata->getNTypes(), opt));
exec_conf.syncAll();
m_pdata->release();
// the force data is now only up to date on the gpu
m_data_location = gpu;
Scalar avg_neigh = m_nlist->estimateNNeigh();
int64_t n_calc = int64_t(avg_neigh * m_pdata->getN());
int64_t mem_transfer = m_pdata->getN() * (4 + 16 + 20) + n_calc * (4 + 16);
int64_t flops = n_calc * (3+12+5+2+2+6+3+2+7);
if (m_slj) {
flops += 11;
mem_transfer += m_pdata->getN() * (4) + n_calc * (4)
}
if (m_prof) m_prof->pop(exec_conf, flops, mem_transfer);
}
void export_LJForceComputeGPU()
{
class_<LJForceComputeGPU, boost::shared_ptr<LJForceComputeGPU>, bases<LJForceCompute>, boost::noncopyable >
("LJForceComputeGPU", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<NeighborList>, Scalar >())
.def("setBlockSize", &LJForceComputeGPU::setBlockSize)
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<commit_msg>left off a semi-colon<commit_after>/*
Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open
Source Software License
Copyright (c) 2008 Ames Laboratory Iowa State University
All rights reserved.
Redistribution and use of HOOMD, 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 holder nor the names HOOMD's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND
CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
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.
*/
// $Id$
// $URL$
/*! \file LJForceComputeGPU.cc
\brief Defines the LJForceComputeGPU class
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include "LJForceComputeGPU.h"
#include "cuda_runtime.h"
#include <stdexcept>
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
using namespace std;
/*! \param sysdef System to compute forces on
\param nlist Neighborlist to use for computing the forces
\param r_cut Cuttoff radius beyond which the force is 0
\param slj Determines if Diameter Shifted LJ potential is being used
\post memory is allocated and all parameters lj1 and lj2 are set to 0.0
\note The LJForceComputeGPU does not own the Neighborlist, the caller should
delete the neighborlist when done.
*/
LJForceComputeGPU::LJForceComputeGPU(boost::shared_ptr<SystemDefinition> sysdef, boost::shared_ptr<NeighborList> nlist, Scalar r_cut)
: LJForceCompute(sysdef, nlist, r_cut)
{
// can't run on the GPU if there aren't any GPUs in the execution configuration
if (exec_conf.gpu.size() == 0)
{
cerr << endl << "***Error! Creating a LJForceComputeGPU with no GPU in the execution configuration" << endl << endl;
throw std::runtime_error("Error initializing LJForceComputeGPU");
}
if (m_ntypes > 44)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle " << m_ntypes << " types" << endl << endl;
throw runtime_error("Error initializing LJForceComputeGPU");
}
// default block size is the highest performance in testing on different hardware
// choose based on compute capability of the device
cudaDeviceProp deviceProp;
int dev;
exec_conf.gpu[0]->call(bind(cudaGetDevice, &dev));
exec_conf.gpu[0]->call(bind(cudaGetDeviceProperties, &deviceProp, dev));
if (deviceProp.major == 1 && deviceProp.minor == 0)
m_block_size = 320;
else if (deviceProp.major == 1 && deviceProp.minor == 1)
m_block_size = 256;
else if (deviceProp.major == 1 && deviceProp.minor < 4)
m_block_size = 384;
else
{
cout << "***Warning! Unknown compute " << deviceProp.major << "." << deviceProp.minor << " when tuning block size for LJForceComputeGPU" << endl;
m_block_size = 64;
}
// ulf workaround setup
#ifndef DISABLE_ULF_WORKAROUND
// the ULF workaround is needed on GTX280 and older GPUS
// it is not needed on C1060, S1070, GTX285, GTX295, and (hopefully) newer ones
m_ulf_workaround = true;
if (deviceProp.major == 1 && deviceProp.minor >= 3)
m_ulf_workaround = false;
if (string(deviceProp.name) == "GTX 280")
m_ulf_workaround = true;
if (m_ulf_workaround)
cout << "Notice: ULF bug workaround enabled for LJForceComputeGPU" << endl;
#else
m_ulf_workaround = false;
#endif
/*
if (m_slj) cout << "Notice: Using Diameter-Shifted LJ Pair Potential for LJForceComputeGPU" << endl;
else cout << "Diameter-Shifted LJ Pair Potential is NOT set for LJForceComputeGPU" << endl;
*/
// allocate the coeff data on the GPU
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
d_coeffs.resize(exec_conf.gpu.size());
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
exec_conf.gpu[cur_gpu]->setTag(__FILE__, __LINE__);
exec_conf.gpu[cur_gpu]->call(bind(cudaMalloc, (void **)((void *)&d_coeffs[cur_gpu]), nbytes));
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaMemset, (void *)d_coeffs[cur_gpu], 0, nbytes));
}
// allocate the coeff data on the CPU
h_coeffs = new float2[m_pdata->getNTypes()*m_pdata->getNTypes()];
}
LJForceComputeGPU::~LJForceComputeGPU()
{
// free the coefficients on the GPU
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaFree, (void *)d_coeffs[cur_gpu]));
}
delete[] h_coeffs;
}
/*! \param block_size Size of the block to run on the device
Performance of the code may be dependant on the block size run
on the GPU. \a block_size should be set to be a multiple of 32.
*/
void LJForceComputeGPU::setBlockSize(int block_size)
{
m_block_size = block_size;
}
/*! \post The parameters \a lj1 and \a lj2 are set for the pairs \a typ1, \a typ2 and \a typ2, \a typ1.
\note \a lj? are low level parameters used in the calculation. In order to specify
these for a normal lennard jones formula (with alpha), they should be set to the following.
- \a lj1 = 4.0 * epsilon * pow(sigma,12.0)
- \a lj2 = alpha * 4.0 * epsilon * pow(sigma,6.0);
Setting the parameters for typ1,typ2 automatically sets the same parameters for typ2,typ1: there
is no need to call this funciton for symmetric pairs. Any pairs that this function is not called
for will have lj1 and lj2 set to 0.0.
\param typ1 Specifies one type of the pair
\param typ2 Specifies the second type of the pair
\param lj1 First parameter used to calcluate forces
\param lj2 Second parameter used to calculate forces
*/
void LJForceComputeGPU::setParams(unsigned int typ1, unsigned int typ2, Scalar lj1, Scalar lj2)
{
assert(h_coeffs);
if (typ1 >= m_ntypes || typ2 >= m_ntypes)
{
cerr << endl << "***Error! Trying to set LJ params for a non existant type! " << typ1 << "," << typ2 << endl << endl;
throw runtime_error("LJForceComputeGpu::setParams argument error");
}
// set coeffs in both symmetric positions in the matrix
h_coeffs[typ1*m_pdata->getNTypes() + typ2] = make_float2(lj1, lj2);
h_coeffs[typ2*m_pdata->getNTypes() + typ1] = make_float2(lj1, lj2);
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->call(bind(cudaMemcpy, d_coeffs[cur_gpu], h_coeffs, nbytes, cudaMemcpyHostToDevice));
}
/*! \post The lennard jones forces are computed for the given timestep on the GPU.
The neighborlist's compute method is called to ensure that it is up to date
before forces are computed.
\param timestep Current time step of the simulation
Calls gpu_compute_lj_forces to do the dirty work.
*/
void LJForceComputeGPU::computeForces(unsigned int timestep)
{
// start by updating the neighborlist
m_nlist->compute(timestep);
// start the profile
if (m_prof) m_prof->push(exec_conf, "LJ pair");
// The GPU implementation CANNOT handle a half neighborlist, error out now
bool third_law = m_nlist->getStorageMode() == NeighborList::half;
if (third_law)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle a half neighborlist" << endl << endl;
throw runtime_error("Error computing forces in LJForceComputeGPU");
}
// access the neighbor list, which just selects the neighborlist into the device's memory, copying
// it there if needed
vector<gpu_nlist_array>& nlist = m_nlist->getListGPU();
// access the particle data
vector<gpu_pdata_arrays>& pdata = m_pdata->acquireReadOnlyGPU();
gpu_boxsize box = m_pdata->getBoxGPU();
// run the kernel on all GPUs in parallel
exec_conf.tagAll(__FILE__, __LINE__);
lj_options opt;
opt.r_cutsq = m_r_cut * m_r_cut;
opt.block_size = m_block_size;
opt.xplor_fraction = m_xplor_fraction;
opt.ulf_workaround = m_ulf_workaround;
opt.shift_mode = m_shift_mode;
opt.slj = m_slj;
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->callAsync(bind(gpu_compute_lj_forces, m_gpu_forces[cur_gpu].d_data, pdata[cur_gpu], box, nlist[cur_gpu], d_coeffs[cur_gpu], m_pdata->getNTypes(), opt));
exec_conf.syncAll();
m_pdata->release();
// the force data is now only up to date on the gpu
m_data_location = gpu;
Scalar avg_neigh = m_nlist->estimateNNeigh();
int64_t n_calc = int64_t(avg_neigh * m_pdata->getN());
int64_t mem_transfer = m_pdata->getN() * (4 + 16 + 20) + n_calc * (4 + 16);
int64_t flops = n_calc * (3+12+5+2+2+6+3+2+7);
if (m_slj) {
flops += 11;
mem_transfer += m_pdata->getN() * (4) + n_calc * (4);
}
if (m_prof) m_prof->pop(exec_conf, flops, mem_transfer);
}
void export_LJForceComputeGPU()
{
class_<LJForceComputeGPU, boost::shared_ptr<LJForceComputeGPU>, bases<LJForceCompute>, boost::noncopyable >
("LJForceComputeGPU", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<NeighborList>, Scalar >())
.def("setBlockSize", &LJForceComputeGPU::setBlockSize)
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<|endoftext|>
|
<commit_before><commit_msg>sensord cleanup (#2111)<commit_after><|endoftext|>
|
<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Tests for writing out the basic record types.
//
// TODO(schwehr): Does this have to free what was read?
#include <sys/stat.h>
#include <memory>
#include <string>
#include "gsf.h"
#include "gsf_ft.h"
#include "gsf_test_util.h"
#include "gtest/gtest.h"
// #include <iostream> // TODO(schwehr): Remove.
// using namespace std; // TODO(schwehr): Remove.
using std::unique_ptr;
namespace generic_sensor_format {
namespace test {
namespace {
// TODO(schwehr): Switch to make_unique when C++14 is available on Travis-CI.
template <typename T, typename... Args>
std::unique_ptr<T> MakeUnique(Args &&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
TEST(GsfWriteSimple, HeaderOnly) {
int handle;
char filename[] = "header-only.gsf";
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(20, buf.st_size);
}
// TODO(schwehr): GSF_RECORD_SWATH_BATHYMETRY_PING.
// TODO(schwehr): GSF_RECORD_SOUND_VELOCITY_PROFILE
// TODO(schwehr): GSF_RECORD_PROCESSING_PARAMETERS
// TODO(schwehr): GSF_RECORD_SENSOR_PARAMETERS
void ValidateWriteComment(const char *filename, bool checksum,
int expected_write_size, const char *comment,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 20);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 40);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_COMMENT, 0};
gsfRecords record;
record.comment = GsfComment({1, 2}, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_COMMENT, data_id.recordID);
VerifyComment(record.comment, read_record.comment);
}
TEST(GsfWriteSimple, CommentEmpty) {
char filename[] = "comment-empty.gsf";
char comment[] = "";
ValidateWriteComment(filename, false, 20, comment, 40);
}
TEST(GsfWriteSimple, CommentEmptyChecksum) {
char filename[] = "comment-empty-checksum.gsf";
char comment[] = "";
ValidateWriteComment(filename, true, 24, comment, 44);
}
TEST(GsfWriteSimple, CommentUpTo5) {
char filename1[] = "comment-1.gsf";
char comment1[] = "a";
ValidateWriteComment(filename1, false, 24, comment1, 44);
char filename2[] = "comment-2.gsf";
char comment2[] = "ab";
ValidateWriteComment(filename2, false, 24, comment2, 44);
char filename3[] = "comment-3.gsf";
char comment3[] = "abc";
ValidateWriteComment(filename3, false, 24, comment3, 44);
char filename4[] = "comment-4.gsf";
char comment4[] = "abcd";
ValidateWriteComment(filename4, false, 24, comment4, 44);
char filename5[] = "comment-5.gsf";
char comment5[] = "abcde";
ValidateWriteComment(filename5, false, 28, comment5, 48);
}
TEST(GsfWriteSimple, CommentLarge) {
char filename[] = "comment-large.gsf";
char comment[] =
"ab"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"de";
ValidateWriteComment(filename, false, 656, comment, 676);
}
void ValidateWriteHistory(const char *filename, bool checksum,
int expected_write_size, const char *host_name,
const char *operator_name, const char *command_line,
const char *comment, int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 28);
ASSERT_NE(nullptr, host_name);
ASSERT_LE(strlen(host_name), GSF_HOST_NAME_LENGTH);
ASSERT_NE(nullptr, operator_name);
ASSERT_LE(strlen(operator_name), GSF_OPERATOR_LENGTH);
ASSERT_NE(nullptr, command_line);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 48);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_HISTORY, 0};
gsfRecords record;
record.history =
GsfHistory({1, 2}, host_name, operator_name, command_line, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_HISTORY, data_id.recordID);
VerifyHistory(record.history, read_record.history);
}
TEST(GsfWriteSimple, History) {
ValidateWriteHistory("history-empty.gsf", false, 28, "", "", "", "", 48);
ValidateWriteHistory("history-empty-checksum.gsf", true, 32, "", "", "", "",
52);
ValidateWriteHistory("history-1.gsf", false, 32, "a", "b", "c", "d", 52);
ValidateWriteHistory("history-longer.gsf", false, 40, "ab", "cde", "fghi",
"jklm", 60);
}
// TODO(schwehr): GSF_RECORD_NAVIGATION_ERROR
// TODO(schwehr): GSF_RECORD_SWATH_BATHY_SUMMARY
// TODO(schwehr): GSF_RECORD_SINGLE_BEAM_PING
// TODO(schwehr): GSF_RECORD_HV_NAVIGATION_ERROR
void ValidateWriteAttitude(const char *filename, bool checksum,
int expected_write_size, const gsfAttitude &attitude,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 20);
ASSERT_GE(expected_file_size, 40);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_ATTITUDE, 0};
gsfRecords record;
record.attitude = attitude;
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_ATTITUDE, data_id.recordID);
VerifyAttitude(record.attitude, read_record.attitude);
}
unique_ptr<gsfAttitude> WriteAttitudeAndReturnRead(const char *filename,
const gsfAttitude &attitude,
int *file_size,
int *num_bytes) {
// TODO(schwehr): Add error handling.
int handle;
if (0 != gsfOpen(filename, GSF_CREATE, &handle)) {
return nullptr;
}
gsfDataID data_id = {false, 0, GSF_RECORD_ATTITUDE, 0};
gsfRecords record;
record.attitude = attitude;
if (gsfWrite(handle, &data_id, &record) < 20) {
// Do not check return since we are already in trouble.
gsfClose(handle);
return nullptr;
}
if (0 != gsfClose(handle)) {
return nullptr;
}
struct stat buf;
if (0 != stat(filename, &buf)) {
return nullptr;
}
*file_size = buf.st_size;
if (0 != gsfOpen(filename, GSF_READONLY, &handle)) {
return nullptr;
}
gsfRecords read_record;
*num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
if (*num_bytes < 24) {
return nullptr;
}
return MakeUnique<gsfAttitude>(read_record.attitude);
}
TEST(GsfWriteSimple, AttitudeEmpty) {
const struct timespec times[] = {{3, 4}};
const gsfAttitude attitude =
GsfAttitude(0, times, nullptr, nullptr, nullptr, nullptr);
ValidateWriteAttitude("attitude-empty.gsf", false, 20, attitude, 40);
}
TEST(GsfWriteSimple, AttitudeLength1Zeros) {
const struct timespec times0[] = {{5, 6}};
const double data0[] = {0.0};
const gsfAttitude attitude0 =
GsfAttitude(1, times0, data0, data0, data0, data0);
ValidateWriteAttitude("attitude-length1-0.gsf", false, 28, attitude0, 48);
}
TEST(GsfWriteSimple, AttitudeLength1) {
const struct timespec times[] = {{7, 8}};
const double pitch[] = {1.2};
const double roll[] = {2.2};
const double heave[] = {3.3};
const double heading[] = {4.4};
const gsfAttitude attitude =
GsfAttitude(1, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length1-1-checksum.gsf", true, 32, attitude,
52);
}
TEST(GsfWriteSimple, AttitudeLength1Negative) {
const struct timespec times[] = {{9, 10}};
const double pitch[] = {-1.2};
const double roll[] = {-3.4};
const double heave[] = {-5.6};
// Stored as a int16 with value * 100, so cannot test negative.
const double heading[] = {7.8};
const gsfAttitude attitude =
GsfAttitude(1, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length1-neg.gsf", false, 28, attitude, 48);
}
TEST(GsfWriteSimple, AttitudeRounding) {
const struct timespec times[] = {{11, 12}};
const double pitch[] = {-1.002};
const double roll[] = {-2.0052};
const double heave[] = {3.0045};
const double heading[] = {4.0052};
const gsfAttitude src = GsfAttitude(1, times, pitch, roll, heave, heading);
int file_size;
int num_bytes;
const unique_ptr<gsfAttitude> dst = WriteAttitudeAndReturnRead(
"attitude-round.gsf", src, &file_size, &num_bytes);
ASSERT_NE(nullptr, dst);
ASSERT_EQ(48, file_size);
ASSERT_EQ(28, num_bytes);
const double pitch2[] = {-1.00};
const double roll2[] = {-2.01};
const double heave2[] = {3.00};
const double heading2[] = {4.01};
const gsfAttitude expected =
GsfAttitude(1, times, pitch2, roll2, heave2, heading2);
VerifyAttitude(expected, *dst);
}
TEST(GsfWriteSimple, AttitudeLength2) {
// TODO(schwehr): Why do the nanoseconds not match?
const struct timespec times[] = {{1438016822, 0},
{1438016823, 0}};
const double pitch[] = {1.2, -3.4};
const double roll[] = {-100.1, 100.2};
const double heave[] = {-200.2, -200.3};
// Stored as a int16 with value * 100, so cannot test negative.
const double heading[] = {181, 359};
const gsfAttitude attitude =
GsfAttitude(2, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length2.gsf", false, 40, attitude, 60);
}
} // namespace
} // namespace test
} // namespace generic_sensor_format
<commit_msg>Make a tv_nsec time big enough to not be lost in precision conversion<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Tests for writing out the basic record types.
//
// TODO(schwehr): Does this have to free what was read?
#include <sys/stat.h>
#include <memory>
#include <string>
#include "gsf.h"
#include "gsf_ft.h"
#include "gsf_test_util.h"
#include "gtest/gtest.h"
// #include <iostream> // TODO(schwehr): Remove.
// using namespace std; // TODO(schwehr): Remove.
using std::unique_ptr;
namespace generic_sensor_format {
namespace test {
namespace {
// TODO(schwehr): Switch to make_unique when C++14 is available on Travis-CI.
template <typename T, typename... Args>
std::unique_ptr<T> MakeUnique(Args &&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
TEST(GsfWriteSimple, HeaderOnly) {
int handle;
char filename[] = "header-only.gsf";
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(20, buf.st_size);
}
// TODO(schwehr): GSF_RECORD_SWATH_BATHYMETRY_PING.
// TODO(schwehr): GSF_RECORD_SOUND_VELOCITY_PROFILE
// TODO(schwehr): GSF_RECORD_PROCESSING_PARAMETERS
// TODO(schwehr): GSF_RECORD_SENSOR_PARAMETERS
void ValidateWriteComment(const char *filename, bool checksum,
int expected_write_size, const char *comment,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 20);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 40);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_COMMENT, 0};
gsfRecords record;
record.comment = GsfComment({1, 2}, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_COMMENT, data_id.recordID);
VerifyComment(record.comment, read_record.comment);
}
TEST(GsfWriteSimple, CommentEmpty) {
char filename[] = "comment-empty.gsf";
char comment[] = "";
ValidateWriteComment(filename, false, 20, comment, 40);
}
TEST(GsfWriteSimple, CommentEmptyChecksum) {
char filename[] = "comment-empty-checksum.gsf";
char comment[] = "";
ValidateWriteComment(filename, true, 24, comment, 44);
}
TEST(GsfWriteSimple, CommentUpTo5) {
char filename1[] = "comment-1.gsf";
char comment1[] = "a";
ValidateWriteComment(filename1, false, 24, comment1, 44);
char filename2[] = "comment-2.gsf";
char comment2[] = "ab";
ValidateWriteComment(filename2, false, 24, comment2, 44);
char filename3[] = "comment-3.gsf";
char comment3[] = "abc";
ValidateWriteComment(filename3, false, 24, comment3, 44);
char filename4[] = "comment-4.gsf";
char comment4[] = "abcd";
ValidateWriteComment(filename4, false, 24, comment4, 44);
char filename5[] = "comment-5.gsf";
char comment5[] = "abcde";
ValidateWriteComment(filename5, false, 28, comment5, 48);
}
TEST(GsfWriteSimple, CommentLarge) {
char filename[] = "comment-large.gsf";
char comment[] =
"ab"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"de";
ValidateWriteComment(filename, false, 656, comment, 676);
}
void ValidateWriteHistory(const char *filename, bool checksum,
int expected_write_size, const char *host_name,
const char *operator_name, const char *command_line,
const char *comment, int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 28);
ASSERT_NE(nullptr, host_name);
ASSERT_LE(strlen(host_name), GSF_HOST_NAME_LENGTH);
ASSERT_NE(nullptr, operator_name);
ASSERT_LE(strlen(operator_name), GSF_OPERATOR_LENGTH);
ASSERT_NE(nullptr, command_line);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 48);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_HISTORY, 0};
gsfRecords record;
record.history =
GsfHistory({1, 2}, host_name, operator_name, command_line, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_HISTORY, data_id.recordID);
VerifyHistory(record.history, read_record.history);
}
TEST(GsfWriteSimple, History) {
ValidateWriteHistory("history-empty.gsf", false, 28, "", "", "", "", 48);
ValidateWriteHistory("history-empty-checksum.gsf", true, 32, "", "", "", "",
52);
ValidateWriteHistory("history-1.gsf", false, 32, "a", "b", "c", "d", 52);
ValidateWriteHistory("history-longer.gsf", false, 40, "ab", "cde", "fghi",
"jklm", 60);
}
// TODO(schwehr): GSF_RECORD_NAVIGATION_ERROR
// TODO(schwehr): GSF_RECORD_SWATH_BATHY_SUMMARY
// TODO(schwehr): GSF_RECORD_SINGLE_BEAM_PING
// TODO(schwehr): GSF_RECORD_HV_NAVIGATION_ERROR
void ValidateWriteAttitude(const char *filename, bool checksum,
int expected_write_size, const gsfAttitude &attitude,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 20);
ASSERT_GE(expected_file_size, 40);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_ATTITUDE, 0};
gsfRecords record;
record.attitude = attitude;
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_ATTITUDE, data_id.recordID);
VerifyAttitude(record.attitude, read_record.attitude);
}
unique_ptr<gsfAttitude> WriteAttitudeAndReturnRead(const char *filename,
const gsfAttitude &attitude,
int *file_size,
int *num_bytes) {
// TODO(schwehr): Add error handling.
int handle;
if (0 != gsfOpen(filename, GSF_CREATE, &handle)) {
return nullptr;
}
gsfDataID data_id = {false, 0, GSF_RECORD_ATTITUDE, 0};
gsfRecords record;
record.attitude = attitude;
if (gsfWrite(handle, &data_id, &record) < 20) {
// Do not check return since we are already in trouble.
gsfClose(handle);
return nullptr;
}
if (0 != gsfClose(handle)) {
return nullptr;
}
struct stat buf;
if (0 != stat(filename, &buf)) {
return nullptr;
}
*file_size = buf.st_size;
if (0 != gsfOpen(filename, GSF_READONLY, &handle)) {
return nullptr;
}
gsfRecords read_record;
*num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
if (*num_bytes < 24) {
return nullptr;
}
return MakeUnique<gsfAttitude>(read_record.attitude);
}
TEST(GsfWriteSimple, AttitudeEmpty) {
const struct timespec times[] = {{3, 4}};
const gsfAttitude attitude =
GsfAttitude(0, times, nullptr, nullptr, nullptr, nullptr);
ValidateWriteAttitude("attitude-empty.gsf", false, 20, attitude, 40);
}
TEST(GsfWriteSimple, AttitudeLength1Zeros) {
const struct timespec times0[] = {{5, 6}};
const double data0[] = {0.0};
const gsfAttitude attitude0 =
GsfAttitude(1, times0, data0, data0, data0, data0);
ValidateWriteAttitude("attitude-length1-0.gsf", false, 28, attitude0, 48);
}
TEST(GsfWriteSimple, AttitudeLength1) {
const struct timespec times[] = {{7, 8}};
const double pitch[] = {1.2};
const double roll[] = {2.2};
const double heave[] = {3.3};
const double heading[] = {4.4};
const gsfAttitude attitude =
GsfAttitude(1, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length1-1-checksum.gsf", true, 32, attitude,
52);
}
TEST(GsfWriteSimple, AttitudeLength1Negative) {
const struct timespec times[] = {{9, 10}};
const double pitch[] = {-1.2};
const double roll[] = {-3.4};
const double heave[] = {-5.6};
// Stored as a int16 with value * 100, so cannot test negative.
const double heading[] = {7.8};
const gsfAttitude attitude =
GsfAttitude(1, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length1-neg.gsf", false, 28, attitude, 48);
}
TEST(GsfWriteSimple, AttitudeRounding) {
const struct timespec times[] = {{11, 12}};
const double pitch[] = {-1.002};
const double roll[] = {-2.0052};
const double heave[] = {3.0045};
const double heading[] = {4.0052};
const gsfAttitude src = GsfAttitude(1, times, pitch, roll, heave, heading);
int file_size;
int num_bytes;
const unique_ptr<gsfAttitude> dst = WriteAttitudeAndReturnRead(
"attitude-round.gsf", src, &file_size, &num_bytes);
ASSERT_NE(nullptr, dst);
ASSERT_EQ(48, file_size);
ASSERT_EQ(28, num_bytes);
const double pitch2[] = {-1.00};
const double roll2[] = {-2.01};
const double heave2[] = {3.00};
const double heading2[] = {4.01};
const gsfAttitude expected =
GsfAttitude(1, times, pitch2, roll2, heave2, heading2);
VerifyAttitude(expected, *dst);
}
TEST(GsfWriteSimple, AttitudeLength2) {
// TODO(schwehr): Why do the nanoseconds not match?
const struct timespec times[] = {{1438016822, 2},
{1438016823, 90000000}};
const double pitch[] = {1.2, -3.4};
const double roll[] = {-100.1, 100.2};
const double heave[] = {-200.2, -200.3};
// Stored as a int16 with value * 100, so cannot test negative.
const double heading[] = {181, 359};
const gsfAttitude attitude =
GsfAttitude(2, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length2.gsf", false, 40, attitude, 60);
}
} // namespace
} // namespace test
} // namespace generic_sensor_format
<|endoftext|>
|
<commit_before>/*
Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open
Source Software License
Copyright (c) 2008 Ames Laboratory Iowa State University
All rights reserved.
Redistribution and use of HOOMD, 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 holder nor the names HOOMD's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND
CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
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.
*/
// $Id$
// $URL$
/*! \file LJForceComputeGPU.cc
\brief Defines the LJForceComputeGPU class
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include "LJForceComputeGPU.h"
#include "cuda_runtime.h"
#include <stdexcept>
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
using namespace std;
/*! \param pdata Particle Data to compute forces on
\param nlist Neighborlist to use for computing the forces
\param r_cut Cuttoff radius beyond which the force is 0
\post memory is allocated and all parameters lj1 and lj2 are set to 0.0
\note The LJForceComputeGPU does not own the Neighborlist, the caller should
delete the neighborlist when done.
*/
LJForceComputeGPU::LJForceComputeGPU(boost::shared_ptr<ParticleData> pdata, boost::shared_ptr<NeighborList> nlist, Scalar r_cut)
: LJForceCompute(pdata, nlist, r_cut)
{
// can't run on the GPU if there aren't any GPUs in the execution configuration
if (exec_conf.gpu.size() == 0)
{
cerr << endl << "***Error! Creating a LJForceComputeGPU with no GPU in the execution configuration" << endl << endl;
throw std::runtime_error("Error initializing LJForceComputeGPU");
}
if (m_ntypes > 44)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle " << m_ntypes << " types" << endl << endl;
throw runtime_error("Error initializing LJForceComputeGPU");
}
// default block size is the highest performance in testing on different hardware
// choose based on compute capability of the device
cudaDeviceProp deviceProp;
int dev;
exec_conf.gpu[0]->call(bind(cudaGetDevice, &dev));
exec_conf.gpu[0]->call(bind(cudaGetDeviceProperties, &deviceProp, dev));
if (deviceProp.major == 1 && deviceProp.minor == 0)
m_block_size = 320;
else if (deviceProp.major == 1 && deviceProp.minor == 1)
m_block_size = 256;
else if (deviceProp.major == 1 && deviceProp.minor < 4)
m_block_size = 352;
else
{
cout << "***Warning! Unknown compute " << deviceProp.major << "." << deviceProp.minor << " when tuning block size for LJForceComputeGPU" << endl;
m_block_size = 64;
}
// ulf workaround setup
#ifndef DISABLE_ULF_WORKAROUND
// the ULF workaround is needed on GTX280 and older GPUS
// it is not needed on C1060, S1070, GTX285, GTX295, and (hopefully) newer ones
m_ulf_workaround = true;
if (deviceProp.major == 1 && deviceProp.minor >= 3)
m_ulf_workaround = false;
if (string(deviceProp.name) == "GTX 280")
m_ulf_workaround = true;
if (m_ulf_workaround)
cout << "Notice: ULF bug workaround enabled for LJForceComputeGPU" << endl;
#else
m_ulf_workaround = false;
#endif
// allocate the coeff data on the GPU
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
d_coeffs.resize(exec_conf.gpu.size());
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
exec_conf.gpu[cur_gpu]->setTag(__FILE__, __LINE__);
exec_conf.gpu[cur_gpu]->call(bind(cudaMalloc, (void **)((void *)&d_coeffs[cur_gpu]), nbytes));
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaMemset, (void *)d_coeffs[cur_gpu], 0, nbytes));
}
// allocate the coeff data on the CPU
h_coeffs = new float2[m_pdata->getNTypes()*m_pdata->getNTypes()];
}
LJForceComputeGPU::~LJForceComputeGPU()
{
// free the coefficients on the GPU
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaFree, (void *)d_coeffs[cur_gpu]));
}
delete[] h_coeffs;
}
/*! \param block_size Size of the block to run on the device
Performance of the code may be dependant on the block size run
on the GPU. \a block_size should be set to be a multiple of 32.
*/
void LJForceComputeGPU::setBlockSize(int block_size)
{
m_block_size = block_size;
}
/*! \post The parameters \a lj1 and \a lj2 are set for the pairs \a typ1, \a typ2 and \a typ2, \a typ1.
\note \a lj? are low level parameters used in the calculation. In order to specify
these for a normal lennard jones formula (with alpha), they should be set to the following.
- \a lj1 = 4.0 * epsilon * pow(sigma,12.0)
- \a lj2 = alpha * 4.0 * epsilon * pow(sigma,6.0);
Setting the parameters for typ1,typ2 automatically sets the same parameters for typ2,typ1: there
is no need to call this funciton for symmetric pairs. Any pairs that this function is not called
for will have lj1 and lj2 set to 0.0.
\param typ1 Specifies one type of the pair
\param typ2 Specifies the second type of the pair
\param lj1 First parameter used to calcluate forces
\param lj2 Second parameter used to calculate forces
*/
void LJForceComputeGPU::setParams(unsigned int typ1, unsigned int typ2, Scalar lj1, Scalar lj2)
{
assert(h_coeffs);
if (typ1 >= m_ntypes || typ2 >= m_ntypes)
{
cerr << endl << "***Error! Trying to set LJ params for a non existant type! " << typ1 << "," << typ2 << endl << endl;
throw runtime_error("LJForceComputeGpu::setParams argument error");
}
// set coeffs in both symmetric positions in the matrix
h_coeffs[typ1*m_pdata->getNTypes() + typ2] = make_float2(lj1, lj2);
h_coeffs[typ2*m_pdata->getNTypes() + typ1] = make_float2(lj1, lj2);
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->call(bind(cudaMemcpy, d_coeffs[cur_gpu], h_coeffs, nbytes, cudaMemcpyHostToDevice));
}
/*! \post The lennard jones forces are computed for the given timestep on the GPU.
The neighborlist's compute method is called to ensure that it is up to date
before forces are computed.
\param timestep Current time step of the simulation
Calls gpu_compute_lj_forces to do the dirty work.
*/
void LJForceComputeGPU::computeForces(unsigned int timestep)
{
// start by updating the neighborlist
m_nlist->compute(timestep);
// start the profile
if (m_prof) m_prof->push(exec_conf, "LJ pair");
// The GPU implementation CANNOT handle a half neighborlist, error out now
bool third_law = m_nlist->getStorageMode() == NeighborList::half;
if (third_law)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle a half neighborlist" << endl << endl;
throw runtime_error("Error computing forces in LJForceComputeGPU");
}
// access the neighbor list, which just selects the neighborlist into the device's memory, copying
// it there if needed
vector<gpu_nlist_array>& nlist = m_nlist->getListGPU();
// access the particle data
vector<gpu_pdata_arrays>& pdata = m_pdata->acquireReadOnlyGPU();
gpu_boxsize box = m_pdata->getBoxGPU();
// run the kernel on all GPUs in parallel
exec_conf.tagAll(__FILE__, __LINE__);
lj_options opt;
opt.r_cutsq = m_r_cut * m_r_cut;
opt.block_size = m_block_size;
opt.xplor_fraction = m_xplor_fraction;
opt.ulf_workaround = m_ulf_workaround;
opt.shift_mode = m_shift_mode;
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->callAsync(bind(gpu_compute_lj_forces, m_gpu_forces[cur_gpu].d_data, pdata[cur_gpu], box, nlist[cur_gpu], d_coeffs[cur_gpu], m_pdata->getNTypes(), opt));
exec_conf.syncAll();
m_pdata->release();
// the force data is now only up to date on the gpu
m_data_location = gpu;
Scalar avg_neigh = m_nlist->estimateNNeigh();
int64_t n_calc = int64_t(avg_neigh * m_pdata->getN());
int64_t mem_transfer = m_pdata->getN() * (4 + 16 + 20) + n_calc * (4 + 16);
int64_t flops = n_calc * (3+12+5+2+2+6+3+2+7);
if (m_prof) m_prof->pop(exec_conf, flops, mem_transfer);
}
void export_LJForceComputeGPU()
{
class_<LJForceComputeGPU, boost::shared_ptr<LJForceComputeGPU>, bases<LJForceCompute>, boost::noncopyable >
("LJForceComputeGPU", init< boost::shared_ptr<ParticleData>, boost::shared_ptr<NeighborList>, Scalar >())
.def("setBlockSize", &LJForceComputeGPU::setBlockSize)
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<commit_msg>Fixed a bug where the ULF workaround was not being enabled in GTX 280 when using CUDA 2.2.<commit_after>/*
Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open
Source Software License
Copyright (c) 2008 Ames Laboratory Iowa State University
All rights reserved.
Redistribution and use of HOOMD, 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 holder nor the names HOOMD's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND
CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
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.
*/
// $Id$
// $URL$
/*! \file LJForceComputeGPU.cc
\brief Defines the LJForceComputeGPU class
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include "LJForceComputeGPU.h"
#include "cuda_runtime.h"
#include <stdexcept>
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
using namespace std;
/*! \param pdata Particle Data to compute forces on
\param nlist Neighborlist to use for computing the forces
\param r_cut Cuttoff radius beyond which the force is 0
\post memory is allocated and all parameters lj1 and lj2 are set to 0.0
\note The LJForceComputeGPU does not own the Neighborlist, the caller should
delete the neighborlist when done.
*/
LJForceComputeGPU::LJForceComputeGPU(boost::shared_ptr<ParticleData> pdata, boost::shared_ptr<NeighborList> nlist, Scalar r_cut)
: LJForceCompute(pdata, nlist, r_cut)
{
// can't run on the GPU if there aren't any GPUs in the execution configuration
if (exec_conf.gpu.size() == 0)
{
cerr << endl << "***Error! Creating a LJForceComputeGPU with no GPU in the execution configuration" << endl << endl;
throw std::runtime_error("Error initializing LJForceComputeGPU");
}
if (m_ntypes > 44)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle " << m_ntypes << " types" << endl << endl;
throw runtime_error("Error initializing LJForceComputeGPU");
}
// default block size is the highest performance in testing on different hardware
// choose based on compute capability of the device
cudaDeviceProp deviceProp;
int dev;
exec_conf.gpu[0]->call(bind(cudaGetDevice, &dev));
exec_conf.gpu[0]->call(bind(cudaGetDeviceProperties, &deviceProp, dev));
if (deviceProp.major == 1 && deviceProp.minor == 0)
m_block_size = 320;
else if (deviceProp.major == 1 && deviceProp.minor == 1)
m_block_size = 256;
else if (deviceProp.major == 1 && deviceProp.minor < 4)
m_block_size = 352;
else
{
cout << "***Warning! Unknown compute " << deviceProp.major << "." << deviceProp.minor << " when tuning block size for LJForceComputeGPU" << endl;
m_block_size = 64;
}
// ulf workaround setup
#ifndef DISABLE_ULF_WORKAROUND
// the ULF workaround is needed on GTX280 and older GPUS
// it is not needed on C1060, S1070, GTX285, GTX295, and (hopefully) newer ones
m_ulf_workaround = true;
if (deviceProp.major == 1 && deviceProp.minor >= 3)
m_ulf_workaround = false;
if (string(deviceProp.name) == "GTX 280")
m_ulf_workaround = true;
if (string(deviceProp.name) == "GeForce GTX 280")
m_ulf_workaround = true;
if (m_ulf_workaround)
cout << "Notice: ULF bug workaround enabled for LJForceComputeGPU" << endl;
#else
m_ulf_workaround = false;
#endif
// allocate the coeff data on the GPU
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
d_coeffs.resize(exec_conf.gpu.size());
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
exec_conf.gpu[cur_gpu]->setTag(__FILE__, __LINE__);
exec_conf.gpu[cur_gpu]->call(bind(cudaMalloc, (void **)((void *)&d_coeffs[cur_gpu]), nbytes));
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaMemset, (void *)d_coeffs[cur_gpu], 0, nbytes));
}
// allocate the coeff data on the CPU
h_coeffs = new float2[m_pdata->getNTypes()*m_pdata->getNTypes()];
}
LJForceComputeGPU::~LJForceComputeGPU()
{
// free the coefficients on the GPU
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaFree, (void *)d_coeffs[cur_gpu]));
}
delete[] h_coeffs;
}
/*! \param block_size Size of the block to run on the device
Performance of the code may be dependant on the block size run
on the GPU. \a block_size should be set to be a multiple of 32.
*/
void LJForceComputeGPU::setBlockSize(int block_size)
{
m_block_size = block_size;
}
/*! \post The parameters \a lj1 and \a lj2 are set for the pairs \a typ1, \a typ2 and \a typ2, \a typ1.
\note \a lj? are low level parameters used in the calculation. In order to specify
these for a normal lennard jones formula (with alpha), they should be set to the following.
- \a lj1 = 4.0 * epsilon * pow(sigma,12.0)
- \a lj2 = alpha * 4.0 * epsilon * pow(sigma,6.0);
Setting the parameters for typ1,typ2 automatically sets the same parameters for typ2,typ1: there
is no need to call this funciton for symmetric pairs. Any pairs that this function is not called
for will have lj1 and lj2 set to 0.0.
\param typ1 Specifies one type of the pair
\param typ2 Specifies the second type of the pair
\param lj1 First parameter used to calcluate forces
\param lj2 Second parameter used to calculate forces
*/
void LJForceComputeGPU::setParams(unsigned int typ1, unsigned int typ2, Scalar lj1, Scalar lj2)
{
assert(h_coeffs);
if (typ1 >= m_ntypes || typ2 >= m_ntypes)
{
cerr << endl << "***Error! Trying to set LJ params for a non existant type! " << typ1 << "," << typ2 << endl << endl;
throw runtime_error("LJForceComputeGpu::setParams argument error");
}
// set coeffs in both symmetric positions in the matrix
h_coeffs[typ1*m_pdata->getNTypes() + typ2] = make_float2(lj1, lj2);
h_coeffs[typ2*m_pdata->getNTypes() + typ1] = make_float2(lj1, lj2);
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->call(bind(cudaMemcpy, d_coeffs[cur_gpu], h_coeffs, nbytes, cudaMemcpyHostToDevice));
}
/*! \post The lennard jones forces are computed for the given timestep on the GPU.
The neighborlist's compute method is called to ensure that it is up to date
before forces are computed.
\param timestep Current time step of the simulation
Calls gpu_compute_lj_forces to do the dirty work.
*/
void LJForceComputeGPU::computeForces(unsigned int timestep)
{
// start by updating the neighborlist
m_nlist->compute(timestep);
// start the profile
if (m_prof) m_prof->push(exec_conf, "LJ pair");
// The GPU implementation CANNOT handle a half neighborlist, error out now
bool third_law = m_nlist->getStorageMode() == NeighborList::half;
if (third_law)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle a half neighborlist" << endl << endl;
throw runtime_error("Error computing forces in LJForceComputeGPU");
}
// access the neighbor list, which just selects the neighborlist into the device's memory, copying
// it there if needed
vector<gpu_nlist_array>& nlist = m_nlist->getListGPU();
// access the particle data
vector<gpu_pdata_arrays>& pdata = m_pdata->acquireReadOnlyGPU();
gpu_boxsize box = m_pdata->getBoxGPU();
// run the kernel on all GPUs in parallel
exec_conf.tagAll(__FILE__, __LINE__);
lj_options opt;
opt.r_cutsq = m_r_cut * m_r_cut;
opt.block_size = m_block_size;
opt.xplor_fraction = m_xplor_fraction;
opt.ulf_workaround = m_ulf_workaround;
opt.shift_mode = m_shift_mode;
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->callAsync(bind(gpu_compute_lj_forces, m_gpu_forces[cur_gpu].d_data, pdata[cur_gpu], box, nlist[cur_gpu], d_coeffs[cur_gpu], m_pdata->getNTypes(), opt));
exec_conf.syncAll();
m_pdata->release();
// the force data is now only up to date on the gpu
m_data_location = gpu;
Scalar avg_neigh = m_nlist->estimateNNeigh();
int64_t n_calc = int64_t(avg_neigh * m_pdata->getN());
int64_t mem_transfer = m_pdata->getN() * (4 + 16 + 20) + n_calc * (4 + 16);
int64_t flops = n_calc * (3+12+5+2+2+6+3+2+7);
if (m_prof) m_prof->pop(exec_conf, flops, mem_transfer);
}
void export_LJForceComputeGPU()
{
class_<LJForceComputeGPU, boost::shared_ptr<LJForceComputeGPU>, bases<LJForceCompute>, boost::noncopyable >
("LJForceComputeGPU", init< boost::shared_ptr<ParticleData>, boost::shared_ptr<NeighborList>, Scalar >())
.def("setBlockSize", &LJForceComputeGPU::setBlockSize)
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<|endoftext|>
|
<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Tests for writing out the basic record types.
//
// TODO(schwehr): Does this have to free what was read?
#include <sys/stat.h>
#include <memory>
#include <string>
#include "gsf.h"
#include "gsf_ft.h"
#include "gsf_test_util.h"
#include "gtest/gtest.h"
// #include <iostream> // TODO(schwehr): Remove.
// using namespace std; // TODO(schwehr): Remove.
using std::unique_ptr;
namespace generic_sensor_format {
namespace test {
namespace {
// TODO(schwehr): Switch to make_unique when C++14 is available on Travis-CI.
template <typename T, typename... Args>
std::unique_ptr<T> MakeUnique(Args &&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
TEST(GsfWriteSimple, HeaderOnly) {
int handle;
char filename[] = "header-only.gsf";
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(20, buf.st_size);
}
// TODO(schwehr): GSF_RECORD_SWATH_BATHYMETRY_PING.
// TODO(schwehr): GSF_RECORD_SOUND_VELOCITY_PROFILE
// TODO(schwehr): GSF_RECORD_PROCESSING_PARAMETERS
// TODO(schwehr): GSF_RECORD_SENSOR_PARAMETERS
void ValidateWriteComment(const char *filename, bool checksum,
int expected_write_size, const char *comment,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 20);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 40);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_COMMENT, 0};
gsfRecords record;
record.comment = GsfComment({1, 2}, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_COMMENT, data_id.recordID);
VerifyComment(record.comment, read_record.comment);
}
TEST(GsfWriteSimple, CommentEmpty) {
char filename[] = "comment-empty.gsf";
char comment[] = "";
ValidateWriteComment(filename, false, 20, comment, 40);
}
TEST(GsfWriteSimple, CommentEmptyChecksum) {
char filename[] = "comment-empty-checksum.gsf";
char comment[] = "";
ValidateWriteComment(filename, true, 24, comment, 44);
}
TEST(GsfWriteSimple, CommentUpTo5) {
char filename1[] = "comment-1.gsf";
char comment1[] = "a";
ValidateWriteComment(filename1, false, 24, comment1, 44);
char filename2[] = "comment-2.gsf";
char comment2[] = "ab";
ValidateWriteComment(filename2, false, 24, comment2, 44);
char filename3[] = "comment-3.gsf";
char comment3[] = "abc";
ValidateWriteComment(filename3, false, 24, comment3, 44);
char filename4[] = "comment-4.gsf";
char comment4[] = "abcd";
ValidateWriteComment(filename4, false, 24, comment4, 44);
char filename5[] = "comment-5.gsf";
char comment5[] = "abcde";
ValidateWriteComment(filename5, false, 28, comment5, 48);
}
TEST(GsfWriteSimple, CommentLarge) {
char filename[] = "comment-large.gsf";
char comment[] =
"ab"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"de";
ValidateWriteComment(filename, false, 656, comment, 676);
}
void ValidateWriteHistory(const char *filename, bool checksum,
int expected_write_size, const char *host_name,
const char *operator_name, const char *command_line,
const char *comment, int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 28);
ASSERT_NE(nullptr, host_name);
ASSERT_LE(strlen(host_name), GSF_HOST_NAME_LENGTH);
ASSERT_NE(nullptr, operator_name);
ASSERT_LE(strlen(operator_name), GSF_OPERATOR_LENGTH);
ASSERT_NE(nullptr, command_line);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 48);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_HISTORY, 0};
gsfRecords record;
record.history =
GsfHistory({1, 2}, host_name, operator_name, command_line, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_HISTORY, data_id.recordID);
VerifyHistory(record.history, read_record.history);
}
TEST(GsfWriteSimple, History) {
ValidateWriteHistory("history-empty.gsf", false, 28, "", "", "", "", 48);
ValidateWriteHistory("history-empty-checksum.gsf", true, 32, "", "", "", "",
52);
ValidateWriteHistory("history-1.gsf", false, 32, "a", "b", "c", "d", 52);
ValidateWriteHistory("history-longer.gsf", false, 40, "ab", "cde", "fghi",
"jklm", 60);
}
// TODO(schwehr): GSF_RECORD_NAVIGATION_ERROR
// TODO(schwehr): GSF_RECORD_SWATH_BATHY_SUMMARY
// TODO(schwehr): GSF_RECORD_SINGLE_BEAM_PING
// TODO(schwehr): GSF_RECORD_HV_NAVIGATION_ERROR
void ValidateWriteAttitude(const char *filename, bool checksum,
int expected_write_size, const gsfAttitude &attitude,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 20);
ASSERT_GE(expected_file_size, 40);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_ATTITUDE, 0};
gsfRecords record;
record.attitude = attitude;
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_ATTITUDE, data_id.recordID);
VerifyAttitude(record.attitude, read_record.attitude);
}
unique_ptr<gsfAttitude> WriteAttitudeAndReturnRead(const char *filename,
const gsfAttitude &attitude,
int *file_size,
int *num_bytes) {
// TODO(schwehr): Add error handling.
int handle;
if (0 != gsfOpen(filename, GSF_CREATE, &handle)) {
return nullptr;
}
gsfDataID data_id = {false, 0, GSF_RECORD_ATTITUDE, 0};
gsfRecords record;
record.attitude = attitude;
if (gsfWrite(handle, &data_id, &record) < 20) {
// Do not check return since we are already in trouble.
gsfClose(handle);
return nullptr;
}
if (0 != gsfClose(handle)) {
return nullptr;
}
struct stat buf;
if (0 != stat(filename, &buf)) {
return nullptr;
}
*file_size = buf.st_size;
if (0 != gsfOpen(filename, GSF_READONLY, &handle)) {
return nullptr;
}
gsfRecords read_record;
*num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
if (*num_bytes < 24) {
return nullptr;
}
return MakeUnique<gsfAttitude>(read_record.attitude);
}
TEST(GsfWriteSimple, AttitudeEmpty) {
const struct timespec times[] = {{3, 4}};
const gsfAttitude attitude =
GsfAttitude(0, times, nullptr, nullptr, nullptr, nullptr);
ValidateWriteAttitude("attitude-empty.gsf", false, 20, attitude, 40);
}
TEST(GsfWriteSimple, AttitudeLength1Zeros) {
const struct timespec times0[] = {{5, 6}};
const double data0[] = {0.0};
const gsfAttitude attitude0 =
GsfAttitude(1, times0, data0, data0, data0, data0);
ValidateWriteAttitude("attitude-length1-0.gsf", false, 28, attitude0, 48);
}
TEST(GsfWriteSimple, AttitudeLength1) {
const struct timespec times[] = {{7, 8}};
const double pitch[] = {1.2};
const double roll[] = {2.2};
const double heave[] = {3.3};
const double heading[] = {4.4};
const gsfAttitude attitude =
GsfAttitude(1, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length1-1-checksum.gsf", true, 32, attitude,
52);
}
TEST(GsfWriteSimple, AttitudeLength1Negative) {
const struct timespec times[] = {{9, 10}};
const double pitch[] = {-1.2};
const double roll[] = {-3.4};
const double heave[] = {-5.6};
// Stored as a int16 with value * 100, so cannot test negative.
const double heading[] = {7.8};
const gsfAttitude attitude =
GsfAttitude(1, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length1-neg.gsf", false, 28, attitude, 48);
}
TEST(GsfWriteSimple, AttitudeRounding) {
const struct timespec times[] = {{11, 12}};
const double pitch[] = {-1.002};
const double roll[] = {-2.0052};
const double heave[] = {3.0045};
const double heading[] = {4.0052};
const gsfAttitude src = GsfAttitude(1, times, pitch, roll, heave, heading);
int file_size;
int num_bytes;
const unique_ptr<gsfAttitude> dst = WriteAttitudeAndReturnRead(
"attitude-round.gsf", src, &file_size, &num_bytes);
ASSERT_NE(nullptr, dst);
ASSERT_EQ(48, file_size);
ASSERT_EQ(28, num_bytes);
const double pitch2[] = {-1.00};
const double roll2[] = {-2.01};
const double heave2[] = {3.00};
const double heading2[] = {4.01};
const gsfAttitude expected =
GsfAttitude(1, times, pitch2, roll2, heave2, heading2);
VerifyAttitude(expected, *dst);
}
TEST(GsfWriteSimple, AttitudeLength2) {
// TODO(schwehr): Why do the nanoseconds not match?
const struct timespec times[] = {{1438016822, 2},
{1438016823, 90000000}};
const double pitch[] = {1.2, -3.4};
const double roll[] = {-100.1, 100.2};
const double heave[] = {-200.2, -200.3};
// Stored as a int16 with value * 100, so cannot test negative.
const double heading[] = {181, 359};
const gsfAttitude attitude =
GsfAttitude(2, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length2.gsf", false, 40, attitude, 60);
}
} // namespace
} // namespace test
} // namespace generic_sensor_format
<commit_msg>Change tv_nsec to be large enough to avoid being lost in rounding.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Tests for writing out the basic record types.
//
// TODO(schwehr): Does this have to free what was read?
#include <sys/stat.h>
#include <memory>
#include <string>
#include "gsf.h"
#include "gsf_ft.h"
#include "gsf_test_util.h"
#include "gtest/gtest.h"
// #include <iostream> // TODO(schwehr): Remove.
// using namespace std; // TODO(schwehr): Remove.
using std::unique_ptr;
namespace generic_sensor_format {
namespace test {
namespace {
// TODO(schwehr): Switch to make_unique when C++14 is available on Travis-CI.
template <typename T, typename... Args>
std::unique_ptr<T> MakeUnique(Args &&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
TEST(GsfWriteSimple, HeaderOnly) {
int handle;
char filename[] = "header-only.gsf";
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(20, buf.st_size);
}
// TODO(schwehr): GSF_RECORD_SWATH_BATHYMETRY_PING.
// TODO(schwehr): GSF_RECORD_SOUND_VELOCITY_PROFILE
// TODO(schwehr): GSF_RECORD_PROCESSING_PARAMETERS
// TODO(schwehr): GSF_RECORD_SENSOR_PARAMETERS
void ValidateWriteComment(const char *filename, bool checksum,
int expected_write_size, const char *comment,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 20);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 40);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_COMMENT, 0};
gsfRecords record;
record.comment = GsfComment({1, 2}, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_COMMENT, data_id.recordID);
VerifyComment(record.comment, read_record.comment);
}
TEST(GsfWriteSimple, CommentEmpty) {
char filename[] = "comment-empty.gsf";
char comment[] = "";
ValidateWriteComment(filename, false, 20, comment, 40);
}
TEST(GsfWriteSimple, CommentEmptyChecksum) {
char filename[] = "comment-empty-checksum.gsf";
char comment[] = "";
ValidateWriteComment(filename, true, 24, comment, 44);
}
TEST(GsfWriteSimple, CommentUpTo5) {
char filename1[] = "comment-1.gsf";
char comment1[] = "a";
ValidateWriteComment(filename1, false, 24, comment1, 44);
char filename2[] = "comment-2.gsf";
char comment2[] = "ab";
ValidateWriteComment(filename2, false, 24, comment2, 44);
char filename3[] = "comment-3.gsf";
char comment3[] = "abc";
ValidateWriteComment(filename3, false, 24, comment3, 44);
char filename4[] = "comment-4.gsf";
char comment4[] = "abcd";
ValidateWriteComment(filename4, false, 24, comment4, 44);
char filename5[] = "comment-5.gsf";
char comment5[] = "abcde";
ValidateWriteComment(filename5, false, 28, comment5, 48);
}
TEST(GsfWriteSimple, CommentLarge) {
char filename[] = "comment-large.gsf";
char comment[] =
"ab"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"de";
ValidateWriteComment(filename, false, 656, comment, 676);
}
void ValidateWriteHistory(const char *filename, bool checksum,
int expected_write_size, const char *host_name,
const char *operator_name, const char *command_line,
const char *comment, int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 28);
ASSERT_NE(nullptr, host_name);
ASSERT_LE(strlen(host_name), GSF_HOST_NAME_LENGTH);
ASSERT_NE(nullptr, operator_name);
ASSERT_LE(strlen(operator_name), GSF_OPERATOR_LENGTH);
ASSERT_NE(nullptr, command_line);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 48);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_HISTORY, 0};
gsfRecords record;
record.history =
GsfHistory({1, 2}, host_name, operator_name, command_line, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_HISTORY, data_id.recordID);
VerifyHistory(record.history, read_record.history);
}
TEST(GsfWriteSimple, History) {
ValidateWriteHistory("history-empty.gsf", false, 28, "", "", "", "", 48);
ValidateWriteHistory("history-empty-checksum.gsf", true, 32, "", "", "", "",
52);
ValidateWriteHistory("history-1.gsf", false, 32, "a", "b", "c", "d", 52);
ValidateWriteHistory("history-longer.gsf", false, 40, "ab", "cde", "fghi",
"jklm", 60);
}
// TODO(schwehr): GSF_RECORD_NAVIGATION_ERROR
// TODO(schwehr): GSF_RECORD_SWATH_BATHY_SUMMARY
// TODO(schwehr): GSF_RECORD_SINGLE_BEAM_PING
// TODO(schwehr): GSF_RECORD_HV_NAVIGATION_ERROR
void ValidateWriteAttitude(const char *filename, bool checksum,
int expected_write_size, const gsfAttitude &attitude,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 20);
ASSERT_GE(expected_file_size, 40);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_ATTITUDE, 0};
gsfRecords record;
record.attitude = attitude;
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_ATTITUDE, data_id.recordID);
VerifyAttitude(record.attitude, read_record.attitude);
}
unique_ptr<gsfAttitude> WriteAttitudeAndReturnRead(const char *filename,
const gsfAttitude &attitude,
int *file_size,
int *num_bytes) {
// TODO(schwehr): Add error handling.
int handle;
if (0 != gsfOpen(filename, GSF_CREATE, &handle)) {
return nullptr;
}
gsfDataID data_id = {false, 0, GSF_RECORD_ATTITUDE, 0};
gsfRecords record;
record.attitude = attitude;
if (gsfWrite(handle, &data_id, &record) < 20) {
// Do not check return since we are already in trouble.
gsfClose(handle);
return nullptr;
}
if (0 != gsfClose(handle)) {
return nullptr;
}
struct stat buf;
if (0 != stat(filename, &buf)) {
return nullptr;
}
*file_size = buf.st_size;
if (0 != gsfOpen(filename, GSF_READONLY, &handle)) {
return nullptr;
}
gsfRecords read_record;
*num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
if (*num_bytes < 24) {
return nullptr;
}
return MakeUnique<gsfAttitude>(read_record.attitude);
}
TEST(GsfWriteSimple, AttitudeEmpty) {
const struct timespec times[] = {{3, 4}};
const gsfAttitude attitude =
GsfAttitude(0, times, nullptr, nullptr, nullptr, nullptr);
ValidateWriteAttitude("attitude-empty.gsf", false, 20, attitude, 40);
}
TEST(GsfWriteSimple, AttitudeLength1Zeros) {
const struct timespec times0[] = {{5, 6}};
const double data0[] = {0.0};
const gsfAttitude attitude0 =
GsfAttitude(1, times0, data0, data0, data0, data0);
ValidateWriteAttitude("attitude-length1-0.gsf", false, 28, attitude0, 48);
}
TEST(GsfWriteSimple, AttitudeLength1) {
const struct timespec times[] = {{7, 8}};
const double pitch[] = {1.2};
const double roll[] = {2.2};
const double heave[] = {3.3};
const double heading[] = {4.4};
const gsfAttitude attitude =
GsfAttitude(1, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length1-1-checksum.gsf", true, 32, attitude,
52);
}
TEST(GsfWriteSimple, AttitudeLength1Negative) {
const struct timespec times[] = {{9, 10}};
const double pitch[] = {-1.2};
const double roll[] = {-3.4};
const double heave[] = {-5.6};
// Stored as a int16 with value * 100, so cannot test negative.
const double heading[] = {7.8};
const gsfAttitude attitude =
GsfAttitude(1, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length1-neg.gsf", false, 28, attitude, 48);
}
TEST(GsfWriteSimple, AttitudeRounding) {
const struct timespec times[] = {{11, 12}};
const double pitch[] = {-1.002};
const double roll[] = {-2.0052};
const double heave[] = {3.0045};
const double heading[] = {4.0052};
const gsfAttitude src = GsfAttitude(1, times, pitch, roll, heave, heading);
int file_size;
int num_bytes;
const unique_ptr<gsfAttitude> dst = WriteAttitudeAndReturnRead(
"attitude-round.gsf", src, &file_size, &num_bytes);
ASSERT_NE(nullptr, dst);
ASSERT_EQ(48, file_size);
ASSERT_EQ(28, num_bytes);
const double pitch2[] = {-1.00};
const double roll2[] = {-2.01};
const double heave2[] = {3.00};
const double heading2[] = {4.01};
const gsfAttitude expected =
GsfAttitude(1, times, pitch2, roll2, heave2, heading2);
VerifyAttitude(expected, *dst);
}
TEST(GsfWriteSimple, AttitudeLength2) {
// TODO(schwehr): Why do the nanoseconds not match?
const struct timespec times[] = {{1438016822, 80000000},
{1438016823, 90000000}};
const double pitch[] = {1.2, -3.4};
const double roll[] = {-100.1, 100.2};
const double heave[] = {-200.2, -200.3};
// Stored as a int16 with value * 100, so cannot test negative.
const double heading[] = {181, 359};
const gsfAttitude attitude =
GsfAttitude(2, times, pitch, roll, heave, heading);
ValidateWriteAttitude("attitude-length2.gsf", false, 40, attitude, 60);
}
} // namespace
} // namespace test
} // namespace generic_sensor_format
<|endoftext|>
|
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
*
* Condor Software Copyright Notice
* Copyright (C) 1990-2006, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE.TXT file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_debug.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "daemon.h"
#include "dc_message.h"
#include "daemon_core_sock_adapter.h"
DCMsg::DCMsg(int cmd) {
m_cmd = cmd;
m_msg_success_debug_level = D_FULLDEBUG;
m_msg_failure_debug_level = (D_ALWAYS|D_FAILURE);
m_delivery_status = DELIVERY_PENDING;
}
DCMsg::~DCMsg() {
}
char const *
DCMsg::name()
{
return getCommandString( m_cmd );
}
void
DCMsg::callMessageSendFailed( DCMessenger *messenger )
{
deliveryStatus( DELIVERY_FAILED );
messageSendFailed( messenger );
}
void
DCMsg::callMessageReceiveFailed( DCMessenger *messenger )
{
deliveryStatus( DELIVERY_FAILED );
messageReceiveFailed( messenger );
}
DCMsg::MessageClosureEnum
DCMsg::callMessageSent(
DCMessenger *messenger, Sock *sock )
{
deliveryStatus( DELIVERY_SUCCEEDED );
return messageSent( messenger, sock );
}
DCMsg::MessageClosureEnum
DCMsg::callMessageReceived(
DCMessenger *messenger, Sock *sock )
{
deliveryStatus( DELIVERY_SUCCEEDED );
return messageReceived( messenger, sock );
}
DCMsg::MessageClosureEnum
DCMsg::messageSent( DCMessenger *messenger, Sock *)
{
reportSuccess( messenger );
return MESSAGE_FINISHED;
}
DCMsg::MessageClosureEnum
DCMsg::messageReceived( DCMessenger *messenger, Sock *)
{
reportSuccess( messenger );
return MESSAGE_FINISHED;
}
void
DCMsg::messageSendFailed( DCMessenger *messenger )
{
reportFailure( messenger );
}
void
DCMsg::messageReceiveFailed( DCMessenger *messenger )
{
reportFailure( messenger );
}
void
DCMsg::reportSuccess( DCMessenger *messenger )
{
dprintf( m_msg_success_debug_level, "Sent %s to %s\n",
getCommandString( m_cmd),
messenger->peerDescription() );
}
void
DCMsg::reportFailure( DCMessenger *messenger )
{
dprintf( m_msg_failure_debug_level, "Failed to send %s to %s: %s\n",
getCommandString( m_cmd ),
messenger->peerDescription(),
m_errstack.getFullText() );
}
void
DCMsg::addError( int code, char const *format, ... )
{
va_list args;
va_start(args, format);
MyString msg;
msg.vsprintf( format,args );
m_errstack.push( "CEDAR", code, msg.Value() );
va_end(args);
}
void
DCMsg::sockFailed( Sock *sock )
{
// TODO: get specific error message from sock, if possible
if( sock->is_encode() ) {
addError( CEDAR_ERR_PUT_FAILED, "failed writing to socket" );
}
else {
addError( CEDAR_ERR_GET_FAILED, "failed reading from socket" );
}
}
DCMessenger::DCMessenger( classy_counted_ptr<Daemon> daemon )
{
m_daemon = daemon;
m_sock = NULL;
m_current_msg = NULL;
}
DCMessenger::DCMessenger( Sock *sock )
{
m_sock = sock;
m_current_msg = NULL;
}
DCMessenger::~DCMessenger()
{
// should never get deleted in the middle of a pending operation
ASSERT(!m_current_msg.get());
if( m_sock ) {
delete m_sock;
}
}
char const *DCMessenger::peerDescription()
{
if( m_daemon.get() ) {
return m_daemon->idStr();
}
if( m_sock ) {
return m_sock->get_sinful_peer();
}
EXCEPT("No daemon or sock object in DCMessenger::peerDescription()");
return NULL;
}
void DCMessenger::startCommand( classy_counted_ptr<DCMsg> msg, Stream::stream_type st, int timeout )
{
MyString error;
if( daemonCoreSockAdapter.TooManyRegisteredSockets(-1,&error) ) {
// Try again in a sec
// Eventually, it would be better to queue this centrally
// (i.e. in DaemonCore) rather than having an independent
// timer for each case. Then it would be possible to control
// priority of different messages etc.
dprintf(D_FULLDEBUG, "Delaying delivery of %s to %s, because %s\n",
msg->name(),peerDescription(),error.Value());
startCommandAfterDelay( 1, msg, st, timeout );
return;
}
// Currently, there may be only one pending operation per messenger.
ASSERT(!m_current_msg.get());
m_current_msg = msg;
incRefCount();
m_daemon->startCommand_nonblocking (
msg->m_cmd,
st,
timeout,
&msg->m_errstack,
&DCMessenger::connectCallback,
this );
}
void
DCMessenger::sendBlockingMsg( classy_counted_ptr<DCMsg> msg, Stream::stream_type st, int timeout )
{
Sock *sock = m_daemon->startCommand (
msg->m_cmd,
st,
timeout,
&msg->m_errstack);
if( !sock ) {
msg->callMessageSendFailed( this );
return;
}
writeMsg( msg, sock );
}
void
DCMessenger::doneWithSock(Stream *sock)
{
// If sock == m_sock, it will be cleaned up when the messenger
// is deleted. Otherwise, do it now.
if( sock != m_sock ) {
if( sock ) {
delete sock;
}
}
}
void
DCMessenger::connectCallback(bool success, Sock *sock, CondorError *, void *misc_data)
{
ASSERT(misc_data);
DCMessenger *self = (DCMessenger *)misc_data;
classy_counted_ptr<DCMsg> msg = self->m_current_msg;
self->m_current_msg = NULL;
if(!success) {
msg->callMessageSendFailed( self );
self->doneWithSock(sock);
}
else {
ASSERT(sock);
self->writeMsg( msg, sock );
}
self->decRefCount();
}
void DCMessenger::writeMsg( classy_counted_ptr<DCMsg> msg, Sock *sock )
{
ASSERT( msg.get() );
ASSERT( sock );
incRefCount();
/* Some day, we may send message asynchronously and call
messageSent() later, after the delivery. For now, we do it
all synchronously, right here. */
sock->encode();
if( !msg->writeMsg( this, sock ) ) {
msg->callMessageSendFailed( this );
}
else if( !sock->eom() ) {
msg->addError( CEDAR_ERR_EOM_FAILED, "failed to send EOM" );
msg->callMessageSendFailed( this );
}
else {
// Success
DCMsg::MessageClosureEnum closure = msg->callMessageSent( this, sock );
switch( closure ) {
case DCMsg::MESSAGE_FINISHED:
doneWithSock(sock);
break;
case DCMsg::MESSAGE_CONTINUING:
break;
}
}
decRefCount();
}
void DCMessenger::startReceiveMsg( classy_counted_ptr<DCMsg> msg, Sock *sock )
{
// Currently, only one pending message per messenger.
ASSERT( !m_current_msg.get() );
MyString name;
name.sprintf("<%s>", msg->name());
incRefCount();
int reg_rc = daemonCoreSockAdapter.
Register_Socket( sock, peerDescription(),
(SocketHandlercpp)&DCMessenger::receiveMsgCallback,
name.Value(), this, ALLOW );
if(reg_rc < 0) {
msg->addError(
CEDAR_ERR_REGISTER_SOCK_FAILED,
"failed to register socket (Register_Socket returned %d)",
reg_rc );
msg->callMessageSendFailed( this );
doneWithSock(sock);
decRefCount();
return;
}
m_current_msg = msg; // prevent msg from going out of reference
ASSERT(daemonCoreSockAdapter.Register_DataPtr( msg.get() ));
}
int
DCMessenger::receiveMsgCallback(Stream *sock)
{
classy_counted_ptr<DCMsg> msg = (DCMsg *) daemonCoreSockAdapter.GetDataPtr();
ASSERT(msg.get());
DCMessenger *self = msg->m_messenger_callback_ref;
ASSERT(self);
m_current_msg = NULL;
daemonCoreSockAdapter.Cancel_Socket( sock );
if( !msg->readMsg( this, (Sock *)sock ) ) {
msg->callMessageReceiveFailed( this );
doneWithSock(sock);
}
else {
ASSERT( sock );
readMsg( msg, (Sock *)sock );
}
decRefCount();
return KEEP_STREAM;
}
void
DCMessenger::readMsg( classy_counted_ptr<DCMsg> msg, Sock *sock )
{
ASSERT( msg.get() );
ASSERT( sock );
incRefCount();
sock->decode();
if( !msg->readMsg( this, sock ) ) {
msg->callMessageReceiveFailed( this );
}
else if( !sock->eom() ) {
msg->addError( CEDAR_ERR_EOM_FAILED, "failed to read EOM" );
msg->callMessageReceiveFailed( this );
}
else {
// Success
DCMsg::MessageClosureEnum closure = msg->callMessageReceived( this, sock );
switch( closure ) {
case DCMsg::MESSAGE_FINISHED:
doneWithSock(sock);
break;
case DCMsg::MESSAGE_CONTINUING:
break;
}
}
decRefCount();
}
struct QueuedCommand {
classy_counted_ptr<DCMsg> msg;
Stream::stream_type stream_type;
int timeout;
int timer_handle;
};
void
DCMessenger::startCommandAfterDelay( unsigned int delay, classy_counted_ptr<DCMsg> msg, Stream::stream_type st, int timeout )
{
QueuedCommand *qc = new QueuedCommand;
qc->msg = msg;
qc->stream_type = st;
qc->timeout = timeout;
incRefCount();
qc->timer_handle = daemonCoreSockAdapter.Register_Timer(
delay,
(Eventcpp)&DCMessenger::startCommandAfterDelay_alarm,
"DCMessenger::startCommandAfterDelay",
this );
ASSERT(qc->timer_handle != -1);
daemonCoreSockAdapter.Register_DataPtr( qc );
}
int DCMessenger::startCommandAfterDelay_alarm()
{
QueuedCommand *qc = (QueuedCommand *)daemonCoreSockAdapter.GetDataPtr();
ASSERT(qc);
startCommand(qc->msg,qc->stream_type,qc->timeout);
delete qc;
decRefCount();
return TRUE;
}
DCStringMsg::DCStringMsg( int cmd, char const *str ):
DCMsg( cmd )
{
m_str = str;
}
bool DCStringMsg::writeMsg( DCMessenger *, Sock *sock )
{
if( !sock->put( (char *)m_str.Value() ) ) {
sockFailed( sock );
return false;
}
return true;
}
bool DCStringMsg::readMsg( DCMessenger *, Sock *sock )
{
char *str = NULL;
if( !sock->get( str ) ){
sockFailed( sock );
return false;
}
m_str = str;
free(str);
return true;
}
<commit_msg>just got rid of some control characters (ctrl-m's) that somehow got into the source file<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
*
* Condor Software Copyright Notice
* Copyright (C) 1990-2006, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE.TXT file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_debug.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "daemon.h"
#include "dc_message.h"
#include "daemon_core_sock_adapter.h"
DCMsg::DCMsg(int cmd) {
m_cmd = cmd;
m_msg_success_debug_level = D_FULLDEBUG;
m_msg_failure_debug_level = (D_ALWAYS|D_FAILURE);
m_delivery_status = DELIVERY_PENDING;
}
DCMsg::~DCMsg() {
}
char const *
DCMsg::name()
{
return getCommandString( m_cmd );
}
void
DCMsg::callMessageSendFailed( DCMessenger *messenger )
{
deliveryStatus( DELIVERY_FAILED );
messageSendFailed( messenger );
}
void
DCMsg::callMessageReceiveFailed( DCMessenger *messenger )
{
deliveryStatus( DELIVERY_FAILED );
messageReceiveFailed( messenger );
}
DCMsg::MessageClosureEnum
DCMsg::callMessageSent(
DCMessenger *messenger, Sock *sock )
{
deliveryStatus( DELIVERY_SUCCEEDED );
return messageSent( messenger, sock );
}
DCMsg::MessageClosureEnum
DCMsg::callMessageReceived(
DCMessenger *messenger, Sock *sock )
{
deliveryStatus( DELIVERY_SUCCEEDED );
return messageReceived( messenger, sock );
}
DCMsg::MessageClosureEnum
DCMsg::messageSent( DCMessenger *messenger, Sock *)
{
reportSuccess( messenger );
return MESSAGE_FINISHED;
}
DCMsg::MessageClosureEnum
DCMsg::messageReceived( DCMessenger *messenger, Sock *)
{
reportSuccess( messenger );
return MESSAGE_FINISHED;
}
void
DCMsg::messageSendFailed( DCMessenger *messenger )
{
reportFailure( messenger );
}
void
DCMsg::messageReceiveFailed( DCMessenger *messenger )
{
reportFailure( messenger );
}
void
DCMsg::reportSuccess( DCMessenger *messenger )
{
dprintf( m_msg_success_debug_level, "Sent %s to %s\n",
getCommandString( m_cmd),
messenger->peerDescription() );
}
void
DCMsg::reportFailure( DCMessenger *messenger )
{
dprintf( m_msg_failure_debug_level, "Failed to send %s to %s: %s\n",
getCommandString( m_cmd ),
messenger->peerDescription(),
m_errstack.getFullText() );
}
void
DCMsg::addError( int code, char const *format, ... )
{
va_list args;
va_start(args, format);
MyString msg;
msg.vsprintf( format,args );
m_errstack.push( "CEDAR", code, msg.Value() );
va_end(args);
}
void
DCMsg::sockFailed( Sock *sock )
{
// TODO: get specific error message from sock, if possible
if( sock->is_encode() ) {
addError( CEDAR_ERR_PUT_FAILED, "failed writing to socket" );
}
else {
addError( CEDAR_ERR_GET_FAILED, "failed reading from socket" );
}
}
DCMessenger::DCMessenger( classy_counted_ptr<Daemon> daemon )
{
m_daemon = daemon;
m_sock = NULL;
m_current_msg = NULL;
}
DCMessenger::DCMessenger( Sock *sock )
{
m_sock = sock;
m_current_msg = NULL;
}
DCMessenger::~DCMessenger()
{
// should never get deleted in the middle of a pending operation
ASSERT(!m_current_msg.get());
if( m_sock ) {
delete m_sock;
}
}
char const *DCMessenger::peerDescription()
{
if( m_daemon.get() ) {
return m_daemon->idStr();
}
if( m_sock ) {
return m_sock->get_sinful_peer();
}
EXCEPT("No daemon or sock object in DCMessenger::peerDescription()");
return NULL;
}
void DCMessenger::startCommand( classy_counted_ptr<DCMsg> msg, Stream::stream_type st, int timeout )
{
MyString error;
if( daemonCoreSockAdapter.TooManyRegisteredSockets(-1,&error) ) {
// Try again in a sec
// Eventually, it would be better to queue this centrally
// (i.e. in DaemonCore) rather than having an independent
// timer for each case. Then it would be possible to control
// priority of different messages etc.
dprintf(D_FULLDEBUG, "Delaying delivery of %s to %s, because %s\n",
msg->name(),peerDescription(),error.Value());
startCommandAfterDelay( 1, msg, st, timeout );
return;
}
// Currently, there may be only one pending operation per messenger.
ASSERT(!m_current_msg.get());
m_current_msg = msg;
incRefCount();
m_daemon->startCommand_nonblocking (
msg->m_cmd,
st,
timeout,
&msg->m_errstack,
&DCMessenger::connectCallback,
this );
}
void
DCMessenger::sendBlockingMsg( classy_counted_ptr<DCMsg> msg, Stream::stream_type st, int timeout )
{
Sock *sock = m_daemon->startCommand (
msg->m_cmd,
st,
timeout,
&msg->m_errstack);
if( !sock ) {
msg->callMessageSendFailed( this );
return;
}
writeMsg( msg, sock );
}
void
DCMessenger::doneWithSock(Stream *sock)
{
// If sock == m_sock, it will be cleaned up when the messenger
// is deleted. Otherwise, do it now.
if( sock != m_sock ) {
if( sock ) {
delete sock;
}
}
}
void
DCMessenger::connectCallback(bool success, Sock *sock, CondorError *, void *misc_data)
{
ASSERT(misc_data);
DCMessenger *self = (DCMessenger *)misc_data;
classy_counted_ptr<DCMsg> msg = self->m_current_msg;
self->m_current_msg = NULL;
if(!success) {
msg->callMessageSendFailed( self );
self->doneWithSock(sock);
}
else {
ASSERT(sock);
self->writeMsg( msg, sock );
}
self->decRefCount();
}
void DCMessenger::writeMsg( classy_counted_ptr<DCMsg> msg, Sock *sock )
{
ASSERT( msg.get() );
ASSERT( sock );
incRefCount();
/* Some day, we may send message asynchronously and call
messageSent() later, after the delivery. For now, we do it
all synchronously, right here. */
sock->encode();
if( !msg->writeMsg( this, sock ) ) {
msg->callMessageSendFailed( this );
}
else if( !sock->eom() ) {
msg->addError( CEDAR_ERR_EOM_FAILED, "failed to send EOM" );
msg->callMessageSendFailed( this );
}
else {
// Success
DCMsg::MessageClosureEnum closure = msg->callMessageSent( this, sock );
switch( closure ) {
case DCMsg::MESSAGE_FINISHED:
doneWithSock(sock);
break;
case DCMsg::MESSAGE_CONTINUING:
break;
}
}
decRefCount();
}
void DCMessenger::startReceiveMsg( classy_counted_ptr<DCMsg> msg, Sock *sock )
{
// Currently, only one pending message per messenger.
ASSERT( !m_current_msg.get() );
MyString name;
name.sprintf("<%s>", msg->name());
incRefCount();
int reg_rc = daemonCoreSockAdapter.
Register_Socket( sock, peerDescription(),
(SocketHandlercpp)&DCMessenger::receiveMsgCallback,
name.Value(), this, ALLOW );
if(reg_rc < 0) {
msg->addError(
CEDAR_ERR_REGISTER_SOCK_FAILED,
"failed to register socket (Register_Socket returned %d)",
reg_rc );
msg->callMessageSendFailed( this );
doneWithSock(sock);
decRefCount();
return;
}
m_current_msg = msg; // prevent msg from going out of reference
ASSERT(daemonCoreSockAdapter.Register_DataPtr( msg.get() ));
}
int
DCMessenger::receiveMsgCallback(Stream *sock)
{
classy_counted_ptr<DCMsg> msg = (DCMsg *) daemonCoreSockAdapter.GetDataPtr();
ASSERT(msg.get());
DCMessenger *self = msg->m_messenger_callback_ref;
ASSERT(self);
m_current_msg = NULL;
daemonCoreSockAdapter.Cancel_Socket( sock );
if( !msg->readMsg( this, (Sock *)sock ) ) {
msg->callMessageReceiveFailed( this );
doneWithSock(sock);
}
else {
ASSERT( sock );
readMsg( msg, (Sock *)sock );
}
decRefCount();
return KEEP_STREAM;
}
void
DCMessenger::readMsg( classy_counted_ptr<DCMsg> msg, Sock *sock )
{
ASSERT( msg.get() );
ASSERT( sock );
incRefCount();
sock->decode();
if( !msg->readMsg( this, sock ) ) {
msg->callMessageReceiveFailed( this );
}
else if( !sock->eom() ) {
msg->addError( CEDAR_ERR_EOM_FAILED, "failed to read EOM" );
msg->callMessageReceiveFailed( this );
}
else {
// Success
DCMsg::MessageClosureEnum closure = msg->callMessageReceived( this, sock );
switch( closure ) {
case DCMsg::MESSAGE_FINISHED:
doneWithSock(sock);
break;
case DCMsg::MESSAGE_CONTINUING:
break;
}
}
decRefCount();
}
struct QueuedCommand {
classy_counted_ptr<DCMsg> msg;
Stream::stream_type stream_type;
int timeout;
int timer_handle;
};
void
DCMessenger::startCommandAfterDelay( unsigned int delay, classy_counted_ptr<DCMsg> msg, Stream::stream_type st, int timeout )
{
QueuedCommand *qc = new QueuedCommand;
qc->msg = msg;
qc->stream_type = st;
qc->timeout = timeout;
incRefCount();
qc->timer_handle = daemonCoreSockAdapter.Register_Timer(
delay,
(Eventcpp)&DCMessenger::startCommandAfterDelay_alarm,
"DCMessenger::startCommandAfterDelay",
this );
ASSERT(qc->timer_handle != -1);
daemonCoreSockAdapter.Register_DataPtr( qc );
}
int DCMessenger::startCommandAfterDelay_alarm()
{
QueuedCommand *qc = (QueuedCommand *)daemonCoreSockAdapter.GetDataPtr();
ASSERT(qc);
startCommand(qc->msg,qc->stream_type,qc->timeout);
delete qc;
decRefCount();
return TRUE;
}
DCStringMsg::DCStringMsg( int cmd, char const *str ):
DCMsg( cmd )
{
m_str = str;
}
bool DCStringMsg::writeMsg( DCMessenger *, Sock *sock )
{
if( !sock->put( (char *)m_str.Value() ) ) {
sockFailed( sock );
return false;
}
return true;
}
bool DCStringMsg::readMsg( DCMessenger *, Sock *sock )
{
char *str = NULL;
if( !sock->get( str ) ){
sockFailed( sock );
return false;
}
m_str = str;
free(str);
return true;
}
<|endoftext|>
|
<commit_before>#ifndef __Data_general__
#define __Data_general__
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm> // has the for_each
using namespace std;
enum GenEd {
// Foundation Studies
FYW, // First-Year Writing
WRI, // Writing in Context
FOL, // Foreign Language
ORC, // Oral Communication
AQR, // Abstract and Quantitative Reasoning
SPM, // Studies in Physical Movement
// Core Studies
HWC, // Historical Studies in Western Culture
MCD, // Multicultural Studies: Domestic
MCG, // Multicultural Studies: Global
ALSA, // Artistic and Literary Studies: Artistic Studies
ALSL, // Artistic and Literary Studies: Literary Studies
BTSB, // Biblical and Theological Studies: Bible
BTST, // Biblical and Theological Studies: Theology
SED, // Studies in Natural Science: Scientific Exploration and Discovery
IST, // Studies in Natural Science: Integrated Scientific Topics
HBS, // Studies in Human Behavior and Society
// Integrative Studies
EIN // Ethical Issues and Normative Perspectives
};
enum dept_t {
AFAM, //0 Africa and the Americas
ALSO, //1 Alternate Language Study Option
AMCON, //2 American Conversation
AMST, //3 American Studies
ARMS, //4 American Racial and Multicultural Studies
ART, //5 Art and Art History
ASIAN, //6 Asian Studies (AS)
BIO, //7 Biology (BI)
BMOLS, //8 Biomolecular Science
CHEM, //9 Chemistry (CH)
CHIN, //10 Chinese
CLASS, //11 Classics
CSCI, //12 Computer Science
DANCE, //13 Dance
ECON, //14 Economics
EDUC, //15 Education
ENGL, //16 English
ENVST, //17 Environmental Studies (ES)
ESAC, //18 Exercise Science Activity
ESTH, //19 Exercise Science Theory
FAMST, //20 Family Studies
FILM, //21 Film Studies
FREN, //22 French
GCON, //23 Great Conversation
GERM, //24 German
GREEK, //25 Greek
HIST, //26 History (HI)
HSPST, //27 Hispanic Studies
// Note: INTER used to be ID, but there was a system conflict.
IDFA, //28
INTD, //29 Interdepartmental
INTER, //30 Interdisciplinary
IS, //31 Integrative Studies
JAPAN, //32 Japanese
LATIN, //33 Latin
MATH, //34 Mathematics
MEDIA, //35 Media Studies
MEDVL, //36 Medieval Studies
MGMT, //37 Management Studies
MUSIC, //38 Music
MUSPF, //39 Music Performance
NEURO, //40 Neuroscience
NORW, //41 Norwegian
NURS, //42 Nursing
PHIL, //43 Philosphy
PHYS, //44 Physics
PSCI, //45 Political Science
PSYCH, //46 Psychology
REL, //47 Religion (RE)
RUSSN, //48 Russian
SCICN, //49 Science Conversation
SOAN, //50 Sociology and Anthropology
SPAN, //51 Spanish
STAT, //52 Statistics
SWRK, //53 Social Work
THEAT, //54 Theater
WMGST, //55 Women's & Gender Studies
WRIT, //56 Writing
NONE,
};
string tostring(int i);
int stringToInt(string const& str);
float stringToFloat(string const& str);
vector<string> &split(const string &s, char delim, vector<string> &elems);
vector<string> split(const string &s, char delim);
string removeAllQuotes(string s);
string removeTrailingSlashes(string s);
string removeTrailingText(string s, string toRemove);
string removeStartingText(string s, string toRemove);
string deDoubleString(string s);
void printEntireRecord(vector<string> record);
#endif
<commit_msg>Remove #include <algorithm> as we didn't use it<commit_after>#ifndef __Data_general__
#define __Data_general__
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
using namespace std;
enum GenEd {
// Foundation Studies
FYW, // First-Year Writing
WRI, // Writing in Context
FOL, // Foreign Language
ORC, // Oral Communication
AQR, // Abstract and Quantitative Reasoning
SPM, // Studies in Physical Movement
// Core Studies
HWC, // Historical Studies in Western Culture
MCD, // Multicultural Studies: Domestic
MCG, // Multicultural Studies: Global
ALSA, // Artistic and Literary Studies: Artistic Studies
ALSL, // Artistic and Literary Studies: Literary Studies
BTSB, // Biblical and Theological Studies: Bible
BTST, // Biblical and Theological Studies: Theology
SED, // Studies in Natural Science: Scientific Exploration and Discovery
IST, // Studies in Natural Science: Integrated Scientific Topics
HBS, // Studies in Human Behavior and Society
// Integrative Studies
EIN // Ethical Issues and Normative Perspectives
};
enum dept_t {
AFAM, //0 Africa and the Americas
ALSO, //1 Alternate Language Study Option
AMCON, //2 American Conversation
AMST, //3 American Studies
ARMS, //4 American Racial and Multicultural Studies
ART, //5 Art and Art History
ASIAN, //6 Asian Studies (AS)
BIO, //7 Biology (BI)
BMOLS, //8 Biomolecular Science
CHEM, //9 Chemistry (CH)
CHIN, //10 Chinese
CLASS, //11 Classics
CSCI, //12 Computer Science
DANCE, //13 Dance
ECON, //14 Economics
EDUC, //15 Education
ENGL, //16 English
ENVST, //17 Environmental Studies (ES)
ESAC, //18 Exercise Science Activity
ESTH, //19 Exercise Science Theory
FAMST, //20 Family Studies
FILM, //21 Film Studies
FREN, //22 French
GCON, //23 Great Conversation
GERM, //24 German
GREEK, //25 Greek
HIST, //26 History (HI)
HSPST, //27 Hispanic Studies
// Note: INTER used to be ID, but there was a system conflict.
IDFA, //28
INTD, //29 Interdepartmental
INTER, //30 Interdisciplinary
IS, //31 Integrative Studies
JAPAN, //32 Japanese
LATIN, //33 Latin
MATH, //34 Mathematics
MEDIA, //35 Media Studies
MEDVL, //36 Medieval Studies
MGMT, //37 Management Studies
MUSIC, //38 Music
MUSPF, //39 Music Performance
NEURO, //40 Neuroscience
NORW, //41 Norwegian
NURS, //42 Nursing
PHIL, //43 Philosphy
PHYS, //44 Physics
PSCI, //45 Political Science
PSYCH, //46 Psychology
REL, //47 Religion (RE)
RUSSN, //48 Russian
SCICN, //49 Science Conversation
SOAN, //50 Sociology and Anthropology
SPAN, //51 Spanish
STAT, //52 Statistics
SWRK, //53 Social Work
THEAT, //54 Theater
WMGST, //55 Women's & Gender Studies
WRIT, //56 Writing
NONE,
};
string tostring(int i);
int stringToInt(string const& str);
float stringToFloat(string const& str);
vector<string> &split(const string &s, char delim, vector<string> &elems);
vector<string> split(const string &s, char delim);
string removeAllQuotes(string s);
string removeTrailingSlashes(string s);
string removeTrailingText(string s, string toRemove);
string removeStartingText(string s, string toRemove);
string deDoubleString(string s);
void printEntireRecord(vector<string> record);
#endif
<|endoftext|>
|
<commit_before>// material_tests.cpp
#include "material_tests.h"
#include <cmath>
#include <gtest/gtest.h>
#include "cyc_limits.h"
#include "error.h"
#include "mat_query.h"
using cyclus::Iso;
using cyclus::CompMap;
using cyclus::Composition;
using cyclus::Material;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Constructors) {
EXPECT_EQ(default_mat_->units(), "kg");
EXPECT_EQ(default_mat_->type(), cyclus::Material::kType);
EXPECT_GE(default_mat_->id(), 0);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Clone) {
cyclus::Resource::Ptr clone_mat;
ASSERT_NO_THROW(clone_mat = test_mat_->Clone());
EXPECT_EQ(test_mat_->type(), clone_mat->type());
EXPECT_EQ(test_mat_->units(), clone_mat->units());
EXPECT_DOUBLE_EQ(test_mat_->quantity(), clone_mat->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractRes) {
EXPECT_DOUBLE_EQ(test_size_, test_mat_->quantity());
double other_size = test_size_ / 3;
cyclus::Resource::Ptr other;
ASSERT_NO_THROW(other = test_mat_->ExtractRes(other_size));
EXPECT_DOUBLE_EQ(test_size_ - other_size, test_mat_->quantity());
EXPECT_DOUBLE_EQ(other_size, other->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, SimpleAbsorb) {
double val = 1.5 * units::kg;
cyclus::Material::Ptr m1 = cyclus::Material::CreateUntracked(val, test_comp_);
cyclus::Material::Ptr m2 = cyclus::Material::CreateUntracked(val, test_comp_);
ASSERT_EQ(m1->comp(), m2->comp());
ASSERT_EQ(m1->quantity(), m2->quantity());
m2->Absorb(m1);
///ASSERT_EQ(m1->comp(), m2->comp());
///EXPECT_EQ(m1->quantity(), 0);
///EXPECT_EQ(m2->quantity(), 2 * val);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbLikeMaterial) {
cyclus::Material::Ptr mat1;
cyclus::Material::Ptr mat2;
cyclus::Material::Ptr mat10;
mat1 = cyclus::Material::CreateUntracked(1 * test_size_, test_comp_);
mat2 = cyclus::Material::CreateUntracked(2 * test_size_, test_comp_);
mat10 = cyclus::Material::CreateUntracked(10 * test_size_, test_comp_);
// see that two materials with the same composition do the right thing
double orig = test_mat_->quantity();
int factor = 2;
ASSERT_NO_THROW(test_mat_->Absorb(mat1));
ASSERT_EQ(test_mat_->comp(), mat1->comp());
EXPECT_DOUBLE_EQ(test_mat_->quantity(), factor * orig);
factor += 2;
ASSERT_NO_THROW(test_mat_->Absorb(mat2));
ASSERT_EQ(test_mat_->comp(), mat2->comp());
EXPECT_DOUBLE_EQ(test_mat_->quantity(), factor * orig);
factor += 10;
ASSERT_NO_THROW(test_mat_->Absorb(mat10));
ASSERT_EQ(test_mat_->comp(), mat10->comp());
EXPECT_DOUBLE_EQ(test_mat_->quantity(), factor * orig);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbUnLikeMaterial) {
// make a number of materials masses 1, 2, and 10
cyclus::Material::Ptr same_as_orig_test_mat = cyclus::Material::CreateUntracked(0,
test_comp_);
CompMap v;
v[pb208_] = 1.0 * units::g;
v[am241_] = 1.0 * units::g;
v[th228_] = 1.0 * units::g;
cyclus::Composition::Ptr diff_test_comp = cyclus::Composition::CreateFromMass(
v);
cyclus::Material::Ptr diff_test_mat = cyclus::Material::CreateUntracked(
test_size_ / 2,
diff_test_comp);
double orig = test_mat_->quantity();
double origdiff = diff_test_mat->quantity();
// see that materials with different compositions do the right thing
ASSERT_NO_THROW(test_mat_->Absorb(diff_test_mat));
EXPECT_NE(test_mat_->comp(), diff_test_mat->comp());
EXPECT_NE(test_mat_->comp(), same_as_orig_test_mat->comp());
EXPECT_DOUBLE_EQ(orig + origdiff, test_mat_->quantity());
EXPECT_TRUE(std::abs(same_as_orig_test_mat->quantity() -
test_mat_->quantity()) > cyclus::eps_rsrc());
// see that an empty material appropriately absorbs a not empty material.
ASSERT_NO_THROW(default_mat_->Absorb(test_mat_));
EXPECT_DOUBLE_EQ(orig + origdiff, default_mat_->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbZeroMaterial) {
Material::Ptr same_as_test_mat = Material::CreateUntracked(0, test_comp_);
EXPECT_NO_THROW(test_mat_->Absorb(same_as_test_mat));
EXPECT_FLOAT_EQ(test_size_, test_mat_->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbIntoZeroMaterial) {
Material::Ptr same_as_test_mat = Material::CreateUntracked(0, test_comp_);
EXPECT_NO_THROW(same_as_test_mat->Absorb(test_mat_));
EXPECT_FLOAT_EQ(test_size_, same_as_test_mat->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractMass) {
double amt = test_size_ / 3;
double diff = test_size_ - amt;
cyclus::Material::Ptr extracted;
EXPECT_DOUBLE_EQ(test_mat_->quantity(), test_size_); // we expect this amt
EXPECT_NO_THROW(extracted = test_mat_->ExtractQty(amt)); // extract an amt
EXPECT_DOUBLE_EQ(extracted->quantity(), amt); // check correctness
EXPECT_DOUBLE_EQ(test_mat_->quantity(), diff); // check correctness
EXPECT_EQ(test_mat_->comp(), extracted->comp());
EXPECT_THROW(two_test_mat_->ExtractQty(2 * two_test_mat_->quantity()),
cyclus::Error);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractComplete) {
cyclus::Material::Ptr m1;
EXPECT_NO_THROW(m1 = test_mat_->ExtractComp(test_size_, test_comp_));
EXPECT_EQ(m1->comp(), test_comp_);
EXPECT_DOUBLE_EQ(0, test_mat_->quantity());
EXPECT_DOUBLE_EQ(test_size_, m1->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractOverQty) {
EXPECT_THROW(diff_mat_->ExtractComp(2 * test_size_, test_comp_),
cyclus::ValueError);
EXPECT_THROW(test_mat_->ExtractComp(2 * test_size_, test_comp_),
cyclus::ValueError);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractOverComp) {
Material::Ptr m;
CompMap inexact = diff_comp_->mass();
inexact[am241_] *= 2;
Composition::Ptr inexact_comp = Composition::CreateFromMass(inexact);
EXPECT_THROW(diff_mat_->ExtractComp(test_size_, inexact_comp),
cyclus::ValueError);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractCompleteInexactComp) {
// Complete extraction
// this should succeed even if inexact, within eps.
Material::Ptr m1;
// make an inexact composition
CompMap inexact = diff_comp_->mass();
inexact[am241_] *= (1 - cyclus::eps_rsrc() / test_size_);
Composition::Ptr inexact_comp = Composition::CreateFromMass(inexact);
m1 = diff_mat_->ExtractComp(test_size_, inexact_comp);
EXPECT_EQ(m1->comp(), inexact_comp);
EXPECT_NEAR(test_size_, m1->quantity(), cyclus::eps_rsrc());
cyclus::MatQuery mq(diff_mat_);
EXPECT_NEAR(0, mq.mass(am241_), cyclus::eps_rsrc());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractHalf) {
cyclus::Material::Ptr m1 = two_test_mat_->ExtractComp(test_size_, test_comp_);
EXPECT_DOUBLE_EQ(test_size_, m1->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractDiffComp) {
// differing comp minus one element equals old comp minus new
cyclus::Material::Ptr m1;
double orig = diff_mat_->quantity();
CompMap v = diff_mat_->comp()->atom();
cyclus::MatQuery mq(diff_mat_);
const double orig_u235 = mq.mass(u235_);
const double orig_am241 = mq.mass(am241_);
const double orig_pb208 = mq.mass(pb208_);
EXPECT_NO_THROW(m1 = diff_mat_->ExtractComp(mq.mass(u235_), test_comp_));
EXPECT_DOUBLE_EQ(orig - m1->quantity(), diff_mat_->quantity());
EXPECT_EQ(m1->comp(), test_comp_);
EXPECT_NE(diff_mat_->comp(), test_comp_);
EXPECT_DOUBLE_EQ(orig_am241, mq.mass(am241_));
EXPECT_DOUBLE_EQ(orig_pb208, mq.mass(pb208_));
EXPECT_NE(orig_u235, mq.mass(u235_));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbThenExtract) {
cyclus::Composition::Ptr comp_to_rem = cyclus::Composition::Ptr(test_comp_);
double kg_to_rem = 0.25 * test_size_;
// if you start with an empty material
EXPECT_DOUBLE_EQ(0, default_mat_->quantity());
// then you absorb another material, they should be identical
EXPECT_NO_THROW(default_mat_->Absorb(test_mat_));
EXPECT_EQ(default_mat_->comp(), test_mat_->comp());
EXPECT_DOUBLE_EQ(test_size_, default_mat_->quantity());
// and it should be okay to extract a fraction of the original composiiton
EXPECT_NO_THROW(default_mat_->ExtractComp(kg_to_rem, comp_to_rem));
EXPECT_DOUBLE_EQ(test_size_ - kg_to_rem, default_mat_->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractInGrams) {
cyclus::Composition::Ptr comp_to_rem = cyclus::Composition::Ptr(test_comp_);
double kg_to_rem = 0.25 * test_size_;
double g_to_rem = 1000 * kg_to_rem;
// if you start with an empty material
EXPECT_DOUBLE_EQ(0, default_mat_->quantity());
// then you absorb another material, they should be identical
EXPECT_NO_THROW(default_mat_->Absorb(test_mat_));
EXPECT_EQ(default_mat_->comp(), test_mat_->comp());
EXPECT_DOUBLE_EQ(test_size_, default_mat_->quantity());
// and it should be okay to extract part of the original composiiton IN GRAMS
EXPECT_NO_THROW(default_mat_->ExtractComp(g_to_rem * units::g, comp_to_rem));
EXPECT_DOUBLE_EQ(test_size_ - kg_to_rem, default_mat_->quantity());
}
<commit_msg>added test that decay shortcut works<commit_after>// material_tests.cpp
#include "material_tests.h"
#include <cmath>
#include <gtest/gtest.h>
#include "cyc_limits.h"
#include "error.h"
#include "mat_query.h"
using cyclus::Iso;
using cyclus::CompMap;
using cyclus::Composition;
using cyclus::Material;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Constructors) {
EXPECT_EQ(default_mat_->units(), "kg");
EXPECT_EQ(default_mat_->type(), cyclus::Material::kType);
EXPECT_GE(default_mat_->id(), 0);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Clone) {
cyclus::Resource::Ptr clone_mat;
ASSERT_NO_THROW(clone_mat = test_mat_->Clone());
EXPECT_EQ(test_mat_->type(), clone_mat->type());
EXPECT_EQ(test_mat_->units(), clone_mat->units());
EXPECT_DOUBLE_EQ(test_mat_->quantity(), clone_mat->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractRes) {
EXPECT_DOUBLE_EQ(test_size_, test_mat_->quantity());
double other_size = test_size_ / 3;
cyclus::Resource::Ptr other;
ASSERT_NO_THROW(other = test_mat_->ExtractRes(other_size));
EXPECT_DOUBLE_EQ(test_size_ - other_size, test_mat_->quantity());
EXPECT_DOUBLE_EQ(other_size, other->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, SimpleAbsorb) {
double val = 1.5 * units::kg;
cyclus::Material::Ptr m1 = cyclus::Material::CreateUntracked(val, test_comp_);
cyclus::Material::Ptr m2 = cyclus::Material::CreateUntracked(val, test_comp_);
ASSERT_EQ(m1->comp(), m2->comp());
ASSERT_EQ(m1->quantity(), m2->quantity());
m2->Absorb(m1);
///ASSERT_EQ(m1->comp(), m2->comp());
///EXPECT_EQ(m1->quantity(), 0);
///EXPECT_EQ(m2->quantity(), 2 * val);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbLikeMaterial) {
cyclus::Material::Ptr mat1;
cyclus::Material::Ptr mat2;
cyclus::Material::Ptr mat10;
mat1 = cyclus::Material::CreateUntracked(1 * test_size_, test_comp_);
mat2 = cyclus::Material::CreateUntracked(2 * test_size_, test_comp_);
mat10 = cyclus::Material::CreateUntracked(10 * test_size_, test_comp_);
// see that two materials with the same composition do the right thing
double orig = test_mat_->quantity();
int factor = 2;
ASSERT_NO_THROW(test_mat_->Absorb(mat1));
ASSERT_EQ(test_mat_->comp(), mat1->comp());
EXPECT_DOUBLE_EQ(test_mat_->quantity(), factor * orig);
factor += 2;
ASSERT_NO_THROW(test_mat_->Absorb(mat2));
ASSERT_EQ(test_mat_->comp(), mat2->comp());
EXPECT_DOUBLE_EQ(test_mat_->quantity(), factor * orig);
factor += 10;
ASSERT_NO_THROW(test_mat_->Absorb(mat10));
ASSERT_EQ(test_mat_->comp(), mat10->comp());
EXPECT_DOUBLE_EQ(test_mat_->quantity(), factor * orig);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbUnLikeMaterial) {
// make a number of materials masses 1, 2, and 10
cyclus::Material::Ptr same_as_orig_test_mat = cyclus::Material::CreateUntracked(0,
test_comp_);
CompMap v;
v[pb208_] = 1.0 * units::g;
v[am241_] = 1.0 * units::g;
v[th228_] = 1.0 * units::g;
cyclus::Composition::Ptr diff_test_comp = cyclus::Composition::CreateFromMass(
v);
cyclus::Material::Ptr diff_test_mat = cyclus::Material::CreateUntracked(
test_size_ / 2,
diff_test_comp);
double orig = test_mat_->quantity();
double origdiff = diff_test_mat->quantity();
// see that materials with different compositions do the right thing
ASSERT_NO_THROW(test_mat_->Absorb(diff_test_mat));
EXPECT_NE(test_mat_->comp(), diff_test_mat->comp());
EXPECT_NE(test_mat_->comp(), same_as_orig_test_mat->comp());
EXPECT_DOUBLE_EQ(orig + origdiff, test_mat_->quantity());
EXPECT_TRUE(std::abs(same_as_orig_test_mat->quantity() -
test_mat_->quantity()) > cyclus::eps_rsrc());
// see that an empty material appropriately absorbs a not empty material.
ASSERT_NO_THROW(default_mat_->Absorb(test_mat_));
EXPECT_DOUBLE_EQ(orig + origdiff, default_mat_->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbZeroMaterial) {
Material::Ptr same_as_test_mat = Material::CreateUntracked(0, test_comp_);
EXPECT_NO_THROW(test_mat_->Absorb(same_as_test_mat));
EXPECT_FLOAT_EQ(test_size_, test_mat_->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbIntoZeroMaterial) {
Material::Ptr same_as_test_mat = Material::CreateUntracked(0, test_comp_);
EXPECT_NO_THROW(same_as_test_mat->Absorb(test_mat_));
EXPECT_FLOAT_EQ(test_size_, same_as_test_mat->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractMass) {
double amt = test_size_ / 3;
double diff = test_size_ - amt;
cyclus::Material::Ptr extracted;
EXPECT_DOUBLE_EQ(test_mat_->quantity(), test_size_); // we expect this amt
EXPECT_NO_THROW(extracted = test_mat_->ExtractQty(amt)); // extract an amt
EXPECT_DOUBLE_EQ(extracted->quantity(), amt); // check correctness
EXPECT_DOUBLE_EQ(test_mat_->quantity(), diff); // check correctness
EXPECT_EQ(test_mat_->comp(), extracted->comp());
EXPECT_THROW(two_test_mat_->ExtractQty(2 * two_test_mat_->quantity()),
cyclus::Error);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractComplete) {
cyclus::Material::Ptr m1;
EXPECT_NO_THROW(m1 = test_mat_->ExtractComp(test_size_, test_comp_));
EXPECT_EQ(m1->comp(), test_comp_);
EXPECT_DOUBLE_EQ(0, test_mat_->quantity());
EXPECT_DOUBLE_EQ(test_size_, m1->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractOverQty) {
EXPECT_THROW(diff_mat_->ExtractComp(2 * test_size_, test_comp_),
cyclus::ValueError);
EXPECT_THROW(test_mat_->ExtractComp(2 * test_size_, test_comp_),
cyclus::ValueError);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractOverComp) {
Material::Ptr m;
CompMap inexact = diff_comp_->mass();
inexact[am241_] *= 2;
Composition::Ptr inexact_comp = Composition::CreateFromMass(inexact);
EXPECT_THROW(diff_mat_->ExtractComp(test_size_, inexact_comp),
cyclus::ValueError);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractCompleteInexactComp) {
// Complete extraction
// this should succeed even if inexact, within eps.
Material::Ptr m1;
// make an inexact composition
CompMap inexact = diff_comp_->mass();
inexact[am241_] *= (1 - cyclus::eps_rsrc() / test_size_);
Composition::Ptr inexact_comp = Composition::CreateFromMass(inexact);
m1 = diff_mat_->ExtractComp(test_size_, inexact_comp);
EXPECT_EQ(m1->comp(), inexact_comp);
EXPECT_NEAR(test_size_, m1->quantity(), cyclus::eps_rsrc());
cyclus::MatQuery mq(diff_mat_);
EXPECT_NEAR(0, mq.mass(am241_), cyclus::eps_rsrc());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractHalf) {
cyclus::Material::Ptr m1 = two_test_mat_->ExtractComp(test_size_, test_comp_);
EXPECT_DOUBLE_EQ(test_size_, m1->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractDiffComp) {
// differing comp minus one element equals old comp minus new
cyclus::Material::Ptr m1;
double orig = diff_mat_->quantity();
CompMap v = diff_mat_->comp()->atom();
cyclus::MatQuery mq(diff_mat_);
const double orig_u235 = mq.mass(u235_);
const double orig_am241 = mq.mass(am241_);
const double orig_pb208 = mq.mass(pb208_);
EXPECT_NO_THROW(m1 = diff_mat_->ExtractComp(mq.mass(u235_), test_comp_));
EXPECT_DOUBLE_EQ(orig - m1->quantity(), diff_mat_->quantity());
EXPECT_EQ(m1->comp(), test_comp_);
EXPECT_NE(diff_mat_->comp(), test_comp_);
EXPECT_DOUBLE_EQ(orig_am241, mq.mass(am241_));
EXPECT_DOUBLE_EQ(orig_pb208, mq.mass(pb208_));
EXPECT_NE(orig_u235, mq.mass(u235_));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbThenExtract) {
cyclus::Composition::Ptr comp_to_rem = cyclus::Composition::Ptr(test_comp_);
double kg_to_rem = 0.25 * test_size_;
// if you start with an empty material
EXPECT_DOUBLE_EQ(0, default_mat_->quantity());
// then you absorb another material, they should be identical
EXPECT_NO_THROW(default_mat_->Absorb(test_mat_));
EXPECT_EQ(default_mat_->comp(), test_mat_->comp());
EXPECT_DOUBLE_EQ(test_size_, default_mat_->quantity());
// and it should be okay to extract a fraction of the original composiiton
EXPECT_NO_THROW(default_mat_->ExtractComp(kg_to_rem, comp_to_rem));
EXPECT_DOUBLE_EQ(test_size_ - kg_to_rem, default_mat_->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractInGrams) {
cyclus::Composition::Ptr comp_to_rem = cyclus::Composition::Ptr(test_comp_);
double kg_to_rem = 0.25 * test_size_;
double g_to_rem = 1000 * kg_to_rem;
// if you start with an empty material
EXPECT_DOUBLE_EQ(0, default_mat_->quantity());
// then you absorb another material, they should be identical
EXPECT_NO_THROW(default_mat_->Absorb(test_mat_));
EXPECT_EQ(default_mat_->comp(), test_mat_->comp());
EXPECT_DOUBLE_EQ(test_size_, default_mat_->quantity());
// and it should be okay to extract part of the original composiiton IN GRAMS
EXPECT_NO_THROW(default_mat_->ExtractComp(g_to_rem * units::g, comp_to_rem));
EXPECT_DOUBLE_EQ(test_size_ - kg_to_rem, default_mat_->quantity());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, DecayShortcut) {
using cyclus::Composition;
cyclus::CompMap mp;
mp[92235] = 1;
Composition::Ptr c = Composition::CreateFromAtom(mp);
cyclus::Material::Ptr m = Material::CreateUntracked(1.0, c);
double u235_decay_const = 8.087e-11; // per month
double eps = 1e-3;
double threshold = -1 * std::log(1-eps) / u235_decay_const;
m->Decay(threshold * 0.9);
EXPECT_EQ(c, m->comp());
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 "code_generator.h"
#include "code_generator_arm.h"
#include "code_generator_x86.h"
#include "dex/verified_method.h"
#include "driver/dex_compilation_unit.h"
#include "gc_map_builder.h"
#include "leb128.h"
#include "mapping_table.h"
#include "utils/assembler.h"
#include "verifier/dex_gc_map.h"
#include "vmap_table.h"
namespace art {
void CodeGenerator::Compile(CodeAllocator* allocator) {
const GrowableArray<HBasicBlock*>* blocks = GetGraph()->GetBlocks();
DCHECK(blocks->Get(0) == GetGraph()->GetEntryBlock());
DCHECK(GoesToNextBlock(GetGraph()->GetEntryBlock(), blocks->Get(1)));
GenerateFrameEntry();
for (size_t i = 0; i < blocks->Size(); i++) {
CompileBlock(blocks->Get(i));
}
size_t code_size = GetAssembler()->CodeSize();
uint8_t* buffer = allocator->Allocate(code_size);
MemoryRegion code(buffer, code_size);
GetAssembler()->FinalizeInstructions(code);
}
void CodeGenerator::CompileBlock(HBasicBlock* block) {
Bind(GetLabelOf(block));
HGraphVisitor* location_builder = GetLocationBuilder();
HGraphVisitor* instruction_visitor = GetInstructionVisitor();
for (HInstructionIterator it(*block->GetInstructions()); !it.Done(); it.Advance()) {
HInstruction* current = it.Current();
current->Accept(location_builder);
InitLocations(current);
current->Accept(instruction_visitor);
}
}
size_t CodeGenerator::AllocateFreeRegisterInternal(
bool* blocked_registers, size_t number_of_registers) const {
for (size_t regno = 0; regno < number_of_registers; regno++) {
if (!blocked_registers[regno]) {
blocked_registers[regno] = true;
return regno;
}
}
LOG(FATAL) << "Unreachable";
return -1;
}
void CodeGenerator::AllocateRegistersLocally(HInstruction* instruction) const {
LocationSummary* locations = instruction->GetLocations();
if (locations == nullptr) return;
for (size_t i = 0, e = GetNumberOfRegisters(); i < e; ++i) {
blocked_registers_[i] = false;
}
// Mark all fixed input, temp and output registers as used.
for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
Location loc = locations->InAt(i);
if (loc.IsRegister()) {
// Check that a register is not specified twice in the summary.
DCHECK(!blocked_registers_[loc.GetEncoding()]);
blocked_registers_[loc.GetEncoding()] = true;
}
}
for (size_t i = 0, e = locations->GetTempCount(); i < e; ++i) {
Location loc = locations->GetTemp(i);
if (loc.IsRegister()) {
// Check that a register is not specified twice in the summary.
DCHECK(!blocked_registers_[loc.GetEncoding()]);
blocked_registers_[loc.GetEncoding()] = true;
}
}
SetupBlockedRegisters(blocked_registers_);
// Allocate all unallocated input locations.
for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
Location loc = locations->InAt(i);
HInstruction* input = instruction->InputAt(i);
if (loc.IsUnallocated()) {
if (loc.GetPolicy() == Location::kRequiresRegister) {
loc = Location::RegisterLocation(
AllocateFreeRegister(input->GetType(), blocked_registers_));
} else {
DCHECK_EQ(loc.GetPolicy(), Location::kAny);
HLoadLocal* load = input->AsLoadLocal();
if (load != nullptr) {
loc = GetStackLocation(load);
} else {
loc = Location::RegisterLocation(
AllocateFreeRegister(input->GetType(), blocked_registers_));
}
}
locations->SetInAt(i, loc);
}
}
// Allocate all unallocated temp locations.
for (size_t i = 0, e = locations->GetTempCount(); i < e; ++i) {
Location loc = locations->GetTemp(i);
if (loc.IsUnallocated()) {
DCHECK_EQ(loc.GetPolicy(), Location::kRequiresRegister);
// TODO: Adjust handling of temps. We currently consider temps to use
// core registers. They may also use floating point registers at some point.
loc = Location::RegisterLocation(static_cast<ManagedRegister>(
AllocateFreeRegister(Primitive::kPrimInt, blocked_registers_)));
locations->SetTempAt(i, loc);
}
}
Location result_location = locations->Out();
if (result_location.IsUnallocated()) {
switch (result_location.GetPolicy()) {
case Location::kAny:
case Location::kRequiresRegister:
result_location = Location::RegisterLocation(
AllocateFreeRegister(instruction->GetType(), blocked_registers_));
break;
case Location::kSameAsFirstInput:
result_location = locations->InAt(0);
break;
}
locations->SetOut(result_location);
}
}
void CodeGenerator::InitLocations(HInstruction* instruction) {
if (instruction->GetLocations() == nullptr) {
return;
}
AllocateRegistersLocally(instruction);
for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
Location location = instruction->GetLocations()->InAt(i);
if (location.IsValid()) {
// Move the input to the desired location.
Move(instruction->InputAt(i), location, instruction);
}
}
}
bool CodeGenerator::GoesToNextBlock(HBasicBlock* current, HBasicBlock* next) const {
// We currently iterate over the block in insertion order.
return current->GetBlockId() + 1 == next->GetBlockId();
}
Label* CodeGenerator::GetLabelOf(HBasicBlock* block) const {
return block_labels_.GetRawStorage() + block->GetBlockId();
}
CodeGenerator* CodeGenerator::Create(ArenaAllocator* allocator,
HGraph* graph,
InstructionSet instruction_set) {
switch (instruction_set) {
case kArm:
case kThumb2: {
return new (allocator) arm::CodeGeneratorARM(graph);
}
case kMips:
return nullptr;
case kX86: {
return new (allocator) x86::CodeGeneratorX86(graph);
}
case kX86_64: {
return new (allocator) x86::CodeGeneratorX86(graph);
}
default:
return nullptr;
}
}
void CodeGenerator::BuildNativeGCMap(
std::vector<uint8_t>* data, const DexCompilationUnit& dex_compilation_unit) const {
const std::vector<uint8_t>& gc_map_raw =
dex_compilation_unit.GetVerifiedMethod()->GetDexGcMap();
verifier::DexPcToReferenceMap dex_gc_map(&(gc_map_raw)[0]);
uint32_t max_native_offset = 0;
for (size_t i = 0; i < pc_infos_.Size(); i++) {
uint32_t native_offset = pc_infos_.Get(i).native_pc;
if (native_offset > max_native_offset) {
max_native_offset = native_offset;
}
}
GcMapBuilder builder(data, pc_infos_.Size(), max_native_offset, dex_gc_map.RegWidth());
for (size_t i = 0; i < pc_infos_.Size(); i++) {
struct PcInfo pc_info = pc_infos_.Get(i);
uint32_t native_offset = pc_info.native_pc;
uint32_t dex_pc = pc_info.dex_pc;
const uint8_t* references = dex_gc_map.FindBitMap(dex_pc, false);
CHECK(references != NULL) << "Missing ref for dex pc 0x" << std::hex << dex_pc;
builder.AddEntry(native_offset, references);
}
}
void CodeGenerator::BuildMappingTable(std::vector<uint8_t>* data) const {
uint32_t pc2dex_data_size = 0u;
uint32_t pc2dex_entries = pc_infos_.Size();
uint32_t pc2dex_offset = 0u;
int32_t pc2dex_dalvik_offset = 0;
uint32_t dex2pc_data_size = 0u;
uint32_t dex2pc_entries = 0u;
// We currently only have pc2dex entries.
for (size_t i = 0; i < pc2dex_entries; i++) {
struct PcInfo pc_info = pc_infos_.Get(i);
pc2dex_data_size += UnsignedLeb128Size(pc_info.native_pc - pc2dex_offset);
pc2dex_data_size += SignedLeb128Size(pc_info.dex_pc - pc2dex_dalvik_offset);
pc2dex_offset = pc_info.native_pc;
pc2dex_dalvik_offset = pc_info.dex_pc;
}
uint32_t total_entries = pc2dex_entries + dex2pc_entries;
uint32_t hdr_data_size = UnsignedLeb128Size(total_entries) + UnsignedLeb128Size(pc2dex_entries);
uint32_t data_size = hdr_data_size + pc2dex_data_size + dex2pc_data_size;
data->resize(data_size);
uint8_t* data_ptr = &(*data)[0];
uint8_t* write_pos = data_ptr;
write_pos = EncodeUnsignedLeb128(write_pos, total_entries);
write_pos = EncodeUnsignedLeb128(write_pos, pc2dex_entries);
DCHECK_EQ(static_cast<size_t>(write_pos - data_ptr), hdr_data_size);
uint8_t* write_pos2 = write_pos + pc2dex_data_size;
pc2dex_offset = 0u;
pc2dex_dalvik_offset = 0u;
for (size_t i = 0; i < pc2dex_entries; i++) {
struct PcInfo pc_info = pc_infos_.Get(i);
DCHECK(pc2dex_offset <= pc_info.native_pc);
write_pos = EncodeUnsignedLeb128(write_pos, pc_info.native_pc - pc2dex_offset);
write_pos = EncodeSignedLeb128(write_pos, pc_info.dex_pc - pc2dex_dalvik_offset);
pc2dex_offset = pc_info.native_pc;
pc2dex_dalvik_offset = pc_info.dex_pc;
}
DCHECK_EQ(static_cast<size_t>(write_pos - data_ptr), hdr_data_size + pc2dex_data_size);
DCHECK_EQ(static_cast<size_t>(write_pos2 - data_ptr), data_size);
if (kIsDebugBuild) {
// Verify the encoded table holds the expected data.
MappingTable table(data_ptr);
CHECK_EQ(table.TotalSize(), total_entries);
CHECK_EQ(table.PcToDexSize(), pc2dex_entries);
auto it = table.PcToDexBegin();
auto it2 = table.DexToPcBegin();
for (size_t i = 0; i < pc2dex_entries; i++) {
struct PcInfo pc_info = pc_infos_.Get(i);
CHECK_EQ(pc_info.native_pc, it.NativePcOffset());
CHECK_EQ(pc_info.dex_pc, it.DexPc());
++it;
}
CHECK(it == table.PcToDexEnd());
CHECK(it2 == table.DexToPcEnd());
}
}
void CodeGenerator::BuildVMapTable(std::vector<uint8_t>* data) const {
Leb128EncodingVector vmap_encoder;
// We currently don't use callee-saved registers.
size_t size = 0 + 1 /* marker */ + 0;
vmap_encoder.Reserve(size + 1u); // All values are likely to be one byte in ULEB128 (<128).
vmap_encoder.PushBackUnsigned(size);
vmap_encoder.PushBackUnsigned(VmapTable::kAdjustedFpMarker);
*data = vmap_encoder.GetData();
}
} // namespace art
<commit_msg>am ac2918a8: am f2f8252a: am 6ab0d9fe: Merge "Make all registers available when allocating an output register."<commit_after>/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 "code_generator.h"
#include "code_generator_arm.h"
#include "code_generator_x86.h"
#include "dex/verified_method.h"
#include "driver/dex_compilation_unit.h"
#include "gc_map_builder.h"
#include "leb128.h"
#include "mapping_table.h"
#include "utils/assembler.h"
#include "verifier/dex_gc_map.h"
#include "vmap_table.h"
namespace art {
void CodeGenerator::Compile(CodeAllocator* allocator) {
const GrowableArray<HBasicBlock*>* blocks = GetGraph()->GetBlocks();
DCHECK(blocks->Get(0) == GetGraph()->GetEntryBlock());
DCHECK(GoesToNextBlock(GetGraph()->GetEntryBlock(), blocks->Get(1)));
GenerateFrameEntry();
for (size_t i = 0; i < blocks->Size(); i++) {
CompileBlock(blocks->Get(i));
}
size_t code_size = GetAssembler()->CodeSize();
uint8_t* buffer = allocator->Allocate(code_size);
MemoryRegion code(buffer, code_size);
GetAssembler()->FinalizeInstructions(code);
}
void CodeGenerator::CompileBlock(HBasicBlock* block) {
Bind(GetLabelOf(block));
HGraphVisitor* location_builder = GetLocationBuilder();
HGraphVisitor* instruction_visitor = GetInstructionVisitor();
for (HInstructionIterator it(*block->GetInstructions()); !it.Done(); it.Advance()) {
HInstruction* current = it.Current();
current->Accept(location_builder);
InitLocations(current);
current->Accept(instruction_visitor);
}
}
size_t CodeGenerator::AllocateFreeRegisterInternal(
bool* blocked_registers, size_t number_of_registers) const {
for (size_t regno = 0; regno < number_of_registers; regno++) {
if (!blocked_registers[regno]) {
blocked_registers[regno] = true;
return regno;
}
}
LOG(FATAL) << "Unreachable";
return -1;
}
void CodeGenerator::AllocateRegistersLocally(HInstruction* instruction) const {
LocationSummary* locations = instruction->GetLocations();
if (locations == nullptr) return;
for (size_t i = 0, e = GetNumberOfRegisters(); i < e; ++i) {
blocked_registers_[i] = false;
}
// Mark all fixed input, temp and output registers as used.
for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
Location loc = locations->InAt(i);
if (loc.IsRegister()) {
// Check that a register is not specified twice in the summary.
DCHECK(!blocked_registers_[loc.GetEncoding()]);
blocked_registers_[loc.GetEncoding()] = true;
}
}
for (size_t i = 0, e = locations->GetTempCount(); i < e; ++i) {
Location loc = locations->GetTemp(i);
if (loc.IsRegister()) {
// Check that a register is not specified twice in the summary.
DCHECK(!blocked_registers_[loc.GetEncoding()]);
blocked_registers_[loc.GetEncoding()] = true;
}
}
SetupBlockedRegisters(blocked_registers_);
// Allocate all unallocated input locations.
for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
Location loc = locations->InAt(i);
HInstruction* input = instruction->InputAt(i);
if (loc.IsUnallocated()) {
if (loc.GetPolicy() == Location::kRequiresRegister) {
loc = Location::RegisterLocation(
AllocateFreeRegister(input->GetType(), blocked_registers_));
} else {
DCHECK_EQ(loc.GetPolicy(), Location::kAny);
HLoadLocal* load = input->AsLoadLocal();
if (load != nullptr) {
loc = GetStackLocation(load);
} else {
loc = Location::RegisterLocation(
AllocateFreeRegister(input->GetType(), blocked_registers_));
}
}
locations->SetInAt(i, loc);
}
}
// Allocate all unallocated temp locations.
for (size_t i = 0, e = locations->GetTempCount(); i < e; ++i) {
Location loc = locations->GetTemp(i);
if (loc.IsUnallocated()) {
DCHECK_EQ(loc.GetPolicy(), Location::kRequiresRegister);
// TODO: Adjust handling of temps. We currently consider temps to use
// core registers. They may also use floating point registers at some point.
loc = Location::RegisterLocation(static_cast<ManagedRegister>(
AllocateFreeRegister(Primitive::kPrimInt, blocked_registers_)));
locations->SetTempAt(i, loc);
}
}
// Make all registers available for the return value.
for (size_t i = 0, e = GetNumberOfRegisters(); i < e; ++i) {
blocked_registers_[i] = false;
}
SetupBlockedRegisters(blocked_registers_);
Location result_location = locations->Out();
if (result_location.IsUnallocated()) {
switch (result_location.GetPolicy()) {
case Location::kAny:
case Location::kRequiresRegister:
result_location = Location::RegisterLocation(
AllocateFreeRegister(instruction->GetType(), blocked_registers_));
break;
case Location::kSameAsFirstInput:
result_location = locations->InAt(0);
break;
}
locations->SetOut(result_location);
}
}
void CodeGenerator::InitLocations(HInstruction* instruction) {
if (instruction->GetLocations() == nullptr) {
return;
}
AllocateRegistersLocally(instruction);
for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
Location location = instruction->GetLocations()->InAt(i);
if (location.IsValid()) {
// Move the input to the desired location.
Move(instruction->InputAt(i), location, instruction);
}
}
}
bool CodeGenerator::GoesToNextBlock(HBasicBlock* current, HBasicBlock* next) const {
// We currently iterate over the block in insertion order.
return current->GetBlockId() + 1 == next->GetBlockId();
}
Label* CodeGenerator::GetLabelOf(HBasicBlock* block) const {
return block_labels_.GetRawStorage() + block->GetBlockId();
}
CodeGenerator* CodeGenerator::Create(ArenaAllocator* allocator,
HGraph* graph,
InstructionSet instruction_set) {
switch (instruction_set) {
case kArm:
case kThumb2: {
return new (allocator) arm::CodeGeneratorARM(graph);
}
case kMips:
return nullptr;
case kX86: {
return new (allocator) x86::CodeGeneratorX86(graph);
}
case kX86_64: {
return new (allocator) x86::CodeGeneratorX86(graph);
}
default:
return nullptr;
}
}
void CodeGenerator::BuildNativeGCMap(
std::vector<uint8_t>* data, const DexCompilationUnit& dex_compilation_unit) const {
const std::vector<uint8_t>& gc_map_raw =
dex_compilation_unit.GetVerifiedMethod()->GetDexGcMap();
verifier::DexPcToReferenceMap dex_gc_map(&(gc_map_raw)[0]);
uint32_t max_native_offset = 0;
for (size_t i = 0; i < pc_infos_.Size(); i++) {
uint32_t native_offset = pc_infos_.Get(i).native_pc;
if (native_offset > max_native_offset) {
max_native_offset = native_offset;
}
}
GcMapBuilder builder(data, pc_infos_.Size(), max_native_offset, dex_gc_map.RegWidth());
for (size_t i = 0; i < pc_infos_.Size(); i++) {
struct PcInfo pc_info = pc_infos_.Get(i);
uint32_t native_offset = pc_info.native_pc;
uint32_t dex_pc = pc_info.dex_pc;
const uint8_t* references = dex_gc_map.FindBitMap(dex_pc, false);
CHECK(references != NULL) << "Missing ref for dex pc 0x" << std::hex << dex_pc;
builder.AddEntry(native_offset, references);
}
}
void CodeGenerator::BuildMappingTable(std::vector<uint8_t>* data) const {
uint32_t pc2dex_data_size = 0u;
uint32_t pc2dex_entries = pc_infos_.Size();
uint32_t pc2dex_offset = 0u;
int32_t pc2dex_dalvik_offset = 0;
uint32_t dex2pc_data_size = 0u;
uint32_t dex2pc_entries = 0u;
// We currently only have pc2dex entries.
for (size_t i = 0; i < pc2dex_entries; i++) {
struct PcInfo pc_info = pc_infos_.Get(i);
pc2dex_data_size += UnsignedLeb128Size(pc_info.native_pc - pc2dex_offset);
pc2dex_data_size += SignedLeb128Size(pc_info.dex_pc - pc2dex_dalvik_offset);
pc2dex_offset = pc_info.native_pc;
pc2dex_dalvik_offset = pc_info.dex_pc;
}
uint32_t total_entries = pc2dex_entries + dex2pc_entries;
uint32_t hdr_data_size = UnsignedLeb128Size(total_entries) + UnsignedLeb128Size(pc2dex_entries);
uint32_t data_size = hdr_data_size + pc2dex_data_size + dex2pc_data_size;
data->resize(data_size);
uint8_t* data_ptr = &(*data)[0];
uint8_t* write_pos = data_ptr;
write_pos = EncodeUnsignedLeb128(write_pos, total_entries);
write_pos = EncodeUnsignedLeb128(write_pos, pc2dex_entries);
DCHECK_EQ(static_cast<size_t>(write_pos - data_ptr), hdr_data_size);
uint8_t* write_pos2 = write_pos + pc2dex_data_size;
pc2dex_offset = 0u;
pc2dex_dalvik_offset = 0u;
for (size_t i = 0; i < pc2dex_entries; i++) {
struct PcInfo pc_info = pc_infos_.Get(i);
DCHECK(pc2dex_offset <= pc_info.native_pc);
write_pos = EncodeUnsignedLeb128(write_pos, pc_info.native_pc - pc2dex_offset);
write_pos = EncodeSignedLeb128(write_pos, pc_info.dex_pc - pc2dex_dalvik_offset);
pc2dex_offset = pc_info.native_pc;
pc2dex_dalvik_offset = pc_info.dex_pc;
}
DCHECK_EQ(static_cast<size_t>(write_pos - data_ptr), hdr_data_size + pc2dex_data_size);
DCHECK_EQ(static_cast<size_t>(write_pos2 - data_ptr), data_size);
if (kIsDebugBuild) {
// Verify the encoded table holds the expected data.
MappingTable table(data_ptr);
CHECK_EQ(table.TotalSize(), total_entries);
CHECK_EQ(table.PcToDexSize(), pc2dex_entries);
auto it = table.PcToDexBegin();
auto it2 = table.DexToPcBegin();
for (size_t i = 0; i < pc2dex_entries; i++) {
struct PcInfo pc_info = pc_infos_.Get(i);
CHECK_EQ(pc_info.native_pc, it.NativePcOffset());
CHECK_EQ(pc_info.dex_pc, it.DexPc());
++it;
}
CHECK(it == table.PcToDexEnd());
CHECK(it2 == table.DexToPcEnd());
}
}
void CodeGenerator::BuildVMapTable(std::vector<uint8_t>* data) const {
Leb128EncodingVector vmap_encoder;
// We currently don't use callee-saved registers.
size_t size = 0 + 1 /* marker */ + 0;
vmap_encoder.Reserve(size + 1u); // All values are likely to be one byte in ULEB128 (<128).
vmap_encoder.PushBackUnsigned(size);
vmap_encoder.PushBackUnsigned(VmapTable::kAdjustedFpMarker);
*data = vmap_encoder.GetData();
}
} // namespace art
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "folly/Bits.h"
#include "folly/CpuId.h"
// None of this is necessary if we're compiling for a target that supports
// popcnt
#ifndef __POPCNT__
namespace {
int popcount_inst(unsigned int x) {
asm ("popcntl %0, %0" : "=r" (x) : "0" (x));
return x;
}
int popcount_builtin(unsigned int x) {
return __builtin_popcount(x);
}
int popcountll_inst(unsigned long long x) {
asm ("popcntq %0, %0" : "=r" (x) : "0" (x));
return x;
}
int popcountll_builtin(unsigned long long x) {
return __builtin_popcountll(x);
}
typedef decltype(popcount_builtin) Type_popcount;
typedef decltype(popcountll_builtin) Type_popcountll;
} // namespace
// This function is called on startup to resolve folly::detail::popcount
extern "C" Type_popcount* folly_popcount_ifunc() {
return folly::CpuId().popcnt() ? popcount_inst : popcount_builtin;
}
// This function is called on startup to resolve folly::detail::popcountll
extern "C" Type_popcountll* folly_popcountll_ifunc() {
return folly::CpuId().popcnt() ? popcountll_inst : popcountll_builtin;
}
namespace folly {
namespace detail {
// Call folly_popcount_ifunc on startup to resolve to either popcount_inst
// or popcount_builtin
int popcount(unsigned int x)
__attribute__((ifunc("folly_popcount_ifunc")));
// Call folly_popcount_ifunc on startup to resolve to either popcountll_inst
// or popcountll_builtin
int popcountll(unsigned long long x)
__attribute__((ifunc("folly_popcountll_ifunc")));
} // namespace detail
} // namespace folly
#endif /* !__POPCNT__ */
<commit_msg>Remove 1 instruction from popcount<commit_after>/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "folly/Bits.h"
#include "folly/CpuId.h"
// None of this is necessary if we're compiling for a target that supports
// popcnt
#ifndef __POPCNT__
namespace {
int popcount_inst(unsigned int x) {
int n;
asm ("popcntl %1, %0" : "=r" (n) : "r" (x));
return n;
}
int popcount_builtin(unsigned int x) {
return __builtin_popcount(x);
}
int popcountll_inst(unsigned long long x) {
unsigned long long n;
asm ("popcntq %1, %0" : "=r" (n) : "r" (x));
return n;
}
int popcountll_builtin(unsigned long long x) {
return __builtin_popcountll(x);
}
typedef decltype(popcount_builtin) Type_popcount;
typedef decltype(popcountll_builtin) Type_popcountll;
} // namespace
// This function is called on startup to resolve folly::detail::popcount
extern "C" Type_popcount* folly_popcount_ifunc() {
return folly::CpuId().popcnt() ? popcount_inst : popcount_builtin;
}
// This function is called on startup to resolve folly::detail::popcountll
extern "C" Type_popcountll* folly_popcountll_ifunc() {
return folly::CpuId().popcnt() ? popcountll_inst : popcountll_builtin;
}
namespace folly {
namespace detail {
// Call folly_popcount_ifunc on startup to resolve to either popcount_inst
// or popcount_builtin
int popcount(unsigned int x)
__attribute__((ifunc("folly_popcount_ifunc")));
// Call folly_popcount_ifunc on startup to resolve to either popcountll_inst
// or popcountll_builtin
int popcountll(unsigned long long x)
__attribute__((ifunc("folly_popcountll_ifunc")));
} // namespace detail
} // namespace folly
#endif /* !__POPCNT__ */
<|endoftext|>
|
<commit_before>#include "country_status_display.hpp"
#include "framework.hpp"
#include "../gui/controller.hpp"
#include "../gui/button.hpp"
#include "../gui/text_view.hpp"
#include "../graphics/overlay_renderer.hpp"
#include "../graphics/display_list.hpp"
#include "../platform/platform.hpp"
#include "../base/thread.hpp"
#include "../base/string_format.hpp"
#include "../std/bind.hpp"
#include "../std/sstream.hpp"
using namespace storage;
CountryStatusDisplay::CountryStatusDisplay(Params const & p)
: gui::Element(p)
, m_activeMaps(p.m_activeMaps)
{
m_activeMapsSlotID = m_activeMaps.AddListener(this);
gui::Button::Params bp;
bp.m_depth = depth();
bp.m_minWidth = 200;
bp.m_minHeight = 40;
bp.m_position = graphics::EPosCenter;
auto createButtonFn = [this](gui::Button::Params const & params)
{
gui::Button * result = new gui::Button(params);
result->setIsVisible(false);
result->setOnClickListener(bind(&CountryStatusDisplay::OnButtonClicked, this, _1));
result->setFont(EActive, graphics::FontDesc(16, graphics::Color(255, 255, 255, 255)));
result->setFont(EPressed, graphics::FontDesc(16, graphics::Color(255, 255, 255, 255)));
result->setColor(EActive, graphics::Color(0, 0, 0, 0.6 * 255));
result->setColor(EPressed, graphics::Color(0, 0, 0, 0.4 * 255));
return result;
};
m_primaryButton.reset(createButtonFn(bp));
m_secondaryButton.reset(createButtonFn(bp));
gui::TextView::Params tp;
tp.m_depth = depth();
tp.m_position = graphics::EPosCenter;
m_label.reset(new gui::TextView(tp));
m_label->setIsVisible(false);
m_label->setFont(gui::Element::EActive, graphics::FontDesc(18));
setIsVisible(false);
}
CountryStatusDisplay::~CountryStatusDisplay()
{
m_activeMaps.RemoveListener(m_activeMapsSlotID);
}
void CountryStatusDisplay::SetCountryIndex(TIndex const & idx)
{
if (m_countryIdx != idx)
{
m_countryIdx = idx;
if (m_countryIdx.IsValid())
{
m_countryStatus = m_activeMaps.GetCountryStatus(m_countryIdx);
m_displayMapName = m_activeMaps.GetFormatedCountryName(m_countryIdx);
}
Repaint();
}
}
void CountryStatusDisplay::DownloadCurrentCountry(int options)
{
// I don't know why this work, but it's terrible
// This method call only on android, from "AndroidUIThread"
DownloadCountry(options, false);
}
void CountryStatusDisplay::setIsVisible(bool isVisible) const
{
if (isVisible && isVisible != TBase::isVisible())
Repaint();
TBase::setIsVisible(isVisible);
}
void CountryStatusDisplay::setIsDirtyLayout(bool isDirty) const
{
TBase::setIsDirtyLayout(isDirty);
m_label->setIsDirtyLayout(isDirty);
m_primaryButton->setIsDirtyLayout(isDirty);
m_secondaryButton->setIsDirtyLayout(isDirty);
if (isDirty)
SetVisibilityForState();
}
void CountryStatusDisplay::draw(graphics::OverlayRenderer * r,
math::Matrix<double, 3, 3> const & m) const
{
if (isVisible())
{
Lock();
checkDirtyLayout();
m_label->draw(r, m);
m_primaryButton->draw(r, m);
m_secondaryButton->draw(r, m);
Unlock();
}
}
void CountryStatusDisplay::layout()
{
if (!isVisible())
return;
SetContentForState();
auto layoutFn = [] (gui::Element * e)
{
if (e->isVisible())
e->layout();
};
layoutFn(m_label.get());
layoutFn(m_primaryButton.get());
layoutFn(m_secondaryButton.get());
ComposeElementsForState();
// !!!! Hack !!!!
// ComposeElementsForState modify pivot point of elements.
// After setPivot all elements must be relayouted.
// For reduce "cache" operations we call layout secondary
layoutFn(m_label.get());
layoutFn(m_primaryButton.get());
layoutFn(m_secondaryButton.get());
}
void CountryStatusDisplay::purge()
{
m_label->purge();
m_primaryButton->purge();
m_secondaryButton->purge();
}
void CountryStatusDisplay::cache()
{
auto cacheFn = [](gui::Element * e)
{
if (e->isVisible())
e->cache();
};
cacheFn(m_label.get());
cacheFn(m_primaryButton.get());
cacheFn(m_secondaryButton.get());
}
m2::RectD CountryStatusDisplay::GetBoundRect() const
{
ASSERT(isVisible(), ());
m2::RectD r(pivot(), pivot());
if (m_primaryButton->isVisible())
r.Add(m_primaryButton->GetBoundRect());
if (m_secondaryButton->isVisible())
r.Add(m_secondaryButton->GetBoundRect());
return r;
}
void CountryStatusDisplay::setController(gui::Controller * controller)
{
Element::setController(controller);
m_label->setController(controller);
m_primaryButton->setController(controller);
m_secondaryButton->setController(controller);
}
bool CountryStatusDisplay::onTapStarted(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapStarted, _1, _2), pt);
}
bool CountryStatusDisplay::onTapMoved(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapMoved, _1, _2), pt);
}
bool CountryStatusDisplay::onTapEnded(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapEnded, _1, _2), pt);
}
bool CountryStatusDisplay::onTapCancelled(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapCancelled, _1, _2), pt);
}
void CountryStatusDisplay::CountryStatusChanged(ActiveMapsLayout::TGroup const & group, int position)
{
TIndex index = m_activeMaps.GetCoreIndex(group, position);
if (m_countryIdx == index)
{
Lock();
m_countryStatus = m_activeMaps.GetCountryStatus(index);
Repaint();
Unlock();
}
}
void CountryStatusDisplay::DownloadingProgressUpdate(ActiveMapsLayout::TGroup const & group, int position, LocalAndRemoteSizeT const & progress)
{
TIndex index = m_activeMaps.GetCoreIndex(group, position);
if (m_countryIdx == index)
{
Lock();
m_countryStatus = m_activeMaps.GetCountryStatus(index);
m_progressSize = progress;
Repaint();
Unlock();
}
}
template <class T1, class T2>
string CountryStatusDisplay::FormatStatusMessage(string const & msgID, T1 const * t1, T2 const * t2)
{
string msg = m_controller->GetStringsBundle()->GetString(msgID);
if (t1)
{
if (t2)
msg = strings::Format(msg, *t1, *t2);
else
{
msg = strings::Format(msg, *t1);
size_t const count = msg.size();
if (count > 0)
{
if (msg[count-1] == '\n')
msg.erase(count-1, 1);
}
}
}
return msg;
}
void CountryStatusDisplay::SetVisibilityForState() const
{
uint8_t visibilityFlags = 0;
uint8_t const labelVisibility = 0x1;
uint8_t const primeVisibility = 0x2;
uint8_t const secondaryVisibility = 0x4;
if (m_countryIdx.IsValid())
{
switch (m_countryStatus)
{
case TStatus::EDownloadFailed:
visibilityFlags |= labelVisibility;
visibilityFlags |= primeVisibility;
break;
case TStatus::EDownloading:
case TStatus::EInQueue:
visibilityFlags |= labelVisibility;
break;
case TStatus::ENotDownloaded:
visibilityFlags |= labelVisibility;
visibilityFlags |= primeVisibility;
visibilityFlags |= secondaryVisibility;
break;
default:
break;
}
}
m_label->setIsVisible(visibilityFlags & labelVisibility);
m_primaryButton->setIsVisible(visibilityFlags & primeVisibility);
m_secondaryButton->setIsVisible(visibilityFlags & secondaryVisibility);
TBase::setIsVisible(m_label->isVisible() || m_primaryButton->isVisible() || m_secondaryButton->isVisible());
}
void CountryStatusDisplay::SetContentForState()
{
if (!isVisible())
return;
switch (m_countryStatus)
{
case TStatus::EDownloadFailed:
case TStatus::EOutOfMemFailed:
SetContentForError();
break;
case TStatus::ENotDownloaded:
SetContentForDownloadPropose();
break;
case TStatus::EDownloading:
SetContentForProgress();
break;
case TStatus::EInQueue:
SetContentForInQueue();
break;
default:
break;
}
}
void CountryStatusDisplay::SetContentForDownloadPropose()
{
ASSERT(m_label->isVisible(), ());
ASSERT(m_primaryButton->isVisible(), ());
ASSERT(m_secondaryButton->isVisible(), ());
LocalAndRemoteSizeT mapOnlySize = m_activeMaps.GetCountrySize(m_countryIdx, TMapOptions::EMapOnly);
LocalAndRemoteSizeT withRouting = m_activeMaps.GetCountrySize(m_countryIdx, TMapOptions::EMapWithCarRouting);
m_label->setText(m_displayMapName);
int mbToDownload = mapOnlySize.second / (1024 * 1024);
m_primaryButton->setText(FormatStatusMessage<int, int>("country_status_download", &mbToDownload));
mbToDownload = withRouting.second / (1024 * 1024);
m_secondaryButton->setText(FormatStatusMessage<int, int>("country_status_download_routing", &mbToDownload));
}
void CountryStatusDisplay::SetContentForProgress()
{
ASSERT(m_label->isVisible(), ());
int const percent = m_progressSize.first * 100 / m_progressSize.second;
m_label->setText(FormatStatusMessage<string, int>("country_status_downloading", &m_displayMapName, &percent));
}
void CountryStatusDisplay::SetContentForInQueue()
{
ASSERT(m_label->isVisible(), ());
m_label->setText(FormatStatusMessage<string, int>("country_status_added_to_queue", &m_displayMapName));
}
void CountryStatusDisplay::SetContentForError()
{
ASSERT(m_label->isVisible(), ());
ASSERT(m_primaryButton->isVisible(), ());
if (m_countryStatus == TStatus::EDownloadFailed)
m_label->setText(FormatStatusMessage<string, int>("country_status_download_failed", &m_displayMapName));
else
m_label->setText(FormatStatusMessage<int, int>("not_enough_free_space_on_sdcard"));
m_primaryButton->setText(m_controller->GetStringsBundle()->GetString("try_again"));
}
void CountryStatusDisplay::ComposeElementsForState()
{
ASSERT(isVisible(), ());
int visibleCount = 0;
auto visibleCheckFn = [&visibleCount](gui::Element const * e)
{
if (e->isVisible())
++visibleCount;
};
visibleCheckFn(m_label.get());
visibleCheckFn(m_primaryButton.get());
visibleCheckFn(m_secondaryButton.get());
ASSERT(visibleCount > 0, ());
m2::PointD const & pv = pivot();
if (visibleCount == 1)
m_label->setPivot(pv);
else if (visibleCount == 2)
{
size_t const labelHeight = m_label->GetBoundRect().SizeY();
size_t const buttonHeight = m_primaryButton->GetBoundRect().SizeY();
size_t const commonHeight = buttonHeight + labelHeight + 10 * visualScale();
m_label->setPivot(m2::PointD(pv.x, pv.y - commonHeight / 2 + labelHeight / 2));
m_primaryButton->setPivot(m2::PointD(pv.x, pv.y + commonHeight / 2 - buttonHeight / 2));
}
else
{
size_t const labelHeight = m_label->GetBoundRect().SizeY();
size_t const primButtonHeight = m_primaryButton->GetBoundRect().SizeY();
size_t const secButtonHeight = m_secondaryButton->GetBoundRect().SizeY();
size_t const emptySpace = 10 * visualScale();
double const offsetFromCenter = (primButtonHeight / 2 + emptySpace);
m_label->setPivot(m2::PointD(pv.x, pv.y - offsetFromCenter - labelHeight / 2));
m_primaryButton->setPivot(pv);
m_secondaryButton->setPivot(m2::PointD(pv.x, pv.y + offsetFromCenter + secButtonHeight / 2.0));
}
}
bool CountryStatusDisplay::OnTapAction(TTapActionFn const & action, const m2::PointD & pt)
{
bool result = false;
if (m_primaryButton->isVisible() && m_primaryButton->hitTest(pt))
result |= action(m_primaryButton, pt);
else if (m_secondaryButton->isVisible() && m_secondaryButton->hitTest(pt))
result |= action(m_secondaryButton, pt);
return result;
}
void CountryStatusDisplay::OnButtonClicked(gui::Element const * button)
{
ASSERT(m_countryIdx.IsValid(), ());
TMapOptions options = TMapOptions::EMapOnly;
if (button == m_secondaryButton.get())
options |= TMapOptions::ECarRouting;
DownloadCountry(static_cast<int>(options));
}
void CountryStatusDisplay::DownloadCountry(int options, bool checkCallback)
{
ASSERT(m_countryIdx.IsValid(), ());
if (checkCallback && m_downloadCallback)
m_downloadCallback(options);
else
{
if (IsStatusFailed())
{
m_progressSize = m_activeMaps.GetDownloadableCountrySize(m_countryIdx);
m_activeMaps.RetryDownloading(m_countryIdx);
}
else
{
TMapOptions mapOptions = static_cast<TMapOptions>(options);
m_progressSize = m_activeMaps.GetCountrySize(m_countryIdx, mapOptions);
m_activeMaps.DownloadMap(m_countryIdx, mapOptions);
}
}
}
void CountryStatusDisplay::Repaint() const
{
setIsDirtyLayout(true);
const_cast<CountryStatusDisplay *>(this)->invalidate();
}
bool CountryStatusDisplay::IsStatusFailed() const
{
return m_countryStatus == TStatus::EOutOfMemFailed || m_countryStatus == TStatus::EDownloadFailed;
}
void CountryStatusDisplay::Lock() const
{
#ifdef OMIM_OS_ANDROID
m_mutex.Lock();
#endif
}
void CountryStatusDisplay::Unlock() const
{
#ifdef OMIM_OS_ANDROID
m_mutex.Unlock();
#endif
}
<commit_msg>[core] correct format map size<commit_after>#include "country_status_display.hpp"
#include "framework.hpp"
#include "../gui/controller.hpp"
#include "../gui/button.hpp"
#include "../gui/text_view.hpp"
#include "../graphics/overlay_renderer.hpp"
#include "../graphics/display_list.hpp"
#include "../platform/platform.hpp"
#include "../base/thread.hpp"
#include "../base/string_format.hpp"
#include "../std/bind.hpp"
#include "../std/sstream.hpp"
using namespace storage;
CountryStatusDisplay::CountryStatusDisplay(Params const & p)
: gui::Element(p)
, m_activeMaps(p.m_activeMaps)
{
m_activeMapsSlotID = m_activeMaps.AddListener(this);
gui::Button::Params bp;
bp.m_depth = depth();
bp.m_minWidth = 200;
bp.m_minHeight = 40;
bp.m_position = graphics::EPosCenter;
auto createButtonFn = [this](gui::Button::Params const & params)
{
gui::Button * result = new gui::Button(params);
result->setIsVisible(false);
result->setOnClickListener(bind(&CountryStatusDisplay::OnButtonClicked, this, _1));
result->setFont(EActive, graphics::FontDesc(16, graphics::Color(255, 255, 255, 255)));
result->setFont(EPressed, graphics::FontDesc(16, graphics::Color(255, 255, 255, 255)));
result->setColor(EActive, graphics::Color(0, 0, 0, 0.6 * 255));
result->setColor(EPressed, graphics::Color(0, 0, 0, 0.4 * 255));
return result;
};
m_primaryButton.reset(createButtonFn(bp));
m_secondaryButton.reset(createButtonFn(bp));
gui::TextView::Params tp;
tp.m_depth = depth();
tp.m_position = graphics::EPosCenter;
m_label.reset(new gui::TextView(tp));
m_label->setIsVisible(false);
m_label->setFont(gui::Element::EActive, graphics::FontDesc(18));
setIsVisible(false);
}
CountryStatusDisplay::~CountryStatusDisplay()
{
m_activeMaps.RemoveListener(m_activeMapsSlotID);
}
void CountryStatusDisplay::SetCountryIndex(TIndex const & idx)
{
if (m_countryIdx != idx)
{
m_countryIdx = idx;
if (m_countryIdx.IsValid())
{
m_countryStatus = m_activeMaps.GetCountryStatus(m_countryIdx);
m_displayMapName = m_activeMaps.GetFormatedCountryName(m_countryIdx);
}
Repaint();
}
}
void CountryStatusDisplay::DownloadCurrentCountry(int options)
{
// I don't know why this work, but it's terrible
// This method call only on android, from "AndroidUIThread"
DownloadCountry(options, false);
}
void CountryStatusDisplay::setIsVisible(bool isVisible) const
{
if (isVisible && isVisible != TBase::isVisible())
Repaint();
TBase::setIsVisible(isVisible);
}
void CountryStatusDisplay::setIsDirtyLayout(bool isDirty) const
{
TBase::setIsDirtyLayout(isDirty);
m_label->setIsDirtyLayout(isDirty);
m_primaryButton->setIsDirtyLayout(isDirty);
m_secondaryButton->setIsDirtyLayout(isDirty);
if (isDirty)
SetVisibilityForState();
}
void CountryStatusDisplay::draw(graphics::OverlayRenderer * r,
math::Matrix<double, 3, 3> const & m) const
{
if (isVisible())
{
Lock();
checkDirtyLayout();
m_label->draw(r, m);
m_primaryButton->draw(r, m);
m_secondaryButton->draw(r, m);
Unlock();
}
}
void CountryStatusDisplay::layout()
{
if (!isVisible())
return;
SetContentForState();
auto layoutFn = [] (gui::Element * e)
{
if (e->isVisible())
e->layout();
};
layoutFn(m_label.get());
layoutFn(m_primaryButton.get());
layoutFn(m_secondaryButton.get());
ComposeElementsForState();
// !!!! Hack !!!!
// ComposeElementsForState modify pivot point of elements.
// After setPivot all elements must be relayouted.
// For reduce "cache" operations we call layout secondary
layoutFn(m_label.get());
layoutFn(m_primaryButton.get());
layoutFn(m_secondaryButton.get());
}
void CountryStatusDisplay::purge()
{
m_label->purge();
m_primaryButton->purge();
m_secondaryButton->purge();
}
void CountryStatusDisplay::cache()
{
auto cacheFn = [](gui::Element * e)
{
if (e->isVisible())
e->cache();
};
cacheFn(m_label.get());
cacheFn(m_primaryButton.get());
cacheFn(m_secondaryButton.get());
}
m2::RectD CountryStatusDisplay::GetBoundRect() const
{
ASSERT(isVisible(), ());
m2::RectD r(pivot(), pivot());
if (m_primaryButton->isVisible())
r.Add(m_primaryButton->GetBoundRect());
if (m_secondaryButton->isVisible())
r.Add(m_secondaryButton->GetBoundRect());
return r;
}
void CountryStatusDisplay::setController(gui::Controller * controller)
{
Element::setController(controller);
m_label->setController(controller);
m_primaryButton->setController(controller);
m_secondaryButton->setController(controller);
}
bool CountryStatusDisplay::onTapStarted(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapStarted, _1, _2), pt);
}
bool CountryStatusDisplay::onTapMoved(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapMoved, _1, _2), pt);
}
bool CountryStatusDisplay::onTapEnded(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapEnded, _1, _2), pt);
}
bool CountryStatusDisplay::onTapCancelled(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapCancelled, _1, _2), pt);
}
void CountryStatusDisplay::CountryStatusChanged(ActiveMapsLayout::TGroup const & group, int position)
{
TIndex index = m_activeMaps.GetCoreIndex(group, position);
if (m_countryIdx == index)
{
Lock();
m_countryStatus = m_activeMaps.GetCountryStatus(index);
Repaint();
Unlock();
}
}
void CountryStatusDisplay::DownloadingProgressUpdate(ActiveMapsLayout::TGroup const & group, int position, LocalAndRemoteSizeT const & progress)
{
TIndex index = m_activeMaps.GetCoreIndex(group, position);
if (m_countryIdx == index)
{
Lock();
m_countryStatus = m_activeMaps.GetCountryStatus(index);
m_progressSize = progress;
Repaint();
Unlock();
}
}
template <class T1, class T2>
string CountryStatusDisplay::FormatStatusMessage(string const & msgID, T1 const * t1, T2 const * t2)
{
string msg = m_controller->GetStringsBundle()->GetString(msgID);
if (t1)
{
if (t2)
msg = strings::Format(msg, *t1, *t2);
else
{
msg = strings::Format(msg, *t1);
size_t const count = msg.size();
if (count > 0)
{
if (msg[count-1] == '\n')
msg.erase(count-1, 1);
}
}
}
return msg;
}
void CountryStatusDisplay::SetVisibilityForState() const
{
uint8_t visibilityFlags = 0;
uint8_t const labelVisibility = 0x1;
uint8_t const primeVisibility = 0x2;
uint8_t const secondaryVisibility = 0x4;
if (m_countryIdx.IsValid())
{
switch (m_countryStatus)
{
case TStatus::EDownloadFailed:
visibilityFlags |= labelVisibility;
visibilityFlags |= primeVisibility;
break;
case TStatus::EDownloading:
case TStatus::EInQueue:
visibilityFlags |= labelVisibility;
break;
case TStatus::ENotDownloaded:
visibilityFlags |= labelVisibility;
visibilityFlags |= primeVisibility;
visibilityFlags |= secondaryVisibility;
break;
default:
break;
}
}
m_label->setIsVisible(visibilityFlags & labelVisibility);
m_primaryButton->setIsVisible(visibilityFlags & primeVisibility);
m_secondaryButton->setIsVisible(visibilityFlags & secondaryVisibility);
TBase::setIsVisible(m_label->isVisible() || m_primaryButton->isVisible() || m_secondaryButton->isVisible());
}
void CountryStatusDisplay::SetContentForState()
{
if (!isVisible())
return;
switch (m_countryStatus)
{
case TStatus::EDownloadFailed:
case TStatus::EOutOfMemFailed:
SetContentForError();
break;
case TStatus::ENotDownloaded:
SetContentForDownloadPropose();
break;
case TStatus::EDownloading:
SetContentForProgress();
break;
case TStatus::EInQueue:
SetContentForInQueue();
break;
default:
break;
}
}
namespace
{
void FormatMapSize(int sizeInBytes, string & units, int & sizeToDownload)
{
int const mbInBytes = 1024 * 1024;
int const kbInBytes = 1024;
if (sizeInBytes < mbInBytes)
{
sizeToDownload = sizeInBytes / kbInBytes;
units = "KB";
}
else
{
sizeToDownload = sizeInBytes / mbInBytes;
units = "MB";
}
}
}
void CountryStatusDisplay::SetContentForDownloadPropose()
{
ASSERT(m_label->isVisible(), ());
ASSERT(m_primaryButton->isVisible(), ());
ASSERT(m_secondaryButton->isVisible(), ());
LocalAndRemoteSizeT mapOnlySize = m_activeMaps.GetCountrySize(m_countryIdx, TMapOptions::EMapOnly);
LocalAndRemoteSizeT withRouting = m_activeMaps.GetCountrySize(m_countryIdx, TMapOptions::EMapWithCarRouting);
m_label->setText(m_displayMapName);
int sizeToDownload;
string units;
FormatMapSize(mapOnlySize.second, units, sizeToDownload);
m_primaryButton->setText(FormatStatusMessage<int, string>("country_status_download", &sizeToDownload, &units));
FormatMapSize(withRouting.second, units, sizeToDownload);
m_secondaryButton->setText(FormatStatusMessage<int, string>("country_status_download_routing", &sizeToDownload));
}
void CountryStatusDisplay::SetContentForProgress()
{
ASSERT(m_label->isVisible(), ());
int const percent = m_progressSize.first * 100 / m_progressSize.second;
m_label->setText(FormatStatusMessage<string, int>("country_status_downloading", &m_displayMapName, &percent));
}
void CountryStatusDisplay::SetContentForInQueue()
{
ASSERT(m_label->isVisible(), ());
m_label->setText(FormatStatusMessage<string, int>("country_status_added_to_queue", &m_displayMapName));
}
void CountryStatusDisplay::SetContentForError()
{
ASSERT(m_label->isVisible(), ());
ASSERT(m_primaryButton->isVisible(), ());
if (m_countryStatus == TStatus::EDownloadFailed)
m_label->setText(FormatStatusMessage<string, int>("country_status_download_failed", &m_displayMapName));
else
m_label->setText(FormatStatusMessage<int, int>("not_enough_free_space_on_sdcard"));
m_primaryButton->setText(m_controller->GetStringsBundle()->GetString("try_again"));
}
void CountryStatusDisplay::ComposeElementsForState()
{
ASSERT(isVisible(), ());
int visibleCount = 0;
auto visibleCheckFn = [&visibleCount](gui::Element const * e)
{
if (e->isVisible())
++visibleCount;
};
visibleCheckFn(m_label.get());
visibleCheckFn(m_primaryButton.get());
visibleCheckFn(m_secondaryButton.get());
ASSERT(visibleCount > 0, ());
m2::PointD const & pv = pivot();
if (visibleCount == 1)
m_label->setPivot(pv);
else if (visibleCount == 2)
{
size_t const labelHeight = m_label->GetBoundRect().SizeY();
size_t const buttonHeight = m_primaryButton->GetBoundRect().SizeY();
size_t const commonHeight = buttonHeight + labelHeight + 10 * visualScale();
m_label->setPivot(m2::PointD(pv.x, pv.y - commonHeight / 2 + labelHeight / 2));
m_primaryButton->setPivot(m2::PointD(pv.x, pv.y + commonHeight / 2 - buttonHeight / 2));
}
else
{
size_t const labelHeight = m_label->GetBoundRect().SizeY();
size_t const primButtonHeight = m_primaryButton->GetBoundRect().SizeY();
size_t const secButtonHeight = m_secondaryButton->GetBoundRect().SizeY();
size_t const emptySpace = 10 * visualScale();
double const offsetFromCenter = (primButtonHeight / 2 + emptySpace);
m_label->setPivot(m2::PointD(pv.x, pv.y - offsetFromCenter - labelHeight / 2));
m_primaryButton->setPivot(pv);
m_secondaryButton->setPivot(m2::PointD(pv.x, pv.y + offsetFromCenter + secButtonHeight / 2.0));
}
}
bool CountryStatusDisplay::OnTapAction(TTapActionFn const & action, const m2::PointD & pt)
{
bool result = false;
if (m_primaryButton->isVisible() && m_primaryButton->hitTest(pt))
result |= action(m_primaryButton, pt);
else if (m_secondaryButton->isVisible() && m_secondaryButton->hitTest(pt))
result |= action(m_secondaryButton, pt);
return result;
}
void CountryStatusDisplay::OnButtonClicked(gui::Element const * button)
{
ASSERT(m_countryIdx.IsValid(), ());
TMapOptions options = TMapOptions::EMapOnly;
if (button == m_secondaryButton.get())
options |= TMapOptions::ECarRouting;
DownloadCountry(static_cast<int>(options));
}
void CountryStatusDisplay::DownloadCountry(int options, bool checkCallback)
{
ASSERT(m_countryIdx.IsValid(), ());
if (checkCallback && m_downloadCallback)
m_downloadCallback(options);
else
{
if (IsStatusFailed())
{
m_progressSize = m_activeMaps.GetDownloadableCountrySize(m_countryIdx);
m_activeMaps.RetryDownloading(m_countryIdx);
}
else
{
TMapOptions mapOptions = static_cast<TMapOptions>(options);
m_progressSize = m_activeMaps.GetCountrySize(m_countryIdx, mapOptions);
m_activeMaps.DownloadMap(m_countryIdx, mapOptions);
}
}
}
void CountryStatusDisplay::Repaint() const
{
setIsDirtyLayout(true);
const_cast<CountryStatusDisplay *>(this)->invalidate();
}
bool CountryStatusDisplay::IsStatusFailed() const
{
return m_countryStatus == TStatus::EOutOfMemFailed || m_countryStatus == TStatus::EDownloadFailed;
}
void CountryStatusDisplay::Lock() const
{
#ifdef OMIM_OS_ANDROID
m_mutex.Lock();
#endif
}
void CountryStatusDisplay::Unlock() const
{
#ifdef OMIM_OS_ANDROID
m_mutex.Unlock();
#endif
}
<|endoftext|>
|
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "dbusmessagewriter.h"
#define DBUS_API_SUBJECT_TO_CHANGE
#include <dbus/dbus.h>
#include "textutils.h"
using namespace std;
DBusMessageWriter::DBusMessageWriter(DBusConnection* c, DBusMessage* msg)
:conn(c), error(0) {
reply = dbus_message_new_method_return(msg);
dbus_message_iter_init_append(reply, &it);
}
DBusMessageWriter::~DBusMessageWriter() {
DBusMessage* msg = (error) ?error :reply;
dbus_uint32_t serial = 0;
dbus_connection_send(conn, msg, &serial);
dbus_connection_flush(conn);
dbus_message_unref(reply);
if (error) {
dbus_message_unref(error);
}
}
void
DBusMessageWriter::setError(const std::string &e) {
error = dbus_message_new(DBUS_MESSAGE_TYPE_ERROR);
dbus_message_set_error_name(error, e.c_str());
}
DBusMessageWriter&
DBusMessageWriter::operator<<(bool b) {
dbus_message_iter_append_basic(&it, DBUS_TYPE_BOOLEAN, &b);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(int32_t i) {
dbus_message_iter_append_basic(&it, DBUS_TYPE_INT32, &i);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(int64_t i) {
dbus_message_iter_append_basic(&it, DBUS_TYPE_INT64, &i);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(double d) {
dbus_message_iter_append_basic(&it, DBUS_TYPE_DOUBLE, &d);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::string& s) {
const char* c = s.c_str();
dbus_message_iter_append_basic(&it, DBUS_TYPE_STRING, &c);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const set<string>& s) {
DBusMessageIter sub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
DBUS_TYPE_STRING_AS_STRING, &sub);
set<string>::const_iterator i;
for (i = s.begin(); i != s.end(); ++i) {
const char* c = i->c_str();
dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &c);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::map<std::string, std::string>& m) {
DBusMessageIter sub, ssub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "{ss}", &sub);
map<string, string>::const_iterator i;
for (i = m.begin(); i != m.end(); ++i) {
dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, 0, &ssub);
const char* c = i->first.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
c = i->second.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
dbus_message_iter_close_container(&sub, &ssub);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::string>& s) {
DBusMessageIter sub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
DBUS_TYPE_STRING_AS_STRING, &sub);
vector<string>::const_iterator i;
for (i = s.begin(); i != s.end(); ++i) {
const char* c = i->c_str();
dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &c);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
/* yes this is ugly, i have to change the interface */
DBusMessageWriter&
DBusMessageWriter::operator<<(const ClientInterface::Hits& s) {
DBusMessageIter sub;
DBusMessageIter ssub;
DBusMessageIter sssub;
DBusMessageIter ssssub;
DBusMessageIter sssssub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
"(sdsssxxa{sas})", &sub);
vector<jstreams::IndexedDocument>::const_iterator i;
for (i=s.hits.begin(); i!=s.hits.end(); ++i) {
dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
const char* c = i->uri.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
double d = i->score;
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_DOUBLE, &d);
// quick bug fix on what is probably a clucene bug
// the fragments as stored are sometimes not properly recoded back
// from usc2 to utf8 which causes dbus to close the connection,
// whereupon the strigidaemon quits
if (jstreams::checkUtf8(i->fragment.c_str(), i->fragment.size())) {
c = i->fragment.c_str();
} else {
c = "";
}
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
c = i->mimetype.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
c = i->sha1.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
int64_t n = i->size;
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT64, &n);
n = i->mtime;
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT64, &n);
dbus_message_iter_open_container(&ssub, DBUS_TYPE_ARRAY, "{sas})",
&sssub);
multimap<string, string>::const_iterator j;
for (j = i->properties.begin(); j != i->properties.end(); ++j) {
dbus_message_iter_open_container(&sssub, DBUS_TYPE_DICT_ENTRY, 0,
&ssssub);
const char* c = j->first.c_str();
dbus_message_iter_append_basic(&ssssub, DBUS_TYPE_STRING, &c);
dbus_message_iter_open_container(&ssssub, DBUS_TYPE_ARRAY, "s",
&sssssub);
c = j->second.c_str();
dbus_message_iter_append_basic(&sssssub, DBUS_TYPE_STRING, &c);
dbus_message_iter_close_container(&ssssub, &sssssub);
dbus_message_iter_close_container(&sssub, &ssssub);
}
dbus_message_iter_close_container(&ssub, &sssub);
dbus_message_iter_close_container(&sub, &ssub);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
/** map multimap<int,string> to 'a(is)' **/
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::multimap<int, std::string>& m) {
DBusMessageIter sub, ssub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(is)", &sub);
multimap<int,string>::const_iterator i;
for (i = m.begin(); i != m.end(); ++i) {
dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
int32_t n = i->first;
const char* s = i->second.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT32, &n);
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
dbus_message_iter_close_container(&sub, &ssub);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::pair<bool, std::string> >& s) {
DBusMessageIter sub, ssub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(bs)", &sub);
vector<pair<bool,string> >::const_iterator i;
for (i = s.begin(); i != s.end(); ++i) {
dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
dbus_bool_t n = i->first;
const char* s = i->second.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_BOOLEAN, &n);
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
dbus_message_iter_close_container(&sub, &ssub);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::pair<std::string, uint32_t> >& s) {
DBusMessageIter sub, ssub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(bs)", &sub);
vector<pair<string,uint32_t> >::const_iterator i;
for (i = s.begin(); i != s.end(); ++i) {
dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
const char* s = i->first.c_str();
dbus_uint32_t n = i->second;
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_UINT32, &n);
dbus_message_iter_close_container(&sub, &ssub);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
<commit_msg>Fix dbus message signature.<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "dbusmessagewriter.h"
#define DBUS_API_SUBJECT_TO_CHANGE
#include <dbus/dbus.h>
#include "textutils.h"
using namespace std;
DBusMessageWriter::DBusMessageWriter(DBusConnection* c, DBusMessage* msg)
:conn(c), error(0) {
reply = dbus_message_new_method_return(msg);
dbus_message_iter_init_append(reply, &it);
}
DBusMessageWriter::~DBusMessageWriter() {
DBusMessage* msg = (error) ?error :reply;
dbus_uint32_t serial = 0;
dbus_connection_send(conn, msg, &serial);
dbus_connection_flush(conn);
dbus_message_unref(reply);
if (error) {
dbus_message_unref(error);
}
}
void
DBusMessageWriter::setError(const std::string &e) {
error = dbus_message_new(DBUS_MESSAGE_TYPE_ERROR);
dbus_message_set_error_name(error, e.c_str());
}
DBusMessageWriter&
DBusMessageWriter::operator<<(bool b) {
dbus_message_iter_append_basic(&it, DBUS_TYPE_BOOLEAN, &b);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(int32_t i) {
dbus_message_iter_append_basic(&it, DBUS_TYPE_INT32, &i);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(int64_t i) {
dbus_message_iter_append_basic(&it, DBUS_TYPE_INT64, &i);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(double d) {
dbus_message_iter_append_basic(&it, DBUS_TYPE_DOUBLE, &d);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::string& s) {
const char* c = s.c_str();
dbus_message_iter_append_basic(&it, DBUS_TYPE_STRING, &c);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const set<string>& s) {
DBusMessageIter sub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
DBUS_TYPE_STRING_AS_STRING, &sub);
set<string>::const_iterator i;
for (i = s.begin(); i != s.end(); ++i) {
const char* c = i->c_str();
dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &c);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::map<std::string, std::string>& m) {
DBusMessageIter sub, ssub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "{ss}", &sub);
map<string, string>::const_iterator i;
for (i = m.begin(); i != m.end(); ++i) {
dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, 0, &ssub);
const char* c = i->first.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
c = i->second.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
dbus_message_iter_close_container(&sub, &ssub);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::string>& s) {
DBusMessageIter sub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
DBUS_TYPE_STRING_AS_STRING, &sub);
vector<string>::const_iterator i;
for (i = s.begin(); i != s.end(); ++i) {
const char* c = i->c_str();
dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &c);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
/* yes this is ugly, i have to change the interface */
DBusMessageWriter&
DBusMessageWriter::operator<<(const ClientInterface::Hits& s) {
DBusMessageIter sub;
DBusMessageIter ssub;
DBusMessageIter sssub;
DBusMessageIter ssssub;
DBusMessageIter sssssub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
"(sdsssxxa{sas})", &sub);
vector<jstreams::IndexedDocument>::const_iterator i;
for (i=s.hits.begin(); i!=s.hits.end(); ++i) {
dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
const char* c = i->uri.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
double d = i->score;
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_DOUBLE, &d);
// quick bug fix on what is probably a clucene bug
// the fragments as stored are sometimes not properly recoded back
// from usc2 to utf8 which causes dbus to close the connection,
// whereupon the strigidaemon quits
if (jstreams::checkUtf8(i->fragment.c_str(), i->fragment.size())) {
c = i->fragment.c_str();
} else {
c = "";
}
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
c = i->mimetype.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
c = i->sha1.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
int64_t n = i->size;
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT64, &n);
n = i->mtime;
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT64, &n);
dbus_message_iter_open_container(&ssub, DBUS_TYPE_ARRAY, "{sas})",
&sssub);
multimap<string, string>::const_iterator j;
for (j = i->properties.begin(); j != i->properties.end(); ++j) {
dbus_message_iter_open_container(&sssub, DBUS_TYPE_DICT_ENTRY, 0,
&ssssub);
const char* c = j->first.c_str();
dbus_message_iter_append_basic(&ssssub, DBUS_TYPE_STRING, &c);
dbus_message_iter_open_container(&ssssub, DBUS_TYPE_ARRAY, "s",
&sssssub);
c = j->second.c_str();
dbus_message_iter_append_basic(&sssssub, DBUS_TYPE_STRING, &c);
dbus_message_iter_close_container(&ssssub, &sssssub);
dbus_message_iter_close_container(&sssub, &ssssub);
}
dbus_message_iter_close_container(&ssub, &sssub);
dbus_message_iter_close_container(&sub, &ssub);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
/** map multimap<int,string> to 'a(is)' **/
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::multimap<int, std::string>& m) {
DBusMessageIter sub, ssub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(is)", &sub);
multimap<int,string>::const_iterator i;
for (i = m.begin(); i != m.end(); ++i) {
dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
int32_t n = i->first;
const char* s = i->second.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT32, &n);
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
dbus_message_iter_close_container(&sub, &ssub);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::pair<bool, std::string> >& s) {
DBusMessageIter sub, ssub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(bs)", &sub);
vector<pair<bool,string> >::const_iterator i;
for (i = s.begin(); i != s.end(); ++i) {
dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
dbus_bool_t n = i->first;
const char* s = i->second.c_str();
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_BOOLEAN, &n);
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
dbus_message_iter_close_container(&sub, &ssub);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::pair<std::string, uint32_t> >& s) {
DBusMessageIter sub, ssub;
dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(su)", &sub);
vector<pair<string,uint32_t> >::const_iterator i;
for (i = s.begin(); i != s.end(); ++i) {
dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
const char* s = i->first.c_str();
dbus_uint32_t n = i->second;
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
dbus_message_iter_append_basic(&ssub, DBUS_TYPE_UINT32, &n);
dbus_message_iter_close_container(&sub, &ssub);
}
dbus_message_iter_close_container(&it, &sub);
return *this;
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <set>
#include "BinaryRegion.hpp"
int main(int argc, char** argv) {
BinaryRegion binaryRegion(
0x00400000, /* Base address */
0, /* Entry point offset */
"\x50\x8B\xD9\xEB\x01\xDE\x83\xF2\x43",
9
);
return EXIT_SUCCESS;
}<commit_msg>furthering region split test<commit_after>#include <cstdlib>
#include <set>
#include <stack>
#include <libdasm.h>
#include <iostream>
#include "BinaryBlock.hpp"
#include "BinaryRegion.hpp"
bool is_address_within_blocks(const int64_t& address, std::set<BinaryBlock*>& binaryBlocks) {
std::set<BinaryBlock*>::const_iterator it = binaryBlocks.begin();
bool match = false;
while(!match && it != binaryBlocks.end()) {
if(address >= (*it)->address() && address <= (*it)->address() + (*it)->length()) {
match = !match;
}
++it;
}
}
void analyze_binary_region(const BinaryRegion& binaryRegion, std::set<BinaryBlock*>& binaryBlocks);
int main(int argc, char** argv) {
BinaryRegion binaryRegion(
0x00400000, /* Base address */
0, /* Entry point offset */
"\x50\x8B\xD9\xEB\x01\xDE\x83\xF2\x43",
9
);
return EXIT_SUCCESS;
}
void analyze_binary_region(const BinaryRegion& binaryRegion, std::set<BinaryBlock*>& binaryBlocks) {
int64_t current_memory_address = binaryRegion.baseAddress() + binaryRegion.entryPointOffset();
// The current_memory_address should not be into any pre-existing binary block
if(is_address_within_blocks(current_memory_address, binaryBlocks)) {
return;
}
}<|endoftext|>
|
<commit_before>/*
This file is part of KAddressBook.
Copyright (c) 2002 Mike Pilone <mpilone@slac.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., 675 Mass Ave, Cambridge, MA 02139, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qapplication.h>
#include <qclipboard.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kprotocolinfo.h>
#include <kxmlguiclient.h>
#include <kxmlguifactory.h>
#include "actionmanager.h"
#include "kaddressbook.h"
#include "viewmanager.h"
#include "undo.h"
ActionManager::ActionManager(KXMLGUIClient *client, KAddressBook *widget,
bool readWrite, QObject *parent)
: QObject(parent)
{
mGUIClient = client;
mACollection = mGUIClient->actionCollection();
mWidget = widget;
connect( mWidget, SIGNAL( addresseeSelected( bool ) ),
SLOT( addresseeSelected( bool ) ) );
connect( mWidget, SIGNAL( modified( bool ) ),
SLOT( modified( bool ) ) );
mViewManager = mWidget->viewManager();
connect( mViewManager, SIGNAL( viewConfigChanged(const QString &) ),
SLOT( viewConfigChanged(const QString &) ) );
connect( QApplication::clipboard(), SIGNAL( dataChanged() ),
SLOT( clipboardDataChanged() ) );
mReadWrite = readWrite;
initReadOnlyActions();
if (mReadWrite)
initReadWriteActions();
// Read our own config
KConfig *config = kapp->config();
config->setGroup("Views");
mActiveViewName = config->readEntry("Active");
config->setGroup("MainWindow");
mActionJumpBar->setChecked(config->readBoolEntry("JumpBar", false));
mActionFeatures->setCurrentItem(config->readNumEntry("Features", 0));
mActionDetails->setChecked(config->readBoolEntry("Details", true));
// Set the defaults
addresseeSelected(false);
modified(false);
quickToolsAction();
mActionViewList.setAutoDelete(true);
// Connect to the signals from the undo/redo stacks so we can update the
// edit menu
connect(UndoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu()));
connect(RedoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu()));
}
ActionManager::~ActionManager()
{
// Write our own config
KConfig *config = kapp->config();
config->setGroup("Views");
config->writeEntry("Active", mActiveViewName);
config->setGroup("MainWindow");
config->writeEntry("JumpBar", mActionJumpBar->isChecked());
config->writeEntry("Features", mActionFeatures->currentItem());
config->writeEntry("Details", mActionDetails->isChecked());
config->sync();
}
void ActionManager::setReadWrite(bool rw)
{
if (rw == mReadWrite)
return;
mReadWrite = rw;
if (mReadWrite)
initReadWriteActions();
else
destroyReadWriteActions();
}
void ActionManager::clipboardDataChanged()
{
if (mReadWrite)
mActionPaste->setEnabled( !QApplication::clipboard()->text().isEmpty() );
}
void ActionManager::initReadOnlyActions()
{
// File menu
mActionSave = new KAction(i18n("&Save"), "filesave", CTRL+Key_S, mWidget,
SLOT(save()), mACollection,"file_sync");
new KAction(i18n("&New Contact..."), "filenew", CTRL+Key_N, mWidget,
SLOT(newAddressee()),mACollection,"file_new_contact");
mActionMail = KStdAction::mail(mViewManager, SLOT(sendMail()),
mACollection);
mActionEditAddressee = new KAction(i18n("&Edit Contact..."), "edit", 0,
mWidget, SLOT(editAddressee()),
mACollection, "file_properties");
KStdAction::print(mWidget, SLOT(print()), mACollection);
new KAction(i18n("Import &KDE 2 Address Book..."), 0, mWidget,
SLOT(importKDE2()), mACollection, "file_import_kde2");
new KAction(i18n("Import vCard..."), 0, mWidget, SLOT(importVCardSimple()),
mACollection, "file_import_vcard");
new KAction(i18n("&Import List..."), 0, mWidget, SLOT(importCSV()),
mACollection, "file_import_csv");
new KAction(i18n("&Export List..."), 0, mWidget, SLOT(exportCSV()),
mACollection, "file_export_csv");
new KAction(i18n("&Export vCard 3.0..."), 0, mWidget, SLOT(exportVCard30()),
mACollection, "file_export_vcard30");
// Edit menu
mActionCopy = KStdAction::copy(mViewManager, SLOT(copy()),
mACollection);
KStdAction::selectAll(mViewManager, SLOT(setSelected()), mACollection);
mActionDelete = new KAction(i18n("&Delete Contact"), "editdelete",
Key_Delete, mViewManager,
SLOT(deleteAddressee()), mACollection,
"edit_delete");
mActionUndo = KStdAction::undo(mWidget, SLOT(undo()), mACollection);
mActionUndo->setEnabled(false);
mActionRedo = KStdAction::redo(mWidget, SLOT(redo()), mACollection);
mActionRedo->setEnabled( false );
// View menu
new KAction(i18n("Modify View..."), "configure", 0, mViewManager,
SLOT(modifyView()), mACollection,
"view_modify");
new KAction(i18n("Add View..."), "window_new", 0, mViewManager,
SLOT(addView()), mACollection,
"view_add");
mActionDeleteView = new KAction(i18n("Delete View"), "view_remove", 0,
mViewManager,
SLOT(deleteView()), mACollection,
"view_delete");
new KAction(i18n("Refresh View"), "reload", 0, mViewManager,
SLOT(refresh()), mACollection,
"view_refresh");
// Only enable LDAP lookup if we can handle the protocol
if( KProtocolInfo::isKnownProtocol( KURL("ldap://localhost") )) {
// LDAP button on toolbar
new KAction(i18n("&Lookup addresses in directory"),
"ldap_lookup", 0, mWidget, SLOT(slotOpenLDAPDialog()),
mACollection,"ldap_lookup");
}
// Settings menu
mActionFeatures = new KSelectAction( i18n("Show Features Bar"),
0, mACollection,
"options_show_features" );
connect( mActionFeatures, SIGNAL( activated( int ) ),
mViewManager, SLOT( showFeatures( int ) ) );
QStringList features;
features << i18n("None") << i18n("Contact Editor")
<< i18n("Distribution Lists");
mActionFeatures->setItems( features );
mActionJumpBar = new KToggleAction(i18n("Show Jump Bar"), "next", 0,
this, SLOT(quickToolsAction()),
mACollection,
"options_show_jump_bar");
mActionDetails = new KToggleAction(i18n("Show Details"), 0,
0, this, SLOT(quickToolsAction()),
mACollection,
"options_show_details");
(void) new KAction(i18n("Edit &Filters..."), "filter",
0, mWidget, SLOT(configureFilters()),
mACollection, "options_edit_filters");
mActionSelectFilter = new KSelectAction(i18n("Select Filter"), 0,
0,
this, SLOT(slotFilterActivated(int)),
mACollection, "select_filter");
#if KDE_VERSION >= 309
mActionSelectFilter->setMenuAccelsEnabled( false );
#endif
connect(mActionSelectFilter, SIGNAL(activated(int)),
SLOT(slotFilterActivated(int)));
connect(this, SIGNAL(filterActivated(int)),
mViewManager, SLOT(filterActivated(int)));
connect(mViewManager, SIGNAL(setFilterNames(const QStringList&)),
SLOT(setFilterNames(const QStringList&)));
connect(mViewManager, SIGNAL(setCurrentFilterName(const QString&)),
SLOT(setCurrentFilterName(const QString&)));
connect(mViewManager, SIGNAL(setCurrentFilter(int)),
SLOT(setCurrentFilter(int)));
}
void ActionManager::initReadWriteActions()
{
// Edit menu
mActionCut = KStdAction::cut(mViewManager, SLOT(cut()), mACollection);
mActionPaste = KStdAction::paste(mViewManager, SLOT(paste()),
mACollection);
clipboardDataChanged();
}
void ActionManager::destroyReadWriteActions()
{
delete mActionCut;
delete mActionPaste;
}
void ActionManager::updateEditMenu()
{
UndoStack *undo = UndoStack::instance();
RedoStack *redo = RedoStack::instance();
if (undo->isEmpty())
mActionUndo->setText( i18n( "Undo" ) );
else
mActionUndo->setText( i18n( "Undo %1" ).arg(undo->top()->name()) );
mActionUndo->setEnabled( !undo->isEmpty() );
if (!redo->top())
mActionRedo->setText( i18n( "Redo" ) );
else
mActionRedo->setText( i18n( "Redo %1" ).arg(redo->top()->name()) );
mActionRedo->setEnabled( !redo->isEmpty() );
}
void ActionManager::addresseeSelected(bool selected)
{
if (mReadWrite)
{
mActionCut->setEnabled(selected);
}
mActionCopy->setEnabled(selected);
mActionDelete->setEnabled(selected);
mActionEditAddressee->setEnabled(selected);
mActionMail->setEnabled(selected);
}
void ActionManager::modified(bool mod)
{
mModified = mod;
mActionSave->setEnabled(mod);
}
void ActionManager::initActionViewList()
{
// Create the view actions, and set the active view
// Find the last active view
QStringList viewNameList = mViewManager->viewNames();
KToggleAction *viewAction = 0;
// Just incast there is no active view!
if (mActiveViewName.isEmpty() ||
(viewNameList.contains(mActiveViewName) == 0))
mActiveViewName = *(viewNameList).at(0);
// unplug the current ones
mGUIClient->factory()->unplugActionList(mGUIClient, "view_loadedviews");
// delete the current ones
mActionViewList.clear();
mActiveActionView = 0L;
// Now find the active one, check the menu item, and raise it to the top
QStringList::Iterator iter;
QString viewName;
for (iter = viewNameList.begin(); iter != viewNameList.end(); ++iter)
{
viewName = *iter;
viewAction = new KToggleAction(viewName, QString::null, this,
SLOT(selectViewAction()), mACollection,
viewName.latin1());
if (mActiveViewName == viewName)
{
mViewManager->setActiveView(viewName);
viewAction->setChecked(true);
mActiveActionView = viewAction;
}
mActionViewList.append(viewAction);
}
// Now append all the actions to the menu.
mGUIClient->factory()->plugActionList(mGUIClient, "view_loadedviews",
mActionViewList);
}
void ActionManager::viewConfigChanged(const QString &newActive)
{
if (!newActive.isEmpty())
{
mActiveViewName = newActive;
}
// we need to rebuild the actions
initActionViewList();
// Only enable delete if there is more than one view
mActionDeleteView->setEnabled(mViewManager->viewNames().size() > 1);
}
void ActionManager::selectViewAction()
{
// See if we can find the selected action
KToggleAction *action = 0;
QString activatedName = sender()->name();
QPtrListIterator<KAction> iter(mActionViewList);
for (iter.toFirst(); iter.current(); ++iter)
{
action = dynamic_cast<KToggleAction*>(*iter);
if (action->name() != activatedName)
action->setChecked(false);
else
{
mActiveActionView = action;
mActiveActionView->setChecked(true);
mActiveViewName = mActiveActionView->name();
// Last, tell the main widget to set the view.
mViewManager->setActiveView(mActiveViewName);
}
}
}
void ActionManager::quickToolsAction()
{
mViewManager->setJumpButtonBarVisible(mActionJumpBar->isChecked());
mViewManager->showFeatures(mActionFeatures->currentItem());
mViewManager->setDetailsVisible(mActionDetails->isChecked());
}
void ActionManager::setFilterNames(const QStringList& list)
{
QString current = mActionSelectFilter->currentText();
QStringList items;
items.append(i18n("None"));
items+=list;
mActionSelectFilter->setItems(items);
setCurrentFilterName( current );
}
void ActionManager::slotFilterActivated(int index)
{
emit filterActivated(index-1);
}
void ActionManager::setCurrentFilterName(const QString& name)
{
QStringList items=mActionSelectFilter->items();
int index=items.findIndex(name);
if( index != -1 )
setCurrentFilter(index);
}
void ActionManager::setCurrentFilter(int index)
{
mActionSelectFilter->setCurrentItem(index);
emit filterActivated(index-1);
}
bool ActionManager::isModified()
{
return mModified;
}
#include "actionmanager.moc"
<commit_msg>Fix signal -> slot<commit_after>/*
This file is part of KAddressBook.
Copyright (c) 2002 Mike Pilone <mpilone@slac.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., 675 Mass Ave, Cambridge, MA 02139, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qapplication.h>
#include <qclipboard.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kprotocolinfo.h>
#include <kxmlguiclient.h>
#include <kxmlguifactory.h>
#include "actionmanager.h"
#include "kaddressbook.h"
#include "viewmanager.h"
#include "undo.h"
ActionManager::ActionManager(KXMLGUIClient *client, KAddressBook *widget,
bool readWrite, QObject *parent)
: QObject(parent)
{
mGUIClient = client;
mACollection = mGUIClient->actionCollection();
mWidget = widget;
connect( mWidget, SIGNAL( addresseeSelected( bool ) ),
SLOT( addresseeSelected( bool ) ) );
connect( mWidget, SIGNAL( modified( bool ) ),
SLOT( modified( bool ) ) );
mViewManager = mWidget->viewManager();
connect( mViewManager, SIGNAL( viewConfigChanged(const QString &) ),
SLOT( viewConfigChanged(const QString &) ) );
connect( QApplication::clipboard(), SIGNAL( dataChanged() ),
SLOT( clipboardDataChanged() ) );
mReadWrite = readWrite;
initReadOnlyActions();
if (mReadWrite)
initReadWriteActions();
// Read our own config
KConfig *config = kapp->config();
config->setGroup("Views");
mActiveViewName = config->readEntry("Active");
config->setGroup("MainWindow");
mActionJumpBar->setChecked(config->readBoolEntry("JumpBar", false));
mActionFeatures->setCurrentItem(config->readNumEntry("Features", 0));
mActionDetails->setChecked(config->readBoolEntry("Details", true));
// Set the defaults
addresseeSelected(false);
modified(false);
quickToolsAction();
mActionViewList.setAutoDelete(true);
// Connect to the signals from the undo/redo stacks so we can update the
// edit menu
connect(UndoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu()));
connect(RedoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu()));
}
ActionManager::~ActionManager()
{
// Write our own config
KConfig *config = kapp->config();
config->setGroup("Views");
config->writeEntry("Active", mActiveViewName);
config->setGroup("MainWindow");
config->writeEntry("JumpBar", mActionJumpBar->isChecked());
config->writeEntry("Features", mActionFeatures->currentItem());
config->writeEntry("Details", mActionDetails->isChecked());
config->sync();
}
void ActionManager::setReadWrite(bool rw)
{
if (rw == mReadWrite)
return;
mReadWrite = rw;
if (mReadWrite)
initReadWriteActions();
else
destroyReadWriteActions();
}
void ActionManager::clipboardDataChanged()
{
if (mReadWrite)
mActionPaste->setEnabled( !QApplication::clipboard()->text().isEmpty() );
}
void ActionManager::initReadOnlyActions()
{
// File menu
mActionSave = new KAction(i18n("&Save"), "filesave", CTRL+Key_S, mWidget,
SLOT(save()), mACollection,"file_sync");
new KAction(i18n("&New Contact..."), "filenew", CTRL+Key_N, mWidget,
SLOT(newAddressee()),mACollection,"file_new_contact");
mActionMail = KStdAction::mail(mViewManager, SLOT(sendMail()),
mACollection);
mActionEditAddressee = new KAction(i18n("&Edit Contact..."), "edit", 0,
mWidget, SLOT(editAddressee()),
mACollection, "file_properties");
KStdAction::print(mWidget, SLOT(print()), mACollection);
new KAction(i18n("Import &KDE 2 Address Book..."), 0, mWidget,
SLOT(importKDE2()), mACollection, "file_import_kde2");
new KAction(i18n("Import vCard..."), 0, mWidget, SLOT(importVCardSimple()),
mACollection, "file_import_vcard");
new KAction(i18n("&Import List..."), 0, mWidget, SLOT(importCSV()),
mACollection, "file_import_csv");
new KAction(i18n("&Export List..."), 0, mWidget, SLOT(exportCSV()),
mACollection, "file_export_csv");
new KAction(i18n("&Export vCard 3.0..."), 0, mWidget, SLOT(exportVCard30()),
mACollection, "file_export_vcard30");
// Edit menu
mActionCopy = KStdAction::copy(mViewManager, SLOT(copy()),
mACollection);
KStdAction::selectAll(mViewManager, SLOT(setSelected()), mACollection);
mActionDelete = new KAction(i18n("&Delete Contact"), "editdelete",
Key_Delete, mViewManager,
SLOT(deleteAddressee()), mACollection,
"edit_delete");
mActionUndo = KStdAction::undo(mWidget, SLOT(undo()), mACollection);
mActionUndo->setEnabled(false);
mActionRedo = KStdAction::redo(mWidget, SLOT(redo()), mACollection);
mActionRedo->setEnabled( false );
// View menu
new KAction(i18n("Modify View..."), "configure", 0, mViewManager,
SLOT(modifyView()), mACollection,
"view_modify");
new KAction(i18n("Add View..."), "window_new", 0, mViewManager,
SLOT(addView()), mACollection,
"view_add");
mActionDeleteView = new KAction(i18n("Delete View"), "view_remove", 0,
mViewManager,
SLOT(deleteView()), mACollection,
"view_delete");
new KAction(i18n("Refresh View"), "reload", 0, mViewManager,
SLOT(refresh()), mACollection,
"view_refresh");
// Only enable LDAP lookup if we can handle the protocol
if( KProtocolInfo::isKnownProtocol( KURL("ldap://localhost") )) {
// LDAP button on toolbar
new KAction(i18n("&Lookup addresses in directory"),
"ldap_lookup", 0, mWidget, SLOT(slotOpenLDAPDialog()),
mACollection,"ldap_lookup");
}
// Settings menu
mActionFeatures = new KSelectAction( i18n("Show Features Bar"),
0, mACollection,
"options_show_features" );
connect( mActionFeatures, SIGNAL( activated( int ) ),
mViewManager, SLOT( showFeatures( int ) ) );
QStringList features;
features << i18n("None") << i18n("Contact Editor")
<< i18n("Distribution Lists");
mActionFeatures->setItems( features );
mActionJumpBar = new KToggleAction(i18n("Show Jump Bar"), "next", 0,
this, SLOT(quickToolsAction()),
mACollection,
"options_show_jump_bar");
mActionDetails = new KToggleAction(i18n("Show Details"), 0,
0, this, SLOT(quickToolsAction()),
mACollection,
"options_show_details");
(void) new KAction(i18n("Edit &Filters..."), "filter",
0, mWidget, SLOT(configureFilters()),
mACollection, "options_edit_filters");
mActionSelectFilter = new KSelectAction(i18n("Select Filter"), 0,
mACollection, "select_filter");
#if KDE_VERSION >= 309
mActionSelectFilter->setMenuAccelsEnabled( false );
#endif
connect(mActionSelectFilter, SIGNAL(activated(int)),
SLOT(slotFilterActivated(int)));
connect(this, SIGNAL(filterActivated(int)),
mViewManager, SLOT(filterActivated(int)));
connect(mViewManager, SIGNAL(setFilterNames(const QStringList&)),
SLOT(setFilterNames(const QStringList&)));
connect(mViewManager, SIGNAL(setCurrentFilterName(const QString&)),
SLOT(setCurrentFilterName(const QString&)));
connect(mViewManager, SIGNAL(setCurrentFilter(int)),
SLOT(setCurrentFilter(int)));
}
void ActionManager::initReadWriteActions()
{
// Edit menu
mActionCut = KStdAction::cut(mViewManager, SLOT(cut()), mACollection);
mActionPaste = KStdAction::paste(mViewManager, SLOT(paste()),
mACollection);
clipboardDataChanged();
}
void ActionManager::destroyReadWriteActions()
{
delete mActionCut;
delete mActionPaste;
}
void ActionManager::updateEditMenu()
{
UndoStack *undo = UndoStack::instance();
RedoStack *redo = RedoStack::instance();
if (undo->isEmpty())
mActionUndo->setText( i18n( "Undo" ) );
else
mActionUndo->setText( i18n( "Undo %1" ).arg(undo->top()->name()) );
mActionUndo->setEnabled( !undo->isEmpty() );
if (!redo->top())
mActionRedo->setText( i18n( "Redo" ) );
else
mActionRedo->setText( i18n( "Redo %1" ).arg(redo->top()->name()) );
mActionRedo->setEnabled( !redo->isEmpty() );
}
void ActionManager::addresseeSelected(bool selected)
{
if (mReadWrite)
{
mActionCut->setEnabled(selected);
}
mActionCopy->setEnabled(selected);
mActionDelete->setEnabled(selected);
mActionEditAddressee->setEnabled(selected);
mActionMail->setEnabled(selected);
}
void ActionManager::modified(bool mod)
{
mModified = mod;
mActionSave->setEnabled(mod);
}
void ActionManager::initActionViewList()
{
// Create the view actions, and set the active view
// Find the last active view
QStringList viewNameList = mViewManager->viewNames();
KToggleAction *viewAction = 0;
// Just incast there is no active view!
if (mActiveViewName.isEmpty() ||
(viewNameList.contains(mActiveViewName) == 0))
mActiveViewName = *(viewNameList).at(0);
// unplug the current ones
mGUIClient->factory()->unplugActionList(mGUIClient, "view_loadedviews");
// delete the current ones
mActionViewList.clear();
mActiveActionView = 0L;
// Now find the active one, check the menu item, and raise it to the top
QStringList::Iterator iter;
QString viewName;
for (iter = viewNameList.begin(); iter != viewNameList.end(); ++iter)
{
viewName = *iter;
viewAction = new KToggleAction(viewName, QString::null, this,
SLOT(selectViewAction()), mACollection,
viewName.latin1());
if (mActiveViewName == viewName)
{
mViewManager->setActiveView(viewName);
viewAction->setChecked(true);
mActiveActionView = viewAction;
}
mActionViewList.append(viewAction);
}
// Now append all the actions to the menu.
mGUIClient->factory()->plugActionList(mGUIClient, "view_loadedviews",
mActionViewList);
}
void ActionManager::viewConfigChanged(const QString &newActive)
{
if (!newActive.isEmpty())
{
mActiveViewName = newActive;
}
// we need to rebuild the actions
initActionViewList();
// Only enable delete if there is more than one view
mActionDeleteView->setEnabled(mViewManager->viewNames().size() > 1);
}
void ActionManager::selectViewAction()
{
// See if we can find the selected action
KToggleAction *action = 0;
QString activatedName = sender()->name();
QPtrListIterator<KAction> iter(mActionViewList);
for (iter.toFirst(); iter.current(); ++iter)
{
action = dynamic_cast<KToggleAction*>(*iter);
if (action->name() != activatedName)
action->setChecked(false);
else
{
mActiveActionView = action;
mActiveActionView->setChecked(true);
mActiveViewName = mActiveActionView->name();
// Last, tell the main widget to set the view.
mViewManager->setActiveView(mActiveViewName);
}
}
}
void ActionManager::quickToolsAction()
{
mViewManager->setJumpButtonBarVisible(mActionJumpBar->isChecked());
mViewManager->showFeatures(mActionFeatures->currentItem());
mViewManager->setDetailsVisible(mActionDetails->isChecked());
}
void ActionManager::setFilterNames(const QStringList& list)
{
QString current = mActionSelectFilter->currentText();
QStringList items;
items.append(i18n("None"));
items+=list;
mActionSelectFilter->setItems(items);
setCurrentFilterName( current );
}
void ActionManager::slotFilterActivated(int index)
{
emit filterActivated(index-1);
}
void ActionManager::setCurrentFilterName(const QString& name)
{
QStringList items=mActionSelectFilter->items();
int index=items.findIndex(name);
if( index != -1 )
setCurrentFilter(index);
}
void ActionManager::setCurrentFilter(int index)
{
mActionSelectFilter->setCurrentItem(index);
emit filterActivated(index-1);
}
bool ActionManager::isModified()
{
return mModified;
}
#include "actionmanager.moc"
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.