<commit_before>/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <folly/compression/CompressionContextPoolSingletons.h>

#include <stdlib.h>

#include <folly/Portability.h>

#ifndef FOLLY_COMPRESSION_USE_HUGEPAGES
#if defined(__linux__) && !defined(__ANDROID__)
#define FOLLY_COMPRESSION_USE_HUGEPAGES 1
#else
#define FOLLY_COMPRESSION_USE_HUGEPAGES 0
#endif
#endif

#if FOLLY_COMPRESSION_USE_HUGEPAGES
#include <folly/experimental/JemallocHugePageAllocator.h>
#endif

#if FOLLY_HAVE_LIBZSTD
#ifndef ZSTD_STATIC_LINKING_ONLY
#define ZSTD_STATIC_LINKING_ONLY
#endif
#include <zstd.h>
#endif

namespace folly {
namespace compression {
namespace contexts {

#if FOLLY_HAVE_LIBZSTD
namespace {
// These objects have no static dependencies and therefore no SIOF issues.
ZSTD_CCtx_Pool zstd_cctx_pool_singleton;
ZSTD_DCtx_Pool zstd_dctx_pool_singleton;

#if FOLLY_COMPRESSION_USE_HUGEPAGES
constexpr bool use_huge_pages = kIsArchAmd64;

void* huge_page_alloc(void*, size_t size) {
  if (size < 16 * 4096) {
    // Arbritrary cutoff: ZSTD_CCtx'es only ever make two kinds of allocations:
    // 1. one small one for the CCtx itself.
    // 2. "big" ones for the workspace (ZSTD_cwksp)
    // The CCtx allocation doesn't need to be in a huge page.
    return malloc(size);
  }
  return JemallocHugePageAllocator::allocate(size);
}

void huge_page_free(void*, void* address) {
  return JemallocHugePageAllocator::deallocate(address);
}

ZSTD_customMem huge_page_custom_mem = {
    use_huge_pages ? huge_page_alloc : nullptr,
    use_huge_pages ? huge_page_free : nullptr,
    nullptr,
};
#else
ZSTD_customMem huge_page_custom_mem = {
    nullptr,
    nullptr,
    nullptr,
};
#endif

} // anonymous namespace

ZSTD_CCtx* ZSTD_CCtx_Creator::operator()() const noexcept {
  return ZSTD_createCCtx_advanced(huge_page_custom_mem);
}

ZSTD_DCtx* ZSTD_DCtx_Creator::operator()() const noexcept {
  return ZSTD_createDCtx_advanced(huge_page_custom_mem);
}

void ZSTD_CCtx_Deleter::operator()(ZSTD_CCtx* ctx) const noexcept {
  ZSTD_freeCCtx(ctx);
}

void ZSTD_DCtx_Deleter::operator()(ZSTD_DCtx* ctx) const noexcept {
  ZSTD_freeDCtx(ctx);
}

void ZSTD_CCtx_Resetter::operator()(ZSTD_CCtx* ctx) const noexcept {
  size_t const err = ZSTD_CCtx_reset(ctx, ZSTD_reset_session_and_parameters);
  assert(!ZSTD_isError(err)); // This function doesn't actually fail
  (void)err;
}

void ZSTD_DCtx_Resetter::operator()(ZSTD_DCtx* ctx) const noexcept {
  size_t const err = ZSTD_DCtx_reset(ctx, ZSTD_reset_session_and_parameters);
  assert(!ZSTD_isError(err)); // This function doesn't actually fail
  (void)err;
}

ZSTD_CCtx_Pool::Ref getZSTD_CCtx() {
  return zstd_cctx_pool_singleton.get();
}

ZSTD_DCtx_Pool::Ref getZSTD_DCtx() {
  return zstd_dctx_pool_singleton.get();
}

ZSTD_CCtx_Pool::Ref getNULL_ZSTD_CCtx() {
  return zstd_cctx_pool_singleton.getNull();
}

ZSTD_DCtx_Pool::Ref getNULL_ZSTD_DCtx() {
  return zstd_dctx_pool_singleton.getNull();
}
#endif // FOLLY_HAVE_LIBZSTD

} // namespace contexts
} // namespace compression
} // namespace folly
<commit_msg>Revert D29856163: Use Huge Page Allocator in Zstd Context Pool<commit_after>/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <folly/compression/CompressionContextPoolSingletons.h>

namespace folly {
namespace compression {
namespace contexts {

#if FOLLY_HAVE_LIBZSTD
namespace {
// These objects have no static dependencies and therefore no SIOF issues.
ZSTD_CCtx_Pool zstd_cctx_pool_singleton;
ZSTD_DCtx_Pool zstd_dctx_pool_singleton;
} // anonymous namespace

ZSTD_CCtx* ZSTD_CCtx_Creator::operator()() const noexcept {
  return ZSTD_createCCtx();
}

ZSTD_DCtx* ZSTD_DCtx_Creator::operator()() const noexcept {
  return ZSTD_createDCtx();
}

void ZSTD_CCtx_Deleter::operator()(ZSTD_CCtx* ctx) const noexcept {
  ZSTD_freeCCtx(ctx);
}

void ZSTD_DCtx_Deleter::operator()(ZSTD_DCtx* ctx) const noexcept {
  ZSTD_freeDCtx(ctx);
}

void ZSTD_CCtx_Resetter::operator()(ZSTD_CCtx* ctx) const noexcept {
  size_t const err = ZSTD_CCtx_reset(ctx, ZSTD_reset_session_and_parameters);
  assert(!ZSTD_isError(err)); // This function doesn't actually fail
  (void)err;
}

void ZSTD_DCtx_Resetter::operator()(ZSTD_DCtx* ctx) const noexcept {
  size_t const err = ZSTD_DCtx_reset(ctx, ZSTD_reset_session_and_parameters);
  assert(!ZSTD_isError(err)); // This function doesn't actually fail
  (void)err;
}

ZSTD_CCtx_Pool::Ref getZSTD_CCtx() {
  return zstd_cctx_pool_singleton.get();
}

ZSTD_DCtx_Pool::Ref getZSTD_DCtx() {
  return zstd_dctx_pool_singleton.get();
}

ZSTD_CCtx_Pool::Ref getNULL_ZSTD_CCtx() {
  return zstd_cctx_pool_singleton.getNull();
}

ZSTD_DCtx_Pool::Ref getNULL_ZSTD_DCtx() {
  return zstd_dctx_pool_singleton.getNull();
}
#endif // FOLLY_HAVE_LIBZSTD

} // namespace contexts
} // namespace compression
} // namespace folly
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: mediatypedetectionhelper.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-25 18:21:53 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_SERVICES_MEDIATYPEDETECTIONHELPER_HXX_
#include <services/mediatypedetectionhelper.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif

#ifndef _INETTYPE_HXX
#include <svtools/inettype.hxx>
#endif

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework
{

using namespace ::com::sun::star        ;
using namespace ::rtl                   ;

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  constructor
//*****************************************************************************************************************
MediaTypeDetectionHelper::MediaTypeDetectionHelper( const uno::Reference< lang::XMultiServiceFactory >& xFactory )
    : m_xFactory( xFactory )
{
}

//*****************************************************************************************************************
//  destructor
//*****************************************************************************************************************
MediaTypeDetectionHelper::~MediaTypeDetectionHelper()
{
}

//*****************************************************************************************************************
//  XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************

DEFINE_XINTERFACE_3                 (   MediaTypeDetectionHelper
                                        , OWeakObject
                                        , DIRECT_INTERFACE( lang::XTypeProvider )
                                        , DIRECT_INTERFACE( lang::XServiceInfo  )
                                        , DIRECT_INTERFACE( util::XStringMapping )
                                    )

DEFINE_XTYPEPROVIDER_3              (   MediaTypeDetectionHelper
                                        , lang::XTypeProvider
                                        , lang::XServiceInfo
                                        , util::XStringMapping
                                    )

DEFINE_XSERVICEINFO_ONEINSTANCESERVICE  (   MediaTypeDetectionHelper
                                        , ::cppu::OWeakObject
                                        , SERVICENAME_MEDIATYPEDETECTIONHELPER
                                        , IMPLEMENTATIONNAME_MEDIATYPEDETECTIONHELPER
                                    )

DEFINE_INIT_SERVICE                 (   MediaTypeDetectionHelper,
                                        {
                                        }
                                    )

//*****************************************************************************************************************
//   XStringMapping
//*****************************************************************************************************************

//virtual
sal_Bool SAL_CALL MediaTypeDetectionHelper::mapStrings(
        uno::Sequence< OUString >& rSeq )
        throw(uno::RuntimeException)
{
    sal_Bool bModified = sal_False;
    for( sal_Int32 i = rSeq.getLength(); i--; )
    {

        OUString& rUrl = rSeq[i];
        INetContentType eType = INetContentTypes::GetContentTypeFromURL( rUrl );

        UniString aType( INetContentTypes::GetContentType( eType ) );
        if( aType.Len() )
        {
            rUrl = aType;
            bModified = sal_True;
        }
    }
    return bModified;
}

}   // namespace framework

<commit_msg>INTEGRATION: CWS ooo19126 (1.6.502); FILE MERGED 2005/09/05 13:06:53 rt 1.6.502.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mediatypedetectionhelper.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 01:44:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_SERVICES_MEDIATYPEDETECTIONHELPER_HXX_
#include <services/mediatypedetectionhelper.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif

#ifndef _INETTYPE_HXX
#include <svtools/inettype.hxx>
#endif

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework
{

using namespace ::com::sun::star        ;
using namespace ::rtl                   ;

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  constructor
//*****************************************************************************************************************
MediaTypeDetectionHelper::MediaTypeDetectionHelper( const uno::Reference< lang::XMultiServiceFactory >& xFactory )
    : m_xFactory( xFactory )
{
}

//*****************************************************************************************************************
//  destructor
//*****************************************************************************************************************
MediaTypeDetectionHelper::~MediaTypeDetectionHelper()
{
}

//*****************************************************************************************************************
//  XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************

DEFINE_XINTERFACE_3                 (   MediaTypeDetectionHelper
                                        , OWeakObject
                                        , DIRECT_INTERFACE( lang::XTypeProvider )
                                        , DIRECT_INTERFACE( lang::XServiceInfo  )
                                        , DIRECT_INTERFACE( util::XStringMapping )
                                    )

DEFINE_XTYPEPROVIDER_3              (   MediaTypeDetectionHelper
                                        , lang::XTypeProvider
                                        , lang::XServiceInfo
                                        , util::XStringMapping
                                    )

DEFINE_XSERVICEINFO_ONEINSTANCESERVICE  (   MediaTypeDetectionHelper
                                        , ::cppu::OWeakObject
                                        , SERVICENAME_MEDIATYPEDETECTIONHELPER
                                        , IMPLEMENTATIONNAME_MEDIATYPEDETECTIONHELPER
                                    )

DEFINE_INIT_SERVICE                 (   MediaTypeDetectionHelper,
                                        {
                                        }
                                    )

//*****************************************************************************************************************
//   XStringMapping
//*****************************************************************************************************************

//virtual
sal_Bool SAL_CALL MediaTypeDetectionHelper::mapStrings(
        uno::Sequence< OUString >& rSeq )
        throw(uno::RuntimeException)
{
    sal_Bool bModified = sal_False;
    for( sal_Int32 i = rSeq.getLength(); i--; )
    {

        OUString& rUrl = rSeq[i];
        INetContentType eType = INetContentTypes::GetContentTypeFromURL( rUrl );

        UniString aType( INetContentTypes::GetContentType( eType ) );
        if( aType.Len() )
        {
            rUrl = aType;
            bModified = sal_True;
        }
    }
    return bModified;
}

}   // namespace framework

<|endoftext|>


