text
stringlengths 54
60.6k
|
|---|
<commit_before>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include <stdlib.h>
#include "net.h"
#include "logging.h"
#include "thread.h"
#if defined(_WINDOWS_) || defined(_MSC_VER)
# include "select_poll.h"
#elif defined(__linux__)
# include "epoll_poll.h"
#endif
#include "worker.h"
Worker::Worker(void)
: running_(false)
, rthread_(NULL)
, wthread_(NULL)
, poll_(NULL)
{
}
Worker::~Worker(void)
{
Stop();
}
bool
Worker::Start(void)
{
if (NULL == poll_)
return false;
rthread_ = new Thread(&Worker::ReadRoutine, this);
if (NULL == rthread_) {
LOG_FAIL("new Thread failed\n");
return false;
}
wthread_ = new Thread(&Worker::WriteRoutine, this);
if (NULL == wthread_) {
LOG_FAIL("new Thread failed\n");
return false;
}
running_ = true;
rthread_->Start();
wthread_->Start();
return true;
}
void
Worker::Stop(void)
{
running_ = false;
if (NULL != rthread_) {
rthread_->Join();
delete rthread_;
rthread_ = NULL;
}
if (NULL != wthread_) {
wthread_->Join();
delete wthread_;
wthread_ = NULL;
}
}
void
Worker::ReadRoutine(void* argument)
{
Worker* self = static_cast<Worker*>(argument);
if (NULL == self)
return;
while (self->running_) {
if (!self->poll_->Polling(kEventTypeRead)) {
Sleep(1);
continue;
}
}
}
void
Worker::WriteRoutine(void* argument)
{
Worker* self = static_cast<Worker*>(argument);
if (NULL == self)
return;
while (self->running_) {
if (!self->poll_->Polling(kEventTypeWrite)) {
Sleep(1);
continue;
}
}
}
<commit_msg>improved worker module<commit_after>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include <stdlib.h>
#include "net.h"
#include "logging.h"
#include "os_tool.h"
#include "thread.h"
#if defined(_WINDOWS_) || defined(_MSC_VER)
# include "select_poll.h"
#elif defined(__linux__)
# include "epoll_poll.h"
#endif
#include "worker.h"
Worker::Worker(void)
: running_(false)
, rthread_(NULL)
, wthread_(NULL)
, poll_(NULL)
{
}
Worker::~Worker(void)
{
Stop();
}
bool
Worker::Start(void)
{
if (NULL == poll_)
return false;
rthread_ = new Thread(&Worker::ReadRoutine, this);
if (NULL == rthread_) {
LOG_FAIL("new Thread failed\n");
return false;
}
wthread_ = new Thread(&Worker::WriteRoutine, this);
if (NULL == wthread_) {
LOG_FAIL("new Thread failed\n");
return false;
}
running_ = true;
rthread_->Start();
wthread_->Start();
return true;
}
void
Worker::Stop(void)
{
running_ = false;
if (NULL != rthread_) {
rthread_->Join();
delete rthread_;
rthread_ = NULL;
}
if (NULL != wthread_) {
wthread_->Join();
delete wthread_;
wthread_ = NULL;
}
}
void
Worker::ReadRoutine(void* argument)
{
Worker* self = static_cast<Worker*>(argument);
if (NULL == self)
return;
while (self->running_) {
if (!self->poll_->Polling(kEventTypeRead)) {
Tools::Sleep(1);
continue;
}
}
}
void
Worker::WriteRoutine(void* argument)
{
Worker* self = static_cast<Worker*>(argument);
if (NULL == self)
return;
while (self->running_) {
if (!self->poll_->Polling(kEventTypeWrite)) {
Tools::Sleep(1);
continue;
}
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include <string>
#include <SharedContext.hpp>
namespace DoremiEngine
{
namespace Core
{
/**
*/
class SharedContextImplementation : public SharedContext
{
public:
SharedContextImplementation()
: m_workingDirectory(""), m_preferenceDirectory(""), m_audio(nullptr), m_core(nullptr),
m_graphic(nullptr), m_memory(nullptr), m_network(nullptr), m_physics(nullptr),
m_script(nullptr)
{
}
void SetAudioModule(Audio::AudioModule* p_audioModule)
{
m_audio = p_audioModule;
}
void SetCoreModule(DoremiEngine* p_coreModule)
{
m_core = p_coreModule;
}
void SetGraphicModule(Graphic::GraphicModule* p_graphicModule)
{
m_graphic = p_graphicModule;
}
void SetMemoryModule(Memory::MemoryModule* p_memoryModule)
{
m_memory = p_memoryModule;
}
void SetNetworkModule(Network::NetworkModule* p_networkModule)
{
m_network = p_networkModule;
}
void SetPhysicsModule(Physics::PhysicsModule* p_physicsModule)
{
m_physics = p_physicsModule;
}
void SetScriptModule(Script::ScriptModule* p_scriptModule)
{
p_scriptModule = m_script;
}
const std::string GetWorkingDirectory() const
{
return m_workingDirectory;
};
const std::string GetPreferenceDirectory() const
{
return m_preferenceDirectory;
};
Audio::AudioModule& GetAudioModule() const
{
return *m_audio;
}
DoremiEngine& GetCoreModule() const
{
return *m_core;
};
Graphic::GraphicModule& GetGraphicModule() const
{
return *m_graphic;
};
Memory::MemoryModule& GetMemoryModule() const
{
return *m_memory;
};
Network::NetworkModule& GetNetworkModule() const
{
return *m_network;
};
Physics::PhysicsModule& GetPhysicsModule() const
{
return *m_physics;
};
Script::ScriptModule& GetScriptModule() const
{
return *m_script;
};
private:
std::string m_workingDirectory;
std::string m_preferenceDirectory;
Audio::AudioModule* m_audio;
DoremiEngine* m_core;
Graphic::GraphicModule* m_graphic;
Memory::MemoryModule* m_memory;
Network::NetworkModule* m_network;
Physics::PhysicsModule* m_physics;
Script::ScriptModule* m_script;
};
}
}<commit_msg>Removed legacy comment brackets<commit_after>#pragma once
#include <string>
#include <SharedContext.hpp>
namespace DoremiEngine
{
namespace Core
{
class SharedContextImplementation : public SharedContext
{
public:
SharedContextImplementation()
: m_workingDirectory(""), m_preferenceDirectory(""), m_audio(nullptr), m_core(nullptr),
m_graphic(nullptr), m_memory(nullptr), m_network(nullptr), m_physics(nullptr),
m_script(nullptr)
{
}
void SetAudioModule(Audio::AudioModule* p_audioModule)
{
m_audio = p_audioModule;
}
void SetCoreModule(DoremiEngine* p_coreModule)
{
m_core = p_coreModule;
}
void SetGraphicModule(Graphic::GraphicModule* p_graphicModule)
{
m_graphic = p_graphicModule;
}
void SetMemoryModule(Memory::MemoryModule* p_memoryModule)
{
m_memory = p_memoryModule;
}
void SetNetworkModule(Network::NetworkModule* p_networkModule)
{
m_network = p_networkModule;
}
void SetPhysicsModule(Physics::PhysicsModule* p_physicsModule)
{
m_physics = p_physicsModule;
}
void SetScriptModule(Script::ScriptModule* p_scriptModule)
{
p_scriptModule = m_script;
}
const std::string GetWorkingDirectory() const
{
return m_workingDirectory;
};
const std::string GetPreferenceDirectory() const
{
return m_preferenceDirectory;
};
Audio::AudioModule& GetAudioModule() const
{
return *m_audio;
}
DoremiEngine& GetCoreModule() const
{
return *m_core;
};
Graphic::GraphicModule& GetGraphicModule() const
{
return *m_graphic;
};
Memory::MemoryModule& GetMemoryModule() const
{
return *m_memory;
};
Network::NetworkModule& GetNetworkModule() const
{
return *m_network;
};
Physics::PhysicsModule& GetPhysicsModule() const
{
return *m_physics;
};
Script::ScriptModule& GetScriptModule() const
{
return *m_script;
};
private:
std::string m_workingDirectory;
std::string m_preferenceDirectory;
Audio::AudioModule* m_audio;
DoremiEngine* m_core;
Graphic::GraphicModule* m_graphic;
Memory::MemoryModule* m_memory;
Network::NetworkModule* m_network;
Physics::PhysicsModule* m_physics;
Script::ScriptModule* m_script;
};
}
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011 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 "video_processing_impl.h"
#include "critical_section_wrapper.h"
#include "trace.h"
#include <cassert>
namespace webrtc {
namespace
{
void
SetSubSampling(VideoProcessingModule::FrameStats& stats,
const WebRtc_Word32 width,
const WebRtc_Word32 height)
{
if (width * height >= 640 * 480)
{
stats.subSamplWidth = 3;
stats.subSamplHeight = 3;
}
else if (width * height >= 352 * 288)
{
stats.subSamplWidth = 2;
stats.subSamplHeight = 2;
}
else if (width * height >= 176 * 144)
{
stats.subSamplWidth = 1;
stats.subSamplHeight = 1;
}
else
{
stats.subSamplWidth = 0;
stats.subSamplHeight = 0;
}
}
}
VideoProcessingModule*
VideoProcessingModule::Create(const WebRtc_Word32 id)
{
WEBRTC_TRACE(webrtc::kTraceModuleCall, webrtc::kTraceVideoPreocessing, id,
"VideoProcessingModule::Create()");
return new VideoProcessingModuleImpl(id);
}
void
VideoProcessingModule::Destroy(VideoProcessingModule* module)
{
if (module)
{
WEBRTC_TRACE(webrtc::kTraceModuleCall, webrtc::kTraceVideoPreocessing,
static_cast<VideoProcessingModuleImpl*>(module)->Id(),
"VideoProcessingModule::destroy()");
delete static_cast<VideoProcessingModuleImpl*>(module);
}
}
WebRtc_Word32
VideoProcessingModuleImpl::ChangeUniqueId(const WebRtc_Word32 id)
{
CriticalSectionScoped mutex(_mutex);
WEBRTC_TRACE(webrtc::kTraceModuleCall, webrtc::kTraceVideoPreocessing, _id, "ChangeUniqueId(new id:%d)", id);
_id = id;
_brightnessDetection.ChangeUniqueId(id);
_deflickering.ChangeUniqueId(id);
_denoising.ChangeUniqueId(id);
_framePreProcessor.ChangeUniqueId(id);
return VPM_OK;
}
WebRtc_Word32
VideoProcessingModuleImpl::Id() const
{
CriticalSectionScoped mutex(_mutex);
return _id;
}
VideoProcessingModuleImpl::VideoProcessingModuleImpl(const WebRtc_Word32 id) :
_id(id),
_mutex(*CriticalSectionWrapper::CreateCriticalSection())
{
_brightnessDetection.ChangeUniqueId(id);
_deflickering.ChangeUniqueId(id);
_denoising.ChangeUniqueId(id);
_framePreProcessor.ChangeUniqueId(id);
WEBRTC_TRACE(webrtc::kTraceMemory, webrtc::kTraceVideoPreocessing, _id, "Created");
}
VideoProcessingModuleImpl::~VideoProcessingModuleImpl()
{
WEBRTC_TRACE(webrtc::kTraceMemory, webrtc::kTraceVideoPreocessing, _id, "Destroyed");
delete &_mutex;
}
void
VideoProcessingModuleImpl::Reset()
{
CriticalSectionScoped mutex(_mutex);
_deflickering.Reset();
_denoising.Reset();
_brightnessDetection.Reset();
_framePreProcessor.Reset();
}
WebRtc_Word32
VideoProcessingModule::GetFrameStats(FrameStats& stats,
const VideoFrame& frame)
{
return GetFrameStats(stats, frame.Buffer(), frame.Width(), frame.Height());
}
WebRtc_Word32
VideoProcessingModule::GetFrameStats(FrameStats& stats,
const WebRtc_UWord8* frame,
const WebRtc_UWord32 width,
const WebRtc_UWord32 height)
{
if (frame == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoPreocessing, -1, "Null frame pointer");
return VPM_PARAMETER_ERROR;
}
if (width == 0 || height == 0)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoPreocessing, -1, "Invalid frame size");
return VPM_PARAMETER_ERROR;
}
ClearFrameStats(stats); // The histogram needs to be zeroed out.
SetSubSampling(stats, width, height);
// Compute histogram and sum of frame
for (WebRtc_UWord32 i = 0; i < height; i += (1 << stats.subSamplHeight))
{
WebRtc_Word32 k = i * width;
for (WebRtc_UWord32 j = 0; j < width; j += (1 << stats.subSamplWidth))
{
stats.hist[frame[k + j]]++;
stats.sum += frame[k + j];
}
}
stats.numPixels = (width * height) / ((1 << stats.subSamplWidth) * (1 << stats.subSamplHeight));
assert(stats.numPixels > 0);
// Compute mean value of frame
stats.mean = stats.sum / stats.numPixels;
return VPM_OK;
}
bool
VideoProcessingModule::ValidFrameStats(const FrameStats& stats)
{
if (stats.numPixels == 0)
{
return false;
}
return true;
}
void
VideoProcessingModule::ClearFrameStats(FrameStats& stats)
{
stats.mean = 0;
stats.sum = 0;
stats.numPixels = 0;
stats.subSamplWidth = 0;
stats.subSamplHeight = 0;
memset(stats.hist, 0, sizeof(stats.hist));
}
WebRtc_Word32
VideoProcessingModule::ColorEnhancement(VideoFrame& frame)
{
return ColorEnhancement(frame.Buffer(), frame.Width(), frame.Height());
}
WebRtc_Word32
VideoProcessingModule::ColorEnhancement(WebRtc_UWord8* frame,
const WebRtc_UWord32 width,
const WebRtc_UWord32 height)
{
return VideoProcessing::ColorEnhancement(frame, width, height);
}
WebRtc_Word32
VideoProcessingModule::Brighten(VideoFrame& frame, int delta)
{
return Brighten(frame.Buffer(), frame.Width(), frame.Height(), delta);
}
WebRtc_Word32
VideoProcessingModule::Brighten(WebRtc_UWord8* frame,
int width,
int height,
int delta)
{
return VideoProcessing::Brighten(frame, width, height, delta);
}
WebRtc_Word32
VideoProcessingModuleImpl::Deflickering(VideoFrame& frame,
FrameStats& stats)
{
return Deflickering(frame.Buffer(), frame.Width(), frame.Height(),
frame.TimeStamp(), stats);
}
WebRtc_Word32
VideoProcessingModuleImpl::Deflickering(WebRtc_UWord8* frame,
const WebRtc_UWord32 width,
const WebRtc_UWord32 height,
const WebRtc_UWord32 timestamp,
FrameStats& stats)
{
CriticalSectionScoped mutex(_mutex);
return _deflickering.ProcessFrame(frame, width, height, timestamp, stats);
}
WebRtc_Word32
VideoProcessingModuleImpl::Denoising(VideoFrame& frame)
{
return Denoising(frame.Buffer(), frame.Width(), frame.Height());
}
WebRtc_Word32
VideoProcessingModuleImpl::Denoising(WebRtc_UWord8* frame,
const WebRtc_UWord32 width,
const WebRtc_UWord32 height)
{
CriticalSectionScoped mutex(_mutex);
return _denoising.ProcessFrame(frame, width, height);
}
WebRtc_Word32
VideoProcessingModuleImpl::BrightnessDetection(const VideoFrame& frame,
const FrameStats& stats)
{
return BrightnessDetection(frame.Buffer(), frame.Width(), frame.Height(), stats);
}
WebRtc_Word32
VideoProcessingModuleImpl::BrightnessDetection(const WebRtc_UWord8* frame,
const WebRtc_UWord32 width,
const WebRtc_UWord32 height,
const FrameStats& stats)
{
CriticalSectionScoped mutex(_mutex);
return _brightnessDetection.ProcessFrame(frame, width, height, stats);
}
void
VideoProcessingModuleImpl::EnableTemporalDecimation(bool enable)
{
CriticalSectionScoped mutex(_mutex);
_framePreProcessor.EnableTemporalDecimation(enable);
}
void
VideoProcessingModuleImpl::SetInputFrameResampleMode(VideoFrameResampling resamplingMode)
{
CriticalSectionScoped cs(_mutex);
_framePreProcessor.SetInputFrameResampleMode(resamplingMode);
}
WebRtc_Word32
VideoProcessingModuleImpl::SetMaxFrameRate(WebRtc_UWord32 maxFrameRate)
{
CriticalSectionScoped cs(_mutex);
return _framePreProcessor.SetMaxFrameRate(maxFrameRate);
}
WebRtc_Word32
VideoProcessingModuleImpl::SetTargetResolution(WebRtc_UWord32 width, WebRtc_UWord32 height, WebRtc_UWord32 frameRate)
{
CriticalSectionScoped cs(_mutex);
return _framePreProcessor.SetTargetResolution(width, height, frameRate);
}
WebRtc_UWord32
VideoProcessingModuleImpl::DecimatedFrameRate()
{
CriticalSectionScoped cs(_mutex);
return _framePreProcessor.DecimatedFrameRate();
}
WebRtc_UWord32
VideoProcessingModuleImpl::DecimatedWidth() const
{
CriticalSectionScoped cs(_mutex);
return _framePreProcessor.DecimatedWidth();
}
WebRtc_UWord32
VideoProcessingModuleImpl::DecimatedHeight() const
{
CriticalSectionScoped cs(_mutex);
return _framePreProcessor.DecimatedHeight();
}
WebRtc_Word32
VideoProcessingModuleImpl::PreprocessFrame(const VideoFrame *frame, VideoFrame **processedFrame)
{
CriticalSectionScoped mutex(_mutex);
return _framePreProcessor.PreprocessFrame(frame, processedFrame);
}
VideoContentMetrics*
VideoProcessingModuleImpl::ContentMetrics() const
{
CriticalSectionScoped mutex(_mutex);
return _framePreProcessor.ContentMetrics();
}
void
VideoProcessingModuleImpl::EnableContentAnalysis(bool enable)
{
CriticalSectionScoped mutex(_mutex);
_framePreProcessor.EnableContentAnalysis(enable);
}
} //namespace
<commit_msg>Remove the deprecated kTraceModuleCall trace from video processing module. Review URL: https://webrtc-codereview.appspot.com/395012<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 "video_processing_impl.h"
#include "critical_section_wrapper.h"
#include "trace.h"
#include <cassert>
namespace webrtc {
namespace
{
void
SetSubSampling(VideoProcessingModule::FrameStats& stats,
const WebRtc_Word32 width,
const WebRtc_Word32 height)
{
if (width * height >= 640 * 480)
{
stats.subSamplWidth = 3;
stats.subSamplHeight = 3;
}
else if (width * height >= 352 * 288)
{
stats.subSamplWidth = 2;
stats.subSamplHeight = 2;
}
else if (width * height >= 176 * 144)
{
stats.subSamplWidth = 1;
stats.subSamplHeight = 1;
}
else
{
stats.subSamplWidth = 0;
stats.subSamplHeight = 0;
}
}
}
VideoProcessingModule*
VideoProcessingModule::Create(const WebRtc_Word32 id)
{
return new VideoProcessingModuleImpl(id);
}
void
VideoProcessingModule::Destroy(VideoProcessingModule* module)
{
if (module)
{
delete static_cast<VideoProcessingModuleImpl*>(module);
}
}
WebRtc_Word32
VideoProcessingModuleImpl::ChangeUniqueId(const WebRtc_Word32 id)
{
CriticalSectionScoped mutex(_mutex);
_id = id;
_brightnessDetection.ChangeUniqueId(id);
_deflickering.ChangeUniqueId(id);
_denoising.ChangeUniqueId(id);
_framePreProcessor.ChangeUniqueId(id);
return VPM_OK;
}
WebRtc_Word32
VideoProcessingModuleImpl::Id() const
{
CriticalSectionScoped mutex(_mutex);
return _id;
}
VideoProcessingModuleImpl::VideoProcessingModuleImpl(const WebRtc_Word32 id) :
_id(id),
_mutex(*CriticalSectionWrapper::CreateCriticalSection())
{
_brightnessDetection.ChangeUniqueId(id);
_deflickering.ChangeUniqueId(id);
_denoising.ChangeUniqueId(id);
_framePreProcessor.ChangeUniqueId(id);
WEBRTC_TRACE(webrtc::kTraceMemory, webrtc::kTraceVideoPreocessing, _id, "Created");
}
VideoProcessingModuleImpl::~VideoProcessingModuleImpl()
{
WEBRTC_TRACE(webrtc::kTraceMemory, webrtc::kTraceVideoPreocessing, _id, "Destroyed");
delete &_mutex;
}
void
VideoProcessingModuleImpl::Reset()
{
CriticalSectionScoped mutex(_mutex);
_deflickering.Reset();
_denoising.Reset();
_brightnessDetection.Reset();
_framePreProcessor.Reset();
}
WebRtc_Word32
VideoProcessingModule::GetFrameStats(FrameStats& stats,
const VideoFrame& frame)
{
return GetFrameStats(stats, frame.Buffer(), frame.Width(), frame.Height());
}
WebRtc_Word32
VideoProcessingModule::GetFrameStats(FrameStats& stats,
const WebRtc_UWord8* frame,
const WebRtc_UWord32 width,
const WebRtc_UWord32 height)
{
if (frame == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoPreocessing, -1, "Null frame pointer");
return VPM_PARAMETER_ERROR;
}
if (width == 0 || height == 0)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoPreocessing, -1, "Invalid frame size");
return VPM_PARAMETER_ERROR;
}
ClearFrameStats(stats); // The histogram needs to be zeroed out.
SetSubSampling(stats, width, height);
// Compute histogram and sum of frame
for (WebRtc_UWord32 i = 0; i < height; i += (1 << stats.subSamplHeight))
{
WebRtc_Word32 k = i * width;
for (WebRtc_UWord32 j = 0; j < width; j += (1 << stats.subSamplWidth))
{
stats.hist[frame[k + j]]++;
stats.sum += frame[k + j];
}
}
stats.numPixels = (width * height) / ((1 << stats.subSamplWidth) * (1 << stats.subSamplHeight));
assert(stats.numPixels > 0);
// Compute mean value of frame
stats.mean = stats.sum / stats.numPixels;
return VPM_OK;
}
bool
VideoProcessingModule::ValidFrameStats(const FrameStats& stats)
{
if (stats.numPixels == 0)
{
return false;
}
return true;
}
void
VideoProcessingModule::ClearFrameStats(FrameStats& stats)
{
stats.mean = 0;
stats.sum = 0;
stats.numPixels = 0;
stats.subSamplWidth = 0;
stats.subSamplHeight = 0;
memset(stats.hist, 0, sizeof(stats.hist));
}
WebRtc_Word32
VideoProcessingModule::ColorEnhancement(VideoFrame& frame)
{
return ColorEnhancement(frame.Buffer(), frame.Width(), frame.Height());
}
WebRtc_Word32
VideoProcessingModule::ColorEnhancement(WebRtc_UWord8* frame,
const WebRtc_UWord32 width,
const WebRtc_UWord32 height)
{
return VideoProcessing::ColorEnhancement(frame, width, height);
}
WebRtc_Word32
VideoProcessingModule::Brighten(VideoFrame& frame, int delta)
{
return Brighten(frame.Buffer(), frame.Width(), frame.Height(), delta);
}
WebRtc_Word32
VideoProcessingModule::Brighten(WebRtc_UWord8* frame,
int width,
int height,
int delta)
{
return VideoProcessing::Brighten(frame, width, height, delta);
}
WebRtc_Word32
VideoProcessingModuleImpl::Deflickering(VideoFrame& frame,
FrameStats& stats)
{
return Deflickering(frame.Buffer(), frame.Width(), frame.Height(),
frame.TimeStamp(), stats);
}
WebRtc_Word32
VideoProcessingModuleImpl::Deflickering(WebRtc_UWord8* frame,
const WebRtc_UWord32 width,
const WebRtc_UWord32 height,
const WebRtc_UWord32 timestamp,
FrameStats& stats)
{
CriticalSectionScoped mutex(_mutex);
return _deflickering.ProcessFrame(frame, width, height, timestamp, stats);
}
WebRtc_Word32
VideoProcessingModuleImpl::Denoising(VideoFrame& frame)
{
return Denoising(frame.Buffer(), frame.Width(), frame.Height());
}
WebRtc_Word32
VideoProcessingModuleImpl::Denoising(WebRtc_UWord8* frame,
const WebRtc_UWord32 width,
const WebRtc_UWord32 height)
{
CriticalSectionScoped mutex(_mutex);
return _denoising.ProcessFrame(frame, width, height);
}
WebRtc_Word32
VideoProcessingModuleImpl::BrightnessDetection(const VideoFrame& frame,
const FrameStats& stats)
{
return BrightnessDetection(frame.Buffer(), frame.Width(), frame.Height(), stats);
}
WebRtc_Word32
VideoProcessingModuleImpl::BrightnessDetection(const WebRtc_UWord8* frame,
const WebRtc_UWord32 width,
const WebRtc_UWord32 height,
const FrameStats& stats)
{
CriticalSectionScoped mutex(_mutex);
return _brightnessDetection.ProcessFrame(frame, width, height, stats);
}
void
VideoProcessingModuleImpl::EnableTemporalDecimation(bool enable)
{
CriticalSectionScoped mutex(_mutex);
_framePreProcessor.EnableTemporalDecimation(enable);
}
void
VideoProcessingModuleImpl::SetInputFrameResampleMode(VideoFrameResampling resamplingMode)
{
CriticalSectionScoped cs(_mutex);
_framePreProcessor.SetInputFrameResampleMode(resamplingMode);
}
WebRtc_Word32
VideoProcessingModuleImpl::SetMaxFrameRate(WebRtc_UWord32 maxFrameRate)
{
CriticalSectionScoped cs(_mutex);
return _framePreProcessor.SetMaxFrameRate(maxFrameRate);
}
WebRtc_Word32
VideoProcessingModuleImpl::SetTargetResolution(WebRtc_UWord32 width, WebRtc_UWord32 height, WebRtc_UWord32 frameRate)
{
CriticalSectionScoped cs(_mutex);
return _framePreProcessor.SetTargetResolution(width, height, frameRate);
}
WebRtc_UWord32
VideoProcessingModuleImpl::DecimatedFrameRate()
{
CriticalSectionScoped cs(_mutex);
return _framePreProcessor.DecimatedFrameRate();
}
WebRtc_UWord32
VideoProcessingModuleImpl::DecimatedWidth() const
{
CriticalSectionScoped cs(_mutex);
return _framePreProcessor.DecimatedWidth();
}
WebRtc_UWord32
VideoProcessingModuleImpl::DecimatedHeight() const
{
CriticalSectionScoped cs(_mutex);
return _framePreProcessor.DecimatedHeight();
}
WebRtc_Word32
VideoProcessingModuleImpl::PreprocessFrame(const VideoFrame *frame, VideoFrame **processedFrame)
{
CriticalSectionScoped mutex(_mutex);
return _framePreProcessor.PreprocessFrame(frame, processedFrame);
}
VideoContentMetrics*
VideoProcessingModuleImpl::ContentMetrics() const
{
CriticalSectionScoped mutex(_mutex);
return _framePreProcessor.ContentMetrics();
}
void
VideoProcessingModuleImpl::EnableContentAnalysis(bool enable)
{
CriticalSectionScoped mutex(_mutex);
_framePreProcessor.EnableContentAnalysis(enable);
}
} //namespace
<|endoftext|>
|
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_POSH_RUNTIME_IPC_RUNTIME_INTERFACE_HPP
#define IOX_POSH_RUNTIME_IPC_RUNTIME_INTERFACE_HPP
#include "iceoryx_posh/internal/runtime/ipc_interface_creator.hpp"
#include "iceoryx_posh/internal/runtime/ipc_interface_user.hpp"
namespace iox
{
namespace runtime
{
class IpcRuntimeInterface
{
public:
/// @brief Runtime Interface for the own IPC channel and the one to the RouDi daemon
/// @param[in] roudiName name of the RouDi IPC channel
/// @param[in] appName name of the appplication and its IPC channel
/// @param[in] roudiWaitingTimeout timeout for searching the RouDi IPC channel
IpcRuntimeInterface(const ProcessName_t& roudiName,
const ProcessName_t& appName,
const units::Duration roudiWaitingTimeout) noexcept;
~IpcRuntimeInterface() = default;
/// @brief Not needed therefore deleted
IpcRuntimeInterface(const IpcRuntimeInterface&) = delete;
IpcRuntimeInterface& operator=(const IpcRuntimeInterface&) = delete;
IpcRuntimeInterface(IpcRuntimeInterface&&) = delete;
IpcRuntimeInterface& operator=(IpcRuntimeInterface&&) = delete;
/// @brief sends the keep alive trigger to the RouDi daemon
/// @return true if sending was successful, false if not
bool sendKeepalive() noexcept;
/// @brief send a request to the RouDi daemon
/// @param[in] msg request to RouDi
/// @param[out] answer response from RouDi
/// @return true if communication was successful, false if not
bool sendRequestToRouDi(const IpcMessage& msg, IpcMessage& answer) noexcept;
/// @brief send a message to the RouDi daemon
/// @param[in] msg message which will be send to RouDi
/// @return true if communication was successful, otherwise false
bool sendMessageToRouDi(const IpcMessage& msg) noexcept;
/// @brief get the adress offset of the segment manager
/// @return address offset as RelativePointer::offset_t
RelativePointer::offset_t getSegmentManagerAddressOffset() const noexcept;
/// @brief get the size of the management shared memory object
/// @return size in bytes
size_t getShmTopicSize() noexcept;
/// @brief get the segment id of the shared memory object
/// @return segment id
uint64_t getSegmentId() const noexcept;
private:
enum class RegAckResult
{
SUCCESS,
TIMEOUT
};
/// @brief
/// @return
void waitForRoudi(cxx::DeadlineTimer& timer) noexcept;
/// @brief
/// @return
RegAckResult waitForRegAck(int64_t transmissionTimestamp) noexcept;
private:
ProcessName_t m_appName;
cxx::optional<RelativePointer::offset_t> m_segmentManagerAddressOffset;
IpcInterfaceCreator m_AppIpcInterface;
IpcInterfaceUser m_RoudiIpcInterface;
size_t m_shmTopicSize{0U};
uint64_t m_segmentId{0U};
};
} // namespace runtime
} // namespace iox
#endif // IOX_POSH_RUNTIME_IPC_RUNTIME_INTERFACE_HPP<commit_msg>iox-#381 Address review findings from Christian Eltzschig removing size_t usage and be strict about const-correctness<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_POSH_RUNTIME_IPC_RUNTIME_INTERFACE_HPP
#define IOX_POSH_RUNTIME_IPC_RUNTIME_INTERFACE_HPP
#include "iceoryx_posh/internal/runtime/ipc_interface_creator.hpp"
#include "iceoryx_posh/internal/runtime/ipc_interface_user.hpp"
namespace iox
{
namespace runtime
{
class IpcRuntimeInterface
{
public:
/// @brief Runtime Interface for the own IPC channel and the one to the RouDi daemon
/// @param[in] roudiName name of the RouDi IPC channel
/// @param[in] appName name of the appplication and its IPC channel
/// @param[in] roudiWaitingTimeout timeout for searching the RouDi IPC channel
IpcRuntimeInterface(const ProcessName_t& roudiName,
const ProcessName_t& appName,
const units::Duration roudiWaitingTimeout) noexcept;
~IpcRuntimeInterface() = default;
/// @brief Not needed therefore deleted
IpcRuntimeInterface(const IpcRuntimeInterface&) = delete;
IpcRuntimeInterface& operator=(const IpcRuntimeInterface&) = delete;
IpcRuntimeInterface(IpcRuntimeInterface&&) = delete;
IpcRuntimeInterface& operator=(IpcRuntimeInterface&&) = delete;
/// @brief sends the keep alive trigger to the RouDi daemon
/// @return true if sending was successful, false if not
bool sendKeepalive() noexcept;
/// @brief send a request to the RouDi daemon
/// @param[in] msg request to RouDi
/// @param[out] answer response from RouDi
/// @return true if communication was successful, false if not
bool sendRequestToRouDi(const IpcMessage& msg, IpcMessage& answer) noexcept;
/// @brief send a message to the RouDi daemon
/// @param[in] msg message which will be send to RouDi
/// @return true if communication was successful, otherwise false
bool sendMessageToRouDi(const IpcMessage& msg) noexcept;
/// @brief get the adress offset of the segment manager
/// @return address offset as RelativePointer::offset_t
RelativePointer::offset_t getSegmentManagerAddressOffset() const noexcept;
/// @brief get the size of the management shared memory object
/// @return size in bytes
size_t getShmTopicSize() noexcept;
/// @brief get the segment id of the shared memory object
/// @return segment id
uint64_t getSegmentId() const noexcept;
private:
enum class RegAckResult
{
SUCCESS,
TIMEOUT
};
/// @brief
/// @return
void waitForRoudi(cxx::DeadlineTimer& timer) noexcept;
/// @brief
/// @return
RegAckResult waitForRegAck(const int64_t transmissionTimestamp) noexcept;
private:
ProcessName_t m_appName;
cxx::optional<RelativePointer::offset_t> m_segmentManagerAddressOffset;
IpcInterfaceCreator m_AppIpcInterface;
IpcInterfaceUser m_RoudiIpcInterface;
uint64_t m_shmTopicSize{0U};
uint64_t m_segmentId{0U};
};
} // namespace runtime
} // namespace iox
#endif // IOX_POSH_RUNTIME_IPC_RUNTIME_INTERFACE_HPP<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, NVIDIA Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the copyright holders or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
// ----------------------------------------------------------------------
// CLAHE
namespace
{
class CLAHE_CalcLut_Body : public cv::ParallelLoopBody
{
public:
CLAHE_CalcLut_Body(const cv::Mat& src, cv::Mat& lut, cv::Size tileSize, int tilesX, int tilesY, int clipLimit, float lutScale) :
src_(src), lut_(lut), tileSize_(tileSize), tilesX_(tilesX), tilesY_(tilesY), clipLimit_(clipLimit), lutScale_(lutScale)
{
}
void operator ()(const cv::Range& range) const;
private:
cv::Mat src_;
mutable cv::Mat lut_;
cv::Size tileSize_;
int tilesX_;
int tilesY_;
int clipLimit_;
float lutScale_;
};
void CLAHE_CalcLut_Body::operator ()(const cv::Range& range) const
{
const int histSize = 256;
uchar* tileLut = lut_.ptr(range.start);
const size_t lut_step = lut_.step;
for (int k = range.start; k < range.end; ++k, tileLut += lut_step)
{
const int ty = k / tilesX_;
const int tx = k % tilesX_;
// retrieve tile submatrix
cv::Rect tileROI;
tileROI.x = tx * tileSize_.width;
tileROI.y = ty * tileSize_.height;
tileROI.width = tileSize_.width;
tileROI.height = tileSize_.height;
const cv::Mat tile = src_(tileROI);
// calc histogram
int tileHist[histSize] = {0, };
int height = tileROI.height;
const size_t sstep = tile.step;
for (const uchar* ptr = tile.ptr<uchar>(0); height--; ptr += sstep)
{
int x = 0;
for (; x <= tileROI.width - 4; x += 4)
{
int t0 = ptr[x], t1 = ptr[x+1];
tileHist[t0]++; tileHist[t1]++;
t0 = ptr[x+2]; t1 = ptr[x+3];
tileHist[t0]++; tileHist[t1]++;
}
for (; x < tileROI.width; ++x)
tileHist[ptr[x]]++;
}
// clip histogram
if (clipLimit_ > 0)
{
// how many pixels were clipped
int clipped = 0;
for (int i = 0; i < histSize; ++i)
{
if (tileHist[i] > clipLimit_)
{
clipped += tileHist[i] - clipLimit_;
tileHist[i] = clipLimit_;
}
}
// redistribute clipped pixels
int redistBatch = clipped / histSize;
int residual = clipped - redistBatch * histSize;
for (int i = 0; i < histSize; ++i)
tileHist[i] += redistBatch;
for (int i = 0; i < residual; ++i)
tileHist[i]++;
}
// calc Lut
int sum = 0;
for (int i = 0; i < histSize; ++i)
{
sum += tileHist[i];
tileLut[i] = cv::saturate_cast<uchar>(sum * lutScale_);
}
}
}
class CLAHE_Interpolation_Body : public cv::ParallelLoopBody
{
public:
CLAHE_Interpolation_Body(const cv::Mat& src, cv::Mat& dst, const cv::Mat& lut, cv::Size tileSize, int tilesX, int tilesY) :
src_(src), dst_(dst), lut_(lut), tileSize_(tileSize), tilesX_(tilesX), tilesY_(tilesY)
{
}
void operator ()(const cv::Range& range) const;
private:
cv::Mat src_;
mutable cv::Mat dst_;
cv::Mat lut_;
cv::Size tileSize_;
int tilesX_;
int tilesY_;
};
void CLAHE_Interpolation_Body::operator ()(const cv::Range& range) const
{
const size_t lut_step = lut_.step;
for (int y = range.start; y < range.end; ++y)
{
const uchar* srcRow = src_.ptr<uchar>(y);
uchar* dstRow = dst_.ptr<uchar>(y);
const float tyf = (static_cast<float>(y) / tileSize_.height) - 0.5f;
int ty1 = cvFloor(tyf);
int ty2 = ty1 + 1;
const float ya = tyf - ty1;
ty1 = std::max(ty1, 0);
ty2 = std::min(ty2, tilesY_ - 1);
const uchar* lutPlane1 = lut_.ptr(ty1 * tilesX_);
const uchar* lutPlane2 = lut_.ptr(ty2 * tilesX_);
for (int x = 0; x < src_.cols; ++x)
{
const float txf = (static_cast<float>(x) / tileSize_.width) - 0.5f;
int tx1 = cvFloor(txf);
int tx2 = tx1 + 1;
const float xa = txf - tx1;
tx1 = std::max(tx1, 0);
tx2 = std::min(tx2, tilesX_ - 1);
const int srcVal = srcRow[x];
const size_t ind1 = tx1 * lut_step + srcVal;
const size_t ind2 = tx2 * lut_step + srcVal;
float res = 0;
res += lutPlane1[ind1] * ((1.0f - xa) * (1.0f - ya));
res += lutPlane1[ind2] * ((xa) * (1.0f - ya));
res += lutPlane2[ind1] * ((1.0f - xa) * (ya));
res += lutPlane2[ind2] * ((xa) * (ya));
dstRow[x] = cv::saturate_cast<uchar>(res);
}
}
}
class CLAHE_Impl : public cv::CLAHE
{
public:
CLAHE_Impl(double clipLimit = 40.0, int tilesX = 8, int tilesY = 8);
cv::AlgorithmInfo* info() const;
void apply(cv::InputArray src, cv::OutputArray dst);
void setClipLimit(double clipLimit);
double getClipLimit() const;
void setTilesGridSize(cv::Size tileGridSize);
cv::Size getTilesGridSize() const;
void collectGarbage();
private:
double clipLimit_;
int tilesX_;
int tilesY_;
cv::Mat srcExt_;
cv::Mat lut_;
};
CLAHE_Impl::CLAHE_Impl(double clipLimit, int tilesX, int tilesY) :
clipLimit_(clipLimit), tilesX_(tilesX), tilesY_(tilesY)
{
}
CV_INIT_ALGORITHM(CLAHE_Impl, "CLAHE",
obj.info()->addParam(obj, "clipLimit", obj.clipLimit_);
obj.info()->addParam(obj, "tilesX", obj.tilesX_);
obj.info()->addParam(obj, "tilesY", obj.tilesY_))
void CLAHE_Impl::apply(cv::InputArray _src, cv::OutputArray _dst)
{
cv::Mat src = _src.getMat();
CV_Assert( src.type() == CV_8UC1 );
_dst.create( src.size(), src.type() );
cv::Mat dst = _dst.getMat();
const int histSize = 256;
lut_.create(tilesX_ * tilesY_, histSize, CV_8UC1);
cv::Size tileSize;
cv::Mat srcForLut;
if (src.cols % tilesX_ == 0 && src.rows % tilesY_ == 0)
{
tileSize = cv::Size(src.cols / tilesX_, src.rows / tilesY_);
srcForLut = src;
}
else
{
cv::copyMakeBorder(src, srcExt_, 0, tilesY_ - (src.rows % tilesY_), 0, tilesX_ - (src.cols % tilesX_), cv::BORDER_REFLECT_101);
tileSize = cv::Size(srcExt_.cols / tilesX_, srcExt_.rows / tilesY_);
srcForLut = srcExt_;
}
const int tileSizeTotal = tileSize.area();
const float lutScale = static_cast<float>(histSize - 1) / tileSizeTotal;
int clipLimit = 0;
if (clipLimit_ > 0.0)
{
clipLimit = static_cast<int>(clipLimit_ * tileSizeTotal / histSize);
clipLimit = std::max(clipLimit, 1);
}
CLAHE_CalcLut_Body calcLutBody(srcForLut, lut_, tileSize, tilesX_, tilesY_, clipLimit, lutScale);
cv::parallel_for_(cv::Range(0, tilesX_ * tilesY_), calcLutBody);
CLAHE_Interpolation_Body interpolationBody(src, dst, lut_, tileSize, tilesX_, tilesY_);
cv::parallel_for_(cv::Range(0, src.rows), interpolationBody);
}
void CLAHE_Impl::setClipLimit(double clipLimit)
{
clipLimit_ = clipLimit;
}
double CLAHE_Impl::getClipLimit() const
{
return clipLimit_;
}
void CLAHE_Impl::setTilesGridSize(cv::Size tileGridSize)
{
tilesX_ = tileGridSize.width;
tilesY_ = tileGridSize.height;
}
cv::Size CLAHE_Impl::getTilesGridSize() const
{
return cv::Size(tilesX_, tilesY_);
}
void CLAHE_Impl::collectGarbage()
{
srcExt_.release();
lut_.release();
}
}
cv::Ptr<cv::CLAHE> cv::createCLAHE(double clipLimit, cv::Size tileGridSize)
{
return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height);
}
<commit_msg>removed unused field<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, NVIDIA Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the copyright holders or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
// ----------------------------------------------------------------------
// CLAHE
namespace
{
class CLAHE_CalcLut_Body : public cv::ParallelLoopBody
{
public:
CLAHE_CalcLut_Body(const cv::Mat& src, cv::Mat& lut, cv::Size tileSize, int tilesX, int clipLimit, float lutScale) :
src_(src), lut_(lut), tileSize_(tileSize), tilesX_(tilesX), clipLimit_(clipLimit), lutScale_(lutScale)
{
}
void operator ()(const cv::Range& range) const;
private:
cv::Mat src_;
mutable cv::Mat lut_;
cv::Size tileSize_;
int tilesX_;
int clipLimit_;
float lutScale_;
};
void CLAHE_CalcLut_Body::operator ()(const cv::Range& range) const
{
const int histSize = 256;
uchar* tileLut = lut_.ptr(range.start);
const size_t lut_step = lut_.step;
for (int k = range.start; k < range.end; ++k, tileLut += lut_step)
{
const int ty = k / tilesX_;
const int tx = k % tilesX_;
// retrieve tile submatrix
cv::Rect tileROI;
tileROI.x = tx * tileSize_.width;
tileROI.y = ty * tileSize_.height;
tileROI.width = tileSize_.width;
tileROI.height = tileSize_.height;
const cv::Mat tile = src_(tileROI);
// calc histogram
int tileHist[histSize] = {0, };
int height = tileROI.height;
const size_t sstep = tile.step;
for (const uchar* ptr = tile.ptr<uchar>(0); height--; ptr += sstep)
{
int x = 0;
for (; x <= tileROI.width - 4; x += 4)
{
int t0 = ptr[x], t1 = ptr[x+1];
tileHist[t0]++; tileHist[t1]++;
t0 = ptr[x+2]; t1 = ptr[x+3];
tileHist[t0]++; tileHist[t1]++;
}
for (; x < tileROI.width; ++x)
tileHist[ptr[x]]++;
}
// clip histogram
if (clipLimit_ > 0)
{
// how many pixels were clipped
int clipped = 0;
for (int i = 0; i < histSize; ++i)
{
if (tileHist[i] > clipLimit_)
{
clipped += tileHist[i] - clipLimit_;
tileHist[i] = clipLimit_;
}
}
// redistribute clipped pixels
int redistBatch = clipped / histSize;
int residual = clipped - redistBatch * histSize;
for (int i = 0; i < histSize; ++i)
tileHist[i] += redistBatch;
for (int i = 0; i < residual; ++i)
tileHist[i]++;
}
// calc Lut
int sum = 0;
for (int i = 0; i < histSize; ++i)
{
sum += tileHist[i];
tileLut[i] = cv::saturate_cast<uchar>(sum * lutScale_);
}
}
}
class CLAHE_Interpolation_Body : public cv::ParallelLoopBody
{
public:
CLAHE_Interpolation_Body(const cv::Mat& src, cv::Mat& dst, const cv::Mat& lut, cv::Size tileSize, int tilesX, int tilesY) :
src_(src), dst_(dst), lut_(lut), tileSize_(tileSize), tilesX_(tilesX), tilesY_(tilesY)
{
}
void operator ()(const cv::Range& range) const;
private:
cv::Mat src_;
mutable cv::Mat dst_;
cv::Mat lut_;
cv::Size tileSize_;
int tilesX_;
int tilesY_;
};
void CLAHE_Interpolation_Body::operator ()(const cv::Range& range) const
{
const size_t lut_step = lut_.step;
for (int y = range.start; y < range.end; ++y)
{
const uchar* srcRow = src_.ptr<uchar>(y);
uchar* dstRow = dst_.ptr<uchar>(y);
const float tyf = (static_cast<float>(y) / tileSize_.height) - 0.5f;
int ty1 = cvFloor(tyf);
int ty2 = ty1 + 1;
const float ya = tyf - ty1;
ty1 = std::max(ty1, 0);
ty2 = std::min(ty2, tilesY_ - 1);
const uchar* lutPlane1 = lut_.ptr(ty1 * tilesX_);
const uchar* lutPlane2 = lut_.ptr(ty2 * tilesX_);
for (int x = 0; x < src_.cols; ++x)
{
const float txf = (static_cast<float>(x) / tileSize_.width) - 0.5f;
int tx1 = cvFloor(txf);
int tx2 = tx1 + 1;
const float xa = txf - tx1;
tx1 = std::max(tx1, 0);
tx2 = std::min(tx2, tilesX_ - 1);
const int srcVal = srcRow[x];
const size_t ind1 = tx1 * lut_step + srcVal;
const size_t ind2 = tx2 * lut_step + srcVal;
float res = 0;
res += lutPlane1[ind1] * ((1.0f - xa) * (1.0f - ya));
res += lutPlane1[ind2] * ((xa) * (1.0f - ya));
res += lutPlane2[ind1] * ((1.0f - xa) * (ya));
res += lutPlane2[ind2] * ((xa) * (ya));
dstRow[x] = cv::saturate_cast<uchar>(res);
}
}
}
class CLAHE_Impl : public cv::CLAHE
{
public:
CLAHE_Impl(double clipLimit = 40.0, int tilesX = 8, int tilesY = 8);
cv::AlgorithmInfo* info() const;
void apply(cv::InputArray src, cv::OutputArray dst);
void setClipLimit(double clipLimit);
double getClipLimit() const;
void setTilesGridSize(cv::Size tileGridSize);
cv::Size getTilesGridSize() const;
void collectGarbage();
private:
double clipLimit_;
int tilesX_;
int tilesY_;
cv::Mat srcExt_;
cv::Mat lut_;
};
CLAHE_Impl::CLAHE_Impl(double clipLimit, int tilesX, int tilesY) :
clipLimit_(clipLimit), tilesX_(tilesX), tilesY_(tilesY)
{
}
CV_INIT_ALGORITHM(CLAHE_Impl, "CLAHE",
obj.info()->addParam(obj, "clipLimit", obj.clipLimit_);
obj.info()->addParam(obj, "tilesX", obj.tilesX_);
obj.info()->addParam(obj, "tilesY", obj.tilesY_))
void CLAHE_Impl::apply(cv::InputArray _src, cv::OutputArray _dst)
{
cv::Mat src = _src.getMat();
CV_Assert( src.type() == CV_8UC1 );
_dst.create( src.size(), src.type() );
cv::Mat dst = _dst.getMat();
const int histSize = 256;
lut_.create(tilesX_ * tilesY_, histSize, CV_8UC1);
cv::Size tileSize;
cv::Mat srcForLut;
if (src.cols % tilesX_ == 0 && src.rows % tilesY_ == 0)
{
tileSize = cv::Size(src.cols / tilesX_, src.rows / tilesY_);
srcForLut = src;
}
else
{
cv::copyMakeBorder(src, srcExt_, 0, tilesY_ - (src.rows % tilesY_), 0, tilesX_ - (src.cols % tilesX_), cv::BORDER_REFLECT_101);
tileSize = cv::Size(srcExt_.cols / tilesX_, srcExt_.rows / tilesY_);
srcForLut = srcExt_;
}
const int tileSizeTotal = tileSize.area();
const float lutScale = static_cast<float>(histSize - 1) / tileSizeTotal;
int clipLimit = 0;
if (clipLimit_ > 0.0)
{
clipLimit = static_cast<int>(clipLimit_ * tileSizeTotal / histSize);
clipLimit = std::max(clipLimit, 1);
}
CLAHE_CalcLut_Body calcLutBody(srcForLut, lut_, tileSize, tilesX_, clipLimit, lutScale);
cv::parallel_for_(cv::Range(0, tilesX_ * tilesY_), calcLutBody);
CLAHE_Interpolation_Body interpolationBody(src, dst, lut_, tileSize, tilesX_, tilesY_);
cv::parallel_for_(cv::Range(0, src.rows), interpolationBody);
}
void CLAHE_Impl::setClipLimit(double clipLimit)
{
clipLimit_ = clipLimit;
}
double CLAHE_Impl::getClipLimit() const
{
return clipLimit_;
}
void CLAHE_Impl::setTilesGridSize(cv::Size tileGridSize)
{
tilesX_ = tileGridSize.width;
tilesY_ = tileGridSize.height;
}
cv::Size CLAHE_Impl::getTilesGridSize() const
{
return cv::Size(tilesX_, tilesY_);
}
void CLAHE_Impl::collectGarbage()
{
srcExt_.release();
lut_.release();
}
}
cv::Ptr<cv::CLAHE> cv::createCLAHE(double clipLimit, cv::Size tileGridSize)
{
return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height);
}
<|endoftext|>
|
<commit_before>#include "ConfigActivationManager.h"
#include "System/Events/EventLoop.h"
#include "Application/Common/ContextTransport.h"
#include "ConfigServer.h"
#include "ConfigQuorumProcessor.h"
void ConfigActivationManager::Init(ConfigServer* configServer_)
{
configServer = configServer_;
activationTimeout.SetCallable(MFUNC(ConfigActivationManager, OnActivationTimeout));
}
void ConfigActivationManager::TryDeactivateShardServer(uint64_t nodeID)
{
ConfigState* configState;
ConfigQuorum* itQuorum;
ConfigShardServer* shardServer;
configState = configServer->GetDatabaseManager()->GetConfigState();
FOREACH(itQuorum, configState->quorums)
{
// don't deactivate the last node due to TotalPaxos semantics
// otherwise, we wouldn't know which one to bring back, which is up-to-date
if (itQuorum->activeNodes.GetLength() <= 1)
continue;
if (itQuorum->isActivatingNode && itQuorum->activatingNodeID == nodeID)
{
shardServer = configState->GetShardServer(itQuorum->activatingNodeID);
assert(shardServer != NULL);
itQuorum->ClearActivation();
UpdateTimeout();
Log_Message("Activation failed for shard server %U and quorum %U...",
itQuorum->quorumID, itQuorum->activatingNodeID);
}
if (itQuorum->IsActiveMember(nodeID))
{
// if this node was part of an activation process, cancel it
if (itQuorum->isActivatingNode)
{
shardServer = configState->GetShardServer(itQuorum->activatingNodeID);
assert(shardServer != NULL);
itQuorum->ClearActivation();
UpdateTimeout();
Log_Message("Activation failed for shard server %U and quorum %U...",
itQuorum->activatingNodeID, itQuorum->quorumID);
}
Log_Message("Deactivating shard server %U...", nodeID);
configServer->GetQuorumProcessor()->DeactivateNode(itQuorum->quorumID, nodeID);
}
}
}
void ConfigActivationManager::TryActivateShardServer(uint64_t nodeID)
{
uint64_t paxosID;
ConfigState* configState;
ConfigQuorum* itQuorum;
ConfigShardServer* shardServer;
uint64_t now;
now = EventLoop::Now();
Log_Trace();
configState = configServer->GetDatabaseManager()->GetConfigState();
shardServer = configState->GetShardServer(nodeID);
FOREACH(itQuorum, configState->quorums)
{
Log_Trace("itQuorum->isActivatingNode: %b", itQuorum->isActivatingNode);
if (itQuorum->isActivatingNode)
continue;
Log_Trace("itQuorum->hasPrimary: %b", itQuorum->hasPrimary);
if (!itQuorum->hasPrimary)
continue;
if (itQuorum->IsInactiveMember(nodeID))
{
paxosID = QuorumInfo::GetQuorumInfo(shardServer->quorumInfos, itQuorum->quorumID)->paxosID;
if (paxosID >= (itQuorum->paxosID - RLOG_REACTIVATION_DIFF) ||
itQuorum->paxosID <= RLOG_REACTIVATION_DIFF)
{
// the shard server is "almost caught up", start the activation process
itQuorum->OnActivationStart(nodeID, now + 3*PAXOSLEASE_MAX_LEASE_TIME);
UpdateTimeout();
Log_Message("Activation started for shard server %U and quorum %U...",
itQuorum->activatingNodeID, itQuorum->quorumID);
}
}
}
}
void ConfigActivationManager::OnExtendLease(ConfigQuorum& quorum, ClusterMessage& message)
{
Log_Trace();
if (!quorum.isActivatingNode || quorum.isReplicatingActivation ||
message.configID != quorum.configID)
{
Log_Trace("ExtendLease condition: %b %b %U %U", quorum.isActivatingNode,
quorum.isReplicatingActivation,
message.configID,
quorum.configID);
return;
}
if (!quorum.isWatchingPaxosID)
{
Log_Message("Activating shard server %U in quorum %U: Starting to monitor the primary's paxosID",
quorum.quorumID, quorum.activatingNodeID);
quorum.OnActivationMonitoring(message.paxosID);
configServer->OnConfigStateChanged();
}
else
{
Log_Trace();
// if the primary was able to increase its paxosID, the new shardserver joined successfully
if (message.paxosID > quorum.activationPaxosID)
{
Log_Message("Activating shard server %U in quorum %U: The primary was able to increase its paxosID!",
quorum.quorumID, quorum.activatingNodeID);
quorum.OnActivationReplication();
configServer->OnConfigStateChanged();
configServer->GetQuorumProcessor()->ActivateNode(quorum.quorumID, quorum.activatingNodeID);
}
else
{
Log_Message("Activating shard server %U in quorum %U: The primary was not able to increase its paxosID so far...",
quorum.quorumID, quorum.activatingNodeID);
}
}
}
void ConfigActivationManager::OnActivationTimeout()
{
uint64_t now;
ConfigState* configState;
ConfigQuorum* itQuorum;
ConfigShardServer* shardServer;
Log_Trace();
now = EventLoop::Now();
configState = configServer->GetDatabaseManager()->GetConfigState();
FOREACH(itQuorum, configState->quorums)
{
if (itQuorum->activationExpireTime > 0 && itQuorum->activationExpireTime < now)
{
// stop activation
assert(itQuorum->isActivatingNode == true);
assert(itQuorum->isReplicatingActivation == false);
shardServer = configState->GetShardServer(itQuorum->activatingNodeID);
assert(shardServer != NULL);
Log_Message("Activating shard server %U in quorum %U: Activation failed...",
itQuorum->activatingNodeID, itQuorum->quorumID);
itQuorum->ClearActivation();
configServer->OnConfigStateChanged();
}
}
UpdateTimeout();
}
void ConfigActivationManager::UpdateTimeout()
{
ConfigQuorum* it;
uint64_t activationExpireTime;
Log_Trace();
activationExpireTime = 0;
FOREACH(it, configServer->GetDatabaseManager()->GetConfigState()->quorums)
{
if (it->isActivatingNode && !it->isReplicatingActivation)
{
if (activationExpireTime == 0 || it->activationExpireTime < activationExpireTime)
activationExpireTime = it->activationExpireTime;
}
}
if (activationExpireTime > 0)
{
activationTimeout.SetExpireTime(activationExpireTime);
EventLoop::Reset(&activationTimeout);
}
}
<commit_msg>Fixed activation bug where the non-primary's paxosID would trigger activation.<commit_after>#include "ConfigActivationManager.h"
#include "System/Events/EventLoop.h"
#include "Application/Common/ContextTransport.h"
#include "ConfigServer.h"
#include "ConfigQuorumProcessor.h"
void ConfigActivationManager::Init(ConfigServer* configServer_)
{
configServer = configServer_;
activationTimeout.SetCallable(MFUNC(ConfigActivationManager, OnActivationTimeout));
}
void ConfigActivationManager::TryDeactivateShardServer(uint64_t nodeID)
{
ConfigState* configState;
ConfigQuorum* itQuorum;
ConfigShardServer* shardServer;
configState = configServer->GetDatabaseManager()->GetConfigState();
FOREACH(itQuorum, configState->quorums)
{
// don't deactivate the last node due to TotalPaxos semantics
// otherwise, we wouldn't know which one to bring back, which is up-to-date
if (itQuorum->activeNodes.GetLength() <= 1)
continue;
if (itQuorum->isActivatingNode && itQuorum->activatingNodeID == nodeID)
{
shardServer = configState->GetShardServer(itQuorum->activatingNodeID);
assert(shardServer != NULL);
itQuorum->ClearActivation();
UpdateTimeout();
Log_Message("Activation failed for shard server %U and quorum %U...",
itQuorum->quorumID, itQuorum->activatingNodeID);
}
if (itQuorum->IsActiveMember(nodeID))
{
// if this node was part of an activation process, cancel it
if (itQuorum->isActivatingNode)
{
shardServer = configState->GetShardServer(itQuorum->activatingNodeID);
assert(shardServer != NULL);
itQuorum->ClearActivation();
UpdateTimeout();
Log_Message("Activation failed for shard server %U and quorum %U...",
itQuorum->activatingNodeID, itQuorum->quorumID);
}
Log_Message("Deactivating shard server %U...", nodeID);
configServer->GetQuorumProcessor()->DeactivateNode(itQuorum->quorumID, nodeID);
}
}
}
void ConfigActivationManager::TryActivateShardServer(uint64_t nodeID)
{
uint64_t paxosID;
ConfigState* configState;
ConfigQuorum* itQuorum;
ConfigShardServer* shardServer;
uint64_t now;
now = EventLoop::Now();
Log_Trace();
configState = configServer->GetDatabaseManager()->GetConfigState();
shardServer = configState->GetShardServer(nodeID);
FOREACH(itQuorum, configState->quorums)
{
Log_Trace("itQuorum->isActivatingNode: %b", itQuorum->isActivatingNode);
if (itQuorum->isActivatingNode)
continue;
Log_Trace("itQuorum->hasPrimary: %b", itQuorum->hasPrimary);
if (!itQuorum->hasPrimary)
continue;
if (itQuorum->IsInactiveMember(nodeID))
{
paxosID = QuorumInfo::GetQuorumInfo(shardServer->quorumInfos, itQuorum->quorumID)->paxosID;
if (paxosID >= (itQuorum->paxosID - RLOG_REACTIVATION_DIFF) ||
itQuorum->paxosID <= RLOG_REACTIVATION_DIFF)
{
// the shard server is "almost caught up", start the activation process
itQuorum->OnActivationStart(nodeID, now + 3*PAXOSLEASE_MAX_LEASE_TIME);
UpdateTimeout();
Log_Message("Activation started for shard server %U and quorum %U...",
itQuorum->activatingNodeID, itQuorum->quorumID);
}
}
}
}
void ConfigActivationManager::OnExtendLease(ConfigQuorum& quorum, ClusterMessage& message)
{
Log_Trace();
if (!quorum.hasPrimary || message.nodeID != quorum.primaryID)
return;
if (!quorum.isActivatingNode || quorum.isReplicatingActivation ||
message.configID != quorum.configID)
{
Log_Trace("ExtendLease condition: %b %b %U %U", quorum.isActivatingNode,
quorum.isReplicatingActivation,
message.configID,
quorum.configID);
return;
}
if (!quorum.isWatchingPaxosID)
{
Log_Message("Activating shard server %U in quorum %U: Starting to monitor the primary's paxosID",
quorum.quorumID, quorum.activatingNodeID);
quorum.OnActivationMonitoring(message.paxosID);
configServer->OnConfigStateChanged();
}
else
{
Log_Trace();
// if the primary was able to increase its paxosID, the new shardserver joined successfully
if (message.paxosID > quorum.activationPaxosID)
{
Log_Message("Activating shard server %U in quorum %U: The primary was able to increase its paxosID!",
quorum.quorumID, quorum.activatingNodeID);
quorum.OnActivationReplication();
configServer->OnConfigStateChanged();
configServer->GetQuorumProcessor()->ActivateNode(quorum.quorumID, quorum.activatingNodeID);
}
else
{
Log_Message("Activating shard server %U in quorum %U: The primary was not able to increase its paxosID so far...",
quorum.quorumID, quorum.activatingNodeID);
}
}
}
void ConfigActivationManager::OnActivationTimeout()
{
uint64_t now;
ConfigState* configState;
ConfigQuorum* itQuorum;
ConfigShardServer* shardServer;
Log_Trace();
now = EventLoop::Now();
configState = configServer->GetDatabaseManager()->GetConfigState();
FOREACH(itQuorum, configState->quorums)
{
if (itQuorum->activationExpireTime > 0 && itQuorum->activationExpireTime < now)
{
// stop activation
assert(itQuorum->isActivatingNode == true);
assert(itQuorum->isReplicatingActivation == false);
shardServer = configState->GetShardServer(itQuorum->activatingNodeID);
assert(shardServer != NULL);
Log_Message("Activating shard server %U in quorum %U: Activation failed...",
itQuorum->activatingNodeID, itQuorum->quorumID);
itQuorum->ClearActivation();
configServer->OnConfigStateChanged();
}
}
UpdateTimeout();
}
void ConfigActivationManager::UpdateTimeout()
{
ConfigQuorum* it;
uint64_t activationExpireTime;
Log_Trace();
activationExpireTime = 0;
FOREACH(it, configServer->GetDatabaseManager()->GetConfigState()->quorums)
{
if (it->isActivatingNode && !it->isReplicatingActivation)
{
if (activationExpireTime == 0 || it->activationExpireTime < activationExpireTime)
activationExpireTime = it->activationExpireTime;
}
}
if (activationExpireTime > 0)
{
activationTimeout.SetExpireTime(activationExpireTime);
EventLoop::Reset(&activationTimeout);
}
}
<|endoftext|>
|
<commit_before>#include "itkPNGImageIO.h"
#include "itkRawImageIO.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCannySegmentationLevelSetImageFilter.h"
#include "itkCastImageFilter.h"
#include <iostream>
extern "C" {
#include <stdio.h>
}
int main(int argc, char *argv[]) {
// Test for command line arguments.
if (argc != 14)
{
std::cerr << "Usage: " << argv[0]
<< " input_image input_model output_model output_features iterations max_rms_change threshold variance propagation_scaling advection_scaling curvature_scaling isovalue negative_features"
<< std::endl;
return 1;
}
// Grab the number of iterations and conductance term
int iterations;
int negative_features=0;
float max_rms_change, threshold, outside_value, variance;
float propagation_scaling, advection_scaling, curvature_scaling, isovalue;
::sscanf(argv[5], "%d", &iterations);
::sscanf(argv[6], "%f", &max_rms_change);
::sscanf(argv[7], "%f", &threshold);
::sscanf(argv[8], "%f", &variance);
::sscanf(argv[9], "%f", &propagation_scaling);
::sscanf(argv[10], "%f", &advection_scaling);
::sscanf(argv[11], "%f", &curvature_scaling);
::sscanf(argv[12], "%f", &isovalue);
::sscanf(argv[13], "%d", &negative_features);
// Convenient typedefs
typedef itk::Image<float, 2> RealImageType;
typedef itk::Image<unsigned char, 2> CharImageType;
typedef itk::CastImageFilter<CharImageType, RealImageType> CastToRealFilterType;
typedef itk::CannySegmentationLevelSetImageFilter<CharImageType, RealImageType>
SegmentationFilterType;
typedef SegmentationFilterType::VectorImageType VectorImageType;
// Create a file IO object for reading PNG.
itk::PNGImageIO::Pointer io = itk::PNGImageIO::New();
io->SetNumberOfDimensions(2);
// Create a file IO object for writing raw floats
itk::RawImageIO<float, 2>::Pointer raw_io = itk::RawImageIO<float,2>::New();
raw_io->SetFileDimensionality(2);
raw_io->SetByteOrderToBigEndian();
// Create two file readers
itk::ImageFileReader<CharImageType>::Pointer seed_reader
= itk::ImageFileReader<CharImageType>::New();
itk::ImageFileReader<CharImageType>::Pointer feature_reader
= itk::ImageFileReader<CharImageType>::New();
seed_reader->SetImageIO(io);
seed_reader->SetFileName(argv[2]);
feature_reader->SetImageIO(io);
feature_reader->SetFileName(argv[1]);
// Create two file writers
itk::ImageFileWriter<RealImageType>::Pointer model_writer
= itk::ImageFileWriter<RealImageType>::New();
itk::ImageFileWriter<RealImageType>::Pointer feature_writer
= itk::ImageFileWriter<RealImageType>::New();
feature_writer->SetImageIO(raw_io);
feature_writer->SetFileName(argv[4]);
model_writer->SetImageIO(raw_io);
model_writer->SetFileName(argv[3]);
// Create the casting filters
CastToRealFilterType::Pointer to_real = CastToRealFilterType::New();
// Create the segmentation filter
SegmentationFilterType::Pointer segmentation = SegmentationFilterType::New();
segmentation->SetMaximumIterations(iterations);
segmentation->SetMaximumRMSError(max_rms_change);
segmentation->SetPropagationScaling(propagation_scaling);
segmentation->SetAdvectionScaling(advection_scaling);
segmentation->SetCurvatureScaling(curvature_scaling);
segmentation->SetIsoSurfaceValue(isovalue);
segmentation->SetThreshold(threshold);
segmentation->SetVariance(variance);
if (negative_features != 0)
{
segmentation->SetUseNegativeFeatures(true);
}
// Connect the pipeline
to_real->SetInput(feature_reader->GetOutput());
segmentation->SetInput(seed_reader->GetOutput());
model_writer->SetInput(segmentation->GetOutput());
// Execute the pipeline
try {
// to_real->Update(); // In the future, the feature image will be a proper
// input to the segmenation filter and this step will
// not be necessary.
segmentation->SetFeatureImage(to_real->GetOutput());
model_writer->Write();
feature_writer->SetInput(segmentation->GetSpeedImage());
feature_writer->Write();
}
catch(itk::ExceptionObject &e)
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
return 0;
}
<commit_msg>FIX: Warning fix on IRIX and Solaris<commit_after>#include "itkPNGImageIO.h"
#include "itkRawImageIO.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCannySegmentationLevelSetImageFilter.h"
#include "itkCastImageFilter.h"
#include <iostream>
extern "C" {
#include <stdio.h>
}
int main(int argc, char *argv[]) {
// Test for command line arguments.
if (argc != 14)
{
std::cerr << "Usage: " << argv[0]
<< " input_image input_model output_model output_features iterations max_rms_change threshold variance propagation_scaling advection_scaling curvature_scaling isovalue negative_features"
<< std::endl;
return 1;
}
// Grab the number of iterations and conductance term
int iterations;
int negative_features=0;
float max_rms_change, threshold, variance;
float propagation_scaling, advection_scaling, curvature_scaling, isovalue;
::sscanf(argv[5], "%d", &iterations);
::sscanf(argv[6], "%f", &max_rms_change);
::sscanf(argv[7], "%f", &threshold);
::sscanf(argv[8], "%f", &variance);
::sscanf(argv[9], "%f", &propagation_scaling);
::sscanf(argv[10], "%f", &advection_scaling);
::sscanf(argv[11], "%f", &curvature_scaling);
::sscanf(argv[12], "%f", &isovalue);
::sscanf(argv[13], "%d", &negative_features);
// Convenient typedefs
typedef itk::Image<float, 2> RealImageType;
typedef itk::Image<unsigned char, 2> CharImageType;
typedef itk::CastImageFilter<CharImageType, RealImageType> CastToRealFilterType;
typedef itk::CannySegmentationLevelSetImageFilter<CharImageType, RealImageType>
SegmentationFilterType;
typedef SegmentationFilterType::VectorImageType VectorImageType;
// Create a file IO object for reading PNG.
itk::PNGImageIO::Pointer io = itk::PNGImageIO::New();
io->SetNumberOfDimensions(2);
// Create a file IO object for writing raw floats
itk::RawImageIO<float, 2>::Pointer raw_io = itk::RawImageIO<float,2>::New();
raw_io->SetFileDimensionality(2);
raw_io->SetByteOrderToBigEndian();
// Create two file readers
itk::ImageFileReader<CharImageType>::Pointer seed_reader
= itk::ImageFileReader<CharImageType>::New();
itk::ImageFileReader<CharImageType>::Pointer feature_reader
= itk::ImageFileReader<CharImageType>::New();
seed_reader->SetImageIO(io);
seed_reader->SetFileName(argv[2]);
feature_reader->SetImageIO(io);
feature_reader->SetFileName(argv[1]);
// Create two file writers
itk::ImageFileWriter<RealImageType>::Pointer model_writer
= itk::ImageFileWriter<RealImageType>::New();
itk::ImageFileWriter<RealImageType>::Pointer feature_writer
= itk::ImageFileWriter<RealImageType>::New();
feature_writer->SetImageIO(raw_io);
feature_writer->SetFileName(argv[4]);
model_writer->SetImageIO(raw_io);
model_writer->SetFileName(argv[3]);
// Create the casting filters
CastToRealFilterType::Pointer to_real = CastToRealFilterType::New();
// Create the segmentation filter
SegmentationFilterType::Pointer segmentation = SegmentationFilterType::New();
segmentation->SetMaximumIterations(iterations);
segmentation->SetMaximumRMSError(max_rms_change);
segmentation->SetPropagationScaling(propagation_scaling);
segmentation->SetAdvectionScaling(advection_scaling);
segmentation->SetCurvatureScaling(curvature_scaling);
segmentation->SetIsoSurfaceValue(isovalue);
segmentation->SetThreshold(threshold);
segmentation->SetVariance(variance);
if (negative_features != 0)
{
segmentation->SetUseNegativeFeatures(true);
}
// Connect the pipeline
to_real->SetInput(feature_reader->GetOutput());
segmentation->SetInput(seed_reader->GetOutput());
model_writer->SetInput(segmentation->GetOutput());
// Execute the pipeline
try {
// to_real->Update(); // In the future, the feature image will be a proper
// input to the segmenation filter and this step will
// not be necessary.
segmentation->SetFeatureImage(to_real->GetOutput());
model_writer->Write();
feature_writer->SetInput(segmentation->GetSpeedImage());
feature_writer->Write();
}
catch(itk::ExceptionObject &e)
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef _EXAMPLES__BORIS__BORIS_SWEEPER__HPP_
#define _EXAMPLES__BORIS__BORIS_SWEEPER__HPP_
#include <cstdlib>
#include <map>
#include <cassert>
#include <pfasst/encap/encap_sweeper.hpp>
#include "particle_2d.hpp"
#include "physics.hpp"
using namespace std;
using namespace pfasst;
using namespace pfasst::encap;
typedef map<pair<size_t, size_t>, double> error_map;
template<
typename scalar,
typename time = time_precision
>
class BorisSweeper
: public EncapSweeper<time>
{
public:
typedef Particle2DEncapsulation<scalar, time> encap_type;
typedef Particle2DFactory<scalar, time> factory_type;
typedef ElectricField<scalar, time, Particle2DEncapsulation> e_field_type;
typedef MagneticField<scalar, time, Particle2DEncapsulation> b_field_type;
private:
shared_ptr<e_field_type> e_field;
shared_ptr<b_field_type> b_field;
error_map errors;
protected:
vector<shared_ptr<encap_type>> particles;
public:
//! @{
BorisSweeper()
: e_field(nullptr)
, b_field(nullptr)
, errors()
{}
BorisSweeper(const BorisSweeper<scalar, time>& other) = delete;
BorisSweeper(BorisSweeper<scalar, time>&& other) = delete;
virtual ~BorisSweeper()
{}
//! @}
//! @{
virtual void set_state(shared_ptr<const Encapsulation<time>> u0, size_t m) override
{
shared_ptr<const encap_type> u0_cast = dynamic_pointer_cast<const encap_type>(u0);
assert(u0_cast);
this->set_state(u0_cast, m);
}
virtual void set_state(shared_ptr<const encap_type> u0, size_t m)
{
UNUSED(u0); UNUSED(m);
// TODO: implement set_state for BorisSweeper
}
virtual shared_ptr<Encapsulation<time>> get_state(size_t m) const override
{
UNUSED(m);
// TODO: implement get_state for BorisSweeper
return NULL;
}
virtual shared_ptr<Encapsulation<time>> get_tau(size_t m) const override
{
UNUSED(m);
// TODO: implement get_tau for BorisSweeper
return NULL;
}
virtual shared_ptr<Encapsulation<time>> get_saved_state(size_t m) const override
{
UNUSED(m);
// TODO: implement get_saved_state for BorisSweeper
return NULL;
}
//! @}
//! @{
virtual void set_e_field(shared_ptr<const e_field_type> e_field)
{
this->e_field = const_pointer_cast<e_field_type>(e_field);
}
virtual shared_ptr<e_field_type> get_e_field()
{
return this->e_field;
}
virtual void set_b_field(shared_ptr<const b_field_type> b_field)
{
this->b_field = const_pointer_cast<b_field_type>(b_field);
}
virtual shared_ptr<b_field_type> get_b_field()
{
return this->b_field;
}
//! @}
//! @{
virtual void exact(shared_ptr<Encapsulation<time>> q, time t)
{
shared_ptr<encap_type> q_cast = dynamic_pointer_cast<encap_type>(q);
assert(q_cast);
this->exact(q_cast, t);
}
virtual void exact(shared_ptr<encap_type> q, time t)
{
UNUSED(q); UNUSED(t);
// TODO: implement exact solution for Boris
}
virtual void echo_error(time t, bool predict = false) const
{
UNUSED(t); UNUSED(predict);
// TODO: implement echo_error
}
virtual error_map get_errors() const
{
return this->errors;
}
//! @}
//! @{
virtual void setup(bool coarse = false) override
{
UNUSED(coarse);
// TODO: implement setup for BorisSweeper
}
virtual void advance() override
{
// TODO: implement advance for BorisSweeper
}
virtual void evaluate(size_t m) override
{
UNUSED(m);
// TODO: implement evaluate for BorisSweeper
}
virtual void predict(bool initial) override
{
UNUSED(initial);
// TODO: implement predict for BorisSweeper
}
virtual void sweep() override
{
// TODO: implement sweep for BorisSweeper
}
virtual void save(bool initial_only=false) override
{
UNUSED(initial_only);
// TODO: implement save for BorisSweeper
}
virtual void spread() override
{
// TODO: implement spread for BorisSweeper
}
//! @}
//! @{
virtual void post(ICommunicator* comm, int tag) override
{
UNUSED(comm); UNUSED(tag);
};
virtual void send(ICommunicator* comm, int tag, bool blocking) override
{
UNUSED(comm); UNUSED(tag); UNUSED(blocking);
NotImplementedYet("pfasst");
}
virtual void recv(ICommunicator* comm, int tag, bool blocking) override
{
UNUSED(comm); UNUSED(tag); UNUSED(blocking);
NotImplementedYet("pfasst");
}
virtual void broadcast(ICommunicator* comm) override
{
UNUSED(comm);
NotImplementedYet("pfasst");
}
//! @}
};
#endif // _EXAMPLES__BORIS__BORIS_SWEEPER__HPP_
<commit_msg>examples: boris: first compiling version of Boris impl_solve<commit_after>#ifndef _EXAMPLES__BORIS__BORIS_SWEEPER__HPP_
#define _EXAMPLES__BORIS__BORIS_SWEEPER__HPP_
#include <cstdlib>
#include <vector>
#include <map>
#include <cassert>
#include <boost/numeric/ublas/matrix.hpp>
using boost::numeric::ublas::matrix;
#include <pfasst/encap/encap_sweeper.hpp>
#include "particle.hpp"
#include "particle_3d.hpp"
#include "physics.hpp"
using namespace std;
using namespace pfasst;
using namespace pfasst::encap;
typedef map<pair<size_t, size_t>, double> error_map;
template<
typename scalar,
typename time = time_precision
>
class BorisSweeper
: public EncapSweeper<time>
{
public:
typedef Particle3DEncapsulation<scalar, time> encap_type;
typedef typename encap_type::position_type position_type;
typedef typename encap_type::velocity_type velocity_type;
typedef typename encap_type::acceleration_type acceleration_type;
typedef Particle3DFactory<scalar, time> factory_type;
typedef ElectricField<scalar, time, Particle3DEncapsulation> e_field_type;
typedef MagneticField<scalar, time, Particle3DEncapsulation> b_field_type;
private:
shared_ptr<e_field_type> e_field;
shared_ptr<b_field_type> b_field;
error_map errors;
protected:
vector<shared_ptr<encap_type>> particles;
vector<shared_ptr<encap_type>> previous_particles;
vector<shared_ptr<encap_type>> tau_corrections;
vector<shared_ptr<velocity_type>> s_integrals;
vector<shared_ptr<position_type>> ss_integrals;
//! delta_nodes[m] = nodes[m] - nodes[m-1]
vector<time> delta_nodes;
matrix<time> s_mat;
matrix<time> ss_mat;
matrix<time> qx_mat;
matrix<time> qt_mat;
public:
//! @{
BorisSweeper()
: e_field(nullptr)
, b_field(nullptr)
, errors()
{}
BorisSweeper(const BorisSweeper<scalar, time>& other) = delete;
BorisSweeper(BorisSweeper<scalar, time>&& other) = delete;
virtual ~BorisSweeper()
{}
//! @}
//! @{
virtual void set_nodes(vector<time> nodes) override
{
EncapSweeper<time>::set_nodes(nodes);
// compute delta nodes
size_t nnodes = this->nodes.size();
this->delta_nodes = vector<time>(nnodes, time(0.0));
for (size_t m = 1; m < nnodes; m++) {
delta_nodes[m] = nodes[m] - nodes[m - 1];
}
}
virtual void set_state(shared_ptr<const Encapsulation<time>> u0, size_t m) override
{
shared_ptr<const encap_type> u0_cast = dynamic_pointer_cast<const encap_type>(u0);
assert(u0_cast);
this->set_state(u0_cast, m);
}
virtual void set_state(shared_ptr<const encap_type> u0, size_t m)
{
this->particles[m]->copy(u0);
}
virtual shared_ptr<Encapsulation<time>> get_state(size_t m) const override
{
return this->particles[m];
}
virtual shared_ptr<Encapsulation<time>> get_tau(size_t m) const override
{
return this->tau_corrections[m];
}
virtual shared_ptr<Encapsulation<time>> get_saved_state(size_t m) const override
{
return this->previous_particles[m];
}
//! @}
//! @{
virtual void set_e_field(shared_ptr<const e_field_type> e_field)
{
this->e_field = const_pointer_cast<e_field_type>(e_field);
}
virtual shared_ptr<e_field_type> get_e_field()
{
return this->e_field;
}
virtual void set_b_field(shared_ptr<const b_field_type> b_field)
{
this->b_field = const_pointer_cast<b_field_type>(b_field);
}
virtual shared_ptr<b_field_type> get_b_field()
{
return this->b_field;
}
//! @}
//! @{
virtual void exact(shared_ptr<Encapsulation<time>> q, time t)
{
shared_ptr<encap_type> q_cast = dynamic_pointer_cast<encap_type>(q);
assert(q_cast);
this->exact(q_cast, t);
}
virtual void exact(shared_ptr<encap_type> q, time t)
{
UNUSED(q); UNUSED(t);
// TODO: implement exact solution for Boris
}
virtual void echo_error(time t, bool predict = false) const
{
UNUSED(t); UNUSED(predict);
// TODO: implement echo_error
}
virtual error_map get_errors() const
{
return this->errors;
}
//! @}
//! @{
virtual void setup(bool coarse = false) override
{
vector<time> nodes = this->get_nodes();
auto is_proper = this->get_is_proper();
assert(nodes.size() >= 1);
size_t nnodes = nodes.size();
matrix<time> q_mat = compute_quadrature(nodes, nodes, is_proper, QuadratureMatrix::Q);
assert(q_mat.size1() == q_mat.size2());
matrix<time> qq_mat = matrix<time>(nnodes, nnodes, time(0.0));
this->s_mat = matrix<time>(nnodes, nnodes, time(0.0));
this->qt_mat = matrix<time>(nnodes, nnodes, time(0.0));
this->qx_mat = matrix<time>(nnodes, nnodes, time(0.0));
this->ss_mat = matrix<time>(nnodes, nnodes, time(0.0));
// compute QQ, S, SS, Q_T, Q_x
// building rules for Q_E and Q_I:
// Q_E is striclty lower diagonal matrix with delta nodes of column index
// Q_I is lower diagonal matrix with first row and column all zero and delta nodes of
// column index minus one
// TODO: should use Boost's matrix product function here sometime
for (size_t i = 0; i < nnodes; i++) {
for (size_t j = 0; i < nnodes; j++) {
// Q_T = 0.5 * (Q_E + Q_I)
this->s_mat(i, j) = q_mat(i, j) - ((i > 0) ? q_mat(i - 1, j) : time(0.0));
this->qt_mat(i, j) = time(0.5) * (((j < i) ? delta_nodes[j + 1] : time(0.0)) +
((j > 0 && j <= i) ? delta_nodes[j + 1] : time(0.0)));
for (size_t k = 0; k < nnodes; k++) {
qq_mat(i, j) += q_mat(i, k) * q_mat(k, j);
// Q_x = Q_E * Q_T + 0.5 * (Q_E ∘ Q_E)
// (only first term, i.e. matrix product)
this->qx_mat(i, j) += ((k < i) ? delta_nodes[k + 1] : time(0.0)) * this->qt_mat(k, j);
}
// continuation of Q_x
// (i.e. Hadamard product of Q_E)
this->qx_mat(i, j) += 0.5 * ((j < i) ? delta_nodes[j + 1] * delta_nodes[j + 1] : time(0.0));
this->ss_mat(i, j) = qq_mat(i, j) - ((i > 0) ? qq_mat(i - 1, j) : time(0.0));
}
}
UNUSED(coarse);
// TODO: implement setup for BorisSweeper
}
virtual void advance() override
{
this->particles[0]->copy(const_pointer_cast<const encap_type>(this->particles.back()));
}
virtual void evaluate(size_t m) override
{
UNUSED(m);
// TODO: implement evaluate for BorisSweeper
}
virtual void predict(bool initial) override
{
UNUSED(initial);
// TODO: implement predict for BorisSweeper
}
virtual void sweep() override
{
const auto nodes = this->get_nodes();
const size_t nnodes = nodes.size();
assert(nnodes >= 1);
velocity_type c_k_term;
// compute integrals
for (size_t m = 1; m < nnodes; m++) {
this->s_integrals[m]->zero();
this->ss_integrals[m]->zero();
for (size_t l = 1; l < nnodes; l++) {
*(this->s_integrals[l].get()) += this->previous_particles[l]
->accel->convert(dt<time>(this->s_mat(m, l)));
*(this->ss_integrals[l].get()) += this->previous_particles[l]
->accel->convert(dtdt<time>(this->ss_mat(m, l)));
}
}
for (size_t m = 0; m < nnodes - 1; m++) {
::dt<time> dt(this->delta_nodes[m+1]);
//// Update Position (explicit)
//
// x_{m+1}^{k+1} = x_{m}^{k}
this->particles[m+1]->pos->copy(this->particles[m]->const_pos());
// + delta_nodes_{m} * v_{0}
*(this->particles[m+1]->pos.get()) += this->particles[0]->vel->convert(dt);
// + \sum_{l=1}^{m} s_{m+1,l}^{x} (f_{l}^{k+1} - f_{l}^{k})
for (size_t l = 1; l < m; l++) {
*(this->particles[m+1]->pos.get()) += this->particles[l]->accel
->convert(dtdt<time>(this->qx_mat(m+1, l)));
this->particles[m+1]->pos->saxpy(-1.0,
this->previous_particles[l]->accel
->convert(dtdt<time>(this->qx_mat(m+1,l))));
}
// + ss_integral[m]
for (size_t l = 1; l < nnodes; l++) {
*(this->particles[m+1]->pos.get()) += this->ss_integrals[l];
}
//// Update Velocity (semi-implicit)
//
c_k_term.zero(); // reset
// - delta_nodes_{m} / 2 * f_{m+1}^{k}
c_k_term.saxpy(-0.5, this->previous_particles[m+1]->accel->convert(dt));
// - delta_nodes_{m} / 2 * f_{m}^{k}
c_k_term.saxpy(-0.5, this->previous_particles[m]->accel->convert(dt));
// + s_integral[m]
for (size_t l = 1; l < nnodes; l++) {
c_k_term += this->s_integrals[l];
}
// doing Boris' magic
this->boris_solve(nodes[m], nodes[m+1], dt, m, c_k_term);
}
}
virtual void save(bool initial_only=false) override
{
if (initial_only) {
this->previous_particles[0]->copy(const_pointer_cast<const encap_type>(this->particles[0]));
} else {
for (size_t m = 0; m < this->previous_particles.size(); m++) {
this->previous_particles[m]->copy(const_pointer_cast<const encap_type>(this->particles[m]));
}
}
}
virtual void spread() override
{
// TODO: implement spread for BorisSweeper
}
//! @}
//! @{
virtual void post(ICommunicator* comm, int tag) override
{
UNUSED(comm); UNUSED(tag);
};
virtual void send(ICommunicator* comm, int tag, bool blocking) override
{
UNUSED(comm); UNUSED(tag); UNUSED(blocking);
NotImplementedYet("pfasst");
}
virtual void recv(ICommunicator* comm, int tag, bool blocking) override
{
UNUSED(comm); UNUSED(tag); UNUSED(blocking);
NotImplementedYet("pfasst");
}
virtual void broadcast(ICommunicator* comm) override
{
UNUSED(comm);
NotImplementedYet("pfasst");
}
//! @}
//! @{
virtual void boris_solve(const time tm, const time t_next, const ::dt<time> dt, const size_t m,
const velocity_type& c_k_term)
{
velocity_type c_k_term_half(scalar(0.5) * c_k_term);
::dt<time> beta(this->particles[m]->charge * dt.v / (scalar(2.0) * this->particles[m]->mass));
acceleration_type e_mean = (this->e_field->evaluate(this->particles[m], tm)
- this->e_field->evaluate(this->particles[m+1], tm))
* scalar(0.5);
// v^{-} = v^{k}
velocity_type v_minus(this->particles[m]->const_vel());
// first Boris' drift
// + \beta * E_{mean} + c^{k} / 2
v_minus += e_mean.convert(beta) + c_k_term_half;
// Boris' kick
velocity_type boris_t = this->b_field->evaluate(this->particles[m], t_next).convert(beta);
velocity_type boris_s = (scalar(2.0) * boris_t) / (scalar(1.0) + (boris_t * boris_t));
velocity_type v_prime(v_minus + boris_t * v_minus);
// final Boris' drift
velocity_type v_plus(v_minus + v_prime * boris_s);
this->particles[m+1]->vel->copy(v_plus + e_mean.convert(beta) + c_k_term_half);
}
//! @}
};
#endif // _EXAMPLES__BORIS__BORIS_SWEEPER__HPP_
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "xercesc.h"
using namespace std;
using namespace xercesc;
namespace foundation
{
//
// XercesCManager class implementation.
//
boost::mutex XercesCManager::s_mutex;
bool XercesCManager::initialize()
{
boost::mutex::scoped_lock lock(s_mutex);
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException&)
{
return false;
}
return true;
}
bool XercesCManager::initialize(Logger& logger)
{
boost::mutex::scoped_lock lock(s_mutex);
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& e)
{
LOG_ERROR(
logger,
"failed to initialize Xerces-C++ library: %s.",
transcode(e.getMessage()).c_str());
return false;
}
return true;
}
void XercesCManager::terminate()
{
boost::mutex::scoped_lock lock(s_mutex);
XMLPlatformUtils::Terminate();
}
//
// XercesCContext class implementation.
//
XercesCContext::XercesCContext()
{
m_initialized = XercesCManager::initialize();
}
XercesCContext::XercesCContext(Logger& logger)
{
m_initialized = XercesCManager::initialize(logger);
}
XercesCContext::~XercesCContext()
{
XercesCManager::terminate();
}
bool XercesCContext::is_initialized() const
{
return m_initialized;
}
//
// ErrorLogger class implementation.
//
ErrorLogger::ErrorLogger(
Logger& logger,
const string& input_filename)
: m_logger(logger)
, m_input_filename(input_filename)
{
resetErrors();
}
void ErrorLogger::resetErrors()
{
m_warning_count = 0;
m_error_count = 0;
m_fatal_error_count = 0;
}
void ErrorLogger::warning(const SAXParseException& e)
{
++m_warning_count;
print(LogMessage::Warning, e);
}
void ErrorLogger::error(const SAXParseException& e)
{
++m_error_count;
print(LogMessage::Error, e);
}
void ErrorLogger::fatalError(const SAXParseException& e)
{
++m_fatal_error_count;
#ifndef WITH_EXTERNAL_XERCES
switch (e.getOriginalExceptionCode())
{
// Using our modified version of Xerces-C++, we can catch the case where
// it failed to open the input file, and print a reasonable error message.
case XMLExcepts::Scan_CouldNotOpenSource:
LOG_ERROR(
m_logger,
"failed to open %s for reading.",
m_input_filename.c_str());
break;
// For now, all other errors will be reported as is.
default:
print(LogMessage::Error, e);
break;
}
#else
print(LogMessage::Error, e);
#endif
}
size_t ErrorLogger::get_warning_count() const
{
return m_warning_count;
}
size_t ErrorLogger::get_error_count() const
{
return m_error_count;
}
size_t ErrorLogger::get_fatal_error_count() const
{
return m_fatal_error_count;
}
void ErrorLogger::print(
const LogMessage::Category category,
const SAXParseException& e) const
{
LOG(
m_logger,
category,
"while reading %s: %s.",
m_input_filename.c_str(),
transcode(e.getMessage()).c_str());
}
} // namespace foundation
<commit_msg>fixed formatting.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "xercesc.h"
using namespace std;
using namespace xercesc;
namespace foundation
{
//
// XercesCManager class implementation.
//
boost::mutex XercesCManager::s_mutex;
bool XercesCManager::initialize()
{
boost::mutex::scoped_lock lock(s_mutex);
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException&)
{
return false;
}
return true;
}
bool XercesCManager::initialize(Logger& logger)
{
boost::mutex::scoped_lock lock(s_mutex);
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& e)
{
LOG_ERROR(
logger,
"failed to initialize Xerces-C++ library: %s.",
transcode(e.getMessage()).c_str());
return false;
}
return true;
}
void XercesCManager::terminate()
{
boost::mutex::scoped_lock lock(s_mutex);
XMLPlatformUtils::Terminate();
}
//
// XercesCContext class implementation.
//
XercesCContext::XercesCContext()
{
m_initialized = XercesCManager::initialize();
}
XercesCContext::XercesCContext(Logger& logger)
{
m_initialized = XercesCManager::initialize(logger);
}
XercesCContext::~XercesCContext()
{
XercesCManager::terminate();
}
bool XercesCContext::is_initialized() const
{
return m_initialized;
}
//
// ErrorLogger class implementation.
//
ErrorLogger::ErrorLogger(
Logger& logger,
const string& input_filename)
: m_logger(logger)
, m_input_filename(input_filename)
{
resetErrors();
}
void ErrorLogger::resetErrors()
{
m_warning_count = 0;
m_error_count = 0;
m_fatal_error_count = 0;
}
void ErrorLogger::warning(const SAXParseException& e)
{
++m_warning_count;
print(LogMessage::Warning, e);
}
void ErrorLogger::error(const SAXParseException& e)
{
++m_error_count;
print(LogMessage::Error, e);
}
void ErrorLogger::fatalError(const SAXParseException& e)
{
++m_fatal_error_count;
#ifndef WITH_EXTERNAL_XERCES
switch (e.getOriginalExceptionCode())
{
// Using our modified version of Xerces-C++, we can catch the case where
// it failed to open the input file, and print a reasonable error message.
case XMLExcepts::Scan_CouldNotOpenSource:
LOG_ERROR(
m_logger,
"failed to open %s for reading.",
m_input_filename.c_str());
break;
// For now, all other errors will be reported as is.
default:
print(LogMessage::Error, e);
break;
}
#else
print(LogMessage::Error, e);
#endif
}
size_t ErrorLogger::get_warning_count() const
{
return m_warning_count;
}
size_t ErrorLogger::get_error_count() const
{
return m_error_count;
}
size_t ErrorLogger::get_fatal_error_count() const
{
return m_fatal_error_count;
}
void ErrorLogger::print(
const LogMessage::Category category,
const SAXParseException& e) const
{
LOG(
m_logger,
category,
"while reading %s: %s.",
m_input_filename.c_str(),
transcode(e.getMessage()).c_str());
}
} // namespace foundation
<|endoftext|>
|
<commit_before>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 <ctkCmdLineModuleManager.h>
#include <ctkCmdLineModuleFrontendFactory.h>
#include <ctkCmdLineModuleFrontend.h>
#include <ctkCmdLineModuleReference.h>
#include <ctkCmdLineModuleDescription.h>
#include <ctkCmdLineModuleParameter.h>
#include <ctkCmdLineModuleRunException.h>
#include <ctkCmdLineModuleFuture.h>
#include <ctkCmdLineModuleFutureWatcher.h>
#include "ctkCmdLineModuleSignalTester.h"
#include "ctkCmdLineModuleBackendLocalProcess.h"
#include "ctkTest.h"
#include <QVariant>
#include <QCoreApplication>
#include <QDebug>
#include <QFutureWatcher>
//-----------------------------------------------------------------------------
class ctkCmdLineModuleFrontendMockupFactory : public ctkCmdLineModuleFrontendFactory
{
public:
virtual ctkCmdLineModuleFrontend* create(const ctkCmdLineModuleReference& moduleRef)
{
struct ModuleFrontendMockup : public ctkCmdLineModuleFrontend
{
ModuleFrontendMockup(const ctkCmdLineModuleReference& moduleRef)
: ctkCmdLineModuleFrontend(moduleRef) {}
virtual QObject* guiHandle() const { return NULL; }
virtual QVariant value(const QString& parameter, int role) const
{
Q_UNUSED(role)
QVariant value = currentValues[parameter];
if (!value.isValid())
return this->moduleReference().description().parameter(parameter).defaultValue();
return value;
}
virtual void setValue(const QString& parameter, const QVariant& value)
{
currentValues[parameter] = value;
}
private:
QHash<QString, QVariant> currentValues;
};
return new ModuleFrontendMockup(moduleRef);
}
virtual QString name() const { return "Mock-up"; }
virtual QString description() const { return "A mock-up factory for testing."; }
};
//-----------------------------------------------------------------------------
class ctkCmdLineModuleFutureTester : public QObject
{
Q_OBJECT
public Q_SLOTS:
void ouputDataReady();
void errorDataReady();
private Q_SLOTS:
void initTestCase();
void init();
void cleanup();
void testStartFinish();
void testProgress();
void testPauseAndCancel();
void testOutput();
void testError();
private:
QByteArray outputData;
QByteArray errorData;
ctkCmdLineModuleFutureWatcher* currentWatcher;
ctkCmdLineModuleFrontendMockupFactory factory;
ctkCmdLineModuleBackendLocalProcess backend;
ctkCmdLineModuleManager manager;
ctkCmdLineModuleReference moduleRef;
ctkCmdLineModuleFrontend* frontend;
};
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::ouputDataReady()
{
if (this->currentWatcher)
{
outputData.append(currentWatcher->readPendingOutputData());
}
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::errorDataReady()
{
if (this->currentWatcher)
{
errorData.append(currentWatcher->readPendingErrorData());
}
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::initTestCase()
{
manager.registerBackend(&backend);
QUrl moduleUrl = QUrl::fromLocalFile(QCoreApplication::applicationDirPath() + "/ctkCmdLineModuleTestBed");
moduleRef = manager.registerModule(moduleUrl);
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::init()
{
currentWatcher = 0;
frontend = factory.create(moduleRef);
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::cleanup()
{
delete frontend;
outputData.clear();
errorData.clear();
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::testStartFinish()
{
QList<QString> expectedSignals;
expectedSignals << "module.started"
<< "module.progressRangeChanged(0,0)"
<< "module.progressValueChanged(0)"
<< "module.progressRangeChanged(0,1000)"
<< "module.errorReady"
<< "module.progressValueChanged(1000)"
<< "module.finished";
ctkCmdLineModuleSignalTester signalTester;
ctkCmdLineModuleFuture future = manager.run(frontend);
signalTester.setFuture(future);
future.waitForFinished();
QCoreApplication::processEvents();
QVERIFY(signalTester.checkSignals(expectedSignals));
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::testProgress()
{
QList<QString> expectedSignals;
expectedSignals << "module.started"
// the following signals are send when connecting a QFutureWatcher to
// an already started QFuture
<< "module.progressRangeChanged(0,0)"
<< "module.progressValueChanged(0)"
<< "module.progressRangeChanged(0,1000)"
// the test module always reports error data when starting
<< "module.errorReady"
// the following two signals are send when the module reports "filter start"
<< "module.progressValueChanged(1)"
<< "module.progressTextChanged(Test Filter)"
// this signal is send when the module reports progress for "output1"
<< "module.progressValueChanged(999)"
// the output data (the order is not really deterministic here...)
<< "module.outputReady"
// the following signal is sent at the end to report completion
<< "module.progressValueChanged(1000)"
<< "module.finished";
ctkCmdLineModuleSignalTester signalTester;
frontend->setValue("numOutputsVar", 1);
ctkCmdLineModuleFuture future = manager.run(frontend);
signalTester.setFuture(future);
future.waitForFinished();
// process pending events
QCoreApplication::processEvents();
QVERIFY(signalTester.checkSignals(expectedSignals));
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::testPauseAndCancel()
{
ctkCmdLineModuleSignalTester signalTester;
frontend->setValue("runtimeVar", 60);
ctkCmdLineModuleFuture future = manager.run(frontend);
signalTester.setFuture(future);
QList<QString> expectedSignals;
expectedSignals << "module.started"
<< "module.progressRangeChanged(0,0)"
<< "module.progressValueChanged(0)"
<< "module.progressRangeChanged(0,1000)"
<< "module.errorReady";
if (future.canPause())
{
// Due to Qt bug 12152, these two signals are reversed
expectedSignals.push_back("module.resumed");
expectedSignals.push_back("module.paused");
}
if (future.canCancel())
{
expectedSignals.push_back("module.canceled");
}
expectedSignals.push_back("module.finished");
QTest::qWait(100);
future.pause();
QTest::qWait(100);
QVERIFY(future.isRunning());
if (future.canPause())
{
QVERIFY(future.isPaused());
}
future.togglePaused();
QTest::qWait(100);
QVERIFY(!future.isPaused());
QVERIFY(future.isRunning());
future.cancel();
future.waitForFinished();
// process pending events
QCoreApplication::processEvents();
QVERIFY(future.isCanceled());
QVERIFY(future.isFinished());
QVERIFY(signalTester.checkSignals(expectedSignals));
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::testOutput()
{
ctkCmdLineModuleSignalTester signalTester;
connect(signalTester.watcher(), SIGNAL(outputDataReady()), SLOT(ouputDataReady()));
connect(signalTester.watcher(), SIGNAL(errorDataReady()), SLOT(errorDataReady()));
this->currentWatcher = signalTester.watcher();
frontend->setValue("numOutputsVar", 2);
frontend->setValue("errorTextVar", "Final error msg.");
ctkCmdLineModuleFuture future = manager.run(frontend);
signalTester.setFuture(future);
future.waitForFinished();
// process pending events
QCoreApplication::processEvents();
QVERIFY(future.isFinished());
QList<QString> expectedSignals;
expectedSignals << "module.started"
<< "module.progressRangeChanged(0,0)"
<< "module.progressValueChanged(0)"
<< "module.progressRangeChanged(0,1000)"
<< "module.errorReady"
<< "module.progressValueChanged(1)"
<< "module.progressTextChanged(Test Filter)"
<< "module.progressValueChanged(500)"
<< "module.outputReady"
<< "module.progressValueChanged(999)"
<< "module.outputReady"
<< "module.errorReady"
<< "module.progressValueChanged(1000)"
<< "module.finished";
QVERIFY(signalTester.checkSignals(expectedSignals));
const char* expectedOutput = "Output 1\nOutput 2\n";
const char* expectedError = "A superficial error message.\nFinal error msg.";
QCOMPARE(this->outputData.data(), expectedOutput);
QCOMPARE(this->errorData.data(), expectedError);
QCOMPARE(future.readAllOutputData().data(), expectedOutput);
QCOMPARE(future.readAllErrorData().data(), expectedError);
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::testError()
{
frontend->setValue("fileVar", "output1");
frontend->setValue("exitCodeVar", 24);
frontend->setValue("errorTextVar", "Some error occured\n");
ctkCmdLineModuleFuture future = manager.run(frontend);
try
{
future.waitForFinished();
QFAIL("Expected exception not thrown.");
}
catch (const ctkCmdLineModuleRunException& e)
{
QVERIFY2(e.errorCode() == 24, "Test matching error code");
QCOMPARE(future.readAllErrorData().data(), "A superficial error message.\nSome error occured\n");
}
}
// ----------------------------------------------------------------------------
CTK_TEST_MAIN(ctkCmdLineModuleFutureTest)
#include "moc_ctkCmdLineModuleFutureTest.cpp"
<commit_msg>Avoid sending pause/resume signals if the future does not support it.<commit_after>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 <ctkCmdLineModuleManager.h>
#include <ctkCmdLineModuleFrontendFactory.h>
#include <ctkCmdLineModuleFrontend.h>
#include <ctkCmdLineModuleReference.h>
#include <ctkCmdLineModuleDescription.h>
#include <ctkCmdLineModuleParameter.h>
#include <ctkCmdLineModuleRunException.h>
#include <ctkCmdLineModuleFuture.h>
#include <ctkCmdLineModuleFutureWatcher.h>
#include "ctkCmdLineModuleSignalTester.h"
#include "ctkCmdLineModuleBackendLocalProcess.h"
#include "ctkTest.h"
#include <QVariant>
#include <QCoreApplication>
#include <QDebug>
#include <QFutureWatcher>
//-----------------------------------------------------------------------------
class ctkCmdLineModuleFrontendMockupFactory : public ctkCmdLineModuleFrontendFactory
{
public:
virtual ctkCmdLineModuleFrontend* create(const ctkCmdLineModuleReference& moduleRef)
{
struct ModuleFrontendMockup : public ctkCmdLineModuleFrontend
{
ModuleFrontendMockup(const ctkCmdLineModuleReference& moduleRef)
: ctkCmdLineModuleFrontend(moduleRef) {}
virtual QObject* guiHandle() const { return NULL; }
virtual QVariant value(const QString& parameter, int role) const
{
Q_UNUSED(role)
QVariant value = currentValues[parameter];
if (!value.isValid())
return this->moduleReference().description().parameter(parameter).defaultValue();
return value;
}
virtual void setValue(const QString& parameter, const QVariant& value)
{
currentValues[parameter] = value;
}
private:
QHash<QString, QVariant> currentValues;
};
return new ModuleFrontendMockup(moduleRef);
}
virtual QString name() const { return "Mock-up"; }
virtual QString description() const { return "A mock-up factory for testing."; }
};
//-----------------------------------------------------------------------------
class ctkCmdLineModuleFutureTester : public QObject
{
Q_OBJECT
public Q_SLOTS:
void ouputDataReady();
void errorDataReady();
private Q_SLOTS:
void initTestCase();
void init();
void cleanup();
void testStartFinish();
void testProgress();
void testPauseAndCancel();
void testOutput();
void testError();
private:
QByteArray outputData;
QByteArray errorData;
ctkCmdLineModuleFutureWatcher* currentWatcher;
ctkCmdLineModuleFrontendMockupFactory factory;
ctkCmdLineModuleBackendLocalProcess backend;
ctkCmdLineModuleManager manager;
ctkCmdLineModuleReference moduleRef;
ctkCmdLineModuleFrontend* frontend;
};
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::ouputDataReady()
{
if (this->currentWatcher)
{
outputData.append(currentWatcher->readPendingOutputData());
}
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::errorDataReady()
{
if (this->currentWatcher)
{
errorData.append(currentWatcher->readPendingErrorData());
}
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::initTestCase()
{
manager.registerBackend(&backend);
QUrl moduleUrl = QUrl::fromLocalFile(QCoreApplication::applicationDirPath() + "/ctkCmdLineModuleTestBed");
moduleRef = manager.registerModule(moduleUrl);
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::init()
{
currentWatcher = 0;
frontend = factory.create(moduleRef);
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::cleanup()
{
delete frontend;
outputData.clear();
errorData.clear();
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::testStartFinish()
{
QList<QString> expectedSignals;
expectedSignals << "module.started"
<< "module.progressRangeChanged(0,0)"
<< "module.progressValueChanged(0)"
<< "module.progressRangeChanged(0,1000)"
<< "module.errorReady"
<< "module.progressValueChanged(1000)"
<< "module.finished";
ctkCmdLineModuleSignalTester signalTester;
ctkCmdLineModuleFuture future = manager.run(frontend);
signalTester.setFuture(future);
future.waitForFinished();
QCoreApplication::processEvents();
QVERIFY(signalTester.checkSignals(expectedSignals));
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::testProgress()
{
QList<QString> expectedSignals;
expectedSignals << "module.started"
// the following signals are send when connecting a QFutureWatcher to
// an already started QFuture
<< "module.progressRangeChanged(0,0)"
<< "module.progressValueChanged(0)"
<< "module.progressRangeChanged(0,1000)"
// the test module always reports error data when starting
<< "module.errorReady"
// the following two signals are send when the module reports "filter start"
<< "module.progressValueChanged(1)"
<< "module.progressTextChanged(Test Filter)"
// this signal is send when the module reports progress for "output1"
<< "module.progressValueChanged(999)"
// the output data (the order is not really deterministic here...)
<< "module.outputReady"
// the following signal is sent at the end to report completion
<< "module.progressValueChanged(1000)"
<< "module.finished";
ctkCmdLineModuleSignalTester signalTester;
frontend->setValue("numOutputsVar", 1);
ctkCmdLineModuleFuture future = manager.run(frontend);
signalTester.setFuture(future);
future.waitForFinished();
// process pending events
QCoreApplication::processEvents();
QVERIFY(signalTester.checkSignals(expectedSignals));
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::testPauseAndCancel()
{
ctkCmdLineModuleSignalTester signalTester;
frontend->setValue("runtimeVar", 60);
ctkCmdLineModuleFuture future = manager.run(frontend);
signalTester.setFuture(future);
QList<QString> expectedSignals;
expectedSignals << "module.started"
<< "module.progressRangeChanged(0,0)"
<< "module.progressValueChanged(0)"
<< "module.progressRangeChanged(0,1000)"
<< "module.errorReady";
if (future.canPause())
{
// Due to Qt bug 12152, these two signals are reversed
expectedSignals.push_back("module.resumed");
expectedSignals.push_back("module.paused");
}
if (future.canCancel())
{
expectedSignals.push_back("module.canceled");
}
expectedSignals.push_back("module.finished");
QTest::qWait(100);
if (future.canPause())
{
future.pause();
QTest::qWait(100);
QVERIFY(future.isPaused());
}
QVERIFY(future.isRunning());
if (future.canPause())
{
future.togglePaused();
QTest::qWait(100);
}
QVERIFY(!future.isPaused());
QVERIFY(future.isRunning());
if (future.canCancel())
{
// give event processing a chance before killing the process
QTest::qWait(200);
future.cancel();
}
future.waitForFinished();
// process pending events
QCoreApplication::processEvents();
QVERIFY(future.isCanceled());
QVERIFY(future.isFinished());
QVERIFY(signalTester.checkSignals(expectedSignals));
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::testOutput()
{
ctkCmdLineModuleSignalTester signalTester;
connect(signalTester.watcher(), SIGNAL(outputDataReady()), SLOT(ouputDataReady()));
connect(signalTester.watcher(), SIGNAL(errorDataReady()), SLOT(errorDataReady()));
this->currentWatcher = signalTester.watcher();
frontend->setValue("numOutputsVar", 2);
frontend->setValue("errorTextVar", "Final error msg.");
ctkCmdLineModuleFuture future = manager.run(frontend);
signalTester.setFuture(future);
future.waitForFinished();
// process pending events
QCoreApplication::processEvents();
QVERIFY(future.isFinished());
QList<QString> expectedSignals;
expectedSignals << "module.started"
<< "module.progressRangeChanged(0,0)"
<< "module.progressValueChanged(0)"
<< "module.progressRangeChanged(0,1000)"
<< "module.errorReady"
<< "module.progressValueChanged(1)"
<< "module.progressTextChanged(Test Filter)"
<< "module.progressValueChanged(500)"
<< "module.outputReady"
<< "module.progressValueChanged(999)"
<< "module.outputReady"
<< "module.errorReady"
<< "module.progressValueChanged(1000)"
<< "module.finished";
QVERIFY(signalTester.checkSignals(expectedSignals));
const char* expectedOutput = "Output 1\nOutput 2\n";
const char* expectedError = "A superficial error message.\nFinal error msg.";
QCOMPARE(this->outputData.data(), expectedOutput);
QCOMPARE(this->errorData.data(), expectedError);
QCOMPARE(future.readAllOutputData().data(), expectedOutput);
QCOMPARE(future.readAllErrorData().data(), expectedError);
}
//-----------------------------------------------------------------------------
void ctkCmdLineModuleFutureTester::testError()
{
frontend->setValue("fileVar", "output1");
frontend->setValue("exitCodeVar", 24);
frontend->setValue("errorTextVar", "Some error occured\n");
ctkCmdLineModuleFuture future = manager.run(frontend);
try
{
future.waitForFinished();
QFAIL("Expected exception not thrown.");
}
catch (const ctkCmdLineModuleRunException& e)
{
QVERIFY2(e.errorCode() == 24, "Test matching error code");
QCOMPARE(future.readAllErrorData().data(), "A superficial error message.\nSome error occured\n");
}
}
// ----------------------------------------------------------------------------
CTK_TEST_MAIN(ctkCmdLineModuleFutureTest)
#include "moc_ctkCmdLineModuleFutureTest.cpp"
<|endoftext|>
|
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/SimpleObject.hpp"
#include <autowiring/AnySharedPointer.h>
#include <autowiring/autowiring.h>
class AnySharedPointerTest:
public testing::Test
{};
class MyUnusedClass {};
template<>
struct SharedPointerSlotT<MyUnusedClass>:
SharedPointerSlot
{
SharedPointerSlotT(const std::shared_ptr<MyUnusedClass>& rhs)
{
dtorStrike() = false;
}
~SharedPointerSlotT(void) {
dtorStrike() = true;
}
bool& dtorStrike(void) {
return (bool&) *m_space;
}
};
TEST_F(AnySharedPointerTest, OperatorEq) {
AutoRequired<SimpleObject> sobj;
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny1(sobj);
ASSERT_TRUE((bool)sobjAny1);
ASSERT_EQ(sobj, sobjAny1) << "An AnySharedPointer instance initialized by constructor violated an identity test";
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny2;
sobjAny2 = sobj;
ASSERT_TRUE((bool)sobjAny2);
ASSERT_EQ(sobj, sobjAny2) << "An AnySharedPointer instance initialized by assignment violated an identity test";
}
TEST_F(AnySharedPointerTest, SimpleDestructorStrike)
{
// We will need a buffer big enough for entire slot:
unsigned char buf[sizeof(SharedPointerSlotT<MyUnusedClass>)];
auto& mucSlot = *(SharedPointerSlotT<MyUnusedClass>*)buf;
// Placement new a basic shared pointer slot in the buffer:
SharedPointerSlot& slot = *new(buf) SharedPointerSlot;
// In-place polymorphism on the slot:
slot = std::make_shared<MyUnusedClass>();
// Destructor shouldn't be hit until we call it:
ASSERT_FALSE(mucSlot.dtorStrike()) << "Destructor was struck prematurely";
// Direct destructor call:
slot.~SharedPointerSlot();
// Verify we hit our dtor in the specialization we declared above:
ASSERT_TRUE(mucSlot.dtorStrike()) << "Virtual destructor on in-place polymorphic class was not hit as expected";
}
TEST_F(AnySharedPointerTest, AnySharedPointerRelease) {
auto t = std::make_shared<int>(5);
// Assign over, then reset
{
AnySharedPointer ptr;
ptr = t;
}
// Verify the AnySharedPointer destructor worked correctly
ASSERT_TRUE(t.unique()) << "AnySharedPointer instance did not properly release a reference when destroyed";
}
TEST_F(AnySharedPointerTest, SlotReassignment) {
auto sharedPointerA = std::make_shared<bool>();
auto sharedPointerB = std::make_shared<bool>();
auto sharedPointerC = std::make_shared<int>();
// Make our slot, and start off with a shared pointer of one type:
AnySharedPointer slot;
slot = sharedPointerA;
// Verify that the assignment worked as anticipated:
ASSERT_EQ(2, sharedPointerA.use_count()) << "Constructor did not properly addref a shared pointer on initialization";
// Recast to another shared pointer, verify reference count goes down:
slot = sharedPointerB;
ASSERT_EQ(2, sharedPointerB.use_count()) << "Reference count was not incremented properly during a shared pointer hold";
ASSERT_TRUE(sharedPointerA.unique()) << "Destructor was not properly invoked for a shared pointer slot";
// Now change the type completely, verify proper release:
slot = sharedPointerC;
ASSERT_TRUE(sharedPointerB.unique()) << "Second assigned shared pointer was not released under type transformation";
}
TEST_F(AnySharedPointerTest, SlotsInVector) {
auto sharedPtr = std::make_shared<bool>();
{
std::list<AnySharedPointer> slots;
// Initialize with a lot of copies of sharedPtr
for(size_t i = 0; i < 10; i++) {
slots.push_back(AnySharedPointer(sharedPtr));
ASSERT_EQ(1 + (long)slots.size(), sharedPtr.use_count()) << "Unexpected number of references to a slotted shared pointer";
}
}
// Now verify that we're unique again:
ASSERT_TRUE(sharedPtr.unique()) << "Slots in a vector did not properly release all local clones";
}
TEST_F(AnySharedPointerTest, SlotDuplication) {
auto sharedPtr = std::make_shared<bool>();
AnySharedPointer slot2;
{
// Create a base slot to hold the shared pointer:
AnySharedPointer slot1(sharedPtr);
ASSERT_FALSE(slot1->empty()) << "A slot initialized from a shared pointer was incorrectly marked as empty";
// Verify the type came across:
ASSERT_EQ(typeid(auto_id<bool>), slot1->type()) << "Dynamic initialization did not correctly adjust the dynamic type";
// Now copy it over:
slot2 = slot1;
// Verify reference count was affected as expected
ASSERT_EQ(3, sharedPtr.use_count()) << "A second-order slot copy didn't increment the reference count as expected";
}
// Verify that the slot still holds a reference and that the reference count is correct:
ASSERT_FALSE(slot2->empty()) << "A slot should have continued to hold a shared pointer, but was prematurely cleared";
ASSERT_EQ(2, sharedPtr.use_count()) << "A slot going out of scope did not correctly decrement a shared pointer reference";
}
TEST_F(AnySharedPointerTest, TrivialRelease) {
auto a = std::make_shared<bool>();
auto b = std::make_shared<int>();
// Assign the slot to two different values, and make sure that they are released properly
AnySharedPointer slot;
slot = a;
slot = b;
ASSERT_TRUE(a.unique()) << "Expected reassignment of a slot to release a formerly held instance";
ASSERT_FALSE(b.unique()) << "Expected slot to hold a reference to the second specified instance";
// Now release, and verify that a release actually took place
slot->reset();
ASSERT_TRUE(b.unique()) << "Releasing a slot did not actually release the held value as expected";
}
TEST_F(AnySharedPointerTest, NoMultipleDelete) {
auto a = std::make_shared<bool>();
std::weak_ptr<bool> b = a;
// Create a slot and validate the behavior of reset, and to ensure that the underlying
// SharedPointerSlot is not multiply deleted.
{
AnySharedPointer slot;
slot = a;
slot->reset();
}
// Now verify that we didn't accidentally overdecrement the count:
ASSERT_FALSE(b.expired()) << "Shared pointer prematurely expired; SharedPointerSlot dtor double-strike suspected";
}
TEST_F(AnySharedPointerTest, InitDerivesCorrectType) {
AnySharedPointer slot;
slot->init<int>();
ASSERT_EQ(typeid(auto_id<int>), slot->type()) << "A manually initialized slot did not have the expected type";
}
TEST_F(AnySharedPointerTest, VoidReturnExpected) {
// Fill out our slot:
auto v = std::make_shared<int>(5);
AnySharedPointer slot;
slot = v;
// Validate equivalence of the void operator:
ASSERT_EQ(v.get(), slot->ptr()) << "Shared pointer slot did not return a void* with an expected value";
}
TEST_F(AnySharedPointerTest, CanHoldCoreObject) {
auto co = std::make_shared<CoreObject>();
AnySharedPointer x = co;
ASSERT_EQ(co, x) << "Held CoreObject was not equivalent to constructed instance";
}
TEST_F(AnySharedPointerTest, CanFastCastToSelf) {
(void)autowiring::fast_pointer_cast_initializer<CoreObject, CoreObject>::sc_init;
auto co = std::make_shared<CoreObject>();
ASSERT_EQ(
co,
autowiring::fast_pointer_cast<CoreObject>(co)
) << "Could not cast a CoreObject instance to itself";
}<commit_msg>Add representational equivalence check<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/SimpleObject.hpp"
#include <autowiring/AnySharedPointer.h>
#include <autowiring/autowiring.h>
class AnySharedPointerTest:
public testing::Test
{};
// Autowiring takes advantage of the representational equivalence of instantiations of
// shared_ptr, and therefore requires that their layouts all be the same.
static_assert(
sizeof(std::shared_ptr<void*>) == sizeof(std::shared_ptr<int>),
"Shared pointer representations must be equivalent for casting to work correctly"
);
TEST_F(AnySharedPointerTest, CanReinterpretCastSharedPtr) {
auto iShared = std::make_shared<int>(101);
auto vShared = *reinterpret_cast<std::shared_ptr<void>*>(&iShared);
ASSERT_EQ(2UL, iShared.use_count()) << "Reinterpretive assignment of a void pointer did not increment the use count";
ASSERT_EQ(iShared.get(), vShared.get()) << "Reinterpreted shared pointer did not properly hold a member variable";
}
class MyUnusedClass {};
template<>
struct SharedPointerSlotT<MyUnusedClass>:
SharedPointerSlot
{
SharedPointerSlotT(const std::shared_ptr<MyUnusedClass>& rhs)
{
dtorStrike() = false;
}
~SharedPointerSlotT(void) {
dtorStrike() = true;
}
bool& dtorStrike(void) {
return (bool&) *m_space;
}
};
TEST_F(AnySharedPointerTest, OperatorEq) {
AutoRequired<SimpleObject> sobj;
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny1(sobj);
ASSERT_TRUE((bool)sobjAny1);
ASSERT_EQ(sobj, sobjAny1) << "An AnySharedPointer instance initialized by constructor violated an identity test";
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny2;
sobjAny2 = sobj;
ASSERT_TRUE((bool)sobjAny2);
ASSERT_EQ(sobj, sobjAny2) << "An AnySharedPointer instance initialized by assignment violated an identity test";
}
TEST_F(AnySharedPointerTest, SimpleDestructorStrike)
{
// We will need a buffer big enough for entire slot:
unsigned char buf[sizeof(SharedPointerSlotT<MyUnusedClass>)];
auto& mucSlot = *(SharedPointerSlotT<MyUnusedClass>*)buf;
// Placement new a basic shared pointer slot in the buffer:
SharedPointerSlot& slot = *new(buf) SharedPointerSlot;
// In-place polymorphism on the slot:
slot = std::make_shared<MyUnusedClass>();
// Destructor shouldn't be hit until we call it:
ASSERT_FALSE(mucSlot.dtorStrike()) << "Destructor was struck prematurely";
// Direct destructor call:
slot.~SharedPointerSlot();
// Verify we hit our dtor in the specialization we declared above:
ASSERT_TRUE(mucSlot.dtorStrike()) << "Virtual destructor on in-place polymorphic class was not hit as expected";
}
TEST_F(AnySharedPointerTest, AnySharedPointerRelease) {
auto t = std::make_shared<int>(5);
// Assign over, then reset
{
AnySharedPointer ptr;
ptr = t;
}
// Verify the AnySharedPointer destructor worked correctly
ASSERT_TRUE(t.unique()) << "AnySharedPointer instance did not properly release a reference when destroyed";
}
TEST_F(AnySharedPointerTest, SlotReassignment) {
auto sharedPointerA = std::make_shared<bool>();
auto sharedPointerB = std::make_shared<bool>();
auto sharedPointerC = std::make_shared<int>();
// Make our slot, and start off with a shared pointer of one type:
AnySharedPointer slot;
slot = sharedPointerA;
// Verify that the assignment worked as anticipated:
ASSERT_EQ(2, sharedPointerA.use_count()) << "Constructor did not properly addref a shared pointer on initialization";
// Recast to another shared pointer, verify reference count goes down:
slot = sharedPointerB;
ASSERT_EQ(2, sharedPointerB.use_count()) << "Reference count was not incremented properly during a shared pointer hold";
ASSERT_TRUE(sharedPointerA.unique()) << "Destructor was not properly invoked for a shared pointer slot";
// Now change the type completely, verify proper release:
slot = sharedPointerC;
ASSERT_TRUE(sharedPointerB.unique()) << "Second assigned shared pointer was not released under type transformation";
}
TEST_F(AnySharedPointerTest, SlotsInVector) {
auto sharedPtr = std::make_shared<bool>();
{
std::list<AnySharedPointer> slots;
// Initialize with a lot of copies of sharedPtr
for(size_t i = 0; i < 10; i++) {
slots.push_back(AnySharedPointer(sharedPtr));
ASSERT_EQ(1 + (long)slots.size(), sharedPtr.use_count()) << "Unexpected number of references to a slotted shared pointer";
}
}
// Now verify that we're unique again:
ASSERT_TRUE(sharedPtr.unique()) << "Slots in a vector did not properly release all local clones";
}
TEST_F(AnySharedPointerTest, SlotDuplication) {
auto sharedPtr = std::make_shared<bool>();
AnySharedPointer slot2;
{
// Create a base slot to hold the shared pointer:
AnySharedPointer slot1(sharedPtr);
ASSERT_FALSE(slot1->empty()) << "A slot initialized from a shared pointer was incorrectly marked as empty";
// Verify the type came across:
ASSERT_EQ(typeid(auto_id<bool>), slot1->type()) << "Dynamic initialization did not correctly adjust the dynamic type";
// Now copy it over:
slot2 = slot1;
// Verify reference count was affected as expected
ASSERT_EQ(3, sharedPtr.use_count()) << "A second-order slot copy didn't increment the reference count as expected";
}
// Verify that the slot still holds a reference and that the reference count is correct:
ASSERT_FALSE(slot2->empty()) << "A slot should have continued to hold a shared pointer, but was prematurely cleared";
ASSERT_EQ(2, sharedPtr.use_count()) << "A slot going out of scope did not correctly decrement a shared pointer reference";
}
TEST_F(AnySharedPointerTest, TrivialRelease) {
auto a = std::make_shared<bool>();
auto b = std::make_shared<int>();
// Assign the slot to two different values, and make sure that they are released properly
AnySharedPointer slot;
slot = a;
slot = b;
ASSERT_TRUE(a.unique()) << "Expected reassignment of a slot to release a formerly held instance";
ASSERT_FALSE(b.unique()) << "Expected slot to hold a reference to the second specified instance";
// Now release, and verify that a release actually took place
slot->reset();
ASSERT_TRUE(b.unique()) << "Releasing a slot did not actually release the held value as expected";
}
TEST_F(AnySharedPointerTest, NoMultipleDelete) {
auto a = std::make_shared<bool>();
std::weak_ptr<bool> b = a;
// Create a slot and validate the behavior of reset, and to ensure that the underlying
// SharedPointerSlot is not multiply deleted.
{
AnySharedPointer slot;
slot = a;
slot->reset();
}
// Now verify that we didn't accidentally overdecrement the count:
ASSERT_FALSE(b.expired()) << "Shared pointer prematurely expired; SharedPointerSlot dtor double-strike suspected";
}
TEST_F(AnySharedPointerTest, InitDerivesCorrectType) {
AnySharedPointer slot;
slot->init<int>();
ASSERT_EQ(typeid(auto_id<int>), slot->type()) << "A manually initialized slot did not have the expected type";
}
TEST_F(AnySharedPointerTest, VoidReturnExpected) {
// Fill out our slot:
auto v = std::make_shared<int>(5);
AnySharedPointer slot;
slot = v;
// Validate equivalence of the void operator:
ASSERT_EQ(v.get(), slot->ptr()) << "Shared pointer slot did not return a void* with an expected value";
}
TEST_F(AnySharedPointerTest, CanHoldCoreObject) {
auto co = std::make_shared<CoreObject>();
AnySharedPointer x = co;
ASSERT_EQ(co, x) << "Held CoreObject was not equivalent to constructed instance";
}
TEST_F(AnySharedPointerTest, CanFastCastToSelf) {
(void)autowiring::fast_pointer_cast_initializer<CoreObject, CoreObject>::sc_init;
auto co = std::make_shared<CoreObject>();
ASSERT_EQ(
co,
autowiring::fast_pointer_cast<CoreObject>(co)
) << "Could not cast a CoreObject instance to itself";
}<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_init.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/test/in_process_browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class BrowserInitTest : public InProcessBrowserTest {
};
class OpenURLsPopupObserver : public BrowserList::Observer {
public:
OpenURLsPopupObserver() : added_browser_(NULL) { }
virtual void OnBrowserAdded(const Browser* browser) {
added_browser_ = browser;
}
virtual void OnBrowserRemoved(const Browser* browser) { }
const Browser* added_browser_;
};
// Test that when there is a popup as the active browser any requests to
// BrowserInit::LaunchWithProfile::OpenURLsInBrowser don't crash because
// there's no explicit profile given.
IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenURLsPopup) {
std::vector<GURL> urls;
urls.push_back(GURL("http://localhost"));
// Note that in our testing we do not ever query the BrowserList for the "last
// active" browser. That's because the browsers are set as "active" by
// platform UI toolkit messages, and those messages are not sent during unit
// testing sessions.
OpenURLsPopupObserver observer;
BrowserList::AddObserver(&observer);
Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP,
browser()->profile());
ASSERT_EQ(popup->type(), Browser::TYPE_POPUP);
ASSERT_EQ(popup, observer.added_browser_);
CommandLine dummy(CommandLine::NO_PROGRAM);
BrowserInit::LaunchWithProfile launch(FilePath(), dummy);
// This should create a new window, but re-use the profile from |popup|. If
// it used a NULL or invalid profile, it would crash.
launch.OpenURLsInBrowser(popup, false, urls);
ASSERT_NE(popup, observer.added_browser_);
BrowserList::RemoveObserver(&observer);
}
// Test that we prevent openning potentially dangerous schemes from the
// command line.
// TODO(jschuh): FLAKY because the process doesn't have sufficient time
// to start on most BuildBot runs and I don't want to add longer delays to
// the test. I'll circle back and make this work properly when i get a chance.
// See http://crbug.com/60026
IN_PROC_BROWSER_TEST_F(BrowserInitTest, FLAKY_BlockBadURLs) {
const char* testurlstr = "http://localhost/";
const GURL testurl(testurlstr);
CommandLine cmdline(CommandLine::NO_PROGRAM);
cmdline.AppendArg(testurlstr);
cmdline.AppendArg("javascript:alert('boo')");
cmdline.AppendArg(testurlstr);
cmdline.AppendArg("view-source:http://localhost/");
// This will pick up the current browser instance.
BrowserInit::LaunchWithProfile launch(FilePath(), cmdline);
launch.Launch(browser()->profile(), false);
// TODO(jschuh): Give the browser a chance to start first.
PlatformThread::Sleep(50);
// Skip about:blank in the first tab
for (int i = 1; i < browser()->tab_count(); i++) {
const GURL &url = browser()->GetTabContentsAt(i)->GetURL();
ASSERT_EQ(url, testurl);
}
ASSERT_EQ(browser()->tab_count(), 3);
}
} // namespace
<commit_msg>Remove BrowserInitTest.BlockBadURLs<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_init.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/test/in_process_browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class BrowserInitTest : public InProcessBrowserTest {
};
class OpenURLsPopupObserver : public BrowserList::Observer {
public:
OpenURLsPopupObserver() : added_browser_(NULL) { }
virtual void OnBrowserAdded(const Browser* browser) {
added_browser_ = browser;
}
virtual void OnBrowserRemoved(const Browser* browser) { }
const Browser* added_browser_;
};
// Test that when there is a popup as the active browser any requests to
// BrowserInit::LaunchWithProfile::OpenURLsInBrowser don't crash because
// there's no explicit profile given.
IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenURLsPopup) {
std::vector<GURL> urls;
urls.push_back(GURL("http://localhost"));
// Note that in our testing we do not ever query the BrowserList for the "last
// active" browser. That's because the browsers are set as "active" by
// platform UI toolkit messages, and those messages are not sent during unit
// testing sessions.
OpenURLsPopupObserver observer;
BrowserList::AddObserver(&observer);
Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP,
browser()->profile());
ASSERT_EQ(popup->type(), Browser::TYPE_POPUP);
ASSERT_EQ(popup, observer.added_browser_);
CommandLine dummy(CommandLine::NO_PROGRAM);
BrowserInit::LaunchWithProfile launch(FilePath(), dummy);
// This should create a new window, but re-use the profile from |popup|. If
// it used a NULL or invalid profile, it would crash.
launch.OpenURLsInBrowser(popup, false, urls);
ASSERT_NE(popup, observer.added_browser_);
BrowserList::RemoveObserver(&observer);
}
} // namespace
<|endoftext|>
|
<commit_before>// Copyright (C) 2012-2017 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/Decoration.hpp"
#include "TestFixtures/SimpleObject.hpp"
#include <autowiring/AnySharedPointer.h>
#include <autowiring/autowiring.h>
class AnySharedPointerTest:
public testing::Test
{};
// Autowiring takes advantage of the representational equivalence of instantiations of
// shared_ptr, and therefore requires that their layouts all be the same.
static_assert(
sizeof(std::shared_ptr<void*>) == sizeof(std::shared_ptr<int>),
"Shared pointer representations must be equivalent for casting to work correctly"
);
TEST_F(AnySharedPointerTest, CanReinterpretCastSharedPtr) {
auto iShared = std::make_shared<int>(101);
auto vShared = *reinterpret_cast<std::shared_ptr<void>*>(&iShared);
ASSERT_EQ(2UL, iShared.use_count()) << "Reinterpretive assignment of a void pointer did not increment the use count";
ASSERT_EQ(iShared.get(), vShared.get()) << "Reinterpreted shared pointer did not properly hold a member variable";
}
class MyUnusedClass {};
TEST_F(AnySharedPointerTest, OperatorEq) {
AutoRequired<SimpleObject> sobj;
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny1(sobj);
ASSERT_TRUE((bool)sobjAny1);
ASSERT_EQ(sobj, sobjAny1) << "An AnySharedPointer instance initialized by constructor violated an identity test";
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny2;
sobjAny2 = sobj;
ASSERT_TRUE((bool)sobjAny2);
ASSERT_EQ(sobj, sobjAny2) << "An AnySharedPointer instance initialized by assignment violated an identity test";
}
TEST_F(AnySharedPointerTest, AnySharedPointerRelease) {
auto t = std::make_shared<int>(5);
// Assign over, then reset
{
AnySharedPointer ptr;
ptr = t;
}
// Verify the AnySharedPointer destructor worked correctly
ASSERT_TRUE(t.unique()) << "AnySharedPointer instance did not properly release a reference when destroyed";
}
TEST_F(AnySharedPointerTest, SlotReassignment) {
auto sharedPointerA = std::make_shared<bool>();
auto sharedPointerB = std::make_shared<bool>();
auto sharedPointerC = std::make_shared<int>();
// Make our slot, and start off with a shared pointer of one type:
AnySharedPointer slot;
slot = sharedPointerA;
// Verify that the assignment worked as anticipated:
ASSERT_EQ(2, sharedPointerA.use_count()) << "Constructor did not properly addref a shared pointer on initialization";
// Recast to another shared pointer, verify reference count goes down:
slot = sharedPointerB;
ASSERT_EQ(2, sharedPointerB.use_count()) << "Reference count was not incremented properly during a shared pointer hold";
ASSERT_TRUE(sharedPointerA.unique()) << "Destructor was not properly invoked for a shared pointer slot";
// Now change the type completely, verify proper release:
slot = sharedPointerC;
ASSERT_TRUE(sharedPointerB.unique()) << "Second assigned shared pointer was not released under type transformation";
}
TEST_F(AnySharedPointerTest, SlotsInVector) {
auto sharedPtr = std::make_shared<bool>();
{
std::list<AnySharedPointer> slots;
// Initialize with a lot of copies of sharedPtr
for(size_t i = 0; i < 10; i++) {
slots.push_back(AnySharedPointer(sharedPtr));
ASSERT_EQ(1 + (long)slots.size(), sharedPtr.use_count()) << "Unexpected number of references to a slotted shared pointer";
}
}
// Now verify that we're unique again:
ASSERT_TRUE(sharedPtr.unique()) << "Slots in a vector did not properly release all local clones";
}
TEST_F(AnySharedPointerTest, SlotDuplication) {
auto sharedPtr = std::make_shared<bool>();
AnySharedPointer slot2;
{
// Create a base slot to hold the shared pointer:
AnySharedPointer slot1(sharedPtr);
ASSERT_FALSE(slot1.empty()) << "A slot initialized from a shared pointer was incorrectly marked as empty";
// Verify the type came across:
ASSERT_EQ(auto_id_t<bool>{}, slot1.type()) << "Dynamic initialization did not correctly adjust the dynamic type";
// Now copy it over:
slot2 = slot1;
// Verify reference count was affected as expected
ASSERT_EQ(3, sharedPtr.use_count()) << "A second-order slot copy didn't increment the reference count as expected";
}
// Verify that the slot still holds a reference and that the reference count is correct:
ASSERT_FALSE(slot2.empty()) << "A slot should have continued to hold a shared pointer, but was prematurely cleared";
ASSERT_EQ(2, sharedPtr.use_count()) << "A slot going out of scope did not correctly decrement a shared pointer reference";
}
TEST_F(AnySharedPointerTest, TrivialRelease) {
auto a = std::make_shared<bool>();
auto b = std::make_shared<int>();
// Assign the slot to two different values, and make sure that they are released properly
AnySharedPointer slot;
slot = a;
slot = b;
ASSERT_TRUE(a.unique()) << "Expected reassignment of a slot to release a formerly held instance";
ASSERT_FALSE(b.unique()) << "Expected slot to hold a reference to the second specified instance";
// Now release, and verify that a release actually took place
slot.reset();
ASSERT_TRUE(b.unique()) << "Releasing a slot did not actually release the held value as expected";
}
TEST_F(AnySharedPointerTest, NoMultipleDelete) {
auto a = std::make_shared<bool>();
std::weak_ptr<bool> b = a;
// Create a slot and validate the behavior of reset, and to ensure that the underlying
// SharedPointerSlot is not multiply deleted.
{
AnySharedPointer slot;
slot = a;
slot.reset();
}
// Now verify that we didn't accidentally overdecrement the count:
ASSERT_FALSE(b.expired()) << "Shared pointer prematurely expired; SharedPointerSlot dtor double-strike suspected";
}
TEST_F(AnySharedPointerTest, InitDerivesCorrectType) {
AnySharedPointer slot;
slot.init<int>();
ASSERT_EQ(auto_id_t<int>{}, slot.type()) << "A manually initialized slot did not have the expected type";
}
TEST_F(AnySharedPointerTest, VoidReturnExpected) {
// Fill out our slot:
auto v = std::make_shared<int>(5);
AnySharedPointer slot;
slot = v;
// Validate equivalence of the void operator:
ASSERT_EQ(v.get(), slot.ptr()) << "Shared pointer slot did not return a void* with an expected value";
}
TEST_F(AnySharedPointerTest, CanHoldCoreObject) {
auto co = std::make_shared<CoreObject>();
AnySharedPointer x = co;
ASSERT_EQ(co, x) << "Held CoreObject was not equivalent to constructed instance";
}
TEST_F(AnySharedPointerTest, CanFastCastToSelf) {
(void)autowiring::fast_pointer_cast_initializer<CoreObject, CoreObject>::sc_init;
auto co = std::make_shared<CoreObject>();
ASSERT_EQ(
co,
autowiring::fast_pointer_cast<CoreObject>(co)
) << "Could not cast a CoreObject instance to itself";
}
class AlternateBase {
public:
virtual ~AlternateBase(void) {}
};
class AnySharedPtrObjA:
public CoreObject
{
public:
int aVal = 101;
int aVal2 = 101;
};
class AnySharedPtrObjB:
public AlternateBase,
public Decoration<0>,
public AnySharedPtrObjA
{
public:
int bVal = 102;
};
TEST_F(AnySharedPointerTest, CanCrossCast) {
(void) auto_id_t_init<AnySharedPtrObjA>::init;
(void) auto_id_t_init<AnySharedPtrObjB>::init;
// Ensure that dynamic casters are non-null in the block:
auto nullCaster = &autowiring::null_cast<AnySharedPtrObjA, CoreObject>;
ASSERT_NE(
nullCaster,
(autowiring::fast_pointer_cast_blind<AnySharedPtrObjA, CoreObject>::cast)
) << "Fast pointer caster for AnySharedPtrObjA was not correctly initialized";
ASSERT_NE(
reinterpret_cast<std::shared_ptr<void>(*)(const std::shared_ptr<CoreObject>&)>(nullCaster),
auto_id_t<AnySharedPtrObjA>::s_block.pFromObj
) << "AnySharedPtrObjA dynamic caster was incorrectly assigned";
auto rootB = std::make_shared<AnySharedPtrObjB>();
auto rootA = std::static_pointer_cast<AnySharedPtrObjA>(rootB);
auto rootBPtr = rootB.get();
auto rootAPtr = static_cast<AnySharedPtrObjA*>(rootB.get());
ASSERT_NE((void*) rootBPtr, (void*) rootAPtr) << "Objects were not correctly detected as having separate offsets";
AnySharedPointer aASP = rootA;
std::shared_ptr<CoreObject> obj = aASP.as_obj();
ASSERT_NE(nullptr, obj) << "An object cast attempt did not succeed as expected";
ASSERT_EQ(101, aASP.as<AnySharedPtrObjA>()->aVal);
AnySharedPointer bASP;
bASP.init<AnySharedPtrObjB>();
bASP.try_assign(obj);
ASSERT_NE(bASP, nullptr) << "An attempted cast incorrectly resulted in a null return";
ASSERT_EQ(102, bASP.as<AnySharedPtrObjB>()->bVal);
ASSERT_EQ(aASP, bASP) << "An aliased shared pointer was not detected as being equal";
}
TEST_F(AnySharedPointerTest, NullAfterMove) {
auto ptr = std::make_shared<bool>(false);
AnySharedPointer p1 = ptr;
AnySharedPointer p2 = std::move(p1);
ASSERT_FALSE(p1) << "Move construction of AnySharedPointer did not nullify rhs";
AnySharedPointer p3;
p3 = std::move(p2);
ASSERT_FALSE(p2) << "Move assignment of AnySharedPointer did not nullify rhs";
}
TEST_F(AnySharedPointerTest, NullPtrConstruction) {
AnySharedPointer x{ nullptr };
ASSERT_EQ(auto_id_t<void>{}, auto_id{}) << "Default auto_id is expected to be void";
ASSERT_EQ(auto_id_t<void>{}, x.type()) << "nullptr type_id should have been void";
AnySharedPointer y;
AnySharedPointer z;
y = nullptr;
ASSERT_EQ(x, y) << "Nullptr initialization was not null";
ASSERT_EQ(x, z) << "Nullptr assignment was not null";
ASSERT_EQ(auto_id_t<void>{}, x.type());
ASSERT_EQ(auto_id_t<void>{}, y.type());
ASSERT_EQ(auto_id_t<void>{}, z.type());
}
TEST_F(AnySharedPointerTest, VoidSharedPointer) {
auto p = std::make_shared<int>(101);
AnySharedPointer x = p;
ASSERT_EQ(std::static_pointer_cast<void>(p), x.as_void()) << "Void cast of shared pointer did not hold the expected value";
}
<commit_msg>Fix compiler warning on Mac<commit_after>// Copyright (C) 2012-2017 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/Decoration.hpp"
#include "TestFixtures/SimpleObject.hpp"
#include <autowiring/AnySharedPointer.h>
#include <autowiring/autowiring.h>
class AnySharedPointerTest:
public testing::Test
{};
// Autowiring takes advantage of the representational equivalence of instantiations of
// shared_ptr, and therefore requires that their layouts all be the same.
static_assert(
sizeof(std::shared_ptr<void*>) == sizeof(std::shared_ptr<int>),
"Shared pointer representations must be equivalent for casting to work correctly"
);
TEST_F(AnySharedPointerTest, CanReinterpretCastSharedPtr) {
auto iShared = std::make_shared<int>(101);
auto vShared = *reinterpret_cast<std::shared_ptr<void>*>(&iShared);
ASSERT_EQ(2UL, iShared.use_count()) << "Reinterpretive assignment of a void pointer did not increment the use count";
ASSERT_EQ(iShared.get(), vShared.get()) << "Reinterpreted shared pointer did not properly hold a member variable";
}
class MyUnusedClass {};
TEST_F(AnySharedPointerTest, OperatorEq) {
AutoRequired<SimpleObject> sobj;
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny1(sobj);
ASSERT_TRUE((bool)sobjAny1);
ASSERT_EQ(sobj, sobjAny1) << "An AnySharedPointer instance initialized by constructor violated an identity test";
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny2;
sobjAny2 = sobj;
ASSERT_TRUE((bool)sobjAny2);
ASSERT_EQ(sobj, sobjAny2) << "An AnySharedPointer instance initialized by assignment violated an identity test";
}
TEST_F(AnySharedPointerTest, AnySharedPointerRelease) {
auto t = std::make_shared<int>(5);
// Assign over, then reset
{
AnySharedPointer ptr;
ptr = t;
}
// Verify the AnySharedPointer destructor worked correctly
ASSERT_TRUE(t.unique()) << "AnySharedPointer instance did not properly release a reference when destroyed";
}
TEST_F(AnySharedPointerTest, SlotReassignment) {
auto sharedPointerA = std::make_shared<bool>();
auto sharedPointerB = std::make_shared<bool>();
auto sharedPointerC = std::make_shared<int>();
// Make our slot, and start off with a shared pointer of one type:
AnySharedPointer slot;
slot = sharedPointerA;
// Verify that the assignment worked as anticipated:
ASSERT_EQ(2, sharedPointerA.use_count()) << "Constructor did not properly addref a shared pointer on initialization";
// Recast to another shared pointer, verify reference count goes down:
slot = sharedPointerB;
ASSERT_EQ(2, sharedPointerB.use_count()) << "Reference count was not incremented properly during a shared pointer hold";
ASSERT_TRUE(sharedPointerA.unique()) << "Destructor was not properly invoked for a shared pointer slot";
// Now change the type completely, verify proper release:
slot = sharedPointerC;
ASSERT_TRUE(sharedPointerB.unique()) << "Second assigned shared pointer was not released under type transformation";
}
TEST_F(AnySharedPointerTest, SlotsInVector) {
auto sharedPtr = std::make_shared<bool>();
{
std::list<AnySharedPointer> slots;
// Initialize with a lot of copies of sharedPtr
for(size_t i = 0; i < 10; i++) {
slots.push_back(AnySharedPointer(sharedPtr));
ASSERT_EQ(1 + (long)slots.size(), sharedPtr.use_count()) << "Unexpected number of references to a slotted shared pointer";
}
}
// Now verify that we're unique again:
ASSERT_TRUE(sharedPtr.unique()) << "Slots in a vector did not properly release all local clones";
}
TEST_F(AnySharedPointerTest, SlotDuplication) {
auto sharedPtr = std::make_shared<bool>();
AnySharedPointer slot2;
{
// Create a base slot to hold the shared pointer:
AnySharedPointer slot1(sharedPtr);
ASSERT_FALSE(slot1.empty()) << "A slot initialized from a shared pointer was incorrectly marked as empty";
// Verify the type came across:
ASSERT_EQ(auto_id_t<bool>{}, slot1.type()) << "Dynamic initialization did not correctly adjust the dynamic type";
// Now copy it over:
slot2 = slot1;
// Verify reference count was affected as expected
ASSERT_EQ(3, sharedPtr.use_count()) << "A second-order slot copy didn't increment the reference count as expected";
}
// Verify that the slot still holds a reference and that the reference count is correct:
ASSERT_FALSE(slot2.empty()) << "A slot should have continued to hold a shared pointer, but was prematurely cleared";
ASSERT_EQ(2, sharedPtr.use_count()) << "A slot going out of scope did not correctly decrement a shared pointer reference";
}
TEST_F(AnySharedPointerTest, TrivialRelease) {
auto a = std::make_shared<bool>();
auto b = std::make_shared<int>();
// Assign the slot to two different values, and make sure that they are released properly
AnySharedPointer slot;
slot = a;
slot = b;
ASSERT_TRUE(a.unique()) << "Expected reassignment of a slot to release a formerly held instance";
ASSERT_FALSE(b.unique()) << "Expected slot to hold a reference to the second specified instance";
// Now release, and verify that a release actually took place
slot.reset();
ASSERT_TRUE(b.unique()) << "Releasing a slot did not actually release the held value as expected";
}
TEST_F(AnySharedPointerTest, NoMultipleDelete) {
auto a = std::make_shared<bool>();
std::weak_ptr<bool> b = a;
// Create a slot and validate the behavior of reset, and to ensure that the underlying
// SharedPointerSlot is not multiply deleted.
{
AnySharedPointer slot;
slot = a;
slot.reset();
}
// Now verify that we didn't accidentally overdecrement the count:
ASSERT_FALSE(b.expired()) << "Shared pointer prematurely expired; SharedPointerSlot dtor double-strike suspected";
}
TEST_F(AnySharedPointerTest, InitDerivesCorrectType) {
AnySharedPointer slot;
slot.init<int>();
ASSERT_EQ(auto_id_t<int>{}, slot.type()) << "A manually initialized slot did not have the expected type";
}
TEST_F(AnySharedPointerTest, VoidReturnExpected) {
// Fill out our slot:
auto v = std::make_shared<int>(5);
AnySharedPointer slot;
slot = v;
// Validate equivalence of the void operator:
ASSERT_EQ(v.get(), slot.ptr()) << "Shared pointer slot did not return a void* with an expected value";
}
TEST_F(AnySharedPointerTest, CanHoldCoreObject) {
auto co = std::make_shared<CoreObject>();
AnySharedPointer x = co;
ASSERT_EQ(co, x) << "Held CoreObject was not equivalent to constructed instance";
}
template<> const autowiring::fast_pointer_cast_initializer<CoreObject, CoreObject> autowiring::fast_pointer_cast_initializer<CoreObject, CoreObject>::sc_init;
TEST_F(AnySharedPointerTest, CanFastCastToSelf) {
(void)autowiring::fast_pointer_cast_initializer<CoreObject, CoreObject>::sc_init;
auto co = std::make_shared<CoreObject>();
ASSERT_EQ(
co,
autowiring::fast_pointer_cast<CoreObject>(co)
) << "Could not cast a CoreObject instance to itself";
}
class AlternateBase {
public:
virtual ~AlternateBase(void) {}
};
class AnySharedPtrObjA:
public CoreObject
{
public:
int aVal = 101;
int aVal2 = 101;
};
class AnySharedPtrObjB:
public AlternateBase,
public Decoration<0>,
public AnySharedPtrObjA
{
public:
int bVal = 102;
};
TEST_F(AnySharedPointerTest, CanCrossCast) {
(void) auto_id_t_init<AnySharedPtrObjA>::init;
(void) auto_id_t_init<AnySharedPtrObjB>::init;
// Ensure that dynamic casters are non-null in the block:
auto nullCaster = &autowiring::null_cast<AnySharedPtrObjA, CoreObject>;
ASSERT_NE(
nullCaster,
(autowiring::fast_pointer_cast_blind<AnySharedPtrObjA, CoreObject>::cast)
) << "Fast pointer caster for AnySharedPtrObjA was not correctly initialized";
ASSERT_NE(
reinterpret_cast<std::shared_ptr<void>(*)(const std::shared_ptr<CoreObject>&)>(nullCaster),
auto_id_t<AnySharedPtrObjA>::s_block.pFromObj
) << "AnySharedPtrObjA dynamic caster was incorrectly assigned";
auto rootB = std::make_shared<AnySharedPtrObjB>();
auto rootA = std::static_pointer_cast<AnySharedPtrObjA>(rootB);
auto rootBPtr = rootB.get();
auto rootAPtr = static_cast<AnySharedPtrObjA*>(rootB.get());
ASSERT_NE((void*) rootBPtr, (void*) rootAPtr) << "Objects were not correctly detected as having separate offsets";
AnySharedPointer aASP = rootA;
std::shared_ptr<CoreObject> obj = aASP.as_obj();
ASSERT_NE(nullptr, obj) << "An object cast attempt did not succeed as expected";
ASSERT_EQ(101, aASP.as<AnySharedPtrObjA>()->aVal);
AnySharedPointer bASP;
bASP.init<AnySharedPtrObjB>();
bASP.try_assign(obj);
ASSERT_NE(bASP, nullptr) << "An attempted cast incorrectly resulted in a null return";
ASSERT_EQ(102, bASP.as<AnySharedPtrObjB>()->bVal);
ASSERT_EQ(aASP, bASP) << "An aliased shared pointer was not detected as being equal";
}
TEST_F(AnySharedPointerTest, NullAfterMove) {
auto ptr = std::make_shared<bool>(false);
AnySharedPointer p1 = ptr;
AnySharedPointer p2 = std::move(p1);
ASSERT_FALSE(p1) << "Move construction of AnySharedPointer did not nullify rhs";
AnySharedPointer p3;
p3 = std::move(p2);
ASSERT_FALSE(p2) << "Move assignment of AnySharedPointer did not nullify rhs";
}
TEST_F(AnySharedPointerTest, NullPtrConstruction) {
AnySharedPointer x{ nullptr };
ASSERT_EQ(auto_id_t<void>{}, auto_id{}) << "Default auto_id is expected to be void";
ASSERT_EQ(auto_id_t<void>{}, x.type()) << "nullptr type_id should have been void";
AnySharedPointer y;
AnySharedPointer z;
y = nullptr;
ASSERT_EQ(x, y) << "Nullptr initialization was not null";
ASSERT_EQ(x, z) << "Nullptr assignment was not null";
ASSERT_EQ(auto_id_t<void>{}, x.type());
ASSERT_EQ(auto_id_t<void>{}, y.type());
ASSERT_EQ(auto_id_t<void>{}, z.type());
}
TEST_F(AnySharedPointerTest, VoidSharedPointer) {
auto p = std::make_shared<int>(101);
AnySharedPointer x = p;
ASSERT_EQ(std::static_pointer_cast<void>(p), x.as_void()) << "Void cast of shared pointer did not hold the expected value";
}
<|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/login/user_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/rounded_view.h"
#include "gfx/canvas.h"
#include "gfx/canvas_skia.h"
#include "gfx/rect.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/background.h"
#include "views/controls/button/text_button.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/painter.h"
namespace {
// Background color and corner radius of the login status label and
// signout button.
const SkColor kSignoutBackgroundColor = 0xFF007700;
const int kSignoutBackgroundCornerRadius = 4;
// Horiz/Vert insets for Signout view.
const int kSignoutViewHorizontalInsets = 10;
const int kSignoutViewVerticalInsets = 5;
// Padding between remove button and top right image corner.
const int kRemoveButtonPadding = 3;
// Draws green-ish background for signout view with
// rounded corners at the bottom.
class SignoutBackgroundPainter : public views::Painter {
virtual void Paint(int w, int h, gfx::Canvas* canvas) {
SkRect rect = {0, 0, w, h};
SkPath path;
SkScalar corners[] = {
0, 0,
0, 0,
kSignoutBackgroundCornerRadius,
kSignoutBackgroundCornerRadius,
kSignoutBackgroundCornerRadius,
kSignoutBackgroundCornerRadius,
};
path.addRoundRect(rect, corners);
SkPaint paint;
paint.setStyle(SkPaint::kFill_Style);
paint.setFlags(SkPaint::kAntiAlias_Flag);
paint.setColor(kSignoutBackgroundColor);
canvas->AsCanvasSkia()->drawPath(path, paint);
}
};
} // namespace
namespace chromeos {
using login::kBackgroundColor;
using login::kTextColor;
using login::kUserImageSize;
// The view that shows the Sign out button below the user's image.
class SignoutView : public views::View {
public:
explicit SignoutView(views::LinkController* link_controller) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
const gfx::Font& font = rb.GetFont(ResourceBundle::SmallFont);
active_user_label_ = new views::Label(
l10n_util::GetString(IDS_SCREEN_LOCK_ACTIVE_USER));
active_user_label_->SetFont(font);
active_user_label_->SetColor(kTextColor);
signout_link_ = new views::Link(
l10n_util::GetString(IDS_SCREEN_LOCK_SIGN_OUT));
signout_link_->SetController(link_controller);
signout_link_->SetFont(font);
signout_link_->SetColor(kTextColor);
signout_link_->SetFocusable(true);
AddChildView(active_user_label_);
AddChildView(signout_link_);
set_background(views::Background::CreateBackgroundPainter(
true, new SignoutBackgroundPainter()));
}
// views::View overrides.
virtual void Layout() {
gfx::Size label = active_user_label_->GetPreferredSize();
gfx::Size button = signout_link_->GetPreferredSize();
active_user_label_->SetBounds(
kSignoutViewHorizontalInsets, (height() - label.height()) / 2,
label.width(), label.height());
signout_link_->SetBounds(
width() - button.width() - kSignoutViewHorizontalInsets,
(height() - button.height()) / 2,
button.width(), button.height());
}
virtual gfx::Size GetPreferredSize() {
gfx::Size label = active_user_label_->GetPreferredSize();
gfx::Size button = signout_link_->GetPreferredSize();
return gfx::Size(label.width() + button.width(),
std::max(label.height(), button.height()) +
kSignoutViewVerticalInsets * 2);
}
views::Link* signout_link() { return signout_link_; }
private:
friend class UserView;
views::Label* active_user_label_;
views::Link* signout_link_;
DISALLOW_COPY_AND_ASSIGN(SignoutView);
};
class RemoveButton : public views::TextButton {
public:
RemoveButton(views::ButtonListener* listener,
const SkBitmap& icon,
const std::wstring& text,
const gfx::Point& top_right)
: views::TextButton(listener, std::wstring()),
icon_(icon),
text_(text),
top_right_(top_right),
was_first_click_(false) {
SetEnabledColor(SK_ColorWHITE);
SetDisabledColor(SK_ColorWHITE);
SetHighlightColor(SK_ColorWHITE);
SetHoverColor(SK_ColorWHITE);
SetIcon(icon_);
UpdatePosition();
}
protected:
// Overridden from View:
virtual void OnMouseExited(const views::MouseEvent& event) {
SetIcon(icon_);
views::TextButton::SetText(std::wstring());
ClearMaxTextSize();
set_background(NULL);
set_border(new views::TextButtonBorder);
UpdatePosition();
views::TextButton::OnMouseExited(event);
was_first_click_ = false;
}
void NotifyClick(const views::Event& event) {
if (!was_first_click_) {
// On first click transform image to "remove" label.
SetIcon(SkBitmap());
views::TextButton::SetText(text_);
const SkColor kStrokeColor = SK_ColorWHITE;
const SkColor kButtonColor = 0xFFE94949;
const int kStrokeWidth = 1;
const int kVerticalPadding = 4;
const int kHorizontalPadding = 8;
const int kCornerRadius = 4;
set_background(
CreateRoundedBackground(
kCornerRadius, kStrokeWidth, kButtonColor, kStrokeColor));
set_border(
views::Border::CreateEmptyBorder(kVerticalPadding,
kHorizontalPadding,
kVerticalPadding,
kHorizontalPadding));
UpdatePosition();
was_first_click_ = true;
} else {
// On second click propagate to base class to fire ButtonPressed.
views::TextButton::NotifyClick(event);
}
}
void SetText(const std::wstring& text) {
text_ = text;
}
private:
// Update button position and schedule paint event for the view and parent.
void UpdatePosition() {
gfx::Size size = GetPreferredSize();
gfx::Point origin = top_right_;
origin.Offset(-size.width(), 0);
SetBounds(gfx::Rect(origin, size));
if (GetParent())
GetParent()->SchedulePaint();
}
SkBitmap icon_;
std::wstring text_;
gfx::Point top_right_;
bool was_first_click_;
DISALLOW_COPY_AND_ASSIGN(RemoveButton);
};
class PodImageView : public views::ImageView {
public:
PodImageView() { }
void SetImage(const SkBitmap& image, const SkBitmap& image_hot) {
image_ = image;
image_hot_ = image_hot;
views::ImageView::SetImage(image_);
}
protected:
// Overridden from View:
virtual void OnMouseEntered(const views::MouseEvent& event) {
views::ImageView::SetImage(image_hot_);
}
virtual void OnMouseExited(const views::MouseEvent& event) {
views::ImageView::SetImage(image_);
}
private:
SkBitmap image_;
SkBitmap image_hot_;
DISALLOW_COPY_AND_ASSIGN(PodImageView);
};
UserView::UserView(Delegate* delegate, bool is_login, bool need_background)
: delegate_(delegate),
signout_view_(NULL),
image_view_(NULL),
remove_button_(NULL) {
DCHECK(delegate);
if (!is_login)
signout_view_ = new SignoutView(this);
if (need_background)
image_view_ = new RoundedView<PodImageView>;
else
image_view_ = new PodImageView;
Init(need_background);
}
void UserView::Init(bool need_background) {
if (need_background) {
image_view_->set_background(
views::Background::CreateSolidBackground(kBackgroundColor));
}
// UserView's layout never changes, so let's layout once here.
image_view_->SetBounds(0, 0, kUserImageSize, kUserImageSize);
AddChildView(image_view_);
if (signout_view_) {
signout_view_->SetBounds(0, kUserImageSize, kUserImageSize,
signout_view_->GetPreferredSize().height());
AddChildView(signout_view_);
}
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
remove_button_ = new RemoveButton(
this,
*rb.GetBitmapNamed(IDR_CLOSE_BAR_H),
l10n_util::GetString(IDS_LOGIN_REMOVE),
gfx::Point(kUserImageSize - kRemoveButtonPadding, kRemoveButtonPadding));
remove_button_->SetVisible(false);
AddChildView(remove_button_);
}
void UserView::SetImage(const SkBitmap& image, const SkBitmap& image_hot) {
int desired_size = std::min(image.width(), image.height());
// Desired size is not preserved if it's greater than 75% of kUserImageSize.
if (desired_size * 4 > 3 * kUserImageSize)
desired_size = kUserImageSize;
image_view_->SetImageSize(gfx::Size(desired_size, desired_size));
image_view_->SetImage(image, image_hot);
}
void UserView::SetTooltipText(const std::wstring& text) {
DCHECK(image_view_);
image_view_->SetTooltipText(text);
}
gfx::Size UserView::GetPreferredSize() {
return gfx::Size(
kUserImageSize,
kUserImageSize +
(signout_view_ ? signout_view_->GetPreferredSize().height() : 0));
}
void UserView::SetSignoutEnabled(bool enabled) {
DCHECK(signout_view_);
signout_view_->signout_link_->SetEnabled(enabled);
}
void UserView::LinkActivated(views::Link* source, int event_flags) {
DCHECK(delegate_);
DCHECK(signout_view_);
if (signout_view_->signout_link_ == source)
delegate_->OnSignout();
}
void UserView::SetRemoveButtonVisible(bool flag) {
remove_button_->SetVisible(flag);
}
void UserView::ButtonPressed(views::Button* sender, const views::Event& event) {
DCHECK(delegate_);
if (remove_button_ == sender)
delegate_->OnRemoveUser();
}
void UserView::OnLocaleChanged() {
remove_button_->SetText(l10n_util::GetString(IDS_LOGIN_REMOVE));
}
} // namespace chromeos
<commit_msg>User pods show hand cursor on hover<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/login/user_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/rounded_view.h"
#include "gfx/canvas.h"
#include "gfx/canvas_skia.h"
#include "gfx/gtk_util.h"
#include "gfx/rect.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/background.h"
#include "views/controls/button/text_button.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/painter.h"
namespace {
// Background color and corner radius of the login status label and
// signout button.
const SkColor kSignoutBackgroundColor = 0xFF007700;
const int kSignoutBackgroundCornerRadius = 4;
// Horiz/Vert insets for Signout view.
const int kSignoutViewHorizontalInsets = 10;
const int kSignoutViewVerticalInsets = 5;
// Padding between remove button and top right image corner.
const int kRemoveButtonPadding = 3;
// Draws green-ish background for signout view with
// rounded corners at the bottom.
class SignoutBackgroundPainter : public views::Painter {
virtual void Paint(int w, int h, gfx::Canvas* canvas) {
SkRect rect = {0, 0, w, h};
SkPath path;
SkScalar corners[] = {
0, 0,
0, 0,
kSignoutBackgroundCornerRadius,
kSignoutBackgroundCornerRadius,
kSignoutBackgroundCornerRadius,
kSignoutBackgroundCornerRadius,
};
path.addRoundRect(rect, corners);
SkPaint paint;
paint.setStyle(SkPaint::kFill_Style);
paint.setFlags(SkPaint::kAntiAlias_Flag);
paint.setColor(kSignoutBackgroundColor);
canvas->AsCanvasSkia()->drawPath(path, paint);
}
};
} // namespace
namespace chromeos {
using login::kBackgroundColor;
using login::kTextColor;
using login::kUserImageSize;
// The view that shows the Sign out button below the user's image.
class SignoutView : public views::View {
public:
explicit SignoutView(views::LinkController* link_controller) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
const gfx::Font& font = rb.GetFont(ResourceBundle::SmallFont);
active_user_label_ = new views::Label(
l10n_util::GetString(IDS_SCREEN_LOCK_ACTIVE_USER));
active_user_label_->SetFont(font);
active_user_label_->SetColor(kTextColor);
signout_link_ = new views::Link(
l10n_util::GetString(IDS_SCREEN_LOCK_SIGN_OUT));
signout_link_->SetController(link_controller);
signout_link_->SetFont(font);
signout_link_->SetColor(kTextColor);
signout_link_->SetFocusable(true);
AddChildView(active_user_label_);
AddChildView(signout_link_);
set_background(views::Background::CreateBackgroundPainter(
true, new SignoutBackgroundPainter()));
}
// views::View overrides.
virtual void Layout() {
gfx::Size label = active_user_label_->GetPreferredSize();
gfx::Size button = signout_link_->GetPreferredSize();
active_user_label_->SetBounds(
kSignoutViewHorizontalInsets, (height() - label.height()) / 2,
label.width(), label.height());
signout_link_->SetBounds(
width() - button.width() - kSignoutViewHorizontalInsets,
(height() - button.height()) / 2,
button.width(), button.height());
}
virtual gfx::Size GetPreferredSize() {
gfx::Size label = active_user_label_->GetPreferredSize();
gfx::Size button = signout_link_->GetPreferredSize();
return gfx::Size(label.width() + button.width(),
std::max(label.height(), button.height()) +
kSignoutViewVerticalInsets * 2);
}
views::Link* signout_link() { return signout_link_; }
private:
friend class UserView;
views::Label* active_user_label_;
views::Link* signout_link_;
DISALLOW_COPY_AND_ASSIGN(SignoutView);
};
class RemoveButton : public views::TextButton {
public:
RemoveButton(views::ButtonListener* listener,
const SkBitmap& icon,
const std::wstring& text,
const gfx::Point& top_right)
: views::TextButton(listener, std::wstring()),
icon_(icon),
text_(text),
top_right_(top_right),
was_first_click_(false) {
SetEnabledColor(SK_ColorWHITE);
SetDisabledColor(SK_ColorWHITE);
SetHighlightColor(SK_ColorWHITE);
SetHoverColor(SK_ColorWHITE);
SetIcon(icon_);
UpdatePosition();
}
protected:
// Overridden from View:
virtual void OnMouseExited(const views::MouseEvent& event) {
SetIcon(icon_);
views::TextButton::SetText(std::wstring());
ClearMaxTextSize();
set_background(NULL);
set_border(new views::TextButtonBorder);
UpdatePosition();
views::TextButton::OnMouseExited(event);
was_first_click_ = false;
}
void NotifyClick(const views::Event& event) {
if (!was_first_click_) {
// On first click transform image to "remove" label.
SetIcon(SkBitmap());
views::TextButton::SetText(text_);
const SkColor kStrokeColor = SK_ColorWHITE;
const SkColor kButtonColor = 0xFFE94949;
const int kStrokeWidth = 1;
const int kVerticalPadding = 4;
const int kHorizontalPadding = 8;
const int kCornerRadius = 4;
set_background(
CreateRoundedBackground(
kCornerRadius, kStrokeWidth, kButtonColor, kStrokeColor));
set_border(
views::Border::CreateEmptyBorder(kVerticalPadding,
kHorizontalPadding,
kVerticalPadding,
kHorizontalPadding));
UpdatePosition();
was_first_click_ = true;
} else {
// On second click propagate to base class to fire ButtonPressed.
views::TextButton::NotifyClick(event);
}
}
void SetText(const std::wstring& text) {
text_ = text;
}
private:
// Update button position and schedule paint event for the view and parent.
void UpdatePosition() {
gfx::Size size = GetPreferredSize();
gfx::Point origin = top_right_;
origin.Offset(-size.width(), 0);
SetBounds(gfx::Rect(origin, size));
if (GetParent())
GetParent()->SchedulePaint();
}
SkBitmap icon_;
std::wstring text_;
gfx::Point top_right_;
bool was_first_click_;
DISALLOW_COPY_AND_ASSIGN(RemoveButton);
};
class PodImageView : public views::ImageView {
public:
PodImageView() { }
void SetImage(const SkBitmap& image, const SkBitmap& image_hot) {
image_ = image;
image_hot_ = image_hot;
views::ImageView::SetImage(image_);
}
protected:
// Overridden from View:
virtual void OnMouseEntered(const views::MouseEvent& event) {
views::ImageView::SetImage(image_hot_);
}
virtual void OnMouseExited(const views::MouseEvent& event) {
views::ImageView::SetImage(image_);
}
gfx::NativeCursor GetCursorForPoint(
views::Event::EventType event_type,
const gfx::Point& p) {
return gfx::GetCursor(GDK_HAND2);
}
private:
SkBitmap image_;
SkBitmap image_hot_;
DISALLOW_COPY_AND_ASSIGN(PodImageView);
};
UserView::UserView(Delegate* delegate, bool is_login, bool need_background)
: delegate_(delegate),
signout_view_(NULL),
image_view_(NULL),
remove_button_(NULL) {
DCHECK(delegate);
if (!is_login)
signout_view_ = new SignoutView(this);
if (need_background)
image_view_ = new RoundedView<PodImageView>;
else
image_view_ = new PodImageView;
Init(need_background);
}
void UserView::Init(bool need_background) {
if (need_background) {
image_view_->set_background(
views::Background::CreateSolidBackground(kBackgroundColor));
}
// UserView's layout never changes, so let's layout once here.
image_view_->SetBounds(0, 0, kUserImageSize, kUserImageSize);
AddChildView(image_view_);
if (signout_view_) {
signout_view_->SetBounds(0, kUserImageSize, kUserImageSize,
signout_view_->GetPreferredSize().height());
AddChildView(signout_view_);
}
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
remove_button_ = new RemoveButton(
this,
*rb.GetBitmapNamed(IDR_CLOSE_BAR_H),
l10n_util::GetString(IDS_LOGIN_REMOVE),
gfx::Point(kUserImageSize - kRemoveButtonPadding, kRemoveButtonPadding));
remove_button_->SetVisible(false);
AddChildView(remove_button_);
}
void UserView::SetImage(const SkBitmap& image, const SkBitmap& image_hot) {
int desired_size = std::min(image.width(), image.height());
// Desired size is not preserved if it's greater than 75% of kUserImageSize.
if (desired_size * 4 > 3 * kUserImageSize)
desired_size = kUserImageSize;
image_view_->SetImageSize(gfx::Size(desired_size, desired_size));
image_view_->SetImage(image, image_hot);
}
void UserView::SetTooltipText(const std::wstring& text) {
DCHECK(image_view_);
image_view_->SetTooltipText(text);
}
gfx::Size UserView::GetPreferredSize() {
return gfx::Size(
kUserImageSize,
kUserImageSize +
(signout_view_ ? signout_view_->GetPreferredSize().height() : 0));
}
void UserView::SetSignoutEnabled(bool enabled) {
DCHECK(signout_view_);
signout_view_->signout_link_->SetEnabled(enabled);
}
void UserView::LinkActivated(views::Link* source, int event_flags) {
DCHECK(delegate_);
DCHECK(signout_view_);
if (signout_view_->signout_link_ == source)
delegate_->OnSignout();
}
void UserView::SetRemoveButtonVisible(bool flag) {
remove_button_->SetVisible(flag);
}
void UserView::ButtonPressed(views::Button* sender, const views::Event& event) {
DCHECK(delegate_);
if (remove_button_ == sender)
delegate_->OnRemoveUser();
}
void UserView::OnLocaleChanged() {
remove_button_->SetText(l10n_util::GetString(IDS_LOGIN_REMOVE));
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/update_observer.h"
#include "app/l10n_util.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/time_format.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
namespace chromeos {
UpdateObserver::UpdateObserver(Profile* profile)
: notification_(profile, "update.chromeos", IDR_NOTIFICATION_UPDATE,
l10n_util::GetStringUTF16(IDS_UPDATE_TITLE)),
progress_(-1) {}
UpdateObserver::~UpdateObserver() {
notification_.Hide();
}
void UpdateObserver::UpdateStatusChanged(UpdateLibrary* library) {
switch (library->status().status) {
case UPDATE_STATUS_IDLE:
case UPDATE_STATUS_CHECKING_FOR_UPDATE:
// Do nothing in these cases, we don't want to notify the user of the
// check unless there is an update. We don't hide here because
// we want the final state to be sticky.
break;
case UPDATE_STATUS_UPDATE_AVAILABLE:
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_AVAILABLE),
false);
break;
case UPDATE_STATUS_DOWNLOADING:
{
int progress = static_cast<int>(library->status().download_progress *
100.0);
if (progress != progress_) {
progress_ = progress;
notification_.Show(l10n_util::GetStringFUTF16(IDS_UPDATE_DOWNLOADING,
base::IntToString16(progress_)), false);
}
}
break;
case UPDATE_STATUS_VERIFYING:
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_VERIFYING),
false);
break;
case UPDATE_STATUS_FINALIZING:
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_FINALIZING),
false);
break;
case UPDATE_STATUS_UPDATED_NEED_REBOOT:
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_COMPLETED), true);
break;
default:
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_ERROR), true);
break;
}
}
} // namespace chromeos
<commit_msg>Handle the REPORTING_ERROR_EVENT state appropriately.<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/update_observer.h"
#include "app/l10n_util.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/time_format.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
namespace chromeos {
UpdateObserver::UpdateObserver(Profile* profile)
: notification_(profile, "update.chromeos", IDR_NOTIFICATION_UPDATE,
l10n_util::GetStringUTF16(IDS_UPDATE_TITLE)),
progress_(-1) {}
UpdateObserver::~UpdateObserver() {
notification_.Hide();
}
void UpdateObserver::UpdateStatusChanged(UpdateLibrary* library) {
switch (library->status().status) {
case UPDATE_STATUS_IDLE:
case UPDATE_STATUS_CHECKING_FOR_UPDATE:
// Do nothing in these cases, we don't want to notify the user of the
// check unless there is an update. We don't hide here because
// we want the final state to be sticky.
break;
case UPDATE_STATUS_UPDATE_AVAILABLE:
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_AVAILABLE),
false);
break;
case UPDATE_STATUS_DOWNLOADING:
{
int progress = static_cast<int>(library->status().download_progress *
100.0);
if (progress != progress_) {
progress_ = progress;
notification_.Show(l10n_util::GetStringFUTF16(IDS_UPDATE_DOWNLOADING,
base::IntToString16(progress_)), false);
}
}
break;
case UPDATE_STATUS_VERIFYING:
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_VERIFYING),
false);
break;
case UPDATE_STATUS_FINALIZING:
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_FINALIZING),
false);
break;
case UPDATE_STATUS_UPDATED_NEED_REBOOT:
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_COMPLETED), true);
break;
case UPDATE_STATUS_REPORTING_ERROR_EVENT:
// If the update engine encounters an error and we have already
// notified the user of the update progress, show an error
// notification. Don't show anything otherwise -- for example,
// in cases where the update engine encounters an error while
// checking for an update.
if (notification_.visible()) {
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_ERROR), true);
}
break;
default:
notification_.Show(l10n_util::GetStringUTF16(IDS_UPDATE_ERROR), true);
break;
}
}
} // namespace chromeos
<|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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_theme_provider.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
const std::wstring DevToolsWindow::kDevToolsApp = L"DevToolsApp";
// static
TabContents* DevToolsWindow::GetDevToolsContents(TabContents* inspected_tab) {
if (!inspected_tab) {
return NULL;
}
if (!DevToolsManager::GetInstance())
return NULL; // Happens only in tests.
DevToolsClientHost* client_host = DevToolsManager::GetInstance()->
GetDevToolsClientHostFor(inspected_tab->render_view_host());
if (!client_host) {
return NULL;
}
DevToolsWindow* window = client_host->AsDevToolsWindow();
if (!window || !window->is_docked()) {
return NULL;
}
return window->tab_contents();
}
DevToolsWindow::DevToolsWindow(Profile* profile,
RenderViewHost* inspected_rvh,
bool docked)
: profile_(profile),
browser_(NULL),
docked_(docked),
is_loaded_(false),
action_on_load_(DEVTOOLS_TOGGLE_ACTION_NONE) {
// Create TabContents with devtools.
tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL);
tab_contents_->render_view_host()->AllowBindings(BindingsPolicy::DOM_UI);
tab_contents_->controller().LoadURL(
GetDevToolsUrl(), GURL(), PageTransition::START_PAGE);
// Wipe out page icon so that the default application icon is used.
NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
entry->favicon().set_bitmap(SkBitmap());
entry->favicon().set_is_valid(true);
// Register on-load actions.
registrar_.Add(this,
NotificationType::LOAD_STOP,
Source<NavigationController>(&tab_contents_->controller()));
registrar_.Add(this,
NotificationType::TAB_CLOSING,
Source<NavigationController>(&tab_contents_->controller()));
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
inspected_tab_ = inspected_rvh->delegate()->GetAsTabContents();
}
DevToolsWindow::~DevToolsWindow() {
}
DevToolsWindow* DevToolsWindow::AsDevToolsWindow() {
return this;
}
void DevToolsWindow::SendMessageToClient(const IPC::Message& message) {
RenderViewHost* target_host = tab_contents_->render_view_host();
IPC::Message* m = new IPC::Message(message);
m->set_routing_id(target_host->routing_id());
target_host->Send(m);
}
void DevToolsWindow::InspectedTabClosing() {
if (docked_) {
// Update dev tools to reflect removed dev tools window.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->UpdateDevTools();
// In case of docked tab_contents we own it, so delete here.
delete tab_contents_;
delete this;
} else {
// First, initiate self-destruct to free all the registrars.
// Then close all tabs. Browser will take care of deleting tab_contents
// for us.
Browser* browser = browser_;
delete this;
browser->CloseAllTabs();
}
}
void DevToolsWindow::Show(DevToolsToggleAction action) {
if (docked_) {
// Just tell inspected browser to update splitter.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window) {
tab_contents_->set_delegate(this);
inspected_window->UpdateDevTools();
SetAttachedWindow();
tab_contents_->view()->SetInitialFocus();
ScheduleAction(action);
return;
} else {
// Sometimes we don't know where to dock. Stay undocked.
docked_ = false;
}
}
if (!browser_)
CreateDevToolsBrowser();
// Avoid consecutive window switching if the devtools window has been opened
// and the Inspect Element shortcut is pressed in the inspected tab.
bool should_show_window =
!browser_ || action != DEVTOOLS_TOGGLE_ACTION_INSPECT;
if (should_show_window)
browser_->window()->Show();
SetAttachedWindow();
if (should_show_window)
tab_contents_->view()->SetInitialFocus();
ScheduleAction(action);
}
void DevToolsWindow::Activate() {
if (!docked_) {
if (!browser_->window()->IsActive()) {
browser_->window()->Activate();
}
} else {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
tab_contents_->view()->Focus();
}
}
void DevToolsWindow::SetDocked(bool docked) {
if (docked_ == docked)
return;
if (docked && !GetInspectedBrowserWindow()) {
// Cannot dock, avoid window flashing due to close-reopen cycle.
return;
}
docked_ = docked;
if (docked) {
// Detach window from the external devtools browser. It will lead to
// the browser object's close and delete. Remove observer first.
TabStripModel* tabstrip_model = browser_->tabstrip_model();
tabstrip_model->DetachTabContentsAt(
tabstrip_model->GetIndexOfTabContents(tab_contents_));
browser_ = NULL;
} else {
// Update inspected window to hide split and reset it.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window) {
inspected_window->UpdateDevTools();
inspected_window = NULL;
}
}
Show(DEVTOOLS_TOGGLE_ACTION_NONE);
}
RenderViewHost* DevToolsWindow::GetRenderViewHost() {
return tab_contents_->render_view_host();
}
void DevToolsWindow::CreateDevToolsBrowser() {
// TODO(pfeldman): Make browser's getter for this key static.
std::wstring wp_key = L"";
wp_key.append(prefs::kBrowserWindowPlacement);
wp_key.append(L"_");
wp_key.append(kDevToolsApp);
PrefService* prefs = g_browser_process->local_state();
if (!prefs->FindPreference(wp_key.c_str())) {
prefs->RegisterDictionaryPref(wp_key.c_str());
}
const DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str());
if (!wp_pref) {
DictionaryValue* defaults = prefs->GetMutableDictionary(wp_key.c_str());
defaults->SetInteger(L"left", 100);
defaults->SetInteger(L"top", 100);
defaults->SetInteger(L"right", 740);
defaults->SetInteger(L"bottom", 740);
defaults->SetBoolean(L"maximized", false);
defaults->SetBoolean(L"always_on_top", false);
}
browser_ = Browser::CreateForDevTools(profile_);
browser_->tabstrip_model()->AddTabContents(
tab_contents_, -1, PageTransition::START_PAGE,
TabStripModel::ADD_SELECTED);
}
BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
Browser* browser = *it;
for (int i = 0; i < browser->tab_count(); ++i) {
TabContents* tab_contents = browser->GetTabContentsAt(i);
if (tab_contents == inspected_tab_) {
return browser->window();
}
}
}
return NULL;
}
void DevToolsWindow::SetAttachedWindow() {
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(
L"", docked_ ? L"WebInspector.setAttachedWindow(true);" :
L"WebInspector.setAttachedWindow(false);");
}
void DevToolsWindow::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::LOAD_STOP) {
SetAttachedWindow();
is_loaded_ = true;
UpdateTheme();
DoAction();
} else if (type == NotificationType::TAB_CLOSING) {
if (Source<NavigationController>(source).ptr() ==
&tab_contents_->controller()) {
// This happens when browser closes all of its tabs as a result
// of window.Close event.
// Notify manager that this DevToolsClientHost no longer exists and
// initiate self-destuct here.
NotifyCloseListener();
delete this;
}
} else if (type == NotificationType::BROWSER_THEME_CHANGED) {
UpdateTheme();
}
}
void DevToolsWindow::ScheduleAction(DevToolsToggleAction action) {
action_on_load_ = action;
if (is_loaded_)
DoAction();
}
void DevToolsWindow::DoAction() {
// TODO: these messages should be pushed through the WebKit API instead.
switch (action_on_load_) {
case DEVTOOLS_TOGGLE_ACTION_SHOW_CONSOLE:
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(L"", L"WebInspector.showConsole();");
break;
case DEVTOOLS_TOGGLE_ACTION_INSPECT:
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(
L"", L"WebInspector.toggleSearchingForNode();");
case DEVTOOLS_TOGGLE_ACTION_NONE:
// Do nothing.
break;
default:
NOTREACHED();
}
action_on_load_ = DEVTOOLS_TOGGLE_ACTION_NONE;
}
std::string SkColorToRGBAString(SkColor color) {
// We convert the alpha using DoubleToString because StringPrintf will use
// locale specific formatters (e.g., use , instead of . in German).
return StringPrintf("rgba(%d,%d,%d,%s)", SkColorGetR(color),
SkColorGetG(color), SkColorGetB(color),
DoubleToString(SkColorGetA(color) / 255.0).c_str());
}
GURL DevToolsWindow::GetDevToolsUrl() {
BrowserThemeProvider* tp = profile_->GetThemeProvider();
CHECK(tp);
SkColor color_toolbar =
tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
SkColor color_tab_text =
tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
std::string url_string = StringPrintf(
"%sdevtools.html?docked=%s&toolbar_color=%s&text_color=%s",
chrome::kChromeUIDevToolsURL,
docked_ ? "true" : "false",
SkColorToRGBAString(color_toolbar).c_str(),
SkColorToRGBAString(color_tab_text).c_str());
return GURL(url_string);
}
void DevToolsWindow::UpdateTheme() {
BrowserThemeProvider* tp = profile_->GetThemeProvider();
CHECK(tp);
SkColor color_toolbar =
tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
SkColor color_tab_text =
tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
std::string command = StringPrintf(
"WebInspector.setToolbarColors(\"%s\", \"%s\")",
SkColorToRGBAString(color_toolbar).c_str(),
SkColorToRGBAString(color_tab_text).c_str());
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(L"", UTF8ToWide(command));
}
bool DevToolsWindow::PreHandleKeyboardEvent(
const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) {
if (docked_) {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
return inspected_window->PreHandleKeyboardEvent(
event, is_keyboard_shortcut);
}
return false;
}
void DevToolsWindow::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
if (docked_) {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->HandleKeyboardEvent(event);
}
}
<commit_msg>Show DevTools window when the Inspect shortcut is hit for the first time<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_theme_provider.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
const std::wstring DevToolsWindow::kDevToolsApp = L"DevToolsApp";
// static
TabContents* DevToolsWindow::GetDevToolsContents(TabContents* inspected_tab) {
if (!inspected_tab) {
return NULL;
}
if (!DevToolsManager::GetInstance())
return NULL; // Happens only in tests.
DevToolsClientHost* client_host = DevToolsManager::GetInstance()->
GetDevToolsClientHostFor(inspected_tab->render_view_host());
if (!client_host) {
return NULL;
}
DevToolsWindow* window = client_host->AsDevToolsWindow();
if (!window || !window->is_docked()) {
return NULL;
}
return window->tab_contents();
}
DevToolsWindow::DevToolsWindow(Profile* profile,
RenderViewHost* inspected_rvh,
bool docked)
: profile_(profile),
browser_(NULL),
docked_(docked),
is_loaded_(false),
action_on_load_(DEVTOOLS_TOGGLE_ACTION_NONE) {
// Create TabContents with devtools.
tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL);
tab_contents_->render_view_host()->AllowBindings(BindingsPolicy::DOM_UI);
tab_contents_->controller().LoadURL(
GetDevToolsUrl(), GURL(), PageTransition::START_PAGE);
// Wipe out page icon so that the default application icon is used.
NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
entry->favicon().set_bitmap(SkBitmap());
entry->favicon().set_is_valid(true);
// Register on-load actions.
registrar_.Add(this,
NotificationType::LOAD_STOP,
Source<NavigationController>(&tab_contents_->controller()));
registrar_.Add(this,
NotificationType::TAB_CLOSING,
Source<NavigationController>(&tab_contents_->controller()));
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
inspected_tab_ = inspected_rvh->delegate()->GetAsTabContents();
}
DevToolsWindow::~DevToolsWindow() {
}
DevToolsWindow* DevToolsWindow::AsDevToolsWindow() {
return this;
}
void DevToolsWindow::SendMessageToClient(const IPC::Message& message) {
RenderViewHost* target_host = tab_contents_->render_view_host();
IPC::Message* m = new IPC::Message(message);
m->set_routing_id(target_host->routing_id());
target_host->Send(m);
}
void DevToolsWindow::InspectedTabClosing() {
if (docked_) {
// Update dev tools to reflect removed dev tools window.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->UpdateDevTools();
// In case of docked tab_contents we own it, so delete here.
delete tab_contents_;
delete this;
} else {
// First, initiate self-destruct to free all the registrars.
// Then close all tabs. Browser will take care of deleting tab_contents
// for us.
Browser* browser = browser_;
delete this;
browser->CloseAllTabs();
}
}
void DevToolsWindow::Show(DevToolsToggleAction action) {
if (docked_) {
// Just tell inspected browser to update splitter.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window) {
tab_contents_->set_delegate(this);
inspected_window->UpdateDevTools();
SetAttachedWindow();
tab_contents_->view()->SetInitialFocus();
ScheduleAction(action);
return;
} else {
// Sometimes we don't know where to dock. Stay undocked.
docked_ = false;
}
}
// Avoid consecutive window switching if the devtools window has been opened
// and the Inspect Element shortcut is pressed in the inspected tab.
bool should_show_window =
!browser_ || action != DEVTOOLS_TOGGLE_ACTION_INSPECT;
if (!browser_)
CreateDevToolsBrowser();
if (should_show_window)
browser_->window()->Show();
SetAttachedWindow();
if (should_show_window)
tab_contents_->view()->SetInitialFocus();
ScheduleAction(action);
}
void DevToolsWindow::Activate() {
if (!docked_) {
if (!browser_->window()->IsActive()) {
browser_->window()->Activate();
}
} else {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
tab_contents_->view()->Focus();
}
}
void DevToolsWindow::SetDocked(bool docked) {
if (docked_ == docked)
return;
if (docked && !GetInspectedBrowserWindow()) {
// Cannot dock, avoid window flashing due to close-reopen cycle.
return;
}
docked_ = docked;
if (docked) {
// Detach window from the external devtools browser. It will lead to
// the browser object's close and delete. Remove observer first.
TabStripModel* tabstrip_model = browser_->tabstrip_model();
tabstrip_model->DetachTabContentsAt(
tabstrip_model->GetIndexOfTabContents(tab_contents_));
browser_ = NULL;
} else {
// Update inspected window to hide split and reset it.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window) {
inspected_window->UpdateDevTools();
inspected_window = NULL;
}
}
Show(DEVTOOLS_TOGGLE_ACTION_NONE);
}
RenderViewHost* DevToolsWindow::GetRenderViewHost() {
return tab_contents_->render_view_host();
}
void DevToolsWindow::CreateDevToolsBrowser() {
// TODO(pfeldman): Make browser's getter for this key static.
std::wstring wp_key = L"";
wp_key.append(prefs::kBrowserWindowPlacement);
wp_key.append(L"_");
wp_key.append(kDevToolsApp);
PrefService* prefs = g_browser_process->local_state();
if (!prefs->FindPreference(wp_key.c_str())) {
prefs->RegisterDictionaryPref(wp_key.c_str());
}
const DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str());
if (!wp_pref) {
DictionaryValue* defaults = prefs->GetMutableDictionary(wp_key.c_str());
defaults->SetInteger(L"left", 100);
defaults->SetInteger(L"top", 100);
defaults->SetInteger(L"right", 740);
defaults->SetInteger(L"bottom", 740);
defaults->SetBoolean(L"maximized", false);
defaults->SetBoolean(L"always_on_top", false);
}
browser_ = Browser::CreateForDevTools(profile_);
browser_->tabstrip_model()->AddTabContents(
tab_contents_, -1, PageTransition::START_PAGE,
TabStripModel::ADD_SELECTED);
}
BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
Browser* browser = *it;
for (int i = 0; i < browser->tab_count(); ++i) {
TabContents* tab_contents = browser->GetTabContentsAt(i);
if (tab_contents == inspected_tab_) {
return browser->window();
}
}
}
return NULL;
}
void DevToolsWindow::SetAttachedWindow() {
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(
L"", docked_ ? L"WebInspector.setAttachedWindow(true);" :
L"WebInspector.setAttachedWindow(false);");
}
void DevToolsWindow::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::LOAD_STOP) {
SetAttachedWindow();
is_loaded_ = true;
UpdateTheme();
DoAction();
} else if (type == NotificationType::TAB_CLOSING) {
if (Source<NavigationController>(source).ptr() ==
&tab_contents_->controller()) {
// This happens when browser closes all of its tabs as a result
// of window.Close event.
// Notify manager that this DevToolsClientHost no longer exists and
// initiate self-destuct here.
NotifyCloseListener();
delete this;
}
} else if (type == NotificationType::BROWSER_THEME_CHANGED) {
UpdateTheme();
}
}
void DevToolsWindow::ScheduleAction(DevToolsToggleAction action) {
action_on_load_ = action;
if (is_loaded_)
DoAction();
}
void DevToolsWindow::DoAction() {
// TODO: these messages should be pushed through the WebKit API instead.
switch (action_on_load_) {
case DEVTOOLS_TOGGLE_ACTION_SHOW_CONSOLE:
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(L"", L"WebInspector.showConsole();");
break;
case DEVTOOLS_TOGGLE_ACTION_INSPECT:
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(
L"", L"WebInspector.toggleSearchingForNode();");
case DEVTOOLS_TOGGLE_ACTION_NONE:
// Do nothing.
break;
default:
NOTREACHED();
}
action_on_load_ = DEVTOOLS_TOGGLE_ACTION_NONE;
}
std::string SkColorToRGBAString(SkColor color) {
// We convert the alpha using DoubleToString because StringPrintf will use
// locale specific formatters (e.g., use , instead of . in German).
return StringPrintf("rgba(%d,%d,%d,%s)", SkColorGetR(color),
SkColorGetG(color), SkColorGetB(color),
DoubleToString(SkColorGetA(color) / 255.0).c_str());
}
GURL DevToolsWindow::GetDevToolsUrl() {
BrowserThemeProvider* tp = profile_->GetThemeProvider();
CHECK(tp);
SkColor color_toolbar =
tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
SkColor color_tab_text =
tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
std::string url_string = StringPrintf(
"%sdevtools.html?docked=%s&toolbar_color=%s&text_color=%s",
chrome::kChromeUIDevToolsURL,
docked_ ? "true" : "false",
SkColorToRGBAString(color_toolbar).c_str(),
SkColorToRGBAString(color_tab_text).c_str());
return GURL(url_string);
}
void DevToolsWindow::UpdateTheme() {
BrowserThemeProvider* tp = profile_->GetThemeProvider();
CHECK(tp);
SkColor color_toolbar =
tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
SkColor color_tab_text =
tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
std::string command = StringPrintf(
"WebInspector.setToolbarColors(\"%s\", \"%s\")",
SkColorToRGBAString(color_toolbar).c_str(),
SkColorToRGBAString(color_tab_text).c_str());
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(L"", UTF8ToWide(command));
}
bool DevToolsWindow::PreHandleKeyboardEvent(
const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) {
if (docked_) {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
return inspected_window->PreHandleKeyboardEvent(
event, is_keyboard_shortcut);
}
return false;
}
void DevToolsWindow::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
if (docked_) {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->HandleKeyboardEvent(event);
}
}
<|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/net/load_timing_observer.h"
#include "base/time.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/net/chrome_net_log.h"
#include "chrome/common/resource_response.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_netlog_params.h"
using base::Time;
using base::TimeTicks;
using webkit_glue::ResourceLoaderBridge;
using webkit_glue::ResourceLoadTimingInfo;
const size_t kMaxNumEntries = 1000;
namespace {
// We know that this conversion is not solid and suffers from world clock
// changes, but it should be good enough for the load timing info.
static Time TimeTicksToTime(const TimeTicks& time_ticks) {
static int64 tick_to_time_offset;
static bool tick_to_time_offset_available = false;
if (!tick_to_time_offset_available) {
int64 cur_time = (Time::Now() - Time()).InMicroseconds();
int64 cur_time_ticks = (TimeTicks::Now() - TimeTicks()).InMicroseconds();
// If we add this number to a time tick value, it gives the timestamp.
tick_to_time_offset = cur_time - cur_time_ticks;
tick_to_time_offset_available = true;
}
return Time::FromInternalValue(time_ticks.ToInternalValue() +
tick_to_time_offset);
}
static int32 TimeTicksToOffset(
const TimeTicks& time_ticks,
LoadTimingObserver::URLRequestRecord* record) {
return static_cast<int32>(
(time_ticks - record->base_ticks).InMillisecondsRoundedUp());
}
} // namespace
LoadTimingObserver::URLRequestRecord::URLRequestRecord()
: connect_job_id(net::NetLog::Source::kInvalidId),
socket_log_id(net::NetLog::Source::kInvalidId),
socket_reused(false) {
}
LoadTimingObserver::LoadTimingObserver()
: ThreadSafeObserver(net::NetLog::LOG_BASIC),
last_connect_job_id_(net::NetLog::Source::kInvalidId) {
}
LoadTimingObserver::~LoadTimingObserver() {
}
LoadTimingObserver::URLRequestRecord*
LoadTimingObserver::GetURLRequestRecord(uint32 source_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
URLRequestToRecordMap::iterator it = url_request_to_record_.find(source_id);
if (it != url_request_to_record_.end())
return &it->second;
return NULL;
}
void LoadTimingObserver::OnAddEntry(net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
// The events that the Observer is interested in only occur on the IO thread.
if (!BrowserThread::CurrentlyOn(BrowserThread::IO))
return;
if (source.type == net::NetLog::SOURCE_URL_REQUEST)
OnAddURLRequestEntry(type, time, source, phase, params);
else if (source.type == net::NetLog::SOURCE_CONNECT_JOB)
OnAddConnectJobEntry(type, time, source, phase, params);
else if (source.type == net::NetLog::SOURCE_SOCKET)
OnAddSocketEntry(type, time, source, phase, params);
}
// static
void LoadTimingObserver::PopulateTimingInfo(net::URLRequest* request,
ResourceResponse* response) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!(request->load_flags() & net::LOAD_ENABLE_LOAD_TIMING))
return;
ChromeNetLog* chrome_net_log = static_cast<ChromeNetLog*>(
request->net_log().net_log());
if (chrome_net_log == NULL)
return;
uint32 source_id = request->net_log().source().id;
LoadTimingObserver* observer = chrome_net_log->load_timing_observer();
LoadTimingObserver::URLRequestRecord* record =
observer->GetURLRequestRecord(source_id);
if (record) {
response->response_head.connection_id = record->socket_log_id;
response->response_head.connection_reused = record->socket_reused;
response->response_head.load_timing = record->timing;
}
}
void LoadTimingObserver::OnAddURLRequestEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
if (type == net::NetLog::TYPE_URL_REQUEST_START_JOB) {
if (is_begin) {
// Only record timing for entries with corresponding flag.
int load_flags = static_cast<URLRequestStartEventParameters*>(params)->
load_flags();
if (!(load_flags & net::LOAD_ENABLE_LOAD_TIMING))
return;
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (url_request_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer url request count has grown "
"larger than expected, resetting";
url_request_to_record_.clear();
}
URLRequestRecord& record = url_request_to_record_[source.id];
record.base_ticks = time;
record.timing.base_time = TimeTicksToTime(time);
}
return;
} else if (type == net::NetLog::TYPE_REQUEST_ALIVE) {
// Cleanup records based on the TYPE_REQUEST_ALIVE entry.
if (is_end)
url_request_to_record_.erase(source.id);
return;
}
URLRequestRecord* record = GetURLRequestRecord(source.id);
if (!record)
return;
ResourceLoadTimingInfo& timing = record->timing;
switch (type) {
case net::NetLog::TYPE_PROXY_SERVICE:
if (is_begin)
timing.proxy_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.proxy_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_SOCKET_POOL:
if (is_begin)
timing.connect_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.connect_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB:
{
uint32 connect_job_id = static_cast<net::NetLogSourceParameter*>(
params)->value().id;
if (last_connect_job_id_ == connect_job_id &&
!last_connect_job_record_.dns_start.is_null()) {
timing.dns_start =
TimeTicksToOffset(last_connect_job_record_.dns_start, record);
timing.dns_end =
TimeTicksToOffset(last_connect_job_record_.dns_end, record);
}
}
break;
case net::NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET:
record->socket_reused = true;
break;
case net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET:
record->socket_log_id = static_cast<net::NetLogSourceParameter*>(
params)->value().id;
if (!record->socket_reused) {
SocketToRecordMap::iterator it =
socket_to_record_.find(record->socket_log_id);
if (it != socket_to_record_.end() && !it->second.ssl_start.is_null()) {
timing.ssl_start = TimeTicksToOffset(it->second.ssl_start, record);
timing.ssl_end = TimeTicksToOffset(it->second.ssl_end, record);
}
}
break;
case net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST:
if (is_begin)
timing.send_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.send_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS:
if (is_begin)
timing.receive_headers_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.receive_headers_end = TimeTicksToOffset(time, record);
break;
default:
break;
}
}
void LoadTimingObserver::OnAddConnectJobEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
// Manage record lifetime based on the SOCKET_POOL_CONNECT_JOB entry.
if (type == net::NetLog::TYPE_SOCKET_POOL_CONNECT_JOB) {
if (is_begin) {
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (connect_job_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer connect job count has grown "
"larger than expected, resetting";
connect_job_to_record_.clear();
}
connect_job_to_record_.insert(
std::make_pair(source.id, ConnectJobRecord()));
} else if (is_end) {
ConnectJobToRecordMap::iterator it =
connect_job_to_record_.find(source.id);
if (it != connect_job_to_record_.end()) {
last_connect_job_id_ = it->first;
last_connect_job_record_ = it->second;
connect_job_to_record_.erase(it);
}
}
} else if (type == net::NetLog::TYPE_HOST_RESOLVER_IMPL) {
ConnectJobToRecordMap::iterator it =
connect_job_to_record_.find(source.id);
if (it != connect_job_to_record_.end()) {
if (is_begin)
it->second.dns_start = time;
else if (is_end)
it->second.dns_end = time;
}
}
}
void LoadTimingObserver::OnAddSocketEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
// Manage record lifetime based on the SOCKET_ALIVE entry.
if (type == net::NetLog::TYPE_SOCKET_ALIVE) {
if (is_begin) {
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (socket_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer socket count has grown "
"larger than expected, resetting";
socket_to_record_.clear();
}
socket_to_record_.insert(
std::make_pair(source.id, SocketRecord()));
} else if (is_end) {
socket_to_record_.erase(source.id);
}
return;
}
SocketToRecordMap::iterator it = socket_to_record_.find(source.id);
if (it == socket_to_record_.end())
return;
if (type == net::NetLog::TYPE_SSL_CONNECT) {
if (is_begin)
it->second.ssl_start = time;
else if (is_end)
it->second.ssl_end = time;
}
}
<commit_msg>DevTools: Network requests are timed with 1.6 days.<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/net/load_timing_observer.h"
#include "base/time.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/net/chrome_net_log.h"
#include "chrome/common/resource_response.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_netlog_params.h"
using base::Time;
using base::TimeTicks;
using webkit_glue::ResourceLoaderBridge;
using webkit_glue::ResourceLoadTimingInfo;
const size_t kMaxNumEntries = 1000;
namespace {
const int64 kSyncPeriodMicroseconds = 1000 * 1000 * 10;
// We know that this conversion is not solid and suffers from world clock
// changes, but given that we sync clock every 10 seconds, it should be good
// enough for the load timing info.
static Time TimeTicksToTime(const TimeTicks& time_ticks) {
static int64 tick_to_time_offset;
static int64 last_sync_ticks = 0;
if (time_ticks.ToInternalValue() - last_sync_ticks >
kSyncPeriodMicroseconds) {
int64 cur_time = (Time::Now() - Time()).InMicroseconds();
int64 cur_time_ticks = (TimeTicks::Now() - TimeTicks()).InMicroseconds();
// If we add this number to a time tick value, it gives the timestamp.
tick_to_time_offset = cur_time - cur_time_ticks;
last_sync_ticks = time_ticks.ToInternalValue();
}
return Time::FromInternalValue(time_ticks.ToInternalValue() +
tick_to_time_offset);
}
static int32 TimeTicksToOffset(
const TimeTicks& time_ticks,
LoadTimingObserver::URLRequestRecord* record) {
return static_cast<int32>(
(time_ticks - record->base_ticks).InMillisecondsRoundedUp());
}
} // namespace
LoadTimingObserver::URLRequestRecord::URLRequestRecord()
: connect_job_id(net::NetLog::Source::kInvalidId),
socket_log_id(net::NetLog::Source::kInvalidId),
socket_reused(false) {
}
LoadTimingObserver::LoadTimingObserver()
: ThreadSafeObserver(net::NetLog::LOG_BASIC),
last_connect_job_id_(net::NetLog::Source::kInvalidId) {
}
LoadTimingObserver::~LoadTimingObserver() {
}
LoadTimingObserver::URLRequestRecord*
LoadTimingObserver::GetURLRequestRecord(uint32 source_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
URLRequestToRecordMap::iterator it = url_request_to_record_.find(source_id);
if (it != url_request_to_record_.end())
return &it->second;
return NULL;
}
void LoadTimingObserver::OnAddEntry(net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
// The events that the Observer is interested in only occur on the IO thread.
if (!BrowserThread::CurrentlyOn(BrowserThread::IO))
return;
if (source.type == net::NetLog::SOURCE_URL_REQUEST)
OnAddURLRequestEntry(type, time, source, phase, params);
else if (source.type == net::NetLog::SOURCE_CONNECT_JOB)
OnAddConnectJobEntry(type, time, source, phase, params);
else if (source.type == net::NetLog::SOURCE_SOCKET)
OnAddSocketEntry(type, time, source, phase, params);
}
// static
void LoadTimingObserver::PopulateTimingInfo(net::URLRequest* request,
ResourceResponse* response) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!(request->load_flags() & net::LOAD_ENABLE_LOAD_TIMING))
return;
ChromeNetLog* chrome_net_log = static_cast<ChromeNetLog*>(
request->net_log().net_log());
if (chrome_net_log == NULL)
return;
uint32 source_id = request->net_log().source().id;
LoadTimingObserver* observer = chrome_net_log->load_timing_observer();
LoadTimingObserver::URLRequestRecord* record =
observer->GetURLRequestRecord(source_id);
if (record) {
response->response_head.connection_id = record->socket_log_id;
response->response_head.connection_reused = record->socket_reused;
response->response_head.load_timing = record->timing;
}
}
void LoadTimingObserver::OnAddURLRequestEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
if (type == net::NetLog::TYPE_URL_REQUEST_START_JOB) {
if (is_begin) {
// Only record timing for entries with corresponding flag.
int load_flags = static_cast<URLRequestStartEventParameters*>(params)->
load_flags();
if (!(load_flags & net::LOAD_ENABLE_LOAD_TIMING))
return;
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (url_request_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer url request count has grown "
"larger than expected, resetting";
url_request_to_record_.clear();
}
URLRequestRecord& record = url_request_to_record_[source.id];
record.base_ticks = time;
record.timing.base_time = TimeTicksToTime(time);
}
return;
} else if (type == net::NetLog::TYPE_REQUEST_ALIVE) {
// Cleanup records based on the TYPE_REQUEST_ALIVE entry.
if (is_end)
url_request_to_record_.erase(source.id);
return;
}
URLRequestRecord* record = GetURLRequestRecord(source.id);
if (!record)
return;
ResourceLoadTimingInfo& timing = record->timing;
switch (type) {
case net::NetLog::TYPE_PROXY_SERVICE:
if (is_begin)
timing.proxy_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.proxy_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_SOCKET_POOL:
if (is_begin)
timing.connect_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.connect_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB:
{
uint32 connect_job_id = static_cast<net::NetLogSourceParameter*>(
params)->value().id;
if (last_connect_job_id_ == connect_job_id &&
!last_connect_job_record_.dns_start.is_null()) {
timing.dns_start =
TimeTicksToOffset(last_connect_job_record_.dns_start, record);
timing.dns_end =
TimeTicksToOffset(last_connect_job_record_.dns_end, record);
}
}
break;
case net::NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET:
record->socket_reused = true;
break;
case net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET:
record->socket_log_id = static_cast<net::NetLogSourceParameter*>(
params)->value().id;
if (!record->socket_reused) {
SocketToRecordMap::iterator it =
socket_to_record_.find(record->socket_log_id);
if (it != socket_to_record_.end() && !it->second.ssl_start.is_null()) {
timing.ssl_start = TimeTicksToOffset(it->second.ssl_start, record);
timing.ssl_end = TimeTicksToOffset(it->second.ssl_end, record);
}
}
break;
case net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST:
if (is_begin)
timing.send_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.send_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS:
if (is_begin)
timing.receive_headers_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.receive_headers_end = TimeTicksToOffset(time, record);
break;
default:
break;
}
}
void LoadTimingObserver::OnAddConnectJobEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
// Manage record lifetime based on the SOCKET_POOL_CONNECT_JOB entry.
if (type == net::NetLog::TYPE_SOCKET_POOL_CONNECT_JOB) {
if (is_begin) {
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (connect_job_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer connect job count has grown "
"larger than expected, resetting";
connect_job_to_record_.clear();
}
connect_job_to_record_.insert(
std::make_pair(source.id, ConnectJobRecord()));
} else if (is_end) {
ConnectJobToRecordMap::iterator it =
connect_job_to_record_.find(source.id);
if (it != connect_job_to_record_.end()) {
last_connect_job_id_ = it->first;
last_connect_job_record_ = it->second;
connect_job_to_record_.erase(it);
}
}
} else if (type == net::NetLog::TYPE_HOST_RESOLVER_IMPL) {
ConnectJobToRecordMap::iterator it =
connect_job_to_record_.find(source.id);
if (it != connect_job_to_record_.end()) {
if (is_begin)
it->second.dns_start = time;
else if (is_end)
it->second.dns_end = time;
}
}
}
void LoadTimingObserver::OnAddSocketEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
// Manage record lifetime based on the SOCKET_ALIVE entry.
if (type == net::NetLog::TYPE_SOCKET_ALIVE) {
if (is_begin) {
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (socket_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer socket count has grown "
"larger than expected, resetting";
socket_to_record_.clear();
}
socket_to_record_.insert(
std::make_pair(source.id, SocketRecord()));
} else if (is_end) {
socket_to_record_.erase(source.id);
}
return;
}
SocketToRecordMap::iterator it = socket_to_record_.find(source.id);
if (it == socket_to_record_.end())
return;
if (type == net::NetLog::TYPE_SSL_CONNECT) {
if (is_begin)
it->second.ssl_start = time;
else if (is_end)
it->second.ssl_end = time;
}
}
<|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 <string.h>
#include <iostream>
#include "chrome/browser/thumbnail_store.h"
#include "base/time.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/gfx/jpeg_codec.h"
#include "base/path_service.h"
#include "base/ref_counted.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/ref_counted_util.h"
#include "chrome/common/thumbnail_score.h"
#include "chrome/tools/profiles/thumbnail-inl.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkPixelRef.h"
inline unsigned int diff(unsigned int a, unsigned int b) {
return a>b ? a-b : b-a;
}
class ThumbnailStoreTest : public testing::Test {
public:
ThumbnailStoreTest() : score1_(.5, true, false),
url1_("http://www.google.com"), url2_("http://www.elgoog.com") {
}
~ThumbnailStoreTest() {
}
protected:
void SetUp();
void TearDown() {
file_util::Delete(file_path_.AppendASCII(url1_.host()), false);
file_util::Delete(file_path_.AppendASCII(url2_.host()), false);
}
// Compute the max difference over all pixels for each RGBA component.
void PrintPixelDiff(SkBitmap* image_a, SkBitmap* image_b);
// The directory where ThumbnailStore will store data.
FilePath file_path_;
SkBitmap image_;
scoped_refptr<RefCountedBytes> jpeg_image_;
ThumbnailScore score1_, score2_;
GURL url1_, url2_;
base::Time time_;
};
void ThumbnailStoreTest::SetUp() {
if (!file_util::GetTempDir(&file_path_))
FAIL();
// Delete any old thumbnail files if they exist.
file_util::Delete(file_path_.AppendASCII(url1_.host()), false);
file_util::Delete(file_path_.AppendASCII(url2_.host()), false);
// image is the original SkBitmap representing the thumbnail
image_ = *(JPEGCodec::Decode(kGoogleThumbnail, sizeof(kGoogleThumbnail)));
SkAutoLockPixels thumbnail_lock(image_);
jpeg_image_ = new RefCountedBytes;
bool encoded = JPEGCodec::Encode(
reinterpret_cast<unsigned char*>(image_.getAddr32(0, 0)),
JPEGCodec::FORMAT_BGRA, image_.width(),
image_.height(),
static_cast<int>(image_.rowBytes()), 90,
&(jpeg_image_->data));
}
void ThumbnailStoreTest::PrintPixelDiff(SkBitmap* image_a, SkBitmap* image_b) {
// Compute the maximum difference in each of the RGBA components across all
// pixels between the retrieved SkBitmap and the original. These
// differences should be small since encoding was done at 90% before
// writing to disk.
if (image_a->height() != image_b->height() ||
image_b->width() != image_b->width() ||
image_a->rowBytes() != image_b->rowBytes())
return;
SkAutoLockPixels lock_a(*image_a);
SkAutoLockPixels lock_b(*image_b);
int ppr = image_a->rowBytesAsPixels();
unsigned int *a, *b;
unsigned int maxv[4];
memset(maxv, 0, sizeof(maxv));
for (int nrows = image_a->height()-1; nrows >= 0; nrows--) {
a = image_a->getAddr32(0, nrows);
b = image_b->getAddr32(0, nrows);
for (int i = 0; i < ppr; i += 4) {
for (int j = 0; j < 4; j++) {
maxv[j] = std::max(diff(*(a+i) >> (j<<3) & 0xff,
*(b+i) >> (j<<3) & 0xff),
maxv[j]);
}
}
}
std::cout << "Max diff btwn original and encoded image (b,g,r,a) = ("
<< maxv[0] << ","
<< maxv[1] << ","
<< maxv[2] << ","
<< maxv[3] << ")" << std::endl;
}
TEST_F(ThumbnailStoreTest, RetrieveFromCache) {
RefCountedBytes* read_image = NULL;
scoped_refptr<ThumbnailStore> store = new ThumbnailStore;
store->file_path_ = file_path_;
store->cache_.reset(new ThumbnailStore::Cache);
store->cache_initialized_ = true;
// Retrieve a thumbnail/score for a nonexistent page.
EXPECT_FALSE(store->GetPageThumbnail(url2_, &read_image));
// Store a thumbnail into the cache and retrieve it.
EXPECT_TRUE(store->SetPageThumbnail(url1_, image_, score1_, false));
EXPECT_TRUE(store->GetPageThumbnail(url1_, &read_image));
EXPECT_TRUE(score1_.Equals((*store->cache_)[url1_].second));
EXPECT_TRUE(read_image->data.size() == jpeg_image_->data.size());
EXPECT_EQ(0, memcmp(&read_image->data[0], &jpeg_image_->data[0],
jpeg_image_->data.size()));
read_image->Release();
}
TEST_F(ThumbnailStoreTest, RetrieveFromDisk) {
scoped_refptr<RefCountedBytes> read_image = new RefCountedBytes;
scoped_refptr<ThumbnailStore> store = new ThumbnailStore;
store->file_path_ = file_path_;
store->cache_.reset(new ThumbnailStore::Cache);
store->cache_initialized_ = true;
// Store a thumbnail onto the disk and retrieve it.
EXPECT_TRUE(store->SetPageThumbnail(url1_, image_, score1_, false));
EXPECT_TRUE(store->WriteThumbnailToDisk(url1_));
EXPECT_TRUE(store->GetPageThumbnailFromDisk(
file_path_.AppendASCII(url1_.host()), &url2_, read_image, &score2_));
read_image->AddRef();
EXPECT_TRUE(url1_ == url2_);
EXPECT_TRUE(score1_.Equals(score2_));
EXPECT_TRUE(read_image->data.size() == jpeg_image_->data.size());
EXPECT_EQ(0, memcmp(&read_image->data[0], &jpeg_image_->data[0],
jpeg_image_->data.size()));
}
<commit_msg>Fix Mac compile bustage Review URL: http://codereview.chromium.org/119379<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string.h>
#include <iostream>
#include "chrome/browser/thumbnail_store.h"
#include "base/time.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/gfx/jpeg_codec.h"
#include "base/path_service.h"
#include "base/ref_counted.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/ref_counted_util.h"
#include "chrome/common/thumbnail_score.h"
#include "chrome/tools/profiles/thumbnail-inl.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkPixelRef.h"
inline unsigned int diff(unsigned int a, unsigned int b) {
return a>b ? a-b : b-a;
}
class ThumbnailStoreTest : public testing::Test {
public:
ThumbnailStoreTest() : score1_(.5, true, false),
url1_("http://www.google.com"), url2_("http://www.elgoog.com") {
}
~ThumbnailStoreTest() {
}
protected:
void SetUp();
void TearDown() {
file_util::Delete(file_path_.AppendASCII(url1_.host()), false);
file_util::Delete(file_path_.AppendASCII(url2_.host()), false);
}
// Compute the max difference over all pixels for each RGBA component.
void PrintPixelDiff(SkBitmap* image_a, SkBitmap* image_b);
// The directory where ThumbnailStore will store data.
FilePath file_path_;
SkBitmap image_;
scoped_refptr<RefCountedBytes> jpeg_image_;
ThumbnailScore score1_, score2_;
GURL url1_, url2_;
base::Time time_;
};
void ThumbnailStoreTest::SetUp() {
if (!file_util::GetTempDir(&file_path_))
FAIL();
// Delete any old thumbnail files if they exist.
file_util::Delete(file_path_.AppendASCII(url1_.host()), false);
file_util::Delete(file_path_.AppendASCII(url2_.host()), false);
// image is the original SkBitmap representing the thumbnail
image_ = *(JPEGCodec::Decode(kGoogleThumbnail, sizeof(kGoogleThumbnail)));
SkAutoLockPixels thumbnail_lock(image_);
jpeg_image_ = new RefCountedBytes;
JPEGCodec::Encode(
reinterpret_cast<unsigned char*>(image_.getAddr32(0, 0)),
JPEGCodec::FORMAT_BGRA, image_.width(),
image_.height(),
static_cast<int>(image_.rowBytes()), 90,
&(jpeg_image_->data));
}
void ThumbnailStoreTest::PrintPixelDiff(SkBitmap* image_a, SkBitmap* image_b) {
// Compute the maximum difference in each of the RGBA components across all
// pixels between the retrieved SkBitmap and the original. These
// differences should be small since encoding was done at 90% before
// writing to disk.
if (image_a->height() != image_b->height() ||
image_b->width() != image_b->width() ||
image_a->rowBytes() != image_b->rowBytes())
return;
SkAutoLockPixels lock_a(*image_a);
SkAutoLockPixels lock_b(*image_b);
int ppr = image_a->rowBytesAsPixels();
unsigned int *a, *b;
unsigned int maxv[4];
memset(maxv, 0, sizeof(maxv));
for (int nrows = image_a->height()-1; nrows >= 0; nrows--) {
a = image_a->getAddr32(0, nrows);
b = image_b->getAddr32(0, nrows);
for (int i = 0; i < ppr; i += 4) {
for (int j = 0; j < 4; j++) {
maxv[j] = std::max(diff(*(a+i) >> (j<<3) & 0xff,
*(b+i) >> (j<<3) & 0xff),
maxv[j]);
}
}
}
std::cout << "Max diff btwn original and encoded image (b,g,r,a) = ("
<< maxv[0] << ","
<< maxv[1] << ","
<< maxv[2] << ","
<< maxv[3] << ")" << std::endl;
}
TEST_F(ThumbnailStoreTest, RetrieveFromCache) {
RefCountedBytes* read_image = NULL;
scoped_refptr<ThumbnailStore> store = new ThumbnailStore;
store->file_path_ = file_path_;
store->cache_.reset(new ThumbnailStore::Cache);
store->cache_initialized_ = true;
// Retrieve a thumbnail/score for a nonexistent page.
EXPECT_FALSE(store->GetPageThumbnail(url2_, &read_image));
// Store a thumbnail into the cache and retrieve it.
EXPECT_TRUE(store->SetPageThumbnail(url1_, image_, score1_, false));
EXPECT_TRUE(store->GetPageThumbnail(url1_, &read_image));
EXPECT_TRUE(score1_.Equals((*store->cache_)[url1_].second));
EXPECT_TRUE(read_image->data.size() == jpeg_image_->data.size());
EXPECT_EQ(0, memcmp(&read_image->data[0], &jpeg_image_->data[0],
jpeg_image_->data.size()));
read_image->Release();
}
TEST_F(ThumbnailStoreTest, RetrieveFromDisk) {
scoped_refptr<RefCountedBytes> read_image = new RefCountedBytes;
scoped_refptr<ThumbnailStore> store = new ThumbnailStore;
store->file_path_ = file_path_;
store->cache_.reset(new ThumbnailStore::Cache);
store->cache_initialized_ = true;
// Store a thumbnail onto the disk and retrieve it.
EXPECT_TRUE(store->SetPageThumbnail(url1_, image_, score1_, false));
EXPECT_TRUE(store->WriteThumbnailToDisk(url1_));
EXPECT_TRUE(store->GetPageThumbnailFromDisk(
file_path_.AppendASCII(url1_.host()), &url2_, read_image, &score2_));
read_image->AddRef();
EXPECT_TRUE(url1_ == url2_);
EXPECT_TRUE(score1_.Equals(score2_));
EXPECT_TRUE(read_image->data.size() == jpeg_image_->data.size());
EXPECT_EQ(0, memcmp(&read_image->data[0], &jpeg_image_->data[0],
jpeg_image_->data.size()));
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "Warg_Server.h"
void game_server(const char *wargspy_address)
{
ENetHost *server;
ENetPeer *wargspy;
Game_State game_state;
std::vector<Chat_Message> chat_log;
std::unique_ptr<Map> map;
std::map<UID, Peer> peers;
auto resource_manager = new Resource_Manager();
auto scene = new Flat_Scene_Graph(resource_manager);
{
map = std::make_unique<Map>(Blades_Edge(*scene));
for (int i = 0; i < 1; i++)
add_dummy(game_state, *map, {1, i, 5});
}
{
ENetAddress addr = { .host = ENET_HOST_ANY, .port = GAME_PORT };
server = enet_host_create(&addr, 32, 2, 0, 0);
}
{
ENetAddress addr = { .port = WARGSPY_PORT };
enet_address_set_host(&addr, wargspy_address);
wargspy = enet_host_connect(server, &addr, 2, 0);
}
{
ENetEvent event;
enet_host_service(server, &event, 5000);
// > 0 && event.type == ENET_EVENT_TYPE_CONNECT);
}
{
float64 current_time = 0.0;
float64 last_time = get_real_time() - dt;
float64 elapsed_time = 0.0;
while (true)
{
const float64 time = get_real_time();
elapsed_time = time - current_time;
last_time = current_time;
while (current_time + dt < last_time + elapsed_time)
{
current_time += dt;
{
uint8 byte = 1;
ENetPacket *packet = enet_packet_create(&byte, 1, 0);
enet_peer_send(wargspy, 0, packet);
}
{
ENetEvent event;
while (enet_host_service(server, &event, 0) > 0)
{
switch (event.type)
{
case ENET_EVENT_TYPE_CONNECT:
{
UID peer_id = uid();
event.peer->data = (void *)peer_id;
peers[peer_id].peer = event.peer;
break;
}
case ENET_EVENT_TYPE_RECEIVE:
{
Buffer b;
b.insert(event.packet->data, event.packet->dataLength);
int32 message_type;
deserialize(b, message_type);
switch (message_type)
{
case SPAWN_MESSAGE:
{
std::string name;
int32 team;
deserialize(b, name);
deserialize(b, team);
Peer &peer = peers[(UID)event.peer->data];
if (none_of(game_state.living_characters, [&](auto& lc) { return lc.id == peer.character; }))
{
UID character = add_char(game_state, *map, team, name);
peer.character = character;
}
break;
}
case MOVE_MESSAGE:
{
int m;
quat orientation;
UID target_id;
deserialize(b, m);
deserialize(b, orientation);
deserialize(b, target_id);
Input command;
command.number = 0;
command.orientation = orientation;
command.m = m;
Peer &peer = peers[(UID)event.peer->data];
UID character = peer.character;
peer.last_input = command;
auto t = find_if(game_state.character_targets, [&](auto &t) { return t.character == character; });
if (t != game_state.character_targets.end())
t->target = target_id;
else
game_state.character_targets.push_back({character, target_id});
break;
}
case CAST_MESSAGE:
{
UID target, spell;
deserialize(b, target);
deserialize(b, spell);
Peer &peer = peers[(UID)event.peer->data];
UID character = peer.character;
cast_spell(game_state, *scene, character, target, spell);
break;
}
case CHAT_MESSAGE:
{
std::string chat_message;
deserialize(b, chat_message);
Peer &peer = peers[(UID)event.peer->data];
auto character = find_if(game_state.characters, [&](auto &c) { return c.id == peer.character; });
Chat_Message cm;
if (character != game_state.characters.end())
cm.name = character->name;
else
cm.name = "Unknown";
cm.message = chat_message;
Buffer b;
serialize_(b, CHAT_MESSAGE_RELAY);
serialize_(b, cm.name);
serialize_(b, cm.message);
for (auto &p : peers)
{
ENetPacket *packet = enet_packet_create(b.data.data(), b.data.size(), ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(p.second.peer, 0, packet);
enet_host_flush(server);
}
}
}
enet_packet_destroy(event.packet);
break;
}
case ENET_EVENT_TYPE_DISCONNECT:
{
peers.erase((UID)event.peer->data);
break;
}
}
}
}
{
std::map<UID, Input> inputs;
for (auto &p : peers)
inputs[p.second.character] = p.second.last_input;
update_game(game_state, *map, *scene, inputs);
}
for (auto &p : peers)
{
Buffer b;
serialize_(b, STATE_MESSAGE);
serialize_(b, game_state);
serialize_(b, p.second.character);
ENetPacket *packet = enet_packet_create(b.data.data(), b.data.size(), ENET_PACKET_FLAG_UNSEQUENCED);
enet_peer_send(p.second.peer, 0, packet);
enet_host_flush(server);
}
}
SDL_Delay(5);
}
}
enet_host_destroy(server);
delete scene;
delete resource_manager;
}
<commit_msg>Add uid_of(peer) helper function to server code<commit_after>#include "stdafx.h"
#include "Warg_Server.h"
UID uid_of(const ENetPeer const *peer)
{
return peer ? (UID)peer->data : 0;
}
void game_server(const char *wargspy_address)
{
ENetHost *server;
ENetPeer *wargspy;
Game_State game_state;
std::vector<Chat_Message> chat_log;
std::unique_ptr<Map> map;
std::map<UID, Peer> peers;
auto resource_manager = new Resource_Manager();
auto scene = new Flat_Scene_Graph(resource_manager);
{
map = std::make_unique<Map>(Blades_Edge(*scene));
for (int i = 0; i < 1; i++)
add_dummy(game_state, *map, {1, i, 5});
}
{
ENetAddress addr = { .host = ENET_HOST_ANY, .port = GAME_PORT };
server = enet_host_create(&addr, 32, 2, 0, 0);
}
{
ENetAddress addr = { .port = WARGSPY_PORT };
enet_address_set_host(&addr, wargspy_address);
wargspy = enet_host_connect(server, &addr, 2, 0);
}
{
ENetEvent event;
enet_host_service(server, &event, 5000);
// > 0 && event.type == ENET_EVENT_TYPE_CONNECT);
}
{
float64 current_time = 0.0;
float64 last_time = get_real_time() - dt;
float64 elapsed_time = 0.0;
while (true)
{
const float64 time = get_real_time();
elapsed_time = time - current_time;
last_time = current_time;
while (current_time + dt < last_time + elapsed_time)
{
current_time += dt;
{
uint8 byte = 1;
ENetPacket *packet = enet_packet_create(&byte, 1, 0);
enet_peer_send(wargspy, 0, packet);
}
{
ENetEvent event;
while (enet_host_service(server, &event, 0) > 0)
{
switch (event.type)
{
case ENET_EVENT_TYPE_CONNECT:
{
UID peer_id = uid();
event.peer->data = (void *)peer_id;
peers[peer_id].peer = event.peer;
break;
}
case ENET_EVENT_TYPE_RECEIVE:
{
Buffer b;
b.insert(event.packet->data, event.packet->dataLength);
int32 message_type;
deserialize(b, message_type);
switch (message_type)
{
case SPAWN_MESSAGE:
{
std::string name;
int32 team;
deserialize(b, name);
deserialize(b, team);
Peer &peer = peers[uid_of(event.peer)];
if (none_of(game_state.living_characters, [&](auto& lc) { return lc.id == peer.character; }))
{
UID character = add_char(game_state, *map, team, name);
peer.character = character;
}
break;
}
case MOVE_MESSAGE:
{
int m;
quat orientation;
UID target_id;
deserialize(b, m);
deserialize(b, orientation);
deserialize(b, target_id);
Input command;
command.number = 0;
command.orientation = orientation;
command.m = m;
Peer &peer = peers[uid_of(event.peer)];
UID character = peer.character;
peer.last_input = command;
auto t = find_if(game_state.character_targets, [&](auto &t) { return t.character == character; });
if (t != game_state.character_targets.end())
t->target = target_id;
else
game_state.character_targets.push_back({character, target_id});
break;
}
case CAST_MESSAGE:
{
UID target, spell;
deserialize(b, target);
deserialize(b, spell);
Peer &peer = peers[uid_of(event.peer)];
UID character = peer.character;
cast_spell(game_state, *scene, character, target, spell);
break;
}
case CHAT_MESSAGE:
{
std::string chat_message;
deserialize(b, chat_message);
Peer &peer = peers[uid_of(event.peer)];
auto character = find_if(game_state.characters, [&](auto &c) { return c.id == peer.character; });
Chat_Message cm;
if (character != game_state.characters.end())
cm.name = character->name;
else
cm.name = "Unknown";
cm.message = chat_message;
Buffer b;
serialize_(b, CHAT_MESSAGE_RELAY);
serialize_(b, cm.name);
serialize_(b, cm.message);
for (auto &p : peers)
{
ENetPacket *packet = enet_packet_create(b.data.data(), b.data.size(), ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(p.second.peer, 0, packet);
}
}
}
enet_packet_destroy(event.packet);
break;
}
case ENET_EVENT_TYPE_DISCONNECT:
{
peers.erase(uid_of(event.peer));
break;
}
}
}
}
{
std::map<UID, Input> inputs;
for (auto &p : peers)
inputs[p.second.character] = p.second.last_input;
update_game(game_state, *map, *scene, inputs);
}
for (auto &p : peers)
{
Buffer b;
serialize_(b, STATE_MESSAGE);
serialize_(b, game_state);
serialize_(b, p.second.character);
ENetPacket *packet = enet_packet_create(b.data.data(), b.data.size(), ENET_PACKET_FLAG_UNSEQUENCED);
enet_peer_send(p.second.peer, 0, packet);
}
}
enet_host_flush(server);
SDL_Delay(5);
}
}
enet_host_destroy(server);
delete scene;
delete resource_manager;
}
<|endoftext|>
|
<commit_before>// TestOwnerUI.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "Main.h"
#include "MainFrame.h"
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
CPaintManagerUI::SetInstance(hInstance);
// CPaintManagerUI::SetResourcePath(CPaintManagerUI::GetInstancePath());
// CPaintManagerUI::SetResourceZip(_T("skin.dat"));
HRESULT Hr = ::CoInitialize(NULL);
if( FAILED(Hr) ) return 0;
CMainFrame duiFrame;
duiFrame.Create(NULL, _T("WeChat"), UI_WNDSTYLE_FRAME, WS_EX_WINDOWEDGE /*| WS_EX_TOPMOST*/);
duiFrame.SetIcon(IDI_WE_CHAT);
duiFrame.CenterWindow();
duiFrame.ShowModal();
::CoUninitialize();
return 0;
}<commit_msg>新增聊天记录本地缓存,优化聊天界面<commit_after>// TestOwnerUI.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "Main.h"
#include "MainFrame.h"
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
CPaintManagerUI::SetInstance(hInstance);
CPaintManagerUI::SetResourcePath(CPaintManagerUI::GetInstancePath());
CPaintManagerUI::SetResourceZip(_T("skin.dat"));
HRESULT Hr = ::CoInitialize(NULL);
if( FAILED(Hr) ) return 0;
CMainFrame duiFrame;
duiFrame.Create(NULL, _T("WeChat"), UI_WNDSTYLE_FRAME, WS_EX_WINDOWEDGE /*| WS_EX_TOPMOST*/);
duiFrame.SetIcon(IDI_WE_CHAT);
duiFrame.CenterWindow();
duiFrame.ShowModal();
::CoUninitialize();
return 0;
}<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Core/Persistent/PersistentSTL.h>
#include <Core/GeometryPrimitives/Tensor.h>
#include <Core/GeometryPrimitives/Vector.h>
#include <Core/Basis/Constant.h>
#include <Core/Basis/NoData.h>
#include <Core/Basis/TriLinearLgn.h>
#include <Core/Basis/CrvLinearLgn.h>
#include <Core/Datatypes/Legacy/Field/TriSurfMesh.h>
#include <Core/Datatypes/Legacy/Field/CurveMesh.h>
#include <Core/Datatypes/Legacy/Field/GenericField.h>
using namespace SCIRun;
//NoData
typedef NoDataBasis<double> NDBasis;
//Linear
typedef ConstantBasis<Tensor> CFDTensorBasis;
typedef ConstantBasis<Vector> CFDVectorBasis;
typedef ConstantBasis<double> CFDdoubleBasis;
typedef ConstantBasis<float> CFDfloatBasis;
typedef ConstantBasis<int> CFDintBasis;
typedef ConstantBasis<long long> CFDlonglongBasis;
typedef ConstantBasis<short> CFDshortBasis;
typedef ConstantBasis<char> CFDcharBasis;
typedef ConstantBasis<unsigned int> CFDuintBasis;
typedef ConstantBasis<unsigned short> CFDushortBasis;
typedef ConstantBasis<unsigned char> CFDucharBasis;
typedef ConstantBasis<unsigned long> CFDulongBasis;
//Linear
typedef TriLinearLgn<Tensor> FDTensorBasis;
typedef TriLinearLgn<Vector> FDVectorBasis;
typedef TriLinearLgn<double> FDdoubleBasis;
typedef TriLinearLgn<float> FDfloatBasis;
typedef TriLinearLgn<int> FDintBasis;
typedef TriLinearLgn<long long> FDlonglongBasis;
typedef TriLinearLgn<short> FDshortBasis;
typedef TriLinearLgn<char> FDcharBasis;
typedef TriLinearLgn<unsigned int> FDuintBasis;
typedef TriLinearLgn<unsigned short> FDushortBasis;
typedef TriLinearLgn<unsigned char> FDucharBasis;
typedef TriLinearLgn<unsigned long> FDulongBasis;
typedef TriSurfMesh<TriLinearLgn<Point> > TSMesh;
namespace SCIRun
{
template class TriSurfMesh<TriLinearLgn<Point> >;
//noData
template class GenericField<TSMesh, NDBasis, std::vector<double> >;
//Constant
template class GenericField<TSMesh, CFDTensorBasis, std::vector<Tensor> >;
template class GenericField<TSMesh, CFDVectorBasis, std::vector<Vector> >;
template class GenericField<TSMesh, CFDdoubleBasis, std::vector<double> >;
template class GenericField<TSMesh, CFDfloatBasis, std::vector<float> >;
template class GenericField<TSMesh, CFDintBasis, std::vector<int> >;
template class GenericField<TSMesh, CFDlonglongBasis,std::vector<long long> >;
template class GenericField<TSMesh, CFDshortBasis, std::vector<short> >;
template class GenericField<TSMesh, CFDcharBasis, std::vector<char> >;
template class GenericField<TSMesh, CFDuintBasis, std::vector<unsigned int> >;
template class GenericField<TSMesh, CFDushortBasis, std::vector<unsigned short> >;
template class GenericField<TSMesh, CFDucharBasis, std::vector<unsigned char> >;
template class GenericField<TSMesh, CFDulongBasis, std::vector<unsigned long> >;
//Linear
template class GenericField<TSMesh, FDTensorBasis, std::vector<Tensor> >;
template class GenericField<TSMesh, FDVectorBasis, std::vector<Vector> >;
template class GenericField<TSMesh, FDdoubleBasis, std::vector<double> >;
template class GenericField<TSMesh, FDfloatBasis, std::vector<float> >;
template class GenericField<TSMesh, FDintBasis, std::vector<int> >;
template class GenericField<TSMesh, FDlonglongBasis,std::vector<long long> >;
template class GenericField<TSMesh, FDshortBasis, std::vector<short> >;
template class GenericField<TSMesh, FDcharBasis, std::vector<char> >;
template class GenericField<TSMesh, FDuintBasis, std::vector<unsigned int> >;
template class GenericField<TSMesh, FDushortBasis, std::vector<unsigned short> >;
template class GenericField<TSMesh, FDucharBasis, std::vector<unsigned char> >;
template class GenericField<TSMesh, FDulongBasis, std::vector<unsigned long> >;
}
PersistentTypeID backwards_compat_TSM("TriSurfMesh", "Mesh",
TSMesh::maker, TSMesh::maker);
PersistentTypeID
backwards_compat_TSFT("TriSurfField<Tensor>", "Field",
GenericField<TSMesh, FDTensorBasis,
std::vector<Tensor> >::maker,
GenericField<TSMesh, CFDTensorBasis,
std::vector<Tensor> >::maker);
PersistentTypeID
backwards_compat_TSFV("TriSurfField<Vector>", "Field",
GenericField<TSMesh, FDVectorBasis,
std::vector<Vector> >::maker,
GenericField<TSMesh, CFDVectorBasis,
std::vector<Vector> >::maker);
PersistentTypeID
backwards_compat_TSFd("TriSurfField<double>", "Field",
GenericField<TSMesh, FDdoubleBasis,
std::vector<double> >::maker,
GenericField<TSMesh, CFDdoubleBasis,
std::vector<double> >::maker);
PersistentTypeID
backwards_compat_TSFf("TriSurfField<float>", "Field",
GenericField<TSMesh, FDfloatBasis,
std::vector<float> >::maker,
GenericField<TSMesh, CFDfloatBasis,
std::vector<float> >::maker);
PersistentTypeID
backwards_compat_TSFi("TriSurfField<int>", "Field",
GenericField<TSMesh, FDintBasis,
std::vector<int> >::maker,
GenericField<TSMesh, CFDintBasis,
std::vector<int> >::maker);
PersistentTypeID
backwards_compat_TSFs("TriSurfField<short>", "Field",
GenericField<TSMesh, FDshortBasis,
std::vector<short> >::maker,
GenericField<TSMesh, CFDshortBasis,
std::vector<short> >::maker);
PersistentTypeID
backwards_compat_TSFc("TriSurfField<char>", "Field",
GenericField<TSMesh, FDcharBasis,
std::vector<char> >::maker,
GenericField<TSMesh, CFDcharBasis,
std::vector<char> >::maker);
PersistentTypeID
backwards_compat_TSFui("TriSurfField<unsigned_int>", "Field",
GenericField<TSMesh, FDuintBasis,
std::vector<unsigned int> >::maker,
GenericField<TSMesh, CFDuintBasis,
std::vector<unsigned int> >::maker);
PersistentTypeID
backwards_compat_TSFus("TriSurfField<unsigned_short>", "Field",
GenericField<TSMesh, FDushortBasis,
std::vector<unsigned short> >::maker,
GenericField<TSMesh, CFDushortBasis,
std::vector<unsigned short> >::maker);
PersistentTypeID
backwards_compat_TSFuc("TriSurfField<unsigned_char>", "Field",
GenericField<TSMesh, FDucharBasis,
std::vector<unsigned char> >::maker,
GenericField<TSMesh, CFDucharBasis,
std::vector<unsigned char> >::maker);
PersistentTypeID
backwards_compat_TSFul("TriSurfField<unsigned_long>", "Field",
GenericField<TSMesh, FDulongBasis,
std::vector<unsigned long> >::maker,
GenericField<TSMesh, CFDulongBasis,
std::vector<unsigned long> >::maker);
//Linear
typedef CrvLinearLgn<Tensor> CrFDTensorBasis;
typedef CrvLinearLgn<Vector> CrFDVectorBasis;
typedef CrvLinearLgn<double> CrFDdoubleBasis;
typedef CrvLinearLgn<float> CrFDfloatBasis;
typedef CrvLinearLgn<int> CrFDintBasis;
typedef CrvLinearLgn<long long> CrFDlonglongBasis;
typedef CrvLinearLgn<short> CrFDshortBasis;
typedef CrvLinearLgn<char> CrFDcharBasis;
typedef CrvLinearLgn<unsigned int> CrFDuintBasis;
typedef CrvLinearLgn<unsigned short> CrFDushortBasis;
typedef CrvLinearLgn<unsigned char> CrFDucharBasis;
typedef CrvLinearLgn<unsigned long> CrFDulongBasis;
typedef CurveMesh<CrvLinearLgn<Point> > CMesh;
PersistentTypeID backwards_compat_CM("CurveMesh", "Mesh",
CMesh::maker, CMesh::maker);
template class CurveMesh<CrvLinearLgn<Point> >;
//NoData
template class GenericField<CMesh, NDBasis, std::vector<double> >;
//Constant
template class GenericField<CMesh, CFDTensorBasis, std::vector<Tensor> >;
template class GenericField<CMesh, CFDVectorBasis, std::vector<Vector> >;
template class GenericField<CMesh, CFDdoubleBasis, std::vector<double> >;
template class GenericField<CMesh, CFDfloatBasis, std::vector<float> >;
template class GenericField<CMesh, CFDintBasis, std::vector<int> >;
template class GenericField<CMesh, CFDlonglongBasis,std::vector<long long> >;
template class GenericField<CMesh, CFDshortBasis, std::vector<short> >;
template class GenericField<CMesh, CFDcharBasis, std::vector<char> >;
template class GenericField<CMesh, CFDuintBasis, std::vector<unsigned int> >;
template class GenericField<CMesh, CFDushortBasis, std::vector<unsigned short> >;
template class GenericField<CMesh, CFDucharBasis, std::vector<unsigned char> >;
template class GenericField<CMesh, CFDulongBasis, std::vector<unsigned long> >;
//Linear
template class GenericField<CMesh, CrFDTensorBasis, std::vector<Tensor> >;
template class GenericField<CMesh, CrFDVectorBasis, std::vector<Vector> >;
template class GenericField<CMesh, CrFDdoubleBasis, std::vector<double> >;
template class GenericField<CMesh, CrFDfloatBasis, std::vector<float> >;
template class GenericField<CMesh, CrFDintBasis, std::vector<int> >;
template class GenericField<CMesh, CrFDlonglongBasis,std::vector<long long> >;
template class GenericField<CMesh, CrFDshortBasis, std::vector<short> >;
template class GenericField<CMesh, CrFDcharBasis, std::vector<char> >;
template class GenericField<CMesh, CrFDuintBasis, std::vector<unsigned int> >;
template class GenericField<CMesh, CrFDushortBasis, std::vector<unsigned short> >;
template class GenericField<CMesh, CrFDucharBasis, std::vector<unsigned char> >;
template class GenericField<CMesh, CrFDulongBasis, std::vector<unsigned long> >;
PersistentTypeID
backwards_compat_CFT("CurveField<Tensor>", "Field",
GenericField<CMesh, CrFDTensorBasis,
std::vector<Tensor> >::maker,
GenericField<CMesh, CFDTensorBasis,
std::vector<Tensor> >::maker);
PersistentTypeID
backwards_compat_CFV("CurveField<Vector>", "Field",
GenericField<CMesh, CrFDVectorBasis,
std::vector<Vector> >::maker,
GenericField<CMesh, CFDVectorBasis,
std::vector<Vector> >::maker);
PersistentTypeID
backwards_compat_CFd("CurveField<double>", "Field",
GenericField<CMesh, CrFDdoubleBasis,
std::vector<double> >::maker,
GenericField<CMesh, CFDdoubleBasis,
std::vector<double> >::maker,
GenericField<CMesh, NDBasis,
std::vector<double> >::maker);
PersistentTypeID
backwards_compat_CFf("CurveField<float>", "Field",
GenericField<CMesh, CrFDfloatBasis,
std::vector<float> >::maker,
GenericField<CMesh, CFDfloatBasis,
std::vector<float> >::maker);
PersistentTypeID
backwards_compat_CFi("CurveField<int>", "Field",
GenericField<CMesh, CrFDintBasis,
std::vector<int> >::maker,
GenericField<CMesh, CFDintBasis,
std::vector<int> >::maker);
PersistentTypeID
backwards_compat_CFs("CurveField<short>", "Field",
GenericField<CMesh, CrFDshortBasis,
std::vector<short> >::maker,
GenericField<CMesh, CFDshortBasis,
std::vector<short> >::maker);
PersistentTypeID
backwards_compat_CFc("CurveField<char>", "Field",
GenericField<CMesh, CrFDcharBasis,
std::vector<char> >::maker,
GenericField<CMesh, CFDcharBasis,
std::vector<char> >::maker);
PersistentTypeID
backwards_compat_CFui("CurveField<unsigned_int>", "Field",
GenericField<CMesh, CrFDuintBasis,
std::vector<unsigned int> >::maker,
GenericField<CMesh, CFDuintBasis,
std::vector<unsigned int> >::maker);
PersistentTypeID
backwards_compat_CFus("CurveField<unsigned_short>", "Field",
GenericField<CMesh, CrFDushortBasis,
std::vector<unsigned short> >::maker,
GenericField<CMesh, CFDushortBasis,
std::vector<unsigned short> >::maker);
PersistentTypeID
backwards_compat_CFuc("CurveField<unsigned_char>", "Field",
GenericField<CMesh, CrFDucharBasis,
std::vector<unsigned char> >::maker,
GenericField<CMesh, CFDucharBasis,
std::vector<unsigned char> >::maker);
PersistentTypeID
backwards_compat_CFul("CurveField<unsigned_long>", "Field",
GenericField<CMesh, CrFDulongBasis,
std::vector<unsigned long> >::maker,
GenericField<CMesh, CFDulongBasis,
std::vector<unsigned long> >::maker);
<commit_msg>Clang fix<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Core/Persistent/PersistentSTL.h>
#include <Core/GeometryPrimitives/Tensor.h>
#include <Core/GeometryPrimitives/Vector.h>
#include <Core/Basis/Constant.h>
#include <Core/Basis/NoData.h>
#include <Core/Basis/TriLinearLgn.h>
#include <Core/Basis/CrvLinearLgn.h>
#include <Core/Datatypes/Legacy/Field/TriSurfMesh.h>
#include <Core/Datatypes/Legacy/Field/CurveMesh.h>
#include <Core/Datatypes/Legacy/Field/GenericField.h>
using namespace SCIRun;
//NoData
typedef NoDataBasis<double> NDBasis;
//Linear
typedef ConstantBasis<Tensor> CFDTensorBasis;
typedef ConstantBasis<Vector> CFDVectorBasis;
typedef ConstantBasis<double> CFDdoubleBasis;
typedef ConstantBasis<float> CFDfloatBasis;
typedef ConstantBasis<int> CFDintBasis;
typedef ConstantBasis<long long> CFDlonglongBasis;
typedef ConstantBasis<short> CFDshortBasis;
typedef ConstantBasis<char> CFDcharBasis;
typedef ConstantBasis<unsigned int> CFDuintBasis;
typedef ConstantBasis<unsigned short> CFDushortBasis;
typedef ConstantBasis<unsigned char> CFDucharBasis;
typedef ConstantBasis<unsigned long> CFDulongBasis;
//Linear
typedef TriLinearLgn<Tensor> FDTensorBasis;
typedef TriLinearLgn<Vector> FDVectorBasis;
typedef TriLinearLgn<double> FDdoubleBasis;
typedef TriLinearLgn<float> FDfloatBasis;
typedef TriLinearLgn<int> FDintBasis;
typedef TriLinearLgn<long long> FDlonglongBasis;
typedef TriLinearLgn<short> FDshortBasis;
typedef TriLinearLgn<char> FDcharBasis;
typedef TriLinearLgn<unsigned int> FDuintBasis;
typedef TriLinearLgn<unsigned short> FDushortBasis;
typedef TriLinearLgn<unsigned char> FDucharBasis;
typedef TriLinearLgn<unsigned long> FDulongBasis;
typedef TriSurfMesh<TriLinearLgn<Point> > TSMesh;
namespace SCIRun
{
template class TriSurfMesh<TriLinearLgn<Point> >;
//noData
template class GenericField<TSMesh, NDBasis, std::vector<double> >;
//Constant
template class GenericField<TSMesh, CFDTensorBasis, std::vector<Tensor> >;
template class GenericField<TSMesh, CFDVectorBasis, std::vector<Vector> >;
template class GenericField<TSMesh, CFDdoubleBasis, std::vector<double> >;
template class GenericField<TSMesh, CFDfloatBasis, std::vector<float> >;
template class GenericField<TSMesh, CFDintBasis, std::vector<int> >;
template class GenericField<TSMesh, CFDlonglongBasis,std::vector<long long> >;
template class GenericField<TSMesh, CFDshortBasis, std::vector<short> >;
template class GenericField<TSMesh, CFDcharBasis, std::vector<char> >;
template class GenericField<TSMesh, CFDuintBasis, std::vector<unsigned int> >;
template class GenericField<TSMesh, CFDushortBasis, std::vector<unsigned short> >;
template class GenericField<TSMesh, CFDucharBasis, std::vector<unsigned char> >;
template class GenericField<TSMesh, CFDulongBasis, std::vector<unsigned long> >;
//Linear
template class GenericField<TSMesh, FDTensorBasis, std::vector<Tensor> >;
template class GenericField<TSMesh, FDVectorBasis, std::vector<Vector> >;
template class GenericField<TSMesh, FDdoubleBasis, std::vector<double> >;
template class GenericField<TSMesh, FDfloatBasis, std::vector<float> >;
template class GenericField<TSMesh, FDintBasis, std::vector<int> >;
template class GenericField<TSMesh, FDlonglongBasis,std::vector<long long> >;
template class GenericField<TSMesh, FDshortBasis, std::vector<short> >;
template class GenericField<TSMesh, FDcharBasis, std::vector<char> >;
template class GenericField<TSMesh, FDuintBasis, std::vector<unsigned int> >;
template class GenericField<TSMesh, FDushortBasis, std::vector<unsigned short> >;
template class GenericField<TSMesh, FDucharBasis, std::vector<unsigned char> >;
template class GenericField<TSMesh, FDulongBasis, std::vector<unsigned long> >;
}
PersistentTypeID backwards_compat_TSM("TriSurfMesh", "Mesh",
TSMesh::maker, TSMesh::maker);
PersistentTypeID
backwards_compat_TSFT("TriSurfField<Tensor>", "Field",
GenericField<TSMesh, FDTensorBasis,
std::vector<Tensor> >::maker,
GenericField<TSMesh, CFDTensorBasis,
std::vector<Tensor> >::maker);
PersistentTypeID
backwards_compat_TSFV("TriSurfField<Vector>", "Field",
GenericField<TSMesh, FDVectorBasis,
std::vector<Vector> >::maker,
GenericField<TSMesh, CFDVectorBasis,
std::vector<Vector> >::maker);
PersistentTypeID
backwards_compat_TSFd("TriSurfField<double>", "Field",
GenericField<TSMesh, FDdoubleBasis,
std::vector<double> >::maker,
GenericField<TSMesh, CFDdoubleBasis,
std::vector<double> >::maker);
PersistentTypeID
backwards_compat_TSFf("TriSurfField<float>", "Field",
GenericField<TSMesh, FDfloatBasis,
std::vector<float> >::maker,
GenericField<TSMesh, CFDfloatBasis,
std::vector<float> >::maker);
PersistentTypeID
backwards_compat_TSFi("TriSurfField<int>", "Field",
GenericField<TSMesh, FDintBasis,
std::vector<int> >::maker,
GenericField<TSMesh, CFDintBasis,
std::vector<int> >::maker);
PersistentTypeID
backwards_compat_TSFs("TriSurfField<short>", "Field",
GenericField<TSMesh, FDshortBasis,
std::vector<short> >::maker,
GenericField<TSMesh, CFDshortBasis,
std::vector<short> >::maker);
PersistentTypeID
backwards_compat_TSFc("TriSurfField<char>", "Field",
GenericField<TSMesh, FDcharBasis,
std::vector<char> >::maker,
GenericField<TSMesh, CFDcharBasis,
std::vector<char> >::maker);
PersistentTypeID
backwards_compat_TSFui("TriSurfField<unsigned_int>", "Field",
GenericField<TSMesh, FDuintBasis,
std::vector<unsigned int> >::maker,
GenericField<TSMesh, CFDuintBasis,
std::vector<unsigned int> >::maker);
PersistentTypeID
backwards_compat_TSFus("TriSurfField<unsigned_short>", "Field",
GenericField<TSMesh, FDushortBasis,
std::vector<unsigned short> >::maker,
GenericField<TSMesh, CFDushortBasis,
std::vector<unsigned short> >::maker);
PersistentTypeID
backwards_compat_TSFuc("TriSurfField<unsigned_char>", "Field",
GenericField<TSMesh, FDucharBasis,
std::vector<unsigned char> >::maker,
GenericField<TSMesh, CFDucharBasis,
std::vector<unsigned char> >::maker);
PersistentTypeID
backwards_compat_TSFul("TriSurfField<unsigned_long>", "Field",
GenericField<TSMesh, FDulongBasis,
std::vector<unsigned long> >::maker,
GenericField<TSMesh, CFDulongBasis,
std::vector<unsigned long> >::maker);
//Linear
typedef CrvLinearLgn<Tensor> CrFDTensorBasis;
typedef CrvLinearLgn<Vector> CrFDVectorBasis;
typedef CrvLinearLgn<double> CrFDdoubleBasis;
typedef CrvLinearLgn<float> CrFDfloatBasis;
typedef CrvLinearLgn<int> CrFDintBasis;
typedef CrvLinearLgn<long long> CrFDlonglongBasis;
typedef CrvLinearLgn<short> CrFDshortBasis;
typedef CrvLinearLgn<char> CrFDcharBasis;
typedef CrvLinearLgn<unsigned int> CrFDuintBasis;
typedef CrvLinearLgn<unsigned short> CrFDushortBasis;
typedef CrvLinearLgn<unsigned char> CrFDucharBasis;
typedef CrvLinearLgn<unsigned long> CrFDulongBasis;
typedef CurveMesh<CrvLinearLgn<Point> > CMesh;
PersistentTypeID backwards_compat_CM("CurveMesh", "Mesh",
CMesh::maker, CMesh::maker);
namespace SCIRun {
template class CurveMesh<CrvLinearLgn<Point> >;
//NoData
template class GenericField<CMesh, NDBasis, std::vector<double> >;
//Constant
template class GenericField<CMesh, CFDTensorBasis, std::vector<Tensor> >;
template class GenericField<CMesh, CFDVectorBasis, std::vector<Vector> >;
template class GenericField<CMesh, CFDdoubleBasis, std::vector<double> >;
template class GenericField<CMesh, CFDfloatBasis, std::vector<float> >;
template class GenericField<CMesh, CFDintBasis, std::vector<int> >;
template class GenericField<CMesh, CFDlonglongBasis,std::vector<long long> >;
template class GenericField<CMesh, CFDshortBasis, std::vector<short> >;
template class GenericField<CMesh, CFDcharBasis, std::vector<char> >;
template class GenericField<CMesh, CFDuintBasis, std::vector<unsigned int> >;
template class GenericField<CMesh, CFDushortBasis, std::vector<unsigned short> >;
template class GenericField<CMesh, CFDucharBasis, std::vector<unsigned char> >;
template class GenericField<CMesh, CFDulongBasis, std::vector<unsigned long> >;
//Linear
template class GenericField<CMesh, CrFDTensorBasis, std::vector<Tensor> >;
template class GenericField<CMesh, CrFDVectorBasis, std::vector<Vector> >;
template class GenericField<CMesh, CrFDdoubleBasis, std::vector<double> >;
template class GenericField<CMesh, CrFDfloatBasis, std::vector<float> >;
template class GenericField<CMesh, CrFDintBasis, std::vector<int> >;
template class GenericField<CMesh, CrFDlonglongBasis,std::vector<long long> >;
template class GenericField<CMesh, CrFDshortBasis, std::vector<short> >;
template class GenericField<CMesh, CrFDcharBasis, std::vector<char> >;
template class GenericField<CMesh, CrFDuintBasis, std::vector<unsigned int> >;
template class GenericField<CMesh, CrFDushortBasis, std::vector<unsigned short> >;
template class GenericField<CMesh, CrFDucharBasis, std::vector<unsigned char> >;
template class GenericField<CMesh, CrFDulongBasis, std::vector<unsigned long> >;
}
PersistentTypeID
backwards_compat_CFT("CurveField<Tensor>", "Field",
GenericField<CMesh, CrFDTensorBasis,
std::vector<Tensor> >::maker,
GenericField<CMesh, CFDTensorBasis,
std::vector<Tensor> >::maker);
PersistentTypeID
backwards_compat_CFV("CurveField<Vector>", "Field",
GenericField<CMesh, CrFDVectorBasis,
std::vector<Vector> >::maker,
GenericField<CMesh, CFDVectorBasis,
std::vector<Vector> >::maker);
PersistentTypeID
backwards_compat_CFd("CurveField<double>", "Field",
GenericField<CMesh, CrFDdoubleBasis,
std::vector<double> >::maker,
GenericField<CMesh, CFDdoubleBasis,
std::vector<double> >::maker,
GenericField<CMesh, NDBasis,
std::vector<double> >::maker);
PersistentTypeID
backwards_compat_CFf("CurveField<float>", "Field",
GenericField<CMesh, CrFDfloatBasis,
std::vector<float> >::maker,
GenericField<CMesh, CFDfloatBasis,
std::vector<float> >::maker);
PersistentTypeID
backwards_compat_CFi("CurveField<int>", "Field",
GenericField<CMesh, CrFDintBasis,
std::vector<int> >::maker,
GenericField<CMesh, CFDintBasis,
std::vector<int> >::maker);
PersistentTypeID
backwards_compat_CFs("CurveField<short>", "Field",
GenericField<CMesh, CrFDshortBasis,
std::vector<short> >::maker,
GenericField<CMesh, CFDshortBasis,
std::vector<short> >::maker);
PersistentTypeID
backwards_compat_CFc("CurveField<char>", "Field",
GenericField<CMesh, CrFDcharBasis,
std::vector<char> >::maker,
GenericField<CMesh, CFDcharBasis,
std::vector<char> >::maker);
PersistentTypeID
backwards_compat_CFui("CurveField<unsigned_int>", "Field",
GenericField<CMesh, CrFDuintBasis,
std::vector<unsigned int> >::maker,
GenericField<CMesh, CFDuintBasis,
std::vector<unsigned int> >::maker);
PersistentTypeID
backwards_compat_CFus("CurveField<unsigned_short>", "Field",
GenericField<CMesh, CrFDushortBasis,
std::vector<unsigned short> >::maker,
GenericField<CMesh, CFDushortBasis,
std::vector<unsigned short> >::maker);
PersistentTypeID
backwards_compat_CFuc("CurveField<unsigned_char>", "Field",
GenericField<CMesh, CrFDucharBasis,
std::vector<unsigned char> >::maker,
GenericField<CMesh, CFDucharBasis,
std::vector<unsigned char> >::maker);
PersistentTypeID
backwards_compat_CFul("CurveField<unsigned_long>", "Field",
GenericField<CMesh, CrFDulongBasis,
std::vector<unsigned long> >::maker,
GenericField<CMesh, CFDulongBasis,
std::vector<unsigned long> >::maker);
<|endoftext|>
|
<commit_before>#include "test.hpp"
#include "cppa/cppa.hpp"
using namespace cppa;
using namespace cppa::placeholders;
struct popular_actor : event_based_actor { // popular actors have a buddy
actor_ptr m_buddy;
popular_actor(const actor_ptr& buddy) : m_buddy(buddy) { }
inline const actor_ptr& buddy() const { return m_buddy; }
void report_failure() {
send(buddy(), atom("failure"));
self->quit();
}
};
/******************************************************************************\
* test case 1: *
* *
* A B C *
* | | | *
* | --(sync_send)--> | | *
* | | --(forward)----> | *
* | X |---\ *
* | | | *
* | |<--/ *
* | <-------------(reply)-------------- | *
* X X *
\******************************************************************************/
struct A : popular_actor {
A(const actor_ptr& buddy) : popular_actor(buddy) { }
void init() {
become (
on(atom("go"), arg_match) >> [=](const actor_ptr& next) {
sync_send(next, atom("gogo")).then([=] {
send(buddy(), atom("success"));
quit();
});
},
others() >> [=] { report_failure(); }
);
}
};
#ifdef __clang__
struct B : sb_actor<B,popular_actor> {
B(const actor_ptr& buddy) : sb_actor<B,popular_actor>(buddy) { }
behavior init_state = (
others() >> [=] {
forward_to(buddy());
quit();
}
);
};
#else
struct B : popular_actor {
B(const actor_ptr& buddy) : popular_actor(buddy) { }
void init() {
become (
others() >> [=] {
forward_to(buddy());
quit();
}
);
}
};
#endif
struct C : sb_actor<C> {
behavior init_state = (
on(atom("gogo")) >> [=] {
reply(atom("gogogo"));
self->quit();
}
);
};
/******************************************************************************\
* test case 2: *
* *
* A D C *
* | | | *
* | --(sync_send)--> | | *
* | | --(sync_send)--> | *
* | | |---\ *
* | | | | *
* | | |<--/ *
* | | <---(reply)----- | *
* | <---(reply)----- | *
* X X *
\******************************************************************************/
struct D : popular_actor {
response_handle m_handle;
D(const actor_ptr& buddy) : popular_actor(buddy) { }
void init() {
become (
others() >> [=] {
m_handle = make_response_handle();
sync_send_tuple(buddy(), last_dequeued()).then([=] {
m_handle.apply(last_dequeued());
quit();
});
}
);
}
};
int main() {
CPPA_TEST(test__sync_send);
auto await_success_message = [&] {
receive (
on(atom("success")) >> CPPA_CHECKPOINT_CB(),
on(atom("failure")) >> CPPA_ERROR_CB("A didn't receive sync response"),
on(atom("DOWN"), arg_match).when(_x2 != exit_reason::normal)
>> [&](uint32_t err) {
CPPA_ERROR("A exited for reason " << err);
}
);
};
send(spawn_monitor<A>(self), atom("go"), spawn<B>(spawn<C>()));
await_success_message();
await_all_others_done();
send(spawn_monitor<A>(self), atom("go"), spawn<D>(spawn<C>()));
await_success_message();
await_all_others_done();
timed_sync_send(self, std::chrono::milliseconds(50), atom("NoWay")).await(
on(atom("TIMEOUT")) >> CPPA_CHECKPOINT_CB(),
others() >> CPPA_UNEXPECTED_MSG_CB()
);
// we should have received two DOWN messages with normal exit reason
int i = 0;
receive_for(i, 2) (
on(atom("DOWN"), exit_reason::normal) >> CPPA_CHECKPOINT_CB(),
others() >> CPPA_UNEXPECTED_MSG_CB(),
after(std::chrono::seconds(0)) >> CPPA_UNEXPECTED_TOUT_CB()
);
shutdown();
return CPPA_TEST_RESULT;
}
<commit_msg>check whether mailbox is empty at end of unit test<commit_after>#include "test.hpp"
#include "cppa/cppa.hpp"
using namespace cppa;
using namespace cppa::placeholders;
struct popular_actor : event_based_actor { // popular actors have a buddy
actor_ptr m_buddy;
popular_actor(const actor_ptr& buddy) : m_buddy(buddy) { }
inline const actor_ptr& buddy() const { return m_buddy; }
void report_failure() {
send(buddy(), atom("failure"));
self->quit();
}
};
/******************************************************************************\
* test case 1: *
* *
* A B C *
* | | | *
* | --(sync_send)--> | | *
* | | --(forward)----> | *
* | X |---\ *
* | | | *
* | |<--/ *
* | <-------------(reply)-------------- | *
* X X *
\******************************************************************************/
struct A : popular_actor {
A(const actor_ptr& buddy) : popular_actor(buddy) { }
void init() {
become (
on(atom("go"), arg_match) >> [=](const actor_ptr& next) {
sync_send(next, atom("gogo")).then([=] {
send(buddy(), atom("success"));
quit();
});
},
others() >> [=] { report_failure(); }
);
}
};
#ifdef __clang__
struct B : sb_actor<B,popular_actor> {
B(const actor_ptr& buddy) : sb_actor<B,popular_actor>(buddy) { }
behavior init_state = (
others() >> [=] {
forward_to(buddy());
quit();
}
);
};
#else
struct B : popular_actor {
B(const actor_ptr& buddy) : popular_actor(buddy) { }
void init() {
become (
others() >> [=] {
forward_to(buddy());
quit();
}
);
}
};
#endif
struct C : sb_actor<C> {
behavior init_state = (
on(atom("gogo")) >> [=] {
reply(atom("gogogo"));
self->quit();
}
);
};
/******************************************************************************\
* test case 2: *
* *
* A D C *
* | | | *
* | --(sync_send)--> | | *
* | | --(sync_send)--> | *
* | | |---\ *
* | | | | *
* | | |<--/ *
* | | <---(reply)----- | *
* | <---(reply)----- | *
* X X *
\******************************************************************************/
struct D : popular_actor {
response_handle m_handle;
D(const actor_ptr& buddy) : popular_actor(buddy) { }
void init() {
become (
others() >> [=] {
m_handle = make_response_handle();
sync_send_tuple(buddy(), last_dequeued()).then([=] {
m_handle.apply(last_dequeued());
quit();
});
}
);
}
};
int main() {
CPPA_TEST(test__sync_send);
auto await_success_message = [&] {
receive (
on(atom("success")) >> CPPA_CHECKPOINT_CB(),
on(atom("failure")) >> CPPA_ERROR_CB("A didn't receive sync response"),
on(atom("DOWN"), arg_match).when(_x2 != exit_reason::normal)
>> [&](uint32_t err) {
CPPA_ERROR("A exited for reason " << err);
}
);
};
send(spawn_monitor<A>(self), atom("go"), spawn<B>(spawn<C>()));
await_success_message();
await_all_others_done();
send(spawn_monitor<A>(self), atom("go"), spawn<D>(spawn<C>()));
await_success_message();
await_all_others_done();
timed_sync_send(self, std::chrono::milliseconds(50), atom("NoWay")).await(
on(atom("TIMEOUT")) >> CPPA_CHECKPOINT_CB(),
others() >> CPPA_UNEXPECTED_MSG_CB()
);
// we should have received two DOWN messages with normal exit reason
// plus 'NoWay'
int i = 0;
receive_for(i, 3) (
on(atom("DOWN"), exit_reason::normal) >> CPPA_CHECKPOINT_CB(),
on(atom("NoWay")) >> CPPA_CHECKPOINT_CB(),
others() >> CPPA_UNEXPECTED_MSG_CB(),
after(std::chrono::seconds(0)) >> CPPA_UNEXPECTED_TOUT_CB()
);
CPPA_CHECKPOINT();
// mailbox should be empty now
receive (
others() >> CPPA_UNEXPECTED_MSG_CB(),
after(std::chrono::seconds(0)) >> CPPA_CHECKPOINT_CB()
);
shutdown();
return CPPA_TEST_RESULT;
}
<|endoftext|>
|
<commit_before>/*
* ObjectControllerImplementation.cpp
*
* Created on: 11/08/2009
* Author: victor
*/
#include "ObjectController.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/objectcontroller/command/CommandConfigManager.h"
#include "server/zone/managers/objectcontroller/command/CommandList.h"
#include "server/zone/objects/creature/LuaCreatureObject.h"
#include "server/zone/objects/player/PlayerCreature.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/db/ServerDatabase.h"
void ObjectControllerImplementation::loadCommands() {
configManager = new CommandConfigManager(server);
queueCommands = new CommandList();
info("loading queue commands...", true);
configManager->loadSlashCommandsFile(queueCommands);
configManager->registerSpecialCommands();
StringBuffer infoMsg;
infoMsg << "loaded " << queueCommands->size() << " commands";
info(infoMsg.toString(), true);
// LUA
init();
Luna<LuaCreatureObject>::Register(L);
}
void ObjectControllerImplementation::finalize() {
info("deleting object controller", true);
delete configManager;
configManager = NULL;
CommandConfigManager::slashCommands = NULL;
delete queueCommands;
queueCommands = NULL;
}
bool ObjectControllerImplementation::transferObject(SceneObject* objectToTransfer, SceneObject* destinationObject, int containmentType, bool notifyClient) {
ManagedReference<SceneObject*> parent = objectToTransfer->getParent();
if (parent == NULL) {
error("objectToTransfer parent is NULL in ObjectManager::transferObject");
return false;
}
if (destinationObject->getZone() != NULL && objectToTransfer->getZone() == NULL)
destinationObject->broadcastObject(objectToTransfer, false);
uint32 oldContainmentType = objectToTransfer->getContainmentType();
//What about nested containers inside of the inventory...
SceneObject* playerParent = objectToTransfer->getParentRecursively(SceneObject::PLAYERCREATURE);
if (playerParent != NULL && destinationObject->isCellObject())
objectToTransfer->sendDestroyTo(playerParent);
if (parent->isCellObject()) {
objectToTransfer->removeFromZone();
parent->removeObject(objectToTransfer, false);
} else {
if (!parent->removeObject(objectToTransfer)) {
error("could not remove objectToTransfer from parent in ObjectManager::transferObject");
return false;
}
}
if (parent->isCellObject()) {
objectToTransfer->sendTo(destinationObject->getParent(), true);
}
if (!destinationObject->addObject(objectToTransfer, containmentType, notifyClient)) {
error("could not add objectToTransfer to destinationObject in ObjectManager::transferObject");
parent->addObject(objectToTransfer, oldContainmentType);
if (parent->isCellObject()) {
Zone* zne = destinationObject->getParent()->getZone();
objectToTransfer->insertToZone(zne);
}
return false;
}
if (destinationObject->isCellObject()) {
if (destinationObject->getParent() != NULL) {
Zone* zne = destinationObject->getParent()->getZone();
if (zne != NULL) {
objectToTransfer->insertToZone(zne);
//System::out << "Inserted to zone" << endl;
}
}
}
if (parent->isContainerObject() && parent->getGameObjectType() == SceneObject::STATICLOOTCONTAINER) {
objectToTransfer->sendTo(destinationObject, true);
}
if (destinationObject->isPlayerCreature() && parent->isCellObject())
objectToTransfer->sendTo(destinationObject, true);
parent->updateToDatabase();
//destinationObject->updateToDatabaseAllObjects(false);
return true;
}
float ObjectControllerImplementation::activateCommand(CreatureObject* object, unsigned int actionCRC, unsigned int actionCount, uint64 targetID, const UnicodeString& arguments) {
// Pre: object is wlocked
// Post: object is wlocked
QueueCommand* queueCommand = getQueueCommand(actionCRC);
float durationTime = 0.f;
if (queueCommand == NULL) {
StringBuffer msg;
msg << "unregistered queue command 0x" << hex << actionCRC << " arguments: " << arguments.toString();
object->error(msg.toString());
return 0.f;
}
/*StringBuffer infoMsg;
infoMsg << "activating queue command 0x" << hex << actionCRC << " " << queueCommand->getQueueCommandName() << " arguments='" << arguments.toString() << "'";
object->info(infoMsg.toString(), true);*/
String characterAbility = queueCommand->getCharacterAbility();
if (characterAbility.length() > 1) {
object->info("activating characterAbility " + characterAbility);
if (object->isPlayerCreature()) {
PlayerObject* playerObject = (PlayerObject*) object->getSlottedObject("ghost");
if (!playerObject->hasSkill(characterAbility)) {
object->clearQueueAction(actionCount, 0, 2);
return 0.f;
}
}
}
int errorNumber = queueCommand->doQueueCommand(object, targetID, arguments);
//onFail onComplete must clear the action from client queue
if (errorNumber != QueueCommand::SUCCESS)
queueCommand->onFail(actionCount, object, errorNumber);
else {
if (queueCommand->getDefaultPriority() != QueueCommand::IMMEDIATE)
durationTime = queueCommand->getCommandDuration(object);
queueCommand->onComplete(actionCount, object, durationTime);
}
return durationTime;
}
void ObjectControllerImplementation::addQueueCommand(QueueCommand* command) {
queueCommands->put(command);
}
QueueCommand* ObjectControllerImplementation::getQueueCommand(const String& name) {
return queueCommands->getSlashCommand(name);
}
QueueCommand* ObjectControllerImplementation::getQueueCommand(uint32 crc) {
return queueCommands->getSlashCommand(crc);
}
<commit_msg>[fixed] ObjectController<commit_after>/*
* ObjectControllerImplementation.cpp
*
* Created on: 11/08/2009
* Author: victor
*/
#include "ObjectController.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/objectcontroller/command/CommandConfigManager.h"
#include "server/zone/managers/objectcontroller/command/CommandList.h"
#include "server/zone/objects/creature/LuaCreatureObject.h"
#include "server/zone/objects/player/PlayerCreature.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/db/ServerDatabase.h"
void ObjectControllerImplementation::loadCommands() {
configManager = new CommandConfigManager(server);
queueCommands = new CommandList();
info("loading queue commands...", true);
configManager->loadSlashCommandsFile(queueCommands);
configManager->registerSpecialCommands();
StringBuffer infoMsg;
infoMsg << "loaded " << queueCommands->size() << " commands";
info(infoMsg.toString(), true);
// LUA
init();
Luna<LuaCreatureObject>::Register(L);
}
void ObjectControllerImplementation::finalize() {
info("deleting object controller", true);
delete configManager;
configManager = NULL;
CommandConfigManager::slashCommands = NULL;
delete queueCommands;
queueCommands = NULL;
}
bool ObjectControllerImplementation::transferObject(SceneObject* objectToTransfer, SceneObject* destinationObject, int containmentType, bool notifyClient) {
ManagedReference<SceneObject*> parent = objectToTransfer->getParent();
if (parent == NULL) {
error("objectToTransfer parent is NULL in ObjectManager::transferObject");
return false;
}
if (destinationObject->getZone() != NULL && objectToTransfer->getZone() == NULL)
destinationObject->broadcastObject(objectToTransfer, false);
uint32 oldContainmentType = objectToTransfer->getContainmentType();
//What about nested containers inside of the inventory...
SceneObject* playerParent = objectToTransfer->getParentRecursively(SceneObject::PLAYERCREATURE);
if (playerParent != NULL && destinationObject->isCellObject())
objectToTransfer->sendDestroyTo(playerParent);
if (parent->isCellObject()) {
objectToTransfer->removeFromZone();
parent->removeObject(objectToTransfer, false);
} else {
if (!parent->removeObject(objectToTransfer)) {
error("could not remove objectToTransfer from parent in ObjectManager::transferObject");
return false;
}
}
if (parent->isCellObject()) {
objectToTransfer->sendTo(destinationObject->getParent(), true);
}
if (!destinationObject->addObject(objectToTransfer, containmentType, notifyClient)) {
error("could not add objectToTransfer to destinationObject in ObjectManager::transferObject");
parent->addObject(objectToTransfer, oldContainmentType);
if (parent->isCellObject()) {
Zone* zne = destinationObject->getParent()->getZone();
objectToTransfer->insertToZone(zne);
}
return false;
}
if (destinationObject->isCellObject()) {
if (destinationObject->getParent() != NULL) {
Zone* zne = destinationObject->getParent()->getZone();
if (zne != NULL) {
objectToTransfer->insertToZone(zne);
//System::out << "Inserted to zone" << endl;
}
}
}
if (parent->isContainerObject() && parent->getGameObjectType() == SceneObject::STATICLOOTCONTAINER) {
objectToTransfer->sendTo(destinationObject, true);
}
if (objectToTransfer->isContainerObject()) {
objectToTransfer->sendTo(destinationObject, true);
}
if (destinationObject->isPlayerCreature() && parent->isCellObject())
objectToTransfer->sendTo(destinationObject, true);
parent->updateToDatabase();
//destinationObject->updateToDatabaseAllObjects(false);
return true;
}
float ObjectControllerImplementation::activateCommand(CreatureObject* object, unsigned int actionCRC, unsigned int actionCount, uint64 targetID, const UnicodeString& arguments) {
// Pre: object is wlocked
// Post: object is wlocked
QueueCommand* queueCommand = getQueueCommand(actionCRC);
float durationTime = 0.f;
if (queueCommand == NULL) {
StringBuffer msg;
msg << "unregistered queue command 0x" << hex << actionCRC << " arguments: " << arguments.toString();
object->error(msg.toString());
return 0.f;
}
/*StringBuffer infoMsg;
infoMsg << "activating queue command 0x" << hex << actionCRC << " " << queueCommand->getQueueCommandName() << " arguments='" << arguments.toString() << "'";
object->info(infoMsg.toString(), true);*/
String characterAbility = queueCommand->getCharacterAbility();
if (characterAbility.length() > 1) {
object->info("activating characterAbility " + characterAbility);
if (object->isPlayerCreature()) {
PlayerObject* playerObject = (PlayerObject*) object->getSlottedObject("ghost");
if (!playerObject->hasSkill(characterAbility)) {
object->clearQueueAction(actionCount, 0, 2);
return 0.f;
}
}
}
int errorNumber = queueCommand->doQueueCommand(object, targetID, arguments);
//onFail onComplete must clear the action from client queue
if (errorNumber != QueueCommand::SUCCESS)
queueCommand->onFail(actionCount, object, errorNumber);
else {
if (queueCommand->getDefaultPriority() != QueueCommand::IMMEDIATE)
durationTime = queueCommand->getCommandDuration(object);
queueCommand->onComplete(actionCount, object, durationTime);
}
return durationTime;
}
void ObjectControllerImplementation::addQueueCommand(QueueCommand* command) {
queueCommands->put(command);
}
QueueCommand* ObjectControllerImplementation::getQueueCommand(const String& name) {
return queueCommands->getSlashCommand(name);
}
QueueCommand* ObjectControllerImplementation::getQueueCommand(uint32 crc) {
return queueCommands->getSlashCommand(crc);
}
<|endoftext|>
|
<commit_before>//===--- tools/extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp ----------=== //
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file This file implements ClangTidyDiagnosticConsumer, ClangTidyMessage,
/// ClangTidyContext and ClangTidyError classes.
///
/// This tool uses the Clang Tooling infrastructure, see
/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
/// for details on setting it up with LLVM source tree.
///
//===----------------------------------------------------------------------===//
#include "ClangTidyDiagnosticConsumer.h"
#include "ClangTidyOptions.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Frontend/DiagnosticRenderer.h"
#include "llvm/ADT/SmallString.h"
#include <set>
#include <tuple>
using namespace clang;
using namespace tidy;
namespace {
class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
public:
ClangTidyDiagnosticRenderer(const LangOptions &LangOpts,
DiagnosticOptions *DiagOpts,
ClangTidyError &Error)
: DiagnosticRenderer(LangOpts, DiagOpts), Error(Error) {}
protected:
void emitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc,
DiagnosticsEngine::Level Level, StringRef Message,
ArrayRef<CharSourceRange> Ranges,
const SourceManager *SM,
DiagOrStoredDiag Info) override {
ClangTidyMessage TidyMessage = Loc.isValid()
? ClangTidyMessage(Message, *SM, Loc)
: ClangTidyMessage(Message);
if (Level == DiagnosticsEngine::Note) {
Error.Notes.push_back(TidyMessage);
return;
}
assert(Error.Message.Message.empty() &&
"Overwriting a diagnostic message");
Error.Message = TidyMessage;
}
void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
DiagnosticsEngine::Level Level,
ArrayRef<CharSourceRange> Ranges,
const SourceManager &SM) override {}
void emitBasicNote(StringRef Message) override {
Error.Notes.push_back(ClangTidyMessage(Message));
}
void emitCodeContext(SourceLocation Loc, DiagnosticsEngine::Level Level,
SmallVectorImpl<CharSourceRange> &Ranges,
ArrayRef<FixItHint> Hints,
const SourceManager &SM) override {
assert(Loc.isValid());
for (const auto &FixIt : Hints) {
CharSourceRange Range = FixIt.RemoveRange;
assert(Range.getBegin().isValid() && Range.getEnd().isValid() &&
"Invalid range in the fix-it hint.");
assert(Range.getBegin().isFileID() && Range.getEnd().isFileID() &&
"Only file locations supported in fix-it hints.");
Error.Fix.insert(tooling::Replacement(SM, Range, FixIt.CodeToInsert));
}
}
void emitIncludeLocation(SourceLocation Loc, PresumedLoc PLoc,
const SourceManager &SM) override {}
void emitImportLocation(SourceLocation Loc, PresumedLoc PLoc,
StringRef ModuleName,
const SourceManager &SM) override {}
void emitBuildingModuleLocation(SourceLocation Loc, PresumedLoc PLoc,
StringRef ModuleName,
const SourceManager &SM) override {}
void endDiagnostic(DiagOrStoredDiag D,
DiagnosticsEngine::Level Level) override {
assert(!Error.Message.Message.empty() && "Message has not been set");
}
private:
ClangTidyError &Error;
};
} // end anonymous namespace
ClangTidyMessage::ClangTidyMessage(StringRef Message) : Message(Message) {}
ClangTidyMessage::ClangTidyMessage(StringRef Message,
const SourceManager &Sources,
SourceLocation Loc)
: Message(Message) {
assert(Loc.isValid() && Loc.isFileID());
FilePath = Sources.getFilename(Loc);
FileOffset = Sources.getFileOffset(Loc);
}
ClangTidyError::ClangTidyError(StringRef CheckName,
ClangTidyError::Level DiagLevel)
: CheckName(CheckName), DiagLevel(DiagLevel) {}
// Returns true if GlobList starts with the negative indicator ('-'), removes it
// from the GlobList.
static bool ConsumeNegativeIndicator(StringRef &GlobList) {
if (GlobList.startswith("-")) {
GlobList = GlobList.substr(1);
return true;
}
return false;
}
// Converts first glob from the comma-separated list of globs to Regex and
// removes it and the trailing comma from the GlobList.
static llvm::Regex ConsumeGlob(StringRef &GlobList) {
StringRef Glob = GlobList.substr(0, GlobList.find(','));
GlobList = GlobList.substr(Glob.size() + 1);
llvm::SmallString<128> RegexText("^");
StringRef MetaChars("()^$|*+?.[]\\{}");
for (char C : Glob) {
if (C == '*')
RegexText.push_back('.');
else if (MetaChars.find(C) != StringRef::npos)
RegexText.push_back('\\');
RegexText.push_back(C);
}
RegexText.push_back('$');
return llvm::Regex(RegexText);
}
ChecksFilter::ChecksFilter(StringRef GlobList)
: Positive(!ConsumeNegativeIndicator(GlobList)),
Regex(ConsumeGlob(GlobList)),
NextFilter(GlobList.empty() ? nullptr : new ChecksFilter(GlobList)) {}
bool ChecksFilter::isCheckEnabled(StringRef Name, bool Enabled) {
if (Regex.match(Name))
Enabled = Positive;
if (NextFilter)
Enabled = NextFilter->isCheckEnabled(Name, Enabled);
return Enabled;
}
ClangTidyContext::ClangTidyContext(ClangTidyOptionsProvider *OptionsProvider)
: DiagEngine(nullptr), OptionsProvider(OptionsProvider) {
// Before the first translation unit we can get errors related to command-line
// parsing, use empty string for the file name in this case.
setCurrentFile("");
}
DiagnosticBuilder ClangTidyContext::diag(
StringRef CheckName, SourceLocation Loc, StringRef Description,
DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
assert(Loc.isValid());
bool Invalid;
const char *CharacterData =
DiagEngine->getSourceManager().getCharacterData(Loc, &Invalid);
if (!Invalid) {
const char *P = CharacterData;
while (*P != '\0' && *P != '\r' && *P != '\n')
++P;
StringRef RestOfLine(CharacterData, P - CharacterData + 1);
// FIXME: Handle /\bNOLINT\b(\([^)]*\))?/ as cpplint.py does.
if (RestOfLine.find("NOLINT") != StringRef::npos) {
Level = DiagnosticIDs::Ignored;
++Stats.ErrorsIgnoredNOLINT;
}
}
unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
Level, (Description + " [" + CheckName + "]").str());
if (CheckNamesByDiagnosticID.count(ID) == 0)
CheckNamesByDiagnosticID.insert(std::make_pair(ID, CheckName.str()));
return DiagEngine->Report(Loc, ID);
}
void ClangTidyContext::setDiagnosticsEngine(DiagnosticsEngine *Engine) {
DiagEngine = Engine;
}
void ClangTidyContext::setSourceManager(SourceManager *SourceMgr) {
DiagEngine->setSourceManager(SourceMgr);
}
void ClangTidyContext::setCurrentFile(StringRef File) {
CurrentFile = File;
CheckFilter.reset(new ChecksFilter(getOptions().Checks));
}
const ClangTidyGlobalOptions &ClangTidyContext::getGlobalOptions() const {
return OptionsProvider->getGlobalOptions();
}
const ClangTidyOptions &ClangTidyContext::getOptions() const {
return OptionsProvider->getOptions(CurrentFile);
}
ChecksFilter &ClangTidyContext::getChecksFilter() {
assert(CheckFilter != nullptr);
return *CheckFilter;
}
/// \brief Store a \c ClangTidyError.
void ClangTidyContext::storeError(const ClangTidyError &Error) {
Errors.push_back(Error);
}
StringRef ClangTidyContext::getCheckName(unsigned DiagnosticID) const {
llvm::DenseMap<unsigned, std::string>::const_iterator I =
CheckNamesByDiagnosticID.find(DiagnosticID);
if (I != CheckNamesByDiagnosticID.end())
return I->second;
return "";
}
ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(ClangTidyContext &Ctx)
: Context(Ctx), LastErrorRelatesToUserCode(false),
LastErrorPassesLineFilter(false) {
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Diags.reset(new DiagnosticsEngine(
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts, this,
/*ShouldOwnClient=*/false));
Context.setDiagnosticsEngine(Diags.get());
}
void ClangTidyDiagnosticConsumer::finalizeLastError() {
if (!Errors.empty()) {
ClangTidyError &Error = Errors.back();
if (!Context.getChecksFilter().isCheckEnabled(Error.CheckName) &&
Error.DiagLevel != ClangTidyError::Error) {
++Context.Stats.ErrorsIgnoredCheckFilter;
Errors.pop_back();
} else if (!LastErrorRelatesToUserCode) {
++Context.Stats.ErrorsIgnoredNonUserCode;
Errors.pop_back();
} else if (!LastErrorPassesLineFilter) {
++Context.Stats.ErrorsIgnoredLineFilter;
Errors.pop_back();
} else {
++Context.Stats.ErrorsDisplayed;
}
}
LastErrorRelatesToUserCode = false;
LastErrorPassesLineFilter = false;
}
void ClangTidyDiagnosticConsumer::HandleDiagnostic(
DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
if (DiagLevel == DiagnosticsEngine::Note) {
assert(!Errors.empty() &&
"A diagnostic note can only be appended to a message.");
} else {
// FIXME: Pass all errors here regardless of filters and non-user code.
finalizeLastError();
StringRef WarningOption =
Context.DiagEngine->getDiagnosticIDs()->getWarningOptionForDiag(
Info.getID());
std::string CheckName = !WarningOption.empty()
? ("clang-diagnostic-" + WarningOption).str()
: Context.getCheckName(Info.getID()).str();
ClangTidyError::Level Level = ClangTidyError::Warning;
if (DiagLevel == DiagnosticsEngine::Error ||
DiagLevel == DiagnosticsEngine::Fatal) {
Level = ClangTidyError::Error;
LastErrorRelatesToUserCode = true;
LastErrorPassesLineFilter = true;
}
Errors.push_back(ClangTidyError(CheckName, Level));
}
// FIXME: Provide correct LangOptions for each file.
LangOptions LangOpts;
ClangTidyDiagnosticRenderer Converter(
LangOpts, &Context.DiagEngine->getDiagnosticOptions(), Errors.back());
SmallString<100> Message;
Info.FormatDiagnostic(Message);
SourceManager *Sources = nullptr;
if (Info.hasSourceManager())
Sources = &Info.getSourceManager();
Converter.emitDiagnostic(Info.getLocation(), DiagLevel, Message,
Info.getRanges(), Info.getFixItHints(), Sources);
checkFilters(Info.getLocation());
}
void ClangTidyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
const Preprocessor *PP) {
// Before the first translation unit we don't need HeaderFilter, as we
// shouldn't get valid source locations in diagnostics.
HeaderFilter.reset(new llvm::Regex(Context.getOptions().HeaderFilterRegex));
}
bool ClangTidyDiagnosticConsumer::passesLineFilter(StringRef FileName,
unsigned LineNumber) const {
if (Context.getGlobalOptions().LineFilter.empty())
return true;
for (const FileFilter& Filter : Context.getGlobalOptions().LineFilter) {
if (FileName.endswith(Filter.Name)) {
if (Filter.LineRanges.empty())
return true;
for (const FileFilter::LineRange &Range : Filter.LineRanges) {
if (Range.first <= LineNumber && LineNumber <= Range.second)
return true;
}
return false;
}
}
return false;
}
void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location) {
// Invalid location may mean a diagnostic in a command line, don't skip these.
if (!Location.isValid()) {
LastErrorRelatesToUserCode = true;
LastErrorPassesLineFilter = true;
return;
}
const SourceManager &Sources = Diags->getSourceManager();
if (Sources.isInSystemHeader(Location))
return;
// FIXME: We start with a conservative approach here, but the actual type of
// location needed depends on the check (in particular, where this check wants
// to apply fixes).
FileID FID = Sources.getDecomposedExpansionLoc(Location).first;
const FileEntry *File = Sources.getFileEntryForID(FID);
// -DMACRO definitions on the command line have locations in a virtual buffer
// that doesn't have a FileEntry. Don't skip these as well.
if (!File) {
LastErrorRelatesToUserCode = true;
LastErrorPassesLineFilter = true;
return;
}
StringRef FileName(File->getName());
assert(LastErrorRelatesToUserCode || Sources.isInMainFile(Location) ||
HeaderFilter != nullptr);
LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
Sources.isInMainFile(Location) ||
HeaderFilter->match(FileName);
unsigned LineNumber = Sources.getExpansionLineNumber(Location);
LastErrorPassesLineFilter =
LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber);
}
namespace {
struct LessClangTidyError {
bool operator()(const ClangTidyError *LHS, const ClangTidyError *RHS) const {
const ClangTidyMessage &M1 = LHS->Message;
const ClangTidyMessage &M2 = RHS->Message;
return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
std::tie(M2.FilePath, M2.FileOffset, M2.Message);
}
};
} // end anonymous namespace
// Flushes the internal diagnostics buffer to the ClangTidyContext.
void ClangTidyDiagnosticConsumer::finish() {
finalizeLastError();
std::set<const ClangTidyError*, LessClangTidyError> UniqueErrors;
for (const ClangTidyError &Error : Errors)
UniqueErrors.insert(&Error);
for (const ClangTidyError *Error : UniqueErrors)
Context.storeError(*Error);
Errors.clear();
}
<commit_msg>Track changes from clang r211448.<commit_after>//===--- tools/extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp ----------=== //
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file This file implements ClangTidyDiagnosticConsumer, ClangTidyMessage,
/// ClangTidyContext and ClangTidyError classes.
///
/// This tool uses the Clang Tooling infrastructure, see
/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
/// for details on setting it up with LLVM source tree.
///
//===----------------------------------------------------------------------===//
#include "ClangTidyDiagnosticConsumer.h"
#include "ClangTidyOptions.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Frontend/DiagnosticRenderer.h"
#include "llvm/ADT/SmallString.h"
#include <set>
#include <tuple>
using namespace clang;
using namespace tidy;
namespace {
class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
public:
ClangTidyDiagnosticRenderer(const LangOptions &LangOpts,
DiagnosticOptions *DiagOpts,
ClangTidyError &Error)
: DiagnosticRenderer(LangOpts, DiagOpts), Error(Error) {}
protected:
void emitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc,
DiagnosticsEngine::Level Level, StringRef Message,
ArrayRef<CharSourceRange> Ranges,
const SourceManager *SM,
DiagOrStoredDiag Info) override {
ClangTidyMessage TidyMessage = Loc.isValid()
? ClangTidyMessage(Message, *SM, Loc)
: ClangTidyMessage(Message);
if (Level == DiagnosticsEngine::Note) {
Error.Notes.push_back(TidyMessage);
return;
}
assert(Error.Message.Message.empty() &&
"Overwriting a diagnostic message");
Error.Message = TidyMessage;
}
void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
DiagnosticsEngine::Level Level,
ArrayRef<CharSourceRange> Ranges,
const SourceManager &SM) override {}
void emitCodeContext(SourceLocation Loc, DiagnosticsEngine::Level Level,
SmallVectorImpl<CharSourceRange> &Ranges,
ArrayRef<FixItHint> Hints,
const SourceManager &SM) override {
assert(Loc.isValid());
for (const auto &FixIt : Hints) {
CharSourceRange Range = FixIt.RemoveRange;
assert(Range.getBegin().isValid() && Range.getEnd().isValid() &&
"Invalid range in the fix-it hint.");
assert(Range.getBegin().isFileID() && Range.getEnd().isFileID() &&
"Only file locations supported in fix-it hints.");
Error.Fix.insert(tooling::Replacement(SM, Range, FixIt.CodeToInsert));
}
}
void emitIncludeLocation(SourceLocation Loc, PresumedLoc PLoc,
const SourceManager &SM) override {}
void emitImportLocation(SourceLocation Loc, PresumedLoc PLoc,
StringRef ModuleName,
const SourceManager &SM) override {}
void emitBuildingModuleLocation(SourceLocation Loc, PresumedLoc PLoc,
StringRef ModuleName,
const SourceManager &SM) override {}
void endDiagnostic(DiagOrStoredDiag D,
DiagnosticsEngine::Level Level) override {
assert(!Error.Message.Message.empty() && "Message has not been set");
}
private:
ClangTidyError &Error;
};
} // end anonymous namespace
ClangTidyMessage::ClangTidyMessage(StringRef Message) : Message(Message) {}
ClangTidyMessage::ClangTidyMessage(StringRef Message,
const SourceManager &Sources,
SourceLocation Loc)
: Message(Message) {
assert(Loc.isValid() && Loc.isFileID());
FilePath = Sources.getFilename(Loc);
FileOffset = Sources.getFileOffset(Loc);
}
ClangTidyError::ClangTidyError(StringRef CheckName,
ClangTidyError::Level DiagLevel)
: CheckName(CheckName), DiagLevel(DiagLevel) {}
// Returns true if GlobList starts with the negative indicator ('-'), removes it
// from the GlobList.
static bool ConsumeNegativeIndicator(StringRef &GlobList) {
if (GlobList.startswith("-")) {
GlobList = GlobList.substr(1);
return true;
}
return false;
}
// Converts first glob from the comma-separated list of globs to Regex and
// removes it and the trailing comma from the GlobList.
static llvm::Regex ConsumeGlob(StringRef &GlobList) {
StringRef Glob = GlobList.substr(0, GlobList.find(','));
GlobList = GlobList.substr(Glob.size() + 1);
llvm::SmallString<128> RegexText("^");
StringRef MetaChars("()^$|*+?.[]\\{}");
for (char C : Glob) {
if (C == '*')
RegexText.push_back('.');
else if (MetaChars.find(C) != StringRef::npos)
RegexText.push_back('\\');
RegexText.push_back(C);
}
RegexText.push_back('$');
return llvm::Regex(RegexText);
}
ChecksFilter::ChecksFilter(StringRef GlobList)
: Positive(!ConsumeNegativeIndicator(GlobList)),
Regex(ConsumeGlob(GlobList)),
NextFilter(GlobList.empty() ? nullptr : new ChecksFilter(GlobList)) {}
bool ChecksFilter::isCheckEnabled(StringRef Name, bool Enabled) {
if (Regex.match(Name))
Enabled = Positive;
if (NextFilter)
Enabled = NextFilter->isCheckEnabled(Name, Enabled);
return Enabled;
}
ClangTidyContext::ClangTidyContext(ClangTidyOptionsProvider *OptionsProvider)
: DiagEngine(nullptr), OptionsProvider(OptionsProvider) {
// Before the first translation unit we can get errors related to command-line
// parsing, use empty string for the file name in this case.
setCurrentFile("");
}
DiagnosticBuilder ClangTidyContext::diag(
StringRef CheckName, SourceLocation Loc, StringRef Description,
DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
assert(Loc.isValid());
bool Invalid;
const char *CharacterData =
DiagEngine->getSourceManager().getCharacterData(Loc, &Invalid);
if (!Invalid) {
const char *P = CharacterData;
while (*P != '\0' && *P != '\r' && *P != '\n')
++P;
StringRef RestOfLine(CharacterData, P - CharacterData + 1);
// FIXME: Handle /\bNOLINT\b(\([^)]*\))?/ as cpplint.py does.
if (RestOfLine.find("NOLINT") != StringRef::npos) {
Level = DiagnosticIDs::Ignored;
++Stats.ErrorsIgnoredNOLINT;
}
}
unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
Level, (Description + " [" + CheckName + "]").str());
if (CheckNamesByDiagnosticID.count(ID) == 0)
CheckNamesByDiagnosticID.insert(std::make_pair(ID, CheckName.str()));
return DiagEngine->Report(Loc, ID);
}
void ClangTidyContext::setDiagnosticsEngine(DiagnosticsEngine *Engine) {
DiagEngine = Engine;
}
void ClangTidyContext::setSourceManager(SourceManager *SourceMgr) {
DiagEngine->setSourceManager(SourceMgr);
}
void ClangTidyContext::setCurrentFile(StringRef File) {
CurrentFile = File;
CheckFilter.reset(new ChecksFilter(getOptions().Checks));
}
const ClangTidyGlobalOptions &ClangTidyContext::getGlobalOptions() const {
return OptionsProvider->getGlobalOptions();
}
const ClangTidyOptions &ClangTidyContext::getOptions() const {
return OptionsProvider->getOptions(CurrentFile);
}
ChecksFilter &ClangTidyContext::getChecksFilter() {
assert(CheckFilter != nullptr);
return *CheckFilter;
}
/// \brief Store a \c ClangTidyError.
void ClangTidyContext::storeError(const ClangTidyError &Error) {
Errors.push_back(Error);
}
StringRef ClangTidyContext::getCheckName(unsigned DiagnosticID) const {
llvm::DenseMap<unsigned, std::string>::const_iterator I =
CheckNamesByDiagnosticID.find(DiagnosticID);
if (I != CheckNamesByDiagnosticID.end())
return I->second;
return "";
}
ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(ClangTidyContext &Ctx)
: Context(Ctx), LastErrorRelatesToUserCode(false),
LastErrorPassesLineFilter(false) {
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Diags.reset(new DiagnosticsEngine(
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts, this,
/*ShouldOwnClient=*/false));
Context.setDiagnosticsEngine(Diags.get());
}
void ClangTidyDiagnosticConsumer::finalizeLastError() {
if (!Errors.empty()) {
ClangTidyError &Error = Errors.back();
if (!Context.getChecksFilter().isCheckEnabled(Error.CheckName) &&
Error.DiagLevel != ClangTidyError::Error) {
++Context.Stats.ErrorsIgnoredCheckFilter;
Errors.pop_back();
} else if (!LastErrorRelatesToUserCode) {
++Context.Stats.ErrorsIgnoredNonUserCode;
Errors.pop_back();
} else if (!LastErrorPassesLineFilter) {
++Context.Stats.ErrorsIgnoredLineFilter;
Errors.pop_back();
} else {
++Context.Stats.ErrorsDisplayed;
}
}
LastErrorRelatesToUserCode = false;
LastErrorPassesLineFilter = false;
}
void ClangTidyDiagnosticConsumer::HandleDiagnostic(
DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
if (DiagLevel == DiagnosticsEngine::Note) {
assert(!Errors.empty() &&
"A diagnostic note can only be appended to a message.");
} else {
// FIXME: Pass all errors here regardless of filters and non-user code.
finalizeLastError();
StringRef WarningOption =
Context.DiagEngine->getDiagnosticIDs()->getWarningOptionForDiag(
Info.getID());
std::string CheckName = !WarningOption.empty()
? ("clang-diagnostic-" + WarningOption).str()
: Context.getCheckName(Info.getID()).str();
ClangTidyError::Level Level = ClangTidyError::Warning;
if (DiagLevel == DiagnosticsEngine::Error ||
DiagLevel == DiagnosticsEngine::Fatal) {
Level = ClangTidyError::Error;
LastErrorRelatesToUserCode = true;
LastErrorPassesLineFilter = true;
}
Errors.push_back(ClangTidyError(CheckName, Level));
}
// FIXME: Provide correct LangOptions for each file.
LangOptions LangOpts;
ClangTidyDiagnosticRenderer Converter(
LangOpts, &Context.DiagEngine->getDiagnosticOptions(), Errors.back());
SmallString<100> Message;
Info.FormatDiagnostic(Message);
SourceManager *Sources = nullptr;
if (Info.hasSourceManager())
Sources = &Info.getSourceManager();
Converter.emitDiagnostic(Info.getLocation(), DiagLevel, Message,
Info.getRanges(), Info.getFixItHints(), Sources);
checkFilters(Info.getLocation());
}
void ClangTidyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
const Preprocessor *PP) {
// Before the first translation unit we don't need HeaderFilter, as we
// shouldn't get valid source locations in diagnostics.
HeaderFilter.reset(new llvm::Regex(Context.getOptions().HeaderFilterRegex));
}
bool ClangTidyDiagnosticConsumer::passesLineFilter(StringRef FileName,
unsigned LineNumber) const {
if (Context.getGlobalOptions().LineFilter.empty())
return true;
for (const FileFilter& Filter : Context.getGlobalOptions().LineFilter) {
if (FileName.endswith(Filter.Name)) {
if (Filter.LineRanges.empty())
return true;
for (const FileFilter::LineRange &Range : Filter.LineRanges) {
if (Range.first <= LineNumber && LineNumber <= Range.second)
return true;
}
return false;
}
}
return false;
}
void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location) {
// Invalid location may mean a diagnostic in a command line, don't skip these.
if (!Location.isValid()) {
LastErrorRelatesToUserCode = true;
LastErrorPassesLineFilter = true;
return;
}
const SourceManager &Sources = Diags->getSourceManager();
if (Sources.isInSystemHeader(Location))
return;
// FIXME: We start with a conservative approach here, but the actual type of
// location needed depends on the check (in particular, where this check wants
// to apply fixes).
FileID FID = Sources.getDecomposedExpansionLoc(Location).first;
const FileEntry *File = Sources.getFileEntryForID(FID);
// -DMACRO definitions on the command line have locations in a virtual buffer
// that doesn't have a FileEntry. Don't skip these as well.
if (!File) {
LastErrorRelatesToUserCode = true;
LastErrorPassesLineFilter = true;
return;
}
StringRef FileName(File->getName());
assert(LastErrorRelatesToUserCode || Sources.isInMainFile(Location) ||
HeaderFilter != nullptr);
LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
Sources.isInMainFile(Location) ||
HeaderFilter->match(FileName);
unsigned LineNumber = Sources.getExpansionLineNumber(Location);
LastErrorPassesLineFilter =
LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber);
}
namespace {
struct LessClangTidyError {
bool operator()(const ClangTidyError *LHS, const ClangTidyError *RHS) const {
const ClangTidyMessage &M1 = LHS->Message;
const ClangTidyMessage &M2 = RHS->Message;
return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
std::tie(M2.FilePath, M2.FileOffset, M2.Message);
}
};
} // end anonymous namespace
// Flushes the internal diagnostics buffer to the ClangTidyContext.
void ClangTidyDiagnosticConsumer::finish() {
finalizeLastError();
std::set<const ClangTidyError*, LessClangTidyError> UniqueErrors;
for (const ClangTidyError &Error : Errors)
UniqueErrors.insert(&Error);
for (const ClangTidyError *Error : UniqueErrors)
Context.storeError(*Error);
Errors.clear();
}
<|endoftext|>
|
<commit_before>/* medBrowserArea.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Fri Sep 25 12:23:43 2009 (+0200)
* Version: $Id$
* Last-Updated: Sat Mar 20 20:06:27 2010 (+0100)
* By: Julien Wintz
* Update #: 289
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "medBrowserArea.h"
#include <QtGui>
#include <medSql/medDatabaseController.h>
#include <medSql/medDatabaseExporter.h>
#include <medSql/medDatabaseImporter.h>
#include <medSql/medDatabaseModel.h>
#include <medSql/medDatabaseView.h>
#include <medSql/medDatabasePreview.h>
#include <medGui/medProgressionStack.h>
#include <medGui/medToolBox.h>
#include <medGui/medToolBoxContainer.h>
// /////////////////////////////////////////////////////////////////
// medBrowserArea
// /////////////////////////////////////////////////////////////////
class medBrowserAreaPrivate
{
public:
medToolBoxContainer *toolbox_container;
medDatabasePreview *preview;
medDatabaseModel *model;
medDatabaseView *view;
QTreeView *filesystem_view;
QFileSystemModel *filesystem_model;
QStatusBar *status;
medProgressionStack *progression_stack;
};
medBrowserArea::medBrowserArea(QWidget *parent) : QWidget(parent), d(new medBrowserAreaPrivate)
{
d->preview = new medDatabasePreview(this);
d->model = new medDatabaseModel;
d->view = new medDatabaseView(this);
d->view->setModel(d->model);
// connect(d->preview, SIGNAL(patientClicked(int)), d->view, SLOT(onPatientClicked(int)));
// connect(d->preview, SIGNAL(studyClicked(int)), d->view, SLOT(onStudyClicked(int)));
// connect(d->preview, SIGNAL(seriesClicked(int)), d->view, SLOT(onSeriesClicked(int)));
// connect(d->preview, SIGNAL(imageClicked(int)), d->view, SLOT(onImageClicked(int)));
connect(d->view, SIGNAL(patientClicked(int)), d->preview, SLOT(onPatientClicked(int)));
connect(d->view, SIGNAL(seriesClicked(int)), d->preview, SLOT(onSeriesClicked(int)));
// Database widget /////////////////////////////////////////////////
QWidget *database_widget = new QWidget(this);
QVBoxLayout *database_layout = new QVBoxLayout(database_widget);
database_layout->setContentsMargins(0, 0, 0, 0);
database_layout->setSpacing(0);
database_layout->addWidget(d->view);
database_layout->addWidget(d->preview);
// Filesystem widget ///////////////////////////////////////////////
d->filesystem_model = new QFileSystemModel;
d->filesystem_model->setRootPath(QDir::rootPath());
d->filesystem_view = new QTreeView(this);
d->filesystem_view->setFrameStyle(QFrame::NoFrame);
d->filesystem_view->setAttribute(Qt::WA_MacShowFocusRect, false);
d->filesystem_view->setUniformRowHeights(true);
d->filesystem_view->setAlternatingRowColors(true);
d->filesystem_view->setSortingEnabled(true);
d->filesystem_view->setModel(d->filesystem_model);
d->filesystem_view->setCurrentIndex(d->filesystem_model->index(QDir::homePath()));
d->filesystem_view->setExpanded(d->filesystem_view->currentIndex(), true);
d->filesystem_view->header()->setResizeMode(QHeaderView::Stretch);
// Pacs widget ///////////////////////////////////////////////
QTreeView *pacs_widget = new QTreeView(this);
pacs_widget->setFrameStyle(QFrame::NoFrame);
pacs_widget->setAttribute(Qt::WA_MacShowFocusRect, false);
pacs_widget->setUniformRowHeights(true);
pacs_widget->setAlternatingRowColors(true);
pacs_widget->setSortingEnabled(true);
// /////////////////////////////////////////////////////////////////
QStackedWidget *stack = new QStackedWidget(this);
stack->addWidget(database_widget);
stack->addWidget(d->filesystem_view);
stack->addWidget(pacs_widget);
// Source selector ///////////////////////////////////////////////
QWidget *database_page = new QWidget(this);
QPushButton *database_page_expand_all_button = new QPushButton("All", database_page);
QPushButton *database_page_collapse_all_button = new QPushButton("All", database_page);
connect(database_page_expand_all_button, SIGNAL(clicked()), d->view, SLOT(expandAll()));
connect(database_page_collapse_all_button, SIGNAL(clicked()), d->view, SLOT(collapseAll()));
QFormLayout *database_page_layout = new QFormLayout(database_page);
database_page_layout->addRow("Expand:", database_page_expand_all_button);
database_page_layout->addRow("Collapse:", database_page_collapse_all_button);
database_page_layout->setFormAlignment(Qt::AlignHCenter);
QWidget *filesystem_page = new QWidget(this);
QPushButton *filesystem_import_button = new QPushButton("Import", filesystem_page);
QPushButton *filesystem_export_button = new QPushButton("Export", filesystem_page);
QFormLayout *filesystem_page_layout = new QFormLayout(filesystem_page);
filesystem_page_layout->addRow("Current item:", filesystem_import_button);
filesystem_page_layout->addRow("Current item:", filesystem_export_button);
filesystem_page_layout->setFormAlignment(Qt::AlignHCenter);
connect(filesystem_import_button, SIGNAL(clicked()), this, SLOT(onFileSystemImportClicked()));
connect(filesystem_export_button, SIGNAL(clicked()), this, SLOT(onFileSystemExportClicked()));
QWidget *pacs_page = new QWidget(this);
QFormLayout *pacs_page_layout = new QFormLayout(pacs_page);
pacs_page_layout->addRow("Url:", new QLineEdit(pacs_page));
pacs_page_layout->addRow("Login:", new QLineEdit(pacs_page));
pacs_page_layout->addRow("Password:", new QLineEdit(pacs_page));
pacs_page_layout->addWidget(new QPushButton("Connect", pacs_page));
pacs_page_layout->setFormAlignment(Qt::AlignHCenter);
medToolBoxTab *tab = new medToolBoxTab(this);
tab->addTab(database_page, "Db");
tab->addTab(filesystem_page, "Fs");
tab->addTab(pacs_page, "Pc");
connect(tab, SIGNAL(currentChanged(int)), stack, SLOT(setCurrentIndex(int)));
medToolBox *sourceSelectorToolBox = new medToolBox(this);
sourceSelectorToolBox->setTitle("Source selector");
sourceSelectorToolBox->setWidget(tab);
// Jobs //////////////////////////////////////////
d->progression_stack = new medProgressionStack(filesystem_page);
medToolBox *jobsToolBox = new medToolBox(this);
jobsToolBox->setTitle("Jobs");
jobsToolBox->setWidget(d->progression_stack);
jobsToolBox->setVisible(false);
connect(d->progression_stack, SIGNAL(shown()), jobsToolBox, SLOT(show()));
connect(d->progression_stack, SIGNAL(hidden()), jobsToolBox, SLOT(hide()));
// Toolbox container /////////////////////////////////////////////
d->toolbox_container = new medToolBoxContainer(this);
d->toolbox_container->setFixedWidth(300);
d->toolbox_container->addToolBox(sourceSelectorToolBox);
d->toolbox_container->addToolBox(jobsToolBox);
// Layout /////////////////////////////////////////////
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->addWidget(d->toolbox_container);
layout->addWidget(stack);
}
medBrowserArea::~medBrowserArea(void)
{
delete d->preview;
delete d->model;
delete d->view;
delete d;
d = NULL;
}
void medBrowserArea::setup(QStatusBar *status)
{
d->status = status;
}
void medBrowserArea::setdw(QStatusBar *status)
{
d->status = status;
}
medDatabaseView *medBrowserArea::view(void)
{
return d->view;
}
medDatabaseModel *medBrowserArea::model(void)
{
return d->model;
}
void medBrowserArea::onFileSystemImportClicked(void)
{
QFileInfo info(d->filesystem_model->filePath(d->filesystem_view->currentIndex()));
medDatabaseImporter *importer = new medDatabaseImporter(info.absoluteFilePath());
connect(importer, SIGNAL(progressed(int)), d->progression_stack, SLOT(setProgress(int)));
connect(importer, SIGNAL(done()), this, SLOT(onFileImported()));
d->progression_stack->setLabel(importer, info.baseName());
QThreadPool::globalInstance()->start(importer);
}
void medBrowserArea::onFileSystemExportClicked(void)
{
medDatabaseExporter *exporter = new medDatabaseExporter;
connect(exporter, SIGNAL(progressed(int)), d->progression_stack, SLOT(setProgress(int)));
QThreadPool::globalInstance()->start(exporter);
}
void medBrowserArea::onFileImported(void)
{
medDatabaseController::instance()->import("");
d->preview->reset();
d->preview->init();
d->preview->update();
}
<commit_msg>File system view columns made resizable<commit_after>/* medBrowserArea.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Fri Sep 25 12:23:43 2009 (+0200)
* Version: $Id$
* Last-Updated: Thu Mar 25 18:43:40 2010 (+0100)
* By: Julien Wintz
* Update #: 290
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "medBrowserArea.h"
#include <QtGui>
#include <medSql/medDatabaseController.h>
#include <medSql/medDatabaseExporter.h>
#include <medSql/medDatabaseImporter.h>
#include <medSql/medDatabaseModel.h>
#include <medSql/medDatabaseView.h>
#include <medSql/medDatabasePreview.h>
#include <medGui/medProgressionStack.h>
#include <medGui/medToolBox.h>
#include <medGui/medToolBoxContainer.h>
// /////////////////////////////////////////////////////////////////
// medBrowserArea
// /////////////////////////////////////////////////////////////////
class medBrowserAreaPrivate
{
public:
medToolBoxContainer *toolbox_container;
medDatabasePreview *preview;
medDatabaseModel *model;
medDatabaseView *view;
QTreeView *filesystem_view;
QFileSystemModel *filesystem_model;
QStatusBar *status;
medProgressionStack *progression_stack;
};
medBrowserArea::medBrowserArea(QWidget *parent) : QWidget(parent), d(new medBrowserAreaPrivate)
{
d->preview = new medDatabasePreview(this);
d->model = new medDatabaseModel;
d->view = new medDatabaseView(this);
d->view->setModel(d->model);
// connect(d->preview, SIGNAL(patientClicked(int)), d->view, SLOT(onPatientClicked(int)));
// connect(d->preview, SIGNAL(studyClicked(int)), d->view, SLOT(onStudyClicked(int)));
// connect(d->preview, SIGNAL(seriesClicked(int)), d->view, SLOT(onSeriesClicked(int)));
// connect(d->preview, SIGNAL(imageClicked(int)), d->view, SLOT(onImageClicked(int)));
connect(d->view, SIGNAL(patientClicked(int)), d->preview, SLOT(onPatientClicked(int)));
connect(d->view, SIGNAL(seriesClicked(int)), d->preview, SLOT(onSeriesClicked(int)));
// Database widget /////////////////////////////////////////////////
QWidget *database_widget = new QWidget(this);
QVBoxLayout *database_layout = new QVBoxLayout(database_widget);
database_layout->setContentsMargins(0, 0, 0, 0);
database_layout->setSpacing(0);
database_layout->addWidget(d->view);
database_layout->addWidget(d->preview);
// Filesystem widget ///////////////////////////////////////////////
d->filesystem_model = new QFileSystemModel;
d->filesystem_model->setRootPath(QDir::rootPath());
d->filesystem_view = new QTreeView(this);
d->filesystem_view->setFrameStyle(QFrame::NoFrame);
d->filesystem_view->setAttribute(Qt::WA_MacShowFocusRect, false);
d->filesystem_view->setUniformRowHeights(true);
d->filesystem_view->setAlternatingRowColors(true);
d->filesystem_view->setSortingEnabled(true);
d->filesystem_view->setModel(d->filesystem_model);
d->filesystem_view->setCurrentIndex(d->filesystem_model->index(QDir::homePath()));
d->filesystem_view->setExpanded(d->filesystem_view->currentIndex(), true);
d->filesystem_view->header()->setResizeMode(QHeaderView::Interactive);
// Pacs widget ///////////////////////////////////////////////
QTreeView *pacs_widget = new QTreeView(this);
pacs_widget->setFrameStyle(QFrame::NoFrame);
pacs_widget->setAttribute(Qt::WA_MacShowFocusRect, false);
pacs_widget->setUniformRowHeights(true);
pacs_widget->setAlternatingRowColors(true);
pacs_widget->setSortingEnabled(true);
// /////////////////////////////////////////////////////////////////
QStackedWidget *stack = new QStackedWidget(this);
stack->addWidget(database_widget);
stack->addWidget(d->filesystem_view);
stack->addWidget(pacs_widget);
// Source selector ///////////////////////////////////////////////
QWidget *database_page = new QWidget(this);
QPushButton *database_page_expand_all_button = new QPushButton("All", database_page);
QPushButton *database_page_collapse_all_button = new QPushButton("All", database_page);
connect(database_page_expand_all_button, SIGNAL(clicked()), d->view, SLOT(expandAll()));
connect(database_page_collapse_all_button, SIGNAL(clicked()), d->view, SLOT(collapseAll()));
QFormLayout *database_page_layout = new QFormLayout(database_page);
database_page_layout->addRow("Expand:", database_page_expand_all_button);
database_page_layout->addRow("Collapse:", database_page_collapse_all_button);
database_page_layout->setFormAlignment(Qt::AlignHCenter);
QWidget *filesystem_page = new QWidget(this);
QPushButton *filesystem_import_button = new QPushButton("Import", filesystem_page);
QPushButton *filesystem_export_button = new QPushButton("Export", filesystem_page);
QFormLayout *filesystem_page_layout = new QFormLayout(filesystem_page);
filesystem_page_layout->addRow("Current item:", filesystem_import_button);
filesystem_page_layout->addRow("Current item:", filesystem_export_button);
filesystem_page_layout->setFormAlignment(Qt::AlignHCenter);
connect(filesystem_import_button, SIGNAL(clicked()), this, SLOT(onFileSystemImportClicked()));
connect(filesystem_export_button, SIGNAL(clicked()), this, SLOT(onFileSystemExportClicked()));
QWidget *pacs_page = new QWidget(this);
QFormLayout *pacs_page_layout = new QFormLayout(pacs_page);
pacs_page_layout->addRow("Url:", new QLineEdit(pacs_page));
pacs_page_layout->addRow("Login:", new QLineEdit(pacs_page));
pacs_page_layout->addRow("Password:", new QLineEdit(pacs_page));
pacs_page_layout->addWidget(new QPushButton("Connect", pacs_page));
pacs_page_layout->setFormAlignment(Qt::AlignHCenter);
medToolBoxTab *tab = new medToolBoxTab(this);
tab->addTab(database_page, "Db");
tab->addTab(filesystem_page, "Fs");
tab->addTab(pacs_page, "Pc");
connect(tab, SIGNAL(currentChanged(int)), stack, SLOT(setCurrentIndex(int)));
medToolBox *sourceSelectorToolBox = new medToolBox(this);
sourceSelectorToolBox->setTitle("Source selector");
sourceSelectorToolBox->setWidget(tab);
// Jobs //////////////////////////////////////////
d->progression_stack = new medProgressionStack(filesystem_page);
medToolBox *jobsToolBox = new medToolBox(this);
jobsToolBox->setTitle("Jobs");
jobsToolBox->setWidget(d->progression_stack);
jobsToolBox->setVisible(false);
connect(d->progression_stack, SIGNAL(shown()), jobsToolBox, SLOT(show()));
connect(d->progression_stack, SIGNAL(hidden()), jobsToolBox, SLOT(hide()));
// Toolbox container /////////////////////////////////////////////
d->toolbox_container = new medToolBoxContainer(this);
d->toolbox_container->setFixedWidth(300);
d->toolbox_container->addToolBox(sourceSelectorToolBox);
d->toolbox_container->addToolBox(jobsToolBox);
// Layout /////////////////////////////////////////////
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->addWidget(d->toolbox_container);
layout->addWidget(stack);
}
medBrowserArea::~medBrowserArea(void)
{
delete d->preview;
delete d->model;
delete d->view;
delete d;
d = NULL;
}
void medBrowserArea::setup(QStatusBar *status)
{
d->status = status;
}
void medBrowserArea::setdw(QStatusBar *status)
{
d->status = status;
}
medDatabaseView *medBrowserArea::view(void)
{
return d->view;
}
medDatabaseModel *medBrowserArea::model(void)
{
return d->model;
}
void medBrowserArea::onFileSystemImportClicked(void)
{
QFileInfo info(d->filesystem_model->filePath(d->filesystem_view->currentIndex()));
medDatabaseImporter *importer = new medDatabaseImporter(info.absoluteFilePath());
connect(importer, SIGNAL(progressed(int)), d->progression_stack, SLOT(setProgress(int)));
connect(importer, SIGNAL(done()), this, SLOT(onFileImported()));
d->progression_stack->setLabel(importer, info.baseName());
QThreadPool::globalInstance()->start(importer);
}
void medBrowserArea::onFileSystemExportClicked(void)
{
medDatabaseExporter *exporter = new medDatabaseExporter;
connect(exporter, SIGNAL(progressed(int)), d->progression_stack, SLOT(setProgress(int)));
QThreadPool::globalInstance()->start(exporter);
}
void medBrowserArea::onFileImported(void)
{
medDatabaseController::instance()->import("");
d->preview->reset();
d->preview->init();
d->preview->update();
}
<|endoftext|>
|
<commit_before>#include "HttpSrv.h"
HttpSrv::Connection::Connection(int _sock,
ResponseInfoPtr _resp_info,
boost::function<void(int, HttpSrv::RequestPtr)> _onRequest):
m_sock(_sock),
alive(true),
closing(false),
m_resp_info(_resp_info),
m_http_status_code(200),
m_onRequest(_onRequest) {
http_parser_init(&m_parser, HTTP_REQUEST);
m_parser.data = (void*)this;
m_parser_settings.on_message_begin = HttpSrv_onMessageBegin;
m_parser_settings.on_url = &HttpSrv_onUrl;
m_parser_settings.on_status = &HttpSrv_onStatus;
m_parser_settings.on_header_field = &HttpSrv_onHeadersField;
m_parser_settings.on_header_value = &HttpSrv_onHeadersValue;
m_parser_settings.on_headers_complete = &HttpSrv_onHeadersComplete;
m_parser_settings.on_body = &HttpSrv_onBody;
m_parser_settings.on_message_complete = &HttpSrv_onMessageComplete;
}
HttpSrv::Connection::~Connection() {
std::cout << "http connection closed\n";
}
void HttpSrv::Connection::setHttpStatus(int _code) {
m_http_status_code = _code;
}
void HttpSrv::Connection::addHeader(const std::string &_header) {
m_headers.push_back(_header);
}
void HttpSrv::Connection::setCookie(const std::string &_name, const std::string &_value) {
m_headers.push_back(std::string("Set-Cookie: ") + _name + "=" + _value + "; expires=Sat, 31 Dec 2039 23:59:59 GMT");
}
void HttpSrv::Connection::sendResponse(const std::string &_content) {
//Sat, 28 Dec 2013 18:33:30 GMT
char content_len_c[50];
sprintf(content_len_c, "%d", (int)_content.size());
std::string content_len(content_len_c);
//char time_c[50];
//sprintf(time_c, "%d", asctime(0));
char time_c[50];
sprintf(time_c, "%d", (int)time(0));
std::string response = "HTTP/1.1 " + inttostr(m_http_status_code) + "\r\n"
"Content-Type: "+m_resp_info->content_type+"\r\n"
"Date: "+time_c+"\r\n"
"Server: "+m_resp_info->server_name+"\r\n"
//"Connection: keep-alive\r\n"
"Transfer-Encoding: none\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Connection: close\r\n";
for (int i = 0; i<m_headers.size(); i++)
response += m_headers[i] + "\r\n";
response += "Content-Length: "+content_len+"\r\n\r\n"+_content;
size_t nsent = ::send(m_sock, response.c_str(), response.size(), 0);
std::cout << "send: " << response << std::endl;
if (nsent<=0 || nsent < response.size())
std::cout << "HttpSrv::Connection::sendResponse SEND ERROR!!_____________"
<< nsent << std::endl;
}
void HttpSrv::Connection::close() {
std::cout << "HttpSrv::Connection::close\n";
closing = true;
}
int HttpSrv::Connection::getSock() {
return m_sock;
}
void HttpSrv::Connection::performRecv() {
std::string readbf;
char bf[2049];
int nread = ::recv(m_sock, bf, 2048, MSG_DONTWAIT);
while (true) {
if (nread > 0) {
bf[ nread ] = '\0';
std::string add (bf);
readbf.append( add );
nread = ::recv(m_sock, bf, 2048, MSG_DONTWAIT);
}
else if (errno == EWOULDBLOCK || errno == EAGAIN) {
//std::cout << "HttpSrv::Connection::recv EWOULDBLOCK || EAGAIN\n";
break;
}
else if (errno == EBADF) {
std::cout << "HttpSrv::Connection::recv EBADF\n";
break;
} else if (errno == ECONNREFUSED) {
std::cout << "HttpSrv::Connection::recv ECONNREFUSED\n";
break;
} else if (errno == EFAULT) {
std::cout << "HttpSrv::Connection::recv EFAULT\n";
break;
} else if (errno == EINTR) {
std::cout << "HttpSrv::Connection::recv EINTR\n";
break;
} else if (errno == EINVAL) {
std::cout << "HttpSrv::Connection::recv EINVAL\n";
break;
} else if (errno == ENOMEM) {
std::cout << "HttpSrv::Connection::recv ENOMEM\n";
break;
} else if (errno == ENOTCONN) {
std::cout << "HttpSrv::Connection::recv ENOTCONN\n";
break;
} else if (errno == ENOTSOCK) {
std::cout << "HttpSrv::Connection::recv ENOTSOCK\n";
break;
} else if (nread == 0) {
break;
}
}
//std::cout << "recv: " << readbf << std::endl;
//m_readbf += std::string(bf);
if (readbf.size() > 0) {
m_req_text += readbf;
std::cout << m_req_text << std::endl;
http_parser_execute(&m_parser, &m_parser_settings, readbf.c_str(), readbf.size());
}
}
void HttpSrv::Connection::performSend() {
}
<commit_msg>Fix http connection closing<commit_after>#include "HttpSrv.h"
HttpSrv::Connection::Connection(int _sock,
ResponseInfoPtr _resp_info,
boost::function<void(int, HttpSrv::RequestPtr)> _onRequest):
m_sock(_sock),
alive(true),
closing(false),
m_resp_info(_resp_info),
m_http_status_code(200),
m_onRequest(_onRequest) {
http_parser_init(&m_parser, HTTP_REQUEST);
m_parser.data = (void*)this;
m_parser_settings.on_message_begin = HttpSrv_onMessageBegin;
m_parser_settings.on_url = &HttpSrv_onUrl;
m_parser_settings.on_status = &HttpSrv_onStatus;
m_parser_settings.on_header_field = &HttpSrv_onHeadersField;
m_parser_settings.on_header_value = &HttpSrv_onHeadersValue;
m_parser_settings.on_headers_complete = &HttpSrv_onHeadersComplete;
m_parser_settings.on_body = &HttpSrv_onBody;
m_parser_settings.on_message_complete = &HttpSrv_onMessageComplete;
}
HttpSrv::Connection::~Connection() {
std::cout << "http connection closed\n";
}
void HttpSrv::Connection::setHttpStatus(int _code) {
m_http_status_code = _code;
}
void HttpSrv::Connection::addHeader(const std::string &_header) {
m_headers.push_back(_header);
}
void HttpSrv::Connection::setCookie(const std::string &_name, const std::string &_value) {
m_headers.push_back(std::string("Set-Cookie: ") + _name + "=" + _value + "; expires=Sat, 31 Dec 2039 23:59:59 GMT");
}
void HttpSrv::Connection::sendResponse(const std::string &_content) {
//Sat, 28 Dec 2013 18:33:30 GMT
char content_len_c[50];
sprintf(content_len_c, "%d", (int)_content.size());
std::string content_len(content_len_c);
//char time_c[50];
//sprintf(time_c, "%d", asctime(0));
char time_c[50];
sprintf(time_c, "%d", (int)time(0));
std::string response = "HTTP/1.1 " + inttostr(m_http_status_code) + "\r\n"
"Content-Type: "+m_resp_info->content_type+"\r\n"
"Date: "+time_c+"\r\n"
"Server: "+m_resp_info->server_name+"\r\n"
//"Connection: keep-alive\r\n"
"Transfer-Encoding: none\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Connection: close\r\n";
for (int i = 0; i<m_headers.size(); i++)
response += m_headers[i] + "\r\n";
response += "Content-Length: "+content_len+"\r\n\r\n"+_content;
size_t nsent = ::send(m_sock, response.c_str(), response.size(), 0);
std::cout << "send: " << response << std::endl;
if (nsent<=0 || nsent < response.size())
std::cout << "HttpSrv::Connection::sendResponse SEND ERROR!!_____________"
<< nsent << std::endl;
}
void HttpSrv::Connection::close() {
std::cout << "HttpSrv::Connection::close\n";
closing = true;
}
int HttpSrv::Connection::getSock() {
return m_sock;
}
void HttpSrv::Connection::performRecv() {
std::string readbf;
char bf[2049];
int nread = ::recv(m_sock, bf, 2048, MSG_DONTWAIT);
while (true) {
if (nread > 0) {
bf[ nread ] = '\0';
std::string add (bf);
readbf.append( add );
nread = ::recv(m_sock, bf, 2048, MSG_DONTWAIT);
}
else if (errno == EWOULDBLOCK || errno == EAGAIN) {
//std::cout << "HttpSrv::Connection::recv EWOULDBLOCK || EAGAIN\n";
break;
}
else if (errno == EBADF) {
std::cout << "HttpSrv::Connection::recv EBADF\n";
close();
return;
} else if (errno == ECONNREFUSED) {
std::cout << "HttpSrv::Connection::recv ECONNREFUSED\n";
close();
return;
} else if (errno == EFAULT) {
std::cout << "HttpSrv::Connection::recv EFAULT\n";
close();
return;
} else if (errno == EINTR) {
std::cout << "HttpSrv::Connection::recv EINTR\n";
close();
return;
} else if (errno == EINVAL) {
std::cout << "HttpSrv::Connection::recv EINVAL\n";
close();
return;
} else if (errno == ENOMEM) {
std::cout << "HttpSrv::Connection::recv ENOMEM\n";
close();
return;
} else if (errno == ENOTCONN) {
std::cout << "HttpSrv::Connection::recv ENOTCONN\n";
close();
return;
} else if (errno == ENOTSOCK) {
std::cout << "HttpSrv::Connection::recv ENOTSOCK\n";
close();
return;
} else if (nread == 0) {
break;
}
}
//std::cout << "recv: " << readbf << std::endl;
//m_readbf += std::string(bf);
if (readbf.size() > 0) {
m_req_text += readbf;
std::cout << m_req_text << std::endl;
http_parser_execute(&m_parser, &m_parser_settings, readbf.c_str(), readbf.size());
}
}
void HttpSrv::Connection::performSend() {
}
<|endoftext|>
|
<commit_before>// IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// 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.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// 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.
#include <ifc2x3/SPFReader.h>
#include <ifc2x3/SPFWriter.h>
#include <ifc2x3/ExpressDataSet.h>
#include <ifc2x3/IfcProject.h>
#include <ifc2x3/IfcLocalPlacement.h>
#include <ifc2x3/IfcAxis2Placement.h>
#include <ifc2x3/IfcAxis2Placement2D.h>
#include <ifc2x3/IfcAxis2Placement3D.h>
#include <Step/CallBack.h>
#include <iostream>
#include "BrepBuilder.h"
class ConsoleCallBack : public Step::CallBack
{
public:
ConsoleCallBack() : _max(1) {}
virtual void setMaximum(size_t max) { _max = max; }
virtual void setProgress(size_t progress) { std::cerr << double(progress)/double(_max)*100.0 << "%" << std::endl; }
protected:
size_t _max;
};
int main(int argc, char **argv)
{
std::cout << "Simple read Brep geometry example of Ifc2x3 SDK" << std::endl;
if (argc < 2)
{
std::cout << "no ifc file to read in command line ." << std::endl;
return 1;
}
bool inMemory = true;
if (argc < 4)
{
inMemory = false;
}
// ** open, load, close the file
std::ifstream ifcFile;
ifcFile.open(argv[1]);
ifc2x3::SPFReader reader;
ConsoleCallBack cb;
reader.setCallBack(&cb);
if ( ifcFile.is_open() )
{
std::cout << "reading file ..." << std::endl;
}
else
{
std::cout << "ERROR: failed to open <" << argv[1] << ">" << std::endl;
return 1;
}
// get length of file
ifcFile.seekg (0, ifcFile.end);
std::ifstream::pos_type length = ifcFile.tellg();
ifcFile.seekg (0, ifcFile.beg);
bool result = reader.read(ifcFile, inMemory ? length : (std::ifstream::pos_type)0);
ifcFile.close();
if (result)
std::cout << "OK!!" << std::endl;
else
{
std::cout << "Ho no, there is a PROBLEM!!" << std::endl;
std::vector<std::string> errors = reader.errors();
std::vector<std::string>::iterator it = errors.begin();
while(it != errors.end())
{
std::cout << *it << std::endl;
++it;
}
return 1;
}
// ** get the model
ifc2x3::ExpressDataSet * expressDataSet = dynamic_cast<ifc2x3::ExpressDataSet*>(reader.getExpressDataSet());
if (expressDataSet == NULL)
{
std::cout << "Ho no ... there is no ExpressDataSet." << std::endl;
return (2);
}
// ** Instantiate the model
expressDataSet->instantiateAll();
// ** Check the root of the model
Step::RefLinkedList< ifc2x3::IfcProject > projects = expressDataSet->getAllIfcProject();
if ( projects.size() == 0 ) {
std::cout << "Strange ... there is no IfcProject" << std::endl;
} else if ( projects.size() > 1 ) {
std::cout << "Strange ... there more than one IfcProject" << std::endl;
} else {
Step::RefPtr< ifc2x3::IfcProject > project = &*(projects.begin());
std::cout << "Project name is: " << project->getName().toISO_8859(Step::String::Western_European) << std::endl;
if ( Step::isUnset(project->getLongName().toISO_8859(Step::String::Western_European) ) ) {
project->setLongName("Je lui donne le nom que je veux");
}
std::cout << "Project long name is: " << project->getLongName().toISO_8859(Step::String::Western_European) << std::endl;
}
return 0;
}
<commit_msg>start to add visitor<commit_after>// IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// 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.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// 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.
#include <ifc2x3/SPFReader.h>
#include <ifc2x3/SPFWriter.h>
#include <ifc2x3/ExpressDataSet.h>
#include <ifc2x3/IfcProject.h>
#include <ifc2x3/IfcLocalPlacement.h>
#include <ifc2x3/IfcAxis2Placement.h>
#include <ifc2x3/IfcAxis2Placement2D.h>
#include <ifc2x3/IfcAxis2Placement3D.h>
#include <Step/CallBack.h>
#include <iostream>
#include "BrepBuilder.h"
#include "BrepReaderVisitor.h"
class ConsoleCallBack : public Step::CallBack
{
public:
ConsoleCallBack() : _max(1) {}
virtual void setMaximum(size_t max) { _max = max; }
virtual void setProgress(size_t progress) { std::cerr << double(progress)/double(_max)*100.0 << "%" << std::endl; }
protected:
size_t _max;
};
int main(int argc, char **argv)
{
std::cout << "Simple read Brep geometry example of Ifc2x3 SDK" << std::endl;
if (argc < 2)
{
std::cout << "no ifc file to read in command line ." << std::endl;
return 1;
}
bool inMemory = true;
if (argc < 4)
{
inMemory = false;
}
// ** open, load, close the file
std::ifstream ifcFile;
ifcFile.open(argv[1]);
ifc2x3::SPFReader reader;
ConsoleCallBack cb;
reader.setCallBack(&cb);
if ( ifcFile.is_open() )
{
std::cout << "reading file ..." << std::endl;
}
else
{
std::cout << "ERROR: failed to open <" << argv[1] << ">" << std::endl;
return 1;
}
// get length of file
ifcFile.seekg (0, ifcFile.end);
std::ifstream::pos_type length = ifcFile.tellg();
ifcFile.seekg (0, ifcFile.beg);
bool result = reader.read(ifcFile, inMemory ? length : (std::ifstream::pos_type)0);
ifcFile.close();
if (result)
std::cout << "OK!!" << std::endl;
else
{
std::cout << "Ho no, there is a PROBLEM!!" << std::endl;
std::vector<std::string> errors = reader.errors();
std::vector<std::string>::iterator it = errors.begin();
while(it != errors.end())
{
std::cout << *it << std::endl;
++it;
}
return 1;
}
// ** get the model
ifc2x3::ExpressDataSet * expressDataSet = dynamic_cast<ifc2x3::ExpressDataSet*>(reader.getExpressDataSet());
if (expressDataSet == NULL)
{
std::cout << "Ho no ... there is no ExpressDataSet." << std::endl;
return (2);
}
// ** Instantiate the model
expressDataSet->instantiateAll();
// ** Get buildingElement
Step::RefLinkedList< ifc2x3::IfcBuildingElement > elements = expressDataSet->getAllIfcBuildingElement();
if ( elements.size() == 0 )
{
std::cout << "Strange ... there is no IfcBuildingElement" << std::endl;
}
else
{
Step::RefPtr< ifc2x3::IfcBuildingElement > element = &*(elements.begin());
Step::RefLinkedList_iterator<ifc2x3::IfcBuildingElement> it,end;
it = expressDataSet->getAllIfcBuildingElement().begin();
end = expressDataSet->getAllIfcBuildingElement().end();
while (it != end)
{
BrepReaderVisitor visitor();
//(*it).acceptVisitor(&visitor);
++it;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>// @(#)root/eve:$Id$
// Author: Matevz Tadel 2007
/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
* See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for *
* full copyright notice. *
**************************************************************************/
#include "AliEveV0Editor.h"
#include "AliEveV0.h"
#include "TVirtualPad.h"
#include "TColor.h"
// Cleanup these includes:
#include "TGLabel.h"
#include "TGButton.h"
#include "TGNumberEntry.h"
#include "TGColorSelect.h"
#include "TGDoubleSlider.h"
//______________________________________________________________________________
// GUI editor for AliEveV0.
//
ClassImp(AliEveV0Editor)
//______________________________________________________________________________
AliEveV0Editor::AliEveV0Editor(const TGWindow *p, Int_t width, Int_t height,
UInt_t options, Pixel_t back) :
TGedFrame(p, width, height, options | kVerticalFrame, back),
fM(0),
fInfoLabel0(0),
fInfoLabel1(0),
fInfoLabelNegDaughter(0),
fInfoLabelPosDaughter(0),
fXButton(0)
// Initialize widget pointers to 0
{
// Constructor.
MakeTitle("AliEveV0");
fInfoLabel0 = new TGLabel(this);
fInfoLabel0->SetTextJustify(kTextLeft);
AddFrame(fInfoLabel0, new TGLayoutHints(kLHintsLeft|kLHintsExpandX,
8, 0, 2, 0));
fInfoLabel1 = new TGLabel(this);
fInfoLabel1->SetTextJustify(kTextLeft);
AddFrame(fInfoLabel1, new TGLayoutHints(kLHintsLeft|kLHintsExpandX,
8, 0, 2, 0));
fInfoLabelNegDaughter = new TGLabel(this);
fInfoLabelNegDaughter->SetTextJustify(kTextLeft);
AddFrame(fInfoLabelNegDaughter, new TGLayoutHints(kLHintsLeft|kLHintsExpandX,
8, 0, 2, 0));
fInfoLabelPosDaughter = new TGLabel(this);
fInfoLabelPosDaughter->SetTextJustify(kTextLeft);
AddFrame(fInfoLabelPosDaughter, new TGLayoutHints(kLHintsLeft|kLHintsExpandX,
8, 0, 2, 0));
fXButton = new TGTextButton(this, "Detailed View");
AddFrame(fXButton, new TGLayoutHints(kLHintsLeft|kLHintsExpandX, 1, 1, 0, 0));
fXButton->Connect("Clicked()", "AliEveV0Editor", this, "DisplayDetailed()");
}
/******************************************************************************/
//______________________________________________________________________________
void AliEveV0Editor::SetModel(TObject* obj)
{
// Set model object.
fM = dynamic_cast<AliEveV0*>(obj);
// Set values of widgets
fInfoLabel0->SetText(Form("Radius = %f, DCA = %f", fM->GetRadius(), fM->GetDaughterDCA()));
fInfoLabel1->SetText(Form("Pt = %f", fM->GetPt()));
fInfoLabelNegDaughter->SetText(Form("Neg. Daughter Prob= %.2f for Pdg= %d", fM->GetNegMaxProbPid(), fM->GetNegMaxProbPdg()));
fInfoLabelPosDaughter->SetText(Form("Pos. Daughter Prob= %.2f for Pdg= %d", fM->GetPosMaxProbPid(), fM->GetPosMaxProbPdg()));
}
/******************************************************************************/
// Implements callback/slot methods
//______________________________________________________________________________
// void AliEveV0Editor::DoXYZZ()
// {
// // Slot for XYZZ.
//
// fM->SetXYZZ(fXYZZ->GetValue());
// Update();
// }
#include <TEveManager.h>
#include <TEveWindow.h>
#include <TEveViewer.h>
#include <TEveScene.h>
#include <TEveGeoNode.h>
#include <TEveProjectionManager.h>
#include <TGLCamera.h>
#include <TGLViewer.h>
#include "TGLCameraOverlay.h"
#include <TLatex.h>
#include <TRootEmbeddedCanvas.h>
#include <TInterpreter.h>
void AliEveV0Editor::DisplayDetailed()
{
TEveWindowSlot *slot = TEveWindow::CreateWindowMainFrame();
TEveWindowPack *pack = slot->MakePack();
pack->SetShowTitleBar(kFALSE);
pack->SetHorizontal();
//
// This part is for getting the different objects to display
//
char displayInfo[100] = {0};
sprintf(displayInfo,"pt = %.3f",fM->GetPt());
TEveLine *lv0TransverseMomentumDirection = new TEveLine(displayInfo);
lv0TransverseMomentumDirection->SetLineColor(kOrange+8);
lv0TransverseMomentumDirection->SetLineWidth(2);
lv0TransverseMomentumDirection->SetLineStyle(2);
lv0TransverseMomentumDirection->SetLineWidth(2);
Float_t scalePt = 100.; // this needs to be available as a ruler
lv0TransverseMomentumDirection->SetPoint(0,fM->fRecDecayV.fX, fM->fRecDecayV.fY, fM->fRecDecayV.fZ);
lv0TransverseMomentumDirection->SetPoint(1,scalePt*fM->fRecDecayP.fX, scalePt*fM->fRecDecayP.fY,0);
TEvePointSet *pvlocation = new TEvePointSet("PV location");
pvlocation->SetNextPoint(fM->fRecBirthV.fX, fM->fRecBirthV.fY, fM->fRecBirthV.fZ);
pvlocation->SetTitle("pv location");
pvlocation->SetMarkerStyle(4);
pvlocation->SetMarkerSize(2.5);
pvlocation->SetMarkerColor(7);
TEvePointSet *v0location = new TEvePointSet("V0 location");
v0location->SetNextPoint(fM->fRecDecayV.fX, fM->fRecDecayV.fY, fM->fRecDecayV.fZ);
v0location->SetTitle("v0 location");
v0location->SetMarkerStyle(4);
v0location->SetMarkerSize(2.5);
v0location->SetMarkerColor(kOrange+8);
//
// This part is for the bending plane view
//
pack->NewSlot()->MakeCurrent();
TEveViewer *bpViewer = gEve->SpawnNewViewer("V0 bending plane View");
TEveScene *bpScene = gEve->SpawnNewScene("V0 bending plane Scene");
TEveUtil::LoadMacro("geom_gentle.C");
Long_t result = gInterpreter->ProcessLine("geom_gentle_rphi()");
if (result)
{
TEveGeoShape *geomRPhi = reinterpret_cast<TEveGeoShape*>(result);
geomRPhi->IncDenyDestroy();
TEveProjectionManager *projMgr = new TEveProjectionManager();
projMgr->ImportElements(geomRPhi, bpScene);
}
else
{
Warning("DisplayDetailed", "Import of R-Phi geometry failed.");
}
bpViewer->AddScene(bpScene);
bpScene->AddElement(fM);
bpScene->AddElement(lv0TransverseMomentumDirection);
bpScene->AddElement(pvlocation);
bpScene->AddElement(v0location);
// This is the to-do list for the bending plane:
// 1. fix the view to orthographic XOY (no rotation allowed but moving the center ok) ->done!
// 2. show axis and tickles along X and Y ->done!
// -> note for the projection the cartesian scales are not very useful
// -> propose a phi and R scale which rotates with a reset at 0;
// -> propose a transformation for an eta scale (keep the z one);
// 3. show the center, the main vertex and the detectors for this view ->done!
// 4. show V0 direction in the bending plane with arrow length proportional to pT ->done!
// 5. show angles with respect to axis (phi angle) ->almost.
// 6. show clusters in the ITS and in the TPC associated with the daughter tracks
// -> include a radius cut for plotting only ITS and TPC
bpViewer->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY);
bpViewer->GetGLViewer()->ResetCamerasAfterNextUpdate();
TGLViewer *lbpGLViewer = bpViewer->GetGLViewer();
TGLCameraOverlay* co = lbpGLViewer->GetCameraOverlay();
co->SetShowOrthographic(true); //(false);
co->SetOrthographicMode(TGLCameraOverlay::kAxis); // ::kPlaneIntersect or ::kBar
// end of the bending plane part
//
// This part is for the decay plane view
//
pack->NewSlot()->MakeCurrent();
TEveViewer *dpViewer = gEve->SpawnNewViewer("V0 decay plane View");
TEveScene *dpScene = gEve->SpawnNewScene("V0 decay plane Scene");
dpViewer->AddScene(dpScene);
result = gInterpreter->ProcessLine("geom_gentle(kFALSE)");
if (result)
{
TEveGeoShape *geom = reinterpret_cast<TEveGeoShape*>(result);
geom->IncDenyDestroy();
geom->FindChild("TRD+TOF")->SetRnrState(kFALSE);
geom->FindChild("PHOS") ->SetRnrState(kFALSE);
geom->FindChild("HMPID") ->SetRnrState(kFALSE);
dpScene->AddElement(geom);
}
else
{
Warning("DisplayDetailed", "Import of 3D geometry failed.");
}
dpScene->AddElement(fM);
dpScene->AddElement(lv0TransverseMomentumDirection);
dpScene->AddElement(pvlocation);
dpScene->AddElement(v0location);
// This is the to-do list for the decay plane:
// 1. fix the view to decay plane (no rotation allowed but moving the center ok)
// 2. show V0 direction with a vertical arrow length proportional to pT -> done!
// 3. show the center, the main vertex and the detectors for this view -> done!
// 4. show the x,y and z axis and the different angles
// -> this needs a referential object that we can move around
// or fix to a selected point (origin being the default)
// 5. draw the dca between daughters and the extrapolation to the main vertex.
// -> this is an issue since we only store the distance: check with J.Belikov
// 6. show clusters in the ITS and in the TPC associated with the daughter tracks
// -> include a radius cut for plotting only ITS and TPC
dpViewer->GetGLViewer()->ResetCamerasAfterNextUpdate();
TGLCamera& dpCam = dpViewer->GetGLViewer()->CurrentCamera();
dpCam.SetExternalCenter(kTRUE);
dpCam.SetCenterVec(fM->fRecDecayV.fX, fM->fRecDecayV.fY, fM->fRecDecayV.fZ);
// end of the decay plane part
//
// This part is for displaying the information
//
slot = pack->NewSlot();
TEveWindowFrame *frame = slot->MakeFrame(new TRootEmbeddedCanvas());
frame->SetElementName("Details");
// Print and show detailed information about the V0
// Calculation of the invariant mass with the max prob PID hypothesis first
// pseudorapidity, phi angle, pt, radius, dcas
char info[100] = {0};
sprintf(info,"#phi = %.3frad = %.1f",fM->GetPhi(),57.296*fM->GetPhi());
TLatex* ltx = new TLatex(0.05, 0.9, info);
ltx->SetTextSize(0.08);
ltx->Draw();
sprintf(info,"radius = %.3f [cm]",fM->GetRadius());
ltx->DrawLatex(0.05, 0.8, info);
sprintf(info,"p_{T} = %.3f [GeV/c]",fM->GetPt());
ltx->DrawLatex(0.05, 0.7, info);
sprintf(info,"daughters dca = %.3f [cm]",fM->GetDaughterDCA());
ltx->DrawLatex(0.05, 0.6, info);
sprintf(info,"#eta = - ln( tan(#theta/2) ) = %.3f",fM->GetEta());
ltx->DrawLatex(0.05, 0.5, info);
sprintf(info,"mass_{K^{0}_{s}} = %.3f [GeV/c^{2}]",fM->GetK0sInvMass());
ltx->DrawLatex(0.05, 0.3, info);
sprintf(info,"mass_{#Lambda} = %.3f [GeV/c^{2}]",fM->GetLambdaInvMass());
ltx->DrawLatex(0.05, 0.2, info);
sprintf(info,"mass_{#bar{#Lambda}} = %.3f [GeV/c^{2}]",fM->GetAntiLambdaInvMass());
ltx->DrawLatex(0.05, 0.1, info);
gEve->Redraw3D();
}
<commit_msg>From Boris: add clusters associated with V0 daughters to the detailed view. Some cleanup.<commit_after>// @(#)root/eve:$Id$
// Author: Matevz Tadel 2007
/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
* See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for *
* full copyright notice. *
**************************************************************************/
#include "AliEveV0Editor.h"
#include "AliEveV0.h"
#include "TVirtualPad.h"
#include "TColor.h"
// Cleanup these includes:
#include "TGLabel.h"
#include "TGButton.h"
#include "TGNumberEntry.h"
#include "TGColorSelect.h"
#include "TGDoubleSlider.h"
//______________________________________________________________________________
// GUI editor for AliEveV0.
//
ClassImp(AliEveV0Editor)
//______________________________________________________________________________
AliEveV0Editor::AliEveV0Editor(const TGWindow *p, Int_t width, Int_t height,
UInt_t options, Pixel_t back) :
TGedFrame(p, width, height, options | kVerticalFrame, back),
fM(0),
fInfoLabel0(0),
fInfoLabel1(0),
fInfoLabelNegDaughter(0),
fInfoLabelPosDaughter(0),
fXButton(0)
// Initialize widget pointers to 0
{
// Constructor.
MakeTitle("AliEveV0");
fInfoLabel0 = new TGLabel(this);
fInfoLabel0->SetTextJustify(kTextLeft);
AddFrame(fInfoLabel0, new TGLayoutHints(kLHintsLeft|kLHintsExpandX,
8, 0, 2, 0));
fInfoLabel1 = new TGLabel(this);
fInfoLabel1->SetTextJustify(kTextLeft);
AddFrame(fInfoLabel1, new TGLayoutHints(kLHintsLeft|kLHintsExpandX,
8, 0, 2, 0));
fInfoLabelNegDaughter = new TGLabel(this);
fInfoLabelNegDaughter->SetTextJustify(kTextLeft);
AddFrame(fInfoLabelNegDaughter, new TGLayoutHints(kLHintsLeft|kLHintsExpandX,
8, 0, 2, 0));
fInfoLabelPosDaughter = new TGLabel(this);
fInfoLabelPosDaughter->SetTextJustify(kTextLeft);
AddFrame(fInfoLabelPosDaughter, new TGLayoutHints(kLHintsLeft|kLHintsExpandX,
8, 0, 2, 0));
fXButton = new TGTextButton(this, "Detailed View");
AddFrame(fXButton, new TGLayoutHints(kLHintsLeft|kLHintsExpandX, 1, 1, 0, 0));
fXButton->Connect("Clicked()", "AliEveV0Editor", this, "DisplayDetailed()");
}
/******************************************************************************/
//______________________________________________________________________________
void AliEveV0Editor::SetModel(TObject* obj)
{
// Set model object.
fM = dynamic_cast<AliEveV0*>(obj);
// Set values of widgets
fInfoLabel0->SetText(Form("Radius = %f, DCA = %f", fM->GetRadius(), fM->GetDaughterDCA()));
fInfoLabel1->SetText(Form("Pt = %f", fM->GetPt()));
fInfoLabelNegDaughter->SetText(Form("Neg. Daughter Prob= %.2f for Pdg= %d", fM->GetNegMaxProbPid(), fM->GetNegMaxProbPdg()));
fInfoLabelPosDaughter->SetText(Form("Pos. Daughter Prob= %.2f for Pdg= %d", fM->GetPosMaxProbPid(), fM->GetPosMaxProbPdg()));
}
/******************************************************************************/
// Implements callback/slot methods
//______________________________________________________________________________
// void AliEveV0Editor::DoXYZZ()
// {
// // Slot for XYZZ.
//
// fM->SetXYZZ(fXYZZ->GetValue());
// Update();
// }
#include <TEveManager.h>
#include <TEveWindow.h>
#include <TEveViewer.h>
#include <TEveScene.h>
#include <TEveGeoNode.h>
#include <TEveProjectionManager.h>
#include <TGLCamera.h>
#include <TGLViewer.h>
#include "TGLCameraOverlay.h"
#include <TLatex.h>
#include <TRootEmbeddedCanvas.h>
#include <TInterpreter.h>
void AliEveV0Editor::DisplayDetailed()
{
TEveWindowSlot *slot = TEveWindow::CreateWindowMainFrame();
TEveWindowPack *pack = slot->MakePack();
pack->SetShowTitleBar(kFALSE);
pack->SetHorizontal();
//
// This part is for getting the different objects to display
//
char displayInfo[100] = {0};
sprintf(displayInfo,"pt = %.3f",fM->GetPt());
TEveLine *lv0TransverseMomentumDirection = new TEveLine(displayInfo);
lv0TransverseMomentumDirection->SetLineColor(kOrange+8);
lv0TransverseMomentumDirection->SetLineWidth(2);
lv0TransverseMomentumDirection->SetLineStyle(2);
lv0TransverseMomentumDirection->SetLineWidth(2);
Float_t scalePt = 100.; // this needs to be available as a ruler
lv0TransverseMomentumDirection->SetPoint(0,fM->fRecDecayV.fX, fM->fRecDecayV.fY, fM->fRecDecayV.fZ);
lv0TransverseMomentumDirection->SetPoint(1,scalePt*fM->fRecDecayP.fX, scalePt*fM->fRecDecayP.fY,0);
TEvePointSet *pvlocation = new TEvePointSet("PV location");
pvlocation->SetNextPoint(fM->fRecBirthV.fX, fM->fRecBirthV.fY, fM->fRecBirthV.fZ);
pvlocation->SetTitle("pv location");
pvlocation->SetMarkerStyle(4);
pvlocation->SetMarkerSize(2.5);
pvlocation->SetMarkerColor(7);
TEvePointSet *v0location = new TEvePointSet("V0 location");
v0location->SetNextPoint(fM->fRecDecayV.fX, fM->fRecDecayV.fY, fM->fRecDecayV.fZ);
v0location->SetTitle("v0 location");
v0location->SetMarkerStyle(4);
v0location->SetMarkerSize(2.5);
v0location->SetMarkerColor(kOrange+8);
TEveUtil::LoadMacro("clusters_from_index.C");
TEveTrack *negTrack = fM->GetNegTrack();
TEveTrack *posTrack = fM->GetPosTrack();
char macroWithIndex[100] = {0};
Int_t daughterIndex = 0;
TEvePointSet *negDaughterCluster = 0;
TEvePointSet *posDaughterCluster = 0;
daughterIndex = negTrack->GetIndex();
sprintf(macroWithIndex,"clusters_from_index(%d)",daughterIndex);
Long_t negResult = gInterpreter->ProcessLine(macroWithIndex);
if (negResult) {
negDaughterCluster = reinterpret_cast<TEvePointSet*>(negResult);
if (negDaughterCluster){
negDaughterCluster->SetMarkerStyle(4);
negDaughterCluster->SetMarkerSize(1.5);
negDaughterCluster->SetMarkerColor(kBlue+3);
}
}
else
{
Warning("DisplayDetailed", "Import of negative daughter's clusters failed.");
}
daughterIndex = posTrack->GetIndex();
sprintf(macroWithIndex,"clusters_from_index(%d)",daughterIndex);
Long_t posResult = gInterpreter->ProcessLine(macroWithIndex);
if (posResult) {
posDaughterCluster = reinterpret_cast<TEvePointSet*>(posResult);
if (posDaughterCluster){
posDaughterCluster->SetMarkerStyle(4);
posDaughterCluster->SetMarkerSize(1.5);
posDaughterCluster->SetMarkerColor(kRed+3);
}
}
else
{
Warning("DisplayDetailed", "Import of positive daughter's clusters failed.");
}
//
// This part is for the bending plane view
//
pack->NewSlot()->MakeCurrent();
TEveViewer *bpViewer = gEve->SpawnNewViewer("V0 bending plane View");
TEveScene *bpScene = gEve->SpawnNewScene("V0 bending plane Scene");
TEveUtil::LoadMacro("geom_gentle.C");
Long_t result = gInterpreter->ProcessLine("geom_gentle_rphi()");
if (result)
{
TEveGeoShape *geomRPhi = reinterpret_cast<TEveGeoShape*>(result);
geomRPhi->IncDenyDestroy();
TEveProjectionManager *projMgr = new TEveProjectionManager();
projMgr->ImportElements(geomRPhi, bpScene);
}
else
{
Warning("DisplayDetailed", "Import of R-Phi geometry failed.");
}
bpViewer->AddScene(bpScene);
bpScene->AddElement(fM);
bpScene->AddElement(lv0TransverseMomentumDirection);
bpScene->AddElement(pvlocation);
bpScene->AddElement(v0location);
if (negDaughterCluster) bpScene->AddElement(negDaughterCluster);
if (posDaughterCluster) bpScene->AddElement(posDaughterCluster);
// This is the to-do list for the bending plane:
// 1. fix the view to orthographic XOY (no rotation allowed but moving the center ok) ->done!
// 2. show axis and tickles along X and Y ->done!
// -> note for the projection the cartesian scales are not very useful
// -> propose a phi and R scale which rotates with a reset at 0;
// -> propose a transformation for an eta scale (keep the z one);
// 3. show the center, the main vertex and the detectors for this view ->done!
// 4. show V0 direction in the bending plane with arrow length proportional to pT ->done!
// 5. show angles with respect to axis (phi angle) ->almost.
// 6. show clusters in the ITS and in the TPC associated with the daughter tracks
// -> include a radius cut for plotting only ITS and TPC ->done!
bpViewer->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY);
bpViewer->GetGLViewer()->ResetCamerasAfterNextUpdate();
TGLViewer *lbpGLViewer = bpViewer->GetGLViewer();
TGLCameraOverlay* co = lbpGLViewer->GetCameraOverlay();
co->SetShowOrthographic(true); //(false);
co->SetOrthographicMode(TGLCameraOverlay::kAxis); // ::kPlaneIntersect or ::kBar
// end of the bending plane part
//
// This part is for the decay plane view
//
pack->NewSlot()->MakeCurrent();
TEveViewer *dpViewer = gEve->SpawnNewViewer("V0 decay plane View");
TEveScene *dpScene = gEve->SpawnNewScene("V0 decay plane Scene");
dpViewer->AddScene(dpScene);
result = gInterpreter->ProcessLine("geom_gentle(kFALSE)");
if (result)
{
TEveGeoShape *geom = reinterpret_cast<TEveGeoShape*>(result);
geom->IncDenyDestroy();
geom->FindChild("TRD+TOF")->SetRnrState(kFALSE);
geom->FindChild("PHOS") ->SetRnrState(kFALSE);
geom->FindChild("HMPID") ->SetRnrState(kFALSE);
dpScene->AddElement(geom);
}
else
{
Warning("DisplayDetailed", "Import of 3D geometry failed.");
}
dpScene->AddElement(fM);
dpScene->AddElement(lv0TransverseMomentumDirection);
dpScene->AddElement(pvlocation);
dpScene->AddElement(v0location);
if (negDaughterCluster) dpScene->AddElement(negDaughterCluster);
if (posDaughterCluster) dpScene->AddElement(posDaughterCluster);
// This is the to-do list for the decay plane:
// 1. fix the view to decay plane (no rotation allowed but moving the center ok)
// 2. show V0 direction with a vertical arrow length proportional to pT -> done!
// 3. show the center, the main vertex and the detectors for this view -> done!
// 4. show the x,y and z axis and the different angles
// -> this needs a referential object that we can move around
// or fix to a selected point (origin being the default)
// 5. draw the dca between daughters and the extrapolation to the main vertex.
// -> this is an issue since we only store the distance: check with J.Belikov
// 6. show clusters in the ITS and in the TPC associated with the daughter tracks
// -> include a radius cut for plotting only ITS and TPC ->done!
dpViewer->GetGLViewer()->ResetCamerasAfterNextUpdate();
TGLCamera& dpCam = dpViewer->GetGLViewer()->CurrentCamera();
dpCam.SetExternalCenter(kTRUE);
dpCam.SetCenterVec(fM->fRecDecayV.fX, fM->fRecDecayV.fY, fM->fRecDecayV.fZ);
dpCam.RotateRad(0,-TMath::Pi()/2.); // RotateRad rotates in radians (hRotate,vRotate)
// Here rotate the _view_ (not the camera) by (fM->GetPhi() - TMath::Pi()/2.)
// In the end maybe truck and rotate properly...
// dpCam.Truck(0,200);// Truck center wrt the view panel: (x=0 pixels, y pixels)
// dpCam.Rotate(0,50,0,0); // Rotate in pixels (xDelta,yDelta)
// end of the decay plane part
//
// This part is for displaying the information
//
slot = pack->NewSlot();
TEveWindowFrame *frame = slot->MakeFrame(new TRootEmbeddedCanvas());
frame->SetElementName("Details");
// Print and show detailed information about the V0
// Calculation of the invariant mass with the max prob PID hypothesis first
// pseudorapidity, phi angle, pt, radius, dcas
char info[100] = {0};
sprintf(info,"#phi = %.3frad = %.1f",fM->GetPhi(),(180./TMath::Pi())*fM->GetPhi());
TLatex* ltx = new TLatex(0.05, 0.9, info);
ltx->SetTextSize(0.08);
ltx->Draw();
sprintf(info,"radius = %.3f [cm]",fM->GetRadius());
ltx->DrawLatex(0.05, 0.8, info);
sprintf(info,"p_{T} = %.3f [GeV/c]",fM->GetPt());
ltx->DrawLatex(0.05, 0.7, info);
sprintf(info,"daughters dca = %.3f [cm]",fM->GetDaughterDCA());
ltx->DrawLatex(0.05, 0.6, info);
sprintf(info,"#eta = - ln( tan(#theta/2) ) = %.3f",fM->GetEta());
ltx->DrawLatex(0.05, 0.5, info);
sprintf(info,"mass_{K^{0}_{s}} = %.3f [GeV/c^{2}]",fM->GetK0sInvMass());
ltx->DrawLatex(0.05, 0.3, info);
sprintf(info,"mass_{#Lambda} = %.3f [GeV/c^{2}]",fM->GetLambdaInvMass());
ltx->DrawLatex(0.05, 0.2, info);
sprintf(info,"mass_{#bar{#Lambda}} = %.3f [GeV/c^{2}]",fM->GetAntiLambdaInvMass());
ltx->DrawLatex(0.05, 0.1, info);
gEve->Redraw3D();
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MAXN = 20000 + 10,MAXM = 200000 + 10;
struct egde
{
int v,next;
}e[MAXM];
int n,m,ans,cnt = 1,mx = -1;
int a[MAXM],b[MAXM],c[MAXM];
int head[MAXN],col[MAXN];
bool flag;
void adde(int u,int v)
{
e[cnt].v = v;
e[cnt].next = head[u];
head[u] = cnt++;
}
void build(int mid)
{
memset(head,-1,sizeof(head));
for(int i = 1;i <= m;i++)if(c[i] > mid)
{
adde(a[i],b[i]);
adde(b[i],a[i]);
}
}
void dfs(int u)
{
if(!flag)return;
for(int i = head[u];i != -1;i = e[i].next)
{
int v = e[i].v;
if(col[v] == -1)
{
col[v] = col[u] ^ 1;
dfs(v);
}
else if(col[u] == col[v])
{
flag = 0;
return;
}
}
}
void work()
{
int l = 0,r = mx,mid;
while(l <= r)
{
mid = (l + r) >> 1;
build(mid);
memset(col,-1,sizeof(col));
flag = 1;
for(int i = 1;i <= n;i++)
{
if(col[i] == -1)
{
col[i] = 0;
dfs(i);
}
if(!flag)break;
}
if(flag)
{
ans = mid;
r = mid - 1;
}
else l = mid + 1;
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i = 1;i <= m;i++)
{
scanf("%d%d%d",&a[i],&b[i],&c[i]);
if (c[i] > mx) mx = c[i];
}
work();
printf("%d\n",ans);
return 0;
}
<commit_msg>code style<commit_after>#include <stdio.h>
#include <string.h>
#define true 1
#define false 0
const int MAXN = 20000 + 10,MAXM = 200000 + 10;
struct egde {
int v,next;
}e[MAXM];
int n,m,ans,cnt = 1,mx = -1;
int a[MAXM],b[MAXM],c[MAXM];
int head[MAXN],col[MAXN];
int flag;
void adde(int u,int v) {
e[cnt].v = v;
e[cnt].next = head[u];
head[u] = cnt++;
}
void build(int mid) {
int i;
memset(head, -1, sizeof(head));
for(i = 1; i <= m; i++)
if(c[i] > mid) {
adde(a[i],b[i]);
adde(b[i],a[i]);
}
}
void dfs(int u) {
if(!flag) return;
int i;
for(i = head[u]; i != -1; i = e[i].next) {
int v = e[i].v;
if(col[v] == -1) {
col[v] = col[u] ^ 1;
dfs(v);
}
else if(col[u] == col[v]) {
flag = 0;
return;
}
}
}
void work() {
int l = 0, r = mx, mid, i;
while(l <= r) {
mid = (l + r) >> 1;
build(mid);
memset(col, -1, sizeof(col));
flag = 1;
for(i = 1; i <= n; i++) {
if(col[i] == -1) {
col[i] = 0;
dfs(i);
}
if(!flag) break;
}
if(flag) {
ans = mid;
r = mid - 1;
}
else l = mid + 1;
}
}
int main() {
int i;
scanf("%d %d", &n, &m);
for(i = 1; i <= m; i++) {
scanf("%d %d %d", &a[i], &b[i], &c[i]);
if (c[i] > mx) mx = c[i];
}
work();
printf("%d\n", ans);
return 0;
}
<|endoftext|>
|
<commit_before>#include <QtCore/QMap>
#include <QtCore/QRegExp>
#include "iTCHMethod.h"
namespace {
// Initialize static values for JSON RPC conversion and checking
cons char JSON_METHOD_REG_EXP[] = "\\{\\s*\"method\":\\s*\"(.*)\"\\s*,\\s*\"params\":\\s*\\[(.*)\\]\\s*,\\s*\"id\":\\s*(.*)\\s*\\}"
const QRegExp __jsonMethodRegExp(JSON_METHOD_REG_EXP, Qt::CaseSensitive, QRegExp::RegExp2);
class __SupportedMethodsMap : public QMap<iTCHMethod::SupportedMethods, QString>
{
(*this)[iTCHMethod::METHOD_IITUNES_BACKTRACK] = "IiTunes::BackTrack";
(*this)[iTCHMethod::METHOD_IITUNES_FASTFORWARD] = "IiTunes::FastForward";
(*this)[iTCHMethod::METHOD_IITUNES_NEXTTRACK] = "IiTunes::NextTrack";
(*this)[iTCHMethod::METHOD_IITUNES_PAUSE] = "IiTunes::Pause";
(*this)[iTCHMethod::METHOD_IITUNES_PLAY] = "IiTunes::Play";
(*this)[iTCHMethod::METHOD_IITUNES_PLAYPAUSE] = "IiTunes::PlayPause";
(*this)[iTCHMethod::METHOD_IITUNES_PREVIOUSTRACK] = "IiTunes::PreviousTrack";
(*this)[iTCHMethod::METHOD_IITUNES_RESUME] = "IiTunes::Resume";
(*this)[iTCHMethod::METHOD_IITUNES_REWIND] = "IiTunes::Rewind";
(*this)[iTCHMethod::METHOD_IITUNES_STOP] = "IiTunes::Stop";
(*this)[iTCHMethod::METHOD_IITUNES_GET_SOUNDVOLUME] = "IiTunes::get_SoundVolume";
(*this)[iTCHMethod::METHOD_IITUNES_PUT_SOUNDVOLUME] = "IiTunes::put_SoundVolume";
(*this)[iTCHMethod::METHOD_IITUNES_GET_MUTE] = "IiTunes::get_Mute";
(*this)[iTCHMethod::METHOD_IITUNES_PUT_MUTE] = "IiTunes::put_Mute";
(*this)[iTCHMethod::METHOD_IITUNES_GET_PLAYERPOSITION] = "IiTunes::get_playerPosition";
(*this)[iTCHMethod::METHOD_IITUNES_PUT_PLAYERPOSITION] = "IiTunes::put_PlayerPosition";
(*this)[iTCHMethod::METHOD_IITCHSERVER_GET_PLAYERSTATE] = "iTCHServer::getPlayserState";
(*this)[iTCHMethod::METHOD_IITCHSERVER_GET_CURRENTTRACK] = "iTCHServer::getCurrentTrack";
(*this)[iTCHMethod::METHOD_IITCHSERVER_GET_CURRENTPLAYLIST] = "iTCHServer::getCurrentPlaylist";
(*this)[iTCHMethod::METHOD_IITCHCLIENT_VOLUMECHANGED] = "iTCHClient::volumeChanged";
(*this)[iTCHMethod::METHOD_IITCHCLIENT_PLAYINGSTARTED] = "iTCHClient::playingStarted";
(*this)[iTCHMethod::METHOD_IITCHCLIENT_PLAYINGSTOPPED] = "iTCHClient::playingStopped";
(*this)[iTCHMethod::METHOD_IITCHCLIENT_TRACKINFOCHANGED] = "iTCHClient::trackInfoChanged";
}
} __supportedMethods;
iTCHMethod::iTCHMethod(const iTCHMethod& method) :
method_(method.method_),
params_(method.params_),
id_(method.id_)
{
}
iTCHMethod::iTCHMethod(SupportedMethods method, const QStringList ¶ms, unsigned int id) :
params_(params),
id_(id)
{
setMethod(method);
}
iTCHMethod::iTCHMethod(const QString &json) :
id_(0)
{
fromJsonRpc(json);
}
void iTCHMethod::setMethod(SupportedMethods method)
{
// Check for supported method name
if (!__supportedMethods.contains(method))
{
throw InvalidValueException(QString("Unsupported method: %1").arg(method));
}
method_ = method;
}
QString iTCHMethod::toJsonRpc() const
{
// Initialize JSON-RPC string with method name
if (!__supportedMethods.contains(method_))
{
throw InvalidValueException(QString("Unsupported method: %1").arg(method_));
}
QString json = QString("{ \"method\": \"%1\", \"params\": [").arg(__supportedMethods[method_]);
// Add paramters to JSON-RPC params list
if (!params_.empty())
{
QStringList::const_iterator paramsIterator = params_.constBegin();
// Add first parameter to list
json += (*paramsIterator++);
// Add remaining parameters with comma separation
for (; paramsIterator != params_.constEnd(); ++paramsIterator)
{
json += QString(", %1").arg(*paramsIterator);
}
}
// Append the id number
json += QString("], \"id\": %1}").arg((id_ > 0) ? QString::number(id_) : "null");
return json;
}
void iTCHMethod::fromJsonRpc(const QString &json)
{
// Extract method, parameters, and id
int pos = __jsonMethodRegExp.indexIn(json);
// Check for valid JSON RPC message
if (pos < 0)
{
throw InvalidValueException(QString("Invalid JSON-RPC message: not correctly formatted"));
}
int n = __jsonMethodRegExp.numCaptures();
if (n != 3)
{
throw InvalidValueException(QString("Invalid JSON-RPC message: incorrect number of parameters (had %1, needs 3)").arg(n));
}
// Extract the method name (checks for supported method)
QString method = __jsonMethodRegExp.cap(1);
if (!__supportedMethods.values().contains(method))
{
throw InvalidValueException(QString("Invalid JSON-RPC message: unsupported method %1)").arg(method));
}
// Get key for method
method_ = __supportedMethods.key(method);
// Extract the
QString params = __jsonMethodRegExp.cap(2);
params_ = params.split(QRegExp("\\s*,\\s*"), QString::SkipEmptyParts);
QString id = __jsonMethodRegExp.cap(3);
bool valid;
id_ = (id == "null") ? 0 : id.toInt(&valid);
}
<commit_msg>Fixed syntax errors from last merge<commit_after>#include <QtCore/QMap>
#include <QtCore/QRegExp>
#include "iTCHMethod.h"
namespace {
// Initialize static values for JSON RPC conversion and checking
const char JSON_METHOD_REG_EXP[] = "\\{\\s*\"method\":\\s*\"(.*)\"\\s*,\\s*\"params\":\\s*\\[(.*)\\]\\s*,\\s*\"id\":\\s*(.*)\\s*\\}";
const QRegExp __jsonMethodRegExp(JSON_METHOD_REG_EXP, Qt::CaseSensitive, QRegExp::RegExp2);
class __SupportedMethodsMap : public QMap<iTCHMethod::SupportedMethods, QString>
{
public:
__SupportedMethodsMap()
{
(*this)[iTCHMethod::METHOD_IITUNES_BACKTRACK] = "IiTunes::BackTrack";
(*this)[iTCHMethod::METHOD_IITUNES_FASTFORWARD] = "IiTunes::FastForward";
(*this)[iTCHMethod::METHOD_IITUNES_NEXTTRACK] = "IiTunes::NextTrack";
(*this)[iTCHMethod::METHOD_IITUNES_PAUSE] = "IiTunes::Pause";
(*this)[iTCHMethod::METHOD_IITUNES_PLAY] = "IiTunes::Play";
(*this)[iTCHMethod::METHOD_IITUNES_PLAYPAUSE] = "IiTunes::PlayPause";
(*this)[iTCHMethod::METHOD_IITUNES_PREVIOUSTRACK] = "IiTunes::PreviousTrack";
(*this)[iTCHMethod::METHOD_IITUNES_RESUME] = "IiTunes::Resume";
(*this)[iTCHMethod::METHOD_IITUNES_REWIND] = "IiTunes::Rewind";
(*this)[iTCHMethod::METHOD_IITUNES_STOP] = "IiTunes::Stop";
(*this)[iTCHMethod::METHOD_IITUNES_GET_SOUNDVOLUME] = "IiTunes::get_SoundVolume";
(*this)[iTCHMethod::METHOD_IITUNES_PUT_SOUNDVOLUME] = "IiTunes::put_SoundVolume";
(*this)[iTCHMethod::METHOD_IITUNES_GET_MUTE] = "IiTunes::get_Mute";
(*this)[iTCHMethod::METHOD_IITUNES_PUT_MUTE] = "IiTunes::put_Mute";
(*this)[iTCHMethod::METHOD_IITUNES_GET_PLAYERPOSITION] = "IiTunes::get_playerPosition";
(*this)[iTCHMethod::METHOD_IITUNES_PUT_PLAYERPOSITION] = "IiTunes::put_PlayerPosition";
(*this)[iTCHMethod::METHOD_IITCHSERVER_GET_PLAYERSTATE] = "iTCHServer::getPlayserState";
(*this)[iTCHMethod::METHOD_IITCHSERVER_GET_CURRENTTRACK] = "iTCHServer::getCurrentTrack";
(*this)[iTCHMethod::METHOD_IITCHSERVER_GET_CURRENTPLAYLIST] = "iTCHServer::getCurrentPlaylist";
(*this)[iTCHMethod::METHOD_IITCHCLIENT_VOLUMECHANGED] = "iTCHClient::volumeChanged";
(*this)[iTCHMethod::METHOD_IITCHCLIENT_PLAYINGSTARTED] = "iTCHClient::playingStarted";
(*this)[iTCHMethod::METHOD_IITCHCLIENT_PLAYINGSTOPPED] = "iTCHClient::playingStopped";
(*this)[iTCHMethod::METHOD_IITCHCLIENT_TRACKINFOCHANGED] = "iTCHClient::trackInfoChanged";
}
} __supportedMethods;
}
iTCHMethod::iTCHMethod(const iTCHMethod& method) :
method_(method.method_),
params_(method.params_),
id_(method.id_)
{
}
iTCHMethod::iTCHMethod(SupportedMethods method, const QStringList ¶ms, unsigned int id) :
params_(params),
id_(id)
{
setMethod(method);
}
iTCHMethod::iTCHMethod(const QString &json) :
id_(0)
{
fromJsonRpc(json);
}
void iTCHMethod::setMethod(SupportedMethods method)
{
// Check for supported method name
if (!__supportedMethods.contains(method))
{
throw InvalidValueException(QString("Unsupported method: %1").arg(method));
}
method_ = method;
}
QString iTCHMethod::toJsonRpc() const
{
// Initialize JSON-RPC string with method name
if (!__supportedMethods.contains(method_))
{
throw InvalidValueException(QString("Unsupported method: %1").arg(method_));
}
QString json = QString("{ \"method\": \"%1\", \"params\": [").arg(__supportedMethods[method_]);
// Add paramters to JSON-RPC params list
if (!params_.empty())
{
QStringList::const_iterator paramsIterator = params_.constBegin();
// Add first parameter to list
json += (*paramsIterator++);
// Add remaining parameters with comma separation
for (; paramsIterator != params_.constEnd(); ++paramsIterator)
{
json += QString(", %1").arg(*paramsIterator);
}
}
// Append the id number
json += QString("], \"id\": %1}").arg((id_ > 0) ? QString::number(id_) : "null");
return json;
}
void iTCHMethod::fromJsonRpc(const QString &json)
{
// Extract method, parameters, and id
int pos = __jsonMethodRegExp.indexIn(json);
// Check for valid JSON RPC message
if (pos < 0)
{
throw InvalidValueException(QString("Invalid JSON-RPC message: not correctly formatted"));
}
int n = __jsonMethodRegExp.numCaptures();
if (n != 3)
{
throw InvalidValueException(QString("Invalid JSON-RPC message: incorrect number of parameters (had %1, needs 3)").arg(n));
}
// Extract the method name (checks for supported method)
QString method = __jsonMethodRegExp.cap(1);
if (!__supportedMethods.values().contains(method))
{
throw InvalidValueException(QString("Invalid JSON-RPC message: unsupported method %1)").arg(method));
}
// Get key for method
method_ = __supportedMethods.key(method);
// Extract the
QString params = __jsonMethodRegExp.cap(2);
params_ = params.split(QRegExp("\\s*,\\s*"), QString::SkipEmptyParts);
QString id = __jsonMethodRegExp.cap(3);
bool valid;
id_ = (id == "null") ? 0 : id.toInt(&valid);
}
<|endoftext|>
|
<commit_before>#include "Build.hpp"
#include "BuildGraph.hpp"
#include "Command.hpp"
#include "DependencyLink.hpp"
#include "Environ.hpp"
#include "error.hpp"
#include "Filesystem.hpp"
#include "log.hpp"
#include "lua/State.hpp"
#include "Platform.hpp"
#include "Rule.hpp"
#include "quote.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/functional/hash.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/scope_exit.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace fs = boost::filesystem;
namespace std {
template<> struct hash<boost::filesystem::path>
{
size_t operator ()(boost::filesystem::path const& p) const
{ return hash_value(p); }
};
}
namespace configure {
static bool starts_with(fs::path const& path, fs::path const& prefix)
{
auto it = path.begin(), end = path.end();
for (auto&& p: prefix)
{
if (it == end) return false;
if (p == ".") continue;
if (*it != p) return false;
++it;
}
return true;
}
struct Build::Impl
{
path_t root_directory;
lua::State& lua;
std::vector<path_t> project_stack;
std::vector<path_t> build_stack;
BuildGraph build_graph;
std::unordered_map<std::string, NodePtr> virtual_nodes;
std::unordered_map<path_t, NodePtr> file_nodes;
std::unordered_map<path_t, NodePtr> directory_nodes;
NodePtr root_node;
Filesystem fs;
Environ env;
fs::path env_path;
std::map<std::string, std::string> options;
std::map<std::string, std::string> build_args;
Platform host_platform;
Platform target_platform;
Impl(Build& build, lua::State& lua, path_t directory)
: root_directory(std::move(directory))
, lua(lua)
, project_stack()
, build_stack()
, build_graph()
, virtual_nodes()
, file_nodes()
, directory_nodes()
, root_node(this->build_graph.add_node<VirtualNode>(""))
, fs(build)
, env()
, env_path(root_directory / ".configure.env")
, options()
, build_args()
, host_platform(Platform::current())
, target_platform(Platform::current())
{}
};
Build::Build(lua::State& lua, path_t directory)
: _this(new Impl(*this, lua, std::move(directory)))
{
_this->build_stack.push_back(_this->root_directory);
if (fs::is_regular_file(_this->env_path))
{
try { _this->env.load(_this->env_path); }
catch (...) {
CONFIGURE_THROW(
error::InvalidEnviron("Couldn't load the configuration file")
<< error::path(_this->env_path)
<< error::nested(std::current_exception())
);
}
}
}
Build::Build(lua::State& lua, path_t root_directory,
std::map<std::string, std::string> build_args)
: Build(lua, std::move(root_directory))
{
for (auto& pair: build_args)
_this->build_args[Environ::normalize(pair.first)] = pair.second;
}
Build::~Build()
{
try { _this->env.save(_this->env_path); }
catch (...) {
log::fatal("Couldn't save environ in", _this->env_path, ":",
error_string());
std::abort();
}
}
void Build::configure(path_t const& project_directory,
path_t const& sub_directory)
{
try {
if (!project_directory.is_absolute())
CONFIGURE_THROW(error::InvalidProject("Not an absolute path"));
if (!fs::is_directory(project_directory))
CONFIGURE_THROW(error::InvalidProject("Not a directory"));
if (fs::equivalent(project_directory, this->directory()))
CONFIGURE_THROW(error::InvalidProject("Same as build directory"));
} catch (error::InvalidProject& err) {
throw err << error::path(project_directory);
}
_this->project_stack.push_back(project_directory);
_this->build_stack.push_back(_prepare_build_directory(sub_directory));
log::status("Configuring project", this->project_directory(), "in", this->directory());
BOOST_SCOPE_EXIT((&_this)){
_this->project_stack.pop_back();
_this->build_stack.pop_back();
} BOOST_SCOPE_EXIT_END
try {
_this->lua.load(find_project_file(project_directory));
_this->lua.getglobal("configure");
// XXX check if not nil
_this->lua.construct<std::reference_wrapper<Build>>(*this);
_this->lua.call(1);
if (_this->project_stack.size() == 1) // Last project on the stack
_finalize_build_directory();
} catch (error::Base& e) {
//e << error::message(
// "While configuring project " + project_directory.string()
//);
throw;
}
}
Build::path_t const& Build::project_directory() const
{
if (_this->project_stack.empty())
throw std::logic_error("No project on the stack");
return _this->project_stack.back();
}
Build::path_t const& Build::root_directory() const
{ return _this->root_directory; }
Build::path_t const& Build::directory() const
{ return _this->build_stack.back(); }
NodePtr const& Build::root_node() const
{ return _this->root_node; }
BuildGraph const& Build::build_graph() const
{ return _this->build_graph; }
Filesystem& Build::fs()
{ return _this->fs; }
Environ& Build::env()
{ return _this->env; }
template<typename T>
boost::optional<T> Build::option(std::string name,
std::string const& description)
{
name = Environ::normalize(std::move(name));
_this->options[name] = description;
auto it = _this->build_args.find(name);
if (it != _this->build_args.end())
{
log::debug("Found option", name, "in command line arguments:", it->second);
if (std::is_same<T, bool>::value)
{
std::string str = boost::to_lower_copy(it->second);
static std::map<std::string, bool> conversions = {
{"true", true}, {"false", false},
{"yes", true}, {"no", false},
{"y", true}, {"n", false},
{"1", true}, {"0", false},
};
bool value;
try { value = conversions.at(str); }
catch (...) {
CONFIGURE_THROW(
error::InvalidOption("Cannot convert '" + it->second +
"' to a boolean")
);
}
_this->env.set(name, value);
}
else
_this->env.set(name, boost::lexical_cast<T>(it->second));
_this->build_args.erase(it);
return boost::optional<T>(_this->env.get<T>(name));
}
return boost::none;
}
template<typename T>
typename Environ::const_ref<T>::type
Build::option(std::string name,
std::string const& description,
typename Environ::const_ref<T>::type default_value)
{
this->option<T>(name, description);
if (!_this->env.has(name))
_this->env.set(name, default_value);
return _this->env.get<T>(name);
}
#define INSTANCIATE(T) \
template \
boost::optional<T> Build::option<T>(std::string name, \
std::string const& description); \
template \
Environ::const_ref<T>::type \
Build::option<T>(std::string name, \
std::string const& description, \
Environ::const_ref<T>::type default_value); \
/**/
INSTANCIATE(std::string);
INSTANCIATE(int);
INSTANCIATE(bool);
INSTANCIATE(fs::path);
Build::path_t Build::_prepare_build_directory(path_t const& sub_directory)
{
fs::create_directories(this->directory() / sub_directory);
return fs::canonical(this->directory() / sub_directory);
}
void Build::_finalize_build_directory()
{
std::unordered_set<fs::path> directories;
for (auto const& pair: _this->file_nodes)
{
if (starts_with(pair.first, this->root_directory()))
directories.insert(pair.first.parent_path());
}
for (auto&& d: directories)
fs::create_directories(d);
}
std::vector<Build::path_t> const& Build::possible_configure_files()
{
static std::vector<path_t> ret {
"configure.lua",
".configure.lua",
".config/project.lua",
};
return ret;
}
Build::path_t Build::find_project_file(path_t project_directory)
{
for (auto&& p: possible_configure_files())
if (fs::is_regular_file(project_directory / p))
return project_directory / p;
throw std::runtime_error("No configuration file found in " + project_directory.string());
}
NodePtr& Build::virtual_node(std::string const& name)
{
if (name.empty())
CONFIGURE_THROW(error::InvalidVirtualNode("Name cannot be empty"));
auto it = _this->virtual_nodes.find(name);
if (it != _this->virtual_nodes.end())
return it->second;
auto node = _this->build_graph.add_node<VirtualNode>(name);
return (_this->virtual_nodes[name] = std::move(node));
}
NodePtr& Build::file_node(path_t const& path)
{
if (!path.is_absolute())
throw std::runtime_error("Not an absolute path: " + path.string());
auto it = _this->file_nodes.find(path);
if (it != _this->file_nodes.end())
return it->second;
auto node = _this->build_graph.add_node<FileNode>(path);
return (_this->file_nodes[path] = std::move(node));
}
NodePtr& Build::directory_node(path_t const& path)
{
if (!path.is_absolute())
throw std::runtime_error("Not an absolute path: " + path.string());
auto it = _this->directory_nodes.find(path);
if (it != _this->directory_nodes.end())
return it->second;
auto node = _this->build_graph.add_node<DirectoryNode>(path);
return (_this->directory_nodes[path] = std::move(node));
}
NodePtr& Build::source_node(path_t const& path)
{
fs::path src;
if (!path.is_absolute())
src = this->project_directory() / path;
else
{
src = path;
if (starts_with(src, this->root_directory()))
CONFIGURE_THROW(
error::InvalidSourceNode("Generated file cannot be a source node")
<< error::path(src)
);
}
if (!fs::is_regular_file(src))
CONFIGURE_THROW(error::InvalidSourceNode("File not found")
<< error::path(src)
);
return this->file_node(src);
}
NodePtr& Build::target_node(path_t const& path)
{
if (path.is_absolute())
return this->file_node(path);
return this->file_node(this->directory() / path);
}
void Build::add_rule(Rule const& rule)
{
CommandPtr cmd = rule.command();
if (rule.targets().empty())
CONFIGURE_THROW(error::InvalidRule("No target specified"));
if (rule.sources().empty())
for (auto& target: rule.targets())
{
try {
_this->build_graph.link(*_this->root_node, *target).command(cmd);
} catch (error::CommandAlreadySet&) {
CONFIGURE_THROW(
error::InvalidRule(
"Trying to generate " + target->string() + " twice"
) << error::nested(std::current_exception())
);
}
}
else
for (auto& target: rule.targets())
for (auto& source: rule.sources())
{
try {
_this->build_graph.link(*source, *target)
.command(cmd);
} catch (error::CommandAlreadySet&) {
CONFIGURE_THROW(
error::InvalidRule(
"Trying to generate " + target->string() + " twice"
) << error::nested(std::current_exception())
);
}
}
}
Platform& Build::host()
{ return _this->host_platform; }
Platform& Build::target()
{ return _this->target_platform; }
void Build::dump_graphviz(std::ostream& out)
{
struct Writer {
Build& _b;
BuildGraph& _g;
Writer(Build& b, BuildGraph& g) : _b(b), _g(g) {}
void operator ()(std::ostream& out, Node::index_type idx) const
{
auto& node = _g.node(idx);
switch (node->kind())
{
case Node::file_node:
case Node::directory_node:
out << "[label=\"" << node->relative_path(_b.directory()).string() << "\"]";
break;
case Node::virtual_node:
out << "[label=\"" << node->name() << "\"]";
break;
default:
out << "[label=\"" << "UNKNOWN" << "\"]";
}
}
void operator ()(std::ostream& out, DependencyLink::index_type idx) const
{
auto const& cmd = _g.link(idx).command();
out << "[label=\"";
bool first = true;
for (auto&& shell_command: cmd.shell_commands())
{
if (first) first = false;
else out << "\\n";
out << quote<CommandParser::unix_shell>(shell_command.dump());
}
out << "\"]";
}
} writer(*this, _this->build_graph);
boost::write_graphviz(
out,
_this->build_graph.graph(),
writer,
writer
);
}
}
<commit_msg>Use correct log level.<commit_after>#include "Build.hpp"
#include "BuildGraph.hpp"
#include "Command.hpp"
#include "DependencyLink.hpp"
#include "Environ.hpp"
#include "error.hpp"
#include "Filesystem.hpp"
#include "log.hpp"
#include "lua/State.hpp"
#include "Platform.hpp"
#include "Rule.hpp"
#include "quote.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/functional/hash.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/scope_exit.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace fs = boost::filesystem;
namespace std {
template<> struct hash<boost::filesystem::path>
{
size_t operator ()(boost::filesystem::path const& p) const
{ return hash_value(p); }
};
}
namespace configure {
static bool starts_with(fs::path const& path, fs::path const& prefix)
{
auto it = path.begin(), end = path.end();
for (auto&& p: prefix)
{
if (it == end) return false;
if (p == ".") continue;
if (*it != p) return false;
++it;
}
return true;
}
struct Build::Impl
{
path_t root_directory;
lua::State& lua;
std::vector<path_t> project_stack;
std::vector<path_t> build_stack;
BuildGraph build_graph;
std::unordered_map<std::string, NodePtr> virtual_nodes;
std::unordered_map<path_t, NodePtr> file_nodes;
std::unordered_map<path_t, NodePtr> directory_nodes;
NodePtr root_node;
Filesystem fs;
Environ env;
fs::path env_path;
std::map<std::string, std::string> options;
std::map<std::string, std::string> build_args;
Platform host_platform;
Platform target_platform;
Impl(Build& build, lua::State& lua, path_t directory)
: root_directory(std::move(directory))
, lua(lua)
, project_stack()
, build_stack()
, build_graph()
, virtual_nodes()
, file_nodes()
, directory_nodes()
, root_node(this->build_graph.add_node<VirtualNode>(""))
, fs(build)
, env()
, env_path(root_directory / ".configure.env")
, options()
, build_args()
, host_platform(Platform::current())
, target_platform(Platform::current())
{}
};
Build::Build(lua::State& lua, path_t directory)
: _this(new Impl(*this, lua, std::move(directory)))
{
_this->build_stack.push_back(_this->root_directory);
if (fs::is_regular_file(_this->env_path))
{
try { _this->env.load(_this->env_path); }
catch (...) {
CONFIGURE_THROW(
error::InvalidEnviron("Couldn't load the configuration file")
<< error::path(_this->env_path)
<< error::nested(std::current_exception())
);
}
}
}
Build::Build(lua::State& lua, path_t root_directory,
std::map<std::string, std::string> build_args)
: Build(lua, std::move(root_directory))
{
for (auto& pair: build_args)
_this->build_args[Environ::normalize(pair.first)] = pair.second;
}
Build::~Build()
{
try { _this->env.save(_this->env_path); }
catch (...) {
log::error("Couldn't save environ in", _this->env_path, ":",
error_string());
std::abort();
}
}
void Build::configure(path_t const& project_directory,
path_t const& sub_directory)
{
try {
if (!project_directory.is_absolute())
CONFIGURE_THROW(error::InvalidProject("Not an absolute path"));
if (!fs::is_directory(project_directory))
CONFIGURE_THROW(error::InvalidProject("Not a directory"));
if (fs::equivalent(project_directory, this->directory()))
CONFIGURE_THROW(error::InvalidProject("Same as build directory"));
} catch (error::InvalidProject& err) {
throw err << error::path(project_directory);
}
_this->project_stack.push_back(project_directory);
_this->build_stack.push_back(_prepare_build_directory(sub_directory));
log::status("Configuring project", this->project_directory(), "in", this->directory());
BOOST_SCOPE_EXIT((&_this)){
_this->project_stack.pop_back();
_this->build_stack.pop_back();
} BOOST_SCOPE_EXIT_END
try {
_this->lua.load(find_project_file(project_directory));
_this->lua.getglobal("configure");
// XXX check if not nil
_this->lua.construct<std::reference_wrapper<Build>>(*this);
_this->lua.call(1);
if (_this->project_stack.size() == 1) // Last project on the stack
_finalize_build_directory();
} catch (error::Base& e) {
//e << error::message(
// "While configuring project " + project_directory.string()
//);
throw;
}
}
Build::path_t const& Build::project_directory() const
{
if (_this->project_stack.empty())
throw std::logic_error("No project on the stack");
return _this->project_stack.back();
}
Build::path_t const& Build::root_directory() const
{ return _this->root_directory; }
Build::path_t const& Build::directory() const
{ return _this->build_stack.back(); }
NodePtr const& Build::root_node() const
{ return _this->root_node; }
BuildGraph const& Build::build_graph() const
{ return _this->build_graph; }
Filesystem& Build::fs()
{ return _this->fs; }
Environ& Build::env()
{ return _this->env; }
template<typename T>
boost::optional<T> Build::option(std::string name,
std::string const& description)
{
name = Environ::normalize(std::move(name));
_this->options[name] = description;
auto it = _this->build_args.find(name);
if (it != _this->build_args.end())
{
log::debug("Found option", name, "in command line arguments:", it->second);
if (std::is_same<T, bool>::value)
{
std::string str = boost::to_lower_copy(it->second);
static std::map<std::string, bool> conversions = {
{"true", true}, {"false", false},
{"yes", true}, {"no", false},
{"y", true}, {"n", false},
{"1", true}, {"0", false},
};
bool value;
try { value = conversions.at(str); }
catch (...) {
CONFIGURE_THROW(
error::InvalidOption("Cannot convert '" + it->second +
"' to a boolean")
);
}
_this->env.set(name, value);
}
else
_this->env.set(name, boost::lexical_cast<T>(it->second));
_this->build_args.erase(it);
return boost::optional<T>(_this->env.get<T>(name));
}
return boost::none;
}
template<typename T>
typename Environ::const_ref<T>::type
Build::option(std::string name,
std::string const& description,
typename Environ::const_ref<T>::type default_value)
{
this->option<T>(name, description);
if (!_this->env.has(name))
_this->env.set(name, default_value);
return _this->env.get<T>(name);
}
#define INSTANCIATE(T) \
template \
boost::optional<T> Build::option<T>(std::string name, \
std::string const& description); \
template \
Environ::const_ref<T>::type \
Build::option<T>(std::string name, \
std::string const& description, \
Environ::const_ref<T>::type default_value); \
/**/
INSTANCIATE(std::string);
INSTANCIATE(int);
INSTANCIATE(bool);
INSTANCIATE(fs::path);
Build::path_t Build::_prepare_build_directory(path_t const& sub_directory)
{
fs::create_directories(this->directory() / sub_directory);
return fs::canonical(this->directory() / sub_directory);
}
void Build::_finalize_build_directory()
{
std::unordered_set<fs::path> directories;
for (auto const& pair: _this->file_nodes)
{
if (starts_with(pair.first, this->root_directory()))
directories.insert(pair.first.parent_path());
}
for (auto&& d: directories)
fs::create_directories(d);
}
std::vector<Build::path_t> const& Build::possible_configure_files()
{
static std::vector<path_t> ret {
"configure.lua",
".configure.lua",
".config/project.lua",
};
return ret;
}
Build::path_t Build::find_project_file(path_t project_directory)
{
for (auto&& p: possible_configure_files())
if (fs::is_regular_file(project_directory / p))
return project_directory / p;
throw std::runtime_error("No configuration file found in " + project_directory.string());
}
NodePtr& Build::virtual_node(std::string const& name)
{
if (name.empty())
CONFIGURE_THROW(error::InvalidVirtualNode("Name cannot be empty"));
auto it = _this->virtual_nodes.find(name);
if (it != _this->virtual_nodes.end())
return it->second;
auto node = _this->build_graph.add_node<VirtualNode>(name);
return (_this->virtual_nodes[name] = std::move(node));
}
NodePtr& Build::file_node(path_t const& path)
{
if (!path.is_absolute())
throw std::runtime_error("Not an absolute path: " + path.string());
auto it = _this->file_nodes.find(path);
if (it != _this->file_nodes.end())
return it->second;
auto node = _this->build_graph.add_node<FileNode>(path);
return (_this->file_nodes[path] = std::move(node));
}
NodePtr& Build::directory_node(path_t const& path)
{
if (!path.is_absolute())
throw std::runtime_error("Not an absolute path: " + path.string());
auto it = _this->directory_nodes.find(path);
if (it != _this->directory_nodes.end())
return it->second;
auto node = _this->build_graph.add_node<DirectoryNode>(path);
return (_this->directory_nodes[path] = std::move(node));
}
NodePtr& Build::source_node(path_t const& path)
{
fs::path src;
if (!path.is_absolute())
src = this->project_directory() / path;
else
{
src = path;
if (starts_with(src, this->root_directory()))
CONFIGURE_THROW(
error::InvalidSourceNode("Generated file cannot be a source node")
<< error::path(src)
);
}
if (!fs::is_regular_file(src))
CONFIGURE_THROW(error::InvalidSourceNode("File not found")
<< error::path(src)
);
return this->file_node(src);
}
NodePtr& Build::target_node(path_t const& path)
{
if (path.is_absolute())
return this->file_node(path);
return this->file_node(this->directory() / path);
}
void Build::add_rule(Rule const& rule)
{
CommandPtr cmd = rule.command();
if (rule.targets().empty())
CONFIGURE_THROW(error::InvalidRule("No target specified"));
if (rule.sources().empty())
for (auto& target: rule.targets())
{
try {
_this->build_graph.link(*_this->root_node, *target).command(cmd);
} catch (error::CommandAlreadySet&) {
CONFIGURE_THROW(
error::InvalidRule(
"Trying to generate " + target->string() + " twice"
) << error::nested(std::current_exception())
);
}
}
else
for (auto& target: rule.targets())
for (auto& source: rule.sources())
{
try {
_this->build_graph.link(*source, *target)
.command(cmd);
} catch (error::CommandAlreadySet&) {
CONFIGURE_THROW(
error::InvalidRule(
"Trying to generate " + target->string() + " twice"
) << error::nested(std::current_exception())
);
}
}
}
Platform& Build::host()
{ return _this->host_platform; }
Platform& Build::target()
{ return _this->target_platform; }
void Build::dump_graphviz(std::ostream& out)
{
struct Writer {
Build& _b;
BuildGraph& _g;
Writer(Build& b, BuildGraph& g) : _b(b), _g(g) {}
void operator ()(std::ostream& out, Node::index_type idx) const
{
auto& node = _g.node(idx);
switch (node->kind())
{
case Node::file_node:
case Node::directory_node:
out << "[label=\"" << node->relative_path(_b.directory()).string() << "\"]";
break;
case Node::virtual_node:
out << "[label=\"" << node->name() << "\"]";
break;
default:
out << "[label=\"" << "UNKNOWN" << "\"]";
}
}
void operator ()(std::ostream& out, DependencyLink::index_type idx) const
{
auto const& cmd = _g.link(idx).command();
out << "[label=\"";
bool first = true;
for (auto&& shell_command: cmd.shell_commands())
{
if (first) first = false;
else out << "\\n";
out << quote<CommandParser::unix_shell>(shell_command.dump());
}
out << "\"]";
}
} writer(*this, _this->build_graph);
boost::write_graphviz(
out,
_this->build_graph.graph(),
writer,
writer
);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) <2011>, Tim Simon <tim.simon@radiumblue.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdlib>
#include <string>
#include <iostream>
#include <stdio.h>
#include "wcl/network/TCPServer.h"
using namespace wcl;
void usage() {
printf("NAME\n\tpcontrol - Network command controller for NEC projectors\n\n"
"SYNOPSIS\n\t pcontrol [options] -a <address> -p <port> [COMMAND]\n\n"
"Options:\n"
"\t-h\n\t--help\n"
"\t\tDisplay usage options.\n"
"\t-a\n\t--address\n"
"\t\tThe address of the projector to communicate with.\n"
"\t-p\n\t--port\n"
"\t\tThe port to communicate on.\n"
"COMMANDS\n[COMMAND] can be any single value of the following:\n"
"\t--ON\n\t\tPower ON\n"
"\t--OFF\n\t\tPower OFF\n"
);
}
int main(int argc, char** argv) {
std::string address = "127.0.0.1";
unsigned int port = 7142;
// Determine whethe the arguments given are valid.
if ( argc >= 2 ) {
for ( int counter = 0; counter < argc ; ++counter ) {
if ( strcmp ( argv[counter], "--help" ) == 0 || strcmp ( argv[counter], "-h" ) == 0 ) {
usage();
return 1;
}
if ( strcmp ( argv[counter], "--address" ) == 0 || strcmp (argv[counter], "-a" ) == 0 ) {
if ( counter+1 <= argc ) {
//TODO double check that argc[counter+1] is a valid IP address.
address=argv[counter+1];
counter++;
} else {
usage();
return 1;
}
}
if ( strcmp ( argv[counter], "--port" ) == 0 || strcmp (argv[counter], "-p" ) == 0 ) {
if ( counter+1 <= argc ) {
char *pEnd;
port = strtol ( argv[counter+1], &pEnd, 10 );
counter++;
} else {
usage();
return 1;
}
}
}
// Now determine whether we actually got given a command to send to the projector or not.
if (( strcmp (argv[argc-1], "--ON" ) == 0 ) || ( strcmp (argv[argc-1], "--OFF" ) == 0 ) ) {
} else {
usage();
return -1;
}
try {
TCPSocket projector(address,port);
// Get the last value, which should be our command, and use it for our command to run.
if ( strcmp (argv[argc-1], "--ON" ) == 0 ) {
// 02H 00H 00H 00H 00H 00H 02H
unsigned char toSend[] = { (unsigned char)2, 0, 0, 0, 0, (unsigned char)2 };
projector.write((char*) toSend, 6);
}
if ( strcmp (argv[argc-1], "--OFF" ) == 0 ) {
// 02H 01H 00H 00H 00H 03H
unsigned char toSend[] = { (unsigned char)2, (unsigned char)1, 0, 0, 0, (unsigned char)3 };
projector.write((char*) toSend, 6);
}
// Read the response from the projector.
unsigned char buffer[4096];
projector.read((char *)buffer, 4096);
if ( (int) buffer[0] == 34 ) {
std::cout << "Projecter sends ACK: Doing task." << std::endl;
} else {
std::cout << "Projector did not send ACK. Recieved: " << (int)buffer[0] << std::endl;
}
projector.close();
} catch (SocketException* e) {
fprintf( stderr, "%s", e->what() );
}
} else {
usage();
return -1;
}
return 0;
}
<commit_msg>pcontrol now uses wcl::RemoteProjector rather then establishing a connection on it's own.<commit_after>/*
* Copyright (c) <2011>, Tim Simon <tim.simon@radiumblue.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdlib>
#include <string>
#include <iostream>
#include <stdio.h>
#include <wcl/projector/RemoteProjector.h>
using namespace wcl;
void usage() {
printf("NAME\n\tpcontrol - Network command controller for NEC projectors\n\n"
"SYNOPSIS\n\t pcontrol [options] -a <address> -p <port> [COMMAND]\n\n"
"Options:\n"
"\t-h\n\t--help\n"
"\t\tDisplay usage options.\n"
"\t-a\n\t--address\n"
"\t\tThe address of the projector to communicate with.\n"
"\t-p\n\t--port\n"
"\t\tThe port to communicate on.\n"
"COMMANDS\n[COMMAND] can be any single value of the following:\n"
"\t--ON\n\t\tPower ON\n"
"\t--OFF\n\t\tPower OFF\n"
);
}
int main(int argc, char** argv) {
std::string address = "127.0.0.1";
unsigned int port = 7142;
// Determine whethe the arguments given are valid.
if ( argc >= 2 ) {
for ( int counter = 0; counter < argc ; ++counter ) {
if ( strcmp ( argv[counter], "--help" ) == 0 || strcmp ( argv[counter], "-h" ) == 0 ) {
usage();
return 1;
}
if ( strcmp ( argv[counter], "--address" ) == 0 || strcmp (argv[counter], "-a" ) == 0 ) {
if ( counter+1 <= argc ) {
//TODO double check that argc[counter+1] is a valid IP address.
address=argv[counter+1];
counter++;
} else {
usage();
return 1;
}
}
if ( strcmp ( argv[counter], "--port" ) == 0 || strcmp (argv[counter], "-p" ) == 0 ) {
if ( counter+1 <= argc ) {
char *pEnd;
port = strtol ( argv[counter+1], &pEnd, 10 );
counter++;
} else {
usage();
return 1;
}
}
}
// Now determine whether we actually got given a command to send to the projector or not.
if (( strcmp (argv[argc-1], "--ON" ) == 0 ) || ( strcmp (argv[argc-1], "--OFF" ) == 0 ) ) {
} else {
usage();
return -1;
}
RemoteProjector *rp = new RemoteProjector(address,port,true);
// Get the last value, which should be our command, and use it for our command to run.
if ( strcmp (argv[argc-1], "--ON" ) == 0 ) {
rp->turnOn();
}
if ( strcmp (argv[argc-1], "--OFF" ) == 0 ) {
rp->turnOff();
}
rp->getResponse();
} else {
usage();
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <QPainter>
#include <QAbstractEventDispatcher>
#include <QApplication>
#include <QPaintEvent>
#include <QFontMetrics>
#include <QTextStream>
#include <qterm.h>
#include <stdio.h>
#include <QKeyEvent>
#include <QTimer>
#include <sys/select.h>
#include <errno.h>
#ifdef __QNX__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <bps/bps.h>
#ifdef BPS_VERSION
#include <bps/virtualkeyboard.h>
#else
#include <bbsupport/Keyboard>
#include <bbsupport/Notification>
#endif
#endif
#define WIDTH 80
#define HEIGHT 17
#define BLINK_SPEED 1000
QTerm::QTerm(QWidget *parent) : QWidget(parent)
{
term_create( &terminal );
term_begin( terminal, WIDTH, HEIGHT, 0 );
init();
}
QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent)
{
this->terminal = terminal;
init();
}
void QTerm::init()
{
char_width = 0;
char_height = 0;
cursor_x = -1;
cursor_y = -1;
cursor_on = 1;
resize(1024, 600);
term_set_user_data( terminal, this );
term_register_update( terminal, term_update );
term_register_cursor( terminal, term_update_cursor );
term_register_bell( terminal, term_bell );
notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read );
exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception );
cursor_timer = new QTimer( this );
QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data()));
QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate()));
QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor()));
// Setup the initial font
font = new QFont();
font->setStyleHint(QFont::Courier);//QFont::TypeWriter);
font->setPointSize(12);
font->setStyleStrategy(QFont::NoAntialias);
font->setFamily("Monospace");
font->setFixedPitch(true);
font->setKerning(false);
// Workaround for a bug in OSX - Dave reports that maxWidth returns 0,
// when width of different characters returns the correct value
QFontMetrics metrics(*font);
char_width = metrics.maxWidth();
if(char_width==0) {
fontWorkAround = true;
char_width = metrics.width(QChar('X'));
}
char_height = metrics.lineSpacing();
#ifdef __QNX__
#ifdef BPS_VERSION
virtualkeyboard_show();
#else
BlackBerry::Keyboard::instance().show();
#endif
#endif
cursor_timer->start(BLINK_SPEED);
}
QTerm::~QTerm()
{
delete notifier;
delete exit_notifier;
term_free( terminal );
}
void QTerm::term_bell(term_t handle)
{
#ifdef __QNX__
char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}";
int f = open("/pps/services/multimedia/sound/control", O_RDWR);
write(f, command, sizeof(command));
::close(f);
#else
QApplication::beep();
#endif
}
void QTerm::term_update(term_t handle, int x, int y, int width, int height)
{
QTerm *term = (QTerm *)term_get_user_data( handle );
term->update( x * term->char_width, y * term->char_height,
width * term->char_width, height * term->char_height + term->char_descent );
}
void QTerm::term_update_cursor(term_t handle, int x, int y)
{
QTerm *term = (QTerm *)term_get_user_data( handle );
// Update old cursor location
term->update( term->cursor_x * term->char_width,
term->cursor_y * term->char_height,
term->char_width, term->char_height );
term->cursor_x = x;
term->cursor_y = y;
// Update new cursor location
term->update( term->cursor_x * term->char_width,
term->cursor_y * term->char_height,
term->char_width, term->char_height );
}
void QTerm::terminal_data()
{
if( !term_process_child( terminal ) ) {
exit(0);
}
}
void QTerm::terminate()
{
exit(0);
}
void QTerm::blink_cursor()
{
int coord_x;
cursor_on ^= 1;
if (fontWorkAround) {
// The update region may not be quite monospaced.
int i;
char str[WIDTH];
const uint32_t **grid;
QFontMetrics metrics(*font);
grid = term_get_grid( terminal );
for (i=0;i < WIDTH; i++) {
str[i] = grid[cursor_y][i];
}
coord_x = metrics.width( QString(str),cursor_x );
} else {
coord_x = cursor_x * char_width;
}
update( coord_x,
cursor_y * char_height,
char_width, char_height );
}
void QTerm::paintEvent(QPaintEvent *event)
{
int i, j, color;
int new_width;
int new_height;
const uint32_t **grid;
const uint32_t **attribs;
const uint32_t **colors;
QPainter painter(this);
char str[WIDTH+1];
int cursor_x_coord;
QColor fgColor(255,255,255);
QColor bgColor(0,0,0);
int maxX=0;
painter.setBackgroundMode(Qt::TransparentMode);
painter.setBrush(QColor(8, 0, 0));
painter.setFont( *font );
// First erase the grid with its current dimensions
painter.drawRect(event->rect());
int x,y,w,h;
event->rect().getRect(&x, &y, &w, &h);
//fprintf(stderr,"Rect: (%d, %d) %d x %d\n", x,y,w,h);
grid = term_get_grid( terminal );
attribs = term_get_attribs( terminal );
colors = term_get_colours( terminal );
if (cursor_x < 0 || cursor_y < 0) {
return;
}
#if 1
// Brute force convesion
for(j=0;j<WIDTH;j++) {
str[j]=grid[cursor_y][j];
}
// Workaround to get the cursor in the right spot. For some
// reason, on OSX (again), the monospace font does is not really
// monospace for skinny characters!
if (fontWorkAround) {
cursor_x_coord = painter.fontMetrics().width(QString(str),cursor_x);
} else {
cursor_x_coord = cursor_x * char_width;
}
if ( cursor_on ) {
painter.setPen(fgColor);
painter.setBrush(fgColor);
painter.drawRect( cursor_x_coord +1,
cursor_y * char_height + 1,
char_width-2, char_height-2);
} else {
painter.setPen(bgColor);
painter.setBrush(bgColor);
painter.drawRect( cursor_x_coord +1,
cursor_y * char_height + 1,
char_width-2, char_height-2);
}
painter.setPen(fgColor);
painter.setBrush(fgColor);
for (i=0; i<term_get_height( terminal );i++) {
// Brute force convesion to 8-bit UTF
for( j=0; j< term_get_width( terminal ); j++) {
str[j]=grid[i][j];
}
str[term_get_width( terminal )]=0;
painter.drawText(0, (i) * char_height,
w, char_height,
Qt::TextExpandTabs,
str,
NULL
);
}
#else
painter.setBrush(fgColor);
for( i = 0; i < term_get_height( terminal ); i ++ ) {
for( j = 0; j < term_get_width( terminal ); j ++ ) {
if( cursor_on && j == cursor_x && i == cursor_y ) {
painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2);
painter.setPen(QColor(0, 0, 0));
painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) );
painter.setPen(QColor(255, 255, 255));
} else {
color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] );
painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF));
painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) );
}
}
}
#endif
}
void QTerm::keyPressEvent(QKeyEvent *event)
{
switch(event->key()) {
// FIXME These first two are a workaround for a bug in QT. Remove once it is fixed
case Qt::Key_CapsLock:
case Qt::Key_Shift:
break;
case Qt::Key_Up:
term_send_special( terminal, TERM_KEY_UP );
break;
case Qt::Key_Down:
term_send_special( terminal, TERM_KEY_DOWN );
break;
case Qt::Key_Right:
term_send_special( terminal, TERM_KEY_RIGHT );
break;
case Qt::Key_Left:
term_send_special( terminal, TERM_KEY_LEFT );
break;
default:
term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() );
break;
}
}
void QTerm::resizeEvent(QResizeEvent *event)
{
if( char_width != 0 && char_height != 0 ) {
#ifdef __QNX__
{
int kbd_height;
#ifdef BPS_VERSION
virtualkeyboard_get_height( &kbd_height );
#else
kbd_height = BlackBerry::Keyboard::instance().keyboardHeight();
#endif
term_resize( terminal, event->size().width() / char_width, (event->size().height() - kbd_height) / char_height, 0 );
}
#else
term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 );
#endif
}
}
int main(int argc, char *argv[])
{
term_t terminal;
#ifdef __QNX__
#ifdef BPS_VERSION
if( bps_initialize() != BPS_SUCCESS ) {
fprintf(stderr, "Failed to initialize bps (%s)\n", strerror( errno ) );
exit(1);
}
#endif
#endif
if( !term_create( &terminal ) ) {
fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) );
exit(1);
}
if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) {
fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) );
exit(1);
}
{
QCoreApplication::addLibraryPath("app/native/lib");
QApplication app(argc, argv);
QTerm term(NULL, terminal);
term.show();
return app.exec();
}
}
<commit_msg>Fix a couple uses of uninitialized variables. This fixes the crash I was seeing, and the descent problem<commit_after>#include <QPainter>
#include <QAbstractEventDispatcher>
#include <QApplication>
#include <QPaintEvent>
#include <QFontMetrics>
#include <QTextStream>
#include <qterm.h>
#include <stdio.h>
#include <QKeyEvent>
#include <QTimer>
#include <sys/select.h>
#include <errno.h>
#ifdef __QNX__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <bps/bps.h>
#ifdef BPS_VERSION
#include <bps/virtualkeyboard.h>
#else
#include <bbsupport/Keyboard>
#include <bbsupport/Notification>
#endif
#endif
#define WIDTH 80
#define HEIGHT 17
#define BLINK_SPEED 1000
QTerm::QTerm(QWidget *parent) : QWidget(parent)
{
term_create( &terminal );
term_begin( terminal, WIDTH, HEIGHT, 0 );
init();
}
QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent)
{
this->terminal = terminal;
init();
}
void QTerm::init()
{
char_width = 0;
char_height = 0;
cursor_x = -1;
cursor_y = -1;
cursor_on = 1;
resize(1024, 600);
term_set_user_data( terminal, this );
term_register_update( terminal, term_update );
term_register_cursor( terminal, term_update_cursor );
term_register_bell( terminal, term_bell );
notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read );
exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception );
cursor_timer = new QTimer( this );
QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data()));
QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate()));
QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor()));
// Setup the initial font
font = new QFont();
font->setStyleHint(QFont::Courier);//QFont::TypeWriter);
font->setPointSize(12);
font->setStyleStrategy(QFont::NoAntialias);
font->setFamily("Monospace");
font->setFixedPitch(true);
font->setKerning(false);
// Workaround for a bug in OSX - Dave reports that maxWidth returns 0,
// when width of different characters returns the correct value
QFontMetrics metrics(*font);
char_width = metrics.maxWidth();
if(char_width==0) {
fontWorkAround = true;
char_width = metrics.width(QChar('X'));
} else {
fontWorkAround = false;
}
char_height = metrics.lineSpacing();
char_descent = metrics.descent();
#ifdef __QNX__
#ifdef BPS_VERSION
virtualkeyboard_show();
#else
BlackBerry::Keyboard::instance().show();
#endif
#endif
cursor_timer->start(BLINK_SPEED);
}
QTerm::~QTerm()
{
delete notifier;
delete exit_notifier;
term_free( terminal );
}
void QTerm::term_bell(term_t handle)
{
#ifdef __QNX__
char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}";
int f = open("/pps/services/multimedia/sound/control", O_RDWR);
write(f, command, sizeof(command));
::close(f);
#else
QApplication::beep();
#endif
}
void QTerm::term_update(term_t handle, int x, int y, int width, int height)
{
QTerm *term = (QTerm *)term_get_user_data( handle );
term->update( x * term->char_width, y * term->char_height,
width * term->char_width, height * term->char_height + term->char_descent );
}
void QTerm::term_update_cursor(term_t handle, int x, int y)
{
QTerm *term = (QTerm *)term_get_user_data( handle );
// Update old cursor location
term->update( term->cursor_x * term->char_width,
term->cursor_y * term->char_height,
term->char_width, term->char_height );
term->cursor_x = x;
term->cursor_y = y;
// Update new cursor location
term->update( term->cursor_x * term->char_width,
term->cursor_y * term->char_height,
term->char_width, term->char_height );
}
void QTerm::terminal_data()
{
if( !term_process_child( terminal ) ) {
exit(0);
}
}
void QTerm::terminate()
{
exit(0);
}
void QTerm::blink_cursor()
{
int coord_x;
cursor_on ^= 1;
if (fontWorkAround) {
// The update region may not be quite monospaced.
int i;
char str[WIDTH];
const uint32_t **grid;
QFontMetrics metrics(*font);
grid = term_get_grid( terminal );
for (i=0;i < WIDTH; i++) {
str[i] = grid[cursor_y][i];
}
coord_x = metrics.width( QString(str),cursor_x );
} else {
coord_x = cursor_x * char_width;
}
update( coord_x,
cursor_y * char_height,
char_width, char_height );
}
void QTerm::paintEvent(QPaintEvent *event)
{
int i, j, color;
int new_width;
int new_height;
const uint32_t **grid;
const uint32_t **attribs;
const uint32_t **colors;
QPainter painter(this);
char str[WIDTH+1];
int cursor_x_coord;
QColor fgColor(255,255,255);
QColor bgColor(0,0,0);
int maxX=0;
painter.setBackgroundMode(Qt::TransparentMode);
painter.setBrush(QColor(8, 0, 0));
painter.setFont( *font );
// First erase the grid with its current dimensions
painter.drawRect(event->rect());
int x,y,w,h;
event->rect().getRect(&x, &y, &w, &h);
//fprintf(stderr,"Rect: (%d, %d) %d x %d\n", x,y,w,h);
grid = term_get_grid( terminal );
attribs = term_get_attribs( terminal );
colors = term_get_colours( terminal );
if (cursor_x < 0 || cursor_y < 0) {
return;
}
#if 1
// Brute force convesion
for(j=0;j<WIDTH;j++) {
str[j]=grid[cursor_y][j];
}
// Workaround to get the cursor in the right spot. For some
// reason, on OSX (again), the monospace font does is not really
// monospace for skinny characters!
if (fontWorkAround) {
cursor_x_coord = painter.fontMetrics().width(QString(str),cursor_x);
} else {
cursor_x_coord = cursor_x * char_width;
}
if ( cursor_on ) {
painter.setPen(fgColor);
painter.setBrush(fgColor);
painter.drawRect( cursor_x_coord +1,
cursor_y * char_height + 1,
char_width-2, char_height-2);
} else {
painter.setPen(bgColor);
painter.setBrush(bgColor);
painter.drawRect( cursor_x_coord +1,
cursor_y * char_height + 1,
char_width-2, char_height-2);
}
painter.setPen(fgColor);
painter.setBrush(fgColor);
for (i=0; i<term_get_height( terminal );i++) {
// Brute force convesion to 8-bit UTF
for( j=0; j< term_get_width( terminal ); j++) {
str[j]=grid[i][j];
}
str[term_get_width( terminal )]=0;
painter.drawText(0, (i) * char_height,
w, char_height,
Qt::TextExpandTabs,
str,
NULL
);
}
#else
painter.setBrush(fgColor);
for( i = 0; i < term_get_height( terminal ); i ++ ) {
for( j = 0; j < term_get_width( terminal ); j ++ ) {
if( cursor_on && j == cursor_x && i == cursor_y ) {
painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2);
painter.setPen(QColor(0, 0, 0));
painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) );
painter.setPen(QColor(255, 255, 255));
} else {
color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] );
painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF));
painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) );
}
}
}
#endif
}
void QTerm::keyPressEvent(QKeyEvent *event)
{
switch(event->key()) {
// FIXME These first two are a workaround for a bug in QT. Remove once it is fixed
case Qt::Key_CapsLock:
case Qt::Key_Shift:
break;
case Qt::Key_Up:
term_send_special( terminal, TERM_KEY_UP );
break;
case Qt::Key_Down:
term_send_special( terminal, TERM_KEY_DOWN );
break;
case Qt::Key_Right:
term_send_special( terminal, TERM_KEY_RIGHT );
break;
case Qt::Key_Left:
term_send_special( terminal, TERM_KEY_LEFT );
break;
default:
term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() );
break;
}
}
void QTerm::resizeEvent(QResizeEvent *event)
{
if( char_width != 0 && char_height != 0 ) {
#ifdef __QNX__
{
int kbd_height;
#ifdef BPS_VERSION
virtualkeyboard_get_height( &kbd_height );
#else
kbd_height = BlackBerry::Keyboard::instance().keyboardHeight();
#endif
term_resize( terminal, event->size().width() / char_width, (event->size().height() - kbd_height) / char_height, 0 );
}
#else
term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 );
#endif
}
}
int main(int argc, char *argv[])
{
term_t terminal;
#ifdef __QNX__
#ifdef BPS_VERSION
if( bps_initialize() != BPS_SUCCESS ) {
fprintf(stderr, "Failed to initialize bps (%s)\n", strerror( errno ) );
exit(1);
}
#endif
#endif
if( !term_create( &terminal ) ) {
fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) );
exit(1);
}
if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) {
fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) );
exit(1);
}
{
QCoreApplication::addLibraryPath("app/native/lib");
QApplication app(argc, argv);
QTerm term(NULL, terminal);
term.show();
return app.exec();
}
}
<|endoftext|>
|
<commit_before>
#include "ImwPlatformWindow.h"
#include "ImwWindowManager.h"
#include <imgui/imgui.h>
#include <imgui/imgui_internal.h>
using namespace ImWindow;
ImwPlatformWindow::ImwPlatformWindow(bool bMain, bool bIsDragWindow)
{
m_bMain = bMain;
m_bIsDragWindow = bIsDragWindow;
m_pContainer = new ImwContainer(this);
m_pState = NULL;
m_pPreviousState = NULL;
void* pTemp = ImGui::GetInternalState();
m_pState = ImwMalloc(ImGui::GetInternalStateSize());
ImGui::SetInternalState(m_pState, true);
ImGui::SetInternalState(pTemp);
}
ImwPlatformWindow::~ImwPlatformWindow()
{
ImwSafeDelete(m_pContainer);
SetState();
if (!IsMain())
{
ImGui::GetIO().Fonts = NULL;
}
ImGui::Shutdown();
RestoreState();
ImwSafeDelete(m_pState);
}
void ImwPlatformWindow::OnClose()
{
ImwWindowManager::GetInstance()->OnClosePlatformWindow(this);
}
static bool s_bStatePush = false;
bool ImwPlatformWindow::IsStateSet()
{
return s_bStatePush;
}
void ImwPlatformWindow::SetState()
{
ImwAssert(s_bStatePush == false);
s_bStatePush = true;
m_pPreviousState = ImGui::GetInternalState();
ImGui::SetInternalState(m_pState);
memcpy(&((ImGuiState*)m_pState)->Style, &((ImGuiState*)m_pPreviousState)->Style, sizeof(ImGuiStyle));
}
void ImwPlatformWindow::RestoreState()
{
ImwAssert(s_bStatePush == true);
s_bStatePush = false;
memcpy(&((ImGuiState*)m_pPreviousState)->Style, &((ImGuiState*)m_pState)->Style, sizeof(ImGuiStyle));
ImGui::SetInternalState(m_pPreviousState);
}
void ImwPlatformWindow::OnLoseFocus()
{
ImGuiState& g = *((ImGuiState*)m_pState);
g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = g.SetNextWindowFocus = 0;
}
void ImwPlatformWindow::Paint()
{
ImwWindowManager::GetInstance()->Paint(this);
}
bool ImwPlatformWindow::IsMain()
{
return m_bMain;
}
void ImwPlatformWindow::Dock(ImwWindow* pWindow)
{
m_pContainer->Dock(pWindow);
}
bool ImwPlatformWindow::UnDock(ImwWindow* pWindow)
{
return m_pContainer->UnDock(pWindow);
}
ImwContainer* ImwPlatformWindow::GetContainer()
{
return m_pContainer;
}
ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow)
{
return m_pContainer->HasWindow(pWindow);
}
void ImwPlatformWindow::PaintContainer()
{
m_pContainer->Paint();
}
<commit_msg>Never create imgui.ini<commit_after>
#include "ImwPlatformWindow.h"
#include "ImwWindowManager.h"
#include <imgui/imgui.h>
#include <imgui/imgui_internal.h>
using namespace ImWindow;
ImwPlatformWindow::ImwPlatformWindow(bool bMain, bool bIsDragWindow)
{
m_bMain = bMain;
m_bIsDragWindow = bIsDragWindow;
m_pContainer = new ImwContainer(this);
m_pState = NULL;
m_pPreviousState = NULL;
void* pTemp = ImGui::GetInternalState();
m_pState = ImwMalloc(ImGui::GetInternalStateSize());
ImGui::SetInternalState(m_pState, true);
ImGui::GetIO().IniFilename = NULL;
ImGui::SetInternalState(pTemp);
}
ImwPlatformWindow::~ImwPlatformWindow()
{
ImwSafeDelete(m_pContainer);
SetState();
if (!IsMain())
{
ImGui::GetIO().Fonts = NULL;
}
ImGui::Shutdown();
RestoreState();
ImwSafeDelete(m_pState);
}
void ImwPlatformWindow::OnClose()
{
ImwWindowManager::GetInstance()->OnClosePlatformWindow(this);
}
static bool s_bStatePush = false;
bool ImwPlatformWindow::IsStateSet()
{
return s_bStatePush;
}
void ImwPlatformWindow::SetState()
{
ImwAssert(s_bStatePush == false);
s_bStatePush = true;
m_pPreviousState = ImGui::GetInternalState();
ImGui::SetInternalState(m_pState);
memcpy(&((ImGuiState*)m_pState)->Style, &((ImGuiState*)m_pPreviousState)->Style, sizeof(ImGuiStyle));
}
void ImwPlatformWindow::RestoreState()
{
ImwAssert(s_bStatePush == true);
s_bStatePush = false;
memcpy(&((ImGuiState*)m_pPreviousState)->Style, &((ImGuiState*)m_pState)->Style, sizeof(ImGuiStyle));
ImGui::SetInternalState(m_pPreviousState);
}
void ImwPlatformWindow::OnLoseFocus()
{
ImGuiState& g = *((ImGuiState*)m_pState);
g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = g.SetNextWindowFocus = 0;
}
void ImwPlatformWindow::Paint()
{
ImwWindowManager::GetInstance()->Paint(this);
}
bool ImwPlatformWindow::IsMain()
{
return m_bMain;
}
void ImwPlatformWindow::Dock(ImwWindow* pWindow)
{
m_pContainer->Dock(pWindow);
}
bool ImwPlatformWindow::UnDock(ImwWindow* pWindow)
{
return m_pContainer->UnDock(pWindow);
}
ImwContainer* ImwPlatformWindow::GetContainer()
{
return m_pContainer;
}
ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow)
{
return m_pContainer->HasWindow(pWindow);
}
void ImwPlatformWindow::PaintContainer()
{
m_pContainer->Paint();
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageAccumulate.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 "vtkImageAccumulate.h"
#include <math.h>
#include <stdlib.h>
#include "vtkObjectFactory.h"
//----------------------------------------------------------------------------
vtkImageAccumulate* vtkImageAccumulate::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageAccumulate");
if(ret)
{
return (vtkImageAccumulate*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkImageAccumulate;
}
//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageAccumulate::vtkImageAccumulate()
{
int idx;
for (idx = 0; idx < 3; ++idx)
{
this->ComponentSpacing[idx] = 1.0;
this->ComponentOrigin[idx] = 0.0;
this->ComponentExtent[idx*2] = 0;
this->ComponentExtent[idx*2+1] = 0;
}
this->ComponentExtent[1] = 255;
this->ReverseStencil = 0;
this->Min[0] = this->Min[1] = this->Min[2] = 0.0;
this->Max[0] = this->Max[1] = this->Max[2] = 0.0;
this->Mean[0] = this->Mean[1] = this->Mean[2] = 0.0;
this->StandardDeviation[0] = this->StandardDeviation[1] = this->StandardDeviation[2] = 0.0;
this->VoxelCount = 0;
}
//----------------------------------------------------------------------------
vtkImageAccumulate::~vtkImageAccumulate()
{
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int extent[6])
{
int idx, modified = 0;
for (idx = 0; idx < 6; ++idx)
{
if (this->ComponentExtent[idx] != extent[idx])
{
this->ComponentExtent[idx] = extent[idx];
this->Modified();
}
}
if (modified)
{
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int minX, int maxX,
int minY, int maxY,
int minZ, int maxZ)
{
int extent[6];
extent[0] = minX; extent[1] = maxX;
extent[2] = minY; extent[3] = maxY;
extent[4] = minZ; extent[5] = maxZ;
this->SetComponentExtent(extent);
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::GetComponentExtent(int extent[6])
{
int idx;
for (idx = 0; idx < 6; ++idx)
{
extent[idx] = this->ComponentExtent[idx];
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetStencil(vtkImageStencilData *stencil)
{
this->vtkProcessObject::SetNthInput(1, stencil);
}
//----------------------------------------------------------------------------
vtkImageStencilData *vtkImageAccumulate::GetStencil()
{
if (this->NumberOfInputs < 2)
{
return NULL;
}
else
{
return (vtkImageStencilData *)(this->Inputs[1]);
}
}
//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class T>
static void vtkImageAccumulateExecute(vtkImageAccumulate *self,
vtkImageData *inData, T *inPtr,
vtkImageData *outData, int *outPtr,
double Min[3],
double Max[3],
double Mean[3],
long int *VoxelCount)
{
int idX, idY, idZ, idxC;
int iter, pmin0, pmax0, min0, max0, min1, max1, min2, max2;
int inInc0, inInc1, inInc2;
T *tempPtr;
int *outPtrC;
int numC, outIdx, *outExtent, *outIncs;
float *origin, *spacing;
unsigned long count = 0;
unsigned long target;
double sumSqr[3], variance;
// variables used to compute statistics (filter handles max 3 components)
double sum[3];
sum[0] = sum[1] = sum[2] = 0.0;
Min[0] = Min[1] = Min[2] = VTK_DOUBLE_MAX;
Max[0] = Max[1] = Max[2] = VTK_DOUBLE_MIN;
sumSqr[0] = sumSqr[1] = sumSqr[2] = 0.0;
StandardDeviation[0] = StandardDeviation[1] = StandardDeviation[2] = 0.0;
*VoxelCount = 0;
vtkImageStencilData *stencil = self->GetStencil();
// Zero count in every bin
outData->GetExtent(min0, max0, min1, max1, min2, max2);
memset((void *)outPtr, 0,
(max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int));
// Get information to march through data
numC = inData->GetNumberOfScalarComponents();
inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2);
inData->GetIncrements(inInc0, inInc1, inInc2);
outExtent = outData->GetExtent();
outIncs = outData->GetIncrements();
origin = outData->GetOrigin();
spacing = outData->GetSpacing();
target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)/50.0);
target++;
// Loop through input pixels
for (idZ = min2; idZ <= max2; idZ++)
{
for (idY = min1; idY <= max1; idY++)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
// loop over stencil sub-extents
iter = 0;
if (self->GetReverseStencil())
{ // flag that we want the complementary extents
iter = -1;
}
pmin0 = min0;
pmax0 = max0;
while ((stencil != 0 &&
stencil->GetNextExtent(pmin0,pmax0,min0,max0,idY,idZ,iter)) ||
(stencil == 0 && iter++ == 0))
{
// set up pointer for sub extent
tempPtr = inPtr + (inInc2*(idZ - min2) +
inInc1*(idY - min1) +
numC*(pmin0 - min0));
// accumulate over the sub extent
for (idX = pmin0; idX <= pmax0; idX++)
{
// find the bin for this pixel.
outPtrC = outPtr;
for (idxC = 0; idxC < numC; ++idxC)
{
// Gather statistics
sum[idxC]+= *tempPtr;
if (*tempPtr > Max[idxC])
{
Max[idxC] = *tempPtr;
}
else if (*tempPtr < Min[idxC])
{
Min[idxC] = *tempPtr;
}
(*VoxelCount)++;
// compute the index
outIdx = (int) floor((((double)*tempPtr++ - origin[idxC])
/ spacing[idxC]));
if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
{
// Out of bin range
outPtrC = NULL;
break;
}
outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
}
if (outPtrC)
{
++(*outPtrC);
}
}
}
}
}
if (*VoxelCount) // avoid the div0
{
Mean[0] = sum[0] / (double)*VoxelCount;
Mean[1] = sum[1] / (double)*VoxelCount;
Mean[2] = sum[2] / (double)*VoxelCount;
variance = sumSqr[0] / (double)*VoxelCount - ((double) *VoxelCount * Mean[0] * Mean[0] / (double) (*VoxelCount - 1));
StandardDeviation[1] = sqrt(variance);
variance = sumSqr[1] / (double)*VoxelCount - ((double) *VoxelCount * Mean[1] * Mean[1] / (double) (*VoxelCount - 1));
StandardDeviation[1] = sqrt(variance);
variance = sumSqr[2] / (double)*VoxelCount - ((double) *VoxelCount * Mean[2] * Mean[2] / (double) (*VoxelCount - 1));
StandardDeviation[2] = sqrt(variance);
}
else
{
Mean[0] = Mean[1] = Mean[2] = 0.0;
StandardDeviation[0] = StandardDeviation[1] = StandardDeviation[2] = 0.0;
}
}
//----------------------------------------------------------------------------
// This method is passed a input and output Data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the Datas data types.
void vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out))
{
void *inPtr;
void *outPtr;
vtkImageData *inData = this->GetInput();
vtkImageData *outData = this->GetOutput();
vtkDebugMacro(<<"Executing image accumulate");
// We need to allocate our own scalars since we are overriding
// the superclasses "Execute()" method.
outData->SetExtent(outData->GetWholeExtent());
outData->AllocateScalars();
inPtr = inData->GetScalarPointerForExtent(inData->GetUpdateExtent());
outPtr = outData->GetScalarPointer();
// Components turned into x, y and z
if (this->GetInput()->GetNumberOfScalarComponents() > 3)
{
vtkErrorMacro("This filter can handle upto 3 components");
return;
}
// this filter expects that output is type int.
if (outData->GetScalarType() != VTK_INT)
{
vtkErrorMacro(<< "Execute: out ScalarType " << outData->GetScalarType()
<< " must be int\n");
return;
}
switch (inData->GetScalarType())
{
vtkTemplateMacro10(vtkImageAccumulateExecute, this,
inData, (VTK_TT *)(inPtr),
outData, (int *)(outPtr),
this->Min, this->Max,
this->Mean,
this->StandardDeviation, &this->VoxelCount);
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::ExecuteInformation(vtkImageData *input,
vtkImageData *output)
{
output->SetWholeExtent(this->ComponentExtent);
output->SetOrigin(this->ComponentOrigin);
output->SetSpacing(this->ComponentSpacing);
output->SetNumberOfScalarComponents(1);
output->SetScalarType(VTK_INT);
// need to set the spacing and origin of the stencil to match the output
vtkImageStencilData *stencil = this->GetStencil();
if (stencil)
{
stencil->SetSpacing(input->GetSpacing());
stencil->SetOrigin(input->GetOrigin());
}
}
//----------------------------------------------------------------------------
// Get ALL of the input.
void vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6],
int outExt[6])
{
int *wholeExtent;
outExt = outExt;
wholeExtent = this->GetInput()->GetWholeExtent();
memcpy(inExt, wholeExtent, 6*sizeof(int));
}
void vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent)
{
vtkImageToImageFilter::PrintSelf(os,indent);
os << indent << "Mean: " << this->Mean << "\n";
os << indent << "Min: " << this->Min << "\n";
os << indent << "Max: " << this->Max << "\n";
os << indent << "StandardDeviation: " << this->StandardDeviation << "\n";
os << indent << "VoxelCount: " << this->VoxelCount << "\n";
os << indent << "Stencil: " << this->GetStencil() << "\n";
os << indent << "ReverseStencil: " << (this->ReverseStencil ?
"On\n" : "Off\n");
os << indent << "ComponentOrigin: ( "
<< this->ComponentOrigin[0] << ", "
<< this->ComponentOrigin[1] << ", "
<< this->ComponentOrigin[2] << " )\n";
os << indent << "ComponentSpacing: ( "
<< this->ComponentSpacing[0] << ", "
<< this->ComponentSpacing[1] << ", "
<< this->ComponentSpacing[2] << " )\n";
os << indent << "ComponentExtent: ( "
<< this->ComponentExtent[0] << "," << this->ComponentExtent[1] << " "
<< this->ComponentExtent[2] << "," << this->ComponentExtent[3] << " "
<< this->ComponentExtent[4] << "," << this->ComponentExtent[5] << " }\n";
}
<commit_msg>ERR: bad method signature.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageAccumulate.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 "vtkImageAccumulate.h"
#include <math.h>
#include <stdlib.h>
#include "vtkObjectFactory.h"
//----------------------------------------------------------------------------
vtkImageAccumulate* vtkImageAccumulate::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageAccumulate");
if(ret)
{
return (vtkImageAccumulate*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkImageAccumulate;
}
//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageAccumulate::vtkImageAccumulate()
{
int idx;
for (idx = 0; idx < 3; ++idx)
{
this->ComponentSpacing[idx] = 1.0;
this->ComponentOrigin[idx] = 0.0;
this->ComponentExtent[idx*2] = 0;
this->ComponentExtent[idx*2+1] = 0;
}
this->ComponentExtent[1] = 255;
this->ReverseStencil = 0;
this->Min[0] = this->Min[1] = this->Min[2] = 0.0;
this->Max[0] = this->Max[1] = this->Max[2] = 0.0;
this->Mean[0] = this->Mean[1] = this->Mean[2] = 0.0;
this->StandardDeviation[0] = this->StandardDeviation[1] = this->StandardDeviation[2] = 0.0;
this->VoxelCount = 0;
}
//----------------------------------------------------------------------------
vtkImageAccumulate::~vtkImageAccumulate()
{
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int extent[6])
{
int idx, modified = 0;
for (idx = 0; idx < 6; ++idx)
{
if (this->ComponentExtent[idx] != extent[idx])
{
this->ComponentExtent[idx] = extent[idx];
this->Modified();
}
}
if (modified)
{
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int minX, int maxX,
int minY, int maxY,
int minZ, int maxZ)
{
int extent[6];
extent[0] = minX; extent[1] = maxX;
extent[2] = minY; extent[3] = maxY;
extent[4] = minZ; extent[5] = maxZ;
this->SetComponentExtent(extent);
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::GetComponentExtent(int extent[6])
{
int idx;
for (idx = 0; idx < 6; ++idx)
{
extent[idx] = this->ComponentExtent[idx];
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetStencil(vtkImageStencilData *stencil)
{
this->vtkProcessObject::SetNthInput(1, stencil);
}
//----------------------------------------------------------------------------
vtkImageStencilData *vtkImageAccumulate::GetStencil()
{
if (this->NumberOfInputs < 2)
{
return NULL;
}
else
{
return (vtkImageStencilData *)(this->Inputs[1]);
}
}
//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class T>
static void vtkImageAccumulateExecute(vtkImageAccumulate *self,
vtkImageData *inData, T *inPtr,
vtkImageData *outData, int *outPtr,
double Min[3],
double Max[3],
double Mean[3],
double StandardDeviation[3],
long int *VoxelCount)
{
int idX, idY, idZ, idxC;
int iter, pmin0, pmax0, min0, max0, min1, max1, min2, max2;
int inInc0, inInc1, inInc2;
T *tempPtr;
int *outPtrC;
int numC, outIdx, *outExtent, *outIncs;
float *origin, *spacing;
unsigned long count = 0;
unsigned long target;
double sumSqr[3], variance;
// variables used to compute statistics (filter handles max 3 components)
double sum[3];
sum[0] = sum[1] = sum[2] = 0.0;
Min[0] = Min[1] = Min[2] = VTK_DOUBLE_MAX;
Max[0] = Max[1] = Max[2] = VTK_DOUBLE_MIN;
sumSqr[0] = sumSqr[1] = sumSqr[2] = 0.0;
StandardDeviation[0] = StandardDeviation[1] = StandardDeviation[2] = 0.0;
*VoxelCount = 0;
vtkImageStencilData *stencil = self->GetStencil();
// Zero count in every bin
outData->GetExtent(min0, max0, min1, max1, min2, max2);
memset((void *)outPtr, 0,
(max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int));
// Get information to march through data
numC = inData->GetNumberOfScalarComponents();
inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2);
inData->GetIncrements(inInc0, inInc1, inInc2);
outExtent = outData->GetExtent();
outIncs = outData->GetIncrements();
origin = outData->GetOrigin();
spacing = outData->GetSpacing();
target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)/50.0);
target++;
// Loop through input pixels
for (idZ = min2; idZ <= max2; idZ++)
{
for (idY = min1; idY <= max1; idY++)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
// loop over stencil sub-extents
iter = 0;
if (self->GetReverseStencil())
{ // flag that we want the complementary extents
iter = -1;
}
pmin0 = min0;
pmax0 = max0;
while ((stencil != 0 &&
stencil->GetNextExtent(pmin0,pmax0,min0,max0,idY,idZ,iter)) ||
(stencil == 0 && iter++ == 0))
{
// set up pointer for sub extent
tempPtr = inPtr + (inInc2*(idZ - min2) +
inInc1*(idY - min1) +
numC*(pmin0 - min0));
// accumulate over the sub extent
for (idX = pmin0; idX <= pmax0; idX++)
{
// find the bin for this pixel.
outPtrC = outPtr;
for (idxC = 0; idxC < numC; ++idxC)
{
// Gather statistics
sum[idxC]+= *tempPtr;
if (*tempPtr > Max[idxC])
{
Max[idxC] = *tempPtr;
}
else if (*tempPtr < Min[idxC])
{
Min[idxC] = *tempPtr;
}
(*VoxelCount)++;
// compute the index
outIdx = (int) floor((((double)*tempPtr++ - origin[idxC])
/ spacing[idxC]));
if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
{
// Out of bin range
outPtrC = NULL;
break;
}
outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
}
if (outPtrC)
{
++(*outPtrC);
}
}
}
}
}
if (*VoxelCount) // avoid the div0
{
Mean[0] = sum[0] / (double)*VoxelCount;
Mean[1] = sum[1] / (double)*VoxelCount;
Mean[2] = sum[2] / (double)*VoxelCount;
variance = sumSqr[0] / (double)*VoxelCount - ((double) *VoxelCount * Mean[0] * Mean[0] / (double) (*VoxelCount - 1));
StandardDeviation[1] = sqrt(variance);
variance = sumSqr[1] / (double)*VoxelCount - ((double) *VoxelCount * Mean[1] * Mean[1] / (double) (*VoxelCount - 1));
StandardDeviation[1] = sqrt(variance);
variance = sumSqr[2] / (double)*VoxelCount - ((double) *VoxelCount * Mean[2] * Mean[2] / (double) (*VoxelCount - 1));
StandardDeviation[2] = sqrt(variance);
}
else
{
Mean[0] = Mean[1] = Mean[2] = 0.0;
StandardDeviation[0] = StandardDeviation[1] = StandardDeviation[2] = 0.0;
}
}
//----------------------------------------------------------------------------
// This method is passed a input and output Data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the Datas data types.
void vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out))
{
void *inPtr;
void *outPtr;
vtkImageData *inData = this->GetInput();
vtkImageData *outData = this->GetOutput();
vtkDebugMacro(<<"Executing image accumulate");
// We need to allocate our own scalars since we are overriding
// the superclasses "Execute()" method.
outData->SetExtent(outData->GetWholeExtent());
outData->AllocateScalars();
inPtr = inData->GetScalarPointerForExtent(inData->GetUpdateExtent());
outPtr = outData->GetScalarPointer();
// Components turned into x, y and z
if (this->GetInput()->GetNumberOfScalarComponents() > 3)
{
vtkErrorMacro("This filter can handle upto 3 components");
return;
}
// this filter expects that output is type int.
if (outData->GetScalarType() != VTK_INT)
{
vtkErrorMacro(<< "Execute: out ScalarType " << outData->GetScalarType()
<< " must be int\n");
return;
}
switch (inData->GetScalarType())
{
vtkTemplateMacro10(vtkImageAccumulateExecute, this,
inData, (VTK_TT *)(inPtr),
outData, (int *)(outPtr),
this->Min, this->Max,
this->Mean,
this->StandardDeviation, &this->VoxelCount);
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::ExecuteInformation(vtkImageData *input,
vtkImageData *output)
{
output->SetWholeExtent(this->ComponentExtent);
output->SetOrigin(this->ComponentOrigin);
output->SetSpacing(this->ComponentSpacing);
output->SetNumberOfScalarComponents(1);
output->SetScalarType(VTK_INT);
// need to set the spacing and origin of the stencil to match the output
vtkImageStencilData *stencil = this->GetStencil();
if (stencil)
{
stencil->SetSpacing(input->GetSpacing());
stencil->SetOrigin(input->GetOrigin());
}
}
//----------------------------------------------------------------------------
// Get ALL of the input.
void vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6],
int outExt[6])
{
int *wholeExtent;
outExt = outExt;
wholeExtent = this->GetInput()->GetWholeExtent();
memcpy(inExt, wholeExtent, 6*sizeof(int));
}
void vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent)
{
vtkImageToImageFilter::PrintSelf(os,indent);
os << indent << "Mean: " << this->Mean << "\n";
os << indent << "Min: " << this->Min << "\n";
os << indent << "Max: " << this->Max << "\n";
os << indent << "StandardDeviation: " << this->StandardDeviation << "\n";
os << indent << "VoxelCount: " << this->VoxelCount << "\n";
os << indent << "Stencil: " << this->GetStencil() << "\n";
os << indent << "ReverseStencil: " << (this->ReverseStencil ?
"On\n" : "Off\n");
os << indent << "ComponentOrigin: ( "
<< this->ComponentOrigin[0] << ", "
<< this->ComponentOrigin[1] << ", "
<< this->ComponentOrigin[2] << " )\n";
os << indent << "ComponentSpacing: ( "
<< this->ComponentSpacing[0] << ", "
<< this->ComponentSpacing[1] << ", "
<< this->ComponentSpacing[2] << " )\n";
os << indent << "ComponentExtent: ( "
<< this->ComponentExtent[0] << "," << this->ComponentExtent[1] << " "
<< this->ComponentExtent[2] << "," << this->ComponentExtent[3] << " "
<< this->ComponentExtent[4] << "," << this->ComponentExtent[5] << " }\n";
}
<|endoftext|>
|
<commit_before>//
// Created by kyle on 10/12/16.
//
#include "tansa/jocsParser.h"
#include <regex>
#include <algorithm>
namespace tansa {
const std::string Jocs::HOME_KEY = "startPosition";
const std::string Jocs::ID_KEY = "id";
const std::string Jocs::UNITS_KEY = "units";
const std::string Jocs::LENGTH_KEY = "length";
const std::string Jocs::TIME_KEY = "time";
const std::string Jocs::ANGLE_KEY = "angle";
const std::string Jocs::THEATER_VOLUME_KEY = "theater_volume";
const std::string Jocs::MIN_KEY = "min";
const std::string Jocs::MAX_KEY = "max";
const std::string Jocs::REPEAT_KEY = "repeat";
const std::string Jocs::CHOREOGRAPHY_KEY = "chor";
const std::string Jocs::ACTION_TIME_KEY = "time";
const std::string Jocs::ACTION_ROOT_KEY = "action";
const std::string Jocs::ACTION_TYPE_KEY = "type";
const std::string Jocs::DURATION_KEY = "duration";
const std::string Jocs::DRONE_ARRAY_KEY = "drones";
const std::string Jocs::DRONE_START_OFF_KEY = "startOffset";
const std::string Jocs::DRONE_END_OFF_KEY = "endOffset";
const std::string Jocs::DRONE_OFF_KEY = "totalOffset"; // TODO: use this for circles and hovers
const std::string Jocs::ACTION_DATA_KEY = "data";
const std::string Jocs::STARTPOS_KEY = "startPoint";
const std::string Jocs::ENDPOS_KEY = "endPoint";
const std::string Jocs::HOVER_KEY = "hoverPoint";
const std::string Jocs::CIRCLE_ORIGIN_KEY = "originPoint";
const std::string Jocs::CIRCLE_RADIUS_KEY = "radius";
const std::string Jocs::CIRCLE_THETA1_KEY = "theta1";
const std::string Jocs::CIRCLE_THETA2_KEY = "theta2";
const double Jocs::FEET_TO_METERS = 0.3048;
const double Jocs::DEGREES_TO_RADIANS = M_PI/180.0;
Jocs Jocs::Parse(std::string jocsPath) {
ifstream jocsStream(jocsPath);
std::string jocsData((std::istreambuf_iterator<char>(jocsStream)), std::istreambuf_iterator<char>());
//For some reason this regex didn't like the end of line $...but does work without it
assert(jocsData.find("//") == std::string::npos);
auto rawJson = nlohmann::json::parse(jocsData);
auto units = rawJson[UNITS_KEY];
bool needConvertToMeters = (units[LENGTH_KEY] == "feet");
bool needConvertToRadians = (units[ANGLE_KEY] == "degrees");
unsigned repeat = rawJson[REPEAT_KEY];
auto ret = Jocs(needConvertToMeters, needConvertToRadians, repeat);
ret.parseActions(rawJson);
auto actions = ret.GetActions();
auto homes = ret.GetHomes();
auto floatComp = [](double a, double b) -> bool { return fabs(a-b) < 0.1; };
auto pointComp = [](Point a, Point b) -> bool { return fabs((a-b).norm()) < 0.1; };
try {
for (unsigned j = 0; j < actions.size(); j++) {
auto startPoint = homes[j];
double startTime = 0.0;
//Sort actions for each drone based on start time
std::sort(actions[j].begin(), actions[j].end(),
[](Action *const &lhs, Action *const &rhs) { return lhs->GetStartTime() < rhs->GetStartTime(); });
for (unsigned i = 0; i < actions[j].size(); i++) {
//Check temporal continuity
Action *a = actions[j][i];
double sTime = a->GetStartTime();
double eTime = a->GetEndTime();
if (!floatComp(sTime, startTime)) {
throw std::runtime_error(
"Time Discontinuity for Drone: " + std::to_string(j) + " with start time: " +
std::to_string(sTime) + " and end time: " + std::to_string(eTime));
}
startTime = eTime;
//Check spatial continuity
if (a->GetActionType() != ActionTypes::Light) {
auto ma = static_cast<MotionAction *>(a);
auto actionStart = ma->GetStartPoint();
if (!pointComp(actionStart, startPoint)) {
throw std::runtime_error(
"Spatial Discontinuity for Drone: " + std::to_string(j) + ". Jumping from point: " +
"[" + std::to_string(startPoint.x()) + " " + std::to_string(startPoint.y()) + " " +
std::to_string(startPoint.z()) + "]" +
" to point: " "[" + std::to_string(actionStart.x()) + " " +
std::to_string(actionStart.y()) + " " + std::to_string(actionStart.z()) + "]" + "\n"
+ "at start time: " + std::to_string(sTime)
);
}
startPoint = ma->GetEndPoint();
}
}
}
} catch (std::runtime_error e){
std::cerr << e.what() << std::endl;
}
return ret;
}
void Jocs::parseActions(const nlohmann::json &data) {
auto actionsJson = data[CHOREOGRAPHY_KEY];
auto drones = data[DRONE_ARRAY_KEY];
assert(drones.is_array());
assert(actionsJson.is_array());
auto droneLength = drones.size();
homes.resize(droneLength);
double conversionFactor = needConvertToMeters ? FEET_TO_METERS : 1.0;
for(unsigned i = 0; i < droneLength; i++){
homes[i] = Point(drones[i][HOME_KEY][0], drones[i][HOME_KEY][1], drones[i][HOME_KEY][2])*conversionFactor;
}
auto length = actionsJson.size();
//allocate space for each subarray for each drone.
actions.resize(droneLength);
// For each drone, gather actions in a vector and add as entry in "actions" 2d vector
double lastTime = 0.0;
for(unsigned k = 0; k < repeat; k++) {
for (unsigned i = 0; i < length; i++) {
if (i == length - 1) {
lastTime = parseAction(actionsJson[i], lastTime);
} else {
parseAction(actionsJson[i], lastTime);
}
}
}
// Go back and review actions such that transitions can be created with polynomial trajectories
for (unsigned i = 0; i < actions.size(); i++) {
// Each entry in "actions" has a vector full of actions for that drone
for (unsigned j = 0; j < actions[i].size(); j++) {
if (!actions[i][j]->IsCalculated()) {
double thisStart = actions[i][j]->GetStartTime();
double thisEnd = actions[i][j]->GetEndTime();
if (j == 0) {
MotionAction *next = static_cast<MotionAction *>(actions[i][j + 1]);
auto endState = next->GetPathState(next->GetStartTime());
delete actions[i][j];
actions[i][j] = new MotionAction(i,
PolynomialTrajectory::compute(
{homes[i]},
thisStart,
{endState.position, endState.velocity,
endState.acceleration},
thisEnd
),
ActionTypes::Transition
);
} else if (j == (actions[i].size() - 1)) {
//TODO: Handle the case of the last action being a transition, where our ending velocity and acceleration are 0 and destination is home.
} else {
// Calculate previous and next motion to generate what's needed for the transition
MotionAction *prev = static_cast<MotionAction *>(actions[i][j - 1]);
MotionAction *next = static_cast<MotionAction *>(actions[i][j + 1]);
// Get states from the previous and next state that were found
auto startState = prev->GetPathState(prev->GetEndTime());
auto endState = next->GetPathState(next->GetStartTime());
// Cleanup object and replace with a new MotionAction
delete actions[i][j];
actions[i][j] = new MotionAction(i, PolynomialTrajectory::compute(
{startState.position, startState.velocity, startState.acceleration},
thisStart,
{endState.position, endState.velocity, endState.acceleration},
thisEnd
),
ActionTypes::Transition
);
}
}
}
}
}
// TODO: rename since it parses all actions at given timeslot
double Jocs::parseAction(const nlohmann::json::reference data, double lastTime){
auto actionsArray = data[ACTION_ROOT_KEY];
assert(actionsArray.is_array());
double startTime = data[ACTION_TIME_KEY];
double endTime = 0.0;
for(unsigned i = 0; i < actionsArray.size(); i++) {
auto actionsArrayElement = actionsArray[i];
double duration = actionsArrayElement[DURATION_KEY];
unsigned type = convertToActionType(actionsArrayElement[ACTION_TYPE_KEY]);
assert(actionsArrayElement[DRONE_ARRAY_KEY].is_array());
auto drones = actionsArrayElement[DRONE_ARRAY_KEY];
double conversionFactor = needConvertToMeters ? FEET_TO_METERS : 1.0;
endTime += lastTime + startTime + duration;
assert(drones.is_array());
for (unsigned j = 0; j < drones.size(); j++) {
unsigned drone = drones[j][ID_KEY];
Point startOffset(drones[j][DRONE_START_OFF_KEY][0],drones[j][DRONE_START_OFF_KEY][1],drones[j][DRONE_START_OFF_KEY][2]);
Point endOffset(drones[j][DRONE_END_OFF_KEY][0],drones[j][DRONE_END_OFF_KEY][1],drones[j][DRONE_END_OFF_KEY][2]);
startOffset*=conversionFactor;
endOffset*=conversionFactor;
switch (type) {
case ActionTypes::Transition: {
// Actual calculation will be processed after this loop
actions[drone].push_back(new EmptyAction(drone, lastTime + startTime, lastTime + startTime + duration));
break;
}
case ActionTypes::Line: {
Point start(
actionsArrayElement[ACTION_DATA_KEY][STARTPOS_KEY][0],
actionsArrayElement[ACTION_DATA_KEY][STARTPOS_KEY][1],
actionsArrayElement[ACTION_DATA_KEY][STARTPOS_KEY][2]);
start*=conversionFactor;
Point end(
actionsArrayElement[ACTION_DATA_KEY][ENDPOS_KEY][0],
actionsArrayElement[ACTION_DATA_KEY][ENDPOS_KEY][1],
actionsArrayElement[ACTION_DATA_KEY][ENDPOS_KEY][2]);
end*=conversionFactor;
actions[drone].push_back(new MotionAction(
drone, new LinearTrajectory(start + startOffset, lastTime + startTime, end + endOffset, lastTime + startTime + duration), ActionTypes::Line));
break;
}
case ActionTypes::Circle: {
Point origin(
actionsArrayElement[ACTION_DATA_KEY][CIRCLE_ORIGIN_KEY][0],
actionsArrayElement[ACTION_DATA_KEY][CIRCLE_ORIGIN_KEY][1],
actionsArrayElement[ACTION_DATA_KEY][CIRCLE_ORIGIN_KEY][2]);
origin*=conversionFactor;
double radius = actionsArrayElement[ACTION_DATA_KEY][CIRCLE_RADIUS_KEY];
double theta1 = actionsArrayElement[ACTION_DATA_KEY][CIRCLE_THETA1_KEY];
radius*=conversionFactor;
double theta2 = actionsArrayElement[ACTION_DATA_KEY][CIRCLE_THETA2_KEY];
if(needConvertToRadians) {
theta1 = theta1 * DEGREES_TO_RADIANS;
theta2 = theta2 * DEGREES_TO_RADIANS;
}
// TODO: use separate offset key for circle and hover
actions[drone].push_back(new MotionAction(
drone,
new CircleTrajectory(origin + startOffset, radius, theta1, lastTime+startTime, theta2, lastTime + startTime + duration),
ActionTypes::Circle
));
break;
}
case ActionTypes::Hover:{
Point hoverPoint(
actionsArrayElement[ACTION_DATA_KEY][HOVER_KEY][0],
actionsArrayElement[ACTION_DATA_KEY][HOVER_KEY][1],
actionsArrayElement[ACTION_DATA_KEY][HOVER_KEY][2]
);
hoverPoint*=conversionFactor;
// TODO: use separate offset key for circle and hover
actions[drone].push_back(new MotionAction(
drone,
new LinearTrajectory(hoverPoint + startOffset, lastTime + startTime, hoverPoint + endOffset, lastTime + startTime + duration),
ActionTypes::Hover
));
break;
}
default: {
break;
}
}
}
}
return endTime;
}
ActionTypes Jocs::convertToActionType(const std::string& data){
if(data == "transition")
return ActionTypes::Transition;
else if (data == "line")
return ActionTypes::Line;
else if (data == "circle")
return ActionTypes::Circle;
else if (data == "hover")
return ActionTypes::Hover;
return ActionTypes::None;
}
}
<commit_msg>Made error messages for time discontinuity better<commit_after>//
// Created by kyle on 10/12/16.
//
#include "tansa/jocsParser.h"
#include <regex>
#include <algorithm>
namespace tansa {
const std::string Jocs::HOME_KEY = "startPosition";
const std::string Jocs::ID_KEY = "id";
const std::string Jocs::UNITS_KEY = "units";
const std::string Jocs::LENGTH_KEY = "length";
const std::string Jocs::TIME_KEY = "time";
const std::string Jocs::ANGLE_KEY = "angle";
const std::string Jocs::THEATER_VOLUME_KEY = "theater_volume";
const std::string Jocs::MIN_KEY = "min";
const std::string Jocs::MAX_KEY = "max";
const std::string Jocs::REPEAT_KEY = "repeat";
const std::string Jocs::CHOREOGRAPHY_KEY = "chor";
const std::string Jocs::ACTION_TIME_KEY = "time";
const std::string Jocs::ACTION_ROOT_KEY = "action";
const std::string Jocs::ACTION_TYPE_KEY = "type";
const std::string Jocs::DURATION_KEY = "duration";
const std::string Jocs::DRONE_ARRAY_KEY = "drones";
const std::string Jocs::DRONE_START_OFF_KEY = "startOffset";
const std::string Jocs::DRONE_END_OFF_KEY = "endOffset";
const std::string Jocs::DRONE_OFF_KEY = "totalOffset"; // TODO: use this for circles and hovers
const std::string Jocs::ACTION_DATA_KEY = "data";
const std::string Jocs::STARTPOS_KEY = "startPoint";
const std::string Jocs::ENDPOS_KEY = "endPoint";
const std::string Jocs::HOVER_KEY = "hoverPoint";
const std::string Jocs::CIRCLE_ORIGIN_KEY = "originPoint";
const std::string Jocs::CIRCLE_RADIUS_KEY = "radius";
const std::string Jocs::CIRCLE_THETA1_KEY = "theta1";
const std::string Jocs::CIRCLE_THETA2_KEY = "theta2";
const double Jocs::FEET_TO_METERS = 0.3048;
const double Jocs::DEGREES_TO_RADIANS = M_PI/180.0;
Jocs Jocs::Parse(std::string jocsPath) {
ifstream jocsStream(jocsPath);
std::string jocsData((std::istreambuf_iterator<char>(jocsStream)), std::istreambuf_iterator<char>());
//For some reason this regex didn't like the end of line $...but does work without it
assert(jocsData.find("//") == std::string::npos);
auto rawJson = nlohmann::json::parse(jocsData);
auto units = rawJson[UNITS_KEY];
bool needConvertToMeters = (units[LENGTH_KEY] == "feet");
bool needConvertToRadians = (units[ANGLE_KEY] == "degrees");
unsigned repeat = rawJson[REPEAT_KEY];
auto ret = Jocs(needConvertToMeters, needConvertToRadians, repeat);
ret.parseActions(rawJson);
auto actions = ret.GetActions();
auto homes = ret.GetHomes();
auto floatComp = [](double a, double b) -> bool { return fabs(a-b) < 0.1; };
auto pointComp = [](Point a, Point b) -> bool { return fabs((a-b).norm()) < 0.1; };
try {
for (unsigned j = 0; j < actions.size(); j++) {
auto startPoint = homes[j];
double startTime = 0.0;
//Sort actions for each drone based on start time
std::sort(actions[j].begin(), actions[j].end(),
[](Action *const &lhs, Action *const &rhs) { return lhs->GetStartTime() < rhs->GetStartTime(); });
for (unsigned i = 0; i < actions[j].size(); i++) {
//Check temporal continuity
Action *a = actions[j][i];
double sTime = a->GetStartTime();
double eTime = a->GetEndTime();
if (!floatComp(sTime, startTime)) {
throw std::runtime_error(
"Time Discontinuity for Drone: " + std::to_string(j) + " with start time: " +
std::to_string(sTime) + ". Last command ended at : " + std::to_string(startTime));
}
startTime = eTime;
//Check spatial continuity
if (a->GetActionType() != ActionTypes::Light) {
auto ma = static_cast<MotionAction *>(a);
auto actionStart = ma->GetStartPoint();
if (!pointComp(actionStart, startPoint)) {
throw std::runtime_error(
"Spatial Discontinuity for Drone: " + std::to_string(j) + ". Jumping from point: " +
"[" + std::to_string(startPoint.x()) + " " + std::to_string(startPoint.y()) + " " +
std::to_string(startPoint.z()) + "]" +
" to point: " "[" + std::to_string(actionStart.x()) + " " +
std::to_string(actionStart.y()) + " " + std::to_string(actionStart.z()) + "]" + "\n"
+ "at start time: " + std::to_string(sTime)
);
}
startPoint = ma->GetEndPoint();
}
}
}
} catch (std::runtime_error e){
std::cerr << e.what() << std::endl;
}
return ret;
}
void Jocs::parseActions(const nlohmann::json &data) {
auto actionsJson = data[CHOREOGRAPHY_KEY];
auto drones = data[DRONE_ARRAY_KEY];
assert(drones.is_array());
assert(actionsJson.is_array());
auto droneLength = drones.size();
homes.resize(droneLength);
double conversionFactor = needConvertToMeters ? FEET_TO_METERS : 1.0;
for(unsigned i = 0; i < droneLength; i++){
homes[i] = Point(drones[i][HOME_KEY][0], drones[i][HOME_KEY][1], drones[i][HOME_KEY][2])*conversionFactor;
}
auto length = actionsJson.size();
//allocate space for each subarray for each drone.
actions.resize(droneLength);
// For each drone, gather actions in a vector and add as entry in "actions" 2d vector
double lastTime = 0.0;
for(unsigned k = 0; k < repeat; k++) {
for (unsigned i = 0; i < length; i++) {
if (i == length - 1) {
lastTime = parseAction(actionsJson[i], lastTime);
} else {
parseAction(actionsJson[i], lastTime);
}
}
}
// Go back and review actions such that transitions can be created with polynomial trajectories
for (unsigned i = 0; i < actions.size(); i++) {
// Each entry in "actions" has a vector full of actions for that drone
for (unsigned j = 0; j < actions[i].size(); j++) {
if (!actions[i][j]->IsCalculated()) {
double thisStart = actions[i][j]->GetStartTime();
double thisEnd = actions[i][j]->GetEndTime();
if (j == 0) {
MotionAction *next = static_cast<MotionAction *>(actions[i][j + 1]);
auto endState = next->GetPathState(next->GetStartTime());
delete actions[i][j];
actions[i][j] = new MotionAction(i,
PolynomialTrajectory::compute(
{homes[i]},
thisStart,
{endState.position, endState.velocity,
endState.acceleration},
thisEnd
),
ActionTypes::Transition
);
} else if (j == (actions[i].size() - 1)) {
//TODO: Handle the case of the last action being a transition, where our ending velocity and acceleration are 0 and destination is home.
} else {
// Calculate previous and next motion to generate what's needed for the transition
MotionAction *prev = static_cast<MotionAction *>(actions[i][j - 1]);
MotionAction *next = static_cast<MotionAction *>(actions[i][j + 1]);
// Get states from the previous and next state that were found
auto startState = prev->GetPathState(prev->GetEndTime());
auto endState = next->GetPathState(next->GetStartTime());
// Cleanup object and replace with a new MotionAction
delete actions[i][j];
actions[i][j] = new MotionAction(i, PolynomialTrajectory::compute(
{startState.position, startState.velocity, startState.acceleration},
thisStart,
{endState.position, endState.velocity, endState.acceleration},
thisEnd
),
ActionTypes::Transition
);
}
}
}
}
}
// TODO: rename since it parses all actions at given timeslot
double Jocs::parseAction(const nlohmann::json::reference data, double lastTime){
auto actionsArray = data[ACTION_ROOT_KEY];
assert(actionsArray.is_array());
double startTime = data[ACTION_TIME_KEY];
double endTime = 0.0;
for(unsigned i = 0; i < actionsArray.size(); i++) {
auto actionsArrayElement = actionsArray[i];
double duration = actionsArrayElement[DURATION_KEY];
unsigned type = convertToActionType(actionsArrayElement[ACTION_TYPE_KEY]);
assert(actionsArrayElement[DRONE_ARRAY_KEY].is_array());
auto drones = actionsArrayElement[DRONE_ARRAY_KEY];
double conversionFactor = needConvertToMeters ? FEET_TO_METERS : 1.0;
endTime += lastTime + startTime + duration;
assert(drones.is_array());
for (unsigned j = 0; j < drones.size(); j++) {
unsigned drone = drones[j][ID_KEY];
Point startOffset(drones[j][DRONE_START_OFF_KEY][0],drones[j][DRONE_START_OFF_KEY][1],drones[j][DRONE_START_OFF_KEY][2]);
Point endOffset(drones[j][DRONE_END_OFF_KEY][0],drones[j][DRONE_END_OFF_KEY][1],drones[j][DRONE_END_OFF_KEY][2]);
startOffset*=conversionFactor;
endOffset*=conversionFactor;
switch (type) {
case ActionTypes::Transition: {
// Actual calculation will be processed after this loop
actions[drone].push_back(new EmptyAction(drone, lastTime + startTime, lastTime + startTime + duration));
break;
}
case ActionTypes::Line: {
Point start(
actionsArrayElement[ACTION_DATA_KEY][STARTPOS_KEY][0],
actionsArrayElement[ACTION_DATA_KEY][STARTPOS_KEY][1],
actionsArrayElement[ACTION_DATA_KEY][STARTPOS_KEY][2]);
start*=conversionFactor;
Point end(
actionsArrayElement[ACTION_DATA_KEY][ENDPOS_KEY][0],
actionsArrayElement[ACTION_DATA_KEY][ENDPOS_KEY][1],
actionsArrayElement[ACTION_DATA_KEY][ENDPOS_KEY][2]);
end*=conversionFactor;
actions[drone].push_back(new MotionAction(
drone, new LinearTrajectory(start + startOffset, lastTime + startTime, end + endOffset, lastTime + startTime + duration), ActionTypes::Line));
break;
}
case ActionTypes::Circle: {
Point origin(
actionsArrayElement[ACTION_DATA_KEY][CIRCLE_ORIGIN_KEY][0],
actionsArrayElement[ACTION_DATA_KEY][CIRCLE_ORIGIN_KEY][1],
actionsArrayElement[ACTION_DATA_KEY][CIRCLE_ORIGIN_KEY][2]);
origin*=conversionFactor;
double radius = actionsArrayElement[ACTION_DATA_KEY][CIRCLE_RADIUS_KEY];
double theta1 = actionsArrayElement[ACTION_DATA_KEY][CIRCLE_THETA1_KEY];
radius*=conversionFactor;
double theta2 = actionsArrayElement[ACTION_DATA_KEY][CIRCLE_THETA2_KEY];
if(needConvertToRadians) {
theta1 = theta1 * DEGREES_TO_RADIANS;
theta2 = theta2 * DEGREES_TO_RADIANS;
}
// TODO: use separate offset key for circle and hover
actions[drone].push_back(new MotionAction(
drone,
new CircleTrajectory(origin + startOffset, radius, theta1, lastTime+startTime, theta2, lastTime + startTime + duration),
ActionTypes::Circle
));
break;
}
case ActionTypes::Hover:{
Point hoverPoint(
actionsArrayElement[ACTION_DATA_KEY][HOVER_KEY][0],
actionsArrayElement[ACTION_DATA_KEY][HOVER_KEY][1],
actionsArrayElement[ACTION_DATA_KEY][HOVER_KEY][2]
);
hoverPoint*=conversionFactor;
// TODO: use separate offset key for circle and hover
actions[drone].push_back(new MotionAction(
drone,
new LinearTrajectory(hoverPoint + startOffset, lastTime + startTime, hoverPoint + endOffset, lastTime + startTime + duration),
ActionTypes::Hover
));
break;
}
default: {
break;
}
}
}
}
return endTime;
}
ActionTypes Jocs::convertToActionType(const std::string& data){
if(data == "transition")
return ActionTypes::Transition;
else if (data == "line")
return ActionTypes::Line;
else if (data == "circle")
return ActionTypes::Circle;
else if (data == "hover")
return ActionTypes::Hover;
return ActionTypes::None;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007 MIPS Technologies, 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 the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Korey Sewell
*
*/
#include "cpu/inorder/resources/graduation_unit.hh"
#include "debug/InOrderGraduation.hh"
using namespace ThePipeline;
GraduationUnit::GraduationUnit(std::string res_name, int res_id, int res_width,
int res_latency, InOrderCPU *_cpu,
ThePipeline::Params *params)
: Resource(res_name, res_id, res_width, res_latency, _cpu),
lastNonSpecTick(0)
{
for (ThreadID tid = 0; tid < ThePipeline::MaxThreads; tid++) {
nonSpecInstActive[tid] = &cpu->nonSpecInstActive[tid];
nonSpecSeqNum[tid] = &cpu->nonSpecSeqNum[tid];
}
}
void
GraduationUnit::execute(int slot_num)
{
ResourceRequest* grad_req = reqs[slot_num];
DynInstPtr inst = reqs[slot_num]->inst;
ThreadID tid = inst->readTid();
int stage_num = inst->curSkedEntry->stageNum;
switch (grad_req->cmd)
{
case GraduateInst:
{
if (lastNonSpecTick == curTick()) {
DPRINTF(InOrderGraduation, "Unable to graduate [sn:%i]. "
"Only 1 nonspec inst. per cycle can graduate.\n");
grad_req->done(false);
return;
}
// Handle Any Faults Before Graduating Instruction
if (inst->fault != NoFault) {
DPRINTF(Fault, "[sn:%i]: fault %s found for %s\n",
inst->seqNum, inst->fault->name(),
inst->instName());
inst->setSquashInfo(stage_num);
setupSquash(inst, stage_num, tid);
cpu->trapContext(inst->fault, tid, inst);
grad_req->done(false);
return;
}
DPRINTF(InOrderGraduation,
"[tid:%i]:[sn:%i]: Graduating instruction %s.\n",
tid, inst->seqNum, inst->instName());
// Release Non-Speculative "Block" on instructions that could not
// execute because there was a non-speculative inst. active.
// @TODO: Fix this functionality. Probably too conservative.
if (inst->isNonSpeculative()) {
*nonSpecInstActive[tid] = false;
DPRINTF(InOrderGraduation,
"[tid:%i] Non-speculative inst [sn:%i] graduated\n",
tid, inst->seqNum);
lastNonSpecTick = curTick();
}
if (inst->traceData) {
inst->traceData->setStageCycle(stage_num, curTick());
}
// Tell CPU that instruction is finished processing
cpu->instDone(inst, tid);
grad_req->done();
}
break;
default:
fatal("Unrecognized command to %s", resName);
}
}
<commit_msg>inorder: optionally track faulting instructions<commit_after>/*
* Copyright (c) 2007 MIPS Technologies, 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 the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Korey Sewell
*
*/
#include "cpu/inorder/resources/graduation_unit.hh"
#include "debug/InOrderGraduation.hh"
using namespace ThePipeline;
GraduationUnit::GraduationUnit(std::string res_name, int res_id, int res_width,
int res_latency, InOrderCPU *_cpu,
ThePipeline::Params *params)
: Resource(res_name, res_id, res_width, res_latency, _cpu),
lastNonSpecTick(0)
{
for (ThreadID tid = 0; tid < ThePipeline::MaxThreads; tid++) {
nonSpecInstActive[tid] = &cpu->nonSpecInstActive[tid];
nonSpecSeqNum[tid] = &cpu->nonSpecSeqNum[tid];
}
}
void
GraduationUnit::execute(int slot_num)
{
ResourceRequest* grad_req = reqs[slot_num];
DynInstPtr inst = reqs[slot_num]->inst;
ThreadID tid = inst->readTid();
int stage_num = inst->curSkedEntry->stageNum;
switch (grad_req->cmd)
{
case GraduateInst:
{
if (lastNonSpecTick == curTick()) {
DPRINTF(InOrderGraduation, "Unable to graduate [sn:%i]. "
"Only 1 nonspec inst. per cycle can graduate.\n");
grad_req->done(false);
return;
}
// Handle Any Faults Before Graduating Instruction
if (inst->fault != NoFault) {
DPRINTF(Fault, "[sn:%i]: fault %s found for %s\n",
inst->seqNum, inst->fault->name(),
inst->instName());
inst->setSquashInfo(stage_num);
setupSquash(inst, stage_num, tid);
if (inst->traceData && DTRACE(ExecFaulting)) {
inst->traceData->setStageCycle(stage_num, curTick());
inst->traceData->setFetchSeq(inst->seqNum);
inst->traceData->dump();
delete inst->traceData;
inst->traceData = NULL;
}
cpu->trapContext(inst->fault, tid, inst);
grad_req->done(false);
return;
}
DPRINTF(InOrderGraduation,
"[tid:%i]:[sn:%i]: Graduating instruction %s.\n",
tid, inst->seqNum, inst->instName());
// Release Non-Speculative "Block" on instructions that could not
// execute because there was a non-speculative inst. active.
// @TODO: Fix this functionality. Probably too conservative.
if (inst->isNonSpeculative()) {
*nonSpecInstActive[tid] = false;
DPRINTF(InOrderGraduation,
"[tid:%i] Non-speculative inst [sn:%i] graduated\n",
tid, inst->seqNum);
lastNonSpecTick = curTick();
}
if (inst->traceData) {
inst->traceData->setStageCycle(stage_num, curTick());
}
// Tell CPU that instruction is finished processing
cpu->instDone(inst, tid);
grad_req->done();
}
break;
default:
fatal("Unrecognized command to %s", resName);
}
}
<|endoftext|>
|
<commit_before>/*
* PresentationLog.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "PresentationLog.hpp"
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <core/Error.hpp>
#include <core/DateTime.hpp>
#include <core/StringUtils.hpp>
#include <core/SafeConvert.hpp>
#include <core/FileSerializer.hpp>
#include <r/RSexp.hpp>
#include <r/RExec.hpp>
#include <r/session/RSessionUtils.hpp>
#include "PresentationState.hpp"
using namespace core;
namespace session {
namespace modules {
namespace presentation {
Log& log()
{
static Log instance;
return instance;
}
Error Log::initialize()
{
// connect to console events
using namespace boost;
using namespace session::module_context;
events().onConsolePrompt.connect(boost::bind(&Log::onConsolePrompt,
this, _1));
events().onConsoleInput.connect(boost::bind(&Log::onConsoleInput,
this, _1));
events().onConsoleOutput.connect(boost::bind(&Log::onConsoleOutput,
this, _1, _2));
return Success();
}
void Log::recordCommand(int slideIndex, const Command& command)
{
if (command.name() == "console-input")
{
std::string params = boost::algorithm::trim_copy(command.params());
slideDeckInputCommands_[slideIndex].insert(params);
}
else if (command.name() == "help-topic")
{
slideHelpTopics_[slideIndex] = command.params();
}
else if (command.name() == "help-doc")
{
slideHelpDocs_[slideIndex] = command.params();
}
}
void Log::onSlideDeckChanged(const SlideDeck& slideDeck)
{
slideDeckInputCommands_.clear();
slideTypes_.clear();
slideHelpTopics_ = std::vector<std::string>(slideDeck.slides().size());
slideHelpDocs_ = std::vector<std::string>(slideDeck.slides().size());
const std::vector<Slide>& slides = slideDeck.slides();
for (std::size_t i = 0; i<slides.size(); i++)
{
slideTypes_.push_back(slides[i].type());
const std::vector<Command>& commands = slides[i].commands();
BOOST_FOREACH(const Command& command, commands)
{
recordCommand(i, command);
}
const std::vector<AtCommand>& atCommands = slides[i].atCommands();
BOOST_FOREACH(const AtCommand& atCommand, atCommands)
{
recordCommand(i, atCommand.command());
}
}
}
void Log::onSlideIndexChanged(int index)
{
currentSlideIndex_ = index;
append(NavigationEntry,
presentation::state::filePath(),
currentSlideIndex_,
currentSlideType(),
currentSlideHelpTopic(),
currentSlideHelpDoc(),
"",
"");
}
void Log::onConsolePrompt(const std::string& prompt)
{
if (!presentation::state::isActive())
return;
// ignore if this isn't the default prompt
if (!r::session::utils::isDefaultPrompt(prompt))
return;
if (!consoleInputBuffer_.empty())
{
std::string input = boost::algorithm::trim_copy(
boost::algorithm::join(consoleInputBuffer_, "\n"));
std::string errors = boost::algorithm::trim_copy(
boost::algorithm::join(errorOutputBuffer_, "\n"));
// check to see if this command was one of the ones instrumented
// by the current slide
if (slideDeckInputCommands_[currentSlideIndex_].count(input) == 0)
{
append(InputEntry,
presentation::state::filePath(),
currentSlideIndex_,
currentSlideType(),
currentSlideHelpTopic(),
currentSlideHelpDoc(),
input,
errors);
}
}
consoleInputBuffer_.clear();
errorOutputBuffer_.clear();
}
void Log::onConsoleInput(const std::string& text)
{
if (!presentation::state::isActive())
return;
consoleInputBuffer_.push_back(text);
}
void Log::onConsoleOutput(module_context::ConsoleOutputType type,
const std::string& output)
{
if (!presentation::state::isActive())
return;
if (type == module_context::ConsoleOutputError)
errorOutputBuffer_.push_back(output);
}
namespace {
std::string csvString(std::string str)
{
boost::algorithm::replace_all(str, "\n", "\\n");
boost::algorithm::replace_all(str, "\"", "\"\"");
return "\"" + str + "\"";
}
std::string timestamp()
{
// generate timestamp
using namespace boost::posix_time;
ptime time = microsec_clock::universal_time();
std::string dateTime = date_time::format(time, "%Y-%m-%dT%H:%M:%SZ");
return dateTime;
}
Error ensureTargetFile(const std::string& filename,
const std::string& header,
FilePath* pTargetFile)
{
using namespace module_context;
FilePath presDir = userScratchPath().childPath("presentation");
Error error = presDir.ensureDirectory();
if (error)
return error;
*pTargetFile = presDir.childPath(filename);
if (!pTargetFile->exists())
{
Error error = core::writeStringToFile(*pTargetFile, header + "\n");
if (error)
return error;
}
return Success();
}
} // anonymous namespace
std::string Log::currentSlideType() const
{
if (currentSlideIndex_ < slideTypes_.size())
return slideTypes_[currentSlideIndex_];
else
return "default";
}
std::string Log::currentSlideHelpTopic() const
{
if (currentSlideIndex_ < slideHelpTopics_.size())
return slideHelpTopics_[currentSlideIndex_];
else
return "";
}
std::string Log::currentSlideHelpDoc() const
{
if (currentSlideIndex_ < slideHelpDocs_.size())
return slideHelpDocs_[currentSlideIndex_];
else
return "";
}
void Log::append(EntryType type,
const FilePath& presPath,
int slideIndex,
const std::string& slideType,
const std::string& helpTopic,
const std::string& helpDoc,
const std::string& input,
const std::string& errors)
{
// ensure target file
FilePath logFilePath;
Error error = ensureTargetFile(
"presentation-log-v1.csv",
"type, timestamp, presentation, slide, slide-type, help-topic, "
"help-doc, input, errors\n",
&logFilePath);
if (error)
{
LOG_ERROR(error);
return;
}
// generate entry
std::vector<std::string> fields;
fields.push_back((type == NavigationEntry) ? "Navigation" : "Input");
fields.push_back(timestamp());
fields.push_back(csvString(module_context::createAliasedPath(presPath)));
fields.push_back(safe_convert::numberToString(slideIndex));
fields.push_back(slideType);
fields.push_back(csvString(helpTopic));
fields.push_back(csvString(helpDoc));
fields.push_back(csvString(input));
fields.push_back(csvString(errors));
std::string entry = boost::algorithm::join(fields, ",");
// append entry
error = core::appendToFile(logFilePath, entry + "\n");
if (error)
LOG_ERROR(error);
}
void Log::recordFeedback(const std::string& feedback)
{
// ensure target file
FilePath feedbackFilePath;
Error error = ensureTargetFile("feedback-v1.csv",
"timestamp, presentation, slide, feedback\n",
&feedbackFilePath);
if (error)
{
LOG_ERROR(error);
return;
}
// generate entry
std::vector<std::string> fields;
fields.push_back(timestamp());
fields.push_back(csvString(module_context::createAliasedPath(
presentation::state::filePath())));
fields.push_back(safe_convert::numberToString(currentSlideIndex_));
fields.push_back(csvString(feedback));
std::string entry = boost::algorithm::join(fields, ",");
// append entry
error = core::appendToFile(feedbackFilePath, entry + "\n");
if (error)
LOG_ERROR(error);
}
} // namespace presentation
} // namespace modules
} // namesapce session
<commit_msg>use namespace alias for boost::algorithm<commit_after>/*
* PresentationLog.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "PresentationLog.hpp"
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <core/Error.hpp>
#include <core/DateTime.hpp>
#include <core/StringUtils.hpp>
#include <core/SafeConvert.hpp>
#include <core/FileSerializer.hpp>
#include <r/RSexp.hpp>
#include <r/RExec.hpp>
#include <r/session/RSessionUtils.hpp>
#include "PresentationState.hpp"
using namespace core;
namespace session {
namespace modules {
namespace presentation {
Log& log()
{
static Log instance;
return instance;
}
Error Log::initialize()
{
// connect to console events
using namespace boost;
using namespace session::module_context;
events().onConsolePrompt.connect(boost::bind(&Log::onConsolePrompt,
this, _1));
events().onConsoleInput.connect(boost::bind(&Log::onConsoleInput,
this, _1));
events().onConsoleOutput.connect(boost::bind(&Log::onConsoleOutput,
this, _1, _2));
return Success();
}
void Log::recordCommand(int slideIndex, const Command& command)
{
if (command.name() == "console-input")
{
std::string params = boost::algorithm::trim_copy(command.params());
slideDeckInputCommands_[slideIndex].insert(params);
}
else if (command.name() == "help-topic")
{
slideHelpTopics_[slideIndex] = command.params();
}
else if (command.name() == "help-doc")
{
slideHelpDocs_[slideIndex] = command.params();
}
}
void Log::onSlideDeckChanged(const SlideDeck& slideDeck)
{
slideDeckInputCommands_.clear();
slideTypes_.clear();
slideHelpTopics_ = std::vector<std::string>(slideDeck.slides().size());
slideHelpDocs_ = std::vector<std::string>(slideDeck.slides().size());
const std::vector<Slide>& slides = slideDeck.slides();
for (std::size_t i = 0; i<slides.size(); i++)
{
slideTypes_.push_back(slides[i].type());
const std::vector<Command>& commands = slides[i].commands();
BOOST_FOREACH(const Command& command, commands)
{
recordCommand(i, command);
}
const std::vector<AtCommand>& atCommands = slides[i].atCommands();
BOOST_FOREACH(const AtCommand& atCommand, atCommands)
{
recordCommand(i, atCommand.command());
}
}
}
void Log::onSlideIndexChanged(int index)
{
currentSlideIndex_ = index;
append(NavigationEntry,
presentation::state::filePath(),
currentSlideIndex_,
currentSlideType(),
currentSlideHelpTopic(),
currentSlideHelpDoc(),
"",
"");
}
void Log::onConsolePrompt(const std::string& prompt)
{
if (!presentation::state::isActive())
return;
// ignore if this isn't the default prompt
if (!r::session::utils::isDefaultPrompt(prompt))
return;
if (!consoleInputBuffer_.empty())
{
using namespace boost::algorithm;
std::string input = trim_copy(join(consoleInputBuffer_, "\n"));
std::string errors = trim_copy(join(errorOutputBuffer_, "\n"));
// check to see if this command was one of the ones instrumented
// by the current slide
if (slideDeckInputCommands_[currentSlideIndex_].count(input) == 0)
{
append(InputEntry,
presentation::state::filePath(),
currentSlideIndex_,
currentSlideType(),
currentSlideHelpTopic(),
currentSlideHelpDoc(),
input,
errors);
}
}
consoleInputBuffer_.clear();
errorOutputBuffer_.clear();
}
void Log::onConsoleInput(const std::string& text)
{
if (!presentation::state::isActive())
return;
consoleInputBuffer_.push_back(text);
}
void Log::onConsoleOutput(module_context::ConsoleOutputType type,
const std::string& output)
{
if (!presentation::state::isActive())
return;
if (type == module_context::ConsoleOutputError)
errorOutputBuffer_.push_back(output);
}
namespace {
std::string csvString(std::string str)
{
boost::algorithm::replace_all(str, "\n", "\\n");
boost::algorithm::replace_all(str, "\"", "\"\"");
return "\"" + str + "\"";
}
std::string timestamp()
{
// generate timestamp
using namespace boost::posix_time;
ptime time = microsec_clock::universal_time();
std::string dateTime = date_time::format(time, "%Y-%m-%dT%H:%M:%SZ");
return dateTime;
}
Error ensureTargetFile(const std::string& filename,
const std::string& header,
FilePath* pTargetFile)
{
using namespace module_context;
FilePath presDir = userScratchPath().childPath("presentation");
Error error = presDir.ensureDirectory();
if (error)
return error;
*pTargetFile = presDir.childPath(filename);
if (!pTargetFile->exists())
{
Error error = core::writeStringToFile(*pTargetFile, header + "\n");
if (error)
return error;
}
return Success();
}
} // anonymous namespace
std::string Log::currentSlideType() const
{
if (currentSlideIndex_ < slideTypes_.size())
return slideTypes_[currentSlideIndex_];
else
return "default";
}
std::string Log::currentSlideHelpTopic() const
{
if (currentSlideIndex_ < slideHelpTopics_.size())
return slideHelpTopics_[currentSlideIndex_];
else
return "";
}
std::string Log::currentSlideHelpDoc() const
{
if (currentSlideIndex_ < slideHelpDocs_.size())
return slideHelpDocs_[currentSlideIndex_];
else
return "";
}
void Log::append(EntryType type,
const FilePath& presPath,
int slideIndex,
const std::string& slideType,
const std::string& helpTopic,
const std::string& helpDoc,
const std::string& input,
const std::string& errors)
{
// ensure target file
FilePath logFilePath;
Error error = ensureTargetFile(
"presentation-log-v1.csv",
"type, timestamp, presentation, slide, slide-type, help-topic, "
"help-doc, input, errors\n",
&logFilePath);
if (error)
{
LOG_ERROR(error);
return;
}
// generate entry
std::vector<std::string> fields;
fields.push_back((type == NavigationEntry) ? "Navigation" : "Input");
fields.push_back(timestamp());
fields.push_back(csvString(module_context::createAliasedPath(presPath)));
fields.push_back(safe_convert::numberToString(slideIndex));
fields.push_back(slideType);
fields.push_back(csvString(helpTopic));
fields.push_back(csvString(helpDoc));
fields.push_back(csvString(input));
fields.push_back(csvString(errors));
std::string entry = boost::algorithm::join(fields, ",");
// append entry
error = core::appendToFile(logFilePath, entry + "\n");
if (error)
LOG_ERROR(error);
}
void Log::recordFeedback(const std::string& feedback)
{
// ensure target file
FilePath feedbackFilePath;
Error error = ensureTargetFile("feedback-v1.csv",
"timestamp, presentation, slide, feedback\n",
&feedbackFilePath);
if (error)
{
LOG_ERROR(error);
return;
}
// generate entry
std::vector<std::string> fields;
fields.push_back(timestamp());
fields.push_back(csvString(module_context::createAliasedPath(
presentation::state::filePath())));
fields.push_back(safe_convert::numberToString(currentSlideIndex_));
fields.push_back(csvString(feedback));
std::string entry = boost::algorithm::join(fields, ",");
// append entry
error = core::appendToFile(feedbackFilePath, entry + "\n");
if (error)
LOG_ERROR(error);
}
} // namespace presentation
} // namespace modules
} // namesapce session
<|endoftext|>
|
<commit_before>//===-- EmitFunctions.cpp - interface to insert instrumentation --*- C++ -*--=//
//
// This inserts a global constant table with function pointers all along
//
//===----------------------------------------------------------------------===//
//#include "llvm/Transforms/Instrumentation/ProfilePaths.h"
//#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
#include "llvm/Support/CFG.h"
#include "llvm/Transforms/Instrumentation/EmitFunctions.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/iMemory.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"
#include <iostream>
#include <fstream>
using std::vector;
struct EmitFunctionTable : public Pass {
const char *getPassName() const { return "EmitFunctionTablePass"; }
bool run(Module &M);
};
// Create a new pass to add function table
//
Pass *createEmitFunctionTablePass() {
return new EmitFunctionTable();
}
//Per Module pass for inserting function table
bool EmitFunctionTable::run(Module &M){
vector<const Type*> vType;
vector<Constant *> vConsts;
for(Module::iterator MI = M.begin(), ME = M.end(); MI!=ME; ++MI){
Function *F = MI;
if(F->size()<=1) continue;
ConstantPointerRef *cpref = ConstantPointerRef::get(F);
vType.push_back(MI->getType());
vConsts.push_back(cpref);
}
StructType *sttype = StructType::get(vType);
ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts);
GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true, true,
cstruct, "llvmFunctionTable");
M.getGlobalList().push_back(gb);
return true; // Always modifies function
}
<commit_msg>* Cleanup pass * The global variable cannot be internal or else we cannot use it! * Always add a function to the table, even if it only has a single basic block.<commit_after>//===-- EmitFunctions.cpp - interface to insert instrumentation --*- C++ -*--=//
//
// This inserts a global constant table with function pointers all along
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Instrumentation/EmitFunctions.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"
using std::vector;
struct EmitFunctionTable : public Pass {
const char *getPassName() const { return "EmitFunctionTablePass"; }
bool run(Module &M);
};
// Create a new pass to add function table
//
Pass *createEmitFunctionTablePass() {
return new EmitFunctionTable();
}
// Per Module pass for inserting function table
bool EmitFunctionTable::run(Module &M){
vector<const Type*> vType;
vector<Constant *> vConsts;
for(Module::iterator MI = M.begin(), ME = M.end(); MI!=ME; ++MI)
if (!MI->isExternal()) {
ConstantPointerRef *CP = ConstantPointerRef::get(MI);
vType.push_back(MI->getType());
vConsts.push_back(CP);
}
StructType *sttype = StructType::get(vType);
ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts);
GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true, false,
cstruct, "llvmFunctionTable");
M.getGlobalList().push_back(gb);
return true; // Always modifies program
}
<|endoftext|>
|
<commit_before><commit_msg>Check event status before notify<commit_after><|endoftext|>
|
<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2020 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef __YLIKUUTIO_ONTOLOGY_ENTITY_FACTORY_HPP_INCLUDED
#define __YLIKUUTIO_ONTOLOGY_ENTITY_FACTORY_HPP_INCLUDED
#include "variable_struct.hpp"
#include "world_struct.hpp"
#include "scene_struct.hpp"
#include "shader_struct.hpp"
#include "material_struct.hpp"
#include "species_struct.hpp"
#include "object_struct.hpp"
#include "symbiosis_struct.hpp"
#include "holobiont_struct.hpp"
#include "vector_font_struct.hpp"
#include "text_struct.hpp"
#include "text3D_struct.hpp"
#include "console_struct.hpp"
#include "font_struct.hpp"
#include "lisp_function_struct.hpp"
#include "camera_struct.hpp"
#include "compute_task_struct.hpp"
#include "brain_struct.hpp"
// Include standard headers
#include <cstddef> // std::size_t
#include <memory> // std::make_shared, std::shared_ptr
#include <string> // std::string
namespace yli::ontology
{
class Entity;
class Variable;
class Universe;
class World;
class Scene;
class Shader;
class Material;
class Species;
class Object;
class VectorFont;
class Text3D;
class Font2D;
class Console;
class ComputeTask;
class Brain;
class EntityFactory
{
public:
// constructor.
EntityFactory(yli::ontology::Universe* const universe);
EntityFactory(const EntityFactory&) = delete; // Delete copy constructor.
EntityFactory& operator=(const EntityFactory&) = delete; // Delete copy assignment.
// destructor.
~EntityFactory();
yli::ontology::Universe* get_universe() const;
yli::ontology::Entity* create_variable(const yli::ontology::VariableStruct& variable_struct) const;
yli::ontology::Entity* create_world(const yli::ontology::WorldStruct& world_struct) const;
yli::ontology::Entity* create_scene(const yli::ontology::SceneStruct& scene_struct) const;
yli::ontology::Entity* create_shader(const yli::ontology::ShaderStruct& shader_struct) const;
yli::ontology::Entity* create_material(const yli::ontology::MaterialStruct& material_struct) const;
yli::ontology::Entity* create_species(const yli::ontology::SpeciesStruct& species_struct) const;
yli::ontology::Entity* create_object(const yli::ontology::ObjectStruct& object_struct) const;
yli::ontology::Entity* create_symbiosis(const yli::ontology::SymbiosisStruct& symbiosis_struct) const;
yli::ontology::Entity* create_holobiont(const yli::ontology::HolobiontStruct& object_struct) const;
yli::ontology::Entity* create_vector_font(const yli::ontology::VectorFontStruct& vector_font_struct) const;
yli::ontology::Entity* create_text2d(const yli::ontology::TextStruct& text_struct) const;
yli::ontology::Entity* create_text3d(const yli::ontology::Text3DStruct& text3D_struct) const;
yli::ontology::Entity* create_font2d(const yli::ontology::FontStruct& font_struct) const;
yli::ontology::Entity* create_console(const yli::ontology::ConsoleStruct& console_struct) const;
yli::ontology::Entity* create_lisp_function(const yli::ontology::LispFunctionStruct& lisp_function_struct) const;
yli::ontology::Entity* create_camera(const yli::ontology::CameraStruct& camera_struct) const;
yli::ontology::Entity* create_compute_task(const yli::ontology::ComputeTaskStruct& compute_task_struct) const;
yli::ontology::Entity* create_brain(const yli::ontology::BrainStruct& brain_struct) const;
yli::ontology::Entity* create_callback_engine_entity() const;
private:
yli::ontology::Universe* universe;
};
}
#endif
<commit_msg>Replace `#include` lines with forward declarations.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2020 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef __YLIKUUTIO_ONTOLOGY_ENTITY_FACTORY_HPP_INCLUDED
#define __YLIKUUTIO_ONTOLOGY_ENTITY_FACTORY_HPP_INCLUDED
// Include standard headers
#include <cstddef> // std::size_t
#include <memory> // std::make_shared, std::shared_ptr
#include <string> // std::string
namespace yli::ontology
{
class Entity;
class Variable;
class Universe;
class World;
class Scene;
class Shader;
class Material;
class Species;
class Object;
class VectorFont;
class Text3D;
class Font2D;
class Console;
class ComputeTask;
class Brain;
struct VariableStruct;
struct WorldStruct;
struct SceneStruct;
struct ShaderStruct;
struct MaterialStruct;
struct SpeciesStruct;
struct ObjectStruct;
struct SymbiosisStruct;
struct HolobiontStruct;
struct VectorFontStruct;
struct FontStruct;
struct TextStruct;
struct Text3DStruct;
struct ConsoleStruct;
struct LispFunctionStruct;
struct CameraStruct;
struct ComputeTaskStruct;
struct BrainStruct;
class EntityFactory
{
public:
// constructor.
EntityFactory(yli::ontology::Universe* const universe);
EntityFactory(const EntityFactory&) = delete; // Delete copy constructor.
EntityFactory& operator=(const EntityFactory&) = delete; // Delete copy assignment.
// destructor.
~EntityFactory();
yli::ontology::Universe* get_universe() const;
yli::ontology::Entity* create_variable(const yli::ontology::VariableStruct& variable_struct) const;
yli::ontology::Entity* create_world(const yli::ontology::WorldStruct& world_struct) const;
yli::ontology::Entity* create_scene(const yli::ontology::SceneStruct& scene_struct) const;
yli::ontology::Entity* create_shader(const yli::ontology::ShaderStruct& shader_struct) const;
yli::ontology::Entity* create_material(const yli::ontology::MaterialStruct& material_struct) const;
yli::ontology::Entity* create_species(const yli::ontology::SpeciesStruct& species_struct) const;
yli::ontology::Entity* create_object(const yli::ontology::ObjectStruct& object_struct) const;
yli::ontology::Entity* create_symbiosis(const yli::ontology::SymbiosisStruct& symbiosis_struct) const;
yli::ontology::Entity* create_holobiont(const yli::ontology::HolobiontStruct& object_struct) const;
yli::ontology::Entity* create_vector_font(const yli::ontology::VectorFontStruct& vector_font_struct) const;
yli::ontology::Entity* create_text2d(const yli::ontology::TextStruct& text_struct) const;
yli::ontology::Entity* create_text3d(const yli::ontology::Text3DStruct& text3D_struct) const;
yli::ontology::Entity* create_font2d(const yli::ontology::FontStruct& font_struct) const;
yli::ontology::Entity* create_console(const yli::ontology::ConsoleStruct& console_struct) const;
yli::ontology::Entity* create_lisp_function(const yli::ontology::LispFunctionStruct& lisp_function_struct) const;
yli::ontology::Entity* create_camera(const yli::ontology::CameraStruct& camera_struct) const;
yli::ontology::Entity* create_compute_task(const yli::ontology::ComputeTaskStruct& compute_task_struct) const;
yli::ontology::Entity* create_brain(const yli::ontology::BrainStruct& brain_struct) const;
yli::ontology::Entity* create_callback_engine_entity() const;
private:
yli::ontology::Universe* universe;
};
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>Bugfix x 3: null terminator of `char` array is taken into count.<commit_after><|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
Copyright (c) 2010 Nigel Atkinson
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 <scriptingsystem.h>
#include <OgreLogManager.h>
#include <inputeventdata.h>
#include <windoweventdata.h>
#include <animationeventdata.h>
#include <luaresource.h>
#include <gameentity.h>
#include <version.h>
#include <LuaBridge.h>
void bindOgre( lua_State* L ); // From ogrebind.cpp
/*
void bindAnimation( lua_State* L ); // From animationbind.cpp
void bindNavigationMesh( lua_State* L); // From navmeshbind.cpp
*/
void bindGorilla( lua_State *L ); // From gorillabind.cpp
template<class D, class B>
D* downcast( B* ptr )
{
return dynamic_cast<D*>( ptr );
}
int ScriptingSystem::GUID = 0;
void queueEventThunk( Event& event, lua_State *L )
{
lua_pushlightuserdata( L, (void *)&ScriptingSystem::GUID );
lua_gettable( L, LUA_REGISTRYINDEX );
ScriptingSystem* scriptingSystem = static_cast<ScriptingSystem*>(lua_touserdata( L, -1 ));
if( scriptingSystem )
{
scriptingSystem->queueEvent( EventPtr( new Event(event) ) );
}
else
{
Ogre::LogManager::getSingleton().stream() << "Error queuing event from Lua; could not retrieve scripting system instance";
}
}
int luaLibraryLoader( lua_State *L )
{
if( ! lua_isstring( L, 1 ) )
{
luaL_error( L, "luaLibraryLoader: Expected string for first parameter" );
}
std::string libraryFile = lua_tostring( L, 1 );
// In order to be compatible with the normal Lua file loader,
// translate '.' to the file system seperator character.
// In this case (An ogre resource) '/'
while( libraryFile.find('.') != std::string::npos )
libraryFile.replace( libraryFile.find('.'), 1, "/" );
libraryFile += ".lua";
if( ! Ogre::ResourceGroupManager::getSingleton().resourceExistsInAnyGroup( libraryFile ) )
{
// Could not find the file.
std::string errMessage = "\n no file '" + libraryFile + "' found in Ogre resource archives.";
lua_pushstring( L, errMessage.c_str() );
}
else
{
LuaResourcePtr library = LuaResourceManager::getSingleton().load( libraryFile, "General" );
if( luaL_loadbuffer( L, library->getScriptSource().c_str(), library->calculateSize(), libraryFile.c_str() ) )
{
luaL_error( L, "Error loading library '%s' from resource archive.\n%s", libraryFile.c_str(), lua_tostring( L, -1 ) );
}
}
return 1;
}
void installLibraryLoader( lua_State *L )
{
// Insert the c++ func 'luaLibraryLoader' into package.loaders.
// Inserted at the start of the table in order to take precedence.
lua_getglobal( L, "table" );
lua_getfield( L, -1, "insert" );
lua_remove( L, -2 ); // table
lua_getglobal( L, "package" );
lua_getfield( L, -1, "searchers" );
lua_remove( L, -2 ); // package
lua_pushnumber( L, 1 ); // index where to insert into loaders table
lua_pushcfunction( L, luaLibraryLoader );
if( lua_pcall( L, 3, 0, 0 ) )
Ogre::LogManager::getSingleton().stream() << lua_tostring( L, 1);
}
void getClassMembers( lua_State* L, luabridge::LuaRef ret )
{
// List keys where they don't start with underscore.
lua_pushnil( L );
while( lua_next( L, -2 ) )
{
lua_pushvalue( L, -2 ); // Push copy of key.
const char *key = lua_tostring( L, -1 );
if( key )
{
if( key[0] != '_' )
{
ret.append( key );
}
}
lua_pop( L, 2 ); // Key copy and value
}
// List properties
lua_pushstring( L, "__propget" );
lua_rawget( L, -2 );
if( lua_istable( L, -1 ) )
{
lua_pushnil( L );
while( lua_next( L, -2 ) )
{
lua_pushvalue( L, -2 ); // Push copy of key.
const char *key = lua_tostring( L, -1 );
if( key )
{
ret.append( key );
}
lua_pop( L, 2 ); // Key copy and value
}
}
lua_pop( L, 1 ); // __propget table
return;
}
int getClassInfo( lua_State* L )
{
luabridge::LuaRef ret = luabridge::newTable( L );
if( lua_istable( L, 1 ) )
{
// Class Type
lua_getmetatable( L, 1 );
// Static members.
getClassMembers( L, ret );
// Regular members.
lua_pushstring( L, "__class" );
lua_rawget( L, -2 );
if( lua_istable( L, -1 ) )
{
getClassMembers( L, ret );
}
}
else if( lua_isuserdata( L, 1 ) )
{
// Class instance
lua_getmetatable( L, 1 );
getClassMembers( L, ret );
}
// Just return an empty table if not a class.
ret.push( L );
return 1;
}
void ScriptingSystem::shutdown()
{
if( mL )
lua_close( mL );
mL = 0;
}
void ScriptingSystem::initialise()
{
mL = luaL_newstate();
luaL_openlibs( mL );
lua_pushlightuserdata( mL, (void *)&GUID );
lua_pushlightuserdata( mL, this );
lua_settable( mL, LUA_REGISTRYINDEX );
bind();
bindOgre( mL );
/*
bindGameEntityClasses( mL );
bindAnimation( mL );
bindNavigationMesh( mL );
*/
bindGorilla( mL );
using namespace luabridge;
LuaResourcePtr mainlua = LuaResourceManager::getSingleton().load( "main.lua" );
if( luaL_loadbuffer( mL,
mainlua->getScriptSource().c_str(),
mainlua->calculateSize(), "main.lua" ) || lua_pcall( mL, 0, LUA_MULTRET, 0) )
{
Ogre::LogManager::getSingleton().stream() << " ****************************** ";
Ogre::LogManager::getSingleton().stream() << " *** main.lua failed to run ";
Ogre::LogManager::getSingleton().stream() << " *** " << lua_tostring( mL, -1 );
Ogre::LogManager::getSingleton().stream() << " ****************************** ";
}
}
void ScriptingSystem::bind()
{
using namespace luabridge;
installLibraryLoader( mL );
getGlobalNamespace( mL )
.addCFunction( "getClassInfo", &getClassInfo )
.beginNamespace( "Engine" )
.beginClass<Event>( "Event" )
.addConstructor<void (*) (const char*)>()
.addData( "type", &Event::type )
.addData( "data", &Event::data )
.addStaticFunction( "hash", &Event::hash )
.endClass()
.addFunction( "queueEvent", &queueEventThunk )
.beginClass<EventData>( "EventData" )
.endClass()
.deriveClass<InputEventData, EventData>( "InputEventData" )
.addConstructor<void (*) (void)>()
.addStaticFunction( "downcast", &downcast<InputEventData, EventData> )
.addData( "x", &InputEventData::x )
.addData( "y", &InputEventData::y )
.addData( "buttons", &InputEventData::parm )
.addProperty( "text", &InputEventDataBindingHelper::getText, &InputEventDataBindingHelper::setText )
.addProperty( "key", &InputEventDataBindingHelper::getKey, &InputEventDataBindingHelper::setKey )
.endClass()
.deriveClass<WindowEventData, EventData>( "WindowEventData" )
.addStaticFunction( "downcast", &downcast<WindowEventData, EventData> )
.addData( "width", &WindowEventData::width )
.addData( "height", &WindowEventData::height )
.endClass()
/*
.deriveClass<AnimationEventData, EventData>( "AnimationEventData" )
.addData( "animation", &AnimationEventData::animation )
.endClass()
*/
.addFunction( "versionString", versionString )
.endNamespace();
}
bool ScriptingSystem::EventNotification( EventPtr event )
{
luabridge::LuaRef notify = luabridge::getGlobal( mL, "EventNotification");
luabridge::LuaRef ret( mL );
if( notify )
{
try
{
ret = notify( *event );
if( ret == true )
return true;
}
catch( luabridge::LuaException& e )
{
Ogre::LogManager::getSingleton().stream() << e.what();
}
}
return false;
}
bool ScriptingSystem::frameStarted(const Ogre::FrameEvent& evt)
{
luabridge::LuaRef func = luabridge::getGlobal( mL, "FrameStarted" );
try
{
// If the function is not defined, don't worry about it.
if( func )
func( evt.timeSinceLastFrame );
}
catch( luabridge::LuaException& e )
{
Ogre::LogManager::getSingleton().stream() << e.what();
}
return true;
}
bool ScriptingSystem::frameEnded(const Ogre::FrameEvent& evt)
{
luabridge::LuaRef func = luabridge::getGlobal( mL, "FrameEnded" );
try
{
// If the function is not defined, don't worry about it.
if( func )
func( evt.timeSinceLastFrame );
}
catch( luabridge::LuaException& e )
{
Ogre::LogManager::getSingleton().stream() << e.what();
}
// Do a Lua garbage collection.
lua_gc( mL, LUA_GCSTEP, 1 );
return true;
}
<commit_msg>Catch __gc metamethod errors on tables with try catch block<commit_after>/*
-----------------------------------------------------------------------------
Copyright (c) 2010 Nigel Atkinson
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 <scriptingsystem.h>
#include <OgreLogManager.h>
#include <inputeventdata.h>
#include <windoweventdata.h>
#include <animationeventdata.h>
#include <luaresource.h>
#include <gameentity.h>
#include <version.h>
#include <LuaBridge.h>
void bindOgre( lua_State* L ); // From ogrebind.cpp
/*
void bindAnimation( lua_State* L ); // From animationbind.cpp
void bindNavigationMesh( lua_State* L); // From navmeshbind.cpp
*/
void bindGorilla( lua_State *L ); // From gorillabind.cpp
template<class D, class B>
D* downcast( B* ptr )
{
return dynamic_cast<D*>( ptr );
}
int ScriptingSystem::GUID = 0;
void queueEventThunk( Event& event, lua_State *L )
{
lua_pushlightuserdata( L, (void *)&ScriptingSystem::GUID );
lua_gettable( L, LUA_REGISTRYINDEX );
ScriptingSystem* scriptingSystem = static_cast<ScriptingSystem*>(lua_touserdata( L, -1 ));
if( scriptingSystem )
{
scriptingSystem->queueEvent( EventPtr( new Event(event) ) );
}
else
{
Ogre::LogManager::getSingleton().stream() << "Error queuing event from Lua; could not retrieve scripting system instance";
}
}
int luaLibraryLoader( lua_State *L )
{
if( ! lua_isstring( L, 1 ) )
{
luaL_error( L, "luaLibraryLoader: Expected string for first parameter" );
}
std::string libraryFile = lua_tostring( L, 1 );
// In order to be compatible with the normal Lua file loader,
// translate '.' to the file system seperator character.
// In this case (An ogre resource) '/'
while( libraryFile.find('.') != std::string::npos )
libraryFile.replace( libraryFile.find('.'), 1, "/" );
libraryFile += ".lua";
if( ! Ogre::ResourceGroupManager::getSingleton().resourceExistsInAnyGroup( libraryFile ) )
{
// Could not find the file.
std::string errMessage = "\n no file '" + libraryFile + "' found in Ogre resource archives.";
lua_pushstring( L, errMessage.c_str() );
}
else
{
LuaResourcePtr library = LuaResourceManager::getSingleton().load( libraryFile, "General" );
if( luaL_loadbuffer( L, library->getScriptSource().c_str(), library->calculateSize(), libraryFile.c_str() ) )
{
luaL_error( L, "Error loading library '%s' from resource archive.\n%s", libraryFile.c_str(), lua_tostring( L, -1 ) );
}
}
return 1;
}
void installLibraryLoader( lua_State *L )
{
// Insert the c++ func 'luaLibraryLoader' into package.loaders.
// Inserted at the start of the table in order to take precedence.
lua_getglobal( L, "table" );
lua_getfield( L, -1, "insert" );
lua_remove( L, -2 ); // table
lua_getglobal( L, "package" );
lua_getfield( L, -1, "searchers" );
lua_remove( L, -2 ); // package
lua_pushnumber( L, 1 ); // index where to insert into loaders table
lua_pushcfunction( L, luaLibraryLoader );
if( lua_pcall( L, 3, 0, 0 ) )
Ogre::LogManager::getSingleton().stream() << lua_tostring( L, 1);
}
void getClassMembers( lua_State* L, luabridge::LuaRef ret )
{
// List keys where they don't start with underscore.
lua_pushnil( L );
while( lua_next( L, -2 ) )
{
lua_pushvalue( L, -2 ); // Push copy of key.
const char *key = lua_tostring( L, -1 );
if( key )
{
if( key[0] != '_' )
{
ret.append( key );
}
}
lua_pop( L, 2 ); // Key copy and value
}
// List properties
lua_pushstring( L, "__propget" );
lua_rawget( L, -2 );
if( lua_istable( L, -1 ) )
{
lua_pushnil( L );
while( lua_next( L, -2 ) )
{
lua_pushvalue( L, -2 ); // Push copy of key.
const char *key = lua_tostring( L, -1 );
if( key )
{
ret.append( key );
}
lua_pop( L, 2 ); // Key copy and value
}
}
lua_pop( L, 1 ); // __propget table
return;
}
int getClassInfo( lua_State* L )
{
luabridge::LuaRef ret = luabridge::newTable( L );
if( lua_istable( L, 1 ) )
{
// Class Type
lua_getmetatable( L, 1 );
// Static members.
getClassMembers( L, ret );
// Regular members.
lua_pushstring( L, "__class" );
lua_rawget( L, -2 );
if( lua_istable( L, -1 ) )
{
getClassMembers( L, ret );
}
}
else if( lua_isuserdata( L, 1 ) )
{
// Class instance
lua_getmetatable( L, 1 );
getClassMembers( L, ret );
}
// Just return an empty table if not a class.
ret.push( L );
return 1;
}
void ScriptingSystem::shutdown()
{
if( mL )
lua_close( mL );
mL = 0;
}
void ScriptingSystem::initialise()
{
mL = luaL_newstate();
luaL_openlibs( mL );
lua_pushlightuserdata( mL, (void *)&GUID );
lua_pushlightuserdata( mL, this );
lua_settable( mL, LUA_REGISTRYINDEX );
bind();
bindOgre( mL );
/*
bindGameEntityClasses( mL );
bindAnimation( mL );
bindNavigationMesh( mL );
*/
bindGorilla( mL );
using namespace luabridge;
LuaResourcePtr mainlua = LuaResourceManager::getSingleton().load( "main.lua" );
if( luaL_loadbuffer( mL,
mainlua->getScriptSource().c_str(),
mainlua->calculateSize(), "main.lua" ) || lua_pcall( mL, 0, LUA_MULTRET, 0) )
{
Ogre::LogManager::getSingleton().stream() << " ****************************** ";
Ogre::LogManager::getSingleton().stream() << " *** main.lua failed to run ";
Ogre::LogManager::getSingleton().stream() << " *** " << lua_tostring( mL, -1 );
Ogre::LogManager::getSingleton().stream() << " ****************************** ";
}
}
void ScriptingSystem::bind()
{
using namespace luabridge;
installLibraryLoader( mL );
getGlobalNamespace( mL )
.addCFunction( "getClassInfo", &getClassInfo )
.beginNamespace( "Engine" )
.beginClass<Event>( "Event" )
.addConstructor<void (*) (const char*)>()
.addData( "type", &Event::type )
.addData( "data", &Event::data )
.addStaticFunction( "hash", &Event::hash )
.endClass()
.addFunction( "queueEvent", &queueEventThunk )
.beginClass<EventData>( "EventData" )
.endClass()
.deriveClass<InputEventData, EventData>( "InputEventData" )
.addConstructor<void (*) (void)>()
.addStaticFunction( "downcast", &downcast<InputEventData, EventData> )
.addData( "x", &InputEventData::x )
.addData( "y", &InputEventData::y )
.addData( "buttons", &InputEventData::parm )
.addProperty( "text", &InputEventDataBindingHelper::getText, &InputEventDataBindingHelper::setText )
.addProperty( "key", &InputEventDataBindingHelper::getKey, &InputEventDataBindingHelper::setKey )
.endClass()
.deriveClass<WindowEventData, EventData>( "WindowEventData" )
.addStaticFunction( "downcast", &downcast<WindowEventData, EventData> )
.addData( "width", &WindowEventData::width )
.addData( "height", &WindowEventData::height )
.endClass()
/*
.deriveClass<AnimationEventData, EventData>( "AnimationEventData" )
.addData( "animation", &AnimationEventData::animation )
.endClass()
*/
.addFunction( "versionString", versionString )
.endNamespace();
}
bool ScriptingSystem::EventNotification( EventPtr event )
{
luabridge::LuaRef notify = luabridge::getGlobal( mL, "EventNotification");
luabridge::LuaRef ret( mL );
if( notify )
{
try
{
ret = notify( *event );
if( ret == true )
return true;
}
catch( luabridge::LuaException& e )
{
Ogre::LogManager::getSingleton().stream() << e.what();
}
}
return false;
}
bool ScriptingSystem::frameStarted(const Ogre::FrameEvent& evt)
{
luabridge::LuaRef func = luabridge::getGlobal( mL, "FrameStarted" );
try
{
// If the function is not defined, don't worry about it.
if( func )
func( evt.timeSinceLastFrame );
}
catch( luabridge::LuaException& e )
{
Ogre::LogManager::getSingleton().stream() << e.what();
}
return true;
}
bool ScriptingSystem::frameEnded(const Ogre::FrameEvent& evt)
{
luabridge::LuaRef func = luabridge::getGlobal( mL, "FrameEnded" );
try
{
// If the function is not defined, don't worry about it.
if( func )
func( evt.timeSinceLastFrame );
// Do a Lua garbage collection.
// We do it like this - as LuaRef translates any errors in finalizers
// to exceptions, which we then catch.
luabridge::LuaRef gc = luabridge::getGlobal( mL, "collectgarbage" );
gc( "step" );
}
catch( luabridge::LuaException& e )
{
Ogre::LogManager::getSingleton().stream() << e.what();
}
return true;
}
<|endoftext|>
|
<commit_before>#include "Marker.hpp"
#include <tf/transform_datatypes.h>
#include <math.h>
Marker::Marker(double xPos, double yPos, double angle, MarkerType t, std::string name) {
pos.position.x = xPos;
pos.position.y = yPos;
pos.orientation = SetQuaternation(0, 0, Deg2Rad(angle));
type = t;
markerName = name;
}
Marker::Marker(geometry_msgs::Pose p, MarkerType t, std::string name) {
pos = p;
type = t;
markerName = name;
}
geometry_msgs::Quaternion Marker::SetQuaternation(double roll, double pitch, double yaw) {
return tf::createQuaternionMsgFromRollPitchYaw(roll, pitch, yaw);
}
double Marker::GetX() {
return pos.position.x;
}
double Marker::GetY() {
return pos.position.y;
}
double Marker::GetAngle() {
tf::Quaternion q;
tf::quaternionMsgToTF(pos.orientation, q);
q.normalize();
return Rad2Deg(tf::getYaw(q));
}
MarkerType Marker::GetType() {
return type;
}
std::string Marker::GetTypeStr() {
if(type == Shelf) {
return "Shelf";
} else if (type == Workstation) {
return "Workstation";
} else if (type == Conveyor) {
return "Conveyor";
} else if (type == Waypoint) {
return "Waypoint";
} else if (type == Precision) {
return "Precision";
} else {
return "Other";
}
}
std::string Marker::GetName() {
return markerName;
}
geometry_msgs::Quaternion Marker::GetQuaternation() {
return pos.orientation;
}
geometry_msgs::Point Marker::GetPoint() {
return pos.position;
}
geometry_msgs::Pose Marker::GetPose() {
return pos;
}
double Marker::Rad2Deg(double rad) {
return (rad * 180.0 / M_PI);
}
double Marker::Deg2Rad(double deg) {
return (deg * M_PI / 180.0);
}<commit_msg>Added check for nan in ngle<commit_after>#include "Marker.hpp"
#include <tf/transform_datatypes.h>
#include <math.h>
Marker::Marker(double xPos, double yPos, double angle, MarkerType t, std::string name) {
pos.position.x = xPos;
pos.position.y = yPos;
pos.orientation = SetQuaternation(0, 0, Deg2Rad(angle));
type = t;
markerName = name;
}
Marker::Marker(geometry_msgs::Pose p, MarkerType t, std::string name) {
pos = p;
type = t;
markerName = name;
}
geometry_msgs::Quaternion Marker::SetQuaternation(double roll, double pitch, double yaw) {
return tf::createQuaternionMsgFromRollPitchYaw(roll, pitch, yaw);
}
double Marker::GetX() {
return pos.position.x;
}
double Marker::GetY() {
return pos.position.y;
}
double Marker::GetAngle() {
tf::Quaternion q;
tf::quaternionMsgToTF(pos.orientation, q);
q.normalize();
double angle = Rad2Deg(tf::getYaw(q));
if(isnan(angle))
{
angle = 0;
}
return angle;
}
MarkerType Marker::GetType() {
return type;
}
std::string Marker::GetTypeStr() {
if(type == Shelf) {
return "Shelf";
} else if (type == Workstation) {
return "Workstation";
} else if (type == Conveyor) {
return "Conveyor";
} else if (type == Waypoint) {
return "Waypoint";
} else if (type == Precision) {
return "Precision";
} else {
return "Other";
}
}
std::string Marker::GetName() {
return markerName;
}
geometry_msgs::Quaternion Marker::GetQuaternation() {
return pos.orientation;
}
geometry_msgs::Point Marker::GetPoint() {
return pos.position;
}
geometry_msgs::Pose Marker::GetPose() {
return pos;
}
double Marker::Rad2Deg(double rad) {
return (rad * 180.0 / M_PI);
}
double Marker::Deg2Rad(double deg) {
return (deg * M_PI / 180.0);
}
<|endoftext|>
|
<commit_before>/** @copyright
* Copyright (c) 2020 Stuart W Baker
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @file SN74HC595GPO.hxx
* This file implements the GPO driver for the 74HC595 shift register. The SN
* prefix is for the Texas Instruments variant, however compatible devices
* from other suppliers may have a different prefix or no prefix.
*
* @author Stuart W. Baker
* @date 23 February 2020
*/
#ifndef _FREERTOS_DRIVERS_COMMON_SN74HC595GPO_HXX_
#define _FREERTOS_DRIVERS_COMMON_SN74HC595GPO_HXX_
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <fcntl.h>
#include <unistd.h>
#include "SPI.hxx"
#include "os/Gpio.hxx"
#include "os/OS.hxx"
template <uint8_t N = 1> class SN74HC595GPO;
/// Driver for the 74HC595 shift register. Note: This driver makes use of
/// std::atomic and requires an implementation of std::atomic on any platform
/// that makes use of it. For example, at the time of creating this device
/// driver, ARMv7-M (Cortex-M3/M4/M4F) does have support for std::atomic,
/// while ARMv6-M (Cortex-M0) does not.
/// @tparam N number of chips on the bus, starting at 1
template <uint8_t N = 1> class SN74HC595 : public OSThread
{
public:
/// Constructor.
/// @param request_refresh_operation This is an application specific
/// callback for triggering a sequence of events that will result
/// in @ref refresh() being called. The exact implementation is
/// application specific, and mostly is determined by whether or not
/// these outputs must be toggled from an interrupt.
SN74HC595(void (*request_refresh_operation)(void))
: requestRefreshOperation_(request_refresh_operation)
, spiFd_(-1)
, sem_()
, ioPending_(false)
{
HASSERT(N > 0);
for (unsigned i = 0; i < N; ++i)
{
gpoData_[i] = 0;
}
}
/// Initialize the SN74HC595 settings. Typically called in hw_postinit(),
/// not hw_preinit() or hw_init().
/// @param spi_name spi interface that the SN74HC595 is on
/// @param priority helper thread priority
void init(const char *spi_name, int priority = get_priority_max())
{
spiFd_ = ::open(spi_name, O_WRONLY);
HASSERT(spiFd_ >= 0);
// configure SPI bus settings
uint8_t spi_mode = SPI_MODE_0;
uint8_t spi_bpw = 8;
uint32_t spi_max_speed_hz = SPI_MAX_SPEED_HZ;
::ioctl(spiFd_, SPI_IOC_WR_MODE, &spi_mode);
::ioctl(spiFd_, SPI_IOC_WR_BITS_PER_WORD, &spi_bpw);
::ioctl(spiFd_, SPI_IOC_WR_MAX_SPEED_HZ, &spi_max_speed_hz);
requestRefreshOperation_();
// start the thread at the highest priority in the system
start("SN74HC595", priority, 384 + N);
}
/// Triggers the helper thread to wakeup and refresh the outputs.
/// @param from_isr true if called from an ISR.
void refresh(bool from_isr = false)
{
if (!ioPending_)
{
ioPending_ = true;
if (from_isr)
{
int woken;
sem_.post_from_isr(&woken);
}
else
{
sem_.post();
}
}
}
private:
/// maximum SPI clock speed in Hz
static constexpr uint32_t SPI_MAX_SPEED_HZ = 1000000;
/// User entry point for the created thread.
/// @return exit status
void *entry() override
{
for ( ; /* forever */ ; )
{
sem_.wait();
if (ioPending_)
{
ioPending_ = false;
uint8_t data[N];
for (unsigned i = 0; i < N; ++i)
{
data[i] = gpoData_[i];
}
::write(spiFd_, data, N);
}
}
}
/// Request that the GPIO cache be refreshed.
void (*requestRefreshOperation_)(void);
int spiFd_; ///< SPI bus that accesses the SN74HC595
OSSem sem_; ///< semaphore for posting events
uint8_t ioPending_ : 1; ///< true if an update is pending
/// local copy of the expansion output data
std::atomic<uint8_t> gpoData_[N];
/// Allow access to SN74HC595 from SN74HC595GPO
friend class SN74HC595GPO<N>;
DISALLOW_COPY_AND_ASSIGN(SN74HC595);
};
/// General Purpose Output (GPO) instance on the 74HC595.
/// @tparam N number of chips on the bus, starting at 1
template <uint8_t N> class SN74HC595GPO : public Gpio
{
public:
/// Constructor.
/// @param instance parrent 74HC595 instance that "owns" the interface.
/// @param chip_index index on the bus for the chip, starting at 0.
/// @param bit bit index (0 through 7) of the output.
constexpr SN74HC595GPO(SN74HC595<N> *instance, uint8_t chip_index, uint8_t bit)
: Gpio()
, instance_(instance)
, chipIndex_(chip_index)
, bit_(bit)
{
HASSERT(bit < 8);
HASSERT(chip_index < sizeof(instance->gpoData_));
HASSERT(N == sizeof(instance->gpoData_));
}
/// Writes a GPO pin (set or clear to a specific state).
/// @param new_state the desired output state. See @ref Value.
void write(Value new_state) const override
{
new_state ? set() : clr();
}
/// Retrieves the current @ref Value of a GPO output sate (requested).
/// @return @ref SET if currently high, @ref CLR if currently low
Value read() const override
{
return instance_->gpoData_[chipIndex_] & (0x1 << bit_) ?
Gpio::SET : Gpio::CLR;
}
/// Sets the GPO pin to high.
void set() const override
{
if (!(instance_->gpoData_[chipIndex_] & (0x1 << bit_)))
{
instance_->gpoData_[chipIndex_] |= 0x1 << bit_;
instance_->requestRefreshOperation_();
}
}
/// Clears the GPO pin to low.
void clr() const override
{
if ((instance_->gpoData_[chipIndex_] & (0x1 << bit_)))
{
instance_->gpoData_[chipIndex_] &= ~(0x1 << bit_);
instance_->requestRefreshOperation_();
}
}
/// Sets the GPO direction (does nothing).
/// @param dir @ref DINPUT or @ref DOUTPUT
void set_direction(Gpio::Direction dir) const override
{
HASSERT(dir == Gpio::Direction::DOUTPUT);
}
/// Gets the GPO direction.
/// @return always returns @ref DOUTPUT
Direction direction() const override
{
return Gpio::Direction::DOUTPUT;
}
private:
/// reference to chip instance
SN74HC595<N> * const instance_;
/// index on the bus for the chip
const uint8_t chipIndex_;
/// bit number representative of the bit
const uint8_t bit_;
DISALLOW_COPY_AND_ASSIGN(SN74HC595GPO);
};
#endif // _FREERTOS_DRIVERS_COMMON_SN74HC595GPO_HXX_
<commit_msg>Increase the MAX supported SPI clock speed. (#366)<commit_after>/** @copyright
* Copyright (c) 2020 Stuart W Baker
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @file SN74HC595GPO.hxx
* This file implements the GPO driver for the 74HC595 shift register. The SN
* prefix is for the Texas Instruments variant, however compatible devices
* from other suppliers may have a different prefix or no prefix.
*
* @author Stuart W. Baker
* @date 23 February 2020
*/
#ifndef _FREERTOS_DRIVERS_COMMON_SN74HC595GPO_HXX_
#define _FREERTOS_DRIVERS_COMMON_SN74HC595GPO_HXX_
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <fcntl.h>
#include <unistd.h>
#include "SPI.hxx"
#include "os/Gpio.hxx"
#include "os/OS.hxx"
template <uint8_t N = 1> class SN74HC595GPO;
/// Driver for the 74HC595 shift register. Note: This driver makes use of
/// std::atomic and requires an implementation of std::atomic on any platform
/// that makes use of it. For example, at the time of creating this device
/// driver, ARMv7-M (Cortex-M3/M4/M4F) does have support for std::atomic,
/// while ARMv6-M (Cortex-M0) does not.
/// @tparam N number of chips on the bus, starting at 1
template <uint8_t N = 1> class SN74HC595 : public OSThread
{
public:
/// Constructor.
/// @param request_refresh_operation This is an application specific
/// callback for triggering a sequence of events that will result
/// in @ref refresh() being called. The exact implementation is
/// application specific, and mostly is determined by whether or not
/// these outputs must be toggled from an interrupt.
SN74HC595(void (*request_refresh_operation)(void))
: requestRefreshOperation_(request_refresh_operation)
, spiFd_(-1)
, sem_()
, ioPending_(false)
{
HASSERT(N > 0);
for (unsigned i = 0; i < N; ++i)
{
gpoData_[i] = 0;
}
}
/// Initialize the SN74HC595 settings. Typically called in hw_postinit(),
/// not hw_preinit() or hw_init().
/// @param spi_name spi interface that the SN74HC595 is on
/// @param priority helper thread priority
void init(const char *spi_name, int priority = get_priority_max())
{
spiFd_ = ::open(spi_name, O_WRONLY);
HASSERT(spiFd_ >= 0);
// configure SPI bus settings
uint8_t spi_mode = SPI_MODE_0;
uint8_t spi_bpw = 8;
uint32_t spi_max_speed_hz = SPI_MAX_SPEED_HZ;
::ioctl(spiFd_, SPI_IOC_WR_MODE, &spi_mode);
::ioctl(spiFd_, SPI_IOC_WR_BITS_PER_WORD, &spi_bpw);
::ioctl(spiFd_, SPI_IOC_WR_MAX_SPEED_HZ, &spi_max_speed_hz);
requestRefreshOperation_();
// start the thread at the highest priority in the system
start("SN74HC595", priority, 384 + N);
}
/// Triggers the helper thread to wakeup and refresh the outputs.
/// @param from_isr true if called from an ISR.
void refresh(bool from_isr = false)
{
if (!ioPending_)
{
ioPending_ = true;
if (from_isr)
{
int woken;
sem_.post_from_isr(&woken);
}
else
{
sem_.post();
}
}
}
private:
/// maximum SPI clock speed in Hz
static constexpr uint32_t SPI_MAX_SPEED_HZ = 4000000;
/// User entry point for the created thread.
/// @return exit status
void *entry() override
{
for ( ; /* forever */ ; )
{
sem_.wait();
if (ioPending_)
{
ioPending_ = false;
uint8_t data[N];
for (unsigned i = 0; i < N; ++i)
{
data[i] = gpoData_[i];
}
::write(spiFd_, data, N);
}
}
}
/// Request that the GPIO cache be refreshed.
void (*requestRefreshOperation_)(void);
int spiFd_; ///< SPI bus that accesses the SN74HC595
OSSem sem_; ///< semaphore for posting events
uint8_t ioPending_ : 1; ///< true if an update is pending
/// local copy of the expansion output data
std::atomic<uint8_t> gpoData_[N];
/// Allow access to SN74HC595 from SN74HC595GPO
friend class SN74HC595GPO<N>;
DISALLOW_COPY_AND_ASSIGN(SN74HC595);
};
/// General Purpose Output (GPO) instance on the 74HC595.
/// @tparam N number of chips on the bus, starting at 1
template <uint8_t N> class SN74HC595GPO : public Gpio
{
public:
/// Constructor.
/// @param instance parrent 74HC595 instance that "owns" the interface.
/// @param chip_index index on the bus for the chip, starting at 0.
/// @param bit bit index (0 through 7) of the output.
constexpr SN74HC595GPO(SN74HC595<N> *instance, uint8_t chip_index, uint8_t bit)
: Gpio()
, instance_(instance)
, chipIndex_(chip_index)
, bit_(bit)
{
HASSERT(bit < 8);
HASSERT(chip_index < sizeof(instance->gpoData_));
HASSERT(N == sizeof(instance->gpoData_));
}
/// Writes a GPO pin (set or clear to a specific state).
/// @param new_state the desired output state. See @ref Value.
void write(Value new_state) const override
{
new_state ? set() : clr();
}
/// Retrieves the current @ref Value of a GPO output sate (requested).
/// @return @ref SET if currently high, @ref CLR if currently low
Value read() const override
{
return instance_->gpoData_[chipIndex_] & (0x1 << bit_) ?
Gpio::SET : Gpio::CLR;
}
/// Sets the GPO pin to high.
void set() const override
{
if (!(instance_->gpoData_[chipIndex_] & (0x1 << bit_)))
{
instance_->gpoData_[chipIndex_] |= 0x1 << bit_;
instance_->requestRefreshOperation_();
}
}
/// Clears the GPO pin to low.
void clr() const override
{
if ((instance_->gpoData_[chipIndex_] & (0x1 << bit_)))
{
instance_->gpoData_[chipIndex_] &= ~(0x1 << bit_);
instance_->requestRefreshOperation_();
}
}
/// Sets the GPO direction (does nothing).
/// @param dir @ref DINPUT or @ref DOUTPUT
void set_direction(Gpio::Direction dir) const override
{
HASSERT(dir == Gpio::Direction::DOUTPUT);
}
/// Gets the GPO direction.
/// @return always returns @ref DOUTPUT
Direction direction() const override
{
return Gpio::Direction::DOUTPUT;
}
private:
/// reference to chip instance
SN74HC595<N> * const instance_;
/// index on the bus for the chip
const uint8_t chipIndex_;
/// bit number representative of the bit
const uint8_t bit_;
DISALLOW_COPY_AND_ASSIGN(SN74HC595GPO);
};
#endif // _FREERTOS_DRIVERS_COMMON_SN74HC595GPO_HXX_
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2017 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 "src/ftrace_reader/proto_translation_table.h"
#include <regex.h>
#include <algorithm>
#include "event_info.h"
#include "ftrace_procfs.h"
#include "perfetto/ftrace_reader/format_parser.h"
#include "perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
namespace perfetto {
namespace {
const std::vector<Event> BuildEventsVector(const std::vector<Event>& events) {
size_t largest_id = 0;
for (const Event& event : events) {
if (event.ftrace_event_id > largest_id)
largest_id = event.ftrace_event_id;
}
std::vector<Event> events_by_id;
events_by_id.resize(largest_id + 1);
for (const Event& event : events) {
events_by_id[event.ftrace_event_id] = event;
}
events_by_id.shrink_to_fit();
return events_by_id;
}
// Merge the information from |ftrace_field| into |field| (mutating it).
// We should set the following fields: offset, size, ftrace field type and
// translation strategy.
bool MergeFieldInfo(const FtraceEvent::Field& ftrace_field,
Field* field,
const char* event_name_for_debug) {
PERFETTO_DCHECK(field->ftrace_name);
PERFETTO_DCHECK(field->proto_field_id);
PERFETTO_DCHECK(field->proto_field_type);
PERFETTO_DCHECK(!field->ftrace_offset);
PERFETTO_DCHECK(!field->ftrace_size);
PERFETTO_DCHECK(!field->ftrace_type);
if (!InferFtraceType(ftrace_field.type_and_name, ftrace_field.size,
ftrace_field.is_signed, &field->ftrace_type)) {
PERFETTO_DLOG(
"Failed to infer ftrace field type for \"%s.%s\" (type:\"%s\" size:%d "
"signed:%d)",
event_name_for_debug, field->ftrace_name,
ftrace_field.type_and_name.c_str(), ftrace_field.size,
ftrace_field.is_signed);
PERFETTO_DCHECK(false);
return false;
}
field->ftrace_offset = ftrace_field.offset;
field->ftrace_size = ftrace_field.size;
if (!SetTranslationStrategy(field->ftrace_type, field->proto_field_type,
&field->strategy)) {
PERFETTO_DLOG(
"Failed to find translation stratagy for ftrace field \"%s.%s\" (%s -> "
"%s)",
event_name_for_debug, field->ftrace_name, ToString(field->ftrace_type),
ToString(field->proto_field_type));
// TODO(hjd): Uncomment DCHECK when proto generation is fixed.
// PERFETTO_DCHECK(false);
return false;
}
return true;
}
// For each field in |fields| find the matching field from |ftrace_fields| (by
// comparing ftrace_name) and copy the information from the FtraceEvent::Field
// into the Field (mutating it). If there is no matching field in
// |ftrace_fields| remove the Field from |fields|. Return the maximum observed
// 'field end' (offset + size).
uint16_t MergeFields(const std::vector<FtraceEvent::Field>& ftrace_fields,
std::vector<Field>* fields,
const char* event_name_for_debug) {
uint16_t fields_end = 0;
// Loop over each Field in |fields| modifiying it with information from the
// matching |ftrace_fields| field or removing it.
auto field = fields->begin();
while (field != fields->end()) {
bool success = false;
for (const FtraceEvent::Field& ftrace_field : ftrace_fields) {
if (GetNameFromTypeAndName(ftrace_field.type_and_name) !=
field->ftrace_name)
continue;
success = MergeFieldInfo(ftrace_field, &*field, event_name_for_debug);
uint16_t field_end = field->ftrace_offset + field->ftrace_size;
fields_end = std::max<uint16_t>(fields_end, field_end);
break;
}
if (success) {
++field;
} else {
field = fields->erase(field);
}
}
return fields_end;
}
bool StartsWith(const std::string& str, const std::string& prefix) {
return str.compare(0, prefix.length(), prefix) == 0;
}
bool Contains(const std::string& haystack, const std::string& needle) {
return haystack.find(needle) != std::string::npos;
}
std::string RegexError(int errcode, const regex_t* preg) {
char buf[64];
regerror(errcode, preg, buf, sizeof(buf));
return {buf, sizeof(buf)};
}
bool Match(const char* string, const char* pattern) {
regex_t re;
int ret = regcomp(&re, pattern, REG_EXTENDED | REG_NOSUB);
if (ret != 0) {
PERFETTO_FATAL("regcomp: %s", RegexError(ret, &re).c_str());
}
ret = regexec(&re, string, 0, nullptr, 0);
regfree(&re);
return ret != REG_NOMATCH;
}
} // namespace
// This is similar but different from InferProtoType (see format_parser.cc).
// TODO(hjd): Fold FtraceEvent(::Field) into Event.
bool InferFtraceType(const std::string& type_and_name,
size_t size,
bool is_signed,
FtraceFieldType* out) {
// Fixed length strings: e.g. "char foo[16]" we don't care about the number
// since we get the size as it's own field. Somewhat awkwardly these fields
// are both fixed size and null terminated meaning that we can't just drop
// them directly into the protobuf (since if the string is shorter than 15
// characters we want only the bit up to the null terminator).
if (Match(type_and_name.c_str(), R"(char [a-zA-Z_]+\[[0-9]+\])")) {
*out = kFtraceFixedCString;
return true;
}
// String pointers: "__data_loc char[] foo" (as in
// 'cpufreq_interactive_boost').
if (Contains(type_and_name, "char[] ")) {
*out = kFtraceStringPtr;
return true;
}
if (Contains(type_and_name, "char * ")) {
*out = kFtraceStringPtr;
return true;
}
// Variable length strings: "char foo" + size: 0 (as in 'print').
if (StartsWith(type_and_name, "char ") && size == 0) {
*out = kFtraceCString;
return true;
}
if (StartsWith(type_and_name, "bool ")) {
*out = kFtraceBool;
return true;
}
if (StartsWith(type_and_name, "ino_t ") ||
StartsWith(type_and_name, "i_ino ")) {
if (size == 4) {
*out = kFtraceInode32;
return true;
} else if (size == 8) {
*out = kFtraceInode64;
return true;
}
}
// Pids (as in 'sched_switch').
if (StartsWith(type_and_name, "pid_t ") && size == 4) {
*out = kFtracePid32;
return true;
}
// Ints of various sizes:
if (size == 1 && !is_signed) {
*out = kFtraceUint8;
return true;
} else if (size == 2 && is_signed) {
*out = kFtraceInt16;
return true;
} else if (size == 2 && !is_signed) {
*out = kFtraceUint16;
return true;
} else if (size == 4 && is_signed) {
*out = kFtraceInt32;
return true;
} else if (size == 4 && !is_signed) {
*out = kFtraceUint32;
return true;
} else if (size == 8 && is_signed) {
*out = kFtraceInt64;
return true;
} else if (size == 8 && !is_signed) {
*out = kFtraceUint64;
return true;
}
PERFETTO_DLOG("Could not infer ftrace type for '%s'", type_and_name.c_str());
return false;
}
// static
std::unique_ptr<ProtoTranslationTable> ProtoTranslationTable::Create(
const FtraceProcfs* ftrace_procfs,
std::vector<Event> events,
std::vector<Field> common_fields) {
bool common_fields_processed = false;
uint16_t common_fields_end = 0;
for (Event& event : events) {
PERFETTO_DCHECK(event.name);
PERFETTO_DCHECK(event.group);
PERFETTO_DCHECK(event.proto_field_id);
PERFETTO_DCHECK(!event.ftrace_event_id);
std::string contents =
ftrace_procfs->ReadEventFormat(event.group, event.name);
FtraceEvent ftrace_event;
if (contents.empty() || !ParseFtraceEvent(contents, &ftrace_event)) {
continue;
}
event.ftrace_event_id = ftrace_event.id;
if (!common_fields_processed) {
common_fields_end =
MergeFields(ftrace_event.common_fields, &common_fields, event.name);
common_fields_processed = true;
}
uint16_t fields_end =
MergeFields(ftrace_event.fields, &event.fields, event.name);
event.size = std::max<uint16_t>(fields_end, common_fields_end);
}
events.erase(std::remove_if(events.begin(), events.end(),
[](const Event& event) {
return event.proto_field_id == 0 ||
event.ftrace_event_id == 0;
}),
events.end());
auto table = std::unique_ptr<ProtoTranslationTable>(
new ProtoTranslationTable(events, std::move(common_fields)));
return table;
}
ProtoTranslationTable::ProtoTranslationTable(const std::vector<Event>& events,
std::vector<Field> common_fields)
: events_(BuildEventsVector(events)),
largest_id_(events_.size() - 1),
common_fields_(std::move(common_fields)) {
for (const Event& event : events) {
name_to_event_[event.name] = &events_.at(event.ftrace_event_id);
}
}
ProtoTranslationTable::~ProtoTranslationTable() = default;
} // namespace perfetto
<commit_msg>ftrace_reader: Comment out DCHECK in proto_translation_table.cc<commit_after>/*
* Copyright (C) 2017 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 "src/ftrace_reader/proto_translation_table.h"
#include <regex.h>
#include <algorithm>
#include "event_info.h"
#include "ftrace_procfs.h"
#include "perfetto/ftrace_reader/format_parser.h"
#include "perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
namespace perfetto {
namespace {
const std::vector<Event> BuildEventsVector(const std::vector<Event>& events) {
size_t largest_id = 0;
for (const Event& event : events) {
if (event.ftrace_event_id > largest_id)
largest_id = event.ftrace_event_id;
}
std::vector<Event> events_by_id;
events_by_id.resize(largest_id + 1);
for (const Event& event : events) {
events_by_id[event.ftrace_event_id] = event;
}
events_by_id.shrink_to_fit();
return events_by_id;
}
// Merge the information from |ftrace_field| into |field| (mutating it).
// We should set the following fields: offset, size, ftrace field type and
// translation strategy.
bool MergeFieldInfo(const FtraceEvent::Field& ftrace_field,
Field* field,
const char* event_name_for_debug) {
PERFETTO_DCHECK(field->ftrace_name);
PERFETTO_DCHECK(field->proto_field_id);
PERFETTO_DCHECK(field->proto_field_type);
PERFETTO_DCHECK(!field->ftrace_offset);
PERFETTO_DCHECK(!field->ftrace_size);
PERFETTO_DCHECK(!field->ftrace_type);
if (!InferFtraceType(ftrace_field.type_and_name, ftrace_field.size,
ftrace_field.is_signed, &field->ftrace_type)) {
PERFETTO_DLOG(
"Failed to infer ftrace field type for \"%s.%s\" (type:\"%s\" size:%d "
"signed:%d)",
event_name_for_debug, field->ftrace_name,
ftrace_field.type_and_name.c_str(), ftrace_field.size,
ftrace_field.is_signed);
// TODO(hjd): Uncomment DCHECK when proto generation is fixed.
// PERFETTO_DCHECK(false);
return false;
}
field->ftrace_offset = ftrace_field.offset;
field->ftrace_size = ftrace_field.size;
if (!SetTranslationStrategy(field->ftrace_type, field->proto_field_type,
&field->strategy)) {
PERFETTO_DLOG(
"Failed to find translation stratagy for ftrace field \"%s.%s\" (%s -> "
"%s)",
event_name_for_debug, field->ftrace_name, ToString(field->ftrace_type),
ToString(field->proto_field_type));
// TODO(hjd): Uncomment DCHECK when proto generation is fixed.
// PERFETTO_DCHECK(false);
return false;
}
return true;
}
// For each field in |fields| find the matching field from |ftrace_fields| (by
// comparing ftrace_name) and copy the information from the FtraceEvent::Field
// into the Field (mutating it). If there is no matching field in
// |ftrace_fields| remove the Field from |fields|. Return the maximum observed
// 'field end' (offset + size).
uint16_t MergeFields(const std::vector<FtraceEvent::Field>& ftrace_fields,
std::vector<Field>* fields,
const char* event_name_for_debug) {
uint16_t fields_end = 0;
// Loop over each Field in |fields| modifiying it with information from the
// matching |ftrace_fields| field or removing it.
auto field = fields->begin();
while (field != fields->end()) {
bool success = false;
for (const FtraceEvent::Field& ftrace_field : ftrace_fields) {
if (GetNameFromTypeAndName(ftrace_field.type_and_name) !=
field->ftrace_name)
continue;
success = MergeFieldInfo(ftrace_field, &*field, event_name_for_debug);
uint16_t field_end = field->ftrace_offset + field->ftrace_size;
fields_end = std::max<uint16_t>(fields_end, field_end);
break;
}
if (success) {
++field;
} else {
field = fields->erase(field);
}
}
return fields_end;
}
bool StartsWith(const std::string& str, const std::string& prefix) {
return str.compare(0, prefix.length(), prefix) == 0;
}
bool Contains(const std::string& haystack, const std::string& needle) {
return haystack.find(needle) != std::string::npos;
}
std::string RegexError(int errcode, const regex_t* preg) {
char buf[64];
regerror(errcode, preg, buf, sizeof(buf));
return {buf, sizeof(buf)};
}
bool Match(const char* string, const char* pattern) {
regex_t re;
int ret = regcomp(&re, pattern, REG_EXTENDED | REG_NOSUB);
if (ret != 0) {
PERFETTO_FATAL("regcomp: %s", RegexError(ret, &re).c_str());
}
ret = regexec(&re, string, 0, nullptr, 0);
regfree(&re);
return ret != REG_NOMATCH;
}
} // namespace
// This is similar but different from InferProtoType (see format_parser.cc).
// TODO(hjd): Fold FtraceEvent(::Field) into Event.
bool InferFtraceType(const std::string& type_and_name,
size_t size,
bool is_signed,
FtraceFieldType* out) {
// Fixed length strings: e.g. "char foo[16]" we don't care about the number
// since we get the size as it's own field. Somewhat awkwardly these fields
// are both fixed size and null terminated meaning that we can't just drop
// them directly into the protobuf (since if the string is shorter than 15
// characters we want only the bit up to the null terminator).
if (Match(type_and_name.c_str(), R"(char [a-zA-Z_]+\[[0-9]+\])")) {
*out = kFtraceFixedCString;
return true;
}
// String pointers: "__data_loc char[] foo" (as in
// 'cpufreq_interactive_boost').
if (Contains(type_and_name, "char[] ")) {
*out = kFtraceStringPtr;
return true;
}
if (Contains(type_and_name, "char * ")) {
*out = kFtraceStringPtr;
return true;
}
// Variable length strings: "char foo" + size: 0 (as in 'print').
if (StartsWith(type_and_name, "char ") && size == 0) {
*out = kFtraceCString;
return true;
}
if (StartsWith(type_and_name, "bool ")) {
*out = kFtraceBool;
return true;
}
if (StartsWith(type_and_name, "ino_t ") ||
StartsWith(type_and_name, "i_ino ")) {
if (size == 4) {
*out = kFtraceInode32;
return true;
} else if (size == 8) {
*out = kFtraceInode64;
return true;
}
}
// Pids (as in 'sched_switch').
if (StartsWith(type_and_name, "pid_t ") && size == 4) {
*out = kFtracePid32;
return true;
}
// Ints of various sizes:
if (size == 1 && !is_signed) {
*out = kFtraceUint8;
return true;
} else if (size == 2 && is_signed) {
*out = kFtraceInt16;
return true;
} else if (size == 2 && !is_signed) {
*out = kFtraceUint16;
return true;
} else if (size == 4 && is_signed) {
*out = kFtraceInt32;
return true;
} else if (size == 4 && !is_signed) {
*out = kFtraceUint32;
return true;
} else if (size == 8 && is_signed) {
*out = kFtraceInt64;
return true;
} else if (size == 8 && !is_signed) {
*out = kFtraceUint64;
return true;
}
PERFETTO_DLOG("Could not infer ftrace type for '%s'", type_and_name.c_str());
return false;
}
// static
std::unique_ptr<ProtoTranslationTable> ProtoTranslationTable::Create(
const FtraceProcfs* ftrace_procfs,
std::vector<Event> events,
std::vector<Field> common_fields) {
bool common_fields_processed = false;
uint16_t common_fields_end = 0;
for (Event& event : events) {
PERFETTO_DCHECK(event.name);
PERFETTO_DCHECK(event.group);
PERFETTO_DCHECK(event.proto_field_id);
PERFETTO_DCHECK(!event.ftrace_event_id);
std::string contents =
ftrace_procfs->ReadEventFormat(event.group, event.name);
FtraceEvent ftrace_event;
if (contents.empty() || !ParseFtraceEvent(contents, &ftrace_event)) {
continue;
}
event.ftrace_event_id = ftrace_event.id;
if (!common_fields_processed) {
common_fields_end =
MergeFields(ftrace_event.common_fields, &common_fields, event.name);
common_fields_processed = true;
}
uint16_t fields_end =
MergeFields(ftrace_event.fields, &event.fields, event.name);
event.size = std::max<uint16_t>(fields_end, common_fields_end);
}
events.erase(std::remove_if(events.begin(), events.end(),
[](const Event& event) {
return event.proto_field_id == 0 ||
event.ftrace_event_id == 0;
}),
events.end());
auto table = std::unique_ptr<ProtoTranslationTable>(
new ProtoTranslationTable(events, std::move(common_fields)));
return table;
}
ProtoTranslationTable::ProtoTranslationTable(const std::vector<Event>& events,
std::vector<Field> common_fields)
: events_(BuildEventsVector(events)),
largest_id_(events_.size() - 1),
common_fields_(std::move(common_fields)) {
for (const Event& event : events) {
name_to_event_[event.name] = &events_.at(event.ftrace_event_id);
}
}
ProtoTranslationTable::~ProtoTranslationTable() = default;
} // namespace perfetto
<|endoftext|>
|
<commit_before>/*
* This file is part of the Gluon project.
* Copyright (C) 2009 Sacha Schutz <istdasklar@free.fr>
* Copyright (C) 2009 Guillaume Martres <smarter@ubuntu.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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kalsound.h"
#include "kalbuffer.h"
#include <sndfile.h>
#include <KDE/KApplication>
#include <KDE/KDebug>
#include "kalengine.h"
class KALSoundPrivate
{
public:
KALBuffer *buffer;
ALuint source;
ALfloat x;
ALfloat y;
ALfloat z;
ALfloat volume;
ALfloat pitch;
};
KALSound::KALSound(QObject * parent)
:QObject(parent),
d(new KALSoundPrivate)
{
init();
d->buffer= new KALBuffer;
}
KALSound::KALSound(const QString &soundFile, QObject *parent)
: QObject(parent),
d(new KALSoundPrivate)
{
init();
d->buffer = new KALBuffer;
load(soundFile);
}
KALSound::KALSound(KALBuffer *buffer, QObject *parent)
:QObject(parent),
d(new KALSoundPrivate)
{
init();
load(buffer);
}
KALSound::KALSound(ALuint buffer, QObject *parent)
:QObject(parent),
d(new KALSoundPrivate)
{
init();
load(buffer);
}
KALSound::~KALSound()
{
alDeleteSources(1, &d->source);
delete d;
}
void KALSound::load (const QString &soundFile)
{
d->buffer->setBuffer(soundFile);
setupSource();
}
void KALSound::load(KALBuffer * buffer) {
d->buffer = buffer;
setupSource();
}
void KALSound::load(ALuint buffer) {
d->buffer = new KALBuffer(buffer);
setupSource();
}
void KALSound::init()
{
d->source=0;
d->x=0;
d->y=0;
d->z=0;
d->volume=0;
d->pitch=0;
}
void KALSound::setupSource()
{
alGenSources(1, &d->source); // Generate the source to play the buffer with
alSourcei(d->source, AL_BUFFER, d->buffer->buffer()); // Attach source to buffer
if (alGetError() != AL_NO_ERROR) {
kDebug() << "Could not process sound while generating source:" << alGetError();
return;
}
if (!d->source) {
kDebug() << "Could not process sound: generated source empty.";
return;
}
}
ALfloat KALSound::elapsedTime()const
{
ALfloat seconds = 0.f;
alGetSourcef(d->source, AL_SEC_OFFSET, &seconds);
return seconds;
}
ALint KALSound::status()const
{
ALint status;
alGetSourcei(d->source, AL_SOURCE_STATE, &status);
return status;
}
void KALSound::setLoop(bool enabled)
{
alSourcei(d->source, AL_LOOPING, enabled);
}
ALfloat KALSound::x()const
{
return d->x;
}
ALfloat KALSound::y()const
{
return d->y;
}
ALfloat KALSound::z()const
{
return d->z;
}
ALfloat KALSound::volume()const
{
return d->volume;
}
ALfloat KALSound::pitch()const
{
return d->pitch;
}
void KALSound::setPosition(ALfloat x, ALfloat y, ALfloat z)
{
d->x = x;
d->y = y;
d->z = z;
ALfloat listenerPosition[] = { x, y, z };
alSourcefv(d->source, AL_POSITION, listenerPosition);
}
void KALSound::setVolume(ALfloat volume)
{
d->volume = volume;
alSourcef(d->source, AL_GAIN, volume);
}
void KALSound::setPitch(ALfloat pitch)
{
d->pitch = pitch;
alSourcef(d->source, AL_PITCH, pitch);
}
void KALSound::play()
{
alSourcePlay(d->source);
}
void KALSound::pause()
{
alSourcePause(d->source);
}
void KALSound::stop()
{
alSourceStop(d->source);
}
void KALSound::rewind()
{
alSourceRewind(d->source);
}
void KALSound::setMinVolume(ALfloat min)
{
alSourcef(d->source, AL_MIN_GAIN, min);
}
void KALSound::setMaxVolume(ALfloat max)
{
alSourcef(d->source, AL_MAX_GAIN, max);
}
void KALSound::setVelocity(ALfloat vx, ALfloat vy, ALfloat vz)
{
ALfloat velocity[] = { vx, vy, vz };
alSourcefv(d->source, AL_VELOCITY, velocity);
}
void KALSound::setDirection(ALfloat dx, ALfloat dy, ALfloat dz)
{
ALfloat direction[] = { dx, dy, dz };
alSourcefv(d->source, AL_POSITION, direction);
}
void KALSound::setTimePosition(ALfloat time)
{
alSourcef(d->source, AL_SEC_OFFSET, time);
}
ALfloat KALSound::duration()const
{
return d->buffer->duration();
}
ALuint KALSound::source()const {
return d->source;
}
<commit_msg>remove unused kapplication include<commit_after>/*
* This file is part of the Gluon project.
* Copyright (C) 2009 Sacha Schutz <istdasklar@free.fr>
* Copyright (C) 2009 Guillaume Martres <smarter@ubuntu.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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kalsound.h"
#include "kalbuffer.h"
#include <sndfile.h>
#include <KDE/KDebug>
#include "kalengine.h"
class KALSoundPrivate
{
public:
KALBuffer *buffer;
ALuint source;
ALfloat x;
ALfloat y;
ALfloat z;
ALfloat volume;
ALfloat pitch;
};
KALSound::KALSound(QObject * parent)
:QObject(parent),
d(new KALSoundPrivate)
{
init();
d->buffer= new KALBuffer;
}
KALSound::KALSound(const QString &soundFile, QObject *parent)
: QObject(parent),
d(new KALSoundPrivate)
{
init();
d->buffer = new KALBuffer;
load(soundFile);
}
KALSound::KALSound(KALBuffer *buffer, QObject *parent)
:QObject(parent),
d(new KALSoundPrivate)
{
init();
load(buffer);
}
KALSound::KALSound(ALuint buffer, QObject *parent)
:QObject(parent),
d(new KALSoundPrivate)
{
init();
load(buffer);
}
KALSound::~KALSound()
{
alDeleteSources(1, &d->source);
delete d;
}
void KALSound::load (const QString &soundFile)
{
d->buffer->setBuffer(soundFile);
setupSource();
}
void KALSound::load(KALBuffer * buffer) {
d->buffer = buffer;
setupSource();
}
void KALSound::load(ALuint buffer) {
d->buffer = new KALBuffer(buffer);
setupSource();
}
void KALSound::init()
{
d->source=0;
d->x=0;
d->y=0;
d->z=0;
d->volume=0;
d->pitch=0;
}
void KALSound::setupSource()
{
alGenSources(1, &d->source); // Generate the source to play the buffer with
alSourcei(d->source, AL_BUFFER, d->buffer->buffer()); // Attach source to buffer
if (alGetError() != AL_NO_ERROR) {
kDebug() << "Could not process sound while generating source:" << alGetError();
return;
}
if (!d->source) {
kDebug() << "Could not process sound: generated source empty.";
return;
}
}
ALfloat KALSound::elapsedTime()const
{
ALfloat seconds = 0.f;
alGetSourcef(d->source, AL_SEC_OFFSET, &seconds);
return seconds;
}
ALint KALSound::status()const
{
ALint status;
alGetSourcei(d->source, AL_SOURCE_STATE, &status);
return status;
}
void KALSound::setLoop(bool enabled)
{
alSourcei(d->source, AL_LOOPING, enabled);
}
ALfloat KALSound::x()const
{
return d->x;
}
ALfloat KALSound::y()const
{
return d->y;
}
ALfloat KALSound::z()const
{
return d->z;
}
ALfloat KALSound::volume()const
{
return d->volume;
}
ALfloat KALSound::pitch()const
{
return d->pitch;
}
void KALSound::setPosition(ALfloat x, ALfloat y, ALfloat z)
{
d->x = x;
d->y = y;
d->z = z;
ALfloat listenerPosition[] = { x, y, z };
alSourcefv(d->source, AL_POSITION, listenerPosition);
}
void KALSound::setVolume(ALfloat volume)
{
d->volume = volume;
alSourcef(d->source, AL_GAIN, volume);
}
void KALSound::setPitch(ALfloat pitch)
{
d->pitch = pitch;
alSourcef(d->source, AL_PITCH, pitch);
}
void KALSound::play()
{
alSourcePlay(d->source);
}
void KALSound::pause()
{
alSourcePause(d->source);
}
void KALSound::stop()
{
alSourceStop(d->source);
}
void KALSound::rewind()
{
alSourceRewind(d->source);
}
void KALSound::setMinVolume(ALfloat min)
{
alSourcef(d->source, AL_MIN_GAIN, min);
}
void KALSound::setMaxVolume(ALfloat max)
{
alSourcef(d->source, AL_MAX_GAIN, max);
}
void KALSound::setVelocity(ALfloat vx, ALfloat vy, ALfloat vz)
{
ALfloat velocity[] = { vx, vy, vz };
alSourcefv(d->source, AL_VELOCITY, velocity);
}
void KALSound::setDirection(ALfloat dx, ALfloat dy, ALfloat dz)
{
ALfloat direction[] = { dx, dy, dz };
alSourcefv(d->source, AL_POSITION, direction);
}
void KALSound::setTimePosition(ALfloat time)
{
alSourcef(d->source, AL_SEC_OFFSET, time);
}
ALfloat KALSound::duration()const
{
return d->buffer->duration();
}
ALuint KALSound::source()const {
return d->source;
}
<|endoftext|>
|
<commit_before>/*
* NotebookWorkingDir.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRmdNotebook.hpp"
#include "NotebookWorkingDir.hpp"
#include <r/RExec.hpp>
#include <core/FilePath.hpp>
#include <session/SessionSourceDatabase.hpp>
#include <session/SessionModuleContext.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
DirCapture::DirCapture():
warned_(false)
{
}
DirCapture::~DirCapture()
{
}
Error DirCapture::connectDir(const std::string& docId,
const core::FilePath& workingDir)
{
if (workingDir.exists())
{
// prefer manually specified working directory
workingDir_ = workingDir;
}
else
{
// no manually specified dir; use working directory to doc path, if it
// has one
std::string docPath;
source_database::getPath(docId, &docPath);
if (!docPath.empty())
{
workingDir_ = module_context::resolveAliasedPath(docPath).parent();
}
}
if (!workingDir_.empty())
{
// if we have a working directory, switch to it, and save directory we're
// changing from (so we can detect changes)
FilePath currentDir = FilePath::safeCurrentPath(workingDir_);
if (currentDir != workingDir_)
{
Error error = FilePath::makeCurrent(workingDir_.absolutePath());
if (error)
return error;
}
prevWorkingDir_ = currentDir.absolutePath();
}
NotebookCapture::connect();
return Success();
}
void DirCapture::disconnect()
{
// restore working directory, if we saved one
if (connected() && !prevWorkingDir_.empty())
{
Error error = FilePath::makeCurrent(prevWorkingDir_);
if (error)
LOG_ERROR(error);
}
NotebookCapture::disconnect();
}
void DirCapture::onExprComplete()
{
if (!warned_ && !workingDir_.empty())
{
// raise a warning when changing a working directory inside the notebook
// (this leads to unexpected behavior)
FilePath currentDir = FilePath::safeCurrentPath(workingDir_);
if (!currentDir.isEquivalentTo(workingDir_))
{
r::exec::warning("The working directory was changed to " +
currentDir.absolutePath() + " inside a notebook chunk. The "
"working directory will be reset when the chunk is finished "
"running. Use the knitr root.dir option in the setup chunk "
"to change the working directory for notebook chunks.");
// don't show warning more than once per chunk
warned_ = true;
}
}
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>include newline in notebook working dir message<commit_after>/*
* NotebookWorkingDir.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRmdNotebook.hpp"
#include "NotebookWorkingDir.hpp"
#include <r/RExec.hpp>
#include <core/FilePath.hpp>
#include <session/SessionSourceDatabase.hpp>
#include <session/SessionModuleContext.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
DirCapture::DirCapture():
warned_(false)
{
}
DirCapture::~DirCapture()
{
}
Error DirCapture::connectDir(const std::string& docId,
const core::FilePath& workingDir)
{
if (workingDir.exists())
{
// prefer manually specified working directory
workingDir_ = workingDir;
}
else
{
// no manually specified dir; use working directory to doc path, if it
// has one
std::string docPath;
source_database::getPath(docId, &docPath);
if (!docPath.empty())
{
workingDir_ = module_context::resolveAliasedPath(docPath).parent();
}
}
if (!workingDir_.empty())
{
// if we have a working directory, switch to it, and save directory we're
// changing from (so we can detect changes)
FilePath currentDir = FilePath::safeCurrentPath(workingDir_);
if (currentDir != workingDir_)
{
Error error = FilePath::makeCurrent(workingDir_.absolutePath());
if (error)
return error;
}
prevWorkingDir_ = currentDir.absolutePath();
}
NotebookCapture::connect();
return Success();
}
void DirCapture::disconnect()
{
// restore working directory, if we saved one
if (connected() && !prevWorkingDir_.empty())
{
Error error = FilePath::makeCurrent(prevWorkingDir_);
if (error)
LOG_ERROR(error);
}
NotebookCapture::disconnect();
}
void DirCapture::onExprComplete()
{
if (!warned_ && !workingDir_.empty())
{
// raise a warning when changing a working directory inside the notebook
// (this leads to unexpected behavior)
FilePath currentDir = FilePath::safeCurrentPath(workingDir_);
if (!currentDir.isEquivalentTo(workingDir_))
{
r::exec::warning("The working directory was changed to " +
currentDir.absolutePath() + " inside a notebook chunk. The "
"working directory will be reset when the chunk is finished "
"running. Use the knitr root.dir option in the setup chunk "
"to change the working directory for notebook chunks.\n");
// don't show warning more than once per chunk
warned_ = true;
}
}
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|>
|
<commit_before>/// HEADER
#include "pointmatrix_to_pointcloud.h"
/// PROJECT
#include <csapex_point_cloud/point_cloud_message.h>
#include <csapex/model/connector_in.h>
#include <csapex/model/connector_out.h>
#include <utils_param/parameter_factory.h>
#include <csapex_vision/cv_mat_message.h>
/// SYSTEM
#include <csapex/utility/register_apex_plugin.h>
#include <pcl/point_types.h>
#include <pcl/conversions.h>
CSAPEX_REGISTER_CLASS(csapex::PointmatrixToPointcloud, csapex::Node)
using namespace csapex;
using namespace csapex::connection_types;
namespace implementation {
inline void convert(const cv::Mat &matrix, pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud)
{
if(matrix.type() != CV_32FC3) {
throw std::runtime_error("3Channel float matrix required!");
}
cloud.reset(new pcl::PointCloud<pcl::PointXYZ>);
cloud->height = matrix.rows;
cloud->width = matrix.cols;
for(int i = 0 ; i < matrix.rows ; ++i) {
for(int j = 0 ; j < matrix.cols ; ++j) {
pcl::PointXYZ pt;
pt.x = matrix.at<float>(i, (j * 3 + 0));
pt.y = matrix.at<float>(i, (j * 3 + 1));
pt.z = matrix.at<float>(i, (j * 3 + 2));
cloud->push_back(pt);
}
}
}
}
PointmatrixToPointcloud::PointmatrixToPointcloud()
{
}
void PointmatrixToPointcloud::process()
{
CvMatMessage::Ptr in = input_->getMessage<connection_types::CvMatMessage>();
PointCloudMessage::Ptr out(new PointCloudMessage);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
implementation::convert(in->value, cloud);
out->value = cloud;
output_->publish(out);
}
void PointmatrixToPointcloud::setup()
{
setSynchronizedInputs(true);
input_ = addInput<CvMatMessage>("Point Matrix");
output_ = addOutput<PointCloudMessage>("PointCloud");
}
<commit_msg>fixed bug: with and height of pointcloud has to be asigned ater the points are pushed in the cloud other wise height will be 1<commit_after>/// HEADER
#include "pointmatrix_to_pointcloud.h"
/// PROJECT
#include <csapex_point_cloud/point_cloud_message.h>
#include <csapex/model/connector_in.h>
#include <csapex/model/connector_out.h>
#include <utils_param/parameter_factory.h>
#include <csapex_vision/cv_mat_message.h>
/// SYSTEM
#include <csapex/utility/register_apex_plugin.h>
#include <pcl/point_types.h>
#include <pcl/conversions.h>
CSAPEX_REGISTER_CLASS(csapex::PointmatrixToPointcloud, csapex::Node)
using namespace csapex;
using namespace csapex::connection_types;
namespace implementation {
inline void convert(const cv::Mat &matrix, pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud)
{
if(matrix.type() != CV_32FC3) {
throw std::runtime_error("3Channel float matrix required!");
}
cloud.reset(new pcl::PointCloud<pcl::PointXYZ>);
for(int i = 0 ; i < matrix.rows ; ++i) {
for(int j = 0 ; j < matrix.cols ; ++j) {
pcl::PointXYZ pt;
pt.x = matrix.at<float>(i, (j * 3 + 0));
pt.y = matrix.at<float>(i, (j * 3 + 1));
pt.z = matrix.at<float>(i, (j * 3 + 2));
cloud->push_back(pt);
}
}
cloud->height = matrix.rows;
cloud->width = matrix.cols;
cloud->is_dense = false;
}
}
PointmatrixToPointcloud::PointmatrixToPointcloud()
{
}
void PointmatrixToPointcloud::process()
{
CvMatMessage::Ptr in = input_->getMessage<connection_types::CvMatMessage>();
PointCloudMessage::Ptr out(new PointCloudMessage);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
implementation::convert(in->value, cloud);
out->value = cloud;
output_->publish(out);
}
void PointmatrixToPointcloud::setup()
{
setSynchronizedInputs(true);
input_ = addInput<CvMatMessage>("Point Matrix");
output_ = addOutput<PointCloudMessage>("PointCloud");
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: schemabuilder.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2003-03-19 16:18:49 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_BACKEND_SCHEMABUILDER_HXX
#define CONFIGMGR_BACKEND_SCHEMABUILDER_HXX
#ifndef CONFIGMGR_BACKEND_MERGEDCOMPONENTDATA_HXX
#include "mergedcomponentdata.hxx"
#endif
#ifndef CONFIGMGR_BACKEND_COMPONENTDATAHELPER_HXX
#include "componentdatahelper.hxx"
#endif
#ifndef CONFIGMGR_BACKEND_MERGEDDATAPROVIDER_HXX
#include "mergeddataprovider.hxx"
#endif
#include <drafts/com/sun/star/configuration/backend/XSchemaHandler.hpp>
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
namespace configmgr
{
// -----------------------------------------------------------------------------
class OTreeNodeFactory;
// -----------------------------------------------------------------------------
namespace backend
{
// -----------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace beans = ::com::sun::star::beans;
namespace container = ::com::sun::star::container;
namespace backenduno = ::drafts::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------
typedef ::cppu::WeakImplHelper1<backenduno::XSchemaHandler> SchemaBuilder_Base;
class SchemaBuilder
: public SchemaBuilder_Base
{
public:
SchemaBuilder( const OUString& aExpectedComponentName, ITemplateDataProvider* aTemplateProvider = NULL );
virtual ~SchemaBuilder();
// checking the result
bool isDone() const { return m_aContext.isDone(); }
MergedComponentData & result();
MergedComponentData const & result() const;
// XSchemaHandler
public:
virtual void SAL_CALL
startSchema( )
throw (MalformedDataException, uno::RuntimeException);
virtual void SAL_CALL
endSchema( )
throw (MalformedDataException, uno::RuntimeException);
virtual void SAL_CALL
importComponent( const OUString& aName )
throw (MalformedDataException, container::NoSuchElementException, lang::IllegalArgumentException, uno::RuntimeException);
virtual void SAL_CALL
startComponent( const OUString& aName )
throw (MalformedDataException, container::ElementExistException, lang::IllegalArgumentException, lang::NoSupportException, uno::RuntimeException);
virtual void SAL_CALL
endComponent( )
throw (MalformedDataException, lang::NoSupportException, uno::RuntimeException);
virtual void SAL_CALL
startGroupTemplate( const TemplateIdentifier& aTemplate, sal_Int16 aAttributes )
throw (MalformedDataException, container::ElementExistException, lang::IllegalArgumentException, lang::NoSupportException, uno::RuntimeException);
virtual void SAL_CALL
startSetTemplate( const TemplateIdentifier& aTemplate, sal_Int16 aAttributes, const TemplateIdentifier& aItemType )
throw (MalformedDataException, container::ElementExistException, container::NoSuchElementException, lang::IllegalArgumentException, lang::NoSupportException, uno::RuntimeException);
virtual void SAL_CALL
endTemplate( )
throw (MalformedDataException, lang::NoSupportException, uno::RuntimeException);
virtual void SAL_CALL
startGroup( const OUString& aName, sal_Int16 aAttributes )
throw (MalformedDataException, container::ElementExistException, lang::IllegalArgumentException, uno::RuntimeException);
virtual void SAL_CALL
startSet( const OUString& aName, sal_Int16 aAttributes, const TemplateIdentifier& aItemType )
throw (MalformedDataException, container::ElementExistException, container::NoSuchElementException, lang::IllegalArgumentException, uno::RuntimeException);
virtual void SAL_CALL
endNode( )
throw (MalformedDataException, uno::RuntimeException);
virtual void SAL_CALL
addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
throw (MalformedDataException, beans::PropertyExistException, beans::IllegalTypeException, lang::IllegalArgumentException, uno::RuntimeException);
virtual void SAL_CALL
addPropertyWithDefault( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aDefaultValue )
throw (MalformedDataException, beans::PropertyExistException, beans::IllegalTypeException, lang::IllegalArgumentException, uno::RuntimeException);
virtual void SAL_CALL
addInstance( const OUString& aName, const TemplateIdentifier& aTemplate )
throw (MalformedDataException, container::ElementExistException, container::NoSuchElementException, lang::IllegalArgumentException, uno::RuntimeException);
virtual void SAL_CALL
addItemType( const TemplateIdentifier& aItemType )
throw (MalformedDataException, container::NoSuchElementException, lang::IllegalArgumentException, uno::RuntimeException);
private:
static node::Attributes getComponentRootAttributes();
static node::Attributes getTemplateBaseAttributes();
node::Attributes makePropertyAttributes(sal_Int16 aSchemaAttributes);
bool isExtensible(sal_Int16 aSchemaAttributes);
void substituteInstances();
private:
MergedComponentData m_aData;
DataBuilderContext m_aContext;
ComponentDataFactory m_aFactory;
ITemplateDataProvider * m_aTemplateProvider;
};
// -----------------------------------------------------------------------------
} // namespace backend
// -----------------------------------------------------------------------------
} // namespace configmgr
#endif
<commit_msg>INTEGRATION: CWS configapi01 (1.3.10); FILE MERGED 2003/04/10 15:47:11 jb 1.3.10.1: #1077715# Move configuration backend API out of drafts; adjust to API changes<commit_after>/*************************************************************************
*
* $RCSfile: schemabuilder.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2003-04-17 13:18:07 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_BACKEND_SCHEMABUILDER_HXX
#define CONFIGMGR_BACKEND_SCHEMABUILDER_HXX
#ifndef CONFIGMGR_BACKEND_MERGEDCOMPONENTDATA_HXX
#include "mergedcomponentdata.hxx"
#endif
#ifndef CONFIGMGR_BACKEND_COMPONENTDATAHELPER_HXX
#include "componentdatahelper.hxx"
#endif
#ifndef CONFIGMGR_BACKEND_MERGEDDATAPROVIDER_HXX
#include "mergeddataprovider.hxx"
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMAHANDLER_HPP_
#include <com/sun/star/configuration/backend/XSchemaHandler.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
namespace configmgr
{
// -----------------------------------------------------------------------------
class OTreeNodeFactory;
// -----------------------------------------------------------------------------
namespace backend
{
// -----------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace backenduno = ::com::sun::star::configuration::backend;
using backenduno::MalformedDataException;
// -----------------------------------------------------------------------------
typedef ::cppu::WeakImplHelper1<backenduno::XSchemaHandler> SchemaBuilder_Base;
class SchemaBuilder
: public SchemaBuilder_Base
{
public:
SchemaBuilder( const OUString& aExpectedComponentName, ITemplateDataProvider* aTemplateProvider = NULL );
virtual ~SchemaBuilder();
// checking the result
bool isDone() const { return m_aContext.isDone(); }
MergedComponentData & result();
MergedComponentData const & result() const;
// XSchemaHandler
public:
virtual void SAL_CALL
startSchema( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
endSchema( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
importComponent( const OUString& aName )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
startComponent( const OUString& aName )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
endComponent( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
startGroupTemplate( const TemplateIdentifier& aTemplate, sal_Int16 aAttributes )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
startSetTemplate( const TemplateIdentifier& aTemplate, sal_Int16 aAttributes, const TemplateIdentifier& aItemType )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
endTemplate( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
startGroup( const OUString& aName, sal_Int16 aAttributes )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
startSet( const OUString& aName, sal_Int16 aAttributes, const TemplateIdentifier& aItemType )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
endNode( )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
addPropertyWithDefault( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aDefaultValue )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
addInstance( const OUString& aName, const TemplateIdentifier& aTemplate )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
virtual void SAL_CALL
addItemType( const TemplateIdentifier& aItemType )
throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);
private:
static node::Attributes getComponentRootAttributes();
static node::Attributes getTemplateBaseAttributes();
node::Attributes makePropertyAttributes(sal_Int16 aSchemaAttributes);
bool isExtensible(sal_Int16 aSchemaAttributes);
void substituteInstances();
private:
MergedComponentData m_aData;
DataBuilderContext m_aContext;
ComponentDataFactory m_aFactory;
ITemplateDataProvider * m_aTemplateProvider;
};
// -----------------------------------------------------------------------------
} // namespace backend
// -----------------------------------------------------------------------------
} // namespace configmgr
#endif
<|endoftext|>
|
<commit_before>#ifdef _MSC_VER
#include <filesystem>
#endif
#include <map>
#include <babylon/core/string.h>
#include <imgui_utils/icons_font_awesome_5.h>
#include <imgui_utils/imgui_utils.h>
#include <babylon/imgui_babylon/sample_list_page.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <imgui.h>
#include <babylon/inspector/inspector.h>
#include <babylon/samples/samples_index.h>
#ifdef _WIN32
#include <windows.h>
#endif // _WIN32
namespace
{
std::string to_snake_case(const std::string &sPascalCase)
{
std::stringstream ss;
bool first = true;
for (auto c : sPascalCase)
{
if (std::tolower(c) != c)
{
if (!first)
ss << "_";
ss << static_cast<unsigned char>(std::tolower(c));
}
else
ss << c;
first = false;
}
return ss.str();
}
const std::string screenshotsFolderCurrent = "../../../assets/screenshots/samples_current/";
const std::string screenshotsFolderOriginal = "../../../assets/screenshots/samples/";
} // end anonymous namespace
namespace BABYLON {
namespace
{
void openBrowser(const std::string &url)
{
#ifndef _WIN32
std::string cmd = std::string("open ") + url;
system(cmd.c_str());
#else
ShellExecute(0, 0, url.c_str(), 0, 0, SW_SHOW);
#endif
}
void openFile(const std::string &filename)
{
#ifndef _WIN32
std::string cmd = std::string("open ") + filename;
system(cmd.c_str());
#else
std::string canonical_path = std::filesystem::canonical(std::filesystem::path(filename)).string();
ShellExecute(0, 0, canonical_path.c_str(), 0, 0, SW_SHOW);
#endif
}
}
using namespace BABYLON::Samples;
class SampleListPageImpl
{
public:
using CategoryName = std::string;
using SampleName = std::string;
SampleListPageImpl()
{
for (const std::string & sample : _samplesIndex.getSampleNames())
_samplesInfos[sample] = _samplesIndex.getSampleInfo(sample);
fillMatchingSamples();
}
void render()
{
render_filter();
ImGui::Checkbox("Show original screenshots", &_showOriginalScreenshots);
ImGui::SameLine();
ImGui::Checkbox("Show current screenshots", &_showCurrentScreenshots);
ImGui::Separator();
render_list();
ImGui::NewLine();
ImGui::Separator();
ImGui::NewLine();
}
SampleListPage::CallbackNewRenderableScene OnNewRenderableScene;
private:
void render_filter()
{
bool changed = false;
ImGui::Text("Filter");
if (ImGui::InputText_String("", _query.query))
changed = true;
if (ImGui::Checkbox("Include disabled", &_query.includeDisabled))
changed = true;
ImGui::SameLine();
if (ImGui::Checkbox("Include failing", &_query.includeFailures))
changed = true;
ImGui::SameLine();
if (ImGui::Checkbox("Only failing", &_query.onlyFailures))
changed = true;
if (changed)
fillMatchingSamples();
}
void render_list()
{
enum class CollapseMode
{
None,
CollapseAll,
ExpandAll
};
CollapseMode collapseMode = CollapseMode::None;
if (ImGui::Button("Collapse All"))
collapseMode = CollapseMode::CollapseAll;
ImGui::SameLine();
if (ImGui::Button("Expand All"))
collapseMode = CollapseMode::ExpandAll;
ImGui::BeginChild("Child1");
for (const auto & kv : _matchingSamples)
{
CategoryName category = kv.first;
auto samples = kv.second;
if (!samples.empty())
{
std::string header = category + " (" + std::to_string(samples.size()) + ")";
if (collapseMode == CollapseMode::CollapseAll)
ImGui::SetNextItemOpen(false);
if (collapseMode == CollapseMode::ExpandAll)
ImGui::SetNextItemOpen(true);
if (ImGui::CollapsingHeader(header.c_str(), ImGuiTreeNodeFlags_DefaultOpen))
{
for (const std::string & sample : samples)
{
//ImGui::Text("%s", sample.c_str());
guiOneSample(sample);
ImGui::Separator();
}
}
}
}
ImGui::EndChild();
}
void guiOneSampleInfos(const std::string & sampleName)
{
const auto & sampleInfo = _samplesInfos.at(sampleName);
std::string runLabel = std::string(ICON_FA_PLAY_CIRCLE " Run##") + sampleName;
if (ImGui::Button(runLabel.c_str()))
{
if (OnNewRenderableScene)
{
BABYLON::ICanvas *dummyCanvas = nullptr;
auto scene = _samplesIndex.createRenderableScene(sampleName, dummyCanvas);
OnNewRenderableScene(std::move(scene));
}
if (Inspector::OnSampleChanged)
Inspector::OnSampleChanged(sampleName);
}
std::string btnHeaderString = std::string(ICON_FA_EYE "##") + sampleInfo.HeaderFile;
if (ImGui::Button(btnHeaderString.c_str()))
openFile(sampleInfo.HeaderFile);
ImGui::SameLine();
ImGui::TextDisabled(".h : %s", sampleInfo.HeaderFile.c_str());
std::string btnSourceString = std::string(ICON_FA_EYE "##") + sampleInfo.SourceFile;
if (ImGui::Button(btnSourceString.c_str()))
openFile(sampleInfo.SourceFile);
ImGui::SameLine();
ImGui::TextDisabled(".cpp: %s", sampleInfo.SourceFile.c_str());
if (!sampleInfo.Links.empty()) {
for (auto link : sampleInfo.Links) {
std::string btnUrlString = std::string(ICON_FA_EXTERNAL_LINK_ALT "##") + link;
if (ImGui::Button(btnUrlString.c_str()))
openBrowser(link);
ImGui::SameLine();
ImVec4 linkColor(0.5f, 0.5f, 0.95f, 1.f);
ImGui::TextColored(linkColor, "%s", link.c_str());
}
}
}
void guiOneSample(const std::string &sampleName)
{
const auto & sampleInfo = _samplesInfos[sampleName];
std::string currentScreenshotFile = screenshotsFolderCurrent + sampleName + ".jpg";
std::string sample_snake = to_snake_case(sampleName);
std::string originalScreenshotFile = screenshotsFolderOriginal + sample_snake + ".png";
if (_showCurrentScreenshots)
{
ImGui::BeginGroup();
ImGuiUtils::ImageFromFile(currentScreenshotFile);
if (_showOriginalScreenshots && _showCurrentScreenshots)
ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 0.7f), "Current(c++)");
ImGui::EndGroup();
ImGui::SameLine();
}
if (_showOriginalScreenshots)
{
ImGui::BeginGroup();
ImGuiUtils::ImageFromFile(originalScreenshotFile);
if (_showOriginalScreenshots && _showCurrentScreenshots)
ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 0.7f), "Original(js)");
ImGui::EndGroup();
ImGui::SameLine();
}
ImGui::BeginGroup();
ImGui::Text("%s", sampleName.c_str());
ImGui::TextWrapped("%s", sampleInfo.Brief.c_str());
auto failure = _samplesIndex.doesSampleFail(sampleName);
if (failure)
{
ImGui::TextColored(ImVec4(0.9f, 0.4f, 0.3f, 1.f), "Failure: %s",
SampleFailureReason_Str(failure.value()).c_str()
);
}
guiOneSampleInfos(sampleName);
ImGui::EndGroup();
ImGui::SameLine();
}
bool doesSampleMatchQuery(const CategoryName & categoryName, const SampleName & sampleName)
{
std::vector<std::string> search_items = BABYLON::String::split(_query.query, ' ');
bool doesMatch = true;
{
std::string all = BABYLON::String::toLowerCase(categoryName + " / " + sampleName);
for (const auto &item : search_items)
if (!BABYLON::String::contains(all, BABYLON::String::toLowerCase(item)))
doesMatch = false;
}
if (!_query.includeDisabled)
if (!_samplesIndex.isSampleEnabled(sampleName))
doesMatch = false;
if (_query.onlyFailures)
{
if (!_samplesIndex.doesSampleFail(sampleName))
doesMatch = false;
}
else if (!_query.includeFailures)
if (_samplesIndex.doesSampleFail(sampleName))
doesMatch = false;
return doesMatch;
}
void fillMatchingSamples()
{
_matchingSamples.clear();
for (CategoryName category : _samplesIndex.getCategoryNames())
{
std::vector<SampleName> s;
for (SampleName sample : _samplesIndex.getSampleNamesInCategory(category))
{
if (doesSampleMatchQuery(category, sample))
s.push_back(sample);
_matchingSamples[category] = s;
}
}
}
std::map<SampleName, SampleInfo> _samplesInfos;
SamplesIndex _samplesIndex;
std::map<CategoryName, std::vector<SampleName>> _matchingSamples;
struct {
std::string query = "";
bool includeFailures = false;
bool onlyFailures = false;
bool includeDisabled = true;
} _query;
bool _showOriginalScreenshots = false;
bool _showCurrentScreenshots = true;
};
SampleListPage::SampleListPage()
{
pImpl = std::make_unique<SampleListPageImpl>();
}
SampleListPage::~SampleListPage() = default;
void SampleListPage::render()
{
pImpl->OnNewRenderableScene = OnNewRenderableScene;
pImpl->render();
}
} // end of namespace BABYLON
<commit_msg>sample_list_page : show relative file paths<commit_after>#ifdef _MSC_VER
#include <filesystem>
#endif
#include <map>
#include <babylon/core/string.h>
#include <babylon/core/filesystem.h>
#include <imgui_utils/icons_font_awesome_5.h>
#include <imgui_utils/imgui_utils.h>
#include <babylon/imgui_babylon/sample_list_page.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <imgui.h>
#include <babylon/inspector/inspector.h>
#include <babylon/samples/samples_index.h>
#ifdef _WIN32
#include <windows.h>
#endif // _WIN32
namespace
{
std::string to_snake_case(const std::string &sPascalCase)
{
std::stringstream ss;
bool first = true;
for (auto c : sPascalCase)
{
if (std::tolower(c) != c)
{
if (!first)
ss << "_";
ss << static_cast<unsigned char>(std::tolower(c));
}
else
ss << c;
first = false;
}
return ss.str();
}
const std::string screenshotsFolderCurrent = "../../../assets/screenshots/samples_current/";
const std::string screenshotsFolderOriginal = "../../../assets/screenshots/samples/";
const std::string repositoryPath = BABYLON::Filesystem::absolutePath("../../../");
std::string repositoryRelativePath(const std::string & path)
{
std::string absPath = BABYLON::Filesystem::absolutePath(path);
std::string fromRepo = BABYLON::String::removeSubstring(absPath, repositoryPath);
return fromRepo;
}
} // end anonymous namespace
namespace BABYLON {
namespace
{
void openBrowser(const std::string &url)
{
#ifndef _WIN32
std::string cmd = std::string("open ") + url;
system(cmd.c_str());
#else
ShellExecute(0, 0, url.c_str(), 0, 0, SW_SHOW);
#endif
}
void openFile(const std::string &filename)
{
#ifndef _WIN32
std::string cmd = std::string("open ") + filename;
system(cmd.c_str());
#else
std::string canonical_path = std::filesystem::canonical(std::filesystem::path(filename)).string();
ShellExecute(0, 0, canonical_path.c_str(), 0, 0, SW_SHOW);
#endif
}
}
using namespace BABYLON::Samples;
class SampleListPageImpl
{
public:
using CategoryName = std::string;
using SampleName = std::string;
SampleListPageImpl()
{
for (const std::string & sample : _samplesIndex.getSampleNames())
_samplesInfos[sample] = _samplesIndex.getSampleInfo(sample);
fillMatchingSamples();
}
void render()
{
render_filter();
ImGui::Checkbox("Show original screenshots", &_showOriginalScreenshots);
ImGui::SameLine();
ImGui::Checkbox("Show current screenshots", &_showCurrentScreenshots);
ImGui::Separator();
render_list();
ImGui::NewLine();
ImGui::Separator();
ImGui::NewLine();
}
SampleListPage::CallbackNewRenderableScene OnNewRenderableScene;
private:
void render_filter()
{
bool changed = false;
ImGui::Text("Filter");
if (ImGui::InputText_String("", _query.query))
changed = true;
if (ImGui::Checkbox("Include disabled", &_query.includeDisabled))
changed = true;
ImGui::SameLine();
if (ImGui::Checkbox("Include failing", &_query.includeFailures))
changed = true;
ImGui::SameLine();
if (ImGui::Checkbox("Only failing", &_query.onlyFailures))
changed = true;
if (changed)
fillMatchingSamples();
}
void render_list()
{
enum class CollapseMode
{
None,
CollapseAll,
ExpandAll
};
CollapseMode collapseMode = CollapseMode::None;
if (ImGui::Button("Collapse All"))
collapseMode = CollapseMode::CollapseAll;
ImGui::SameLine();
if (ImGui::Button("Expand All"))
collapseMode = CollapseMode::ExpandAll;
ImGui::BeginChild("Child1");
for (const auto & kv : _matchingSamples)
{
CategoryName category = kv.first;
auto samples = kv.second;
if (!samples.empty())
{
std::string header = category + " (" + std::to_string(samples.size()) + ")";
if (collapseMode == CollapseMode::CollapseAll)
ImGui::SetNextItemOpen(false);
if (collapseMode == CollapseMode::ExpandAll)
ImGui::SetNextItemOpen(true);
if (ImGui::CollapsingHeader(header.c_str(), ImGuiTreeNodeFlags_DefaultOpen))
{
for (const std::string & sample : samples)
{
//ImGui::Text("%s", sample.c_str());
guiOneSample(sample);
ImGui::Separator();
}
}
}
}
ImGui::EndChild();
}
void guiOneSampleInfos(const std::string & sampleName)
{
const auto & sampleInfo = _samplesInfos.at(sampleName);
std::string runLabel = std::string(ICON_FA_PLAY_CIRCLE " Run##") + sampleName;
if (ImGui::Button(runLabel.c_str()))
{
if (OnNewRenderableScene)
{
BABYLON::ICanvas *dummyCanvas = nullptr;
auto scene = _samplesIndex.createRenderableScene(sampleName, dummyCanvas);
OnNewRenderableScene(std::move(scene));
}
if (Inspector::OnSampleChanged)
Inspector::OnSampleChanged(sampleName);
}
std::string btnHeaderString = std::string(ICON_FA_EYE "##") + sampleInfo.HeaderFile;
if (ImGui::Button(btnHeaderString.c_str()))
openFile(sampleInfo.HeaderFile);
ImGui::SameLine();
ImGui::TextDisabled(".h : %s", repositoryRelativePath(sampleInfo.HeaderFile).c_str());
std::string btnSourceString = std::string(ICON_FA_EYE "##") + sampleInfo.SourceFile;
if (ImGui::Button(btnSourceString.c_str()))
openFile(sampleInfo.SourceFile);
ImGui::SameLine();
ImGui::TextDisabled(".cpp: %s", repositoryRelativePath(sampleInfo.SourceFile).c_str());
if (!sampleInfo.Links.empty()) {
for (auto link : sampleInfo.Links) {
std::string btnUrlString = std::string(ICON_FA_EXTERNAL_LINK_ALT "##") + link;
if (ImGui::Button(btnUrlString.c_str()))
openBrowser(link);
ImGui::SameLine();
ImVec4 linkColor(0.5f, 0.5f, 0.95f, 1.f);
ImGui::TextColored(linkColor, "%s", link.c_str());
}
}
}
void guiOneSample(const std::string &sampleName)
{
const auto & sampleInfo = _samplesInfos[sampleName];
std::string currentScreenshotFile = screenshotsFolderCurrent + sampleName + ".jpg";
std::string sample_snake = to_snake_case(sampleName);
std::string originalScreenshotFile = screenshotsFolderOriginal + sample_snake + ".png";
if (_showCurrentScreenshots)
{
ImGui::BeginGroup();
ImGuiUtils::ImageFromFile(currentScreenshotFile);
if (_showOriginalScreenshots && _showCurrentScreenshots)
ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 0.7f), "Current(c++)");
ImGui::EndGroup();
ImGui::SameLine();
}
if (_showOriginalScreenshots)
{
ImGui::BeginGroup();
ImGuiUtils::ImageFromFile(originalScreenshotFile);
if (_showOriginalScreenshots && _showCurrentScreenshots)
ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 0.7f), "Original(js)");
ImGui::EndGroup();
ImGui::SameLine();
}
ImGui::BeginGroup();
ImGui::Text("%s", sampleName.c_str());
ImGui::TextWrapped("%s", sampleInfo.Brief.c_str());
auto failure = _samplesIndex.doesSampleFail(sampleName);
if (failure)
{
ImGui::TextColored(ImVec4(0.9f, 0.4f, 0.3f, 1.f), "Failure: %s",
SampleFailureReason_Str(failure.value()).c_str()
);
}
guiOneSampleInfos(sampleName);
ImGui::EndGroup();
ImGui::SameLine();
}
bool doesSampleMatchQuery(const CategoryName & categoryName, const SampleName & sampleName)
{
std::vector<std::string> search_items = BABYLON::String::split(_query.query, ' ');
bool doesMatch = true;
{
std::string all = BABYLON::String::toLowerCase(categoryName + " / " + sampleName);
for (const auto &item : search_items)
if (!BABYLON::String::contains(all, BABYLON::String::toLowerCase(item)))
doesMatch = false;
}
if (!_query.includeDisabled)
if (!_samplesIndex.isSampleEnabled(sampleName))
doesMatch = false;
if (_query.onlyFailures)
{
if (!_samplesIndex.doesSampleFail(sampleName))
doesMatch = false;
}
else if (!_query.includeFailures)
if (_samplesIndex.doesSampleFail(sampleName))
doesMatch = false;
return doesMatch;
}
void fillMatchingSamples()
{
_matchingSamples.clear();
for (CategoryName category : _samplesIndex.getCategoryNames())
{
std::vector<SampleName> s;
for (SampleName sample : _samplesIndex.getSampleNamesInCategory(category))
{
if (doesSampleMatchQuery(category, sample))
s.push_back(sample);
_matchingSamples[category] = s;
}
}
}
std::map<SampleName, SampleInfo> _samplesInfos;
SamplesIndex _samplesIndex;
std::map<CategoryName, std::vector<SampleName>> _matchingSamples;
struct {
std::string query = "";
bool includeFailures = false;
bool onlyFailures = false;
bool includeDisabled = true;
} _query;
bool _showOriginalScreenshots = false;
bool _showCurrentScreenshots = true;
};
SampleListPage::SampleListPage()
{
pImpl = std::make_unique<SampleListPageImpl>();
}
SampleListPage::~SampleListPage() = default;
void SampleListPage::render()
{
pImpl->OnNewRenderableScene = OnNewRenderableScene;
pImpl->render();
}
} // end of namespace BABYLON
<|endoftext|>
|
<commit_before>/***************************************************************************
constraintmaxdaysbetweenactivitiesform.cpp - description
-------------------
begin : 2009
copyright : (C) 2009 by Lalescu Liviu
email : Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)
***************************************************************************/
/***************************************************************************
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
***************************************************************************/
#include <QMessageBox>
#include "longtextmessagebox.h"
#include "constraintmaxdaysbetweenactivitiesform.h"
#include "addconstraintmaxdaysbetweenactivitiesform.h"
#include "modifyconstraintmaxdaysbetweenactivitiesform.h"
#include <QListWidget>
#include <QScrollBar>
#include <QAbstractItemView>
ConstraintMaxDaysBetweenActivitiesForm::ConstraintMaxDaysBetweenActivitiesForm(QWidget* parent): QDialog(parent)
{
setupUi(this);
currentConstraintTextEdit->setReadOnly(true);
modifyConstraintPushButton->setDefault(true);
constraintsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
connect(constraintsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(constraintChanged(int)));
connect(addConstraintPushButton, SIGNAL(clicked()), this, SLOT(addConstraint()));
connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
connect(removeConstraintPushButton, SIGNAL(clicked()), this, SLOT(removeConstraint()));
connect(modifyConstraintPushButton, SIGNAL(clicked()), this, SLOT(modifyConstraint()));
connect(constraintsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(modifyConstraint()));
connect(teachersComboBox, SIGNAL(activated(QString)), this, SLOT(filterChanged()));
connect(studentsComboBox, SIGNAL(activated(QString)), this, SLOT(filterChanged()));
connect(subjectsComboBox, SIGNAL(activated(QString)), this, SLOT(filterChanged()));
connect(activityTagsComboBox, SIGNAL(activated(QString)), this, SLOT(filterChanged()));
connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));
centerWidgetOnScreen(this);
restoreFETDialogGeometry(this);
QSize tmp1=teachersComboBox->minimumSizeHint();
Q_UNUSED(tmp1);
QSize tmp2=studentsComboBox->minimumSizeHint();
Q_UNUSED(tmp2);
QSize tmp3=subjectsComboBox->minimumSizeHint();
Q_UNUSED(tmp3);
QSize tmp4=activityTagsComboBox->minimumSizeHint();
Q_UNUSED(tmp4);
/////////////
teachersComboBox->addItem("");
for(int i=0; i<gt.rules.teachersList.size(); i++){
Teacher* tch=gt.rules.teachersList[i];
teachersComboBox->addItem(tch->name);
}
teachersComboBox->setCurrentIndex(0);
subjectsComboBox->addItem("");
for(int i=0; i<gt.rules.subjectsList.size(); i++){
Subject* sb=gt.rules.subjectsList[i];
subjectsComboBox->addItem(sb->name);
}
subjectsComboBox->setCurrentIndex(0);
activityTagsComboBox->addItem("");
for(int i=0; i<gt.rules.activityTagsList.size(); i++){
ActivityTag* st=gt.rules.activityTagsList[i];
activityTagsComboBox->addItem(st->name);
}
activityTagsComboBox->setCurrentIndex(0);
studentsComboBox->addItem("");
for(int i=0; i<gt.rules.yearsList.size(); i++){
StudentsYear* sty=gt.rules.yearsList[i];
studentsComboBox->addItem(sty->name);
for(int j=0; j<sty->groupsList.size(); j++){
StudentsGroup* stg=sty->groupsList[j];
studentsComboBox->addItem(stg->name);
if(SHOW_SUBGROUPS_IN_COMBO_BOXES) for(int k=0; k<stg->subgroupsList.size(); k++){
StudentsSubgroup* sts=stg->subgroupsList[k];
studentsComboBox->addItem(sts->name);
}
}
}
studentsComboBox->setCurrentIndex(0);
///////////////
this->filterChanged();
}
ConstraintMaxDaysBetweenActivitiesForm::~ConstraintMaxDaysBetweenActivitiesForm()
{
saveFETDialogGeometry(this);
}
bool ConstraintMaxDaysBetweenActivitiesForm::filterOk(TimeConstraint* ctr)
{
if(ctr->type!=CONSTRAINT_MAX_DAYS_BETWEEN_ACTIVITIES)
return false;
ConstraintMaxDaysBetweenActivities* c=(ConstraintMaxDaysBetweenActivities*) ctr;
QString tn=teachersComboBox->currentText();
QString sbn=subjectsComboBox->currentText();
QString sbtn=activityTagsComboBox->currentText();
QString stn=studentsComboBox->currentText();
if(tn=="" && sbn=="" && sbtn=="" && stn=="")
return true;
bool foundTeacher=false, foundStudents=false, foundSubject=false, foundActivityTag=false;
for(int i=0; i<c->n_activities; i++){
int id=c->activitiesId[i];
Activity* act=NULL;
foreach(Activity* a, gt.rules.activitiesList)
if(a->id==id)
act=a;
if(act!=NULL){
//teacher
if(tn!=""){
bool ok2=false;
for(QStringList::Iterator it=act->teachersNames.begin(); it!=act->teachersNames.end(); it++)
if(*it == tn){
ok2=true;
break;
}
if(ok2)
foundTeacher=true;
}
else
foundTeacher=true;
//subject
if(sbn!="" && sbn!=act->subjectName)
;
else
foundSubject=true;
//activity tag
if(sbtn!="" && !act->activityTagsNames.contains(sbtn))
;
else
foundActivityTag=true;
//students
if(stn!=""){
bool ok2=false;
for(QStringList::Iterator it=act->studentsNames.begin(); it!=act->studentsNames.end(); it++)
if(*it == stn){
ok2=true;
break;
}
if(ok2)
foundStudents=true;
}
else
foundStudents=true;
}
}
if(foundTeacher && foundStudents && foundSubject && foundActivityTag)
return true;
else
return false;
}
void ConstraintMaxDaysBetweenActivitiesForm::filterChanged()
{
this->visibleConstraintsList.clear();
constraintsListWidget->clear();
for(int i=0; i<gt.rules.timeConstraintsList.size(); i++){
TimeConstraint* ctr=gt.rules.timeConstraintsList[i];
if(filterOk(ctr)){
visibleConstraintsList.append(ctr);
constraintsListWidget->addItem(ctr->getDescription(gt.rules));
}
}
if(constraintsListWidget->count()>0)
constraintsListWidget->setCurrentRow(0);
else
currentConstraintTextEdit->setPlainText(QString(""));
}
void ConstraintMaxDaysBetweenActivitiesForm::constraintChanged(int index)
{
if(index<0){
currentConstraintTextEdit->setPlainText("");
return;
}
assert(index<this->visibleConstraintsList.size());
TimeConstraint* ctr=this->visibleConstraintsList.at(index);
assert(ctr!=NULL);
currentConstraintTextEdit->setPlainText(ctr->getDetailedDescription(gt.rules));
}
void ConstraintMaxDaysBetweenActivitiesForm::addConstraint()
{
AddConstraintMaxDaysBetweenActivitiesForm form(this);
setParentAndOtherThings(&form, this);
form.exec();
filterChanged();
constraintsListWidget->setCurrentRow(constraintsListWidget->count()-1);
}
void ConstraintMaxDaysBetweenActivitiesForm::modifyConstraint()
{
int valv=constraintsListWidget->verticalScrollBar()->value();
int valh=constraintsListWidget->horizontalScrollBar()->value();
int i=constraintsListWidget->currentRow();
if(i<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint"));
return;
}
TimeConstraint* ctr=this->visibleConstraintsList.at(i);
ModifyConstraintMaxDaysBetweenActivitiesForm form(this, (ConstraintMaxDaysBetweenActivities*)ctr);
setParentAndOtherThings(&form, this);
form.exec();
filterChanged();
constraintsListWidget->verticalScrollBar()->setValue(valv);
constraintsListWidget->horizontalScrollBar()->setValue(valh);
if(i>=constraintsListWidget->count())
i=constraintsListWidget->count()-1;
if(i>=0)
constraintsListWidget->setCurrentRow(i);
else
this->constraintChanged(-1);
}
void ConstraintMaxDaysBetweenActivitiesForm::removeConstraint()
{
int i=constraintsListWidget->currentRow();
if(i<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint"));
return;
}
TimeConstraint* ctr=this->visibleConstraintsList.at(i);
QString s;
s=tr("Remove constraint?");
s+="\n\n";
s+=ctr->getDetailedDescription(gt.rules);
QListWidgetItem* item;
switch( LongTextMessageBox::confirmation( this, tr("FET confirmation"),
s, tr("Yes"), tr("No"), 0, 0, 1 ) ){
case 0: // The user clicked the OK button or pressed Enter
gt.rules.removeTimeConstraint(ctr);
visibleConstraintsList.removeAt(i);
constraintsListWidget->setCurrentRow(-1);
item=constraintsListWidget->takeItem(i);
delete item;
break;
case 1: // The user clicked the Cancel button or pressed Escape
break;
}
if(i>=constraintsListWidget->count())
i=constraintsListWidget->count()-1;
if(i>=0)
constraintsListWidget->setCurrentRow(i);
else
this->constraintChanged(-1);
}
void ConstraintMaxDaysBetweenActivitiesForm::help()
{
QString s;
s+=tr("Help about the constraint max days between activities:");
s+="\n\n";
s+=tr("This constraint was suggested for the following situation: a user needed that activities A1, A2 and A3 to be in follower days"
" (like: A1 on Tuesday, A2 on Wednesday and A3 on Thursday. So, they must be in 3 consecutive days). This is simple: add a constraint"
" max days between activities for A1, A2 and A3, with max 2 days between them. It is supposed that these activities are constrained"
" not to be in the same day by a constraint min days between activities.");
s+="\n\n";
s+=tr("So, the general situation: this constraint ensures that between each pair from the selected activities, the distance in days is at most the selected value."
" Distance = 1 day between a pair A1 and A2 means that A1 and A2 are in consecutive days (like Thursday and Friday)."
" Distance = 3 days means that A1 and A2 are 3 days apart, for instance Monday and Thursday.");
s+="\n\n";
s+=tr("Another example: teacher T wants to ensure that his activities take place in at most 4 consecutive days (so, from Monday to Thursday or from"
" Tuesday to Friday). Then, add all his activities and max days between them = 3.");
LongTextMessageBox::largeInformation(this, tr("FET help"), s);
}
<commit_msg>Minor string bug fix<commit_after>/***************************************************************************
constraintmaxdaysbetweenactivitiesform.cpp - description
-------------------
begin : 2009
copyright : (C) 2009 by Lalescu Liviu
email : Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)
***************************************************************************/
/***************************************************************************
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
***************************************************************************/
#include <QMessageBox>
#include "longtextmessagebox.h"
#include "constraintmaxdaysbetweenactivitiesform.h"
#include "addconstraintmaxdaysbetweenactivitiesform.h"
#include "modifyconstraintmaxdaysbetweenactivitiesform.h"
#include <QListWidget>
#include <QScrollBar>
#include <QAbstractItemView>
ConstraintMaxDaysBetweenActivitiesForm::ConstraintMaxDaysBetweenActivitiesForm(QWidget* parent): QDialog(parent)
{
setupUi(this);
currentConstraintTextEdit->setReadOnly(true);
modifyConstraintPushButton->setDefault(true);
constraintsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
connect(constraintsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(constraintChanged(int)));
connect(addConstraintPushButton, SIGNAL(clicked()), this, SLOT(addConstraint()));
connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
connect(removeConstraintPushButton, SIGNAL(clicked()), this, SLOT(removeConstraint()));
connect(modifyConstraintPushButton, SIGNAL(clicked()), this, SLOT(modifyConstraint()));
connect(constraintsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(modifyConstraint()));
connect(teachersComboBox, SIGNAL(activated(QString)), this, SLOT(filterChanged()));
connect(studentsComboBox, SIGNAL(activated(QString)), this, SLOT(filterChanged()));
connect(subjectsComboBox, SIGNAL(activated(QString)), this, SLOT(filterChanged()));
connect(activityTagsComboBox, SIGNAL(activated(QString)), this, SLOT(filterChanged()));
connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));
centerWidgetOnScreen(this);
restoreFETDialogGeometry(this);
QSize tmp1=teachersComboBox->minimumSizeHint();
Q_UNUSED(tmp1);
QSize tmp2=studentsComboBox->minimumSizeHint();
Q_UNUSED(tmp2);
QSize tmp3=subjectsComboBox->minimumSizeHint();
Q_UNUSED(tmp3);
QSize tmp4=activityTagsComboBox->minimumSizeHint();
Q_UNUSED(tmp4);
/////////////
teachersComboBox->addItem("");
for(int i=0; i<gt.rules.teachersList.size(); i++){
Teacher* tch=gt.rules.teachersList[i];
teachersComboBox->addItem(tch->name);
}
teachersComboBox->setCurrentIndex(0);
subjectsComboBox->addItem("");
for(int i=0; i<gt.rules.subjectsList.size(); i++){
Subject* sb=gt.rules.subjectsList[i];
subjectsComboBox->addItem(sb->name);
}
subjectsComboBox->setCurrentIndex(0);
activityTagsComboBox->addItem("");
for(int i=0; i<gt.rules.activityTagsList.size(); i++){
ActivityTag* st=gt.rules.activityTagsList[i];
activityTagsComboBox->addItem(st->name);
}
activityTagsComboBox->setCurrentIndex(0);
studentsComboBox->addItem("");
for(int i=0; i<gt.rules.yearsList.size(); i++){
StudentsYear* sty=gt.rules.yearsList[i];
studentsComboBox->addItem(sty->name);
for(int j=0; j<sty->groupsList.size(); j++){
StudentsGroup* stg=sty->groupsList[j];
studentsComboBox->addItem(stg->name);
if(SHOW_SUBGROUPS_IN_COMBO_BOXES) for(int k=0; k<stg->subgroupsList.size(); k++){
StudentsSubgroup* sts=stg->subgroupsList[k];
studentsComboBox->addItem(sts->name);
}
}
}
studentsComboBox->setCurrentIndex(0);
///////////////
this->filterChanged();
}
ConstraintMaxDaysBetweenActivitiesForm::~ConstraintMaxDaysBetweenActivitiesForm()
{
saveFETDialogGeometry(this);
}
bool ConstraintMaxDaysBetweenActivitiesForm::filterOk(TimeConstraint* ctr)
{
if(ctr->type!=CONSTRAINT_MAX_DAYS_BETWEEN_ACTIVITIES)
return false;
ConstraintMaxDaysBetweenActivities* c=(ConstraintMaxDaysBetweenActivities*) ctr;
QString tn=teachersComboBox->currentText();
QString sbn=subjectsComboBox->currentText();
QString sbtn=activityTagsComboBox->currentText();
QString stn=studentsComboBox->currentText();
if(tn=="" && sbn=="" && sbtn=="" && stn=="")
return true;
bool foundTeacher=false, foundStudents=false, foundSubject=false, foundActivityTag=false;
for(int i=0; i<c->n_activities; i++){
int id=c->activitiesId[i];
Activity* act=NULL;
foreach(Activity* a, gt.rules.activitiesList)
if(a->id==id)
act=a;
if(act!=NULL){
//teacher
if(tn!=""){
bool ok2=false;
for(QStringList::Iterator it=act->teachersNames.begin(); it!=act->teachersNames.end(); it++)
if(*it == tn){
ok2=true;
break;
}
if(ok2)
foundTeacher=true;
}
else
foundTeacher=true;
//subject
if(sbn!="" && sbn!=act->subjectName)
;
else
foundSubject=true;
//activity tag
if(sbtn!="" && !act->activityTagsNames.contains(sbtn))
;
else
foundActivityTag=true;
//students
if(stn!=""){
bool ok2=false;
for(QStringList::Iterator it=act->studentsNames.begin(); it!=act->studentsNames.end(); it++)
if(*it == stn){
ok2=true;
break;
}
if(ok2)
foundStudents=true;
}
else
foundStudents=true;
}
}
if(foundTeacher && foundStudents && foundSubject && foundActivityTag)
return true;
else
return false;
}
void ConstraintMaxDaysBetweenActivitiesForm::filterChanged()
{
this->visibleConstraintsList.clear();
constraintsListWidget->clear();
for(int i=0; i<gt.rules.timeConstraintsList.size(); i++){
TimeConstraint* ctr=gt.rules.timeConstraintsList[i];
if(filterOk(ctr)){
visibleConstraintsList.append(ctr);
constraintsListWidget->addItem(ctr->getDescription(gt.rules));
}
}
if(constraintsListWidget->count()>0)
constraintsListWidget->setCurrentRow(0);
else
currentConstraintTextEdit->setPlainText(QString(""));
}
void ConstraintMaxDaysBetweenActivitiesForm::constraintChanged(int index)
{
if(index<0){
currentConstraintTextEdit->setPlainText("");
return;
}
assert(index<this->visibleConstraintsList.size());
TimeConstraint* ctr=this->visibleConstraintsList.at(index);
assert(ctr!=NULL);
currentConstraintTextEdit->setPlainText(ctr->getDetailedDescription(gt.rules));
}
void ConstraintMaxDaysBetweenActivitiesForm::addConstraint()
{
AddConstraintMaxDaysBetweenActivitiesForm form(this);
setParentAndOtherThings(&form, this);
form.exec();
filterChanged();
constraintsListWidget->setCurrentRow(constraintsListWidget->count()-1);
}
void ConstraintMaxDaysBetweenActivitiesForm::modifyConstraint()
{
int valv=constraintsListWidget->verticalScrollBar()->value();
int valh=constraintsListWidget->horizontalScrollBar()->value();
int i=constraintsListWidget->currentRow();
if(i<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint"));
return;
}
TimeConstraint* ctr=this->visibleConstraintsList.at(i);
ModifyConstraintMaxDaysBetweenActivitiesForm form(this, (ConstraintMaxDaysBetweenActivities*)ctr);
setParentAndOtherThings(&form, this);
form.exec();
filterChanged();
constraintsListWidget->verticalScrollBar()->setValue(valv);
constraintsListWidget->horizontalScrollBar()->setValue(valh);
if(i>=constraintsListWidget->count())
i=constraintsListWidget->count()-1;
if(i>=0)
constraintsListWidget->setCurrentRow(i);
else
this->constraintChanged(-1);
}
void ConstraintMaxDaysBetweenActivitiesForm::removeConstraint()
{
int i=constraintsListWidget->currentRow();
if(i<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint"));
return;
}
TimeConstraint* ctr=this->visibleConstraintsList.at(i);
QString s;
s=tr("Remove constraint?");
s+="\n\n";
s+=ctr->getDetailedDescription(gt.rules);
QListWidgetItem* item;
switch( LongTextMessageBox::confirmation( this, tr("FET confirmation"),
s, tr("Yes"), tr("No"), 0, 0, 1 ) ){
case 0: // The user clicked the OK button or pressed Enter
gt.rules.removeTimeConstraint(ctr);
visibleConstraintsList.removeAt(i);
constraintsListWidget->setCurrentRow(-1);
item=constraintsListWidget->takeItem(i);
delete item;
break;
case 1: // The user clicked the Cancel button or pressed Escape
break;
}
if(i>=constraintsListWidget->count())
i=constraintsListWidget->count()-1;
if(i>=0)
constraintsListWidget->setCurrentRow(i);
else
this->constraintChanged(-1);
}
void ConstraintMaxDaysBetweenActivitiesForm::help()
{
QString s;
s+=tr("Help about the constraint max days between activities:");
s+="\n\n";
s+=tr("This constraint was suggested for the following situation: a user needed that activities A1, A2 and A3 to be in consecutive days"
" (like: A1 on Tuesday, A2 on Wednesday and A3 on Thursday. So, they must be in 3 consecutive days). This is simple: add a constraint"
" max days between activities for A1, A2 and A3, with max 2 days between them. It is supposed that these activities are constrained"
" not to be in the same day by a constraint min days between activities.");
s+="\n\n";
s+=tr("So, the general situation: this constraint ensures that between each pair from the selected activities, the distance in days is at most the selected value."
" Distance = 1 day between a pair A1 and A2 means that A1 and A2 are in consecutive days (like Thursday and Friday)."
" Distance = 3 days means that A1 and A2 are 3 days apart, for instance Monday and Thursday.");
s+="\n\n";
s+=tr("Another example: teacher T wants to ensure that his activities take place in at most 4 consecutive days (so, from Monday to Thursday or from"
" Tuesday to Friday). Then, add all his activities and max days between them = 3.");
LongTextMessageBox::largeInformation(this, tr("FET help"), s);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
using namespace std;
#define L 6
#define INPUTFILE "mod6-10m.txt"
#define OUTPUTFILE "output.csv"
#define INTSIZE 30
//#define DEBUG
/*
For n = 5/6, each 10 3-bit values uses one unsigned int as bit representation.
I.e. For any n = 10k, n -> number, such that
p(n + offset) = (number >> (3 * offset)) & 0x7.
*/
/*
Database format (n == 5/6):
CREATE TABLE `*************`.`p_n_mod5` (
`n` INT( 12 ) UNSIGNED NOT NULL COMMENT 'independent variable',
`parity` INT( 30 ) UNSIGNED NOT NULL COMMENT 'PartitionsP(n) mod 5',
UNIQUE (
`n`
)
) ENGINE = MYISAM COMMENT = 'Data access: p(10k+offset) = p(10k)''s ''offset * 3 + 2~0'' bit.';
*/
int main()
{
ifstream input(INPUTFILE);
if (!input.is_open())
{
cerr << "Cannot open input file \"" << INPUTFILE << "\"!" << endl;
system("pause");
return -1;
}
ofstream output(OUTPUTFILE);
if (!output.is_open())
{
cerr << "Cannot open output file \"" << OUTPUTFILE << "\"!" << endl;
system("pause");
return -1;
}
#ifdef DEBUG
const long limit = 20;
#endif
long count = 0;
unsigned int temp = 0;
char curr;
while (true)
{
++count;
input >> curr;
#ifdef DEBUG
cout << curr << endl;
if (count > limit)
break;
#else
if (input.eof())
break;
if (curr < '0' || curr > '0' + L)
{
--count; // Discard current character
cerr << "Illegal character detected!" << endl;
continue;
}
if ((3 * count) % INTSIZE == 0)
{
output << "'" << (count - INTSIZE / 3) << "','" << temp << "'" << endl;
temp = 0;
}
switch (curr)
{
case '1':
temp |= (1 << (3 * (count % INTSIZE)));
break;
case '2':
temp |= (2 << (3 * (count % INTSIZE)));
break;
case '3':
temp |= (3 << (3 * (count % INTSIZE)));
break;
case '4':
temp |= (4 << (3 * (count % INTSIZE)));
break;
#if (L == 6)
case '5':
temp |= (5 << (3 * (count % INTSIZE)));
break;
#endif
}
#endif
}
#ifndef DEBUG
output << "'" << (count - count % (INTSIZE / 3)) << "','" << temp << "'" << endl;
#endif
system("pause");
return 0;
}<commit_msg>Fixed shift bug.<commit_after>#include <iostream>
#include <fstream>
#include <cassert>
using namespace std;
#define L 6
#define INPUTFILE "mod6-10m.txt"
#define OUTPUTFILE "output.csv"
#define INTSIZE 30
//#define DEBUG
/*
For n = 5/6, each 10 3-bit values uses one unsigned int as bit representation.
I.e. For any n = 10k, n -> number, such that
p(n + offset) = (number >> (3 * offset)) & 0x7.
*/
/*
Database format (n == 5/6):
CREATE TABLE `*************`.`p_n_mod5` (
`n` INT( 12 ) UNSIGNED NOT NULL COMMENT 'independent variable',
`parity` INT( 30 ) UNSIGNED NOT NULL COMMENT 'PartitionsP(n) mod 5',
UNIQUE (
`n`
)
) ENGINE = MYISAM COMMENT = 'Data access: p(10k+offset) = p(10k)''s ''offset * 3 + 2~0'' bit.';
*/
int main()
{
ifstream input(INPUTFILE);
if (!input.is_open())
{
cerr << "Cannot open input file \"" << INPUTFILE << "\"!" << endl;
system("pause");
return -1;
}
ofstream output(OUTPUTFILE);
if (!output.is_open())
{
cerr << "Cannot open output file \"" << OUTPUTFILE << "\"!" << endl;
system("pause");
return -1;
}
#ifdef DEBUG
const long limit = 20;
#endif
long count = 0;
unsigned int temp = 0;
char curr;
while (true)
{
++count;
input >> curr;
#ifdef DEBUG
cout << curr << endl;
if (count > limit)
break;
#else
if (input.eof())
break;
if (curr < '0' || curr > '0' + L)
{
--count; // Discard current character
cerr << "Illegal character detected!" << endl;
continue;
}
if ((3 * count) % INTSIZE == 0)
{
output << "'" << (count - INTSIZE / 3) << "','" << temp << "'" << endl;
temp = 0;
}
switch (curr)
{
case '1':
temp |= (1 << ((3 * count) % INTSIZE));
break;
case '2':
temp |= (2 << ((3 * count) % INTSIZE));
break;
case '3':
temp |= (3 << ((3 * count) % INTSIZE));
break;
case '4':
temp |= (4 << ((3 * count) % INTSIZE));
break;
#if (L == 6)
case '5':
temp |= (5 << ((3 * count) % INTSIZE));
break;
#endif
}
#endif
}
#ifndef DEBUG
output << "'" << (count - count % (INTSIZE / 3)) << "','" << temp << "'" << endl;
#endif
system("pause");
return 0;
}<|endoftext|>
|
<commit_before>/** \file add_subsystem_tags.cc
* \brief Add additional tags for interfaces to identitify subset views of
IxTheo like RelBib and Bibstudies
* \author Johannes Riedl
*/
/*
Copyright (C) 2018, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "File.h"
#include "FileUtil.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "util.h"
namespace {
const std::string RELBIB_TAG("REL");
const std::string BIBSTUDIES_TAG("BIB");
enum SubSystem { RELBIB, BIBSTUDIES };
const unsigned NUM_OF_SUBSYSTEMS(2);
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " marc_input marc_output\n";
std::exit(EXIT_FAILURE);
}
bool HasRelBibSSGN(const MARC::Record &record) {
for (const auto& field : record.getTagRange("084")) {
const MARC::Subfields subfields(field.getSubfields());
if (subfields.hasSubfieldWithValue('2', "ssgn") and subfields.hasSubfieldWithValue('a', "0"))
return true;
}
return false;
}
bool HasRelBibIxTheoNotation(const MARC::Record &record) {
// Integrate IxTheo Notations A*.B*,T*,V*,X*,Z*
static const std::string RELBIB_IXTHEO_NOTATION_PATTERN("^[ABTVXZ][A-Z].*|.*:[ABTVXZ][A-Z].*");
static RegexMatcher * const relbib_ixtheo_notations_matcher(RegexMatcher::RegexMatcherFactory(RELBIB_IXTHEO_NOTATION_PATTERN));
for (const auto& field : record.getTagRange("652")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_ixtheo_notations_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool HasPlausibleDDCPrefix(const std::string &ddc_string) {
// Exclude records that where the entry in the DCC field is not plausible
static const std::string PLAUSIBLE_DDC_PREFIX_PATTERN("^\\d\\d");
static RegexMatcher * const plausible_ddc_prefix_matcher(RegexMatcher::RegexMatcherFactoryOrDie(PLAUSIBLE_DDC_PREFIX_PATTERN));
return plausible_ddc_prefix_matcher->matched(ddc_string);
}
// Additional criteria that prevent the exclusion of a record that has a 220-289 field
bool HasAdditionalRelbibAdmissionDDC(const MARC::Record &record) {
static const std::string RELBIB_ADMIT_DDC_PATTERN("^([12][01][0-9]|2[9][0-9]|[3-9][0-9][0-9]).*$");
static RegexMatcher * const relbib_admit_ddc_range_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_ADMIT_DDC_PATTERN));
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (HasPlausibleDDCPrefix(subfield_a) and relbib_admit_ddc_range_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool HasRelBibExcludeDDC(const MARC::Record &record) {
if (not record.hasTag("082"))
return true;
// Exclude DDC 220-289
static const std::string RELBIB_EXCLUDE_DDC_RANGE_PATTERN("^2[2-8][0-9](/|\\.){0,2}[^.]*$");
static RegexMatcher * const relbib_exclude_ddc_range_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_EXCLUDE_DDC_RANGE_PATTERN));
// Make sure we have 082-fields to examine
if (not record.hasTag("082"))
return false;
// In general we exclude if the exclude range is matched
// But we include it anyway if we find another reasonable DDC-code
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_exclude_ddc_range_matcher->matched(subfield_a)) {
if (not HasAdditionalRelbibAdmissionDDC(record))
return true;
}
}
}
// Exclude item if it has only a 400 or 800 DDC notation
static const std::string RELBIB_EXCLUDE_DDC_CATEGORIES_PATTERN("^[48][0-9][0-9]$");
static RegexMatcher * const relbib_exclude_ddc_categories_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_EXCLUDE_DDC_CATEGORIES_PATTERN));
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields('a')) {
if (HasPlausibleDDCPrefix(subfield_a) and not relbib_exclude_ddc_categories_matcher->matched(subfield_a))
return false;
}
}
return true;
}
bool MatchesRelBibDDC(const MARC::Record &record) {
return not HasRelBibExcludeDDC(record);
}
bool IsDefinitelyRelBib(const MARC::Record &record) {
return HasRelBibSSGN(record) or HasRelBibIxTheoNotation(record) or MatchesRelBibDDC(record);
}
bool IsProbablyRelBib(const MARC::Record &record) {
for (const auto& field : record.getTagRange("191")) {
for (const auto& subfield : field.getSubfields().extractSubfields("a")) {
if (subfield == "1")
return true;
}
}
return false;
}
std::set<std::string> GetTemporarySuperiorRelBibList() {
const std::string relbib_superior_temporary_file("/usr/local/ub_tools/cpp/data/relbib_superior_temporary.txt");
std::set<std::string> superior_temporary_list;
File superior_temporary(relbib_superior_temporary_file, "r");
std::string line;
while (superior_temporary.getline(&line) and not superior_temporary.eof())
superior_temporary_list.emplace(line);
return superior_temporary_list;
}
bool IsTemporaryRelBibSuperior(const MARC::Record &record) {
static std::set<std::string> superior_temporary_list(GetTemporarySuperiorRelBibList());
if (superior_temporary_list.find(record.getControlNumber()) != superior_temporary_list.end())
return true;
return false;
}
bool ExcludeBecauseOfRWEX(const MARC::Record &record) {
for (const auto &field : record.getTagRange("LOK")) {
const auto &subfields(field.getSubfields());
for (const auto &subfield0: subfields.extractSubfields('0')) {
if (not StringUtil::StartsWith(subfield0, "935"))
continue;
for (const auto &subfield_a : subfields.extractSubfields('a')) {
if (subfield_a == "rwex")
return true;
}
}
}
return false;
}
bool IsRelBibRecord(const MARC::Record &record) {
return ((IsDefinitelyRelBib(record) or
IsProbablyRelBib(record) or
IsTemporaryRelBibSuperior(record))
and not ExcludeBecauseOfRWEX(record));
}
bool HasBibStudiesIxTheoNotation(const MARC::Record &record) {
static const std::string BIBSTUDIES_IXTHEO_PATTERN("^[H][A-Z].*|.*:[H][A-Z].*");
static RegexMatcher * const relbib_ixtheo_notations_matcher(RegexMatcher::RegexMatcherFactory(BIBSTUDIES_IXTHEO_PATTERN));
for (const auto &field : record.getTagRange("652")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_ixtheo_notations_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool IsBibStudiesRecord(const MARC::Record &record) {
return HasBibStudiesIxTheoNotation(record);
}
void AddSubsystemTag(MARC::Record * const record, const std::string &tag) {
// Don't insert twice
if (record->getFirstField(tag) != record->end())
return;
MARC::Subfields subfields;
subfields.addSubfield('a', "1");
record->insertField(tag, subfields);
}
void CollectSuperiorOrParallelWorks(const MARC::Record &record, std::unordered_set<std::string> * const superior_or_parallel_works) {
const std::set<std::string> parallel(MARC::ExtractCrossReferencePPNs(record));
superior_or_parallel_works->insert(parallel.begin(), parallel.end());
superior_or_parallel_works->insert(record.getSuperiorControlNumber());
}
// Get set of immediately belonging or superior or parallel records
void GetSubsystemPPNSet(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
std::vector<std::unordered_set<std::string>> * const subsystem_sets) {
while (const MARC::Record record = marc_reader->read()) {
if (IsRelBibRecord(record)) {
((*subsystem_sets)[RELBIB]).emplace(record.getControlNumber());
CollectSuperiorOrParallelWorks(record, &((*subsystem_sets)[RELBIB]));
}
if (IsBibStudiesRecord(record)) {
((*subsystem_sets)[BIBSTUDIES]).emplace(record.getControlNumber());
CollectSuperiorOrParallelWorks(record, &((*subsystem_sets)[BIBSTUDIES]));
}
marc_writer->write(record);
}
}
void AddSubsystemTags(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
const std::vector<std::unordered_set<std::string>> &subsystem_sets) {
unsigned record_count(0), modified_count(0);
while (MARC::Record record = marc_reader->read()) {
++record_count;
bool modified_record(false);
if ((subsystem_sets[RELBIB]).find(record.getControlNumber()) != subsystem_sets[RELBIB].end()) {
AddSubsystemTag(&record, RELBIB_TAG);
modified_record = true;
}
if ((subsystem_sets[BIBSTUDIES]).find(record.getControlNumber()) != subsystem_sets[RELBIB].end()) {
AddSubsystemTag(&record, BIBSTUDIES_TAG);
modified_record = true;
}
if (modified_record)
++modified_count;
marc_writer->write(record);
}
LOG_INFO("Modified " + std::to_string(modified_count) + " of " + std::to_string(record_count) + " records.");
}
void InitializeSubsystemPPNSets(std::vector<std::unordered_set<std::string>> * const subsystem_ppn_sets) {
for (unsigned i(0); i < NUM_OF_SUBSYSTEMS; ++i)
subsystem_ppn_sets->push_back(std::unordered_set<std::string>());
}
} //unnamed namespace
int Main(int argc, char **argv) {
if (argc != 3)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string marc_output_filename(argv[2]);
if (unlikely(marc_input_filename == marc_output_filename))
LOG_ERROR("Title data input file name equals output file name!");
std::vector<std::unordered_set<std::string>> subsystem_sets;
InitializeSubsystemPPNSets(&subsystem_sets);
std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename));
FileUtil::AutoTempFile tmp_marc_file("/dev/shm/", ".mrc");
std::unique_ptr<MARC::Writer> marc_tmp_writer(MARC::Writer::Factory(tmp_marc_file.getFilePath()));
GetSubsystemPPNSet(marc_reader.get(), marc_tmp_writer.get(), &subsystem_sets);
if (not marc_tmp_writer->flush())
LOG_ERROR("Could not flush to " + tmp_marc_file.getFilePath());
std::unique_ptr<MARC::Reader> marc_tmp_reader(MARC::Reader::Factory(tmp_marc_file.getFilePath()));
std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename));
AddSubsystemTags(marc_tmp_reader.get(), marc_writer.get(), subsystem_sets);
return EXIT_SUCCESS;
}
<commit_msg>Cosmetic.<commit_after>/** \file add_subsystem_tags.cc
* \brief Add additional tags for interfaces to identitify subset views of
IxTheo like RelBib and Bibstudies
* \author Johannes Riedl
*/
/*
Copyright (C) 2018,2019 Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "File.h"
#include "FileUtil.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "util.h"
namespace {
const std::string RELBIB_TAG("REL");
const std::string BIBSTUDIES_TAG("BIB");
enum SubSystem { RELBIB, BIBSTUDIES };
const unsigned NUM_OF_SUBSYSTEMS(2);
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " marc_input marc_output\n";
std::exit(EXIT_FAILURE);
}
bool HasRelBibSSGN(const MARC::Record &record) {
for (const auto& field : record.getTagRange("084")) {
const MARC::Subfields subfields(field.getSubfields());
if (subfields.hasSubfieldWithValue('2', "ssgn") and subfields.hasSubfieldWithValue('a', "0"))
return true;
}
return false;
}
bool HasRelBibIxTheoNotation(const MARC::Record &record) {
// Integrate IxTheo Notations A*.B*,T*,V*,X*,Z*
static const std::string RELBIB_IXTHEO_NOTATION_PATTERN("^[ABTVXZ][A-Z].*|.*:[ABTVXZ][A-Z].*");
static RegexMatcher * const relbib_ixtheo_notations_matcher(RegexMatcher::RegexMatcherFactory(RELBIB_IXTHEO_NOTATION_PATTERN));
for (const auto& field : record.getTagRange("652")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_ixtheo_notations_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool HasPlausibleDDCPrefix(const std::string &ddc_string) {
// Exclude records that where the entry in the DCC field is not plausible
static const std::string PLAUSIBLE_DDC_PREFIX_PATTERN("^\\d\\d");
static RegexMatcher * const plausible_ddc_prefix_matcher(RegexMatcher::RegexMatcherFactoryOrDie(PLAUSIBLE_DDC_PREFIX_PATTERN));
return plausible_ddc_prefix_matcher->matched(ddc_string);
}
// Additional criteria that prevent the exclusion of a record that has a 220-289 field
bool HasAdditionalRelbibAdmissionDDC(const MARC::Record &record) {
static const std::string RELBIB_ADMIT_DDC_PATTERN("^([12][01][0-9]|2[9][0-9]|[3-9][0-9][0-9]).*$");
static RegexMatcher * const relbib_admit_ddc_range_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_ADMIT_DDC_PATTERN));
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (HasPlausibleDDCPrefix(subfield_a) and relbib_admit_ddc_range_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool HasRelBibExcludeDDC(const MARC::Record &record) {
if (not record.hasTag("082"))
return true;
// Exclude DDC 220-289
static const std::string RELBIB_EXCLUDE_DDC_RANGE_PATTERN("^2[2-8][0-9](/|\\.){0,2}[^.]*$");
static RegexMatcher * const relbib_exclude_ddc_range_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_EXCLUDE_DDC_RANGE_PATTERN));
// Make sure we have 082-fields to examine
if (not record.hasTag("082"))
return false;
// In general we exclude if the exclude range is matched
// But we include it anyway if we find another reasonable DDC-code
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_exclude_ddc_range_matcher->matched(subfield_a)) {
if (not HasAdditionalRelbibAdmissionDDC(record))
return true;
}
}
}
// Exclude item if it has only a 400 or 800 DDC notation
static const std::string RELBIB_EXCLUDE_DDC_CATEGORIES_PATTERN("^[48][0-9][0-9]$");
static RegexMatcher * const relbib_exclude_ddc_categories_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_EXCLUDE_DDC_CATEGORIES_PATTERN));
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields('a')) {
if (HasPlausibleDDCPrefix(subfield_a) and not relbib_exclude_ddc_categories_matcher->matched(subfield_a))
return false;
}
}
return true;
}
bool MatchesRelBibDDC(const MARC::Record &record) {
return not HasRelBibExcludeDDC(record);
}
bool IsDefinitelyRelBib(const MARC::Record &record) {
return HasRelBibSSGN(record) or HasRelBibIxTheoNotation(record) or MatchesRelBibDDC(record);
}
bool IsProbablyRelBib(const MARC::Record &record) {
for (const auto& field : record.getTagRange("191")) {
for (const auto& subfield : field.getSubfields().extractSubfields("a")) {
if (subfield == "1")
return true;
}
}
return false;
}
std::set<std::string> GetTemporarySuperiorRelBibList() {
const std::string relbib_superior_temporary_file("/usr/local/ub_tools/cpp/data/relbib_superior_temporary.txt");
std::set<std::string> superior_temporary_list;
File superior_temporary(relbib_superior_temporary_file, "r");
std::string line;
while (superior_temporary.getline(&line) and not superior_temporary.eof())
superior_temporary_list.emplace(line);
return superior_temporary_list;
}
bool IsTemporaryRelBibSuperior(const MARC::Record &record) {
static std::set<std::string> superior_temporary_list(GetTemporarySuperiorRelBibList());
if (superior_temporary_list.find(record.getControlNumber()) != superior_temporary_list.end())
return true;
return false;
}
bool ExcludeBecauseOfRWEX(const MARC::Record &record) {
for (const auto &field : record.getTagRange("LOK")) {
const auto &subfields(field.getSubfields());
for (const auto &subfield0: subfields.extractSubfields('0')) {
if (not StringUtil::StartsWith(subfield0, "935"))
continue;
for (const auto &subfield_a : subfields.extractSubfields('a')) {
if (subfield_a == "rwex")
return true;
}
}
}
return false;
}
bool IsRelBibRecord(const MARC::Record &record) {
return ((IsDefinitelyRelBib(record) or
IsProbablyRelBib(record) or
IsTemporaryRelBibSuperior(record))
and not ExcludeBecauseOfRWEX(record));
}
bool HasBibStudiesIxTheoNotation(const MARC::Record &record) {
static const std::string BIBSTUDIES_IXTHEO_PATTERN("^[H][A-Z].*|.*:[H][A-Z].*");
static RegexMatcher * const relbib_ixtheo_notations_matcher(RegexMatcher::RegexMatcherFactory(BIBSTUDIES_IXTHEO_PATTERN));
for (const auto &field : record.getTagRange("652")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_ixtheo_notations_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool IsBibStudiesRecord(const MARC::Record &record) {
return HasBibStudiesIxTheoNotation(record);
}
void AddSubsystemTag(MARC::Record * const record, const std::string &tag) {
// Don't insert twice
if (record->getFirstField(tag) != record->end())
return;
MARC::Subfields subfields;
subfields.addSubfield('a', "1");
record->insertField(tag, subfields);
}
void CollectSuperiorOrParallelWorks(const MARC::Record &record, std::unordered_set<std::string> * const superior_or_parallel_works) {
const std::set<std::string> parallel(MARC::ExtractCrossReferencePPNs(record));
superior_or_parallel_works->insert(parallel.begin(), parallel.end());
superior_or_parallel_works->insert(record.getSuperiorControlNumber());
}
// Get set of immediately belonging or superior or parallel records
void GetSubsystemPPNSet(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
std::vector<std::unordered_set<std::string>> * const subsystem_sets)
{
while (const MARC::Record record = marc_reader->read()) {
if (IsRelBibRecord(record)) {
((*subsystem_sets)[RELBIB]).emplace(record.getControlNumber());
CollectSuperiorOrParallelWorks(record, &((*subsystem_sets)[RELBIB]));
}
if (IsBibStudiesRecord(record)) {
((*subsystem_sets)[BIBSTUDIES]).emplace(record.getControlNumber());
CollectSuperiorOrParallelWorks(record, &((*subsystem_sets)[BIBSTUDIES]));
}
marc_writer->write(record);
}
}
void AddSubsystemTags(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
const std::vector<std::unordered_set<std::string>> &subsystem_sets) {
unsigned record_count(0), modified_count(0);
while (MARC::Record record = marc_reader->read()) {
++record_count;
bool modified_record(false);
if ((subsystem_sets[RELBIB]).find(record.getControlNumber()) != subsystem_sets[RELBIB].end()) {
AddSubsystemTag(&record, RELBIB_TAG);
modified_record = true;
}
if ((subsystem_sets[BIBSTUDIES]).find(record.getControlNumber()) != subsystem_sets[RELBIB].end()) {
AddSubsystemTag(&record, BIBSTUDIES_TAG);
modified_record = true;
}
if (modified_record)
++modified_count;
marc_writer->write(record);
}
LOG_INFO("Modified " + std::to_string(modified_count) + " of " + std::to_string(record_count) + " records.");
}
void InitializeSubsystemPPNSets(std::vector<std::unordered_set<std::string>> * const subsystem_ppn_sets) {
for (unsigned i(0); i < NUM_OF_SUBSYSTEMS; ++i)
subsystem_ppn_sets->push_back(std::unordered_set<std::string>());
}
} //unnamed namespace
int Main(int argc, char **argv) {
if (argc != 3)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string marc_output_filename(argv[2]);
if (unlikely(marc_input_filename == marc_output_filename))
LOG_ERROR("Title data input file name equals output file name!");
std::vector<std::unordered_set<std::string>> subsystem_sets;
InitializeSubsystemPPNSets(&subsystem_sets);
std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename));
FileUtil::AutoTempFile tmp_marc_file("/dev/shm/", ".mrc");
std::unique_ptr<MARC::Writer> marc_tmp_writer(MARC::Writer::Factory(tmp_marc_file.getFilePath()));
GetSubsystemPPNSet(marc_reader.get(), marc_tmp_writer.get(), &subsystem_sets);
if (not marc_tmp_writer->flush())
LOG_ERROR("Could not flush to " + tmp_marc_file.getFilePath());
std::unique_ptr<MARC::Reader> marc_tmp_reader(MARC::Reader::Factory(tmp_marc_file.getFilePath()));
std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename));
AddSubsystemTags(marc_tmp_reader.get(), marc_writer.get(), subsystem_sets);
return EXIT_SUCCESS;
}
<|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 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#include "update_statement.hh"
#include "unimplemented.hh"
#include "cql3/operation_impl.hh"
namespace cql3 {
namespace statements {
void update_statement::add_update_for_key(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) {
if (s->is_dense()) {
throw std::runtime_error("Dense tables not supported yet");
#if 0
if (prefix.isEmpty())
throw new InvalidRequestException(String.format("Missing PRIMARY KEY part %s", cfm.clusteringColumns().get(0)));
// An empty name for the compact value is what we use to recognize the case where there is not column
// outside the PK, see CreateStatement.
if (!cfm.compactValueColumn().name.bytes.hasRemaining())
{
// There is no column outside the PK. So no operation could have passed through validation
assert updates.isEmpty();
new Constants.Setter(cfm.compactValueColumn(), EMPTY).execute(key, cf, prefix, params);
}
else
{
// dense means we don't have a row marker, so don't accept to set only the PK. See CASSANDRA-5648.
if (updates.isEmpty())
throw new InvalidRequestException(String.format("Column %s is mandatory for this COMPACT STORAGE table", cfm.compactValueColumn().name));
for (Operation update : updates)
update.execute(key, cf, prefix, params);
}
#endif
} else {
if (type == statement_type::INSERT && prefix) {
auto& row = m.partition().clustered_row(clustering_key::from_clustering_prefix(*s, prefix));
row.apply(params.timestamp());
}
}
for (auto&& update : _column_operations) {
update->execute(m, prefix, params);
}
warn(unimplemented::cause::INDEXES);
#if 0
SecondaryIndexManager indexManager = Keyspace.open(cfm.ksName).getColumnFamilyStore(cfm.cfId).indexManager;
if (indexManager.hasIndexes())
{
for (Cell cell : cf)
{
// Indexed values must be validated by any applicable index. See CASSANDRA-3057/4240/8081 for more details
if (!indexManager.validate(cell))
throw new InvalidRequestException(String.format("Can't index column value of size %d for index %s on %s.%s",
cell.value().remaining(),
cfm.getColumnDefinition(cell.name()).getIndexName(),
cfm.ksName,
cfm.cfName));
}
}
}
#endif
}
::shared_ptr<modification_statement>
update_statement::parsed_insert::prepare_internal(database& db, schema_ptr schema,
::shared_ptr<variable_specifications> bound_names, std::unique_ptr<attributes> attrs)
{
auto stmt = ::make_shared<update_statement>(statement_type::INSERT, bound_names->size(), schema, std::move(attrs));
// Created from an INSERT
if (stmt->is_counter()) {
throw exceptions::invalid_request_exception("INSERT statement are not allowed on counter tables, use UPDATE instead");
}
if (_column_names.size() != _column_values.size()) {
throw exceptions::invalid_request_exception("Unmatched column names/values");
}
if (_column_names.empty()) {
throw exceptions::invalid_request_exception("No columns provided to INSERT");
}
for (size_t i = 0; i < _column_names.size(); i++) {
auto id = _column_names[i]->prepare_column_identifier(schema);
auto def = get_column_definition(schema, *id);
if (!def) {
throw exceptions::invalid_request_exception(sprint("Unknown identifier %s", *id));
}
for (size_t j = 0; j < i; j++) {
auto other_id = _column_names[j]->prepare_column_identifier(schema);
if (*id == *other_id) {
throw exceptions::invalid_request_exception(sprint("Multiple definitions found for column %s", *id));
}
}
auto&& value = _column_values[i];
if (def->is_primary_key()) {
auto t = value->prepare(db, keyspace(), def->column_specification);
t->collect_marker_specification(bound_names);
stmt->add_key_value(*def, std::move(t));
} else {
auto operation = operation::set_value(value).prepare(db, keyspace(), *def);
operation->collect_marker_specification(bound_names);
stmt->add_operation(std::move(operation));
};
}
return stmt;
}
::shared_ptr<modification_statement>
update_statement::parsed_update::prepare_internal(database& db, schema_ptr schema,
::shared_ptr<variable_specifications> bound_names, std::unique_ptr<attributes> attrs)
{
auto stmt = ::make_shared<update_statement>(statement_type::UPDATE, bound_names->size(), schema, std::move(attrs));
for (auto&& entry : _updates) {
auto id = entry.first->prepare_column_identifier(schema);
auto def = get_column_definition(schema, *id);
if (!def) {
throw exceptions::invalid_request_exception(sprint("Unknown identifier %s", *entry.first));
}
auto operation = entry.second->prepare(db, keyspace(), *def);
operation->collect_marker_specification(bound_names);
if (def->is_primary_key()) {
throw exceptions::invalid_request_exception(sprint("PRIMARY KEY part %s found in SET part", *entry.first));
}
stmt->add_operation(std::move(operation));
}
stmt->process_where_clause(db, _where_clause, bound_names);
return stmt;
}
}
}
<commit_msg>cql: Fix 'insert' statement not creating row marker for non-clustered tables<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 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#include "update_statement.hh"
#include "unimplemented.hh"
#include "cql3/operation_impl.hh"
namespace cql3 {
namespace statements {
void update_statement::add_update_for_key(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) {
if (s->is_dense()) {
throw std::runtime_error("Dense tables not supported yet");
#if 0
if (prefix.isEmpty())
throw new InvalidRequestException(String.format("Missing PRIMARY KEY part %s", cfm.clusteringColumns().get(0)));
// An empty name for the compact value is what we use to recognize the case where there is not column
// outside the PK, see CreateStatement.
if (!cfm.compactValueColumn().name.bytes.hasRemaining())
{
// There is no column outside the PK. So no operation could have passed through validation
assert updates.isEmpty();
new Constants.Setter(cfm.compactValueColumn(), EMPTY).execute(key, cf, prefix, params);
}
else
{
// dense means we don't have a row marker, so don't accept to set only the PK. See CASSANDRA-5648.
if (updates.isEmpty())
throw new InvalidRequestException(String.format("Column %s is mandatory for this COMPACT STORAGE table", cfm.compactValueColumn().name));
for (Operation update : updates)
update.execute(key, cf, prefix, params);
}
#endif
} else {
// If there are static columns, there also must be clustering columns, in which
// case empty prefix can only refer to the static row.
bool is_static_prefix = s->has_static_columns() && !prefix;
if (type == statement_type::INSERT && !is_static_prefix) {
auto& row = m.partition().clustered_row(clustering_key::from_clustering_prefix(*s, prefix));
row.apply(params.timestamp());
}
}
for (auto&& update : _column_operations) {
update->execute(m, prefix, params);
}
warn(unimplemented::cause::INDEXES);
#if 0
SecondaryIndexManager indexManager = Keyspace.open(cfm.ksName).getColumnFamilyStore(cfm.cfId).indexManager;
if (indexManager.hasIndexes())
{
for (Cell cell : cf)
{
// Indexed values must be validated by any applicable index. See CASSANDRA-3057/4240/8081 for more details
if (!indexManager.validate(cell))
throw new InvalidRequestException(String.format("Can't index column value of size %d for index %s on %s.%s",
cell.value().remaining(),
cfm.getColumnDefinition(cell.name()).getIndexName(),
cfm.ksName,
cfm.cfName));
}
}
}
#endif
}
::shared_ptr<modification_statement>
update_statement::parsed_insert::prepare_internal(database& db, schema_ptr schema,
::shared_ptr<variable_specifications> bound_names, std::unique_ptr<attributes> attrs)
{
auto stmt = ::make_shared<update_statement>(statement_type::INSERT, bound_names->size(), schema, std::move(attrs));
// Created from an INSERT
if (stmt->is_counter()) {
throw exceptions::invalid_request_exception("INSERT statement are not allowed on counter tables, use UPDATE instead");
}
if (_column_names.size() != _column_values.size()) {
throw exceptions::invalid_request_exception("Unmatched column names/values");
}
if (_column_names.empty()) {
throw exceptions::invalid_request_exception("No columns provided to INSERT");
}
for (size_t i = 0; i < _column_names.size(); i++) {
auto id = _column_names[i]->prepare_column_identifier(schema);
auto def = get_column_definition(schema, *id);
if (!def) {
throw exceptions::invalid_request_exception(sprint("Unknown identifier %s", *id));
}
for (size_t j = 0; j < i; j++) {
auto other_id = _column_names[j]->prepare_column_identifier(schema);
if (*id == *other_id) {
throw exceptions::invalid_request_exception(sprint("Multiple definitions found for column %s", *id));
}
}
auto&& value = _column_values[i];
if (def->is_primary_key()) {
auto t = value->prepare(db, keyspace(), def->column_specification);
t->collect_marker_specification(bound_names);
stmt->add_key_value(*def, std::move(t));
} else {
auto operation = operation::set_value(value).prepare(db, keyspace(), *def);
operation->collect_marker_specification(bound_names);
stmt->add_operation(std::move(operation));
};
}
return stmt;
}
::shared_ptr<modification_statement>
update_statement::parsed_update::prepare_internal(database& db, schema_ptr schema,
::shared_ptr<variable_specifications> bound_names, std::unique_ptr<attributes> attrs)
{
auto stmt = ::make_shared<update_statement>(statement_type::UPDATE, bound_names->size(), schema, std::move(attrs));
for (auto&& entry : _updates) {
auto id = entry.first->prepare_column_identifier(schema);
auto def = get_column_definition(schema, *id);
if (!def) {
throw exceptions::invalid_request_exception(sprint("Unknown identifier %s", *entry.first));
}
auto operation = entry.second->prepare(db, keyspace(), *def);
operation->collect_marker_specification(bound_names);
if (def->is_primary_key()) {
throw exceptions::invalid_request_exception(sprint("PRIMARY KEY part %s found in SET part", *entry.first));
}
stmt->add_operation(std::move(operation));
}
stmt->process_where_clause(db, _where_clause, bound_names);
return stmt;
}
}
}
<|endoftext|>
|
<commit_before>/** Copyright (C) 2017 European Spallation Source ERIC */
#include <memory>
#include <stdio.h>
#include <unistd.h>
#include <gdgem/clustering/HitSorter.h>
#include <gdgem/clustering/DoroClusterer.h>
#include <gdgem/clustering/ClusterMatcher.h>
#include <test/TestBase.h>
#include <functional>
#include <gdgem/clustering/TestDataShort.h>
#include <gdgem/nmx/ReadoutFile.h>
#define UNUSED __attribute__((unused))
class ClusterMatcherTest : public TestBase {
protected:
std::vector<Readout> long_data;
uint16_t pADCThreshold = 0;
size_t pMinClusterSize = 3;
// Maximum time difference between hits in time sorted cluster (x or y)
double pMaxTimeGap = 200;
// Maximum number of missing strips in strip sorted cluster (x or y)
uint16_t pMaxStripGap = 2;
//Maximum cluster time difference between matching clusters in x and y
//Cluster time is either calculated with center-of-mass or uTPC method
double pDeltaTimePlanes = 200;
// Maximum time span for total cluster (x or y)
// double pDeltaTimeSpan = 500;
SRSMappings mapping;
std::shared_ptr<ClusterMatcher> matcher;
std::shared_ptr<HitSorter> sorter_x;
std::shared_ptr<HitSorter> sorter_y;
virtual void SetUp() {
std::string DataPath = TEST_DATA_PATH;
ReadoutFile::read(DataPath + "run16long.h5", long_data);
mapping.set_mapping(1, 0, 0, 0);
mapping.set_mapping(1, 1, 0, 64);
mapping.set_mapping(1, 6, 0, 128);
mapping.set_mapping(1, 7, 0, 192);
mapping.set_mapping(1, 10, 1, 0);
mapping.set_mapping(1, 11, 1, 64);
mapping.set_mapping(1, 14, 1, 128);
mapping.set_mapping(1, 15, 1, 192);
SRSTime srstime;
srstime.set_bc_clock(20);
srstime.set_tac_slope(60);
srstime.set_trigger_resolution_ns(3.125);
srstime.set_acquisition_window(4000);
matcher = std::make_shared<ClusterMatcher>(pDeltaTimePlanes);
sorter_x = std::make_shared<HitSorter>(srstime, mapping, pADCThreshold, pMaxTimeGap);
sorter_y = std::make_shared<HitSorter>(srstime, mapping, pADCThreshold, pMaxTimeGap);
sorter_x->clusterer = std::make_shared<DoroClusterer>(pMaxTimeGap, pMaxStripGap, pMinClusterSize);
sorter_y->clusterer = std::make_shared<DoroClusterer>(pMaxTimeGap, pMaxStripGap, pMinClusterSize);
}
virtual void TearDown() {
}
void store_hit(const Readout& readout)
{
uint8_t planeID = mapping.get_plane(readout);
if (planeID == 1) {
sorter_y->insert(readout);
} else {
sorter_x->insert(readout);
}
}
Cluster mock_cluster(uint8_t plane, uint16_t strip_start, uint16_t strip_end,
double time_start, double time_end) {
Cluster ret;
Hit e;
e.plane_id = plane;
e.adc = 1;
double time_step = (time_end - time_start) / 10.0;
for (e.time = time_start; e.time <= time_end; e.time += time_step)
for (e.strip = strip_start; e.strip <= strip_end; ++e.strip)
ret.insert_hit(e);
e.time = time_end;
ret.insert_hit(e);
return ret;
}
};
TEST_F(ClusterMatcherTest, OneX) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0, 10, 0, 200));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 1);
ASSERT_EQ(matcher->matched_clusters.size(), 1);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 0);
}
TEST_F(ClusterMatcherTest, OneY) {
matcher->unmatched_clusters.push_back(mock_cluster(1, 0, 10, 0, 200));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 1);
ASSERT_EQ(matcher->matched_clusters.size(), 1);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 122);
}
TEST_F(ClusterMatcherTest, TwoX) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0, 10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(0, 0, 10, 500, 700));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 2);
ASSERT_EQ(matcher->matched_clusters.size(), 2);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.back().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.back().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.back().y.entries.size(), 0);
}
TEST_F(ClusterMatcherTest, TwoY) {
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 500, 700));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 2);
ASSERT_EQ(matcher->matched_clusters.size(), 2);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.back().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.back().x.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.back().y.entries.size(), 122);
}
TEST_F(ClusterMatcherTest, OneXOneY) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 500, 700));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 2);
ASSERT_EQ(matcher->matched_clusters.size(), 2);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.back().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.back().x.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.back().y.entries.size(), 122);
}
TEST_F(ClusterMatcherTest, OneXY) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 0, 200));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 1);
ASSERT_EQ(matcher->matched_clusters.size(), 1);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 122);
}
TEST_F(ClusterMatcherTest, TwoXY) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 1, 300));
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 600, 800));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 650, 850));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 2);
ASSERT_EQ(matcher->matched_clusters.size(), 2);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 300);
EXPECT_EQ(matcher->matched_clusters.back().time_span(), 250);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.back().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.back().y.entries.size(), 122);
}
TEST_F(ClusterMatcherTest, JustIntside) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 200, 400));
matcher->match_end(true);
ASSERT_EQ(matcher->matched_clusters.size(), 1);
}
TEST_F(ClusterMatcherTest, JustOutside) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 200, 401));
matcher->match_end(true);
ASSERT_EQ(matcher->matched_clusters.size(), 2);
}
TEST_F(ClusterMatcherTest, DontForce) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 200, 401));
matcher->match_end(false);
ASSERT_EQ(matcher->matched_clusters.size(), 0);
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 800, 1000));
matcher->match_end(false);
ASSERT_EQ(matcher->matched_clusters.size(), 0);
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 900, 1000));
matcher->match_end(false);
ASSERT_EQ(matcher->matched_clusters.size(), 0);
}
TEST_F(ClusterMatcherTest, Run16_Short) {
uint32_t bonus = 0;
uint32_t old = 0;
for (auto readout : Run16) {
if (readout.srs_timestamp < old)
bonus++;
old = readout.srs_timestamp;
readout.bonus_timestamp = bonus;
store_hit(readout);
}
EXPECT_EQ(sorter_x->clusterer->stats_cluster_count, 3);
EXPECT_EQ(sorter_y->clusterer->stats_cluster_count, 4);
matcher->merge(0, sorter_x->clusterer->clusters);
matcher->merge(1, sorter_y->clusterer->clusters);
matcher->match_end(false);
EXPECT_EQ(matcher->stats_cluster_count, 1);
sorter_x->flush();
sorter_y->flush();
EXPECT_EQ(sorter_x->clusterer->stats_cluster_count, 7);
EXPECT_EQ(sorter_y->clusterer->stats_cluster_count, 11);
matcher->merge(0, sorter_x->clusterer->clusters);
matcher->merge(1, sorter_y->clusterer->clusters);
matcher->match_end(true);
EXPECT_EQ(matcher->stats_cluster_count, 6);
}
TEST_F(ClusterMatcherTest, Run16_Long_identical) {
uint32_t bonus = 0;
uint32_t old = 0;
for (auto readout : long_data) {
if (readout.srs_timestamp < old)
bonus++;
old = readout.srs_timestamp;
readout.bonus_timestamp = bonus;
sorter_y->insert(readout);
sorter_x->insert(readout);
}
sorter_x->flush();
sorter_y->flush();
EXPECT_EQ(sorter_x->clusterer->clusters.size(), 20282);
EXPECT_EQ(sorter_y->clusterer->clusters.size(), 20282);
matcher = std::make_shared<ClusterMatcher>(0);
matcher->merge(0, sorter_x->clusterer->clusters);
matcher->merge(1, sorter_y->clusterer->clusters);
EXPECT_EQ(matcher->unmatched_clusters.size(), 40564);
matcher->match_end(true);
EXPECT_EQ(matcher->stats_cluster_count, 16963);
}
TEST_F(ClusterMatcherTest, Run16_Long) {
uint32_t bonus = 0;
uint32_t old = 0;
for (auto readout : long_data) {
if (readout.srs_timestamp < old)
bonus++;
old = readout.srs_timestamp;
readout.bonus_timestamp = bonus;
store_hit(readout);
}
sorter_x->flush();
sorter_y->flush();
EXPECT_EQ(sorter_x->clusterer->stats_cluster_count, 10206);
EXPECT_EQ(sorter_y->clusterer->stats_cluster_count, 12443);
matcher = std::make_shared<ClusterMatcher>(10);
matcher->merge(0, sorter_x->clusterer->clusters);
matcher->merge(1, sorter_y->clusterer->clusters);
EXPECT_EQ(matcher->unmatched_clusters.size(), 22649);
matcher->match_end(true);
// EXPECT_EQ(matcher->stats_cluster_count, 6250);
EXPECT_EQ(matcher->stats_cluster_count, 19073);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>retro fitting gtest asserts after changing tdc calculation - this is a hack<commit_after>/** Copyright (C) 2017 European Spallation Source ERIC */
#include <memory>
#include <stdio.h>
#include <unistd.h>
#include <gdgem/clustering/HitSorter.h>
#include <gdgem/clustering/DoroClusterer.h>
#include <gdgem/clustering/ClusterMatcher.h>
#include <test/TestBase.h>
#include <functional>
#include <gdgem/clustering/TestDataShort.h>
#include <gdgem/nmx/ReadoutFile.h>
#define UNUSED __attribute__((unused))
class ClusterMatcherTest : public TestBase {
protected:
std::vector<Readout> long_data;
uint16_t pADCThreshold = 0;
size_t pMinClusterSize = 3;
// Maximum time difference between hits in time sorted cluster (x or y)
double pMaxTimeGap = 200;
// Maximum number of missing strips in strip sorted cluster (x or y)
uint16_t pMaxStripGap = 2;
//Maximum cluster time difference between matching clusters in x and y
//Cluster time is either calculated with center-of-mass or uTPC method
double pDeltaTimePlanes = 200;
// Maximum time span for total cluster (x or y)
// double pDeltaTimeSpan = 500;
SRSMappings mapping;
std::shared_ptr<ClusterMatcher> matcher;
std::shared_ptr<HitSorter> sorter_x;
std::shared_ptr<HitSorter> sorter_y;
virtual void SetUp() {
std::string DataPath = TEST_DATA_PATH;
ReadoutFile::read(DataPath + "run16long.h5", long_data);
mapping.set_mapping(1, 0, 0, 0);
mapping.set_mapping(1, 1, 0, 64);
mapping.set_mapping(1, 6, 0, 128);
mapping.set_mapping(1, 7, 0, 192);
mapping.set_mapping(1, 10, 1, 0);
mapping.set_mapping(1, 11, 1, 64);
mapping.set_mapping(1, 14, 1, 128);
mapping.set_mapping(1, 15, 1, 192);
SRSTime srstime;
srstime.set_bc_clock(20);
srstime.set_tac_slope(60);
srstime.set_trigger_resolution_ns(3.125);
srstime.set_acquisition_window(4000);
matcher = std::make_shared<ClusterMatcher>(pDeltaTimePlanes);
sorter_x = std::make_shared<HitSorter>(srstime, mapping, pADCThreshold, pMaxTimeGap);
sorter_y = std::make_shared<HitSorter>(srstime, mapping, pADCThreshold, pMaxTimeGap);
sorter_x->clusterer = std::make_shared<DoroClusterer>(pMaxTimeGap, pMaxStripGap, pMinClusterSize);
sorter_y->clusterer = std::make_shared<DoroClusterer>(pMaxTimeGap, pMaxStripGap, pMinClusterSize);
}
virtual void TearDown() {
}
void store_hit(const Readout& readout)
{
uint8_t planeID = mapping.get_plane(readout);
if (planeID == 1) {
sorter_y->insert(readout);
} else {
sorter_x->insert(readout);
}
}
Cluster mock_cluster(uint8_t plane, uint16_t strip_start, uint16_t strip_end,
double time_start, double time_end) {
Cluster ret;
Hit e;
e.plane_id = plane;
e.adc = 1;
double time_step = (time_end - time_start) / 10.0;
for (e.time = time_start; e.time <= time_end; e.time += time_step)
for (e.strip = strip_start; e.strip <= strip_end; ++e.strip)
ret.insert_hit(e);
e.time = time_end;
ret.insert_hit(e);
return ret;
}
};
TEST_F(ClusterMatcherTest, OneX) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0, 10, 0, 200));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 1);
ASSERT_EQ(matcher->matched_clusters.size(), 1);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 0);
}
TEST_F(ClusterMatcherTest, OneY) {
matcher->unmatched_clusters.push_back(mock_cluster(1, 0, 10, 0, 200));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 1);
ASSERT_EQ(matcher->matched_clusters.size(), 1);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 122);
}
TEST_F(ClusterMatcherTest, TwoX) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0, 10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(0, 0, 10, 500, 700));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 2);
ASSERT_EQ(matcher->matched_clusters.size(), 2);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.back().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.back().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.back().y.entries.size(), 0);
}
TEST_F(ClusterMatcherTest, TwoY) {
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 500, 700));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 2);
ASSERT_EQ(matcher->matched_clusters.size(), 2);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.back().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.back().x.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.back().y.entries.size(), 122);
}
TEST_F(ClusterMatcherTest, OneXOneY) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 500, 700));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 2);
ASSERT_EQ(matcher->matched_clusters.size(), 2);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.back().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.back().x.entries.size(), 0);
EXPECT_EQ(matcher->matched_clusters.back().y.entries.size(), 122);
}
TEST_F(ClusterMatcherTest, OneXY) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 0, 200));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 1);
ASSERT_EQ(matcher->matched_clusters.size(), 1);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 200);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 122);
}
TEST_F(ClusterMatcherTest, TwoXY) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 1, 300));
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 600, 800));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 650, 850));
matcher->match_end(true);
ASSERT_EQ(matcher->stats_cluster_count, 2);
ASSERT_EQ(matcher->matched_clusters.size(), 2);
EXPECT_EQ(matcher->matched_clusters.front().time_span(), 300);
EXPECT_EQ(matcher->matched_clusters.back().time_span(), 250);
EXPECT_EQ(matcher->matched_clusters.front().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.front().y.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.back().x.entries.size(), 122);
EXPECT_EQ(matcher->matched_clusters.back().y.entries.size(), 122);
}
TEST_F(ClusterMatcherTest, JustIntside) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 200, 400));
matcher->match_end(true);
ASSERT_EQ(matcher->matched_clusters.size(), 1);
}
TEST_F(ClusterMatcherTest, JustOutside) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 200, 401));
matcher->match_end(true);
ASSERT_EQ(matcher->matched_clusters.size(), 2);
}
TEST_F(ClusterMatcherTest, DontForce) {
matcher->unmatched_clusters.push_back(mock_cluster(0, 0,10, 0, 200));
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 200, 401));
matcher->match_end(false);
ASSERT_EQ(matcher->matched_clusters.size(), 0);
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 800, 1000));
matcher->match_end(false);
ASSERT_EQ(matcher->matched_clusters.size(), 0);
matcher->unmatched_clusters.push_back(mock_cluster(1, 0,10, 900, 1000));
matcher->match_end(false);
ASSERT_EQ(matcher->matched_clusters.size(), 0);
}
TEST_F(ClusterMatcherTest, Run16_Short) {
uint32_t bonus = 0;
uint32_t old = 0;
for (auto readout : Run16) {
if (readout.srs_timestamp < old)
bonus++;
old = readout.srs_timestamp;
readout.bonus_timestamp = bonus;
store_hit(readout);
}
EXPECT_EQ(sorter_x->clusterer->stats_cluster_count, 3);
EXPECT_EQ(sorter_y->clusterer->stats_cluster_count, 4);
matcher->merge(0, sorter_x->clusterer->clusters);
matcher->merge(1, sorter_y->clusterer->clusters);
matcher->match_end(false);
EXPECT_EQ(matcher->stats_cluster_count, 1);
sorter_x->flush();
sorter_y->flush();
EXPECT_EQ(sorter_x->clusterer->stats_cluster_count, 7);
EXPECT_EQ(sorter_y->clusterer->stats_cluster_count, 11);
matcher->merge(0, sorter_x->clusterer->clusters);
matcher->merge(1, sorter_y->clusterer->clusters);
matcher->match_end(true);
EXPECT_EQ(matcher->stats_cluster_count, 6);
}
TEST_F(ClusterMatcherTest, Run16_Long_identical) {
uint32_t bonus = 0;
uint32_t old = 0;
for (auto readout : long_data) {
if (readout.srs_timestamp < old)
bonus++;
old = readout.srs_timestamp;
readout.bonus_timestamp = bonus;
sorter_y->insert(readout);
sorter_x->insert(readout);
}
sorter_x->flush();
sorter_y->flush();
EXPECT_EQ(sorter_x->clusterer->clusters.size(), 20293);
EXPECT_EQ(sorter_y->clusterer->clusters.size(), 20293);
matcher = std::make_shared<ClusterMatcher>(0);
matcher->merge(0, sorter_x->clusterer->clusters);
matcher->merge(1, sorter_y->clusterer->clusters);
EXPECT_EQ(matcher->unmatched_clusters.size(), 40586);
matcher->match_end(true);
EXPECT_EQ(matcher->stats_cluster_count, 16954);
}
TEST_F(ClusterMatcherTest, Run16_Long) {
uint32_t bonus = 0;
uint32_t old = 0;
for (auto readout : long_data) {
if (readout.srs_timestamp < old)
bonus++;
old = readout.srs_timestamp;
readout.bonus_timestamp = bonus;
store_hit(readout);
}
sorter_x->flush();
sorter_y->flush();
EXPECT_EQ(sorter_x->clusterer->stats_cluster_count, 10226);
EXPECT_EQ(sorter_y->clusterer->stats_cluster_count, 12467);
matcher = std::make_shared<ClusterMatcher>(10);
matcher->merge(0, sorter_x->clusterer->clusters);
matcher->merge(1, sorter_y->clusterer->clusters);
EXPECT_EQ(matcher->unmatched_clusters.size(), 22693);
matcher->match_end(true);
// EXPECT_EQ(matcher->stats_cluster_count, 6250);
EXPECT_EQ(matcher->stats_cluster_count, 19080);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>#ifndef SERVER_HTTP_HPP
#define SERVER_HTTP_HPP
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <regex>
#include <unordered_map>
#include <thread>
#include <functional>
#include <iostream>
namespace SimpleWeb {
template <class socket_type>
class ServerBase {
public:
class Response {
friend class ServerBase<socket_type>;
private:
std::shared_ptr<boost::asio::strand> strand;
boost::asio::yield_context& yield;
boost::asio::streambuf streambuf;
std::shared_ptr<socket_type> socket;
std::shared_ptr<boost::asio::deadline_timer> async_timer;
std::shared_ptr<bool> async_writing;
std::shared_ptr<bool> async_waiting;
Response(boost::asio::io_service& io_service, std::shared_ptr<socket_type> socket, std::shared_ptr<boost::asio::strand> strand,
boost::asio::yield_context& yield):
strand(strand), yield(yield), socket(socket), async_timer(new boost::asio::deadline_timer(io_service)),
async_writing(new bool(false)), async_waiting(new bool(false)), stream(&streambuf) {}
void async_flush(std::function<void(const boost::system::error_code&)> callback=nullptr) {
if(!callback && !socket->lowest_layer().is_open()) {
if(*async_waiting)
async_timer->cancel();
throw std::runtime_error("Broken pipe.");
}
std::shared_ptr<boost::asio::streambuf> write_buffer(new boost::asio::streambuf);
std::ostream response(write_buffer.get());
response << stream.rdbuf();
//Wait until previous async_flush is finished
strand->dispatch([this](){
if(*async_writing) {
*async_waiting=true;
try {
async_timer->async_wait(yield);
}
catch(std::exception& e) {
}
*async_waiting=false;
}
});
*async_writing=true;
auto socket_=this->socket;
auto async_writing_=this->async_writing;
auto async_timer_=this->async_timer;
auto async_waiting_=this->async_waiting;
boost::asio::async_write(*socket, *write_buffer,
strand->wrap([socket_, write_buffer, callback, async_writing_, async_timer_, async_waiting_]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
*async_writing_=false;
if(*async_waiting_)
async_timer_->cancel();
if(callback)
callback(ec);
}));
}
void flush() {
boost::asio::streambuf write_buffer;
std::ostream response(&write_buffer);
response << stream.rdbuf();
boost::asio::async_write(*socket, write_buffer, yield);
}
public:
std::ostream stream;
template <class T>
Response& operator<<(const T& t) {
stream << t;
return *this;
}
Response& operator<<(std::ostream& (*manip)(std::ostream&)) {
stream << manip;
return *this;
}
Response& operator<<(Response& (*manip)(Response&)) {
return manip(*this);
}
};
static Response& async_flush(Response& r) {
r.async_flush();
return r;
}
static Response& flush(Response& r) {
r.flush();
return r;
}
class Request {
friend class ServerBase<socket_type>;
public:
std::string method, path, http_version;
std::istream content;
std::unordered_multimap<std::string, std::string> header;
std::smatch path_match;
std::string remote_endpoint_address;
unsigned short remote_endpoint_port;
private:
Request(): content(&streambuf) {}
boost::asio::streambuf streambuf;
void read_remote_endpoint_data(socket_type& socket) {
try {
remote_endpoint_address=socket.lowest_layer().remote_endpoint().address().to_string();
remote_endpoint_port=socket.lowest_layer().remote_endpoint().port();
}
catch(const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
};
std::unordered_map<std::string, std::unordered_map<std::string,
std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > > resource;
std::unordered_map<std::string,
std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > default_resource;
private:
std::vector<std::pair<std::string, std::vector<std::pair<std::regex,
std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > > > > opt_resource;
public:
void start() {
//Copy the resources to opt_resource for more efficient request processing
opt_resource.clear();
for(auto& res: resource) {
for(auto& res_method: res.second) {
auto it=opt_resource.end();
for(auto opt_it=opt_resource.begin();opt_it!=opt_resource.end();opt_it++) {
if(res_method.first==opt_it->first) {
it=opt_it;
break;
}
}
if(it==opt_resource.end()) {
opt_resource.emplace_back();
it=opt_resource.begin()+(opt_resource.size()-1);
it->first=res_method.first;
}
it->second.emplace_back(std::regex(res.first), res_method.second);
}
}
accept();
//If num_threads>1, start m_io_service.run() in (num_threads-1) threads for thread-pooling
threads.clear();
for(size_t c=1;c<num_threads;c++) {
threads.emplace_back([this](){
io_service.run();
});
}
//Main thread
io_service.run();
//Wait for the rest of the threads, if any, to finish as well
for(auto& t: threads) {
t.join();
}
}
void stop() {
io_service.stop();
}
protected:
boost::asio::io_service io_service;
boost::asio::ip::tcp::endpoint endpoint;
boost::asio::ip::tcp::acceptor acceptor;
size_t num_threads;
std::vector<std::thread> threads;
size_t timeout_request;
size_t timeout_content;
ServerBase(unsigned short port, size_t num_threads, size_t timeout_request, size_t timeout_send_or_receive) :
endpoint(boost::asio::ip::tcp::v4(), port), acceptor(io_service, endpoint), num_threads(num_threads),
timeout_request(timeout_request), timeout_content(timeout_send_or_receive) {}
virtual void accept()=0;
std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<socket_type> socket, size_t seconds) {
std::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(io_service));
timer->expires_from_now(boost::posix_time::seconds(seconds));
timer->async_wait([socket](const boost::system::error_code& ec){
if(!ec) {
boost::system::error_code ec;
socket->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
socket->lowest_layer().close();
}
});
return timer;
}
std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<socket_type> socket, std::shared_ptr<boost::asio::strand> strand, size_t seconds) {
std::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(io_service));
timer->expires_from_now(boost::posix_time::seconds(seconds));
timer->async_wait(strand->wrap([socket](const boost::system::error_code& ec){
if(!ec) {
boost::system::error_code ec;
socket->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
socket->lowest_layer().close();
}
}));
return timer;
}
void read_request_and_content(std::shared_ptr<socket_type> socket) {
//Create new streambuf (Request::streambuf) for async_read_until()
//shared_ptr is used to pass temporary objects to the asynchronous functions
std::shared_ptr<Request> request(new Request());
request->read_remote_endpoint_data(*socket);
//Set timeout on the following boost::asio::async-read or write function
std::shared_ptr<boost::asio::deadline_timer> timer;
if(timeout_request>0)
timer=set_timeout_on_socket(socket, timeout_request);
boost::asio::async_read_until(*socket, request->streambuf, "\r\n\r\n",
[this, socket, request, timer](const boost::system::error_code& ec, size_t bytes_transferred) {
if(timeout_request>0)
timer->cancel();
if(!ec) {
//request->streambuf.size() is not necessarily the same as bytes_transferred, from Boost-docs:
//"After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter"
//The chosen solution is to extract lines from the stream directly when parsing the header. What is left of the
//streambuf (maybe some bytes of the content) is appended to in the async_read-function below (for retrieving content).
size_t num_additional_bytes=request->streambuf.size()-bytes_transferred;
parse_request(request, request->content);
//If content, read that as well
const auto it=request->header.find("Content-Length");
if(it!=request->header.end()) {
//Set timeout on the following boost::asio::async-read or write function
std::shared_ptr<boost::asio::deadline_timer> timer;
if(timeout_content>0)
timer=set_timeout_on_socket(socket, timeout_content);
try {
auto content_length=stoull(it->second);
boost::asio::async_read(*socket, request->streambuf,
boost::asio::transfer_exactly(stoull(it->second)-num_additional_bytes),
[this, socket, request, timer]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(timeout_content>0)
timer->cancel();
if(!ec)
find_resource(socket, request);
});
}
catch(const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
else {
find_resource(socket, request);
}
}
});
}
void parse_request(std::shared_ptr<Request> request, std::istream& stream) const {
std::string line;
getline(stream, line);
size_t method_end=line.find(' ');
size_t path_end=line.find(' ', method_end+1);
if(method_end!=std::string::npos && path_end!=std::string::npos) {
request->method=line.substr(0, method_end);
request->path=line.substr(method_end+1, path_end-method_end-1);
request->http_version=line.substr(path_end+6, line.size()-path_end-7);
getline(stream, line);
size_t param_end=line.find(':');
while(param_end!=std::string::npos) {
size_t value_start=param_end+1;
if(line[value_start]==' ')
value_start++;
std::string key=line.substr(0, param_end);
request->header.insert(std::make_pair(key, line.substr(value_start, line.size()-value_start-1)));
getline(stream, line);
param_end=line.find(':');
}
}
}
void find_resource(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request) {
//Find path- and method-match, and call write_response
for(auto& res: opt_resource) {
if(request->method==res.first) {
for(auto& res_path: res.second) {
std::smatch sm_res;
if(std::regex_match(request->path, sm_res, res_path.first)) {
request->path_match=std::move(sm_res);
write_response(socket, request, res_path.second);
return;
}
}
}
}
auto it_method=default_resource.find(request->method);
if(it_method!=default_resource.end()) {
write_response(socket, request, it_method->second);
}
}
void write_response(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request,
std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)>& resource_function) {
std::shared_ptr<boost::asio::strand> strand(new boost::asio::strand(io_service));
//Set timeout on the following boost::asio::async-read or write function
std::shared_ptr<boost::asio::deadline_timer> timer;
if(timeout_content>0)
timer=set_timeout_on_socket(socket, strand, timeout_content);
boost::asio::spawn(*strand, [this, strand, &resource_function, socket, request, timer](boost::asio::yield_context yield) {
Response response(io_service, socket, strand, yield);
try {
resource_function(response, request);
}
catch(std::exception& e) {
return;
}
response.async_flush([this, socket, request, timer](const boost::system::error_code& ec) {
if(timeout_content>0)
timer->cancel();
if(!ec && stof(request->http_version)>1.05)
read_request_and_content(socket);
});
});
}
};
template<class socket_type>
class Server : public ServerBase<socket_type> {};
typedef boost::asio::ip::tcp::socket HTTP;
template<>
class Server<HTTP> : public ServerBase<HTTP> {
public:
Server(unsigned short port, size_t num_threads=1, size_t timeout_request=5, size_t timeout_content=300) :
ServerBase<HTTP>::ServerBase(port, num_threads, timeout_request, timeout_content) {}
private:
void accept() {
//Create new socket for this connection
//Shared_ptr is used to pass temporary objects to the asynchronous functions
std::shared_ptr<HTTP> socket(new HTTP(io_service));
acceptor.async_accept(*socket, [this, socket](const boost::system::error_code& ec){
//Immediately start accepting a new connection
accept();
if(!ec) {
boost::asio::ip::tcp::no_delay option(true);
socket->set_option(option);
read_request_and_content(socket);
}
});
}
};
}
#endif /* SERVER_HTTP_HPP */
<commit_msg>Minor fix.<commit_after>#ifndef SERVER_HTTP_HPP
#define SERVER_HTTP_HPP
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <regex>
#include <unordered_map>
#include <thread>
#include <functional>
#include <iostream>
namespace SimpleWeb {
template <class socket_type>
class ServerBase {
public:
class Response {
friend class ServerBase<socket_type>;
private:
std::shared_ptr<boost::asio::strand> strand;
boost::asio::yield_context& yield;
boost::asio::streambuf streambuf;
std::shared_ptr<socket_type> socket;
std::shared_ptr<boost::asio::deadline_timer> async_timer;
std::shared_ptr<bool> async_writing;
std::shared_ptr<bool> async_waiting;
Response(boost::asio::io_service& io_service, std::shared_ptr<socket_type> socket, std::shared_ptr<boost::asio::strand> strand,
boost::asio::yield_context& yield):
strand(strand), yield(yield), socket(socket), async_timer(new boost::asio::deadline_timer(io_service)),
async_writing(new bool(false)), async_waiting(new bool(false)), stream(&streambuf) {}
void async_flush(std::function<void(const boost::system::error_code&)> callback=nullptr) {
if(!callback && !socket->lowest_layer().is_open()) {
if(*async_waiting)
async_timer->cancel();
throw std::runtime_error("Broken pipe.");
}
std::shared_ptr<boost::asio::streambuf> write_buffer(new boost::asio::streambuf);
std::ostream response(write_buffer.get());
response << stream.rdbuf();
//Wait until previous async_flush is finished
strand->dispatch([this](){
if(*async_writing) {
*async_waiting=true;
try {
async_timer->async_wait(yield);
}
catch(std::exception& e) {
}
*async_waiting=false;
}
});
*async_writing=true;
auto socket_=this->socket;
auto async_writing_=this->async_writing;
auto async_timer_=this->async_timer;
auto async_waiting_=this->async_waiting;
boost::asio::async_write(*socket, *write_buffer,
strand->wrap([socket_, write_buffer, callback, async_writing_, async_timer_, async_waiting_]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
*async_writing_=false;
if(*async_waiting_)
async_timer_->cancel();
if(callback)
callback(ec);
}));
}
void flush() {
boost::asio::streambuf write_buffer;
std::ostream response(&write_buffer);
response << stream.rdbuf();
boost::asio::async_write(*socket, write_buffer, yield);
}
public:
std::ostream stream;
template <class T>
Response& operator<<(const T& t) {
stream << t;
return *this;
}
Response& operator<<(std::ostream& (*manip)(std::ostream&)) {
stream << manip;
return *this;
}
Response& operator<<(Response& (*manip)(Response&)) {
return manip(*this);
}
};
static Response& async_flush(Response& r) {
r.async_flush();
return r;
}
static Response& flush(Response& r) {
r.flush();
return r;
}
class Request {
friend class ServerBase<socket_type>;
public:
std::string method, path, http_version;
std::istream content;
std::unordered_multimap<std::string, std::string> header;
std::smatch path_match;
std::string remote_endpoint_address;
unsigned short remote_endpoint_port;
private:
Request(): content(&streambuf) {}
boost::asio::streambuf streambuf;
void read_remote_endpoint_data(socket_type& socket) {
try {
remote_endpoint_address=socket.lowest_layer().remote_endpoint().address().to_string();
remote_endpoint_port=socket.lowest_layer().remote_endpoint().port();
}
catch(const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
};
std::unordered_map<std::string, std::unordered_map<std::string,
std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > > resource;
std::unordered_map<std::string,
std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > default_resource;
private:
std::vector<std::pair<std::string, std::vector<std::pair<std::regex,
std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > > > > opt_resource;
public:
void start() {
//Copy the resources to opt_resource for more efficient request processing
opt_resource.clear();
for(auto& res: resource) {
for(auto& res_method: res.second) {
auto it=opt_resource.end();
for(auto opt_it=opt_resource.begin();opt_it!=opt_resource.end();opt_it++) {
if(res_method.first==opt_it->first) {
it=opt_it;
break;
}
}
if(it==opt_resource.end()) {
opt_resource.emplace_back();
it=opt_resource.begin()+(opt_resource.size()-1);
it->first=res_method.first;
}
it->second.emplace_back(std::regex(res.first), res_method.second);
}
}
accept();
//If num_threads>1, start m_io_service.run() in (num_threads-1) threads for thread-pooling
threads.clear();
for(size_t c=1;c<num_threads;c++) {
threads.emplace_back([this](){
io_service.run();
});
}
//Main thread
io_service.run();
//Wait for the rest of the threads, if any, to finish as well
for(auto& t: threads) {
t.join();
}
}
void stop() {
io_service.stop();
}
protected:
boost::asio::io_service io_service;
boost::asio::ip::tcp::endpoint endpoint;
boost::asio::ip::tcp::acceptor acceptor;
size_t num_threads;
std::vector<std::thread> threads;
size_t timeout_request;
size_t timeout_content;
ServerBase(unsigned short port, size_t num_threads, size_t timeout_request, size_t timeout_send_or_receive) :
endpoint(boost::asio::ip::tcp::v4(), port), acceptor(io_service, endpoint), num_threads(num_threads),
timeout_request(timeout_request), timeout_content(timeout_send_or_receive) {}
virtual void accept()=0;
std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<socket_type> socket, size_t seconds) {
std::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(io_service));
timer->expires_from_now(boost::posix_time::seconds(seconds));
timer->async_wait([socket](const boost::system::error_code& ec){
if(!ec) {
boost::system::error_code ec;
socket->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
socket->lowest_layer().close();
}
});
return timer;
}
std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<socket_type> socket, std::shared_ptr<boost::asio::strand> strand, size_t seconds) {
std::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(io_service));
timer->expires_from_now(boost::posix_time::seconds(seconds));
timer->async_wait(strand->wrap([socket](const boost::system::error_code& ec){
if(!ec) {
boost::system::error_code ec;
socket->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
socket->lowest_layer().close();
}
}));
return timer;
}
void read_request_and_content(std::shared_ptr<socket_type> socket) {
//Create new streambuf (Request::streambuf) for async_read_until()
//shared_ptr is used to pass temporary objects to the asynchronous functions
std::shared_ptr<Request> request(new Request());
request->read_remote_endpoint_data(*socket);
//Set timeout on the following boost::asio::async-read or write function
std::shared_ptr<boost::asio::deadline_timer> timer;
if(timeout_request>0)
timer=set_timeout_on_socket(socket, timeout_request);
boost::asio::async_read_until(*socket, request->streambuf, "\r\n\r\n",
[this, socket, request, timer](const boost::system::error_code& ec, size_t bytes_transferred) {
if(timeout_request>0)
timer->cancel();
if(!ec) {
//request->streambuf.size() is not necessarily the same as bytes_transferred, from Boost-docs:
//"After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter"
//The chosen solution is to extract lines from the stream directly when parsing the header. What is left of the
//streambuf (maybe some bytes of the content) is appended to in the async_read-function below (for retrieving content).
size_t num_additional_bytes=request->streambuf.size()-bytes_transferred;
parse_request(request, request->content);
//If content, read that as well
const auto it=request->header.find("Content-Length");
if(it!=request->header.end()) {
//Set timeout on the following boost::asio::async-read or write function
std::shared_ptr<boost::asio::deadline_timer> timer;
if(timeout_content>0)
timer=set_timeout_on_socket(socket, timeout_content);
try {
auto content_length=stoull(it->second);
boost::asio::async_read(*socket, request->streambuf,
boost::asio::transfer_exactly(content_length-num_additional_bytes),
[this, socket, request, timer]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(timeout_content>0)
timer->cancel();
if(!ec)
find_resource(socket, request);
});
}
catch(const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
else {
find_resource(socket, request);
}
}
});
}
void parse_request(std::shared_ptr<Request> request, std::istream& stream) const {
std::string line;
getline(stream, line);
size_t method_end=line.find(' ');
size_t path_end=line.find(' ', method_end+1);
if(method_end!=std::string::npos && path_end!=std::string::npos) {
request->method=line.substr(0, method_end);
request->path=line.substr(method_end+1, path_end-method_end-1);
request->http_version=line.substr(path_end+6, line.size()-path_end-7);
getline(stream, line);
size_t param_end=line.find(':');
while(param_end!=std::string::npos) {
size_t value_start=param_end+1;
if(line[value_start]==' ')
value_start++;
std::string key=line.substr(0, param_end);
request->header.insert(std::make_pair(key, line.substr(value_start, line.size()-value_start-1)));
getline(stream, line);
param_end=line.find(':');
}
}
}
void find_resource(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request) {
//Find path- and method-match, and call write_response
for(auto& res: opt_resource) {
if(request->method==res.first) {
for(auto& res_path: res.second) {
std::smatch sm_res;
if(std::regex_match(request->path, sm_res, res_path.first)) {
request->path_match=std::move(sm_res);
write_response(socket, request, res_path.second);
return;
}
}
}
}
auto it_method=default_resource.find(request->method);
if(it_method!=default_resource.end()) {
write_response(socket, request, it_method->second);
}
}
void write_response(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request,
std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)>& resource_function) {
std::shared_ptr<boost::asio::strand> strand(new boost::asio::strand(io_service));
//Set timeout on the following boost::asio::async-read or write function
std::shared_ptr<boost::asio::deadline_timer> timer;
if(timeout_content>0)
timer=set_timeout_on_socket(socket, strand, timeout_content);
boost::asio::spawn(*strand, [this, strand, &resource_function, socket, request, timer](boost::asio::yield_context yield) {
Response response(io_service, socket, strand, yield);
try {
resource_function(response, request);
}
catch(std::exception& e) {
return;
}
response.async_flush([this, socket, request, timer](const boost::system::error_code& ec) {
if(timeout_content>0)
timer->cancel();
if(!ec && stof(request->http_version)>1.05)
read_request_and_content(socket);
});
});
}
};
template<class socket_type>
class Server : public ServerBase<socket_type> {};
typedef boost::asio::ip::tcp::socket HTTP;
template<>
class Server<HTTP> : public ServerBase<HTTP> {
public:
Server(unsigned short port, size_t num_threads=1, size_t timeout_request=5, size_t timeout_content=300) :
ServerBase<HTTP>::ServerBase(port, num_threads, timeout_request, timeout_content) {}
private:
void accept() {
//Create new socket for this connection
//Shared_ptr is used to pass temporary objects to the asynchronous functions
std::shared_ptr<HTTP> socket(new HTTP(io_service));
acceptor.async_accept(*socket, [this, socket](const boost::system::error_code& ec){
//Immediately start accepting a new connection
accept();
if(!ec) {
boost::asio::ip::tcp::no_delay option(true);
socket->set_option(option);
read_request_and_content(socket);
}
});
}
};
}
#endif /* SERVER_HTTP_HPP */
<|endoftext|>
|
<commit_before>/*
** Copyright 2009-2011 Merethis
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <string.h>
#include "com/centreon/broker/neb/log_entry.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/neb/internal.hh"
#include "com/centreon/broker/neb/set_log_data.hh"
using namespace com::centreon::broker;
/**
* Extract the first element of a log string.
*/
static char* log_extract_first(char* str, char** lasts) {
char* data(strtok_r(str, ";", lasts));
if (!data)
throw (exceptions::msg() << "log: data extraction failed");
return (data);
}
/**
* Extract following elements of a log string.
*/
static char* log_extract(char** lasts) {
char* data(strtok_r(NULL, ";", lasts));
if (!data)
throw (exceptions::msg() << "log: data extraction failed");
return (data);
}
/**
* Get the id of a log status.
*/
static int status_id(char const* status) {
int id;
if (!strcmp(status, "DOWN") || !strcmp(status, "WARNING"))
id = 1;
else if (!strcmp(status, "UNREACHABLE") || !strcmp(status, "CRITICAL"))
id = 2;
else if (!strcmp(status, "UNKNOWN"))
id = 3;
else if (!strcmp(status, "PENDING"))
id = 4;
else
id = 0;
return (id);
}
/**
* Get the id of a log type.
*/
static int type_id(char const* type) {
int id;
if (!strcmp(type, "HARD"))
id = 1;
else
id = 0;
return (id);
}
/**
* Extract Nagios-formated log data to the C++ object.
*/
void neb::set_log_data(neb::log_entry& le, char const* log_data) {
// Duplicate string so that we can split it with strtok_r.
char* datadup(strdup(log_data));
if (!datadup)
throw (exceptions::msg() << "log: data extraction failed");
try {
char* lasts;
// First part is the log description.
lasts = datadup + strcspn(datadup, ":");
if (*lasts) {
*lasts = '\0';
lasts = lasts + 1 + strspn(lasts + 1, " ");
}
if (!strcmp(datadup, "SERVICE ALERT")) {
le.msg_type = 0;
le.host_name = log_extract_first(lasts, &lasts);
le.service_description = log_extract(&lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "HOST ALERT")) {
le.msg_type = 1;
le.host_name = log_extract_first(lasts, &lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "SERVICE NOTIFICATION")) {
le.msg_type = 2;
le.notification_contact = log_extract_first(lasts, &lasts);
le.host_name = log_extract(&lasts);
le.service_description = log_extract(&lasts);
le.status = status_id(log_extract(&lasts));
le.notification_cmd = log_extract(&lasts);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "HOST NOTIFICATION")) {
le.msg_type = 3;
le.notification_contact = log_extract_first(lasts, &lasts);
le.host_name = log_extract(&lasts);
le.status = status_id(log_extract(&lasts));
le.notification_cmd = log_extract(&lasts);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "CURRENT SERVICE STATE")) {
le.msg_type = 6;
le.host_name = log_extract_first(lasts, &lasts);
le.service_description = log_extract(&lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "CURRENT HOST STATE")) {
le.msg_type = 7;
le.host_name = log_extract_first(lasts, &lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "INITIAL HOST STATE")) {
le.msg_type = 9;
le.host_name = log_extract_first(lasts, &lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "INITIAL SERVICE STATE")) {
le.msg_type = 8;
le.host_name = log_extract_first(lasts, &lasts);
le.service_description = log_extract(&lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "EXTERNAL COMMAND")) {
char* data(log_extract_first(lasts, &lasts));
if (!strcmp(data, "ACKNOWLEDGE_SVC_PROBLEM")) {
le.msg_type = 10;
le.host_name = log_extract(&lasts);
le.service_description = log_extract(&lasts);
log_extract(&lasts);
log_extract(&lasts);
log_extract(&lasts);
le.notification_contact = log_extract(&lasts);
le.output = log_extract(&lasts);
}
else if (!strcmp(data, "ACKNOWLEDGE_HOST_PROBLEM")) {
le.msg_type = 11;
le.host_name = log_extract(&lasts);
log_extract(&lasts);
log_extract(&lasts);
log_extract(&lasts);
le.notification_contact = log_extract(&lasts);
le.output = log_extract(&lasts);
}
else
// XXX : seems like it should be something else ...
throw (exceptions::msg() << "log: data extraction failed");
}
else if (!strcmp(datadup, "Warning")) {
le.msg_type = 4;
le.output = lasts;
}
else {
le.msg_type = 5;
le.output = log_data;
}
}
catch (...) {}
free(datadup);
// Set host and service IDs.
std::map<std::string, int>::const_iterator host_it;
std::map<std::pair<std::string, std::string>, std::pair<int, int> >::const_iterator service_it;
host_it = neb::gl_hosts.find(le.host_name.toStdString());
if (host_it != neb::gl_hosts.end())
le.host_id = host_it->second;
service_it = neb::gl_services.find(std::make_pair(le.host_name.toStdString(),
le.service_description.toStdString()));
if (service_it != neb::gl_services.end()) {
le.host_id = service_it->second.first;
le.service_id = service_it->second.second;
}
return ;
}
<commit_msg>Fix log entries of external commands.<commit_after>/*
** Copyright 2009-2011 Merethis
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <string.h>
#include "com/centreon/broker/neb/log_entry.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/neb/internal.hh"
#include "com/centreon/broker/neb/set_log_data.hh"
using namespace com::centreon::broker;
/**
* Extract the first element of a log string.
*/
static char* log_extract_first(char* str, char** lasts) {
char* data(strtok_r(str, ";", lasts));
if (!data)
throw (exceptions::msg() << "log: data extraction failed");
return (data);
}
/**
* Extract following elements of a log string.
*/
static char* log_extract(char** lasts) {
char* data(strtok_r(NULL, ";", lasts));
if (!data)
throw (exceptions::msg() << "log: data extraction failed");
return (data);
}
/**
* Get the id of a log status.
*/
static int status_id(char const* status) {
int id;
if (!strcmp(status, "DOWN") || !strcmp(status, "WARNING"))
id = 1;
else if (!strcmp(status, "UNREACHABLE") || !strcmp(status, "CRITICAL"))
id = 2;
else if (!strcmp(status, "UNKNOWN"))
id = 3;
else if (!strcmp(status, "PENDING"))
id = 4;
else
id = 0;
return (id);
}
/**
* Get the id of a log type.
*/
static int type_id(char const* type) {
int id;
if (!strcmp(type, "HARD"))
id = 1;
else
id = 0;
return (id);
}
/**
* Extract Nagios-formated log data to the C++ object.
*/
void neb::set_log_data(neb::log_entry& le, char const* log_data) {
// Duplicate string so that we can split it with strtok_r.
char* datadup(strdup(log_data));
if (!datadup)
throw (exceptions::msg() << "log: data extraction failed");
try {
char* lasts;
// First part is the log description.
lasts = datadup + strcspn(datadup, ":");
if (*lasts) {
*lasts = '\0';
lasts = lasts + 1 + strspn(lasts + 1, " ");
}
if (!strcmp(datadup, "SERVICE ALERT")) {
le.msg_type = 0;
le.host_name = log_extract_first(lasts, &lasts);
le.service_description = log_extract(&lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "HOST ALERT")) {
le.msg_type = 1;
le.host_name = log_extract_first(lasts, &lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "SERVICE NOTIFICATION")) {
le.msg_type = 2;
le.notification_contact = log_extract_first(lasts, &lasts);
le.host_name = log_extract(&lasts);
le.service_description = log_extract(&lasts);
le.status = status_id(log_extract(&lasts));
le.notification_cmd = log_extract(&lasts);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "HOST NOTIFICATION")) {
le.msg_type = 3;
le.notification_contact = log_extract_first(lasts, &lasts);
le.host_name = log_extract(&lasts);
le.status = status_id(log_extract(&lasts));
le.notification_cmd = log_extract(&lasts);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "CURRENT SERVICE STATE")) {
le.msg_type = 6;
le.host_name = log_extract_first(lasts, &lasts);
le.service_description = log_extract(&lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "CURRENT HOST STATE")) {
le.msg_type = 7;
le.host_name = log_extract_first(lasts, &lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "INITIAL HOST STATE")) {
le.msg_type = 9;
le.host_name = log_extract_first(lasts, &lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "INITIAL SERVICE STATE")) {
le.msg_type = 8;
le.host_name = log_extract_first(lasts, &lasts);
le.service_description = log_extract(&lasts);
le.status = status_id(log_extract(&lasts));
le.log_type = type_id(log_extract(&lasts));
le.retry = strtol(log_extract(&lasts), NULL, 10);
le.output = log_extract(&lasts);
}
else if (!strcmp(datadup, "EXTERNAL COMMAND")) {
char* data(log_extract_first(lasts, &lasts));
if (!strcmp(data, "ACKNOWLEDGE_SVC_PROBLEM")) {
le.msg_type = 10;
le.host_name = log_extract(&lasts);
le.service_description = log_extract(&lasts);
log_extract(&lasts);
log_extract(&lasts);
log_extract(&lasts);
le.notification_contact = log_extract(&lasts);
le.output = log_extract(&lasts);
}
else if (!strcmp(data, "ACKNOWLEDGE_HOST_PROBLEM")) {
le.msg_type = 11;
le.host_name = log_extract(&lasts);
log_extract(&lasts);
log_extract(&lasts);
log_extract(&lasts);
le.notification_contact = log_extract(&lasts);
le.output = log_extract(&lasts);
}
else {
le.msg_type = 5;
le.output = "EXTERNAL COMMAND: ";
le.output.append(lasts);
}
}
else if (!strcmp(datadup, "Warning")) {
le.msg_type = 4;
le.output = lasts;
}
else {
le.msg_type = 5;
le.output = log_data;
}
}
catch (...) {}
free(datadup);
// Set host and service IDs.
std::map<std::string, int>::const_iterator host_it;
std::map<std::pair<std::string, std::string>, std::pair<int, int> >::const_iterator service_it;
host_it = neb::gl_hosts.find(le.host_name.toStdString());
if (host_it != neb::gl_hosts.end())
le.host_id = host_it->second;
service_it = neb::gl_services.find(std::make_pair(le.host_name.toStdString(),
le.service_description.toStdString()));
if (service_it != neb::gl_services.end()) {
le.host_id = service_it->second.first;
le.service_id = service_it->second.second;
}
return ;
}
<|endoftext|>
|
<commit_before>/// HEADER
#include "svm_array_trainer.h"
/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/generic_vector_message.hpp>
CSAPEX_REGISTER_CLASS(csapex::SVMArrayTrainer, csapex::Node)
using namespace csapex;
using namespace csapex::connection_types;
template<typename T>
inline std::string toString(const T value)
{
std::stringstream ss;
ss << value;
return ss.str();
}
struct ExtendedSVM : public cv::SVM {
typedef std::shared_ptr<ExtendedSVM> Ptr;
CvSVMDecisionFunc* get_decision_function()
{
return decision_func;
}
void print_decision_func()
{
std::cout << "alpha: [";
for(int i = 0 ; i < decision_func->sv_count - 1; ++i) {
std::cout << decision_func->alpha[i] << ", ";
}
std::cout << decision_func->alpha[decision_func->sv_count - 1]
<< "]" << std::endl;
std::cout << "rho: " << decision_func->rho * -1 << std::endl;
}
void export_decision_func(cv::FileStorage &fs)
{
fs << "svm_alpha" << "[";
for(int i = 0 ; i < decision_func->sv_count ; ++i)
fs << decision_func->alpha[i];
fs << "]";
fs << "svm_rho" << -decision_func->rho;
}
void set_parameters(const cv::SVMParams ¶ms)
{
set_params(params);
}
};
SVMArrayTrainer::SVMArrayTrainer()
{
}
void SVMArrayTrainer::setupParameters(Parameterizable& parameters)
{
CollectionNode<connection_types::FeaturesMessage>::setupParameters(parameters);
parameters.addParameter(param::ParameterFactory::declareFileOutputPath("svm/path",
param::ParameterDescription("File to write svm to."),
"",
"*.yaml *.tar.gz"),
path_);
parameters.addParameter(param::ParameterFactory::declareBool("svm/save_coeffs",
param::ParameterDescription("Save precomputed vector for HOG."),
false),
save_for_hog_);
std::map<std::string, int> kernel_types = {
{"LINEAR", cv::SVM::LINEAR},
{"POLY", cv::SVM::POLY},
{"RBF", cv::SVM::RBF},
{"SIGMOID", cv::SVM::SIGMOID}
};
parameters.addParameter(param::ParameterFactory::declareParameterSet("svm/kernel_type",
csapex::param::ParameterDescription("Kernel type to be trained."),
kernel_types,
(int) cv::SVM::RBF),
svm_params_.kernel_type);
std::map<std::string, int> svm_types = {
{"C_SVC", cv::SVM::C_SVC},
{"NU_SVC", cv::SVM::NU_SVC},
{"ONE_CLASS", cv::SVM::ONE_CLASS},
{"EPS_SVR", cv::SVM::EPS_SVR},
{"NU_SVR", cv::SVM::NU_SVR}
};
parameters.addParameter(param::ParameterFactory::declareParameterSet("svm type",
csapex::param::ParameterDescription("SVM type to be trained."),
svm_types,
(int) cv::SVM::EPS_SVR),
svm_params_.svm_type);
std::function<bool()> deg_cond = [this]() {
return svm_params_.kernel_type == cv::SVM::POLY;};
std::function<bool()> gamma_cond = [this]() {
return svm_params_.kernel_type == cv::SVM::POLY ||
svm_params_.kernel_type == cv::SVM::RBF ||
svm_params_.kernel_type == cv::SVM::SIGMOID;};
std::function<bool()> coeff0_cond = [this]() {
return svm_params_.kernel_type == cv::SVM::POLY ||
svm_params_.kernel_type == cv::SVM::SIGMOID;};
std::function<bool()> c_cond = [this]() {
return svm_params_.svm_type == cv::SVM::C_SVC ||
svm_params_.svm_type == cv::SVM::EPS_SVR ||
svm_params_.svm_type == cv::SVM::NU_SVR;};
std::function<bool()> nu_cond = [this]() {
return svm_params_.svm_type == cv::SVM::ONE_CLASS ||
svm_params_.svm_type == cv::SVM::NU_SVR ||
svm_params_.svm_type == cv::SVM::EPS_SVR;};
std::function<bool()> p_cond = [this]() {
return svm_params_.svm_type == cv::SVM::EPS_SVR;};
parameters.addConditionalParameter(param::ParameterFactory::declareRange<double>("degree", 0.0, 9.0, 3.0, 1.0),
deg_cond,
svm_params_.degree);
parameters.addConditionalParameter(param::ParameterFactory::declareRange<double>("gamma", 0.0, 10.0, 0.0, 0.01),
gamma_cond,
svm_params_.gamma);
parameters.addConditionalParameter(param::ParameterFactory::declareRange<double>("coef0", -10.0, 10.0, 0.0, 0.01),
coeff0_cond,
svm_params_.coef0);
parameters.addConditionalParameter(param::ParameterFactory::declareRange<double>("C", 0.0, 10.0, 0.01, 0.01),
c_cond,
svm_params_.C);
parameters.addConditionalParameter(param::ParameterFactory::declareRange<double>("nu", 0.0, 1.0, 0.5, 0.01),
nu_cond,
svm_params_.nu);
parameters.addConditionalParameter(csapex::param::ParameterFactory::declareRange<double>("p", 0.0, 1.0, 0.1, 0.01),
p_cond,
svm_params_.p);
}
void SVMArrayTrainer::processCollection(std::vector<FeaturesMessage> &collection)
{
/// TODO : Mix classes for negative samples?
if(collection.empty())
return;
std::size_t step = collection.front().value.size();
std::map<int, std::vector<std::size_t>> indices_by_label;
for(std::size_t i = 0 ; i < collection.size() ; ++i) {
const FeaturesMessage &fm = collection[i];
if(fm.value.size() != step)
throw std::runtime_error("All descriptors must have the same length!");
indices_by_label[fm.classification].push_back(i);
}
std::map<int, ExtendedSVM::Ptr> svms;
if(svm_params_.svm_type != cv::SVM::ONE_CLASS) {
if(indices_by_label.find(NEGATIVE) == indices_by_label.end()) {
throw std::runtime_error("Need negative examples labelled with -1");
}
if(indices_by_label.size() == 1) {
throw std::runtime_error("Multi class SVMs require multiple classes!");
}
std::vector<std::size_t> neg_indices = indices_by_label[NEGATIVE];
indices_by_label.erase(NEGATIVE);
/// iterate samples
for(std::size_t i = 0 ; i < indices_by_label.size() ; ++i) {
auto it = indices_by_label.begin();
std::advance(it, i);
/// allocate svm
ExtendedSVM::Ptr svm(new ExtendedSVM);
svms[it->first] = svm;
/// gather data
const std::vector<std::size_t> &pos_indices = it->second;
const std::size_t sample_size = pos_indices.size() + neg_indices.size();
cv::Mat samples(sample_size, step, CV_32FC1, cv::Scalar());
cv::Mat labels(sample_size, 1, CV_32FC1, cv::Scalar());
cv::Mat neg_samples = samples.rowRange(0, neg_indices.size());
cv::Mat pos_samples = samples.rowRange(neg_indices.size(), sample_size);
cv::Mat neg_labels = labels.rowRange(0, neg_indices.size());
cv::Mat pos_labels = labels.rowRange(neg_indices.size(), sample_size);
for(int i = 0 ; i < neg_samples.rows; ++i) {
const std::vector<float> &data = collection.at(neg_indices.at(i)).value;
neg_labels.at<float>(i) = NEGATIVE;
for(std::size_t j = 0 ; j < step ; ++j) {
neg_samples.at<float>(i,j) = data.at(j);
}
}
for(int i = 0 ; i < pos_samples.rows ; ++i) {
const std::vector<float> &data = collection.at(pos_indices.at(i)).value;
pos_labels.at<float>(i) = POSITIVE;
for(std::size_t j = 0 ; j < step ; ++j) {
pos_samples.at<float>(i,j) = data.at(j);
}
}
cv::SVMParams params = svm_params_;
if(params.gamma == 0) {
params.gamma = 1.0 / labels.rows;
}
/// train the svm
std::cout << "Started training for '" << it->first << std::endl;
svm.reset(new ExtendedSVM);
if(svm->train(samples, labels, cv::Mat(), cv::Mat(), params)) {
std::cout << "Finished training for '" << it->first << std::endl;
}
}
} else {
if(indices_by_label.find(NEGATIVE) != indices_by_label.end()) {
indices_by_label.erase(NEGATIVE);
}
/// iterate samples
/// mixed classes?
for(std::size_t i = 0 ; i < indices_by_label.size() ; ++i) {
auto it = indices_by_label.begin();
std::advance(it, i);
/// allocate svm
ExtendedSVM::Ptr svm(new ExtendedSVM);
svms[it->first] = svm;
/// gather data
const std::vector<std::size_t> &indices = it->second;
const std::size_t sample_size = indices.size();
cv::Mat samples(sample_size, step, CV_32FC1, cv::Scalar());
cv::Mat labels(sample_size, 1, CV_32FC1, cv::Scalar());
for(int i = 0 ; i < samples.rows ; ++i) {
const std::vector<float> &data = collection.at(indices.at(i)).value;
labels.at<float>(i) = POSITIVE;
for(std::size_t j = 0 ; j < step ; ++j) {
samples.at<float>(i,j) = data.at(j);
}
}
cv::SVMParams params = svm_params_;
if(params.gamma == 0) {
params.gamma = 1.0 / labels.rows;
}
/// train the svm
std::cout << "Started training for '" << it->first << std::endl;
svm.reset(new ExtendedSVM);
if(svm->train(samples, labels, cv::Mat(), cv::Mat(), params)) {
std::cout << "Finished training for '" << it->first << std::endl;
}
}
}
/// write all svms to disk
cv::FileStorage fs(path_, cv::FileStorage::WRITE);
const static std::string prefix = "svm_";
std::vector<int> labels;
for(auto &svm_entry : svms) {
std::string label = prefix + toString(svm_entry.first);
ExtendedSVM::Ptr svm = svm_entry.second;
svm->write(fs.fs, label.c_str());
labels.push_back(svm_entry.first);
}
fs << "labels" << labels;
fs.release();
}
<commit_msg>svm array training works now<commit_after>/// HEADER
#include "svm_array_trainer.h"
/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/generic_vector_message.hpp>
CSAPEX_REGISTER_CLASS(csapex::SVMArrayTrainer, csapex::Node)
using namespace csapex;
using namespace csapex::connection_types;
template<typename T>
inline std::string toString(const T value)
{
std::stringstream ss;
ss << value;
return ss.str();
}
struct ExtendedSVM : public cv::SVM {
typedef std::shared_ptr<ExtendedSVM> Ptr;
CvSVMDecisionFunc* get_decision_function()
{
return decision_func;
}
void print_decision_func()
{
std::cout << "alpha: [";
for(int i = 0 ; i < decision_func->sv_count - 1; ++i) {
std::cout << decision_func->alpha[i] << ", ";
}
std::cout << decision_func->alpha[decision_func->sv_count - 1]
<< "]" << std::endl;
std::cout << "rho: " << decision_func->rho * -1 << std::endl;
}
void export_decision_func(cv::FileStorage &fs)
{
fs << "svm_alpha" << "[";
for(int i = 0 ; i < decision_func->sv_count ; ++i)
fs << decision_func->alpha[i];
fs << "]";
fs << "svm_rho" << -decision_func->rho;
}
void set_parameters(const cv::SVMParams ¶ms)
{
set_params(params);
}
};
SVMArrayTrainer::SVMArrayTrainer()
{
}
void SVMArrayTrainer::setupParameters(Parameterizable& parameters)
{
CollectionNode<connection_types::FeaturesMessage>::setupParameters(parameters);
parameters.addParameter(param::ParameterFactory::declareFileOutputPath("svm/path",
param::ParameterDescription("File to write svm to."),
"",
"*.yaml *.tar.gz"),
path_);
parameters.addParameter(param::ParameterFactory::declareBool("svm/save_coeffs",
param::ParameterDescription("Save precomputed vector for HOG."),
false),
save_for_hog_);
std::map<std::string, int> kernel_types = {
{"LINEAR", cv::SVM::LINEAR},
{"POLY", cv::SVM::POLY},
{"RBF", cv::SVM::RBF},
{"SIGMOID", cv::SVM::SIGMOID}
};
parameters.addParameter(param::ParameterFactory::declareParameterSet("svm/kernel_type",
csapex::param::ParameterDescription("Kernel type to be trained."),
kernel_types,
(int) cv::SVM::RBF),
svm_params_.kernel_type);
std::map<std::string, int> svm_types = {
{"C_SVC", cv::SVM::C_SVC},
{"NU_SVC", cv::SVM::NU_SVC},
{"ONE_CLASS", cv::SVM::ONE_CLASS},
{"EPS_SVR", cv::SVM::EPS_SVR},
{"NU_SVR", cv::SVM::NU_SVR}
};
parameters.addParameter(param::ParameterFactory::declareParameterSet("svm type",
csapex::param::ParameterDescription("SVM type to be trained."),
svm_types,
(int) cv::SVM::EPS_SVR),
svm_params_.svm_type);
std::function<bool()> deg_cond = [this]() {
return svm_params_.kernel_type == cv::SVM::POLY;};
std::function<bool()> gamma_cond = [this]() {
return svm_params_.kernel_type == cv::SVM::POLY ||
svm_params_.kernel_type == cv::SVM::RBF ||
svm_params_.kernel_type == cv::SVM::SIGMOID;};
std::function<bool()> coeff0_cond = [this]() {
return svm_params_.kernel_type == cv::SVM::POLY ||
svm_params_.kernel_type == cv::SVM::SIGMOID;};
std::function<bool()> c_cond = [this]() {
return svm_params_.svm_type == cv::SVM::C_SVC ||
svm_params_.svm_type == cv::SVM::EPS_SVR ||
svm_params_.svm_type == cv::SVM::NU_SVR;};
std::function<bool()> nu_cond = [this]() {
return svm_params_.svm_type == cv::SVM::ONE_CLASS ||
svm_params_.svm_type == cv::SVM::NU_SVR ||
svm_params_.svm_type == cv::SVM::EPS_SVR;};
std::function<bool()> p_cond = [this]() {
return svm_params_.svm_type == cv::SVM::EPS_SVR;};
parameters.addConditionalParameter(param::ParameterFactory::declareRange<double>("degree", 0.0, 9.0, 3.0, 1.0),
deg_cond,
svm_params_.degree);
parameters.addConditionalParameter(param::ParameterFactory::declareRange<double>("gamma", 0.0, 10.0, 0.0, 0.01),
gamma_cond,
svm_params_.gamma);
parameters.addConditionalParameter(param::ParameterFactory::declareRange<double>("coef0", -10.0, 10.0, 0.0, 0.01),
coeff0_cond,
svm_params_.coef0);
parameters.addConditionalParameter(param::ParameterFactory::declareRange<double>("C", 0.0, 10.0, 0.01, 0.01),
c_cond,
svm_params_.C);
parameters.addConditionalParameter(param::ParameterFactory::declareRange<double>("nu", 0.0, 1.0, 0.5, 0.01),
nu_cond,
svm_params_.nu);
parameters.addConditionalParameter(csapex::param::ParameterFactory::declareRange<double>("p", 0.0, 1.0, 0.1, 0.01),
p_cond,
svm_params_.p);
}
void SVMArrayTrainer::processCollection(std::vector<FeaturesMessage> &collection)
{
/// TODO : Mix classes for negative samples?
if(collection.empty())
return;
std::size_t step = collection.front().value.size();
std::map<int, std::vector<std::size_t>> indices_by_label;
for(std::size_t i = 0 ; i < collection.size() ; ++i) {
const FeaturesMessage &fm = collection[i];
if(fm.value.size() != step)
throw std::runtime_error("All descriptors must have the same length!");
indices_by_label[fm.classification].push_back(i);
}
// /// write all svms to disk
// for(auto &svm_entry : svms) {
// }
std::vector<int> svm_labels;
cv::FileStorage fs(path_, cv::FileStorage::WRITE);
const static std::string prefix = "svm_";
if(svm_params_.svm_type != cv::SVM::ONE_CLASS) {
if(indices_by_label.find(NEGATIVE) == indices_by_label.end()) {
throw std::runtime_error("Need negative examples labelled with -1");
}
if(indices_by_label.size() == 1) {
throw std::runtime_error("Multi class SVMs require multiple classes!");
}
std::vector<std::size_t> neg_indices = indices_by_label[NEGATIVE];
indices_by_label.erase(NEGATIVE);
/// iterate samples
for(std::size_t i = 0 ; i < indices_by_label.size() ; ++i) {
auto it = indices_by_label.begin();
std::advance(it, i);
/// allocate svm
ExtendedSVM svm;
/// gather data
const std::vector<std::size_t> &pos_indices = it->second;
const std::size_t sample_size = pos_indices.size() + neg_indices.size();
cv::Mat samples(sample_size, step, CV_32FC1, cv::Scalar());
cv::Mat labels(sample_size, 1, CV_32FC1, cv::Scalar());
cv::Mat neg_samples = samples.rowRange(0, neg_indices.size());
cv::Mat pos_samples = samples.rowRange(neg_indices.size(), sample_size);
cv::Mat neg_labels = labels.rowRange(0, neg_indices.size());
cv::Mat pos_labels = labels.rowRange(neg_indices.size(), sample_size);
for(int i = 0 ; i < neg_samples.rows; ++i) {
const std::vector<float> &data = collection.at(neg_indices.at(i)).value;
neg_labels.at<float>(i) = NEGATIVE;
for(std::size_t j = 0 ; j < step ; ++j) {
neg_samples.at<float>(i,j) = data.at(j);
}
}
for(int i = 0 ; i < pos_samples.rows ; ++i) {
const std::vector<float> &data = collection.at(pos_indices.at(i)).value;
pos_labels.at<float>(i) = POSITIVE;
for(std::size_t j = 0 ; j < step ; ++j) {
pos_samples.at<float>(i,j) = data.at(j);
}
}
cv::SVMParams params = svm_params_;
if(params.gamma == 0) {
params.gamma = 1.0 / labels.rows;
}
/// train the svm
std::cout << "Started training for '" << it->first << std::endl;
if(svm.train(samples, labels, cv::Mat(), cv::Mat(), params)) {
std::cout << "Finished training for '" << it->first << "'!" << std::endl;
std::string label = prefix + toString(it->first);
svm.write(fs.fs, label.c_str());
svm_labels.push_back(it->first);
} else {
std::cerr << "Failed traininng for '" << it->first << "'!" << std::endl;
}
}
} else {
if(indices_by_label.find(NEGATIVE) != indices_by_label.end()) {
indices_by_label.erase(NEGATIVE);
}
/// iterate samples
/// mixed classes?
for(std::size_t i = 0 ; i < indices_by_label.size() ; ++i) {
auto it = indices_by_label.begin();
std::advance(it, i);
/// allocate svm
ExtendedSVM svm;
/// gather data
const std::vector<std::size_t> &indices = it->second;
const std::size_t sample_size = indices.size();
cv::Mat samples(sample_size, step, CV_32FC1, cv::Scalar());
cv::Mat labels(sample_size, 1, CV_32FC1, cv::Scalar());
for(int i = 0 ; i < samples.rows ; ++i) {
const std::vector<float> &data = collection.at(indices.at(i)).value;
labels.at<float>(i) = POSITIVE;
for(std::size_t j = 0 ; j < step ; ++j) {
samples.at<float>(i,j) = data.at(j);
}
}
cv::SVMParams params = svm_params_;
if(params.gamma == 0) {
params.gamma = 1.0 / labels.rows;
}
/// train the svm
std::cout << "Started training for '" << it->first << std::endl;
if(svm.train(samples, labels, cv::Mat(), cv::Mat(), params)) {
std::cout << "Finished training for '" << it->first << std::endl;
std::string label = prefix + toString(it->first);
svm.write(fs.fs, label.c_str());
svm_labels.push_back(it->first);
} else {
std::cerr << "Failed traininng for '" << it->first << "'!" << std::endl;
}
}
}
fs << "labels" << svm_labels;
fs.release();
// /// write all svms to disk
// cv::FileStorage fs(path_, cv::FileStorage::WRITE);
// const static std::string prefix = "svm_";
// std::vector<int> labels;
// for(auto &svm_entry : svms) {
// std::string label = prefix + toString(svm_entry.first);
// ExtendedSVM::Ptr svm = svm_entry.second;
// svm->write(fs.fs, label.c_str());
// labels.push_back(svm_entry.first);
// }
// fs << "labels" << labels;
// fs.release();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2009 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/// \file Win32FaultHandler.cpp
//-----------------------------------------------------------------------------
// Only produce minidumps in release code
/*
* Get everything set up now.
* Use only standard Windows functions in FaultHandler
*
* *** *** *** *** ***
* NOTE: NO MFC CODE
* *** *** *** *** ***
*/
#ifndef _DEBUG
#include "stdafx.h"
#include "resource3.h"
#include <stdio.h>
#include <sys/timeb.h>
#include <time.h>
#include "Dbghelp.h"
LONG Win32FaultHandler(struct _EXCEPTION_POINTERS *ExInfo);
static DWORD dwTimeStamp;
static int iMajor, iMinor, iBuild;
static wchar_t *wcRevision = NULL;
static wchar_t *wcMsg1 = NULL;
static wchar_t *wcMsg2 = NULL;
static wchar_t *wcMsg3 = NULL;
static wchar_t *wcCaption = NULL;
void InstallFaultHandler(const int major, const int minor, const int build,
const wchar_t *revision, const DWORD timestamp)
{
iMajor = major;
iMinor = minor;
iBuild = build;
wcRevision = _wcsdup(revision);
dwTimeStamp = timestamp;
// Set up message now - just in case!
wchar_t wcBuffer[4096];
LoadString(GetModuleHandle(NULL), IDS_MD_MSG1, wcBuffer, 4096);
wcMsg1 = _wcsdup(wcBuffer);
LoadString(GetModuleHandle(NULL), IDS_MD_MSG2, wcBuffer, 4096);
wcMsg2 = _wcsdup(wcBuffer);
LoadString(GetModuleHandle(NULL), IDS_MD_MSG3, wcBuffer, 4096);
wcMsg3 = _wcsdup(wcBuffer);
LoadString(GetModuleHandle(NULL), IDS_MD_CAPTION, wcBuffer, 4096);
wcCaption = _wcsdup(wcBuffer);
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)Win32FaultHandler);
}
LONG Win32FaultHandler(struct _EXCEPTION_POINTERS *ExInfo)
{
// Use standard functions as much as possible
wchar_t szTempName[MAX_PATH + 1];
wchar_t szDrive[_MAX_DRIVE], szDir[_MAX_DIR], szFName[_MAX_FNAME];
wchar_t wcTempPath[4096];
DWORD dwBufSize(4096);
// Get the temp path
DWORD dwrc = GetTempPathW(dwBufSize, wcTempPath);
if (dwrc == 0 || dwrc > dwBufSize)
goto exit;
// Create a temporary file.
struct tm xt;
struct __timeb32 timebuffer;
_ftime32_s(&timebuffer);
localtime_s(&xt, &(timebuffer.time));
_wsplitpath_s(wcTempPath, szDrive, _MAX_DRIVE, szDir, _MAX_DIR,
NULL, 0, NULL, 0);
swprintf_s(szFName, _MAX_FNAME, L"PWS_Minidump_%04d%02d%02d_%02d%02d%02d%03d",
xt.tm_year + 1900, xt.tm_mon + 1, xt.tm_mday,
xt.tm_hour, xt.tm_min, xt.tm_sec, timebuffer.millitm);
_wmakepath_s(szTempName, MAX_PATH + 1, szDrive, szDir, szFName, L"dmp");
wchar_t szUserData[MAX_PATH];
swprintf_s(szUserData, MAX_PATH, L"PasswordSafe V%d.%d.%d(%s). Module timestamp: %08x",
iMajor, iMinor, iBuild, wcRevision, dwTimeStamp);
HANDLE hFile = CreateFile(szTempName, GENERIC_READ | GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
MINIDUMP_EXCEPTION_INFORMATION excpInfo;
excpInfo.ClientPointers = FALSE;
excpInfo.ExceptionPointers = ExInfo;
excpInfo.ThreadId = GetCurrentThreadId();
MINIDUMP_USER_STREAM UserStreams[1];
UserStreams[0].Type = LastReservedStream + 1;
UserStreams[0].Buffer = (void *)szUserData;
UserStreams[0].BufferSize = sizeof(szUserData);
MINIDUMP_USER_STREAM_INFORMATION musi;
musi.UserStreamCount = 1;
musi.UserStreamArray = UserStreams;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile,
MiniDumpNormal, &excpInfo, &musi, NULL);
CloseHandle(hFile);
size_t len = wcslen(wcMsg1) + wcslen(szFName) + wcslen(wcMsg2) +
wcslen(wcTempPath) + wcslen(wcMsg3) + 3;
wchar_t *sz_errormsg = (wchar_t *)malloc(len * sizeof(wchar_t));
wcscpy_s(sz_errormsg, len, wcMsg1);
wcscat_s(sz_errormsg, len, szFName);
wcscat_s(sz_errormsg, len, wcMsg2);
wcscat_s(sz_errormsg, len, wcTempPath);
wcscat_s(sz_errormsg, len, wcMsg3);
// Issue error message
wchar_t szCaption[MAX_PATH];
swprintf_s(szCaption, MAX_PATH, wcCaption,
iMajor, iMinor, iBuild, wcRevision);
int irc = ::MessageBox(GetForegroundWindow(), sz_errormsg, szCaption,
MB_YESNO | MB_APPLMODAL | MB_ICONERROR);
if (irc == IDNO)
_wremove(szTempName);
free(sz_errormsg);
free(wcRevision);
free(wcMsg1);
free(wcMsg2);
free(wcMsg3);
free(wcCaption);
wcRevision = NULL;
wcMsg1 = NULL;
wcMsg2 = NULL;
wcMsg3 = NULL;
wcCaption = NULL;
exit:
return EXCEPTION_CONTINUE_SEARCH;
}
void RemoveFaultHandler()
{
free(wcRevision);
free(wcMsg1);
free(wcMsg2);
free(wcMsg3);
free(wcCaption);
wcRevision = NULL;
wcMsg1 = NULL;
wcMsg2 = NULL;
wcMsg3 = NULL;
wcCaption = NULL;
SetUnhandledExceptionFilter(NULL);
}
#endif
<commit_msg>robust++ fault handling<commit_after>/*
* Copyright (c) 2003-2009 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/// \file Win32FaultHandler.cpp
//-----------------------------------------------------------------------------
// Only produce minidumps in release code
/*
* Get everything set up now.
* Use only standard Windows functions in FaultHandler
*
* *** *** *** *** ***
* NOTE: NO MFC CODE
* *** *** *** *** ***
*/
#ifndef _DEBUG
#include "stdafx.h"
#include "resource3.h"
#include <stdio.h>
#include <sys/timeb.h>
#include <time.h>
#include "Dbghelp.h"
LONG Win32FaultHandler(struct _EXCEPTION_POINTERS *ExInfo);
const int MSGSIZE = 1024; // use static arrays, in case heap gets corrupted
static DWORD dwTimeStamp;
static int iMajor, iMinor, iBuild;
static wchar_t wcRevision[MSGSIZE];
static wchar_t wcMsg1[MSGSIZE];
static wchar_t wcMsg2[MSGSIZE];
static wchar_t wcMsg3[MSGSIZE];
static wchar_t wcCaption[MSGSIZE];
void InstallFaultHandler(const int major, const int minor, const int build,
const wchar_t *revision, const DWORD timestamp)
{
iMajor = major;
iMinor = minor;
iBuild = build;
wcscpy_s(wcRevision, revision);
dwTimeStamp = timestamp;
// Set up message now - just in case!
LoadString(GetModuleHandle(NULL), IDS_MD_MSG1, wcMsg1, MSGSIZE);
LoadString(GetModuleHandle(NULL), IDS_MD_MSG2, wcMsg2, MSGSIZE);
LoadString(GetModuleHandle(NULL), IDS_MD_MSG3, wcMsg3, MSGSIZE);
LoadString(GetModuleHandle(NULL), IDS_MD_CAPTION, wcCaption, MSGSIZE);
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)Win32FaultHandler);
}
LONG Win32FaultHandler(struct _EXCEPTION_POINTERS *ExInfo)
{
// Use standard functions as much as possible
wchar_t szTempName[MAX_PATH + 1];
wchar_t szDrive[_MAX_DRIVE], szDir[_MAX_DIR], szFName[_MAX_FNAME];
wchar_t wcTempPath[4096];
DWORD dwBufSize(4096);
// Get the temp path
DWORD dwrc = GetTempPathW(dwBufSize, wcTempPath);
if (dwrc == 0 || dwrc > dwBufSize)
goto exit;
// Create a temporary file.
struct tm xt;
struct __timeb32 timebuffer;
_ftime32_s(&timebuffer);
localtime_s(&xt, &(timebuffer.time));
_wsplitpath_s(wcTempPath, szDrive, _MAX_DRIVE, szDir, _MAX_DIR,
NULL, 0, NULL, 0);
swprintf_s(szFName, _MAX_FNAME, L"PWS_Minidump_%04d%02d%02d_%02d%02d%02d%03d",
xt.tm_year + 1900, xt.tm_mon + 1, xt.tm_mday,
xt.tm_hour, xt.tm_min, xt.tm_sec, timebuffer.millitm);
_wmakepath_s(szTempName, MAX_PATH + 1, szDrive, szDir, szFName, L"dmp");
wchar_t szUserData[MAX_PATH];
swprintf_s(szUserData, MAX_PATH, L"PasswordSafe V%d.%d.%d(%s). Module timestamp: %08x",
iMajor, iMinor, iBuild, wcRevision, dwTimeStamp);
HANDLE hFile = CreateFile(szTempName, GENERIC_READ | GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
MINIDUMP_EXCEPTION_INFORMATION excpInfo;
excpInfo.ClientPointers = FALSE;
excpInfo.ExceptionPointers = ExInfo;
excpInfo.ThreadId = GetCurrentThreadId();
MINIDUMP_USER_STREAM UserStreams[1];
UserStreams[0].Type = LastReservedStream + 1;
UserStreams[0].Buffer = (void *)szUserData;
UserStreams[0].BufferSize = sizeof(szUserData);
MINIDUMP_USER_STREAM_INFORMATION musi;
musi.UserStreamCount = 1;
musi.UserStreamArray = UserStreams;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile,
MiniDumpNormal, &excpInfo, &musi, NULL);
CloseHandle(hFile);
size_t len = wcslen(wcMsg1) + wcslen(szFName) + wcslen(wcMsg2) +
wcslen(wcTempPath) + wcslen(wcMsg3) + 3;
wchar_t sz_errormsg[4*MSGSIZE]; // not a good place for malloc, as the heap
// may be corrupt...
wcscpy_s(sz_errormsg, len, wcMsg1);
wcscat_s(sz_errormsg, len, szFName);
wcscat_s(sz_errormsg, len, wcMsg2);
wcscat_s(sz_errormsg, len, wcTempPath);
wcscat_s(sz_errormsg, len, wcMsg3);
// Issue error message
wchar_t szCaption[MAX_PATH];
swprintf_s(szCaption, MAX_PATH, wcCaption, iMajor, iMinor, iBuild, wcRevision);
int irc = ::MessageBox(GetForegroundWindow(), sz_errormsg, szCaption,
MB_YESNO | MB_APPLMODAL | MB_ICONERROR);
if (irc == IDNO)
_wremove(szTempName);
} // valid file handle
exit:
return EXCEPTION_CONTINUE_SEARCH;
}
void RemoveFaultHandler()
{
SetUnhandledExceptionFilter(NULL);
}
#endif
<|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: xmlMasterFields.cxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_reportdesign.hxx"
#include "xmlMasterFields.hxx"
#include "xmlfilter.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/nmspmap.hxx>
#include "xmlEnums.hxx"
#include "xmlReport.hxx"
#include <tools/debug.hxx>
namespace rptxml
{
using namespace ::com::sun::star;
using namespace ::com::sun::star::report;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
DBG_NAME( rpt_OXMLMasterFields )
OXMLMasterFields::OXMLMasterFields( ORptFilter& rImport,
sal_uInt16 nPrfx, const ::rtl::OUString& rLName,
const Reference< XAttributeList > & _xAttrList
,IMasterDetailFieds* _pReport
) :
SvXMLImportContext( rImport, nPrfx, rLName)
,m_pReport(_pReport)
{
DBG_CTOR( rpt_OXMLMasterFields,NULL);
const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = rImport.GetSubDocumentElemTokenMap();
::rtl::OUString sMasterField,sDetailField;
const sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
for(sal_Int16 i = 0; i < nLength; ++i)
{
::rtl::OUString sLocalName;
const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
const rtl::OUString sValue = _xAttrList->getValueByIndex( i );
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_MASTER:
sMasterField = sValue;
break;
case XML_TOK_SUB_DETAIL:
sDetailField = sValue;
break;
default:
break;
}
}
if ( !sDetailField.getLength() )
sDetailField = sMasterField;
m_pReport->addMasterDetailPair(::std::pair< ::rtl::OUString,::rtl::OUString >(sMasterField,sDetailField));
}
// -----------------------------------------------------------------------------
OXMLMasterFields::~OXMLMasterFields()
{
DBG_DTOR( rpt_OXMLMasterFields,NULL);
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLMasterFields::CreateChildContext(
sal_uInt16 _nPrefix,
const ::rtl::OUString& _rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = static_cast<ORptFilter&>(GetImport()).GetSubDocumentElemTokenMap();
switch( rTokenMap.Get( _nPrefix, _rLocalName ) )
{
case XML_TOK_MASTER_DETAIL_FIELD:
{
GetImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLMasterFields(static_cast<ORptFilter&>(GetImport()), _nPrefix, _rLocalName,xAttrList ,m_pReport);
}
break;
default:
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), _nPrefix, _rLocalName );
return pContext;
}
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS rptchart02 (1.5.4); FILE MERGED 2008/04/16 06:29:18 oj 1.5.4.2: RESYNC: (1.5-1.6); FILE MERGED 2008/03/12 09:45:17 oj 1.5.4.1: impl chart handling<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: xmlMasterFields.cxx,v $
* $Revision: 1.7 $
*
* 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 "precompiled_reportdesign.hxx"
#include "xmlMasterFields.hxx"
#include "xmlfilter.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/nmspmap.hxx>
#include "xmlEnums.hxx"
#include "xmlReport.hxx"
#include <tools/debug.hxx>
namespace rptxml
{
using namespace ::com::sun::star;
using namespace ::com::sun::star::report;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
DBG_NAME( rpt_OXMLMasterFields )
OXMLMasterFields::OXMLMasterFields( ORptFilter& rImport,
sal_uInt16 nPrfx, const ::rtl::OUString& rLName,
const Reference< XAttributeList > & _xAttrList
,IMasterDetailFieds* _pReport
) :
SvXMLImportContext( rImport, nPrfx, rLName)
,m_pReport(_pReport)
{
DBG_CTOR( rpt_OXMLMasterFields,NULL);
const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = rImport.GetSubDocumentElemTokenMap();
::rtl::OUString sMasterField,sDetailField;
const sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
for(sal_Int16 i = 0; i < nLength; ++i)
{
::rtl::OUString sLocalName;
const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
const rtl::OUString sValue = _xAttrList->getValueByIndex( i );
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_MASTER:
sMasterField = sValue;
break;
case XML_TOK_SUB_DETAIL:
sDetailField = sValue;
break;
default:
break;
}
}
if ( !sDetailField.getLength() )
sDetailField = sMasterField;
if ( sMasterField.getLength() )
m_pReport->addMasterDetailPair(::std::pair< ::rtl::OUString,::rtl::OUString >(sMasterField,sDetailField));
}
// -----------------------------------------------------------------------------
OXMLMasterFields::~OXMLMasterFields()
{
DBG_DTOR( rpt_OXMLMasterFields,NULL);
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLMasterFields::CreateChildContext(
sal_uInt16 _nPrefix,
const ::rtl::OUString& _rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = static_cast<ORptFilter&>(GetImport()).GetSubDocumentElemTokenMap();
switch( rTokenMap.Get( _nPrefix, _rLocalName ) )
{
case XML_TOK_MASTER_DETAIL_FIELD:
{
GetImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLMasterFields(static_cast<ORptFilter&>(GetImport()), _nPrefix, _rLocalName,xAttrList ,m_pReport);
}
break;
default:
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), _nPrefix, _rLocalName );
return pContext;
}
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the Apache License 2.0.
*/
#include <string>
#include <triton/astContext.hpp>
#include <triton/exceptions.hpp>
#include <triton/solverModel.hpp>
#include <triton/symbolicVariable.hpp>
#include <triton/tritonToZ3Ast.hpp>
#include <triton/tritonTypes.hpp>
#include <triton/z3Solver.hpp>
#include <triton/z3ToTritonAst.hpp>
namespace triton {
namespace engines {
namespace solver {
//! Wrapper to handle variadict number of arguments or'd togethers
z3::expr mk_or(z3::expr_vector args) {
std::vector<Z3_ast> array;
for (triton::uint32 i = 0; i < args.size(); i++)
array.push_back(args[i]);
return to_expr(args.ctx(), Z3_mk_or(args.ctx(), static_cast<triton::uint32>(array.size()), &(array[0])));
}
Z3Solver::Z3Solver() {
this->timeout = 0;
this->memoryLimit = 0;
}
std::vector<std::unordered_map<triton::usize, SolverModel>> Z3Solver::getModels(const triton::ast::SharedAbstractNode& node, triton::uint32 limit, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
std::vector<std::unordered_map<triton::usize, SolverModel>> ret;
triton::ast::SharedAbstractNode onode = node;
triton::ast::TritonToZ3Ast z3Ast{false};
try {
if (onode == nullptr)
throw triton::exceptions::SolverEngine("Z3Solver::getModels(): node cannot be null.");
/* Z3 does not need an assert() as root node */
if (node->getType() == triton::ast::ASSERT_NODE)
onode = node->getChildren()[0];
if (onode->isLogical() == false)
throw triton::exceptions::SolverEngine("Z3Solver::getModels(): Must be a logical node.");
z3::expr expr = z3Ast.convert(onode);
z3::context& ctx = expr.ctx();
z3::solver solver(ctx);
/* Create a solver and add the expression */
solver.add(expr);
z3::params p(ctx);
/* Define the timeout */
if (timeout) {
p.set(":timeout", timeout);
}
else if (this->timeout) {
p.set(":timeout", this->timeout);
}
/* Define memory limit */
if (this->memoryLimit) {
p.set(":max_memory", this->memoryLimit);
}
solver.set(p);
/* Get first model */
z3::check_result res = solver.check();
/* Write back the status code of the first constraint */
this->writeBackStatus(solver, res, status);
/* Check if it is sat */
while (res == z3::sat && limit >= 1) {
/* Get model */
z3::model m = solver.get_model();
/* Traversing the model */
std::unordered_map<triton::usize, SolverModel> smodel;
z3::expr_vector args(ctx);
for (triton::uint32 i = 0; i < m.size(); i++) {
/* Get the z3 variable */
z3::func_decl z3Variable = m[i];
/* Get the name as std::string from a z3 variable */
std::string varName = z3Variable.name().str();
/* Get z3 expr */
z3::expr exp = m.get_const_interp(z3Variable);
/* Get the size of a z3 expr */
triton::uint32 bvSize = exp.get_sort().bv_size();
/* Get the value of a z3 expr */
std::string svalue = Z3_get_numeral_string(ctx, exp);
/* Convert a string value to a integer value */
triton::uint512 value = triton::uint512(svalue);
/* Create a triton model */
SolverModel trionModel = SolverModel(z3Ast.variables[varName], value);
/* Map the result */
smodel[trionModel.getId()] = trionModel;
/* Uniq result */
if (exp.get_sort().is_bv())
args.push_back(ctx.bv_const(varName.c_str(), bvSize) != ctx.bv_val(svalue.c_str(), bvSize));
}
/* Check that model is available */
if (smodel.empty())
break;
/* Push model */
ret.push_back(smodel);
if (--limit) {
/* Escape last models */
solver.add(triton::engines::solver::mk_or(args));
/* Get next model */
res = solver.check();
}
}
}
catch (const z3::exception& e) {
if (!strcmp(e.msg(), "max. memory exceeded")) {
if (status) {
*status = triton::engines::solver::OUTOFMEM;
}
return {};
}
throw triton::exceptions::SolverEngine(std::string("Z3Solver::getModels(): ") + e.msg());
}
return ret;
}
bool Z3Solver::isSat(const triton::ast::SharedAbstractNode& node, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
triton::ast::TritonToZ3Ast z3Ast{false};
if (node == nullptr)
throw triton::exceptions::SolverEngine("Z3Solver::isSat(): node cannot be null.");
if (node->isLogical() == false)
throw triton::exceptions::SolverEngine("Z3Solver::isSat(): Must be a logical node.");
try {
z3::expr expr = z3Ast.convert(node);
z3::context& ctx = expr.ctx();
z3::solver solver(ctx);
/* Create a solver and add the expression */
solver.add(expr);
z3::params p(ctx);
/* Define the timeout */
if (timeout) {
p.set(":timeout", timeout);
}
else if (this->timeout) {
p.set(":timeout", this->timeout);
}
/* Define memory limit */
if (this->memoryLimit) {
p.set(":max_memory", this->memoryLimit);
}
solver.set(p);
z3::check_result res = solver.check();
this->writeBackStatus(solver, res, status);
return res == z3::sat;
}
catch (const z3::exception& e) {
if (!strcmp(e.msg(), "max. memory exceeded")) {
if (status) {
*status = triton::engines::solver::OUTOFMEM;
}
return {};
}
throw triton::exceptions::SolverEngine(std::string("Z3Solver::isSat(): ") + e.msg());
}
}
std::unordered_map<triton::usize, SolverModel> Z3Solver::getModel(const triton::ast::SharedAbstractNode& node, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
std::unordered_map<triton::usize, SolverModel> ret;
std::vector<std::unordered_map<triton::usize, SolverModel>> allModels;
allModels = this->getModels(node, 1, status, timeout);
if (allModels.size() > 0)
ret = allModels.front();
return ret;
}
triton::ast::SharedAbstractNode Z3Solver::simplify(const triton::ast::SharedAbstractNode& node) const {
if (node == nullptr)
throw triton::exceptions::AstTranslations("Z3Solver::simplify(): node cannot be null.");
try {
triton::ast::TritonToZ3Ast z3Ast{false};
triton::ast::Z3ToTritonAst tritonAst{node->getContext()};
/* From Triton to Z3 */
z3::expr expr = z3Ast.convert(node);
/* Simplify and back to Triton's AST */
auto snode = tritonAst.convert(expr.simplify());
return snode;
}
catch (const z3::exception& e) {
throw triton::exceptions::AstTranslations(std::string("Z3Solver::evaluate(): ") + e.msg());
}
}
triton::uint512 Z3Solver::evaluate(const triton::ast::SharedAbstractNode& node) const {
if (node == nullptr)
throw triton::exceptions::AstTranslations("Z3Solver::simplify(): node cannot be null.");
try {
triton::ast::TritonToZ3Ast z3ast{true};
/* From Triton to Z3 */
z3::expr expr = z3ast.convert(node);
/* Simplify the expression to get a constant */
expr = expr.simplify();
triton::uint512 res = 0;
if (expr.get_sort().is_bool())
res = Z3_get_bool_value(expr.ctx(), expr) == Z3_L_TRUE ? true : false;
else
res = triton::uint512{Z3_get_numeral_string(expr.ctx(), expr)};
return res;
}
catch (const z3::exception& e) {
throw triton::exceptions::AstTranslations(std::string("Z3Solver::evaluate(): ") + e.msg());
}
}
void Z3Solver::writeBackStatus(z3::solver& solver, z3::check_result res, triton::engines::solver::status_e* status) const {
if (status != nullptr) {
switch (res) {
case z3::sat:
*status = triton::engines::solver::SAT;
break;
case z3::unsat:
*status = triton::engines::solver::UNSAT;
break;
case z3::unknown:
if (solver.reason_unknown() == "timeout") {
*status = triton::engines::solver::TIMEOUT;
}
else if (solver.reason_unknown() == "max. memory exceeded")
{
*status = triton::engines::solver::OUTOFMEM;
}
else {
*status = triton::engines::solver::UNKNOWN;
}
break;
}
}
}
std::string Z3Solver::getName(void) const {
return "z3";
}
void Z3Solver::setTimeout(triton::uint32 ms) {
this->timeout = ms;
}
void Z3Solver::setMemoryLimit(triton::uint32 limit) {
this->memoryLimit = limit;
}
};
};
};
<commit_msg>Check that vector for mk_or is not empty<commit_after>//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the Apache License 2.0.
*/
#include <string>
#include <triton/astContext.hpp>
#include <triton/exceptions.hpp>
#include <triton/solverModel.hpp>
#include <triton/symbolicVariable.hpp>
#include <triton/tritonToZ3Ast.hpp>
#include <triton/tritonTypes.hpp>
#include <triton/z3Solver.hpp>
#include <triton/z3ToTritonAst.hpp>
namespace triton {
namespace engines {
namespace solver {
//! Wrapper to handle variadict number of arguments or'd togethers
z3::expr mk_or(z3::expr_vector args) {
std::vector<Z3_ast> array;
for (triton::uint32 i = 0; i < args.size(); i++)
array.push_back(args[i]);
return to_expr(args.ctx(), Z3_mk_or(args.ctx(), static_cast<triton::uint32>(array.size()), &(array[0])));
}
Z3Solver::Z3Solver() {
this->timeout = 0;
this->memoryLimit = 0;
}
std::vector<std::unordered_map<triton::usize, SolverModel>> Z3Solver::getModels(const triton::ast::SharedAbstractNode& node, triton::uint32 limit, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
std::vector<std::unordered_map<triton::usize, SolverModel>> ret;
triton::ast::SharedAbstractNode onode = node;
triton::ast::TritonToZ3Ast z3Ast{false};
try {
if (onode == nullptr)
throw triton::exceptions::SolverEngine("Z3Solver::getModels(): node cannot be null.");
/* Z3 does not need an assert() as root node */
if (node->getType() == triton::ast::ASSERT_NODE)
onode = node->getChildren()[0];
if (onode->isLogical() == false)
throw triton::exceptions::SolverEngine("Z3Solver::getModels(): Must be a logical node.");
z3::expr expr = z3Ast.convert(onode);
z3::context& ctx = expr.ctx();
z3::solver solver(ctx);
/* Create a solver and add the expression */
solver.add(expr);
z3::params p(ctx);
/* Define the timeout */
if (timeout) {
p.set(":timeout", timeout);
}
else if (this->timeout) {
p.set(":timeout", this->timeout);
}
/* Define memory limit */
if (this->memoryLimit) {
p.set(":max_memory", this->memoryLimit);
}
solver.set(p);
/* Get first model */
z3::check_result res = solver.check();
/* Write back the status code of the first constraint */
this->writeBackStatus(solver, res, status);
/* Check if it is sat */
while (res == z3::sat && limit >= 1) {
/* Get model */
z3::model m = solver.get_model();
/* Traversing the model */
std::unordered_map<triton::usize, SolverModel> smodel;
z3::expr_vector args(ctx);
for (triton::uint32 i = 0; i < m.size(); i++) {
/* Get the z3 variable */
z3::func_decl z3Variable = m[i];
/* Get the name as std::string from a z3 variable */
std::string varName = z3Variable.name().str();
/* Get z3 expr */
z3::expr exp = m.get_const_interp(z3Variable);
/* Get the size of a z3 expr */
triton::uint32 bvSize = exp.get_sort().bv_size();
/* Get the value of a z3 expr */
std::string svalue = Z3_get_numeral_string(ctx, exp);
/* Convert a string value to a integer value */
triton::uint512 value = triton::uint512(svalue);
/* Create a triton model */
SolverModel trionModel = SolverModel(z3Ast.variables[varName], value);
/* Map the result */
smodel[trionModel.getId()] = trionModel;
/* Uniq result */
if (exp.get_sort().is_bv())
args.push_back(ctx.bv_const(varName.c_str(), bvSize) != ctx.bv_val(svalue.c_str(), bvSize));
}
/* Check that model is available */
if (smodel.empty())
break;
/* Push model */
ret.push_back(smodel);
if (--limit) {
/* Escape last models */
if (!args.empty()) {
solver.add(triton::engines::solver::mk_or(args));
}
/* Get next model */
res = solver.check();
}
}
}
catch (const z3::exception& e) {
if (!strcmp(e.msg(), "max. memory exceeded")) {
if (status) {
*status = triton::engines::solver::OUTOFMEM;
}
return {};
}
throw triton::exceptions::SolverEngine(std::string("Z3Solver::getModels(): ") + e.msg());
}
return ret;
}
bool Z3Solver::isSat(const triton::ast::SharedAbstractNode& node, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
triton::ast::TritonToZ3Ast z3Ast{false};
if (node == nullptr)
throw triton::exceptions::SolverEngine("Z3Solver::isSat(): node cannot be null.");
if (node->isLogical() == false)
throw triton::exceptions::SolverEngine("Z3Solver::isSat(): Must be a logical node.");
try {
z3::expr expr = z3Ast.convert(node);
z3::context& ctx = expr.ctx();
z3::solver solver(ctx);
/* Create a solver and add the expression */
solver.add(expr);
z3::params p(ctx);
/* Define the timeout */
if (timeout) {
p.set(":timeout", timeout);
}
else if (this->timeout) {
p.set(":timeout", this->timeout);
}
/* Define memory limit */
if (this->memoryLimit) {
p.set(":max_memory", this->memoryLimit);
}
solver.set(p);
z3::check_result res = solver.check();
this->writeBackStatus(solver, res, status);
return res == z3::sat;
}
catch (const z3::exception& e) {
if (!strcmp(e.msg(), "max. memory exceeded")) {
if (status) {
*status = triton::engines::solver::OUTOFMEM;
}
return {};
}
throw triton::exceptions::SolverEngine(std::string("Z3Solver::isSat(): ") + e.msg());
}
}
std::unordered_map<triton::usize, SolverModel> Z3Solver::getModel(const triton::ast::SharedAbstractNode& node, triton::engines::solver::status_e* status, triton::uint32 timeout) const {
std::unordered_map<triton::usize, SolverModel> ret;
std::vector<std::unordered_map<triton::usize, SolverModel>> allModels;
allModels = this->getModels(node, 1, status, timeout);
if (allModels.size() > 0)
ret = allModels.front();
return ret;
}
triton::ast::SharedAbstractNode Z3Solver::simplify(const triton::ast::SharedAbstractNode& node) const {
if (node == nullptr)
throw triton::exceptions::AstTranslations("Z3Solver::simplify(): node cannot be null.");
try {
triton::ast::TritonToZ3Ast z3Ast{false};
triton::ast::Z3ToTritonAst tritonAst{node->getContext()};
/* From Triton to Z3 */
z3::expr expr = z3Ast.convert(node);
/* Simplify and back to Triton's AST */
auto snode = tritonAst.convert(expr.simplify());
return snode;
}
catch (const z3::exception& e) {
throw triton::exceptions::AstTranslations(std::string("Z3Solver::evaluate(): ") + e.msg());
}
}
triton::uint512 Z3Solver::evaluate(const triton::ast::SharedAbstractNode& node) const {
if (node == nullptr)
throw triton::exceptions::AstTranslations("Z3Solver::simplify(): node cannot be null.");
try {
triton::ast::TritonToZ3Ast z3ast{true};
/* From Triton to Z3 */
z3::expr expr = z3ast.convert(node);
/* Simplify the expression to get a constant */
expr = expr.simplify();
triton::uint512 res = 0;
if (expr.get_sort().is_bool())
res = Z3_get_bool_value(expr.ctx(), expr) == Z3_L_TRUE ? true : false;
else
res = triton::uint512{Z3_get_numeral_string(expr.ctx(), expr)};
return res;
}
catch (const z3::exception& e) {
throw triton::exceptions::AstTranslations(std::string("Z3Solver::evaluate(): ") + e.msg());
}
}
void Z3Solver::writeBackStatus(z3::solver& solver, z3::check_result res, triton::engines::solver::status_e* status) const {
if (status != nullptr) {
switch (res) {
case z3::sat:
*status = triton::engines::solver::SAT;
break;
case z3::unsat:
*status = triton::engines::solver::UNSAT;
break;
case z3::unknown:
if (solver.reason_unknown() == "timeout") {
*status = triton::engines::solver::TIMEOUT;
}
else if (solver.reason_unknown() == "max. memory exceeded")
{
*status = triton::engines::solver::OUTOFMEM;
}
else {
*status = triton::engines::solver::UNKNOWN;
}
break;
}
}
}
std::string Z3Solver::getName(void) const {
return "z3";
}
void Z3Solver::setTimeout(triton::uint32 ms) {
this->timeout = ms;
}
void Z3Solver::setMemoryLimit(triton::uint32 limit) {
this->memoryLimit = limit;
}
};
};
};
<|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 "content/renderer/java_bridge_dispatcher.h"
#include "content/common/child_process.h"
#include "content/common/java_bridge_messages.h"
#include "content/common/npobject_util.h" // For CreateNPVariant()
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "content/renderer/java_bridge_channel.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebBindings.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
JavaBridgeDispatcher::JavaBridgeDispatcher(
content::RenderView* render_view,
const IPC::ChannelHandle& channel_handle)
: RenderViewObserver(render_view) {
channel_.reset(JavaBridgeChannel::GetJavaBridgeChannel(
channel_handle, ChildProcess::current()->io_message_loop_proxy()));
}
JavaBridgeDispatcher::~JavaBridgeDispatcher() {
for (ObjectMap::const_iterator iter = objects_.begin();
iter != objects_.end(); ++iter) {
WebKit::WebBindings::releaseObject(NPVARIANT_TO_OBJECT(iter->second));
}
}
bool JavaBridgeDispatcher::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(JavaBridgeDispatcher, msg)
IPC_MESSAGE_HANDLER(JavaBridgeMsg_AddNamedObject, OnAddNamedObject)
IPC_MESSAGE_HANDLER(JavaBridgeMsg_RemoveNamedObject,
OnRemoveNamedObject)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void JavaBridgeDispatcher::DidClearWindowObject(WebKit::WebFrame* web_frame) {
// We only inject objects into the main frame.
if (web_frame != render_view()->GetWebView()->mainFrame())
return;
// Note that we have to (re)bind all objects, as they will have been unbound
// when the window object was cleared.
for (ObjectMap::const_iterator iter = objects_.begin();
iter != objects_.end(); ++iter) {
// This refs the NPObject. This reference is dropped when either the window
// object is later cleared, or the object is GC'ed. So the object may be
// deleted at any time after OnRemoveNamedObject() is called.
web_frame->bindToWindowObject(iter->first,
NPVARIANT_TO_OBJECT(iter->second));
}
}
void JavaBridgeDispatcher::OnAddNamedObject(
const string16& name,
const NPVariant_Param& variant_param) {
DCHECK_EQ(variant_param.type, NPVARIANT_PARAM_SENDER_OBJECT_ROUTING_ID);
// This creates an NPObject, wrapped as an NPVariant. We don't need the
// containing window or the page URL, as we don't do re-entrant sync IPC.
NPVariant variant;
bool created =
CreateNPVariant(variant_param, channel_.get(), &variant, NULL, GURL());
DCHECK(created);
DCHECK_EQ(variant.type, NPVariantType_Object);
// The NPObject is created with a ref count of one, which we remove when
// OnRemoveNamedObject() is called for that object.
ObjectMap::iterator iter = objects_.find(name);
if (iter != objects_.end()) {
WebKit::WebBindings::releaseObject(NPVARIANT_TO_OBJECT(iter->second));
}
objects_[name] = variant;
}
void JavaBridgeDispatcher::OnRemoveNamedObject(const string16& name) {
// Removing an object does not unbind it from JavaScript until the window
// object is next cleared. Note that the browser checks that the named object
// is present.
ObjectMap::iterator iter = objects_.find(name);
DCHECK(iter != objects_.end());
WebKit::WebBindings::releaseObject(NPVARIANT_TO_OBJECT(iter->second));
objects_.erase(iter);
}
<commit_msg>Use 0 instead of NULL to make GCC 4.6 for Chrome OS happy.<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 "content/renderer/java_bridge_dispatcher.h"
#include "content/common/child_process.h"
#include "content/common/java_bridge_messages.h"
#include "content/common/npobject_util.h" // For CreateNPVariant()
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "content/renderer/java_bridge_channel.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebBindings.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
JavaBridgeDispatcher::JavaBridgeDispatcher(
content::RenderView* render_view,
const IPC::ChannelHandle& channel_handle)
: RenderViewObserver(render_view) {
channel_.reset(JavaBridgeChannel::GetJavaBridgeChannel(
channel_handle, ChildProcess::current()->io_message_loop_proxy()));
}
JavaBridgeDispatcher::~JavaBridgeDispatcher() {
for (ObjectMap::const_iterator iter = objects_.begin();
iter != objects_.end(); ++iter) {
WebKit::WebBindings::releaseObject(NPVARIANT_TO_OBJECT(iter->second));
}
}
bool JavaBridgeDispatcher::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(JavaBridgeDispatcher, msg)
IPC_MESSAGE_HANDLER(JavaBridgeMsg_AddNamedObject, OnAddNamedObject)
IPC_MESSAGE_HANDLER(JavaBridgeMsg_RemoveNamedObject,
OnRemoveNamedObject)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void JavaBridgeDispatcher::DidClearWindowObject(WebKit::WebFrame* web_frame) {
// We only inject objects into the main frame.
if (web_frame != render_view()->GetWebView()->mainFrame())
return;
// Note that we have to (re)bind all objects, as they will have been unbound
// when the window object was cleared.
for (ObjectMap::const_iterator iter = objects_.begin();
iter != objects_.end(); ++iter) {
// This refs the NPObject. This reference is dropped when either the window
// object is later cleared, or the object is GC'ed. So the object may be
// deleted at any time after OnRemoveNamedObject() is called.
web_frame->bindToWindowObject(iter->first,
NPVARIANT_TO_OBJECT(iter->second));
}
}
void JavaBridgeDispatcher::OnAddNamedObject(
const string16& name,
const NPVariant_Param& variant_param) {
DCHECK_EQ(variant_param.type, NPVARIANT_PARAM_SENDER_OBJECT_ROUTING_ID);
// This creates an NPObject, wrapped as an NPVariant. We don't need the
// containing window or the page URL, as we don't do re-entrant sync IPC.
NPVariant variant;
bool created =
CreateNPVariant(variant_param, channel_.get(), &variant, 0, GURL());
DCHECK(created);
DCHECK_EQ(variant.type, NPVariantType_Object);
// The NPObject is created with a ref count of one, which we remove when
// OnRemoveNamedObject() is called for that object.
ObjectMap::iterator iter = objects_.find(name);
if (iter != objects_.end()) {
WebKit::WebBindings::releaseObject(NPVARIANT_TO_OBJECT(iter->second));
}
objects_[name] = variant;
}
void JavaBridgeDispatcher::OnRemoveNamedObject(const string16& name) {
// Removing an object does not unbind it from JavaScript until the window
// object is next cleared. Note that the browser checks that the named object
// is present.
ObjectMap::iterator iter = objects_.find(name);
DCHECK(iter != objects_.end());
WebKit::WebBindings::releaseObject(NPVARIANT_TO_OBJECT(iter->second));
objects_.erase(iter);
}
<|endoftext|>
|
<commit_before>// Copyright 2015 Open Source Robotics Foundation, 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 <string.h>
#include <functional>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "rcutils/allocator.h"
#include "rcutils/error_handling.h"
#include "rcutils/logging_macros.h"
#include "rcutils/strdup.h"
#include "rcutils/types.h"
#include "rmw/allocators.h"
#include "rmw/convert_rcutils_ret_to_rmw_ret.h"
#include "rmw/error_handling.h"
#include "rmw/get_topic_names_and_types.h"
#include "rmw/impl/cpp/macros.hpp"
#include "rmw/impl/cpp/key_value.hpp"
#include "rmw/names_and_types.h"
#include "rmw/rmw.h"
#include "rmw_connext_shared_cpp/node_info_and_types.hpp"
#include "rmw_connext_shared_cpp/types.hpp"
#include "rmw_connext_shared_cpp/names_and_types_helpers.hpp"
#include "rmw_connext_shared_cpp/ndds_include.hpp"
#include "rmw_connext_shared_cpp/guid_helper.hpp"
/**
* Check to see if a node name and namespace match the user data QoS policy
* of a node.
*
* @param user_data_qos to inspect
* @param node_name to match
* @param node_namespace to match
* @return true if match
*/
bool
__is_node_match(
DDS::UserDataQosPolicy & user_data_qos,
const char * node_name,
const char * node_namespace)
{
uint8_t * buf = user_data_qos.value.get_contiguous_buffer();
if (buf) {
std::vector<uint8_t> kv(buf, buf + user_data_qos.value.length());
auto map = rmw::impl::cpp::parse_key_value(kv);
auto name_found = map.find("name");
auto ns_found = map.find("namespace");
if (name_found != map.end() && ns_found != map.end()) {
std::string name(name_found->second.begin(), name_found->second.end());
std::string ns(ns_found->second.begin(), ns_found->second.end());
return (name == node_name) && (ns == node_namespace);
}
}
return false;
}
/**
* Get a DDS GUID key for the discovered participant which matches the
* node_name and node_namepace supplied.
*
* @param node_info to discover nodes
* @param node_name to match
* @param node_namespace to match
* @param key [out] guid key that matches the node name and namespace
*
* @return RMW_RET_OK if success, ERROR otherwise
*/
rmw_ret_t
__get_key(
ConnextNodeInfo * node_info,
const char * node_name,
const char * node_namespace,
DDS::GUID_t & key)
{
auto participant = node_info->participant;
RMW_CHECK_FOR_NULL_WITH_MSG(participant, "participant handle is null", return RMW_RET_ERROR);
DDS::DomainParticipantQos dpqos;
auto dds_ret = participant->get_qos(dpqos);
if (dds_ret == DDS::RETCODE_OK && __is_node_match(dpqos.user_data, node_name, node_namespace)) {
DDS_InstanceHandle_to_GUID(&key, participant->get_instance_handle());
return RMW_RET_OK;
}
DDS::InstanceHandleSeq handles;
if (participant->get_discovered_participants(handles) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("unable to fetch discovered participants.");
return RMW_RET_ERROR;
}
for (DDS::Long i = 0; i < handles.length(); ++i) {
DDS::ParticipantBuiltinTopicData pbtd;
auto dds_ret = participant->get_discovered_participant_data(pbtd, handles[i]);
if (dds_ret == DDS::RETCODE_OK) {
uint8_t * buf = pbtd.user_data.value.get_contiguous_buffer();
if (buf) {
std::vector<uint8_t> kv(buf, buf + pbtd.user_data.value.length());
auto map = rmw::impl::cpp::parse_key_value(kv);
auto name_found = map.find("name");
auto ns_found = map.find("namespace");
if (name_found != map.end() && ns_found != map.end()) {
std::string name(name_found->second.begin(), name_found->second.end());
std::string ns(ns_found->second.begin(), ns_found->second.end());
if ((name == node_name) && (ns == node_namespace)) {
DDS_BuiltinTopicKey_to_GUID(&key, pbtd.key);
return RMW_RET_OK;
}
}
}
} else {
RMW_SET_ERROR_MSG("unable to fetch discovered participants data.");
return RMW_RET_ERROR;
}
}
RMW_SET_ERROR_MSG("unable to match node_name/namespace with discovered nodes.");
return RMW_RET_ERROR;
}
rmw_ret_t
validate_names_and_namespace(
const char * node_name,
const char * node_namespace)
{
if (!node_name) {
RMW_SET_ERROR_MSG("null node name");
return RMW_RET_INVALID_ARGUMENT;
}
if (!node_namespace) {
RMW_SET_ERROR_MSG("null node namespace");
return RMW_RET_INVALID_ARGUMENT;
}
return RMW_RET_OK;
}
rmw_ret_t
get_subscriber_names_and_types_by_node(
const char * implementation_identifier,
const rmw_node_t * node,
rcutils_allocator_t * allocator,
const char * node_name,
const char * node_namespace,
bool no_demangle,
rmw_names_and_types_t * topic_names_and_types)
{
if (!node) {
RMW_SET_ERROR_MSG("null node handle");
return RMW_RET_INVALID_ARGUMENT;
}
if (node->implementation_identifier != implementation_identifier) {
RMW_SET_ERROR_MSG("node handle is not from this rmw implementation");
return RMW_RET_ERROR;
}
rmw_ret_t ret = rmw_names_and_types_check_zero(topic_names_and_types);
if (ret != RMW_RET_OK) {
return ret;
}
ret = validate_names_and_namespace(node_name, node_namespace);
if (ret != RMW_RET_OK) {
return ret;
}
auto node_info = static_cast<ConnextNodeInfo *>(node->data);
if (!node_info) {
RMW_SET_ERROR_MSG("node info handle is null");
return RMW_RET_ERROR;
}
DDS::GUID_t key;
auto get_guid_err = __get_key(node_info, node_name, node_namespace, key);
if (get_guid_err != RMW_RET_OK) {
return get_guid_err;
}
// combine publisher and subscriber information
std::map<std::string, std::set<std::string>> topics;
node_info->subscriber_listener->fill_topic_names_and_types_by_guid(no_demangle, topics, key);
return copy_topics_names_and_types(topics, allocator, no_demangle, topic_names_and_types);
}
rmw_ret_t
get_publisher_names_and_types_by_node(
const char * implementation_identifier,
const rmw_node_t * node,
rcutils_allocator_t * allocator,
const char * node_name,
const char * node_namespace,
bool no_demangle,
rmw_names_and_types_t * topic_names_and_types)
{
if (!node) {
RMW_SET_ERROR_MSG("null node handle");
return RMW_RET_INVALID_ARGUMENT;
}
if (node->implementation_identifier != implementation_identifier) {
RMW_SET_ERROR_MSG("node handle is not from this rmw implementation");
return RMW_RET_ERROR;
}
rmw_ret_t ret = rmw_names_and_types_check_zero(topic_names_and_types);
if (ret != RMW_RET_OK) {
return ret;
}
ret = validate_names_and_namespace(node_name, node_namespace);
if (ret != RMW_RET_OK) {
return ret;
}
auto node_info = static_cast<ConnextNodeInfo *>(node->data);
if (!node_info) {
RMW_SET_ERROR_MSG("node info handle is null");
return RMW_RET_ERROR;
}
DDS::GUID_t key;
auto get_guid_err = __get_key(node_info, node_name, node_namespace, key);
if (get_guid_err != RMW_RET_OK) {
return get_guid_err;
}
// combine publisher and subscriber information
std::map<std::string, std::set<std::string>> topics;
node_info->publisher_listener->fill_topic_names_and_types_by_guid(no_demangle, topics, key);
return copy_topics_names_and_types(topics, allocator, no_demangle, topic_names_and_types);
}
static
rmw_ret_t
__get_service_names_and_types_by_node(
const char * implementation_identifier,
const rmw_node_t * node,
rcutils_allocator_t * allocator,
const char * node_name,
const char * node_namespace,
rmw_names_and_types_t * service_names_and_types,
const char * suffix)
{
if (!node) {
RMW_SET_ERROR_MSG("null node handle");
return RMW_RET_INVALID_ARGUMENT;
}
if (node->implementation_identifier != implementation_identifier) {
RMW_SET_ERROR_MSG("node handle is not from this rmw implementation");
return RMW_RET_ERROR;
}
rmw_ret_t ret = rmw_names_and_types_check_zero(service_names_and_types);
if (ret != RMW_RET_OK) {
return ret;
}
auto node_info = static_cast<ConnextNodeInfo *>(node->data);
if (!node_info) {
RMW_SET_ERROR_MSG("node info handle is null");
return RMW_RET_ERROR;
}
DDS::GUID_t key;
auto get_guid_err = __get_key(node_info, node_name, node_namespace, key);
if (get_guid_err != RMW_RET_OK) {
return get_guid_err;
}
// combine publisher and subscriber information
std::map<std::string, std::set<std::string>> services;
node_info->subscriber_listener->fill_service_names_and_types_by_guid(services, key, suffix);
rmw_ret_t rmw_ret =
copy_services_to_names_and_types(services, allocator, service_names_and_types);
if (rmw_ret != RMW_RET_OK) {
return rmw_ret;
}
return RMW_RET_OK;
}
rmw_ret_t
get_service_names_and_types_by_node(
const char * implementation_identifier,
const rmw_node_t * node,
rcutils_allocator_t * allocator,
const char * node_name,
const char * node_namespace,
rmw_names_and_types_t * service_names_and_types)
{
return __get_service_names_and_types_by_node(
implementation_identifier,
node,
allocator,
node_name,
node_namespace,
service_names_and_types,
"Request");
}
rmw_ret_t
get_client_names_and_types_by_node(
const char * implementation_identifier,
const rmw_node_t * node,
rcutils_allocator_t * allocator,
const char * node_name,
const char * node_namespace,
rmw_names_and_types_t * service_names_and_types)
{
return __get_service_names_and_types_by_node(
implementation_identifier,
node,
allocator,
node_name,
node_namespace,
service_names_and_types,
"Reply");
}
<commit_msg>Return specific error when not finding a node name (#365)<commit_after>// Copyright 2015 Open Source Robotics Foundation, 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 <string.h>
#include <functional>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "rcutils/allocator.h"
#include "rcutils/error_handling.h"
#include "rcutils/logging_macros.h"
#include "rcutils/strdup.h"
#include "rcutils/types.h"
#include "rmw/allocators.h"
#include "rmw/convert_rcutils_ret_to_rmw_ret.h"
#include "rmw/error_handling.h"
#include "rmw/get_topic_names_and_types.h"
#include "rmw/impl/cpp/macros.hpp"
#include "rmw/impl/cpp/key_value.hpp"
#include "rmw/names_and_types.h"
#include "rmw/rmw.h"
#include "rmw_connext_shared_cpp/node_info_and_types.hpp"
#include "rmw_connext_shared_cpp/types.hpp"
#include "rmw_connext_shared_cpp/names_and_types_helpers.hpp"
#include "rmw_connext_shared_cpp/ndds_include.hpp"
#include "rmw_connext_shared_cpp/guid_helper.hpp"
/**
* Check to see if a node name and namespace match the user data QoS policy
* of a node.
*
* @param user_data_qos to inspect
* @param node_name to match
* @param node_namespace to match
* @return true if match
*/
bool
__is_node_match(
DDS::UserDataQosPolicy & user_data_qos,
const char * node_name,
const char * node_namespace)
{
uint8_t * buf = user_data_qos.value.get_contiguous_buffer();
if (buf) {
std::vector<uint8_t> kv(buf, buf + user_data_qos.value.length());
auto map = rmw::impl::cpp::parse_key_value(kv);
auto name_found = map.find("name");
auto ns_found = map.find("namespace");
if (name_found != map.end() && ns_found != map.end()) {
std::string name(name_found->second.begin(), name_found->second.end());
std::string ns(ns_found->second.begin(), ns_found->second.end());
return (name == node_name) && (ns == node_namespace);
}
}
return false;
}
/**
* Get a DDS GUID key for the discovered participant which matches the
* node_name and node_namepace supplied.
*
* @param node_info to discover nodes
* @param node_name to match
* @param node_namespace to match
* @param key [out] guid key that matches the node name and namespace
*
* @return RMW_RET_OK if success, ERROR otherwise
*/
rmw_ret_t
__get_key(
ConnextNodeInfo * node_info,
const char * node_name,
const char * node_namespace,
DDS::GUID_t & key)
{
auto participant = node_info->participant;
RMW_CHECK_FOR_NULL_WITH_MSG(participant, "participant handle is null", return RMW_RET_ERROR);
DDS::DomainParticipantQos dpqos;
auto dds_ret = participant->get_qos(dpqos);
if (dds_ret == DDS::RETCODE_OK && __is_node_match(dpqos.user_data, node_name, node_namespace)) {
DDS_InstanceHandle_to_GUID(&key, participant->get_instance_handle());
return RMW_RET_OK;
}
DDS::InstanceHandleSeq handles;
if (participant->get_discovered_participants(handles) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("unable to fetch discovered participants.");
return RMW_RET_ERROR;
}
for (DDS::Long i = 0; i < handles.length(); ++i) {
DDS::ParticipantBuiltinTopicData pbtd;
auto dds_ret = participant->get_discovered_participant_data(pbtd, handles[i]);
if (dds_ret == DDS::RETCODE_OK) {
uint8_t * buf = pbtd.user_data.value.get_contiguous_buffer();
if (buf) {
std::vector<uint8_t> kv(buf, buf + pbtd.user_data.value.length());
auto map = rmw::impl::cpp::parse_key_value(kv);
auto name_found = map.find("name");
auto ns_found = map.find("namespace");
if (name_found != map.end() && ns_found != map.end()) {
std::string name(name_found->second.begin(), name_found->second.end());
std::string ns(ns_found->second.begin(), ns_found->second.end());
if ((name == node_name) && (ns == node_namespace)) {
DDS_BuiltinTopicKey_to_GUID(&key, pbtd.key);
return RMW_RET_OK;
}
}
}
} else {
RMW_SET_ERROR_MSG("unable to fetch discovered participants data.");
return RMW_RET_ERROR;
}
}
RMW_SET_ERROR_MSG_WITH_FORMAT_STRING(
"Node name not found: ns='%s', name='%s",
node_namespace,
node_name
);
return RMW_RET_NODE_NAME_NON_EXISTENT;
}
rmw_ret_t
validate_names_and_namespace(
const char * node_name,
const char * node_namespace)
{
if (!node_name) {
RMW_SET_ERROR_MSG("null node name");
return RMW_RET_INVALID_ARGUMENT;
}
if (!node_namespace) {
RMW_SET_ERROR_MSG("null node namespace");
return RMW_RET_INVALID_ARGUMENT;
}
return RMW_RET_OK;
}
rmw_ret_t
get_subscriber_names_and_types_by_node(
const char * implementation_identifier,
const rmw_node_t * node,
rcutils_allocator_t * allocator,
const char * node_name,
const char * node_namespace,
bool no_demangle,
rmw_names_and_types_t * topic_names_and_types)
{
if (!node) {
RMW_SET_ERROR_MSG("null node handle");
return RMW_RET_INVALID_ARGUMENT;
}
if (node->implementation_identifier != implementation_identifier) {
RMW_SET_ERROR_MSG("node handle is not from this rmw implementation");
return RMW_RET_ERROR;
}
rmw_ret_t ret = rmw_names_and_types_check_zero(topic_names_and_types);
if (ret != RMW_RET_OK) {
return ret;
}
ret = validate_names_and_namespace(node_name, node_namespace);
if (ret != RMW_RET_OK) {
return ret;
}
auto node_info = static_cast<ConnextNodeInfo *>(node->data);
if (!node_info) {
RMW_SET_ERROR_MSG("node info handle is null");
return RMW_RET_ERROR;
}
DDS::GUID_t key;
auto get_guid_err = __get_key(node_info, node_name, node_namespace, key);
if (get_guid_err != RMW_RET_OK) {
return get_guid_err;
}
// combine publisher and subscriber information
std::map<std::string, std::set<std::string>> topics;
node_info->subscriber_listener->fill_topic_names_and_types_by_guid(no_demangle, topics, key);
return copy_topics_names_and_types(topics, allocator, no_demangle, topic_names_and_types);
}
rmw_ret_t
get_publisher_names_and_types_by_node(
const char * implementation_identifier,
const rmw_node_t * node,
rcutils_allocator_t * allocator,
const char * node_name,
const char * node_namespace,
bool no_demangle,
rmw_names_and_types_t * topic_names_and_types)
{
if (!node) {
RMW_SET_ERROR_MSG("null node handle");
return RMW_RET_INVALID_ARGUMENT;
}
if (node->implementation_identifier != implementation_identifier) {
RMW_SET_ERROR_MSG("node handle is not from this rmw implementation");
return RMW_RET_ERROR;
}
rmw_ret_t ret = rmw_names_and_types_check_zero(topic_names_and_types);
if (ret != RMW_RET_OK) {
return ret;
}
ret = validate_names_and_namespace(node_name, node_namespace);
if (ret != RMW_RET_OK) {
return ret;
}
auto node_info = static_cast<ConnextNodeInfo *>(node->data);
if (!node_info) {
RMW_SET_ERROR_MSG("node info handle is null");
return RMW_RET_ERROR;
}
DDS::GUID_t key;
auto get_guid_err = __get_key(node_info, node_name, node_namespace, key);
if (get_guid_err != RMW_RET_OK) {
return get_guid_err;
}
// combine publisher and subscriber information
std::map<std::string, std::set<std::string>> topics;
node_info->publisher_listener->fill_topic_names_and_types_by_guid(no_demangle, topics, key);
return copy_topics_names_and_types(topics, allocator, no_demangle, topic_names_and_types);
}
static
rmw_ret_t
__get_service_names_and_types_by_node(
const char * implementation_identifier,
const rmw_node_t * node,
rcutils_allocator_t * allocator,
const char * node_name,
const char * node_namespace,
rmw_names_and_types_t * service_names_and_types,
const char * suffix)
{
if (!node) {
RMW_SET_ERROR_MSG("null node handle");
return RMW_RET_INVALID_ARGUMENT;
}
if (node->implementation_identifier != implementation_identifier) {
RMW_SET_ERROR_MSG("node handle is not from this rmw implementation");
return RMW_RET_ERROR;
}
rmw_ret_t ret = rmw_names_and_types_check_zero(service_names_and_types);
if (ret != RMW_RET_OK) {
return ret;
}
auto node_info = static_cast<ConnextNodeInfo *>(node->data);
if (!node_info) {
RMW_SET_ERROR_MSG("node info handle is null");
return RMW_RET_ERROR;
}
DDS::GUID_t key;
auto get_guid_err = __get_key(node_info, node_name, node_namespace, key);
if (get_guid_err != RMW_RET_OK) {
return get_guid_err;
}
// combine publisher and subscriber information
std::map<std::string, std::set<std::string>> services;
node_info->subscriber_listener->fill_service_names_and_types_by_guid(services, key, suffix);
rmw_ret_t rmw_ret =
copy_services_to_names_and_types(services, allocator, service_names_and_types);
if (rmw_ret != RMW_RET_OK) {
return rmw_ret;
}
return RMW_RET_OK;
}
rmw_ret_t
get_service_names_and_types_by_node(
const char * implementation_identifier,
const rmw_node_t * node,
rcutils_allocator_t * allocator,
const char * node_name,
const char * node_namespace,
rmw_names_and_types_t * service_names_and_types)
{
return __get_service_names_and_types_by_node(
implementation_identifier,
node,
allocator,
node_name,
node_namespace,
service_names_and_types,
"Request");
}
rmw_ret_t
get_client_names_and_types_by_node(
const char * implementation_identifier,
const rmw_node_t * node,
rcutils_allocator_t * allocator,
const char * node_name,
const char * node_namespace,
rmw_names_and_types_t * service_names_and_types)
{
return __get_service_names_and_types_by_node(
implementation_identifier,
node,
allocator,
node_name,
node_namespace,
service_names_and_types,
"Reply");
}
<|endoftext|>
|
<commit_before>/*
* DefaultForwardChainerCB.cc
*
* Copyright (C) 2015 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "DefaultForwardChainerCB.h"
#include "PLNCommons.h"
#include <opencog/query/PatternMatch.h>
#include <opencog/guile/SchemeSmob.h>
DefaultForwardChainerCB::DefaultForwardChainerCB(
AtomSpace* as, target_selection_mode ts_mode /*=TV_FITNESS_BASED*/) :
ForwardChainerCallBack(as)
{
as_ = as;
fcim_ = new ForwardChainInputMatchCB(as);
fcpm_ = new ForwardChainPatternMatchCB(as);
ts_mode_ = ts_mode;
}
DefaultForwardChainerCB::~DefaultForwardChainerCB()
{
delete fcim_;
delete fcpm_;
}
/**
* choose rule based on premises of rule matching the target
* uses temporary atomspace to limit the search space
*
* @param fcmem forward chainer's working memory
* @return a vector of chosen rules
*/
vector<Rule*> DefaultForwardChainerCB::choose_rule(FCMemory& fcmem)
{
Handle target = fcmem.get_cur_target();
if (target == Handle::UNDEFINED or NodeCast(target))
throw InvalidParamException(TRACE_INFO,
"Needs a target atom of type LINK");
HandleSeq chosen_bindlinks;
if (LinkCast(target)) {
AtomSpace rule_atomspace;
Handle target_cpy = rule_atomspace.addAtom(target);
// Copy rules to the temporary atomspace.
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
rule_atomspace.addAtom(r->get_handle());
}
// Create bindlink with target as an implicant.
PLNCommons pc(&rule_atomspace);
Handle copy = pc.replace_nodes_with_varnode(target_cpy, NODE);
Handle bind_link = pc.create_bindLink(copy, false);
// Pattern match.
DefaultImplicator imp(&rule_atomspace);
try {
PatternMatch pm;
pm.do_bindlink(bind_link, imp);
} catch (InvalidParamException& e) {
cout << "VALIDATION FAILED:" << endl << e.what() << endl;
}
// Get matched bindLinks.
HandleSeq matches = imp.result_list;
if (matches.empty()) {
logger().debug(
"No matching BindLink was found.Returning empty vector");
return vector<Rule*> { };
}
HandleSeq bindlinks;
for (Handle hm : matches) {
//get all BindLinks whose part of their premise matches with hm
HandleSeq hs = get_rootlinks(hm, &rule_atomspace, BIND_LINK);
for (Handle hi : hs) {
if (find(bindlinks.begin(), bindlinks.end(), hi) == bindlinks.end()) {
bindlinks.push_back(hi);
}
}
}
// Copy handles to main atomspace.
for (Handle h : bindlinks) {
chosen_bindlinks.push_back(as_->addAtom(h));
}
}
// Try to find specialized rules that contain the target node.
if (NodeCast(target)) {
chosen_bindlinks = get_rootlinks(target, as_, BIND_LINK);
}
// Find the rules containing the bindLink in copied_back.
vector<Rule*> matched_rules;
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
auto it = find(chosen_bindlinks.begin(), chosen_bindlinks.end(),
r->get_handle()); //xxx not matching
if (it != chosen_bindlinks.end()) {
matched_rules.push_back(r);
}
}
return matched_rules;
}
/**
* Gets all top level links of certain types and subclasses that contain @param htarget
*
* @param htarget handle whose top level links are to be searched
* @param as the atomspace in which search is to be done
* @param link_type the root link types to be searched
* @param subclasses a flag that tells to look subclasses of @link_type
*/
HandleSeq DefaultForwardChainerCB::get_rootlinks(Handle htarget, AtomSpace* as,
Type link_type,
bool subclasses)
{
auto outgoing = [as](Handle h) {return as->getOutgoing(h);};
PLNCommons pc(as);
HandleSeq chosen_roots;
HandleSeq candidates_roots;
pc.get_root_links(htarget, candidates_roots);
for (Handle hr : candidates_roots) {
bool notexist = find(chosen_roots.begin(), chosen_roots.end(), hr)
== chosen_roots.end();
auto type = as->getType(hr);
bool subtype = (subclasses and classserver().isA(type, link_type));
if (((type == link_type) or subtype) and notexist) {
//make sure matches are actually part of the premise list rather than the output of the bindLink
Handle hpremise = outgoing(outgoing(hr)[1])[0]; //extracting premise from (BindLink((ListLinK..)(ImpLink (premise) (..))))
if (pc.exists_in(hpremise, htarget)) {
chosen_roots.push_back(hr);
}
}
}
return chosen_roots;
}
HandleSeq DefaultForwardChainerCB::choose_input(FCMemory& fcmem)
{
HandleSeq inputs;
PLNCommons pc(as_);
Handle htarget = fcmem.get_cur_target();
//Get everything associated with the target handle.
HandleSeq neighbors = as_->getNeighbors(htarget, true, true, LINK, true);
//Add all root links of atoms in @param neighbors.
for (auto hn : neighbors) {
if (hn->getType() != VARIABLE_NODE) {
HandleSeq roots;
pc.get_root_links(hn, roots);
for (auto r : roots) {
if (find(inputs.begin(), inputs.end(), r) == inputs.end() and r->getType()
!= BIND_LINK)
inputs.push_back(r);
}
}
}
return inputs;
}
Handle DefaultForwardChainerCB::choose_next_target(FCMemory& fcmem)
{
HandleSeq tlist = fcmem.get_premise_list();
map<Handle, float> tournament_elem;
PLNCommons pc(as_);
Handle hchosen = Handle::UNDEFINED;
for (Handle t : tlist) {
switch (ts_mode_) {
case TV_FITNESS_BASED: {
float fitness = pc.target_tv_fitness(t);
tournament_elem[t] = fitness;
}
break;
case STI_BASED:
tournament_elem[t] = t->getSTI();
break;
default:
throw RuntimeException(TRACE_INFO,
"Unknown target selection mode.");
break;
}
}
//!Choose a new target that has never been chosen before.
//!xxx FIXME since same handle might be chosen multiple times the following
//!code doesn't guarantee all targets have been exhaustively looked.
for (size_t i = 0; i < tournament_elem.size(); i++) {
Handle hselected = pc.tournament_select(tournament_elem);
if (fcmem.isin_target_list(hselected)) {
continue;
} else {
hchosen = hselected;
break;
}
}
return hchosen;
}
//TODO applier should check on atoms (Inference.matched_atoms when Inference.Rule =Cur_Rule), for mutex rules
HandleSeq DefaultForwardChainerCB::apply_rule(FCMemory& fcmem)
{
Rule * cur_rule = fcmem.get_cur_rule();
fcpm_->set_fcmem(&fcmem);
PatternMatch pm;
try {
pm.do_bindlink(cur_rule->get_handle(), *fcpm_);
} catch (InvalidParamException& e) {
cout << "VALIDATION FAILED:" << endl << e.what() << endl;
}
return fcpm_->get_products();
}
<commit_msg>Return new inferences only<commit_after>/*
* DefaultForwardChainerCB.cc
*
* Copyright (C) 2015 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "DefaultForwardChainerCB.h"
#include "PLNCommons.h"
#include <opencog/query/PatternMatch.h>
#include <opencog/guile/SchemeSmob.h>
DefaultForwardChainerCB::DefaultForwardChainerCB(
AtomSpace* as, target_selection_mode ts_mode /*=TV_FITNESS_BASED*/) :
ForwardChainerCallBack(as)
{
as_ = as;
fcim_ = new ForwardChainInputMatchCB(as);
fcpm_ = new ForwardChainPatternMatchCB(as);
ts_mode_ = ts_mode;
}
DefaultForwardChainerCB::~DefaultForwardChainerCB()
{
delete fcim_;
delete fcpm_;
}
/**
* choose rule based on premises of rule matching the target
* uses temporary atomspace to limit the search space
*
* @param fcmem forward chainer's working memory
* @return a vector of chosen rules
*/
vector<Rule*> DefaultForwardChainerCB::choose_rule(FCMemory& fcmem)
{
Handle target = fcmem.get_cur_target();
if (target == Handle::UNDEFINED or NodeCast(target))
throw InvalidParamException(TRACE_INFO,
"Needs a target atom of type LINK");
HandleSeq chosen_bindlinks;
if (LinkCast(target)) {
AtomSpace rule_atomspace;
Handle target_cpy = rule_atomspace.addAtom(target);
// Copy rules to the temporary atomspace.
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
rule_atomspace.addAtom(r->get_handle());
}
// Create bindlink with target as an implicant.
PLNCommons pc(&rule_atomspace);
Handle copy = pc.replace_nodes_with_varnode(target_cpy, NODE);
Handle bind_link = pc.create_bindLink(copy, false);
// Pattern match.
DefaultImplicator imp(&rule_atomspace);
try {
PatternMatch pm;
pm.do_bindlink(bind_link, imp);
} catch (InvalidParamException& e) {
cout << "VALIDATION FAILED:" << endl << e.what() << endl;
}
// Get matched bindLinks.
HandleSeq matches = imp.result_list;
if (matches.empty()) {
logger().debug(
"No matching BindLink was found.Returning empty vector");
return vector<Rule*> { };
}
HandleSeq bindlinks;
for (Handle hm : matches) {
//get all BindLinks whose part of their premise matches with hm
HandleSeq hs = get_rootlinks(hm, &rule_atomspace, BIND_LINK);
for (Handle hi : hs) {
if (find(bindlinks.begin(), bindlinks.end(), hi) == bindlinks.end()) {
bindlinks.push_back(hi);
}
}
}
// Copy handles to main atomspace.
for (Handle h : bindlinks) {
chosen_bindlinks.push_back(as_->addAtom(h));
}
}
// Try to find specialized rules that contain the target node.
if (NodeCast(target)) {
chosen_bindlinks = get_rootlinks(target, as_, BIND_LINK);
}
// Find the rules containing the bindLink in copied_back.
vector<Rule*> matched_rules;
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
auto it = find(chosen_bindlinks.begin(), chosen_bindlinks.end(),
r->get_handle()); //xxx not matching
if (it != chosen_bindlinks.end()) {
matched_rules.push_back(r);
}
}
return matched_rules;
}
/**
* Gets all top level links of certain types and subclasses that contain @param htarget
*
* @param htarget handle whose top level links are to be searched
* @param as the atomspace in which search is to be done
* @param link_type the root link types to be searched
* @param subclasses a flag that tells to look subclasses of @link_type
*/
HandleSeq DefaultForwardChainerCB::get_rootlinks(Handle htarget, AtomSpace* as,
Type link_type,
bool subclasses)
{
auto outgoing = [as](Handle h) {return as->getOutgoing(h);};
PLNCommons pc(as);
HandleSeq chosen_roots;
HandleSeq candidates_roots;
pc.get_root_links(htarget, candidates_roots);
for (Handle hr : candidates_roots) {
bool notexist = find(chosen_roots.begin(), chosen_roots.end(), hr)
== chosen_roots.end();
auto type = as->getType(hr);
bool subtype = (subclasses and classserver().isA(type, link_type));
if (((type == link_type) or subtype) and notexist) {
//make sure matches are actually part of the premise list rather than the output of the bindLink
Handle hpremise = outgoing(outgoing(hr)[1])[0]; //extracting premise from (BindLink((ListLinK..)(ImpLink (premise) (..))))
if (pc.exists_in(hpremise, htarget)) {
chosen_roots.push_back(hr);
}
}
}
return chosen_roots;
}
HandleSeq DefaultForwardChainerCB::choose_input(FCMemory& fcmem)
{
HandleSeq inputs;
PLNCommons pc(as_);
Handle htarget = fcmem.get_cur_target();
//Get everything associated with the target handle.
HandleSeq neighbors = as_->getNeighbors(htarget, true, true, LINK, true);
//Add all root links of atoms in @param neighbors.
for (auto hn : neighbors) {
if (hn->getType() != VARIABLE_NODE) {
HandleSeq roots;
pc.get_root_links(hn, roots);
for (auto r : roots) {
if (find(inputs.begin(), inputs.end(), r) == inputs.end() and r->getType()
!= BIND_LINK)
inputs.push_back(r);
}
}
}
return inputs;
}
Handle DefaultForwardChainerCB::choose_next_target(FCMemory& fcmem)
{
HandleSeq tlist = fcmem.get_premise_list();
map<Handle, float> tournament_elem;
PLNCommons pc(as_);
Handle hchosen = Handle::UNDEFINED;
for (Handle t : tlist) {
switch (ts_mode_) {
case TV_FITNESS_BASED: {
float fitness = pc.target_tv_fitness(t);
tournament_elem[t] = fitness;
}
break;
case STI_BASED:
tournament_elem[t] = t->getSTI();
break;
default:
throw RuntimeException(TRACE_INFO,
"Unknown target selection mode.");
break;
}
}
//!Choose a new target that has never been chosen before.
//!xxx FIXME since same handle might be chosen multiple times the following
//!code doesn't guarantee all targets have been exhaustively looked.
for (size_t i = 0; i < tournament_elem.size(); i++) {
Handle hselected = pc.tournament_select(tournament_elem);
if (fcmem.isin_target_list(hselected)) {
continue;
} else {
hchosen = hselected;
break;
}
}
return hchosen;
}
//TODO applier should check on atoms (Inference.matched_atoms when Inference.Rule =Cur_Rule), for mutex rules
HandleSeq DefaultForwardChainerCB::apply_rule(FCMemory& fcmem)
{
Rule * cur_rule = fcmem.get_cur_rule();
fcpm_->set_fcmem(&fcmem);
PatternMatch pm;
try {
pm.do_bindlink(cur_rule->get_handle(), *fcpm_);
} catch (InvalidParamException& e) {
cout << "VALIDATION FAILED:" << endl << e.what() << endl;
}
HandleSeq product = fcpm_->get_products();
//! Make sure the inferences made are new.
HandleSeq new_product;
for (auto h : product) {
if (not fcmem.isin_premise_list(h))
new_product.push_back(h);
}
return new_product;
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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 <cassert>
#include "boost/format.hpp"
#include "IECoreGL/ToGLMeshConverter.h"
#include "IECoreGL/MeshPrimitive.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/TriangulateOp.h"
#include "IECore/MeshNormalsOp.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/MessageHandler.h"
using namespace IECoreGL;
class ToGLMeshConverter::ToFaceVaryingConverter
{
public:
typedef IECore::DataPtr ReturnType;
ToFaceVaryingConverter( IECore::ConstIntVectorDataPtr vertIds ) : m_vertIds( vertIds )
{
assert( m_vertIds );
}
template<typename T>
IECore::DataPtr operator()( typename T::Ptr inData )
{
assert( inData );
const typename T::Ptr outData = new T();
outData->writable().resize( m_vertIds->readable().size() );
typename T::ValueType::iterator outIt = outData->writable().begin();
for ( typename T::ValueType::size_type i = 0; i < m_vertIds->readable().size(); i++ )
{
*outIt++ = inData->readable()[ m_vertIds->readable()[ i ] ];
}
return outData;
}
IECore::ConstIntVectorDataPtr m_vertIds;
};
ToGLMeshConverter::ToGLMeshConverter( IECore::ConstMeshPrimitivePtr toConvert )
: ToGLConverter( staticTypeName(), "Converts IECore::MeshPrimitive objects to IECoreGL::MeshPrimitive objects.", IECore::MeshPrimitiveTypeId )
{
srcParameter()->setValue( boost::const_pointer_cast<IECore::MeshPrimitive>( toConvert ) );
}
ToGLMeshConverter::~ToGLMeshConverter()
{
}
IECore::RunTimeTypedPtr ToGLMeshConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const
{
IECore::MeshPrimitivePtr mesh = boost::static_pointer_cast<IECore::MeshPrimitive>( src->copy() ); // safe because the parameter validated it for us
IECore::TriangulateOpPtr op = new IECore::TriangulateOp();
op->inputParameter()->setValue( mesh );
op->throwExceptionsParameter()->setTypedValue( false ); // it's better to see something than nothing
mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( op->operate() );
assert( mesh );
IECore::ConstV3fVectorDataPtr p = 0;
IECore::PrimitiveVariableMap::const_iterator pIt = mesh->variables.find( "P" );
if( pIt!=mesh->variables.end() )
{
if( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex )
{
p = IECore::runTimeCast<const IECore::V3fVectorData>( pIt->second.data );
}
}
if( !p )
{
throw IECore::Exception( "Must specify primitive variable \"P\", of type V3fVectorData and interpolation type Vertex." );
}
IECore::ConstV3fVectorDataPtr n = 0;
IECore::PrimitiveVariableMap::const_iterator nIt = mesh->variables.find( "N" );
if( nIt != mesh->variables.end() )
{
if( nIt->second.interpolation==IECore::PrimitiveVariable::Vertex || nIt->second.interpolation==IECore::PrimitiveVariable::Varying || nIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
{
n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
}
if( !n )
{
throw IECore::Exception( "Must specify primitive variable \"N\", of type V3fVectorData" );
}
}
else
{
IECore::MeshNormalsOpPtr normOp = new IECore::MeshNormalsOp();
normOp->inputParameter()->setValue( mesh );
mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( normOp->operate() );
assert( mesh );
nIt = mesh->variables.find( "N" );
assert( nIt != mesh->variables.end() );
n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
}
assert( n );
MeshPrimitivePtr glMesh = new MeshPrimitive( mesh->vertexIds(), p );
ToFaceVaryingConverter primVarConverter( mesh->vertexIds() );
for ( IECore::PrimitiveVariableMap::iterator pIt = mesh->variables.begin(); pIt != mesh->variables.end(); ++pIt )
{
if ( pIt->second.data )
{
if ( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex || pIt->second.interpolation==IECore::PrimitiveVariable::Varying )
{
IECore::DataPtr newData = IECore::despatchTypedData< ToFaceVaryingConverter, IECore::TypeTraits::IsVectorTypedData >( pIt->second.data, primVarConverter );
pIt->second.interpolation = IECore::PrimitiveVariable::FaceVarying;
glMesh->addVertexAttribute( pIt->first, newData );
}
else if ( pIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
{
glMesh->addVertexAttribute( pIt->first, pIt->second.data );
}
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", boost::format( "No data given for primvar \"%s\"" ) % pIt->first );
}
}
IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( "s" );
IECore::PrimitiveVariableMap::const_iterator tIt = mesh->variables.find( "t" );
if ( sIt != mesh->variables.end() && tIt != mesh->variables.end() )
{
if ( sIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying
&& tIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying )
{
IECore::ConstFloatVectorDataPtr s = IECore::runTimeCast< const IECore::FloatVectorData >( sIt->second.data );
IECore::ConstFloatVectorDataPtr t = IECore::runTimeCast< const IECore::FloatVectorData >( tIt->second.data );
if ( s && t )
{
/// Should hold true if primvarsAreValid
assert( s->readable().size() == t->readable().size() );
IECore::V2fVectorDataPtr stData = new IECore::V2fVectorData();
stData->writable().resize( s->readable().size() );
for ( unsigned i = 0; i < s->readable().size(); i++ )
{
stData->writable()[i] = Imath::V2f( s->readable()[i], t->readable()[i] );
}
glMesh->addVertexAttribute( "st", stData );
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
}
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
}
}
else if ( sIt != mesh->variables.end() || tIt != mesh->variables.end() )
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "Primitive variable \"s\" or \"t\" found, but not both." );
}
return glMesh;
}
<commit_msg>Fixed a bug which meant that vertex s,t primvars would add invalid data to the gl mesh. They are now converted to facevarying and added.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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 <cassert>
#include "boost/format.hpp"
#include "IECoreGL/ToGLMeshConverter.h"
#include "IECoreGL/MeshPrimitive.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/TriangulateOp.h"
#include "IECore/MeshNormalsOp.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/MessageHandler.h"
using namespace IECoreGL;
/// \todo This should be in a standalone Op, and should cope with more than just Vertex interpolated input.
class ToGLMeshConverter::ToFaceVaryingConverter
{
public:
typedef IECore::DataPtr ReturnType;
ToFaceVaryingConverter( IECore::ConstIntVectorDataPtr vertIds ) : m_vertIds( vertIds )
{
assert( m_vertIds );
}
template<typename T>
IECore::DataPtr operator()( typename T::Ptr inData )
{
assert( inData );
const typename T::Ptr outData = new T();
outData->writable().resize( m_vertIds->readable().size() );
typename T::ValueType::iterator outIt = outData->writable().begin();
for ( typename T::ValueType::size_type i = 0; i < m_vertIds->readable().size(); i++ )
{
*outIt++ = inData->readable()[ m_vertIds->readable()[ i ] ];
}
return outData;
}
IECore::ConstIntVectorDataPtr m_vertIds;
};
ToGLMeshConverter::ToGLMeshConverter( IECore::ConstMeshPrimitivePtr toConvert )
: ToGLConverter( staticTypeName(), "Converts IECore::MeshPrimitive objects to IECoreGL::MeshPrimitive objects.", IECore::MeshPrimitiveTypeId )
{
srcParameter()->setValue( boost::const_pointer_cast<IECore::MeshPrimitive>( toConvert ) );
}
ToGLMeshConverter::~ToGLMeshConverter()
{
}
IECore::RunTimeTypedPtr ToGLMeshConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const
{
IECore::MeshPrimitivePtr mesh = boost::static_pointer_cast<IECore::MeshPrimitive>( src->copy() ); // safe because the parameter validated it for us
IECore::TriangulateOpPtr op = new IECore::TriangulateOp();
op->inputParameter()->setValue( mesh );
op->throwExceptionsParameter()->setTypedValue( false ); // it's better to see something than nothing
mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( op->operate() );
assert( mesh );
IECore::ConstV3fVectorDataPtr p = 0;
IECore::PrimitiveVariableMap::const_iterator pIt = mesh->variables.find( "P" );
if( pIt!=mesh->variables.end() )
{
if( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex )
{
p = IECore::runTimeCast<const IECore::V3fVectorData>( pIt->second.data );
}
}
if( !p )
{
throw IECore::Exception( "Must specify primitive variable \"P\", of type V3fVectorData and interpolation type Vertex." );
}
IECore::ConstV3fVectorDataPtr n = 0;
IECore::PrimitiveVariableMap::const_iterator nIt = mesh->variables.find( "N" );
if( nIt != mesh->variables.end() )
{
if( nIt->second.interpolation==IECore::PrimitiveVariable::Vertex || nIt->second.interpolation==IECore::PrimitiveVariable::Varying || nIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
{
n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
}
if( !n )
{
throw IECore::Exception( "Must specify primitive variable \"N\", of type V3fVectorData" );
}
}
else
{
IECore::MeshNormalsOpPtr normOp = new IECore::MeshNormalsOp();
normOp->inputParameter()->setValue( mesh );
mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( normOp->operate() );
assert( mesh );
nIt = mesh->variables.find( "N" );
assert( nIt != mesh->variables.end() );
n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
}
assert( n );
MeshPrimitivePtr glMesh = new MeshPrimitive( mesh->vertexIds(), p );
ToFaceVaryingConverter primVarConverter( mesh->vertexIds() );
for ( IECore::PrimitiveVariableMap::iterator pIt = mesh->variables.begin(); pIt != mesh->variables.end(); ++pIt )
{
if ( pIt->second.data )
{
if ( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex || pIt->second.interpolation==IECore::PrimitiveVariable::Varying )
{
// convert to facevarying
IECore::DataPtr newData = IECore::despatchTypedData< ToFaceVaryingConverter, IECore::TypeTraits::IsVectorTypedData >( pIt->second.data, primVarConverter );
glMesh->addVertexAttribute( pIt->first, newData );
// modify the primvar we converted in case it is "s" or "t", then we don't have to do another conversion below.
pIt->second.interpolation = IECore::PrimitiveVariable::FaceVarying;
pIt->second.data = newData;
}
else if ( pIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
{
glMesh->addVertexAttribute( pIt->first, pIt->second.data );
}
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", boost::format( "No data given for primvar \"%s\"" ) % pIt->first );
}
}
IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( "s" );
IECore::PrimitiveVariableMap::const_iterator tIt = mesh->variables.find( "t" );
if ( sIt != mesh->variables.end() && tIt != mesh->variables.end() )
{
if ( sIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying
&& tIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying )
{
IECore::ConstFloatVectorDataPtr s = IECore::runTimeCast< const IECore::FloatVectorData >( sIt->second.data );
IECore::ConstFloatVectorDataPtr t = IECore::runTimeCast< const IECore::FloatVectorData >( tIt->second.data );
if ( s && t )
{
/// Should hold true if primvarsAreValid
assert( s->readable().size() == t->readable().size() );
IECore::V2fVectorDataPtr stData = new IECore::V2fVectorData();
stData->writable().resize( s->readable().size() );
for ( unsigned i = 0; i < s->readable().size(); i++ )
{
stData->writable()[i] = Imath::V2f( s->readable()[i], t->readable()[i] );
}
glMesh->addVertexAttribute( "st", stData );
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
}
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
}
}
else if ( sIt != mesh->variables.end() || tIt != mesh->variables.end() )
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "Primitive variable \"s\" or \"t\" found, but not both." );
}
return glMesh;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2014, Paul Houx - All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/App.h"
#include "cinder/Log.h"
#include "SMAA.h"
#include "AreaTex.h"
#include "SearchTex.h"
using namespace ci;
using namespace ci::app;
using namespace std;
SMAA::SMAA()
{
// Load and compile our shaders
try {
// Define the format by specifying the vertex and fragment shader files and defining the quality settings.
auto fmt = gl::GlslProg::Format().vertex( loadAsset( "smaa.vert" ) ).fragment( loadAsset( "smaa.frag" ) ).define( "SMAA_PRESET_ULTRA" ).define( "SMAA_GLSL_3", "1" );
// Each pass uses the same files, but with a different value for the SMAA_PASS pre-processor directive.
mGlslFirstPass = gl::GlslProg::create( gl::GlslProg::Format( fmt ).define( "SMAA_PASS", "1" ) );
mGlslSecondPass = gl::GlslProg::create( gl::GlslProg::Format( fmt ).define( "SMAA_PASS", "2" ) );
mGlslThirdPass = gl::GlslProg::create( gl::GlslProg::Format( fmt ).define( "SMAA_PASS", "3" ) );
}
catch( const std::exception& e ) {
CI_LOG_EXCEPTION( "exception caught loading smaa shaders", e );
}
// Create lookup textures
gl::Texture2d::Format fmt;
fmt.setMinFilter( GL_LINEAR );
fmt.setMagFilter( GL_LINEAR );
fmt.setWrap( GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE );
// Search Texture (Grayscale, 8 bits unsigned).
fmt.setInternalFormat( GL_R8 );
fmt.setSwizzleMask( GL_RED, GL_RED, GL_RED, GL_ONE );
fmt.loadTopDown( true );
mSearchTex = gl::Texture2d::create( searchTexBytes, GL_RED, SEARCHTEX_WIDTH, SEARCHTEX_HEIGHT, fmt );
// Area Texture (Red+Green Channels, 8 bits unsigned).
fmt.setInternalFormat( GL_RG8 );
fmt.setSwizzleMask( GL_RED, GL_GREEN, GL_ZERO, GL_ONE );
fmt.loadTopDown( true );
mAreaTex = gl::Texture2d::create( areaTexBytes, GL_RG, AREATEX_WIDTH, AREATEX_HEIGHT, fmt );
// Specify the Fbo format.
gl::Texture2d::Format tfmt;
tfmt.setMinFilter( GL_LINEAR );
tfmt.setMagFilter( GL_LINEAR );
tfmt.setInternalFormat( GL_RGBA8 );
mFboFormat.setColorTextureFormat( tfmt );
mFboFormat.enableDepthBuffer( false );
}
void SMAA::apply( const gl::FboRef &destination, const gl::FboRef &source )
{
gl::ScopedFramebuffer fbo( destination );
gl::ScopedViewport viewport( 0, 0, destination->getWidth(), destination->getHeight() );
gl::ScopedMatrices matrices;
gl::setMatricesWindow( destination->getSize() );
// Make sure our source is linearly interpolated.
GLenum minFilter = source->getFormat().getColorTextureFormat().getMinFilter();
GLenum magFilter = source->getFormat().getColorTextureFormat().getMagFilter();
bool filterChanged = ( minFilter != GL_LINEAR || magFilter != GL_LINEAR );
if( filterChanged ) {
source->getColorTexture()->setMinFilter( GL_LINEAR );
source->getColorTexture()->setMagFilter( GL_LINEAR );
}
// Perform SMAA anti-aliasing.
gl::clear( ColorA( 0, 0, 0, 0 ) );
draw( source->getColorTexture(), destination->getBounds() );
// Restore texture parameters.
if( filterChanged ) {
source->getColorTexture()->setMinFilter( minFilter );
source->getColorTexture()->setMagFilter( magFilter );
}
}
void SMAA::draw( const gl::Texture2dRef &source, const Area &bounds )
{
if( ! mGlslFirstPass || ! mGlslSecondPass || ! mGlslThirdPass )
return;
// Create or resize buffers.
const int width = source->getWidth();
const int height = source->getHeight();
createBuffers( width, height );
// Apply first two passes.
doEdgePass( source );
doBlendPass();
// Apply SMAA.
gl::ScopedTextureBind tex0( source );
gl::ScopedTextureBind tex1( mFboBlendPass->getColorTexture(), 1 );
gl::ScopedGlslProg glslScope( mGlslThirdPass );
mGlslThirdPass->uniform( "SMAA_RT_METRICS", mMetrics );
mGlslThirdPass->uniform( "uColorTex", 0 );
mGlslThirdPass->uniform( "uBlendTex", 1 );
gl::color( Color::white() );
gl::drawSolidRect( bounds );
// gl::draw( mAreaTex );
}
gl::TextureRef SMAA::getEdgePass()
{
return mFboEdgePass->getColorTexture();
}
gl::TextureRef SMAA::getBlendPass()
{
return mFboBlendPass->getColorTexture();
}
void SMAA::createBuffers( int width, int height )
{
// Create or resize frame buffers
if( !mFboEdgePass || mFboEdgePass->getWidth() != width || mFboEdgePass->getHeight() != height ) {
mFboEdgePass = gl::Fbo::create( width, height, mFboFormat );
}
if( !mFboBlendPass || mFboBlendPass->getWidth() != width || mFboBlendPass->getHeight() != height ) {
mFboBlendPass = gl::Fbo::create( width, height, mFboFormat );
}
mMetrics = vec4( 1.0f / width, 1.0f / height, (float) width, (float) height );
}
void SMAA::doEdgePass( const gl::Texture2dRef &source )
{
// Enable frame buffer, bind textures and shader.
gl::ScopedFramebuffer fbo( mFboEdgePass );
gl::clear( ColorA( 0, 0, 0, 0 ) );
gl::ScopedTextureBind tex0( source );
gl::ScopedGlslProg glslScope( mGlslFirstPass );
mGlslFirstPass->uniform( "SMAA_RT_METRICS", mMetrics );
mGlslFirstPass->uniform( "uColorTex", 0 );
// Execute shader by drawing a 'full screen' rectangle.
gl::color( Color::white() );
gl::drawSolidRect( mFboEdgePass->getBounds() );
}
void SMAA::doBlendPass()
{
// Enable frame buffer, bind textures and shader.
gl::ScopedFramebuffer fbo( mFboBlendPass );
gl::clear( ColorA( 0, 0, 0, 0 ) );
gl::ScopedTextureBind tex0( mFboEdgePass->getColorTexture() );
gl::ScopedTextureBind tex1( mAreaTex, 1 );
gl::ScopedTextureBind tex2( mSearchTex, 2 );
gl::ScopedGlslProg glslScope( mGlslSecondPass );
mGlslSecondPass->uniform( "SMAA_RT_METRICS", mMetrics );
mGlslSecondPass->uniform( "uEdgesTex", 0 );
mGlslSecondPass->uniform( "uAreaTex", 1 );
mGlslSecondPass->uniform( "uSearchTex", 2 );
// Execute shader by drawing a 'full screen' rectangle.
gl::color( Color::white() );
gl::drawSolidRect( mFboBlendPass->getBounds() );
}<commit_msg>Removed 'loadTopDown' as it was ignored and triggered a warning.<commit_after>/*
Copyright (c) 2014, Paul Houx - All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/App.h"
#include "cinder/Log.h"
#include "SMAA.h"
#include "AreaTex.h"
#include "SearchTex.h"
using namespace ci;
using namespace ci::app;
using namespace std;
SMAA::SMAA()
{
// Load and compile our shaders
try {
// Define the format by specifying the vertex and fragment shader files and defining the quality settings.
auto fmt = gl::GlslProg::Format().vertex( loadAsset( "smaa.vert" ) ).fragment( loadAsset( "smaa.frag" ) ).define( "SMAA_PRESET_ULTRA" ).define( "SMAA_GLSL_3", "1" );
// Each pass uses the same files, but with a different value for the SMAA_PASS pre-processor directive.
mGlslFirstPass = gl::GlslProg::create( gl::GlslProg::Format( fmt ).define( "SMAA_PASS", "1" ) );
mGlslSecondPass = gl::GlslProg::create( gl::GlslProg::Format( fmt ).define( "SMAA_PASS", "2" ) );
mGlslThirdPass = gl::GlslProg::create( gl::GlslProg::Format( fmt ).define( "SMAA_PASS", "3" ) );
}
catch( const std::exception& e ) {
CI_LOG_EXCEPTION( "exception caught loading smaa shaders", e );
}
// Create lookup textures
gl::Texture2d::Format fmt;
fmt.setMinFilter( GL_LINEAR );
fmt.setMagFilter( GL_LINEAR );
fmt.setWrap( GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE );
// Search Texture (Grayscale, 8 bits unsigned).
fmt.setInternalFormat( GL_R8 );
fmt.setSwizzleMask( GL_RED, GL_RED, GL_RED, GL_ONE );
mSearchTex = gl::Texture2d::create( searchTexBytes, GL_RED, SEARCHTEX_WIDTH, SEARCHTEX_HEIGHT, fmt );
// Area Texture (Red+Green Channels, 8 bits unsigned).
fmt.setInternalFormat( GL_RG8 );
fmt.setSwizzleMask( GL_RED, GL_GREEN, GL_ZERO, GL_ONE );
mAreaTex = gl::Texture2d::create( areaTexBytes, GL_RG, AREATEX_WIDTH, AREATEX_HEIGHT, fmt );
// Specify the Fbo format.
gl::Texture2d::Format tfmt;
tfmt.setMinFilter( GL_LINEAR );
tfmt.setMagFilter( GL_LINEAR );
tfmt.setInternalFormat( GL_RGBA8 );
mFboFormat.setColorTextureFormat( tfmt );
mFboFormat.enableDepthBuffer( false );
}
void SMAA::apply( const gl::FboRef &destination, const gl::FboRef &source )
{
gl::ScopedFramebuffer fbo( destination );
gl::ScopedViewport viewport( 0, 0, destination->getWidth(), destination->getHeight() );
gl::ScopedMatrices matrices;
gl::setMatricesWindow( destination->getSize() );
// Make sure our source is linearly interpolated.
GLenum minFilter = source->getFormat().getColorTextureFormat().getMinFilter();
GLenum magFilter = source->getFormat().getColorTextureFormat().getMagFilter();
bool filterChanged = ( minFilter != GL_LINEAR || magFilter != GL_LINEAR );
if( filterChanged ) {
source->getColorTexture()->setMinFilter( GL_LINEAR );
source->getColorTexture()->setMagFilter( GL_LINEAR );
}
// Perform SMAA anti-aliasing.
gl::clear( ColorA( 0, 0, 0, 0 ) );
draw( source->getColorTexture(), destination->getBounds() );
// Restore texture parameters.
if( filterChanged ) {
source->getColorTexture()->setMinFilter( minFilter );
source->getColorTexture()->setMagFilter( magFilter );
}
}
void SMAA::draw( const gl::Texture2dRef &source, const Area &bounds )
{
if( ! mGlslFirstPass || ! mGlslSecondPass || ! mGlslThirdPass )
return;
// Create or resize buffers.
const int width = source->getWidth();
const int height = source->getHeight();
createBuffers( width, height );
// Apply first two passes.
doEdgePass( source );
doBlendPass();
// Apply SMAA.
gl::ScopedTextureBind tex0( source );
gl::ScopedTextureBind tex1( mFboBlendPass->getColorTexture(), 1 );
gl::ScopedGlslProg glslScope( mGlslThirdPass );
mGlslThirdPass->uniform( "SMAA_RT_METRICS", mMetrics );
mGlslThirdPass->uniform( "uColorTex", 0 );
mGlslThirdPass->uniform( "uBlendTex", 1 );
gl::color( Color::white() );
gl::drawSolidRect( bounds );
// gl::draw( mAreaTex );
}
gl::TextureRef SMAA::getEdgePass()
{
return mFboEdgePass->getColorTexture();
}
gl::TextureRef SMAA::getBlendPass()
{
return mFboBlendPass->getColorTexture();
}
void SMAA::createBuffers( int width, int height )
{
// Create or resize frame buffers
if( !mFboEdgePass || mFboEdgePass->getWidth() != width || mFboEdgePass->getHeight() != height ) {
mFboEdgePass = gl::Fbo::create( width, height, mFboFormat );
}
if( !mFboBlendPass || mFboBlendPass->getWidth() != width || mFboBlendPass->getHeight() != height ) {
mFboBlendPass = gl::Fbo::create( width, height, mFboFormat );
}
mMetrics = vec4( 1.0f / width, 1.0f / height, (float) width, (float) height );
}
void SMAA::doEdgePass( const gl::Texture2dRef &source )
{
// Enable frame buffer, bind textures and shader.
gl::ScopedFramebuffer fbo( mFboEdgePass );
gl::clear( ColorA( 0, 0, 0, 0 ) );
gl::ScopedTextureBind tex0( source );
gl::ScopedGlslProg glslScope( mGlslFirstPass );
mGlslFirstPass->uniform( "SMAA_RT_METRICS", mMetrics );
mGlslFirstPass->uniform( "uColorTex", 0 );
// Execute shader by drawing a 'full screen' rectangle.
gl::color( Color::white() );
gl::drawSolidRect( mFboEdgePass->getBounds() );
}
void SMAA::doBlendPass()
{
// Enable frame buffer, bind textures and shader.
gl::ScopedFramebuffer fbo( mFboBlendPass );
gl::clear( ColorA( 0, 0, 0, 0 ) );
gl::ScopedTextureBind tex0( mFboEdgePass->getColorTexture() );
gl::ScopedTextureBind tex1( mAreaTex, 1 );
gl::ScopedTextureBind tex2( mSearchTex, 2 );
gl::ScopedGlslProg glslScope( mGlslSecondPass );
mGlslSecondPass->uniform( "SMAA_RT_METRICS", mMetrics );
mGlslSecondPass->uniform( "uEdgesTex", 0 );
mGlslSecondPass->uniform( "uAreaTex", 1 );
mGlslSecondPass->uniform( "uSearchTex", 2 );
// Execute shader by drawing a 'full screen' rectangle.
gl::color( Color::white() );
gl::drawSolidRect( mFboBlendPass->getBounds() );
}<|endoftext|>
|
<commit_before>// Copyright (C) 2010 - 2012 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "copasi.h"
#include "CEvaluationNode.h"
#include "CEvaluationTree.h"
#include "sbml/math/ASTNode.h"
CEvaluationNodeLogical::CEvaluationNodeLogical():
CEvaluationNode(CEvaluationNode::INVALID, ""),
mpLeft(NULL),
mpRight(NULL)
{}
CEvaluationNodeLogical::CEvaluationNodeLogical(const SubType & subType,
const Data & data):
CEvaluationNode((Type)(CEvaluationNode::LOGICAL | subType), data),
mpLeft(NULL),
mpRight(NULL)
{
switch (mType & 0x00FFFFFF)
{
case OR:
mPrecedence = PRECEDENCE_LOGIG_OR;
break;
case XOR:
mPrecedence = PRECEDENCE_LOGIG_XOR;
break;
case AND:
mPrecedence = PRECEDENCE_LOGIG_AND;
break;
case EQ:
mPrecedence = PRECEDENCE_LOGIG_EQ;
break;
case NE:
mPrecedence = PRECEDENCE_LOGIG_NE;
break;
case GT:
mPrecedence = PRECEDENCE_LOGIG_GT;
break;
case GE:
mPrecedence = PRECEDENCE_LOGIG_GE;
break;
case LT:
mPrecedence = PRECEDENCE_LOGIG_LT;
break;
case LE:
mPrecedence = PRECEDENCE_LOGIG_LE;
break;
}
}
CEvaluationNodeLogical::CEvaluationNodeLogical(const CEvaluationNodeLogical & src):
CEvaluationNode(src),
mpLeft(NULL),
mpRight(NULL)
{}
CEvaluationNodeLogical::~CEvaluationNodeLogical() {}
bool CEvaluationNodeLogical::compile(const CEvaluationTree * /* pTree */)
{
mpLeft = static_cast<CEvaluationNode *>(getChild());
if (mpLeft == NULL) return false;
mpRight = static_cast<CEvaluationNode *>(mpLeft->getSibling());
if (mpRight == NULL) return false;
return (mpRight->getSibling() == NULL); // We must have exactly two children
}
// virtual
std::string CEvaluationNodeLogical::getInfix(const std::vector< std::string > & children) const
{
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
Data Infix;
if (*mpLeft < * (CEvaluationNode *)this)
Infix = "(" + children[0] + ")";
else
Infix = children[0];
Infix += " " + mData + " ";
if (!(*(CEvaluationNode *)this < *mpRight))
Infix += "(" + children[1] + ")";
else
Infix += children[1];
return Infix;
}
else
return "@";
}
// virtual
std::string CEvaluationNodeLogical::getDisplayString(const std::vector< std::string > & children) const
{
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
Data DisplayString;
if (*mpLeft < * (CEvaluationNode *)this)
DisplayString = "(" + children[0] + ")";
else
DisplayString = children[0] + " ";
DisplayString += mData;
if (!(*(CEvaluationNode *)this < *mpRight))
DisplayString += "(" + children[1] + ")";
else
DisplayString += " " + children[1];
return DisplayString;
}
else
return "@";
}
// virtual
std::string CEvaluationNodeLogical::getCCodeString(const std::vector< std::string > & children) const
{
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
Data DisplayString;
Data data;
switch ((SubType)CEvaluationNode::subType(this->getType()))
{
case AND:
data = "&&";
break;
case OR:
data = "||";
break;
case EQ:
data = "==";
break;
case GE:
data = ">=";
break;
case GT:
data = ">";
break;
case LE:
data = "<=";
break;
case LT:
data = "<";
break;
case NE:
data = "!=";
break;
default:
/*
* case XOR:
*/
data = "@";
break;
}
if (*mpLeft < * (CEvaluationNode *)this)
DisplayString = "(" + children[0] + ")";
else
DisplayString = children[0] + " ";
DisplayString += data;
if (!(*(CEvaluationNode *)this < *mpRight))
DisplayString += "(" + children[1] + ")";
else
DisplayString += " " + children[1];
return DisplayString;
}
else
return "@";
}
// virtual
std::string CEvaluationNodeLogical::getBerkeleyMadonnaString(const std::vector< std::string > & children) const
{
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
Data DisplayString;
Data data;
switch ((SubType)CEvaluationNode::subType(this->getType()))
{
case AND:
data = "AND";
break;
case OR:
data = "OR";
break;
/* case XOR:
break; */
case EQ:
data = "=";
break;
case GE:
data = ">=";
break;
case GT:
data = ">";
break;
case LE:
data = "<=";
break;
case LT:
data = "<";
break;
case NE:
data = "<>";
break;
default:
data = "@";
break;
}
if (*mpLeft < * (CEvaluationNode *)this)
DisplayString = "(" + children[0] + ")";
else
DisplayString = children[0] + " ";
DisplayString += data;
if (!(*(CEvaluationNode *)this < *mpRight))
DisplayString += "(" + children[1] + ")";
else
DisplayString += " " + children[1];
return DisplayString;
}
else
return "@";
}
// virtual
std::string CEvaluationNodeLogical::getXPPString(const std::vector< std::string > & children) const
{
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
Data DisplayString;
Data data;
switch ((SubType)CEvaluationNode::subType(this->getType()))
{
case AND:
data = "&";
break;
case OR:
data = "|";
break;
case EQ:
data = "==";
break;
case GE:
data = ">=";
break;
case GT:
data = ">";
break;
case LE:
data = "<=";
break;
case LT:
data = "<";
break;
case NE:
data = "!=";
break;
default:
/* case XOR: */
CCopasiMessage(CCopasiMessage::WARNING, " TODO ");
data = "@"; //TODO
break;
}
if (*mpLeft < * (CEvaluationNode *)this)
DisplayString = "(" + children[0] + ")";
else
DisplayString = children[0] + " ";
DisplayString += data;
if (!(*(CEvaluationNode *)this < *mpRight))
DisplayString += "(" + children[1] + ")";
else
DisplayString += " " + children[1];
return DisplayString;
}
else
return "@"; //TODO
}
// static
CEvaluationNode * CEvaluationNodeLogical::fromAST(const ASTNode * pASTNode, const std::vector< CEvaluationNode * > & children)
{
assert(pASTNode->getNumChildren() == children.size());
size_t i = 0;
size_t iMax = children.size();
SubType subType;
std::string data = "";
switch (pASTNode->getType())
{
case AST_LOGICAL_AND:
subType = AND;
data = "and";
break;
case AST_LOGICAL_OR:
subType = OR;
data = "or";
break;
case AST_LOGICAL_XOR:
subType = XOR;
data = "xor";
break;
case AST_RELATIONAL_EQ:
subType = EQ;
data = "eq";
break;
case AST_RELATIONAL_GEQ:
subType = GE;
data = "ge";
break;
case AST_RELATIONAL_GT:
subType = GT;
data = "gt";
break;
case AST_RELATIONAL_LEQ:
subType = LE;
data = "le";
break;
case AST_RELATIONAL_LT:
subType = LT;
data = "lt";
break;
case AST_RELATIONAL_NEQ:
subType = NE;
data = "ne";
break;
default:
subType = INVALID;
break;
}
CEvaluationNode* pNode = NULL;
// convert the two children
switch (subType)
{
case AND:
case OR:
case XOR:
// The number of chidren may vary
switch (iMax)
{
case 0:
if (subType == AND)
pNode = new CEvaluationNodeConstant(CEvaluationNodeConstant::TRUE, "TRUE");
else
pNode = new CEvaluationNodeConstant(CEvaluationNodeConstant::FALSE, "FALSE");
break;
case 1:
pNode = children[0];
break;
default:
{
pNode = new CEvaluationNodeLogical(subType, data);
CEvaluationNode * pCurrent = pNode;
// We have at least 2 children
while (i < iMax - 1)
{
// add the first value
pCurrent->addChild(children[i++]);
switch (iMax - i)
{
case 1:
// We have only 1 more child
pCurrent->addChild(children[i++]);
break;
default:
// We have at least 2 more children
{
// create a new node with the same operator
CEvaluationNode * pTmp = new CEvaluationNodeLogical(subType, data);
pCurrent->addChild(pTmp);
pCurrent = pTmp;
}
break;
}
}
}
break;
}
break;
case EQ:
case NE:
case GE:
case GT:
case LE:
case LT:
// all these are binary
assert(iMax == 2);
pNode = new CEvaluationNodeLogical(subType, data);
pNode->addChild(children[0]);
pNode->addChild(children[1]);
break;
case INVALID:
// do nothing
break;
}
return pNode;
}
// virtual
bool CEvaluationNodeLogical::isBoolean() const
{return true;}
ASTNode* CEvaluationNodeLogical::toAST(const CCopasiDataModel* pDataModel) const
{
SubType subType = (SubType)CEvaluationNode::subType(this->getType());
ASTNode* node = new ASTNode();
switch (subType)
{
case AND:
node->setType(AST_LOGICAL_AND);
break;
case OR:
node->setType(AST_LOGICAL_OR);
break;
case XOR:
node->setType(AST_LOGICAL_XOR);
break;
case EQ:
node->setType(AST_RELATIONAL_EQ);
break;
case NE:
node->setType(AST_RELATIONAL_NEQ);
break;
case GT:
node->setType(AST_RELATIONAL_GT);
break;
case GE:
node->setType(AST_RELATIONAL_GEQ);
break;
case LT:
node->setType(AST_RELATIONAL_LT);
break;
case LE:
node->setType(AST_RELATIONAL_LEQ);
break;
case INVALID:
break;
default:
subType = INVALID;
break;
}
if (subType != INVALID)
{
const CEvaluationNode* child1 = dynamic_cast<const CEvaluationNode*>(this->getChild());
const CEvaluationNode* child2 = dynamic_cast<const CEvaluationNode*>(child1->getSibling());
node->addChild(child1->toAST(pDataModel));
node->addChild(child2->toAST(pDataModel));
}
return node;
}
#include "utilities/copasimathml.h"
// virtual
std::string CEvaluationNodeLogical::getMMLString(const std::vector< std::string > & children,
bool /* expand */,
const std::vector< std::vector< std::string > > & /* variables */) const
{
std::ostringstream out;
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
std::string data = "";
bool flag = false;
switch ((SubType)CEvaluationNode::subType(this->getType()))
{
case AND:
data = " and ";
break;
case OR:
data = " or ";
break;
case XOR:
data = " xor ";
break;
case EQ:
data = "=";
break;
case GE:
data = ">=";
break;
case GT:
data = ">";
break;
case LE:
data = "<=";
break;
case LT:
data = "<";
break;
case NE:
data = "≠";
break;
default:
/*
*
*/
data = "@";
break;
}
out << "<mrow>" << std::endl;
flag = ((*mpLeft < * (CEvaluationNode *)this));
if (flag) out << "<mfenced>" << std::endl;
out << children[0];
if (flag) out << "</mfenced>" << std::endl;
out << "<mo>" << data << "</mo>" << std::endl;
flag = ((*(CEvaluationNode *)this < *mpRight));
if (!flag) out << "<mfenced>" << std::endl;
out << children[1];
if (!flag) out << "</mfenced>" << std::endl;
out << "</mrow>" << std::endl;
}
return out.str();
}
<commit_msg>- fix for bug 1965: missing xor export, now instead of (a @ b) it exports (!a != !b)<commit_after>// Copyright (C) 2010 - 2012 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "copasi.h"
#include "CEvaluationNode.h"
#include "CEvaluationTree.h"
#include "sbml/math/ASTNode.h"
CEvaluationNodeLogical::CEvaluationNodeLogical():
CEvaluationNode(CEvaluationNode::INVALID, ""),
mpLeft(NULL),
mpRight(NULL)
{}
CEvaluationNodeLogical::CEvaluationNodeLogical(const SubType & subType,
const Data & data):
CEvaluationNode((Type)(CEvaluationNode::LOGICAL | subType), data),
mpLeft(NULL),
mpRight(NULL)
{
switch (mType & 0x00FFFFFF)
{
case OR:
mPrecedence = PRECEDENCE_LOGIG_OR;
break;
case XOR:
mPrecedence = PRECEDENCE_LOGIG_XOR;
break;
case AND:
mPrecedence = PRECEDENCE_LOGIG_AND;
break;
case EQ:
mPrecedence = PRECEDENCE_LOGIG_EQ;
break;
case NE:
mPrecedence = PRECEDENCE_LOGIG_NE;
break;
case GT:
mPrecedence = PRECEDENCE_LOGIG_GT;
break;
case GE:
mPrecedence = PRECEDENCE_LOGIG_GE;
break;
case LT:
mPrecedence = PRECEDENCE_LOGIG_LT;
break;
case LE:
mPrecedence = PRECEDENCE_LOGIG_LE;
break;
}
}
CEvaluationNodeLogical::CEvaluationNodeLogical(const CEvaluationNodeLogical & src):
CEvaluationNode(src),
mpLeft(NULL),
mpRight(NULL)
{}
CEvaluationNodeLogical::~CEvaluationNodeLogical() {}
bool CEvaluationNodeLogical::compile(const CEvaluationTree * /* pTree */)
{
mpLeft = static_cast<CEvaluationNode *>(getChild());
if (mpLeft == NULL) return false;
mpRight = static_cast<CEvaluationNode *>(mpLeft->getSibling());
if (mpRight == NULL) return false;
return (mpRight->getSibling() == NULL); // We must have exactly two children
}
// virtual
std::string CEvaluationNodeLogical::getInfix(const std::vector< std::string > & children) const
{
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
Data Infix;
if (*mpLeft < * (CEvaluationNode *)this)
Infix = "(" + children[0] + ")";
else
Infix = children[0];
Infix += " " + mData + " ";
if (!(*(CEvaluationNode *)this < *mpRight))
Infix += "(" + children[1] + ")";
else
Infix += children[1];
return Infix;
}
else
return "@";
}
// virtual
std::string CEvaluationNodeLogical::getDisplayString(const std::vector< std::string > & children) const
{
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
Data DisplayString;
if (*mpLeft < * (CEvaluationNode *)this)
DisplayString = "(" + children[0] + ")";
else
DisplayString = children[0] + " ";
DisplayString += mData;
if (!(*(CEvaluationNode *)this < *mpRight))
DisplayString += "(" + children[1] + ")";
else
DisplayString += " " + children[1];
return DisplayString;
}
else
return "@";
}
// virtual
std::string CEvaluationNodeLogical::getCCodeString(const std::vector< std::string > & children) const
{
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
Data DisplayString;
Data data;
bool isXor = false;
switch ((SubType)CEvaluationNode::subType(this->getType()))
{
case AND:
data = "&&";
break;
case OR:
data = "||";
break;
case EQ:
data = "==";
break;
case GE:
data = ">=";
break;
case GT:
data = ">";
break;
case LE:
data = "<=";
break;
case LT:
data = "<";
break;
case NE:
data = "!=";
break;
default:
/*
* case XOR:
*/
data = "!=";
isXor = true;
break;
}
if (isXor)
DisplayString = " !";
else
DisplayString = "";
if (*mpLeft < * (CEvaluationNode *)this)
DisplayString += "(" + children[0] + ")";
else
DisplayString += children[0] + " ";
DisplayString += data;
if (isXor)
DisplayString += " !";
if (!(*(CEvaluationNode *)this < *mpRight))
DisplayString += "(" + children[1] + ")";
else
DisplayString += " " + children[1];
return DisplayString;
}
else
return "@";
}
// virtual
std::string CEvaluationNodeLogical::getBerkeleyMadonnaString(const std::vector< std::string > & children) const
{
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
Data DisplayString;
Data data;
switch ((SubType)CEvaluationNode::subType(this->getType()))
{
case AND:
data = "AND";
break;
case OR:
data = "OR";
break;
/* case XOR:
break; */
case EQ:
data = "=";
break;
case GE:
data = ">=";
break;
case GT:
data = ">";
break;
case LE:
data = "<=";
break;
case LT:
data = "<";
break;
case NE:
data = "<>";
break;
default:
data = "@";
break;
}
if (*mpLeft < * (CEvaluationNode *)this)
DisplayString = "(" + children[0] + ")";
else
DisplayString = children[0] + " ";
DisplayString += data;
if (!(*(CEvaluationNode *)this < *mpRight))
DisplayString += "(" + children[1] + ")";
else
DisplayString += " " + children[1];
return DisplayString;
}
else
return "@";
}
// virtual
std::string CEvaluationNodeLogical::getXPPString(const std::vector< std::string > & children) const
{
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
Data DisplayString;
Data data;
switch ((SubType)CEvaluationNode::subType(this->getType()))
{
case AND:
data = "&";
break;
case OR:
data = "|";
break;
case EQ:
data = "==";
break;
case GE:
data = ">=";
break;
case GT:
data = ">";
break;
case LE:
data = "<=";
break;
case LT:
data = "<";
break;
case NE:
data = "!=";
break;
default:
/* case XOR: */
CCopasiMessage(CCopasiMessage::WARNING, " TODO ");
data = "@"; //TODO
break;
}
if (*mpLeft < * (CEvaluationNode *)this)
DisplayString = "(" + children[0] + ")";
else
DisplayString = children[0] + " ";
DisplayString += data;
if (!(*(CEvaluationNode *)this < *mpRight))
DisplayString += "(" + children[1] + ")";
else
DisplayString += " " + children[1];
return DisplayString;
}
else
return "@"; //TODO
}
// static
CEvaluationNode * CEvaluationNodeLogical::fromAST(const ASTNode * pASTNode, const std::vector< CEvaluationNode * > & children)
{
assert(pASTNode->getNumChildren() == children.size());
size_t i = 0;
size_t iMax = children.size();
SubType subType;
std::string data = "";
switch (pASTNode->getType())
{
case AST_LOGICAL_AND:
subType = AND;
data = "and";
break;
case AST_LOGICAL_OR:
subType = OR;
data = "or";
break;
case AST_LOGICAL_XOR:
subType = XOR;
data = "xor";
break;
case AST_RELATIONAL_EQ:
subType = EQ;
data = "eq";
break;
case AST_RELATIONAL_GEQ:
subType = GE;
data = "ge";
break;
case AST_RELATIONAL_GT:
subType = GT;
data = "gt";
break;
case AST_RELATIONAL_LEQ:
subType = LE;
data = "le";
break;
case AST_RELATIONAL_LT:
subType = LT;
data = "lt";
break;
case AST_RELATIONAL_NEQ:
subType = NE;
data = "ne";
break;
default:
subType = INVALID;
break;
}
CEvaluationNode* pNode = NULL;
// convert the two children
switch (subType)
{
case AND:
case OR:
case XOR:
// The number of chidren may vary
switch (iMax)
{
case 0:
if (subType == AND)
pNode = new CEvaluationNodeConstant(CEvaluationNodeConstant::TRUE, "TRUE");
else
pNode = new CEvaluationNodeConstant(CEvaluationNodeConstant::FALSE, "FALSE");
break;
case 1:
pNode = children[0];
break;
default:
{
pNode = new CEvaluationNodeLogical(subType, data);
CEvaluationNode * pCurrent = pNode;
// We have at least 2 children
while (i < iMax - 1)
{
// add the first value
pCurrent->addChild(children[i++]);
switch (iMax - i)
{
case 1:
// We have only 1 more child
pCurrent->addChild(children[i++]);
break;
default:
// We have at least 2 more children
{
// create a new node with the same operator
CEvaluationNode * pTmp = new CEvaluationNodeLogical(subType, data);
pCurrent->addChild(pTmp);
pCurrent = pTmp;
}
break;
}
}
}
break;
}
break;
case EQ:
case NE:
case GE:
case GT:
case LE:
case LT:
// all these are binary
assert(iMax == 2);
pNode = new CEvaluationNodeLogical(subType, data);
pNode->addChild(children[0]);
pNode->addChild(children[1]);
break;
case INVALID:
// do nothing
break;
}
return pNode;
}
// virtual
bool CEvaluationNodeLogical::isBoolean() const
{return true;}
ASTNode* CEvaluationNodeLogical::toAST(const CCopasiDataModel* pDataModel) const
{
SubType subType = (SubType)CEvaluationNode::subType(this->getType());
ASTNode* node = new ASTNode();
switch (subType)
{
case AND:
node->setType(AST_LOGICAL_AND);
break;
case OR:
node->setType(AST_LOGICAL_OR);
break;
case XOR:
node->setType(AST_LOGICAL_XOR);
break;
case EQ:
node->setType(AST_RELATIONAL_EQ);
break;
case NE:
node->setType(AST_RELATIONAL_NEQ);
break;
case GT:
node->setType(AST_RELATIONAL_GT);
break;
case GE:
node->setType(AST_RELATIONAL_GEQ);
break;
case LT:
node->setType(AST_RELATIONAL_LT);
break;
case LE:
node->setType(AST_RELATIONAL_LEQ);
break;
case INVALID:
break;
default:
subType = INVALID;
break;
}
if (subType != INVALID)
{
const CEvaluationNode* child1 = dynamic_cast<const CEvaluationNode*>(this->getChild());
const CEvaluationNode* child2 = dynamic_cast<const CEvaluationNode*>(child1->getSibling());
node->addChild(child1->toAST(pDataModel));
node->addChild(child2->toAST(pDataModel));
}
return node;
}
#include "utilities/copasimathml.h"
// virtual
std::string CEvaluationNodeLogical::getMMLString(const std::vector< std::string > & children,
bool /* expand */,
const std::vector< std::vector< std::string > > & /* variables */) const
{
std::ostringstream out;
if (const_cast<CEvaluationNodeLogical *>(this)->compile(NULL))
{
std::string data = "";
bool flag = false;
switch ((SubType)CEvaluationNode::subType(this->getType()))
{
case AND:
data = " and ";
break;
case OR:
data = " or ";
break;
case XOR:
data = " xor ";
break;
case EQ:
data = "=";
break;
case GE:
data = ">=";
break;
case GT:
data = ">";
break;
case LE:
data = "<=";
break;
case LT:
data = "<";
break;
case NE:
data = "≠";
break;
default:
/*
*
*/
data = "@";
break;
}
out << "<mrow>" << std::endl;
flag = ((*mpLeft < * (CEvaluationNode *)this));
if (flag) out << "<mfenced>" << std::endl;
out << children[0];
if (flag) out << "</mfenced>" << std::endl;
out << "<mo>" << data << "</mo>" << std::endl;
flag = ((*(CEvaluationNode *)this < *mpRight));
if (!flag) out << "<mfenced>" << std::endl;
out << children[1];
if (!flag) out << "</mfenced>" << std::endl;
out << "</mrow>" << std::endl;
}
return out.str();
}
<|endoftext|>
|
<commit_before>#pragma once
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include "boundary.hpp"
#include "mass_matrix_assembly.hpp"
#include "neumann_boundary_assemble.hpp"
#include "stiffness_matrix_assembly.hpp"
//! Evolves the solution in time using the explicit Forward Euler scheme
//!
//! @param vertices the list of vertices that build the triangular mesh
//! @param triangles the list of indices that represent the triangular mesh
//! @param u0 the initial data
//! @param gamma the parameter gamma (has to do with the boundary conditions)
//! @param m number of timesteps to perform
//! @returns a pair which contains as first parameter the solution at time = 1,
//! and second parameter the energy evolving over time.
std::pair<Eigen::VectorXd, std::vector<double>> radiativeTimeEvolutionExplicit(const Eigen::MatrixXd &vertices,
const Eigen::MatrixXi &triangles,
const Eigen::VectorXd &u0,
const double gamma,
const int m) {
std::vector<double> energy;
Eigen::VectorXd u(u0.size());
u = u0;
double dt = 1.0 / m;
// Get the edges, this is used to compute the neumann boundary matrix
Eigen::MatrixXi edges = getBoundaryEdges(vertices, triangles);
// Define the needed matrices and solvers
// (write your solution here)
for (int timestep = 0; timestep < m; ++timestep) {
// Step the solution forward in time
// (write your solution here)
energy.push_back(u.sum() / u.rows());
}
return std::make_pair(u, energy);
}
<commit_msg>Solved series 4 problem 1i<commit_after>#pragma once
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include "boundary.hpp"
#include "mass_matrix_assembly.hpp"
#include "neumann_boundary_assemble.hpp"
#include "stiffness_matrix_assembly.hpp"
//! Evolves the solution in time using the explicit Forward Euler scheme
//!
//! @param vertices the list of vertices that build the triangular mesh
//! @param triangles the list of indices that represent the triangular mesh
//! @param u0 the initial data
//! @param gamma the parameter gamma (has to do with the boundary conditions)
//! @param m number of timesteps to perform
//! @returns a pair which contains as first parameter the solution at time = 1,
//! and second parameter the energy evolving over time.
std::pair<Eigen::VectorXd, std::vector<double>> radiativeTimeEvolutionExplicit(const Eigen::MatrixXd &vertices,
const Eigen::MatrixXi &triangles,
const Eigen::VectorXd &u0,
const double gamma,
const int m) {
std::vector<double> energy;
Eigen::VectorXd u(u0.size());
u = u0;
double dt = 1.0 / m;
// Get the edges, this is used to compute the neumann boundary matrix
Eigen::MatrixXi edges = getBoundaryEdges(vertices, triangles);
// Define the needed matrices and solvers
SparseMatrix M = assembleMassMatrix(vertices, triangles);
SparseMatrix A = assembleStiffnessMatrix(vertices, triangles);
SparseMatrix B = assembleBoundaryMatrix(vertices, edges, gamma);
A += B;
Eigen::SimplicialLDLT<SparseMatrix> SolverM;
SolverM.compute(M);
if (SolverM.info() != Eigen::Success) {
throw std::runtime_error("Could not decompose matrix M");
}
// (write your solution here)
for (int timestep = 0; timestep < m; ++timestep) {
// Step the solution forward in time
// (write your solution here)
u += SolverM.solve(-1.0 * dt * A * u).eval();
energy.push_back(u.sum() / u.rows());
}
return std::make_pair(u, energy);
}
<|endoftext|>
|
<commit_before>/** \file patch_up_ppns_for_k10plus.cc
* \brief Swaps out all persistent old PPN's with new PPN's.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2019, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <kchashdb.h>
#include "Compiler.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "MapUtil.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "UBTools.h"
#include "util.h"
#include "VuFind.h"
namespace {
[[noreturn]] void Usage() {
::Usage("[--store-only] marc_input1 [marc_input2 .. marc_inputN]"
"If --store-only has been specified, no swapping will be performed and only the persistent map file will be overwritten.");
}
struct PPNsAndSigil {
std::string old_ppn_, old_sigil_, new_ppn_;
public:
PPNsAndSigil(const std::string &old_ppn, const std::string &old_sigil, const std::string &new_ppn)
: old_ppn_(old_ppn), old_sigil_(old_sigil), new_ppn_(new_ppn) { }
PPNsAndSigil() = default;
PPNsAndSigil(const PPNsAndSigil &other) = default;
};
void LoadMapping(MARC::Reader * const marc_reader,
const std::unordered_multimap<std::string, std::string> &already_processed_ppns_and_sigils,
std::vector<PPNsAndSigil> * const old_ppns_sigils_and_new_ppns)
{
// We need to consider the sigil of the old BSZ as well as the K10+ sigil because in future there may also be merges of
// K10+ entities which will lead to old PPN's being K10+ PPN's.
auto matcher(RegexMatcher::RegexMatcherFactoryOrDie("^\\((DE-576|DE-627)\\)(.+)"));
while (const auto record = marc_reader->read()) {
for (const auto &field : record.getTagRange("035")) {
const auto subfield_a(field.getFirstSubfieldWithCode('a'));
if (matcher->matched(subfield_a)) {
const std::string old_sigil((*matcher)[1]);
const std::string old_ppn((*matcher)[2]);
if (not MapUtil::Contains(already_processed_ppns_and_sigils, old_ppn, old_sigil))
old_ppns_sigils_and_new_ppns->emplace_back(old_ppn, old_sigil, record.getControlNumber());
}
}
}
LOG_INFO("Found " + std::to_string(old_ppns_sigils_and_new_ppns->size()) + " new mappings of old PPN's to new PPN's in \""
+ marc_reader->getPath() + "\".\n");
}
void PatchTable(DbConnection * const db_connection, const std::string &table, const std::string &column,
const std::vector<PPNsAndSigil> &old_ppns_sigils_and_new_ppns)
{
const unsigned MAX_BATCH_SIZE(100);
db_connection->queryOrDie("BEGIN");
unsigned replacement_count(0), batch_size(0);
for (const auto &old_ppn_sigil_and_new_ppn : old_ppns_sigils_and_new_ppns) {
++batch_size;
db_connection->queryOrDie("UPDATE IGNORE " + table + " SET " + column + "='" + old_ppn_sigil_and_new_ppn.new_ppn_
+ "' WHERE " + column + "='" + old_ppn_sigil_and_new_ppn.old_ppn_ + "'");
replacement_count += db_connection->getNoOfAffectedRows();
if (batch_size >= MAX_BATCH_SIZE) {
db_connection->queryOrDie("COMMIT");
db_connection->queryOrDie("BEGIN");
}
}
db_connection->queryOrDie("COMMIT");
LOG_INFO("Replaced " + std::to_string(replacement_count) + " rows in " + table + ".");
}
void PatchNotifiedDB(const std::string &user_type, const std::vector<PPNsAndSigil> &old_ppns_sigils_and_new_ppns) {
const std::string DB_FILENAME(UBTools::GetTuelibPath() + user_type + "_notified.db");
std::unique_ptr<kyotocabinet::HashDB> db(new kyotocabinet::HashDB());
if (not (db->open(DB_FILENAME, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OREADER))) {
LOG_INFO("\"" + DB_FILENAME + "\" not found!");
return;
}
unsigned updated_count(0);
for (const auto &ppns_and_sigil : old_ppns_sigils_and_new_ppns) {
std::string value;
if (db->get(ppns_and_sigil.old_ppn_, &value)) {
if (unlikely(not db->remove(ppns_and_sigil.old_ppn_)))
LOG_ERROR("failed to remove key \"" + ppns_and_sigil.old_ppn_ + "\" from \"" + DB_FILENAME + "\"!");
if (unlikely(not db->add(ppns_and_sigil.old_ppn_, value)))
LOG_ERROR("failed to add key \"" + ppns_and_sigil.old_ppn_ + "\" from \"" + DB_FILENAME + "\"!");
++updated_count;
}
}
LOG_INFO("Updated " + std::to_string(updated_count) + " entries in \"" + DB_FILENAME + "\".");
}
bool HaveAllPermissions(DbConnection * const db_connection, const std::string &database) {
const std::string QUERY("SHOW GRANTS FOR '" + db_connection->getUser() + "'@'" + db_connection->getHost() + "'");
if (not db_connection->query(QUERY)) {
if (db_connection->getLastErrorCode() == 1141)
return false;
LOG_ERROR(QUERY + " failed: " + db_connection->getLastErrorMessage());
}
DbResultSet result_set(db_connection->getLastResultSet());
while (const auto row = result_set.getNextRow()) {
if (row[0]
== "GRANT ALL PRIVILEGES ON `" + database + "`.* TO '" + db_connection->getUser() + "'@'" + db_connection->getHost() + "'")
return true;
}
return false;
}
void CheckMySQLPermissions(DbConnection * const db_connection) {
if (not HaveAllPermissions(db_connection, "vufind"))
LOG_ERROR("'" + db_connection->getUser() + "'@'" + db_connection->getHost() + "' needs all permissions on the vufind database!");
if (VuFind::GetTueFindFlavour() == "ixtheo") {
if (not HaveAllPermissions(db_connection, "ixtheo"))
LOG_ERROR("'" + db_connection->getUser() + "'@' " + db_connection->getHost()
+ "' needs all permissions on the ixtheo database!");
}
}
void AddPPNsAndSigilsToMultiMap(const std::vector<PPNsAndSigil> &old_ppns_sigils_and_new_ppns,
std::unordered_multimap<std::string, std::string> * const already_processed_ppns_and_sigils)
{
for (const auto &old_ppn_sigil_and_new_ppn : old_ppns_sigils_and_new_ppns)
already_processed_ppns_and_sigils->emplace(std::make_pair(old_ppn_sigil_and_new_ppn.old_ppn_, old_ppn_sigil_and_new_ppn.old_sigil_));
}
} // unnamed namespace
static const std::string ALREADY_SWAPPED_PPNS_MAP_FILE(UBTools::GetTuelibPath() + "k10+_ppn_map.map");
int Main(int argc, char **argv) {
if (argc < 2)
Usage();
bool store_only(false);
if (std::strcmp(argv[1], "--store-only") == 0) {
store_only = true;
--argc, ++argv;
if (argc < 2)
Usage();
}
DbConnection db_connection; // ub_tools user
CheckMySQLPermissions(&db_connection);
std::unordered_multimap<std::string, std::string> already_processed_ppns_and_sigils;
if (not store_only)
MapUtil::DeserialiseMap(ALREADY_SWAPPED_PPNS_MAP_FILE, &already_processed_ppns_and_sigils);
std::vector<PPNsAndSigil> old_ppns_sigils_and_new_ppns;
for (int arg_no(1); arg_no < argc; ++arg_no) {
const auto marc_reader(MARC::Reader::Factory(argv[arg_no]));
LoadMapping(marc_reader.get(), already_processed_ppns_and_sigils, &old_ppns_sigils_and_new_ppns);
}
if (old_ppns_sigils_and_new_ppns.empty()) {
LOG_INFO("nothing to do!");
return EXIT_SUCCESS;
}
if (store_only) {
AddPPNsAndSigilsToMultiMap(old_ppns_sigils_and_new_ppns, &already_processed_ppns_and_sigils);
MapUtil::SerialiseMap(ALREADY_SWAPPED_PPNS_MAP_FILE, already_processed_ppns_and_sigils);
return EXIT_SUCCESS;
}
PatchNotifiedDB("ixtheo", old_ppns_sigils_and_new_ppns);
PatchNotifiedDB("relbib", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.resource", "record_id", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.record", "record_id", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.change_tracker", "id", old_ppns_sigils_and_new_ppns);
if (VuFind::GetTueFindFlavour() == "ixtheo") {
PatchTable(&db_connection, "ixtheo.keyword_translations", "ppn", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.ixtheo_journal_subscriptions", "journal_control_number_or_bundle_name",
old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.ixtheo_pda_subscriptions", "book_ppn", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.relbib_ids", "record_id", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.bibstudies_ids", "record_id", old_ppns_sigils_and_new_ppns);
}
AddPPNsAndSigilsToMultiMap(old_ppns_sigils_and_new_ppns, &already_processed_ppns_and_sigils);
MapUtil::SerialiseMap(ALREADY_SWAPPED_PPNS_MAP_FILE, already_processed_ppns_and_sigils);
return EXIT_SUCCESS;
}
<commit_msg>patch_up_ppns_for_k10plus: create ALREADY_SWAPPED_PPNS_MAP_FILE if not exists<commit_after>/** \file patch_up_ppns_for_k10plus.cc
* \brief Swaps out all persistent old PPN's with new PPN's.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2019, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <kchashdb.h>
#include "Compiler.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "FileUtil.h"
#include "MapUtil.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "UBTools.h"
#include "util.h"
#include "VuFind.h"
namespace {
[[noreturn]] void Usage() {
::Usage("[--store-only] marc_input1 [marc_input2 .. marc_inputN]"
"If --store-only has been specified, no swapping will be performed and only the persistent map file will be overwritten.");
}
struct PPNsAndSigil {
std::string old_ppn_, old_sigil_, new_ppn_;
public:
PPNsAndSigil(const std::string &old_ppn, const std::string &old_sigil, const std::string &new_ppn)
: old_ppn_(old_ppn), old_sigil_(old_sigil), new_ppn_(new_ppn) { }
PPNsAndSigil() = default;
PPNsAndSigil(const PPNsAndSigil &other) = default;
};
void LoadMapping(MARC::Reader * const marc_reader,
const std::unordered_multimap<std::string, std::string> &already_processed_ppns_and_sigils,
std::vector<PPNsAndSigil> * const old_ppns_sigils_and_new_ppns)
{
// We need to consider the sigil of the old BSZ as well as the K10+ sigil because in future there may also be merges of
// K10+ entities which will lead to old PPN's being K10+ PPN's.
auto matcher(RegexMatcher::RegexMatcherFactoryOrDie("^\\((DE-576|DE-627)\\)(.+)"));
while (const auto record = marc_reader->read()) {
for (const auto &field : record.getTagRange("035")) {
const auto subfield_a(field.getFirstSubfieldWithCode('a'));
if (matcher->matched(subfield_a)) {
const std::string old_sigil((*matcher)[1]);
const std::string old_ppn((*matcher)[2]);
if (not MapUtil::Contains(already_processed_ppns_and_sigils, old_ppn, old_sigil))
old_ppns_sigils_and_new_ppns->emplace_back(old_ppn, old_sigil, record.getControlNumber());
}
}
}
LOG_INFO("Found " + std::to_string(old_ppns_sigils_and_new_ppns->size()) + " new mappings of old PPN's to new PPN's in \""
+ marc_reader->getPath() + "\".\n");
}
void PatchTable(DbConnection * const db_connection, const std::string &table, const std::string &column,
const std::vector<PPNsAndSigil> &old_ppns_sigils_and_new_ppns)
{
const unsigned MAX_BATCH_SIZE(100);
db_connection->queryOrDie("BEGIN");
unsigned replacement_count(0), batch_size(0);
for (const auto &old_ppn_sigil_and_new_ppn : old_ppns_sigils_and_new_ppns) {
++batch_size;
db_connection->queryOrDie("UPDATE IGNORE " + table + " SET " + column + "='" + old_ppn_sigil_and_new_ppn.new_ppn_
+ "' WHERE " + column + "='" + old_ppn_sigil_and_new_ppn.old_ppn_ + "'");
replacement_count += db_connection->getNoOfAffectedRows();
if (batch_size >= MAX_BATCH_SIZE) {
db_connection->queryOrDie("COMMIT");
db_connection->queryOrDie("BEGIN");
}
}
db_connection->queryOrDie("COMMIT");
LOG_INFO("Replaced " + std::to_string(replacement_count) + " rows in " + table + ".");
}
void PatchNotifiedDB(const std::string &user_type, const std::vector<PPNsAndSigil> &old_ppns_sigils_and_new_ppns) {
const std::string DB_FILENAME(UBTools::GetTuelibPath() + user_type + "_notified.db");
std::unique_ptr<kyotocabinet::HashDB> db(new kyotocabinet::HashDB());
if (not (db->open(DB_FILENAME, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OREADER))) {
LOG_INFO("\"" + DB_FILENAME + "\" not found!");
return;
}
unsigned updated_count(0);
for (const auto &ppns_and_sigil : old_ppns_sigils_and_new_ppns) {
std::string value;
if (db->get(ppns_and_sigil.old_ppn_, &value)) {
if (unlikely(not db->remove(ppns_and_sigil.old_ppn_)))
LOG_ERROR("failed to remove key \"" + ppns_and_sigil.old_ppn_ + "\" from \"" + DB_FILENAME + "\"!");
if (unlikely(not db->add(ppns_and_sigil.old_ppn_, value)))
LOG_ERROR("failed to add key \"" + ppns_and_sigil.old_ppn_ + "\" from \"" + DB_FILENAME + "\"!");
++updated_count;
}
}
LOG_INFO("Updated " + std::to_string(updated_count) + " entries in \"" + DB_FILENAME + "\".");
}
bool HaveAllPermissions(DbConnection * const db_connection, const std::string &database) {
const std::string QUERY("SHOW GRANTS FOR '" + db_connection->getUser() + "'@'" + db_connection->getHost() + "'");
if (not db_connection->query(QUERY)) {
if (db_connection->getLastErrorCode() == 1141)
return false;
LOG_ERROR(QUERY + " failed: " + db_connection->getLastErrorMessage());
}
DbResultSet result_set(db_connection->getLastResultSet());
while (const auto row = result_set.getNextRow()) {
if (row[0]
== "GRANT ALL PRIVILEGES ON `" + database + "`.* TO '" + db_connection->getUser() + "'@'" + db_connection->getHost() + "'")
return true;
}
return false;
}
void CheckMySQLPermissions(DbConnection * const db_connection) {
if (not HaveAllPermissions(db_connection, "vufind"))
LOG_ERROR("'" + db_connection->getUser() + "'@'" + db_connection->getHost() + "' needs all permissions on the vufind database!");
if (VuFind::GetTueFindFlavour() == "ixtheo") {
if (not HaveAllPermissions(db_connection, "ixtheo"))
LOG_ERROR("'" + db_connection->getUser() + "'@' " + db_connection->getHost()
+ "' needs all permissions on the ixtheo database!");
}
}
void AddPPNsAndSigilsToMultiMap(const std::vector<PPNsAndSigil> &old_ppns_sigils_and_new_ppns,
std::unordered_multimap<std::string, std::string> * const already_processed_ppns_and_sigils)
{
for (const auto &old_ppn_sigil_and_new_ppn : old_ppns_sigils_and_new_ppns)
already_processed_ppns_and_sigils->emplace(std::make_pair(old_ppn_sigil_and_new_ppn.old_ppn_, old_ppn_sigil_and_new_ppn.old_sigil_));
}
} // unnamed namespace
static const std::string ALREADY_SWAPPED_PPNS_MAP_FILE(UBTools::GetTuelibPath() + "k10+_ppn_map.map");
int Main(int argc, char **argv) {
if (argc < 2)
Usage();
bool store_only(false);
if (std::strcmp(argv[1], "--store-only") == 0) {
store_only = true;
--argc, ++argv;
if (argc < 2)
Usage();
}
DbConnection db_connection; // ub_tools user
CheckMySQLPermissions(&db_connection);
std::unordered_multimap<std::string, std::string> already_processed_ppns_and_sigils;
if (not FileUtil::Exists(ALREADY_SWAPPED_PPNS_MAP_FILE))
FileUtil::WriteStringOrDie(ALREADY_SWAPPED_PPNS_MAP_FILE, "");
if (not store_only)
MapUtil::DeserialiseMap(ALREADY_SWAPPED_PPNS_MAP_FILE, &already_processed_ppns_and_sigils);
std::vector<PPNsAndSigil> old_ppns_sigils_and_new_ppns;
for (int arg_no(1); arg_no < argc; ++arg_no) {
const auto marc_reader(MARC::Reader::Factory(argv[arg_no]));
LoadMapping(marc_reader.get(), already_processed_ppns_and_sigils, &old_ppns_sigils_and_new_ppns);
}
if (old_ppns_sigils_and_new_ppns.empty()) {
LOG_INFO("nothing to do!");
return EXIT_SUCCESS;
}
if (store_only) {
AddPPNsAndSigilsToMultiMap(old_ppns_sigils_and_new_ppns, &already_processed_ppns_and_sigils);
MapUtil::SerialiseMap(ALREADY_SWAPPED_PPNS_MAP_FILE, already_processed_ppns_and_sigils);
return EXIT_SUCCESS;
}
PatchNotifiedDB("ixtheo", old_ppns_sigils_and_new_ppns);
PatchNotifiedDB("relbib", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.resource", "record_id", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.record", "record_id", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.change_tracker", "id", old_ppns_sigils_and_new_ppns);
if (VuFind::GetTueFindFlavour() == "ixtheo") {
PatchTable(&db_connection, "ixtheo.keyword_translations", "ppn", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.ixtheo_journal_subscriptions", "journal_control_number_or_bundle_name",
old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.ixtheo_pda_subscriptions", "book_ppn", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.relbib_ids", "record_id", old_ppns_sigils_and_new_ppns);
PatchTable(&db_connection, "vufind.bibstudies_ids", "record_id", old_ppns_sigils_and_new_ppns);
}
AddPPNsAndSigilsToMultiMap(old_ppns_sigils_and_new_ppns, &already_processed_ppns_and_sigils);
MapUtil::SerialiseMap(ALREADY_SWAPPED_PPNS_MAP_FILE, already_processed_ppns_and_sigils);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/app/plugin.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/operation_history_object.hpp>
namespace graphene { namespace elasticsearch {
using namespace chain;
//
// Plugins should #define their SPACE_ID's so plugins with
// conflicting SPACE_ID assignments can be compiled into the
// same binary (by simply re-assigning some of the conflicting #defined
// SPACE_ID's in a build script).
//
// Assignment of SPACE_ID's cannot be done at run-time because
// various template automagic depends on them being known at compile
// time.
//
#ifndef ELASTICSEARCH_SPACE_ID
#define ELASTICSEARCH_SPACE_ID 6
#endif
namespace detail
{
class elasticsearch_plugin_impl;
}
class elasticsearch_plugin : public graphene::app::plugin
{
public:
elasticsearch_plugin();
virtual ~elasticsearch_plugin();
std::string plugin_name()const override;
std::string plugin_description()const override;
virtual void plugin_set_program_options(
boost::program_options::options_description& cli,
boost::program_options::options_description& cfg) override;
virtual void plugin_initialize(const boost::program_options::variables_map& options) override;
virtual void plugin_startup() override;
friend class detail::elasticsearch_plugin_impl;
std::unique_ptr<detail::elasticsearch_plugin_impl> my;
};
struct operation_visitor
{
typedef void result_type;
share_type fee_amount;
asset_id_type fee_asset;
asset_id_type transfer_asset_id;
share_type transfer_amount;
account_id_type transfer_from;
account_id_type transfer_to;
void operator()( const graphene::chain::transfer_operation& o )
{
fee_asset = o.fee.asset_id;
fee_amount = o.fee.amount;
transfer_asset_id = o.amount.asset_id;
transfer_amount = o.amount.amount;
transfer_from = o.from;
transfer_to = o.to;
}
object_id_type fill_order_id;
account_id_type fill_account_id;
asset_id_type fill_pays_asset_id;
share_type fill_pays_amount;
asset_id_type fill_receives_asset_id;
share_type fill_receives_amount;
double fill_fill_price;
bool fill_is_maker;
void operator()( const graphene::chain::fill_order_operation& o )
{
fee_asset = o.fee.asset_id;
fee_amount = o.fee.amount;
fill_order_id = o.order_id;
fill_account_id = o.account_id;
fill_pays_asset_id = o.pays.asset_id;
fill_pays_amount = o.pays.amount;
fill_receives_asset_id = o.receives.asset_id;
fill_receives_amount = o.receives.amount;
fill_fill_price = o.fill_price.to_real();
fill_is_maker = o.is_maker;
}
template<typename T>
void operator()( const T& o )
{
fee_asset = o.fee.asset_id;
fee_amount = o.fee.amount;
}
};
struct operation_history_struct {
int trx_in_block;
int op_in_trx;
std::string operation_result;
int virtual_op;
std::string op;
variant op_object;
};
struct block_struct {
int block_num;
fc::time_point_sec block_time;
std::string trx_id;
};
struct fee_struct {
asset_id_type asset;
std::string asset_name;
share_type amount;
double amount_units;
};
struct transfer_struct {
asset_id_type asset;
std::string asset_name;
share_type amount;
double amount_units;
account_id_type from;
account_id_type to;
};
struct fill_struct {
object_id_type order_id;
account_id_type account_id;
asset_id_type pays_asset_id;
std::string pays_asset_name;
share_type pays_amount;
double pays_amount_units;
asset_id_type receives_asset_id;
std::string receives_asset_name;
share_type receives_amount;
double receives_amount_units;
double fill_price;
double fill_price_units;
bool is_maker;
};
struct visitor_struct {
fee_struct fee_data;
transfer_struct transfer_data;
fill_struct fill_data;
};
struct bulk_struct {
account_transaction_history_object account_history;
operation_history_struct operation_history;
int operation_type;
int operation_id_num;
block_struct block_data;
optional<visitor_struct> additional_data;
};
struct adaptor_struct {
variant adapt(const variant_object& op)
{
fc::mutable_variant_object o(op);
vector<string> keys_to_rename;
for (auto i = o.begin(); i != o.end(); ++i)
{
auto& element = (*i).value();
if (element.is_object())
{
const string& name = (*i).key();
auto& vo = element.get_object();
if (vo.contains(name.c_str()))
keys_to_rename.emplace_back(name);
element = adapt(vo);
}
else if (element.is_array())
adapt(element.get_array());
}
for (const auto& i : keys_to_rename)
{
string new_name = i + "_";
o[new_name] = variant(o[i]);
o.erase(i);
}
if (o.find("memo") != o.end())
{
auto& memo = o["memo"];
if (memo.is_string())
{
o["memo_"] = o["memo"];
o.erase("memo");
}
else if (memo.is_object())
{
fc::mutable_variant_object tmp(memo.get_object());
if (tmp.find("nonce") != tmp.end())
{
tmp["nonce"] = tmp["nonce"].as_string();
o["memo"] = tmp;
}
}
}
if (o.find("new_parameters") != o.end())
{
auto& tmp = o["new_parameters"];
if (tmp.is_object())
{
fc::mutable_variant_object tmp2(tmp.get_object());
if (tmp2.find("current_fees") != tmp2.end())
{
tmp2.erase("current_fees");
o["new_parameters"] = tmp2;
}
}
}
if (o.find("owner") != o.end() && o["owner"].is_string())
{
o["owner_"] = o["owner"].as_string();
o.erase("owner");
}
if (o.find("proposed_ops") != o.end())
{
o["proposed_ops"] = fc::json::to_string(o["proposed_ops"]);
}
if (o.find("initializer") != o.end())
{
o["initializer"] = fc::json::to_string(o["initializer"]);
}
if (o.find("policy") != o.end())
{
o["policy"] = fc::json::to_string(o["policy"]);
}
if (o.find("predicates") != o.end())
{
o["predicates"] = fc::json::to_string(o["predicates"]);
}
variant v;
fc::to_variant(o, v, FC_PACK_MAX_DEPTH);
return v;
}
void adapt(fc::variants& v)
{
for (auto& array_element : v)
{
if (array_element.is_object())
array_element = adapt(array_element.get_object());
else if (array_element.is_array())
adapt(array_element.get_array());
else
array_element = array_element.as_string();
}
}
};
} } //graphene::elasticsearch
FC_REFLECT( graphene::elasticsearch::operation_history_struct, (trx_in_block)(op_in_trx)(operation_result)(virtual_op)(op)(op_object) )
FC_REFLECT( graphene::elasticsearch::block_struct, (block_num)(block_time)(trx_id) )
FC_REFLECT( graphene::elasticsearch::fee_struct, (asset)(asset_name)(amount)(amount_units) )
FC_REFLECT( graphene::elasticsearch::transfer_struct, (asset)(asset_name)(amount)(amount_units)(from)(to) )
FC_REFLECT( graphene::elasticsearch::fill_struct, (order_id)(account_id)(pays_asset_id)(pays_asset_name)(pays_amount)(pays_amount_units)
(receives_asset_id)(receives_asset_name)(receives_amount)(receives_amount_units)(fill_price)
(fill_price_units)(is_maker))
FC_REFLECT( graphene::elasticsearch::visitor_struct, (fee_data)(transfer_data)(fill_data) )
FC_REFLECT( graphene::elasticsearch::bulk_struct, (account_history)(operation_history)(operation_type)(operation_id_num)(block_data)(additional_data) )
<commit_msg>add active_special_authority to adaptor<commit_after>/*
* Copyright (c) 2017 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/app/plugin.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/operation_history_object.hpp>
namespace graphene { namespace elasticsearch {
using namespace chain;
//
// Plugins should #define their SPACE_ID's so plugins with
// conflicting SPACE_ID assignments can be compiled into the
// same binary (by simply re-assigning some of the conflicting #defined
// SPACE_ID's in a build script).
//
// Assignment of SPACE_ID's cannot be done at run-time because
// various template automagic depends on them being known at compile
// time.
//
#ifndef ELASTICSEARCH_SPACE_ID
#define ELASTICSEARCH_SPACE_ID 6
#endif
namespace detail
{
class elasticsearch_plugin_impl;
}
class elasticsearch_plugin : public graphene::app::plugin
{
public:
elasticsearch_plugin();
virtual ~elasticsearch_plugin();
std::string plugin_name()const override;
std::string plugin_description()const override;
virtual void plugin_set_program_options(
boost::program_options::options_description& cli,
boost::program_options::options_description& cfg) override;
virtual void plugin_initialize(const boost::program_options::variables_map& options) override;
virtual void plugin_startup() override;
friend class detail::elasticsearch_plugin_impl;
std::unique_ptr<detail::elasticsearch_plugin_impl> my;
};
struct operation_visitor
{
typedef void result_type;
share_type fee_amount;
asset_id_type fee_asset;
asset_id_type transfer_asset_id;
share_type transfer_amount;
account_id_type transfer_from;
account_id_type transfer_to;
void operator()( const graphene::chain::transfer_operation& o )
{
fee_asset = o.fee.asset_id;
fee_amount = o.fee.amount;
transfer_asset_id = o.amount.asset_id;
transfer_amount = o.amount.amount;
transfer_from = o.from;
transfer_to = o.to;
}
object_id_type fill_order_id;
account_id_type fill_account_id;
asset_id_type fill_pays_asset_id;
share_type fill_pays_amount;
asset_id_type fill_receives_asset_id;
share_type fill_receives_amount;
double fill_fill_price;
bool fill_is_maker;
void operator()( const graphene::chain::fill_order_operation& o )
{
fee_asset = o.fee.asset_id;
fee_amount = o.fee.amount;
fill_order_id = o.order_id;
fill_account_id = o.account_id;
fill_pays_asset_id = o.pays.asset_id;
fill_pays_amount = o.pays.amount;
fill_receives_asset_id = o.receives.asset_id;
fill_receives_amount = o.receives.amount;
fill_fill_price = o.fill_price.to_real();
fill_is_maker = o.is_maker;
}
template<typename T>
void operator()( const T& o )
{
fee_asset = o.fee.asset_id;
fee_amount = o.fee.amount;
}
};
struct operation_history_struct {
int trx_in_block;
int op_in_trx;
std::string operation_result;
int virtual_op;
std::string op;
variant op_object;
};
struct block_struct {
int block_num;
fc::time_point_sec block_time;
std::string trx_id;
};
struct fee_struct {
asset_id_type asset;
std::string asset_name;
share_type amount;
double amount_units;
};
struct transfer_struct {
asset_id_type asset;
std::string asset_name;
share_type amount;
double amount_units;
account_id_type from;
account_id_type to;
};
struct fill_struct {
object_id_type order_id;
account_id_type account_id;
asset_id_type pays_asset_id;
std::string pays_asset_name;
share_type pays_amount;
double pays_amount_units;
asset_id_type receives_asset_id;
std::string receives_asset_name;
share_type receives_amount;
double receives_amount_units;
double fill_price;
double fill_price_units;
bool is_maker;
};
struct visitor_struct {
fee_struct fee_data;
transfer_struct transfer_data;
fill_struct fill_data;
};
struct bulk_struct {
account_transaction_history_object account_history;
operation_history_struct operation_history;
int operation_type;
int operation_id_num;
block_struct block_data;
optional<visitor_struct> additional_data;
};
struct adaptor_struct {
variant adapt(const variant_object& op)
{
fc::mutable_variant_object o(op);
vector<string> keys_to_rename;
for (auto i = o.begin(); i != o.end(); ++i)
{
auto& element = (*i).value();
if (element.is_object())
{
const string& name = (*i).key();
auto& vo = element.get_object();
if (vo.contains(name.c_str()))
keys_to_rename.emplace_back(name);
element = adapt(vo);
}
else if (element.is_array())
adapt(element.get_array());
}
for (const auto& i : keys_to_rename)
{
string new_name = i + "_";
o[new_name] = variant(o[i]);
o.erase(i);
}
if (o.find("memo") != o.end())
{
auto& memo = o["memo"];
if (memo.is_string())
{
o["memo_"] = o["memo"];
o.erase("memo");
}
else if (memo.is_object())
{
fc::mutable_variant_object tmp(memo.get_object());
if (tmp.find("nonce") != tmp.end())
{
tmp["nonce"] = tmp["nonce"].as_string();
o["memo"] = tmp;
}
}
}
if (o.find("new_parameters") != o.end())
{
auto& tmp = o["new_parameters"];
if (tmp.is_object())
{
fc::mutable_variant_object tmp2(tmp.get_object());
if (tmp2.find("current_fees") != tmp2.end())
{
tmp2.erase("current_fees");
o["new_parameters"] = tmp2;
}
}
}
if (o.find("owner") != o.end() && o["owner"].is_string())
{
o["owner_"] = o["owner"].as_string();
o.erase("owner");
}
if (o.find("proposed_ops") != o.end())
{
o["proposed_ops"] = fc::json::to_string(o["proposed_ops"]);
}
if (o.find("initializer") != o.end())
{
o["initializer"] = fc::json::to_string(o["initializer"]);
}
if (o.find("policy") != o.end())
{
o["policy"] = fc::json::to_string(o["policy"]);
}
if (o.find("predicates") != o.end())
{
o["predicates"] = fc::json::to_string(o["predicates"]);
}
if (o.find("active_special_authority") != o.end())
{
o["active_special_authority"] = fc::json::to_string(o["active_special_authority"]);
}
variant v;
fc::to_variant(o, v, FC_PACK_MAX_DEPTH);
return v;
}
void adapt(fc::variants& v)
{
for (auto& array_element : v)
{
if (array_element.is_object())
array_element = adapt(array_element.get_object());
else if (array_element.is_array())
adapt(array_element.get_array());
else
array_element = array_element.as_string();
}
}
};
} } //graphene::elasticsearch
FC_REFLECT( graphene::elasticsearch::operation_history_struct, (trx_in_block)(op_in_trx)(operation_result)(virtual_op)(op)(op_object) )
FC_REFLECT( graphene::elasticsearch::block_struct, (block_num)(block_time)(trx_id) )
FC_REFLECT( graphene::elasticsearch::fee_struct, (asset)(asset_name)(amount)(amount_units) )
FC_REFLECT( graphene::elasticsearch::transfer_struct, (asset)(asset_name)(amount)(amount_units)(from)(to) )
FC_REFLECT( graphene::elasticsearch::fill_struct, (order_id)(account_id)(pays_asset_id)(pays_asset_name)(pays_amount)(pays_amount_units)
(receives_asset_id)(receives_asset_name)(receives_amount)(receives_amount_units)(fill_price)
(fill_price_units)(is_maker))
FC_REFLECT( graphene::elasticsearch::visitor_struct, (fee_data)(transfer_data)(fill_data) )
FC_REFLECT( graphene::elasticsearch::bulk_struct, (account_history)(operation_history)(operation_type)(operation_id_num)(block_data)(additional_data) )
<|endoftext|>
|
<commit_before>#include "vlcplugin_win.h"
#include "../common/win32_fullscreen.h"
static HMODULE hDllModule= 0;
HMODULE DllGetModule()
{
return hDllModule;
};
extern "C"
BOOL WINAPI DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved )
{
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
hDllModule = (HMODULE)hModule;
break;
default:
break;
}
return TRUE;
};
static LRESULT CALLBACK Manage( HWND p_hwnd, UINT i_msg, WPARAM wpar, LPARAM lpar )
{
VlcPluginWin *p_plugin = reinterpret_cast<VlcPluginWin *>(GetWindowLongPtr(p_hwnd, GWLP_USERDATA));
switch( i_msg )
{
case WM_ERASEBKGND:
return 1L;
case WM_PAINT:
{
PAINTSTRUCT paintstruct;
HDC hdc;
RECT rect;
hdc = BeginPaint( p_hwnd, &paintstruct );
GetClientRect( p_hwnd, &rect );
FillRect( hdc, &rect, (HBRUSH)GetStockObject(BLACK_BRUSH) );
SetTextColor(hdc, RGB(255, 255, 255));
SetBkColor(hdc, RGB(0, 0, 0));
if( p_plugin->psz_text )
DrawText( hdc, p_plugin->psz_text, strlen(p_plugin->psz_text), &rect,
DT_CENTER|DT_VCENTER|DT_SINGLELINE);
EndPaint( p_hwnd, &paintstruct );
return 0L;
}
case WM_SIZE:{
int new_client_width = LOWORD(lpar);
int new_client_height = HIWORD(lpar);
//first child will be resized to client area
HWND hChildWnd = GetWindow(p_hwnd, GW_CHILD);
if(hChildWnd){
MoveWindow(hChildWnd, 0, 0, new_client_width, new_client_height, FALSE);
}
return 0L;
}
case WM_LBUTTONDBLCLK:{
p_plugin->toggle_fullscreen();
return 0L;
}
default:
/* delegate to default handler */
return CallWindowProc( p_plugin->getWindowProc(), p_hwnd,
i_msg, wpar, lpar );
}
}
VlcPluginWin::VlcPluginWin(NPP instance, NPuint16_t mode) :
VlcPluginBase(instance, mode),
pf_wndproc(NULL),
_WindowsManager(DllGetModule())
{
}
VlcPluginWin::~VlcPluginWin()
{
destroy_windows();
}
void VlcPluginWin::toggle_fullscreen()
{
_WindowsManager.ToggleFullScreen();
}
void VlcPluginWin::set_fullscreen(int yes)
{
if(yes){
_WindowsManager.StartFullScreen();
}
else{
_WindowsManager.EndFullScreen();
}
}
int VlcPluginWin::get_fullscreen()
{
return _WindowsManager.IsFullScreen();
}
void VlcPluginWin::show_toolbar()
{
/* TODO */
}
void VlcPluginWin::hide_toolbar()
{
/* TODO */
}
void VlcPluginWin::update_controls()
{
/* TODO */
}
bool VlcPluginWin::create_windows()
{
HWND drawable = (HWND) (getWindow().window);
/* attach our plugin object */
SetWindowLongPtr(drawable, GWLP_USERDATA,
(LONG_PTR)this);
/* install our WNDPROC */
setWindowProc( (WNDPROC)SetWindowLongPtr( drawable,
GWLP_WNDPROC, (LONG_PTR)Manage ) );
/* change window style to our liking */
LONG style = GetWindowLong(drawable, GWL_STYLE);
style |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
SetWindowLong(drawable, GWL_STYLE, style);
_WindowsManager.CreateWindows(drawable);
return true;
}
bool VlcPluginWin::resize_windows()
{
/* TODO */
HWND drawable = (HWND) (getWindow().window);
/* Redraw window */
InvalidateRect( drawable, NULL, TRUE );
UpdateWindow( drawable );
return true;
}
bool VlcPluginWin::destroy_windows()
{
_WindowsManager.DestroyWindows();
HWND oldwin = (HWND)npwindow.window;
if( oldwin )
{
WNDPROC winproc = getWindowProc();
if( winproc )
{
/* reset WNDPROC */
SetWindowLongPtr( oldwin, GWLP_WNDPROC, (LONG_PTR)winproc );
setWindowProc(NULL);
}
npwindow.window = NULL;
}
return true;
}
void VlcPluginWin::on_media_player_new()
{
_WindowsManager.LibVlcAttach(libvlc_media_player);
}
void VlcPluginWin::on_media_player_release()
{
_WindowsManager.LibVlcDetach();
}
<commit_msg>npapi win32: move holder window resizing to resize_window();<commit_after>#include "vlcplugin_win.h"
#include "../common/win32_fullscreen.h"
static HMODULE hDllModule= 0;
HMODULE DllGetModule()
{
return hDllModule;
};
extern "C"
BOOL WINAPI DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved )
{
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
hDllModule = (HMODULE)hModule;
break;
default:
break;
}
return TRUE;
};
static LRESULT CALLBACK Manage( HWND p_hwnd, UINT i_msg, WPARAM wpar, LPARAM lpar )
{
VlcPluginWin *p_plugin = reinterpret_cast<VlcPluginWin *>(GetWindowLongPtr(p_hwnd, GWLP_USERDATA));
switch( i_msg )
{
case WM_ERASEBKGND:
return 1L;
case WM_PAINT:
{
PAINTSTRUCT paintstruct;
HDC hdc;
RECT rect;
hdc = BeginPaint( p_hwnd, &paintstruct );
GetClientRect( p_hwnd, &rect );
FillRect( hdc, &rect, (HBRUSH)GetStockObject(BLACK_BRUSH) );
SetTextColor(hdc, RGB(255, 255, 255));
SetBkColor(hdc, RGB(0, 0, 0));
if( p_plugin->psz_text )
DrawText( hdc, p_plugin->psz_text, strlen(p_plugin->psz_text), &rect,
DT_CENTER|DT_VCENTER|DT_SINGLELINE);
EndPaint( p_hwnd, &paintstruct );
return 0L;
}
case WM_LBUTTONDBLCLK:{
p_plugin->toggle_fullscreen();
return 0L;
}
default:
/* delegate to default handler */
return CallWindowProc( p_plugin->getWindowProc(), p_hwnd,
i_msg, wpar, lpar );
}
}
VlcPluginWin::VlcPluginWin(NPP instance, NPuint16_t mode) :
VlcPluginBase(instance, mode),
pf_wndproc(NULL),
_WindowsManager(DllGetModule())
{
}
VlcPluginWin::~VlcPluginWin()
{
destroy_windows();
}
void VlcPluginWin::toggle_fullscreen()
{
_WindowsManager.ToggleFullScreen();
}
void VlcPluginWin::set_fullscreen(int yes)
{
if(yes){
_WindowsManager.StartFullScreen();
}
else{
_WindowsManager.EndFullScreen();
}
}
int VlcPluginWin::get_fullscreen()
{
return _WindowsManager.IsFullScreen();
}
void VlcPluginWin::show_toolbar()
{
/* TODO */
}
void VlcPluginWin::hide_toolbar()
{
/* TODO */
}
void VlcPluginWin::update_controls()
{
/* TODO */
}
bool VlcPluginWin::create_windows()
{
HWND drawable = (HWND) (getWindow().window);
/* attach our plugin object */
SetWindowLongPtr(drawable, GWLP_USERDATA,
(LONG_PTR)this);
/* install our WNDPROC */
setWindowProc( (WNDPROC)SetWindowLongPtr( drawable,
GWLP_WNDPROC, (LONG_PTR)Manage ) );
/* change window style to our liking */
LONG style = GetWindowLong(drawable, GWL_STYLE);
style |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
SetWindowLong(drawable, GWL_STYLE, style);
_WindowsManager.CreateWindows(drawable);
return true;
}
bool VlcPluginWin::resize_windows()
{
HWND drawable = (HWND) (getWindow().window);
RECT rect;
GetClientRect(drawable, &rect);
if(!_WindowsManager.IsFullScreen() && _WindowsManager.getHolderWnd()){
HWND hHolderWnd = _WindowsManager.getHolderWnd()->getHWND();
MoveWindow(hHolderWnd, 0, 0, rect.right - rect.left, rect.bottom - rect.top, TRUE);
}
return true;
}
bool VlcPluginWin::destroy_windows()
{
_WindowsManager.DestroyWindows();
HWND oldwin = (HWND)npwindow.window;
if( oldwin )
{
WNDPROC winproc = getWindowProc();
if( winproc )
{
/* reset WNDPROC */
SetWindowLongPtr( oldwin, GWLP_WNDPROC, (LONG_PTR)winproc );
setWindowProc(NULL);
}
npwindow.window = NULL;
}
return true;
}
void VlcPluginWin::on_media_player_new()
{
_WindowsManager.LibVlcAttach(libvlc_media_player);
}
void VlcPluginWin::on_media_player_release()
{
_WindowsManager.LibVlcDetach();
}
<|endoftext|>
|
<commit_before>#include "interpreter.h"
#include <QtCore/QCoreApplication>
#include <QtWidgets/QAction>
#include <QtCore/QDebug>
#include <qrtext/languageToolboxInterface.h>
#include <utils/timelineInterface.h>
#include <utils/tracer.h>
#include <interpreterBase/robotModel/robotModelInterface.h>
using namespace qReal;
using namespace interpreterCore::interpreter;
using namespace interpreterBase::robotModel;
int const maxThreadsCount = 100;
Interpreter::Interpreter(GraphicalModelAssistInterface const &graphicalModelApi
, LogicalModelAssistInterface &logicalModelApi
, qReal::gui::MainWindowInterpretersInterface &interpretersInterface
, qReal::ProjectManagementInterface const &projectManager
, BlocksFactoryManagerInterface &blocksFactoryManager
, interpreterBase::robotModel::RobotModelManagerInterface const &robotModelManager
, qrtext::LanguageToolboxInterface &languageToolbox
, QAction &connectToRobotAction
)
: mGraphicalModelApi(graphicalModelApi)
, mLogicalModelApi(logicalModelApi)
, mInterpretersInterface(interpretersInterface)
, mState(idle)
, mRobotModelManager(robotModelManager)
, mBlocksTable(new details::BlocksTable(blocksFactoryManager, robotModelManager))
, mActionConnectToRobot(connectToRobotAction)
, mSensorVariablesUpdater(robotModelManager, languageToolbox)
, mAutoconfigurer(mGraphicalModelApi, *mBlocksTable, *mInterpretersInterface.errorReporter())
, mLanguageToolbox(languageToolbox)
{
connect(
&mRobotModelManager
, &interpreterBase::robotModel::RobotModelManagerInterface::allDevicesConfigured
, this
, &Interpreter::devicesConfiguredSlot
);
connect(
&mRobotModelManager
, &interpreterBase::robotModel::RobotModelManagerInterface::connected
, this
, &Interpreter::connectedSlot
);
connect(&projectManager, &qReal::ProjectManagementInterface::beforeOpen, this, &Interpreter::stopRobot);
connectDevicesConfigurationProvider(&mAutoconfigurer);
}
Interpreter::~Interpreter()
{
qDeleteAll(mThreads);
delete mBlocksTable;
}
void Interpreter::interpret()
{
mInterpretersInterface.errorReporter()->clear();
if (mRobotModelManager.model().connectionState() != RobotModelInterface::connectedState) {
mInterpretersInterface.errorReporter()->addInformation(tr("No connection to robot"));
return;
}
if (mState != idle) {
mInterpretersInterface.errorReporter()->addInformation(tr("Interpreter is already running"));
return;
}
mBlocksTable->clear();
mState = waitingForDevicesConfiguredToLaunch;
if (!mAutoconfigurer.configure(mGraphicalModelApi.children(Id::rootId()), mRobotModelManager.model().name())) {
return;
}
mLanguageToolbox.clear();
/// @todo Temporarily loading initial configuration from a network of SensorConfigurationProviders.
/// To be done more adequately.
for (PortInfo const &port : mRobotModelManager.model().configurablePorts()) {
QString const modelName = mRobotModelManager.model().name();
DeviceInfo const deviceInfo = currentConfiguration(modelName, port);
mRobotModelManager.model().configureDevice(port, deviceInfo);
}
mRobotModelManager.model().applyConfiguration();
}
void Interpreter::stopRobot()
{
mSensorVariablesUpdater.suspend();
mRobotModelManager.model().stopRobot();
mState = idle;
qDeleteAll(mThreads);
mThreads.clear();
mBlocksTable->setFailure();
emit stopped();
}
int Interpreter::timeElapsed() const
{
return mState == interpreting
? mRobotModelManager.model().timeline().timestamp() - mInterpretationStartedTimestamp
: 0;
}
void Interpreter::connectedSlot(bool success)
{
qDebug() << "Interpreter::connectedSlot";
if (success) {
if (mRobotModelManager.model().needsConnection()) {
mInterpretersInterface.errorReporter()->addInformation(tr("Connected successfully"));
}
} else {
utils::Tracer::debug(utils::Tracer::initialization, "Interpreter::connectedSlot"
, "Robot connection status: " + QString::number(success));
mInterpretersInterface.errorReporter()->addError(tr("Can't connect to a robot."));
}
mActionConnectToRobot.setChecked(success);
}
void Interpreter::devicesConfiguredSlot()
{
utils::Tracer::debug(utils::Tracer::initialization
, "Interpreter::devicesConfiguredSlot", "Sensors are configured");
if (mRobotModelManager.model().connectionState() != RobotModelInterface::connectedState) {
mInterpretersInterface.errorReporter()->addInformation(tr("No connection to robot"));
mState = idle;
return;
}
if (mState == waitingForDevicesConfiguredToLaunch) {
mState = interpreting;
mInterpretationStartedTimestamp = mRobotModelManager.model().timeline().timestamp();
mSensorVariablesUpdater.run();
utils::Tracer::debug(utils::Tracer::initialization
, "Interpreter::devicesConfiguredSlot", "Starting interpretation");
Id const ¤tDiagramId = mInterpretersInterface.activeDiagram();
details::Thread * const initialThread = new details::Thread(&mGraphicalModelApi
, mInterpretersInterface, currentDiagramId, *mBlocksTable);
emit started();
addThread(initialThread);
}
}
void Interpreter::threadStopped()
{
details::Thread * const thread = static_cast<details::Thread *>(sender());
mThreads.removeAll(thread);
delete thread;
if (mThreads.isEmpty()) {
stopRobot();
}
}
void Interpreter::newThread(Id const &startBlockId)
{
details::Thread * const thread = new details::Thread(&mGraphicalModelApi
, mInterpretersInterface, *mBlocksTable, startBlockId);
addThread(thread);
}
void Interpreter::addThread(details::Thread * const thread)
{
if (mThreads.count() >= maxThreadsCount) {
reportError(tr("Threads limit exceeded. Maximum threads count is %1").arg(maxThreadsCount));
stopRobot();
}
mThreads.append(thread);
connect(thread, SIGNAL(stopped()), this, SLOT(threadStopped()));
connect(thread, &details::Thread::newThread, this, &Interpreter::newThread);
QCoreApplication::processEvents();
if (mState != idle) {
thread->interpret();
}
}
void Interpreter::connectToRobot()
{
if (mState == interpreting) {
return;
}
if (mRobotModelManager.model().connectionState() == RobotModelInterface::connectedState) {
mRobotModelManager.model().stopRobot();
mRobotModelManager.model().disconnectFromRobot();
} else {
mRobotModelManager.model().connectToRobot();
}
mActionConnectToRobot.setChecked(
mRobotModelManager.model().connectionState() == RobotModelInterface::connectedState);
}
void Interpreter::disconnectSlot()
{
mActionConnectToRobot.setChecked(false);
stopRobot();
}
void Interpreter::reportError(QString const &message)
{
mInterpretersInterface.errorReporter()->addError(message);
}
<commit_msg>stop robot before interpretation<commit_after>#include "interpreter.h"
#include <QtCore/QCoreApplication>
#include <QtWidgets/QAction>
#include <QtCore/QDebug>
#include <qrtext/languageToolboxInterface.h>
#include <utils/timelineInterface.h>
#include <utils/tracer.h>
#include <interpreterBase/robotModel/robotModelInterface.h>
using namespace qReal;
using namespace interpreterCore::interpreter;
using namespace interpreterBase::robotModel;
int const maxThreadsCount = 100;
Interpreter::Interpreter(GraphicalModelAssistInterface const &graphicalModelApi
, LogicalModelAssistInterface &logicalModelApi
, qReal::gui::MainWindowInterpretersInterface &interpretersInterface
, qReal::ProjectManagementInterface const &projectManager
, BlocksFactoryManagerInterface &blocksFactoryManager
, interpreterBase::robotModel::RobotModelManagerInterface const &robotModelManager
, qrtext::LanguageToolboxInterface &languageToolbox
, QAction &connectToRobotAction
)
: mGraphicalModelApi(graphicalModelApi)
, mLogicalModelApi(logicalModelApi)
, mInterpretersInterface(interpretersInterface)
, mState(idle)
, mRobotModelManager(robotModelManager)
, mBlocksTable(new details::BlocksTable(blocksFactoryManager, robotModelManager))
, mActionConnectToRobot(connectToRobotAction)
, mSensorVariablesUpdater(robotModelManager, languageToolbox)
, mAutoconfigurer(mGraphicalModelApi, *mBlocksTable, *mInterpretersInterface.errorReporter())
, mLanguageToolbox(languageToolbox)
{
connect(
&mRobotModelManager
, &interpreterBase::robotModel::RobotModelManagerInterface::allDevicesConfigured
, this
, &Interpreter::devicesConfiguredSlot
);
connect(
&mRobotModelManager
, &interpreterBase::robotModel::RobotModelManagerInterface::connected
, this
, &Interpreter::connectedSlot
);
connect(&projectManager, &qReal::ProjectManagementInterface::beforeOpen, this, &Interpreter::stopRobot);
connectDevicesConfigurationProvider(&mAutoconfigurer);
}
Interpreter::~Interpreter()
{
qDeleteAll(mThreads);
delete mBlocksTable;
}
void Interpreter::interpret()
{
mInterpretersInterface.errorReporter()->clear();
if (mRobotModelManager.model().connectionState() != RobotModelInterface::connectedState) {
mInterpretersInterface.errorReporter()->addInformation(tr("No connection to robot"));
return;
}
if (mState != idle) {
mInterpretersInterface.errorReporter()->addInformation(tr("Interpreter is already running"));
return;
}
mRobotModelManager.model().stopRobot();
mBlocksTable->clear();
mState = waitingForDevicesConfiguredToLaunch;
if (!mAutoconfigurer.configure(mGraphicalModelApi.children(Id::rootId()), mRobotModelManager.model().name())) {
return;
}
mLanguageToolbox.clear();
/// @todo Temporarily loading initial configuration from a network of SensorConfigurationProviders.
/// To be done more adequately.
for (PortInfo const &port : mRobotModelManager.model().configurablePorts()) {
QString const modelName = mRobotModelManager.model().name();
DeviceInfo const deviceInfo = currentConfiguration(modelName, port);
mRobotModelManager.model().configureDevice(port, deviceInfo);
}
mRobotModelManager.model().applyConfiguration();
}
void Interpreter::stopRobot()
{
mSensorVariablesUpdater.suspend();
mRobotModelManager.model().stopRobot();
mState = idle;
qDeleteAll(mThreads);
mThreads.clear();
mBlocksTable->setFailure();
emit stopped();
}
int Interpreter::timeElapsed() const
{
return mState == interpreting
? mRobotModelManager.model().timeline().timestamp() - mInterpretationStartedTimestamp
: 0;
}
void Interpreter::connectedSlot(bool success)
{
qDebug() << "Interpreter::connectedSlot";
if (success) {
if (mRobotModelManager.model().needsConnection()) {
mInterpretersInterface.errorReporter()->addInformation(tr("Connected successfully"));
}
} else {
utils::Tracer::debug(utils::Tracer::initialization, "Interpreter::connectedSlot"
, "Robot connection status: " + QString::number(success));
mInterpretersInterface.errorReporter()->addError(tr("Can't connect to a robot."));
}
mActionConnectToRobot.setChecked(success);
}
void Interpreter::devicesConfiguredSlot()
{
utils::Tracer::debug(utils::Tracer::initialization
, "Interpreter::devicesConfiguredSlot", "Sensors are configured");
if (mRobotModelManager.model().connectionState() != RobotModelInterface::connectedState) {
mInterpretersInterface.errorReporter()->addInformation(tr("No connection to robot"));
mState = idle;
return;
}
if (mState == waitingForDevicesConfiguredToLaunch) {
mState = interpreting;
mInterpretationStartedTimestamp = mRobotModelManager.model().timeline().timestamp();
mSensorVariablesUpdater.run();
utils::Tracer::debug(utils::Tracer::initialization
, "Interpreter::devicesConfiguredSlot", "Starting interpretation");
Id const ¤tDiagramId = mInterpretersInterface.activeDiagram();
details::Thread * const initialThread = new details::Thread(&mGraphicalModelApi
, mInterpretersInterface, currentDiagramId, *mBlocksTable);
emit started();
addThread(initialThread);
}
}
void Interpreter::threadStopped()
{
details::Thread * const thread = static_cast<details::Thread *>(sender());
mThreads.removeAll(thread);
delete thread;
if (mThreads.isEmpty()) {
stopRobot();
}
}
void Interpreter::newThread(Id const &startBlockId)
{
details::Thread * const thread = new details::Thread(&mGraphicalModelApi
, mInterpretersInterface, *mBlocksTable, startBlockId);
addThread(thread);
}
void Interpreter::addThread(details::Thread * const thread)
{
if (mThreads.count() >= maxThreadsCount) {
reportError(tr("Threads limit exceeded. Maximum threads count is %1").arg(maxThreadsCount));
stopRobot();
}
mThreads.append(thread);
connect(thread, SIGNAL(stopped()), this, SLOT(threadStopped()));
connect(thread, &details::Thread::newThread, this, &Interpreter::newThread);
QCoreApplication::processEvents();
if (mState != idle) {
thread->interpret();
}
}
void Interpreter::connectToRobot()
{
if (mState == interpreting) {
return;
}
if (mRobotModelManager.model().connectionState() == RobotModelInterface::connectedState) {
mRobotModelManager.model().stopRobot();
mRobotModelManager.model().disconnectFromRobot();
} else {
mRobotModelManager.model().connectToRobot();
}
mActionConnectToRobot.setChecked(
mRobotModelManager.model().connectionState() == RobotModelInterface::connectedState);
}
void Interpreter::disconnectSlot()
{
mActionConnectToRobot.setChecked(false);
stopRobot();
}
void Interpreter::reportError(QString const &message)
{
mInterpretersInterface.errorReporter()->addError(message);
}
<|endoftext|>
|
<commit_before>//===- PDB.cpp ------------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "PDB.h"
#include "Chunks.h"
#include "Config.h"
#include "Error.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
#include "llvm/DebugInfo/CodeView/SymbolDumper.h"
#include "llvm/DebugInfo/CodeView/TypeDatabase.h"
#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
#include "llvm/DebugInfo/MSF/MSFBuilder.h"
#include "llvm/DebugInfo/MSF/MSFCommon.h"
#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBTypeServerHandler.h"
#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/BinaryByteStream.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
#include <memory>
using namespace lld;
using namespace lld::coff;
using namespace llvm;
using namespace llvm::codeview;
using namespace llvm::support;
using namespace llvm::support::endian;
using llvm::object::coff_section;
static ExitOnError ExitOnErr;
// Returns a list of all SectionChunks.
static std::vector<coff_section> getInputSections(SymbolTable *Symtab) {
std::vector<coff_section> V;
for (Chunk *C : Symtab->getChunks())
if (auto *SC = dyn_cast<SectionChunk>(C))
V.push_back(*SC->Header);
return V;
}
static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
StringRef Name) {
for (SectionChunk *C : Sections)
if (C->getSectionName() == Name)
return C;
return nullptr;
}
static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) {
SectionChunk *Sec = findByName(File->getDebugChunks(), SecName);
if (!Sec)
return {};
// First 4 bytes are section magic.
ArrayRef<uint8_t> Data = Sec->getContents();
if (Data.size() < 4)
fatal(SecName + " too short");
if (read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
fatal(SecName + " has an invalid magic");
return Data.slice(4);
}
static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
codeview::TypeTableBuilder &TypeTable) {
// Start the TPI or IPI stream header.
TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
// Flatten the in memory type table.
TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
// FIXME: Hash types.
TpiBuilder.addTypeRecord(Rec, None);
});
}
// Merge .debug$T sections into IpiData and TpiData.
static void mergeDebugT(SymbolTable *Symtab, pdb::PDBFileBuilder &Builder,
codeview::TypeTableBuilder &TypeTable,
codeview::TypeTableBuilder &IDTable) {
// Visit all .debug$T sections to add them to Builder.
for (ObjectFile *File : Symtab->ObjectFiles) {
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
if (Data.empty())
continue;
BinaryByteStream Stream(Data, support::little);
codeview::CVTypeArray Types;
BinaryStreamReader Reader(Stream);
SmallVector<TypeIndex, 128> SourceToDest;
// Follow type servers. If the same type server is encountered more than
// once for this instance of `PDBTypeServerHandler` (for example if many
// object files reference the same TypeServer), the types from the
// TypeServer will only be visited once.
pdb::PDBTypeServerHandler Handler;
Handler.addSearchPath(llvm::sys::path::parent_path(File->getName()));
if (auto EC = Reader.readArray(Types, Reader.getLength()))
fatal(EC, "Reader::readArray failed");
if (auto Err = codeview::mergeTypeStreams(IDTable, TypeTable, SourceToDest,
&Handler, Types))
fatal(Err, "codeview::mergeTypeStreams failed");
}
// Construct TPI stream contents.
addTypeInfo(Builder.getTpiBuilder(), TypeTable);
// Construct IPI stream contents.
addTypeInfo(Builder.getIpiBuilder(), IDTable);
}
static void dumpDebugT(ScopedPrinter &W, ObjectFile *File) {
ListScope LS(W, "DebugT");
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
if (Data.empty())
return;
LazyRandomTypeCollection Types(Data, 100);
TypeDumpVisitor TDV(Types, &W, false);
// Use a default implementation that does not follow type servers and instead
// just dumps the contents of the TypeServer2 record.
if (auto EC = codeview::visitTypeStream(Types, TDV))
fatal(EC, "CVTypeDumper::dump failed");
}
static void dumpDebugS(ScopedPrinter &W, ObjectFile *File) {
ListScope LS(W, "DebugS");
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$S");
if (Data.empty())
return;
BinaryByteStream Stream(Data, llvm::support::little);
CVSymbolArray Symbols;
BinaryStreamReader Reader(Stream);
if (auto EC = Reader.readArray(Symbols, Reader.getLength()))
fatal(EC, "StreamReader.readArray<CVSymbolArray> failed");
TypeDatabase TDB(0);
CVSymbolDumper SymbolDumper(W, TDB, nullptr, false);
if (auto EC = SymbolDumper.dump(Symbols))
fatal(EC, "CVSymbolDumper::dump failed");
}
// Dump CodeView debug info. This is for debugging.
static void dumpCodeView(SymbolTable *Symtab) {
ScopedPrinter W(outs());
for (ObjectFile *File : Symtab->ObjectFiles) {
dumpDebugT(W, File);
dumpDebugS(W, File);
}
}
// Creates a PDB file.
void coff::createPDB(StringRef Path, SymbolTable *Symtab,
ArrayRef<uint8_t> SectionTable,
const llvm::codeview::DebugInfo *DI) {
if (Config->DumpPdb)
dumpCodeView(Symtab);
BumpPtrAllocator Alloc;
pdb::PDBFileBuilder Builder(Alloc);
ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
// Create streams in MSF for predefined streams, namely
// PDB, TPI, DBI and IPI.
for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
ExitOnErr(Builder.getMsfBuilder().addStream(0));
// Add an Info stream.
auto &InfoBuilder = Builder.getInfoBuilder();
InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
pdb::PDB_UniqueId uuid{};
if (DI)
memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
InfoBuilder.setGuid(uuid);
// Should be the current time, but set 0 for reproducibilty.
InfoBuilder.setSignature(0);
InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
// Add an empty DPI stream.
auto &DbiBuilder = Builder.getDbiBuilder();
DbiBuilder.setVersionHeader(pdb::PdbDbiV110);
codeview::TypeTableBuilder TypeTable(BAlloc);
codeview::TypeTableBuilder IDTable(BAlloc);
mergeDebugT(Symtab, Builder, TypeTable, IDTable);
// Add Section Contributions.
std::vector<pdb::SectionContrib> Contribs =
pdb::DbiStreamBuilder::createSectionContribs(getInputSections(Symtab));
DbiBuilder.setSectionContribs(Contribs);
// Add Section Map stream.
ArrayRef<object::coff_section> Sections = {
(const object::coff_section *)SectionTable.data(),
SectionTable.size() / sizeof(object::coff_section)};
std::vector<pdb::SecMapEntry> SectionMap =
pdb::DbiStreamBuilder::createSectionMap(Sections);
DbiBuilder.setSectionMap(SectionMap);
ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
// Add COFF section header stream.
ExitOnErr(
DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
// Write to a file.
ExitOnErr(Builder.commit(Path));
}
<commit_msg>Implement various flavors of type merging.<commit_after>//===- PDB.cpp ------------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "PDB.h"
#include "Chunks.h"
#include "Config.h"
#include "Error.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
#include "llvm/DebugInfo/CodeView/SymbolDumper.h"
#include "llvm/DebugInfo/CodeView/TypeDatabase.h"
#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
#include "llvm/DebugInfo/MSF/MSFBuilder.h"
#include "llvm/DebugInfo/MSF/MSFCommon.h"
#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBTypeServerHandler.h"
#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/BinaryByteStream.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
#include <memory>
using namespace lld;
using namespace lld::coff;
using namespace llvm;
using namespace llvm::codeview;
using namespace llvm::support;
using namespace llvm::support::endian;
using llvm::object::coff_section;
static ExitOnError ExitOnErr;
// Returns a list of all SectionChunks.
static std::vector<coff_section> getInputSections(SymbolTable *Symtab) {
std::vector<coff_section> V;
for (Chunk *C : Symtab->getChunks())
if (auto *SC = dyn_cast<SectionChunk>(C))
V.push_back(*SC->Header);
return V;
}
static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
StringRef Name) {
for (SectionChunk *C : Sections)
if (C->getSectionName() == Name)
return C;
return nullptr;
}
static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) {
SectionChunk *Sec = findByName(File->getDebugChunks(), SecName);
if (!Sec)
return {};
// First 4 bytes are section magic.
ArrayRef<uint8_t> Data = Sec->getContents();
if (Data.size() < 4)
fatal(SecName + " too short");
if (read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
fatal(SecName + " has an invalid magic");
return Data.slice(4);
}
static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
codeview::TypeTableBuilder &TypeTable) {
// Start the TPI or IPI stream header.
TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
// Flatten the in memory type table.
TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
// FIXME: Hash types.
TpiBuilder.addTypeRecord(Rec, None);
});
}
// Merge .debug$T sections into IpiData and TpiData.
static void mergeDebugT(SymbolTable *Symtab, pdb::PDBFileBuilder &Builder,
codeview::TypeTableBuilder &TypeTable,
codeview::TypeTableBuilder &IDTable) {
// Visit all .debug$T sections to add them to Builder.
for (ObjectFile *File : Symtab->ObjectFiles) {
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
if (Data.empty())
continue;
BinaryByteStream Stream(Data, support::little);
codeview::CVTypeArray Types;
BinaryStreamReader Reader(Stream);
SmallVector<TypeIndex, 128> SourceToDest;
// Follow type servers. If the same type server is encountered more than
// once for this instance of `PDBTypeServerHandler` (for example if many
// object files reference the same TypeServer), the types from the
// TypeServer will only be visited once.
pdb::PDBTypeServerHandler Handler;
Handler.addSearchPath(llvm::sys::path::parent_path(File->getName()));
if (auto EC = Reader.readArray(Types, Reader.getLength()))
fatal(EC, "Reader::readArray failed");
codeview::LazyRandomTypeCollection TypesAndIds(Types, 100);
if (auto Err = codeview::mergeTypeAndIdRecords(
IDTable, TypeTable, SourceToDest, &Handler, TypesAndIds))
fatal(Err, "codeview::mergeTypeStreams failed");
}
// Construct TPI stream contents.
addTypeInfo(Builder.getTpiBuilder(), TypeTable);
// Construct IPI stream contents.
addTypeInfo(Builder.getIpiBuilder(), IDTable);
}
static void dumpDebugT(ScopedPrinter &W, ObjectFile *File) {
ListScope LS(W, "DebugT");
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
if (Data.empty())
return;
LazyRandomTypeCollection Types(Data, 100);
TypeDumpVisitor TDV(Types, &W, false);
// Use a default implementation that does not follow type servers and instead
// just dumps the contents of the TypeServer2 record.
if (auto EC = codeview::visitTypeStream(Types, TDV))
fatal(EC, "CVTypeDumper::dump failed");
}
static void dumpDebugS(ScopedPrinter &W, ObjectFile *File) {
ListScope LS(W, "DebugS");
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$S");
if (Data.empty())
return;
BinaryByteStream Stream(Data, llvm::support::little);
CVSymbolArray Symbols;
BinaryStreamReader Reader(Stream);
if (auto EC = Reader.readArray(Symbols, Reader.getLength()))
fatal(EC, "StreamReader.readArray<CVSymbolArray> failed");
TypeDatabase TDB(0);
CVSymbolDumper SymbolDumper(W, TDB, nullptr, false);
if (auto EC = SymbolDumper.dump(Symbols))
fatal(EC, "CVSymbolDumper::dump failed");
}
// Dump CodeView debug info. This is for debugging.
static void dumpCodeView(SymbolTable *Symtab) {
ScopedPrinter W(outs());
for (ObjectFile *File : Symtab->ObjectFiles) {
dumpDebugT(W, File);
dumpDebugS(W, File);
}
}
// Creates a PDB file.
void coff::createPDB(StringRef Path, SymbolTable *Symtab,
ArrayRef<uint8_t> SectionTable,
const llvm::codeview::DebugInfo *DI) {
if (Config->DumpPdb)
dumpCodeView(Symtab);
BumpPtrAllocator Alloc;
pdb::PDBFileBuilder Builder(Alloc);
ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
// Create streams in MSF for predefined streams, namely
// PDB, TPI, DBI and IPI.
for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
ExitOnErr(Builder.getMsfBuilder().addStream(0));
// Add an Info stream.
auto &InfoBuilder = Builder.getInfoBuilder();
InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
pdb::PDB_UniqueId uuid{};
if (DI)
memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
InfoBuilder.setGuid(uuid);
// Should be the current time, but set 0 for reproducibilty.
InfoBuilder.setSignature(0);
InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
// Add an empty DPI stream.
auto &DbiBuilder = Builder.getDbiBuilder();
DbiBuilder.setVersionHeader(pdb::PdbDbiV110);
codeview::TypeTableBuilder TypeTable(BAlloc);
codeview::TypeTableBuilder IDTable(BAlloc);
mergeDebugT(Symtab, Builder, TypeTable, IDTable);
// Add Section Contributions.
std::vector<pdb::SectionContrib> Contribs =
pdb::DbiStreamBuilder::createSectionContribs(getInputSections(Symtab));
DbiBuilder.setSectionContribs(Contribs);
// Add Section Map stream.
ArrayRef<object::coff_section> Sections = {
(const object::coff_section *)SectionTable.data(),
SectionTable.size() / sizeof(object::coff_section)};
std::vector<pdb::SecMapEntry> SectionMap =
pdb::DbiStreamBuilder::createSectionMap(Sections);
DbiBuilder.setSectionMap(SectionMap);
ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
// Add COFF section header stream.
ExitOnErr(
DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
// Write to a file.
ExitOnErr(Builder.commit(Path));
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtMediaServices module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmediapluginloader_p.h"
#include <QtCore/qcoreapplication.h>
#include <QtCore/qpluginloader.h>
#include <QtCore/qdir.h>
#include <QtCore/qdebug.h>
#include <QtMediaServices/qmediaserviceproviderplugin.h>
QT_BEGIN_NAMESPACE
typedef QMap<QString,QObjectList> ObjectListMap;
Q_GLOBAL_STATIC(ObjectListMap, staticMediaPlugins);
QMediaPluginLoader::QMediaPluginLoader(const char *iid, const QString &location, Qt::CaseSensitivity):
m_iid(iid)
{
m_location = location + QLatin1String("/");
load();
}
QStringList QMediaPluginLoader::keys() const
{
return m_instances.keys();
}
QObject* QMediaPluginLoader::instance(QString const &key)
{
return m_instances.value(key);
}
QList<QObject*> QMediaPluginLoader::instances(QString const &key)
{
return m_instances.values(key);
}
//to be used for testing purposes only
void QMediaPluginLoader::setStaticPlugins(const QString &location, const QObjectList& objects)
{
staticMediaPlugins()->insert(location + QLatin1String("/"), objects);
}
void QMediaPluginLoader::load()
{
if (!m_instances.isEmpty())
return;
if (staticMediaPlugins() && staticMediaPlugins()->contains(m_location)) {
foreach(QObject *o, staticMediaPlugins()->value(m_location)) {
if (o != 0 && o->qt_metacast(m_iid) != 0) {
QFactoryInterface* p = qobject_cast<QFactoryInterface*>(o);
if (p != 0) {
foreach (QString const &key, p->keys())
m_instances.insertMulti(key, o);
}
}
}
} else {
#ifndef QT_NO_LIBRARY
QStringList paths = QCoreApplication::libraryPaths();
foreach (QString const &path, paths) {
QString pluginPathName(path + m_location);
QDir pluginDir(pluginPathName);
if (!pluginDir.exists())
continue;
foreach (QString pluginLib, pluginDir.entryList(QDir::Files)) {
QPluginLoader loader(pluginPathName + pluginLib);
QObject *o = loader.instance();
if (o != 0 && o->qt_metacast(m_iid) != 0) {
QFactoryInterface* p = qobject_cast<QFactoryInterface*>(o);
if (p != 0) {
foreach (QString const &key, p->keys())
m_instances.insertMulti(key, o);
}
continue;
} else {
qWarning() << "QMediaPluginLoader: Failed to load plugin: " << pluginLib << loader.errorString();
}
delete o;
loader.unload();
}
}
#endif
}
}
QT_END_NAMESPACE
<commit_msg>MediaServices; Don't look at the debug info when looking for plugins.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtMediaServices module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmediapluginloader_p.h"
#include <QtCore/qcoreapplication.h>
#include <QtCore/qpluginloader.h>
#include <QtCore/qdir.h>
#include <QtCore/qdebug.h>
#include <QtMediaServices/qmediaserviceproviderplugin.h>
QT_BEGIN_NAMESPACE
typedef QMap<QString,QObjectList> ObjectListMap;
Q_GLOBAL_STATIC(ObjectListMap, staticMediaPlugins);
QMediaPluginLoader::QMediaPluginLoader(const char *iid, const QString &location, Qt::CaseSensitivity):
m_iid(iid)
{
m_location = location + QLatin1String("/");
load();
}
QStringList QMediaPluginLoader::keys() const
{
return m_instances.keys();
}
QObject* QMediaPluginLoader::instance(QString const &key)
{
return m_instances.value(key);
}
QList<QObject*> QMediaPluginLoader::instances(QString const &key)
{
return m_instances.values(key);
}
//to be used for testing purposes only
void QMediaPluginLoader::setStaticPlugins(const QString &location, const QObjectList& objects)
{
staticMediaPlugins()->insert(location + QLatin1String("/"), objects);
}
void QMediaPluginLoader::load()
{
if (!m_instances.isEmpty())
return;
if (staticMediaPlugins() && staticMediaPlugins()->contains(m_location)) {
foreach(QObject *o, staticMediaPlugins()->value(m_location)) {
if (o != 0 && o->qt_metacast(m_iid) != 0) {
QFactoryInterface* p = qobject_cast<QFactoryInterface*>(o);
if (p != 0) {
foreach (QString const &key, p->keys())
m_instances.insertMulti(key, o);
}
}
}
} else {
#ifndef QT_NO_LIBRARY
QStringList paths = QCoreApplication::libraryPaths();
foreach (QString const &path, paths) {
QString pluginPathName(path + m_location);
QDir pluginDir(pluginPathName);
if (!pluginDir.exists())
continue;
foreach (const QString &pluginLib, pluginDir.entryList(QDir::Files)) {
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
if (pluginLib.endsWith(QLatin1String(".debug")))
continue;
#endif
QPluginLoader loader(pluginPathName + pluginLib);
QObject *o = loader.instance();
if (o != 0 && o->qt_metacast(m_iid) != 0) {
QFactoryInterface* p = qobject_cast<QFactoryInterface*>(o);
if (p != 0) {
foreach (QString const &key, p->keys())
m_instances.insertMulti(key, o);
}
continue;
} else {
qWarning() << "QMediaPluginLoader: Failed to load plugin: " << pluginLib << loader.errorString();
}
delete o;
loader.unload();
}
}
#endif
}
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "remotelinuxruncontrolfactory.h"
#include "remotelinuxdebugsupport.h"
#include "remotelinuxrunconfiguration.h"
#include "remotelinuxruncontrol.h"
#include <debugger/debuggerconstants.h>
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerrunner.h>
#include <debugger/debuggerstartparameters.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/portlist.h>
using namespace Debugger;
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace Internal {
RemoteLinuxRunControlFactory::RemoteLinuxRunControlFactory(QObject *parent)
: IRunControlFactory(parent)
{
}
RemoteLinuxRunControlFactory::~RemoteLinuxRunControlFactory()
{
}
bool RemoteLinuxRunControlFactory::canRun(RunConfiguration *runConfiguration, RunMode mode) const
{
if (mode != NormalRunMode && mode != DebugRunMode)
return false;
const QString idStr = QString::fromLatin1(runConfiguration->id().name());
if (!runConfiguration->isEnabled()
|| !idStr.startsWith(RemoteLinuxRunConfiguration::Id)) {
return false;
}
const RemoteLinuxRunConfiguration * const remoteRunConfig
= qobject_cast<RemoteLinuxRunConfiguration *>(runConfiguration);
if (mode == DebugRunMode)
return remoteRunConfig->portsUsedByDebuggers() <= remoteRunConfig->freePorts().count();
return true;
}
RunControl *RemoteLinuxRunControlFactory::create(RunConfiguration *runConfig, RunMode mode)
{
Q_ASSERT(canRun(runConfig, mode));
RemoteLinuxRunConfiguration *rc = qobject_cast<RemoteLinuxRunConfiguration *>(runConfig);
Q_ASSERT(rc);
if (mode == ProjectExplorer::NormalRunMode)
return new RemoteLinuxRunControl(rc);
const DebuggerStartParameters params
= AbstractRemoteLinuxDebugSupport::startParameters(rc);
DebuggerRunControl * const runControl = DebuggerPlugin::createDebugger(params, rc);
if (!runControl)
return 0;
RemoteLinuxDebugSupport *debugSupport =
new RemoteLinuxDebugSupport(rc, runControl->engine());
connect(runControl, SIGNAL(finished()), debugSupport, SLOT(handleDebuggingFinished()));
return runControl;
}
QString RemoteLinuxRunControlFactory::displayName() const
{
return tr("Run on remote Linux device");
}
RunConfigWidget *RemoteLinuxRunControlFactory::createConfigurationWidget(RunConfiguration *config)
{
Q_UNUSED(config)
return 0;
}
} // namespace Internal
} // namespace RemoteLinux
<commit_msg>embeddedlinux: let F10/F11 start debugging with break on main<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "remotelinuxruncontrolfactory.h"
#include "remotelinuxdebugsupport.h"
#include "remotelinuxrunconfiguration.h"
#include "remotelinuxruncontrol.h"
#include <debugger/debuggerconstants.h>
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerrunner.h>
#include <debugger/debuggerstartparameters.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/portlist.h>
using namespace Debugger;
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace Internal {
RemoteLinuxRunControlFactory::RemoteLinuxRunControlFactory(QObject *parent)
: IRunControlFactory(parent)
{
}
RemoteLinuxRunControlFactory::~RemoteLinuxRunControlFactory()
{
}
bool RemoteLinuxRunControlFactory::canRun(RunConfiguration *runConfiguration, RunMode mode) const
{
if (mode != NormalRunMode && mode != DebugRunMode && mode != DebugRunModeWithBreakOnMain)
return false;
const QString idStr = QString::fromLatin1(runConfiguration->id().name());
if (!runConfiguration->isEnabled()
|| !idStr.startsWith(RemoteLinuxRunConfiguration::Id)) {
return false;
}
if (mode == NormalRunMode)
return true;
const RemoteLinuxRunConfiguration * const remoteRunConfig
= qobject_cast<RemoteLinuxRunConfiguration *>(runConfiguration);
return remoteRunConfig->portsUsedByDebuggers() <= remoteRunConfig->freePorts().count();
}
RunControl *RemoteLinuxRunControlFactory::create(RunConfiguration *runConfig, RunMode mode)
{
Q_ASSERT(canRun(runConfig, mode));
RemoteLinuxRunConfiguration *rc = qobject_cast<RemoteLinuxRunConfiguration *>(runConfig);
Q_ASSERT(rc);
if (mode == ProjectExplorer::NormalRunMode)
return new RemoteLinuxRunControl(rc);
const DebuggerStartParameters params
= AbstractRemoteLinuxDebugSupport::startParameters(rc);
DebuggerRunControl * const runControl = DebuggerPlugin::createDebugger(params, rc);
if (!runControl)
return 0;
RemoteLinuxDebugSupport *debugSupport =
new RemoteLinuxDebugSupport(rc, runControl->engine());
connect(runControl, SIGNAL(finished()), debugSupport, SLOT(handleDebuggingFinished()));
return runControl;
}
QString RemoteLinuxRunControlFactory::displayName() const
{
return tr("Run on remote Linux device");
}
RunConfigWidget *RemoteLinuxRunControlFactory::createConfigurationWidget(RunConfiguration *config)
{
Q_UNUSED(config)
return 0;
}
} // namespace Internal
} // namespace RemoteLinux
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, 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 "mesh_resource_marker.h"
#include "marker_selection_handler.h"
#include "rviz/default_plugin/marker_display.h"
#include "rviz/selection/selection_manager.h"
#include "rviz/display_context.h"
#include "rviz/mesh_loader.h"
#include "marker_display.h"
#include <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <OgreEntity.h>
#include <OgreSubEntity.h>
#include <OgreMaterialManager.h>
#include <OgreTextureManager.h>
#include <OgreSharedPtr.h>
#include <OgreTechnique.h>
namespace rviz
{
MeshResourceMarker::MeshResourceMarker(MarkerDisplay* owner, DisplayContext* context, Ogre::SceneNode* parent_node)
: MarkerBase(owner, context, parent_node)
, entity_(0)
{
}
MeshResourceMarker::~MeshResourceMarker()
{
reset();
}
void MeshResourceMarker::reset()
{
//destroy entity
if (entity_)
{
context_->getSceneManager()->destroyEntity(entity_);
entity_ = 0;
}
// destroy all the materials we've created
S_MaterialPtr::iterator it;
for (it = materials_.begin(); it != materials_.end(); it++)
{
Ogre::MaterialPtr material = *it;
if (!material.isNull())
{
material->unload();
Ogre::MaterialManager::getSingleton().remove(material->getName());
}
}
materials_.clear();
// the actual passes are deleted by the material
color_tint_passes_.clear();
}
void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);
// flag indicating if the mesh material color needs to be updated
bool update_color = false;
scene_node_->setVisible(false);
if (!entity_ ||
old_message->mesh_resource != new_message->mesh_resource ||
old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials)
{
reset();
if (new_message->mesh_resource.empty())
{
return;
}
if (loadMeshFromResource(new_message->mesh_resource).isNull())
{
std::stringstream ss;
ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
if (owner_)
{
owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());
}
ROS_DEBUG("%s", ss.str().c_str());
return;
}
static uint32_t count = 0;
std::stringstream ss;
ss << "mesh_resource_marker_" << count++;
std::string id = ss.str();
entity_ = context_->getSceneManager()->createEntity(id, new_message->mesh_resource);
scene_node_->attachObject(entity_);
// create a default material for any sub-entities which don't have their own.
ss << "Material";
Ogre::MaterialPtr default_material = Ogre::MaterialManager::getSingleton().create(ss.str(), ROS_PACKAGE_NAME);
default_material->setReceiveShadows(false);
default_material->getTechnique(0)->setLightingEnabled(true);
default_material->getTechnique(0)->setAmbient(0.5, 0.5, 0.5);
materials_.insert(default_material);
if (new_message->mesh_use_embedded_materials)
{
// make clones of all embedded materials so selection works correctly
S_MaterialPtr materials = getMaterials();
S_MaterialPtr::iterator it;
for (it = materials.begin(); it != materials.end(); it++)
{
if ((*it)->getName() != "BaseWhiteNoLighting")
{
Ogre::MaterialPtr new_material = (*it)->clone(id + (*it)->getName());
materials_.insert(new_material);
}
}
// make sub-entities use cloned materials
for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
{
std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
if (mat_name != "BaseWhiteNoLighting")
{
entity_->getSubEntity(i)->setMaterialName(id + mat_name);
}
else
{
// BaseWhiteNoLighting is the default material Ogre uses
// when it sees a mesh with no material. Here we replace
// that with our default_material which gets colored with
// new_message->color.
entity_->getSubEntity(i)->setMaterial(default_material);
}
}
}
else
{
entity_->setMaterial(default_material);
}
// add a pass to every material to perform the color tinting
S_MaterialPtr::iterator material_it;
for (material_it = materials_.begin(); material_it != materials_.end(); material_it++)
{
Ogre::Technique* technique = (*material_it)->getTechnique(0);
color_tint_passes_.push_back(technique->createPass());
}
// always update color on resource change
update_color = true;
handler_.reset(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id), context_));
handler_->addTrackedObject(entity_);
}
else
{
// underlying mesh resource has not changed but if the color has
// then we need to update the materials color
if (!old_message
|| old_message->color.r != new_message->color.r
|| old_message->color.g != new_message->color.g
|| old_message->color.b != new_message->color.b
|| old_message->color.a != new_message->color.a)
{
update_color = true;
}
}
// update material color
// if the mesh_use_embedded_materials is true and color is non-zero
// then the color will be used to tint the embedded materials
if (update_color)
{
float r = new_message->color.r;
float g = new_message->color.g;
float b = new_message->color.b;
float a = new_message->color.a;
Ogre::SceneBlendType blending;
bool depth_write;
if (a < 0.9998)
{
blending = Ogre::SBT_TRANSPARENT_ALPHA;
depth_write = false;
}
else
{
blending = Ogre::SBT_REPLACE;
depth_write = true;
}
for (std::vector<Ogre::Pass*>::iterator it = color_tint_passes_.begin();
it != color_tint_passes_.end();
++it)
{
(*it)->setAmbient(0.5 * r, 0.5 * g, 0.5 * b);
(*it)->setDiffuse(r, g, b, a);
(*it)->setSceneBlending(blending);
(*it)->setDepthWriteEnabled(depth_write);
(*it)->setLightingEnabled(true);
}
}
Ogre::Vector3 pos, scale;
Ogre::Quaternion orient;
transform(new_message, pos, orient, scale);
scene_node_->setVisible(true);
setPosition(pos);
setOrientation(orient);
scene_node_->setScale(scale);
}
S_MaterialPtr MeshResourceMarker::getMaterials()
{
S_MaterialPtr materials;
if (entity_)
{
extractMaterials(entity_, materials);
}
return materials;
}
}
<commit_msg>mesh markers: Fixing mesh alpha and tinting<commit_after>/*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, 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 "mesh_resource_marker.h"
#include "marker_selection_handler.h"
#include "rviz/default_plugin/marker_display.h"
#include "rviz/selection/selection_manager.h"
#include "rviz/display_context.h"
#include "rviz/mesh_loader.h"
#include "marker_display.h"
#include <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <OgreEntity.h>
#include <OgreSubEntity.h>
#include <OgreMaterialManager.h>
#include <OgreTextureManager.h>
#include <OgreSharedPtr.h>
#include <OgreTechnique.h>
namespace rviz
{
MeshResourceMarker::MeshResourceMarker(MarkerDisplay* owner, DisplayContext* context, Ogre::SceneNode* parent_node)
: MarkerBase(owner, context, parent_node)
, entity_(0)
{
}
MeshResourceMarker::~MeshResourceMarker()
{
reset();
}
void MeshResourceMarker::reset()
{
//destroy entity
if (entity_)
{
context_->getSceneManager()->destroyEntity(entity_);
entity_ = 0;
}
// destroy all the materials we've created
S_MaterialPtr::iterator it;
for (it = materials_.begin(); it != materials_.end(); it++)
{
Ogre::MaterialPtr material = *it;
if (!material.isNull())
{
material->unload();
Ogre::MaterialManager::getSingleton().remove(material->getName());
}
}
materials_.clear();
// the actual passes are deleted by the material
color_tint_passes_.clear();
}
void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);
// flag indicating if the mesh material color needs to be updated
bool update_color = false;
scene_node_->setVisible(false);
// Get the color information from the message
float r = new_message->color.r;
float g = new_message->color.g;
float b = new_message->color.b;
float a = new_message->color.a;
Ogre::SceneBlendType blending;
bool depth_write;
if (a < 0.9998)
{
blending = Ogre::SBT_TRANSPARENT_ALPHA;
depth_write = false;
}
else
{
blending = Ogre::SBT_REPLACE;
depth_write = true;
}
if (!entity_ ||
old_message->mesh_resource != new_message->mesh_resource ||
old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials)
{
reset();
if (new_message->mesh_resource.empty())
{
return;
}
if (loadMeshFromResource(new_message->mesh_resource).isNull())
{
std::stringstream ss;
ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
if (owner_)
{
owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());
}
ROS_DEBUG("%s", ss.str().c_str());
return;
}
static uint32_t count = 0;
std::stringstream ss;
ss << "mesh_resource_marker_" << count++;
std::string id = ss.str();
entity_ = context_->getSceneManager()->createEntity(id, new_message->mesh_resource);
scene_node_->attachObject(entity_);
// create a default material for any sub-entities which don't have their own.
ss << "Material";
Ogre::MaterialPtr default_material = Ogre::MaterialManager::getSingleton().create(ss.str(), ROS_PACKAGE_NAME);
default_material->setReceiveShadows(false);
default_material->getTechnique(0)->setLightingEnabled(true);
default_material->getTechnique(0)->setAmbient(0.5, 0.5, 0.5);
materials_.insert(default_material);
if (new_message->mesh_use_embedded_materials)
{
// make clones of all embedded materials so selection works correctly
S_MaterialPtr materials = getMaterials();
S_MaterialPtr::iterator it;
for (it = materials.begin(); it != materials.end(); it++)
{
if ((*it)->getName() != "BaseWhiteNoLighting")
{
Ogre::MaterialPtr new_material = (*it)->clone(id + (*it)->getName());
materials_.insert(new_material);
}
}
// make sub-entities use cloned materials
for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
{
std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
if (mat_name != "BaseWhiteNoLighting")
{
entity_->getSubEntity(i)->setMaterialName(id + mat_name);
}
else
{
// BaseWhiteNoLighting is the default material Ogre uses
// when it sees a mesh with no material. Here we replace
// that with our default_material which gets colored with
// new_message->color.
entity_->getSubEntity(i)->setMaterial(default_material);
}
}
}
else
{
entity_->setMaterial(default_material);
}
// always update color on resource change
update_color = true;
handler_.reset(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id), context_));
handler_->addTrackedObject(entity_);
}
else
{
// underlying mesh resource has not changed but if the color has
// then we need to update the materials color
if (!old_message
|| old_message->color.r != new_message->color.r
|| old_message->color.g != new_message->color.g
|| old_message->color.b != new_message->color.b
|| old_message->color.a != new_message->color.a)
{
update_color = true;
}
}
// update material color
// if the mesh_use_embedded_materials is true and color is non-zero
// then the color will be used to tint the embedded materials
if (update_color)
{ // add a pass to every material to perform the color tinting
S_MaterialPtr::iterator material_it;
for (material_it = materials_.begin(); material_it != materials_.end(); material_it++)
{
Ogre::Technique* technique = (*material_it)->getTechnique(0);
//color_tint_passes_.push_back(technique->createPass());
technique->setAmbient( r*0.5, g*0.5, b*0.5 );
technique->setDiffuse( r, g, b, a );
technique->setSceneBlending( blending );
technique->setDepthWriteEnabled( depth_write );
technique->setLightingEnabled( true );
}
// for (std::vector<Ogre::Pass*>::iterator it = color_tint_passes_.begin();
// it != color_tint_passes_.end();
// ++it)
// {
//(*it)->setAmbient(0.5 * r, 0.5 * g, 0.5 * b);
//(*it)->setDiffuse(r, g, b, a);
//(*it)->setSceneBlending(blending);
//(*it)->setDepthWriteEnabled(depth_write);
//(*it)->setLightingEnabled(true);
//}
}
Ogre::Vector3 pos, scale;
Ogre::Quaternion orient;
transform(new_message, pos, orient, scale);
scene_node_->setVisible(true);
setPosition(pos);
setOrientation(orient);
scene_node_->setScale(scale);
}
S_MaterialPtr MeshResourceMarker::getMaterials()
{
S_MaterialPtr materials;
if (entity_)
{
extractMaterials(entity_, materials);
}
return materials;
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylanddisplay.h"
#include "qwaylandeventthread.h"
#include "qwaylandwindow.h"
#include "qwaylandscreen.h"
#include "qwaylandcursor.h"
#include "qwaylandinputdevice.h"
#include "qwaylandclipboard.h"
#include "qwaylanddatadevicemanager.h"
#ifdef QT_WAYLAND_GL_SUPPORT
#include "qwaylandglintegration.h"
#endif
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif
#include "qwaylandextendedoutput.h"
#include "qwaylandextendedsurface.h"
#include "qwaylandsubsurface.h"
#include "qwaylandtouch.h"
#include "qwaylandqtkey.h"
#include <QtCore/QAbstractEventDispatcher>
#include <QtGui/private/qguiapplication_p.h>
#include <QtCore/QDebug>
QT_USE_NAMESPACE
struct wl_surface *QWaylandDisplay::createSurface(void *handle)
{
struct wl_surface *surface = mCompositor.create_surface();
wl_surface_set_user_data(surface, handle);
return surface;
}
#ifdef QT_WAYLAND_GL_SUPPORT
QWaylandGLIntegration * QWaylandDisplay::eglIntegration()
{
return mEglIntegration;
}
#endif
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
QWaylandWindowManagerIntegration *QWaylandDisplay::windowManagerIntegration()
{
return mWindowManagerIntegration;
}
#endif
QWaylandInputDevice *QWaylandDisplay::lastKeyboardFocusInputDevice() const
{
return mLastKeyboardFocusInputDevice;
}
void QWaylandDisplay::setLastKeyboardFocusInputDevice(QWaylandInputDevice *device)
{
mLastKeyboardFocusInputDevice = device;
}
static QWaylandDisplay *display = 0;
QWaylandDisplay::QWaylandDisplay()
: mLastKeyboardFocusInputDevice(0)
, mDndSelectionHandler(0)
, mWindowExtension(0)
, mSubSurfaceExtension(0)
, mOutputExtension(0)
, mTouchExtension(0)
, mQtKeyExtension(0)
{
display = this;
qRegisterMetaType<uint32_t>("uint32_t");
mEventThreadObject = new QWaylandEventThread(0);
mEventThread = new QThread(this);
mEventThreadObject->moveToThread(mEventThread);
mEventThread->start();
mEventThreadObject->displayConnect();
mDisplay = mEventThreadObject->display(); //blocks until display is available
//Create a new even queue for the QtGui thread
mEventQueue = wl_display_create_queue(mDisplay);
struct ::wl_registry *registry = wl_display_get_registry(mDisplay);
wl_proxy_set_queue((struct wl_proxy *)registry, mEventQueue);
init(registry);
QAbstractEventDispatcher *dispatcher = QGuiApplicationPrivate::eventDispatcher;
connect(dispatcher, SIGNAL(aboutToBlock()), this, SLOT(flushRequests()));
connect(mEventThreadObject, SIGNAL(newEventsRead()), this, SLOT(flushRequests()));
#ifdef QT_WAYLAND_GL_SUPPORT
mEglIntegration = QWaylandGLIntegration::createGLIntegration(this);
#endif
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
mWindowManagerIntegration = new QWaylandWindowManagerIntegration(this);
#endif
blockingReadEvents();
#ifdef QT_WAYLAND_GL_SUPPORT
mEglIntegration->initialize();
flushRequests();
while (mEglIntegration->waitingForEvents())
blockingReadEvents();
#endif
waitForScreens();
}
QWaylandDisplay::~QWaylandDisplay(void)
{
#ifdef QT_WAYLAND_GL_SUPPORT
delete mEglIntegration;
#endif
mEventThread->quit();
mEventThread->wait();
delete mEventThreadObject;
}
void QWaylandDisplay::flushRequests()
{
wl_display_dispatch_queue_pending(mDisplay, mEventQueue);
wl_display_flush(mDisplay);
}
void QWaylandDisplay::blockingReadEvents()
{
wl_display_dispatch_queue(mDisplay, mEventQueue);
}
QWaylandScreen *QWaylandDisplay::screenForOutput(struct wl_output *output) const
{
for (int i = 0; i < mScreens.size(); ++i) {
QWaylandScreen *screen = static_cast<QWaylandScreen *>(mScreens.at(i));
if (screen->output() == output)
return screen;
}
return 0;
}
void QWaylandDisplay::addRegistryListener(RegistryListener listener, void *data)
{
Listener l = { listener, data };
mRegistryListeners.append(l);
}
void QWaylandDisplay::waitForScreens()
{
flushRequests();
while (mScreens.isEmpty())
blockingReadEvents();
}
void QWaylandDisplay::registry_global(uint32_t id, const QString &interface, uint32_t version)
{
Q_UNUSED(version);
struct ::wl_registry *registry = object();
if (interface == "wl_output") {
mScreens.append(new QWaylandScreen(this, id));
} else if (interface == "wl_compositor") {
mCompositor.init(registry, id);
} else if (interface == "wl_shm") {
mShm = static_cast<struct wl_shm *>(wl_registry_bind(registry, id, &wl_shm_interface,1));
} else if (interface == "wl_shell"){
mShell = new QtWayland::wl_shell(registry, id);
} else if (interface == "wl_seat") {
QWaylandInputDevice *inputDevice = new QWaylandInputDevice(this, id);
mInputDevices.append(inputDevice);
} else if (interface == "wl_data_device_manager") {
mDndSelectionHandler = new QWaylandDataDeviceManager(this, id);
} else if (interface == "wl_output_extension") {
mOutputExtension = new QtWayland::qt_output_extension(registry, id);
foreach (QPlatformScreen *screen, screens())
static_cast<QWaylandScreen *>(screen)->createExtendedOutput();
} else if (interface == "wl_surface_extension") {
mWindowExtension = new QtWayland::qt_surface_extension(registry, id);
} else if (interface == "wl_sub_surface_extension") {
mSubSurfaceExtension = new QtWayland::qt_sub_surface_extension(registry, id);
} else if (interface == "wl_touch_extension") {
mTouchExtension = new QWaylandTouchExtension(this, id);
} else if (interface == "wl_qtkey_extension") {
mQtKeyExtension = new QWaylandQtKeyExtension(this, id);
}
foreach (Listener l, mRegistryListeners)
(*l.listener)(l.data, registry, id, interface, version);
}
uint32_t QWaylandDisplay::currentTimeMillisec()
{
//### we throw away the time information
struct timeval tv;
int ret = gettimeofday(&tv, 0);
if (ret == 0)
return tv.tv_sec*1000 + tv.tv_usec/1000;
return 0;
}
void QWaylandDisplay::forceRoundTrip()
{
wl_display_roundtrip(mDisplay);
}
<commit_msg>Make plugin pick up Qt wayland extensions<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylanddisplay.h"
#include "qwaylandeventthread.h"
#include "qwaylandwindow.h"
#include "qwaylandscreen.h"
#include "qwaylandcursor.h"
#include "qwaylandinputdevice.h"
#include "qwaylandclipboard.h"
#include "qwaylanddatadevicemanager.h"
#ifdef QT_WAYLAND_GL_SUPPORT
#include "qwaylandglintegration.h"
#endif
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif
#include "qwaylandextendedoutput.h"
#include "qwaylandextendedsurface.h"
#include "qwaylandsubsurface.h"
#include "qwaylandtouch.h"
#include "qwaylandqtkey.h"
#include <QtCore/QAbstractEventDispatcher>
#include <QtGui/private/qguiapplication_p.h>
#include <QtCore/QDebug>
QT_USE_NAMESPACE
struct wl_surface *QWaylandDisplay::createSurface(void *handle)
{
struct wl_surface *surface = mCompositor.create_surface();
wl_surface_set_user_data(surface, handle);
return surface;
}
#ifdef QT_WAYLAND_GL_SUPPORT
QWaylandGLIntegration * QWaylandDisplay::eglIntegration()
{
return mEglIntegration;
}
#endif
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
QWaylandWindowManagerIntegration *QWaylandDisplay::windowManagerIntegration()
{
return mWindowManagerIntegration;
}
#endif
QWaylandInputDevice *QWaylandDisplay::lastKeyboardFocusInputDevice() const
{
return mLastKeyboardFocusInputDevice;
}
void QWaylandDisplay::setLastKeyboardFocusInputDevice(QWaylandInputDevice *device)
{
mLastKeyboardFocusInputDevice = device;
}
static QWaylandDisplay *display = 0;
QWaylandDisplay::QWaylandDisplay()
: mLastKeyboardFocusInputDevice(0)
, mDndSelectionHandler(0)
, mWindowExtension(0)
, mSubSurfaceExtension(0)
, mOutputExtension(0)
, mTouchExtension(0)
, mQtKeyExtension(0)
{
display = this;
qRegisterMetaType<uint32_t>("uint32_t");
mEventThreadObject = new QWaylandEventThread(0);
mEventThread = new QThread(this);
mEventThreadObject->moveToThread(mEventThread);
mEventThread->start();
mEventThreadObject->displayConnect();
mDisplay = mEventThreadObject->display(); //blocks until display is available
//Create a new even queue for the QtGui thread
mEventQueue = wl_display_create_queue(mDisplay);
struct ::wl_registry *registry = wl_display_get_registry(mDisplay);
wl_proxy_set_queue((struct wl_proxy *)registry, mEventQueue);
init(registry);
QAbstractEventDispatcher *dispatcher = QGuiApplicationPrivate::eventDispatcher;
connect(dispatcher, SIGNAL(aboutToBlock()), this, SLOT(flushRequests()));
connect(mEventThreadObject, SIGNAL(newEventsRead()), this, SLOT(flushRequests()));
#ifdef QT_WAYLAND_GL_SUPPORT
mEglIntegration = QWaylandGLIntegration::createGLIntegration(this);
#endif
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
mWindowManagerIntegration = new QWaylandWindowManagerIntegration(this);
#endif
blockingReadEvents();
#ifdef QT_WAYLAND_GL_SUPPORT
mEglIntegration->initialize();
flushRequests();
while (mEglIntegration->waitingForEvents())
blockingReadEvents();
#endif
waitForScreens();
}
QWaylandDisplay::~QWaylandDisplay(void)
{
#ifdef QT_WAYLAND_GL_SUPPORT
delete mEglIntegration;
#endif
mEventThread->quit();
mEventThread->wait();
delete mEventThreadObject;
}
void QWaylandDisplay::flushRequests()
{
wl_display_dispatch_queue_pending(mDisplay, mEventQueue);
wl_display_flush(mDisplay);
}
void QWaylandDisplay::blockingReadEvents()
{
wl_display_dispatch_queue(mDisplay, mEventQueue);
}
QWaylandScreen *QWaylandDisplay::screenForOutput(struct wl_output *output) const
{
for (int i = 0; i < mScreens.size(); ++i) {
QWaylandScreen *screen = static_cast<QWaylandScreen *>(mScreens.at(i));
if (screen->output() == output)
return screen;
}
return 0;
}
void QWaylandDisplay::addRegistryListener(RegistryListener listener, void *data)
{
Listener l = { listener, data };
mRegistryListeners.append(l);
}
void QWaylandDisplay::waitForScreens()
{
flushRequests();
while (mScreens.isEmpty())
blockingReadEvents();
}
void QWaylandDisplay::registry_global(uint32_t id, const QString &interface, uint32_t version)
{
Q_UNUSED(version);
struct ::wl_registry *registry = object();
if (interface == "wl_output") {
mScreens.append(new QWaylandScreen(this, id));
} else if (interface == "wl_compositor") {
mCompositor.init(registry, id);
} else if (interface == "wl_shm") {
mShm = static_cast<struct wl_shm *>(wl_registry_bind(registry, id, &wl_shm_interface,1));
} else if (interface == "wl_shell"){
mShell = new QtWayland::wl_shell(registry, id);
} else if (interface == "wl_seat") {
QWaylandInputDevice *inputDevice = new QWaylandInputDevice(this, id);
mInputDevices.append(inputDevice);
} else if (interface == "wl_data_device_manager") {
mDndSelectionHandler = new QWaylandDataDeviceManager(this, id);
} else if (interface == "qt_output_extension") {
mOutputExtension = new QtWayland::qt_output_extension(registry, id);
foreach (QPlatformScreen *screen, screens())
static_cast<QWaylandScreen *>(screen)->createExtendedOutput();
} else if (interface == "qt_surface_extension") {
mWindowExtension = new QtWayland::qt_surface_extension(registry, id);
} else if (interface == "qt_sub_surface_extension") {
mSubSurfaceExtension = new QtWayland::qt_sub_surface_extension(registry, id);
} else if (interface == "qt_touch_extension") {
mTouchExtension = new QWaylandTouchExtension(this, id);
} else if (interface == "qt_qtkey_extension") {
mQtKeyExtension = new QWaylandQtKeyExtension(this, id);
}
foreach (Listener l, mRegistryListeners)
(*l.listener)(l.data, registry, id, interface, version);
}
uint32_t QWaylandDisplay::currentTimeMillisec()
{
//### we throw away the time information
struct timeval tv;
int ret = gettimeofday(&tv, 0);
if (ret == 0)
return tv.tv_sec*1000 + tv.tv_usec/1000;
return 0;
}
void QWaylandDisplay::forceRoundTrip()
{
wl_display_roundtrip(mDisplay);
}
<|endoftext|>
|
<commit_before>#include <gst/gst.h>
#include "MediaPipeline.hpp"
#include <WebRtcEndpointImplFactory.hpp>
#include "WebRtcEndpointImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <gst/gst.h>
#include <boost/filesystem.hpp>
#include <IceCandidate.hpp>
#include <webrtcendpoint/kmsicecandidate.h>
#define GST_CAT_DEFAULT kurento_web_rtc_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoWebRtcEndpointImpl"
#define FACTORY_NAME "webrtcendpoint"
namespace kurento
{
static const std::string CERTTOOL_TEMPLATE = "autoCerttool.tmpl";
static const std::string CERT_KEY_PEM_FILE = "autoCertkey.pem";
static const uint DEFAULT_STUN_PORT = 3478;
static std::shared_ptr<std::string> pemCertificate;
std::mutex WebRtcEndpointImpl::certificateMutex;
static void
on_ice_candidate (GstElement *webrtcendpoint, KmsIceCandidate *candidate,
gpointer data)
{
auto handler = reinterpret_cast<std::function<void (KmsIceCandidate *) >*>
(data);
(*handler) (candidate);
}
static void
on_ice_gathering_done (GstElement *webrtcendpoint, gpointer data)
{
auto handler = reinterpret_cast<std::function<void() >*> (data);
(*handler) ();
}
class TemporalDirectory
{
public:
~TemporalDirectory() {
if (!dir.string ().empty() ) {
boost::filesystem::remove_all (dir);
}
}
void setDir (boost::filesystem::path &dir) {
this->dir = dir;
}
private:
boost::filesystem::path dir;
};
static TemporalDirectory tmpDir;
static void
create_pem_certificate ()
{
int ret;
boost::filesystem::path temporalDirectory = boost::filesystem::unique_path (
boost::filesystem::temp_directory_path() / "WebRtcEndpoint_%%%%%%%%" );
boost::filesystem::create_directories (temporalDirectory);
tmpDir.setDir (temporalDirectory);
boost::filesystem::path pemFile = temporalDirectory / CERT_KEY_PEM_FILE;
std::string pemGenerationCommand =
"/bin/sh -c \"certtool --generate-privkey --outfile " + pemFile .string() +
"\"";
ret = system (pemGenerationCommand.c_str() );
if (ret == -1) {
return;
}
boost::filesystem::path templateFile = temporalDirectory / CERTTOOL_TEMPLATE;
std::string certtoolCommand = "/bin/sh -c \"echo 'organization = kurento' > " +
templateFile.string() + " && certtool --generate-self-signed --load-privkey " +
pemFile.string() + " --template " + templateFile.string() + " >> " +
pemFile.string() + " 2>/dev/null\"";
ret = system (certtoolCommand.c_str() );
if (ret == -1) {
return;
}
pemCertificate = std::shared_ptr <std::string> (new std::string (
pemFile.string() ) );
}
std::shared_ptr<std::string>
WebRtcEndpointImpl::getPemCertificate ()
{
std::unique_lock<std::mutex> lock (certificateMutex);
if (pemCertificate) {
return pemCertificate;
}
try {
boost::filesystem::path pem_certificate_file_name (
getConfigValue<std::string, WebRtcEndpoint> ("pemCertificate") );
if (pem_certificate_file_name.is_relative() ) {
pem_certificate_file_name = boost::filesystem::path (
config.get<std::string> ("configPath") ) / pem_certificate_file_name;
}
pemCertificate = std::shared_ptr <std::string> (new std::string (
pem_certificate_file_name.string() ) );
return pemCertificate;
} catch (boost::property_tree::ptree_error &e) {
}
create_pem_certificate();
return pemCertificate;
}
WebRtcEndpointImpl::WebRtcEndpointImpl (const boost::property_tree::ptree &conf,
std::shared_ptr<MediaPipeline>
mediaPipeline) : BaseRtpEndpointImpl (conf,
std::dynamic_pointer_cast<MediaObjectImpl>
(mediaPipeline), FACTORY_NAME)
{
uint stunPort;
std::string stunAddress;
std::string turnURL;
//set properties
try {
stunPort = getConfigValue <uint, WebRtcEndpoint> ("stunServerPort");
} catch (boost::property_tree::ptree_error &e) {
GST_INFO ("Setting default port %d to stun server",
DEFAULT_STUN_PORT);
stunPort = DEFAULT_STUN_PORT;
}
if (stunPort != 0) {
try {
stunAddress = getConfigValue
<std::string, WebRtcEndpoint> ("stunServerAddress");
} catch (boost::property_tree::ptree_error &e) {
GST_INFO ("Stun address not found in config, cannot operate behind a NAT" );
}
if (!stunAddress.empty() ) {
GST_INFO ("stun port %d\n", stunPort );
g_object_set ( G_OBJECT (element), "stun-server-port",
stunPort, NULL);
GST_INFO ("stun address %s\n", stunAddress.c_str() );
g_object_set ( G_OBJECT (element), "stun-server",
stunAddress.c_str(),
NULL);
}
}
try {
turnURL = getConfigValue <std::string, WebRtcEndpoint> ("turnURL");
GST_INFO ("turn info: %s\n", turnURL.c_str() );
g_object_set ( G_OBJECT (element), "turn-url", turnURL.c_str(),
NULL);
} catch (boost::property_tree::ptree_error &e) {
}
g_object_set ( G_OBJECT (element), "certificate-pem-file",
getPemCertificate ()->c_str(), NULL);
onIceCandidateLambda = [&] (KmsIceCandidate * candidate) {
try {
std::string cand_str (kms_ice_candidate_get_candidate (candidate) );
std::string mid_str (kms_ice_candidate_get_sdp_mid (candidate) );
int sdp_m_line_index = kms_ice_candidate_get_sdp_m_line_index (candidate);
std::shared_ptr <IceCandidate> cand ( new IceCandidate
(cand_str, mid_str, sdp_m_line_index) );
OnIceCandidate event (cand, shared_from_this(), OnIceCandidate::getName() );
signalOnIceCandidate (event);
} catch (std::bad_weak_ptr &e) {
}
};
handlerOnIceCandidate = g_signal_connect (element, "on-ice-candidate",
G_CALLBACK (on_ice_candidate),
&onIceCandidateLambda);
onIceGatheringDoneLambda = [&] () {
try {
OnIceGatheringDone event (shared_from_this(), OnIceGatheringDone::getName() );
signalOnIceGatheringDone (event);
} catch (std::bad_weak_ptr &e) {
}
};
handlerOnIceGatheringDone = g_signal_connect (element, "on-ice-gathering-done",
G_CALLBACK (on_ice_gathering_done),
&onIceGatheringDoneLambda);
}
WebRtcEndpointImpl::~WebRtcEndpointImpl()
{
g_signal_handler_disconnect (element, handlerOnIceCandidate);
g_signal_handler_disconnect (element, handlerOnIceGatheringDone);
}
void
WebRtcEndpointImpl::gatherCandidates ()
{
gboolean ret;
g_signal_emit_by_name (element, "gather-candidates", &ret);
if (!ret) {
throw KurentoException (ICE_GATHER_CANDIDATES_ERROR,
"Error gathering candidates");
}
}
void
WebRtcEndpointImpl::addIceCandidate (std::shared_ptr<IceCandidate> candidate)
{
gboolean ret;
const char *cand_str = candidate->getCandidate().c_str ();
const char *mid_str = candidate->getSdpMid().c_str ();
guint8 sdp_m_line_index = candidate->getSdpMLineIndex ();
KmsIceCandidate *cand = kms_ice_candidate_new (cand_str, mid_str,
sdp_m_line_index);
g_signal_emit_by_name (element, "add-ice-candidate", cand, &ret);
if (!ret) {
throw KurentoException (ICE_ADD_CANDIDATE_ERROR, "Error adding candidate");
}
}
MediaObjectImpl *
WebRtcEndpointImplFactory::createObject (const boost::property_tree::ptree
&conf, std::shared_ptr<MediaPipeline>
mediaPipeline) const
{
return new WebRtcEndpointImpl (conf, mediaPipeline);
}
WebRtcEndpointImpl::StaticConstructor WebRtcEndpointImpl::staticConstructor;
WebRtcEndpointImpl::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} /* kurento */
<commit_msg>WebRtcEndpoint: Fix format<commit_after>#include <gst/gst.h>
#include "MediaPipeline.hpp"
#include <WebRtcEndpointImplFactory.hpp>
#include "WebRtcEndpointImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <gst/gst.h>
#include <boost/filesystem.hpp>
#include <IceCandidate.hpp>
#include <webrtcendpoint/kmsicecandidate.h>
#define GST_CAT_DEFAULT kurento_web_rtc_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoWebRtcEndpointImpl"
#define FACTORY_NAME "webrtcendpoint"
namespace kurento
{
static const std::string CERTTOOL_TEMPLATE = "autoCerttool.tmpl";
static const std::string CERT_KEY_PEM_FILE = "autoCertkey.pem";
static const uint DEFAULT_STUN_PORT = 3478;
static std::shared_ptr<std::string> pemCertificate;
std::mutex WebRtcEndpointImpl::certificateMutex;
static void
on_ice_candidate (GstElement *webrtcendpoint, KmsIceCandidate *candidate,
gpointer data)
{
auto handler = reinterpret_cast<std::function<void (KmsIceCandidate *) >*>
(data);
(*handler) (candidate);
}
static void
on_ice_gathering_done (GstElement *webrtcendpoint, gpointer data)
{
auto handler = reinterpret_cast<std::function<void() >*> (data);
(*handler) ();
}
class TemporalDirectory
{
public:
~TemporalDirectory()
{
if (!dir.string ().empty() ) {
boost::filesystem::remove_all (dir);
}
}
void setDir (boost::filesystem::path &dir)
{
this->dir = dir;
}
private:
boost::filesystem::path dir;
};
static TemporalDirectory tmpDir;
static void
create_pem_certificate ()
{
int ret;
boost::filesystem::path temporalDirectory = boost::filesystem::unique_path (
boost::filesystem::temp_directory_path() / "WebRtcEndpoint_%%%%%%%%" );
boost::filesystem::create_directories (temporalDirectory);
tmpDir.setDir (temporalDirectory);
boost::filesystem::path pemFile = temporalDirectory / CERT_KEY_PEM_FILE;
std::string pemGenerationCommand =
"/bin/sh -c \"certtool --generate-privkey --outfile " + pemFile .string() +
"\"";
ret = system (pemGenerationCommand.c_str() );
if (ret == -1) {
return;
}
boost::filesystem::path templateFile = temporalDirectory / CERTTOOL_TEMPLATE;
std::string certtoolCommand = "/bin/sh -c \"echo 'organization = kurento' > " +
templateFile.string() + " && certtool --generate-self-signed --load-privkey " +
pemFile.string() + " --template " + templateFile.string() + " >> " +
pemFile.string() + " 2>/dev/null\"";
ret = system (certtoolCommand.c_str() );
if (ret == -1) {
return;
}
pemCertificate = std::shared_ptr <std::string> (new std::string (
pemFile.string() ) );
}
std::shared_ptr<std::string>
WebRtcEndpointImpl::getPemCertificate ()
{
std::unique_lock<std::mutex> lock (certificateMutex);
if (pemCertificate) {
return pemCertificate;
}
try {
boost::filesystem::path pem_certificate_file_name (
getConfigValue<std::string, WebRtcEndpoint> ("pemCertificate") );
if (pem_certificate_file_name.is_relative() ) {
pem_certificate_file_name = boost::filesystem::path (
config.get<std::string> ("configPath") ) / pem_certificate_file_name;
}
pemCertificate = std::shared_ptr <std::string> (new std::string (
pem_certificate_file_name.string() ) );
return pemCertificate;
} catch (boost::property_tree::ptree_error &e) {
}
create_pem_certificate();
return pemCertificate;
}
WebRtcEndpointImpl::WebRtcEndpointImpl (const boost::property_tree::ptree &conf,
std::shared_ptr<MediaPipeline>
mediaPipeline) : BaseRtpEndpointImpl (conf,
std::dynamic_pointer_cast<MediaObjectImpl>
(mediaPipeline), FACTORY_NAME)
{
uint stunPort;
std::string stunAddress;
std::string turnURL;
//set properties
try {
stunPort = getConfigValue <uint, WebRtcEndpoint> ("stunServerPort");
} catch (boost::property_tree::ptree_error &e) {
GST_INFO ("Setting default port %d to stun server",
DEFAULT_STUN_PORT);
stunPort = DEFAULT_STUN_PORT;
}
if (stunPort != 0) {
try {
stunAddress = getConfigValue
<std::string, WebRtcEndpoint> ("stunServerAddress");
} catch (boost::property_tree::ptree_error &e) {
GST_INFO ("Stun address not found in config, cannot operate behind a NAT" );
}
if (!stunAddress.empty() ) {
GST_INFO ("stun port %d\n", stunPort );
g_object_set ( G_OBJECT (element), "stun-server-port",
stunPort, NULL);
GST_INFO ("stun address %s\n", stunAddress.c_str() );
g_object_set ( G_OBJECT (element), "stun-server",
stunAddress.c_str(),
NULL);
}
}
try {
turnURL = getConfigValue <std::string, WebRtcEndpoint> ("turnURL");
GST_INFO ("turn info: %s\n", turnURL.c_str() );
g_object_set ( G_OBJECT (element), "turn-url", turnURL.c_str(),
NULL);
} catch (boost::property_tree::ptree_error &e) {
}
g_object_set ( G_OBJECT (element), "certificate-pem-file",
getPemCertificate ()->c_str(), NULL);
onIceCandidateLambda = [&] (KmsIceCandidate * candidate) {
try {
std::string cand_str (kms_ice_candidate_get_candidate (candidate) );
std::string mid_str (kms_ice_candidate_get_sdp_mid (candidate) );
int sdp_m_line_index = kms_ice_candidate_get_sdp_m_line_index (candidate);
std::shared_ptr <IceCandidate> cand ( new IceCandidate
(cand_str, mid_str, sdp_m_line_index) );
OnIceCandidate event (cand, shared_from_this(), OnIceCandidate::getName() );
signalOnIceCandidate (event);
} catch (std::bad_weak_ptr &e) {
}
};
handlerOnIceCandidate = g_signal_connect (element, "on-ice-candidate",
G_CALLBACK (on_ice_candidate),
&onIceCandidateLambda);
onIceGatheringDoneLambda = [&] () {
try {
OnIceGatheringDone event (shared_from_this(), OnIceGatheringDone::getName() );
signalOnIceGatheringDone (event);
} catch (std::bad_weak_ptr &e) {
}
};
handlerOnIceGatheringDone = g_signal_connect (element, "on-ice-gathering-done",
G_CALLBACK (on_ice_gathering_done),
&onIceGatheringDoneLambda);
}
WebRtcEndpointImpl::~WebRtcEndpointImpl()
{
g_signal_handler_disconnect (element, handlerOnIceCandidate);
g_signal_handler_disconnect (element, handlerOnIceGatheringDone);
}
void
WebRtcEndpointImpl::gatherCandidates ()
{
gboolean ret;
g_signal_emit_by_name (element, "gather-candidates", &ret);
if (!ret) {
throw KurentoException (ICE_GATHER_CANDIDATES_ERROR,
"Error gathering candidates");
}
}
void
WebRtcEndpointImpl::addIceCandidate (std::shared_ptr<IceCandidate> candidate)
{
gboolean ret;
const char *cand_str = candidate->getCandidate().c_str ();
const char *mid_str = candidate->getSdpMid().c_str ();
guint8 sdp_m_line_index = candidate->getSdpMLineIndex ();
KmsIceCandidate *cand = kms_ice_candidate_new (cand_str, mid_str,
sdp_m_line_index);
g_signal_emit_by_name (element, "add-ice-candidate", cand, &ret);
if (!ret) {
throw KurentoException (ICE_ADD_CANDIDATE_ERROR, "Error adding candidate");
}
}
MediaObjectImpl *
WebRtcEndpointImplFactory::createObject (const boost::property_tree::ptree
&conf, std::shared_ptr<MediaPipeline>
mediaPipeline) const
{
return new WebRtcEndpointImpl (conf, mediaPipeline);
}
WebRtcEndpointImpl::StaticConstructor WebRtcEndpointImpl::staticConstructor;
WebRtcEndpointImpl::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} /* kurento */
<|endoftext|>
|
<commit_before>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <math.h>
#define F(i, a, b) for(int i = a; i <= b; i++)
#define FB(i, a, b) for(int i = a; i >= b; i--)
#define MAX3(a, b, c) (a>b?a:b)>c?(a>b?a:b):c
#define MAXDP 100001
#define maxLen 100001
typedef int entry_type;
using namespace std;
class Queue{
public:
Queue(){
begin = 0;
end = 0;
length = 0;
entry_array = new entry_type [maxLen];
}
int append( entry_type entry ){
if( !full() ){
entry_array[end] = entry;
if( end <= maxLen-2 ){
end++;
}
else{
end = 0;
}
length++;
return 0;
}
else{
cerr<<"error: appending: full Queue! can't append anymore!\n";
return 1;
}
}
int serve(){
if( !empty() ){
if( begin <= maxLen-2 ){
begin++;
}
else{
begin = 0;
}
length--;
return 0;
}
else{
cerr<<"error: serving: empty Queue!\n";
return 1;
}
}
int retrieve( entry_type *ret ){
if( !empty() ){
* ret = entry_array[begin];
return 0;
}
else{
cerr<<"error: retrieving: empty Queue!\n";
return 1;
}
}
bool full(){
if( length >= maxLen ){
return true;
}
else{
return false;
}
}
bool empty(){
if( length <= 0 ){
return true;
}
else{
return false;
}
}
int clear(){
length = 0;
begin = 0;
end = 0;
return 0;
}
int size(){
return length;
}
private:
entry_type * entry_array ;
int length;
int begin;
int end;
};
class Stack{
public:
Stack(){
length = 0;
entry_array = new entry_type [maxLen];
}
int push( entry_type entry ){
if( !full() ){
entry_array[length] = entry;
length++;
return 0;
}
else{
cerr<<"error: pushing: full Stack! can't push anymore!\n";
return 1;
}
}
int pop(){
if( !empty() ){
length--;
return 0;
}
else{
cerr<<"error: popping: empty Stack!\n";
return 1;
}
}
int top( entry_type *ret ){
if( !empty() ){
* ret = entry_array[length-1];
return 0;
}
else{
cerr<<"error: topping: empty Stack!\n";
return 1;
}
}
bool full(){
if( length >= maxLen ){
return true;
}
else{
return false;
}
}
bool empty(){
if( length <= 0 ){
return true;
}
else{
return false;
}
}
int clear(){
length = 0;
return 0;
}
int size(){
return length;
}
private:
entry_type * entry_array ;
int length;
};
int main()
{
Stack st = Stack();
int tmp = 0;
if( !st.top(&tmp) ){
cout << "top: " << tmp << endl;
}
if( !st.pop() ){
cout << "pop " << endl;
}
if( !st.push(3) ){
cout << "push: " << 3 << endl;
}
if( !st.top(&tmp) ){
cout << "top: " << tmp << endl;
}
if( !st.push(5) ){
cout << "push: " << 5 << endl;
}
if( !st.top(&tmp) ){
cout << "top: " << tmp << endl;
}
if( !st.clear() ){
cout << "clear: " << endl;
}
if( !st.top(&tmp) ){
cout << "top: " << tmp << endl;
}
cout << endl;
Queue qt = Queue();
if( !qt.retrieve(&tmp) ){
cout << "retrieve: " << tmp << endl;
}
if( !qt.serve() ){
cout << "serve " << endl;
}
if( !qt.append(3) ){
cout << "append: " << 3 << endl;
}
if( !qt.retrieve(&tmp) ){
cout << "retrieve: " << tmp << endl;
}
if( !qt.append(5) ){
cout << "append: " << 5 << endl;
}
if( !qt.retrieve(&tmp) ){
cout << "retrieve: " << tmp << endl;
}
if( !qt.serve() ){
cout << "serve " << endl;
}
if( !qt.retrieve(&tmp) ){
cout << "retrieve: " << tmp << endl;
}
if( !qt.clear() ){
cout << "clear: " << endl;
}
if( !qt.retrieve(&tmp) ){
cout << "retrieve: " << tmp << endl;
}
system("pause");
return 0;
}
<commit_msg>Update Queue.cpp<commit_after>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <math.h>
#define F(i, a, b) for(int i = a; i <= b; i++)
#define FB(i, a, b) for(int i = a; i >= b; i--)
#define MAX3(a, b, c) (a>b?a:b)>c?(a>b?a:b):c
#define MAXDP 100001
#define maxLen 100001
typedef int entry_type;
using namespace std;
class Queue{
public:
Queue(){
begin = 0;
end = 0;
length = 0;
entry_array = new entry_type [maxLen];
}
int next(int ret){
if( ret <= maxLen-2 ){
ret++;
}
else{
ret = 0;
}
return ret;
}
int append( entry_type entry ){
if( !full() ){
entry_array[end] = entry;
end = next(end);
length++;
return 0;
}
else{
cerr<<"error: appending: full Queue! can't append anymore!\n";
return 1;
}
}
int serve(){
if( !empty() ){
begin = next(begin);
length--;
return 0;
}
else{
cerr<<"error: serving: empty Queue!\n";
return 1;
}
}
int retrieve( entry_type *ret ){
if( !empty() ){
* ret = entry_array[begin];
return 0;
}
else{
cerr<<"error: retrieving: empty Queue!\n";
return 1;
}
}
bool full(){
if( length >= maxLen ){
return true;
}
else{
return false;
}
}
bool empty(){
if( length <= 0 ){
return true;
}
else{
return false;
}
}
int clear(){
length = 0;
begin = 0;
end = 0;
return 0;
}
int size(){
return length;
}
private:
entry_type * entry_array ;
int length;
int begin;
int end;
};
class Stack{
public:
Stack(){
length = 0;
entry_array = new entry_type [maxLen];
}
int push( entry_type entry ){
if( !full() ){
entry_array[length] = entry;
length++;
return 0;
}
else{
cerr<<"error: pushing: full Stack! can't push anymore!\n";
return 1;
}
}
int pop(){
if( !empty() ){
length--;
return 0;
}
else{
cerr<<"error: popping: empty Stack!\n";
return 1;
}
}
int top( entry_type *ret ){
if( !empty() ){
* ret = entry_array[length-1];
return 0;
}
else{
cerr<<"error: topping: empty Stack!\n";
return 1;
}
}
bool full(){
if( length >= maxLen ){
return true;
}
else{
return false;
}
}
bool empty(){
if( length <= 0 ){
return true;
}
else{
return false;
}
}
int clear(){
length = 0;
return 0;
}
int size(){
return length;
}
private:
entry_type * entry_array ;
int length;
};
int main()
{
Stack st = Stack();
int tmp = 0;
if( !st.top(&tmp) ){
cout << "top: " << tmp << endl;
}
if( !st.pop() ){
cout << "pop " << endl;
}
if( !st.push(3) ){
cout << "push: " << 3 << endl;
}
if( !st.top(&tmp) ){
cout << "top: " << tmp << endl;
}
if( !st.push(5) ){
cout << "push: " << 5 << endl;
}
if( !st.top(&tmp) ){
cout << "top: " << tmp << endl;
}
if( !st.clear() ){
cout << "clear: " << endl;
}
if( !st.top(&tmp) ){
cout << "top: " << tmp << endl;
}
cout << endl;
Queue qt = Queue();
if( !qt.retrieve(&tmp) ){
cout << "retrieve: " << tmp << endl;
}
if( !qt.serve() ){
cout << "serve " << endl;
}
if( !qt.append(3) ){
cout << "append: " << 3 << endl;
}
if( !qt.retrieve(&tmp) ){
cout << "retrieve: " << tmp << endl;
}
if( !qt.append(5) ){
cout << "append: " << 5 << endl;
}
if( !qt.retrieve(&tmp) ){
cout << "retrieve: " << tmp << endl;
}
if( !qt.serve() ){
cout << "serve " << endl;
}
if( !qt.retrieve(&tmp) ){
cout << "retrieve: " << tmp << endl;
}
if( !qt.clear() ){
cout << "clear: " << endl;
}
if( !qt.retrieve(&tmp) ){
cout << "retrieve: " << tmp << endl;
}
system("pause");
return 0;
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <iostream>
#include <cmath>
#include "common.h"
#include GLUT_INCLUDE
#include "Decimate.h"
#include "Array3D.h"
static inline void drawVert(const Isosurface& surface, const Point3D& p1, const Point3D& p2, float isolevel)
{
float v1 = p1.value;
float v2 = p2.value;
float x, y, z;
if (v2 == v1) {
x = (p1.x + p2.x) / 2.0f;
y = (p1.y + p2.y) / 2.0f;
z = (p1.z + p2.z) / 2.0f;
} else {
/*
<----+-----+---+----->
v1 | v2
isolevel
<----+-----+---+----->
0 | 1
interp
*/
// interp == 0: vert should be at p1
// interp == 1: vert should be at p2
float interp = (isolevel - v1) / (v2 - v1);
float oneMinusInterp = 1 - interp;
x = p1.x * oneMinusInterp + p2.x * interp;
y = p1.y * oneMinusInterp + p2.y * interp;
z = p1.z * oneMinusInterp + p2.z * interp;
}
Vector3D normal = surface.gradientAt(x, y, z);
glNormal3f(normal.x, normal.y, normal.z);
glVertex3f(x, y, z);
}
static void drawTetrahedron(const Isosurface& surface, const Point3D p[4], float isolevel)
{
/*
Tetrahedron layout:
0
*
/|
/ |
3 *-----* 1
\ | /
\|/
*
2
*/
unsigned char index = 0;
for (int i = 0; i < 4; ++i)
if (p[i].value < isolevel)
index |= (1 << i);
switch (index) {
// we don't do anything if everyone is inside or outside
case 0x00:
case 0x0F:
break;
// only vert 0 is inside
case 0x01:
drawVert(surface, p[0], p[1], isolevel);
drawVert(surface, p[0], p[3], isolevel);
drawVert(surface, p[0], p[2], isolevel);
break;
// only vert 1 is inside
case 0x02:
drawVert(surface, p[1], p[0], isolevel);
drawVert(surface, p[1], p[2], isolevel);
drawVert(surface, p[1], p[3], isolevel);
break;
// only vert 2 is inside
case 0x04:
drawVert(surface, p[2], p[0], isolevel);
drawVert(surface, p[2], p[3], isolevel);
drawVert(surface, p[2], p[1], isolevel);
break;
// only vert 3 is inside
case 0x08:
drawVert(surface, p[3], p[1], isolevel);
drawVert(surface, p[3], p[2], isolevel);
drawVert(surface, p[3], p[0], isolevel);
break;
// verts 0, 1 are inside
case 0x03:
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[2], p[0], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[2], p[0], isolevel);
drawVert(surface, p[2], p[1], isolevel);
drawVert(surface, p[1], p[3], isolevel);
break;
// verts 0, 2 are inside
case 0x05:
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[1], p[2], isolevel);
drawVert(surface, p[1], p[0], isolevel);
drawVert(surface, p[1], p[2], isolevel);
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[2], p[3], isolevel);
break;
// verts 0, 3 are inside
case 0x09:
drawVert(surface, p[0], p[1], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[0], p[2], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[3], p[2], isolevel);
drawVert(surface, p[0], p[2], isolevel);
break;
// verts 1, 2 are inside
case 0x06:
drawVert(surface, p[0], p[1], isolevel);
drawVert(surface, p[0], p[2], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[0], p[2], isolevel);
drawVert(surface, p[3], p[2], isolevel);
break;
// verts 2, 3 are inside
case 0x0C:
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[2], p[0], isolevel);
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[2], p[0], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[2], p[1], isolevel);
break;
// verts 1, 3 are inside
case 0x0A:
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[1], p[0], isolevel);
drawVert(surface, p[1], p[2], isolevel);
drawVert(surface, p[1], p[2], isolevel);
drawVert(surface, p[2], p[3], isolevel);
drawVert(surface, p[3], p[0], isolevel);
break;
// verts 0, 1, 2 are inside
case 0x07:
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[3], p[2], isolevel);
drawVert(surface, p[3], p[1], isolevel);
break;
// verts 0, 1, 3 are inside
case 0x0B:
drawVert(surface, p[2], p[1], isolevel);
drawVert(surface, p[2], p[3], isolevel);
drawVert(surface, p[2], p[0], isolevel);
break;
// verts 0, 2, 3 are inside
case 0x0D:
drawVert(surface, p[1], p[0], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[1], p[2], isolevel);
break;
// verts 1, 2, 3 are inside
case 0x0E:
drawVert(surface, p[0], p[1], isolevel);
drawVert(surface, p[0], p[2], isolevel);
drawVert(surface, p[0], p[3], isolevel);
break;
// what is this I don't even
default:
assert(false);
}
}
void decimate(const Isosurface& surface,
float xMin, float xMax,
float yMin, float yMax,
float zMin, float zMax,
float isolevel,
std::size_t resolution) // resolution indicates # of cubes
{
std::size_t pointRes = resolution + 1; // indicates the # of points per side
float xrange = xMax - xMin;
float yrange = yMax - yMin;
float zrange = zMax - zMin;
Array3D<float> grid(pointRes, pointRes, pointRes);
for (std::size_t i = 0; i <= resolution; ++i) {
float x = (float)i/resolution * xrange + xMin;
for (std::size_t j = 0; j <= resolution; ++j) {
float y = (float)j/resolution * yrange + yMin;
for (std::size_t k = 0; k <= resolution; ++k) {
float z = (float)k/resolution * zrange + zMin;
float value = surface.valueAt(x, y, z);
grid.set(i, j, k, value);
}
}
}
glBegin(GL_TRIANGLES);
for (std::size_t i = 0; i < resolution; ++i) {
float x1 = (float)i/resolution * xrange + xMin;
float x2 = (float)(i+1)/resolution * xrange + xMin;
for (std::size_t j = 0; j < resolution; ++j) {
float y1 = (float)j/resolution * yrange + yMin;
float y2 = (float)(j+1)/resolution * yrange + yMin;
for (std::size_t k = 0; k < resolution; ++k) {
float z1 = (float)k/resolution * zrange + zMin;
float z2 = (float)(k+1)/resolution * zrange + zMin;
/*
Coordinates:
z
|
|___ y
/
/
x
Cube layout:
4-------7
/| /|
/ | / |
5-------6 |
| 0----|--3
| / | /
|/ |/
1-------2
Tetrahedrons are:
0, 7, 3, 2
0, 7, 2, 6
0, 4, 6, 7
0, 6, 1, 2
0, 6, 1, 4
5, 6, 1, 4
*/
const Point3D v[8] = {
{x1, y1, z1, grid.get(i, j, k )},
{x2, y1, z1, grid.get(i + 1, j, k )},
{x2, y2, z1, grid.get(i + 1, j + 1, k )},
{x1, y2, z1, grid.get(i, j + 1, k )},
{x1, y1, z2, grid.get(i, j, k + 1)},
{x2, y1, z2, grid.get(i + 1, j, k + 1)},
{x2, y2, z2, grid.get(i + 1, j + 1, k + 1)},
{x1, y2, z2, grid.get(i, j + 1, k + 1)}
};
const Point3D tetrahedra[6][4] = {
{ v[0], v[7], v[3], v[2] },
{ v[0], v[7], v[2], v[6] },
{ v[0], v[4], v[7], v[6] },
{ v[0], v[1], v[6], v[2] },
{ v[0], v[4], v[6], v[1] },
{ v[5], v[1], v[6], v[4] }
};
for (int t = 0; t < 6; ++t)
drawTetrahedron(surface, tetrahedra[t], isolevel);
}
}
}
glEnd();
}
<commit_msg>Fix an ASCII diagram<commit_after>#include <cassert>
#include <iostream>
#include <cmath>
#include "common.h"
#include GLUT_INCLUDE
#include "Decimate.h"
#include "Array3D.h"
static inline void drawVert(const Isosurface& surface, const Point3D& p1, const Point3D& p2, float isolevel)
{
float v1 = p1.value;
float v2 = p2.value;
float x, y, z;
if (v2 == v1) {
x = (p1.x + p2.x) / 2.0f;
y = (p1.y + p2.y) / 2.0f;
z = (p1.z + p2.z) / 2.0f;
} else {
/*
<----+-----+---+----->
v1 | v2
isolevel
<----+-----+---+----->
0 | 1
interp
*/
// interp == 0: vert should be at p1
// interp == 1: vert should be at p2
float interp = (isolevel - v1) / (v2 - v1);
float oneMinusInterp = 1 - interp;
x = p1.x * oneMinusInterp + p2.x * interp;
y = p1.y * oneMinusInterp + p2.y * interp;
z = p1.z * oneMinusInterp + p2.z * interp;
}
Vector3D normal = surface.gradientAt(x, y, z);
glNormal3f(normal.x, normal.y, normal.z);
glVertex3f(x, y, z);
}
static void drawTetrahedron(const Isosurface& surface, const Point3D p[4], float isolevel)
{
/*
Tetrahedron layout:
0
*
/|\
/ | \
3 *-----* 1
\ | /
\|/
*
2
*/
unsigned char index = 0;
for (int i = 0; i < 4; ++i)
if (p[i].value < isolevel)
index |= (1 << i);
switch (index) {
// we don't do anything if everyone is inside or outside
case 0x00:
case 0x0F:
break;
// only vert 0 is inside
case 0x01:
drawVert(surface, p[0], p[1], isolevel);
drawVert(surface, p[0], p[3], isolevel);
drawVert(surface, p[0], p[2], isolevel);
break;
// only vert 1 is inside
case 0x02:
drawVert(surface, p[1], p[0], isolevel);
drawVert(surface, p[1], p[2], isolevel);
drawVert(surface, p[1], p[3], isolevel);
break;
// only vert 2 is inside
case 0x04:
drawVert(surface, p[2], p[0], isolevel);
drawVert(surface, p[2], p[3], isolevel);
drawVert(surface, p[2], p[1], isolevel);
break;
// only vert 3 is inside
case 0x08:
drawVert(surface, p[3], p[1], isolevel);
drawVert(surface, p[3], p[2], isolevel);
drawVert(surface, p[3], p[0], isolevel);
break;
// verts 0, 1 are inside
case 0x03:
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[2], p[0], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[2], p[0], isolevel);
drawVert(surface, p[2], p[1], isolevel);
drawVert(surface, p[1], p[3], isolevel);
break;
// verts 0, 2 are inside
case 0x05:
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[1], p[2], isolevel);
drawVert(surface, p[1], p[0], isolevel);
drawVert(surface, p[1], p[2], isolevel);
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[2], p[3], isolevel);
break;
// verts 0, 3 are inside
case 0x09:
drawVert(surface, p[0], p[1], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[0], p[2], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[3], p[2], isolevel);
drawVert(surface, p[0], p[2], isolevel);
break;
// verts 1, 2 are inside
case 0x06:
drawVert(surface, p[0], p[1], isolevel);
drawVert(surface, p[0], p[2], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[0], p[2], isolevel);
drawVert(surface, p[3], p[2], isolevel);
break;
// verts 2, 3 are inside
case 0x0C:
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[2], p[0], isolevel);
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[2], p[0], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[2], p[1], isolevel);
break;
// verts 1, 3 are inside
case 0x0A:
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[1], p[0], isolevel);
drawVert(surface, p[1], p[2], isolevel);
drawVert(surface, p[1], p[2], isolevel);
drawVert(surface, p[2], p[3], isolevel);
drawVert(surface, p[3], p[0], isolevel);
break;
// verts 0, 1, 2 are inside
case 0x07:
drawVert(surface, p[3], p[0], isolevel);
drawVert(surface, p[3], p[2], isolevel);
drawVert(surface, p[3], p[1], isolevel);
break;
// verts 0, 1, 3 are inside
case 0x0B:
drawVert(surface, p[2], p[1], isolevel);
drawVert(surface, p[2], p[3], isolevel);
drawVert(surface, p[2], p[0], isolevel);
break;
// verts 0, 2, 3 are inside
case 0x0D:
drawVert(surface, p[1], p[0], isolevel);
drawVert(surface, p[1], p[3], isolevel);
drawVert(surface, p[1], p[2], isolevel);
break;
// verts 1, 2, 3 are inside
case 0x0E:
drawVert(surface, p[0], p[1], isolevel);
drawVert(surface, p[0], p[2], isolevel);
drawVert(surface, p[0], p[3], isolevel);
break;
// what is this I don't even
default:
assert(false);
}
}
void decimate(const Isosurface& surface,
float xMin, float xMax,
float yMin, float yMax,
float zMin, float zMax,
float isolevel,
std::size_t resolution) // resolution indicates # of cubes
{
std::size_t pointRes = resolution + 1; // indicates the # of points per side
float xrange = xMax - xMin;
float yrange = yMax - yMin;
float zrange = zMax - zMin;
Array3D<float> grid(pointRes, pointRes, pointRes);
for (std::size_t i = 0; i <= resolution; ++i) {
float x = (float)i/resolution * xrange + xMin;
for (std::size_t j = 0; j <= resolution; ++j) {
float y = (float)j/resolution * yrange + yMin;
for (std::size_t k = 0; k <= resolution; ++k) {
float z = (float)k/resolution * zrange + zMin;
float value = surface.valueAt(x, y, z);
grid.set(i, j, k, value);
}
}
}
glBegin(GL_TRIANGLES);
for (std::size_t i = 0; i < resolution; ++i) {
float x1 = (float)i/resolution * xrange + xMin;
float x2 = (float)(i+1)/resolution * xrange + xMin;
for (std::size_t j = 0; j < resolution; ++j) {
float y1 = (float)j/resolution * yrange + yMin;
float y2 = (float)(j+1)/resolution * yrange + yMin;
for (std::size_t k = 0; k < resolution; ++k) {
float z1 = (float)k/resolution * zrange + zMin;
float z2 = (float)(k+1)/resolution * zrange + zMin;
/*
Coordinates:
z
|
|___ y
/
/
x
Cube layout:
4-------7
/| /|
/ | / |
5-------6 |
| 0----|--3
| / | /
|/ |/
1-------2
Tetrahedrons are:
0, 7, 3, 2
0, 7, 2, 6
0, 4, 6, 7
0, 6, 1, 2
0, 6, 1, 4
5, 6, 1, 4
*/
const Point3D v[8] = {
{x1, y1, z1, grid.get(i, j, k )},
{x2, y1, z1, grid.get(i + 1, j, k )},
{x2, y2, z1, grid.get(i + 1, j + 1, k )},
{x1, y2, z1, grid.get(i, j + 1, k )},
{x1, y1, z2, grid.get(i, j, k + 1)},
{x2, y1, z2, grid.get(i + 1, j, k + 1)},
{x2, y2, z2, grid.get(i + 1, j + 1, k + 1)},
{x1, y2, z2, grid.get(i, j + 1, k + 1)}
};
const Point3D tetrahedra[6][4] = {
{ v[0], v[7], v[3], v[2] },
{ v[0], v[7], v[2], v[6] },
{ v[0], v[4], v[7], v[6] },
{ v[0], v[1], v[6], v[2] },
{ v[0], v[4], v[6], v[1] },
{ v[5], v[1], v[6], v[4] }
};
for (int t = 0; t < 6; ++t)
drawTetrahedron(surface, tetrahedra[t], isolevel);
}
}
}
glEnd();
}
<|endoftext|>
|
<commit_before>/*
* test_sphere_advection.cpp
*
* Created on: 3 Apr 2018
* Author: martin
*/
#ifndef SWEET_GUI
#define SWEET_GUI 1
#endif
#include <sweet/sphere/SphereData.hpp>
#if SWEET_GUI
#include "sweet/VisSweet.hpp"
#endif
#include <benchmarks_sphere/SWESphereBenchmarksCombined.hpp>
#include <sweet/SimulationVariables.hpp>
#include <sweet/sphere/SphereOperators.hpp>
#include <sweet/Convert_SphereData_To_PlaneData.hpp>
#include <sweet/Convert_SphereDataPhysical_To_PlaneData.hpp>
#include "../programs/advection_sphere/Adv_Sphere_TimeSteppers.hpp"
// Sphere data config
SphereDataConfig sphereDataConfigInstance;
SphereDataConfig *sphereDataConfig = &sphereDataConfigInstance;
#if SWEET_GUI
PlaneDataConfig planeDataConfigInstance;
PlaneDataConfig *planeDataConfig = &planeDataConfigInstance;
#endif
SimulationVariables simVars;
class SimulationInstance
{
public:
SphereData prog_h;
SphereData prog_h0; // at t0
SphereData prog_vort, prog_div;
Adv_Sphere_TimeSteppers timeSteppers;
SphereOperators op;
/*
* LMax error to h0
*/
double max_error_h0;
/*
* RMS error to h0
*/
double rms_error_h0;
#if SWEET_GUI
PlaneData viz_plane_data;
int render_primitive_id = 1;
#endif
SWESphereBenchmarksCombined sphereBenchmarksCombined;
public:
SimulationInstance() :
prog_h(sphereDataConfig),
prog_h0(sphereDataConfig),
prog_vort(sphereDataConfig),
prog_div(sphereDataConfig),
op(sphereDataConfig, simVars.sim.sphere_radius)
#if SWEET_GUI
,
viz_plane_data(planeDataConfig)
#endif
{
reset();
}
void reset()
{
simVars.reset();
sphereBenchmarksCombined.setup(simVars, op);
sphereBenchmarksCombined.setupInitialConditions(prog_h, prog_vort, prog_div);
prog_h0 = prog_h;
// setup sphereDataconfig instance again
sphereDataConfigInstance.setupAuto(simVars.disc.space_res_physical, simVars.disc.space_res_spectral, simVars.misc.reuse_spectral_transformation_plans);
timeSteppers.setup(simVars.disc.timestepping_method, op, simVars);
//simVars.outputConfig();
}
void run_timestep()
{
if (simVars.timecontrol.current_simulation_time + simVars.timecontrol.current_timestep_size > simVars.timecontrol.max_simulation_time)
simVars.timecontrol.current_timestep_size = simVars.timecontrol.max_simulation_time - simVars.timecontrol.current_simulation_time;
timeSteppers.master->run_timestep(
prog_h, prog_vort, prog_div,
simVars.timecontrol.current_timestep_size,
simVars.timecontrol.current_simulation_time
);
double dt = simVars.timecontrol.current_timestep_size;
// advance in time
simVars.timecontrol.current_simulation_time += dt;
simVars.timecontrol.current_timestep_nr++;
if (simVars.misc.verbosity >= 10)
std::cout << simVars.timecontrol.current_timestep_nr << ": " << simVars.timecontrol.current_simulation_time/(60*60*24.0) << std::endl;
max_error_h0 = (prog_h0-prog_h).physical_reduce_max_abs();
rms_error_h0 = (prog_h0-prog_h).physical_reduce_rms();
}
void compute_error()
{
#if 0
double t = simVars.timecontrol.current_simulation_time;
SphereData prog_testh(sphereDataConfig);
prog_testh.physical_update_lambda_array_indices(
[&](int i, int j, double &io_data)
{
double x = (((double)i)/(double)simVars.disc.space_res_physical[0])*simVars.sim.domain_size[0];
double y = (((double)j)/(double)simVars.disc.space_res_physical[1])*simVars.sim.domain_size[1];
x -= param_velocity_u*t;
y -= param_velocity_v*t;
while (x < 0)
x += simVars.sim.domain_size[0];
while (y < 0)
y += simVars.sim.domain_size[1];
x = std::fmod(x, simVars.sim.domain_size[0]);
y = std::fmod(y, simVars.sim.domain_size[1]);
io_data = SWESphereBenchmarks::return_h(simVars, x, y);
}
);
std::cout << "Lmax Error: " << (prog_h-prog_testh).reduce_maxAbs() << std::endl;
#endif
}
bool should_quit()
{
if (simVars.timecontrol.max_timesteps_nr != -1 && simVars.timecontrol.max_timesteps_nr <= simVars.timecontrol.current_timestep_nr)
return true;
double diff = std::abs(simVars.timecontrol.max_simulation_time - simVars.timecontrol.current_simulation_time);
if ( simVars.timecontrol.max_simulation_time != -1 &&
(
simVars.timecontrol.max_simulation_time <= simVars.timecontrol.current_simulation_time ||
diff/simVars.timecontrol.max_simulation_time < 1e-11 // avoid numerical issues in time stepping if current time step is 1e-14 smaller than max time step
)
)
return true;
return false;
}
#if SWEET_GUI
/**
* postprocessing of frame: do time stepping
*/
void vis_post_frame_processing(int i_num_iterations)
{
if (simVars.timecontrol.run_simulation_timesteps)
for (int i = 0; i < i_num_iterations && !should_quit(); i++)
run_timestep();
compute_error();
}
void vis_get_vis_data_array(
const PlaneData **o_dataArray,
double *o_aspect_ratio,
int *o_render_primitive_id,
void **o_bogus_data
)
{
*o_render_primitive_id = render_primitive_id;
*o_bogus_data = sphereDataConfig;
int id = simVars.misc.vis_id % 5;
switch (id)
{
case 0:
viz_plane_data = Convert_SphereData_To_PlaneData::physical_convert(prog_h, planeDataConfig);
break;
case 1:
{
SphereDataPhysical u(sphereDataConfig);
SphereDataPhysical v(sphereDataConfig);
// op.robert_vortdiv_to_uv(prog_vort, prog_div, u, v);
op.vortdiv_to_uv(prog_vort, prog_div, u, v);
viz_plane_data = Convert_SphereDataPhysical_To_PlaneData::physical_convert(u, planeDataConfig);
}
break;
case 2:
{
SphereDataPhysical u(sphereDataConfig);
SphereDataPhysical v(sphereDataConfig);
// op.robert_vortdiv_to_uv(prog_vort, prog_div, u, v);
op.vortdiv_to_uv(prog_vort, prog_div, u, v);
viz_plane_data = Convert_SphereDataPhysical_To_PlaneData::physical_convert(v, planeDataConfig);
}
break;
case 3:
viz_plane_data = Convert_SphereData_To_PlaneData::physical_convert(prog_vort, planeDataConfig);
break;
case 4:
viz_plane_data = Convert_SphereData_To_PlaneData::physical_convert(prog_div, planeDataConfig);
break;
}
*o_dataArray = &viz_plane_data;
*o_aspect_ratio = 0.5;
}
const char* vis_get_status_string()
{
const char* description = "";
int id = simVars.misc.vis_id % 3;
switch (id)
{
default:
case 0:
description = "H";
break;
case 1:
description = "vort";
break;
case 2:
description = "div";
break;
}
static char title_string[2048];
//sprintf(title_string, "Time (days): %f (%.2f d), Timestep: %i, timestep size: %.14e, Vis: %s, Mass: %.14e, Energy: %.14e, Potential Entrophy: %.14e",
sprintf(title_string,
#if SWEET_MPI
"Rank %i - "
#endif
"Time: %f (%.2f d), k: %i, dt: %.3e, Vis: %s, TMass: %.6e, TEnergy: %.6e, PotEnstrophy: %.6e, MaxVal: %.6e, MinVal: %.6e ",
#if SWEET_MPI
mpi_rank,
#endif
simVars.timecontrol.current_simulation_time,
simVars.timecontrol.current_simulation_time/(60.0*60.0*24.0),
simVars.timecontrol.current_timestep_nr,
simVars.timecontrol.current_timestep_size,
description,
simVars.diag.total_mass,
simVars.diag.total_energy,
simVars.diag.total_potential_enstrophy,
viz_plane_data.reduce_max(),
viz_plane_data.reduce_min()
);
return title_string;
}
void vis_pause()
{
simVars.timecontrol.run_simulation_timesteps = !simVars.timecontrol.run_simulation_timesteps;
}
void vis_keypress(int i_key)
{
switch(i_key)
{
case 'v':
simVars.misc.vis_id++;
break;
case 'V':
simVars.misc.vis_id--;
break;
case 'b':
render_primitive_id = (render_primitive_id + 1) % 2;
break;
}
}
#endif
};
int main(int i_argc, char *i_argv[])
{
if (!simVars.setupFromMainParameters(i_argc, i_argv))
{
std::cout << std::endl;
return -1;
}
int initial_spectral_modes = simVars.disc.space_res_spectral[0];
if (simVars.timecontrol.current_timestep_size < 0)
FatalError("Timestep size not set");
SphereDataSemiLagrangian::alpha() = simVars.benchmark.advection_rotation_angle;
int max_modes = 256;
if (simVars.disc.timestepping_order == 1)
max_modes = 512;
else if (simVars.disc.timestepping_order == 2)
max_modes = 256;
double prev_max_error = -1;
for (int i = initial_spectral_modes; i <= max_modes; i *= 2)
{
simVars.timecontrol.current_timestep_size *= 0.5;
if (simVars.disc.timestepping_method == "na_sl")
{
simVars.disc.space_res_spectral[0] = i;
simVars.disc.space_res_spectral[1] = i;
simVars.disc.space_res_physical[0] = 2*i;
simVars.disc.space_res_physical[1] = i;
}
else
{
simVars.disc.space_res_spectral[0] = initial_spectral_modes;
simVars.disc.space_res_spectral[1] = initial_spectral_modes;
simVars.disc.space_res_physical[0] = 0;
simVars.disc.space_res_physical[1] = 0;
}
sphereDataConfigInstance.setupAuto(simVars.disc.space_res_physical, simVars.disc.space_res_spectral, simVars.misc.reuse_spectral_transformation_plans);
std::cout << "Testing with " << sphereDataConfigInstance.getUniqueIDString() << std::endl;
std::cout << "Testing with dt=" << simVars.timecontrol.current_timestep_size << std::endl;
SimulationInstance simulation;
#if SWEET_GUI
if (simVars.misc.gui_enabled)
{
planeDataConfigInstance.setupAutoSpectralSpace(
simVars.disc.space_res_physical,
simVars.misc.reuse_spectral_transformation_plans,
simVars.misc.reuse_spectral_transformation_plans
);
VisSweet<SimulationInstance> visSweet(&simulation);
return 0;
}
else
#endif
{
// simulation.reset();
while (!simulation.should_quit())
simulation.run_timestep();
std::cout << "Error compared to initial condition" << std::endl;
std::cout << "Lmax error: " << simulation.max_error_h0 << std::endl;
std::cout << "RMS error: " << simulation.rms_error_h0 << std::endl;
if (prev_max_error >= 0)
{
//double conv = (prev_max_error - simulation.max_error) / simulation.max_error;
double conv = prev_max_error / simulation.max_error_h0;
std::cout << "Convergence: " << conv << std::endl;
if (conv*1.1 < std::pow(2.0, (double)simVars.disc.timestepping_order))
FatalError("Convergence not given!");
}
if (simulation.max_error_h0 > 1e10)
FatalError("Lmax error exceeded threshold!");
prev_max_error = simulation.max_error_h0;
std::cout << "*********************************************" << std::endl;
}
}
return 0;
}
<commit_msg>fixed compile bug<commit_after>/*
* test_sphere_advection.cpp
*
* Created on: 3 Apr 2018
* Author: martin
*/
#ifndef SWEET_GUI
#define SWEET_GUI 1
#endif
#include <sweet/sphere/SphereData.hpp>
#if SWEET_GUI
#include "sweet/VisSweet.hpp"
#endif
#include <benchmarks_sphere/SWESphereBenchmarksCombined.hpp>
#include <sweet/SimulationVariables.hpp>
#include <sweet/sphere/SphereOperators.hpp>
#include <sweet/Convert_SphereData_To_PlaneData.hpp>
#include <sweet/Convert_SphereDataPhysical_To_PlaneData.hpp>
#include "../programs/advection_sphere/Adv_Sphere_TimeSteppers.hpp"
// Sphere data config
SphereDataConfig sphereDataConfigInstance;
SphereDataConfig *sphereDataConfig = &sphereDataConfigInstance;
#if SWEET_GUI
PlaneDataConfig planeDataConfigInstance;
PlaneDataConfig *planeDataConfig = &planeDataConfigInstance;
#endif
SimulationVariables simVars;
class SimulationInstance
{
public:
SphereData prog_h;
SphereData prog_h0; // at t0
SphereData prog_vort, prog_div;
Adv_Sphere_TimeSteppers timeSteppers;
SphereOperators op;
/*
* LMax error to h0
*/
double max_error_h0;
/*
* RMS error to h0
*/
double rms_error_h0;
#if SWEET_GUI
PlaneData viz_plane_data;
int render_primitive_id = 1;
#endif
SWESphereBenchmarksCombined sphereBenchmarksCombined;
public:
SimulationInstance() :
prog_h(sphereDataConfig),
prog_h0(sphereDataConfig),
prog_vort(sphereDataConfig),
prog_div(sphereDataConfig),
op(sphereDataConfig, simVars.sim.sphere_radius)
#if SWEET_GUI
,
viz_plane_data(planeDataConfig)
#endif
{
reset();
}
void reset()
{
simVars.reset();
sphereBenchmarksCombined.setup(simVars, op);
sphereBenchmarksCombined.setupInitialConditions(prog_h, prog_vort, prog_div);
prog_h0 = prog_h;
// setup sphereDataconfig instance again
sphereDataConfigInstance.setupAuto(simVars.disc.space_res_physical, simVars.disc.space_res_spectral, simVars.misc.reuse_spectral_transformation_plans);
timeSteppers.setup(simVars.disc.timestepping_method, op, simVars);
//simVars.outputConfig();
}
void run_timestep()
{
if (simVars.timecontrol.current_simulation_time + simVars.timecontrol.current_timestep_size > simVars.timecontrol.max_simulation_time)
simVars.timecontrol.current_timestep_size = simVars.timecontrol.max_simulation_time - simVars.timecontrol.current_simulation_time;
timeSteppers.master->run_timestep(
prog_h, prog_vort, prog_div,
simVars.timecontrol.current_timestep_size,
simVars.timecontrol.current_simulation_time
);
double dt = simVars.timecontrol.current_timestep_size;
// advance in time
simVars.timecontrol.current_simulation_time += dt;
simVars.timecontrol.current_timestep_nr++;
if (simVars.misc.verbosity >= 10)
std::cout << simVars.timecontrol.current_timestep_nr << ": " << simVars.timecontrol.current_simulation_time/(60*60*24.0) << std::endl;
max_error_h0 = (prog_h0-prog_h).physical_reduce_max_abs();
rms_error_h0 = (prog_h0-prog_h).physical_reduce_rms();
}
void compute_error()
{
#if 0
double t = simVars.timecontrol.current_simulation_time;
SphereData prog_testh(sphereDataConfig);
prog_testh.physical_update_lambda_array_indices(
[&](int i, int j, double &io_data)
{
double x = (((double)i)/(double)simVars.disc.space_res_physical[0])*simVars.sim.domain_size[0];
double y = (((double)j)/(double)simVars.disc.space_res_physical[1])*simVars.sim.domain_size[1];
x -= param_velocity_u*t;
y -= param_velocity_v*t;
while (x < 0)
x += simVars.sim.domain_size[0];
while (y < 0)
y += simVars.sim.domain_size[1];
x = std::fmod(x, simVars.sim.domain_size[0]);
y = std::fmod(y, simVars.sim.domain_size[1]);
io_data = SWESphereBenchmarks::return_h(simVars, x, y);
}
);
std::cout << "Lmax Error: " << (prog_h-prog_testh).reduce_maxAbs() << std::endl;
#endif
}
bool should_quit()
{
if (simVars.timecontrol.max_timesteps_nr != -1 && simVars.timecontrol.max_timesteps_nr <= simVars.timecontrol.current_timestep_nr)
return true;
double diff = std::abs(simVars.timecontrol.max_simulation_time - simVars.timecontrol.current_simulation_time);
if ( simVars.timecontrol.max_simulation_time != -1 &&
(
simVars.timecontrol.max_simulation_time <= simVars.timecontrol.current_simulation_time ||
diff/simVars.timecontrol.max_simulation_time < 1e-11 // avoid numerical issues in time stepping if current time step is 1e-14 smaller than max time step
)
)
return true;
return false;
}
#if SWEET_GUI
/**
* postprocessing of frame: do time stepping
*/
void vis_post_frame_processing(int i_num_iterations)
{
if (simVars.timecontrol.run_simulation_timesteps)
for (int i = 0; i < i_num_iterations && !should_quit(); i++)
run_timestep();
compute_error();
}
void vis_get_vis_data_array(
const PlaneData **o_dataArray,
double *o_aspect_ratio,
int *o_render_primitive_id,
void **o_bogus_data
)
{
*o_render_primitive_id = render_primitive_id;
*o_bogus_data = sphereDataConfig;
int id = simVars.misc.vis_id % 5;
switch (id)
{
case 0:
viz_plane_data = Convert_SphereData_To_PlaneData::physical_convert(prog_h, planeDataConfig);
break;
case 1:
{
SphereDataPhysical u(sphereDataConfig);
SphereDataPhysical v(sphereDataConfig);
// op.robert_vortdiv_to_uv(prog_vort, prog_div, u, v);
op.vortdiv_to_uv(prog_vort, prog_div, u, v);
viz_plane_data = Convert_SphereDataPhysical_To_PlaneData::physical_convert(u, planeDataConfig);
}
break;
case 2:
{
SphereDataPhysical u(sphereDataConfig);
SphereDataPhysical v(sphereDataConfig);
// op.robert_vortdiv_to_uv(prog_vort, prog_div, u, v);
op.vortdiv_to_uv(prog_vort, prog_div, u, v);
viz_plane_data = Convert_SphereDataPhysical_To_PlaneData::physical_convert(v, planeDataConfig);
}
break;
case 3:
viz_plane_data = Convert_SphereData_To_PlaneData::physical_convert(prog_vort, planeDataConfig);
break;
case 4:
viz_plane_data = Convert_SphereData_To_PlaneData::physical_convert(prog_div, planeDataConfig);
break;
}
*o_dataArray = &viz_plane_data;
*o_aspect_ratio = 0.5;
}
const char* vis_get_status_string()
{
const char* description = "";
int id = simVars.misc.vis_id % 3;
switch (id)
{
default:
case 0:
description = "H";
break;
case 1:
description = "vort";
break;
case 2:
description = "div";
break;
}
static char title_string[2048];
//sprintf(title_string, "Time (days): %f (%.2f d), Timestep: %i, timestep size: %.14e, Vis: %s, Mass: %.14e, Energy: %.14e, Potential Entrophy: %.14e",
sprintf(title_string,
#if SWEET_MPI
"Rank %i - "
#endif
"Time: %f (%.2f d), k: %i, dt: %.3e, Vis: %s, TMass: %.6e, TEnergy: %.6e, PotEnstrophy: %.6e, MaxVal: %.6e, MinVal: %.6e ",
#if SWEET_MPI
mpi_rank,
#endif
simVars.timecontrol.current_simulation_time,
simVars.timecontrol.current_simulation_time/(60.0*60.0*24.0),
simVars.timecontrol.current_timestep_nr,
simVars.timecontrol.current_timestep_size,
description,
simVars.diag.total_mass,
simVars.diag.total_energy,
simVars.diag.total_potential_enstrophy,
viz_plane_data.reduce_max(),
viz_plane_data.reduce_min()
);
return title_string;
}
void vis_pause()
{
simVars.timecontrol.run_simulation_timesteps = !simVars.timecontrol.run_simulation_timesteps;
}
void vis_keypress(int i_key)
{
switch(i_key)
{
case 'v':
simVars.misc.vis_id++;
break;
case 'V':
simVars.misc.vis_id--;
break;
case 'b':
render_primitive_id = (render_primitive_id + 1) % 2;
break;
}
}
#endif
};
int main(int i_argc, char *i_argv[])
{
if (!simVars.setupFromMainParameters(i_argc, i_argv))
{
std::cout << std::endl;
return -1;
}
int initial_spectral_modes = simVars.disc.space_res_spectral[0];
if (simVars.timecontrol.current_timestep_size < 0)
FatalError("Timestep size not set");
SphereDataSemiLagrangian::alpha() = simVars.benchmark.sphere_advection_rotation_angle;
int max_modes = 256;
if (simVars.disc.timestepping_order == 1)
max_modes = 512;
else if (simVars.disc.timestepping_order == 2)
max_modes = 256;
double prev_max_error = -1;
for (int i = initial_spectral_modes; i <= max_modes; i *= 2)
{
simVars.timecontrol.current_timestep_size *= 0.5;
if (simVars.disc.timestepping_method == "na_sl")
{
simVars.disc.space_res_spectral[0] = i;
simVars.disc.space_res_spectral[1] = i;
simVars.disc.space_res_physical[0] = 2*i;
simVars.disc.space_res_physical[1] = i;
}
else
{
simVars.disc.space_res_spectral[0] = initial_spectral_modes;
simVars.disc.space_res_spectral[1] = initial_spectral_modes;
simVars.disc.space_res_physical[0] = 0;
simVars.disc.space_res_physical[1] = 0;
}
sphereDataConfigInstance.setupAuto(simVars.disc.space_res_physical, simVars.disc.space_res_spectral, simVars.misc.reuse_spectral_transformation_plans);
std::cout << "Testing with " << sphereDataConfigInstance.getUniqueIDString() << std::endl;
std::cout << "Testing with dt=" << simVars.timecontrol.current_timestep_size << std::endl;
SimulationInstance simulation;
#if SWEET_GUI
if (simVars.misc.gui_enabled)
{
planeDataConfigInstance.setupAutoSpectralSpace(
simVars.disc.space_res_physical,
simVars.misc.reuse_spectral_transformation_plans,
simVars.misc.reuse_spectral_transformation_plans
);
VisSweet<SimulationInstance> visSweet(&simulation);
return 0;
}
else
#endif
{
// simulation.reset();
while (!simulation.should_quit())
simulation.run_timestep();
std::cout << "Error compared to initial condition" << std::endl;
std::cout << "Lmax error: " << simulation.max_error_h0 << std::endl;
std::cout << "RMS error: " << simulation.rms_error_h0 << std::endl;
if (prev_max_error >= 0)
{
//double conv = (prev_max_error - simulation.max_error) / simulation.max_error;
double conv = prev_max_error / simulation.max_error_h0;
std::cout << "Convergence: " << conv << std::endl;
if (conv*1.1 < std::pow(2.0, (double)simVars.disc.timestepping_order))
FatalError("Convergence not given!");
}
if (simulation.max_error_h0 > 1e10)
FatalError("Lmax error exceeded threshold!");
prev_max_error = simulation.max_error_h0;
std::cout << "*********************************************" << std::endl;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2011 Gregory Szorc
//
// 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 <zippylog/persisted_state_manager.hpp>
#include <gtest/gtest.h>
namespace zippylog {
} // namespaces
<commit_msg>start to implement tests<commit_after>// Copyright 2011 Gregory Szorc
//
// 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 <zippylog/persisted_state_manager.hpp>
#include <zippylog/platform.hpp>
#include <gtest/gtest.h>
#include <string>
using ::std::invalid_argument;
using ::std::string;
namespace zippylog {
class PersistedStateManagerTest : public ::testing::Test
{
protected:
string id;
string path;
string store_uri;
void SetUp()
{
this->id = platform::CreateUUID(true);
this->path = "test/stores/" + id;
this->store_uri = "simpledirectory://" + this->path;
ASSERT_FALSE(platform::PathIsDirectory(this->path));
ASSERT_TRUE(platform::MakeDirectory(this->path));
}
void TearDown()
{
if (platform::PathIsDirectory(this->path)) {
EXPECT_TRUE(platform::RemoveDirectoryA(this->path));
}
}
};
TEST_F(PersistedStateManagerTest, Constructor)
{
PersistedStateManagerStartParams p;
EXPECT_THROW(PersistedStateManager m(p), invalid_argument);
p.store_uri = this->store_uri;
EXPECT_NO_THROW(PersistedStateManager m(p));
}
} // namespaces
<|endoftext|>
|
<commit_before>/**
* @copyright
* ====================================================================
* Copyright (c) 2007 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
* @endcopyright
*
* @file LogMessageCallback.cpp
* @brief Implementation of the class LogMessageCallback
*/
#include "LogMessageCallback.h"
#include "JNIUtil.h"
#include "svn_time.h"
#include "svn_sorts.h"
/**
* Create a LogMessageCallback object
* @param jcallback the Java callback object.
*/
LogMessageCallback::LogMessageCallback(jobject jcallback)
{
m_callback = jcallback;
}
/**
* Destroy a LogMessageCallback object
*/
LogMessageCallback::~LogMessageCallback()
{
// The m_callback does not need to be destroyed because it is the
// passed in parameter to the Java SVNClientInterface.logMessages
// method.
}
svn_error_t *
LogMessageCallback::callback(void *baton,
svn_log_entry_t *log_entry,
apr_pool_t *pool)
{
if (baton)
return ((LogMessageCallback *)baton)->singleMessage(log_entry, pool);
return SVN_NO_ERROR;
}
/**
* Callback called for a single log message
*/
svn_error_t *
LogMessageCallback::singleMessage(svn_log_entry_t *log_entry, apr_pool_t *pool)
{
JNIEnv *env = JNIUtil::getEnv();
// The method id will not change during the time this library is
// loaded, so it can be cached.
static jmethodID sm_mid = 0;
if (sm_mid == 0)
{
jclass clazz = env->FindClass(JAVA_PACKAGE"/LogMessageCallback");
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
sm_mid = env->GetMethodID(clazz,
"singleMessage",
"([L"JAVA_PACKAGE"/ChangePath;"
"JLjava/lang/String;"
"JLjava/lang/String;J)V");
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(clazz);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
}
jclass clazzCP = env->FindClass(JAVA_PACKAGE"/ChangePath");
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
static jmethodID midCP = 0;
if (midCP == 0)
{
midCP = env->GetMethodID(clazzCP,
"<init>",
"(Ljava/lang/String;JLjava/lang/String;C)V");
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
}
apr_time_t commit_time = -1;
if (log_entry->date != NULL && *log_entry->date != '\0')
SVN_ERR(svn_time_from_cstring(&commit_time, log_entry->date, pool));
jstring jauthor = JNIUtil::makeJString(log_entry->author);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
jobjectArray jChangedPaths = NULL;
if (log_entry->changed_paths)
{
apr_array_header_t *sorted_paths;
int i;
/* Get an array of sorted hash keys. */
sorted_paths = svn_sort__hash(log_entry->changed_paths,
svn_sort_compare_items_as_paths,
pool);
jChangedPaths = env->NewObjectArray(sorted_paths->nelts,
clazzCP,
NULL);
for (i = 0; i < sorted_paths->nelts; ++i)
{
svn_sort__item_t *item = &(APR_ARRAY_IDX(sorted_paths, i,
svn_sort__item_t));
const char *path = (const char *)item->key;
svn_log_changed_path_t *log_item
= (svn_log_changed_path_t *)
apr_hash_get(log_entry->changed_paths, item->key, item->klen);
jstring jpath = JNIUtil::makeJString(path);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
jstring jcopyFromPath =
JNIUtil::makeJString(log_item->copyfrom_path);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
jlong jcopyFromRev = log_item->copyfrom_rev;
jchar jaction = log_item->action;
jobject cp = env->NewObject(clazzCP, midCP, jpath, jcopyFromRev,
jcopyFromPath, jaction);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->SetObjectArrayElement(jChangedPaths, i, cp);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(cp);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(jpath);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(jcopyFromPath);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
}
}
jstring jmessage = JNIUtil::makeJString(log_entry->message);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->CallVoidMethod(m_callback,
sm_mid,
jChangedPaths,
(jlong)log_entry->revision,
jauthor,
(jlong)commit_time,
jmessage,
(jlong)log_entry->nbr_children);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(jauthor);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(jmessage);
// No need to check for an exception here, because we return anyway.
return SVN_NO_ERROR;
}
<commit_msg>Followup to 26426: Fix compile error<commit_after>/**
* @copyright
* ====================================================================
* Copyright (c) 2007 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
* @endcopyright
*
* @file LogMessageCallback.cpp
* @brief Implementation of the class LogMessageCallback
*/
#include "LogMessageCallback.h"
#include "JNIUtil.h"
#include "svn_time.h"
#include "svn_sorts.h"
/**
* Create a LogMessageCallback object
* @param jcallback the Java callback object.
*/
LogMessageCallback::LogMessageCallback(jobject jcallback)
{
m_callback = jcallback;
}
/**
* Destroy a LogMessageCallback object
*/
LogMessageCallback::~LogMessageCallback()
{
// The m_callback does not need to be destroyed because it is the
// passed in parameter to the Java SVNClientInterface.logMessages
// method.
}
svn_error_t *
LogMessageCallback::callback(void *baton,
svn_log_entry_t *log_entry,
apr_pool_t *pool)
{
if (baton)
return ((LogMessageCallback *)baton)->singleMessage(log_entry, pool);
return SVN_NO_ERROR;
}
/**
* Callback called for a single log message
*/
svn_error_t *
LogMessageCallback::singleMessage(svn_log_entry_t *log_entry, apr_pool_t *pool)
{
JNIEnv *env = JNIUtil::getEnv();
// The method id will not change during the time this library is
// loaded, so it can be cached.
static jmethodID sm_mid = 0;
if (sm_mid == 0)
{
jclass clazz = env->FindClass(JAVA_PACKAGE"/LogMessageCallback");
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
sm_mid = env->GetMethodID(clazz,
"singleMessage",
"([L"JAVA_PACKAGE"/ChangePath;"
"JLjava/lang/String;"
"JLjava/lang/String;J)V");
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(clazz);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
}
jclass clazzCP = env->FindClass(JAVA_PACKAGE"/ChangePath");
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
static jmethodID midCP = 0;
if (midCP == 0)
{
midCP = env->GetMethodID(clazzCP,
"<init>",
"(Ljava/lang/String;JLjava/lang/String;C)V");
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
}
apr_time_t commit_time = -1;
if (log_entry->date != NULL && *log_entry->date != '\0')
SVN_ERR(svn_time_from_cstring(&commit_time, log_entry->date, pool));
jstring jauthor = JNIUtil::makeJString(log_entry->author);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
jobjectArray jChangedPaths = NULL;
if (log_entry->changed_paths)
{
apr_array_header_t *sorted_paths;
int i;
/* Get an array of sorted hash keys. */
sorted_paths = svn_sort__hash(log_entry->changed_paths,
svn_sort_compare_items_as_paths,
pool);
jChangedPaths = env->NewObjectArray(sorted_paths->nelts,
clazzCP,
NULL);
for (i = 0; i < sorted_paths->nelts; ++i)
{
svn_sort__item_t *item = &(APR_ARRAY_IDX(sorted_paths, i,
svn_sort__item_t));
const char *path = (const char *)item->key;
svn_log_changed_path_t *log_item
= (svn_log_changed_path_t *)
apr_hash_get(log_entry->changed_paths, item->key, item->klen);
jstring jpath = JNIUtil::makeJString(path);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
jstring jcopyFromPath =
JNIUtil::makeJString(log_item->copyfrom_path);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
jlong jcopyFromRev = log_item->copyfrom_rev;
jchar jaction = log_item->action;
jobject cp = env->NewObject(clazzCP, midCP, jpath, jcopyFromRev,
jcopyFromPath, jaction);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->SetObjectArrayElement(jChangedPaths, i, cp);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(cp);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(jpath);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(jcopyFromPath);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
}
}
jstring jmessage = JNIUtil::makeJString(log_entry->message);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->CallVoidMethod(m_callback,
sm_mid,
jChangedPaths,
(jlong)log_entry->revision,
jauthor,
(jlong)commit_time,
jmessage,
(jboolean)log_entry->has_children);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(jauthor);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(jmessage);
// No need to check for an exception here, because we return anyway.
return SVN_NO_ERROR;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
#include <string>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include "util/testharness.h"
#include "util/auto_roll_logger.h"
#include "rocksdb/db.h"
#include <sys/stat.h>
#include <errno.h>
using namespace std;
namespace rocksdb {
class AutoRollLoggerTest {
public:
static void InitTestDb() {
string deleteCmd = "rm -rf " + kTestDir;
ASSERT_TRUE(system(deleteCmd.c_str()) == 0);
Env::Default()->CreateDir(kTestDir);
}
void RollLogFileBySizeTest(AutoRollLogger* logger,
size_t log_max_size,
const string& log_message);
uint64_t RollLogFileByTimeTest(AutoRollLogger* logger,
size_t time,
const string& log_message);
static const string kSampleMessage;
static const string kTestDir;
static const string kLogFile;
static Env* env;
};
const string AutoRollLoggerTest::kSampleMessage(
"this is the message to be written to the log file!!");
const string AutoRollLoggerTest::kTestDir(test::TmpDir() + "/db_log_test");
const string AutoRollLoggerTest::kLogFile(test::TmpDir() + "/db_log_test/LOG");
Env* AutoRollLoggerTest::env = Env::Default();
// In this test we only want to Log some simple log message with
// no format. LogMessage() provides such a simple interface and
// avoids the [format-security] warning which occurs when you
// call Log(logger, log_message) directly.
namespace {
void LogMessage(Logger* logger, const char* message) {
Log(logger, "%s", message);
}
void LogMessage(const InfoLogLevel log_level, Logger* logger,
const char* message) {
Log(log_level, logger, "%s", message);
}
} // namespace
namespace {
void GetFileCreateTime(const std::string& fname, uint64_t* file_ctime) {
struct stat s;
if (stat(fname.c_str(), &s) != 0) {
*file_ctime = (uint64_t)0;
}
*file_ctime = static_cast<uint64_t>(s.st_ctime);
}
} // namespace
void AutoRollLoggerTest::RollLogFileBySizeTest(AutoRollLogger* logger,
size_t log_max_size,
const string& log_message) {
logger->SetInfoLogLevel(InfoLogLevel::INFO_LEVEL);
// measure the size of each message, which is supposed
// to be equal or greater than log_message.size()
LogMessage(logger, log_message.c_str());
size_t message_size = logger->GetLogFileSize();
size_t current_log_size = message_size;
// Test the cases when the log file will not be rolled.
while (current_log_size + message_size < log_max_size) {
LogMessage(logger, log_message.c_str());
current_log_size += message_size;
ASSERT_EQ(current_log_size, logger->GetLogFileSize());
}
// Now the log file will be rolled
LogMessage(logger, log_message.c_str());
// Since rotation is checked before actual logging, we need to
// trigger the rotation by logging another message.
LogMessage(logger, log_message.c_str());
ASSERT_TRUE(message_size == logger->GetLogFileSize());
}
uint64_t AutoRollLoggerTest::RollLogFileByTimeTest(
AutoRollLogger* logger, size_t time, const string& log_message) {
uint64_t expected_create_time;
uint64_t actual_create_time;
uint64_t total_log_size;
ASSERT_OK(env->GetFileSize(kLogFile, &total_log_size));
GetFileCreateTime(kLogFile, &expected_create_time);
logger->SetCallNowMicrosEveryNRecords(0);
// -- Write to the log for several times, which is supposed
// to be finished before time.
for (int i = 0; i < 10; ++i) {
LogMessage(logger, log_message.c_str());
ASSERT_OK(logger->GetStatus());
// Make sure we always write to the same log file (by
// checking the create time);
GetFileCreateTime(kLogFile, &actual_create_time);
// Also make sure the log size is increasing.
ASSERT_EQ(expected_create_time, actual_create_time);
ASSERT_GT(logger->GetLogFileSize(), total_log_size);
total_log_size = logger->GetLogFileSize();
}
// -- Make the log file expire
sleep(time);
LogMessage(logger, log_message.c_str());
// At this time, the new log file should be created.
GetFileCreateTime(kLogFile, &actual_create_time);
ASSERT_GT(actual_create_time, expected_create_time);
ASSERT_LT(logger->GetLogFileSize(), total_log_size);
expected_create_time = actual_create_time;
return expected_create_time;
}
TEST(AutoRollLoggerTest, RollLogFileBySize) {
InitTestDb();
size_t log_max_size = 1024 * 5;
AutoRollLogger logger(Env::Default(), kTestDir, "", log_max_size, 0);
RollLogFileBySizeTest(&logger, log_max_size,
kSampleMessage + ":RollLogFileBySize");
}
TEST(AutoRollLoggerTest, RollLogFileByTime) {
size_t time = 1;
size_t log_size = 1024 * 5;
InitTestDb();
// -- Test the existence of file during the server restart.
ASSERT_TRUE(!env->FileExists(kLogFile));
AutoRollLogger logger(Env::Default(), kTestDir, "", log_size, 1);
ASSERT_TRUE(env->FileExists(kLogFile));
RollLogFileByTimeTest(&logger, time, kSampleMessage + ":RollLogFileByTime");
}
TEST(AutoRollLoggerTest,
OpenLogFilesMultipleTimesWithOptionLog_max_size) {
// If only 'log_max_size' options is specified, then every time
// when rocksdb is restarted, a new empty log file will be created.
InitTestDb();
// WORKAROUND:
// avoid complier's complaint of "comparison between signed
// and unsigned integer expressions" because literal 0 is
// treated as "singed".
size_t kZero = 0;
size_t log_size = 1024;
AutoRollLogger* logger = new AutoRollLogger(
Env::Default(), kTestDir, "", log_size, 0);
LogMessage(logger, kSampleMessage.c_str());
ASSERT_GT(logger->GetLogFileSize(), kZero);
delete logger;
// reopens the log file and an empty log file will be created.
logger = new AutoRollLogger(
Env::Default(), kTestDir, "", log_size, 0);
ASSERT_EQ(logger->GetLogFileSize(), kZero);
delete logger;
}
TEST(AutoRollLoggerTest, CompositeRollByTimeAndSizeLogger) {
size_t time = 1, log_max_size = 1024 * 5;
InitTestDb();
AutoRollLogger logger(Env::Default(), kTestDir, "", log_max_size, time);
// Test the ability to roll by size
RollLogFileBySizeTest(
&logger, log_max_size,
kSampleMessage + ":CompositeRollByTimeAndSizeLogger");
// Test the ability to roll by Time
RollLogFileByTimeTest( &logger, time,
kSampleMessage + ":CompositeRollByTimeAndSizeLogger");
}
TEST(AutoRollLoggerTest, CreateLoggerFromOptions) {
DBOptions options;
shared_ptr<Logger> logger;
// Normal logger
ASSERT_OK(CreateLoggerFromOptions(kTestDir, "", env, options, &logger));
ASSERT_TRUE(dynamic_cast<PosixLogger*>(logger.get()));
// Only roll by size
InitTestDb();
options.max_log_file_size = 1024;
ASSERT_OK(CreateLoggerFromOptions(kTestDir, "", env, options, &logger));
AutoRollLogger* auto_roll_logger =
dynamic_cast<AutoRollLogger*>(logger.get());
ASSERT_TRUE(auto_roll_logger);
RollLogFileBySizeTest(
auto_roll_logger, options.max_log_file_size,
kSampleMessage + ":CreateLoggerFromOptions - size");
// Only roll by Time
InitTestDb();
options.max_log_file_size = 0;
options.log_file_time_to_roll = 1;
ASSERT_OK(CreateLoggerFromOptions(kTestDir, "", env, options, &logger));
auto_roll_logger =
dynamic_cast<AutoRollLogger*>(logger.get());
RollLogFileByTimeTest(
auto_roll_logger, options.log_file_time_to_roll,
kSampleMessage + ":CreateLoggerFromOptions - time");
// roll by both Time and size
InitTestDb();
options.max_log_file_size = 1024 * 5;
options.log_file_time_to_roll = 1;
ASSERT_OK(CreateLoggerFromOptions(kTestDir, "", env, options, &logger));
auto_roll_logger =
dynamic_cast<AutoRollLogger*>(logger.get());
RollLogFileBySizeTest(
auto_roll_logger, options.max_log_file_size,
kSampleMessage + ":CreateLoggerFromOptions - both");
RollLogFileByTimeTest(
auto_roll_logger, options.log_file_time_to_roll,
kSampleMessage + ":CreateLoggerFromOptions - both");
}
TEST(AutoRollLoggerTest, InfoLogLevel) {
InitTestDb();
size_t log_size = 8192;
size_t log_lines = 0;
// an extra-scope to force the AutoRollLogger to flush the log file when it
// becomes out of scope.
{
AutoRollLogger logger(Env::Default(), kTestDir, "", log_size, 0);
for (int log_level = InfoLogLevel::FATAL_LEVEL;
log_level >= InfoLogLevel::DEBUG_LEVEL; log_level--) {
logger.SetInfoLogLevel((InfoLogLevel)log_level);
for (int log_type = InfoLogLevel::DEBUG_LEVEL;
log_type <= InfoLogLevel::FATAL_LEVEL; log_type++) {
// log messages with log level smaller than log_level will not be
// logged.
LogMessage((InfoLogLevel)log_type, &logger, kSampleMessage.c_str());
}
log_lines += InfoLogLevel::FATAL_LEVEL - log_level + 1;
}
for (int log_level = InfoLogLevel::FATAL_LEVEL;
log_level >= InfoLogLevel::DEBUG_LEVEL; log_level--) {
logger.SetInfoLogLevel((InfoLogLevel)log_level);
// again, messages with level smaller than log_level will not be logged.
Debug(&logger, "%s", kSampleMessage.c_str());
Info(&logger, "%s", kSampleMessage.c_str());
Warn(&logger, "%s", kSampleMessage.c_str());
Error(&logger, "%s", kSampleMessage.c_str());
Fatal(&logger, "%s", kSampleMessage.c_str());
log_lines += InfoLogLevel::FATAL_LEVEL - log_level + 1;
}
}
std::ifstream inFile(AutoRollLoggerTest::kLogFile.c_str());
size_t lines = std::count(std::istreambuf_iterator<char>(inFile),
std::istreambuf_iterator<char>(), '\n');
ASSERT_EQ(log_lines, lines);
inFile.close();
}
TEST(AutoRollLoggerTest, LogFileExistence) {
rocksdb::DB* db;
rocksdb::Options options;
string deleteCmd = "rm -rf " + kTestDir;
ASSERT_EQ(system(deleteCmd.c_str()), 0);
options.max_log_file_size = 100 * 1024 * 1024;
options.create_if_missing = true;
ASSERT_OK(rocksdb::DB::Open(options, kTestDir, &db));
ASSERT_TRUE(env->FileExists(kLogFile));
delete db;
}
} // namespace rocksdb
int main(int argc, char** argv) {
return rocksdb::test::RunAllTests();
}
<commit_msg>attempt to fix auto_roll_logger_test<commit_after>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
#include <string>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include "util/testharness.h"
#include "util/auto_roll_logger.h"
#include "rocksdb/db.h"
#include <sys/stat.h>
#include <errno.h>
using namespace std;
namespace rocksdb {
class AutoRollLoggerTest {
public:
static void InitTestDb() {
string deleteCmd = "rm -rf " + kTestDir;
ASSERT_TRUE(system(deleteCmd.c_str()) == 0);
Env::Default()->CreateDir(kTestDir);
}
void RollLogFileBySizeTest(AutoRollLogger* logger,
size_t log_max_size,
const string& log_message);
uint64_t RollLogFileByTimeTest(AutoRollLogger* logger,
size_t time,
const string& log_message);
static const string kSampleMessage;
static const string kTestDir;
static const string kLogFile;
static Env* env;
};
const string AutoRollLoggerTest::kSampleMessage(
"this is the message to be written to the log file!!");
const string AutoRollLoggerTest::kTestDir(test::TmpDir() + "/db_log_test");
const string AutoRollLoggerTest::kLogFile(test::TmpDir() + "/db_log_test/LOG");
Env* AutoRollLoggerTest::env = Env::Default();
// In this test we only want to Log some simple log message with
// no format. LogMessage() provides such a simple interface and
// avoids the [format-security] warning which occurs when you
// call Log(logger, log_message) directly.
namespace {
void LogMessage(Logger* logger, const char* message) {
Log(logger, "%s", message);
}
void LogMessage(const InfoLogLevel log_level, Logger* logger,
const char* message) {
Log(log_level, logger, "%s", message);
}
} // namespace
namespace {
void GetFileCreateTime(const std::string& fname, uint64_t* file_ctime) {
struct stat s;
if (stat(fname.c_str(), &s) != 0) {
*file_ctime = (uint64_t)0;
}
*file_ctime = static_cast<uint64_t>(s.st_ctime);
}
} // namespace
void AutoRollLoggerTest::RollLogFileBySizeTest(AutoRollLogger* logger,
size_t log_max_size,
const string& log_message) {
logger->SetInfoLogLevel(InfoLogLevel::INFO_LEVEL);
// measure the size of each message, which is supposed
// to be equal or greater than log_message.size()
LogMessage(logger, log_message.c_str());
size_t message_size = logger->GetLogFileSize();
size_t current_log_size = message_size;
// Test the cases when the log file will not be rolled.
while (current_log_size + message_size < log_max_size) {
LogMessage(logger, log_message.c_str());
current_log_size += message_size;
ASSERT_EQ(current_log_size, logger->GetLogFileSize());
}
// Now the log file will be rolled
LogMessage(logger, log_message.c_str());
// Since rotation is checked before actual logging, we need to
// trigger the rotation by logging another message.
LogMessage(logger, log_message.c_str());
ASSERT_TRUE(message_size == logger->GetLogFileSize());
}
uint64_t AutoRollLoggerTest::RollLogFileByTimeTest(
AutoRollLogger* logger, size_t time, const string& log_message) {
uint64_t expected_create_time;
uint64_t actual_create_time;
uint64_t total_log_size;
ASSERT_OK(env->GetFileSize(kLogFile, &total_log_size));
GetFileCreateTime(kLogFile, &expected_create_time);
logger->SetCallNowMicrosEveryNRecords(0);
// -- Write to the log for several times, which is supposed
// to be finished before time.
for (int i = 0; i < 10; ++i) {
LogMessage(logger, log_message.c_str());
ASSERT_OK(logger->GetStatus());
// Make sure we always write to the same log file (by
// checking the create time);
GetFileCreateTime(kLogFile, &actual_create_time);
// Also make sure the log size is increasing.
ASSERT_EQ(expected_create_time, actual_create_time);
ASSERT_GT(logger->GetLogFileSize(), total_log_size);
total_log_size = logger->GetLogFileSize();
}
// -- Make the log file expire
sleep(time);
LogMessage(logger, log_message.c_str());
// At this time, the new log file should be created.
GetFileCreateTime(kLogFile, &actual_create_time);
ASSERT_GT(actual_create_time, expected_create_time);
ASSERT_LT(logger->GetLogFileSize(), total_log_size);
expected_create_time = actual_create_time;
return expected_create_time;
}
TEST(AutoRollLoggerTest, RollLogFileBySize) {
InitTestDb();
size_t log_max_size = 1024 * 5;
AutoRollLogger logger(Env::Default(), kTestDir, "", log_max_size, 0);
RollLogFileBySizeTest(&logger, log_max_size,
kSampleMessage + ":RollLogFileBySize");
}
TEST(AutoRollLoggerTest, RollLogFileByTime) {
size_t time = 2;
size_t log_size = 1024 * 5;
InitTestDb();
// -- Test the existence of file during the server restart.
ASSERT_TRUE(!env->FileExists(kLogFile));
AutoRollLogger logger(Env::Default(), kTestDir, "", log_size, time);
ASSERT_TRUE(env->FileExists(kLogFile));
RollLogFileByTimeTest(&logger, time, kSampleMessage + ":RollLogFileByTime");
}
TEST(AutoRollLoggerTest,
OpenLogFilesMultipleTimesWithOptionLog_max_size) {
// If only 'log_max_size' options is specified, then every time
// when rocksdb is restarted, a new empty log file will be created.
InitTestDb();
// WORKAROUND:
// avoid complier's complaint of "comparison between signed
// and unsigned integer expressions" because literal 0 is
// treated as "singed".
size_t kZero = 0;
size_t log_size = 1024;
AutoRollLogger* logger = new AutoRollLogger(
Env::Default(), kTestDir, "", log_size, 0);
LogMessage(logger, kSampleMessage.c_str());
ASSERT_GT(logger->GetLogFileSize(), kZero);
delete logger;
// reopens the log file and an empty log file will be created.
logger = new AutoRollLogger(
Env::Default(), kTestDir, "", log_size, 0);
ASSERT_EQ(logger->GetLogFileSize(), kZero);
delete logger;
}
TEST(AutoRollLoggerTest, CompositeRollByTimeAndSizeLogger) {
size_t time = 2, log_max_size = 1024 * 5;
InitTestDb();
AutoRollLogger logger(Env::Default(), kTestDir, "", log_max_size, time);
// Test the ability to roll by size
RollLogFileBySizeTest(
&logger, log_max_size,
kSampleMessage + ":CompositeRollByTimeAndSizeLogger");
// Test the ability to roll by Time
RollLogFileByTimeTest( &logger, time,
kSampleMessage + ":CompositeRollByTimeAndSizeLogger");
}
TEST(AutoRollLoggerTest, CreateLoggerFromOptions) {
DBOptions options;
shared_ptr<Logger> logger;
// Normal logger
ASSERT_OK(CreateLoggerFromOptions(kTestDir, "", env, options, &logger));
ASSERT_TRUE(dynamic_cast<PosixLogger*>(logger.get()));
// Only roll by size
InitTestDb();
options.max_log_file_size = 1024;
ASSERT_OK(CreateLoggerFromOptions(kTestDir, "", env, options, &logger));
AutoRollLogger* auto_roll_logger =
dynamic_cast<AutoRollLogger*>(logger.get());
ASSERT_TRUE(auto_roll_logger);
RollLogFileBySizeTest(
auto_roll_logger, options.max_log_file_size,
kSampleMessage + ":CreateLoggerFromOptions - size");
// Only roll by Time
InitTestDb();
options.max_log_file_size = 0;
options.log_file_time_to_roll = 2;
ASSERT_OK(CreateLoggerFromOptions(kTestDir, "", env, options, &logger));
auto_roll_logger =
dynamic_cast<AutoRollLogger*>(logger.get());
RollLogFileByTimeTest(
auto_roll_logger, options.log_file_time_to_roll,
kSampleMessage + ":CreateLoggerFromOptions - time");
// roll by both Time and size
InitTestDb();
options.max_log_file_size = 1024 * 5;
options.log_file_time_to_roll = 2;
ASSERT_OK(CreateLoggerFromOptions(kTestDir, "", env, options, &logger));
auto_roll_logger =
dynamic_cast<AutoRollLogger*>(logger.get());
RollLogFileBySizeTest(
auto_roll_logger, options.max_log_file_size,
kSampleMessage + ":CreateLoggerFromOptions - both");
RollLogFileByTimeTest(
auto_roll_logger, options.log_file_time_to_roll,
kSampleMessage + ":CreateLoggerFromOptions - both");
}
TEST(AutoRollLoggerTest, InfoLogLevel) {
InitTestDb();
size_t log_size = 8192;
size_t log_lines = 0;
// an extra-scope to force the AutoRollLogger to flush the log file when it
// becomes out of scope.
{
AutoRollLogger logger(Env::Default(), kTestDir, "", log_size, 0);
for (int log_level = InfoLogLevel::FATAL_LEVEL;
log_level >= InfoLogLevel::DEBUG_LEVEL; log_level--) {
logger.SetInfoLogLevel((InfoLogLevel)log_level);
for (int log_type = InfoLogLevel::DEBUG_LEVEL;
log_type <= InfoLogLevel::FATAL_LEVEL; log_type++) {
// log messages with log level smaller than log_level will not be
// logged.
LogMessage((InfoLogLevel)log_type, &logger, kSampleMessage.c_str());
}
log_lines += InfoLogLevel::FATAL_LEVEL - log_level + 1;
}
for (int log_level = InfoLogLevel::FATAL_LEVEL;
log_level >= InfoLogLevel::DEBUG_LEVEL; log_level--) {
logger.SetInfoLogLevel((InfoLogLevel)log_level);
// again, messages with level smaller than log_level will not be logged.
Debug(&logger, "%s", kSampleMessage.c_str());
Info(&logger, "%s", kSampleMessage.c_str());
Warn(&logger, "%s", kSampleMessage.c_str());
Error(&logger, "%s", kSampleMessage.c_str());
Fatal(&logger, "%s", kSampleMessage.c_str());
log_lines += InfoLogLevel::FATAL_LEVEL - log_level + 1;
}
}
std::ifstream inFile(AutoRollLoggerTest::kLogFile.c_str());
size_t lines = std::count(std::istreambuf_iterator<char>(inFile),
std::istreambuf_iterator<char>(), '\n');
ASSERT_EQ(log_lines, lines);
inFile.close();
}
TEST(AutoRollLoggerTest, LogFileExistence) {
rocksdb::DB* db;
rocksdb::Options options;
string deleteCmd = "rm -rf " + kTestDir;
ASSERT_EQ(system(deleteCmd.c_str()), 0);
options.max_log_file_size = 100 * 1024 * 1024;
options.create_if_missing = true;
ASSERT_OK(rocksdb::DB::Open(options, kTestDir, &db));
ASSERT_TRUE(env->FileExists(kLogFile));
delete db;
}
} // namespace rocksdb
int main(int argc, char** argv) {
return rocksdb::test::RunAllTests();
}
<|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: accel.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "vcl/arrange.hxx"
#include "osl/diagnose.h"
using namespace vcl;
// ----------------------------------------
// vcl::WindowArranger
//-----------------------------------------
WindowArranger::~WindowArranger()
{}
void WindowArranger::setParent( WindowArranger* i_pParent )
{
OSL_VERIFY( i_pParent->m_pParentWindow == m_pParentWindow || m_pParentWindow == NULL );
m_pParentArranger = i_pParent;
m_pParentWindow = i_pParent->m_pParentWindow;
setParentWindow( m_pParentWindow );
}
// ----------------------------------------
// vcl::RowOrColumn
//-----------------------------------------
RowOrColumn::~RowOrColumn()
{
for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin();
it != m_aElements.end(); ++it )
{
it->deleteChild();
}
}
WindowArranger* RowOrColumn::getChild( size_t i_nIndex ) const
{
return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pChild.get() : NULL;
}
Window* RowOrColumn::getWindow( size_t i_nIndex ) const
{
return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pElement : NULL;
}
Size RowOrColumn::getOptimalSize( WindowSizeType i_eType ) const
{
Size aRet( 0, 0 );
if( ! m_aElements.empty() )
{
if( m_bColumn )
aRet.Height() -= m_nBorderWidth;
else
aRet.Width() -= m_nBorderWidth;
}
for( std::vector< WindowArranger::Element >::const_iterator it = m_aElements.begin();
it != m_aElements.end(); ++it )
{
// get the size of type of the managed element
Size aElementSize( it->m_pElement
? it->m_pElement->GetOptimalSize( i_eType )
: it->m_pChild
? it->m_pChild->getOptimalSize( i_eType )
: Size() );
if( m_bColumn )
{
// add the distance between elements
aRet.Height() += m_nBorderWidth;
// check if the width needs adjustment
if( aRet.Width() < aElementSize.Width() )
aRet.Width() = aElementSize.Width();
aRet.Height() += aElementSize.Height();
}
else
{
// add the distance between elements
aRet.Width() += m_nBorderWidth;
// check if the height needs adjustment
if( aRet.Height() < aElementSize.Height() )
aRet.Height() = aElementSize.Height();
aRet.Width() += aElementSize.Width();
}
}
// add the outer border
aRet.Width() += 2*m_nOuterBorder;
aRet.Height() += 2*m_nOuterBorder;
return aRet;
}
void RowOrColumn::distributeRowWidth( std::vector<Size>& io_rSizes, long /*i_nUsedWidth*/, long i_nExtraWidth )
{
if( ! io_rSizes.empty() )
{
// distribute extra space evenly among elements
size_t nElements = io_rSizes.size();
long nDelta = i_nExtraWidth / nElements;
for( size_t i = 0; i < nElements; i++ )
{
io_rSizes[i].Width() += nDelta;
i_nExtraWidth -= nDelta;
}
// add the last pixels to the last row element
if( i_nExtraWidth > 0 && nElements > 0 )
io_rSizes.back().Width() += i_nExtraWidth;
}
}
void RowOrColumn::resize()
{
// check if we can get optimal size, else fallback to minimal size
Size aOptSize( getOptimalSize( WINDOWSIZE_PREFERRED ) );
WindowSizeType eType = WINDOWSIZE_PREFERRED;
if( m_bColumn )
{
if( aOptSize.Height() > m_aManagedArea.GetHeight() )
eType = WINDOWSIZE_MINIMUM;
}
else
{
if( aOptSize.Width() > m_aManagedArea.GetWidth() )
eType = WINDOWSIZE_MINIMUM;
}
size_t nElements = m_aElements.size();
// get all element sizes for sizing
std::vector<Size> aElementSizes( nElements );
long nUsedWidth = 2*m_nOuterBorder - (nElements ? m_nBorderWidth : 0);
for( size_t i = 0; i < nElements; i++ )
{
aElementSizes[i] = m_aElements[i].m_pElement
? m_aElements[i].m_pElement->GetOptimalSize( eType )
: m_aElements[i].m_pChild
? m_aElements[i].m_pChild->getOptimalSize( eType )
: Size();
if( m_bColumn )
{
aElementSizes[i].Width() = m_aManagedArea.GetWidth() - 2* m_nOuterBorder;
nUsedWidth += aElementSizes[i].Height() + m_nBorderWidth;
}
else
{
aElementSizes[i].Height() = m_aManagedArea.GetHeight() - 2* m_nOuterBorder;
nUsedWidth += aElementSizes[i].Width() + m_nBorderWidth;
}
}
long nExtraWidth = m_aManagedArea.GetWidth() - nUsedWidth;
if( nExtraWidth > 0 )
if( ! m_bColumn )
distributeRowWidth( aElementSizes, nUsedWidth, nExtraWidth );
// get starting position
Point aElementPos( m_aManagedArea.TopLeft() );
// outer border
aElementPos.X() += m_nOuterBorder;
aElementPos.Y() += m_nOuterBorder;
// position managed windows
for( size_t i = 0; i < nElements; i++ )
{
// get the size of type of the managed element
if( m_aElements[i].m_pElement ) // this actually is a window
{
m_aElements[i].m_pElement->SetPosSizePixel( aElementPos, aElementSizes[i] );
}
else if( m_aElements[i].m_pChild )
{
m_aElements[i].m_pChild->setManagedArea( Rectangle( aElementPos, aElementSizes[i] ) );
}
if( m_bColumn )
aElementPos.Y() += m_nBorderWidth + aElementSizes[i].Height();
else
aElementPos.X() += m_nBorderWidth + aElementSizes[i].Width();
}
}
void RowOrColumn::setParentWindow( Window* i_pNewParent )
{
m_pParentWindow = i_pNewParent;
for( std::vector< WindowArranger::Element >::const_iterator it = m_aElements.begin();
it != m_aElements.end(); ++it )
{
#if OSL_DEBUG_LEVEL > 0
if( it->m_pElement )
{
OSL_VERIFY( it->m_pElement->GetParent() == i_pNewParent );
}
#endif
if( it->m_pChild )
it->m_pChild->setParentWindow( i_pNewParent );
}
}
void RowOrColumn::addWindow( Window* i_pWindow, sal_Int32 i_nIndex )
{
if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() )
m_aElements.push_back( WindowArranger::Element( i_pWindow, NULL ) );
else
{
std::vector< WindowArranger::Element >::iterator it = m_aElements.begin();
while( i_nIndex-- )
++it;
m_aElements.insert( it, WindowArranger::Element( i_pWindow, NULL ) );
}
}
void RowOrColumn::addChild( WindowArranger* i_pChild, sal_Int32 i_nIndex )
{
if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() )
m_aElements.push_back( WindowArranger::Element( NULL, i_pChild ) );
else
{
std::vector< WindowArranger::Element >::iterator it = m_aElements.begin();
while( i_nIndex-- )
++it;
m_aElements.insert( it, WindowArranger::Element( NULL, i_pChild ) );
}
}
void RowOrColumn::remove( Window* i_pWindow )
{
if( i_pWindow )
{
for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin();
it != m_aElements.end(); ++it )
{
if( it->m_pElement == i_pWindow )
{
m_aElements.erase( it );
return;
}
}
}
}
void RowOrColumn::remove( WindowArranger* i_pChild )
{
if( i_pChild )
{
for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin();
it != m_aElements.end(); ++it )
{
if( it->m_pChild.get() == i_pChild )
{
m_aElements.erase( it );
return;
}
}
}
}
// ----------------------------------------
// vcl::Indenter
//-----------------------------------------
Indenter::~Indenter()
{
m_aElement.deleteChild();
}
Size Indenter::getOptimalSize( WindowSizeType i_eType ) const
{
Size aSize( m_aElement.m_pElement
? m_aElement.m_pElement->GetOptimalSize( i_eType )
: m_aElement.m_pChild
? m_aElement.m_pChild->getOptimalSize( i_eType )
: Size() );
aSize.Width() += 2*m_nOuterBorder + m_nIndent;
aSize.Height() += 2*m_nOuterBorder;
return aSize;
}
void Indenter::resize()
{
Point aPt( m_aManagedArea.TopLeft() );
aPt.X() += m_nOuterBorder + m_nIndent;
aPt.Y() += m_nOuterBorder;
Size aSz( m_aManagedArea.GetSize() );
aSz.Width() -= 2*m_nOuterBorder - m_nIndent;
aSz.Height() -= 2*m_nOuterBorder;
if( m_aElement.m_pElement )
m_aElement.m_pElement->SetPosSizePixel( aPt, aSz );
else if( m_aElement.m_pChild )
m_aElement.m_pChild->setManagedArea( Rectangle( aPt, aSz ) );
}
void Indenter::setWindow( Window* i_pWindow )
{
OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0) || i_pWindow == 0 );
OSL_VERIFY( i_pWindow == 0 || i_pWindow->GetParent() == m_pParentWindow );
m_aElement.m_pElement = i_pWindow;
}
void Indenter::setChild( WindowArranger* i_pChild )
{
OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0 ) || i_pChild == 0 );
m_aElement.m_pChild.reset( i_pChild );
}
void Indenter::setParentWindow( Window* i_pNewParent )
{
m_pParentWindow = i_pNewParent;
#if OSL_DEBUG_LEVEL > 0
if( m_aElement.m_pElement )
{
OSL_VERIFY( m_aElement.m_pElement->GetParent() == i_pNewParent );
}
#endif
if( m_aElement.m_pChild )
m_aElement.m_pChild->setParentWindow( i_pNewParent );
}
<commit_msg>add completely useless PCH directive to satisfy stupid windows compiler<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: accel.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_vcl.hxx"
#include "vcl/arrange.hxx"
#include "osl/diagnose.h"
using namespace vcl;
// ----------------------------------------
// vcl::WindowArranger
//-----------------------------------------
WindowArranger::~WindowArranger()
{}
void WindowArranger::setParent( WindowArranger* i_pParent )
{
OSL_VERIFY( i_pParent->m_pParentWindow == m_pParentWindow || m_pParentWindow == NULL );
m_pParentArranger = i_pParent;
m_pParentWindow = i_pParent->m_pParentWindow;
setParentWindow( m_pParentWindow );
}
// ----------------------------------------
// vcl::RowOrColumn
//-----------------------------------------
RowOrColumn::~RowOrColumn()
{
for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin();
it != m_aElements.end(); ++it )
{
it->deleteChild();
}
}
WindowArranger* RowOrColumn::getChild( size_t i_nIndex ) const
{
return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pChild.get() : NULL;
}
Window* RowOrColumn::getWindow( size_t i_nIndex ) const
{
return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pElement : NULL;
}
Size RowOrColumn::getOptimalSize( WindowSizeType i_eType ) const
{
Size aRet( 0, 0 );
if( ! m_aElements.empty() )
{
if( m_bColumn )
aRet.Height() -= m_nBorderWidth;
else
aRet.Width() -= m_nBorderWidth;
}
for( std::vector< WindowArranger::Element >::const_iterator it = m_aElements.begin();
it != m_aElements.end(); ++it )
{
// get the size of type of the managed element
Size aElementSize( it->m_pElement
? it->m_pElement->GetOptimalSize( i_eType )
: it->m_pChild
? it->m_pChild->getOptimalSize( i_eType )
: Size() );
if( m_bColumn )
{
// add the distance between elements
aRet.Height() += m_nBorderWidth;
// check if the width needs adjustment
if( aRet.Width() < aElementSize.Width() )
aRet.Width() = aElementSize.Width();
aRet.Height() += aElementSize.Height();
}
else
{
// add the distance between elements
aRet.Width() += m_nBorderWidth;
// check if the height needs adjustment
if( aRet.Height() < aElementSize.Height() )
aRet.Height() = aElementSize.Height();
aRet.Width() += aElementSize.Width();
}
}
// add the outer border
aRet.Width() += 2*m_nOuterBorder;
aRet.Height() += 2*m_nOuterBorder;
return aRet;
}
void RowOrColumn::distributeRowWidth( std::vector<Size>& io_rSizes, long /*i_nUsedWidth*/, long i_nExtraWidth )
{
if( ! io_rSizes.empty() )
{
// distribute extra space evenly among elements
size_t nElements = io_rSizes.size();
long nDelta = i_nExtraWidth / nElements;
for( size_t i = 0; i < nElements; i++ )
{
io_rSizes[i].Width() += nDelta;
i_nExtraWidth -= nDelta;
}
// add the last pixels to the last row element
if( i_nExtraWidth > 0 && nElements > 0 )
io_rSizes.back().Width() += i_nExtraWidth;
}
}
void RowOrColumn::resize()
{
// check if we can get optimal size, else fallback to minimal size
Size aOptSize( getOptimalSize( WINDOWSIZE_PREFERRED ) );
WindowSizeType eType = WINDOWSIZE_PREFERRED;
if( m_bColumn )
{
if( aOptSize.Height() > m_aManagedArea.GetHeight() )
eType = WINDOWSIZE_MINIMUM;
}
else
{
if( aOptSize.Width() > m_aManagedArea.GetWidth() )
eType = WINDOWSIZE_MINIMUM;
}
size_t nElements = m_aElements.size();
// get all element sizes for sizing
std::vector<Size> aElementSizes( nElements );
long nUsedWidth = 2*m_nOuterBorder - (nElements ? m_nBorderWidth : 0);
for( size_t i = 0; i < nElements; i++ )
{
aElementSizes[i] = m_aElements[i].m_pElement
? m_aElements[i].m_pElement->GetOptimalSize( eType )
: m_aElements[i].m_pChild
? m_aElements[i].m_pChild->getOptimalSize( eType )
: Size();
if( m_bColumn )
{
aElementSizes[i].Width() = m_aManagedArea.GetWidth() - 2* m_nOuterBorder;
nUsedWidth += aElementSizes[i].Height() + m_nBorderWidth;
}
else
{
aElementSizes[i].Height() = m_aManagedArea.GetHeight() - 2* m_nOuterBorder;
nUsedWidth += aElementSizes[i].Width() + m_nBorderWidth;
}
}
long nExtraWidth = m_aManagedArea.GetWidth() - nUsedWidth;
if( nExtraWidth > 0 )
if( ! m_bColumn )
distributeRowWidth( aElementSizes, nUsedWidth, nExtraWidth );
// get starting position
Point aElementPos( m_aManagedArea.TopLeft() );
// outer border
aElementPos.X() += m_nOuterBorder;
aElementPos.Y() += m_nOuterBorder;
// position managed windows
for( size_t i = 0; i < nElements; i++ )
{
// get the size of type of the managed element
if( m_aElements[i].m_pElement ) // this actually is a window
{
m_aElements[i].m_pElement->SetPosSizePixel( aElementPos, aElementSizes[i] );
}
else if( m_aElements[i].m_pChild )
{
m_aElements[i].m_pChild->setManagedArea( Rectangle( aElementPos, aElementSizes[i] ) );
}
if( m_bColumn )
aElementPos.Y() += m_nBorderWidth + aElementSizes[i].Height();
else
aElementPos.X() += m_nBorderWidth + aElementSizes[i].Width();
}
}
void RowOrColumn::setParentWindow( Window* i_pNewParent )
{
m_pParentWindow = i_pNewParent;
for( std::vector< WindowArranger::Element >::const_iterator it = m_aElements.begin();
it != m_aElements.end(); ++it )
{
#if OSL_DEBUG_LEVEL > 0
if( it->m_pElement )
{
OSL_VERIFY( it->m_pElement->GetParent() == i_pNewParent );
}
#endif
if( it->m_pChild )
it->m_pChild->setParentWindow( i_pNewParent );
}
}
void RowOrColumn::addWindow( Window* i_pWindow, sal_Int32 i_nIndex )
{
if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() )
m_aElements.push_back( WindowArranger::Element( i_pWindow, NULL ) );
else
{
std::vector< WindowArranger::Element >::iterator it = m_aElements.begin();
while( i_nIndex-- )
++it;
m_aElements.insert( it, WindowArranger::Element( i_pWindow, NULL ) );
}
}
void RowOrColumn::addChild( WindowArranger* i_pChild, sal_Int32 i_nIndex )
{
if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() )
m_aElements.push_back( WindowArranger::Element( NULL, i_pChild ) );
else
{
std::vector< WindowArranger::Element >::iterator it = m_aElements.begin();
while( i_nIndex-- )
++it;
m_aElements.insert( it, WindowArranger::Element( NULL, i_pChild ) );
}
}
void RowOrColumn::remove( Window* i_pWindow )
{
if( i_pWindow )
{
for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin();
it != m_aElements.end(); ++it )
{
if( it->m_pElement == i_pWindow )
{
m_aElements.erase( it );
return;
}
}
}
}
void RowOrColumn::remove( WindowArranger* i_pChild )
{
if( i_pChild )
{
for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin();
it != m_aElements.end(); ++it )
{
if( it->m_pChild.get() == i_pChild )
{
m_aElements.erase( it );
return;
}
}
}
}
// ----------------------------------------
// vcl::Indenter
//-----------------------------------------
Indenter::~Indenter()
{
m_aElement.deleteChild();
}
Size Indenter::getOptimalSize( WindowSizeType i_eType ) const
{
Size aSize( m_aElement.m_pElement
? m_aElement.m_pElement->GetOptimalSize( i_eType )
: m_aElement.m_pChild
? m_aElement.m_pChild->getOptimalSize( i_eType )
: Size() );
aSize.Width() += 2*m_nOuterBorder + m_nIndent;
aSize.Height() += 2*m_nOuterBorder;
return aSize;
}
void Indenter::resize()
{
Point aPt( m_aManagedArea.TopLeft() );
aPt.X() += m_nOuterBorder + m_nIndent;
aPt.Y() += m_nOuterBorder;
Size aSz( m_aManagedArea.GetSize() );
aSz.Width() -= 2*m_nOuterBorder - m_nIndent;
aSz.Height() -= 2*m_nOuterBorder;
if( m_aElement.m_pElement )
m_aElement.m_pElement->SetPosSizePixel( aPt, aSz );
else if( m_aElement.m_pChild )
m_aElement.m_pChild->setManagedArea( Rectangle( aPt, aSz ) );
}
void Indenter::setWindow( Window* i_pWindow )
{
OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0) || i_pWindow == 0 );
OSL_VERIFY( i_pWindow == 0 || i_pWindow->GetParent() == m_pParentWindow );
m_aElement.m_pElement = i_pWindow;
}
void Indenter::setChild( WindowArranger* i_pChild )
{
OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0 ) || i_pChild == 0 );
m_aElement.m_pChild.reset( i_pChild );
}
void Indenter::setParentWindow( Window* i_pNewParent )
{
m_pParentWindow = i_pNewParent;
#if OSL_DEBUG_LEVEL > 0
if( m_aElement.m_pElement )
{
OSL_VERIFY( m_aElement.m_pElement->GetParent() == i_pNewParent );
}
#endif
if( m_aElement.m_pChild )
m_aElement.m_pChild->setParentWindow( i_pNewParent );
}
<|endoftext|>
|
<commit_before><commit_msg>Be more specific in warning<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Streams_LoggingInputOutputStream_inl_
#define _Stroika_Foundation_Streams_LoggingInputOutputStream_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace Streams {
/*
********************************************************************************
**************** Streams::LoggingInputOutputStream::Rep_ ***********************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
class LoggingInputOutputStream<ELEMENT_TYPE>::Rep_ : public InputOutputStream<ELEMENT_TYPE>::_IRep, private Debug::AssertExternallySynchronizedLock {
public:
Rep_ (const typename InputOutputStream<ELEMENT_TYPE>::Ptr& realStream, const typename OutputStream<ELEMENT_TYPE>::Ptr& logInput, const typename OutputStream<ELEMENT_TYPE>::Ptr& logOutput)
: InputOutputStream<ELEMENT_TYPE>::_IRep ()
, fRealStream_ (realStream)
, fLogInput_ (logInput)
, fLogOutput_ (logOutput)
{
}
// Stream<ELEMENT_TYPE>::_IRep
public:
virtual bool IsSeekable () const override
{
return fRealOut1_.IsSeekable ();
}
// InputStream::_IRep
public:
virtual void CloseRead () override
{
fRealStream_.CloseRead ();
fLogInput_.Close ();
}
virtual bool IsOpenRead () const override
{
return fRealStream_.IsOpenRead ();
}
virtual SeekOffsetType GetReadOffset () const override
{
return fRealStream_.GetReadOffset ();
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
SeekOffsetType result = fRealStream_.SeekRead (whence, offset);
// @todo - perhaps should seek the fLogInput_ stream? But not clear by how much
return result;
}
virtual size_t Read (ElementType* intoStart, ElementType* intoEnd) override
{
size_t result = fRealStream_.Read (intoStart, intoEnd);
fLogInput_.Write (intoStart, intoStart + result);
return result;
}
virtual Memory::Optional<size_t> ReadNonBlocking (ElementType* intoStart, ElementType* intoEnd) override
{
size_t result = fRealStream_.ReadNonBlocking (intoStart, intoEnd);
fLogInput_.Write (intoStart, intoStart + result);
return result;
}
// OutputStream::_IRep
public:
virtual void CloseWrite () override
{
Require (IsOpenWrite ());
fRealStream_.CloseWrite ();
Assert (fRealStream_ == nullptr);
}
virtual bool IsOpenWrite () const override
{
return fRealStream_.IsOpenWrite ();
}
virtual SeekOffsetType GetWriteOffset () const override
{
return fRealStream_.GetWriteOffset ();
}
virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override
{
Require (IsOpenWrite ());
SeekOffsetType o1 = fRealStream_.SeekWrite (whence, offset);
SeekOffsetType o2 = fLogOutput_.SeekWrite (whence, offset); // @todo - not sure if/how mcuh to see - since not totally in sync
return o1;
}
virtual void Flush () override
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (IsOpenWrite ());
fRealStream_.Flush ();
}
// pointer must refer to valid memory at least bufSize long, and cannot be nullptr. BufSize must always be >= 1.
// Writes always succeed fully or throw.
virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override
{
Require (start < end); // for OutputStream<Byte> - this funciton requires non-empty write
Require (IsOpenWrite ());
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
fRealStream_.Write (start, end);
fLogOutput_.Write (start, end);
}
private:
typename InputOutputStream<ELEMENT_TYPE>::Ptr fRealStream_;
typename OutputStream<ELEMENT_TYPE>::Ptr fLogInput_;
typename OutputStream<ELEMENT_TYPE>::Ptr fLogOutput_;
};
/*
********************************************************************************
**************** Streams::LoggingInputOutputStream::Rep_ ***********************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
typename LoggingInputOutputStream<ELEMENT_TYPE>::Ptr LoggingInputOutputStream<ELEMENT_TYPE>::New (const typename InputOutputStream<ELEMENT_TYPE>::Ptr& realStream, const typename OutputStream<ELEMENT_TYPE>::Ptr& logInput, const typename OutputStream<ELEMENT_TYPE>::Ptr& logOutput)
{
return make_shared<Rep_> (realStream, logInput, logOutput);
}
template <typename ELEMENT_TYPE>
typename LoggingInputOutputStream<ELEMENT_TYPE>::Ptr LoggingInputOutputStream<ELEMENT_TYPE>::New (Execution::InternallySyncrhonized internallySyncrhonized, const typename InputOutputStream<ELEMENT_TYPE>::Ptr& realStream, const typename OutputStream<ELEMENT_TYPE>::Ptr& logInput, const typename OutputStream<ELEMENT_TYPE>::Ptr& logOutput)
{
switch (internallySyncrhonized) {
case Execution::eInternallySynchronized:
return InternalSyncRep_::New (realStream, logInput, logOutput);
case Execution::eNotKnownInternallySynchronized:
return New (realStream, logInput, logOutput);
default:
RequireNotReached ();
return nullptr;
}
}
}
}
}
#endif /*_Stroika_Foundation_Streams_LoggingInputOutputStream_inl_*/
<commit_msg>fixes to new Streams/LoggingInputOutputStream<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Streams_LoggingInputOutputStream_inl_
#define _Stroika_Foundation_Streams_LoggingInputOutputStream_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace Streams {
/*
********************************************************************************
**************** Streams::LoggingInputOutputStream::Rep_ ***********************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
class LoggingInputOutputStream<ELEMENT_TYPE>::Rep_ : public InputOutputStream<ELEMENT_TYPE>::_IRep, private Debug::AssertExternallySynchronizedLock {
public:
Rep_ (const typename InputOutputStream<ELEMENT_TYPE>::Ptr& realStream, const typename OutputStream<ELEMENT_TYPE>::Ptr& logInput, const typename OutputStream<ELEMENT_TYPE>::Ptr& logOutput)
: InputOutputStream<ELEMENT_TYPE>::_IRep ()
, fRealStream_ (realStream)
, fLogInput_ (logInput)
, fLogOutput_ (logOutput)
{
Require (not realStream.IsSeekable () or (logInput.IsSeekable () and logOutput.IsSeekable ())); // since may need to delegate seeks
}
// Stream<ELEMENT_TYPE>::_IRep
public:
virtual bool IsSeekable () const override
{
return fRealStream_.IsSeekable ();
}
// InputStream::_IRep
public:
virtual void CloseRead () override
{
fRealStream_.CloseRead ();
fLogInput_.Close ();
}
virtual bool IsOpenRead () const override
{
return fRealStream_.IsOpenRead ();
}
virtual SeekOffsetType GetReadOffset () const override
{
return fRealStream_.GetReadOffset ();
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
SeekOffsetType result = fRealStream_.SeekRead (whence, offset);
// @todo - perhaps should seek the fLogInput_ stream? But not clear by how much
return result;
}
virtual size_t Read (ElementType* intoStart, ElementType* intoEnd) override
{
size_t result = fRealStream_.Read (intoStart, intoEnd);
fLogInput_.Write (intoStart, intoStart + result);
return result;
}
virtual Memory::Optional<size_t> ReadNonBlocking (ElementType* intoStart, ElementType* intoEnd) override
{
Memory::Optional<size_t> result = fRealStream_.ReadNonBlocking (intoStart, intoEnd);
if (result) {
fLogInput_.Write (intoStart, intoStart + *result);
}
return result;
}
// OutputStream::_IRep
public:
virtual void CloseWrite () override
{
Require (IsOpenWrite ());
fRealStream_.CloseWrite ();
Assert (fRealStream_ == nullptr);
}
virtual bool IsOpenWrite () const override
{
return fRealStream_.IsOpenWrite ();
}
virtual SeekOffsetType GetWriteOffset () const override
{
return fRealStream_.GetWriteOffset ();
}
virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override
{
Require (IsOpenWrite ());
SeekOffsetType o1 = fRealStream_.SeekWrite (whence, offset);
SeekOffsetType o2 = fLogOutput_.Seek (whence, offset); // @todo - not sure if/how mcuh to see - since not totally in sync
return o1;
}
virtual void Flush () override
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (IsOpenWrite ());
fRealStream_.Flush ();
}
// pointer must refer to valid memory at least bufSize long, and cannot be nullptr. BufSize must always be >= 1.
// Writes always succeed fully or throw.
virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override
{
Require (start < end); // for OutputStream<Byte> - this funciton requires non-empty write
Require (IsOpenWrite ());
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
fRealStream_.Write (start, end);
fLogOutput_.Write (start, end);
}
private:
typename InputOutputStream<ELEMENT_TYPE>::Ptr fRealStream_;
typename OutputStream<ELEMENT_TYPE>::Ptr fLogInput_;
typename OutputStream<ELEMENT_TYPE>::Ptr fLogOutput_;
};
/*
********************************************************************************
**************** Streams::LoggingInputOutputStream::Rep_ ***********************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
typename LoggingInputOutputStream<ELEMENT_TYPE>::Ptr LoggingInputOutputStream<ELEMENT_TYPE>::New (const typename InputOutputStream<ELEMENT_TYPE>::Ptr& realStream, const typename OutputStream<ELEMENT_TYPE>::Ptr& logInput, const typename OutputStream<ELEMENT_TYPE>::Ptr& logOutput)
{
return make_shared<Rep_> (realStream, logInput, logOutput);
}
template <typename ELEMENT_TYPE>
typename LoggingInputOutputStream<ELEMENT_TYPE>::Ptr LoggingInputOutputStream<ELEMENT_TYPE>::New (Execution::InternallySyncrhonized internallySyncrhonized, const typename InputOutputStream<ELEMENT_TYPE>::Ptr& realStream, const typename OutputStream<ELEMENT_TYPE>::Ptr& logInput, const typename OutputStream<ELEMENT_TYPE>::Ptr& logOutput)
{
switch (internallySyncrhonized) {
case Execution::eInternallySynchronized:
return InternalSyncRep_::New (realStream, logInput, logOutput);
case Execution::eNotKnownInternallySynchronized:
return New (realStream, logInput, logOutput);
default:
RequireNotReached ();
return nullptr;
}
}
}
}
}
#endif /*_Stroika_Foundation_Streams_LoggingInputOutputStream_inl_*/
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <Windows.h>
#endif
#include "../../../Foundation/Characters/String_Constant.h"
#include "../../../Foundation/Characters/String2Float.h"
#include "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h"
#include "../../../Foundation/Debug/Assertions.h"
#include "../../../Foundation/Execution/Sleep.h"
#include "../../../Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include "../../../Foundation/Math/Common.h"
#include "CPU.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using namespace Stroika::Frameworks::SystemPerformance::Instruments::CPU;
using Characters::String_Constant;
using Time::DurationSecondsType;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
#if qSupport_SystemPerformance_Instruments_CPU_LoadAverage
/*
********************************************************************************
*********************** Instruments::CPU::Info::LoadAverage ********************
********************************************************************************
*/
Instruments::CPU::Info::LoadAverage::LoadAverage (double oneMinuteAve, double fiveMinuteAve, double fifteenMinuteAve)
: f1MinuteAve (oneMinuteAve)
, f5MinuteAve (fiveMinuteAve)
, f15MinuteAve (fifteenMinuteAve)
{
}
#endif
/*
********************************************************************************
***************** Instruments::CPU::GetObjectVariantMapper *********************
********************************************************************************
*/
ObjectVariantMapper Instruments::CPU::GetObjectVariantMapper ()
{
using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
#if qSupport_SystemPerformance_Instruments_CPU_LoadAverage
mapper.AddClass<Info::LoadAverage> (initializer_list<StructureFieldInfo> {
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f1MinuteAve), String_Constant (L"1-minute") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f5MinuteAve), String_Constant (L"5-minute") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f15MinuteAve), String_Constant (L"15-minute") },
});
mapper.AddCommonType<Optional_Indirect_Storage<Info::LoadAverage>> ();
#endif
mapper.AddClass<Info> (initializer_list<StructureFieldInfo> {
#if qSupport_SystemPerformance_Instruments_CPU_LoadAverage
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLoadAverage), String_Constant (L"Load-Average"), StructureFieldInfo::NullFieldHandling::eOmit },
#endif
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fTotalCPUUsage), String_Constant (L"Total-CPU-Usage") },
});
DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
return mapper;
} ();
return sMapper_;
}
namespace {
struct CapturerWithContext_COMMON_ {
Options fOptions_;
DurationSecondsType fPostponeCaptureUntil_ { 0 };
DateTime fLastCapturedAt;
DurationSecondsType fMinimumAveragingInterval_;
CapturerWithContext_COMMON_ (const Options& options)
: fOptions_ (options)
, fMinimumAveragingInterval_ (options.fMinimumAveragingInterval)
{
}
void NoteCompletedCapture_ ()
{
fPostponeCaptureUntil_ = Time::GetTickCount () + fMinimumAveragingInterval_;
fLastCapturedAt = DateTime::Now ();
}
};
}
#if qPlatform_POSIX
namespace {
struct CapturerWithContext_POSIX_ : CapturerWithContext_COMMON_ {
struct POSIXSysTimeCaptureContext_ {
double user;
//double nice;
double system;
double idle;
};
POSIXSysTimeCaptureContext_ fContext_ {};
CapturerWithContext_POSIX_ (const Options& options)
: CapturerWithContext_COMMON_ (options)
{
capture_ (); // Force fill of context - ignore results
}
/*
* /proc/stat
* EXAMPLE:
* lewis@LewisLinuxDevVM2:~$ cat /proc/stat
* cpu 361378 1170 50632 2812384 5609 3 2684 0 0 0
* cpu0 202907 894 27261 1382587 3014 3 2672 0 0 0
* cpu1 158471 276 23371 1429797 2595 0 12 0 0 0
*
* From http://man7.org/linux/man-pages/man5/proc.5.html
*
* kernel/system statistics. Varies with architecture. Common
* entries include:
*
* cpu 3357 0 4313 1362393
* The amount of time, measured in units of USER_HZ
* (1/100ths of a second on most architectures, use
* sysconf(_SC_CLK_TCK) to obtain the right value), that
* the system spent in various states:
*
* user (1) Time spent in user mode.
*
* nice (2) Time spent in user mode with low priority
* (nice).
*
* system (3) Time spent in system mode.
*
* idle (4) Time spent in the idle task. This value
* should be USER_HZ times the second entry in the
* /proc/uptime pseudo-file.
*/
static inline POSIXSysTimeCaptureContext_ GetSysTimes_ ()
{
POSIXSysTimeCaptureContext_ result;
using IO::FileSystem::BinaryFileInputStream;
using Characters::String2Float;
DataExchange::CharacterDelimitedLines::Reader reader {{' ', '\t' }};
const String_Constant kFileName_ { L"/proc/stat" };
// Note - /procfs files always unseekable
for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kFileName_, BinaryFileInputStream::eNotSeekable))) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"***in Instruments::CPU::capture_GetSysTimes_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ());
#endif
if (line.size () >= 5 and line[0] == L"cpu") {
result.user = String2Float<double> (line[1]);
result.system = String2Float<double> (line[3]);
result.idle = String2Float<double> (line[4]);
break; // once found no need to read the rest...
}
}
return result;
}
double cputime_ ()
{
POSIXSysTimeCaptureContext_ baseline = fContext_;
POSIXSysTimeCaptureContext_ newVal = GetSysTimes_ ();
fContext_ = newVal;
double usedSysTime = (newVal.user - baseline.user) + (newVal.system - baseline.system);
double totalTime = usedSysTime + (newVal.idle - baseline.idle);
if (Math::NearlyEquals<double> (totalTime, 0)) {
// can happen if called too quickly together. No good answer
DbgTrace ("Warning - times too close together for cputime_");
return 0;
}
Assert (totalTime > 0);
double cpu = usedSysTime * 100 / totalTime;
return Math::PinInRange<double> (cpu, 0, 100);
}
Info capture_ ()
{
Execution::SleepUntil (fPostponeCaptureUntil_);
Info result;
#if qSupport_SystemPerformance_Instruments_CPU_LoadAverage
{
double loadAve[3];
int lr = ::getloadavg (loadAve, 3);
if (lr == 3) {
result.fLoadAverage = Info::LoadAverage (loadAve[0], loadAve[1], loadAve[2]);
}
else {
DbgTrace ("getloadave failed - with result = %d", lr);
}
}
#endif
result.fTotalCPUUsage = cputime_ ();
NoteCompletedCapture_ ();
return result;
}
};
}
#endif
#if qPlatform_Windows
namespace {
struct CapturerWithContext_Windows_ : CapturerWithContext_COMMON_ {
struct WinSysTimeCaptureContext_ {
double IdleTime;
double KernelTime;
double UserTime;
};
WinSysTimeCaptureContext_ fContext_;
CapturerWithContext_Windows_ (const Options& options)
: CapturerWithContext_COMMON_ (options)
{
capture_ (); // Force fill of context
}
static inline double GetAsSeconds_ (FILETIME ft)
{
ULARGE_INTEGER ui;
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
// convert from 100-nanosecond units
return static_cast<double> (ui.QuadPart) / 10000000;
}
static inline WinSysTimeCaptureContext_ GetSysTimes_ ()
{
FILETIME curIdleTime_;
FILETIME curKernelTime_;
FILETIME curUserTime_;
memset (&curIdleTime_, 0, sizeof (curIdleTime_));
memset (&curKernelTime_, 0, sizeof (curKernelTime_));
memset (&curUserTime_, 0, sizeof (curUserTime_));
Verify (::GetSystemTimes (&curIdleTime_, &curKernelTime_, &curUserTime_));
return WinSysTimeCaptureContext_ { GetAsSeconds_ (curIdleTime_), GetAsSeconds_ (curKernelTime_), GetAsSeconds_ (curUserTime_) };
}
double cputime_ ()
{
WinSysTimeCaptureContext_ baseline = fContext_;
WinSysTimeCaptureContext_ newVal = GetSysTimes_ ();
fContext_ = newVal;
double idleTimeOverInterval = newVal.IdleTime - baseline.IdleTime;
double kernelTimeOverInterval = newVal.KernelTime - baseline.KernelTime;
double userTimeOverInterval = newVal.UserTime - baseline.UserTime;
double sys = kernelTimeOverInterval + userTimeOverInterval;
Assert (sys > 0);
double cpu = (sys - idleTimeOverInterval) * 100 / sys;
return Math::PinInRange<double> (cpu, 0, 100);
}
Info capture_ ()
{
Info result;
Execution::SleepUntil (fPostponeCaptureUntil_);
result.fTotalCPUUsage = cputime_ ();
NoteCompletedCapture_ ();
return result;
}
};
}
#endif
namespace {
struct CapturerWithContext_
: Debug::AssertExternallySynchronizedLock
#if qPlatform_POSIX
, CapturerWithContext_POSIX_
#elif qPlatform_Windows
, CapturerWithContext_Windows_
#endif
{
#if qPlatform_POSIX
using inherited = CapturerWithContext_POSIX_;
#elif qPlatform_Windows
using inherited = CapturerWithContext_Windows_;
#endif
CapturerWithContext_ (Options options)
: inherited (options)
{
}
Info capture_ ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx ("Instruments::CPU capture_");
#endif
return inherited::capture_ ();
}
};
}
/*
********************************************************************************
************************* Instruments::CPU::GetInstrument **********************
********************************************************************************
*/
Instrument SystemPerformance::Instruments::CPU::GetInstrument (Options options)
{
CapturerWithContext_ useCaptureContext { options }; // capture context so copyable in mutable lambda
static const MeasurementType kCPUMeasurment_ = MeasurementType (String_Constant (L"CPU-Usage"));
return Instrument (
InstrumentNameType (String_Constant (L"CPU")),
[useCaptureContext] () mutable -> MeasurementSet {
MeasurementSet results;
DateTime before = useCaptureContext.fLastCapturedAt;
Info rawMeasurement = useCaptureContext.capture_ ();
results.fMeasuredAt = DateTimeRange (before, useCaptureContext.fLastCapturedAt);
Measurement m;
m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement);
m.fType = kCPUMeasurment_;
results.fMeasurements.Add (m);
return results;
},
{kCPUMeasurment_},
GetObjectVariantMapper ()
);
}
<commit_msg>Comments<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <Windows.h>
#endif
#include "../../../Foundation/Characters/String_Constant.h"
#include "../../../Foundation/Characters/String2Float.h"
#include "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h"
#include "../../../Foundation/Debug/Assertions.h"
#include "../../../Foundation/Execution/Sleep.h"
#include "../../../Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include "../../../Foundation/Math/Common.h"
#include "CPU.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using namespace Stroika::Frameworks::SystemPerformance::Instruments::CPU;
using Characters::String_Constant;
using Time::DurationSecondsType;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
#if qSupport_SystemPerformance_Instruments_CPU_LoadAverage
/*
********************************************************************************
*********************** Instruments::CPU::Info::LoadAverage ********************
********************************************************************************
*/
Instruments::CPU::Info::LoadAverage::LoadAverage (double oneMinuteAve, double fiveMinuteAve, double fifteenMinuteAve)
: f1MinuteAve (oneMinuteAve)
, f5MinuteAve (fiveMinuteAve)
, f15MinuteAve (fifteenMinuteAve)
{
}
#endif
/*
********************************************************************************
***************** Instruments::CPU::GetObjectVariantMapper *********************
********************************************************************************
*/
ObjectVariantMapper Instruments::CPU::GetObjectVariantMapper ()
{
using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
#if qSupport_SystemPerformance_Instruments_CPU_LoadAverage
mapper.AddClass<Info::LoadAverage> (initializer_list<StructureFieldInfo> {
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f1MinuteAve), String_Constant (L"1-minute") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f5MinuteAve), String_Constant (L"5-minute") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f15MinuteAve), String_Constant (L"15-minute") },
});
mapper.AddCommonType<Optional_Indirect_Storage<Info::LoadAverage>> ();
#endif
mapper.AddClass<Info> (initializer_list<StructureFieldInfo> {
#if qSupport_SystemPerformance_Instruments_CPU_LoadAverage
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLoadAverage), String_Constant (L"Load-Average"), StructureFieldInfo::NullFieldHandling::eOmit },
#endif
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fTotalCPUUsage), String_Constant (L"Total-CPU-Usage") },
});
DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
return mapper;
} ();
return sMapper_;
}
namespace {
struct CapturerWithContext_COMMON_ {
Options fOptions_;
DurationSecondsType fPostponeCaptureUntil_ { 0 };
DateTime fLastCapturedAt;
DurationSecondsType fMinimumAveragingInterval_;
CapturerWithContext_COMMON_ (const Options& options)
: fOptions_ (options)
, fMinimumAveragingInterval_ (options.fMinimumAveragingInterval)
{
}
void NoteCompletedCapture_ ()
{
fPostponeCaptureUntil_ = Time::GetTickCount () + fMinimumAveragingInterval_;
fLastCapturedAt = DateTime::Now ();
}
};
}
#if qPlatform_POSIX
namespace {
struct CapturerWithContext_POSIX_ : CapturerWithContext_COMMON_ {
struct POSIXSysTimeCaptureContext_ {
double user;
//double nice;
double system;
double idle;
};
POSIXSysTimeCaptureContext_ fContext_ {};
CapturerWithContext_POSIX_ (const Options& options)
: CapturerWithContext_COMMON_ (options)
{
capture_ (); // Force fill of context - ignore results
}
/*
* /proc/stat
* EXAMPLE:
* lewis@LewisLinuxDevVM2:~$ cat /proc/stat
* cpu 361378 1170 50632 2812384 5609 3 2684 0 0 0
* cpu0 202907 894 27261 1382587 3014 3 2672 0 0 0
* cpu1 158471 276 23371 1429797 2595 0 12 0 0 0
*
* From http://man7.org/linux/man-pages/man5/proc.5.html
*
* kernel/system statistics. Varies with architecture. Common
* entries include:
*
* cpu 3357 0 4313 1362393
* The amount of time, measured in units of USER_HZ
* (1/100ths of a second on most architectures, use
* sysconf(_SC_CLK_TCK) to obtain the right value), that
* the system spent in various states:
*
* user (1) Time spent in user mode.
*
* nice (2) Time spent in user mode with low priority
* (nice).
*
* system (3) Time spent in system mode.
*
* idle (4) Time spent in the idle task. This value
* should be USER_HZ times the second entry in the
* /proc/uptime pseudo-file.
*/
static inline POSIXSysTimeCaptureContext_ GetSysTimes_ ()
{
POSIXSysTimeCaptureContext_ result;
using IO::FileSystem::BinaryFileInputStream;
using Characters::String2Float;
DataExchange::CharacterDelimitedLines::Reader reader {{' ', '\t' }};
const String_Constant kFileName_ { L"/proc/stat" };
// Note - /procfs files always unseekable
for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kFileName_, BinaryFileInputStream::eNotSeekable))) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"***in Instruments::CPU::capture_GetSysTimes_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ());
#endif
if (line.size () >= 5 and line[0] == L"cpu") {
result.user = String2Float<double> (line[1]);
result.system = String2Float<double> (line[3]);
result.idle = String2Float<double> (line[4]);
break; // once found no need to read the rest...
}
}
return result;
}
double cputime_ ()
{
POSIXSysTimeCaptureContext_ baseline = fContext_;
POSIXSysTimeCaptureContext_ newVal = GetSysTimes_ ();
fContext_ = newVal;
double usedSysTime = (newVal.user - baseline.user) + (newVal.system - baseline.system);
double totalTime = usedSysTime + (newVal.idle - baseline.idle);
if (Math::NearlyEquals<double> (totalTime, 0)) {
// can happen if called too quickly together. No good answer
DbgTrace ("Warning - times too close together for cputime_");
return 0;
}
Assert (totalTime > 0);
double cpu = usedSysTime * 100 / totalTime;
return Math::PinInRange<double> (cpu, 0, 100);
}
Info capture_ ()
{
Execution::SleepUntil (fPostponeCaptureUntil_);
Info result;
#if qSupport_SystemPerformance_Instruments_CPU_LoadAverage
{
double loadAve[3];
int lr = ::getloadavg (loadAve, 3);
if (lr == 3) {
result.fLoadAverage = Info::LoadAverage (loadAve[0], loadAve[1], loadAve[2]);
}
else {
DbgTrace ("getloadave failed - with result = %d", lr);
}
}
#endif
result.fTotalCPUUsage = cputime_ ();
NoteCompletedCapture_ ();
return result;
}
};
}
#endif
#if qPlatform_Windows
namespace {
struct CapturerWithContext_Windows_ : CapturerWithContext_COMMON_ {
struct WinSysTimeCaptureContext_ {
double IdleTime;
double KernelTime;
double UserTime;
};
WinSysTimeCaptureContext_ fContext_;
CapturerWithContext_Windows_ (const Options& options)
: CapturerWithContext_COMMON_ (options)
{
capture_ (); // Force fill of context
}
static inline double GetAsSeconds_ (FILETIME ft)
{
ULARGE_INTEGER ui;
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
// convert from 100-nanosecond units
return static_cast<double> (ui.QuadPart) / 10000000;
}
static inline WinSysTimeCaptureContext_ GetSysTimes_ ()
{
FILETIME curIdleTime_;
FILETIME curKernelTime_;
FILETIME curUserTime_;
memset (&curIdleTime_, 0, sizeof (curIdleTime_));
memset (&curKernelTime_, 0, sizeof (curKernelTime_));
memset (&curUserTime_, 0, sizeof (curUserTime_));
Verify (::GetSystemTimes (&curIdleTime_, &curKernelTime_, &curUserTime_));
return WinSysTimeCaptureContext_ { GetAsSeconds_ (curIdleTime_), GetAsSeconds_ (curKernelTime_), GetAsSeconds_ (curUserTime_) };
}
double cputime_ ()
{
/*
* This logic seems queer (sys = kern + user, and why isnt numerator userTime?), but is cribbed from
* http://en.literateprograms.org/CPU_usage_%28C,_Windows_XP%29
* http://www.codeproject.com/Articles/9113/Get-CPU-Usage-with-GetSystemTimes
*/
WinSysTimeCaptureContext_ baseline = fContext_;
WinSysTimeCaptureContext_ newVal = GetSysTimes_ ();
fContext_ = newVal;
double idleTimeOverInterval = newVal.IdleTime - baseline.IdleTime;
double kernelTimeOverInterval = newVal.KernelTime - baseline.KernelTime;
double userTimeOverInterval = newVal.UserTime - baseline.UserTime;
double sys = kernelTimeOverInterval + userTimeOverInterval;
Assert (sys > 0);
double cpu = (sys - idleTimeOverInterval) * 100 / sys;
return Math::PinInRange<double> (cpu, 0, 100);
}
Info capture_ ()
{
Info result;
Execution::SleepUntil (fPostponeCaptureUntil_);
result.fTotalCPUUsage = cputime_ ();
NoteCompletedCapture_ ();
return result;
}
};
}
#endif
namespace {
struct CapturerWithContext_
: Debug::AssertExternallySynchronizedLock
#if qPlatform_POSIX
, CapturerWithContext_POSIX_
#elif qPlatform_Windows
, CapturerWithContext_Windows_
#endif
{
#if qPlatform_POSIX
using inherited = CapturerWithContext_POSIX_;
#elif qPlatform_Windows
using inherited = CapturerWithContext_Windows_;
#endif
CapturerWithContext_ (Options options)
: inherited (options)
{
}
Info capture_ ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx ("Instruments::CPU capture_");
#endif
return inherited::capture_ ();
}
};
}
/*
********************************************************************************
************************* Instruments::CPU::GetInstrument **********************
********************************************************************************
*/
Instrument SystemPerformance::Instruments::CPU::GetInstrument (Options options)
{
CapturerWithContext_ useCaptureContext { options }; // capture context so copyable in mutable lambda
static const MeasurementType kCPUMeasurment_ = MeasurementType (String_Constant (L"CPU-Usage"));
return Instrument (
InstrumentNameType (String_Constant (L"CPU")),
[useCaptureContext] () mutable -> MeasurementSet {
MeasurementSet results;
DateTime before = useCaptureContext.fLastCapturedAt;
Info rawMeasurement = useCaptureContext.capture_ ();
results.fMeasuredAt = DateTimeRange (before, useCaptureContext.fLastCapturedAt);
Measurement m;
m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement);
m.fType = kCPUMeasurment_;
results.fMeasurements.Add (m);
return results;
},
{kCPUMeasurment_},
GetObjectVariantMapper ()
);
}
<|endoftext|>
|
<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */
//#include <algorithm>
//#include <memory>
#include <multigrid/mgmesytec/Data.h>
#include <multigrid/mgmesytec/TestData.h>
#include <test/TestBase.h>
class MesytecDataTest : public TestBase {
protected:
MesytecData mesytec;
virtual void SetUp() { }
virtual void TearDown() { }
};
/** Test cases below */
TEST_F(MesytecDataTest, ErrUnsupportedCommand) {
auto res = mesytec.parse((char *)&err_unsupported_cmd[0], err_unsupported_cmd.size());
ASSERT_EQ(res, -MesytecData::error::EUNSUPP);
}
TEST_F(MesytecDataTest, ErrPktShort) {
auto res = mesytec.parse((char *)&err_pkt_too_short[0], err_pkt_too_short.size());
ASSERT_EQ(res, -MesytecData::error::ESIZE);
}
TEST_F(MesytecDataTest, ParseRecordedWSData) {
auto res = mesytec.parse((char *)&ws1[0], ws1.size());
ASSERT_EQ(res, -MesytecData::error::OK);
ASSERT_EQ(mesytec.readouts, 128 - (128-92)); // Readout provides more than 92 channels
}
TEST_F(MesytecDataTest, ParseRecordedWSDataII) {
auto res = mesytec.parse((char *)&ws2[0], ws2.size());
ASSERT_EQ(res, -MesytecData::error::OK);
ASSERT_EQ(mesytec.readouts, 256 - 2*(128-92)); // Readout provides more than 92 channels
}
TEST_F(MesytecDataTest, ParseRecordedWSDataIII) {
auto res = mesytec.parse((char *)&ws3[0], ws3.size());
ASSERT_EQ(res, -MesytecData::error::OK);
ASSERT_EQ(mesytec.readouts, 256 - 2*(128-92)); // Readout provides more than 92 channels
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>do not suppress unused channels, for now<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */
//#include <algorithm>
//#include <memory>
#include <multigrid/mgmesytec/Data.h>
#include <multigrid/mgmesytec/TestData.h>
#include <test/TestBase.h>
class MesytecDataTest : public TestBase {
protected:
MesytecData mesytec;
virtual void SetUp() { }
virtual void TearDown() { }
};
/** Test cases below */
TEST_F(MesytecDataTest, ErrUnsupportedCommand) {
auto res = mesytec.parse((char *)&err_unsupported_cmd[0], err_unsupported_cmd.size());
ASSERT_EQ(res, -MesytecData::error::EUNSUPP);
}
TEST_F(MesytecDataTest, ErrPktShort) {
auto res = mesytec.parse((char *)&err_pkt_too_short[0], err_pkt_too_short.size());
ASSERT_EQ(res, -MesytecData::error::ESIZE);
}
TEST_F(MesytecDataTest, ParseRecordedWSData) {
auto res = mesytec.parse((char *)&ws1[0], ws1.size());
ASSERT_EQ(res, -MesytecData::error::OK);
ASSERT_EQ(mesytec.readouts, 128);
}
TEST_F(MesytecDataTest, ParseRecordedWSDataII) {
auto res = mesytec.parse((char *)&ws2[0], ws2.size());
ASSERT_EQ(res, -MesytecData::error::OK);
ASSERT_EQ(mesytec.readouts, 256);
}
TEST_F(MesytecDataTest, ParseRecordedWSDataIII) {
auto res = mesytec.parse((char *)&ws3[0], ws3.size());
ASSERT_EQ(res, -MesytecData::error::OK);
ASSERT_EQ(mesytec.readouts, 256); // Readout provides more than 92 channels
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>/*
* InstrumentImplementation.cpp
*
* Created on: 31/10/2010
* Author: victor
*/
#include "server/zone/objects/tangible/Instrument.h"
#include "server/zone/objects/tangible/InstrumentObserver.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/managers/object/ObjectManager.h"
#include "server/zone/objects/cell/CellObject.h"
#include "server/zone/objects/structure/StructureObject.h"
#include "server/zone/Zone.h"
void InstrumentImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) {
if (instrumentType != OMNIBOX && instrumentType != NALARGON)
return;
if (canDropInstrument()) {
ManagedReference<SceneObject*> parent = getParentRecursively(SceneObjectType::PLAYERCREATURE).get();
if (parent != NULL && parent == player->asSceneObject())
menuResponse->addRadialMenuItem(20, 3, "@ui_radial:item_use");
} else {
if (spawnerPlayer != NULL && spawnerPlayer == player) {
if (!player->isPlayingMusic())
menuResponse->addRadialMenuItem(20, 3, "@radial_performance:play_instrument");
else
menuResponse->addRadialMenuItem(20, 3, "@radial_performance:stop_playing");
}
}
}
int InstrumentImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
if (instrumentType != OMNIBOX && instrumentType != NALARGON)
return 1;
if (selectedID != 20)
return 1;
if (canDropInstrument()) {
ManagedReference<SceneObject*> parent = getParentRecursively(SceneObjectType::PLAYERCREATURE).get();
if (parent == NULL || parent != player->asSceneObject())
return 1;
if (player->isSkillAnimating()) {
player->sendSystemMessage("@performance:music_fail"); // You are unable to do that at this time.
return 1;
}
SortedVector<ManagedReference<Observer* > > observers = player->getObservers(ObserverEventType::POSITIONCHANGED);
for (int i = 0; i < observers.size(); ++i) {
InstrumentObserver* observer = dynamic_cast<InstrumentObserver*>(observers.get(i).get());
if (observer != NULL) {
ManagedReference<Instrument*> oldInstrument = observer->getInstrument().get();
if (oldInstrument != NULL) {
Locker locker(oldInstrument);
oldInstrument->destroyObjectFromWorld(true);
player->dropObserver(ObserverEventType::POSITIONCHANGED, observer);
player->dropObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, observer);
}
}
}
ManagedReference<SceneObject*> playerParent = player->getParent();
if (playerParent != NULL) {
if (!playerParent->isCellObject()) {
return 1;
} else {
CellObject* cell = cast<CellObject*>( playerParent.get());
StructureObject* structureObject = dynamic_cast<StructureObject*>(cell->getParent().get().get());
if (structureObject == NULL)
return 1;
if (!structureObject->isOnAdminList(player))
spawnNonAdmin(player);
else {
spawnInAdminCell(player);
}
}
} else {
spawnNonAdmin(player);
}
} else {
if (getZone() == NULL)
return 1;
if (spawnerPlayer == NULL || spawnerPlayer != player)
return 1;
if (player->isPlayingMusic()) {
player->executeObjectControllerAction(STRING_HASHCODE("stopmusic"), getObjectID(), "");
} else {
Reference<Instrument*> instrument = player->getSlottedObject("hold_r").castTo<Instrument*>();
if (instrument != NULL) {
player->sendSystemMessage("@performance:music_must_unequip");
return 1;
}
Reference<PlayerObject*> ghost = player->getSlottedObject("ghost").castTo<PlayerObject*>();
if (ghost == NULL)
return 1;
if (!ghost->hasAbility("startmusic")) {
player->sendSystemMessage("@performance:music_lack_skill_instrument");
return 1;
}
if (player->getDistanceTo(_this.getReferenceUnsafeStaticCast()) >= 5) {
player->sendSystemMessage("@elevator_text:too_far");
} else
player->executeObjectControllerAction(STRING_HASHCODE("startmusic"), getObjectID(), "");
}
}
return 0;
}
bool InstrumentImplementation::canDropInstrument() {
ManagedReference<SceneObject*> parent = getParent().get();
if (isInQuadTree() || (parent != NULL && parent->isCellObject()))
return false;
return true;
}
void InstrumentImplementation::spawnNonAdmin(CreatureObject* player) {
if (spawnedObject == NULL) {
spawnedObject = ObjectManager::instance()->createObject(serverObjectCRC, 0, "sceneobjects");
spawnedObject->setParent(NULL);
spawnedObject->setZone(NULL);
}
if (spawnedObject->getZone() == NULL) {
Instrument* instrument = cast<Instrument*>( spawnedObject.get());
Locker locker(instrument);
instrument->initializePosition(player->getPositionX(), player->getPositionZ(), player->getPositionY());
instrument->setSpawnerPlayer(player);
ManagedReference<SceneObject*> parent = player->getParent().get();
Zone* zone = player->getZone();
if (parent != NULL) {
parent->transferObject(instrument, -1);
} else if (zone != NULL) {
zone->transferObject(instrument, -1, true);
} else {
return;
}
ManagedReference<InstrumentObserver*> posObserver = new InstrumentObserver(instrument);
player->registerObserver(ObserverEventType::POSITIONCHANGED, posObserver);
player->registerObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, posObserver);
} else {
spawnedObject->teleport(player->getPositionX(), player->getPositionZ(), player->getPositionY(), player->getParentID());
}
spawnerPlayer = player;
}
void InstrumentImplementation::spawnInAdminCell(CreatureObject* player) {
StringBuffer arguments;
arguments << player->getParent().get()->getObjectID() << " -1 " << player->getPositionX() << " " << player->getPositionZ() << " " << player->getPositionY();
UnicodeString uni = arguments.toString();
player->executeObjectControllerAction(STRING_HASHCODE("transferitemmisc"), _this.getReferenceUnsafeStaticCast()->getObjectID(), uni);
spawnerPlayer = NULL;
if (spawnedObject != NULL) {
Locker locker(spawnedObject);
spawnedObject->destroyObjectFromWorld(true);
spawnedObject = NULL;
}
}
<commit_msg>[fixed] Droppable instrument pickup bug - mantis 6170<commit_after>/*
* InstrumentImplementation.cpp
*
* Created on: 31/10/2010
* Author: victor
*/
#include "server/zone/objects/tangible/Instrument.h"
#include "server/zone/objects/tangible/InstrumentObserver.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/managers/object/ObjectManager.h"
#include "server/zone/objects/cell/CellObject.h"
#include "server/zone/objects/structure/StructureObject.h"
#include "server/zone/Zone.h"
void InstrumentImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) {
if (instrumentType != OMNIBOX && instrumentType != NALARGON)
return;
if (canDropInstrument()) {
ManagedReference<SceneObject*> parent = getParentRecursively(SceneObjectType::PLAYERCREATURE).get();
if (parent != NULL && parent == player->asSceneObject())
menuResponse->addRadialMenuItem(20, 3, "@ui_radial:item_use");
} else {
if (spawnerPlayer != NULL && spawnerPlayer == player) {
if (!player->isPlayingMusic())
menuResponse->addRadialMenuItem(20, 3, "@radial_performance:play_instrument");
else
menuResponse->addRadialMenuItem(20, 3, "@radial_performance:stop_playing");
}
}
TangibleObjectImplementation::fillObjectMenuResponse(menuResponse, player);
}
int InstrumentImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
if (instrumentType != OMNIBOX && instrumentType != NALARGON)
return 1;
if (selectedID != 20)
return 1;
if (canDropInstrument()) {
ManagedReference<SceneObject*> parent = getParentRecursively(SceneObjectType::PLAYERCREATURE).get();
if (parent == NULL || parent != player->asSceneObject())
return 1;
if (player->isSkillAnimating()) {
player->sendSystemMessage("@performance:music_fail"); // You are unable to do that at this time.
return 1;
}
SortedVector<ManagedReference<Observer* > > observers = player->getObservers(ObserverEventType::POSITIONCHANGED);
for (int i = 0; i < observers.size(); ++i) {
InstrumentObserver* observer = dynamic_cast<InstrumentObserver*>(observers.get(i).get());
if (observer != NULL) {
ManagedReference<Instrument*> oldInstrument = observer->getInstrument().get();
if (oldInstrument != NULL) {
Locker locker(oldInstrument);
oldInstrument->destroyObjectFromWorld(true);
player->dropObserver(ObserverEventType::POSITIONCHANGED, observer);
player->dropObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, observer);
}
}
}
ManagedReference<SceneObject*> playerParent = player->getParent();
if (playerParent != NULL) {
if (!playerParent->isCellObject()) {
return 1;
} else {
CellObject* cell = cast<CellObject*>( playerParent.get());
StructureObject* structureObject = dynamic_cast<StructureObject*>(cell->getParent().get().get());
if (structureObject == NULL)
return 1;
if (!structureObject->isOnAdminList(player))
spawnNonAdmin(player);
else {
spawnInAdminCell(player);
}
}
} else {
spawnNonAdmin(player);
}
} else {
if (getZone() == NULL)
return 1;
if (spawnerPlayer == NULL || spawnerPlayer != player)
return 1;
if (player->isPlayingMusic()) {
player->executeObjectControllerAction(STRING_HASHCODE("stopmusic"), getObjectID(), "");
} else {
Reference<Instrument*> instrument = player->getSlottedObject("hold_r").castTo<Instrument*>();
if (instrument != NULL) {
player->sendSystemMessage("@performance:music_must_unequip");
return 1;
}
Reference<PlayerObject*> ghost = player->getSlottedObject("ghost").castTo<PlayerObject*>();
if (ghost == NULL)
return 1;
if (!ghost->hasAbility("startmusic")) {
player->sendSystemMessage("@performance:music_lack_skill_instrument");
return 1;
}
if (player->getDistanceTo(_this.getReferenceUnsafeStaticCast()) >= 5) {
player->sendSystemMessage("@elevator_text:too_far");
} else
player->executeObjectControllerAction(STRING_HASHCODE("startmusic"), getObjectID(), "");
}
}
return 0;
}
bool InstrumentImplementation::canDropInstrument() {
ManagedReference<SceneObject*> parent = getParent().get();
if (isInQuadTree() || (parent != NULL && parent->isCellObject()))
return false;
return true;
}
void InstrumentImplementation::spawnNonAdmin(CreatureObject* player) {
if (spawnedObject == NULL) {
spawnedObject = ObjectManager::instance()->createObject(serverObjectCRC, 0, "sceneobjects");
spawnedObject->setParent(NULL);
spawnedObject->setZone(NULL);
}
if (spawnedObject->getZone() == NULL) {
Instrument* instrument = cast<Instrument*>( spawnedObject.get());
Locker locker(instrument);
instrument->initializePosition(player->getPositionX(), player->getPositionZ(), player->getPositionY());
instrument->setSpawnerPlayer(player);
ManagedReference<SceneObject*> parent = player->getParent().get();
Zone* zone = player->getZone();
if (parent != NULL) {
parent->transferObject(instrument, -1);
} else if (zone != NULL) {
zone->transferObject(instrument, -1, true);
} else {
return;
}
ManagedReference<InstrumentObserver*> posObserver = new InstrumentObserver(instrument);
player->registerObserver(ObserverEventType::POSITIONCHANGED, posObserver);
player->registerObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, posObserver);
} else {
spawnedObject->teleport(player->getPositionX(), player->getPositionZ(), player->getPositionY(), player->getParentID());
}
spawnerPlayer = player;
}
void InstrumentImplementation::spawnInAdminCell(CreatureObject* player) {
StringBuffer arguments;
arguments << player->getParent().get()->getObjectID() << " -1 " << player->getPositionX() << " " << player->getPositionZ() << " " << player->getPositionY();
UnicodeString uni = arguments.toString();
player->executeObjectControllerAction(STRING_HASHCODE("transferitemmisc"), _this.getReferenceUnsafeStaticCast()->getObjectID(), uni);
spawnerPlayer = NULL;
if (spawnedObject != NULL) {
Locker locker(spawnedObject);
spawnedObject->destroyObjectFromWorld(true);
spawnedObject = NULL;
}
}
<|endoftext|>
|
<commit_before>#include "AngleControl.h"
AngleControl::AngleControl() {
// Use requires() here to declare subsystem dependencies
Requires(shooter);
}
// Called just before this Command runs the first time
void AngleControl::Initialize() {
}
// Called repeatedly when this Command is scheduled to run
void AngleControl::Execute() {
shooter->SetSpeedAngle(oi->GetDriverStickAxis(false,2));
SmartDashboard::PutNumber("Shooter Angle", shooter->AnglePotVoltage());
}
// Make this return true when this Command no longer needs to run execute()
bool AngleControl::IsFinished() {
return false;
}
// Called once after isFinished returns true
void AngleControl::End() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void AngleControl::Interrupted() {
}
<commit_msg>Direction change in AngleCtrl, Driver Pref<commit_after>#include "AngleControl.h"
AngleControl::AngleControl() {
// Use requires() here to declare subsystem dependencies
Requires(shooter);
}
// Called just before this Command runs the first time
void AngleControl::Initialize() {
}
// Called repeatedly when this Command is scheduled to run
void AngleControl::Execute() {
shooter->SetSpeedAngle(oi->GetDriverStickAxis(false,2) * -1);
SmartDashboard::PutNumber("Shooter Angle", shooter->AnglePotVoltage());
}
// Make this return true when this Command no longer needs to run execute()
bool AngleControl::IsFinished() {
return false;
}
// Called once after isFinished returns true
void AngleControl::End() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void AngleControl::Interrupted() {
}
<|endoftext|>
|
<commit_before>#include "BulletsConverter.h"
#include "StylesWriter.h"
using namespace PPT_FORMAT;
BulletsConverter::BulletsConverter(CRelsGenerator* pRels) : m_pRels(pRels) {}
void BulletsConverter::FillPPr(PPTX::Logic::TextParagraphPr &oPPr, CParagraph ¶graph)
{
oPPr.lvl = paragraph.m_lTextLevel;
auto* pPF = &(paragraph.m_oPFRun);
if (pPF)
ConvertPFRun(oPPr, pPF);
}
void BulletsConverter::ConvertPFRun(PPTX::Logic::TextParagraphPr &oPPr, CTextPFRun *pPF)
{
int leftMargin = 0;
if (pPF->leftMargin.is_init())
{
leftMargin = pPF->leftMargin.get();
oPPr.marL = leftMargin;
}
if (pPF->indent.is_init())
{
if (pPF->hasBullet.get_value_or(false) && pPF->indent.get() != -leftMargin)
{
oPPr.indent = pPF->indent.get() - leftMargin;
}
else
{
oPPr.indent = pPF->indent.get();
}
} else if (pPF->hasBullet.get_value_or(false))
{
oPPr.indent = -leftMargin;
}
if (pPF->textAlignment.is_init())
{
oPPr.algn = new PPTX::Limit::TextAlign;
oPPr.algn->set(CStylesWriter::GetTextAlign(pPF->textAlignment.get()));
}
if (pPF->defaultTabSize.is_init())
{
oPPr.defTabSz = pPF->defaultTabSize.get();
}
if (pPF->textDirection.is_init())
{
if (pPF->textDirection.get() == 1) oPPr.rtl = true;
else oPPr.rtl = false;
}
if (pPF->fontAlign.is_init())
{
oPPr.fontAlgn = new PPTX::Limit::FontAlign;
oPPr.fontAlgn->set(CStylesWriter::GetFontAlign(pPF->fontAlign.get()));
}
if (pPF->wrapFlags.is_init() && pPF->wrapFlags.get() & 0b111)
{
const auto& flags = pPF->wrapFlags.get();
if (flags & 0b100)
oPPr.hangingPunct = true;
}
ConvertTabStops(oPPr.tabLst, pPF->tabStops);
if (pPF->lineSpacing.is_init())
{
LONG val = pPF->lineSpacing.get();
auto pLnSpc = new PPTX::Logic::TextSpacing;
pLnSpc->m_name = L"a:lnSpc";
if (val > 0)
pLnSpc->spcPct = val * 12.5;
else if (val < 0 && val > -13200)
pLnSpc->spcPct = val * -1000;
oPPr.lnSpc = pLnSpc;
}
if (pPF->spaceAfter.is_init())
{
LONG val = pPF->spaceAfter.get();
auto pSpcAft = new PPTX::Logic::TextSpacing;
pSpcAft->m_name = L"a:spcAft";
if (val > 0)
pSpcAft->spcPts = round(12.5 * pPF->spaceAfter.get());
else if (val < 0 && val > -13200)
pSpcAft->spcPts = val * -1000;
oPPr.spcAft = pSpcAft;
}
if (pPF->spaceBefore.is_init())
{
LONG val = pPF->spaceBefore.get();
auto pSpcBef = new PPTX::Logic::TextSpacing;
pSpcBef->m_name = L"a:spcBef";
if (val > 0)
pSpcBef->spcPts = round(12.5 * pPF->spaceBefore.get());
else if (val < 0 && val > -13200)
pSpcBef->spcPct = val * -1000;
oPPr.spcBef = pSpcBef;
}
ConvertAllBullets(oPPr, pPF);
}
void BulletsConverter::ConvertTabStops(std::vector<PPTX::Logic::Tab> &arrTabs, std::vector<std::pair<int, int> > &arrTabStops)
{
for (size_t t = 0 ; t < arrTabStops.size(); t++)
{
PPTX::Logic::Tab tab;
tab.pos = arrTabStops[t].first;
auto pAlgn = new PPTX::Limit::TextTabAlignType;
switch (arrTabStops[t].second)
{
case 1: pAlgn->set(L"ctr"); break;
case 2: pAlgn->set(L"r"); break;
case 3: pAlgn->set(L"dec"); break;
default: pAlgn->set(L"l");
}
tab.algn = pAlgn;
arrTabs.push_back(tab);
}
}
void BulletsConverter::FillBuChar(PPTX::Logic::Bullet &oBullet, WCHAR symbol, CTextPFRun *pPF)
{
auto pBuChar = new PPTX::Logic::BuChar;
pBuChar->Char.clear();
if (pPF != nullptr && pPF->bulletFontProperties.IsInit())
{
const auto& fontProp = *(pPF->bulletFontProperties);
if (fontProp.Charset == 10)
{
symbol &= 0x00ff;
symbol |= 0xf000;
}
}
pBuChar->Char.push_back(symbol);
oBullet.m_Bullet.reset(pBuChar);
}
void BulletsConverter::ConvertAllBullets(PPTX::Logic::TextParagraphPr &oPPr, CTextPFRun *pPF)
{
if (pPF->hasBullet.is_init())
{
if (pPF->hasBullet.get())
{
if (pPF->bulletColor.is_init())
{
FillBuClr(oPPr.buColor, pPF->bulletColor.get());
}
if (pPF->bulletSize.is_init())
{
PPTX::WrapperWritingElement* pBuSize(nullptr);
if (pPF->bulletSize.get() > 24 && pPF->bulletSize.get() < 401)
{
pBuSize = new PPTX::Logic::BuSzPct;
static_cast<PPTX::Logic::BuSzPct*>(pBuSize)->val = pPF->bulletSize.get() * 1000 ;
}
if (pPF->bulletSize.get() < 0 && pPF->bulletSize.get() > -4001)
{
pBuSize = new PPTX::Logic::BuSzPts;
static_cast<PPTX::Logic::BuSzPts*>(pBuSize)->val = - (pPF->bulletSize.get());
}
if (pBuSize != nullptr)
oPPr.buSize.m_Size = pBuSize;
}
if (pPF->bulletFontProperties.is_init())
{
auto pBuFont = new PPTX::Logic::TextFont;
pBuFont->m_name = L"a:buFont";
pBuFont->typeface = pPF->bulletFontProperties->Name;
if ( pPF->bulletFontProperties->PitchFamily > 0)
pBuFont->pitchFamily = std::to_wstring(pPF->bulletFontProperties->PitchFamily);
if ( pPF->bulletFontProperties->Charset > 0)
pBuFont->charset = std::to_wstring(pPF->bulletFontProperties->Charset);
oPPr.buTypeface.m_Typeface.reset(pBuFont);
}
// Bullets (numbering, else picture, else char, else default)
if (pPF->bulletBlip.is_init() && pPF->bulletBlip->tmpImagePath.size() && m_pRels != nullptr)
{
auto strRID = m_pRels->WriteImage(pPF->bulletBlip->tmpImagePath);
if (strRID.empty())
FillBuChar(oPPr.ParagraphBullet, L'\x2022'); // error rId
else
{
auto pBuBlip = new PPTX::Logic::BuBlip;
pBuBlip->blip.embed = new OOX::RId(strRID);
oPPr.ParagraphBullet.m_Bullet.reset(pBuBlip);
}
}
else if (pPF->bulletAutoNum.is_init())
{
auto pBuAutoNum = new PPTX::Logic::BuAutoNum;
oPPr.ParagraphBullet.m_Bullet.reset(pBuAutoNum);
if (pPF->bulletAutoNum->startAt.is_init() && pPF->bulletAutoNum->startAt.get() != 1)
pBuAutoNum->startAt = pPF->bulletAutoNum->startAt.get();
if (pPF->bulletAutoNum->type.is_init())
pBuAutoNum->type = pPF->bulletAutoNum->type.get();
}
else if (pPF->bulletChar.is_init())
{
FillBuChar(oPPr.ParagraphBullet, pPF->bulletChar.get(), pPF);
}
else
{
FillBuChar(oPPr.ParagraphBullet, L'\x2022');
}
}
else
{
oPPr.buTypeface.m_Typeface.reset(new PPTX::Logic::BuNone);
}
}
}
void BulletsConverter::FillBuClr(PPTX::Logic::BulletColor &oBuClr, CColor &oColor)
{
auto pBuClr = new PPTX::Logic::BuClr;
pBuClr->Color.SetRGBColor(oColor.GetR(), oColor.GetG(), oColor.GetB());
oBuClr.m_Color.reset(pBuClr);
}
<commit_msg>fix bug #57029<commit_after>#include "BulletsConverter.h"
#include "StylesWriter.h"
using namespace PPT_FORMAT;
BulletsConverter::BulletsConverter(CRelsGenerator* pRels) : m_pRels(pRels) {}
void BulletsConverter::FillPPr(PPTX::Logic::TextParagraphPr &oPPr, CParagraph ¶graph)
{
oPPr.lvl = paragraph.m_lTextLevel;
auto* pPF = &(paragraph.m_oPFRun);
if (pPF)
ConvertPFRun(oPPr, pPF);
}
void BulletsConverter::ConvertPFRun(PPTX::Logic::TextParagraphPr &oPPr, CTextPFRun *pPF)
{
const int oneTabSize = 457200;
int leftMargin = 0;
if (pPF->leftMargin.is_init())
{
leftMargin = pPF->leftMargin.get();
oPPr.marL = leftMargin;
}
if (pPF->indent.is_init())
{
if (pPF->hasBullet.get_value_or(false) && pPF->indent.get() != -leftMargin)
{
oPPr.indent = pPF->indent.get() - leftMargin;
}
else
{
oPPr.indent = pPF->indent.get();
}
} else if (pPF->hasBullet.get_value_or(false))
{
const int tabLvl = oPPr.lvl.get_value_or(0);
if (tabLvl != -1)
oPPr.indent = oneTabSize*tabLvl - leftMargin;
else
oPPr.indent = -leftMargin;
}
if (pPF->textAlignment.is_init())
{
oPPr.algn = new PPTX::Limit::TextAlign;
oPPr.algn->set(CStylesWriter::GetTextAlign(pPF->textAlignment.get()));
}
if (pPF->defaultTabSize.is_init())
{
oPPr.defTabSz = pPF->defaultTabSize.get();
}
if (pPF->textDirection.is_init())
{
if (pPF->textDirection.get() == 1) oPPr.rtl = true;
else oPPr.rtl = false;
}
if (pPF->fontAlign.is_init())
{
oPPr.fontAlgn = new PPTX::Limit::FontAlign;
oPPr.fontAlgn->set(CStylesWriter::GetFontAlign(pPF->fontAlign.get()));
}
if (pPF->wrapFlags.is_init() && pPF->wrapFlags.get() & 0b111)
{
const auto& flags = pPF->wrapFlags.get();
if (flags & 0b100)
oPPr.hangingPunct = true;
}
ConvertTabStops(oPPr.tabLst, pPF->tabStops);
if (pPF->lineSpacing.is_init())
{
LONG val = pPF->lineSpacing.get();
auto pLnSpc = new PPTX::Logic::TextSpacing;
pLnSpc->m_name = L"a:lnSpc";
if (val > 0)
pLnSpc->spcPct = val * 12.5;
else if (val < 0 && val > -13200)
pLnSpc->spcPct = val * -1000;
oPPr.lnSpc = pLnSpc;
}
if (pPF->spaceAfter.is_init())
{
LONG val = pPF->spaceAfter.get();
auto pSpcAft = new PPTX::Logic::TextSpacing;
pSpcAft->m_name = L"a:spcAft";
if (val > 0)
pSpcAft->spcPts = round(12.5 * pPF->spaceAfter.get());
else if (val < 0 && val > -13200)
pSpcAft->spcPts = val * -1000;
oPPr.spcAft = pSpcAft;
}
if (pPF->spaceBefore.is_init())
{
LONG val = pPF->spaceBefore.get();
auto pSpcBef = new PPTX::Logic::TextSpacing;
pSpcBef->m_name = L"a:spcBef";
if (val > 0)
pSpcBef->spcPts = round(12.5 * pPF->spaceBefore.get());
else if (val < 0 && val > -13200)
pSpcBef->spcPct = val * -1000;
oPPr.spcBef = pSpcBef;
}
ConvertAllBullets(oPPr, pPF);
}
void BulletsConverter::ConvertTabStops(std::vector<PPTX::Logic::Tab> &arrTabs, std::vector<std::pair<int, int> > &arrTabStops)
{
for (size_t t = 0 ; t < arrTabStops.size(); t++)
{
PPTX::Logic::Tab tab;
tab.pos = arrTabStops[t].first;
auto pAlgn = new PPTX::Limit::TextTabAlignType;
switch (arrTabStops[t].second)
{
case 1: pAlgn->set(L"ctr"); break;
case 2: pAlgn->set(L"r"); break;
case 3: pAlgn->set(L"dec"); break;
default: pAlgn->set(L"l");
}
tab.algn = pAlgn;
arrTabs.push_back(tab);
}
}
void BulletsConverter::FillBuChar(PPTX::Logic::Bullet &oBullet, WCHAR symbol, CTextPFRun *pPF)
{
auto pBuChar = new PPTX::Logic::BuChar;
pBuChar->Char.clear();
if (pPF != nullptr && pPF->bulletFontProperties.IsInit())
{
const auto& fontProp = *(pPF->bulletFontProperties);
if (fontProp.Charset == 10)
{
symbol &= 0x00ff;
symbol |= 0xf000;
}
}
pBuChar->Char.push_back(symbol);
oBullet.m_Bullet.reset(pBuChar);
}
void BulletsConverter::ConvertAllBullets(PPTX::Logic::TextParagraphPr &oPPr, CTextPFRun *pPF)
{
if (pPF->hasBullet.is_init())
{
if (pPF->hasBullet.get())
{
if (pPF->bulletColor.is_init())
{
FillBuClr(oPPr.buColor, pPF->bulletColor.get());
}
if (pPF->bulletSize.is_init())
{
PPTX::WrapperWritingElement* pBuSize(nullptr);
if (pPF->bulletSize.get() > 24 && pPF->bulletSize.get() < 401)
{
pBuSize = new PPTX::Logic::BuSzPct;
static_cast<PPTX::Logic::BuSzPct*>(pBuSize)->val = pPF->bulletSize.get() * 1000 ;
}
if (pPF->bulletSize.get() < 0 && pPF->bulletSize.get() > -4001)
{
pBuSize = new PPTX::Logic::BuSzPts;
static_cast<PPTX::Logic::BuSzPts*>(pBuSize)->val = - (pPF->bulletSize.get());
}
if (pBuSize != nullptr)
oPPr.buSize.m_Size = pBuSize;
}
if (pPF->bulletFontProperties.is_init())
{
auto pBuFont = new PPTX::Logic::TextFont;
pBuFont->m_name = L"a:buFont";
pBuFont->typeface = pPF->bulletFontProperties->Name;
if ( pPF->bulletFontProperties->PitchFamily > 0)
pBuFont->pitchFamily = std::to_wstring(pPF->bulletFontProperties->PitchFamily);
if ( pPF->bulletFontProperties->Charset > 0)
pBuFont->charset = std::to_wstring(pPF->bulletFontProperties->Charset);
oPPr.buTypeface.m_Typeface.reset(pBuFont);
}
// Bullets (numbering, else picture, else char, else default)
if (pPF->bulletBlip.is_init() && pPF->bulletBlip->tmpImagePath.size() && m_pRels != nullptr)
{
auto strRID = m_pRels->WriteImage(pPF->bulletBlip->tmpImagePath);
if (strRID.empty())
FillBuChar(oPPr.ParagraphBullet, L'\x2022'); // error rId
else
{
auto pBuBlip = new PPTX::Logic::BuBlip;
pBuBlip->blip.embed = new OOX::RId(strRID);
oPPr.ParagraphBullet.m_Bullet.reset(pBuBlip);
}
}
else if (pPF->bulletAutoNum.is_init())
{
auto pBuAutoNum = new PPTX::Logic::BuAutoNum;
oPPr.ParagraphBullet.m_Bullet.reset(pBuAutoNum);
if (pPF->bulletAutoNum->startAt.is_init() && pPF->bulletAutoNum->startAt.get() != 1)
pBuAutoNum->startAt = pPF->bulletAutoNum->startAt.get();
if (pPF->bulletAutoNum->type.is_init())
pBuAutoNum->type = pPF->bulletAutoNum->type.get();
}
else if (pPF->bulletChar.is_init())
{
FillBuChar(oPPr.ParagraphBullet, pPF->bulletChar.get(), pPF);
}
else
{
FillBuChar(oPPr.ParagraphBullet, L'\x2022');
}
}
else
{
oPPr.buTypeface.m_Typeface.reset(new PPTX::Logic::BuNone);
}
}
}
void BulletsConverter::FillBuClr(PPTX::Logic::BulletColor &oBuClr, CColor &oColor)
{
auto pBuClr = new PPTX::Logic::BuClr;
pBuClr->Color.SetRGBColor(oColor.GetR(), oColor.GetG(), oColor.GetB());
oBuClr.m_Color.reset(pBuClr);
}
<|endoftext|>
|
<commit_before><commit_msg>Commented out unused parameters<commit_after><|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkFEMHeatConduction2D.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkFEMHeatConduction2D.h"
#include "itkFEMElementBase.h"
namespace itk {
namespace fem {
FEMHeatConduction2D
::FEMHeatConduction2D()
{
m_Mesh = FEMMeshType::New();
}
FEMHeatConduction2D
::~FEMHeatConduction2D()
{
}
void
FEMHeatConduction2D
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
void
FEMHeatConduction2D
::AssembleMasterEquation(void)
{
// Here instantiate all the visitors and
// send them to walk through the mesh
}
}} // end namespace itk::fem
<commit_msg>ENH: A set of visitors is now intantiated to go an compute stiffness matrices.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkFEMHeatConduction2D.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkFEMHeatConduction2D.h"
#include "itkFEMElementTriangleHeatConductionVisitor.h"
#include "itkFEMElementQuadrilateralHeatConductionVisitor.h"
namespace itk {
namespace fem {
FEMHeatConduction2D
::FEMHeatConduction2D()
{
m_Mesh = FEMMeshType::New();
}
FEMHeatConduction2D
::~FEMHeatConduction2D()
{
}
void
FEMHeatConduction2D
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
void
FEMHeatConduction2D
::AssembleMasterEquation(void)
{
// Instantiate Visitors
// Types for Triangles
typedef itk::fem::FEMElementTriangle<
FEMMeshType > TriangleElementType;
typedef itk::fem::FEMElementTriangleHeatConductionVisitor<
FEMMeshType > TriangleHeatConductionVisitorType;
typedef itk::fem::FEMElementVisitorImplementation<
FEMMeshType,
TriangleElementType,
TriangleHeatConductionVisitorType
> TriangleHeatConductionVisitorImplementationType;
TriangleHeatConductionVisitorImplementationType::Pointer triangleVisitor =
TriangleHeatConductionVisitorImplementationType::New();
// Types for Quadrilaterals
typedef itk::fem::FEMElementQuadrilateral<
FEMMeshType > QuadrilateralElementType;
typedef itk::fem::FEMElementQuadrilateralHeatConductionVisitor<
FEMMeshType > QuadrilateralHeatConductionVisitorType;
typedef itk::fem::FEMElementVisitorImplementation<
FEMMeshType,
QuadrilateralElementType,
QuadrilateralHeatConductionVisitorType
> QuadrilateralHeatConductionVisitorImplementationType;
QuadrilateralHeatConductionVisitorImplementationType::Pointer quadrilateralVisitor =
QuadrilateralHeatConductionVisitorImplementationType::New();
triangleVisitor->SetMesh( m_Mesh );
quadrilateralVisitor->SetMesh( m_Mesh );
// Create a MultiVisitor
typedef FEMMeshType::ElementMultiVisitorType MultiVisitorType;
MultiVisitorType::Pointer multiVisitor = MultiVisitorType::New();
multiVisitor->AddVisitor( triangleVisitor );
multiVisitor->AddVisitor( quadrilateralVisitor );
// Now ask the mesh to accept the multivisitor which
// will Call Visit for each cell in the mesh that matches the
// cell types of the visitors added to the MultiVisitor
m_Mesh->Accept( multiVisitor );
std::cout << "Heat Conduction Visitors Done ! " << std::endl;
}
}} // end namespace itk::fem
<|endoftext|>
|
<commit_before>#include "pch.h"
#include "NativeFileHelper.h"
#include "FileHelper.h"
#include "StringHelper.h"
#include <string>
#include <vector>
#include <stack>
#include <iostream>
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
using namespace FileComponent;
using namespace Platform;
using namespace Windows::Storage;
using namespace Platform;
/** 写文件0=失败,1=成功,2=写入长度不正确 */
int writeFile(Platform::String^ strPath, char *data, int length) {
HANDLE hFile;
char *DataBuffer = data;
DWORD dwBytesToWrite = length;
DWORD dwBytesWritten = 0;
BOOL bErrorFlag = FALSE;
hFile = CreateFile2(strPath->Data(),
GENERIC_WRITE,
FILE_SHARE_READ,
CREATE_ALWAYS,
NULL);
int result = 0;
if (hFile != INVALID_HANDLE_VALUE) {
bErrorFlag = WriteFile(
hFile,
DataBuffer,
dwBytesToWrite,
&dwBytesWritten,
NULL);
if (bErrorFlag != FALSE)
{
if (dwBytesWritten != dwBytesToWrite)
{
result = 2;
printf("Error: dwBytesWritten != dwBytesToWrite\n");
}
else
{
result = 1;
}
}
}
CloseHandle(hFile);
return result;
}
Platform::Array<byte>^ readFile(Platform::String ^strPath)
{
HANDLE pfile = CreateFile2(strPath->Data(), // name of the write
GENERIC_READ, // open for writing
FILE_SHARE_READ, // do not share
OPEN_EXISTING, // default security
NULL); // no attr. template
LARGE_INTEGER fileSize;
GetFileSizeEx(pfile, &fileSize);
int64 size = fileSize.QuadPart;
char* buffer = new char[size]; // 最后一位为 '/0',C-Style 字符串的结束符
DWORD readsize;
ReadFile(pfile, buffer, size, &readsize, NULL);
CloseHandle(pfile);
byte *byteData = (byte *)buffer;
Platform::Array<byte>^ result = ref new Platform::Array<byte>(byteData, size);
delete[] buffer;
return result;
}
unsigned __int64 getFolderSize(std::wstring path, std::wstring mask) {
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
std::wstring spec;
std::stack<std::wstring> directories;
directories.push(path);
unsigned __int64 result = 0;
while (!directories.empty()) {
path = directories.top();
spec = path + L"\\" + mask;
directories.pop();
hFind = FindFirstFileEx(spec.c_str(), FindExInfoStandard, &ffd, FINDEX_SEARCH_OPS::FindExSearchNameMatch, NULL, FIND_FIRST_EX_LARGE_FETCH);
if (hFind == INVALID_HANDLE_VALUE) {
return result;
}
do {
if (wcscmp(ffd.cFileName, L".") != 0 &&
wcscmp(ffd.cFileName, L"..") != 0) {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
directories.push(path + L"\\" + ffd.cFileName);
}
else {
//This is file name
result += ffd.nFileSizeLow + (ffd.nFileSizeHigh * MAXDWORD);
//files.push_back(path + "\\" + ffd.cFileName);
}
}
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
FindClose(hFind);
return result;
}
FindClose(hFind);
hFind = INVALID_HANDLE_VALUE;
}
return result;
}
int NativeFileHelper::FileExists(Platform::String^ pathOfFolder)
{
DWORD ftyp = GetFileAttributesW(pathOfFolder->Data());
if (ftyp != INVALID_FILE_ATTRIBUTES && !(ftyp & FILE_ATTRIBUTE_DIRECTORY))
{
return 1;
}
else
{
return 0;
}
}
int NativeFileHelper::DirectoryExists(Platform::String^ pathOfFolder)
{
DWORD ftyp = GetFileAttributesW(pathOfFolder->Data());
if (ftyp != INVALID_FILE_ATTRIBUTES && (ftyp & FILE_ATTRIBUTE_DIRECTORY))
{
return 1;
}
else
{
return 0;
}
}
std::wstring getDirectory(std::wstring path)
{
return path.substr(0, path.find_last_of(L"/\\"));
}
int NativeFileHelper::RemoveFile(Platform::String^ pathOfFile)
{
int result = ::DeleteFile(pathOfFile->Data());
if (result != 0) {
return 1;
}
else {
return 0;
}
}
uint64 NativeFileHelper::GetFolderSize(Platform::String^ pathOfFolder)
{
return getFolderSize(pathOfFolder->Data(), L"*");
}
uint64 NativeFileHelper::GetFileSize(Platform::String^ pathOfFile)
{
HANDLE pfile = CreateFile2(pathOfFile->Data(), // name of the write
GENERIC_READ, // open for writing
FILE_SHARE_READ, // do not share
OPEN_EXISTING, // default security
NULL); // no attr. template
LARGE_INTEGER fileSize;
GetFileSizeEx(pfile, &fileSize);
return fileSize.QuadPart;
}
int removeDirectory(const std::wstring &strDir)
{
WIN32_FIND_DATA fdFile;
::memset(&fdFile, 0, sizeof(fdFile));
HANDLE hFind = INVALID_HANDLE_VALUE;
std::wstring strSearch = strDir + L"\\*.*";
hFind = ::FindFirstFile(strSearch.data(), &fdFile);
if (hFind == INVALID_HANDLE_VALUE) {
return 0;
}
do {
std::wstring strDelete = strDir + L"\\" + fdFile.cFileName;
if (isDirectory(fdFile) == TRUE) {
if (isDots(fdFile.cFileName) == TRUE) {
continue;
}
removeDirectory(strDelete);
}
else {
::DeleteFile(strDelete.data());
}
} while (::FindNextFile(hFind, &fdFile) == TRUE);
::FindClose(hFind);
::RemoveDirectory(strDir.data());
return 1;
}
int NativeFileHelper::RemoveDirectory(Platform::String^ pathOfFolder)
{
return removeDirectory(pathOfFolder->Data());
}
/** 写文件,返回值:0=失败,1=成功,2=写入长度不正确 */
int NativeFileHelper::WriteFile(Platform::String^ pathOfFolder, const Platform::Array<byte>^ data)
{
//如果目录不存在则创建
const std::wstring directory = getDirectory(pathOfFolder->Data());
CreateDirectoryW(directory.c_str(), NULL);
uint32 length = data->Length;
unsigned char* content = data->Data;
char *charContent = (char *)content;
return writeFile(pathOfFolder, charContent, length);
}
Platform::Array<byte>^ NativeFileHelper::ReadFile(Platform::String^ pathOfFile)
{
return readFile(pathOfFile);
}
/** 获取文件夹子项目:1=当前目录文件,2=当前目录文件夹,3=当前目录所有子文件(含子文件夹) */
Platform::Array<Platform::String^>^ getSubItems(Platform::String^ pathOfFolder, BOOL isDirectory)
{
std::wstring path = pathOfFolder->Data();
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
std::wstring spec;
Platform::Collections::Vector<Platform::String^>^ items = ref new Platform::Collections::Vector<Platform::String^>();
unsigned __int64 result = 0;
spec = path + L"\\*";
hFind = FindFirstFileEx(spec.c_str(), FindExInfoStandard, &ffd, FINDEX_SEARCH_OPS::FindExSearchNameMatch, NULL, FIND_FIRST_EX_LARGE_FETCH);
if (hFind == INVALID_HANDLE_VALUE) {
return ref new Platform::Array<Platform::String^>(0);
}
do {
if (wcscmp(ffd.cFileName, L".") != 0 && wcscmp(ffd.cFileName, L"..") != 0) {
if (isDirectory == TRUE) {
//文件夹
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
items->Append(ref new Platform::String((path + L"\\" + ffd.cFileName).c_str()));
}
}
else if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
//文件
items->Append(ref new Platform::String((path + L"\\" + ffd.cFileName).c_str()));
}
}
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() == ERROR_NO_MORE_FILES) {
FindClose(hFind);
Platform::Array<Platform::String^>^ array = ref new Platform::Array<Platform::String^>(items->Size);
int i = 0;
for each (Platform::String^ item in items)
{
array[i] = item;
i++;
}
return array;
}
else {
FindClose(hFind);
return ref new Platform::Array<Platform::String^>(0);
}
}
Platform::Array<Platform::String^>^ NativeFileHelper::GetSubFiles(Platform::String^ pathOfFolder)
{
return getSubItems(pathOfFolder, FALSE);
}
Platform::Array<Platform::String^>^ NativeFileHelper::GetSubDirectories(Platform::String^ pathOfFolder)
{
return getSubItems(pathOfFolder, TRUE);
}
//int NativeFileHelper::RenameItem(Platform::String^ source, Platform::String^ dest)
//{
// //如果目录不存在则创建
// const std::wstring directory = getDirectory(dest->Data());
// CreateDirectoryW(directory.c_str(), NULL);
//
// return MoveFileExW(source->Data(),
// dest->Data(), NULL);
//}
Platform::Array<Platform::String^>^ NativeFileHelper::GetAllFiles(Platform::String^ pathOfFolder)
{
std::wstring path = pathOfFolder->Data();
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
std::wstring spec;
std::stack<std::wstring> directories;
Platform::Collections::Vector<Platform::String^>^ files = ref new Platform::Collections::Vector<Platform::String^>();
directories.push(path);
unsigned __int64 result = 0;
while (!directories.empty()) {
path = directories.top();
spec = path + L"\\*";
directories.pop();
hFind = FindFirstFileEx(spec.c_str(), FindExInfoStandard, &ffd, FINDEX_SEARCH_OPS::FindExSearchNameMatch, NULL, FIND_FIRST_EX_LARGE_FETCH);
if (hFind == INVALID_HANDLE_VALUE) {
return ref new Platform::Array<Platform::String^>(0);
}
do {
if (wcscmp(ffd.cFileName, L".") != 0 && wcscmp(ffd.cFileName, L"..") != 0) {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
directories.push(path + L"\\" + ffd.cFileName);
}
else {
files->Append(ref new Platform::String((path + L"\\" + ffd.cFileName).c_str()));
}
}
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
FindClose(hFind);
}
FindClose(hFind);
hFind = INVALID_HANDLE_VALUE;
}
Platform::Array<Platform::String^>^ array = ref new Platform::Array<Platform::String^>(files->Size);
int i = 0;
for each (Platform::String^ item in files)
{
array[i] = item;
i++;
}
return array;
}<commit_msg>fix readfile bug, update nuget<commit_after>#include "pch.h"
#include "NativeFileHelper.h"
#include "FileHelper.h"
#include "StringHelper.h"
#include <string>
#include <vector>
#include <stack>
#include <iostream>
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
using namespace FileComponent;
using namespace Platform;
using namespace Windows::Storage;
using namespace Platform;
/** 写文件0=失败,1=成功,2=写入长度不正确 */
int writeFile(Platform::String^ strPath, char *data, int length) {
HANDLE hFile;
char *DataBuffer = data;
DWORD dwBytesToWrite = length;
DWORD dwBytesWritten = 0;
BOOL bErrorFlag = FALSE;
hFile = CreateFile2(strPath->Data(),
GENERIC_WRITE,
FILE_SHARE_READ,
CREATE_ALWAYS,
NULL);
int result = 0;
if (hFile != INVALID_HANDLE_VALUE) {
bErrorFlag = WriteFile(
hFile,
DataBuffer,
dwBytesToWrite,
&dwBytesWritten,
NULL);
if (bErrorFlag != FALSE)
{
if (dwBytesWritten != dwBytesToWrite)
{
result = 2;
printf("Error: dwBytesWritten != dwBytesToWrite\n");
}
else
{
result = 1;
}
}
}
CloseHandle(hFile);
return result;
}
Platform::Array<byte>^ readFile(Platform::String ^strPath)
{
DWORD ftyp = GetFileAttributesW(strPath->Data());
if (ftyp != INVALID_FILE_ATTRIBUTES && !(ftyp & FILE_ATTRIBUTE_DIRECTORY))
{
HANDLE pfile = CreateFile2(strPath->Data(), // name of the write
GENERIC_READ, // open for writing
FILE_SHARE_READ, // do not share
OPEN_EXISTING, // default security
NULL); // no attr. template
LARGE_INTEGER fileSize;
GetFileSizeEx(pfile, &fileSize);
int64 size = fileSize.QuadPart;
char* buffer = new char[size]; // 最后一位为 '/0',C-Style 字符串的结束符
DWORD readsize;
ReadFile(pfile, buffer, size, &readsize, NULL);
CloseHandle(pfile);
byte *byteData = (byte *)buffer;
Platform::Array<byte>^ result = ref new Platform::Array<byte>(byteData, size);
delete[] buffer;
return result;
}
else {
return nullptr;
}
}
unsigned __int64 getFolderSize(std::wstring path, std::wstring mask) {
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
std::wstring spec;
std::stack<std::wstring> directories;
directories.push(path);
unsigned __int64 result = 0;
while (!directories.empty()) {
path = directories.top();
spec = path + L"\\" + mask;
directories.pop();
hFind = FindFirstFileEx(spec.c_str(), FindExInfoStandard, &ffd, FINDEX_SEARCH_OPS::FindExSearchNameMatch, NULL, FIND_FIRST_EX_LARGE_FETCH);
if (hFind == INVALID_HANDLE_VALUE) {
return result;
}
do {
if (wcscmp(ffd.cFileName, L".") != 0 &&
wcscmp(ffd.cFileName, L"..") != 0) {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
directories.push(path + L"\\" + ffd.cFileName);
}
else {
//This is file name
result += ffd.nFileSizeLow + (ffd.nFileSizeHigh * MAXDWORD);
//files.push_back(path + "\\" + ffd.cFileName);
}
}
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
FindClose(hFind);
return result;
}
FindClose(hFind);
hFind = INVALID_HANDLE_VALUE;
}
return result;
}
int NativeFileHelper::FileExists(Platform::String^ pathOfFolder)
{
DWORD ftyp = GetFileAttributesW(pathOfFolder->Data());
if (ftyp != INVALID_FILE_ATTRIBUTES && !(ftyp & FILE_ATTRIBUTE_DIRECTORY))
{
return 1;
}
else
{
return 0;
}
}
int NativeFileHelper::DirectoryExists(Platform::String^ pathOfFolder)
{
DWORD ftyp = GetFileAttributesW(pathOfFolder->Data());
if (ftyp != INVALID_FILE_ATTRIBUTES && (ftyp & FILE_ATTRIBUTE_DIRECTORY))
{
return 1;
}
else
{
return 0;
}
}
std::wstring getDirectory(std::wstring path)
{
return path.substr(0, path.find_last_of(L"/\\"));
}
int NativeFileHelper::RemoveFile(Platform::String^ pathOfFile)
{
int result = ::DeleteFile(pathOfFile->Data());
if (result != 0) {
return 1;
}
else {
return 0;
}
}
uint64 NativeFileHelper::GetFolderSize(Platform::String^ pathOfFolder)
{
return getFolderSize(pathOfFolder->Data(), L"*");
}
uint64 NativeFileHelper::GetFileSize(Platform::String^ pathOfFile)
{
HANDLE pfile = CreateFile2(pathOfFile->Data(), // name of the write
GENERIC_READ, // open for writing
FILE_SHARE_READ, // do not share
OPEN_EXISTING, // default security
NULL); // no attr. template
LARGE_INTEGER fileSize;
GetFileSizeEx(pfile, &fileSize);
return fileSize.QuadPart;
}
int removeDirectory(const std::wstring &strDir)
{
WIN32_FIND_DATA fdFile;
::memset(&fdFile, 0, sizeof(fdFile));
HANDLE hFind = INVALID_HANDLE_VALUE;
std::wstring strSearch = strDir + L"\\*.*";
hFind = ::FindFirstFile(strSearch.data(), &fdFile);
if (hFind == INVALID_HANDLE_VALUE) {
return 0;
}
do {
std::wstring strDelete = strDir + L"\\" + fdFile.cFileName;
if (isDirectory(fdFile) == TRUE) {
if (isDots(fdFile.cFileName) == TRUE) {
continue;
}
removeDirectory(strDelete);
}
else {
::DeleteFile(strDelete.data());
}
} while (::FindNextFile(hFind, &fdFile) == TRUE);
::FindClose(hFind);
::RemoveDirectory(strDir.data());
return 1;
}
int NativeFileHelper::RemoveDirectory(Platform::String^ pathOfFolder)
{
return removeDirectory(pathOfFolder->Data());
}
/** 写文件,返回值:0=失败,1=成功,2=写入长度不正确 */
int NativeFileHelper::WriteFile(Platform::String^ pathOfFolder, const Platform::Array<byte>^ data)
{
//如果目录不存在则创建
const std::wstring directory = getDirectory(pathOfFolder->Data());
CreateDirectoryW(directory.c_str(), NULL);
uint32 length = data->Length;
unsigned char* content = data->Data;
char *charContent = (char *)content;
return writeFile(pathOfFolder, charContent, length);
}
Platform::Array<byte>^ NativeFileHelper::ReadFile(Platform::String^ pathOfFile)
{
return readFile(pathOfFile);
}
/** 获取文件夹子项目:1=当前目录文件,2=当前目录文件夹,3=当前目录所有子文件(含子文件夹) */
Platform::Array<Platform::String^>^ getSubItems(Platform::String^ pathOfFolder, BOOL isDirectory)
{
std::wstring path = pathOfFolder->Data();
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
std::wstring spec;
Platform::Collections::Vector<Platform::String^>^ items = ref new Platform::Collections::Vector<Platform::String^>();
unsigned __int64 result = 0;
spec = path + L"\\*";
hFind = FindFirstFileEx(spec.c_str(), FindExInfoStandard, &ffd, FINDEX_SEARCH_OPS::FindExSearchNameMatch, NULL, FIND_FIRST_EX_LARGE_FETCH);
if (hFind == INVALID_HANDLE_VALUE) {
return ref new Platform::Array<Platform::String^>(0);
}
do {
if (wcscmp(ffd.cFileName, L".") != 0 && wcscmp(ffd.cFileName, L"..") != 0) {
if (isDirectory == TRUE) {
//文件夹
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
items->Append(ref new Platform::String((path + L"\\" + ffd.cFileName).c_str()));
}
}
else if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
//文件
items->Append(ref new Platform::String((path + L"\\" + ffd.cFileName).c_str()));
}
}
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() == ERROR_NO_MORE_FILES) {
FindClose(hFind);
Platform::Array<Platform::String^>^ array = ref new Platform::Array<Platform::String^>(items->Size);
int i = 0;
for each (Platform::String^ item in items)
{
array[i] = item;
i++;
}
return array;
}
else {
FindClose(hFind);
return ref new Platform::Array<Platform::String^>(0);
}
}
Platform::Array<Platform::String^>^ NativeFileHelper::GetSubFiles(Platform::String^ pathOfFolder)
{
return getSubItems(pathOfFolder, FALSE);
}
Platform::Array<Platform::String^>^ NativeFileHelper::GetSubDirectories(Platform::String^ pathOfFolder)
{
return getSubItems(pathOfFolder, TRUE);
}
//int NativeFileHelper::RenameItem(Platform::String^ source, Platform::String^ dest)
//{
// //如果目录不存在则创建
// const std::wstring directory = getDirectory(dest->Data());
// CreateDirectoryW(directory.c_str(), NULL);
//
// return MoveFileExW(source->Data(),
// dest->Data(), NULL);
//}
Platform::Array<Platform::String^>^ NativeFileHelper::GetAllFiles(Platform::String^ pathOfFolder)
{
std::wstring path = pathOfFolder->Data();
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
std::wstring spec;
std::stack<std::wstring> directories;
Platform::Collections::Vector<Platform::String^>^ files = ref new Platform::Collections::Vector<Platform::String^>();
directories.push(path);
unsigned __int64 result = 0;
while (!directories.empty()) {
path = directories.top();
spec = path + L"\\*";
directories.pop();
hFind = FindFirstFileEx(spec.c_str(), FindExInfoStandard, &ffd, FINDEX_SEARCH_OPS::FindExSearchNameMatch, NULL, FIND_FIRST_EX_LARGE_FETCH);
if (hFind == INVALID_HANDLE_VALUE) {
return ref new Platform::Array<Platform::String^>(0);
}
do {
if (wcscmp(ffd.cFileName, L".") != 0 && wcscmp(ffd.cFileName, L"..") != 0) {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
directories.push(path + L"\\" + ffd.cFileName);
}
else {
files->Append(ref new Platform::String((path + L"\\" + ffd.cFileName).c_str()));
}
}
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
FindClose(hFind);
}
FindClose(hFind);
hFind = INVALID_HANDLE_VALUE;
}
Platform::Array<Platform::String^>^ array = ref new Platform::Array<Platform::String^>(files->Size);
int i = 0;
for each (Platform::String^ item in files)
{
array[i] = item;
i++;
}
return array;
}<|endoftext|>
|
<commit_before>// Copyright 2010-2014 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "JavascriptPropertyWrapper.h"
#include "CefAppWrapper.h"
using namespace System;
namespace CefSharp
{
void JavascriptPropertyWrapper::Bind()
{
auto methodName = StringUtils::ToNative(_javascriptProperty->JavascriptName);
auto clrMethodName = _javascriptProperty->JavascriptName;
if (_javascriptProperty->IsComplexType)
{
//auto wrapperObject = gcnew JavascriptObjectWrapper(_javascriptProperty->Value);
//wrapperObject->V8Value = V8Value.get();
//wrapperObject->Bind();
}
else
{
V8Value->SetValue(methodName, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE);
}
};
void JavascriptPropertyWrapper::SetProperty(String^ memberName, Object^ value)
{
auto browserProxy = CefAppWrapper::Instance->CreateBrowserProxy();
browserProxy->SetProperty(_ownerId, memberName, value);
};
Object^ JavascriptPropertyWrapper::GetProperty(String^ memberName)
{
auto browserProxy = CefAppWrapper::Instance->CreateBrowserProxy();
return browserProxy->GetProperty(_ownerId, memberName);
};
}<commit_msg>Get complex object support code to compile!<commit_after>// Copyright 2010-2014 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "JavascriptPropertyWrapper.h"
#include "JavascriptObjectWrapper.h"
#include "CefAppWrapper.h"
using namespace System;
namespace CefSharp
{
void JavascriptPropertyWrapper::Bind()
{
auto methodName = StringUtils::ToNative(_javascriptProperty->JavascriptName);
auto clrMethodName = _javascriptProperty->JavascriptName;
if (_javascriptProperty->IsComplexType)
{
auto wrapperObject = gcnew JavascriptObjectWrapper(_javascriptProperty->Value);
wrapperObject->V8Value = V8Value.get();
wrapperObject->Bind();
}
else
{
V8Value->SetValue(methodName, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE);
}
};
void JavascriptPropertyWrapper::SetProperty(String^ memberName, Object^ value)
{
auto browserProxy = CefAppWrapper::Instance->CreateBrowserProxy();
browserProxy->SetProperty(_ownerId, memberName, value);
};
Object^ JavascriptPropertyWrapper::GetProperty(String^ memberName)
{
auto browserProxy = CefAppWrapper::Instance->CreateBrowserProxy();
return browserProxy->GetProperty(_ownerId, memberName);
};
}<|endoftext|>
|
<commit_before>#include <stdarg.h>
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#define INTERLEAVE_TEST
#define __code
#define __data
#define __pdata
#define __xdata
#define PARAM_ECC 1
int interleave=1;
int param_get(int param)
{
// ECC_PARAM returns "Golay + interlacing"
if (interleave)
return 2;
else return 1;
}
#include "interleave.c"
#include "golay.c"
int show(char *msg,int n,unsigned char *b)
{
int i;
printf("%s:\n",msg);
for(i=0;i<n;i++) {
if (!(i&0xf)) printf("\n%02x:",i);
printf(" %02x",b[i]);
}
printf("\n");
return 0;
}
int prefill(unsigned char *b)
{
int i;
for(i=0;i<256;i++) b[i]=i;
return 0;
}
int countones(int n,unsigned char *b)
{
int j,i=0;
int count=0;
for(i=0;i<n;i++) {
for(j=0;j<8;j++)
if (b[i]&(1<<j)) count++;
}
return count;
}
int main()
{
int n;
unsigned char in[256];
unsigned char out[512];
unsigned char verify[256];
printf("Testing interleaver at low level\n");
for(n=6;n<=510;n+=6) {
// Perform some diagnostics on the interleaver
bzero(out,512);
interleave_data_size=n;
// printf("step=%d bits.\n",steps[n/3]);
int i;
for(i=0;i<n;i++) {
interleave_setbyte(out,i,0xff);
int ones=countones(n,out);
if (ones!=((i+1)*8)) {
printf("Test failed for golay encoded packet size=%d\n",n);
printf("n=%d, i=%d\n",n,i);
show("bits clash with another byte",n,out);
int k,l;
for(k=0;k<(8*i);k++)
for(l=0;l<8;l++)
if (bitnumber(n,k)==bitnumber(n,i*8+l)) {
printf(" byte %d.%d (bit=%d) clashes with bit %d of this byte"
" @ bit %d\n",
k/8,k&7,k,l,bitnumber(n,i*8+l));
printf("them: bit*steps[n/3]%%(n*8) = %d*steps[%d]%%%d = %d\n",
k,n/3,n*8,k*steps[n/3]%(n*8));
printf("us: bit*steps[n/3]%%(n*8) = %d*steps[%d]%%%d = %d\n",
i*8+l,n/3,n*8,(i*8+l)*steps[n/3]%(n*8));
}
exit(-1);
}
}
}
printf(" -- test passed\n");
// Try interleaving and golay protecting a block of data
printf("Testing interleaving at golay_{en,de}code() level.\n");
for(n=0;n<256;n+=3) {
prefill(in);
interleave=1;
golay_encode(n,in,out);
int icount=countones(n*2,out);
interleave=0;
golay_encode(n,in,out);
int ncount=countones(n*2,out);
if (icount!=ncount) {
printf("Test failed: different number of set bits with/without"
" interleaving: %d vs %d\n",icount,ncount);
exit(-1);
}
bzero(verify,256);
golay_decode(n*2,out,verify);
if (bcmp(in,verify,n)) {
printf("Decode error for packet of %d bytes\n",n);
show("input",n,in);
show("verify error (should be 0x00 -- 0xnn)",n,verify);
exit(-1);
}
}
printf(" -- test passed.\n");
return 0;
}
<commit_msg>tests now pass - encoding and decoding both work.<commit_after>#include <stdarg.h>
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#define INTERLEAVE_TEST
#define __code
#define __data
#define __pdata
#define __xdata
#define PARAM_ECC 1
int interleave=1;
int param_get(int param)
{
// ECC_PARAM returns "Golay + interlacing"
if (interleave)
return 2;
else return 1;
}
#include "interleave.c"
#include "golay.c"
int show(char *msg,int n,unsigned char *b)
{
int i;
printf("%s:\n",msg);
for(i=0;i<n;i++) {
if (!(i&0xf)) printf("\n%02x:",i);
printf(" %02x",b[i]);
}
printf("\n");
return 0;
}
int prefill(unsigned char *b)
{
int i;
for(i=0;i<256;i++) b[i]=i;
return 0;
}
int countones(int n,unsigned char *b)
{
int j,i=0;
int count=0;
for(i=0;i<n;i++) {
for(j=0;j<8;j++)
if (b[i]&(1<<j)) count++;
}
return count;
}
int main()
{
int n;
unsigned char in[256];
unsigned char out[512];
unsigned char verify[256];
printf("Testing interleaver at low level\n");
for(n=6;n<=510;n+=6) {
// Perform some diagnostics on the interleaver
bzero(out,512);
interleave_data_size=n;
// printf("step=%d bits.\n",steps[n/3]);
int i;
for(i=0;i<n;i++) {
interleave_setbyte(out,i,0xff);
int ones=countones(n,out);
if (ones!=((i+1)*8)) {
printf("Test failed for golay encoded packet size=%d\n",n);
printf("n=%d, i=%d\n",n,i);
show("bits clash with another byte",n,out);
int k,l;
for(k=0;k<(8*i);k++)
for(l=0;l<8;l++)
if (bitnumber(n,k)==bitnumber(n,i*8+l)) {
printf(" byte %d.%d (bit=%d) clashes with bit %d of this byte"
" @ bit %d\n",
k/8,k&7,k,l,bitnumber(n,i*8+l));
printf("them: bit*steps[n/3]%%(n*8) = %d*steps[%d]%%%d = %d\n",
k,n/3,n*8,k*steps[n/3]%(n*8));
printf("us: bit*steps[n/3]%%(n*8) = %d*steps[%d]%%%d = %d\n",
i*8+l,n/3,n*8,(i*8+l)*steps[n/3]%(n*8));
}
exit(-1);
}
}
}
printf(" -- test passed\n");
// Try interleaving and golay protecting a block of data
// 256 bytes of golay protected data = 128 bytes of raw data.
printf("Testing interleaving at golay_{en,de}code() level.\n");
for(n=0;n<128;n+=3) {
prefill(in);
interleave=1;
golay_encode(n,in,out);
int icount=countones(n*2,out);
interleave=0;
golay_encode(n,in,out);
int ncount=countones(n*2,out);
if (icount!=ncount) {
printf("Test failed: different number of set bits with/without"
" interleaving: %d vs %d\n",icount,ncount);
exit(-1);
}
bzero(verify,256);
golay_decode(n*2,out,verify);
if (bcmp(in,verify,n)) {
printf("Decode error for packet of %d bytes\n",n);
show("input",n,in);
show("verify error (should be 0x00 -- 0xnn)",n,verify);
exit(-1);
}
}
printf(" -- test passed.\n");
return 0;
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2020)
#include "config.h"
#include <dune/pybindxi/pybind11.h>
#include <dune/pybindxi/stl.h>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/grids.hh>
#include <dune/xt/grid/gridprovider/provider.hh>
#include <dune/gdt/local/integrands/laplace.hh>
#include <python/dune/xt/common/configuration.hh>
#include <python/dune/xt/common/fvector.hh>
#include <python/dune/xt/grid/grids.bindings.hh>
namespace Dune {
namespace GDT {
namespace bindings {
template <class E, size_t r = 1, class F = double>
class LocalLaplaceIntegrand
{
using G = std::decay_t<XT::Grid::extract_grid_t<E>>;
using GP = XT::Grid::GridProvider<G>;
static const size_t d = G::dimension;
public:
using type = GDT::LocalLaplaceIntegrand<E, r, F>;
using base_type = GDT::LocalBinaryElementIntegrandInterface<E, r, 1, F, F, r, 1, F>;
using bound_type = pybind11::class_<type, base_type>;
private:
template <bool oned = (d == 1), bool anything = true>
struct add_bind /*<true, anything>*/
{
static void ctor(bound_type&) {}
static void factory(pybind11::module&, const std::string&) {}
};
template <bool anything>
struct add_bind<false, anything>
{
static void ctor(bound_type& c)
{
namespace py = pybind11;
using namespace pybind11::literals;
c.def(py::init<const FieldMatrix<F, d, d>&>(), "constant_diffusion_tensor"_a);
c.def(py::init<const XT::Functions::FunctionInterface<d, d, d, F>&>(),
"diffusion_tensor_function"_a,
py::keep_alive<1, 2>());
}
static void factory(pybind11::module& m, const std::string& FactoryName)
{
namespace py = pybind11;
using namespace pybind11::literals;
m.def(FactoryName.c_str(),
[](const GP&, const FieldMatrix<F, d, d>& constant_diffusion_tensor) {
return type(constant_diffusion_tensor);
},
"unused_grid_to_select_type"_a,
"constant_diffusion_tensor"_a);
m.def(FactoryName.c_str(),
[](const GP&, const XT::Functions::FunctionInterface<d, d, d, F>& diffusion_tensor_function) {
return type(diffusion_tensor_function);
},
"unused_grid_to_select_type"_a,
"diffusion_tensor_function"_a,
py::keep_alive<0, 2>());
}
}; // struct add_bind<false, ...>
public:
static bound_type bind(pybind11::module& m,
const std::string& class_id = "local_laplace_integrand",
const std::string& grid_id = XT::Grid::bindings::grid_name<G>::value(),
const std::string& layer_id = "")
{
namespace py = pybind11;
using namespace pybind11::literals;
std::string class_name = class_id;
class_name += "_" + grid_id;
if (!layer_id.empty())
class_name += "_" + layer_id;
class_name += "_" + XT::Common::to_string(r) + "d_bases";
class_name += "_to_scalar";
if (!std::is_same<F, double>::value)
class_name += "_" + XT::Common::Typename<F>::value(/*fail_wo_typeid=*/true);
const auto ClassName = XT::Common::to_camel_case(class_name);
bound_type c(m, ClassName.c_str(), ClassName.c_str());
c.def(py::init<const F&>(), "constant_scalar_diffusion"_a);
c.def(py::init<const XT::Functions::FunctionInterface<d, 1, 1, F>&>(),
"scalar_diffusion_function"_a,
py::keep_alive<1, 2>());
add_bind<>::ctor(c);
c.def(py::init<const XT::Functions::GridFunctionInterface<E, 1, 1, F>&>(),
"scalar_diffusion_grid_function"_a,
py::keep_alive<1, 2>());
c.def(py::init<const XT::Functions::GridFunctionInterface<E, d, d, F>&>(),
"diffusion_tensor_grid_function"_a,
py::keep_alive<1, 2>());
// factories
const auto FactoryName = XT::Common::to_camel_case(class_id);
m.def(FactoryName.c_str(),
[](const GP&, const F& constant_scalar_diffusion) { return type(constant_scalar_diffusion); },
"unused_grid_to_select_type"_a,
"constant_scalar_diffusion"_a);
add_bind<>::factory(m, FactoryName);
m.def(FactoryName.c_str(),
[](const GP&, const XT::Functions::FunctionInterface<d, 1, 1, F>& scalar_diffusion_function) {
return type(scalar_diffusion_function);
},
"unused_grid_to_select_type"_a,
"scalar_diffusion_function"_a,
py::keep_alive<0, 2>());
m.def(FactoryName.c_str(),
[](const XT::Functions::GridFunctionInterface<E, 1, 1, F>& scalar_diffusion_grid_function) {
return type(scalar_diffusion_grid_function);
},
"scalar_diffusion_grid_function"_a,
py::keep_alive<0, 1>());
m.def(FactoryName.c_str(),
[](const XT::Functions::GridFunctionInterface<E, d, d, F>& diffusion_tensor_grid_function) {
return type(diffusion_tensor_grid_function);
},
"diffusion_tensor_grid_function"_a,
py::keep_alive<0, 1>());
return c;
} // ... bind(...)
}; // class LocalLaplaceIntegrand
} // namespace bindings
} // namespace GDT
} // namespace Dune
template <class GridTypes = Dune::XT::Grid::AvailableGridTypes>
struct LocalLaplaceIntegrand_for_all_grids
{
using G = typename GridTypes::head_type;
using GV = typename G::LeafGridView;
using E = Dune::XT::Grid::extract_entity_t<GV>;
static const constexpr size_t d = G::dimension;
static void bind(pybind11::module& m)
{
Dune::GDT::bindings::LocalLaplaceIntegrand<E>::bind(m);
if (d > 1)
Dune::GDT::bindings::LocalLaplaceIntegrand<E, d>::bind(m);
// add your extra dimensions here
// ...
LocalLaplaceIntegrand_for_all_grids<typename GridTypes::tail_type>::bind(m);
}
};
template <>
struct LocalLaplaceIntegrand_for_all_grids<boost::tuples::null_type>
{
static void bind(pybind11::module& /*m*/) {}
};
PYBIND11_MODULE(_local_integrands_laplace, m)
{
namespace py = pybind11;
using namespace Dune;
using namespace Dune::XT;
using namespace Dune::GDT;
py::module::import("dune.xt.common");
py::module::import("dune.xt.la");
py::module::import("dune.xt.grid");
py::module::import("dune.xt.functions");
py::module::import("dune.gdt._local_integrands_binary_element_interface");
LocalLaplaceIntegrand_for_all_grids<XT::Grid::AvailableGridTypes>::bind(m);
}
<commit_msg>[python|integrands] minor rephrase<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2020)
#include "config.h"
#include <dune/pybindxi/pybind11.h>
#include <dune/pybindxi/stl.h>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/grids.hh>
#include <dune/xt/grid/gridprovider/provider.hh>
#include <dune/gdt/local/integrands/laplace.hh>
#include <python/dune/xt/common/configuration.hh>
#include <python/dune/xt/common/fvector.hh>
#include <python/dune/xt/grid/grids.bindings.hh>
namespace Dune {
namespace GDT {
namespace bindings {
template <class E, size_t r = 1, class F = double>
class LocalLaplaceIntegrand
{
using G = std::decay_t<XT::Grid::extract_grid_t<E>>;
using GP = XT::Grid::GridProvider<G>;
static const size_t d = G::dimension;
public:
using type = GDT::LocalLaplaceIntegrand<E, r, F>;
using base_type = GDT::LocalBinaryElementIntegrandInterface<E, r, 1, F, F, r, 1, F>;
using bound_type = pybind11::class_<type, base_type>;
private:
template <bool oned = (d == 1), bool anything = true>
struct add_bind /*<true, anything>*/
{
static void ctor(bound_type&) {}
static void factory(pybind11::module&, const std::string&) {}
};
template <bool anything>
struct add_bind<false, anything>
{
static void ctor(bound_type& c)
{
namespace py = pybind11;
using namespace pybind11::literals;
c.def(py::init<const FieldMatrix<F, d, d>&>(), "constant_diffusion_tensor"_a);
c.def(py::init<const XT::Functions::FunctionInterface<d, d, d, F>&>(),
"diffusion_tensor_function"_a,
py::keep_alive<1, 2>());
}
static void factory(pybind11::module& m, const std::string& FactoryName)
{
namespace py = pybind11;
using namespace pybind11::literals;
m.def(FactoryName.c_str(),
[](const GP&, const FieldMatrix<F, d, d>& constant_diffusion_tensor) {
return type(constant_diffusion_tensor);
},
"grid"_a,
"constant_diffusion_tensor"_a);
m.def(FactoryName.c_str(),
[](const GP&, const XT::Functions::FunctionInterface<d, d, d, F>& diffusion_tensor_function) {
return type(diffusion_tensor_function);
},
"grid"_a,
"diffusion_tensor_function"_a,
py::keep_alive<0, 2>());
}
}; // struct add_bind<false, ...>
public:
static bound_type bind(pybind11::module& m,
const std::string& class_id = "local_laplace_integrand",
const std::string& grid_id = XT::Grid::bindings::grid_name<G>::value(),
const std::string& layer_id = "")
{
namespace py = pybind11;
using namespace pybind11::literals;
std::string class_name = class_id;
class_name += "_" + grid_id;
if (!layer_id.empty())
class_name += "_" + layer_id;
class_name += "_" + XT::Common::to_string(r) + "d_bases";
class_name += "_to_scalar";
if (!std::is_same<F, double>::value)
class_name += "_" + XT::Common::Typename<F>::value(/*fail_wo_typeid=*/true);
const auto ClassName = XT::Common::to_camel_case(class_name);
bound_type c(m, ClassName.c_str(), ClassName.c_str());
c.def(py::init<const F&>(), "constant_scalar_diffusion"_a);
c.def(py::init<const XT::Functions::FunctionInterface<d, 1, 1, F>&>(),
"scalar_diffusion_function"_a,
py::keep_alive<1, 2>());
add_bind<>::ctor(c);
c.def(py::init<const XT::Functions::GridFunctionInterface<E, 1, 1, F>&>(),
"scalar_diffusion_grid_function"_a,
py::keep_alive<1, 2>());
c.def(py::init<const XT::Functions::GridFunctionInterface<E, d, d, F>&>(),
"diffusion_tensor_grid_function"_a,
py::keep_alive<1, 2>());
// factories
const auto FactoryName = XT::Common::to_camel_case(class_id);
m.def(FactoryName.c_str(),
[](const GP&, const F& constant_scalar_diffusion) { return type(constant_scalar_diffusion); },
"grid"_a,
"constant_scalar_diffusion"_a);
add_bind<>::factory(m, FactoryName);
m.def(FactoryName.c_str(),
[](const GP&, const XT::Functions::FunctionInterface<d, 1, 1, F>& scalar_diffusion_function) {
return type(scalar_diffusion_function);
},
"grid"_a,
"scalar_diffusion_function"_a,
py::keep_alive<0, 2>());
m.def(FactoryName.c_str(),
[](const XT::Functions::GridFunctionInterface<E, 1, 1, F>& scalar_diffusion_grid_function) {
return type(scalar_diffusion_grid_function);
},
"scalar_diffusion_grid_function"_a,
py::keep_alive<0, 1>());
m.def(FactoryName.c_str(),
[](const XT::Functions::GridFunctionInterface<E, d, d, F>& diffusion_tensor_grid_function) {
return type(diffusion_tensor_grid_function);
},
"diffusion_tensor_grid_function"_a,
py::keep_alive<0, 1>());
return c;
} // ... bind(...)
}; // class LocalLaplaceIntegrand
} // namespace bindings
} // namespace GDT
} // namespace Dune
template <class GridTypes = Dune::XT::Grid::AvailableGridTypes>
struct LocalLaplaceIntegrand_for_all_grids
{
using G = typename GridTypes::head_type;
using GV = typename G::LeafGridView;
using E = Dune::XT::Grid::extract_entity_t<GV>;
static const constexpr size_t d = G::dimension;
static void bind(pybind11::module& m)
{
Dune::GDT::bindings::LocalLaplaceIntegrand<E>::bind(m);
if (d > 1)
Dune::GDT::bindings::LocalLaplaceIntegrand<E, d>::bind(m);
// add your extra dimensions here
// ...
LocalLaplaceIntegrand_for_all_grids<typename GridTypes::tail_type>::bind(m);
}
};
template <>
struct LocalLaplaceIntegrand_for_all_grids<boost::tuples::null_type>
{
static void bind(pybind11::module& /*m*/) {}
};
PYBIND11_MODULE(_local_integrands_laplace, m)
{
namespace py = pybind11;
using namespace Dune;
using namespace Dune::XT;
using namespace Dune::GDT;
py::module::import("dune.xt.common");
py::module::import("dune.xt.la");
py::module::import("dune.xt.grid");
py::module::import("dune.xt.functions");
py::module::import("dune.gdt._local_integrands_binary_element_interface");
LocalLaplaceIntegrand_for_all_grids<XT::Grid::AvailableGridTypes>::bind(m);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: acceleratorconfiguration.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2005-03-01 19:37:19 $
*
* 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 __FRAMEWORK_ACCELERATORS_ACCELERATORCONFIGURATION_HXX_
#define __FRAMEWORK_ACCELERATORS_ACCELERATORCONFIGURATION_HXX_
//__________________________________________
// own includes
#ifndef __FRAMEWORK_ACCELERATORS_ISTORAGELISTENER_HXX_
#include <accelerators/istoragelistener.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_PRESETHANDLER_HXX_
#include <accelerators/presethandler.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_ACCELERATORCACHE_HXX_
#include <accelerators/acceleratorcache.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//__________________________________________
// interface includes
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XACCELERATORCONFIGURATION_HPP_
#include <com/sun/star/ui/XAcceleratorConfiguration.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATION_HPP_
#include <com/sun/star/ui/XUIConfiguration.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONPERSISTENCE_HPP_
#include <com/sun/star/ui/XUIConfigurationPersistence.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONSTORAGE_HDL_
#include <com/sun/star/ui/XUIConfigurationStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
// TODO use XPresetHandler interface instead if available
#ifndef _COM_SUN_STAR_FORM_XRESET_HPP_
#include <com/sun/star/form/XReset.hpp>
#endif
//__________________________________________
// other includes
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COMPHELPER_LOCALE_HXX_
#include <comphelper/locale.hxx>
#endif
//__________________________________________
// definition
namespace framework
{
/** "global" type to make accelerator presets unique, so they can be used
in combination with the salhelper::SingletonRef mechanism! */
typedef PresetHandler AcceleratorPresets;
//__________________________________________
/**
implements a read/write access to the accelerator configuration.
*/
class AcceleratorConfiguration : protected ThreadHelpBase // attention! Must be the first base class to guarentee right initialize lock ...
, public IStorageListener
, public ::cppu::OWeakObject
, public css::lang::XTypeProvider
, public css::form::XReset // TODO use XPresetHandler instead if available
, public css::ui::XAcceleratorConfiguration // => css::ui::XUIConfigurationPersistence
// css::ui::XUIConfigurationStorage
// css::ui::XUIConfiguration
{
//______________________________________
// member
protected:
//---------------------------------------
/** the global uno service manager.
Must be used to create own needed services. */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
//---------------------------------------
/** used to:
i ) copy configuration files from the share to the user layer
ii ) provide access to these config files
iii) cache all sub storages on the path from the top to the bottom(!)
iv ) provide commit for changes. */
PresetHandler m_aPresetHandler;
//---------------------------------------
/** contains the cached configuration data */
AcceleratorCache m_aReadCache;
//---------------------------------------
/** used to implement the copy on write pattern! */
AcceleratorCache* m_pWriteCache;
//______________________________________
// native interface!
public:
AcceleratorConfiguration( const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR );
virtual ~AcceleratorConfiguration( );
//______________________________________
// uno interface!
public:
// XInterface, XTypeProvider
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
// XAcceleratorConfiguration
virtual css::uno::Sequence< css::awt::KeyEvent > SAL_CALL getAllKeyEvents()
throw(css::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCommandByKeyEvent(const css::awt::KeyEvent& aKeyEvent)
throw(css::container::NoSuchElementException,
css::uno::RuntimeException );
virtual void SAL_CALL setKeyEvent(const css::awt::KeyEvent& aKeyEvent,
const ::rtl::OUString& sCommand )
throw(css::lang::IllegalArgumentException,
css::uno::RuntimeException );
virtual void SAL_CALL removeKeyEvent(const css::awt::KeyEvent& aKeyEvent)
throw(css::container::NoSuchElementException,
css::uno::RuntimeException );
virtual css::uno::Sequence< css::awt::KeyEvent > SAL_CALL getKeyEventsByCommand(const ::rtl::OUString& sCommand)
throw(css::lang::IllegalArgumentException ,
css::container::NoSuchElementException,
css::uno::RuntimeException );
virtual css::uno::Sequence< css::uno::Any > SAL_CALL getPreferredKeyEventsForCommandList(const css::uno::Sequence< ::rtl::OUString >& lCommandList)
throw(css::lang::IllegalArgumentException ,
css::uno::RuntimeException );
virtual void SAL_CALL removeCommandFromAllKeyEvents(const ::rtl::OUString& sCommand)
throw(css::lang::IllegalArgumentException ,
css::container::NoSuchElementException,
css::uno::RuntimeException );
// XUIConfigurationPersistence
virtual void SAL_CALL reload()
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual void SAL_CALL store()
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual void SAL_CALL storeToStorage(const css::uno::Reference< css::embed::XStorage >& xStorage)
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL isModified()
throw(css::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL isReadOnly()
throw(css::uno::RuntimeException);
// XUIConfigurationStorage
virtual void SAL_CALL setStorage(const css::uno::Reference< css::embed::XStorage >& xStorage)
throw(css::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL hasStorage()
throw(css::uno::RuntimeException);
// XUIConfiguration
virtual void SAL_CALL addConfigurationListener(const css::uno::Reference< css::ui::XUIConfigurationListener >& xListener)
throw(css::uno::RuntimeException);
virtual void SAL_CALL removeConfigurationListener(const css::uno::Reference< css::ui::XUIConfigurationListener >& xListener)
throw(css::uno::RuntimeException);
// XReset
// TODO use XPresetHandler instead if available
virtual void SAL_CALL reset()
throw(css::uno::RuntimeException);
virtual void SAL_CALL addResetListener(const css::uno::Reference< css::form::XResetListener >& xListener)
throw(css::uno::RuntimeException);
virtual void SAL_CALL removeResetListener(const css::uno::Reference< css::form::XResetListener >& xListener)
throw(css::uno::RuntimeException);
// IStorageListener
virtual void changesOccured(const ::rtl::OUString& sPath);
//______________________________________
// helper for derived classes
protected:
//---------------------------------------
/** @short return the current office locale.
@descr We does not cache this value, because we are not listen
for changes on the configuration layer ...
@return ::comphelper::Locale
The current office locale.
*/
::comphelper::Locale impl_ts_getLocale() const;
//______________________________________
// helper
private:
//---------------------------------------
/** @short load a configuration set, using the given stream.
@param xStream
provides the XML structure as stream.
*/
void impl_ts_load(const css::uno::Reference< css::io::XInputStream >& xStream);
//---------------------------------------
/** @short save a configuration set, using the given stream.
@param xStream
the XML structure can be written there.
*/
void impl_ts_save(const css::uno::Reference< css::io::XOutputStream >& xStream);
//---------------------------------------
/** @short try to locate and open a sub storage.
@descr It search at the root storage for the specified
sub storage. If it exists - it will be opened.
By default this method tries to open the storage
for reading. But the calli can request a writeable
storage.
@param xRooStorage
used to locate the sub storage.
@param sSubStorage
relativ path of the sub storage.
@param bOutStream
force open of the sub storage in
write mode - instead of read mode, which
is the default.
@return [XInterface]
will be a css::io::XInpoutStream or a css::io::XOutputStream.
Depends from the parameter bWriteable!
*/
css::uno::Reference< css::uno::XInterface > impl_ts_openSubStorage(const css::uno::Reference< css::embed::XStorage >& xRootStorage,
const ::rtl::OUString& sSubStorage ,
sal_Bool bOutStream );
//---------------------------------------
/** @short returns a reference to one of our internal cache members.
@descr We implement the copy-on-write pattern. Doing so
we know two caches internaly. The second one is used
only, if the container was changed.
This method here returns access to one of these
caches - depending on the change state of this
configuration service.
@param bWriteAccessRequested
if the outside code whish to change the container
it must call this method with "TRUE". So the internal
cache can be prepared for that (means copy-on-write ...).
@return [AcceleratorCache]
c++ reference(!) to one of our internal caches.
*/
AcceleratorCache& impl_getCFG(sal_Bool bWriteAccessRequested = sal_False);
};
} // namespace framework
#endif // __FRAMEWORK_ACCELERATORS_ACCELERATORCONFIGURATION_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.128); FILE MERGED 2005/09/05 13:06:27 rt 1.3.128.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: acceleratorconfiguration.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:28:52 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_ACCELERATORS_ACCELERATORCONFIGURATION_HXX_
#define __FRAMEWORK_ACCELERATORS_ACCELERATORCONFIGURATION_HXX_
//__________________________________________
// own includes
#ifndef __FRAMEWORK_ACCELERATORS_ISTORAGELISTENER_HXX_
#include <accelerators/istoragelistener.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_PRESETHANDLER_HXX_
#include <accelerators/presethandler.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_ACCELERATORCACHE_HXX_
#include <accelerators/acceleratorcache.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//__________________________________________
// interface includes
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XACCELERATORCONFIGURATION_HPP_
#include <com/sun/star/ui/XAcceleratorConfiguration.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATION_HPP_
#include <com/sun/star/ui/XUIConfiguration.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONPERSISTENCE_HPP_
#include <com/sun/star/ui/XUIConfigurationPersistence.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONSTORAGE_HDL_
#include <com/sun/star/ui/XUIConfigurationStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
// TODO use XPresetHandler interface instead if available
#ifndef _COM_SUN_STAR_FORM_XRESET_HPP_
#include <com/sun/star/form/XReset.hpp>
#endif
//__________________________________________
// other includes
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COMPHELPER_LOCALE_HXX_
#include <comphelper/locale.hxx>
#endif
//__________________________________________
// definition
namespace framework
{
/** "global" type to make accelerator presets unique, so they can be used
in combination with the salhelper::SingletonRef mechanism! */
typedef PresetHandler AcceleratorPresets;
//__________________________________________
/**
implements a read/write access to the accelerator configuration.
*/
class AcceleratorConfiguration : protected ThreadHelpBase // attention! Must be the first base class to guarentee right initialize lock ...
, public IStorageListener
, public ::cppu::OWeakObject
, public css::lang::XTypeProvider
, public css::form::XReset // TODO use XPresetHandler instead if available
, public css::ui::XAcceleratorConfiguration // => css::ui::XUIConfigurationPersistence
// css::ui::XUIConfigurationStorage
// css::ui::XUIConfiguration
{
//______________________________________
// member
protected:
//---------------------------------------
/** the global uno service manager.
Must be used to create own needed services. */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
//---------------------------------------
/** used to:
i ) copy configuration files from the share to the user layer
ii ) provide access to these config files
iii) cache all sub storages on the path from the top to the bottom(!)
iv ) provide commit for changes. */
PresetHandler m_aPresetHandler;
//---------------------------------------
/** contains the cached configuration data */
AcceleratorCache m_aReadCache;
//---------------------------------------
/** used to implement the copy on write pattern! */
AcceleratorCache* m_pWriteCache;
//______________________________________
// native interface!
public:
AcceleratorConfiguration( const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR );
virtual ~AcceleratorConfiguration( );
//______________________________________
// uno interface!
public:
// XInterface, XTypeProvider
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
// XAcceleratorConfiguration
virtual css::uno::Sequence< css::awt::KeyEvent > SAL_CALL getAllKeyEvents()
throw(css::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCommandByKeyEvent(const css::awt::KeyEvent& aKeyEvent)
throw(css::container::NoSuchElementException,
css::uno::RuntimeException );
virtual void SAL_CALL setKeyEvent(const css::awt::KeyEvent& aKeyEvent,
const ::rtl::OUString& sCommand )
throw(css::lang::IllegalArgumentException,
css::uno::RuntimeException );
virtual void SAL_CALL removeKeyEvent(const css::awt::KeyEvent& aKeyEvent)
throw(css::container::NoSuchElementException,
css::uno::RuntimeException );
virtual css::uno::Sequence< css::awt::KeyEvent > SAL_CALL getKeyEventsByCommand(const ::rtl::OUString& sCommand)
throw(css::lang::IllegalArgumentException ,
css::container::NoSuchElementException,
css::uno::RuntimeException );
virtual css::uno::Sequence< css::uno::Any > SAL_CALL getPreferredKeyEventsForCommandList(const css::uno::Sequence< ::rtl::OUString >& lCommandList)
throw(css::lang::IllegalArgumentException ,
css::uno::RuntimeException );
virtual void SAL_CALL removeCommandFromAllKeyEvents(const ::rtl::OUString& sCommand)
throw(css::lang::IllegalArgumentException ,
css::container::NoSuchElementException,
css::uno::RuntimeException );
// XUIConfigurationPersistence
virtual void SAL_CALL reload()
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual void SAL_CALL store()
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual void SAL_CALL storeToStorage(const css::uno::Reference< css::embed::XStorage >& xStorage)
throw(css::uno::Exception ,
css::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL isModified()
throw(css::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL isReadOnly()
throw(css::uno::RuntimeException);
// XUIConfigurationStorage
virtual void SAL_CALL setStorage(const css::uno::Reference< css::embed::XStorage >& xStorage)
throw(css::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL hasStorage()
throw(css::uno::RuntimeException);
// XUIConfiguration
virtual void SAL_CALL addConfigurationListener(const css::uno::Reference< css::ui::XUIConfigurationListener >& xListener)
throw(css::uno::RuntimeException);
virtual void SAL_CALL removeConfigurationListener(const css::uno::Reference< css::ui::XUIConfigurationListener >& xListener)
throw(css::uno::RuntimeException);
// XReset
// TODO use XPresetHandler instead if available
virtual void SAL_CALL reset()
throw(css::uno::RuntimeException);
virtual void SAL_CALL addResetListener(const css::uno::Reference< css::form::XResetListener >& xListener)
throw(css::uno::RuntimeException);
virtual void SAL_CALL removeResetListener(const css::uno::Reference< css::form::XResetListener >& xListener)
throw(css::uno::RuntimeException);
// IStorageListener
virtual void changesOccured(const ::rtl::OUString& sPath);
//______________________________________
// helper for derived classes
protected:
//---------------------------------------
/** @short return the current office locale.
@descr We does not cache this value, because we are not listen
for changes on the configuration layer ...
@return ::comphelper::Locale
The current office locale.
*/
::comphelper::Locale impl_ts_getLocale() const;
//______________________________________
// helper
private:
//---------------------------------------
/** @short load a configuration set, using the given stream.
@param xStream
provides the XML structure as stream.
*/
void impl_ts_load(const css::uno::Reference< css::io::XInputStream >& xStream);
//---------------------------------------
/** @short save a configuration set, using the given stream.
@param xStream
the XML structure can be written there.
*/
void impl_ts_save(const css::uno::Reference< css::io::XOutputStream >& xStream);
//---------------------------------------
/** @short try to locate and open a sub storage.
@descr It search at the root storage for the specified
sub storage. If it exists - it will be opened.
By default this method tries to open the storage
for reading. But the calli can request a writeable
storage.
@param xRooStorage
used to locate the sub storage.
@param sSubStorage
relativ path of the sub storage.
@param bOutStream
force open of the sub storage in
write mode - instead of read mode, which
is the default.
@return [XInterface]
will be a css::io::XInpoutStream or a css::io::XOutputStream.
Depends from the parameter bWriteable!
*/
css::uno::Reference< css::uno::XInterface > impl_ts_openSubStorage(const css::uno::Reference< css::embed::XStorage >& xRootStorage,
const ::rtl::OUString& sSubStorage ,
sal_Bool bOutStream );
//---------------------------------------
/** @short returns a reference to one of our internal cache members.
@descr We implement the copy-on-write pattern. Doing so
we know two caches internaly. The second one is used
only, if the container was changed.
This method here returns access to one of these
caches - depending on the change state of this
configuration service.
@param bWriteAccessRequested
if the outside code whish to change the container
it must call this method with "TRUE". So the internal
cache can be prepared for that (means copy-on-write ...).
@return [AcceleratorCache]
c++ reference(!) to one of our internal caches.
*/
AcceleratorCache& impl_getCFG(sal_Bool bWriteAccessRequested = sal_False);
};
} // namespace framework
#endif // __FRAMEWORK_ACCELERATORS_ACCELERATORCONFIGURATION_HXX_
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.