<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2014 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//
//  Original author of this file is Nick Hebner (hebnern@gmail.com).
//

#include "AudioEngine.h"

#include "Dynamics.h"

#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/TimeSource.h"

#include <iostream>

using namespace std;
using namespace boost;

namespace avg {

AudioEngine* AudioEngine::s_pInstance = 0;

AudioEngine* AudioEngine::get()
{
    return s_pInstance;
}

AudioEngine::AudioEngine()
    : m_pTempBuffer(),
      m_pMixBuffer(0),
      m_pLimiter(0),
      m_pGobblerThread(0),
      m_bEnabled(true),
      m_Volume(1),
      m_bInitialized(false)
{
    AVG_ASSERT(s_pInstance == 0);
    if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
        AVG_LOG_ERROR("Can't init SDL audio subsystem.");
        exit(-1);
    }
    s_pInstance = this;
}

AudioEngine::~AudioEngine()
{
    if (m_pMixBuffer) {
        delete[] m_pMixBuffer;
    }
    if (m_pLimiter) {
        delete m_pLimiter;
        m_pLimiter = 0;
    }
    SDL_QuitSubSystem(SDL_INIT_AUDIO);
    m_AudioSources.clear();
}

int AudioEngine::getChannels()
{
    return m_AP.m_Channels;
}

int AudioEngine::getSampleRate()
{
    return m_AP.m_SampleRate;
}

const AudioParams * AudioEngine::getParams()
{
    if (isEnabled()) {
        return &m_AP;
    } else {
        return 0;
    }
}

void AudioEngine::init(const AudioParams& ap, float volume)
{
    m_Volume = volume;
    if (!m_bInitialized) {
        m_bInitialized = true;
        m_AP = ap;
        Dynamics<float, 2>* pLimiter = new Dynamics<float, 2>(float(m_AP.m_SampleRate));
        pLimiter->setThreshold(0.f); // in dB
        pLimiter->setAttackTime(0.f); // in seconds
        pLimiter->setReleaseTime(0.05f); // in seconds
        pLimiter->setRmsTime(0.f); // in seconds
        pLimiter->setRatio(std::numeric_limits<float>::infinity());
        pLimiter->setMakeupGain(0.f); // in dB
        m_pLimiter = pLimiter;

        SDL_AudioSpec desired;
        desired.freq = m_AP.m_SampleRate;
        desired.format = AUDIO_S16SYS;
        desired.channels = m_AP.m_Channels;
        desired.silence = 0;
        desired.samples = m_AP.m_OutputBufferSamples;
        desired.callback = audioCallback;
        desired.userdata = this;

        int err = SDL_OpenAudio(&desired, 0);
        if (err < 0) {
            AVG_TRACE(Logger::category::CONFIG, Logger::severity::WARNING,
                    "Can't open audio: " << SDL_GetError());
            m_bStopGobbler = false;
            m_bFakeAudio = true;
            m_pGobblerThread = new boost::thread(&AudioEngine::consumeBuffers, this);
        } else {
            m_bFakeAudio = false;
        }

    } else {
        if (m_bFakeAudio) {
            m_bStopGobbler = false;
            m_pGobblerThread = new boost::thread(&AudioEngine::consumeBuffers, this);
        } else {
            SDL_PauseAudio(0);
        }
    }
}

void AudioEngine::teardown()
{
    if (m_bFakeAudio) {
        if (m_pGobblerThread) {
            m_bStopGobbler = true;
            m_pGobblerThread->join();
            delete m_pGobblerThread;
            m_pGobblerThread = 0;
        }
    } else {
        lock_guard lock(m_Mutex);
        SDL_PauseAudio(1);
// Optimized away - takes too long.
//        SDL_CloseAudio();
    }

    m_AudioSources.clear();
}

void AudioEngine::setAudioEnabled(bool bEnabled)
{
    SDL_LockAudio();
    lock_guard lock(m_Mutex);
    AVG_ASSERT(m_AudioSources.empty());
    m_bEnabled = bEnabled;
    if (m_bEnabled) {
        play();
    } else {
        pause();
    }
    SDL_UnlockAudio();
}

void AudioEngine::play()
{
    SDL_PauseAudio(0);
}

void AudioEngine::pause()
{
    SDL_PauseAudio(1);
}

int AudioEngine::addSource(AudioMsgQueue& dataQ, AudioMsgQueue& statusQ)
{
    SDL_LockAudio();
    lock_guard lock(m_Mutex);
    static int nextID = -1;
    nextID++;
    AudioSourcePtr pSrc(new AudioSource(dataQ, statusQ, m_AP.m_SampleRate));
    m_AudioSources[nextID] = pSrc;
    SDL_UnlockAudio();
    return nextID;
}

void AudioEngine::removeSource(int id)
{
    SDL_LockAudio();
    lock_guard lock(m_Mutex);
    int numErased = m_AudioSources.erase(id);
    AVG_ASSERT(numErased == 1);
    SDL_UnlockAudio();
}

void AudioEngine::pauseSource(int id)
{
    lock_guard lock(m_Mutex);
    AudioSourceMap::iterator itSource = m_AudioSources.find(id);
    AVG_ASSERT(itSource != m_AudioSources.end());
    AudioSourcePtr pSource = itSource->second;
    pSource->pause();
}

void AudioEngine::playSource(int id)
{
    lock_guard lock(m_Mutex);
    AudioSourceMap::iterator itSource = m_AudioSources.find(id);
    AVG_ASSERT(itSource != m_AudioSources.end());
    AudioSourcePtr pSource = itSource->second;
    pSource->play();
}

void AudioEngine::notifySeek(int id)
{
    lock_guard lock(m_Mutex);
    AudioSourceMap::iterator itSource = m_AudioSources.find(id);
    AVG_ASSERT(itSource != m_AudioSources.end());
    AudioSourcePtr pSource = itSource->second;
    pSource->notifySeek();
}

void AudioEngine::setSourceVolume(int id, float volume)
{
    lock_guard lock(m_Mutex);
    AudioSourceMap::iterator itSource = m_AudioSources.find(id);
    AVG_ASSERT(itSource != m_AudioSources.end());
    AudioSourcePtr pSource = itSource->second;
    pSource->setVolume(volume);
}

void AudioEngine::setVolume(float volume)
{
    SDL_LockAudio();
    lock_guard lock(m_Mutex);
    m_Volume = volume;
    SDL_UnlockAudio();
}

float AudioEngine::getVolume() const
{
    return m_Volume;
}

bool AudioEngine::isEnabled() const
{
    return m_bEnabled;
}

void AudioEngine::mixAudio(Uint8 *pDestBuffer, int destBufferLen)
{
    int numFrames = destBufferLen/(2*getChannels()); // 16 bit samples.

    if (!m_pTempBuffer || m_pTempBuffer->getNumFrames() < numFrames) {
        if (m_pTempBuffer) {
            delete[] m_pMixBuffer;
        }
        m_pTempBuffer = AudioBufferPtr(new AudioBuffer(numFrames, m_AP));
        m_pMixBuffer = new float[getChannels()*numFrames];
    }

    for (int i = 0; i < getChannels()*numFrames; ++i) {
        m_pMixBuffer[i]=0;
    }
    {
        lock_guard lock(m_Mutex);
        AudioSourceMap::iterator it;
        for (it = m_AudioSources.begin(); it != m_AudioSources.end(); it++) {
            m_pTempBuffer->clear();
            it->second->fillAudioBuffer(m_pTempBuffer);
            addBuffers(m_pMixBuffer, m_pTempBuffer);
        }
    }
    calcVolume(m_pMixBuffer, numFrames*getChannels(), getVolume());
    for (int i = 0; i < numFrames; ++i) {
        m_pLimiter->process(m_pMixBuffer+i*getChannels());
        for (int j = 0; j < getChannels(); ++j) {
            ((short*)pDestBuffer)[i*2+j]=short(m_pMixBuffer[i*2+j]*32768);
        }
    }
}

void AudioEngine::consumeBuffers()
{
    // Separate thread that's active only if we don't have a running sound subsystem.
    while (!m_bStopGobbler) {
        msleep(3);
        AudioSourceMap::iterator it;
        lock_guard lock(m_Mutex);
        for (it = m_AudioSources.begin(); it != m_AudioSources.end(); it++) {
            it->second->clearQueue();
        }
    }
}

void AudioEngine::audioCallback(void *userData, Uint8 *audioBuffer, int audioBufferLen)
{
    AudioEngine *pThis = (AudioEngine*)userData;
    pThis->mixAudio(audioBuffer, audioBufferLen);
}

void AudioEngine::addBuffers(float *pDest, AudioBufferPtr pSrc)
{
    int numFrames = pSrc->getNumFrames();
    short * pData = pSrc->getData();
    for(int i = 0; i < numFrames*getChannels(); ++i) {
        pDest[i] += pData[i]/32768.0f;
    }
}

void AudioEngine::calcVolume(float *pBuffer, int numSamples, float volume)
{
    // TODO: We need a VolumeFader class that keeps state.
    for(int i = 0; i < numSamples; ++i) {
        pBuffer[i] *= volume;
    }
}

}
<commit_msg>Fix for spurious Raspberry Pi hangs.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2014 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//
//  Original author of this file is Nick Hebner (hebnern@gmail.com).
//

#include "AudioEngine.h"

#include "Dynamics.h"

#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/TimeSource.h"

#include <iostream>

using namespace std;
using namespace boost;

namespace avg {

AudioEngine* AudioEngine::s_pInstance = 0;

AudioEngine* AudioEngine::get()
{
    return s_pInstance;
}

AudioEngine::AudioEngine()
    : m_pTempBuffer(),
      m_pMixBuffer(0),
      m_pLimiter(0),
      m_pGobblerThread(0),
      m_bEnabled(true),
      m_Volume(1),
      m_bInitialized(false)
{
    AVG_ASSERT(s_pInstance == 0);
    if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
        AVG_LOG_ERROR("Can't init SDL audio subsystem.");
        exit(-1);
    }
    s_pInstance = this;
}

AudioEngine::~AudioEngine()
{
    if (m_pMixBuffer) {
        delete[] m_pMixBuffer;
    }
    if (m_pLimiter) {
        delete m_pLimiter;
        m_pLimiter = 0;
    }
    SDL_QuitSubSystem(SDL_INIT_AUDIO);
    m_AudioSources.clear();
}

int AudioEngine::getChannels()
{
    return m_AP.m_Channels;
}