<commit_before>/*
 * Renderer.cpp
 *
 *  Created on: 2012-12-02
 *      Author: Nathan
 */

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include "Renderer.h"
#include "Shaders/shaders.h"

Shader* shader;
glm::mat4 projection;

Renderer::Renderer(int width, int height) {
    this->height = height;
    this->width = width;
    std::cout << matrixStack.size() << std::endl;
    matrixStack.push_back(glm::mat4(1.0f));
    std::cout << matrixStack.size() << std::endl;
    loadShader("");
    useShader(0);
    uniforms.projection = setUniform("uprojection");
    uniforms.camera = setUniform("ucamera");
    uniforms.model = setUniform("umodel");
    uniforms.color = setUniform("ucolor");

    glm::mat4 projection = setProjection(width, height);
}

void Renderer::loadShader(const std::string &name){
    shader = new Shader("res/shaders/vert.glsl", "res/shaders/frag.glsl", width, height);
}

glm::vec3 Renderer::unProject(int x, int y, double z){
    glm::ivec4 viewport;
    glGetIntegerv(GL_VIEWPORT, glm::value_ptr(viewport));
    return glm::unProject(glm::vec3(x, y, z), currentMatrix(), projection, viewport);
}

void Renderer::setColor(float r, float g, float b, float a){
    glUniform4f(uniforms.color, r, g, b, a);
}

glm::vec3 Renderer::getCursorPos(int x, int y){
    pushMatrix();
    glm::vec3 p0 = unProject(x, y, 0.0);
    glm::vec3 p1 = unProject(x, y, 1.0);
    float u = -p0.z/(p1.z - p0.z);
    popMatrix();
    return p0 + (p1 - p0)*u;
}

void Renderer::loadFont(const std::string &name){
    _font.reset(new Font(name));
}

void Renderer::bindTexture(int texture){
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glUniform1i(uniforms.texture, 0);
}

GLuint Renderer::makeBuffer(GLenum target, const void *buffer_data, GLsizei buffer_size){
    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(target, vbo);
    glBufferData(target, buffer_size, buffer_data, GL_STATIC_DRAW);
    return vbo;
}

void Renderer::drawVertexArray(const std::vector<float> &vertices){
    GLuint vbo = makeBuffer(GL_ARRAY_BUFFER, &vertices[0], vertices.size());
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glEnableVertexAttribArray(0);
    /*
       glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
       glDrawArrays(GL_TRIANGLES, 0, vertices.size()/4);
       glDisableVertexAttribArray(0);
       */
}

void Renderer::renderString(glm::vec3 pos, const std::string &text){
    pushMatrix();
    for(unsigned i = 0; i < text.size(); ++i){
        Glyph g = _font->getGlyph(text[i]);
        float x = pos.x + g.left;
        float y = pos.y + g.top;
        float w = g.w;
        float h = g.h;
        glEnable(GL_TEXTURE);
        bindTexture(g.texture);
        glBegin(GL_QUADS);
        glVertex3f(x - w, y - h, 0);
        glVertex3f(x + w, y - h, 0);
        glVertex3f(x - w, y + h, 0);
        glVertex3f(x + w, y + h, 0);
        glEnd();
        //          glBufferData(GL_ARRAY_BUFFER, sizeof (box), box, GL_DYNAMIC_DRAW);
        //          glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        pos.x += (g.adv);
    }
    popMatrix();
}

#define NEAR_PLANE 0.0625f
#define FAR_PLANE 256.0f

glm::mat4 Renderer::setProjection(int width, int height){
    float aspectRatio = static_cast<float>(width) / static_cast<float>(height);
    projection = glm::perspective(glm::radians(45.f), aspectRatio, NEAR_PLANE, FAR_PLANE);
    glUniformMatrix4fv(uniforms.projection, 1, GL_FALSE, glm::value_ptr(projection));
    return projection;
}

void Renderer::uploadModelView(){
    glUniformMatrix4fv(uniforms.model, 1, GL_FALSE, glm::value_ptr(currentMatrix()));
}

void Renderer::setCamera(float x, float y, float z){
    camera = glm::translate(glm::mat4(1.f), -glm::vec3(x, y, z));
    glUniformMatrix4fv(uniforms.camera, 1, GL_FALSE, glm::value_ptr(camera));
}

void Renderer::pushMatrix(){
    matrixStack.push_back(matrixStack.back());
    uploadModelView();
}

void Renderer::popMatrix(){
    if(matrixStack.size() > 1) {
        matrixStack.pop_back();
        uploadModelView();
    }
}

