<commit_before>#include <tuple>
#include <type_traits>
#include <utility>
#include <nek/utility/pointer_traits.hpp>
#include <gtest/gtest.h>

namespace
{
  template <class T>
  class complete_smart_pointer_mock
  {
  private:
    T* ptr_ = nullptr;

  public:
    using element_type = T;
    using difference_type = char;

    complete_smart_pointer_mock() = default;

    explicit complete_smart_pointer_mock(T& p)
      : ptr_(&p)
    {
    }

    template <class U>
    struct rebind
    {
      using other = complete_smart_pointer_mock<U>;
    };

    static complete_smart_pointer_mock pointer_to(T& p)
    {
      return complete_smart_pointer_mock(p);
    }

    friend bool operator==(complete_smart_pointer_mock const& l, complete_smart_pointer_mock const& r)
    {
      return l.ptr_ == r.ptr_;
    }
  };

  template <class T>
  class simple_smart_pointer_mock
  {
  private:
    T* ptr_ = nullptr;

  public:
    simple_smart_pointer_mock() = default;

    simple_smart_pointer_mock(T* p)
      : ptr_(p)
    {
    }

    friend bool operator==(simple_smart_pointer_mock const& l, simple_smart_pointer_mock const& r)
    {
      return l.ptr_ == r.ptr_;
    }
  };
}

template <class T>
class pointer_traits_test
  : public ::testing::Test
{
protected:
  using ptr_t = typename std::tuple_element<0, T>::type;
  using elem_t = typename std::tuple_element<1, T>::type;
  using diff_t = typename std::tuple_element<2, T>::type;
  using pointer_t = typename std::tuple_element<3, T>::type;
};

TYPED_TEST_CASE_P(pointer_traits_test);

TYPED_TEST_P(pointer_traits_test, element_type)
{
  using actual_t = typename nek::pointer_traits<ptr_t>::element_type;
  static_assert(std::is_same<actual_t, elem_t>::value, "");
}

TYPED_TEST_P(pointer_traits_test, difference_type)
{
  using actual_t = typename nek::pointer_traits<ptr_t>::difference_type;
  static_assert(std::is_same<actual_t, diff_t>::value, "");
}

TYPED_TEST_P(pointer_traits_test, pointer)
{
  using actual_t = typename nek::pointer_traits<ptr_t>::pointer;
  static_assert(std::is_same<actual_t, pointer_t>::value, "");
}

TYPED_TEST_P(pointer_traits_test, rebind)
{
  using actual_t = typename nek::pointer_traits<ptr_t>::template rebind<double>::other;
  using expect_t = typename std::tuple_element<4, TypeParam>::type;
  static_assert(std::is_same<actual_t, expect_t>::value, "");
}

TEST(pointer_to_test, raw_type)
{
  int val = 0;
  EXPECT_EQ(&val, nek::pointer_traits<int*>::pointer_to(val));
}

TEST(pointer_to_test, complete_smart_ptr)
{
  int val = 0;
  EXPECT_EQ(complete_smart_pointer_mock<int>(val), nek::pointer_traits<complete_smart_pointer_mock<int>>::pointer_to(val));
}

TEST(pointer_to_test, simple_smart_pointer)
{
  // when smart pointer does not provide a static member function pointer_to,
  // instantiation of this function must be a compile-time error.
  //int val = 0;
  //EXPECT_EQ(simple_smart_pointer_mock<int>(&val), nek::pointer_traits<simple_smart_pointer_mock<int>>::pointer_to(val));
}

REGISTER_TYPED_TEST_CASE_P(
  pointer_traits_test,
  element_type,
  difference_type,
  pointer,
  rebind);

using types = ::testing::Types<
  //        <pointer_type,                     element_type, difference_type, pointer,                          rebind<double>::other,
  std::tuple<int*,                             int,          std::ptrdiff_t,  int*,                             double*>,
  std::tuple<complete_smart_pointer_mock<int>, int,          char,            complete_smart_pointer_mock<int>, complete_smart_pointer_mock<double>>,
  std::tuple<simple_smart_pointer_mock<int>,   int,          std::ptrdiff_t,  simple_smart_pointer_mock<int>,   simple_smart_pointer_mock<double>>
>;

INSTANTIATE_TYPED_TEST_CASE_P(parameterized, pointer_traits_test, types);<commit_msg>fix comment<commit_after>#include <tuple>
#include <type_traits>
#include <utility>
#include <nek/utility/pointer_traits.hpp>
#include <gtest/gtest.h>

namespace
{
  template <class T>
  class complete_smart_pointer_mock
  {
  private:
    T* ptr_ = nullptr;

  public:
    using element_type = T;
    using difference_type = char;

    complete_smart_pointer_mock() = default;

    explicit complete_smart_pointer_mock(T& p)
      : ptr_(&p)
    {
    }

    template <class U>
    struct rebind
    {
      using other = complete_smart_pointer_mock<U>;
    };

    static complete_smart_pointer_mock pointer_to(T& p)
    {
      return complete_smart_pointer_mock(p);
    }

    friend bool operator==(complete_smart_pointer_mock const& l, complete_smart_pointer_mock const& r)
    {
      return l.ptr_ == r.ptr_;
    }
  };

  template <class T>
  class simple_smart_pointer_mock
  {
  private:
    T* ptr_ = nullptr;

  public:
    simple_smart_pointer_mock() = default;

    simple_smart_pointer_mock(T* p)
      : ptr_(p)
    {
    }

    friend bool operator==(simple_smart_pointer_mock const& l, simple_smart_pointer_mock const& r)
    {
      return l.ptr_ == r.ptr_;
    }
  };
}

template <class T>
class pointer_traits_test
  : public ::testing::Test
{
protected:
  using ptr_t = typename std::tuple_element<0, T>::type;
  using elem_t = typename std::tuple_element<1, T>::type;
  using diff_t = typename std::tuple_element<2, T>::type;
  using pointer_t = typename std::tuple_element<3, T>::type;
};

TYPED_TEST_CASE_P(pointer_traits_test);

TYPED_TEST_P(pointer_traits_test, element_type)
{
  using actual_t = typename nek::pointer_traits<ptr_t>::element_type;
  static_assert(std::is_same<actual_t, elem_t>::value, "");
}

TYPED_TEST_P(pointer_traits_test, difference_type)
{
  using actual_t = typename nek::pointer_traits<ptr_t>::difference_type;
  static_assert(std::is_same<actual_t, diff_t>::value, "");
}

TYPED_TEST_P(pointer_traits_test, pointer)
{
  using actual_t = typename nek::pointer_traits<ptr_t>::pointer;
  static_assert(std::is_same<actual_t, pointer_t>::value, "");
}

TYPED_TEST_P(pointer_traits_test, rebind)
{
  using actual_t = typename nek::pointer_traits<ptr_t>::template rebind<double>::other;
  using expect_t = typename std::tuple_element<4, TypeParam>::type;
  static_assert(std::is_same<actual_t, expect_t>::value, "");
}

TEST(pointer_to_test, raw_type)
{
  int val = 0;
  EXPECT_EQ(&val, nek::pointer_traits<int*>::pointer_to(val));
}

TEST(pointer_to_test, complete_smart_ptr)
{
  int val = 0;
  EXPECT_EQ(complete_smart_pointer_mock<int>(val), nek::pointer_traits<complete_smart_pointer_mock<int>>::pointer_to(val));
}

TEST(pointer_to_test, simple_smart_pointer)
{
  // if smart pointer does not provide a static member function pointer_to,
  // instantiation of this test must be a compile time error.
  //int val = 0;
  //EXPECT_EQ(simple_smart_pointer_mock<int>(&val), nek::pointer_traits<simple_smart_pointer_mock<int>>::pointer_to(val));
}

REGISTER_TYPED_TEST_CASE_P(
  pointer_traits_test,
  element_type,
  difference_type,
  pointer,
  rebind);

using types = ::testing::Types<
  //        <pointer_type,                     element_type, difference_type, pointer,                          rebind<double>::other,
  std::tuple<int*,                             int,          std::ptrdiff_t,  int*,                             double*>,
  std::tuple<complete_smart_pointer_mock<int>, int,          char,            complete_smart_pointer_mock<int>, complete_smart_pointer_mock<double>>,
  std::tuple<simple_smart_pointer_mock<int>,   int,          std::ptrdiff_t,  simple_smart_pointer_mock<int>,   simple_smart_pointer_mock<double>>
>;

INSTANTIATE_TYPED_TEST_CASE_P(parameterized, pointer_traits_test, types);<|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 "gpu/gpu_plugin/gpu_plugin.h"
#include "webkit/glue/plugins/nphostapi.h"

namespace gpu_plugin {

// Definitions of NPAPI plugin entry points.

namespace {

NPError NPP_New(NPMIMEType plugin_type, NPP instance,
                uint16 mode, int16 argc, char* argn[],
                char* argv[], NPSavedData* saved) {
  if (!instance)
    return NPERR_INVALID_INSTANCE_ERROR;

  return NPERR_NO_ERROR;
}

NPError NPP_Destroy(NPP instance, NPSavedData** saved) {
  if (!instance)
    return NPERR_INVALID_INSTANCE_ERROR;

  return NPERR_NO_ERROR;
}

NPError NPP_SetWindow(NPP instance, NPWindow* window) {
  return NPERR_NO_ERROR;
}

int16 NPP_HandleEvent(NPP instance, void* event) {
  return 0;
}

NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) {
  if (!instance)
    return NPERR_INVALID_INSTANCE_ERROR;
  switch (variable) {
    case NPPVpluginNeedsXEmbed:
      *static_cast<NPBool *>(value) = 1;
      return NPERR_NO_ERROR;
    default:
      return NPERR_INVALID_PARAM;
  }
}

NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) {
  return NPERR_NO_ERROR;
}
}

NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* funcs) {
  funcs->newp = NPP_New;
  funcs->destroy = NPP_Destroy;
  funcs->setwindow = NPP_SetWindow;
  funcs->event = NPP_HandleEvent;
  funcs->getvalue = NPP_GetValue;
  funcs->setvalue = NPP_SetValue;
  return NPERR_NO_ERROR;
}

#if defined(OS_LINUX)
NPError API_CALL NP_Initialize(NPNetscapeFuncs *browser_funcs,
                               NPPluginFuncs* plugin_funcs) {
#else
NPError API_CALL NP_Initialize(NPNetscapeFuncs *browser_funcs) {
#endif
  if (!browser_funcs)
    return NPERR_INVALID_FUNCTABLE_ERROR;

#if defined(OS_LINUX)
  NP_GetEntryPoints(plugin_funcs);
#endif

  return NPERR_NO_ERROR;
}

NPError API_CALL NP_Shutdown() {
  return NPERR_NO_ERROR;
}
}  // namespace gpu_plugin
<commit_msg>Dummy whitespace change to force a build.<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 "gpu/gpu_plugin/gpu_plugin.h"
#include "webkit/glue/plugins/nphostapi.h"

namespace gpu_plugin {

// Definitions of NPAPI plugin entry points.

namespace {

NPError NPP_New(NPMIMEType plugin_type, NPP instance,
                uint16 mode, int16 argc, char* argn[],
                char* argv[], NPSavedData* saved) {
  if (!instance)
    return NPERR_INVALID_INSTANCE_ERROR;

  return NPERR_NO_ERROR;
}

NPError NPP_Destroy(NPP instance, NPSavedData** saved) {
  if (!instance)
    return NPERR_INVALID_INSTANCE_ERROR;

  return NPERR_NO_ERROR;
}

NPError NPP_SetWindow(NPP instance, NPWindow* window) {
  return NPERR_NO_ERROR;
}

int16 NPP_HandleEvent(NPP instance, void* event) {
  return 0;
}

NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) {
  if (!instance)
    return NPERR_INVALID_INSTANCE_ERROR;
  switch (variable) {
    case NPPVpluginNeedsXEmbed:
      *static_cast<NPBool *>(value) = 1;
      return NPERR_NO_ERROR;
    default:
      return NPERR_INVALID_PARAM;
  }
}

NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) {
  return NPERR_NO_ERROR;
}

}  // namespace

NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* funcs) {
  funcs->newp = NPP_New;
  funcs->destroy = NPP_Destroy;
  funcs->setwindow = NPP_SetWindow;
  funcs->event = NPP_HandleEvent;
  funcs->getvalue = NPP_GetValue;
  funcs->setvalue = NPP_SetValue;
  return NPERR_NO_ERROR;
}

#if defined(OS_LINUX)
NPError API_CALL NP_Initialize(NPNetscapeFuncs *browser_funcs,
                               NPPluginFuncs* plugin_funcs) {
#else
NPError API_CALL NP_Initialize(NPNetscapeFuncs *browser_funcs) {
#endif
  if (!browser_funcs)
    return NPERR_INVALID_FUNCTABLE_ERROR;

#if defined(OS_LINUX)
  NP_GetEntryPoints(plugin_funcs);
#endif

  return NPERR_NO_ERROR;
}

NPError API_CALL NP_Shutdown() {
  return NPERR_NO_ERROR;
}
}  // namespace gpu_plugin
<|endoftext|>


<commit_before>#include "BlinkSignal.h"

BlinkSignal::BlinkSignal(uint8_t pin, unsigned long pulseWidth) {
    this->pin = pin;
    this->lowPulseWidth = pulseWidth;
    this->highPulseWidth = pulseWidth;
    pinMode(pin, OUTPUT);
}

void BlinkSignal::invertOutput(bool invert) {
    this->invert = invert;
}

void BlinkSignal::setOffPulseWidth(unsigned long pulseWidth) {
    this->lowPulseWidth = pulseWidth;
}

void BlinkSignal::setOnPulseCount(uint8_t count) {
    this->highPulseCount = count * 2 - 1;
    this->highPulseWidth = lowPulseWidth / highPulseCount ;
    this->countDown = this->highPulseCount;
}

void BlinkSignal::update(unsigned long millis) {
    if (millis >= nextMillis) {
    	    if (countDown > 0) {
    	    	    countDown--;
    	    	    nextMillis = millis + highPulseWidth;
    	    } else {
    	    	    countDown = highPulseCount;
		    nextMillis = millis + lowPulseWidth;
    	    }
    	    currentState = currentState == HIGH ? LOW : HIGH;
    	    illuminate();
    }
}

void BlinkSignal::illuminate() {
    // invert, since LED cathode is connected to GPIO pin
    uint8_t value = invert ? (currentState == HIGH ? LOW : HIGH): currentState;
    digitalWrite(pin, value);
}
<commit_msg>Fix the damn tabs!<commit_after>#include "BlinkSignal.h"

BlinkSignal::BlinkSignal(uint8_t pin, unsigned long pulseWidth) {
    this->pin = pin;
    this->lowPulseWidth = pulseWidth;
    this->highPulseWidth = pulseWidth;
    pinMode(pin, OUTPUT);
}

void BlinkSignal::invertOutput(bool invert) {
    this->invert = invert;
}

void BlinkSignal::setOffPulseWidth(unsigned long pulseWidth) {
    this->lowPulseWidth = pulseWidth;
}

void BlinkSignal::setOnPulseCount(uint8_t count) {
    this->highPulseCount = count * 2 - 1;
    this->highPulseWidth = lowPulseWidth / highPulseCount ;
    this->countDown = this->highPulseCount;
}

void BlinkSignal::update(unsigned long millis) {
    if (millis >= nextMillis) {
        if (countDown > 0) {
            countDown--;
            nextMillis = millis + highPulseWidth;
        } else {
            countDown = highPulseCount;
            nextMillis = millis + lowPulseWidth;
        }
        currentState = currentState == HIGH ? LOW : HIGH;
        illuminate();
    }
}

void BlinkSignal::illuminate() {
    // invert, since LED cathode is connected to GPIO pin
    uint8_t value = invert ? (currentState == HIGH ? LOW : HIGH): currentState;
    digitalWrite(pin, value);
}
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIOgreRenderer.cpp
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUIOgreRenderer.h"
#include "CEGUIOgreGeometryBuffer.h"
#include "CEGUIOgreTextureTarget.h"
#include "CEGUIOgreTexture.h"
#include "CEGUIOgreWindowTarget.h"
#include "CEGUIRenderingRoot.h"
#include "CEGUIExceptions.h"
#include "CEGUISystem.h"
#include "CEGUIOgreResourceProvider.h"
#include "CEGUIOgreImageCodec.h"

#include <OgreRoot.h>
#include <OgreRenderSystem.h>
#include <OgreRenderWindow.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
// Internal Ogre::FrameListener based class.  This is how we noew hook into the
// rendering process (as opposed to render queues previously)
static class OgreGUIFrameListener : public Ogre::FrameListener
{
public:
    OgreGUIFrameListener();

    void setCEGUIRenderEnabled(bool enabled);
    bool isCEGUIRenderEnabled() const;

    bool frameRenderingQueued(const Ogre::FrameEvent& evt);

private:
    bool d_enabled;

} S_frameListener;

//----------------------------------------------------------------------------//
String OgreRenderer::d_rendererID(
"CEGUI::OgreRenderer - Official OGRE based 2nd generation renderer module.");

//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::bootstrapSystem()
{
    if (System::getSingletonPtr())
        throw InvalidRequestException("OgreRenderer::bootstrapSystem: "
            "CEGUI::System object is already initialised.");

    OgreRenderer& renderer = create();
    OgreResourceProvider& rp = createOgreResourceProvider();
    OgreImageCodec& ic = createOgreImageCodec();
    System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic);

    return renderer;
}

//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::bootstrapSystem(Ogre::RenderTarget& target)
{
    if (System::getSingletonPtr())
        throw InvalidRequestException("OgreRenderer::bootstrapSystem: "
            "CEGUI::System object is already initialised.");

    OgreRenderer& renderer = OgreRenderer::create(target);
    OgreResourceProvider& rp = createOgreResourceProvider();
    OgreImageCodec& ic = createOgreImageCodec();
    System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic);

    return renderer;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroySystem()
{
    System* sys;
    if (!(sys = System::getSingletonPtr()))
        throw InvalidRequestException("OgreRenderer::destroySystem: "
            "CEGUI::System object is not created or was already destroyed.");

    OgreRenderer* renderer = static_cast<OgreRenderer*>(sys->getRenderer());
    OgreResourceProvider* rp =
        static_cast<OgreResourceProvider*>(sys->getResourceProvider());

    OgreImageCodec* ic = &static_cast<OgreImageCodec&>(sys->getImageCodec());

    System::destroy();
    destroyOgreImageCodec(*ic);
    destroyOgreResourceProvider(*rp);
    destroy(*renderer);
}

//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::create()
{
    return *new OgreRenderer;
}