int AudioEngine::getSampleRate()
{
    return m_AP.m_SampleRate;
}

const AudioParams * AudioEngine::getParams()
{
    if (isEnabled()) {
        return &m_AP;
    } else {
        return 0;
    }
}

void AudioEngine::init(const AudioParams& ap, float volume)
{
    m_Volume = volume;
    if (!m_bInitialized) {
        m_bInitialized = true;
        m_AP = ap;
        Dynamics<float, 2>* pLimiter = new Dynamics<float, 2>(float(m_AP.m_SampleRate));
        pLimiter->setThreshold(0.f); // in dB
        pLimiter->setAttackTime(0.f); // in seconds
        pLimiter->setReleaseTime(0.05f); // in seconds
        pLimiter->setRmsTime(0.f); // in seconds
        pLimiter->setRatio(std::numeric_limits<float>::infinity());
        pLimiter->setMakeupGain(0.f); // in dB
        m_pLimiter = pLimiter;

        SDL_AudioSpec desired;
        desired.freq = m_AP.m_SampleRate;
        desired.format = AUDIO_S16SYS;
        desired.channels = m_AP.m_Channels;
        desired.silence = 0;
        desired.samples = m_AP.m_OutputBufferSamples;
        desired.callback = audioCallback;
        desired.userdata = this;

        int err = SDL_OpenAudio(&desired, 0);
        if (err < 0) {
            AVG_TRACE(Logger::category::CONFIG, Logger::severity::WARNING,
                    "Can't open audio: " << SDL_GetError());
            m_bStopGobbler = false;
            m_bFakeAudio = true;
            m_pGobblerThread = new boost::thread(&AudioEngine::consumeBuffers, this);
        } else {
            m_bFakeAudio = false;
        }

    } else {
        if (m_bFakeAudio) {
            m_bStopGobbler = false;
            m_pGobblerThread = new boost::thread(&AudioEngine::consumeBuffers, this);
        } else {
            SDL_PauseAudio(0);
        }
    }
}

void AudioEngine::teardown()
{
    if (m_bFakeAudio) {
        if (m_pGobblerThread) {
            m_bStopGobbler = true;
            m_pGobblerThread->join();
            delete m_pGobblerThread;
            m_pGobblerThread = 0;
        }
    } else {
        lock_guard lock(m_Mutex);
        SDL_PauseAudio(1);
#ifdef AVG_ENABLE_RPI
        // Optimized away for all but Raspberry PI - takes too long.
        // But: Leaving it away on the RPi causes hangs.
        SDL_CloseAudio();
#endif
    }

    m_AudioSources.clear();
}

void AudioEngine::setAudioEnabled(bool bEnabled)
{
    SDL_LockAudio();
    lock_guard lock(m_Mutex);
    AVG_ASSERT(m_AudioSources.empty());
    m_bEnabled = bEnabled;
    if (m_bEnabled) {
        play();
    } else {
        pause();
    }
    SDL_UnlockAudio();
}

void AudioEngine::play()
{
    SDL_PauseAudio(0);
}

void AudioEngine::pause()
{
    SDL_PauseAudio(1);
}

int AudioEngine::addSource(AudioMsgQueue& dataQ, AudioMsgQueue& statusQ)
{
    SDL_LockAudio();
    lock_guard lock(m_Mutex);
    static int nextID = -1;
    nextID++;
    AudioSourcePtr pSrc(new AudioSource(dataQ, statusQ, m_AP.m_SampleRate));
    m_AudioSources[nextID] = pSrc;
    SDL_UnlockAudio();
    return nextID;
}

void AudioEngine::removeSource(int id)
{
    SDL_LockAudio();
    lock_guard lock(m_Mutex);
    int numErased = m_AudioSources.erase(id);
    AVG_ASSERT(numErased == 1);
    SDL_UnlockAudio();
}

void AudioEngine::pauseSource(int id)
{
    lock_guard lock(m_Mutex);
    AudioSourceMap::iterator itSource = m_AudioSources.find(id);
    AVG_ASSERT(itSource != m_AudioSources.end());
    AudioSourcePtr pSource = itSource->second;
    pSource->pause();
}

void AudioEngine::playSource(int id)
{
    lock_guard lock(m_Mutex);
    AudioSourceMap::iterator itSource = m_AudioSources.find(id);
    AVG_ASSERT(itSource != m_AudioSources.end());
    AudioSourcePtr pSource = itSource->second;
    pSource->play();
}

void AudioEngine::notifySeek(int id)
{
    lock_guard lock(m_Mutex);
    AudioSourceMap::iterator itSource = m_AudioSources.find(id);
    AVG_ASSERT(itSource != m_AudioSources.end());
    AudioSourcePtr pSource = itSource->second;
    pSource->notifySeek();
}

void AudioEngine::setSourceVolume(int id, float volume)
{
    lock_guard lock(m_Mutex);
    AudioSourceMap::iterator itSource = m_AudioSources.find(id);
    AVG_ASSERT(itSource != m_AudioSources.end());
    AudioSourcePtr pSource = itSource->second;
    pSource->setVolume(volume);
}

void AudioEngine::setVolume(float volume)
{
    SDL_LockAudio();
    lock_guard lock(m_Mutex);
    m_Volume = volume;
    SDL_UnlockAudio();
}

float AudioEngine::getVolume() const
{
    return m_Volume;
}

bool AudioEngine::isEnabled() const
{
    return m_bEnabled;
}

void AudioEngine::mixAudio(Uint8 *pDestBuffer, int destBufferLen)
{
    int numFrames = destBufferLen/(2*getChannels()); // 16 bit samples.

    if (!m_pTempBuffer || m_pTempBuffer->getNumFrames() < numFrames) {
        if (m_pTempBuffer) {
            delete[] m_pMixBuffer;
        }
        m_pTempBuffer = AudioBufferPtr(new AudioBuffer(numFrames, m_AP));
        m_pMixBuffer = new float[getChannels()*numFrames];
    }

    for (int i = 0; i < getChannels()*numFrames; ++i) {
        m_pMixBuffer[i]=0;
    }
    {
        lock_guard lock(m_Mutex);
        AudioSourceMap::iterator it;
        for (it = m_AudioSources.begin(); it != m_AudioSources.end(); it++) {
            m_pTempBuffer->clear();
            it->second->fillAudioBuffer(m_pTempBuffer);
            addBuffers(m_pMixBuffer, m_pTempBuffer);
        }
    }
    calcVolume(m_pMixBuffer, numFrames*getChannels(), getVolume());
    for (int i = 0; i < numFrames; ++i) {
        m_pLimiter->process(m_pMixBuffer+i*getChannels());
        for (int j = 0; j < getChannels(); ++j) {
            ((short*)pDestBuffer)[i*2+j]=short(m_pMixBuffer[i*2+j]*32768);
        }
    }
}

void AudioEngine::consumeBuffers()
{
    // Separate thread that's active only if we don't have a running sound subsystem.
    while (!m_bStopGobbler) {
        msleep(3);
        AudioSourceMap::iterator it;
        lock_guard lock(m_Mutex);
        for (it = m_AudioSources.begin(); it != m_AudioSources.end(); it++) {
            it->second->clearQueue();
        }
    }
}

void AudioEngine::audioCallback(void *userData, Uint8 *audioBuffer, int audioBufferLen)
{
    AudioEngine *pThis = (AudioEngine*)userData;
    pThis->mixAudio(audioBuffer, audioBufferLen);
}

void AudioEngine::addBuffers(float *pDest, AudioBufferPtr pSrc)
{
    int numFrames = pSrc->getNumFrames();
    short * pData = pSrc->getData();
    for(int i = 0; i < numFrames*getChannels(); ++i) {
        pDest[i] += pData[i]/32768.0f;
    }
}

void AudioEngine::calcVolume(float *pBuffer, int numSamples, float volume)
{
    // TODO: We need a VolumeFader class that keeps state.
    for(int i = 0; i < numSamples; ++i) {
        pBuffer[i] *= volume;
    }
}

}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkContextActor.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkContextActor.h"

#include "vtkContext2D.h"
#include "vtkOpenGLContextDevice2D.h"
#include "vtkOpenGL2ContextDevice2D.h"

#include "vtkContext3D.h"
#include "vtkOpenGLContextDevice3D.h"
#include "vtkContextScene.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGL2ContextDevice2D.h"
#include "vtkOpenGLContextDevice2D.h"
#include "vtkOpenGLExtensionManager.h"
#include "vtkOpenGLRenderer.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkTransform2D.h"
#include "vtkViewport.h"
#include "vtkWindow.h"

#include <algorithm>

namespace
{
  // vtkViewportSpecification is a helper class that makes it easier to do some
  // of the arithmetic for dealing with tiled displays (in VTK, for saving large
  // images and in ParaView for actual tiled display).
  template <class T>
    class vtkViewportSpecification
      {
    public:
      vtkViewportSpecification(const T* input)
        {
        this->Data[0] = input[0];
        this->Data[1] = input[1];
        this->Data[2] = input[2];
        this->Data[3] = input[3];
        }

      vtkViewportSpecification(const vtkViewportSpecification<T> &other)
        {
        this->Data[0] = other.Data[0];
        this->Data[1] = other.Data[1];
        this->Data[2] = other.Data[2];
        this->Data[3] = other.Data[3];
        }

      // returns false is intersection results in an empty box, otherwise returns true.
      // here we assume that typename T handles signed values correctly.
      bool intersect(const vtkViewportSpecification<T> &other)
        {
        vtkViewportSpecification<T> clone(*this);

        this->Data[0] = std::max(other.x(), clone.x());
        this->Data[1] = std::max(other.y(), clone.y());

        T _width = std::min(clone.x() + clone.width(),
          other.x() + other.width()) - this->Data[0];

        T _height = std::min(clone.y() + clone.height(),
          other.y() + other.height()) - this->Data[1];

        _width = std::max(0, _width);
        _height = std::max(0, _height);

        this->Data[2] = this->x() + _width;
        this->Data[3] = this->y() + _height;
        return (_width !=0 && _height != 0);
        }

      const T* data() const { return this->Data; }
      const T& x() const { return this->Data[0]; }
      const T& y() const { return this->Data[1]; }
      T width() const { return this->Data[2] - this->Data[0]; }
      T height() const { return this->Data[3] - this->Data[1]; }

    private:
      T Data[4];
      };