glm::mat4 Renderer::translate(float x, float y, float z){
    glm::mat4 t = glm::translate(glm::mat4(1.f), glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::rotate(const glm::vec3 &from, const glm::vec3 &to){
    auto q = glm::quat( from, to );
    auto m = glm::toMat4( q );
    matrixStack.back() = matrixStack.back() * m;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::rotate(float angle, float x, float y, float z){
    glm::mat4 t = glm::rotate(glm::mat4(1.f), angle, glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::scale(float x, float y, float z){
    glm::mat4 t = glm::scale(
            glm::mat4(1.0f),
            glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4& Renderer::currentMatrix(){
    return matrixStack.back();
}

void Renderer::loadIdentity(){

}

GLuint Renderer::setUniform(const std::string &name){
    return shader->setUniform(name);
}

void Renderer::useShader(int id){
    shader->enable();
}

void Renderer::disableShader(){
    shader->disable();
}

Renderer::~Renderer() {}
<commit_msg>Delete unused vertex buffer generation<commit_after>/*
 * Renderer.cpp
 *
 *  Created on: 2012-12-02
 *      Author: Nathan
 */

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include "Renderer.h"
#include "Shaders/shaders.h"

Shader* shader;
glm::mat4 projection;

Renderer::Renderer(int width, int height) {
    this->height = height;
    this->width = width;
    std::cout << matrixStack.size() << std::endl;
    matrixStack.push_back(glm::mat4(1.0f));
    std::cout << matrixStack.size() << std::endl;
    loadShader("");
    useShader(0);
    uniforms.projection = setUniform("uprojection");
    uniforms.camera = setUniform("ucamera");
    uniforms.model = setUniform("umodel");
    uniforms.color = setUniform("ucolor");

    glm::mat4 projection = setProjection(width, height);
}

void Renderer::loadShader(const std::string &name){
    shader = new Shader("res/shaders/vert.glsl", "res/shaders/frag.glsl", width, height);
}

glm::vec3 Renderer::unProject(int x, int y, double z){
    glm::ivec4 viewport;
    glGetIntegerv(GL_VIEWPORT, glm::value_ptr(viewport));
    return glm::unProject(glm::vec3(x, y, z), currentMatrix(), projection, viewport);
}

void Renderer::setColor(float r, float g, float b, float a){
    glUniform4f(uniforms.color, r, g, b, a);
}

glm::vec3 Renderer::getCursorPos(int x, int y){
    pushMatrix();
    glm::vec3 p0 = unProject(x, y, 0.0);
    glm::vec3 p1 = unProject(x, y, 1.0);
    float u = -p0.z/(p1.z - p0.z);
    popMatrix();
    return p0 + (p1 - p0)*u;
}

void Renderer::loadFont(const std::string &name){
    _font.reset(new Font(name));
}

void Renderer::bindTexture(int texture){
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glUniform1i(uniforms.texture, 0);
}

void Renderer::renderString(glm::vec3 pos, const std::string &text){
    pushMatrix();
    for(unsigned i = 0; i < text.size(); ++i){
        Glyph g = _font->getGlyph(text[i]);
        float x = pos.x + g.left;
        float y = pos.y + g.top;
        float w = g.w;
        float h = g.h;
        glEnable(GL_TEXTURE);
        bindTexture(g.texture);
        glBegin(GL_QUADS);
        glVertex3f(x - w, y - h, 0);
        glVertex3f(x + w, y - h, 0);
        glVertex3f(x - w, y + h, 0);
        glVertex3f(x + w, y + h, 0);
        glEnd();
        //          glBufferData(GL_ARRAY_BUFFER, sizeof (box), box, GL_DYNAMIC_DRAW);
        //          glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        pos.x += (g.adv);
    }
    popMatrix();
}

#define NEAR_PLANE 0.0625f
#define FAR_PLANE 256.0f

glm::mat4 Renderer::setProjection(int width, int height){
    float aspectRatio = static_cast<float>(width) / static_cast<float>(height);
    projection = glm::perspective(glm::radians(45.f), aspectRatio, NEAR_PLANE, FAR_PLANE);
    glUniformMatrix4fv(uniforms.projection, 1, GL_FALSE, glm::value_ptr(projection));
    return projection;
}

void Renderer::uploadModelView(){
    glUniformMatrix4fv(uniforms.model, 1, GL_FALSE, glm::value_ptr(currentMatrix()));
}

void Renderer::setCamera(float x, float y, float z){
    camera = glm::translate(glm::mat4(1.f), -glm::vec3(x, y, z));
    glUniformMatrix4fv(uniforms.camera, 1, GL_FALSE, glm::value_ptr(camera));
}

void Renderer::pushMatrix(){
    matrixStack.push_back(matrixStack.back());
    uploadModelView();
}

void Renderer::popMatrix(){
    if(matrixStack.size() > 1) {
        matrixStack.pop_back();
        uploadModelView();
    }
}

glm::mat4 Renderer::translate(float x, float y, float z){
    glm::mat4 t = glm::translate(glm::mat4(1.f), glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::rotate(const glm::vec3 &from, const glm::vec3 &to){
    auto q = glm::quat( from, to );
    auto m = glm::toMat4( q );
    matrixStack.back() = matrixStack.back() * m;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::rotate(float angle, float x, float y, float z){
    glm::mat4 t = glm::rotate(glm::mat4(1.f), angle, glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::scale(float x, float y, float z){
    glm::mat4 t = glm::scale(
            glm::mat4(1.0f),
            glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4& Renderer::currentMatrix(){
    return matrixStack.back();
}

void Renderer::loadIdentity(){

}

GLuint Renderer::setUniform(const std::string &name){
    return shader->setUniform(name);
}

void Renderer::useShader(int id){
    shader->enable();
}

void Renderer::disableShader(){
    shader->disable();
}

Renderer::~Renderer() {}
<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/BSpline.h"
#include "cinder/cairo/Cairo.h"
#include "cinder/ImageIo.h"
#include "cinder/Utilities.h"

#include <vector>

using namespace ci;
using namespace ci::app;
using std::vector;

class bsplineApp : public App {
 public:
	bsplineApp() : mTrackedPoint( -1 ), mDegree( 3 ), mOpen( true ), mLoop( false ) {}

	int		findNearestPt( const vec2 &aPt );
	void	calcLength();

	void	mouseDown( MouseEvent event );
	void	mouseUp( MouseEvent event );
	void	mouseDrag( MouseEvent event );
	void	keyDown( KeyEvent event );

	void	drawBSpline( cairo::Context &ctx );
	void	draw();

	vector<vec2>		mPoints;
	int					mTrackedPoint;
	int					mDegree;
	bool				mOpen, mLoop;
};

void bsplineApp::mouseDown( MouseEvent event )
{
	const float MIN_CLICK_DISTANCE = 6.0f;
	if( event.isLeft() ) { // line
		vec2 clickPt = vec2( event.getPos() );
		int nearestIdx = findNearestPt( clickPt );
		if( ( nearestIdx < 0 ) || ( distance( mPoints[nearestIdx], clickPt ) > MIN_CLICK_DISTANCE ) ) {
			mPoints.push_back( vec2( event.getPos() ) );
			mTrackedPoint = -1;
		}
		else
			mTrackedPoint = nearestIdx;
		calcLength();
	}
}

void bsplineApp::mouseDrag( MouseEvent event )
{
	if( mTrackedPoint >= 0 ) {
		mPoints[mTrackedPoint] = vec2( event.getPos() );
		calcLength();
	}
}

void bsplineApp::mouseUp( MouseEvent event )
{
	mTrackedPoint = -1;
}

void bsplineApp::keyDown( KeyEvent event ) {
	if( event.getCode() == KeyEvent::KEY_ESCAPE ) {
		setFullScreen( false );
	}
	else if( event.getChar() == 'x' ) {
		mPoints.clear();
	}
	else if( event.getChar() == 'd' ) { // reduce the degree
		mDegree = ( mDegree > 1 ) ? mDegree - 1 : mDegree;
		calcLength();
	}
	else if( event.getChar() == 'D' ) { // increase the degree
		mDegree++;
		calcLength();
	}
	else if( event.getChar() == 'o' ) { // toggle between open/periodic
		mOpen = ! mOpen;
		calcLength();
	}
	else if( event.getChar() == 'l' ) { // toggle between looping
		mLoop = ! mLoop;
		calcLength();
	}
	else if( event.getChar() == 'i' ) { // export to png image
		writeImage( getHomeDirectory() / "bsplineOutput.png", copyWindowSurface() );
	}
	else if( event.getChar() == 's' ) { // export to svg
		cairo::Context ctx( cairo::SurfaceSvg( getHomeDirectory() / "output.svg", getWindowWidth(), getWindowHeight() ) );
		drawBSpline( ctx );
	}
	else if( event.getChar() == 'e' ) { // export to eps
		cairo::Context ctx( cairo::SurfaceEps( getHomeDirectory() / "output.eps", getWindowWidth(), getWindowHeight() ) );
		drawBSpline( ctx );
	}
	else if( event.getChar() == 'f' ) { // export to pdf
		cairo::Context ctx( cairo::SurfacePdf( getHomeDirectory() / "output.pdf", getWindowWidth(), getWindowHeight() ) );
		drawBSpline( ctx );
	}
	else if( event.getChar() == 'p' ) { // export to postscript
		cairo::Context ctx( cairo::SurfacePs( getHomeDirectory() / "output.ps", getWindowWidth(), getWindowHeight() ) );
		drawBSpline( ctx );
	}
}

int bsplineApp::findNearestPt( const vec2 &aPt )
{
	if( mPoints.empty() ) return -1;

	int result = 0;
	float nearestDist = distance( mPoints[0], aPt );
	for( size_t i = 1; i < mPoints.size(); ++i ) {
		if( distance( mPoints[i], aPt ) < nearestDist ) {
			result = i;
			nearestDist = distance( mPoints[i], aPt );
		}
	}

	return result;
}

void bsplineApp::calcLength()
{
	if( mPoints.size() > (size_t)mDegree ) {
		BSpline2f spline( mPoints, mDegree, mLoop, mOpen );
		console() << "Arc Length: " << spline.getLength( 0, 1 ) << std::endl;
	}
}

void bsplineApp::drawBSpline( cairo::Context &ctx )
{
	if( mPoints.size() > (size_t)mDegree ) {
		ctx.setLineWidth( 2.5f );
		ctx.setSourceRgb( 1.0f, 0.5f, 0.25f );
		ctx.appendPath( Path2d( BSpline2f( mPoints, mDegree, mLoop, mOpen ) ) );
		ctx.stroke();
//		ctx.fill();
	}
}

void bsplineApp::draw()
{
	// clear to the background color
	cairo::Context ctx( cairo::createWindowSurface() );
	ctx.setSourceRgb( 0.0f, 0.1f, 0.2f );
	ctx.paint();

	// draw the control points
	ctx.setSourceRgb( 1.0f, 1.0f, 0.0f );
	for( size_t p = 0; p < mPoints.size(); ++p ) {
		ctx.newSubPath();
		ctx.arc( mPoints[p], 2.5f, 0, 2 * 3.14159 );
	}
	ctx.stroke();

	if( mPoints.size() > (size_t)mDegree ) {
		// draw the curve by approximating via linear subdivision
		BSpline2f spline( mPoints, mDegree, mLoop, mOpen );
		ctx.setLineWidth( 8.0f );
		ctx.setSourceRgb( 0.25f, 1.0f, 0.5f );
		ctx.moveTo( spline.getPosition( 0 ) );
		for( float t = 0; t < 1.0f; t += 0.001f ) {
			ctx.lineTo( spline.getPosition( t ) );
		}

		ctx.stroke();

		// draw points 1/4, 1/2 and 3/4 along the length
		ctx.setSourceRgb( 0.0f, 0.7f, 1.0f );
		float totalLength = spline.getLength( 0, 1 );
		for( float p = 0.25f; p < 0.99f; p += 0.25f ) {
			ctx.newSubPath();
			ctx.arc( spline.getPosition( spline.getTime( p * totalLength ) ), 2.5f, 0, 2 * 3.14159f );
		}

		ctx.stroke();
	}

	// draw the curve by bezier path
	drawBSpline( ctx );
}

CINDER_APP( bsplineApp, Renderer2d )<commit_msg>BSpline sample minor implementation udpates<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/BSpline.h"
#include "cinder/cairo/Cairo.h"
#include "cinder/ImageIo.h"
#include "cinder/Utilities.h"

#include <vector>

using namespace ci;
using namespace ci::app;
using std::vector;

class BSplineApp : public App {
 public:
	BSplineApp() : mTrackedPoint( -1 ), mDegree( 3 ), mOpen( true ), mLoop( false ) {}

	int		findNearestPt( const vec2 &aPt );
	void	calcLength();

	void	mouseDown( MouseEvent event ) override;
	void	mouseUp( MouseEvent event ) override;
	void	mouseDrag( MouseEvent event ) override;
	void	keyDown( KeyEvent event ) override;

	void	drawBSpline( cairo::Context &ctx );
	void	draw() override;

	vector<vec2>		mPoints;
	int					mTrackedPoint;
	int					mDegree;
	bool				mOpen, mLoop;
};

void BSplineApp::mouseDown( MouseEvent event )
{
	const float MIN_CLICK_DISTANCE = 6.0f;
	if( event.isLeft() ) { // line
		vec2 clickPt = vec2( event.getPos() );
		int nearestIdx = findNearestPt( clickPt );
		if( ( nearestIdx < 0 ) || ( distance( mPoints[nearestIdx], clickPt ) > MIN_CLICK_DISTANCE ) ) {
			mPoints.push_back( vec2( event.getPos() ) );
			mTrackedPoint = -1;
		}
		else
			mTrackedPoint = nearestIdx;
		calcLength();
	}
}

void BSplineApp::mouseDrag( MouseEvent event )
{
	if( mTrackedPoint >= 0 ) {
		mPoints[mTrackedPoint] = vec2( event.getPos() );
		calcLength();
	}
}

void BSplineApp::mouseUp( MouseEvent event )
{
	mTrackedPoint = -1;
}

void BSplineApp::keyDown( KeyEvent event ) {
	if( event.getCode() == KeyEvent::KEY_ESCAPE ) {
		setFullScreen( false );
	}
	else if( event.getChar() == 'x' ) {
		mPoints.clear();
	}
	else if( event.getChar() == 'd' ) { // reduce the degree
		mDegree = ( mDegree > 1 ) ? mDegree - 1 : mDegree;
		calcLength();
	}
	else if( event.getChar() == 'D' ) { // increase the degree
		mDegree++;
		calcLength();
	}
	else if( event.getChar() == 'o' ) { // toggle between open/periodic
		mOpen = ! mOpen;
		calcLength();
	}
	else if( event.getChar() == 'l' ) { // toggle between looping
		mLoop = ! mLoop;
		calcLength();
	}
	else if( event.getChar() == 'i' ) { // export to png image
		writeImage( getHomeDirectory() / "bsplineOutput.png", copyWindowSurface() );
	}
	else if( event.getChar() == 's' ) { // export to svg
		cairo::Context ctx( cairo::SurfaceSvg( getHomeDirectory() / "output.svg", getWindowWidth(), getWindowHeight() ) );
		drawBSpline( ctx );
	}
}

int BSplineApp::findNearestPt( const vec2 &aPt )
{
	if( mPoints.empty() )
		return -1;

	int result = 0;
	float nearestDist = distance( mPoints[0], aPt );
	for( size_t i = 1; i < mPoints.size(); ++i ) {
		if( distance( mPoints[i], aPt ) < nearestDist ) {
			result = i;
			nearestDist = distance( mPoints[i], aPt );
		}
	}

	return result;
}

void BSplineApp::calcLength()
{
	if( mPoints.size() > (size_t)mDegree ) {
		BSpline2f spline( mPoints, mDegree, mLoop, mOpen );
		console() << "Arc Length: " << spline.getLength( 0, 1 ) << std::endl;
	}
}

void BSplineApp::drawBSpline( cairo::Context &ctx )
{
	if( mPoints.size() > (size_t)mDegree ) {
		ctx.setLineWidth( 2.5f );
		ctx.setSourceRgb( 1.0f, 0.5f, 0.25f );
		ctx.appendPath( Path2d( BSpline2f( mPoints, mDegree, mLoop, mOpen ) ) );
		ctx.stroke();
//		ctx.fill();
	}
}

void BSplineApp::draw()
{
	// clear to the background color
	cairo::Context ctx( cairo::createWindowSurface() );
	ctx.setSourceRgb( 0.0f, 0.1f, 0.2f );
	ctx.paint();

	// draw the control points
	ctx.setSourceRgb( 1.0f, 1.0f, 0.0f );
	for( size_t p = 0; p < mPoints.size(); ++p ) {
		ctx.newSubPath();
		ctx.arc( mPoints[p], 2.5f, 0, 2 * 3.14159 );
	}
	ctx.stroke();

	if( mPoints.size() > (size_t)mDegree ) {
		// draw the curve by approximating via linear subdivision as an alternative to the technique used in drawBSpline()
		BSpline2f spline( mPoints, mDegree, mLoop, mOpen );
		ctx.setLineWidth( 8.0f );
		ctx.setSourceRgb( 0.25f, 1.0f, 0.5f );
		ctx.moveTo( spline.getPosition( 0 ) );
		for( float t = 0; t < 1.0f; t += 0.001f )
			ctx.lineTo( spline.getPosition( t ) );

		ctx.stroke();

		// draw points 1/4, 1/2 and 3/4 along the length
		ctx.setSourceRgb( 0.0f, 0.7f, 1.0f );
		float totalLength = spline.getLength( 0, 1 );
		for( float p = 0.25f; p < 0.99f; p += 0.25f ) {
			ctx.newSubPath();
			ctx.arc( spline.getPosition( spline.getTime( p * totalLength ) ), 2.5f, 0, 2 * 3.14159f );
		}

		ctx.stroke();
	}

	// draw the curve by bezier path
	drawBSpline( ctx );
}

CINDER_APP( BSplineApp, Renderer2d )<|endoftext|>


<commit_before>#include <Core/Device.h>
#include <iostream>
#include <Graphics/DebugRenderer.h>

using namespace Osm;

static void error_callback(int error, const char* description)
{
	fputs(description, stderr);
}

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
	if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
		glfwSetWindowShouldClose(window, GL_TRUE);
}

GraphicsDevice::GraphicsDevice(CEngine& engine) : Component(engine)
{
	if (!glfwInit())
		exit(EXIT_FAILURE);

	glfwSetErrorCallback(error_callback);

	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);		 // yes, 3 and 2!!!
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // But also 4 if present
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_SAMPLES, 4);
	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);

	const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor());

	// _window = glfwCreateWindow(mode->width, mode->height, "Blastastic", glfwGetPrimaryMonitor(), nullptr);
	_window = glfwCreateWindow(1920, 1080, "Blastastic", nullptr, nullptr);
	// _window = glfwCreateWindow(640, 360, "Blastastic", nullptr, nullptr);

	//_window = glfwCreateWindow(1280, 720, "Blastastic", nullptr, nullptr);

	int major = glfwGetWindowAttrib(_window, GLFW_CONTEXT_VERSION_MAJOR);
	int minor = glfwGetWindowAttrib(_window, GLFW_CONTEXT_VERSION_MINOR);
	int revision = glfwGetWindowAttrib(_window, GLFW_CONTEXT_REVISION);
	std::cout << "OpenGL Version " << major << "." << minor << "." << revision << std::endl;

	if (!_window)
	{
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
	glfwMakeContextCurrent(_window);
	glfwSwapInterval(1);
	glfwSetKeyCallback(_window, key_callback);

	if (!gladLoadGLLoader(GLADloadproc(glfwGetProcAddress)))
	{
		cout << "Failed to initialize OpenGL context" << endl;
		ASSERT(false);
	}
	InitDebugMessages();

	glfwGetFramebufferSize(_window, &_width, &_height);
	_ratio = _width / float(_height);
}

GraphicsDevice::~GraphicsDevice()
{
	glfwDestroyWindow(_window);
	glfwTerminate();
}

int GraphicsDevice::GetScreenWidth() const
{
	return _width;
}

int GraphicsDevice::GetScreenHeight() const
{
	return _height;
}

bool GraphicsDevice::GetKeyOnce(char key)
{
	return (glfwGetKey(_window, key) ?
		(_keyOnce[key] ? false : (_keyOnce[key] = true)) : \
		(_keyOnce[key] = false));
}
<commit_msg>Full screen adjustment<commit_after>#include <Core/Device.h>
#include <iostream>
#include <Graphics/DebugRenderer.h>

using namespace Osm;

static void error_callback(int error, const char* description)
{
	fputs(description, stderr);
}

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
	if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
		glfwSetWindowShouldClose(window, GL_TRUE);
}

GraphicsDevice::GraphicsDevice(CEngine& engine) : Component(engine)
{
	if (!glfwInit())
		exit(EXIT_FAILURE);

	glfwSetErrorCallback(error_callback);

	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);		 // yes, 3 and 2!!!
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // But also 4 if present
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_SAMPLES, 4);
	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);

	const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor());

	_window = glfwCreateWindow(mode->width, mode->height, "Blastastic", glfwGetPrimaryMonitor(), nullptr);
	//_window = glfwCreateWindow(1920, 1080, "Blastastic", nullptr, nullptr);
	// _window = glfwCreateWindow(640, 360, "Blastastic", nullptr, nullptr);

	//_window = glfwCreateWindow(1280, 720, "Blastastic", nullptr, nullptr);

	int major = glfwGetWindowAttrib(_window, GLFW_CONTEXT_VERSION_MAJOR);
	int minor = glfwGetWindowAttrib(_window, GLFW_CONTEXT_VERSION_MINOR);
	int revision = glfwGetWindowAttrib(_window, GLFW_CONTEXT_REVISION);
	std::cout << "OpenGL Version " << major << "." << minor << "." << revision << std::endl;

	if (!_window)
	{
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
	glfwMakeContextCurrent(_window);
	glfwSwapInterval(1);
	glfwSetKeyCallback(_window, key_callback);

	if (!gladLoadGLLoader(GLADloadproc(glfwGetProcAddress)))
	{
		cout << "Failed to initialize OpenGL context" << endl;
		ASSERT(false);
	}
	InitDebugMessages();

	glfwGetFramebufferSize(_window, &_width, &_height);
	_ratio = _width / float(_height);
}

GraphicsDevice::~GraphicsDevice()
{
	glfwDestroyWindow(_window);
	glfwTerminate();
}

int GraphicsDevice::GetScreenWidth() const
{
	return _width;
}

int GraphicsDevice::GetScreenHeight() const
{
	return _height;
}

bool GraphicsDevice::GetKeyOnce(char key)
{
	return (glfwGetKey(_window, key) ?
		(_keyOnce[key] ? false : (_keyOnce[key] = true)) : \
		(_keyOnce[key] = false));
}
<|endoftext|>


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

#include "remoting/jingle_glue/ssl_socket_adapter.h"

#include "base/base64.h"
#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "jingle/glue/utils.h"
#include "net/base/address_list.h"
#include "net/base/cert_verifier.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_errors.h"
#include "net/base/ssl_config_service.h"
#include "net/base/sys_addrinfo.h"
#include "net/socket/client_socket_factory.h"
#include "net/url_request/url_request_context.h"

namespace remoting {

namespace {

// NSS doesn't load root certificates when running in sandbox, so we
// need to have gmail's cert hardcoded.
//
// TODO(sergeyu): Remove this when we don't make XMPP connection from
// inside of sandbox.
const char kGmailCertBase64[] =
    "MIIC2TCCAkKgAwIBAgIDBz+SMA0GCSqGSIb3DQEBBQUAME4xCzAJBgNVBAYTAlVT"
    "MRAwDgYDVQQKEwdFcXVpZmF4MS0wKwYDVQQLEyRFcXVpZmF4IFNlY3VyZSBDZXJ0"
    "aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDcwNDExMTcxNzM4WhcNMTIwNDEwMTcxNzM4"
    "WjBkMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN"
    "TW91bnRhaW4gVmlldzEUMBIGA1UEChMLR29vZ2xlIEluYy4xEjAQBgNVBAMTCWdt"
    "YWlsLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1Hds2jWwXAVGef06"
    "7PeSJF/h9BnoYlTdykx0lBTDc92/JLvuq0lJkytqll1UR4kHmF4vwqQkwcqOK03w"
    "k8qDK8fh6M13PYhvPEXP02ozsuL3vqE8hcCva2B9HVnOPY17Qok37rYQ+yexswN5"
    "eh0+93nddEa1PyHgEQ8CDKCJaWUCAwEAAaOBrjCBqzAOBgNVHQ8BAf8EBAMCBPAw"
    "HQYDVR0OBBYEFJcjzXEevMEDIEvuQiT7puEJY737MDoGA1UdHwQzMDEwL6AtoCuG"
    "KWh0dHA6Ly9jcmwuZ2VvdHJ1c3QuY29tL2NybHMvc2VjdXJlY2EuY3JsMB8GA1Ud"
    "IwQYMBaAFEjmaPkr0rKV10fYIyAQTzOYkJ/UMB0GA1UdJQQWMBQGCCsGAQUFBwMB"
    "BggrBgEFBQcDAjANBgkqhkiG9w0BAQUFAAOBgQB74cGpjdENf9U+WEd29dfzY3Tz"
    "JehnlY5cH5as8bOTe7PNPzj967OJ7TPWEycMwlS7CsqIsmfRGOFFfoHxo+iPugZ8"
    "uO2Kd++QHCXL+MumGjkW4FcTFmceV/Q12Wdh3WApcqIZZciQ79MAeFh7bzteAYqf"
    "wC98YQwylC9wVhf1yw==";

}  // namespace

SSLSocketAdapter* SSLSocketAdapter::Create(AsyncSocket* socket) {
  return new SSLSocketAdapter(socket);
}

SSLSocketAdapter::SSLSocketAdapter(AsyncSocket* socket)
    : SSLAdapter(socket),
      ignore_bad_cert_(false),
      cert_verifier_(new net::CertVerifier()),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          connected_callback_(this, &SSLSocketAdapter::OnConnected)),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          read_callback_(this, &SSLSocketAdapter::OnRead)),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          write_callback_(this, &SSLSocketAdapter::OnWrite)),
      ssl_state_(SSLSTATE_NONE),
      read_state_(IOSTATE_NONE),
      write_state_(IOSTATE_NONE) {
  transport_socket_ = new TransportSocket(socket, this);
}

SSLSocketAdapter::~SSLSocketAdapter() {
}

int SSLSocketAdapter::StartSSL(const char* hostname, bool restartable) {
  DCHECK(!restartable);
  hostname_ = hostname;

  if (socket_->GetState() != Socket::CS_CONNECTED) {
    ssl_state_ = SSLSTATE_WAIT;
    return 0;
  } else {
    return BeginSSL();
  }
}

int SSLSocketAdapter::BeginSSL() {
  if (!MessageLoop::current()) {
    // Certificate verification is done via the Chrome message loop.
    // Without this check, if we don't have a chrome message loop the
    // SSL connection just hangs silently.
    LOG(DFATAL) << "Chrome message loop (needed by SSL certificate "
                << "verification) does not exist";
    return net::ERR_UNEXPECTED;
  }

  // SSLConfigService is not thread-safe, and the default values for SSLConfig
  // are correct for us, so we don't use the config service to initialize this
  // object.
  net::SSLConfig ssl_config;

  std::string gmail_cert_binary;
  base::Base64Decode(kGmailCertBase64, &gmail_cert_binary);
  scoped_refptr<net::X509Certificate> gmail_cert =
      net::X509Certificate::CreateFromBytes(gmail_cert_binary.data(),
                                            gmail_cert_binary.size());
  DCHECK(gmail_cert);
  net::SSLConfig::CertAndStatus gmail_cert_status;
  gmail_cert_status.cert = gmail_cert;
  gmail_cert_status.cert_status = 0;
  ssl_config.allowed_bad_certs.push_back(gmail_cert_status);

  transport_socket_->set_addr(talk_base::SocketAddress(hostname_, 0));
  ssl_socket_.reset(
      net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket(
          transport_socket_, net::HostPortPair(hostname_, 443), ssl_config,
          NULL /* ssl_host_info */,
          cert_verifier_.get()));

  int result = ssl_socket_->Connect(&connected_callback_);

  if (result == net::ERR_IO_PENDING || result == net::OK) {
    return 0;
  } else {
    LOG(ERROR) << "Could not start SSL: " << net::ErrorToString(result);
    return result;
  }
}

int SSLSocketAdapter::Send(const void* buf, size_t len) {
  if (ssl_state_ != SSLSTATE_CONNECTED) {
    return AsyncSocketAdapter::Send(buf, len);
  } else {
    scoped_refptr<net::IOBuffer> transport_buf(new net::IOBuffer(len));
    memcpy(transport_buf->data(), buf, len);

    int result = ssl_socket_->Write(transport_buf, len, NULL);
    if (result == net::ERR_IO_PENDING) {
      SetError(EWOULDBLOCK);
    }
    transport_buf = NULL;
    return result;
  }
}

int SSLSocketAdapter::Recv(void* buf, size_t len) {
  switch (ssl_state_) {
    case SSLSTATE_NONE:
      return AsyncSocketAdapter::Recv(buf, len);

    case SSLSTATE_WAIT:
      SetError(EWOULDBLOCK);
      return -1;

    case SSLSTATE_CONNECTED:
      switch (read_state_) {
        case IOSTATE_NONE: {
          transport_buf_ = new net::IOBuffer(len);
          int result = ssl_socket_->Read(transport_buf_, len, &read_callback_);
          if (result >= 0) {
            memcpy(buf, transport_buf_->data(), len);
          }

          if (result == net::ERR_IO_PENDING) {
            read_state_ = IOSTATE_PENDING;
            SetError(EWOULDBLOCK);
          } else {
            if (result < 0) {
              SetError(result);
              VLOG(1) << "Socket error " << result;
            }
            transport_buf_ = NULL;
          }
          return result;
        }
        case IOSTATE_PENDING:
          SetError(EWOULDBLOCK);
          return -1;

        case IOSTATE_COMPLETE:
          memcpy(buf, transport_buf_->data(), len);
          transport_buf_ = NULL;
          read_state_ = IOSTATE_NONE;
          return data_transferred_;
      }
  }

  NOTREACHED();
  return -1;
}

void SSLSocketAdapter::OnConnected(int result) {
  if (result == net::OK) {
    ssl_state_ = SSLSTATE_CONNECTED;
    OnConnectEvent(this);
  } else {
    LOG(WARNING) << "OnConnected failed with error " << result;
  }
}

void SSLSocketAdapter::OnRead(int result) {
  DCHECK(read_state_ == IOSTATE_PENDING);
  read_state_ = IOSTATE_COMPLETE;
  data_transferred_ = result;
  AsyncSocketAdapter::OnReadEvent(this);
}

void SSLSocketAdapter::OnWrite(int result) {
  DCHECK(write_state_ == IOSTATE_PENDING);
  write_state_ = IOSTATE_COMPLETE;
  data_transferred_ = result;
  AsyncSocketAdapter::OnWriteEvent(this);
}

void SSLSocketAdapter::OnConnectEvent(talk_base::AsyncSocket* socket) {
  if (ssl_state_ != SSLSTATE_WAIT) {
    AsyncSocketAdapter::OnConnectEvent(socket);
  } else {
    ssl_state_ = SSLSTATE_NONE;
    int result = BeginSSL();
    if (0 != result) {
      // TODO(zork): Handle this case gracefully.
      LOG(WARNING) << "BeginSSL() failed with " << result;
    }
  }
}

TransportSocket::TransportSocket(talk_base::AsyncSocket* socket,
                                 SSLSocketAdapter *ssl_adapter)
    : read_callback_(NULL),
      write_callback_(NULL),
      read_buffer_len_(0),
      write_buffer_len_(0),
      socket_(socket),
      was_used_to_convey_data_(false) {
  socket_->SignalReadEvent.connect(this, &TransportSocket::OnReadEvent);
  socket_->SignalWriteEvent.connect(this, &TransportSocket::OnWriteEvent);
}

TransportSocket::~TransportSocket() {
}

int TransportSocket::Connect(net::CompletionCallback* callback) {
  // Connect is never called by SSLClientSocket, instead SSLSocketAdapter
  // calls Connect() on socket_ directly.
  NOTREACHED();
  return false;
}

void TransportSocket::Disconnect() {
  socket_->Close();
}

bool TransportSocket::IsConnected() const {
  return (socket_->GetState() == talk_base::Socket::CS_CONNECTED);
}

bool TransportSocket::IsConnectedAndIdle() const {
  // Not implemented.
  NOTREACHED();
  return false;
}

int TransportSocket::GetPeerAddress(net::AddressList* address) const {
  talk_base::SocketAddress socket_address = socket_->GetRemoteAddress();

  // libjingle supports only IPv4 addresses.
  sockaddr_in ipv4addr;
  socket_address.ToSockAddr(&ipv4addr);

  struct addrinfo ai;
  memset(&ai, 0, sizeof(ai));
  ai.ai_family = ipv4addr.sin_family;
  ai.ai_socktype = SOCK_STREAM;
  ai.ai_protocol = IPPROTO_TCP;
  ai.ai_addr = reinterpret_cast<struct sockaddr*>(&ipv4addr);
  ai.ai_addrlen = sizeof(ipv4addr);

  *address = net::AddressList::CreateByCopyingFirstAddress(&ai);
  return net::OK;
}

int TransportSocket::GetLocalAddress(net::IPEndPoint* address) const {
  talk_base::SocketAddress socket_address = socket_->GetLocalAddress();
  if (jingle_glue::SocketAddressToIPEndPoint(socket_address, address)) {
    return net::OK;
  } else {
    return net::ERR_FAILED;
  }
}

const net::BoundNetLog& TransportSocket::NetLog() const {
  return net_log_;
}

void TransportSocket::SetSubresourceSpeculation() {
  NOTREACHED();
}

void TransportSocket::SetOmniboxSpeculation() {
  NOTREACHED();
}

bool TransportSocket::WasEverUsed() const {
  // We don't use this in ClientSocketPools, so this should never be used.
  NOTREACHED();
  return was_used_to_convey_data_;
}

bool TransportSocket::UsingTCPFastOpen() const {
  return false;
}

int TransportSocket::Read(net::IOBuffer* buf, int buf_len,
                          net::CompletionCallback* callback) {
  DCHECK(buf);
  DCHECK(!read_callback_);
  DCHECK(!read_buffer_.get());
  int result = socket_->Recv(buf->data(), buf_len);
  if (result < 0) {
    result = net::MapSystemError(socket_->GetError());
    if (result == net::ERR_IO_PENDING) {
      read_callback_ = callback;
      read_buffer_ = buf;
      read_buffer_len_ = buf_len;
    }
  }
  if (result != net::ERR_IO_PENDING)
    was_used_to_convey_data_ = true;
  return result;
}

int TransportSocket::Write(net::IOBuffer* buf, int buf_len,
                           net::CompletionCallback* callback) {
  DCHECK(buf);
  DCHECK(!write_callback_);
  DCHECK(!write_buffer_.get());
  int result = socket_->Send(buf->data(), buf_len);
  if (result < 0) {
    result = net::MapSystemError(socket_->GetError());
    if (result == net::ERR_IO_PENDING) {
      write_callback_ = callback;
      write_buffer_ = buf;
      write_buffer_len_ = buf_len;
    }
  }
  if (result != net::ERR_IO_PENDING)
    was_used_to_convey_data_ = true;
  return result;
}

bool TransportSocket::SetReceiveBufferSize(int32 size) {
  // Not implemented.
  return false;
}

bool TransportSocket::SetSendBufferSize(int32 size) {
  // Not implemented.
  return false;
}

void TransportSocket::OnReadEvent(talk_base::AsyncSocket* socket) {
  if (read_callback_) {
    DCHECK(read_buffer_.get());
    net::CompletionCallback* callback = read_callback_;
    scoped_refptr<net::IOBuffer> buffer = read_buffer_;
    int buffer_len = read_buffer_len_;

    read_callback_ = NULL;
    read_buffer_ = NULL;
    read_buffer_len_ = 0;

    int result = socket_->Recv(buffer->data(), buffer_len);
    if (result < 0) {
      result = net::MapSystemError(socket_->GetError());
      if (result == net::ERR_IO_PENDING) {
        read_callback_ = callback;
        read_buffer_ = buffer;
        read_buffer_len_ = buffer_len;
        return;
      }
    }
    was_used_to_convey_data_ = true;
    callback->RunWithParams(Tuple1<int>(result));
  }
}

void TransportSocket::OnWriteEvent(talk_base::AsyncSocket* socket) {
  if (write_callback_) {
    DCHECK(write_buffer_.get());
    net::CompletionCallback* callback = write_callback_;
    scoped_refptr<net::IOBuffer> buffer = write_buffer_;
    int buffer_len = write_buffer_len_;

    write_callback_ = NULL;
    write_buffer_ = NULL;
    write_buffer_len_ = 0;

    int result = socket_->Send(buffer->data(), buffer_len);
    if (result < 0) {
      result = net::MapSystemError(socket_->GetError());
      if (result == net::ERR_IO_PENDING) {
        write_callback_ = callback;
        write_buffer_ = buffer;
        write_buffer_len_ = buffer_len;
        return;
      }
    }
    was_used_to_convey_data_ = true;
    callback->RunWithParams(Tuple1<int>(result));
  }
}

}  // namespace remoting
<commit_msg>Remove gmail cert from SSLSocketAdapter.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/jingle_glue/ssl_socket_adapter.h"

#include "base/base64.h"
#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "jingle/glue/utils.h"
#include "net/base/address_list.h"
#include "net/base/cert_verifier.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_errors.h"
#include "net/base/ssl_config_service.h"
#include "net/base/sys_addrinfo.h"
#include "net/socket/client_socket_factory.h"
#include "net/url_request/url_request_context.h"

namespace remoting {

SSLSocketAdapter* SSLSocketAdapter::Create(AsyncSocket* socket) {
  return new SSLSocketAdapter(socket);
}

SSLSocketAdapter::SSLSocketAdapter(AsyncSocket* socket)
    : SSLAdapter(socket),
      ignore_bad_cert_(false),
      cert_verifier_(new net::CertVerifier()),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          connected_callback_(this, &SSLSocketAdapter::OnConnected)),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          read_callback_(this, &SSLSocketAdapter::OnRead)),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          write_callback_(this, &SSLSocketAdapter::OnWrite)),
      ssl_state_(SSLSTATE_NONE),
      read_state_(IOSTATE_NONE),
      write_state_(IOSTATE_NONE) {
  transport_socket_ = new TransportSocket(socket, this);
}

SSLSocketAdapter::~SSLSocketAdapter() {
}

int SSLSocketAdapter::StartSSL(const char* hostname, bool restartable) {
  DCHECK(!restartable);
  hostname_ = hostname;

  if (socket_->GetState() != Socket::CS_CONNECTED) {
    ssl_state_ = SSLSTATE_WAIT;
    return 0;
  } else {
    return BeginSSL();
  }
}

int SSLSocketAdapter::BeginSSL() {
  if (!MessageLoop::current()) {
    // Certificate verification is done via the Chrome message loop.
    // Without this check, if we don't have a chrome message loop the
    // SSL connection just hangs silently.
    LOG(DFATAL) << "Chrome message loop (needed by SSL certificate "
                << "verification) does not exist";
    return net::ERR_UNEXPECTED;
  }

  // SSLConfigService is not thread-safe, and the default values for SSLConfig
  // are correct for us, so we don't use the config service to initialize this
  // object.
  net::SSLConfig ssl_config;

  transport_socket_->set_addr(talk_base::SocketAddress(hostname_, 0));
  ssl_socket_.reset(
      net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket(
          transport_socket_, net::HostPortPair(hostname_, 443), ssl_config,
          NULL /* ssl_host_info */,
          cert_verifier_.get()));

  int result = ssl_socket_->Connect(&connected_callback_);

  if (result == net::ERR_IO_PENDING || result == net::OK) {
    return 0;
  } else {
    LOG(ERROR) << "Could not start SSL: " << net::ErrorToString(result);
    return result;
  }
}

int SSLSocketAdapter::Send(const void* buf, size_t len) {
  if (ssl_state_ != SSLSTATE_CONNECTED) {
    return AsyncSocketAdapter::Send(buf, len);
  } else {
    scoped_refptr<net::IOBuffer> transport_buf(new net::IOBuffer(len));
    memcpy(transport_buf->data(), buf, len);

    int result = ssl_socket_->Write(transport_buf, len, NULL);
    if (result == net::ERR_IO_PENDING) {
      SetError(EWOULDBLOCK);
    }
    transport_buf = NULL;
    return result;
  }
}

int SSLSocketAdapter::Recv(void* buf, size_t len) {
  switch (ssl_state_) {
    case SSLSTATE_NONE:
      return AsyncSocketAdapter::Recv(buf, len);

    case SSLSTATE_WAIT:
      SetError(EWOULDBLOCK);
      return -1;

    case SSLSTATE_CONNECTED:
      switch (read_state_) {
        case IOSTATE_NONE: {
          transport_buf_ = new net::IOBuffer(len);
          int result = ssl_socket_->Read(transport_buf_, len, &read_callback_);
          if (result >= 0) {
            memcpy(buf, transport_buf_->data(), len);
          }

          if (result == net::ERR_IO_PENDING) {
            read_state_ = IOSTATE_PENDING;
            SetError(EWOULDBLOCK);
          } else {
            if (result < 0) {
              SetError(result);
              VLOG(1) << "Socket error " << result;
            }
            transport_buf_ = NULL;
          }
          return result;
        }
        case IOSTATE_PENDING:
          SetError(EWOULDBLOCK);
          return -1;

        case IOSTATE_COMPLETE:
          memcpy(buf, transport_buf_->data(), len);
          transport_buf_ = NULL;
          read_state_ = IOSTATE_NONE;
          return data_transferred_;
      }
  }

  NOTREACHED();
  return -1;
}

void SSLSocketAdapter::OnConnected(int result) {
  if (result == net::OK) {
    ssl_state_ = SSLSTATE_CONNECTED;
    OnConnectEvent(this);
  } else {
    LOG(WARNING) << "OnConnected failed with error " << result;
  }
}

void SSLSocketAdapter::OnRead(int result) {
  DCHECK(read_state_ == IOSTATE_PENDING);
  read_state_ = IOSTATE_COMPLETE;
  data_transferred_ = result;
  AsyncSocketAdapter::OnReadEvent(this);
}

void SSLSocketAdapter::OnWrite(int result) {
  DCHECK(write_state_ == IOSTATE_PENDING);
  write_state_ = IOSTATE_COMPLETE;
  data_transferred_ = result;
  AsyncSocketAdapter::OnWriteEvent(this);
}

void SSLSocketAdapter::OnConnectEvent(talk_base::AsyncSocket* socket) {
  if (ssl_state_ != SSLSTATE_WAIT) {
    AsyncSocketAdapter::OnConnectEvent(socket);
  } else {
    ssl_state_ = SSLSTATE_NONE;
    int result = BeginSSL();
    if (0 != result) {
      // TODO(zork): Handle this case gracefully.
      LOG(WARNING) << "BeginSSL() failed with " << result;
    }
  }
}

TransportSocket::TransportSocket(talk_base::AsyncSocket* socket,
                                 SSLSocketAdapter *ssl_adapter)
    : read_callback_(NULL),
      write_callback_(NULL),
      read_buffer_len_(0),
      write_buffer_len_(0),
      socket_(socket),
      was_used_to_convey_data_(false) {
  socket_->SignalReadEvent.connect(this, &TransportSocket::OnReadEvent);
  socket_->SignalWriteEvent.connect(this, &TransportSocket::OnWriteEvent);
}

TransportSocket::~TransportSocket() {
}

int TransportSocket::Connect(net::CompletionCallback* callback) {
  // Connect is never called by SSLClientSocket, instead SSLSocketAdapter
  // calls Connect() on socket_ directly.
  NOTREACHED();
  return false;
}

void TransportSocket::Disconnect() {
  socket_->Close();
}

bool TransportSocket::IsConnected() const {
  return (socket_->GetState() == talk_base::Socket::CS_CONNECTED);
}

bool TransportSocket::IsConnectedAndIdle() const {
  // Not implemented.
  NOTREACHED();
  return false;
}

int TransportSocket::GetPeerAddress(net::AddressList* address) const {
  talk_base::SocketAddress socket_address = socket_->GetRemoteAddress();

  // libjingle supports only IPv4 addresses.
  sockaddr_in ipv4addr;
  socket_address.ToSockAddr(&ipv4addr);

  struct addrinfo ai;
  memset(&ai, 0, sizeof(ai));
  ai.ai_family = ipv4addr.sin_family;
  ai.ai_socktype = SOCK_STREAM;
  ai.ai_protocol = IPPROTO_TCP;
  ai.ai_addr = reinterpret_cast<struct sockaddr*>(&ipv4addr);
  ai.ai_addrlen = sizeof(ipv4addr);

  *address = net::AddressList::CreateByCopyingFirstAddress(&ai);
  return net::OK;
}

int TransportSocket::GetLocalAddress(net::IPEndPoint* address) const {
  talk_base::SocketAddress socket_address = socket_->GetLocalAddress();
  if (jingle_glue::SocketAddressToIPEndPoint(socket_address, address)) {
    return net::OK;
  } else {
    return net::ERR_FAILED;
  }
}

const net::BoundNetLog& TransportSocket::NetLog() const {
  return net_log_;
}

void TransportSocket::SetSubresourceSpeculation() {
  NOTREACHED();
}

void TransportSocket::SetOmniboxSpeculation() {
  NOTREACHED();
}

bool TransportSocket::WasEverUsed() const {
  // We don't use this in ClientSocketPools, so this should never be used.
  NOTREACHED();
  return was_used_to_convey_data_;
}

bool TransportSocket::UsingTCPFastOpen() const {
  return false;
}

int TransportSocket::Read(net::IOBuffer* buf, int buf_len,
                          net::CompletionCallback* callback) {
  DCHECK(buf);
  DCHECK(!read_callback_);
  DCHECK(!read_buffer_.get());
  int result = socket_->Recv(buf->data(), buf_len);
  if (result < 0) {
    result = net::MapSystemError(socket_->GetError());
    if (result == net::ERR_IO_PENDING) {
      read_callback_ = callback;
      read_buffer_ = buf;
      read_buffer_len_ = buf_len;
    }
  }
  if (result != net::ERR_IO_PENDING)
    was_used_to_convey_data_ = true;
  return result;
}

int TransportSocket::Write(net::IOBuffer* buf, int buf_len,
                           net::CompletionCallback* callback) {
  DCHECK(buf);
  DCHECK(!write_callback_);
  DCHECK(!write_buffer_.get());
  int result = socket_->Send(buf->data(), buf_len);
  if (result < 0) {
    result = net::MapSystemError(socket_->GetError());
    if (result == net::ERR_IO_PENDING) {
      write_callback_ = callback;
      write_buffer_ = buf;
      write_buffer_len_ = buf_len;
    }
  }
  if (result != net::ERR_IO_PENDING)
    was_used_to_convey_data_ = true;
  return result;
}

bool TransportSocket::SetReceiveBufferSize(int32 size) {
  // Not implemented.
  return false;
}

bool TransportSocket::SetSendBufferSize(int32 size) {
  // Not implemented.
  return false;
}

void TransportSocket::OnReadEvent(talk_base::AsyncSocket* socket) {
  if (read_callback_) {
    DCHECK(read_buffer_.get());
    net::CompletionCallback* callback = read_callback_;
    scoped_refptr<net::IOBuffer> buffer = read_buffer_;
    int buffer_len = read_buffer_len_;

    read_callback_ = NULL;
    read_buffer_ = NULL;
    read_buffer_len_ = 0;

    int result = socket_->Recv(buffer->data(), buffer_len);
    if (result < 0) {
      result = net::MapSystemError(socket_->GetError());
      if (result == net::ERR_IO_PENDING) {
        read_callback_ = callback;
        read_buffer_ = buffer;
        read_buffer_len_ = buffer_len;
        return;
      }
    }
    was_used_to_convey_data_ = true;
    callback->RunWithParams(Tuple1<int>(result));
  }
}

void TransportSocket::OnWriteEvent(talk_base::AsyncSocket* socket) {
  if (write_callback_) {
    DCHECK(write_buffer_.get());
    net::CompletionCallback* callback = write_callback_;
    scoped_refptr<net::IOBuffer> buffer = write_buffer_;
    int buffer_len = write_buffer_len_;

    write_callback_ = NULL;
    write_buffer_ = NULL;
    write_buffer_len_ = 0;

    int result = socket_->Send(buffer->data(), buffer_len);
    if (result < 0) {
      result = net::MapSystemError(socket_->GetError());
      if (result == net::ERR_IO_PENDING) {
        write_callback_ = callback;
        write_buffer_ = buffer;
        write_buffer_len_ = buffer_len;
        return;
      }
    }
    was_used_to_convey_data_ = true;
    callback->RunWithParams(Tuple1<int>(result));
  }
}

}  // namespace remoting
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