//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::create(Ogre::RenderTarget& target)
{
    return *new OgreRenderer(target);
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroy(OgreRenderer& renderer)
{
    delete &renderer;
}

//----------------------------------------------------------------------------//
OgreResourceProvider& OgreRenderer::createOgreResourceProvider()
{
    return *new OgreResourceProvider;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyOgreResourceProvider(OgreResourceProvider& rp)
{
    delete &rp;
}

//----------------------------------------------------------------------------//
OgreImageCodec& OgreRenderer::createOgreImageCodec()
{
    return *new OgreImageCodec;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyOgreImageCodec(OgreImageCodec& ic)
{
    delete
}

//----------------------------------------------------------------------------//
void OgreRenderer::setRenderingEnabled(const bool enabled)
{
    S_frameListener.setCEGUIRenderEnabled(enabled);
}

//----------------------------------------------------------------------------//
bool OgreRenderer::isRenderingEnabled() const
{
    return S_frameListener.isCEGUIRenderEnabled();
}

//----------------------------------------------------------------------------//
RenderingRoot& OgreRenderer::getDefaultRenderingRoot()
{
    return *d_defaultRoot;
}

//----------------------------------------------------------------------------//
GeometryBuffer& OgreRenderer::createGeometryBuffer()
{
    OgreGeometryBuffer* gb =
        new OgreGeometryBuffer(*d_renderSystem);

    d_geometryBuffers.push_back(gb);
    return *gb;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer)
{
    GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(),
                                               d_geometryBuffers.end(),
                                               &buffer);

    if (d_geometryBuffers.end() != i)
    {
        d_geometryBuffers.erase(i);
        delete &buffer;
    }
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllGeometryBuffers()
{
    while (!d_geometryBuffers.empty())
        destroyGeometryBuffer(**d_geometryBuffers.begin());
}

//----------------------------------------------------------------------------//
TextureTarget* OgreRenderer::createTextureTarget()
{
    TextureTarget* tt = new OgreTextureTarget(*this, *d_renderSystem);
    d_textureTargets.push_back(tt);
    return tt;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyTextureTarget(TextureTarget* target)
{
    TextureTargetList::iterator i = std::find(d_textureTargets.begin(),
                                              d_textureTargets.end(),
                                              target);

    if (d_textureTargets.end() != i)
    {
        d_textureTargets.erase(i);
        delete target;
    }
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllTextureTargets()
{
    while (!d_textureTargets.empty())
        destroyTextureTarget(*d_textureTargets.begin());
}

//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture()
{
    OgreTexture* t = new OgreTexture;
    d_textures.push_back(t);
    return *t;
}

//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(const String& filename,
                                     const String& resourceGroup)
{
    OgreTexture* t = new OgreTexture(filename, resourceGroup);
    d_textures.push_back(t);
    return *t;
}

//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(const Size& size)
{
    OgreTexture* t = new OgreTexture(size);
    d_textures.push_back(t);
    return *t;
}

//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(Ogre::TexturePtr& tex, bool take_ownership)
{
    OgreTexture* t = new OgreTexture(tex, take_ownership);
    d_textures.push_back(t);
    return *t;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyTexture(Texture& texture)
{
    TextureList::iterator i = std::find(d_textures.begin(),
                                        d_textures.end(),
                                        &texture);

    if (d_textures.end() != i)
    {
        d_textures.erase(i);
        delete &static_cast<OgreTexture&>(texture);
    }
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllTextures()
{
    while (!d_textures.empty())
        destroyTexture(**d_textures.begin());
}

//----------------------------------------------------------------------------//
void OgreRenderer::beginRendering()
{
    using namespace Ogre;

    // initialise render settings
    d_renderSystem->setLightingEnabled(false);
    d_renderSystem->_setDepthBufferParams(false, false);
    d_renderSystem->_setDepthBias(0, 0);
    d_renderSystem->_setCullingMode(CULL_NONE);
    d_renderSystem->_setFog(FOG_NONE);
    d_renderSystem->_setColourBufferWriteEnabled(true, true, true, true);
    d_renderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
    d_renderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM);
    d_renderSystem->setShadingType(SO_GOURAUD);
    d_renderSystem->_setPolygonMode(PM_SOLID);

    // enable alpha blending
    d_renderSystem->_setSceneBlending(SBF_SOURCE_ALPHA,
                                      SBF_ONE_MINUS_SOURCE_ALPHA);

    d_renderSystem->_beginFrame();
}

//----------------------------------------------------------------------------//
void OgreRenderer::endRendering()
{
    d_renderSystem->_endFrame();
}

//----------------------------------------------------------------------------//
const Size& OgreRenderer::getDisplaySize() const
{
    return d_displaySize;
}

//----------------------------------------------------------------------------//
const Vector2& OgreRenderer::getDisplayDPI() const
{
    return d_displayDPI;
}

//----------------------------------------------------------------------------//
uint OgreRenderer::getMaxTextureSize() const
{
    return d_maxTextureSize;
}

//----------------------------------------------------------------------------//
const String& OgreRenderer::getIdentifierString() const
{
    return d_rendererID;
}

//----------------------------------------------------------------------------//
OgreRenderer::OgreRenderer() :
    d_displayDPI(96, 96),
    // TODO: should be set to correct value
    d_maxTextureSize(2048),
    d_ogreRoot(Ogre::Root::getSingletonPtr())
{
    checkOgreInitialised();

    // get auto created window
    Ogre::RenderWindow* rwnd = d_ogreRoot->getAutoCreatedWindow();
    if (!rwnd)
        throw RendererException("Ogre was not initialised to automatically "
                                "create a window, you should therefore be "
                                "explicitly specifying a Ogre::RenderTarget in "
                                "the OgreRenderer::create function.");

    constructor_impl(*rwnd);
}

//----------------------------------------------------------------------------//
OgreRenderer::OgreRenderer(Ogre::RenderTarget& target) :
    d_displayDPI(96, 96),
    // TODO: should be set to correct value
    d_maxTextureSize(2048),
    d_ogreRoot(Ogre::Root::getSingletonPtr())
{
    checkOgreInitialised();

    constructor_impl(target);
}

//----------------------------------------------------------------------------//
OgreRenderer::~OgreRenderer()
{
    d_ogreRoot->removeFrameListener(&S_frameListener);

    destroyAllGeometryBuffers();
    destroyAllTextureTargets();
    destroyAllTextures();

    delete d_defaultRoot;
    delete d_defaultTarget;
}

//----------------------------------------------------------------------------//
void OgreRenderer::checkOgreInitialised()
{
    if (!d_ogreRoot)
        throw RendererException("The Ogre::Root object has not been created. "
                                "You must initialise Ogre first!");

    if (!d_ogreRoot->isInitialised())
        throw RendererException("Ogre has not been initialised. You must "
                                "initialise Ogre first!");
}

//----------------------------------------------------------------------------//
void OgreRenderer::constructor_impl(Ogre::RenderTarget& target)
{
    d_renderSystem = d_ogreRoot->getRenderSystem();

    d_displaySize.d_width  = target.getWidth();
    d_displaySize.d_height = target.getHeight();

    // create default target & rendering root (surface) that uses it
    d_defaultTarget = new OgreWindowTarget(*this, *d_renderSystem, target);
    d_defaultRoot = new RenderingRoot(*d_defaultTarget);

    // hook into the rendering process
    d_ogreRoot->addFrameListener(&S_frameListener);
}

//----------------------------------------------------------------------------//
void OgreRenderer::setDisplaySize(const Size& sz)
{
    if (sz != d_displaySize)
    {
        d_displaySize = sz;

        // FIXME: This is probably not the right thing to do in all cases.
        Rect area(d_defaultTarget->getArea());
        area.setSize(sz);
        d_defaultTarget->setArea(area);
    }

}

//----------------------------------------------------------------------------//
OgreGUIFrameListener::OgreGUIFrameListener() :
    d_enabled(true)
{
}

//----------------------------------------------------------------------------//
void OgreGUIFrameListener::setCEGUIRenderEnabled(bool enabled)
{
    d_enabled = enabled;
}

//----------------------------------------------------------------------------//
bool OgreGUIFrameListener::isCEGUIRenderEnabled() const
{
    return d_enabled;
}

//----------------------------------------------------------------------------//
bool OgreGUIFrameListener::frameRenderingQueued(const Ogre::FrameEvent&)
{
    if (d_enabled)
        System::getSingleton().renderGUI();

    return true;
}

} // End of  CEGUI namespace section
<commit_msg>FIX: Alpha blend issue for the Ogre renderer.<commit_after>/***********************************************************************
    filename:   CEGUIOgreRenderer.cpp
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUIOgreRenderer.h"
#include "CEGUIOgreGeometryBuffer.h"
#include "CEGUIOgreTextureTarget.h"
#include "CEGUIOgreTexture.h"
#include "CEGUIOgreWindowTarget.h"
#include "CEGUIRenderingRoot.h"
#include "CEGUIExceptions.h"
#include "CEGUISystem.h"
#include "CEGUIOgreResourceProvider.h"
#include "CEGUIOgreImageCodec.h"

#include <OgreRoot.h>
#include <OgreRenderSystem.h>
#include <OgreRenderWindow.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
// Internal Ogre::FrameListener based class.  This is how we noew hook into the
// rendering process (as opposed to render queues previously)
static class OgreGUIFrameListener : public Ogre::FrameListener
{
public:
    OgreGUIFrameListener();

    void setCEGUIRenderEnabled(bool enabled);
    bool isCEGUIRenderEnabled() const;

    bool frameRenderingQueued(const Ogre::FrameEvent& evt);

private:
    bool d_enabled;

} S_frameListener;

//----------------------------------------------------------------------------//
String OgreRenderer::d_rendererID(
"CEGUI::OgreRenderer - Official OGRE based 2nd generation renderer module.");

//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::bootstrapSystem()
{
    if (System::getSingletonPtr())
        throw InvalidRequestException("OgreRenderer::bootstrapSystem: "
            "CEGUI::System object is already initialised.");

    OgreRenderer& renderer = create();
    OgreResourceProvider& rp = createOgreResourceProvider();
    OgreImageCodec& ic = createOgreImageCodec();
    System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic);

    return renderer;
}

//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::bootstrapSystem(Ogre::RenderTarget& target)
{
    if (System::getSingletonPtr())
        throw InvalidRequestException("OgreRenderer::bootstrapSystem: "
            "CEGUI::System object is already initialised.");

    OgreRenderer& renderer = OgreRenderer::create(target);
    OgreResourceProvider& rp = createOgreResourceProvider();
    OgreImageCodec& ic = createOgreImageCodec();
    System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic);

    return renderer;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroySystem()
{
    System* sys;
    if (!(sys = System::getSingletonPtr()))
        throw InvalidRequestException("OgreRenderer::destroySystem: "
            "CEGUI::System object is not created or was already destroyed.");

    OgreRenderer* renderer = static_cast<OgreRenderer*>(sys->getRenderer());
    OgreResourceProvider* rp =
        static_cast<OgreResourceProvider*>(sys->getResourceProvider());

    OgreImageCodec* ic = &static_cast<OgreImageCodec&>(sys->getImageCodec());

    System::destroy();
    destroyOgreImageCodec(*ic);
    destroyOgreResourceProvider(*rp);
    destroy(*renderer);
}

//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::create()
{
    return *new OgreRenderer;
}

//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::create(Ogre::RenderTarget& target)
{
    return *new OgreRenderer(target);
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroy(OgreRenderer& renderer)
{
    delete &renderer;
}

//----------------------------------------------------------------------------//
OgreResourceProvider& OgreRenderer::createOgreResourceProvider()
{
    return *new OgreResourceProvider;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyOgreResourceProvider(OgreResourceProvider& rp)
{
    delete &rp;
}

//----------------------------------------------------------------------------//
OgreImageCodec& OgreRenderer::createOgreImageCodec()
{
    return *new OgreImageCodec;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyOgreImageCodec(OgreImageCodec& ic)
{
    delete
}

//----------------------------------------------------------------------------//
void OgreRenderer::setRenderingEnabled(const bool enabled)
{
    S_frameListener.setCEGUIRenderEnabled(enabled);
}

//----------------------------------------------------------------------------//
bool OgreRenderer::isRenderingEnabled() const
{
    return S_frameListener.isCEGUIRenderEnabled();
}

//----------------------------------------------------------------------------//
RenderingRoot& OgreRenderer::getDefaultRenderingRoot()
{
    return *d_defaultRoot;
}

//----------------------------------------------------------------------------//
GeometryBuffer& OgreRenderer::createGeometryBuffer()
{
    OgreGeometryBuffer* gb =
        new OgreGeometryBuffer(*d_renderSystem);

    d_geometryBuffers.push_back(gb);
    return *gb;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer)
{
    GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(),
                                               d_geometryBuffers.end(),
                                               &buffer);

    if (d_geometryBuffers.end() != i)
    {
        d_geometryBuffers.erase(i);
        delete &buffer;
    }
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllGeometryBuffers()
{
    while (!d_geometryBuffers.empty())
        destroyGeometryBuffer(**d_geometryBuffers.begin());
}

//----------------------------------------------------------------------------//
TextureTarget* OgreRenderer::createTextureTarget()
{
    TextureTarget* tt = new OgreTextureTarget(*this, *d_renderSystem);
    d_textureTargets.push_back(tt);
    return tt;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyTextureTarget(TextureTarget* target)
{
    TextureTargetList::iterator i = std::find(d_textureTargets.begin(),
                                              d_textureTargets.end(),
                                              target);

    if (d_textureTargets.end() != i)
    {
        d_textureTargets.erase(i);
        delete target;
    }
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllTextureTargets()
{
    while (!d_textureTargets.empty())
        destroyTextureTarget(*d_textureTargets.begin());
}

//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture()
{
    OgreTexture* t = new OgreTexture;
    d_textures.push_back(t);
    return *t;
}

//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(const String& filename,
                                     const String& resourceGroup)
{
    OgreTexture* t = new OgreTexture(filename, resourceGroup);
    d_textures.push_back(t);
    return *t;
}

//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(const Size& size)
{
    OgreTexture* t = new OgreTexture(size);
    d_textures.push_back(t);
    return *t;
}

//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(Ogre::TexturePtr& tex, bool take_ownership)
{
    OgreTexture* t = new OgreTexture(tex, take_ownership);
    d_textures.push_back(t);
    return *t;
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyTexture(Texture& texture)
{
    TextureList::iterator i = std::find(d_textures.begin(),
                                        d_textures.end(),
                                        &texture);

    if (d_textures.end() != i)
    {
        d_textures.erase(i);
        delete &static_cast<OgreTexture&>(texture);
    }
}

//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllTextures()
{
    while (!d_textures.empty())
        destroyTexture(**d_textures.begin());
}

//----------------------------------------------------------------------------//
void OgreRenderer::beginRendering()
{
    using namespace Ogre;

    // initialise render settings
    d_renderSystem->setLightingEnabled(false);
    d_renderSystem->_setDepthBufferParams(false, false);
    d_renderSystem->_setDepthBias(0, 0);
    d_renderSystem->_setCullingMode(CULL_NONE);
    d_renderSystem->_setFog(FOG_NONE);
    d_renderSystem->_setColourBufferWriteEnabled(true, true, true, true);
    d_renderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
    d_renderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM);
    d_renderSystem->setShadingType(SO_GOURAUD);
    d_renderSystem->_setPolygonMode(PM_SOLID);

    // enable alpha blending
    d_renderSystem->_setSeparateSceneBlending(SBF_SOURCE_ALPHA,
                                              SBF_ONE_MINUS_SOURCE_ALPHA,
                                              SBF_SOURCE_ALPHA,
                                              SBF_ONE);

    d_renderSystem->_beginFrame();
}

//----------------------------------------------------------------------------//
void OgreRenderer::endRendering()
{
    d_renderSystem->_endFrame();
}

//----------------------------------------------------------------------------//
const Size& OgreRenderer::getDisplaySize() const
{
    return d_displaySize;
}

//----------------------------------------------------------------------------//
const Vector2& OgreRenderer::getDisplayDPI() const
{
    return d_displayDPI;
}

//----------------------------------------------------------------------------//
uint OgreRenderer::getMaxTextureSize() const
{
    return d_maxTextureSize;
}

//----------------------------------------------------------------------------//
const String& OgreRenderer::getIdentifierString() const
{
    return d_rendererID;
}

//----------------------------------------------------------------------------//
OgreRenderer::OgreRenderer() :
    d_displayDPI(96, 96),
    // TODO: should be set to correct value
    d_maxTextureSize(2048),
    d_ogreRoot(Ogre::Root::getSingletonPtr())
{
    checkOgreInitialised();

    // get auto created window
    Ogre::RenderWindow* rwnd = d_ogreRoot->getAutoCreatedWindow();
    if (!rwnd)
        throw RendererException("Ogre was not initialised to automatically "
                                "create a window, you should therefore be "
                                "explicitly specifying a Ogre::RenderTarget in "
                                "the OgreRenderer::create function.");

    constructor_impl(*rwnd);
}

//----------------------------------------------------------------------------//
OgreRenderer::OgreRenderer(Ogre::RenderTarget& target) :
    d_displayDPI(96, 96),
    // TODO: should be set to correct value
    d_maxTextureSize(2048),
    d_ogreRoot(Ogre::Root::getSingletonPtr())
{
    checkOgreInitialised();

    constructor_impl(target);
}

//----------------------------------------------------------------------------//
OgreRenderer::~OgreRenderer()
{
    d_ogreRoot->removeFrameListener(&S_frameListener);

    destroyAllGeometryBuffers();
    destroyAllTextureTargets();
    destroyAllTextures();

    delete d_defaultRoot;
    delete d_defaultTarget;
}

//----------------------------------------------------------------------------//
void OgreRenderer::checkOgreInitialised()
{
    if (!d_ogreRoot)
        throw RendererException("The Ogre::Root object has not been created. "
                                "You must initialise Ogre first!");

    if (!d_ogreRoot->isInitialised())
        throw RendererException("Ogre has not been initialised. You must "
                                "initialise Ogre first!");
}

//----------------------------------------------------------------------------//
void OgreRenderer::constructor_impl(Ogre::RenderTarget& target)
{
    d_renderSystem = d_ogreRoot->getRenderSystem();

    d_displaySize.d_width  = target.getWidth();
    d_displaySize.d_height = target.getHeight();

    // create default target & rendering root (surface) that uses it
    d_defaultTarget = new OgreWindowTarget(*this, *d_renderSystem, target);
    d_defaultRoot = new RenderingRoot(*d_defaultTarget);

    // hook into the rendering process
    d_ogreRoot->addFrameListener(&S_frameListener);
}

//----------------------------------------------------------------------------//
void OgreRenderer::setDisplaySize(const Size& sz)
{
    if (sz != d_displaySize)
    {
        d_displaySize = sz;

        // FIXME: This is probably not the right thing to do in all cases.
        Rect area(d_defaultTarget->getArea());
        area.setSize(sz);
        d_defaultTarget->setArea(area);
    }

}

//----------------------------------------------------------------------------//
OgreGUIFrameListener::OgreGUIFrameListener() :
    d_enabled(true)
{
}

//----------------------------------------------------------------------------//
void OgreGUIFrameListener::setCEGUIRenderEnabled(bool enabled)
{
    d_enabled = enabled;
}

//----------------------------------------------------------------------------//
bool OgreGUIFrameListener::isCEGUIRenderEnabled() const
{
    return d_enabled;
}

//----------------------------------------------------------------------------//
bool OgreGUIFrameListener::frameRenderingQueued(const Ogre::FrameEvent&)
{
    if (d_enabled)
        System::getSingleton().renderGUI();

    return true;
}

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/gview_request_interceptor.h"

#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_redirect_job.h"
#include "googleurl/src/gurl.h"

namespace chromeos {

// This is the list of mime types currently supported by the Google
// Document Viewer.
static const char* const supported_mime_type_list[] = {
  "application/pdf",
  "application/vnd.ms-powerpoint"
};

static const char* const kGViewUrlPrefix = "http://docs.google.com/gview?url=";

GViewRequestInterceptor::GViewRequestInterceptor() {
  URLRequest::RegisterRequestInterceptor(this);
  for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) {
    supported_mime_types_.insert(supported_mime_type_list[i]);
  }
}

GViewRequestInterceptor::~GViewRequestInterceptor() {
  URLRequest::UnregisterRequestInterceptor(this);
}

URLRequestJob* GViewRequestInterceptor::MaybeIntercept(URLRequest* request) {
  // Don't attempt to intercept here as we want to wait until the mime
  // type is fully determined.
  return NULL;
}

URLRequestJob* GViewRequestInterceptor::MaybeInterceptResponse(
    URLRequest* request) {
  // Do not intercept this request if it is a download.
  if (request->load_flags() & net::LOAD_IS_DOWNLOAD) {
    return NULL;
  }

  std::string mime_type;
  request->GetMimeType(&mime_type);
  // If supported, build the URL to the Google Document Viewer
  // including the origial document's URL, then create a new job that
  // will redirect the browser to this new URL.
  if (supported_mime_types_.count(mime_type) > 0) {
    std::string url(kGViewUrlPrefix);
    url += EscapePath(request->url().spec());
    return new URLRequestRedirectJob(request, GURL(url));
  }
  return NULL;
}

URLRequest::Interceptor* GViewRequestInterceptor::GetGViewRequestInterceptor() {
  return Singleton<GViewRequestInterceptor>::get();
}

}  // namespace chromeos
<commit_msg>ChromeOS PDF handling: if the built-in PDF viewer plug-in is active, don't intercept PDF opening and forward to gView, but use the plug-in instead.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/gview_request_interceptor.h"

#include "base/file_path.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_redirect_job.h"
#include "googleurl/src/gurl.h"
#include "webkit/glue/plugins/plugin_list.h"

namespace chromeos {

// The PDF mime type is treated special if the browser has a built-in
// PDF viewer plug-in installed - we want to intercept only if we're
// told to.
static const char* const kPdfMimeType = "application/pdf";

// This is the list of mime types currently supported by the Google
// Document Viewer.
static const char* const supported_mime_type_list[] = {
  kPdfMimeType,
  "application/vnd.ms-powerpoint"
};

static const char* const kGViewUrlPrefix = "http://docs.google.com/gview?url=";

GViewRequestInterceptor::GViewRequestInterceptor() {
  URLRequest::RegisterRequestInterceptor(this);
  for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) {
    supported_mime_types_.insert(supported_mime_type_list[i]);
  }
}

GViewRequestInterceptor::~GViewRequestInterceptor() {
  URLRequest::UnregisterRequestInterceptor(this);
}

URLRequestJob* GViewRequestInterceptor::MaybeIntercept(URLRequest* request) {
  // Don't attempt to intercept here as we want to wait until the mime
  // type is fully determined.
  return NULL;
}

URLRequestJob* GViewRequestInterceptor::MaybeInterceptResponse(
    URLRequest* request) {
  // Do not intercept this request if it is a download.
  if (request->load_flags() & net::LOAD_IS_DOWNLOAD) {
    return NULL;
  }

  std::string mime_type;
  request->GetMimeType(&mime_type);
  // If the local PDF viewing plug-in is installed and enabled, don't
  // redirect PDF files to Google Document Viewer.
  if (mime_type == kPdfMimeType) {
    FilePath pdf_path;
    WebPluginInfo info;
    PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path);
    if (NPAPI::PluginList::Singleton()->GetPluginInfoByPath(pdf_path, &info) &&
        info.enabled)
      return NULL;
  }
  // If supported, build the URL to the Google Document Viewer
  // including the origial document's URL, then create a new job that
  // will redirect the browser to this new URL.
  if (supported_mime_types_.count(mime_type) > 0) {
    std::string url(kGViewUrlPrefix);
    url += EscapePath(request->url().spec());
    return new URLRequestRedirectJob(request, GURL(url));
  }
  return NULL;
}

URLRequest::Interceptor* GViewRequestInterceptor::GetGViewRequestInterceptor() {
  return Singleton<GViewRequestInterceptor>::get();
}

}  // namespace chromeos
<|endoftext|>


<commit_before>#include <iostream>
#include "kernel.h"
#include "ilwisdata.h"
#include "symboltable.h"
#include "OperationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
#include "commandhandler.h"
#include "text2output.h"

using namespace Ilwis;
using namespace BaseOperations;

Text2Output::Text2Output()
{
}

Text2Output::Text2Output(quint64 metaid, const Ilwis::OperationExpression &expr) :
    OperationImplementation(metaid, expr)
{
}

bool Text2Output::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;
    std::cout << _text.toStdString() << "\n"    ;

    return true;
}

Ilwis::OperationImplementation *Text2Output::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new Text2Output(metaid, expr);
}

Ilwis::OperationImplementation::State Text2Output::prepare(ExecutionContext *ctx, const Ilwis::SymbolTable &)
{
    for(int i=0; i < _expression.parameterCount(); ++i){
        QString str = _expression.parm(i).value();
        if ( str.size() > 0 && str[0] == '"' && str[str.size()-1] == '"'){
            str = str.remove('"');
        }
        _text += str;
    }
    if ( _expression.parameterCount() == 2)     {
        //TODO, file based cases
    }
    return sPREPARED;

}

quint64 Text2Output::createMetadata()
{
    QString url = QString("ilwis://operations/text2output");
    Resource res(QUrl(url), itOPERATIONMETADATA);
    res.addProperty("namespace","ilwis");
    res.addProperty("longname","text2output");
    res.addProperty("syntax","text2output(text,[text]+)");
    res.addProperty("inparameters","1+");
    res.addProperty("pin_1_type", itANY);
    res.addProperty("pin_1_name", TR("input string"));
    res.addProperty("pin_1_desc",TR("input string"));
    res.addProperty("pin_2_type", itANY);
    res.addProperty("pin_2_name", TR("filename or path"));
    res.addProperty("pin_2_desc",TR("optional file were strings will be written; if no path is provided, current working folder will be used"));
    res.addProperty("outparameters",0);
    res.prepare();
    url += "=" + QString::number(res.id());
    res.setUrl(url);

    mastercatalog()->addItems({res});
    return res.id();
}
<commit_msg>removed a case that will not be used anymore<commit_after>#include <iostream>
#include "kernel.h"
#include "ilwisdata.h"
#include "symboltable.h"
#include "OperationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
#include "commandhandler.h"
#include "text2output.h"

using namespace Ilwis;
using namespace BaseOperations;

Text2Output::Text2Output()
{
}

Text2Output::Text2Output(quint64 metaid, const Ilwis::OperationExpression &expr) :
    OperationImplementation(metaid, expr)
{
}

bool Text2Output::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;
    std::cout << _text.toStdString() << "\n"    ;

    return true;
}

Ilwis::OperationImplementation *Text2Output::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new Text2Output(metaid, expr);
}

Ilwis::OperationImplementation::State Text2Output::prepare(ExecutionContext *ctx, const Ilwis::SymbolTable &)
{
    for(int i=0; i < _expression.parameterCount(); ++i){
        QString str = _expression.parm(i).value();
        if ( str.size() > 0 && str[0] == '"' && str[str.size()-1] == '"'){
            str = str.remove('"');
        }
        _text += str;
    }
    return sPREPARED;

}

quint64 Text2Output::createMetadata()
{
    QString url = QString("ilwis://operations/text2output");
    Resource res(QUrl(url), itOPERATIONMETADATA);
    res.addProperty("namespace","ilwis");
    res.addProperty("longname","text2output");
    res.addProperty("syntax","text2output(text,[text]+)");
    res.addProperty("inparameters","1+");
    res.addProperty("pin_1_type", itANY);
    res.addProperty("pin_1_name", TR("input string"));
    res.addProperty("pin_1_desc",TR("input string"));
    res.addProperty("pin_2_type", itANY);
    res.addProperty("pin_2_name", TR("filename or path"));
    res.addProperty("pin_2_desc",TR("optional file were strings will be written; if no path is provided, current working folder will be used"));
    res.addProperty("outparameters",0);
    res.prepare();
    url += "=" + QString::number(res.id());
    res.setUrl(url);

    mastercatalog()->addItems({res});
    return res.id();
}
<|endoftext|>


<commit_before>// @(#)root/eve:$Id$
// Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

/*************************************************************************
 * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TEveMacro.h"

#include "TSystem.h"
#include "TROOT.h"

//______________________________________________________________________________
// TEveMacro
//
// Sub-class of TMacro, overriding Exec to unload the previous verison
// and cleanup after the execution.

ClassImp(TEveMacro)

//______________________________________________________________________________
TEveMacro::TEveMacro() : TMacro()
{
   // Default constructor.
}

TEveMacro::TEveMacro(const TEveMacro& m) : TMacro(m)
{
   // Copy constructor.
}

TEveMacro::TEveMacro(const char* name) :
   TMacro()
{
   // Constructor with file name.

   if (!name) return;

   fTitle = name;

   char *dot   = (char*)strrchr(name, '.');
   char *slash = (char*)strrchr(name, '/');
   if (dot) *dot = 0;
   if (slash) fName = slash + 1;
   else       fName = name;

   ReadFile(fTitle);
}

/******************************************************************************/

#include "TTimer.h"

//______________________________________________________________________________
Long_t TEveMacro::Exec(const char* params, Int_t* error)
{
   // Execute the macro.

   Long_t retval = -1;

   if (gROOT->GetGlobalFunction(fName, 0, kTRUE) != 0)
   {
      gROOT->SetExecutingMacro(kTRUE);
      gROOT->SetExecutingMacro(kFALSE);
      retval = gROOT->ProcessLine(Form("%s()", fName.Data()), error);
   }
   else
   {
      // Copy from TMacro::Exec. Difference is that the file is really placed
      // into the /tmp.
      TString fname = "/tmp/";
      {
         //the current implementation uses a file in the current directory.
         //should be replaced by a direct execution from memory by CINT
         fname += GetName();
         fname += ".C";
         SaveSource(fname);
         //disable a possible call to gROOT->Reset from the executed script
         gROOT->SetExecutingMacro(kTRUE);
         //execute script in /tmp
         TString exec = ".x " + fname;
         TString p = params;
         if (p == "") p = fParams;
         if (p != "")
            exec += "(" + p + ")";
         retval = gROOT->ProcessLine(exec, error);
         //enable gROOT->Reset
         gROOT->SetExecutingMacro(kFALSE);
         //delete the temporary file
         gSystem->Unlink(fname);
      }
   }

   //G__unloadfile(fname);

   // In case an exception was thrown (which i do not know how to detect
   // the execution of next macros does not succeed.
   // However strange this might seem, this solves the problem.
   // TTimer::SingleShot(100, "TEveMacro", this, "ResetRoot()");
   //
   // 27.8.07 - ok, this does not work any more. Seems I'll have to fix
   // this real soon now.
   //
   // !!!! FIX MACRO HANDLING !!!!
   //

   return retval;
}

#include "TApplication.h"

//______________________________________________________________________________
void TEveMacro::ResetRoot()
{
   // Call gROOT->Reset() via interpreter.

   // printf ("TEveMacro::ResetRoot doing 'gROOT->Reset()'.\n");
   gROOT->GetApplication()->ProcessLine("gROOT->Reset()");
}
<commit_msg>Use TPMERegexp to determine macro name instead of strrchr and hacking the input const char array (reported by Benjamin Hess).<commit_after>// @(#)root/eve:$Id$
// Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

/*************************************************************************
 * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TEveMacro.h"

#include "TPRegexp.h"
#include "TSystem.h"
#include "TROOT.h"

//______________________________________________________________________________
//
// Sub-class of TMacro, overriding Exec to unload the previous verison
// and cleanup after the execution.

ClassImp(TEveMacro);

//______________________________________________________________________________
TEveMacro::TEveMacro() : TMacro()
{
   // Default constructor.
}

TEveMacro::TEveMacro(const TEveMacro& m) : TMacro(m)
{
   // Copy constructor.
}

TEveMacro::TEveMacro(const char* name) :
   TMacro()
{
   // Constructor with file name.

   if (!name) return;

   fTitle = name;

   TPMERegexp re("([^/]+?)(?:\\.\\w*)?$");
   Int_t nm = re.Match(fTitle);
   if (nm >= 2) {
      fName = re[1];
   } else {
      fName = "<unknown>";
   }
   ReadFile(fTitle);
}

/******************************************************************************/

#include "TTimer.h"

//______________________________________________________________________________
Long_t TEveMacro::Exec(const char* params, Int_t* error)
{
   // Execute the macro.

   Long_t retval = -1;

   if (gROOT->GetGlobalFunction(fName, 0, kTRUE) != 0)
   {
      gROOT->SetExecutingMacro(kTRUE);
      gROOT->SetExecutingMacro(kFALSE);
      retval = gROOT->ProcessLine(Form("%s()", fName.Data()), error);
   }
   else
   {
      // Copy from TMacro::Exec. Difference is that the file is really placed
      // into the /tmp.
      TString fname = "/tmp/";
      {
         //the current implementation uses a file in the current directory.
         //should be replaced by a direct execution from memory by CINT
         fname += GetName();
         fname += ".C";
         SaveSource(fname);
         //disable a possible call to gROOT->Reset from the executed script
         gROOT->SetExecutingMacro(kTRUE);
         //execute script in /tmp
         TString exec = ".x " + fname;
         TString p = params;
         if (p == "") p = fParams;
         if (p != "")
            exec += "(" + p + ")";
         retval = gROOT->ProcessLine(exec, error);
         //enable gROOT->Reset
         gROOT->SetExecutingMacro(kFALSE);
         //delete the temporary file
         gSystem->Unlink(fname);
      }
   }

   //G__unloadfile(fname);

   // In case an exception was thrown (which i do not know how to detect
   // the execution of next macros does not succeed.
   // However strange this might seem, this solves the problem.
   // TTimer::SingleShot(100, "TEveMacro", this, "ResetRoot()");
   //
   // 27.8.07 - ok, this does not work any more. Seems I'll have to fix
   // this real soon now.
   //
   // !!!! FIX MACRO HANDLING !!!!
   //

   return retval;
}

#include "TApplication.h"

//______________________________________________________________________________
void TEveMacro::ResetRoot()
{
   // Call gROOT->Reset() via interpreter.

   // printf ("TEveMacro::ResetRoot doing 'gROOT->Reset()'.\n");
   gROOT->GetApplication()->ProcessLine("gROOT->Reset()");
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/tabs/tab_overview_controller.h"

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#if defined(TOOLKIT_VIEWS)
#include "chrome/common/x11_util.h"
#include "chrome/browser/views/frame/browser_extender.h"
#include "chrome/browser/views/frame/browser_view.h"
#else
#include "chrome/browser/gtk/browser_window_gtk.h"
#endif
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/thumbnail_generator.h"
#include "chrome/browser/views/tabs/tab_overview_cell.h"
#include "chrome/browser/views/tabs/tab_overview_container.h"
#include "chrome/browser/views/tabs/tab_overview_drag_controller.h"
#include "chrome/browser/views/tabs/tab_overview_grid.h"
#include "chrome/browser/views/tabs/tab_overview_types.h"
#include "chrome/browser/window_sizer.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"

// Horizontal padding from the edge of the monitor to the overview.
static int kMonitorPadding = 20;
// Vertical padding between the overview and the windows along on the bottom.
static int kWindowToOverviewPadding = 25;
// Height of the windows along the bottom, as a percentage of the monitors
// height.
static float kWindowHeight = .30;
// Height of the tab overview, as a percentage of monitors height.
static float kOverviewHeight = .55;

TabOverviewController::TabOverviewController(
    const gfx::Point& monitor_origin)
    : host_(NULL),
      container_(NULL),
      grid_(NULL),
      browser_(NULL),
      drag_browser_(NULL),
      moved_offscreen_(false),
      shown_(false),
      horizontal_center_(0),
      change_window_bounds_on_animate_(false),
      mutating_grid_(false),
      show_thumbnails_(false) {
  grid_ = new TabOverviewGrid(this);

  // Determine the max size for the overview.
  scoped_ptr<WindowSizer::MonitorInfoProvider> provider(
      WindowSizer::CreateDefaultMonitorInfoProvider());
  monitor_bounds_ = provider->GetMonitorWorkAreaMatching(
      gfx::Rect(monitor_origin.x(), monitor_origin.y(), 1, 1));

  // Create the host.
  views::WidgetGtk* host = new views::WidgetGtk(views::WidgetGtk::TYPE_POPUP);
  host->set_delete_on_destroy(false);
  host->MakeTransparent();
  host->Init(NULL, CalculateHostBounds());
  TabOverviewTypes::instance()->SetWindowType(
      host->GetNativeView(),
      TabOverviewTypes::WINDOW_TYPE_CHROME_TAB_SUMMARY,
      NULL);
  host_ = host;

  container_ = new TabOverviewContainer();
  container_->AddChildView(grid_);
  host->GetRootView()->AddChildView(container_);

  container_->SetMaxSize(CalculateHostBounds().size());

  horizontal_center_ = monitor_bounds_.x() + monitor_bounds_.width() / 2;
}

TabOverviewController::~TabOverviewController() {
  if (browser_)
    model()->RemoveObserver(this);
  host_->Close();
  // The drag controller may call back to us from it's destructor. Make sure
  // it's destroyed before us.
  grid()->CancelDrag();
}

void TabOverviewController::SetBrowser(Browser* browser,
                                       int horizontal_center) {
  horizontal_center_ = horizontal_center;
  if (browser_)
    model()->RemoveObserver(this);
  browser_ = browser;
  if (browser_)
    model()->AddObserver(this);

  show_thumbnails_ = false;
  StartDelayTimer();

  gfx::Rect host_bounds = CalculateHostBounds();
  if (moved_offscreen_ && model() && model()->count()) {
    // Need to reset the bounds if we were offscreen.
    host_->SetBounds(host_bounds);
    moved_offscreen_ = false;
  } else if (!model() && shown_) {
    MoveOffscreen();
  }
  if (!moved_offscreen_)
    container_->SchedulePaint();

  RecreateCells();

  container_->set_arrow_center(horizontal_center_ - host_bounds.x());

  if (!moved_offscreen_)
    container_->SchedulePaint();
}

TabStripModel* TabOverviewController::model() const {
  return browser_ ? browser_->tabstrip_model() : NULL;
}

void TabOverviewController::SetMouseOverMiniWindow(bool over_mini_window) {
  if (grid_->drag_controller())
    grid_->drag_controller()->set_mouse_over_mini_window(over_mini_window);
}

void TabOverviewController::Show() {
  if (host_->IsVisible())
    return;

  shown_ = true;
  DCHECK(model());  // The model needs to be set before showing.
  host_->Show();

  show_thumbnails_ = false;
  StartDelayTimer();
}

void TabOverviewController::ConfigureCell(TabOverviewCell* cell,
                                          TabContents* contents) {
  if (contents) {
    cell->SetTitle(contents->GetTitle());
    cell->SetFavIcon(contents->GetFavIcon());

    if (show_thumbnails_) {
      ThumbnailGenerator* generator =
          g_browser_process->GetThumbnailGenerator();
      cell->SetThumbnail(
          generator->GetThumbnailForRenderer(contents->render_view_host()));
    }
    cell->SchedulePaint();
  } else {
    // Need to figure out under what circumstances this is null and deal.
    NOTIMPLEMENTED();

    // Make sure we set the thumbnail, otherwise configured_thumbnail
    // remains false and ConfigureNextUnconfiguredCell would get stuck.
    if (show_thumbnails_)
      cell->SetThumbnail(SkBitmap());
  }
}

void TabOverviewController::DragStarted() {
  DCHECK(!drag_browser_);
  drag_browser_ = browser_;
#if defined(TOOLKIT_VIEWS)
  static_cast<BrowserView*>(browser_->window())->
      browser_extender()->set_can_close(false);
#else
  static_cast<BrowserWindowGtk*>(browser_->window())->set_drag_active(true);
#endif
}

void TabOverviewController::DragEnded() {
#if defined(TOOLKIT_VIEWS)
  static_cast<BrowserView*>(browser_->window())->
      browser_extender()->set_can_close(true);
#else
  static_cast<BrowserWindowGtk*>(drag_browser_->window())->
      set_drag_active(false);
#endif
  if (drag_browser_->tabstrip_model()->count() == 0)
    drag_browser_->tabstrip_model()->delegate()->CloseFrameAfterDragSession();
  drag_browser_ = NULL;
}

void TabOverviewController::MoveOffscreen() {
  gfx::Rect bounds;
  moved_offscreen_ = true;
  host_->GetBounds(&bounds, true);
  host_->SetBounds(gfx::Rect(-10000, -10000, bounds.width(), bounds.height()));
}

void TabOverviewController::SelectTab(int index) {
  browser_->SelectTabContentsAt(index, true);
}

void TabOverviewController::FocusBrowser() {
  TabOverviewTypes::Message message;
  message.set_type(TabOverviewTypes::Message::WM_FOCUS_WINDOW);
  GtkWidget* browser_widget = GTK_WIDGET(browser_->window()->GetNativeHandle());
  message.set_param(0, x11_util::GetX11WindowFromGtkWidget(browser_widget));
  TabOverviewTypes::instance()->SendMessage(message);
}

void TabOverviewController::GridAnimationEnded() {
  if (moved_offscreen_ || !change_window_bounds_on_animate_ || mutating_grid_)
    return;

  container_->SetBounds(target_bounds_);
  grid_->UpdateDragController();
  change_window_bounds_on_animate_ = false;
}

void TabOverviewController::GridAnimationProgressed() {
  if (moved_offscreen_ || !change_window_bounds_on_animate_)
    return;

  DCHECK(!mutating_grid_);

  // Schedule a paint before and after changing sizes to deal with the case
  // of the view shrinking in size.
  container_->SchedulePaint();
  container_->SetBounds(
      grid_->AnimationPosition(start_bounds_, target_bounds_));
  container_->SchedulePaint();

  // Update the position of the dragged cell.
  grid_->UpdateDragController();
}

void TabOverviewController::GridAnimationCanceled() {
  change_window_bounds_on_animate_ = false;
}

void TabOverviewController::TabInsertedAt(TabContents* contents,
                                          int index,
                                          bool foreground) {
  if (!grid_->modifying_model())
    grid_->CancelDrag();

  TabOverviewCell* child = new TabOverviewCell();
  ConfigureCell(child, index);
  mutating_grid_ = true;
  grid_->InsertCell(index, child);
  mutating_grid_ = false;

  UpdateStartAndTargetBounds();
}

void TabOverviewController::TabClosingAt(TabContents* contents, int index) {
  // Nothing to do, we only care when the tab is actually detached.
}

void TabOverviewController::TabDetachedAt(TabContents* contents, int index) {
  if (!grid_->modifying_model())
    grid_->CancelDrag();

  scoped_ptr<TabOverviewCell> child(grid_->GetTabOverviewCellAt(index));
  mutating_grid_ = true;
  grid_->RemoveCell(index);
  mutating_grid_ = false;

  UpdateStartAndTargetBounds();
}

void TabOverviewController::TabMoved(TabContents* contents,
                                     int from_index,
                                     int to_index,
                                     bool pinned_state_changed) {
  if (!grid_->modifying_model())
    grid_->CancelDrag();

  mutating_grid_ = true;
  grid_->MoveCell(from_index, to_index);
  mutating_grid_ = false;

  UpdateStartAndTargetBounds();
}

void TabOverviewController::TabChangedAt(TabContents* contents, int index,
                                         TabChangeType change_type) {
  ConfigureCell(grid_->GetTabOverviewCellAt(index), index);
}

void TabOverviewController::TabStripEmpty() {
  if (!grid_->modifying_model()) {
    grid_->CancelDrag();
    // The tab strip is empty, hide the grid.
    host_->Hide();
  }
}

void TabOverviewController::ConfigureCell(TabOverviewCell* cell, int index) {
  ConfigureCell(cell, model()->GetTabContentsAt(index));
}

void TabOverviewController::RecreateCells() {
  grid_->RemoveAllChildViews(true);

  if (model()) {
    for (int i = 0; i < model()->count(); ++i) {
      TabOverviewCell* child = new TabOverviewCell();
      ConfigureCell(child, i);
      grid_->AddChildView(child);
    }
  }

  if (moved_offscreen_)
    return;

  if (grid()->GetChildViewCount() > 0) {
    if (shown_)
      host_->Show();
  } else {
    host_->Hide();
  }
  container_->SetBounds(CalculateContainerBounds());
}

void TabOverviewController::UpdateStartAndTargetBounds() {
  if (moved_offscreen_ || !shown_)
    return;

  if (grid()->GetChildViewCount() == 0) {
    host_->Hide();
  } else {
    start_bounds_ = container_->bounds();
    target_bounds_ = CalculateContainerBounds();
    change_window_bounds_on_animate_ = (start_bounds_ != target_bounds_);
  }
}

gfx::Rect TabOverviewController::CalculateContainerBounds() {
  gfx::Rect host_bounds = CalculateHostBounds();
  const gfx::Size& host_size = CalculateHostBounds().size();
  gfx::Size pref = container_->GetPreferredSize();
  int relative_horizontal_center = horizontal_center_ - host_bounds.x();
  int x = relative_horizontal_center - pref.width() / 2;
  int y = host_size.height() - pref.height();
  return gfx::Rect(x, y, pref.width(), pref.height()).
      AdjustToFit(gfx::Rect(0, 0, host_size.width(), host_size.height()));
}

gfx::Rect TabOverviewController::CalculateHostBounds() {
  int max_width = monitor_bounds_.width() - kMonitorPadding * 2;
  int window_height = monitor_bounds_.height() * kWindowHeight;
  int max_height = static_cast<int>(monitor_bounds_.height() *
                                    kOverviewHeight);
  return gfx::Rect(monitor_bounds_.x() + kMonitorPadding,
                   monitor_bounds_.bottom() - window_height -
                   kWindowToOverviewPadding - max_height, max_width,
                   max_height);
}

void TabOverviewController::StartConfiguring() {
  show_thumbnails_ = true;
  configure_timer_.Stop();
  configure_timer_.Start(
      base::TimeDelta::FromMilliseconds(10), this,
      &TabOverviewController::ConfigureNextUnconfiguredCell);
}

void TabOverviewController::ConfigureNextUnconfiguredCell() {
  for (int i = 0; i < grid_->GetChildViewCount(); ++i) {
    TabOverviewCell* cell = grid_->GetTabOverviewCellAt(i);
    if (!cell->configured_thumbnail()) {
      ConfigureCell(cell, i);
      return;
    }
  }
  configure_timer_.Stop();
}

void TabOverviewController::StartDelayTimer() {
  configure_timer_.Stop();
  delay_timer_.Stop();
  delay_timer_.Start(
      base::TimeDelta::FromMilliseconds(350), this,
      &TabOverviewController::StartConfiguring);
}
<commit_msg>Fixes crash in dragging a tab out in overview mode. This regression was introduced when adding the views/gtk support. As we don't need non-views/gtk support anymore, I'm nuking the defines in this file.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/tabs/tab_overview_controller.h"

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/views/frame/browser_extender.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/thumbnail_generator.h"
#include "chrome/browser/views/tabs/tab_overview_cell.h"
#include "chrome/browser/views/tabs/tab_overview_container.h"
#include "chrome/browser/views/tabs/tab_overview_drag_controller.h"
#include "chrome/browser/views/tabs/tab_overview_grid.h"
#include "chrome/browser/views/tabs/tab_overview_types.h"
#include "chrome/browser/window_sizer.h"
#include "chrome/common/x11_util.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"

// Horizontal padding from the edge of the monitor to the overview.
static int kMonitorPadding = 20;
// Vertical padding between the overview and the windows along on the bottom.
static int kWindowToOverviewPadding = 25;
// Height of the windows along the bottom, as a percentage of the monitors
// height.
static float kWindowHeight = .30;
// Height of the tab overview, as a percentage of monitors height.
static float kOverviewHeight = .55;

TabOverviewController::TabOverviewController(
    const gfx::Point& monitor_origin)
    : host_(NULL),
      container_(NULL),
      grid_(NULL),
      browser_(NULL),
      drag_browser_(NULL),
      moved_offscreen_(false),
      shown_(false),
      horizontal_center_(0),
      change_window_bounds_on_animate_(false),
      mutating_grid_(false),
      show_thumbnails_(false) {
  grid_ = new TabOverviewGrid(this);

  // Determine the max size for the overview.
  scoped_ptr<WindowSizer::MonitorInfoProvider> provider(
      WindowSizer::CreateDefaultMonitorInfoProvider());
  monitor_bounds_ = provider->GetMonitorWorkAreaMatching(
      gfx::Rect(monitor_origin.x(), monitor_origin.y(), 1, 1));

  // Create the host.
  views::WidgetGtk* host = new views::WidgetGtk(views::WidgetGtk::TYPE_POPUP);
  host->set_delete_on_destroy(false);
  host->MakeTransparent();
  host->Init(NULL, CalculateHostBounds());
  TabOverviewTypes::instance()->SetWindowType(
      host->GetNativeView(),
      TabOverviewTypes::WINDOW_TYPE_CHROME_TAB_SUMMARY,
      NULL);
  host_ = host;

  container_ = new TabOverviewContainer();
  container_->AddChildView(grid_);
  host->GetRootView()->AddChildView(container_);

  container_->SetMaxSize(CalculateHostBounds().size());

  horizontal_center_ = monitor_bounds_.x() + monitor_bounds_.width() / 2;
}

TabOverviewController::~TabOverviewController() {
  if (browser_)
    model()->RemoveObserver(this);
  host_->Close();
  // The drag controller may call back to us from it's destructor. Make sure
  // it's destroyed before us.
  grid()->CancelDrag();
}

void TabOverviewController::SetBrowser(Browser* browser,
                                       int horizontal_center) {
  horizontal_center_ = horizontal_center;
  if (browser_)
    model()->RemoveObserver(this);
  browser_ = browser;
  if (browser_)
    model()->AddObserver(this);

  show_thumbnails_ = false;
  StartDelayTimer();

  gfx::Rect host_bounds = CalculateHostBounds();
  if (moved_offscreen_ && model() && model()->count()) {
    // Need to reset the bounds if we were offscreen.
    host_->SetBounds(host_bounds);
    moved_offscreen_ = false;
  } else if (!model() && shown_) {
    MoveOffscreen();
  }
  if (!moved_offscreen_)
    container_->SchedulePaint();

  RecreateCells();

  container_->set_arrow_center(horizontal_center_ - host_bounds.x());

  if (!moved_offscreen_)
    container_->SchedulePaint();
}

TabStripModel* TabOverviewController::model() const {
  return browser_ ? browser_->tabstrip_model() : NULL;
}

void TabOverviewController::SetMouseOverMiniWindow(bool over_mini_window) {
  if (grid_->drag_controller())
    grid_->drag_controller()->set_mouse_over_mini_window(over_mini_window);
}

void TabOverviewController::Show() {
  if (host_->IsVisible())
    return;

  shown_ = true;
  DCHECK(model());  // The model needs to be set before showing.
  host_->Show();

  show_thumbnails_ = false;
  StartDelayTimer();
}

void TabOverviewController::ConfigureCell(TabOverviewCell* cell,
                                          TabContents* contents) {
  if (contents) {
    cell->SetTitle(contents->GetTitle());
    cell->SetFavIcon(contents->GetFavIcon());

    if (show_thumbnails_) {
      ThumbnailGenerator* generator =
          g_browser_process->GetThumbnailGenerator();
      cell->SetThumbnail(
          generator->GetThumbnailForRenderer(contents->render_view_host()));
    }
    cell->SchedulePaint();
  } else {
    // Need to figure out under what circumstances this is null and deal.
    NOTIMPLEMENTED();

    // Make sure we set the thumbnail, otherwise configured_thumbnail
    // remains false and ConfigureNextUnconfiguredCell would get stuck.
    if (show_thumbnails_)
      cell->SetThumbnail(SkBitmap());
  }
}

void TabOverviewController::DragStarted() {
  DCHECK(!drag_browser_);
  drag_browser_ = browser_;
  static_cast<BrowserView*>(drag_browser_->window())->
      browser_extender()->set_can_close(false);
}

void TabOverviewController::DragEnded() {
  static_cast<BrowserView*>(drag_browser_->window())->
      browser_extender()->set_can_close(true);
  if (drag_browser_->tabstrip_model()->count() == 0)
    drag_browser_->tabstrip_model()->delegate()->CloseFrameAfterDragSession();
  drag_browser_ = NULL;
}

void TabOverviewController::MoveOffscreen() {
  gfx::Rect bounds;
  moved_offscreen_ = true;
  host_->GetBounds(&bounds, true);
  host_->SetBounds(gfx::Rect(-10000, -10000, bounds.width(), bounds.height()));
}

void TabOverviewController::SelectTab(int index) {
  browser_->SelectTabContentsAt(index, true);
}

void TabOverviewController::FocusBrowser() {
  TabOverviewTypes::Message message;
  message.set_type(TabOverviewTypes::Message::WM_FOCUS_WINDOW);
  GtkWidget* browser_widget = GTK_WIDGET(browser_->window()->GetNativeHandle());
  message.set_param(0, x11_util::GetX11WindowFromGtkWidget(browser_widget));
  TabOverviewTypes::instance()->SendMessage(message);
}

void TabOverviewController::GridAnimationEnded() {
  if (moved_offscreen_ || !change_window_bounds_on_animate_ || mutating_grid_)
    return;

  container_->SetBounds(target_bounds_);
  grid_->UpdateDragController();
  change_window_bounds_on_animate_ = false;
}

void TabOverviewController::GridAnimationProgressed() {
  if (moved_offscreen_ || !change_window_bounds_on_animate_)
    return;

  DCHECK(!mutating_grid_);

  // Schedule a paint before and after changing sizes to deal with the case
  // of the view shrinking in size.
  container_->SchedulePaint();
  container_->SetBounds(
      grid_->AnimationPosition(start_bounds_, target_bounds_));
  container_->SchedulePaint();

  // Update the position of the dragged cell.
  grid_->UpdateDragController();
}

void TabOverviewController::GridAnimationCanceled() {
  change_window_bounds_on_animate_ = false;
}

void TabOverviewController::TabInsertedAt(TabContents* contents,
                                          int index,
                                          bool foreground) {
  if (!grid_->modifying_model())
    grid_->CancelDrag();

  TabOverviewCell* child = new TabOverviewCell();
  ConfigureCell(child, index);
  mutating_grid_ = true;
  grid_->InsertCell(index, child);
  mutating_grid_ = false;

  UpdateStartAndTargetBounds();
}

void TabOverviewController::TabClosingAt(TabContents* contents, int index) {
  // Nothing to do, we only care when the tab is actually detached.
}

void TabOverviewController::TabDetachedAt(TabContents* contents, int index) {
  if (!grid_->modifying_model())
    grid_->CancelDrag();

  scoped_ptr<TabOverviewCell> child(grid_->GetTabOverviewCellAt(index));
  mutating_grid_ = true;
  grid_->RemoveCell(index);
  mutating_grid_ = false;

  UpdateStartAndTargetBounds();
}

void TabOverviewController::TabMoved(TabContents* contents,
                                     int from_index,
                                     int to_index,
                                     bool pinned_state_changed) {
  if (!grid_->modifying_model())
    grid_->CancelDrag();

  mutating_grid_ = true;
  grid_->MoveCell(from_index, to_index);
  mutating_grid_ = false;

  UpdateStartAndTargetBounds();
}

void TabOverviewController::TabChangedAt(TabContents* contents, int index,
                                         TabChangeType change_type) {
  ConfigureCell(grid_->GetTabOverviewCellAt(index), index);
}

void TabOverviewController::TabStripEmpty() {
  if (!grid_->modifying_model()) {
    grid_->CancelDrag();
    // The tab strip is empty, hide the grid.
    host_->Hide();
  }
}

void TabOverviewController::ConfigureCell(TabOverviewCell* cell, int index) {
  ConfigureCell(cell, model()->GetTabContentsAt(index));
}

void TabOverviewController::RecreateCells() {
  grid_->RemoveAllChildViews(true);

  if (model()) {
    for (int i = 0; i < model()->count(); ++i) {
      TabOverviewCell* child = new TabOverviewCell();
      ConfigureCell(child, i);
      grid_->AddChildView(child);
    }
  }

  if (moved_offscreen_)
    return;

  if (grid()->GetChildViewCount() > 0) {
    if (shown_)
      host_->Show();
  } else {
    host_->Hide();
  }
  container_->SetBounds(CalculateContainerBounds());
}

void TabOverviewController::UpdateStartAndTargetBounds() {
  if (moved_offscreen_ || !shown_)
    return;

  if (grid()->GetChildViewCount() == 0) {
    host_->Hide();
  } else {
    start_bounds_ = container_->bounds();
    target_bounds_ = CalculateContainerBounds();
    change_window_bounds_on_animate_ = (start_bounds_ != target_bounds_);
  }
}

gfx::Rect TabOverviewController::CalculateContainerBounds() {
  gfx::Rect host_bounds = CalculateHostBounds();
  const gfx::Size& host_size = CalculateHostBounds().size();
  gfx::Size pref = container_->GetPreferredSize();
  int relative_horizontal_center = horizontal_center_ - host_bounds.x();
  int x = relative_horizontal_center - pref.width() / 2;
  int y = host_size.height() - pref.height();
  return gfx::Rect(x, y, pref.width(), pref.height()).
      AdjustToFit(gfx::Rect(0, 0, host_size.width(), host_size.height()));
}

gfx::Rect TabOverviewController::CalculateHostBounds() {
  int max_width = monitor_bounds_.width() - kMonitorPadding * 2;
  int window_height = monitor_bounds_.height() * kWindowHeight;
  int max_height = static_cast<int>(monitor_bounds_.height() *
                                    kOverviewHeight);
  return gfx::Rect(monitor_bounds_.x() + kMonitorPadding,
                   monitor_bounds_.bottom() - window_height -
                   kWindowToOverviewPadding - max_height, max_width,
                   max_height);
}

void TabOverviewController::StartConfiguring() {
  show_thumbnails_ = true;
  configure_timer_.Stop();
  configure_timer_.Start(
      base::TimeDelta::FromMilliseconds(10), this,
      &TabOverviewController::ConfigureNextUnconfiguredCell);
}

void TabOverviewController::ConfigureNextUnconfiguredCell() {
  for (int i = 0; i < grid_->GetChildViewCount(); ++i) {
    TabOverviewCell* cell = grid_->GetTabOverviewCellAt(i);
    if (!cell->configured_thumbnail()) {
      ConfigureCell(cell, i);
      return;
    }
  }
  configure_timer_.Stop();
}

void TabOverviewController::StartDelayTimer() {
  configure_timer_.Stop();
  delay_timer_.Stop();
  delay_timer_.Start(
      base::TimeDelta::FromMilliseconds(350), this,
      &TabOverviewController::StartConfiguring);
}
<|endoftext|>


<commit_before>#include "JsDebugger.h"
#include "V8GlobalHelpers.h"
#include "JniLocalRef.h"
#include "NativeScriptException.h"
#include "NativeScriptAssert.h"
#include <assert.h>
#include <sstream>

using namespace std;
using namespace tns;

JsDebugger::JsDebugger()
{
}

void JsDebugger::Init(v8::Isolate *isolate, const string& packageName, jobject jsDebugger)
{
	s_isolate = isolate;
	s_packageName = packageName;

	JEnv env;
	s_jsDebugger = env.NewGlobalRef(jsDebugger);

	s_JsDebuggerClass = env.FindClass("com/tns/JsDebugger");
	assert(s_JsDebuggerClass != nullptr);

	s_EnqueueMessage = env.GetMethodID(s_JsDebuggerClass, "enqueueMessage", "(Ljava/lang/String;)V");
	assert(s_EnqueueMessage != nullptr);

	s_EnableAgent = env.GetMethodID(s_JsDebuggerClass, "enableAgent", "()V");
	assert(s_EnableAgent != nullptr);
}

string JsDebugger::GetPackageName()
{
	return s_packageName;
}

/* *
 * sets who will handle the messages when they start comming from v8
 */
void JsDebugger::Enable()
{
	auto isolate = s_isolate;
	v8::Isolate::Scope isolate_scope(isolate);
	v8::HandleScope handleScope(isolate);

	v8::Debug::SetMessageHandler(MyMessageHandler);
	enabled = true;
}

/* *
 * the message that come from v8 will not be handled anymore
 */
void JsDebugger::Disable()
{
	enabled = false;
	auto isolate = s_isolate;
	v8::Isolate::Scope isolate_scope(isolate);
	v8::HandleScope handleScope(isolate);

	v8::Debug::SetMessageHandler(nullptr);
}

/* *
 * schedule a debugger break to happen when JavaScript code is run in the given isolate
 * (cli command: tns debug android --debug-brk) ?
 */
void JsDebugger::DebugBreak()
{
	auto isolate = s_isolate;
	v8::Isolate::Scope isolate_scope(isolate);
	v8::HandleScope handleScope(isolate);

	v8::Debug::DebugBreak(isolate);
}

void JsDebugger::ProcessDebugMessages()
{
	auto isolate = s_isolate;
	v8::Isolate::Scope isolate_scope(isolate);
	v8::HandleScope handleScope(isolate);

	v8::Debug::ProcessDebugMessages();
}

void JsDebugger::SendCommand(JNIEnv *_env, jobject obj, jbyteArray command, jint length)
{
	tns::JEnv env(_env);
	auto buf = new jbyte[length];

	env.GetByteArrayRegion(command, 0, length, buf);

	int len = length / sizeof(uint16_t);
	SendCommandToV8(reinterpret_cast<uint16_t*>(buf), len);

	delete[] buf;
}

void JsDebugger::DebugBreakCallback(const v8::FunctionCallbackInfo<v8::Value>& args)
{
	if (s_jsDebugger == nullptr)
	{
		return;
	}

	try
	{
		JEnv env;
		env.CallStaticVoidMethod(s_JsDebuggerClass, s_EnableAgent);

		DebugBreak();
	}
	catch (NativeScriptException& e)
	{
		e.ReThrowToV8();
	}
	catch (std::exception e) {
		stringstream ss;
		ss << "Error: c++ exception: " << e.what() << endl;
		NativeScriptException nsEx(ss.str());
		nsEx.ReThrowToV8();
	}
	catch (...) {
		NativeScriptException nsEx(std::string("Error: c++ exception!"));
		nsEx.ReThrowToV8();
	}
}

void JsDebugger::ConsoleMessageCallback(const v8::FunctionCallbackInfo<v8::Value>& args)
{
	if (s_jsDebugger == nullptr || !enabled)
	{
		return;
	}

	auto isolate = s_isolate;
	v8::Isolate::Scope isolate_scope(isolate);
	v8::HandleScope handleScope(isolate);

	if ((args.Length() > 0) && args[0]->IsString())
	{
		std::string message = ConvertToString(args[0]->ToString());
		//jboolean isError = (jboolean) = args[1]->ToBoolean()->BooleanValue();

		JEnv env;
		JniLocalRef s(env.NewStringUTF(message.c_str()));
		env.CallVoidMethod(s_jsDebugger, s_EnqueueMessage, (jstring) s);
	}
}

void JsDebugger::SendCommandToV8(uint16_t *cmd, int length)
{
	auto isolate = s_isolate;

	v8::Debug::SendCommand(isolate, cmd, length, nullptr);
}

/* *
 * private method that takes debug message as json from v8
 * after it gets the message the message handler passes it to enqueueMessage method in java
 */
void JsDebugger::MyMessageHandler(const v8::Debug::Message& message)
{
	if (s_jsDebugger == nullptr)
	{
		return;
	}

	auto json = message.GetJSON();
	auto str = ConvertToString(json);

	JEnv env;
	JniLocalRef s(env.NewStringUTF(str.c_str()));
	env.CallVoidMethod(s_jsDebugger, s_EnqueueMessage, (jstring) s);
}

bool JsDebugger::enabled = false;
v8::Isolate* JsDebugger::s_isolate = nullptr;
jobject JsDebugger::s_jsDebugger = nullptr;
string JsDebugger::s_packageName = "";
jclass JsDebugger::s_JsDebuggerClass = nullptr;
jmethodID JsDebugger::s_EnqueueMessage = nullptr;
jmethodID JsDebugger::s_EnableAgent = nullptr;

<commit_msg>better console message event<commit_after>#include "JsDebugger.h"
#include "V8GlobalHelpers.h"
#include "JniLocalRef.h"
#include "NativeScriptException.h"
#include "NativeScriptAssert.h"
#include <assert.h>
#include <sstream>

using namespace std;
using namespace tns;
using namespace v8;

JsDebugger::JsDebugger()
{
}

void JsDebugger::Init(v8::Isolate *isolate, const string& packageName, jobject jsDebugger)
{
	s_isolate = isolate;
	s_packageName = packageName;

	JEnv env;
	s_jsDebugger = env.NewGlobalRef(jsDebugger);

	s_JsDebuggerClass = env.FindClass("com/tns/JsDebugger");
	assert(s_JsDebuggerClass != nullptr);

	s_EnqueueMessage = env.GetMethodID(s_JsDebuggerClass, "enqueueMessage", "(Ljava/lang/String;)V");
	assert(s_EnqueueMessage != nullptr);

	s_EnableAgent = env.GetMethodID(s_JsDebuggerClass, "enableAgent", "()V");
	assert(s_EnableAgent != nullptr);
}

string JsDebugger::GetPackageName()
{
	return s_packageName;
}

/* *
 * sets who will handle the messages when they start comming from v8
 */
void JsDebugger::Enable()
{
	auto isolate = s_isolate;
	v8::Isolate::Scope isolate_scope(isolate);
	v8::HandleScope handleScope(isolate);

	v8::Debug::SetMessageHandler(MyMessageHandler);
	enabled = true;
}

/* *
 * the message that come from v8 will not be handled anymore
 */
void JsDebugger::Disable()
{
	enabled = false;
	auto isolate = s_isolate;
	v8::Isolate::Scope isolate_scope(isolate);
	v8::HandleScope handleScope(isolate);

	v8::Debug::SetMessageHandler(nullptr);
}

/* *
 * schedule a debugger break to happen when JavaScript code is run in the given isolate
 * (cli command: tns debug android --debug-brk) ?
 */
void JsDebugger::DebugBreak()
{
	auto isolate = s_isolate;
	v8::Isolate::Scope isolate_scope(isolate);
	v8::HandleScope handleScope(isolate);

	v8::Debug::DebugBreak(isolate);
}

void JsDebugger::ProcessDebugMessages()
{
	auto isolate = s_isolate;
	v8::Isolate::Scope isolate_scope(isolate);
	v8::HandleScope handleScope(isolate);

	v8::Debug::ProcessDebugMessages();
}

void JsDebugger::SendCommand(JNIEnv *_env, jobject obj, jbyteArray command, jint length)
{
	tns::JEnv env(_env);
	auto buf = new jbyte[length];

	env.GetByteArrayRegion(command, 0, length, buf);

	int len = length / sizeof(uint16_t);
	SendCommandToV8(reinterpret_cast<uint16_t*>(buf), len);

	delete[] buf;
}

void JsDebugger::DebugBreakCallback(const v8::FunctionCallbackInfo<v8::Value>& args)
{
	if (s_jsDebugger == nullptr)
	{
		return;
	}

	try
	{
		JEnv env;
		env.CallStaticVoidMethod(s_JsDebuggerClass, s_EnableAgent);

		DebugBreak();
	}
	catch (NativeScriptException& e)
	{
		e.ReThrowToV8();
	}
	catch (std::exception e) {
		stringstream ss;
		ss << "Error: c++ exception: " << e.what() << endl;
		NativeScriptException nsEx(ss.str());
		nsEx.ReThrowToV8();
	}
	catch (...) {
		NativeScriptException nsEx(std::string("Error: c++ exception!"));
		nsEx.ReThrowToV8();
	}
}

void JsDebugger::ConsoleMessageCallback(const v8::FunctionCallbackInfo<v8::Value>& args)
{
	if (s_jsDebugger == nullptr || !enabled)
	{
		return;
	}

	auto isolate = s_isolate;
	Isolate::Scope isolate_scope(isolate);
	HandleScope handleScope(isolate);

	if ((args.Length() > 0) && args[0]->IsString())
	{
		std::string message = ConvertToString(args[0]->ToString());
		//jboolean isError = (jboolean) = args[1]->ToBoolean()->BooleanValue();

		std:string type = "log";
		if (args.Length() > 1  && args[1]->IsString())
		{
			type = ConvertToString(args[1]->ToString());
		}

		string srcFileName = "";
		int lineNumber = 0;
		int columnNumber = 0;

		auto stackTrace = StackTrace::CurrentStackTrace(Isolate::GetCurrent(), 2, StackTrace::kOverview);
		if (!stackTrace.IsEmpty())
		{
			auto frame = stackTrace->GetFrame(1);
			if (!frame.IsEmpty())
			{
				auto scriptName = frame->GetScriptName();
				if (!scriptName.IsEmpty())
				{
					srcFileName = ConvertToString(scriptName);
				}

				lineNumber = frame->GetLineNumber();
				columnNumber = frame->GetColumn();
			}
		}

		//    			var consoleEvent = {
		//	    			"seq":0,
		//	    			"type":"event",
		//	    			"event":"messageAdded",
		//	    			"success":true,
		//	    			"body":
		//	    			{
		//	    				"message":
		//	    				{
		//	    			        "source":"console-api",
		//	    			        "type": "log",
		//	    			        "level": '',
		//	    			        "line": 0,
		//	    			        "column": 0,
		//	    			        "url": "",
		//	    			        "groupLevel": 7,
		//	    			        "repeatCount": 1,
		//	    			        "text": "My message"
		//	    			    }
		//	    			}
		//    			};

		stringstream consoleEventSS;
		consoleEventSS << "{\"seq\":0, \"type\":\"event\", \"event\":\"messageAdded\", \"success\":true, \"body\": { \"message\": { \"source\":\"console-api\", "
				<< " \"type\": \"" << type << "\", "
				<< " \"level\": \"\", "
				<< " \"line\": " << lineNumber << ","
				<< " \"colum\": " << columnNumber << ","
				<< " \"url\" : \"" << srcFileName << "\","
				<< " \"groupLevel\": 7, \"repeatCount\": 1, "
				<< " \"text\": \"" << message << "\" } } }";

		JEnv env;
		JniLocalRef s(env.NewStringUTF(consoleEventSS.str().c_str()));
		env.CallVoidMethod(s_jsDebugger, s_EnqueueMessage, (jstring) s);
	}
}

void JsDebugger::SendCommandToV8(uint16_t *cmd, int length)
{
	auto isolate = s_isolate;

	v8::Debug::SendCommand(isolate, cmd, length, nullptr);
}

/* *
 * private method that takes debug message as json from v8
 * after it gets the message the message handler passes it to enqueueMessage method in java
 */
void JsDebugger::MyMessageHandler(const v8::Debug::Message& message)
{
	if (s_jsDebugger == nullptr)
	{
		return;
	}

	auto json = message.GetJSON();
	auto str = ConvertToString(json);

	JEnv env;
	JniLocalRef s(env.NewStringUTF(str.c_str()));
	env.CallVoidMethod(s_jsDebugger, s_EnqueueMessage, (jstring) s);
}

bool JsDebugger::enabled = false;
v8::Isolate* JsDebugger::s_isolate = nullptr;
jobject JsDebugger::s_jsDebugger = nullptr;
string JsDebugger::s_packageName = "";
jclass JsDebugger::s_JsDebuggerClass = nullptr;
jmethodID JsDebugger::s_EnqueueMessage = nullptr;
jmethodID JsDebugger::s_EnableAgent = nullptr;

<|endoftext|>


<commit_before>#include <tiramisu/tiramisu.h>

#define NN 1024
#define MM 1024

using namespace tiramisu;

int main(int argc, char* argv[])
{
    tiramisu::init("edge_tiramisu");

    var i("i", 0, NN-2), j("j", 0, MM-2), c("c", 0, 3);
    input Img("Img", {i, j, c}, p_uint8);

    // Layer I

    /* Ring blur filter. */
    computation R("R", {c, j, i}, (Img(c, j, i)   + Img(c, j+1, i)   + Img(c, j+2, i)+
				   Img(c, j, i+1)                    + Img(c, j+2, i+1)+
				   Img(c, j, i+2) + Img(c, j+1, i+2) + Img(c, j+2, i+2))/((uint8_t) 8));

    /* Robert's edge detection filter. */
    computation Out("Out", {c, j, i}, (R(c, j+1, i+1)-R(c, j, i+2)) + (R(c, j+1, i+2)-R(c, j, i+1)));

    // Layer II
    Out.after(R, computation::root);

    // Layer III
    buffer b_Img("Img", {NN, MM, 3}, p_uint8, a_input);
    buffer   b_R("R",   {NN, MM, 3}, p_uint8, a_temporary);

    Img.store_in(&b_Img);
    R.store_in(&b_R);
    Out.store_in(&b_Img);

    tiramisu::codegen({&b_Img}, "build/generated_fct_edge.o");

  return 0;
}

<commit_msg>Update edge<commit_after>#include <tiramisu/tiramisu.h>

#define NN 1024
#define MM 1024

using namespace tiramisu;

int main(int argc, char* argv[])
{
    tiramisu::init("edge_tiramisu");

    var i("i", 0, NN-2), j("j", 0, MM-2), c("c", 0, 3);
    input Img("Img", {i, j, c}, p_uint8);

    // Layer I

    /* Ring blur filter. */
    computation R("R", {c, j, i}, (Img(c, j, i)   + Img(c, j+1, i)   + Img(c, j+2, i)+
				   Img(c, j, i+1)                    + Img(c, j+2, i+1)+
				   Img(c, j, i+2) + Img(c, j+1, i+2) + Img(c, j+2, i+2))/((uint8_t) 8));

    /* Robert's edge detection filter. */
    computation Out("Out", {c, j, i}, (R(c, j+1, i+1)-R(c, j, i+2)) + (R(c, j+1, i+2)-R(c, j, i+1)));

    // Layer II
    R.parallelize(c);
    Out.parallelize(c);
    R.tile(j, i, 32, 32);
    Out.tile(j, i, 32, 32);
    Out.after(R, computation::root);

    // Layer III
    buffer b_Img("Img", {NN, MM, 3}, p_uint8, a_input);
    buffer   b_R("R",   {NN, MM, 3}, p_uint8, a_temporary);

    Img.store_in(&b_Img);
    R.store_in(&b_R);
    Out.store_in(&b_Img);

    tiramisu::codegen({&b_Img}, "build/generated_fct_edge.o");

  return 0;
}

<|endoftext|>