  template <class T>
    ostream& operator << (ostream& str, const vtkViewportSpecification<T>& other)
      {
      str << other.data()[0] << ", "
        << other.data()[1] << ", "
        << other.data()[2] << ", "
        << other.data()[3];
      return str;
      }

  // use this method to convert from normalized-to-display space i.e. [0.0, 1.0]
  // to screen pixels.
  vtkViewportSpecification<int> convert(
    const vtkViewportSpecification<double>& other,
    int width, int height)
    {
    int value[4];
    value[0] = static_cast<int>(other.data()[0] * width);
    value[1] = static_cast<int>(other.data()[1] * height);
    value[2] = static_cast<int>(other.data()[2] * width);
    value[3] = static_cast<int>(other.data()[3] * height);

    return vtkViewportSpecification<int>(value);
    }
}

vtkStandardNewMacro(vtkContextActor);

//----------------------------------------------------------------------------
vtkContextActor::vtkContextActor()
{
  this->Initialized = false;
  this->Scene = vtkSmartPointer<vtkContextScene>::New();

  this->Context->SetContext3D(this->Context3D.GetPointer());
}

//----------------------------------------------------------------------------
vtkContextActor::~vtkContextActor()
{
  if (this->Context.GetPointer())
    {
    this->Context->End();
    }
  if (this->Context3D.GetPointer())
    {
    this->Context3D->End();
    }
}

//----------------------------------------------------------------------------
vtkContextScene * vtkContextActor::GetScene()
{
  return this->Scene.GetPointer();
}

//----------------------------------------------------------------------------
void vtkContextActor::SetScene(vtkContextScene *scene)
{
  this->Scene = scene;
}

//----------------------------------------------------------------------------
void vtkContextActor::ReleaseGraphicsResources(vtkWindow *window)
{
  vtkOpenGLContextDevice2D *device =
      vtkOpenGLContextDevice2D::SafeDownCast(this->Context->GetDevice());
  if (device)
    {
    device->ReleaseGraphicsResources(window);
    }

  if(this->Scene.GetPointer())
    {
    this->Scene->ReleaseGraphicsResources();
    }
}

//----------------------------------------------------------------------------
// Renders an actor2D's property and then it's mapper.
int vtkContextActor::RenderOverlay(vtkViewport* viewport)
{
  vtkDebugMacro(<< "vtkContextActor::RenderOverlay");

  if (!this->Context.GetPointer())
    {
    vtkErrorMacro(<< "vtkContextActor::Render - No painter set");
    return 0;
    }

  // view_viewport is a normalized viewport specification for this view in a
  // large "single" window where 0.0 is min and 1.0 is max. For multi-tile
  // views, the range (0-1) will span across multiple tiles.
  vtkViewportSpecification<double> view_viewport(
    viewport->GetViewport());

  // tileviewport is a normalized viewport specification for this "window"
  // mapping where in a multi-tile display, does the current window correspond.
  vtkViewportSpecification<double> tile_viewport(
    viewport->GetVTKWindow()->GetTileViewport());

  // this size is already scaled using TileScale.
  const int *tile_size = viewport->GetVTKWindow()->GetSize();

  // convert both to pixel space before we start doing our arithmetic.
  vtkViewportSpecification<int> tile_viewport_pixels =
    convert(tile_viewport, tile_size[0], tile_size[1]);
  vtkViewportSpecification<int> view_viewport_pixels=
    convert(view_viewport, tile_size[0], tile_size[1]);

  // interacted space.
  vtkViewportSpecification<int> actual_viewport_pixels(view_viewport_pixels);
  if (!actual_viewport_pixels.intersect(tile_viewport_pixels))
    {
    return 1;
    }

  vtkTransform2D* transform = this->Scene->GetTransform();
  transform->Identity();
  transform->Translate(
    view_viewport_pixels.x() - actual_viewport_pixels.x(),
    view_viewport_pixels.y() - actual_viewport_pixels.y());

  if (!this->Initialized)
    {
    this->Initialize(viewport);
    }

  // Pass the viewport details onto the context device.
  int size[2];
  size[0] = view_viewport_pixels.width();
  size[1] = view_viewport_pixels.height();
  vtkRecti viewportRect(actual_viewport_pixels.x() - view_viewport_pixels.x(),
                        actual_viewport_pixels.y() - view_viewport_pixels.y(),
                        actual_viewport_pixels.width(),
                        actual_viewport_pixels.height());
  this->Context->GetDevice()->SetViewportSize(vtkVector2i(size));
  this->Context->GetDevice()->SetViewportRect(viewportRect);

  // This is the entry point for all 2D rendering.
  // First initialize the drawing device.
  this->Context->GetDevice()->Begin(viewport);
  this->Scene->SetGeometry(size);
  this->Scene->Paint(this->Context.GetPointer());
  this->Context->GetDevice()->End();
  return 1;
}

//----------------------------------------------------------------------------
void vtkContextActor::Initialize(vtkViewport* viewport)
{
  vtkContextDevice2D *device = NULL;
  if (vtkOpenGL2ContextDevice2D::IsSupported(viewport))
    {
    vtkDebugMacro("Using OpenGL 2 for 2D rendering.")
    device = vtkOpenGL2ContextDevice2D::New();
    vtkContextDevice3D *dev = vtkOpenGLContextDevice3D::New();
    this->Context3D->Begin(dev);
    dev->Delete();
    }
  else
    {
    vtkDebugMacro("Using OpenGL 1 for 2D rendering.")
    device = vtkOpenGLContextDevice2D::New();
    }
  if (device)
    {
    this->Context->Begin(device);
    device->Delete();
    this->Initialized = true;
    }
  else
    {
    // Failed
    vtkErrorMacro("Error: failed to initialize the render device.")
    }
}

//----------------------------------------------------------------------------
void vtkContextActor::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Context: " << this->Context << "\n";
  if (this->Context.GetPointer())
    {
    this->Context->PrintSelf(os, indent.GetNextIndent());
    }
}
<commit_msg>Ensure we always initialize the 3D drawing device<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkContextActor.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkContextActor.h"

#include "vtkContext2D.h"
#include "vtkOpenGLContextDevice2D.h"
#include "vtkOpenGL2ContextDevice2D.h"

#include "vtkContext3D.h"
#include "vtkOpenGLContextDevice3D.h"
#include "vtkContextScene.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGL2ContextDevice2D.h"
#include "vtkOpenGLContextDevice2D.h"
#include "vtkOpenGLExtensionManager.h"
#include "vtkOpenGLRenderer.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkTransform2D.h"
#include "vtkViewport.h"
#include "vtkWindow.h"

#include <algorithm>

namespace
{
  // vtkViewportSpecification is a helper class that makes it easier to do some
  // of the arithmetic for dealing with tiled displays (in VTK, for saving large
  // images and in ParaView for actual tiled display).
  template <class T>
    class vtkViewportSpecification
      {
    public:
      vtkViewportSpecification(const T* input)
        {
        this->Data[0] = input[0];
        this->Data[1] = input[1];
        this->Data[2] = input[2];
        this->Data[3] = input[3];
        }

      vtkViewportSpecification(const vtkViewportSpecification<T> &other)
        {
        this->Data[0] = other.Data[0];
        this->Data[1] = other.Data[1];
        this->Data[2] = other.Data[2];
        this->Data[3] = other.Data[3];
        }

      // returns false is intersection results in an empty box, otherwise returns true.
      // here we assume that typename T handles signed values correctly.
      bool intersect(const vtkViewportSpecification<T> &other)
        {
        vtkViewportSpecification<T> clone(*this);

        this->Data[0] = std::max(other.x(), clone.x());
        this->Data[1] = std::max(other.y(), clone.y());

        T _width = std::min(clone.x() + clone.width(),
          other.x() + other.width()) - this->Data[0];

        T _height = std::min(clone.y() + clone.height(),
          other.y() + other.height()) - this->Data[1];

        _width = std::max(0, _width);
        _height = std::max(0, _height);

        this->Data[2] = this->x() + _width;
        this->Data[3] = this->y() + _height;
        return (_width !=0 && _height != 0);
        }

      const T* data() const { return this->Data; }
      const T& x() const { return this->Data[0]; }
      const T& y() const { return this->Data[1]; }
      T width() const { return this->Data[2] - this->Data[0]; }
      T height() const { return this->Data[3] - this->Data[1]; }

    private:
      T Data[4];
      };

  template <class T>
    ostream& operator << (ostream& str, const vtkViewportSpecification<T>& other)
      {
      str << other.data()[0] << ", "
        << other.data()[1] << ", "
        << other.data()[2] << ", "
        << other.data()[3];
      return str;
      }

  // use this method to convert from normalized-to-display space i.e. [0.0, 1.0]
  // to screen pixels.
  vtkViewportSpecification<int> convert(
    const vtkViewportSpecification<double>& other,
    int width, int height)
    {
    int value[4];
    value[0] = static_cast<int>(other.data()[0] * width);
    value[1] = static_cast<int>(other.data()[1] * height);
    value[2] = static_cast<int>(other.data()[2] * width);
    value[3] = static_cast<int>(other.data()[3] * height);

    return vtkViewportSpecification<int>(value);
    }
}

vtkStandardNewMacro(vtkContextActor);

//----------------------------------------------------------------------------
vtkContextActor::vtkContextActor()
{
  this->Initialized = false;
  this->Scene = vtkSmartPointer<vtkContextScene>::New();

  this->Context->SetContext3D(this->Context3D.GetPointer());
}

//----------------------------------------------------------------------------
vtkContextActor::~vtkContextActor()
{
  if (this->Context.GetPointer())
    {
    this->Context->End();
    }
  if (this->Context3D.GetPointer())
    {
    this->Context3D->End();
    }
}

//----------------------------------------------------------------------------
vtkContextScene * vtkContextActor::GetScene()
{
  return this->Scene.GetPointer();
}

//----------------------------------------------------------------------------
void vtkContextActor::SetScene(vtkContextScene *scene)
{
  this->Scene = scene;
}

//----------------------------------------------------------------------------
void vtkContextActor::ReleaseGraphicsResources(vtkWindow *window)
{
  vtkOpenGLContextDevice2D *device =
      vtkOpenGLContextDevice2D::SafeDownCast(this->Context->GetDevice());
  if (device)
    {
    device->ReleaseGraphicsResources(window);
    }

  if(this->Scene.GetPointer())
    {
    this->Scene->ReleaseGraphicsResources();
    }
}