int main(int argc, char** argv)
{
	srand((unsigned int)time(NULL));
	for(int i=0; i<15; i++)
	{
		unsigned long int l_ui32Vale1=(rand()&0x00ffffff);
		unsigned long int l_ui32Vale2=(rand()&0xffffffff);
		printf("#define OV_ClassId_                                        OpenViBE::CIdentifier(0x%08X, 0x%08X)\n", (int)l_ui32Vale1, (int)l_ui32Vale2);
	}

	return 0;
}
<commit_msg><commit_after>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

int main(int argc, char** argv)
{
	srand((unsigned int)time(NULL));
	for(int i=0; i<15; i++)
	{
		unsigned long int l_ui32Vale1=(rand()&0xffffffff);
		unsigned long int l_ui32Vale2=(rand()&0xffffffff);
		printf("#define OV_ClassId_                                        OpenViBE::CIdentifier(0x%08X, 0x%08X)\n", (int)l_ui32Vale1, (int)l_ui32Vale2);
	}

	return 0;
}
<|endoftext|>


<commit_before>#include "types.h"
#include "stat.h"
#include "user.h"
#include "mtrace.h"
#include "amd64.h"
#include "uspinlock.h"

static struct uspinlock l;
static volatile int tcount;
enum { readaccess = 1 };
enum { verbose = 0 };

