<commit_before>#include <limits>

#include <Bull/Core/Log.hpp>

#include <Bull/Render/Context/Glx/GlxContext.hpp>
#include <Bull/Render/Context/Glx/GlxCreateContextARB.hpp>
#include <Bull/Render/Context/Glx/GlxSwapControlEXT.hpp>
#include <Bull/Render/Context/Glx/GlxSwapControlMESA.hpp>
#include <Bull/Render/Context/Glx/GlxSwapControlSGI.hpp>

#include <Bull/Utility/Window/X11/ErrorHandler.hpp>

namespace Bull
{
    namespace prv
    {
        void* GlxContext::getFunction(const String& function)
        {
            return reinterpret_cast<void*>(glXGetProcAddressARB(reinterpret_cast<const unsigned char*>(static_cast<const char*>(function))));
        }

        void GlxContext::requireExtensions(const ExtensionsLoader::Instance& loader)
        {
            loader->require(GlxCreateContextARB);

            if(isSupported(GlxSwapControlEXT))
            {
                loader->require(GlxSwapControlEXT);
            }
            else if(isSupported(GlxSwapControlMESA))
            {
                loader->require(GlxSwapControlMESA);
            }
            else if(isSupported(GlxSwapControlSGI))
            {
                loader->require(GlxSwapControlSGI);
            }
            else
            {
                Log::get()->write("VSync is not available on your system", Log::Level::Notice);
            }
        }

        GLXFBConfig GlxContext::chooseBestConfig(Display::Instance display, const ContextSettings& settings, unsigned int bitsPerPixel)
        {
            int attributes[] =
            {
                GLX_X_RENDERABLE  , True,
                GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT,
                GLX_RENDER_TYPE   , GLX_RGBA_BIT,
                GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR,
                GLX_RED_SIZE      , static_cast<int>(bitsPerPixel) / 4,
                GLX_GREEN_SIZE    , static_cast<int>(bitsPerPixel) / 4,
                GLX_BLUE_SIZE     , static_cast<int>(bitsPerPixel) / 4,
                GLX_ALPHA_SIZE    , static_cast<int>(bitsPerPixel) / 4,
                GLX_DEPTH_SIZE    , settings.depths,
                GLX_STENCIL_SIZE  , settings.stencil,
                GLX_DOUBLEBUFFER  , True,
                GLX_SAMPLE_BUFFERS, settings.antialiasing == 0 ? 0 : 1,
                GLX_SAMPLES       , settings.antialiasing,
                0
            };

            int fbCounts = 0;
            int bestConfig = 0, bestScore = std::numeric_limits<int>::max();
            GLXFBConfig config;
            GLXFBConfig* configs = glXChooseFBConfig(display->getHandler(), display->getDefaultScreen(), attributes, &fbCounts);

            for(int i = 0; i < fbCounts; i++)
            {
                XVisualInfo* visual = glXGetVisualFromFBConfig(display->getHandler(), configs[i]);

                if(visual)
                {
                    int red, green, blue, alpha;
                    int sampleBuffers, samples;
                    int depths, stencil;

                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_RED_SIZE,   &red);
                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_GREEN_SIZE, &green);
                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_BLUE_SIZE,  &blue);
                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_ALPHA_SIZE, &alpha);

                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_SAMPLE_BUFFERS, &sampleBuffers);
                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_SAMPLES, &samples);

                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_DEPTH_SIZE,   &depths);
                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_STENCIL_SIZE, &stencil);

                    int currentBitsPerPixel = red + green + blue + alpha;
                    int score = evaluatePixelFormat(currentBitsPerPixel, depths, stencil, sampleBuffers ? samples : 0, bitsPerPixel, settings);

                    if(score < bestScore)
                    {
                        bestScore  = score;
                        bestConfig = i;
                    }
                }
            }

            config = configs[bestConfig];

            XFree(configs);

            return config;
        }

        GlxContext::GlxContext(const std::shared_ptr<GlxContext>& shared) :
            GlxContext(shared, VideoMode(1, 1), ContextSettings())
        {
            /// Nothing
        }

        GlxContext::GlxContext(const std::shared_ptr<GlxContext>& shared, const VideoMode& mode, const ContextSettings& settings) :
            GlContext(settings),
            m_window(0),
            m_render(0),
            m_display(Display::get()),
            m_ownWindow(false)
        {
            m_config = chooseBestConfig(m_display, m_settings, mode.bitsPerPixel);

            createSurface(mode.width, mode.height, mode.bitsPerPixel);

            if(m_window)
            {
                createContext(shared);
            }
        }

        GlxContext::GlxContext(const std::shared_ptr<GlxContext>& shared, unsigned int bitsPerPixel, const ContextSettings& settings) :
            GlxContext(shared, VideoMode(1, 1, bitsPerPixel), settings)
        {
            /// Nothing
        }

        GlxContext::GlxContext(const std::shared_ptr<GlxContext>& shared, WindowHandler window, unsigned int bitsPerPixel, const ContextSettings& settings) :
            GlContext(settings),
            m_window(0),
            m_render(0),
            m_display(Display::get()),
            m_ownWindow(false)
        {
            m_config = chooseBestConfig(m_display, m_settings, bitsPerPixel);

            createSurface(window);

            if(window)
            {
                createContext(shared);
            }
        }

        GlxContext::~GlxContext()
        {
            if(m_ownWindow)
            {
                XDestroyWindow(m_display->getHandler(), m_window);
            }

            if(m_render)
            {
                if(glXGetCurrentContext() == m_render)
                {
                    glXMakeCurrent(m_display->getHandler(), 0, 0);
                }

                glXDestroyContext(m_display->getHandler(), m_render);
            }
        }

        void GlxContext::display()
        {
            if(m_window && m_render)
            {
                glXSwapBuffers(m_display->getHandler(), m_window);
            }
        }

        void GlxContext::enableVsync(bool active)
        {

        }

        SurfaceHandler GlxContext::getSurfaceHandler() const
        {
            return m_display->getDefaultScreen();
        }

        bool GlxContext::makeCurrent()
        {
            if(m_window && m_render)
            {
                ErrorHandler handler;
                return glXMakeCurrent(m_display->getHandler(), m_window, m_render) == True;
            }

            return false;
        }

        void GlxContext::createSurface(WindowHandler handler)
        {
            m_window = handler;
        }

        void GlxContext::createSurface(unsigned int width, unsigned int height, unsigned int bitsPerPixel)
        {
            XVisualInfo*         vi;
            GLXFBConfig          config;
            ErrorHandler         handler;
            XSetWindowAttributes attributes;

            config = GlxContext::chooseBestConfig(m_display, m_settings, bitsPerPixel);

            vi = glXGetVisualFromFBConfig(m_display->getHandler(), config);

            attributes.background_pixel = 0;
            attributes.border_pixel     = 0;
            attributes.colormap         = XCreateColormap(m_display->getHandler(), m_display->getRootWindow(vi->screen), vi->visual, AllocNone);

            m_window = XCreateWindow(m_display->getHandler(),
                                     m_display->getRootWindow(),
                                     0, 0,
                                     width, height,
                                     0,
                                     vi->depth,
                                     InputOnly,
                                     vi->visual,
                                     CWBackPixel | CWBorderPixel | CWColormap,
                                     &attributes);
        }

        void GlxContext::createContext(const std::shared_ptr<GlxContext>& shared)
        {
            GLXContext sharedHandler = shared.get() != nullptr ? shared->m_render : 0;

            int glxMajor, glxMinor;

            glXQueryVersion(m_display->getHandler(), &glxMajor, &glxMinor);

            if(isSupported(GlxCreateContextARB) && (glxMajor > 1 || glxMinor >= 3))
            {
                do
                {
                    ErrorHandler handler;
                    std::vector<int> attribs;

                    attribs.push_back(GLX_CONTEXT_MAJOR_VERSION_ARB);
                    attribs.push_back(m_settings.major);
                    attribs.push_back(GLX_CONTEXT_MINOR_VERSION_ARB);
                    attribs.push_back(m_settings.minor);

                    if(isSupported("GLX_ARB_create_context_profile"))
                    {
                        int flags   = 0;
                        int profile = (m_settings.flags & ContextSettings::Compatibility) ? GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB : GLX_CONTEXT_CORE_PROFILE_BIT_ARB;

                        if(m_settings.flags & ContextSettings::Debug)
                        {
                            flags |= GLX_CONTEXT_DEBUG_BIT_ARB;
                        }

                        if(m_settings.flags & ContextSettings::ForwardCompatible)
                        {
                            flags |= GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
                        }

                        attribs.push_back(GLX_CONTEXT_PROFILE_MASK_ARB);
                        attribs.push_back(profile);
                        attribs.push_back(GLX_CONTEXT_FLAGS_ARB);
                        attribs.push_back(flags);
                    }

                    attribs.push_back(0);

                    m_render = glXCreateContextAttribs(m_display->getHandler(), m_config, sharedHandler, True, &attribs[0]);

                    if(!m_render)
                    {
                        if(m_settings.minor == 0)
                        {
                            m_settings.major -= 1;
                            m_settings.minor  = 9;
                        }
                        else
                        {
                            m_settings.minor -= 1;
                        }
                    }
                }while(!m_render && m_settings.major >= 1);
            }

            if(!m_render)
            {
                ErrorHandler handler;
                m_render = glXCreateNewContext(m_display->getHandler(), m_config, GLX_RGBA_TYPE, sharedHandler, True);
            }

            m_isDirect = glXIsDirect(m_display->getHandler(), m_render);
        }
    }
}
<commit_msg>Render/GlxContext Implement VSync support<commit_after>#include <limits>

#include <Bull/Core/Log.hpp>

#include <Bull/Render/Context/Glx/GlxContext.hpp>
#include <Bull/Render/Context/Glx/GlxCreateContextARB.hpp>
#include <Bull/Render/Context/Glx/GlxSwapControlEXT.hpp>
#include <Bull/Render/Context/Glx/GlxSwapControlMESA.hpp>
#include <Bull/Render/Context/Glx/GlxSwapControlSGI.hpp>

#include <Bull/Utility/Window/X11/ErrorHandler.hpp>