//----------------------------------------------------------------------------
// Renders an actor2D's property and then it's mapper.
int vtkContextActor::RenderOverlay(vtkViewport* viewport)
{
  vtkDebugMacro(<< "vtkContextActor::RenderOverlay");

  if (!this->Context.GetPointer())
    {
    vtkErrorMacro(<< "vtkContextActor::Render - No painter set");
    return 0;
    }

  // view_viewport is a normalized viewport specification for this view in a
  // large "single" window where 0.0 is min and 1.0 is max. For multi-tile
  // views, the range (0-1) will span across multiple tiles.
  vtkViewportSpecification<double> view_viewport(
    viewport->GetViewport());

  // tileviewport is a normalized viewport specification for this "window"
  // mapping where in a multi-tile display, does the current window correspond.
  vtkViewportSpecification<double> tile_viewport(
    viewport->GetVTKWindow()->GetTileViewport());

  // this size is already scaled using TileScale.
  const int *tile_size = viewport->GetVTKWindow()->GetSize();

  // convert both to pixel space before we start doing our arithmetic.
  vtkViewportSpecification<int> tile_viewport_pixels =
    convert(tile_viewport, tile_size[0], tile_size[1]);
  vtkViewportSpecification<int> view_viewport_pixels=
    convert(view_viewport, tile_size[0], tile_size[1]);

  // interacted space.
  vtkViewportSpecification<int> actual_viewport_pixels(view_viewport_pixels);
  if (!actual_viewport_pixels.intersect(tile_viewport_pixels))
    {
    return 1;
    }

  vtkTransform2D* transform = this->Scene->GetTransform();
  transform->Identity();
  transform->Translate(
    view_viewport_pixels.x() - actual_viewport_pixels.x(),
    view_viewport_pixels.y() - actual_viewport_pixels.y());

  if (!this->Initialized)
    {
    this->Initialize(viewport);
    }

  // Pass the viewport details onto the context device.
  int size[2];
  size[0] = view_viewport_pixels.width();
  size[1] = view_viewport_pixels.height();
  vtkRecti viewportRect(actual_viewport_pixels.x() - view_viewport_pixels.x(),
                        actual_viewport_pixels.y() - view_viewport_pixels.y(),
                        actual_viewport_pixels.width(),
                        actual_viewport_pixels.height());
  this->Context->GetDevice()->SetViewportSize(vtkVector2i(size));
  this->Context->GetDevice()->SetViewportRect(viewportRect);

  // This is the entry point for all 2D rendering.
  // First initialize the drawing device.
  this->Context->GetDevice()->Begin(viewport);
  this->Scene->SetGeometry(size);
  this->Scene->Paint(this->Context.GetPointer());
  this->Context->GetDevice()->End();
  return 1;
}

//----------------------------------------------------------------------------
void vtkContextActor::Initialize(vtkViewport* viewport)
{
  vtkContextDevice2D *device = NULL;
  vtkNew<vtkOpenGLContextDevice3D> dev;
  this->Context3D->Begin(dev.GetPointer());
  if (vtkOpenGL2ContextDevice2D::IsSupported(viewport))
    {
    vtkDebugMacro("Using OpenGL 2 for 2D rendering.")
    device = vtkOpenGL2ContextDevice2D::New();
    }
  else
    {
    vtkDebugMacro("Using OpenGL 1 for 2D rendering.")
    device = vtkOpenGLContextDevice2D::New();
    }
  if (device)
    {
    this->Context->Begin(device);
    device->Delete();
    this->Initialized = true;
    }
  else
    {
    // Failed
    vtkErrorMacro("Error: failed to initialize the render device.")
    }
}