void
thr(void *arg)
{
  u64 tid = (u64)arg;

  for (int i = 0; i < 10000; i++) {
    if (verbose && ((i % 100) == 0))
      fprintf(1, "%d: %d ops\n", tid, i);

    volatile char *p = (char*) (0x40000UL + tid * 8 * 4096);
    if (map((void *) p, 8 * 4096) < 0) {
      fprintf(1, "%d: map failed\n", tid);
      exit();
    }

    if (readaccess) {
      for (int j = 0; j < 8 * 4096; j++)
	p[j] = '\0';
    }

    if (unmap((void *) p, 8 * 4096) < 0) {
      fprintf(1, "%d: unmap failed\n", tid);
      exit();
    }
  }

  acquire(&l);
  // fprintf(1, "mapbench[%d]: done\n", getpid());
  tcount++;
  release(&l);
}

int
main(int ac, char **av)
{
  mtenable("xv6-mapbench");

  if (ac != 2) {
    fprintf(1, "usage: %s nthreads\n", av[0]);
    exit();
  }

  int nthread = atoi(av[1]);

  acquire(&l);
  // fprintf(1, "mapbench[%d]: start esp %x, nthread=%d\n", getpid(), rrsp(), nthread);

  for(int i = 0; i < nthread; i++) {
    sbrk(8192);
    void *tstack = sbrk(0);
    // fprintf(1, "tstack %lx\n", tstack);
    int tid = forkt(tstack, (void*) thr, (void *)(u64)i);
    if (0) fprintf(1, "mapbench[%d]: child %d\n", getpid(), tid);
  }

  for(;;){
    int lastc = tcount;
    // fprintf(1, "mapbench[%d]: tcount=%d\n", getpid(), lastc);
    release(&l);
    if(lastc==nthread)
      break;
    while(tcount==lastc)
      __asm __volatile("":::"memory");
    acquire(&l);
  }
  release(&l);
  // fprintf(1, "mapbench[%d]: done\n", getpid());

  for(int i = 0; i < nthread; i++)
    wait();

  mtdisable("xv6-mapbench");
  // halt();
  exit();
}
<commit_msg>benchmark 1M map/unmap ops, no PFs<commit_after>#include "types.h"
#include "stat.h"
#include "user.h"
#include "mtrace.h"
#include "amd64.h"
#include "uspinlock.h"