namespace Bull
{
    namespace prv
    {
        void* GlxContext::getFunction(const String& function)
        {
            return reinterpret_cast<void*>(glXGetProcAddressARB(reinterpret_cast<const unsigned char*>(static_cast<const char*>(function))));
        }

        void GlxContext::requireExtensions(const ExtensionsLoader::Instance& loader)
        {
            loader->require(GlxCreateContextARB);

            if(isSupported(GlxSwapControlEXT))
            {
                loader->require(GlxSwapControlEXT);
            }
            else if(isSupported(GlxSwapControlMESA))
            {
                loader->require(GlxSwapControlMESA);
            }
            else if(isSupported(GlxSwapControlSGI))
            {
                loader->require(GlxSwapControlSGI);
            }
            else
            {
                Log::get()->write("VSync is not available on your system", Log::Level::Notice);
            }
        }

        GLXFBConfig GlxContext::chooseBestConfig(Display::Instance display, const ContextSettings& settings, unsigned int bitsPerPixel)
        {
            int attributes[] =
            {
                GLX_X_RENDERABLE  , True,
                GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT,
                GLX_RENDER_TYPE   , GLX_RGBA_BIT,
                GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR,
                GLX_RED_SIZE      , static_cast<int>(bitsPerPixel) / 4,
                GLX_GREEN_SIZE    , static_cast<int>(bitsPerPixel) / 4,
                GLX_BLUE_SIZE     , static_cast<int>(bitsPerPixel) / 4,
                GLX_ALPHA_SIZE    , static_cast<int>(bitsPerPixel) / 4,
                GLX_DEPTH_SIZE    , settings.depths,
                GLX_STENCIL_SIZE  , settings.stencil,
                GLX_DOUBLEBUFFER  , True,
                GLX_SAMPLE_BUFFERS, settings.antialiasing ? 1 : 0,
                GLX_SAMPLES       , settings.antialiasing,
                0
            };

            int fbCounts = 0;
            int bestConfig = 0, bestScore = std::numeric_limits<int>::max();
            GLXFBConfig config;
            GLXFBConfig* configs = glXChooseFBConfig(display->getHandler(), display->getDefaultScreen(), attributes, &fbCounts);

            for(int i = 0; i < fbCounts; i++)
            {
                XVisualInfo* visual = glXGetVisualFromFBConfig(display->getHandler(), configs[i]);

                if(visual)
                {
                    int red, green, blue, alpha;
                    int sampleBuffers, samples;
                    int depths, stencil;

                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_RED_SIZE,   &red);
                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_GREEN_SIZE, &green);
                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_BLUE_SIZE,  &blue);
                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_ALPHA_SIZE, &alpha);

                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_SAMPLE_BUFFERS, &sampleBuffers);
                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_SAMPLES, &samples);

                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_DEPTH_SIZE,   &depths);
                    glXGetFBConfigAttrib(display->getHandler(), configs[i], GLX_STENCIL_SIZE, &stencil);

                    int currentBitsPerPixel = red + green + blue + alpha;
                    int score = evaluatePixelFormat(currentBitsPerPixel, depths, stencil, sampleBuffers ? samples : 0, bitsPerPixel, settings);

                    if(score < bestScore)
                    {
                        bestScore  = score;
                        bestConfig = i;
                    }
                }
            }

            config = configs[bestConfig];

            XFree(configs);

            return config;
        }

        GlxContext::GlxContext(const std::shared_ptr<GlxContext>& shared) :
            GlxContext(shared, VideoMode(1, 1), ContextSettings())
        {
            /// Nothing
        }

        GlxContext::GlxContext(const std::shared_ptr<GlxContext>& shared, const VideoMode& mode, const ContextSettings& settings) :
            GlContext(settings),
            m_window(0),
            m_render(0),
            m_display(Display::get()),
            m_ownWindow(false)
        {
            m_config = chooseBestConfig(m_display, m_settings, mode.bitsPerPixel);

            createSurface(mode.width, mode.height, mode.bitsPerPixel);

            if(m_window)
            {
                createContext(shared);
            }
        }

        GlxContext::GlxContext(const std::shared_ptr<GlxContext>& shared, unsigned int bitsPerPixel, const ContextSettings& settings) :
            GlxContext(shared, VideoMode(1, 1, bitsPerPixel), settings)
        {
            /// Nothing
        }

        GlxContext::GlxContext(const std::shared_ptr<GlxContext>& shared, WindowHandler window, unsigned int bitsPerPixel, const ContextSettings& settings) :
            GlContext(settings),
            m_window(0),
            m_render(0),
            m_display(Display::get()),
            m_ownWindow(false)
        {
            m_config = chooseBestConfig(m_display, m_settings, bitsPerPixel);

            createSurface(window);

            if(window)
            {
                createContext(shared);
            }
        }

        GlxContext::~GlxContext()
        {
            if(m_ownWindow)
            {
                XDestroyWindow(m_display->getHandler(), m_window);
            }

            if(m_render)
            {
                if(glXGetCurrentContext() == m_render)
                {
                    glXMakeCurrent(m_display->getHandler(), 0, 0);
                }

                glXDestroyContext(m_display->getHandler(), m_render);
            }
        }

        void GlxContext::display()
        {
            if(m_window && m_render)
            {
                glXSwapBuffers(m_display->getHandler(), m_window);
            }
        }

        void GlxContext::enableVsync(bool active)
        {
            if(isSupported(GlxSwapControlEXT))
            {
                ext::glXSwapInterval(m_display->getHandler(), m_window, active ? 1 : 0);
            }
            else if(isSupported(GlxSwapControlMESA))
            {
                mesa::glXSwapInterval(active ? 1 : 0);
            }
            else if(isSupported(GlxSwapControlSGI))
            {
                sgi::glXSwapInterval(active ? 1 : 0);
            }
        }

        SurfaceHandler GlxContext::getSurfaceHandler() const
        {
            return m_display->getDefaultScreen();
        }

        bool GlxContext::makeCurrent()
        {
            if(m_window && m_render)
            {
                ErrorHandler handler;
                return glXMakeCurrent(m_display->getHandler(), m_window, m_render) == True;
            }

            return false;
        }

        void GlxContext::createSurface(WindowHandler handler)
        {
            m_window = handler;
        }

        void GlxContext::createSurface(unsigned int width, unsigned int height, unsigned int bitsPerPixel)
        {
            XVisualInfo*         vi;
            GLXFBConfig          config;
            ErrorHandler         handler;
            XSetWindowAttributes attributes;

            config = GlxContext::chooseBestConfig(m_display, m_settings, bitsPerPixel);

            vi = glXGetVisualFromFBConfig(m_display->getHandler(), config);

            attributes.background_pixel = 0;
            attributes.border_pixel     = 0;
            attributes.colormap         = XCreateColormap(m_display->getHandler(), m_display->getRootWindow(vi->screen), vi->visual, AllocNone);

            m_window = XCreateWindow(m_display->getHandler(),
                                     m_display->getRootWindow(),
                                     0, 0,
                                     width, height,
                                     0,
                                     vi->depth,
                                     InputOnly,
                                     vi->visual,
                                     CWBackPixel | CWBorderPixel | CWColormap,
                                     &attributes);
        }

        void GlxContext::createContext(const std::shared_ptr<GlxContext>& shared)
        {
            GLXContext sharedHandler = shared.get() != nullptr ? shared->m_render : 0;

            int glxMajor, glxMinor;

            glXQueryVersion(m_display->getHandler(), &glxMajor, &glxMinor);

            if(isSupported(GlxCreateContextARB) && (glxMajor > 1 || glxMinor >= 3))
            {
                do
                {
                    ErrorHandler handler;
                    std::vector<int> attribs;

                    attribs.push_back(GLX_CONTEXT_MAJOR_VERSION_ARB);
                    attribs.push_back(m_settings.major);
                    attribs.push_back(GLX_CONTEXT_MINOR_VERSION_ARB);
                    attribs.push_back(m_settings.minor);

                    if(isSupported("GLX_ARB_create_context_profile"))
                    {
                        int flags   = 0;
                        int profile = (m_settings.flags & ContextSettings::Compatibility) ? GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB : GLX_CONTEXT_CORE_PROFILE_BIT_ARB;

                        if(m_settings.flags & ContextSettings::Debug)
                        {
                            flags |= GLX_CONTEXT_DEBUG_BIT_ARB;
                        }

                        if(m_settings.flags & ContextSettings::ForwardCompatible)
                        {
                            flags |= GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
                        }

                        attribs.push_back(GLX_CONTEXT_PROFILE_MASK_ARB);
                        attribs.push_back(profile);
                        attribs.push_back(GLX_CONTEXT_FLAGS_ARB);
                        attribs.push_back(flags);
                    }

                    attribs.push_back(0);

                    m_render = glXCreateContextAttribs(m_display->getHandler(), m_config, sharedHandler, True, &attribs[0]);

                    if(!m_render)
                    {
                        if(m_settings.minor == 0)
                        {
                            m_settings.major -= 1;
                            m_settings.minor  = 9;
                        }
                        else
                        {
                            m_settings.minor -= 1;
                        }
                    }
                }while(!m_render && m_settings.major >= 1);
            }

            if(!m_render)
            {
                ErrorHandler handler;
                m_render = glXCreateNewContext(m_display->getHandler(), m_config, GLX_RGBA_TYPE, sharedHandler, True);
            }

            m_isDirect = glXIsDirect(m_display->getHandler(), m_render);
        }
    }
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageReadMagnitudeAndPhaseWriteComplexTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2006 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

/** Example illustrating use of functions to convert between complex valued
 * voxels, magnitude and phase, and real and imaginary representations.
 *
 * \author Simon K. Warfield simon.warfield@childrens.harvard.edu
 *
 * \note Attribution Notice. This research work was made possible by Grant
 * Number R01 RR021885 (PI Simon K. Warfield, Ph.D.) from
 * the National Center for Research Resources (NCRR), a component of the
 * National Institutes of Health (NIH).  Its contents are solely the
 * responsibility of the authors and do not necessarily represent the
 * official view of NCRR or NIH.
 *
 */

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkMagnitudeAndPhaseToComplexImageFilter.h"