//----------------------------------------------------------------------------
void vtkContextActor::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Context: " << this->Context << "\n";
  if (this->Context.GetPointer())
    {
    this->Context->PrintSelf(os, indent.GetNextIndent());
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hfi_globalindex.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 11:57:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_globalindex.hxx"

// NOT FULLY DEFINED SERVICES
#include <cosv/template/tpltools.hxx>
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_language.hxx>
#include <ary/idl/i_module.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_navibar.hxx"
#include "hfi_typetext.hxx"
#include "hi_linkhelper.hxx"

namespace
{

/**
*/
enum E_Types
{
        t_service           = 0,
        t_interface         = 1,
        t_struct            = 2,
        t_exception         = 3,
        t_enum              = 4,
        t_typedef           = 5,
        t_constantsgroup    = 6,
        t_property          = 7,
        t_function          = 8,
        t_structelement     = 9,
        t_enumvalue         = 10,
        t_constant          = 11,
        t_module            = 12,
        t_singleton         = 13,
        t_attribute         = 14,
        t_siservice         = 15,
        t_sisingleton       = 16,
        t_MAX
};

String  G_sDummy;
uintt   G_nDummy;

/*  RC-Ids for IDL types (see reposy.cxx):

    Module              2000
    Interface           2001
    Function            2002
    Service             2003
    Property            2004

    Enum                2005
    EnumValue           2006
    Typedef             2007
    Struct              2008
    StructElement       2009

    Exception           2010
    ConstantGroup       2011
    Constant            2012
    Singleton           2013
    Attribute           2014
    SglIfcService       2015
    SglIfcSingleton     2016
*/
const int C_nNumberOfIdlTypes = 17;
const char *    C_sTypeNames[C_nNumberOfIdlTypes] =
                    { "module ",    "interface ",   "function ",    "service ",     "property ",
                      "enum ",      "value ",       "typedef ",     "struct ",      "field ",
                      "exception ", "constants group ", "constant ","singleton ",   "attribute ",
                      "service",    "singleton"
                    };
const char *    C_sOwnerNames[C_nNumberOfIdlTypes] =
                    { "module ",    "module ",      "interface ",   "module ",      "service ",
                      "module ",    "enum ",        "module ",      "module ",      "", // could be struct or exception
                      "module ",    "module ",      "constants group ", "module ",  "interface ",
                      "module",     "module"
                    };
const intt C_nNamesArrayOffset = intt(ary::idl::Module::class_id);
const int C_nIxField = 9;

const char C_cAlphabet[] =
"A B C D E "
"F G H I J "
"K L M N O "
"P Q R S T "
"U V W X Y "
"Z";

HF_IdlGlobalIndex::PageData     G_PageData;

}   // end anonymous namespace

inline void
HF_IdlGlobalIndex::write_EntryItself( Xml::Element &               o_destination,
                                      const ary::idl::CodeEntity & i_ce,
                                      const HF_IdlTypeText &       i_typeLinkWriter ) const
{
    i_typeLinkWriter.Produce_IndexLink(o_destination, i_ce);
    o_destination << " - ";
}

HF_IdlGlobalIndex::HF_IdlGlobalIndex( Environment &     io_rEnv,
                                      Xml::Element &    o_rOut )
    :   HtmlFactory_Idl(io_rEnv, &o_rOut)
{
}

HF_IdlGlobalIndex::~HF_IdlGlobalIndex()
{
}

void
HF_IdlGlobalIndex::Produce_Page(ary::idl::alphabetical_index::E_Letter i_letter) const
{
    make_Navibar();

    HF_TitleTable
        aTitle(CurOut());
    StreamLock sl(100);
    aTitle.Produce_Title( sl()
                          << "Global Index "
                          << ( i_letter != ary::idl::alphabetical_index::non_alpha
                                ?   char(int(i_letter)-'a'+'A')
                                :   '_' )
                          << c_str );

    // Letters Index
    aTitle.Add_Row()
        << new Xml::XmlCode(
            "
A B C D E F G H I J"
            " K L M N O P Q R S T"
            " U V W X Y Z _
" );

    Out().Enter(CurOut() >> *new Html::DefList);

    csv::erase_container(G_PageData);
    Env().Data().Get_IndexData(G_PageData, i_letter);

    // Helper object to produce links to the index Entries.
    HF_IdlTypeText aTypeLinkWriter(Env(),HF_IdlTypeText::use_for_javacompatible_index);

    PageData::const_iterator itEnd = G_PageData.end();
    for ( PageData::const_iterator iter = G_PageData.begin();
          iter != itEnd;
          ++iter )
    {
        produce_Line(iter, aTypeLinkWriter);
    }   // end for

    Out().Leave();
    CurOut() << new Html::HorizontalLine;
}

void
HF_IdlGlobalIndex::make_Navibar() const
{
    HF_IdlNavigationBar
        aNaviBar(Env(), CurOut());
    aNaviBar.Produce_IndexMainRow();

    CurOut() << new Html::HorizontalLine();
}

void
HF_IdlGlobalIndex::produce_Line( PageData::const_iterator i_entry,
                                 const HF_IdlTypeText &   i_typeLinkWriter) const
{
    const client &
        rCe = Env().Data().Find_Ce(*i_entry);
    if (NOT rCe.Owner().IsValid())
        return; // Omit global namespace.

    // The destination for the created output:
    Xml::Element & rDT = CurOut() >> *new Html::DefListTerm;

    /** The following code is intended to produce an output that
        will be recognized by the context help system of Forte.
        That is reached by making it similar to the indices, that
        Javadoc produces.
        If the link to the Entry contains a hashmark, the Forte-Help
        requires following a link to the owner.
        But if there is no hashmark, the following link must go to
        the same Entry again. Doesn't make really sense :-(, but that's
        like it is.
    */
    write_EntryItself(rDT,rCe,i_typeLinkWriter);
    if (rCe.SightLevel() == ary::idl::sl_Member)
        write_OwnerOfEntry(rDT,rCe,i_typeLinkWriter);
    else
        write_EntrySecondTime(rDT,rCe,i_typeLinkWriter);

    // This produces an empty "

", which is also needed to reach
    //   similarity to the Javadoc index:
    CurOut() << new Html::DefListDefinition;
}

void
HF_IdlGlobalIndex::write_OwnerOfEntry( Xml::Element &               o_destination,
                                       const ary::idl::CodeEntity & i_ce,
                                       const HF_IdlTypeText &       i_typeLinkWriter ) const
{
    const client &
        rOwner = Env().Data().Find_Ce(i_ce.Owner());

    int nIx = int(i_ce.ClassId() - C_nNamesArrayOffset);
    csv_assert(csv::in_range(0,nIx,C_nNumberOfIdlTypes));

    o_destination << C_sTypeNames[nIx]
                  << "in ";
    if (nIx != C_nIxField)
    {
        o_destination << C_sOwnerNames[nIx];
    }
    else
    {
        uintt nOwnerIx = rOwner.ClassId() - C_nNamesArrayOffset;
        csv_assert(0 <= nOwnerIx && nOwnerIx < C_nNumberOfIdlTypes);
        o_destination << C_sTypeNames[nOwnerIx];
    }
    i_typeLinkWriter.Produce_IndexOwnerLink(o_destination, rOwner);
}

void
HF_IdlGlobalIndex::write_EntrySecondTime( Xml::Element &                o_destination,
                                          const ary::idl::CodeEntity &  i_ce,
                                          const HF_IdlTypeText &        i_typeLinkWriter ) const
{
    int nIx = int(i_ce.ClassId() - C_nNamesArrayOffset);
    csv_assert(csv::in_range(0,nIx,C_nNumberOfIdlTypes));

    o_destination << C_sTypeNames[nIx]
                  << " ";
    i_typeLinkWriter.Produce_IndexSecondEntryLink(o_destination, i_ce);
}
<commit_msg>INTEGRATION: CWS sb56 (1.7.2); FILE MERGED 2006/07/07 08:57:10 sb 1.7.2.1: #i67105# Made code compile (warning-free) with debug=x.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hfi_globalindex.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: ihi $ $Date: 2006-08-24 10:44:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_globalindex.hxx"

// NOT FULLY DEFINED SERVICES
#include <cosv/template/tpltools.hxx>
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_language.hxx>
#include <ary/idl/i_module.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_navibar.hxx"
#include "hfi_typetext.hxx"
#include "hi_linkhelper.hxx"

namespace
{

/**
*/
enum E_Types
{
        t_service           = 0,
        t_interface         = 1,
        t_struct            = 2,
        t_exception         = 3,
        t_enum              = 4,
        t_typedef           = 5,
        t_constantsgroup    = 6,
        t_property          = 7,
        t_function          = 8,
        t_structelement     = 9,
        t_enumvalue         = 10,
        t_constant          = 11,
        t_module            = 12,
        t_singleton         = 13,
        t_attribute         = 14,
        t_siservice         = 15,
        t_sisingleton       = 16,
        t_MAX
};

String  G_sDummy;
uintt   G_nDummy;

/*  RC-Ids for IDL types (see reposy.cxx):

    Module              2000
    Interface           2001
    Function            2002
    Service             2003
    Property            2004

    Enum                2005
    EnumValue           2006
    Typedef             2007
    Struct              2008
    StructElement       2009

    Exception           2010
    ConstantGroup       2011
    Constant            2012
    Singleton           2013
    Attribute           2014
    SglIfcService       2015
    SglIfcSingleton     2016
*/
const int C_nNumberOfIdlTypes = 17;
const char *    C_sTypeNames[C_nNumberOfIdlTypes] =
                    { "module ",    "interface ",   "function ",    "service ",     "property ",
                      "enum ",      "value ",       "typedef ",     "struct ",      "field ",
                      "exception ", "constants group ", "constant ","singleton ",   "attribute ",
                      "service",    "singleton"
                    };
const char *    C_sOwnerNames[C_nNumberOfIdlTypes] =
                    { "module ",    "module ",      "interface ",   "module ",      "service ",
                      "module ",    "enum ",        "module ",      "module ",      "", // could be struct or exception
                      "module ",    "module ",      "constants group ", "module ",  "interface ",
                      "module",     "module"
                    };
const intt C_nNamesArrayOffset = intt(ary::idl::Module::class_id);
const int C_nIxField = 9;

const char C_cAlphabet[] =
"A B C D E "
"F G H I J "
"K L M N O "
"P Q R S T "
"U V W X Y "
"Z";

HF_IdlGlobalIndex::PageData     G_PageData;

}   // end anonymous namespace

inline void
HF_IdlGlobalIndex::write_EntryItself( Xml::Element &               o_destination,
                                      const ary::idl::CodeEntity & i_ce,
                                      const HF_IdlTypeText &       i_typeLinkWriter ) const
{
    i_typeLinkWriter.Produce_IndexLink(o_destination, i_ce);
    o_destination << " - ";
}

HF_IdlGlobalIndex::HF_IdlGlobalIndex( Environment &     io_rEnv,
                                      Xml::Element &    o_rOut )
    :   HtmlFactory_Idl(io_rEnv, &o_rOut)
{
}

HF_IdlGlobalIndex::~HF_IdlGlobalIndex()
{
}

void
HF_IdlGlobalIndex::Produce_Page(ary::idl::alphabetical_index::E_Letter i_letter) const
{
    make_Navibar();

    HF_TitleTable
        aTitle(CurOut());
    StreamLock sl(100);
    aTitle.Produce_Title( sl()
                          << "Global Index "
                          << ( i_letter != ary::idl::alphabetical_index::non_alpha
                                ?   char(int(i_letter)-'a'+'A')
                                :   '_' )
                          << c_str );

    // Letters Index
    aTitle.Add_Row()
        << new Xml::XmlCode(
            "
A B C D E F G H I J"
            " K L M N O P Q R S T"
            " U V W X Y Z _
" );

    Out().Enter(CurOut() >> *new Html::DefList);

    csv::erase_container(G_PageData);
    Env().Data().Get_IndexData(G_PageData, i_letter);

    // Helper object to produce links to the index Entries.
    HF_IdlTypeText aTypeLinkWriter(Env(),HF_IdlTypeText::use_for_javacompatible_index);

    PageData::const_iterator itEnd = G_PageData.end();
    for ( PageData::const_iterator iter = G_PageData.begin();
          iter != itEnd;
          ++iter )
    {
        produce_Line(iter, aTypeLinkWriter);
    }   // end for

    Out().Leave();
    CurOut() << new Html::HorizontalLine;
}

void
HF_IdlGlobalIndex::make_Navibar() const
{
    HF_IdlNavigationBar
        aNaviBar(Env(), CurOut());
    aNaviBar.Produce_IndexMainRow();

    CurOut() << new Html::HorizontalLine();
}

void
HF_IdlGlobalIndex::produce_Line( PageData::const_iterator i_entry,
                                 const HF_IdlTypeText &   i_typeLinkWriter) const
{
    const client &
        rCe = Env().Data().Find_Ce(*i_entry);
    if (NOT rCe.Owner().IsValid())
        return; // Omit global namespace.

    // The destination for the created output:
    Xml::Element & rDT = CurOut() >> *new Html::DefListTerm;

    /** The following code is intended to produce an output that
        will be recognized by the context help system of Forte.
        That is reached by making it similar to the indices, that
        Javadoc produces.
        If the link to the Entry contains a hashmark, the Forte-Help
        requires following a link to the owner.
        But if there is no hashmark, the following link must go to
        the same Entry again. Doesn't make really sense :-(, but that's
        like it is.
    */
    write_EntryItself(rDT,rCe,i_typeLinkWriter);
    if (rCe.SightLevel() == ary::idl::sl_Member)
        write_OwnerOfEntry(rDT,rCe,i_typeLinkWriter);
    else
        write_EntrySecondTime(rDT,rCe,i_typeLinkWriter);

    // This produces an empty "

", which is also needed to reach
    //   similarity to the Javadoc index:
    CurOut() << new Html::DefListDefinition;
}

void
HF_IdlGlobalIndex::write_OwnerOfEntry( Xml::Element &               o_destination,
                                       const ary::idl::CodeEntity & i_ce,
                                       const HF_IdlTypeText &       i_typeLinkWriter ) const
{
    const client &
        rOwner = Env().Data().Find_Ce(i_ce.Owner());

    int nIx = int(i_ce.ClassId() - C_nNamesArrayOffset);
    csv_assert(csv::in_range(0,nIx,C_nNumberOfIdlTypes));

    o_destination << C_sTypeNames[nIx]
                  << "in ";
    if (nIx != C_nIxField)
    {
        o_destination << C_sOwnerNames[nIx];
    }
    else
    {
        uintt nOwnerIx = rOwner.ClassId() - C_nNamesArrayOffset;
        csv_assert(
            nOwnerIx < static_cast< unsigned int >(C_nNumberOfIdlTypes));
        o_destination << C_sTypeNames[nOwnerIx];
    }
    i_typeLinkWriter.Produce_IndexOwnerLink(o_destination, rOwner);
}

void
HF_IdlGlobalIndex::write_EntrySecondTime( Xml::Element &                o_destination,
                                          const ary::idl::CodeEntity &  i_ce,
                                          const HF_IdlTypeText &        i_typeLinkWriter ) const
{
    int nIx = int(i_ce.ClassId() - C_nNamesArrayOffset);
    csv_assert(csv::in_range(0,nIx,C_nNumberOfIdlTypes));

    o_destination << C_sTypeNames[nIx]
                  << " ";
    i_typeLinkWriter.Produce_IndexSecondEntryLink(o_destination, i_ce);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "core/rendering/svg/SVGPathData.h"

#include "SVGNames.h"
#include "core/svg/SVGCircleElement.h"
#include "core/svg/SVGEllipseElement.h"
#include "core/svg/SVGLineElement.h"
#include "core/svg/SVGPathElement.h"
#include "core/svg/SVGPathUtilities.h"
#include "core/svg/SVGPolygonElement.h"
#include "core/svg/SVGPolylineElement.h"
#include "core/svg/SVGRectElement.h"
#include "platform/graphics/Path.h"
#include "wtf/HashMap.h"

namespace WebCore {

static void updatePathFromCircleElement(SVGElement* element, Path& path)
{
    SVGCircleElement* circle = toSVGCircleElement(element);

    SVGLengthContext lengthContext(element);
    float r = circle->r()->currentValue()->value(lengthContext);
    if (r > 0)
        path.addEllipse(FloatRect(circle->cx()->currentValue()->value(lengthContext) - r, circle->cy()->currentValue()->value(lengthContext) - r, r * 2, r * 2));
}

static void updatePathFromEllipseElement(SVGElement* element, Path& path)
{
    SVGEllipseElement* ellipse = toSVGEllipseElement(element);

    SVGLengthContext lengthContext(element);
    float rx = ellipse->rx()->currentValue()->value(lengthContext);
    if (rx <= 0)
        return;
    float ry = ellipse->ry()->currentValue()->value(lengthContext);
    if (ry <= 0)
        return;
    path.addEllipse(FloatRect(ellipse->cx()->currentValue()->value(lengthContext) - rx, ellipse->cy()->currentValue()->value(lengthContext) - ry, rx * 2, ry * 2));
}

static void updatePathFromLineElement(SVGElement* element, Path& path)
{
    SVGLineElement* line = toSVGLineElement(element);

    SVGLengthContext lengthContext(element);
    path.moveTo(FloatPoint(line->x1()->currentValue()->value(lengthContext), line->y1()->currentValue()->value(lengthContext)));
    path.addLineTo(FloatPoint(line->x2()->currentValue()->value(lengthContext), line->y2()->currentValue()->value(lengthContext)));
}

static void updatePathFromPathElement(SVGElement* element, Path& path)
{
    buildPathFromByteStream(toSVGPathElement(element)->pathByteStream(), path);
}

static void updatePathFromPolygonElement(SVGElement* element, Path& path)
{
    SVGPointList& points = toSVGPolygonElement(element)->pointsCurrentValue();
    if (points.isEmpty())
        return;

    path.moveTo(points.first());

    unsigned size = points.size();
    for (unsigned i = 1; i < size; ++i)
        path.addLineTo(points.at(i));

    path.closeSubpath();
}

static void updatePathFromPolylineElement(SVGElement* element, Path& path)
{
    SVGPointList& points = toSVGPolylineElement(element)->pointsCurrentValue();
    if (points.isEmpty())
        return;

    path.moveTo(points.first());

    unsigned size = points.size();
    for (unsigned i = 1; i < size; ++i)
        path.addLineTo(points.at(i));
}

static void updatePathFromRectElement(SVGElement* element, Path& path)
{
    SVGRectElement* rect = toSVGRectElement(element);

    SVGLengthContext lengthContext(element);
    float width = rect->width()->currentValue()->value(lengthContext);
    if (width <= 0)
        return;
    float height = rect->height()->currentValue()->value(lengthContext);
    if (height <= 0)
        return;
    float x = rect->x()->currentValue()->value(lengthContext);
    float y = rect->y()->currentValue()->value(lengthContext);
    bool hasRx = rect->rx()->currentValue()->value(lengthContext) > 0;
    bool hasRy = rect->ry()->currentValue()->value(lengthContext) > 0;
    if (hasRx || hasRy) {
        float rx = rect->rx()->currentValue()->value(lengthContext);
        float ry = rect->ry()->currentValue()->value(lengthContext);
        if (!hasRx)
            rx = ry;
        else if (!hasRy)
            ry = rx;

        path.addRoundedRect(FloatRect(x, y, width, height), FloatSize(rx, ry));
        return;
    }

    path.addRect(FloatRect(x, y, width, height));
}

void updatePathFromGraphicsElement(SVGElement* element, Path& path)
{
    ASSERT(element);
    ASSERT(path.isEmpty());

    typedef void (*PathUpdateFunction)(SVGElement*, Path&);
    static HashMap<StringImpl*, PathUpdateFunction>* map = 0;
    if (!map) {
        map = new HashMap<StringImpl*, PathUpdateFunction>;
        map->set(SVGNames::circleTag.localName().impl(), updatePathFromCircleElement);
        map->set(SVGNames::ellipseTag.localName().impl(), updatePathFromEllipseElement);
        map->set(SVGNames::lineTag.localName().impl(), updatePathFromLineElement);
        map->set(SVGNames::pathTag.localName().impl(), updatePathFromPathElement);
        map->set(SVGNames::polygonTag.localName().impl(), updatePathFromPolygonElement);
        map->set(SVGNames::polylineTag.localName().impl(), updatePathFromPolylineElement);
        map->set(SVGNames::rectTag.localName().impl(), updatePathFromRectElement);
    }

    if (PathUpdateFunction pathUpdateFunction = map->get(element->localName().impl()))
        (*pathUpdateFunction)(element, path);
}

} // namespace WebCore
<commit_msg>Refactor calculation of hasRx and hasRy values in SVGPathData<commit_after>/*
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "core/rendering/svg/SVGPathData.h"

#include "SVGNames.h"
#include "core/svg/SVGCircleElement.h"
#include "core/svg/SVGEllipseElement.h"
#include "core/svg/SVGLineElement.h"
#include "core/svg/SVGPathElement.h"
#include "core/svg/SVGPathUtilities.h"
#include "core/svg/SVGPolygonElement.h"
#include "core/svg/SVGPolylineElement.h"
#include "core/svg/SVGRectElement.h"
#include "platform/graphics/Path.h"
#include "wtf/HashMap.h"

namespace WebCore {

static void updatePathFromCircleElement(SVGElement* element, Path& path)
{
    SVGCircleElement* circle = toSVGCircleElement(element);

    SVGLengthContext lengthContext(element);
    float r = circle->r()->currentValue()->value(lengthContext);
    if (r > 0)
        path.addEllipse(FloatRect(circle->cx()->currentValue()->value(lengthContext) - r, circle->cy()->currentValue()->value(lengthContext) - r, r * 2, r * 2));
}

static void updatePathFromEllipseElement(SVGElement* element, Path& path)
{
    SVGEllipseElement* ellipse = toSVGEllipseElement(element);

    SVGLengthContext lengthContext(element);
    float rx = ellipse->rx()->currentValue()->value(lengthContext);
    if (rx <= 0)
        return;
    float ry = ellipse->ry()->currentValue()->value(lengthContext);
    if (ry <= 0)
        return;
    path.addEllipse(FloatRect(ellipse->cx()->currentValue()->value(lengthContext) - rx, ellipse->cy()->currentValue()->value(lengthContext) - ry, rx * 2, ry * 2));
}

static void updatePathFromLineElement(SVGElement* element, Path& path)
{
    SVGLineElement* line = toSVGLineElement(element);

    SVGLengthContext lengthContext(element);
    path.moveTo(FloatPoint(line->x1()->currentValue()->value(lengthContext), line->y1()->currentValue()->value(lengthContext)));
    path.addLineTo(FloatPoint(line->x2()->currentValue()->value(lengthContext), line->y2()->currentValue()->value(lengthContext)));
}

static void updatePathFromPathElement(SVGElement* element, Path& path)
{
    buildPathFromByteStream(toSVGPathElement(element)->pathByteStream(), path);
}

static void updatePathFromPolygonElement(SVGElement* element, Path& path)
{
    SVGPointList& points = toSVGPolygonElement(element)->pointsCurrentValue();
    if (points.isEmpty())
        return;

    path.moveTo(points.first());

    unsigned size = points.size();
    for (unsigned i = 1; i < size; ++i)
        path.addLineTo(points.at(i));

    path.closeSubpath();
}

static void updatePathFromPolylineElement(SVGElement* element, Path& path)
{
    SVGPointList& points = toSVGPolylineElement(element)->pointsCurrentValue();
    if (points.isEmpty())
        return;

    path.moveTo(points.first());

    unsigned size = points.size();
    for (unsigned i = 1; i < size; ++i)
        path.addLineTo(points.at(i));
}

static void updatePathFromRectElement(SVGElement* element, Path& path)
{
    SVGRectElement* rect = toSVGRectElement(element);

    SVGLengthContext lengthContext(element);
    float width = rect->width()->currentValue()->value(lengthContext);
    if (width <= 0)
        return;
    float height = rect->height()->currentValue()->value(lengthContext);
    if (height <= 0)
        return;
    float x = rect->x()->currentValue()->value(lengthContext);
    float y = rect->y()->currentValue()->value(lengthContext);
    float rx = rect->rx()->currentValue()->value(lengthContext);
    float ry = rect->ry()->currentValue()->value(lengthContext);
    bool hasRx = rx > 0;
    bool hasRy = ry > 0;
    if (hasRx || hasRy) {
        if (!hasRx)
            rx = ry;
        else if (!hasRy)
            ry = rx;

        path.addRoundedRect(FloatRect(x, y, width, height), FloatSize(rx, ry));
        return;
    }

    path.addRect(FloatRect(x, y, width, height));
}

void updatePathFromGraphicsElement(SVGElement* element, Path& path)
{
    ASSERT(element);
    ASSERT(path.isEmpty());

    typedef void (*PathUpdateFunction)(SVGElement*, Path&);
    static HashMap<StringImpl*, PathUpdateFunction>* map = 0;
    if (!map) {
        map = new HashMap<StringImpl*, PathUpdateFunction>;
        map->set(SVGNames::circleTag.localName().impl(), updatePathFromCircleElement);
        map->set(SVGNames::ellipseTag.localName().impl(), updatePathFromEllipseElement);
        map->set(SVGNames::lineTag.localName().impl(), updatePathFromLineElement);
        map->set(SVGNames::pathTag.localName().impl(), updatePathFromPathElement);
        map->set(SVGNames::polygonTag.localName().impl(), updatePathFromPolygonElement);
        map->set(SVGNames::polylineTag.localName().impl(), updatePathFromPolylineElement);
        map->set(SVGNames::rectTag.localName().impl(), updatePathFromRectElement);
    }

    if (PathUpdateFunction pathUpdateFunction = map->get(element->localName().impl()))
        (*pathUpdateFunction)(element, path);
}

} // namespace WebCore
<|endoftext|>


<commit_before>#include "auto/ShootCommand.h"

#include "subsystems/Shooter.h"
#include "subsystems/Intake.h"
#include "util/PidTuner.h"

ShootCommand::ShootCommand(Shooter* shooter, Intake* intake, bool runIntake,
		                   double shootSpeed, int shotsToFire, double timeout, bool intakeDown) {
  SetTimeout(timeout);
  shooter_ = shooter;
  intake_ = intake;
  runIntake_ = runIntake;
  shootSpeed_ = shootSpeed;
  shotSpotterTimer_ = new Timer();
  shotsToFire_ = shotsToFire;
  reachedSpeed_ = false;
  shotsFired_ = 0;
  downCycles_ = 0;
  atSpeedCycles_ = 0;
  intakeDown_ = intakeDown;
}

void ShootCommand::Initialize() {
   shooter_->Reset();
   shooter_->SetTargetVelocity(shootSpeed_);
   AutoCommand::Initialize();
   if (intakeDown_) {
   	  intake_->SetIntakePosition(Intake::INTAKE_DOWN);
   	  ///reachedSpeed_ = true;
   }
}

bool ShootCommand::Run() {
  //intake_->SetIntakePosition(Intake::INTAKE_DOWN);
  shooter_->SetTargetVelocity(shootSpeed_);

  if (timer_->Get() > 2.2 && intakeDown_) {
	  intake_->SetIntakePosition(Intake::INTAKE_FLOATING);
	  intakeDown_ = false;
  }

  bool atSpeed = shooter_->AtTargetVelocity();
  bool goBack = false;

  if (atSpeed) {
    if (atSpeedCycles_++ > 5)
      reachedSpeed_ = true;
    downCycles_ = 0;
  } else {
    atSpeedCycles_ = 0;
    if(shooter_->GetVelocity() < shootSpeed_ - 4  && reachedSpeed_) {
      if (downCycles_++ > 5) {
        downCycles_ = 0;
        shotsFired_++;
        goBack = true;
        reachedSpeed_ = false; // Stop running the conveyor
        intakeDown_ = false;
        if(shotsFired_ >= shotsToFire_) {
          shotSpotterTimer_->Start();
        }
      }
    }
  }

  if (reachedSpeed_) {
    shooter_->SetLinearConveyorPower(1);
    if (runIntake_) {
      intake_->SetIntakePower(1);
    } else {
       intake_->SetIntakePower(0);
    }
  }
  else if (goBack) {
	  shooter_->SetLinearConveyorPower(-1);
	  intake_->SetIntakePower(0);
  } else if (intakeDown_) {
	  shooter_->SetLinearConveyorPower(1);
	  intake_->SetIntakePower(1);
  } else {
    shooter_->SetLinearConveyorPower(0);
    intake_->SetIntakePower(0);
  }

  bool done = TimeoutExpired() || (shotsFired_ >= shotsToFire_ &&
		  shotSpotterTimer_->Get() > .25);
  if (done) {
    //shooter_->SetTargetVelocity(0);
    shooter_->SetLinearConveyorPower(0.0);
    intake_->SetIntakePower(0);
  }
  return done;
}

ShootCommand::~ShootCommand()  {
  printf("destrcutor for shoot command\n");
}

<commit_msg>Modification to ShootCommand<commit_after>#include "auto/ShootCommand.h"

#include "subsystems/Shooter.h"
#include "subsystems/Intake.h"
#include "util/PidTuner.h"

ShootCommand::ShootCommand(Shooter* shooter, Intake* intake, bool runIntake,
		                   double shootSpeed, int shotsToFire, double timeout, bool intakeDown) {
  SetTimeout(timeout);
  shooter_ = shooter;
  intake_ = intake;
  runIntake_ = runIntake;
  shootSpeed_ = shootSpeed;
  shotSpotterTimer_ = new Timer();
  shotsToFire_ = shotsToFire;
  reachedSpeed_ = false;
  shotsFired_ = 0;
  downCycles_ = 0;
  atSpeedCycles_ = 0;
  intakeDown_ = intakeDown;
}

void ShootCommand::Initialize() {
   shooter_->Reset();
   shooter_->SetTargetVelocity(shootSpeed_);
   AutoCommand::Initialize();
   if (intakeDown_) {
   	  intake_->SetIntakePosition(Intake::INTAKE_DOWN);
   	  ///reachedSpeed_ = true;
   }
}

bool ShootCommand::Run() {
  //intake_->SetIntakePosition(Intake::INTAKE_DOWN);
  shooter_->SetTargetVelocity(shootSpeed_);

  if (timer_->Get() > 2.2 && intakeDown_) {
	  intake_->SetIntakePosition(Intake::INTAKE_FLOATING);
  }
  if (timer_->Get() > 3.5 && intakeDown_)
	  intakeDown_ = false;

  bool atSpeed = shooter_->AtTargetVelocity();
  bool goBack = false;

  if (atSpeed) {
    if (atSpeedCycles_++ > 5)
      reachedSpeed_ = true;
    downCycles_ = 0;
  } else {
    atSpeedCycles_ = 0;
    if(shooter_->GetVelocity() < shootSpeed_ - 4  && reachedSpeed_) {
      if (downCycles_++ > 5) {
        downCycles_ = 0;
        shotsFired_++;
        goBack = true;
        reachedSpeed_ = false; // Stop running the conveyor
        intakeDown_ = false;
        if(shotsFired_ >= shotsToFire_) {
          shotSpotterTimer_->Start();
        }
      }
    }
  }

  if (reachedSpeed_) {
    shooter_->SetLinearConveyorPower(1);
    if (runIntake_) {
      intake_->SetIntakePower(1);
    } else {
       intake_->SetIntakePower(0);
    }
  }
  else if (goBack) {
	  shooter_->SetLinearConveyorPower(-1);
	  intake_->SetIntakePower(0);
  } else if (intakeDown_) {
	  shooter_->SetLinearConveyorPower(1);
	  intake_->SetIntakePower(1);
  } else {
    shooter_->SetLinearConveyorPower(0);
    intake_->SetIntakePower(0);
  }

  bool done = TimeoutExpired() || (shotsFired_ >= shotsToFire_ &&
		  shotSpotterTimer_->Get() > .25);
  if (done) {
    //shooter_->SetTargetVelocity(0);
    shooter_->SetLinearConveyorPower(0.0);
    intake_->SetIntakePower(0);
  }
  return done;
}

ShootCommand::~ShootCommand()  {
  printf("destrcutor for shoot command\n");
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: shelljob.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ihi $ $Date: 2007-07-11 15:01:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_JOBS_SHELLJOB_HXX_
#define __FRAMEWORK_JOBS_SHELLJOB_HXX_

//_______________________________________________
// my own includes

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif

//_______________________________________________
// other includes

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

//_______________________________________________
// uno includes

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_
#include <com/sun/star/task/XJob.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <com/sun/star/frame/XModuleManager.hpp>
#endif

//_______________________________________________
// namespace

namespace framework{

//_______________________________________________
// declarations

//_______________________________________________
/** @short  implements a job component which can be used
            to execute system shell commands.

    @descr  Because the job will be implemented generic
            it can be bound to any event where jobs can be
            registered for. Further there is a generic
            way to configure the shell command and it's list
            of arguments.

    @author as96863
 */
class ShellJob : public css::lang::XTypeProvider
               , public css::lang::XServiceInfo
               , public css::task::XJob
               , private ThreadHelpBase
               , public ::cppu::OWeakObject
{
    //-------------------------------------------
    // member
    private:

        //.......................................
        /** @short  reference to an uno service manager. */
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;

    //-------------------------------------------
    // native interface
    public:

        //---------------------------------------
        /** @short  create new instance of this class.

            @param  xSMGR
                    reference to the uno service manager, which created this instance.
                    Can be used later to create own needed uno resources on demand.
         */
        ShellJob(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);

        //---------------------------------------
        /** @short  does nothing real ...

            @descr  But it should exists as virtual function,
                    so this class cant make trouble
                    related to inline/symbols etcpp.!
         */
        virtual ~ShellJob();

    //-------------------------------------------
    // uno interface
    public:

        //---------------------------------------
        // css.uno.XInterface
        // css.lang.XTypeProvider
        // css.lang.XServiceInfo
        FWK_DECLARE_XINTERFACE
        FWK_DECLARE_XTYPEPROVIDER
        DECLARE_XSERVICEINFO

        // css.task.XJob
        virtual css::uno::Any SAL_CALL execute(const css::uno::Sequence< css::beans::NamedValue >& lArguments)
            throw(css::lang::IllegalArgumentException,
                  css::uno::Exception                ,
                  css::uno::RuntimeException         );

    //-------------------------------------------
    // helper
    private:

        //---------------------------------------
        /** generate a return value for method execute()
            which will force deactivation of this job for further requests.

            @return an Any following the job protocol for deactivation.
         */
        static css::uno::Any impl_generateAnswer4Deactivation();

        //---------------------------------------
        /** substitute all might existing placeholder variables
            within the configured command.

            The command is part of the job configuration.
            These will make changes more easy (no code changes required).
            Further the command can use placeholder as they are supported
            by the global substitution service (e.g. $(prog) etcpp)

            @param  sCommand
                    the command containing placeholder variables.

            @return the substituted command.
         */
        ::rtl::OUString impl_substituteCommandVariables(const ::rtl::OUString& sCommand);

        //---------------------------------------
        /** converts the configured command to a system path.

            Because the used service XSystemShellExecute supports
            URLs and system pathes ... but the office works on
            URLs only ... we have to make those conversion
            explicit. This will be triggered by another configuration entry
            named "NeedsSystemPathConversion".

            @param  sURL
                    the command URL for conversion.

            @return the command as system path ... or an empty string on errors.
         */
        ::rtl::OUString impl_convertCommandURL2SystemPath(const ::rtl::OUString& sURL);

        //---------------------------------------
        /** executes the command.

            @param  sCommand
                    the absolute command as URL or system path (without any argument !).

            @param  sArguments
                    the complete list of arguments formated as one string.

            @return TRUE if command was executed successfully; FALSE otherwise.
         */
        ::sal_Bool impl_execute(const ::rtl::OUString& sCommand  ,
                                const ::rtl::OUString& sArguments);
};

} // namespace framework

#endif // __FRAMEWORK_JOBS_SHELLJOB_HXX_
<commit_msg>INTEGRATION: CWS fwk84_SRC680 (1.2.92); FILE MERGED 2008/01/29 07:29:53 as 1.2.92.2: #153305# osl_executeProcess supports file URLs only 2008/01/25 15:27:09 as 1.2.92.1: #153305, 153306# use osl_executeProcess instead of SystemShellExecute<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: shelljob.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2008-02-12 17:24:53 $
 *
 *  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_JOBS_SHELLJOB_HXX_
#define __FRAMEWORK_JOBS_SHELLJOB_HXX_

//_______________________________________________
// my own includes

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif

//_______________________________________________
// other includes

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

//_______________________________________________
// uno includes

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_
#include <com/sun/star/task/XJob.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <com/sun/star/frame/XModuleManager.hpp>
#endif

//_______________________________________________
// namespace

namespace framework{

//_______________________________________________
// declarations

//_______________________________________________
/** @short  implements a job component which can be used
            to execute system shell commands.

    @descr  Because the job will be implemented generic
            it can be bound to any event where jobs can be
            registered for. Further there is a generic
            way to configure the shell command and it's list
            of arguments.

    @author as96863
 */
class ShellJob : public css::lang::XTypeProvider
               , public css::lang::XServiceInfo
               , public css::task::XJob
               , private ThreadHelpBase
               , public ::cppu::OWeakObject
{
    //-------------------------------------------
    // member
    private:

        //.......................................
        /** @short  reference to an uno service manager. */
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;

    //-------------------------------------------
    // native interface
    public:

        //---------------------------------------
        /** @short  create new instance of this class.

            @param  xSMGR
                    reference to the uno service manager, which created this instance.
                    Can be used later to create own needed uno resources on demand.
         */
        ShellJob(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);

        //---------------------------------------
        /** @short  does nothing real ...

            @descr  But it should exists as virtual function,
                    so this class cant make trouble
                    related to inline/symbols etcpp.!
         */
        virtual ~ShellJob();

    //-------------------------------------------
    // uno interface
    public:

        //---------------------------------------
        // css.uno.XInterface
        // css.lang.XTypeProvider
        // css.lang.XServiceInfo
        FWK_DECLARE_XINTERFACE
        FWK_DECLARE_XTYPEPROVIDER
        DECLARE_XSERVICEINFO

        // css.task.XJob
        virtual css::uno::Any SAL_CALL execute(const css::uno::Sequence< css::beans::NamedValue >& lArguments)
            throw(css::lang::IllegalArgumentException,
                  css::uno::Exception                ,
                  css::uno::RuntimeException         );

    //-------------------------------------------
    // helper
    private:

        //---------------------------------------
        /** generate a return value for method execute()
            which will force deactivation of this job for further requests.

            @return an Any following the job protocol for deactivation.
         */
        static css::uno::Any impl_generateAnswer4Deactivation();

        //---------------------------------------
        /** substitute all might existing placeholder variables
            within the configured command.

            The command is part of the job configuration.
            These will make changes more easy (no code changes required).
            Further the command can use placeholder as they are supported
            by the global substitution service (e.g. $(prog) etcpp)

            @param  sCommand
                    the command containing placeholder variables.

            @return the substituted command.
         */
        ::rtl::OUString impl_substituteCommandVariables(const ::rtl::OUString& sCommand);

        //---------------------------------------
        /** executes the command.

            @param  sCommand
                    the absolute command as URL or system path (without any argument !).

            @param  lArguments
                    the complete list of arguments configured for these job.

            @param  bCheckExitCode
                    bind the execution result to the exit code of the started process.
                    If it's set to false we return false only in case executable couldnt be found
                    or couldnt be started.

            @return TRUE if command was executed successfully; FALSE otherwise.
         */
        ::sal_Bool impl_execute(const ::rtl::OUString&                       sCommand      ,
                                const css::uno::Sequence< ::rtl::OUString >& lArguments    ,
                                      ::sal_Bool                             bCheckExitCode);
};

} // namespace framework

#endif // __FRAMEWORK_JOBS_SHELLJOB_HXX_
<|endoftext|>


<commit_before>/*
 * SelectDescriptors.cpp
 *
 *  Created on: Nov 7, 2013
 *      Author: andresf
 */

#include <ctime>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <vector>

#include <DynamicMat.hpp>
#include <FileUtils.hpp>
#include <FunctionUtils.hpp>

#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/flann/random.h>

static const size_t DESC_CHUNK = 4000;

int main(int argc, char **argv) {

	if (argc != 4) {
		printf(
				"\nUsage:\n"
						"\tSelectDescriptors <in.descriptors.folder> <in.percentage> <out.sampled.descriptors.folder>\n\n");
		return EXIT_FAILURE;
	}

	std::string in_descs_folder = argv[1];
	double in_percentage = atof(argv[2]);
	std::string out_folder = argv[3];

	if (in_percentage <= 0.0 || in_percentage >= 100.0) {
		fprintf(stderr,
				"<in.percentage> must be a number between 0 and 100 excluding limits\n");
		return EXIT_FAILURE;
	} else {
		in_percentage = in_percentage / 100.0;
	}

	// Step 1: read descriptors list
	printf("-- Reading files in folder [%s]\n", in_descs_folder.c_str());
	std::vector<std::string> descriptorsFilenames;
	FileUtils::readFolder(in_descs_folder.c_str(), descriptorsFilenames);
	printf("   Done, got [%lu] entries\n", descriptorsFilenames.size());

	for (std::string& descriptors : descriptorsFilenames) {
		descriptors = in_descs_folder + "/" + descriptors;
	}

	// Step 2: read descriptors files
	printf("-- Reading descriptors files\n");

	vlr::Mat mergedDescriptors(descriptorsFilenames);

	// Step 3: randomly select a percentage of the descriptors

	printf("-- Selecting randomly [%f] of descriptors, hence [%d] of [%d]\n",
			in_percentage, int(mergedDescriptors.rows * in_percentage),
			mergedDescriptors.rows);

	cvflann::seed_random(unsigned(std::time(0)));
	cvflann::UniqueRandom randGen(mergedDescriptors.rows);

	std::vector<int> indices(int(mergedDescriptors.rows * in_percentage));
	for (unsigned int i = 0; i < indices.size(); ++i) {
		indices[i] = randGen.next();
	}

	// Sort the array of indices
	std::sort(indices.begin(), indices.end());

	// Step 4: iterate over the loaded descriptors and save to files in chunks
	printf("-- Accessing chosen descriptor and saving them into [%s]\n",
			out_folder.c_str());

	cv::Mat imgDescriptors = cv::Mat::zeros(DESC_CHUNK, mergedDescriptors.cols,
			mergedDescriptors.type());

	for (size_t i = 0; i < indices.size(); ++i) {

		// If it is a starting descriptor or the last one then save
		if (i > 0 && ((i % DESC_CHUNK) == 0 || i + 1 == indices.size())) {
			// Prepare filename
			char buffer[50];

			sprintf(buffer, "descriptors_%04d.bin",
					int(
							floor(i / DESC_CHUNK)
									+ ((i % DESC_CHUNK == 0) ? 0 : 1)));

			printf("   %02d/%02d %s\n",
					int(
							floor(i / DESC_CHUNK)
									+ ((i % DESC_CHUNK == 0) ? 0 : 1)),
					int(
							floor((indices.size() - 1) / DESC_CHUNK)
									+ (((indices.size() - 1) % DESC_CHUNK == 0) ?
											0 : 1)), buffer);

			CV_Assert(imgDescriptors.rows == (int )DESC_CHUNK);

			// Save features
			FileUtils::saveDescriptors(out_folder + "/" + std::string(buffer),
					imgDescriptors);

			// Clean descriptors matrix and key-points vector
			imgDescriptors.release();
			imgDescriptors = cv::Mat::zeros(DESC_CHUNK, mergedDescriptors.cols,
					mergedDescriptors.type());
		}

		cv::Mat submat = imgDescriptors.rowRange(i % DESC_CHUNK,
				(i % DESC_CHUNK) + 1);
		mergedDescriptors.row(indices[i]).copyTo(submat);

	}

}
<commit_msg>Fixed bug, validating correctly the percentage of descriptors to select.<commit_after>/*
 * SelectDescriptors.cpp
 *
 *  Created on: Nov 7, 2013
 *      Author: andresf
 */

#include <ctime>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <vector>

#include <DynamicMat.hpp>
#include <FileUtils.hpp>
#include <FunctionUtils.hpp>

#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/flann/random.h>

static const size_t DESC_CHUNK = 4000;

int main(int argc, char **argv) {

	if (argc != 4) {
		printf(
				"\nUsage:\n"
						"\tSelectDescriptors <in.descriptors.folder> <in.percentage> <out.sampled.descriptors.folder>\n\n");
		return EXIT_FAILURE;
	}

	std::string in_descs_folder = argv[1];
	double in_percentage = atof(argv[2]);
	std::string out_folder = argv[3];

	if (in_percentage <= 0.0 || in_percentage > 100.0) {
		fprintf(stderr,
				"<in.percentage> must be a number in the range (0, 100]\n");
		return EXIT_FAILURE;
	} else {
		in_percentage = in_percentage / 100.0;
	}

	// Step 1: read descriptors list
	printf("-- Reading files in folder [%s]\n", in_descs_folder.c_str());
	std::vector<std::string> descriptorsFilenames;
	FileUtils::readFolder(in_descs_folder.c_str(), descriptorsFilenames);
	printf("   Done, got [%lu] entries\n", descriptorsFilenames.size());

	for (std::string& descriptors : descriptorsFilenames) {
		descriptors = in_descs_folder + "/" + descriptors;
	}

	// Step 2: read descriptors files
	printf("-- Reading descriptors files\n");

	vlr::Mat mergedDescriptors(descriptorsFilenames);

	// Step 3: randomly select a percentage of the descriptors

	printf("-- Selecting randomly [%f] of descriptors, hence [%d] of [%d]\n",
			in_percentage, int(mergedDescriptors.rows * in_percentage),
			mergedDescriptors.rows);

	cvflann::seed_random(unsigned(std::time(0)));
	cvflann::UniqueRandom randGen(mergedDescriptors.rows);

	std::vector<int> indices(int(mergedDescriptors.rows * in_percentage));
	for (unsigned int i = 0; i < indices.size(); ++i) {
		indices[i] = randGen.next();
	}

	// Sort the array of indices
	std::sort(indices.begin(), indices.end());

	// Step 4: iterate over the loaded descriptors and save to files in chunks
	printf("-- Accessing chosen descriptor and saving them into [%s]\n",
			out_folder.c_str());

	cv::Mat imgDescriptors = cv::Mat::zeros(DESC_CHUNK, mergedDescriptors.cols,
			mergedDescriptors.type());

	for (size_t i = 0; i < indices.size(); ++i) {

		// If it is a starting descriptor or the last one then save
		if (i > 0 && ((i % DESC_CHUNK) == 0 || i + 1 == indices.size())) {
			// Prepare filename
			char buffer[50];

			sprintf(buffer, "descriptors_%04d.bin",
					int(
							floor(i / DESC_CHUNK)
									+ ((i % DESC_CHUNK == 0) ? 0 : 1)));

			printf("   %02d/%02d %s\n",
					int(
							floor(i / DESC_CHUNK)
									+ ((i % DESC_CHUNK == 0) ? 0 : 1)),
					int(
							floor((indices.size() - 1) / DESC_CHUNK)
									+ (((indices.size() - 1) % DESC_CHUNK == 0) ?
											0 : 1)), buffer);

			CV_Assert(imgDescriptors.rows == (int )DESC_CHUNK);

			// Save features
			FileUtils::saveDescriptors(out_folder + "/" + std::string(buffer),
					imgDescriptors);

			// Clean descriptors matrix and key-points vector
			imgDescriptors.release();
			imgDescriptors = cv::Mat::zeros(DESC_CHUNK, mergedDescriptors.cols,
					mergedDescriptors.type());
		}

		cv::Mat submat = imgDescriptors.rowRange(i % DESC_CHUNK,
				(i % DESC_CHUNK) + 1);
		mergedDescriptors.row(indices[i]).copyTo(submat);

	}

}
<|endoftext|>