static struct uspinlock l;
static volatile int tcount;
enum { readaccess = 0 };
enum { verbose = 0 };
enum { npg = 1 };

void
thr(void *arg)
{
  u64 tid = (u64)arg;

  for (int i = 0; i < 1000000; i++) {
    if (verbose && ((i % 100) == 0))
      fprintf(1, "%d: %d ops\n", tid, i);

    volatile char *p = (char*) (0x40000UL + tid * npg * 4096);
    if (map((void *) p, npg * 4096) < 0) {
      fprintf(1, "%d: map failed\n", tid);
      exit();
    }

    if (readaccess) {
      for (int j = 0; j < npg * 4096; j++)
	p[j] = '\0';
    }

    if (unmap((void *) p, npg * 4096) < 0) {
      fprintf(1, "%d: unmap failed\n", tid);
      exit();
    }
  }

  acquire(&l);
  // fprintf(1, "mapbench[%d]: done\n", getpid());
  tcount++;
  release(&l);
}

int
main(int ac, char **av)
{
  mtenable("xv6-mapbench");

  if (ac != 2) {
    fprintf(1, "usage: %s nthreads\n", av[0]);
    exit();
  }

  int nthread = atoi(av[1]);

  acquire(&l);
  // fprintf(1, "mapbench[%d]: start esp %x, nthread=%d\n", getpid(), rrsp(), nthread);

  for(int i = 0; i < nthread; i++) {
    sbrk(8192);
    void *tstack = sbrk(0);
    // fprintf(1, "tstack %lx\n", tstack);
    int tid = forkt(tstack, (void*) thr, (void *)(u64)i);
    if (0) fprintf(1, "mapbench[%d]: child %d\n", getpid(), tid);
  }

  for(;;){
    int lastc = tcount;
    // fprintf(1, "mapbench[%d]: tcount=%d\n", getpid(), lastc);
    release(&l);
    if(lastc==nthread)
      break;
    while(tcount==lastc)
      __asm __volatile("":::"memory");
    acquire(&l);
  }
  release(&l);
  // fprintf(1, "mapbench[%d]: done\n", getpid());

  for(int i = 0; i < nthread; i++)
    wait();

  mtdisable("xv6-mapbench");
  // halt();
  exit();
}
<|endoftext|>


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