int itkImageReadMagnitudeAndPhaseWriteComplexTest( int argc, char * argv[] )
{
  if( argc != 4 )
    {
    std::cerr << "Usage: " << argv[0] << " inputMagnitude inputPhase outputComplex" << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int Dimension = 2;

  typedef float InputPixelType;
  typedef float OutputPixelType;
  typedef itk::Image< InputPixelType  ,  Dimension > InputImageType;
  typedef itk::Image< std::complex<OutputPixelType> ,  Dimension > OutputImageType;
  typedef itk::ImageFileReader< InputImageType > ReaderType;
  typedef itk::ImageFileWriter< OutputImageType > WriterType;

  typedef itk::MagnitudeAndPhaseToComplexImageFilter <
    InputPixelType, InputPixelType, OutputPixelType, Dimension > MagnitudeAndPhase2ComplexFilterType;

  ReaderType::Pointer readerReal = ReaderType::New();
  ReaderType::Pointer readerImag = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();
  MagnitudeAndPhase2ComplexFilterType::Pointer MagnitudeAndPhase2Complex = MagnitudeAndPhase2ComplexFilterType::New();

  readerReal->SetFileName( argv[1] );
  readerImag->SetFileName( argv[2] );
  writer->SetFileName( argv[3] );

// Read the image and get its size
  readerReal->Update();
  readerImag->Update();

  MagnitudeAndPhase2Complex->SetInput1(readerReal->GetOutput());
  MagnitudeAndPhase2Complex->SetInput2(readerImag->GetOutput());

  writer->SetInput(MagnitudeAndPhase2Complex->GetOutput());

  try
    {
    writer->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Error writing the magnitude image: " << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}

<commit_msg>STYLE: Fixing typedefs alignment.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageReadMagnitudeAndPhaseWriteComplexTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/

#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

/** Example illustrating use of functions to convert between complex valued
 * voxels, magnitude and phase, and real and imaginary representations.
 *
 * \author Simon K. Warfield simon.warfield@childrens.harvard.edu
 *
 * \note Attribution Notice. This research work was made possible by Grant
 * Number R01 RR021885 (PI Simon K. Warfield, Ph.D.) from
 * the National Center for Research Resources (NCRR), a component of the
 * National Institutes of Health (NIH).  Its contents are solely the
 * responsibility of the authors and do not necessarily represent the
 * official view of NCRR or NIH.
 *
 */

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkMagnitudeAndPhaseToComplexImageFilter.h"

int itkImageReadMagnitudeAndPhaseWriteComplexTest( int argc, char * argv[] )
{
  if( argc != 4 )
    {
    std::cerr << "Usage: " << argv[0] << " inputMagnitude inputPhase outputComplex" << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int Dimension = 2;

  typedef float InputPixelType;
  typedef float OutputPixelType;

  typedef itk::Image< InputPixelType  ,  Dimension >                    InputImageType;
  typedef itk::Image< std::complex<OutputPixelType> ,  Dimension >      OutputImageType;

  typedef itk::ImageFileReader< InputImageType >      ReaderType;
  typedef itk::ImageFileWriter< OutputImageType >     WriterType;

  typedef itk::MagnitudeAndPhaseToComplexImageFilter <
    InputPixelType, InputPixelType, OutputPixelType, Dimension > MagnitudeAndPhase2ComplexFilterType;

  ReaderType::Pointer readerReal = ReaderType::New();
  ReaderType::Pointer readerImag = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();
  MagnitudeAndPhase2ComplexFilterType::Pointer MagnitudeAndPhase2Complex = MagnitudeAndPhase2ComplexFilterType::New();

  readerReal->SetFileName( argv[1] );
  readerImag->SetFileName( argv[2] );
  writer->SetFileName( argv[3] );

// Read the image and get its size
  readerReal->Update();
  readerImag->Update();

  MagnitudeAndPhase2Complex->SetInput1(readerReal->GetOutput());
  MagnitudeAndPhase2Complex->SetInput2(readerImag->GetOutput());

  writer->SetInput(MagnitudeAndPhase2Complex->GetOutput());

  try
    {
    writer->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Error writing the magnitude image: " << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "ChromiumBridge.h"

#include <googleurl/src/url_util.h>

#include "WebClipboard.h"
#include "WebData.h"
#include "WebImage.h"
#include "WebKit.h"
#include "WebKitClient.h"
#include "WebMimeRegistry.h"
#include "WebPluginListBuilderImpl.h"
#include "WebString.h"
#include "WebURL.h"

#if PLATFORM(WIN_OS)
#include "WebRect.h"
#include "WebSandboxSupport.h"
#include "WebThemeEngine.h"
#endif

#include "BitmapImage.h"
#include "GraphicsContext.h"
#include "KURL.h"
#include "NativeImageSkia.h"
#include "NotImplemented.h"
#include "PlatformContextSkia.h"
#include "PluginData.h"
#include <wtf/Assertions.h>

// We are part of the WebKit implementation.
using namespace WebKit;

namespace WebCore {

// Clipboard ------------------------------------------------------------------

COMPILE_ASSERT(
    int(PasteboardPrivate::HTMLFormat) == int(WebClipboard::FormatHTML),
    FormatHTML);
COMPILE_ASSERT(
    int(PasteboardPrivate::BookmarkFormat) == int(WebClipboard::FormatBookmark),
    FormatBookmark);
COMPILE_ASSERT(
    int(PasteboardPrivate::WebSmartPasteFormat) == int(WebClipboard::FormatSmartPaste),
    FormatSmartPaste);

bool ChromiumBridge::clipboardIsFormatAvailable(
    PasteboardPrivate::ClipboardFormat format)
{
    return webKitClient()->clipboard()->isFormatAvailable(
        static_cast<WebClipboard::Format>(format));
}

String ChromiumBridge::clipboardReadPlainText()
{
    return webKitClient()->clipboard()->readPlainText();
}

void ChromiumBridge::clipboardReadHTML(String* htmlText, KURL* sourceURL)
{
    WebURL url;
    *htmlText = webKitClient()->clipboard()->readHTML(&url);
    *sourceURL = url;
}

void ChromiumBridge::clipboardWriteSelection(const String& htmlText,
                                             const KURL& sourceURL,
                                             const String& plainText,
                                             bool writeSmartPaste)
{
    webKitClient()->clipboard()->writeHTML(
        htmlText, sourceURL, plainText, writeSmartPaste);
}

void ChromiumBridge::clipboardWriteURL(const KURL& url, const String& title)
{
    webKitClient()->clipboard()->writeURL(url, title);
}

void ChromiumBridge::clipboardWriteImage(const NativeImageSkia* image,
                                         const KURL& sourceURL,
                                         const String& title)
{
#if WEBKIT_USING_SKIA
    webKitClient()->clipboard()->writeImage(
        WebImage(*image), sourceURL, title);
#else
    // FIXME clipboardWriteImage probably shouldn't take a NativeImageSkia
    notImplemented();
#endif
}

// Cookies --------------------------------------------------------------------

void ChromiumBridge::setCookies(const KURL& url,
                                const KURL& firstPartyForCookies,
                                const String& cookie)
{
    webKitClient()->setCookies(url, firstPartyForCookies, cookie);
}

String ChromiumBridge::cookies(const KURL& url,
                               const KURL& firstPartyForCookies)
{
    return webKitClient()->cookies(url, firstPartyForCookies);
}

// DNS ------------------------------------------------------------------------

void ChromiumBridge::prefetchDNS(const String& hostname)
{
    webKitClient()->prefetchHostName(hostname);
}

// Font -----------------------------------------------------------------------

#if defined(OS_WIN)
bool ChromiumBridge::ensureFontLoaded(HFONT font)
{
    return webKitClient()->sandboxSupport()->ensureFontLoaded(font);
}
#endif

// Language -------------------------------------------------------------------

String ChromiumBridge::computedDefaultLanguage()
{
    return webKitClient()->defaultLocale();
}

// LayoutTestMode -------------------------------------------------------------

bool ChromiumBridge::layoutTestMode()
{
    return WebKit::layoutTestMode();
}

// MimeType -------------------------------------------------------------------

bool ChromiumBridge::isSupportedImageMIMEType(const String& mimeType)
{
    return webKitClient()->mimeRegistry()->supportsImageMIMEType(mimeType);
}

bool ChromiumBridge::isSupportedJavaScriptMIMEType(const String& mimeType)
{
    return webKitClient()->mimeRegistry()->supportsJavaScriptMIMEType(mimeType);
}

bool ChromiumBridge::isSupportedNonImageMIMEType(const String& mimeType)
{
    return webKitClient()->mimeRegistry()->supportsNonImageMIMEType(mimeType);
}

String ChromiumBridge::mimeTypeForExtension(const String& extension)
{
    return webKitClient()->mimeRegistry()->mimeTypeForExtension(extension);
}

String ChromiumBridge::mimeTypeFromFile(const String& path)
{
    return webKitClient()->mimeRegistry()->mimeTypeFromFile(path);
}

String ChromiumBridge::preferredExtensionForMIMEType(const String& mimeType)
{
    return webKitClient()->mimeRegistry()->preferredExtensionForMIMEType(mimeType);
}

// Plugin ---------------------------------------------------------------------

bool ChromiumBridge::plugins(bool refresh, Vector<PluginInfo*>* results)
{
    WebPluginListBuilderImpl builder(results);
    webKitClient()->getPluginList(refresh, &builder);
    return true;  // FIXME: There is no need for this function to return a value.
}

// Resources ------------------------------------------------------------------

PassRefPtr<Image> ChromiumBridge::loadPlatformImageResource(const char* name)
{
    const WebData& resource = webKitClient()->loadResource(name);
    if (resource.isEmpty())
        return Image::nullImage();

    RefPtr<Image> image = BitmapImage::create();
    image->setData(resource, true);
    return image;
}

// SharedTimers ---------------------------------------------------------------

void ChromiumBridge::setSharedTimerFiredFunction(void (*func)())
{
    webKitClient()->setSharedTimerFiredFunction(func);
}

void ChromiumBridge::setSharedTimerFireTime(double fireTime)
{
    webKitClient()->setSharedTimerFireTime(fireTime);
}

void ChromiumBridge::stopSharedTimer()
{
    webKitClient()->stopSharedTimer();
}

// StatsCounters --------------------------------------------------------------

void ChromiumBridge::decrementStatsCounter(const char* name)
{
    webKitClient()->decrementStatsCounter(name);
}

void ChromiumBridge::incrementStatsCounter(const char* name)
{
    webKitClient()->incrementStatsCounter(name);
}

// Sudden Termination ---------------------------------------------------------

void ChromiumBridge::suddenTerminationChanged(bool enabled)
{
    webKitClient()->suddenTerminationChanged(enabled);
}

// SystemTime -----------------------------------------------------------------

double ChromiumBridge::currentTime()
{
    return webKitClient()->currentTime();
}

// Theming --------------------------------------------------------------------

#if PLATFORM(WIN_OS)

void ChromiumBridge::paintButton(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect)
{
    webKitClient()->themeEngine()->paintButton(
        gc->platformContext()->canvas(), part, state, classicState, rect);
}

void ChromiumBridge::paintMenuList(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect)
{
    webKitClient()->themeEngine()->paintMenuList(
        gc->platformContext()->canvas(), part, state, classicState, rect);
}

void ChromiumBridge::paintScrollbarArrow(
    GraphicsContext* gc, int state, int classicState,
    const IntRect& rect)
{
    webKitClient()->themeEngine()->paintScrollbarArrow(
        gc->platformContext()->canvas(), state, classicState, rect);
}

void ChromiumBridge::paintScrollbarThumb(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect)
{
    webKitClient()->themeEngine()->paintScrollbarThumb(
        gc->platformContext()->canvas(), part, state, classicState, rect);
}

void ChromiumBridge::paintScrollbarTrack(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect, const IntRect& alignRect)
{
    webKitClient()->themeEngine()->paintScrollbarTrack(
        gc->platformContext()->canvas(), part, state, classicState, rect,
        alignRect);
}

void ChromiumBridge::paintTextField(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect, const Color& color, bool fillContentArea,
    bool drawEdges)
{
    webKitClient()->themeEngine()->paintTextField(
        gc->platformContext()->canvas(), part, state, classicState, rect,
        color.rgb(), fillContentArea, drawEdges);
}

void ChromiumBridge::paintTrackbar(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect)
{
    webKitClient()->themeEngine()->paintTrackbar(
        gc->platformContext()->canvas(), part, state, classicState, rect);
}

#endif

// Trace Event ----------------------------------------------------------------

void ChromiumBridge::traceEventBegin(const char* name, void* id, const char* extra)
{
    webKitClient()->traceEventBegin(name, id, extra);
}

void ChromiumBridge::traceEventEnd(const char* name, void* id, const char* extra)
{
    webKitClient()->traceEventEnd(name, id, extra);
}

// Visited Links --------------------------------------------------------------

WebCore::LinkHash ChromiumBridge::visitedLinkHash(const UChar* url,
                                                  unsigned length)
{
    url_canon::RawCanonOutput<2048> buffer;
    url_parse::Parsed parsed;
    if (!url_util::Canonicalize(url, length, NULL, &buffer, &parsed))
        return 0;  // Invalid URLs are unvisited.
    return webKitClient()->visitedLinkHash(buffer.data(), buffer.length());
}

WebCore::LinkHash ChromiumBridge::visitedLinkHash(const WebCore::KURL& base,
                                                  const WebCore::AtomicString& attributeURL)
{
    // Resolve the relative URL using googleurl and pass the absolute URL up to
    // the embedder. We could create a GURL object from the base and resolve
    // the relative URL that way, but calling the lower-level functions
    // directly saves us the string allocation in most cases.
    url_canon::RawCanonOutput<2048> buffer;
    url_parse::Parsed parsed;

#if USE(GOOGLEURL)
    const WebCore::CString& cstr = base.utf8String();
    const char* data = cstr.data();
    int length = cstr.length();
    const url_parse::Parsed& srcParsed = base.parsed();
#else
    // When we're not using GoogleURL, first canonicalize it so we can resolve it
    // below.
    url_canon::RawCanonOutput<2048> srcCanon;
    url_parse::Parsed srcParsed;
    WebCore::String str = base.string();
    if (!url_util::Canonicalize(str.characters(), str.length(), NULL, &srcCanon, &srcParsed))
        return 0;
    const char* data = srcCanon.data();
    int length = srcCanon.length();
#endif

    if (!url_util::ResolveRelative(data, length, srcParsed, attributeURL.characters(),
                                   attributeURL.length(), NULL, &buffer, &parsed))
        return 0;  // Invalid resolved URL.

    return webKitClient()->visitedLinkHash(buffer.data(), buffer.length());
}

bool ChromiumBridge::isLinkVisited(WebCore::LinkHash visitedLinkHash)
{
    return webKitClient()->isLinkVisited(visitedLinkHash);
}

} // namespace WebCore
<commit_msg>Let ChromiumBridge::paintTextField check if the Color object passed in is valid or not. If not valid, just pass white to ThemeEngine.<commit_after>/*
 * Copyright (C) 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "ChromiumBridge.h"

#include <googleurl/src/url_util.h>

#include "WebClipboard.h"
#include "WebData.h"
#include "WebImage.h"
#include "WebKit.h"
#include "WebKitClient.h"
#include "WebMimeRegistry.h"
#include "WebPluginListBuilderImpl.h"
#include "WebString.h"
#include "WebURL.h"

#if PLATFORM(WIN_OS)
#include "WebRect.h"
#include "WebSandboxSupport.h"
#include "WebThemeEngine.h"
#endif

#include "BitmapImage.h"
#include "GraphicsContext.h"
#include "KURL.h"
#include "NativeImageSkia.h"
#include "NotImplemented.h"
#include "PlatformContextSkia.h"
#include "PluginData.h"
#include <wtf/Assertions.h>

// We are part of the WebKit implementation.
using namespace WebKit;

namespace WebCore {

// Clipboard ------------------------------------------------------------------

COMPILE_ASSERT(
    int(PasteboardPrivate::HTMLFormat) == int(WebClipboard::FormatHTML),
    FormatHTML);
COMPILE_ASSERT(
    int(PasteboardPrivate::BookmarkFormat) == int(WebClipboard::FormatBookmark),
    FormatBookmark);
COMPILE_ASSERT(
    int(PasteboardPrivate::WebSmartPasteFormat) == int(WebClipboard::FormatSmartPaste),
    FormatSmartPaste);

bool ChromiumBridge::clipboardIsFormatAvailable(
    PasteboardPrivate::ClipboardFormat format)
{
    return webKitClient()->clipboard()->isFormatAvailable(
        static_cast<WebClipboard::Format>(format));
}

String ChromiumBridge::clipboardReadPlainText()
{
    return webKitClient()->clipboard()->readPlainText();
}

void ChromiumBridge::clipboardReadHTML(String* htmlText, KURL* sourceURL)
{
    WebURL url;
    *htmlText = webKitClient()->clipboard()->readHTML(&url);
    *sourceURL = url;
}

void ChromiumBridge::clipboardWriteSelection(const String& htmlText,
                                             const KURL& sourceURL,
                                             const String& plainText,
                                             bool writeSmartPaste)
{
    webKitClient()->clipboard()->writeHTML(
        htmlText, sourceURL, plainText, writeSmartPaste);
}

void ChromiumBridge::clipboardWriteURL(const KURL& url, const String& title)
{
    webKitClient()->clipboard()->writeURL(url, title);
}

void ChromiumBridge::clipboardWriteImage(const NativeImageSkia* image,
                                         const KURL& sourceURL,
                                         const String& title)
{
#if WEBKIT_USING_SKIA
    webKitClient()->clipboard()->writeImage(
        WebImage(*image), sourceURL, title);
#else
    // FIXME clipboardWriteImage probably shouldn't take a NativeImageSkia
    notImplemented();
#endif
}

// Cookies --------------------------------------------------------------------

void ChromiumBridge::setCookies(const KURL& url,
                                const KURL& firstPartyForCookies,
                                const String& cookie)
{
    webKitClient()->setCookies(url, firstPartyForCookies, cookie);
}

String ChromiumBridge::cookies(const KURL& url,
                               const KURL& firstPartyForCookies)
{
    return webKitClient()->cookies(url, firstPartyForCookies);
}

// DNS ------------------------------------------------------------------------

void ChromiumBridge::prefetchDNS(const String& hostname)
{
    webKitClient()->prefetchHostName(hostname);
}

// Font -----------------------------------------------------------------------

#if defined(OS_WIN)
bool ChromiumBridge::ensureFontLoaded(HFONT font)
{
    return webKitClient()->sandboxSupport()->ensureFontLoaded(font);
}
#endif

// Language -------------------------------------------------------------------

String ChromiumBridge::computedDefaultLanguage()
{
    return webKitClient()->defaultLocale();
}

// LayoutTestMode -------------------------------------------------------------

bool ChromiumBridge::layoutTestMode()
{
    return WebKit::layoutTestMode();
}

// MimeType -------------------------------------------------------------------

bool ChromiumBridge::isSupportedImageMIMEType(const String& mimeType)
{
    return webKitClient()->mimeRegistry()->supportsImageMIMEType(mimeType);
}

bool ChromiumBridge::isSupportedJavaScriptMIMEType(const String& mimeType)
{
    return webKitClient()->mimeRegistry()->supportsJavaScriptMIMEType(mimeType);
}

bool ChromiumBridge::isSupportedNonImageMIMEType(const String& mimeType)
{
    return webKitClient()->mimeRegistry()->supportsNonImageMIMEType(mimeType);
}

String ChromiumBridge::mimeTypeForExtension(const String& extension)
{
    return webKitClient()->mimeRegistry()->mimeTypeForExtension(extension);
}

String ChromiumBridge::mimeTypeFromFile(const String& path)
{
    return webKitClient()->mimeRegistry()->mimeTypeFromFile(path);
}

String ChromiumBridge::preferredExtensionForMIMEType(const String& mimeType)
{
    return webKitClient()->mimeRegistry()->preferredExtensionForMIMEType(mimeType);
}

// Plugin ---------------------------------------------------------------------

bool ChromiumBridge::plugins(bool refresh, Vector<PluginInfo*>* results)
{
    WebPluginListBuilderImpl builder(results);
    webKitClient()->getPluginList(refresh, &builder);
    return true;  // FIXME: There is no need for this function to return a value.
}

// Resources ------------------------------------------------------------------

PassRefPtr<Image> ChromiumBridge::loadPlatformImageResource(const char* name)
{
    const WebData& resource = webKitClient()->loadResource(name);
    if (resource.isEmpty())
        return Image::nullImage();

    RefPtr<Image> image = BitmapImage::create();
    image->setData(resource, true);
    return image;
}

// SharedTimers ---------------------------------------------------------------

void ChromiumBridge::setSharedTimerFiredFunction(void (*func)())
{
    webKitClient()->setSharedTimerFiredFunction(func);
}

void ChromiumBridge::setSharedTimerFireTime(double fireTime)
{
    webKitClient()->setSharedTimerFireTime(fireTime);
}

void ChromiumBridge::stopSharedTimer()
{
    webKitClient()->stopSharedTimer();
}

// StatsCounters --------------------------------------------------------------

void ChromiumBridge::decrementStatsCounter(const char* name)
{
    webKitClient()->decrementStatsCounter(name);
}

void ChromiumBridge::incrementStatsCounter(const char* name)
{
    webKitClient()->incrementStatsCounter(name);
}

// Sudden Termination ---------------------------------------------------------

void ChromiumBridge::suddenTerminationChanged(bool enabled)
{
    webKitClient()->suddenTerminationChanged(enabled);
}

// SystemTime -----------------------------------------------------------------

double ChromiumBridge::currentTime()
{
    return webKitClient()->currentTime();
}

// Theming --------------------------------------------------------------------

#if PLATFORM(WIN_OS)

void ChromiumBridge::paintButton(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect)
{
    webKitClient()->themeEngine()->paintButton(
        gc->platformContext()->canvas(), part, state, classicState, rect);
}

void ChromiumBridge::paintMenuList(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect)
{
    webKitClient()->themeEngine()->paintMenuList(
        gc->platformContext()->canvas(), part, state, classicState, rect);
}

void ChromiumBridge::paintScrollbarArrow(
    GraphicsContext* gc, int state, int classicState,
    const IntRect& rect)
{
    webKitClient()->themeEngine()->paintScrollbarArrow(
        gc->platformContext()->canvas(), state, classicState, rect);
}

void ChromiumBridge::paintScrollbarThumb(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect)
{
    webKitClient()->themeEngine()->paintScrollbarThumb(
        gc->platformContext()->canvas(), part, state, classicState, rect);
}

void ChromiumBridge::paintScrollbarTrack(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect, const IntRect& alignRect)
{
    webKitClient()->themeEngine()->paintScrollbarTrack(
        gc->platformContext()->canvas(), part, state, classicState, rect,
        alignRect);
}

void ChromiumBridge::paintTextField(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect, const Color& color, bool fillContentArea,
    bool drawEdges)
{
    // Fallback to white when |color| is invalid.
    RGBA32 backgroundColor = color.isValid() ? color.rgb() : Color::white;

    webKitClient()->themeEngine()->paintTextField(
        gc->platformContext()->canvas(), part, state, classicState, rect,
        backgroundColor, fillContentArea, drawEdges);
}

void ChromiumBridge::paintTrackbar(
    GraphicsContext* gc, int part, int state, int classicState,
    const IntRect& rect)
{
    webKitClient()->themeEngine()->paintTrackbar(
        gc->platformContext()->canvas(), part, state, classicState, rect);
}

#endif

// Trace Event ----------------------------------------------------------------

void ChromiumBridge::traceEventBegin(const char* name, void* id, const char* extra)
{
    webKitClient()->traceEventBegin(name, id, extra);
}

void ChromiumBridge::traceEventEnd(const char* name, void* id, const char* extra)
{
    webKitClient()->traceEventEnd(name, id, extra);
}

// Visited Links --------------------------------------------------------------

WebCore::LinkHash ChromiumBridge::visitedLinkHash(const UChar* url,
                                                  unsigned length)
{
    url_canon::RawCanonOutput<2048> buffer;
    url_parse::Parsed parsed;
    if (!url_util::Canonicalize(url, length, NULL, &buffer, &parsed))
        return 0;  // Invalid URLs are unvisited.
    return webKitClient()->visitedLinkHash(buffer.data(), buffer.length());
}

WebCore::LinkHash ChromiumBridge::visitedLinkHash(const WebCore::KURL& base,
                                                  const WebCore::AtomicString& attributeURL)
{
    // Resolve the relative URL using googleurl and pass the absolute URL up to
    // the embedder. We could create a GURL object from the base and resolve
    // the relative URL that way, but calling the lower-level functions
    // directly saves us the string allocation in most cases.
    url_canon::RawCanonOutput<2048> buffer;
    url_parse::Parsed parsed;

#if USE(GOOGLEURL)
    const WebCore::CString& cstr = base.utf8String();
    const char* data = cstr.data();
    int length = cstr.length();
    const url_parse::Parsed& srcParsed = base.parsed();
#else
    // When we're not using GoogleURL, first canonicalize it so we can resolve it
    // below.
    url_canon::RawCanonOutput<2048> srcCanon;
    url_parse::Parsed srcParsed;
    WebCore::String str = base.string();
    if (!url_util::Canonicalize(str.characters(), str.length(), NULL, &srcCanon, &srcParsed))
        return 0;
    const char* data = srcCanon.data();
    int length = srcCanon.length();
#endif

    if (!url_util::ResolveRelative(data, length, srcParsed, attributeURL.characters(),
                                   attributeURL.length(), NULL, &buffer, &parsed))
        return 0;  // Invalid resolved URL.

    return webKitClient()->visitedLinkHash(buffer.data(), buffer.length());
}

bool ChromiumBridge::isLinkVisited(WebCore::LinkHash visitedLinkHash)
{
    return webKitClient()->isLinkVisited(visitedLinkHash);
}

} // namespace WebCore
<|endoftext|>


<commit_before><commit_msg>Fix a FORWARD_NULL defect reported by Coverity.<commit_after><|endoftext|>


<commit_before>/*
  Copyright 2003 John Plevyak
*/

/* UnionFind by Tarjan (adapted) */

#include "geysa.h"
#include "pattern.h"

uint prime2[] = {
  1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191,
  16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143,
  4194301, 8388593, 16777213, 33554393, 67108859, 134217689,
  268435399, 536870909
};

// binary search over intervals
static int
i_find(Intervals *i, int x) {
  assert(i->n);
  int l = 0, h = i->n;
 Lrecurse:
  if (h <= l + 2) {
    if (h <= l)
      return -(l + 1);
    if (x < i->v[l] || x > i->v[l + 1])
      return -(l + 1);
    return h;
  }
  int m = (((h - l) / 4) * 2) + l;
  if (x > i->v[m + 1]) {
    l = m;
    goto Lrecurse;
  }
  if (x < i->v[m]) {
    h = m;
    goto Lrecurse;
  }
  return (l + 1);
}

int
Intervals::in(int x) {
  if (!n)
    return 0;
  if (i_find(this, x) > 0)
    return 1;
  return 0;
}

// insert into interval with merge
void
Intervals::insert(int x) {
  if (!n) {
    add(x);
    add(x);
    return;
  }
  int l = i_find(this, x);
  if (l > 0)
    return;
  l = -l - 1;

  if (x > v[l + 1]) {
    if (x == v[l + 1] + 1) {
      v[l + 1]++;
      goto Lmerge;
    }
    l += 2;
    if (l < n) {
      if (x == v[l] - 1) {
        v[l]--;
        goto Lmerge;
      }
    }
    goto Lmore;
  } else {
    assert(x < v[l]);
    if (x == v[l] - 1) {
      v[l]--;
      goto Lmerge;
    }
    if (!l)
      goto Lmore;
    l -= 2;
    if (x == v[l + 1] + 1) {
      v[l + 1]++;
      goto Lmerge;
    }
  }
 Lmore:
  fill(n + 2);
  if (n - 2 - l > 0)
    memmove(v + l + 2, v + l, sizeof(int) * (n - 2 - l));
  v[l] = x;
  v[l+1] = x;
  return;
 Lmerge:
  if (l) {
    if (v[l] - v[l-1] < 2) {
      l -= 2;
      goto Ldomerge;
    }
  }
  if (l < n - 2) {
    if (v[l + 2] - v[l + 1] < 2)
      goto Ldomerge;
  }
  return;
 Ldomerge:
  memmove(v + l + 1, v + l + 3, sizeof(int) * (n - 3 - l));
  n -= 2;
  goto Lmerge;
}

void
UnionFind::size(int s) {
  int nn = n;
  fill(s);
  for (int i = nn; i < n; i++)
    v[i] = -1;
}

int
UnionFind::find(int n) {
  int i, t;
  for (i = n; v[i] >= 0; i = v[i]);
  while (v[n] >= 0) {
    t = n;
    n = v[n];
    v[t] = i;
  }
  return i;
}

void
UnionFind::unify(int n, int m) {
  n = find(n);
  m = find(m);
  if (n != m) {
    if (v[m] < v[n]) {
      v[m] += (v[n] - 1);
      v[n] = m;
    } else {
      v[n] += (v[m] - 1);
      v[m] = n;
    }
  }
}

#ifdef TEST_LIB
void
test_vec() {
  Vec<void *> v, vv, vvv;
  int tt = 99 * 50, t = 0;

  for (int i = 0; i < 100; i++)
    v.add((void*)i);
  for (int i = 0; i < 100; i++)
    t += (int)v.v[i];
  assert(t == tt);

  t = 0;
  for (int i = 1; i < 100; i++)
    vv.set_add((void*)i);
  for (int i = 1; i < 100; i++)
    vvv.set_add((void*)i);
  for (int i = 1; i < 100; i++)
    vvv.set_add((void*)(i * 1000));
  vv.set_union(vvv);
  for (int i = 0; i < vv.n; i++)
    if (vv.v[i])
      t += (int)vv.v[i];
  assert(t == tt + 1000 * tt);

  Intervals in;
  in.insert(1);
  assert(in.n == 2);
  in.insert(2);
  assert(in.n == 2);
  in.insert(6);
  assert(in.n == 4);
  in.insert(7);
  assert(in.n == 4);
  in.insert(9);
  assert(in.n == 6);
  in.insert(4);
  assert(in.n == 8);
  in.insert(5);
  assert(in.n == 6);
  in.insert(3);
  assert(in.n == 4);
  in.insert(8);
  assert(in.n == 2);

  UnionFind uf;
  uf.size(4);
  uf.unify(0,1);
  uf.unify(2,3);
  assert(uf.find(2) == uf.find(3));
  assert(uf.find(0) == uf.find(1));
  assert(uf.find(0) != uf.find(3));
  assert(uf.find(1) != uf.find(3));
  assert(uf.find(1) != uf.find(2));
  assert(uf.find(0) != uf.find(2));
  uf.unify(1,2);
  assert(uf.find(0) == uf.find(3));
  assert(uf.find(1) == uf.find(3));
}
#endif
<commit_msg>More x86_64 fixes... should be a clean build now.<commit_after>/*
  Copyright 2003 John Plevyak
*/

/* UnionFind by Tarjan (adapted) */

#include "geysa.h"
#include "pattern.h"

uint prime2[] = {
  1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191,
  16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143,
  4194301, 8388593, 16777213, 33554393, 67108859, 134217689,
  268435399, 536870909
};

// binary search over intervals
static int
i_find(Intervals *i, int x) {
  assert(i->n);
  int l = 0, h = i->n;
 Lrecurse:
  if (h <= l + 2) {
    if (h <= l)
      return -(l + 1);
    if (x < i->v[l] || x > i->v[l + 1])
      return -(l + 1);
    return h;
  }
  int m = (((h - l) / 4) * 2) + l;
  if (x > i->v[m + 1]) {
    l = m;
    goto Lrecurse;
  }
  if (x < i->v[m]) {
    h = m;
    goto Lrecurse;
  }
  return (l + 1);
}

int
Intervals::in(int x) {
  if (!n)
    return 0;
  if (i_find(this, x) > 0)
    return 1;
  return 0;
}

// insert into interval with merge
void
Intervals::insert(int x) {
  if (!n) {
    add(x);
    add(x);
    return;
  }
  int l = i_find(this, x);
  if (l > 0)
    return;
  l = -l - 1;

  if (x > v[l + 1]) {
    if (x == v[l + 1] + 1) {
      v[l + 1]++;
      goto Lmerge;
    }
    l += 2;
    if (l < n) {
      if (x == v[l] - 1) {
        v[l]--;
        goto Lmerge;
      }
    }
    goto Lmore;
  } else {
    assert(x < v[l]);
    if (x == v[l] - 1) {
      v[l]--;
      goto Lmerge;
    }
    if (!l)
      goto Lmore;
    l -= 2;
    if (x == v[l + 1] + 1) {
      v[l + 1]++;
      goto Lmerge;
    }
  }
 Lmore:
  fill(n + 2);
  if (n - 2 - l > 0)
    memmove(v + l + 2, v + l, sizeof(int) * (n - 2 - l));
  v[l] = x;
  v[l+1] = x;
  return;
 Lmerge:
  if (l) {
    if (v[l] - v[l-1] < 2) {
      l -= 2;
      goto Ldomerge;
    }
  }
  if (l < n - 2) {
    if (v[l + 2] - v[l + 1] < 2)
      goto Ldomerge;
  }
  return;
 Ldomerge:
  memmove(v + l + 1, v + l + 3, sizeof(int) * (n - 3 - l));
  n -= 2;
  goto Lmerge;
}

void
UnionFind::size(int s) {
  int nn = n;
  fill(s);
  for (int i = nn; i < n; i++)
    v[i] = -1;
}

int
UnionFind::find(int n) {
  int i, t;
  for (i = n; v[i] >= 0; i = v[i]);
  while (v[n] >= 0) {
    t = n;
    n = v[n];
    v[t] = i;
  }
  return i;
}

void
UnionFind::unify(int n, int m) {
  n = find(n);
  m = find(m);
  if (n != m) {
    if (v[m] < v[n]) {
      v[m] += (v[n] - 1);
      v[n] = m;
    } else {
      v[n] += (v[m] - 1);
      v[m] = n;
    }
  }
}

#ifdef TEST_LIB
void
test_vec() {
  Vec<void *> v, vv, vvv;
  int tt = 99 * 50, t = 0;

  for (int i = 0; i < 100; i++)
    v.add((void*)(intptr_t)i);
  for (int i = 0; i < 100; i++)
    t += (int)(intptr_t)v.v[i];
  assert(t == tt);

  t = 0;
  for (int i = 1; i < 100; i++)
    vv.set_add((void*)(intptr_t)i);
  for (int i = 1; i < 100; i++)
    vvv.set_add((void*)(intptr_t)i);
  for (int i = 1; i < 100; i++)
    vvv.set_add((void*)(intptr_t)(i * 1000));
  vv.set_union(vvv);
  for (int i = 0; i < vv.n; i++)
    if (vv.v[i])
      t += (int)(intptr_t)vv.v[i];
  assert(t == tt + 1000 * tt);

  Intervals in;
  in.insert(1);
  assert(in.n == 2);
  in.insert(2);
  assert(in.n == 2);
  in.insert(6);
  assert(in.n == 4);
  in.insert(7);
  assert(in.n == 4);
  in.insert(9);
  assert(in.n == 6);
  in.insert(4);
  assert(in.n == 8);
  in.insert(5);
  assert(in.n == 6);
  in.insert(3);
  assert(in.n == 4);
  in.insert(8);
  assert(in.n == 2);

  UnionFind uf;
  uf.size(4);
  uf.unify(0,1);
  uf.unify(2,3);
  assert(uf.find(2) == uf.find(3));
  assert(uf.find(0) == uf.find(1));
  assert(uf.find(0) != uf.find(3));
  assert(uf.find(1) != uf.find(3));
  assert(uf.find(1) != uf.find(2));
  assert(uf.find(0) != uf.find(2));
  uf.unify(1,2);
  assert(uf.find(0) == uf.find(3));
  assert(uf.find(1) == uf.find(3));
}
#endif
<|endoftext|>


<commit_before>//
//  TileRenderer.h
//  G3MiOSSDK
//
//  Created by Agustín Trujillo Pino on 12/06/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#ifndef G3MiOSSDK_TileRenderer_h
#define G3MiOSSDK_TileRenderer_h

#include "Renderer.hpp"

class Tile;
class TileTessellator;
class TileTexturizer;

#include "Sector.hpp"
#include <vector>

#include "Tile.hpp"

//class TileCacheEntry {
//public:
//  Tile* _tile;
//  long  _timestamp;
//
//  TileCacheEntry(Tile* tile,
//                 long  timestamp) :
//  _tile(tile),
//  _timestamp(timestamp)
//  {
//
//  }
//
//  ~TileCacheEntry() {
//    if (_tile != NULL) {
//      delete _tile;
//    }
//  }
//};
//
//class TileRenderer;
//
//class TilesCache {
//private:
//  TileRenderer*                _tileRenderer;
//  const int                    _maxElements;
//  std::vector<TileCacheEntry*> _entries;
//
//  long _tsCounter;
//
//public:
//  TilesCache(TileRenderer* tileRenderer, int maxElements) :
//  _tileRenderer(tileRenderer),
//  _maxElements(maxElements),
//  _tsCounter(0)
//  {
//
//  }
//
//  Tile* getTile(const int level,
//                const int row, const int column);
//
//  void putTile(Tile* tile);
//
//};

class TileParameters {
public:
  const Sector _topSector;
  const int    _splitsByLatitude;
  const int    _splitsByLongitude;
  const int    _topLevel;
  const int    _maxLevel;
  const int    _tileTextureHeight;
  const int    _tileTextureWidth;
  const int    _tileResolution;

  TileParameters(const Sector topSector,
                 const int    splitsByLatitude,
                 const int    splitsByLongitude,
                 const int    topLevel,
                 const int    maxLevel,
                 const int    tileTextureHeight,
                 const int    tileTextureWidth,
                 const int    tileResolution) :
  _topSector(topSector),
  _splitsByLatitude(splitsByLatitude),
  _splitsByLongitude(splitsByLongitude),
  _topLevel(topLevel),
  _maxLevel(maxLevel),
  _tileTextureHeight(tileTextureHeight),
  _tileTextureWidth(tileTextureWidth),
  _tileResolution(tileResolution)
  {

  }

  static TileParameters* createDefault() {
    const int K = 1;
    const int splitsByLatitude = 2 * K;
    const int splitsByLongitude = 4 * K;
    const int topLevel = 0;
    const int maxLevel = 8;
    const int tileTextureHeight = 256;
    const int tileTextureWidth = 256;
    const int tRes = 16;

    return new TileParameters(Sector::fullSphere(),
                              splitsByLatitude,
                              splitsByLongitude,
                              topLevel,
                              maxLevel,
                              tileTextureHeight,
                              tileTextureWidth,
                              tRes);
  }
};

class TileRenderer: public Renderer {
private:
  const TileTessellator* _tessellator;
  TileTexturizer*  _texturizer;
  const TileParameters*  _parameters;

  std::vector<Tile*>     _topLevelTiles;

  void clearTopLevelTiles();
  void createTopLevelTiles(const InitializationContext* ic);

public:
  TileRenderer(const TileTessellator* tessellator,
               TileTexturizer*  texturizer,
               const TileParameters* parameters) :
  _tessellator(tessellator),
  _texturizer(texturizer),
  _parameters(parameters)
  {

  }

  ~TileRenderer();

  void initialize(const InitializationContext* ic);

  int render(const RenderContext* rc);

  bool onTouchEvent(const TouchEvent* touchEvent) {
    return false;
  }

  void onResizeViewportEvent(int width, int height) {

  }

};

#endif
<commit_msg>first version of LOD in TiledRenderer<commit_after>//
//  TileRenderer.h
//  G3MiOSSDK
//
//  Created by Agustín Trujillo Pino on 12/06/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#ifndef G3MiOSSDK_TileRenderer_h
#define G3MiOSSDK_TileRenderer_h

#include "Renderer.hpp"

class Tile;
class TileTessellator;
class TileTexturizer;

#include "Sector.hpp"
#include <vector>

#include "Tile.hpp"

//class TileCacheEntry {
//public:
//  Tile* _tile;
//  long  _timestamp;
//
//  TileCacheEntry(Tile* tile,
//                 long  timestamp) :
//  _tile(tile),
//  _timestamp(timestamp)
//  {
//
//  }
//
//  ~TileCacheEntry() {
//    if (_tile != NULL) {
//      delete _tile;
//    }
//  }
//};
//
//class TileRenderer;
//
//class TilesCache {
//private:
//  TileRenderer*                _tileRenderer;
//  const int                    _maxElements;
//  std::vector<TileCacheEntry*> _entries;
//
//  long _tsCounter;
//
//public:
//  TilesCache(TileRenderer* tileRenderer, int maxElements) :
//  _tileRenderer(tileRenderer),
//  _maxElements(maxElements),
//  _tsCounter(0)
//  {
//
//  }
//
//  Tile* getTile(const int level,
//                const int row, const int column);
//
//  void putTile(Tile* tile);
//
//};

class TileParameters {
public:
  const Sector _topSector;
  const int    _splitsByLatitude;
  const int    _splitsByLongitude;
  const int    _topLevel;
  const int    _maxLevel;
  const int    _tileTextureHeight;
  const int    _tileTextureWidth;
  const int    _tileResolution;

  TileParameters(const Sector topSector,
                 const int    splitsByLatitude,
                 const int    splitsByLongitude,
                 const int    topLevel,
                 const int    maxLevel,
                 const int    tileTextureHeight,
                 const int    tileTextureWidth,
                 const int    tileResolution) :
  _topSector(topSector),
  _splitsByLatitude(splitsByLatitude),
  _splitsByLongitude(splitsByLongitude),
  _topLevel(topLevel),
  _maxLevel(maxLevel),
  _tileTextureHeight(tileTextureHeight),
  _tileTextureWidth(tileTextureWidth),
  _tileResolution(tileResolution)
  {

  }

  static TileParameters* createDefault() {
    const int K = 1;
    const int splitsByLatitude = 2 * K;
    const int splitsByLongitude = 4 * K;
    const int topLevel = 0;
    const int maxLevel = 20;
    const int tileTextureHeight = 256;
    const int tileTextureWidth = 256;
    const int tRes = 16;

    return new TileParameters(Sector::fullSphere(),
                              splitsByLatitude,
                              splitsByLongitude,
                              topLevel,
                              maxLevel,
                              tileTextureHeight,
                              tileTextureWidth,
                              tRes);
  }
};

class TileRenderer: public Renderer {
private:
  const TileTessellator* _tessellator;
  TileTexturizer*  _texturizer;
  const TileParameters*  _parameters;

  std::vector<Tile*>     _topLevelTiles;

  void clearTopLevelTiles();
  void createTopLevelTiles(const InitializationContext* ic);

public:
  TileRenderer(const TileTessellator* tessellator,
               TileTexturizer*  texturizer,
               const TileParameters* parameters) :
  _tessellator(tessellator),
  _texturizer(texturizer),
  _parameters(parameters)
  {

  }

  ~TileRenderer();

  void initialize(const InitializationContext* ic);

  int render(const RenderContext* rc);

  bool onTouchEvent(const TouchEvent* touchEvent) {
    return false;
  }

  void onResizeViewportEvent(int width, int height) {

  }

};

#endif
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2001-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include <Include/PlatformDefinitions.hpp>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

#include <xercesc/util/PlatformUtils.hpp>

#include <Include/XalanAutoPtr.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

//#define XALAN_VQ_SPECIAL_TRACE
#if defined(XALAN_VQ_SPECIAL_TRACE)
#include "C:/Program Files/Rational/Quantify/pure.h"
#endif

#if !defined (XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::endl;
#endif

void
Usage()
{
	cerr << endl
		 << "Xalan version "
		 << XALAN_FULLVERSIONDOT
		 << endl
		 << "Xerces version "
		 << XERCES_FULLVERSIONDOT
		 << endl
		 << "Usage: Xalan [options] source stylesheet"
		 << endl
	     << "Options:"
		 << endl
		 << "  -a                    Use xml-stylesheet PI, not the 'stylesheet' argument"
		 << endl
		 << "  -o filename           Write output to the specified file."
		 << endl
		 << "  -p name expression    Sets a stylesheet parameter."
		 << endl
		 << "  -v                    Validates source documents."
		 << endl
		 << "  -?                    Display this message."
		 << endl;
}

class Params
{
public:

	Params(unsigned long	maxParams) :
		m_validate(false),
		m_useStylesheetPI(false),
		m_inFileName(0),
		m_xslFileName(0),
		m_outFileName(0),
		m_params(),
		m_maxParams(maxParams),
		m_currentParam(0)
	{
	}

	bool
	addParam(
			const char*		name,
			const char*		expression)
	{
		if (m_currentParam == m_maxParams)
		{
			return false;
		}
		else
		{
			// Allocate memory if necessary...
			if (m_params.get() == 0)
			{
				m_params.reset(new ParamPair[m_maxParams]);
			}
			assert(m_params.get() != 0);

			m_params[m_currentParam].m_name = name;
			m_params[m_currentParam].m_expression = expression;

			++m_currentParam;

			return true;
		}
	};

	void
	setParams(XalanTransformer&		theTransformer)
	{
		theTransformer.setUseValidation(m_validate);

		for(unsigned long i = 0; i < m_currentParam; ++i)
		{
			theTransformer.setStylesheetParam(
				m_params[i].m_name,
				m_params[i].m_expression);
		}
	}

	bool			m_validate;
	bool			m_useStylesheetPI;

	const char*		m_inFileName;
	const char*		m_xslFileName;
	const char*		m_outFileName;

private:

	struct ParamPair
	{
		ParamPair() :
			m_name(0),
			m_expression(0)
		{
		}

		const char*		m_name;
		const char*		m_expression;
	};

	XalanArrayAutoPtr<ParamPair>	m_params;

	const unsigned long				m_maxParams;
	unsigned long					m_currentParam;
};

bool
getArgs(
			int					argc,
			const char*			argv[],
			Params&				params)
{
#if defined(XALAN_STRICT_ANSI_HEADERS)
	using std::strlen;
#endif

	bool fSuccess = true;

	for (int i = 1; i < argc && fSuccess == true; ++i)
	{
		if (argv[i][0] == '-')
		{
			if (strlen(argv[i]) != 2)
			{
				fSuccess = false;
			}
			else if (params.m_inFileName != 0 || params.m_xslFileName != 0)
			{
				fSuccess = false;
			}
			else if (argv[i][1] == 'a')
			{
				params.m_useStylesheetPI = true;
			}
			else if (argv[i][1] == 'o')
			{
				++i;

				if(i < argc && argv[i][0] != '-' &&
				   strlen(argv[i]) != 0)
				{
					params.m_outFileName = argv[i];
				}
				else
				{
					fSuccess = false;
				}
			}
			else if (argv[i][1] == 'p')
			{
				++i;

				if(i >= argc || argv[i][0] == '-')
				{
					fSuccess = false;
				}
				else
				{
					const char* const	name = argv[i];

					++i;

					// Don't check for '-' here, since that might
					// be a valid character in a parameter value.
					if(i >= argc)
					{
						fSuccess = false;
					}
					else
					{
						const char* const	value = argv[i];

						if (params.addParam(name, value) == false)
						{
							cerr << "Maximum numbers of stylesheets params has been exceeded!" << endl;

							fSuccess = false;
						}
					}
				}
			}
			else if (argv[i][1] == 'v')
			{
				params.m_validate = true;
			}
		}
		else if (params.m_inFileName == 0 &&
				 strlen(argv[i]) != 0)
		{
			params.m_inFileName = argv[i];

			if (strlen(params.m_inFileName) == 0)
			{
				fSuccess = false;
			}
		}
		else if (params.m_xslFileName == 0 &&
				 strlen(argv[i]) != 0 &&
				 params.m_useStylesheetPI == false)
		{
			params.m_xslFileName = argv[i];

			if (strlen(params.m_xslFileName) == 0)
			{
				fSuccess = false;
			}
		}
		else
		{
			fSuccess = false;
		}
	}

	if (fSuccess == true && params.m_inFileName == 0)
	{
		return false;
	}
	else if (params.m_xslFileName == 0 && params.m_useStylesheetPI == false)
	{
		return false;
	}
	else
	{
		return fSuccess;
	}
}

int
xsltMain(
			int				argc,
			const char*		argv[])

{
	int	theResult = -1;

	// Set the maximum number of params as half of argc - 1.
	// It's actually argc - 2, but that could get us into negative
	// numbers, so don't bother.  Also, always add 1, in case
	// (argc - 1) / 2 is 0.
	Params	theParams((argc - 1) / 2 + 1);

	if (getArgs(argc, argv, theParams) == false)
	{
		Usage();
	}
	else
	{
		// Call the static initializer for Xerces...
		XMLPlatformUtils::Initialize();

		// Initialize Xalan...
		XalanTransformer::initialize();

		{
			// Create a XalanTransformer instance...
			XalanTransformer	theTransformer;

			// Set any options...
			theParams.setParams(theTransformer);

			if (theParams.m_outFileName != 0)
			{
				theResult = theTransformer.transform(
						theParams.m_inFileName,
						theParams.m_xslFileName,
						theParams.m_outFileName);
			}
			else
			{
				theResult = theTransformer.transform(
						theParams.m_inFileName,
						theParams.m_xslFileName,
						cout);
			}

			if (theResult != 0)
			{
				cerr << theTransformer.getLastError() << endl;
			}
		}

		// Terminate Xalan...
		XalanTransformer::terminate();

		// Terminate Xerces...
		XMLPlatformUtils::Terminate();
	}

	return theResult;
}

int
main(
			int				argc,
			const char*		argv[])
{
#if !defined(XALAN_USE_ICU) && !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

#if defined(XALAN_VQ_SPECIAL_TRACE)
	QuantifyStopRecordingData();
	QuantifyClearData();
#endif

    if (argc < 2)
	{
		Usage();

		return -1;
	}
	else
	{
		return xsltMain(argc, argv);
	}
}
<commit_msg>Implemented new command line options.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2001-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include <Include/PlatformDefinitions.hpp>

#include <cstdlib>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

#include <xercesc/util/PlatformUtils.hpp>

#include <Include/XalanAutoPtr.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

//#define XALAN_VQ_SPECIAL_TRACE
#if defined(XALAN_VQ_SPECIAL_TRACE)
#include "C:/Program Files/Rational/Quantify/pure.h"
#endif

#if !defined (XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::endl;
#endif

#if defined(XALAN_STRICT_ANSI_HEADERS)
using std::atoi;
#endif

void
Usage()
{
	cerr << endl
		 << "Xalan version "
		 << XALAN_FULLVERSIONDOT
		 << endl
		 << "Xerces version "
		 << XERCES_FULLVERSIONDOT
		 << endl
		 << "Usage: Xalan [options] source stylesheet"
		 << endl
	     << "Options:"
		 << endl
		 << "  -a                    Use xml-stylesheet PI, not the 'stylesheet' argument"
		 << endl
		 << "  -i integer            Indent the specified amount."
		 << endl
		 << "  -m                    Omit the META tag in HTML output."
		 << endl
		 << "  -o filename           Write output to the specified file."
		 << endl
		 << "  -p name expression    Sets a stylesheet parameter."
		 << endl
		 << "  -u                    Disable escaping of URLs in HTML output."
		 << endl
		 << "  -v                    Validates source documents."
		 << endl
		 << "  -?                    Display this message."
		 << endl;
}

class Params
{
public:

	Params(unsigned long	maxParams) :
		m_validate(false),
		m_useStylesheetPI(false),
		m_omitMETATag(false),
		m_noURLEscaping(false),
		m_indentAmount(-1),
		m_inFileName(0),
		m_xslFileName(0),
		m_outFileName(0),
		m_params(),
		m_maxParams(maxParams),
		m_currentParam(0)
	{
	}

	bool
	addParam(
			const char*		name,
			const char*		expression)
	{
		if (m_currentParam == m_maxParams)
		{
			return false;
		}
		else
		{
			// Allocate memory if necessary...
			if (m_params.get() == 0)
			{
				m_params.reset(new ParamPair[m_maxParams]);
			}
			assert(m_params.get() != 0);

			m_params[m_currentParam].m_name = name;
			m_params[m_currentParam].m_expression = expression;

			++m_currentParam;

			return true;
		}
	};

	void
	setParams(XalanTransformer&		theTransformer)
	{
		theTransformer.setUseValidation(m_validate);

		if (m_omitMETATag == true)
		{
			theTransformer.setOmitMETATag(XalanTransformer::eOmitMETATagYes);
		}

		if (m_noURLEscaping == true)
		{
			theTransformer.setEscapeURLs(XalanTransformer::eEscapeURLsNo);
		}

		if (m_indentAmount >= 0)
		{
			theTransformer.setIndent(m_indentAmount);
		}

		for(unsigned long i = 0; i < m_currentParam; ++i)
		{
			theTransformer.setStylesheetParam(
				m_params[i].m_name,
				m_params[i].m_expression);
		}
	}

	bool			m_validate;
	bool			m_useStylesheetPI;
	bool			m_omitMETATag;
	bool			m_noURLEscaping;

	int				m_indentAmount;

	const char*		m_inFileName;
	const char*		m_xslFileName;
	const char*		m_outFileName;

private:

	struct ParamPair
	{
		ParamPair() :
			m_name(0),
			m_expression(0)
		{
		}

		const char*		m_name;
		const char*		m_expression;
	};

	XalanArrayAutoPtr<ParamPair>	m_params;

	const unsigned long				m_maxParams;
	unsigned long					m_currentParam;
};

bool
getArgs(
			int					argc,
			const char*			argv[],
			Params&				params)
{
#if defined(XALAN_STRICT_ANSI_HEADERS)
	using std::strlen;
#endif

	bool fSuccess = true;

	for (int i = 1; i < argc && fSuccess == true; ++i)
	{
		if (argv[i][0] == '-')
		{
			if (strlen(argv[i]) != 2)
			{
				fSuccess = false;
			}
			else if (params.m_inFileName != 0 || params.m_xslFileName != 0)
			{
				fSuccess = false;
			}
			else if (argv[i][1] == 'a')
			{
				params.m_useStylesheetPI = true;
			}
			else if (argv[i][1] == 'i')
			{
				++i;

				if(i < argc && argv[i][0] != '-' &&
				   strlen(argv[i]) != 0)
				{
					params.m_indentAmount = atoi(argv[i]);
				}
				else
				{
					fSuccess = false;
				}
			}
			else if (argv[i][1] == 'm')
			{
				params.m_omitMETATag = true;
			}
			else if (argv[i][1] == 'o')
			{
				++i;

				if(i < argc && argv[i][0] != '-' &&
				   strlen(argv[i]) != 0)
				{
					params.m_outFileName = argv[i];
				}
				else
				{
					fSuccess = false;
				}
			}
			else if (argv[i][1] == 'p')
			{
				++i;

				if(i >= argc || argv[i][0] == '-')
				{
					fSuccess = false;
				}
				else
				{
					const char* const	name = argv[i];

					++i;

					// Don't check for '-' here, since that might
					// be a valid character in a parameter value.
					if(i >= argc)
					{
						fSuccess = false;
					}
					else
					{
						const char* const	value = argv[i];

						if (params.addParam(name, value) == false)
						{
							cerr << "Maximum numbers of stylesheets params has been exceeded!" << endl;

							fSuccess = false;
						}
					}
				}
			}
			else if (argv[i][1] == 'u')
			{
				params.m_noURLEscaping = true;
			}
			else if (argv[i][1] == 'v')
			{
				params.m_validate = true;
			}
		}
		else if (params.m_inFileName == 0 &&
				 strlen(argv[i]) != 0)
		{
			params.m_inFileName = argv[i];

			if (strlen(params.m_inFileName) == 0)
			{
				fSuccess = false;
			}
		}
		else if (params.m_xslFileName == 0 &&
				 strlen(argv[i]) != 0 &&
				 params.m_useStylesheetPI == false)
		{
			params.m_xslFileName = argv[i];

			if (strlen(params.m_xslFileName) == 0)
			{
				fSuccess = false;
			}
		}
		else
		{
			fSuccess = false;
		}
	}

	if (fSuccess == true && params.m_inFileName == 0)
	{
		return false;
	}
	else if (params.m_xslFileName == 0 && params.m_useStylesheetPI == false)
	{
		return false;
	}
	else
	{
		return fSuccess;
	}
}

int
xsltMain(
			int				argc,
			const char*		argv[])

{
	int	theResult = -1;

	// Set the maximum number of params as half of argc - 1.
	// It's actually argc - 2, but that could get us into negative
	// numbers, so don't bother.  Also, always add 1, in case
	// (argc - 1) / 2 is 0.
	Params	theParams((argc - 1) / 2 + 1);

	if (getArgs(argc, argv, theParams) == false)
	{
		Usage();
	}
	else
	{
		// Call the static initializer for Xerces...
		XMLPlatformUtils::Initialize();

		// Initialize Xalan...
		XalanTransformer::initialize();

		{
			// Create a XalanTransformer instance...
			XalanTransformer	theTransformer;

			// Set any options...
			theParams.setParams(theTransformer);

			if (theParams.m_outFileName != 0)
			{
				theResult = theTransformer.transform(
						theParams.m_inFileName,
						theParams.m_xslFileName,
						theParams.m_outFileName);
			}
			else
			{
				theResult = theTransformer.transform(
						theParams.m_inFileName,
						theParams.m_xslFileName,
						cout);
			}

			if (theResult != 0)
			{
				cerr << theTransformer.getLastError() << endl;
			}
		}

		// Terminate Xalan...
		XalanTransformer::terminate();

		// Terminate Xerces...
		XMLPlatformUtils::Terminate();
	}

	return theResult;
}

int
main(
			int				argc,
			const char*		argv[])
{
#if !defined(XALAN_USE_ICU) && !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

#if defined(XALAN_VQ_SPECIAL_TRACE)
	QuantifyStopRecordingData();
	QuantifyClearData();
#endif

    if (argc < 2)
	{
		Usage();

		return -1;
	}
	else
	{
		return xsltMain(argc, argv);
	}
}
<|endoftext|>


<commit_before>#pragma once

#include <vector>
#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/Point3f.hpp"

namespace dai {

struct Extrinsics {
    std::vector<std::vector<float>> rotationMatrix;
    // (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket obtained through calibration
    Point3f translation;
    // (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket measured through CAD design
    Point3f measuredTranslation;
    CameraBoardSocket toCameraSocket;
    /** FIXME(sachin): Why does fromCameraSocket needs to be vector? fromCameraSockets
     * is not part of eeprom write. it just enables in linking between cameras after eeprom read.
     */
    std::vector<CameraBoardSocket> fromCameraSockets;
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(Extrinsics, rotationMatrix, translation, measuredTranslation, toCameraSocket, fromCameraSockets);
};

}  // namespace dai<commit_msg>changed from vector to single link<commit_after>#pragma once

#include <vector>
#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/Point3f.hpp"

namespace dai {

struct Extrinsics {
    std::vector<std::vector<float>> rotationMatrix;
    // (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket obtained through calibration
    Point3f translation;
    // (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket measured through CAD design
    Point3f measuredTranslation;
    CameraBoardSocket toCameraSocket;
    /** FIXME(sachin): Why does fromCameraSocket needs to be vector? fromCameraSockets
     * is not part of eeprom write. it just enables in linking between cameras after eeprom read.
     */
    CameraBoardSocket fromCameraSockets;
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(Extrinsics, rotationMatrix, translation, measuredTranslation, toCameraSocket, fromCameraSockets);
};

}  // namespace dai<|endoftext|>