#ifndef SC_XECONTENT_HXX
#define SC_XECONTENT_HXX

#ifndef SC_RANGELST_HXX
#include "rangelst.hxx"
#endif

#ifndef SC_XLCONTENT_HXX
#include "xlcontent.hxx"
#endif
#ifndef SC_XLADDRESS_HXX
#include "xladdress.hxx"
#endif
#ifndef SC_XEROOT_HXX
#include "xeroot.hxx"
#endif
#ifndef SC_XERECORD_HXX
#include "xerecord.hxx"
#endif
#ifndef SC_XESTRING_HXX
#include "xestring.hxx"
#endif
#ifndef SC_XEFORMULA_HXX
#include "xeformula.hxx"
#endif

/* ============================================================================
Classes to export the big Excel document contents (related to several cells or
globals for the sheet or document).
- Shared string table
- Merged cells
- Hyperlinks
- Label ranges
- Conditional formatting
- Data validation
- Web Queries
============================================================================ */

// Shared string table ========================================================

class XclExpSstImpl;

/** Provides export of the SST (shared string table) record.
    @descr  Contains all strings in the document and writes the SST. */
class XclExpSst : public XclExpRecordBase
{
public:
    explicit            XclExpSst();
    virtual             ~XclExpSst();

    /** Inserts a new string into the table.
        @return  The index of the string in the SST, used in other records. */
    sal_uInt32          Insert( XclExpStringRef xString );

    /** Writes the complete SST and EXTSST records. */
    virtual void        Save( XclExpStream& rStrm );

private:
    typedef ::std::auto_ptr< XclExpSstImpl > XclExpSstImplPtr;
    XclExpSstImplPtr    mxImpl;
};

// Merged cells ===============================================================

/** Represents a MERGEDCELLS record containing all merged cell ranges in a sheet. */
class XclExpMergedcells : public XclExpRecordBase, protected XclExpRoot
{
public:
    explicit            XclExpMergedcells( const XclExpRoot& rRoot );

    /** Appends a new range to the list of merged cell ranges. */
    void                AppendRange( const ScRange& rRange, sal_uInt32 nBaseXFId );
    /** Returns the XF identifier of the top-left cell in a merged range. */
    sal_uInt32          GetBaseXFId( const ScAddress& rPos ) const;

    /** Writes the record, if it contains at least one merged cell range. */
    virtual void        Save( XclExpStream& rStrm );

private:
    ScRangeList         maMergedRanges;     /// All merged cell ranges of the sheet.
    ScfUInt32Vec        maBaseXFIds;        /// The XF identifiers of the top-left cells.
};

// Hyperlinks =================================================================

class SvxURLField;
class INetURLObject;

/** Provides export of hyperlink data. */
class XclExpHyperlink : public XclExpRecord
{
public:
    /** Constructs the HLINK record from an URL text field. */
    explicit            XclExpHyperlink( const XclExpRoot& rRoot,
                            const SvxURLField& rUrlField, const ScAddress& rScPos );
    virtual             ~XclExpHyperlink();

    /** Returns the cell representation text or 0, if not available. */
    inline const String* GetRepr() const { return mxRepr.get(); }

private:
    /** Builds file name from the passed file URL. Tries to convert to relative file name.
        @param rnLevel  (out-param) The parent directory level.
        @param rbRel  (out-param) true = path is relative. */
    String              BuildFileName(
                            sal_uInt16& rnLevel, bool& rbRel,
                            const String& rUrl, const XclExpRoot& rRoot ) const;

    /** Writes the body of the HLINK record. */
    virtual void        WriteBody( XclExpStream& rStrm );

private:
    typedef ::std::auto_ptr< String >   StringPtr;
    typedef ::std::auto_ptr< SvStream > SvStreamPtr;

    ScAddress           maScPos;            /// Position of the hyperlink.
    StringPtr           mxRepr;             /// Cell representation text.
    SvStreamPtr         mxVarData;          /// Buffer stream with variable data.
    sal_uInt32          mnFlags;            /// Option flags.
};

typedef XclExpRecordList< XclExpHyperlink > XclExpHyperlinkList;

// Label ranges ===============================================================

/** Provides export of the row/column label range list of a sheet. */
class XclExpLabelranges : public XclExpRecordBase, protected XclExpRoot
{
public:
    /** Fills the cell range lists with all ranges of the current sheet. */
    explicit            XclExpLabelranges( const XclExpRoot& rRoot );

    /** Writes the LABELRANGES record if it contains at least one range. */
    virtual void        Save( XclExpStream& rStrm );

private:
    /** Fills the specified range list with all label headers of the current sheet.
        @param rRanges  The cell range list to fill.
        @param xLabelRangesRef  The core range list with all ranges.
        @param nScTab  The current Calc sheet index. */
    void                FillRangeList( ScRangeList& rScRanges,
                            ScRangePairListRef xLabelRangesRef, SCTAB nScTab );

private:
    ScRangeList         maRowRanges;    /// Cell range list for row labels.
    ScRangeList         maColRanges;    /// Cell range list for column labels.
};

// Conditional formatting =====================================================

class ScCondFormatEntry;
class XclExpCFImpl;

/** Represents a CF record that contains one condition of a conditional format. */
class XclExpCF : public XclExpRecord, protected XclExpRoot
{
public:
    explicit            XclExpCF( const XclExpRoot& rRoot, const ScCondFormatEntry& rFormatEntry );
    virtual             ~XclExpCF();

private:
    /** Writes the body of the CF record. */
    virtual void        WriteBody( XclExpStream& rStrm );

private:
    typedef ::std::auto_ptr< XclExpCFImpl > XclExpCFImplPtr;
    XclExpCFImplPtr     mxImpl;
};

// ----------------------------------------------------------------------------

class ScConditionalFormat;

/** Represents a CONDFMT record that contains all conditions of a conditional format.
    @descr  Contains the conditions which are stored in CF records. */
class XclExpCondfmt : public XclExpRecord, protected XclExpRoot
{
public:
    explicit            XclExpCondfmt( const XclExpRoot& rRoot, const ScConditionalFormat& rCondFormat );
    virtual             ~XclExpCondfmt();

    /** Returns true, if this conditional format contains at least one cell range and CF record. */
    bool                IsValid() const;

    /** Writes the CONDFMT record with following CF records, if there is valid data. */
    virtual void        Save( XclExpStream& rStrm );

private:
    /** Writes the body of the CONDFMT record. */
    virtual void        WriteBody( XclExpStream& rStrm );

private:
    typedef XclExpRecordList< XclExpCF > XclExpCFList;

    XclExpCFList        maCFList;       /// List of CF records.
    XclRangeList        maXclRanges;    /// Cell ranges for this conditional format.
};

// ----------------------------------------------------------------------------

/** Contains all conditional formats of a specific sheet. */
class XclExpCondFormatBuffer : public XclExpRecordBase, protected XclExpRoot
{
public:
    /** Constructs CONDFMT and CF records containing the conditional formats of the current sheet. */
    explicit            XclExpCondFormatBuffer( const XclExpRoot& rRoot );

    /** Writes all contained CONDFMT records with their CF records. */
    virtual void        Save( XclExpStream& rStrm );

private:
    typedef XclExpRecordList< XclExpCondfmt > XclExpCondfmtList;
    XclExpCondfmtList   maCondfmtList;  /// List of CONDFMT records.
};

// Data Validation ============================================================

class ScValidationData;

/** Provides export of the data of a DV record.
    @descr  This record contains the settings for a data validation. In detail
    this is a pointer to the core validation data and a cell range list with all
    affected cells. The handle index is used to optimize list search algorithm. */
class XclExpDV : public XclExpRecord, protected XclExpRoot
{
public:
    explicit            XclExpDV( const XclExpRoot& rRoot, ULONG nScHandle );
    virtual             ~XclExpDV();

    /** Returns the core handle of the validation data. */
    inline ULONG        GetScHandle() const { return mnScHandle; }

    /** Inserts a new cell range into the cell range list. */
    void                InsertCellRange( const ScRange& rPos );
    /** Converts the Calc range list to the Excel range list.
        @return  false = Resulting range list empty - do not write this record. */
    bool                Finalize();

private:
    /** Writes the body of the DV record. */
    virtual void        WriteBody( XclExpStream& rStrm );

private:
    ScRangeList         maScRanges;     /// Calc range list with all affected cells.
    XclRangeList        maXclRanges;    /// Excel range list with all affected cells.
    XclExpString        maPromptTitle;  /// The prompt title.
    XclExpString        maPromptText;   /// The prompt text.
    XclExpString        maErrorTitle;   /// The error title.
    XclExpString        maErrorText;    /// The error text.
    XclExpStringRef     mxString1;      /// String for first condition formula.
    XclTokenArrayRef    mxTokArr1;      /// Formula for first condition.
    XclTokenArrayRef    mxTokArr2;      /// Formula for second condition.
    sal_uInt32          mnFlags;        /// Miscellaneous flags.
    ULONG               mnScHandle;     /// The core handle for quick list search.
};

// ----------------------------------------------------------------------------

/** This class contains the DV record list following the DVAL record. */
class XclExpDval : public XclExpRecord, protected XclExpRoot
{
public:
    explicit            XclExpDval( const XclExpRoot& rRoot );
    virtual             ~XclExpDval();

    /** Inserts the cell range into the range list of the DV record with the specified handle. */
    void                InsertCellRange( const ScRange& rRange, ULONG nScHandle );

    /** Writes the DVAL record and the DV record list. */
    virtual void        Save( XclExpStream& rStrm );

private:
    /** Searches for or creates a XclExpDV record object with the specified handle. */
    XclExpDV&           SearchOrCreateDv( ULONG nScHandle );

    /** Writes the body of the DVAL record. */
    virtual void        WriteBody( XclExpStream& rStrm );

private:
    typedef XclExpRecordList< XclExpDV >    XclExpDVList;
    typedef XclExpDVList::RecordRefType     XclExpDVRef;

    XclExpDVList        maDVList;       /// List of DV records
    XclExpDVRef         mxLastFoundDV;  /// For search optimization.
};

// Web Queries ================================================================

/** Contains all records for a web query (linked tables in an HTML document).
    @descr  mode 1 (entire document): mpQryTables==0, mbEntireDoc==true;
    mode 2 (all tables): mpQryTables==0, mbEntireDoc==false;
    mode 3 (custom range list): mpQryTables!=0, mbEntireDoc==false. */
class XclExpWebQuery : public XclExpRecordBase
{
public:
    /** Constructs a web query record container with settings from Calc. */
    explicit            XclExpWebQuery(
                            const String& rRangeName,
                            const String& rUrl,
                            const String& rSource,
                            sal_Int32 nRefrSecs );
    virtual             ~XclExpWebQuery();

    /** Writes all needed records for this web query. */
    virtual void        Save( XclExpStream& rStrm );

private:
    XclExpString        maDestRange;    /// Destination range.
    XclExpString        maUrl;          /// Source document URL.
    XclExpStringRef     mxQryTables;    /// List of source range names.
    sal_Int16           mnRefresh;      /// Refresh time in minutes.
    bool                mbEntireDoc;    /// true = entire document.
};

// ----------------------------------------------------------------------------

/** Contains all web query records for this document. */
class XclExpWebQueryBuffer : public XclExpRecordList< XclExpWebQuery >
{
public:
    explicit            XclExpWebQueryBuffer( const XclExpRoot& rRoot );
};

// ============================================================================

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.13.498); FILE MERGED 2008/04/01 12:36:21 thb 1.13.498.2: #i85898# Stripping all external header guards 2008/03/31 17:14:45 rt 1.13.498.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xecontent.hxx,v $
 * $Revision: 1.14 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SC_XECONTENT_HXX
#define SC_XECONTENT_HXX

#include "rangelst.hxx"
#include "xlcontent.hxx"
#include "xladdress.hxx"
#include "xeroot.hxx"
#include "xerecord.hxx"
#include "xestring.hxx"
#include "xeformula.hxx"

/* ============================================================================
Classes to export the big Excel document contents (related to several cells or
globals for the sheet or document).
- Shared string table
- Merged cells
- Hyperlinks
- Label ranges
- Conditional formatting
- Data validation
- Web Queries
============================================================================ */

// Shared string table ========================================================

class XclExpSstImpl;

/** Provides export of the SST (shared string table) record.
    @descr  Contains all strings in the document and writes the SST. */
class XclExpSst : public XclExpRecordBase
{
public:
    explicit            XclExpSst();
    virtual             ~XclExpSst();

    /** Inserts a new string into the table.
        @return  The index of the string in the SST, used in other records. */
    sal_uInt32          Insert( XclExpStringRef xString );

    /** Writes the complete SST and EXTSST records. */
    virtual void        Save( XclExpStream& rStrm );

private:
    typedef ::std::auto_ptr< XclExpSstImpl > XclExpSstImplPtr;
    XclExpSstImplPtr    mxImpl;
};

// Merged cells ===============================================================

/** Represents a MERGEDCELLS record containing all merged cell ranges in a sheet. */
class XclExpMergedcells : public XclExpRecordBase, protected XclExpRoot
{
public:
    explicit            XclExpMergedcells( const XclExpRoot& rRoot );

    /** Appends a new range to the list of merged cell ranges. */
    void                AppendRange( const ScRange& rRange, sal_uInt32 nBaseXFId );
    /** Returns the XF identifier of the top-left cell in a merged range. */
    sal_uInt32          GetBaseXFId( const ScAddress& rPos ) const;

    /** Writes the record, if it contains at least one merged cell range. */
    virtual void        Save( XclExpStream& rStrm );

private:
    ScRangeList         maMergedRanges;     /// All merged cell ranges of the sheet.
    ScfUInt32Vec        maBaseXFIds;        /// The XF identifiers of the top-left cells.
};

// Hyperlinks =================================================================

class SvxURLField;
class INetURLObject;

/** Provides export of hyperlink data. */
class XclExpHyperlink : public XclExpRecord
{
public:
    /** Constructs the HLINK record from an URL text field. */
    explicit            XclExpHyperlink( const XclExpRoot& rRoot,
                            const SvxURLField& rUrlField, const ScAddress& rScPos );
    virtual             ~XclExpHyperlink();

    /** Returns the cell representation text or 0, if not available. */
    inline const String* GetRepr() const { return mxRepr.get(); }

private:
    /** Builds file name from the passed file URL. Tries to convert to relative file name.
        @param rnLevel  (out-param) The parent directory level.
        @param rbRel  (out-param) true = path is relative. */
    String              BuildFileName(
                            sal_uInt16& rnLevel, bool& rbRel,
                            const String& rUrl, const XclExpRoot& rRoot ) const;

    /** Writes the body of the HLINK record. */
    virtual void        WriteBody( XclExpStream& rStrm );

private:
    typedef ::std::auto_ptr< String >   StringPtr;
    typedef ::std::auto_ptr< SvStream > SvStreamPtr;

    ScAddress           maScPos;            /// Position of the hyperlink.
    StringPtr           mxRepr;             /// Cell representation text.
    SvStreamPtr         mxVarData;          /// Buffer stream with variable data.
    sal_uInt32          mnFlags;            /// Option flags.
};

typedef XclExpRecordList< XclExpHyperlink > XclExpHyperlinkList;

// Label ranges ===============================================================

/** Provides export of the row/column label range list of a sheet. */
class XclExpLabelranges : public XclExpRecordBase, protected XclExpRoot
{
public:
    /** Fills the cell range lists with all ranges of the current sheet. */
    explicit            XclExpLabelranges( const XclExpRoot& rRoot );

    /** Writes the LABELRANGES record if it contains at least one range. */
    virtual void        Save( XclExpStream& rStrm );

private:
    /** Fills the specified range list with all label headers of the current sheet.
        @param rRanges  The cell range list to fill.
        @param xLabelRangesRef  The core range list with all ranges.
        @param nScTab  The current Calc sheet index. */
    void                FillRangeList( ScRangeList& rScRanges,
                            ScRangePairListRef xLabelRangesRef, SCTAB nScTab );

private:
    ScRangeList         maRowRanges;    /// Cell range list for row labels.
    ScRangeList         maColRanges;    /// Cell range list for column labels.
};

// Conditional formatting =====================================================

class ScCondFormatEntry;
class XclExpCFImpl;

/** Represents a CF record that contains one condition of a conditional format. */
class XclExpCF : public XclExpRecord, protected XclExpRoot
{
public:
    explicit            XclExpCF( const XclExpRoot& rRoot, const ScCondFormatEntry& rFormatEntry );
    virtual             ~XclExpCF();

private:
    /** Writes the body of the CF record. */
    virtual void        WriteBody( XclExpStream& rStrm );

private:
    typedef ::std::auto_ptr< XclExpCFImpl > XclExpCFImplPtr;
    XclExpCFImplPtr     mxImpl;
};

// ----------------------------------------------------------------------------

class ScConditionalFormat;

/** Represents a CONDFMT record that contains all conditions of a conditional format.
    @descr  Contains the conditions which are stored in CF records. */
class XclExpCondfmt : public XclExpRecord, protected XclExpRoot
{
public:
    explicit            XclExpCondfmt( const XclExpRoot& rRoot, const ScConditionalFormat& rCondFormat );
    virtual             ~XclExpCondfmt();

    /** Returns true, if this conditional format contains at least one cell range and CF record. */
    bool                IsValid() const;

    /** Writes the CONDFMT record with following CF records, if there is valid data. */
    virtual void        Save( XclExpStream& rStrm );

private:
    /** Writes the body of the CONDFMT record. */
    virtual void        WriteBody( XclExpStream& rStrm );

private:
    typedef XclExpRecordList< XclExpCF > XclExpCFList;

    XclExpCFList        maCFList;       /// List of CF records.
    XclRangeList        maXclRanges;    /// Cell ranges for this conditional format.
};

// ----------------------------------------------------------------------------

/** Contains all conditional formats of a specific sheet. */
class XclExpCondFormatBuffer : public XclExpRecordBase, protected XclExpRoot
{
public:
    /** Constructs CONDFMT and CF records containing the conditional formats of the current sheet. */
    explicit            XclExpCondFormatBuffer( const XclExpRoot& rRoot );

    /** Writes all contained CONDFMT records with their CF records. */
    virtual void        Save( XclExpStream& rStrm );

private:
    typedef XclExpRecordList< XclExpCondfmt > XclExpCondfmtList;
    XclExpCondfmtList   maCondfmtList;  /// List of CONDFMT records.
};

// Data Validation ============================================================

class ScValidationData;

/** Provides export of the data of a DV record.
    @descr  This record contains the settings for a data validation. In detail
    this is a pointer to the core validation data and a cell range list with all
    affected cells. The handle index is used to optimize list search algorithm. */
class XclExpDV : public XclExpRecord, protected XclExpRoot
{
public:
    explicit            XclExpDV( const XclExpRoot& rRoot, ULONG nScHandle );
    virtual             ~XclExpDV();

    /** Returns the core handle of the validation data. */
    inline ULONG        GetScHandle() const { return mnScHandle; }

    /** Inserts a new cell range into the cell range list. */
    void                InsertCellRange( const ScRange& rPos );
    /** Converts the Calc range list to the Excel range list.
        @return  false = Resulting range list empty - do not write this record. */
    bool                Finalize();

private:
    /** Writes the body of the DV record. */
    virtual void        WriteBody( XclExpStream& rStrm );

private:
    ScRangeList         maScRanges;     /// Calc range list with all affected cells.
    XclRangeList        maXclRanges;    /// Excel range list with all affected cells.
    XclExpString        maPromptTitle;  /// The prompt title.
    XclExpString        maPromptText;   /// The prompt text.
    XclExpString        maErrorTitle;   /// The error title.
    XclExpString        maErrorText;    /// The error text.
    XclExpStringRef     mxString1;      /// String for first condition formula.
    XclTokenArrayRef    mxTokArr1;      /// Formula for first condition.
    XclTokenArrayRef    mxTokArr2;      /// Formula for second condition.
    sal_uInt32          mnFlags;        /// Miscellaneous flags.
    ULONG               mnScHandle;     /// The core handle for quick list search.
};

// ----------------------------------------------------------------------------

/** This class contains the DV record list following the DVAL record. */
class XclExpDval : public XclExpRecord, protected XclExpRoot
{
public:
    explicit            XclExpDval( const XclExpRoot& rRoot );
    virtual             ~XclExpDval();

    /** Inserts the cell range into the range list of the DV record with the specified handle. */
    void                InsertCellRange( const ScRange& rRange, ULONG nScHandle );

    /** Writes the DVAL record and the DV record list. */
    virtual void        Save( XclExpStream& rStrm );

private:
    /** Searches for or creates a XclExpDV record object with the specified handle. */
    XclExpDV&           SearchOrCreateDv( ULONG nScHandle );

    /** Writes the body of the DVAL record. */
    virtual void        WriteBody( XclExpStream& rStrm );

private:
    typedef XclExpRecordList< XclExpDV >    XclExpDVList;
    typedef XclExpDVList::RecordRefType     XclExpDVRef;

    XclExpDVList        maDVList;       /// List of DV records
    XclExpDVRef         mxLastFoundDV;  /// For search optimization.
};

// Web Queries ================================================================

/** Contains all records for a web query (linked tables in an HTML document).
    @descr  mode 1 (entire document): mpQryTables==0, mbEntireDoc==true;
    mode 2 (all tables): mpQryTables==0, mbEntireDoc==false;
    mode 3 (custom range list): mpQryTables!=0, mbEntireDoc==false. */
class XclExpWebQuery : public XclExpRecordBase
{
public:
    /** Constructs a web query record container with settings from Calc. */
    explicit            XclExpWebQuery(
                            const String& rRangeName,
                            const String& rUrl,
                            const String& rSource,
                            sal_Int32 nRefrSecs );
    virtual             ~XclExpWebQuery();

    /** Writes all needed records for this web query. */
    virtual void        Save( XclExpStream& rStrm );

private:
    XclExpString        maDestRange;    /// Destination range.
    XclExpString        maUrl;          /// Source document URL.
    XclExpStringRef     mxQryTables;    /// List of source range names.
    sal_Int16           mnRefresh;      /// Refresh time in minutes.
    bool                mbEntireDoc;    /// true = entire document.
};

// ----------------------------------------------------------------------------

/** Contains all web query records for this document. */
class XclExpWebQueryBuffer : public XclExpRecordList< XclExpWebQuery >
{
public:
    explicit            XclExpWebQueryBuffer( const XclExpRoot& rRoot );
};

// ============================================================================

#endif

<|endoftext|>