<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "supservs.hxx"
#include <com/sun/star/lang/Locale.hpp>
#include <comphelper/sharedmutex.hxx>
#include <cppuhelper/supportsservice.hxx>
#include <cppuhelper/queryinterface.hxx>
#include <i18nlangtag/mslangid.hxx>
#include <tools/debug.hxx>
#include <osl/mutex.hxx>
#include <osl/diagnose.h>
#include <tools/stream.hxx>
#include <svl/instrm.hxx>

#include <registerservices.hxx>
#include <strmadpt.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::utl;

Reference< XInterface > SAL_CALL SvNumberFormatsSupplierServiceObject_CreateInstance(const Reference< XMultiServiceFactory >& _rxFactory)
{
    return static_cast< ::cppu::OWeakObject* >(new SvNumberFormatsSupplierServiceObject( comphelper::getComponentContext(_rxFactory) ));
}

SvNumberFormatsSupplierServiceObject::SvNumberFormatsSupplierServiceObject(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxORB)
    :m_pOwnFormatter(NULL)
    ,m_xORB(_rxORB)
{
}

SvNumberFormatsSupplierServiceObject::~SvNumberFormatsSupplierServiceObject()
{
    if (m_pOwnFormatter)
    {
        delete m_pOwnFormatter;
        m_pOwnFormatter = NULL;
    }
}

Any SAL_CALL SvNumberFormatsSupplierServiceObject::queryAggregation( const Type& _rType ) throw (RuntimeException, std::exception)
{
    Any aReturn = ::cppu::queryInterface(_rType,
        static_cast< XInitialization* >(this),
        static_cast< XServiceInfo* >(this)
    );

    if (!aReturn.hasValue())
        aReturn = SvNumberFormatsSupplierObj::queryAggregation(_rType);

    return aReturn;
}

void SAL_CALL SvNumberFormatsSupplierServiceObject::initialize( const Sequence< Any >& _rArguments ) throw(Exception, RuntimeException, std::exception)
{
    ::osl::MutexGuard aGuard( getSharedMutex() );

    DBG_ASSERT(m_pOwnFormatter == NULL,
        "SvNumberFormatsSupplierServiceObject::initialize : already initialized !");
        // maybe you already called a method which needed the formatter
        // you should use XMultiServiceFactory::createInstanceWithArguments to avoid that
    if (m_pOwnFormatter)
    {   // !!! this is only a emergency handling, normally this should not occur !!!
        delete m_pOwnFormatter;
        m_pOwnFormatter = NULL;
        SetNumberFormatter(m_pOwnFormatter);
    }

    Type aExpectedArgType = ::cppu::UnoType<Locale>::get();
    LanguageType eNewFormatterLanguage = LANGUAGE_ENGLISH_US;
        // the default

    const Any* pArgs = _rArguments.getConstArray();
    for (sal_Int32 i=0; i<_rArguments.getLength(); ++i, ++pArgs)
    {
        if (pArgs->getValueType().equals(aExpectedArgType))
        {
            Locale aLocale;
            *pArgs >>= aLocale;
            eNewFormatterLanguage = LanguageTag::convertToLanguageType( aLocale, false);
        }
#ifdef DBG_UTIL
        else
        {
            OSL_FAIL("SvNumberFormatsSupplierServiceObject::initialize : unknown argument !");
        }
#endif
    }

    m_pOwnFormatter = new SvNumberFormatter( m_xORB, eNewFormatterLanguage);
    m_pOwnFormatter->SetEvalDateFormat( NF_EVALDATEFORMAT_FORMAT_INTL );
    SetNumberFormatter(m_pOwnFormatter);
}

OUString SAL_CALL SvNumberFormatsSupplierServiceObject::getImplementationName(  ) throw(RuntimeException, std::exception)
{
    return OUString("com.sun.star.uno.util.numbers.SvNumberFormatsSupplierServiceObject");
}

sal_Bool SAL_CALL SvNumberFormatsSupplierServiceObject::supportsService( const OUString& _rServiceName ) throw(RuntimeException, std::exception)
{
    return cppu::supportsService(this, _rServiceName);
}

Sequence< OUString > SAL_CALL SvNumberFormatsSupplierServiceObject::getSupportedServiceNames(  ) throw(RuntimeException, std::exception)
{
    Sequence< OUString > aSupported(1);
    aSupported.getArray()[0] = "com.sun.star.util.NumberFormatsSupplier";
    return aSupported;
}

Reference< XPropertySet > SAL_CALL SvNumberFormatsSupplierServiceObject::getNumberFormatSettings() throw(RuntimeException, std::exception)
{
    ::osl::MutexGuard aGuard( getSharedMutex() );
    implEnsureFormatter();
    return SvNumberFormatsSupplierObj::getNumberFormatSettings();
}

Reference< XNumberFormats > SAL_CALL SvNumberFormatsSupplierServiceObject::getNumberFormats() throw(RuntimeException, std::exception)
{
    ::osl::MutexGuard aGuard( getSharedMutex() );
    implEnsureFormatter();
    return SvNumberFormatsSupplierObj::getNumberFormats();
}

sal_Int64 SAL_CALL SvNumberFormatsSupplierServiceObject::getSomething( const Sequence< sal_Int8 >& aIdentifier ) throw (RuntimeException, std::exception)
{
    sal_Int64 nReturn = SvNumberFormatsSupplierObj::getSomething( aIdentifier );
    if ( nReturn )
        // if somebody accesses internals then we should have the formatter
        implEnsureFormatter();
    return nReturn;
}

void SvNumberFormatsSupplierServiceObject::implEnsureFormatter()
{
    if (!m_pOwnFormatter)
    {
        // get the office's UI locale
        SvtSysLocale aSysLocale;
        Locale aOfficeLocale = aSysLocale.GetLocaleData().getLanguageTag().getLocale();

        // initi with this locale
        Sequence< Any > aFakedInitProps( 1 );
        aFakedInitProps[0] <<= aOfficeLocale;

        initialize( aFakedInitProps );
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>yet another Windows build fix<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "supservs.hxx"
#include <com/sun/star/lang/Locale.hpp>
#include <comphelper/sharedmutex.hxx>
#include <cppuhelper/supportsservice.hxx>
#include <cppuhelper/queryinterface.hxx>
#include <i18nlangtag/mslangid.hxx>
#include <tools/debug.hxx>
#include <osl/mutex.hxx>
#include <osl/diagnose.h>
#include <tools/stream.hxx>
#include <svl/instrm.hxx>

#include <registerservices.hxx>
#include <strmadpt.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::utl;

Reference< XInterface > SAL_CALL SvNumberFormatsSupplierServiceObject_CreateInstance(const Reference< XMultiServiceFactory >& _rxFactory)
{
    return static_cast< ::cppu::OWeakObject* >(new SvNumberFormatsSupplierServiceObject( comphelper::getComponentContext(_rxFactory) ));
}

SvNumberFormatsSupplierServiceObject::SvNumberFormatsSupplierServiceObject(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxORB)
    :m_pOwnFormatter(NULL)
    ,m_xORB(_rxORB)
{
}

SvNumberFormatsSupplierServiceObject::~SvNumberFormatsSupplierServiceObject()
{
    if (m_pOwnFormatter)
    {
        delete m_pOwnFormatter;
        m_pOwnFormatter = NULL;
    }
}

Any SAL_CALL SvNumberFormatsSupplierServiceObject::queryAggregation( const Type& _rType ) throw (RuntimeException, std::exception)
{
    Any aReturn = ::cppu::queryInterface(_rType,
        static_cast< XInitialization* >(this),
        static_cast< XServiceInfo* >(this)
    );

    if (!aReturn.hasValue())
        aReturn = SvNumberFormatsSupplierObj::queryAggregation(_rType);

    return aReturn;
}

void SAL_CALL SvNumberFormatsSupplierServiceObject::initialize( const Sequence< Any >& _rArguments ) throw(Exception, RuntimeException, std::exception)
{
    ::osl::MutexGuard aGuard( getSharedMutex() );

    DBG_ASSERT(m_pOwnFormatter == NULL,
        "SvNumberFormatsSupplierServiceObject::initialize : already initialized !");
        // maybe you already called a method which needed the formatter
        // you should use XMultiServiceFactory::createInstanceWithArguments to avoid that
    if (m_pOwnFormatter)
    {   // !!! this is only a emergency handling, normally this should not occur !!!
        delete m_pOwnFormatter;
        m_pOwnFormatter = NULL;
        SetNumberFormatter(m_pOwnFormatter);
    }

    Type aExpectedArgType = ::cppu::UnoType<css::lang::Locale>::get();
    LanguageType eNewFormatterLanguage = LANGUAGE_ENGLISH_US;
        // the default

    const Any* pArgs = _rArguments.getConstArray();
    for (sal_Int32 i=0; i<_rArguments.getLength(); ++i, ++pArgs)
    {
        if (pArgs->getValueType().equals(aExpectedArgType))
        {
            css::lang::Locale aLocale;
            *pArgs >>= aLocale;
            eNewFormatterLanguage = LanguageTag::convertToLanguageType( aLocale, false);
        }
#ifdef DBG_UTIL
        else
        {
            OSL_FAIL("SvNumberFormatsSupplierServiceObject::initialize : unknown argument !");
        }
#endif
    }

    m_pOwnFormatter = new SvNumberFormatter( m_xORB, eNewFormatterLanguage);
    m_pOwnFormatter->SetEvalDateFormat( NF_EVALDATEFORMAT_FORMAT_INTL );
    SetNumberFormatter(m_pOwnFormatter);
}

OUString SAL_CALL SvNumberFormatsSupplierServiceObject::getImplementationName(  ) throw(RuntimeException, std::exception)
{
    return OUString("com.sun.star.uno.util.numbers.SvNumberFormatsSupplierServiceObject");
}

sal_Bool SAL_CALL SvNumberFormatsSupplierServiceObject::supportsService( const OUString& _rServiceName ) throw(RuntimeException, std::exception)
{
    return cppu::supportsService(this, _rServiceName);
}

Sequence< OUString > SAL_CALL SvNumberFormatsSupplierServiceObject::getSupportedServiceNames(  ) throw(RuntimeException, std::exception)
{
    Sequence< OUString > aSupported(1);
    aSupported.getArray()[0] = "com.sun.star.util.NumberFormatsSupplier";
    return aSupported;
}

Reference< XPropertySet > SAL_CALL SvNumberFormatsSupplierServiceObject::getNumberFormatSettings() throw(RuntimeException, std::exception)
{
    ::osl::MutexGuard aGuard( getSharedMutex() );
    implEnsureFormatter();
    return SvNumberFormatsSupplierObj::getNumberFormatSettings();
}

Reference< XNumberFormats > SAL_CALL SvNumberFormatsSupplierServiceObject::getNumberFormats() throw(RuntimeException, std::exception)
{
    ::osl::MutexGuard aGuard( getSharedMutex() );
    implEnsureFormatter();
    return SvNumberFormatsSupplierObj::getNumberFormats();
}

sal_Int64 SAL_CALL SvNumberFormatsSupplierServiceObject::getSomething( const Sequence< sal_Int8 >& aIdentifier ) throw (RuntimeException, std::exception)
{
    sal_Int64 nReturn = SvNumberFormatsSupplierObj::getSomething( aIdentifier );
    if ( nReturn )
        // if somebody accesses internals then we should have the formatter
        implEnsureFormatter();
    return nReturn;
}

void SvNumberFormatsSupplierServiceObject::implEnsureFormatter()
{
    if (!m_pOwnFormatter)
    {
        // get the office's UI locale
        SvtSysLocale aSysLocale;
        css::lang::Locale aOfficeLocale = aSysLocale.GetLocaleData().getLanguageTag().getLocale();

        // initi with this locale
        Sequence< Any > aFakedInitProps( 1 );
        aFakedInitProps[0] <<= aOfficeLocale;

        initialize( aFakedInitProps );
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "lua.hpp"
#include <osg/MatrixTransform>
#include "osgLuaBinding.h"

osg::Node* swig_lua_toOsgNode(lua_State* L, int index);

osg::Node* lua_toOsgNode(lua_State *L, int index)
{
    osg::ref_ptr<osg::Node> node = swig_lua_toOsgNode(L, index);
    if (!node && lua_istable(L, index) && lua_checkstack(L, 2))
    {
        osg::ref_ptr<osg::Group> group = new osg::Group;

        lua_pushnil(L);  /* first key */
        int tableIndex = index >= 0 ? index : index-1;
        while (lua_next(L, tableIndex) != 0)
        {
            osg::ref_ptr<osg::Node> tableNode = lua_toOsgNode(L, -1);
            if (tableNode.valid())
            {
                osg::ref_ptr<osg::Group> indexNode = lua_toOsgMatrixTransform(L, -2);
                if (indexNode.valid())
                {
                    indexNode->addChild(tableNode);
                    tableNode = indexNode;
                }
                group->addChild(tableNode);
            }
            lua_pop(L, 1);
        }

        if (group->getNumChildren() == 1)
        {
            node = group->getChild(0);
        }
        else if (group->getNumChildren() > 0)
        {
            node = group;
        }
    }
    return node.release();
}

osg::Group* lua_toOsgMatrixTransform(lua_State *L, int index)
{
    if(lua_istable(L, index))
    {
        osg::Vec3 vec3 = lua_toOsgVec3(L, index);
        if (vec3.valid())
        {
            osg::Matrix matrix;
            matrix.setTrans(vec3);
            osg::ref_ptr<osg::MatrixTransform> matrixTransform = new osg::MatrixTransform(matrix);
            return matrixTransform.release();
        }
    }
    return 0;
}

template <class V>
const V lua_toOsgVec(lua_State *L, int index, char firstComponentName)
{
    V vec;
    if (lua_istable(L, index) && lua_checkstack(L, 2))
    {
        unsigned int vecComponentMask = 0;
        const unsigned int vecComponentCompleteMask = (1 << vec.num_components) - 1;

        lua_pushnil(L);  /* first key */
        int tableIndex = index >= 0 ? index : index-1;
        while (lua_next(L, tableIndex) != 0)
        {
            int vecComponentPos = -1;
            if (lua_isnumber(L, -2))
            {
                vecComponentPos = lua_tonumber(L, -2) - 1;
            }
            else if(lua_isstring(L, -2) && lua_objlen(L, -2) == 1)
            {
                vecComponentPos = lua_tostring(L, -2)[0] - firstComponentName;
            }

            if (vecComponentPos >= 0 && vecComponentPos < vec.num_components)
            {
                vecComponentMask |= 1 << vecComponentPos;
                if (lua_isnumber(L, -1))
                {
                    vec[vecComponentPos] = lua_tonumber(L, -1);
                }
                else
                {
                    vec[vecComponentPos] = NAN;
                }
            }

            lua_pop(L, 1);
            if (vecComponentMask == vecComponentCompleteMask)
            {
                lua_pop(L, 1);
                break;
            }
        }
    }
    else
    {
        vec[0] = NAN;
    }
    return vec;
}
<commit_msg>adding inline fonction to decrement lua stack index<commit_after>#include "lua.hpp"
#include <osg/MatrixTransform>
#include "osgLuaBinding.h"

static inline int lua_decrement(int index)
{
    return index < 0 && index > LUA_REGISTRYINDEX ? index-1 : index;
}

osg::Node* swig_lua_toOsgNode(lua_State* L, int index);

osg::Node* lua_toOsgNode(lua_State *L, int index)
{
    osg::ref_ptr<osg::Node> node = swig_lua_toOsgNode(L, index);
    if (!node && lua_istable(L, index) && lua_checkstack(L, 2))
    {
        osg::ref_ptr<osg::Group> group = new osg::Group;

        lua_pushnil(L);  /* first key */
        int tableIndex = lua_decrement(index);
        while (lua_next(L, tableIndex) != 0)
        {
            osg::ref_ptr<osg::Node> tableNode = lua_toOsgNode(L, -1);
            if (tableNode.valid())
            {
                osg::ref_ptr<osg::Group> indexNode = lua_toOsgMatrixTransform(L, -2);
                if (indexNode.valid())
                {
                    indexNode->addChild(tableNode);
                    tableNode = indexNode;
                }
                group->addChild(tableNode);
            }
            lua_pop(L, 1);
        }

        if (group->getNumChildren() == 1)
        {
            node = group->getChild(0);
        }
        else if (group->getNumChildren() > 0)
        {
            node = group;
        }
    }
    return node.release();
}

osg::Group* lua_toOsgMatrixTransform(lua_State *L, int index)
{
    if(lua_istable(L, index))
    {
        osg::Vec3 vec3 = lua_toOsgVec3(L, index);
        if (vec3.valid())
        {
            osg::Matrix matrix;
            matrix.setTrans(vec3);
            osg::ref_ptr<osg::MatrixTransform> matrixTransform = new osg::MatrixTransform(matrix);
            return matrixTransform.release();
        }
    }
    return 0;
}

template <class V>
const V lua_toOsgVec(lua_State *L, int index, char firstComponentName)
{
    V vec;
    if (lua_istable(L, index) && lua_checkstack(L, 2))
    {
        unsigned int vecComponentMask = 0;
        const unsigned int vecComponentCompleteMask = (1 << vec.num_components) - 1;

        lua_pushnil(L);  /* first key */
        int tableIndex = lua_decrement(index);
        while (lua_next(L, tableIndex) != 0)
        {
            int vecComponentPos = -1;
            if (lua_isnumber(L, -2))
            {
                vecComponentPos = lua_tonumber(L, -2) - 1;
            }
            else if(lua_isstring(L, -2) && lua_objlen(L, -2) == 1)
            {
                vecComponentPos = lua_tostring(L, -2)[0] - firstComponentName;
            }

            if (vecComponentPos >= 0 && vecComponentPos < vec.num_components)
            {
                vecComponentMask |= 1 << vecComponentPos;
                if (lua_isnumber(L, -1))
                {
                    vec[vecComponentPos] = lua_tonumber(L, -1);
                }
                else
                {
                    vec[vecComponentPos] = NAN;
                }
            }

            lua_pop(L, 1);
            if (vecComponentMask == vecComponentCompleteMask)
            {
                lua_pop(L, 1);
                break;
            }
        }
    }
    else
    {
        vec[0] = NAN;
    }
    return vec;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008 Apple Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "NetworkStateNotifier.h"

namespace WebCore {

// Chromium doesn't currently support network state notifications. This causes
// an extra DLL to get loaded into the renderer which can slow things down a
// bit. We may want an alternate design.

void NetworkStateNotifier::updateState()
{
}

NetworkStateNotifier::NetworkStateNotifier()
    : m_isOnLine(true)
{
}

}
<commit_msg>Fix assert in debug. I had this change locally and forgot to include it in the CL that landed the merge. Fixes test_shell_tests crash as well.<commit_after>/*
 * Copyright (C) 2008 Apple Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "NetworkStateNotifier.h"

namespace WebCore {

// Chromium doesn't currently support network state notifications. This causes
// an extra DLL to get loaded into the renderer which can slow things down a
// bit. We may want an alternate design.

void NetworkStateNotifier::updateState()
{
}

NetworkStateNotifier::NetworkStateNotifier()
    : m_isOnLine(true)
    , m_networkStateChangedFunction(0)
{
}

}
<|endoftext|>


<commit_before>#pragma once

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/version.hpp>

#include "blackhole/error.hpp"
#include "blackhole/factory.hpp"
#include "blackhole/sink/files/rotation.hpp"

namespace blackhole {

namespace sink {

class boost_backend_t {
    const boost::filesystem::path m_path;
    boost::filesystem::ofstream m_file;
public:
    boost_backend_t(const std::string& path) :
        m_path(path)
    {
    }

    bool opened() const {
        return m_file.is_open();
    }

    bool exists(const std::string& filename) const {
        return boost::filesystem::exists(m_path.parent_path() / filename);
    }

    std::vector<std::string> listdir() const {
        //!@todo: Implement me!
        return std::vector<std::string>();
    }

    std::time_t changed(const std::string&) const {
        //!@todo: Implement me!
        return std::time(nullptr);
    }

    bool open() {
        if (!create_directories(m_path.parent_path())) {
            return false;
        }

        m_file.open(m_path, std::ios_base::out | std::ios_base::app);
        return m_file.is_open();
    }

    void close() {
        m_file.close();
    }

    void rename(const std::string& oldname, const std::string& newname) {
        const boost::filesystem::path& path = m_path.parent_path();
        boost::filesystem::rename(path / oldname, path / newname);
    }

    std::string filename() const {
#if BOOST_VERSION >= 104600
        return m_path.filename().string();
#else
        return m_path.filename();
#endif
    }

    std::string path() const {
        return m_path.string();
    }

    void write(const std::string& message) {
        m_file.write(message.data(), static_cast<std::streamsize>(message.size()));
        m_file.put('\n');
    }

    void flush() {
        m_file.flush();
    }

private:
    template<typename Path>
    bool create_directories(const Path& path) {
        try {
            boost::filesystem::create_directories(path);
        } catch (const boost::filesystem::filesystem_error&) {
            return false;
        }

        return true;
    }
};

namespace file {

template<class Rotator = NoRotation>
struct config_t {
    std::string path;
    bool autoflush;

    config_t(const std::string& path = "/dev/stdout", bool autoflush = true) :
        path(path),
        autoflush(autoflush)
    {}
};

template<class Backend, class Watcher, class Timer>
struct config_t<rotator_t<Backend, Watcher, Timer>> {
    std::string path;
    bool autoflush;
    rotation::config_t rotator;

    config_t(const std::string& path = "/dev/stdout", bool autoflush = true, const rotation::config_t& rotator = rotation::config_t()) :
        path(path),
        autoflush(autoflush),
        rotator(rotator)
    {}
};

} // namespace file

template<class Backend>
class writer_t {
    Backend& backend;
public:
    writer_t(Backend& backend) :
        backend(backend)
    {}

    void write(const std::string& message) {
        if (!backend.opened()) {
            if (!backend.open()) {
                throw error_t("failed to open file '%s' for writing", backend.path());
            }
        }
        backend.write(message);
    }
};

template<class Backend>
class flusher_t {
    bool autoflush;
    Backend& backend;
public:
    flusher_t(bool autoflush, Backend& backend) :
        autoflush(autoflush),
        backend(backend)
    {}

    void flush() {
        if (autoflush) {
            backend.flush();
        }
    }
};

template<class Backend = boost_backend_t, class Rotator = NoRotation, typename = void>
class file_t;

template<class Backend>
class file_t<Backend, NoRotation, void> {
    Backend m_backend;
    writer_t<Backend> m_writer;
    flusher_t<Backend> m_flusher;
public:
    typedef file::config_t<NoRotation> config_type;

    static const char* name() {
        return "files";
    }

    file_t(const config_type& config) :
        m_backend(config.path),
        m_writer(m_backend),
        m_flusher(config.autoflush, m_backend)
    {}

    void consume(const std::string& message) {
        m_writer.write(message);
        m_flusher.flush();
    }

    Backend& backend() {
        return m_backend;
    }
};

//template<template<typename...> class T, template<typename...> class U> struct is_same : public std::false_type {};
//template<template<typename...> class T> struct is_same<T, T> : public std::true_type {};

template<class Backend, class Rotator>
class file_t<
    Backend,
    Rotator,
    typename std::enable_if<
        !std::is_same<Rotator, NoRotation>::value
    >::type>
{
    Backend m_backend;
    writer_t<Backend> m_writer;
    flusher_t<Backend> m_flusher;
    Rotator m_rotator;
public:
    typedef file::config_t<Rotator> config_type;

    static const char* name() {
        return "files";
    }

    file_t(const config_type& config) :
        m_backend(config.path),
        m_writer(m_backend),
        m_flusher(config.autoflush, m_backend),
        m_rotator(config.rotator, m_backend)
    {}

    void consume(const std::string& message) {
        m_writer.write(message);
        m_flusher.flush();
        if (m_rotator.necessary()) {
            m_rotator.rotate();
        }
    }

    Backend& backend() {
        return m_backend;
    }
};

} // namespace sink

namespace generator {

const uint ROTATOR_POS = 2;

//template<class Backend, class Rotator>
//struct id<sink::file_t<Backend, Rotator>> {
//    static std::string extract(const boost::any& config) {
//        std::vector<boost::any> cfg;
//        aux::any_to(config, cfg);
//        std::string rotator;

//        if (cfg.size() > ROTATOR_POS && aux::is<std::vector<boost::any>>(cfg.at(ROTATOR_POS))) {
//            rotator += "/";
//            rotator += Rotator::name();
//        }

//        return utils::format("%s%s", sink::file_t<Backend, Rotator>::name(), rotator);
//    }
//};

template<class Backend, class Watcher>
struct id<sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>> {
    static std::string extract(const boost::any& config) {
        typedef sink::rotator_t<Backend, Watcher> rotator_type;

        std::vector<boost::any> cfg;
        aux::any_to(config, cfg);
        std::string rotator;

        if (cfg.size() > ROTATOR_POS && aux::is<std::vector<boost::any>>(cfg.at(ROTATOR_POS))) {
            rotator += "/";
            rotator += rotator_type::name();
        }

        return utils::format("%s%s", sink::file_t<Backend, rotator_type>::name(), rotator);
    }
};

} // namespace generator

template<class Backend>
struct config_traits<sink::file_t<Backend, sink::NoRotation>> {
    static std::string name() {
        return sink::file_t<Backend, sink::NoRotation>::name();
    }
};

template<class Backend, class Rotator>
struct config_traits<sink::file_t<Backend, Rotator>> {
    static std::string name() {
        return utils::format("%s/%s", sink::file_t<Backend, Rotator>::name(), Rotator::name());
    }
};

template<class Backend>
struct factory_traits<sink::file_t<Backend>> {
    typedef typename sink::file_t<Backend>::config_type config_type;

    static config_type map_config(const boost::any& config) {
        config_type cfg;
        aux::vector_to(config, cfg.path, cfg.autoflush);
        return cfg;
    }
};

template<class Backend, class Watcher>
struct factory_traits<sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>> {
    typedef typename sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>::config_type config_type;

    static config_type map_config(const boost::any& config) {
        config_type cfg;
        std::vector<boost::any> rotator;
        aux::vector_to(config, cfg.path, cfg.autoflush, rotator);
        aux::vector_to(rotator, cfg.rotator.size, cfg.rotator.backups);
        return cfg;
    }
};

} // namespace blackhole
<commit_msg>Drop dead code.<commit_after>#pragma once

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/version.hpp>

#include "blackhole/error.hpp"
#include "blackhole/factory.hpp"
#include "blackhole/sink/files/rotation.hpp"

namespace blackhole {

namespace sink {

class boost_backend_t {
    const boost::filesystem::path m_path;
    boost::filesystem::ofstream m_file;
public:
    boost_backend_t(const std::string& path) :
        m_path(path)
    {
    }

    bool opened() const {
        return m_file.is_open();
    }

    bool exists(const std::string& filename) const {
        return boost::filesystem::exists(m_path.parent_path() / filename);
    }

    std::vector<std::string> listdir() const {
        //!@todo: Implement me!
        return std::vector<std::string>();
    }

    std::time_t changed(const std::string&) const {
        //!@todo: Implement me!
        return std::time(nullptr);
    }

    bool open() {
        if (!create_directories(m_path.parent_path())) {
            return false;
        }

        m_file.open(m_path, std::ios_base::out | std::ios_base::app);
        return m_file.is_open();
    }

    void close() {
        m_file.close();
    }

    void rename(const std::string& oldname, const std::string& newname) {
        const boost::filesystem::path& path = m_path.parent_path();
        boost::filesystem::rename(path / oldname, path / newname);
    }

    std::string filename() const {
#if BOOST_VERSION >= 104600
        return m_path.filename().string();
#else
        return m_path.filename();
#endif
    }

    std::string path() const {
        return m_path.string();
    }

    void write(const std::string& message) {
        m_file.write(message.data(), static_cast<std::streamsize>(message.size()));
        m_file.put('\n');
    }

    void flush() {
        m_file.flush();
    }

private:
    template<typename Path>
    bool create_directories(const Path& path) {
        try {
            boost::filesystem::create_directories(path);
        } catch (const boost::filesystem::filesystem_error&) {
            return false;
        }

        return true;
    }
};

namespace file {

template<class Rotator = NoRotation>
struct config_t {
    std::string path;
    bool autoflush;

    config_t(const std::string& path = "/dev/stdout", bool autoflush = true) :
        path(path),
        autoflush(autoflush)
    {}
};

template<class Backend, class Watcher, class Timer>
struct config_t<rotator_t<Backend, Watcher, Timer>> {
    std::string path;
    bool autoflush;
    rotation::config_t rotator;

    config_t(const std::string& path = "/dev/stdout", bool autoflush = true, const rotation::config_t& rotator = rotation::config_t()) :
        path(path),
        autoflush(autoflush),
        rotator(rotator)
    {}
};

} // namespace file

template<class Backend>
class writer_t {
    Backend& backend;
public:
    writer_t(Backend& backend) :
        backend(backend)
    {}

    void write(const std::string& message) {
        if (!backend.opened()) {
            if (!backend.open()) {
                throw error_t("failed to open file '%s' for writing", backend.path());
            }
        }
        backend.write(message);
    }
};

template<class Backend>
class flusher_t {
    bool autoflush;
    Backend& backend;
public:
    flusher_t(bool autoflush, Backend& backend) :
        autoflush(autoflush),
        backend(backend)
    {}

    void flush() {
        if (autoflush) {
            backend.flush();
        }
    }
};

template<class Backend = boost_backend_t, class Rotator = NoRotation, typename = void>
class file_t;

template<class Backend>
class file_t<Backend, NoRotation, void> {
    Backend m_backend;
    writer_t<Backend> m_writer;
    flusher_t<Backend> m_flusher;
public:
    typedef file::config_t<NoRotation> config_type;

    static const char* name() {
        return "files";
    }

    file_t(const config_type& config) :
        m_backend(config.path),
        m_writer(m_backend),
        m_flusher(config.autoflush, m_backend)
    {}

    void consume(const std::string& message) {
        m_writer.write(message);
        m_flusher.flush();
    }

    Backend& backend() {
        return m_backend;
    }
};

//template<template<typename...> class T, template<typename...> class U> struct is_same : public std::false_type {};
//template<template<typename...> class T> struct is_same<T, T> : public std::true_type {};

template<class Backend, class Rotator>
class file_t<
    Backend,
    Rotator,
    typename std::enable_if<
        !std::is_same<Rotator, NoRotation>::value
    >::type>
{
    Backend m_backend;
    writer_t<Backend> m_writer;
    flusher_t<Backend> m_flusher;
    Rotator m_rotator;
public:
    typedef file::config_t<Rotator> config_type;

    static const char* name() {
        return "files";
    }

    file_t(const config_type& config) :
        m_backend(config.path),
        m_writer(m_backend),
        m_flusher(config.autoflush, m_backend),
        m_rotator(config.rotator, m_backend)
    {}

    void consume(const std::string& message) {
        m_writer.write(message);
        m_flusher.flush();
        if (m_rotator.necessary()) {
            m_rotator.rotate();
        }
    }

    Backend& backend() {
        return m_backend;
    }
};

} // namespace sink

namespace generator {

const uint ROTATOR_POS = 2;

template<class Backend, class Watcher>
struct id<sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>> {
    static std::string extract(const boost::any& config) {
        typedef sink::rotator_t<Backend, Watcher> rotator_type;

        std::vector<boost::any> cfg;
        aux::any_to(config, cfg);
        std::string rotator;

        if (cfg.size() > ROTATOR_POS && aux::is<std::vector<boost::any>>(cfg.at(ROTATOR_POS))) {
            rotator += "/";
            rotator += rotator_type::name();
        }

        return utils::format("%s%s", sink::file_t<Backend, rotator_type>::name(), rotator);
    }
};

} // namespace generator

template<class Backend>
struct config_traits<sink::file_t<Backend, sink::NoRotation>> {
    static std::string name() {
        return sink::file_t<Backend, sink::NoRotation>::name();
    }
};

template<class Backend, class Rotator>
struct config_traits<sink::file_t<Backend, Rotator>> {
    static std::string name() {
        return utils::format("%s/%s", sink::file_t<Backend, Rotator>::name(), Rotator::name());
    }
};

template<class Backend>
struct factory_traits<sink::file_t<Backend>> {
    typedef typename sink::file_t<Backend>::config_type config_type;

    static config_type map_config(const boost::any& config) {
        config_type cfg;
        aux::vector_to(config, cfg.path, cfg.autoflush);
        return cfg;
    }
};

template<class Backend, class Watcher>
struct factory_traits<sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>> {
    typedef typename sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>::config_type config_type;

    static config_type map_config(const boost::any& config) {
        config_type cfg;
        std::vector<boost::any> rotator;
        aux::vector_to(config, cfg.path, cfg.autoflush, rotator);
        aux::vector_to(rotator, cfg.rotator.size, cfg.rotator.backups);
        return cfg;
    }
};

} // namespace blackhole
<|endoftext|>


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

#include "DisplayEngine.h"
#include "../avgconfigwrapper.h"

#ifdef __APPLE__
#include "SDLMain.h"
#endif

#include "Event.h"
#include "MouseEvent.h"
#include "KeyEvent.h"
#include "SDLWindow.h"
#include "DisplayParams.h"
#ifndef AVG_ENABLE_EGL
  #include "SecondaryWindow.h"
#endif

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

#include "../graphics/Display.h"
#include "../graphics/BitmapLoader.h"
#include "../graphics/Bitmap.h"
#include "../graphics/GLContext.h"

#include "../video/VideoDecoder.h"

#ifdef __APPLE__
#include <ApplicationServices/ApplicationServices.h>
#endif

#include <SDL/SDL.h>

#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#endif

#ifdef AVG_ENABLE_XINERAMA
#include <X11/extensions/Xinerama.h>
#endif

#include <signal.h>
#include <iostream>

#ifdef _WIN32
#include <windows.h>
#endif

using namespace std;

namespace avg {

void DisplayEngine::initSDL()
{
#ifdef __APPLE__
    static bool bSDLInitialized = false;
    if (!bSDLInitialized) {
        CustomSDLMain();
        bSDLInitialized = true;
    }
#endif
#ifdef __linux__
    // Disable all other video drivers (DirectFB, libcaca, ...) to avoid confusing
    // error messages.
    SDL_putenv((char*)"SDL_VIDEODRIVER=x11");
#endif
    int err = SDL_InitSubSystem(SDL_INIT_VIDEO);
    if (err == -1) {
        throw Exception(AVG_ERR_VIDEO_INIT_FAILED, SDL_GetError());
    }
}

void DisplayEngine::quitSDL()
{
    SDL_QuitSubSystem(SDL_INIT_VIDEO);
}

DisplayEngine::DisplayEngine()
    : InputDevice("DisplayEngine"),
      m_Size(0,0),
      m_NumFrames(0),
      m_VBRate(0),
      m_Framerate(60),
      m_bInitialized(false),
      m_EffFramerate(0)
{
    initSDL();

    m_Gamma[0] = 1.0;
    m_Gamma[1] = 1.0;
    m_Gamma[2] = 1.0;
}

DisplayEngine::~DisplayEngine()
{
}

void DisplayEngine::init(const DisplayParams& dp, GLConfig glConfig)
{
    if (m_Gamma[0] != 1.0f || m_Gamma[1] != 1.0f || m_Gamma[2] != 1.0f) {
        internalSetGamma(1.0f, 1.0f, 1.0f);
    }

    m_pWindows.push_back(WindowPtr(new SDLWindow(dp, glConfig)));
#ifndef AVG_ENABLE_EGL
    for (int i=1; i<dp.getNumWindows(); ++i) {
        m_pWindows.push_back(WindowPtr(new SecondaryWindow(dp.getWindowParams(i),
                dp.isFullscreen(), glConfig)));
    }
#endif

    Display::get()->getRefreshRate();

    setGamma(dp.getGamma(0), dp.getGamma(1), dp.getGamma(2));
    showCursor(dp.isCursorVisible());
    if (dp.getFramerate() == 0) {
        setVBlankRate(dp.getVBRate());
    } else {
        setFramerate(dp.getFramerate());
    }

    // SDL sets up a signal handler we really don't want.
    signal(SIGSEGV, SIG_DFL);
    VideoDecoder::logConfig();

    SDL_EnableUNICODE(1);
}

void DisplayEngine::teardown()
{
    m_pWindows.clear();
}

void DisplayEngine::initRender()
{
    m_NumFrames = 0;
    m_FramesTooLate = 0;
    m_TimeSpentWaiting = 0;
    m_StartTime = TimeSource::get()->getCurrentMicrosecs();
    m_LastFrameTime = m_StartTime;
    m_bInitialized = true;
    if (m_VBRate != 0) {
        setVBlankRate(m_VBRate);
    } else {
        setFramerate(m_Framerate);
    }
}

void DisplayEngine::deinitRender()
{
    AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO,
            "Framerate statistics: ");
    AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO,
            "  Total frames: " <<m_NumFrames);
    float TotalTime = float(TimeSource::get()->getCurrentMicrosecs()
            -m_StartTime)/1000000;
    AVG_TRACE(Logger::category::PROFILE,  Logger::severity::INFO,
            "  Total time: " << TotalTime << " seconds");
    float actualFramerate = (m_NumFrames+1)/TotalTime;
    AVG_TRACE(Logger::category::PROFILE,  Logger::severity::INFO,
            "  Framerate achieved: " << actualFramerate);
    AVG_TRACE(Logger::category::PROFILE,  Logger::severity::INFO,
            "  Frames too late: " << m_FramesTooLate);
    AVG_TRACE(Logger::category::PROFILE,  Logger::severity::INFO,
            "  Percent of time spent waiting: "
            << float (m_TimeSpentWaiting)/(10000*TotalTime));
    if (m_Framerate != 0) {
        AVG_TRACE(Logger::category::PROFILE,  Logger::severity::INFO,
                "  Framerate goal was: " << m_Framerate);
        if (m_Framerate*2 < actualFramerate && m_NumFrames > 10) {
            AVG_LOG_WARNING("Actual framerate was a lot higher than framerate goal.\
                    Is vblank sync forced off?");
        }
    }
    m_bInitialized = false;
}

void DisplayEngine::setFramerate(float rate)
{
    if (rate != 0 && m_bInitialized) {
        for (unsigned i=0; i<m_pWindows.size(); ++i) {
            GLContext* pContext = m_pWindows[i]->getGLContext();
            pContext->activate();
            pContext->initVBlank(0);
        }
    }
    m_Framerate = rate;
    m_VBRate = 0;
}

float DisplayEngine::getFramerate()
{
    return m_Framerate;
}

float DisplayEngine::getEffectiveFramerate()
{
    return m_EffFramerate;
}

void DisplayEngine::setVBlankRate(int rate)
{
    m_VBRate = rate;
    if (m_bInitialized) {
        GLContext* pContext = m_pWindows[0]->getGLContext();
        pContext->activate();
        bool bOK = pContext->initVBlank(rate);
        m_Framerate = Display::get()->getRefreshRate()/m_VBRate;
        if (!bOK || rate == 0) {
            AVG_LOG_WARNING("Using framerate of " << m_Framerate <<
                    " instead of VBRate of " << m_VBRate);
            m_VBRate = 0;
        }
    }
}

bool DisplayEngine::wasFrameLate()
{
    return m_bFrameLate;
}

void DisplayEngine::setGamma(float red, float green, float blue)
{
    if (red > 0) {
        bool bOk = internalSetGamma(red, green, blue);
        m_Gamma[0] = red;
        m_Gamma[1] = green;
        m_Gamma[2] = blue;
        if (!bOk) {
            AVG_LOG_WARNING("Unable to set display gamma.");
        }
    }
}

void DisplayEngine::setMousePos(const IntPoint& pos)
{
    SDL_WarpMouse(pos.x, pos.y);
}

int DisplayEngine::getKeyModifierState() const
{
    return SDL_GetModState();
}

void DisplayEngine::setWindowTitle(const string& sTitle)
{
    SDL_WM_SetCaption(sTitle.c_str(), 0);
}

unsigned DisplayEngine::getNumWindows() const
{
    return m_pWindows.size();
}

const WindowPtr DisplayEngine::getWindow(unsigned i) const
{
    return m_pWindows[i];
}

SDLWindowPtr DisplayEngine::getSDLWindow() const
{
    return boost::dynamic_pointer_cast<SDLWindow>(m_pWindows[0]);
}

static ProfilingZoneID WaitProfilingZone("Render - wait");

void DisplayEngine::frameWait()
{
    ScopeTimer Timer(WaitProfilingZone);

    m_NumFrames++;

    m_FrameWaitStartTime = TimeSource::get()->getCurrentMicrosecs();
    m_TargetTime = m_LastFrameTime+(long long)(1000000/m_Framerate);
    m_bFrameLate = false;
    if (m_VBRate == 0) {
        if (m_FrameWaitStartTime <= m_TargetTime) {
            long long WaitTime = (m_TargetTime-m_FrameWaitStartTime)/1000;
            if (WaitTime > 5000) {
                AVG_LOG_WARNING("DisplayEngine: waiting " << WaitTime << " ms.");
            }
            TimeSource::get()->sleepUntil(m_TargetTime/1000);
        }
    }
}

void DisplayEngine::swapBuffers()
{
    for (unsigned i=0; i<m_pWindows.size(); ++i) {
        m_pWindows[i]->swapBuffers();
    }
}

void DisplayEngine::checkJitter()
{
    if (m_LastFrameTime == 0) {
        m_EffFramerate = 0;
    } else {
        long long curIntervalTime = TimeSource::get()->getCurrentMicrosecs()
                -m_LastFrameTime;
        m_EffFramerate = 1000000.0f/curIntervalTime;
    }

    long long frameTime = TimeSource::get()->getCurrentMicrosecs();
    int maxDelay;
    if (m_VBRate == 0) {
        maxDelay = 2;
    } else {
        maxDelay = 6;
    }
    if ((frameTime - m_TargetTime)/1000 > maxDelay || m_bFrameLate) {
        m_bFrameLate = true;
        m_FramesTooLate++;
    }

    m_LastFrameTime = frameTime;
    m_TimeSpentWaiting += m_LastFrameTime-m_FrameWaitStartTime;
//    cerr << m_LastFrameTime << ", m_FrameWaitStartTime=" << m_FrameWaitStartTime << endl;
//    cerr << m_TimeSpentWaiting << endl;
}

long long DisplayEngine::getDisplayTime()
{
    return (m_LastFrameTime-m_StartTime)/1000;
}

const IntPoint& DisplayEngine::getSize() const
{
    return m_Size;
}

IntPoint DisplayEngine::getWindowSize() const
{
    if (m_pWindows.empty()) {
        return IntPoint(0,0);
    } else {
        return m_pWindows[0]->getSize();
    }
}

bool DisplayEngine::isFullscreen() const
{
    AVG_ASSERT(!m_pWindows.empty());
    return m_pWindows[0]->isFullscreen();
}

void DisplayEngine::showCursor(bool bShow)
{
#ifdef _WIN32
#define MAX_CORE_POINTERS   6
    // Hack to fix a pointer issue with fullscreen, SDL and touchscreens
    // Refer to Mantis bug #140
    for (int i = 0; i < MAX_CORE_POINTERS; ++i) {
        ShowCursor(bShow);
    }
#else
    if (bShow) {
        SDL_ShowCursor(SDL_ENABLE);
    } else {
        SDL_ShowCursor(SDL_DISABLE);
    }
#endif
}

BitmapPtr DisplayEngine::screenshot(int buffer)
{
    IntRect destRect;
    for (unsigned i=0; i != m_pWindows.size(); ++i) {
        IntRect winDims(m_pWindows[i]->getPos(),
                m_pWindows[i]->getPos()+m_pWindows[i]->getSize());
        destRect.expand(winDims);
    }

    BitmapPtr pDestBmp = BitmapPtr(new Bitmap(destRect.size(),
            BitmapLoader::get()->getDefaultPixelFormat(false)));
    for (unsigned i=0; i != m_pWindows.size(); ++i) {
        BitmapPtr pWinBmp = m_pWindows[i]->screenshot(buffer);
        IntPoint pos = m_pWindows[i]->getPos() - destRect.tl;
        pDestBmp->blt(*pWinBmp, pos);
    }
    return pDestBmp;
}

vector<EventPtr> DisplayEngine::pollEvents()
{
    vector<EventPtr> pEvents;
    for (unsigned i=0; i != m_pWindows.size(); ++i) {
        vector<EventPtr> pWinEvents =  m_pWindows[i]->pollEvents();
        pEvents.insert(pEvents.end(), pWinEvents.begin(), pWinEvents.end());
    }
    return pEvents;
}

bool DisplayEngine::internalSetGamma(float red, float green, float blue)
{
#ifdef __APPLE__
    // Workaround for broken SDL_SetGamma for libSDL 1.2.15 under Lion
    CGError err = CGSetDisplayTransferByFormula(kCGDirectMainDisplay, 0, 1, 1/red,
            0, 1, 1/green, 0, 1, 1/blue);
    return (err == CGDisplayNoErr);
#else
    int err = SDL_SetGamma(float(red), float(green), float(blue));
    return (err != -1);
#endif
}

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

#include "DisplayEngine.h"
#include "../avgconfigwrapper.h"

#ifdef __APPLE__
#include "SDLMain.h"
#endif

#include "Event.h"
#include "MouseEvent.h"
#include "KeyEvent.h"
#include "SDLWindow.h"
#include "DisplayParams.h"
#ifndef AVG_ENABLE_EGL
  #include "SecondaryWindow.h"
#endif

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

#include "../graphics/Display.h"
#include "../graphics/BitmapLoader.h"
#include "../graphics/Bitmap.h"
#include "../graphics/GLContext.h"

#include "../video/VideoDecoder.h"

#ifdef __APPLE__
#include <ApplicationServices/ApplicationServices.h>
#endif

#include <SDL/SDL.h>

#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#endif

#ifdef AVG_ENABLE_XINERAMA
#include <X11/extensions/Xinerama.h>
#endif

#include <signal.h>
#include <iostream>

#ifdef _WIN32
#include <windows.h>
#endif

using namespace std;

namespace avg {

void DisplayEngine::initSDL()
{
#ifdef __APPLE__
    static bool bSDLInitialized = false;
    if (!bSDLInitialized) {
        CustomSDLMain();
        bSDLInitialized = true;
    }
#endif
#ifdef __linux__
    // Disable all other video drivers (DirectFB, libcaca, ...) to avoid confusing
    // error messages.
    SDL_putenv((char*)"SDL_VIDEODRIVER=x11");
#endif
    int err = SDL_InitSubSystem(SDL_INIT_VIDEO);
    if (err == -1) {
        throw Exception(AVG_ERR_VIDEO_INIT_FAILED, SDL_GetError());
    }
}

void DisplayEngine::quitSDL()
{
    SDL_QuitSubSystem(SDL_INIT_VIDEO);
}

DisplayEngine::DisplayEngine()
    : InputDevice("DisplayEngine"),
      m_Size(0,0),
      m_NumFrames(0),
      m_VBRate(0),
      m_Framerate(60),
      m_bInitialized(false),
      m_EffFramerate(0)
{
    initSDL();

    m_Gamma[0] = 1.0;
    m_Gamma[1] = 1.0;
    m_Gamma[2] = 1.0;
}

DisplayEngine::~DisplayEngine()
{
}

void DisplayEngine::init(const DisplayParams& dp, GLConfig glConfig)
{
    if (m_Gamma[0] != 1.0f || m_Gamma[1] != 1.0f || m_Gamma[2] != 1.0f) {
        internalSetGamma(1.0f, 1.0f, 1.0f);
    }

    m_pWindows.push_back(WindowPtr(new SDLWindow(dp, glConfig)));
#ifndef AVG_ENABLE_EGL
    for (int i=1; i<dp.getNumWindows(); ++i) {
        m_pWindows.push_back(WindowPtr(new SecondaryWindow(dp.getWindowParams(i),
                dp.isFullscreen(), glConfig)));
    }
#endif
    m_Size = dp.getWindowParams(0).m_Viewport.size();

    Display::get()->getRefreshRate();

    setGamma(dp.getGamma(0), dp.getGamma(1), dp.getGamma(2));
    showCursor(dp.isCursorVisible());
    if (dp.getFramerate() == 0) {
        setVBlankRate(dp.getVBRate());
    } else {
        setFramerate(dp.getFramerate());
    }

    // SDL sets up a signal handler we really don't want.
    signal(SIGSEGV, SIG_DFL);
    VideoDecoder::logConfig();

    SDL_EnableUNICODE(1);
}

void DisplayEngine::teardown()
{
    m_pWindows.clear();
}

void DisplayEngine::initRender()
{
    m_NumFrames = 0;
    m_FramesTooLate = 0;
    m_TimeSpentWaiting = 0;
    m_StartTime = TimeSource::get()->getCurrentMicrosecs();
    m_LastFrameTime = m_StartTime;
    m_bInitialized = true;
    if (m_VBRate != 0) {
        setVBlankRate(m_VBRate);
    } else {
        setFramerate(m_Framerate);
    }
}

void DisplayEngine::deinitRender()
{
    AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO,
            "Framerate statistics: ");
    AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO,
            "  Total frames: " <<m_NumFrames);
    float TotalTime = float(TimeSource::get()->getCurrentMicrosecs()
            -m_StartTime)/1000000;
    AVG_TRACE(Logger::category::PROFILE,  Logger::severity::INFO,
            "  Total time: " << TotalTime << " seconds");
    float actualFramerate = (m_NumFrames+1)/TotalTime;
    AVG_TRACE(Logger::category::PROFILE,  Logger::severity::INFO,
            "  Framerate achieved: " << actualFramerate);
    AVG_TRACE(Logger::category::PROFILE,  Logger::severity::INFO,
            "  Frames too late: " << m_FramesTooLate);
    AVG_TRACE(Logger::category::PROFILE,  Logger::severity::INFO,
            "  Percent of time spent waiting: "
            << float (m_TimeSpentWaiting)/(10000*TotalTime));
    if (m_Framerate != 0) {
        AVG_TRACE(Logger::category::PROFILE,  Logger::severity::INFO,
                "  Framerate goal was: " << m_Framerate);
        if (m_Framerate*2 < actualFramerate && m_NumFrames > 10) {
            AVG_LOG_WARNING("Actual framerate was a lot higher than framerate goal.\
                    Is vblank sync forced off?");
        }
    }
    m_bInitialized = false;
}

void DisplayEngine::setFramerate(float rate)
{
    if (rate != 0 && m_bInitialized) {
        for (unsigned i=0; i<m_pWindows.size(); ++i) {
            GLContext* pContext = m_pWindows[i]->getGLContext();
            pContext->activate();
            pContext->initVBlank(0);
        }
    }
    m_Framerate = rate;
    m_VBRate = 0;
}

float DisplayEngine::getFramerate()
{
    return m_Framerate;
}

float DisplayEngine::getEffectiveFramerate()
{
    return m_EffFramerate;
}

void DisplayEngine::setVBlankRate(int rate)
{
    m_VBRate = rate;
    if (m_bInitialized) {
        GLContext* pContext = m_pWindows[0]->getGLContext();
        pContext->activate();
        bool bOK = pContext->initVBlank(rate);
        m_Framerate = Display::get()->getRefreshRate()/m_VBRate;
        if (!bOK || rate == 0) {
            AVG_LOG_WARNING("Using framerate of " << m_Framerate <<
                    " instead of VBRate of " << m_VBRate);
            m_VBRate = 0;
        }
    }
}

bool DisplayEngine::wasFrameLate()
{
    return m_bFrameLate;
}

void DisplayEngine::setGamma(float red, float green, float blue)
{
    if (red > 0) {
        bool bOk = internalSetGamma(red, green, blue);
        m_Gamma[0] = red;
        m_Gamma[1] = green;
        m_Gamma[2] = blue;
        if (!bOk) {
            AVG_LOG_WARNING("Unable to set display gamma.");
        }
    }
}

void DisplayEngine::setMousePos(const IntPoint& pos)
{
    SDL_WarpMouse(pos.x, pos.y);
}

int DisplayEngine::getKeyModifierState() const
{
    return SDL_GetModState();
}

void DisplayEngine::setWindowTitle(const string& sTitle)
{
    SDL_WM_SetCaption(sTitle.c_str(), 0);
}

unsigned DisplayEngine::getNumWindows() const
{
    return m_pWindows.size();
}

const WindowPtr DisplayEngine::getWindow(unsigned i) const
{
    return m_pWindows[i];
}

SDLWindowPtr DisplayEngine::getSDLWindow() const
{
    return boost::dynamic_pointer_cast<SDLWindow>(m_pWindows[0]);
}

static ProfilingZoneID WaitProfilingZone("Render - wait");

void DisplayEngine::frameWait()
{
    ScopeTimer Timer(WaitProfilingZone);

    m_NumFrames++;

    m_FrameWaitStartTime = TimeSource::get()->getCurrentMicrosecs();
    m_TargetTime = m_LastFrameTime+(long long)(1000000/m_Framerate);
    m_bFrameLate = false;
    if (m_VBRate == 0) {
        if (m_FrameWaitStartTime <= m_TargetTime) {
            long long WaitTime = (m_TargetTime-m_FrameWaitStartTime)/1000;
            if (WaitTime > 5000) {
                AVG_LOG_WARNING("DisplayEngine: waiting " << WaitTime << " ms.");
            }
            TimeSource::get()->sleepUntil(m_TargetTime/1000);
        }
    }
}

void DisplayEngine::swapBuffers()
{
    for (unsigned i=0; i<m_pWindows.size(); ++i) {
        m_pWindows[i]->swapBuffers();
    }
}

void DisplayEngine::checkJitter()
{
    if (m_LastFrameTime == 0) {
        m_EffFramerate = 0;
    } else {
        long long curIntervalTime = TimeSource::get()->getCurrentMicrosecs()
                -m_LastFrameTime;
        m_EffFramerate = 1000000.0f/curIntervalTime;
    }

    long long frameTime = TimeSource::get()->getCurrentMicrosecs();
    int maxDelay;
    if (m_VBRate == 0) {
        maxDelay = 2;
    } else {
        maxDelay = 6;
    }
    if ((frameTime - m_TargetTime)/1000 > maxDelay || m_bFrameLate) {
        m_bFrameLate = true;
        m_FramesTooLate++;
    }

    m_LastFrameTime = frameTime;
    m_TimeSpentWaiting += m_LastFrameTime-m_FrameWaitStartTime;
//    cerr << m_LastFrameTime << ", m_FrameWaitStartTime=" << m_FrameWaitStartTime << endl;
//    cerr << m_TimeSpentWaiting << endl;
}

long long DisplayEngine::getDisplayTime()
{
    return (m_LastFrameTime-m_StartTime)/1000;
}

const IntPoint& DisplayEngine::getSize() const
{
    return m_Size;
}

IntPoint DisplayEngine::getWindowSize() const
{
    if (m_pWindows.empty()) {
        return IntPoint(0,0);
    } else {
        return m_pWindows[0]->getSize();
    }
}

bool DisplayEngine::isFullscreen() const
{
    AVG_ASSERT(!m_pWindows.empty());
    return m_pWindows[0]->isFullscreen();
}

void DisplayEngine::showCursor(bool bShow)
{
#ifdef _WIN32
#define MAX_CORE_POINTERS   6
    // Hack to fix a pointer issue with fullscreen, SDL and touchscreens
    // Refer to Mantis bug #140
    for (int i = 0; i < MAX_CORE_POINTERS; ++i) {
        ShowCursor(bShow);
    }
#else
    if (bShow) {
        SDL_ShowCursor(SDL_ENABLE);
    } else {
        SDL_ShowCursor(SDL_DISABLE);
    }
#endif
}

BitmapPtr DisplayEngine::screenshot(int buffer)
{
    IntRect destRect;
    for (unsigned i=0; i != m_pWindows.size(); ++i) {
        IntRect winDims(m_pWindows[i]->getPos(),
                m_pWindows[i]->getPos()+m_pWindows[i]->getSize());
        destRect.expand(winDims);
    }

    BitmapPtr pDestBmp = BitmapPtr(new Bitmap(destRect.size(),
            BitmapLoader::get()->getDefaultPixelFormat(false)));
    for (unsigned i=0; i != m_pWindows.size(); ++i) {
        BitmapPtr pWinBmp = m_pWindows[i]->screenshot(buffer);
        IntPoint pos = m_pWindows[i]->getPos() - destRect.tl;
        pDestBmp->blt(*pWinBmp, pos);
    }
    return pDestBmp;
}

vector<EventPtr> DisplayEngine::pollEvents()
{
    vector<EventPtr> pEvents;
    for (unsigned i=0; i != m_pWindows.size(); ++i) {
        vector<EventPtr> pWinEvents =  m_pWindows[i]->pollEvents();
        pEvents.insert(pEvents.end(), pWinEvents.begin(), pWinEvents.end());
    }
    return pEvents;
}

bool DisplayEngine::internalSetGamma(float red, float green, float blue)
{
#ifdef __APPLE__
    // Workaround for broken SDL_SetGamma for libSDL 1.2.15 under Lion
    CGError err = CGSetDisplayTransferByFormula(kCGDirectMainDisplay, 0, 1, 1/red,
            0, 1, 1/green, 0, 1, 1/blue);
    return (err == CGDisplayNoErr);
#else
    int err = SDL_SetGamma(float(red), float(green), float(blue));
    return (err != -1);
#endif
}

}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

//testing headers
#include <mitkTestingMacros.h>
#include <mitkTestFixture.h>
#include <mitkIOUtil.h>
#include <mitkIGTException.h>
#include <mitkNavigationToolStorageTestHelper.h>

//headers of IGT classes releated to the tested class
#include <mitkNavigationToolStorageSerializer.h>

#include <Poco/Path.h>

class mitkNavigationToolStorageSerializerTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkNavigationToolStorageSerializerTestSuite);
  MITK_TEST(TestInstantiationSerializer);
  MITK_TEST(TestWriteSimpleToolStorage);
  MITK_TEST(TestWriteComplexToolStorage);
  MITK_TEST(TestWriteStorageToInvalidFile);
  MITK_TEST(TestWriteEmptyToolStorage);
  MITK_TEST(TestSerializerForExceptions);
  CPPUNIT_TEST_SUITE_END();

private:
  /** Members used inside the different test methods. All members are initialized via setUp().*/
  std::string m_FileName1;
  mitk::NavigationToolStorageSerializer::Pointer m_Serializer;

public:

  /**@brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members for a new test case. (If the members are not used in a test, the method does not need to be called).*/
  void setUp()
  {
    try {
      m_FileName1 = mitk::IOUtil::CreateTemporaryFile();
      std::ofstream file;
      file.open(m_FileName1.c_str());
      if (!file.good()) {MITK_ERROR <<"Could not create a valid file during setUp() method.";}
      file.close();
    }
    catch (std::exception& e) {
      MITK_ERROR << "File access Exception: " << e.what();
      MITK_ERROR <<"Could not create filename during setUp() method.";
    }
    m_Serializer = mitk::NavigationToolStorageSerializer::New();
  }

  void tearDown()
  {
    m_Serializer = NULL;
    try
    {
      std::remove(m_FileName1.c_str());
    }
    catch(...)
    {
      MITK_ERROR << "Warning: Error occured when deleting test file!";
    }
  }

  void TestInstantiationSerializer()
  {
  // let's create objects of our classes
  mitk::NavigationToolStorageSerializer::Pointer testSerializer = mitk::NavigationToolStorageSerializer::New();
  CPPUNIT_ASSERT_MESSAGE("Testing instantiation of NavigationToolStorageSerializer",testSerializer.IsNotNull());
  }

  void TestWriteSimpleToolStorage()
  {
  //create Tool Storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_SimpleStorage();

  //test serialization
  bool success = m_Serializer->Serialize(m_FileName1,myStorage);
  CPPUNIT_ASSERT_MESSAGE("Testing serialization of simple tool storage",success);
  }

  void TestWriteComplexToolStorage()
  {
    //create navigation tool storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_ComplexStorage(GetTestDataFilePath("ClaronTool"),GetTestDataFilePath("IGT-Data/ClaronTool.stl"),GetTestDataFilePath("IGT-Data/EMTool.stl"));

    //test serialization
    bool success = m_Serializer->Serialize(m_FileName1,myStorage);
    CPPUNIT_ASSERT_MESSAGE("Testing serialization of complex tool storage",success);
  }

  void TestWriteStorageToInvalidFile()
  {
    //create Tool Storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_SimpleStorage();

    //create invalid filename
  #ifdef WIN32
    std::string filename = "C:\342INVALIDFILE<>.storage"; //invalid filename for windows
  #else
    std::string filename = "/dsfdsf:$�$342INVALIDFILE.storage"; //invalid filename for linux
  #endif

    //test serialization (should throw exception)
    CPPUNIT_ASSERT_THROW_MESSAGE("Test serialization with simple storage and invalid filename, an exception is expected.",m_Serializer->Serialize(filename,myStorage),mitk::IGTException);
  }

  void TestWriteEmptyToolStorage()
  {
    //create Tool Storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();

    //test serialization
    bool success = m_Serializer->Serialize(m_FileName1,myStorage);
    CPPUNIT_ASSERT_MESSAGE("Testing serialization of simple tool storage",success);
  }

  void TestSerializerForExceptions()
  {
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();

    //create an invalid filename
    std::string filename = std::string( MITK_TEST_OUTPUT_DIR )+Poco::Path::separator()+"";

    //now try to serialize an check if an exception is thrown
    CPPUNIT_ASSERT_THROW_MESSAGE("Test serialization with empty storage and invalid filename, an exception is expected.",m_Serializer->Serialize(filename,myStorage),mitk::IGTException);
  }
};
MITK_TEST_SUITE_REGISTRATION(mitkNavigationToolStorageSerializer)
<commit_msg>also changed name and path of the temporary file of the test<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

//testing headers
#include <mitkTestingMacros.h>
#include <mitkTestFixture.h>
#include <mitkIOUtil.h>
#include <mitkIGTException.h>
#include <mitkNavigationToolStorageTestHelper.h>

//headers of IGT classes releated to the tested class
#include <mitkNavigationToolStorageSerializer.h>

#include <Poco/Path.h>

class mitkNavigationToolStorageSerializerTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkNavigationToolStorageSerializerTestSuite);
  MITK_TEST(TestInstantiationSerializer);
  MITK_TEST(TestWriteSimpleToolStorage);
  MITK_TEST(TestWriteComplexToolStorage);
  MITK_TEST(TestWriteStorageToInvalidFile);
  MITK_TEST(TestWriteEmptyToolStorage);
  MITK_TEST(TestSerializerForExceptions);
  CPPUNIT_TEST_SUITE_END();

private:
  /** Members used inside the different test methods. All members are initialized via setUp().*/
  std::string m_FileName1;
  mitk::NavigationToolStorageSerializer::Pointer m_Serializer;

public:

  /**@brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members for a new test case. (If the members are not used in a test, the method does not need to be called).*/
  void setUp()
  {
    try {
      m_FileName1 = mitk::IOUtil::CreateTemporaryFile("NavigationToolStorageSerializerTestTmp_XXXXXX.IGTToolStorage",mitk::IOUtil::GetProgramPath());
      std::ofstream file;
      file.open(m_FileName1.c_str());
      if (!file.good()) {MITK_ERROR <<"Could not create a valid file during setUp() method.";}
      file.close();
    }
    catch (std::exception& e) {
      MITK_ERROR << "File access Exception: " << e.what();
      MITK_ERROR <<"Could not create filename during setUp() method.";
    }
    m_Serializer = mitk::NavigationToolStorageSerializer::New();
  }

  void tearDown()
  {
    m_Serializer = NULL;
    try
    {
      std::remove(m_FileName1.c_str());
    }
    catch(...)
    {
      MITK_ERROR << "Warning: Error occured when deleting test file!";
    }
  }

  void TestInstantiationSerializer()
  {
  // let's create objects of our classes
  mitk::NavigationToolStorageSerializer::Pointer testSerializer = mitk::NavigationToolStorageSerializer::New();
  CPPUNIT_ASSERT_MESSAGE("Testing instantiation of NavigationToolStorageSerializer",testSerializer.IsNotNull());
  }

  void TestWriteSimpleToolStorage()
  {
  //create Tool Storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_SimpleStorage();

  //test serialization
  bool success = m_Serializer->Serialize(m_FileName1,myStorage);
  CPPUNIT_ASSERT_MESSAGE("Testing serialization of simple tool storage",success);
  }

  void TestWriteComplexToolStorage()
  {
    //create navigation tool storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_ComplexStorage(GetTestDataFilePath("ClaronTool"),GetTestDataFilePath("IGT-Data/ClaronTool.stl"),GetTestDataFilePath("IGT-Data/EMTool.stl"));

    //test serialization
    bool success = m_Serializer->Serialize(m_FileName1,myStorage);
    CPPUNIT_ASSERT_MESSAGE("Testing serialization of complex tool storage",success);
  }

  void TestWriteStorageToInvalidFile()
  {
    //create Tool Storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_SimpleStorage();

    //create invalid filename
  #ifdef WIN32
    std::string filename = "C:\342INVALIDFILE<>.storage"; //invalid filename for windows
  #else
    std::string filename = "/dsfdsf:$�$342INVALIDFILE.storage"; //invalid filename for linux
  #endif

    //test serialization (should throw exception)
    CPPUNIT_ASSERT_THROW_MESSAGE("Test serialization with simple storage and invalid filename, an exception is expected.",m_Serializer->Serialize(filename,myStorage),mitk::IGTException);
  }

  void TestWriteEmptyToolStorage()
  {
    //create Tool Storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();

    //test serialization
    bool success = m_Serializer->Serialize(m_FileName1,myStorage);
    CPPUNIT_ASSERT_MESSAGE("Testing serialization of simple tool storage",success);
  }

  void TestSerializerForExceptions()
  {
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();

    //create an invalid filename
    std::string filename = std::string( MITK_TEST_OUTPUT_DIR )+Poco::Path::separator()+"";

    //now try to serialize an check if an exception is thrown
    CPPUNIT_ASSERT_THROW_MESSAGE("Test serialization with empty storage and invalid filename, an exception is expected.",m_Serializer->Serialize(filename,myStorage),mitk::IGTException);
  }
};
MITK_TEST_SUITE_REGISTRATION(mitkNavigationToolStorageSerializer)
<|endoftext|>


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

#include <iostream>
#include <array>

#include "geometry.hpp"
#include "origin.hpp"
#include "point.hpp"
#include "vector.hpp"

TEST(Line, ShiftOrigin) {
  static constexpr const int dim = 3;
  using fptype = float;
  const fptype eps = 1e-4;
  struct TestCase {
    std::array<fptype, dim> newOrigin;
    std::array<fptype, dim> origOffset;
    std::array<fptype, dim> dir;
    std::array<fptype, dim> expectedOffset;
  };
  struct TestCase tests[] = {
      {{{0.0, 0.0, 0.0}},
       {{0.0, 0.0, 0.0}},
       {{0.0, 0.0, 1.0}},
       {{0.0, 0.0, 0.0}}},

      {{{0.0, 0.0, 0.0}},
       {{1.0, 0.0, 0.0}},
       {{0.0, 1.0, 1.0}},
       {{1.0, 0.0, 0.0}}},

      {{{2.0, 0.0, 0.0}},
       {{1.0, 0.0, 0.0}},
       {{0.0, 1.0, 1.0}},
       {{-1.0, 0.0, 0.0}}},

      {{{1.0, 0.0, 0.0}},
       {{1.0, 0.0, 0.0}},
       {{0.0, 1.0, 1.0}},
       {{0.0, 0.0, 0.0}}},

      {{{0.0, 0.0, 0.0}},
       {{1.0, 1.0, 0.0}},
       {{0.0, 1.0, 1.0}},
       {{1.0, 0.5, -0.5}}},
  };
  Geometry::Origin<dim, fptype> defOrigin;
  for(auto t : tests) {
    Geometry::Point<dim, fptype> intersect(
        defOrigin,
        Geometry::Vector<dim, fptype>(t.origOffset));
    Geometry::Vector<dim, fptype> dir(
        Geometry::Vector<dim, fptype>(t.dir).normalize());
    Geometry::Line<dim, fptype> line(intersect, dir);
    Geometry::Origin<dim, fptype> o(t.newOrigin);
    line.shiftOrigin(o);
    Geometry::Vector<dim, fptype> newOff(
        line.getIntercept().getOffset());
    for(unsigned i = 0; i < dim; i++) {
      EXPECT_NEAR(newOff(i), t.expectedOffset[i], eps);
    }
  }
}
<commit_msg>Added test for computing a point at a given distance along a line computation<commit_after>
#include <gtest/gtest.h>

#include <iostream>
#include <array>

#include "geometry.hpp"
#include "origin.hpp"
#include "point.hpp"
#include "vector.hpp"

TEST(Line, ShiftOrigin) {
  static constexpr const int dim = 3;
  using fptype = float;
  const fptype eps = 1e-4;
  struct TestCase {
    std::array<fptype, dim> newOrigin;
    std::array<fptype, dim> origOffset;
    std::array<fptype, dim> dir;
    std::array<fptype, dim> expectedOffset;
  };
  struct TestCase tests[] = {
      {{{0.0, 0.0, 0.0}},
       {{0.0, 0.0, 0.0}},
       {{0.0, 0.0, 1.0}},
       {{0.0, 0.0, 0.0}}},

      {{{0.0, 0.0, 0.0}},
       {{1.0, 0.0, 0.0}},
       {{0.0, 1.0, 1.0}},
       {{1.0, 0.0, 0.0}}},

      {{{2.0, 0.0, 0.0}},
       {{1.0, 0.0, 0.0}},
       {{0.0, 1.0, 1.0}},
       {{-1.0, 0.0, 0.0}}},

      {{{1.0, 0.0, 0.0}},
       {{1.0, 0.0, 0.0}},
       {{0.0, 1.0, 1.0}},
       {{0.0, 0.0, 0.0}}},

      {{{0.0, 0.0, 0.0}},
       {{1.0, 1.0, 0.0}},
       {{0.0, 1.0, 1.0}},
       {{1.0, 0.5, -0.5}}},
  };
  Geometry::Origin<dim, fptype> defOrigin;
  for(auto t : tests) {
    Geometry::Point<dim, fptype> intersect(
        defOrigin,
        Geometry::Vector<dim, fptype>(t.origOffset));
    Geometry::Vector<dim, fptype> dir(
        Geometry::Vector<dim, fptype>(t.dir).normalize());
    Geometry::Line<dim, fptype> line(intersect, dir);
    Geometry::Origin<dim, fptype> o(t.newOrigin);
    line.shiftOrigin(o);
    Geometry::Vector<dim, fptype> newOff(
        line.getIntercept().getOffset());
    for(unsigned i = 0; i < dim; i++) {
      EXPECT_NEAR(newOff(i), t.expectedOffset[i], eps);
    }
  }
}

TEST(Line, CalcPointAtDistance) {
  static constexpr const int dim = 3;
  using fptype = float;
  const fptype eps = 1e-6;
  struct TestCase {
    fptype distance;
    std::array<fptype, dim> offset;
    std::array<fptype, dim> dir;
    std::array<fptype, dim> expected;
  };
  struct TestCase tests[] = {
      {0.0,
       {{0.0, 0.0, 0.0}},
       {{0.0, 0.0, 1.0}},
       {{0.0, 0.0, 0.0}}},
      {1.0,
       {{0.0, 0.0, 0.0}},
       {{0.0, 0.0, 1.0}},
       {{0.0, 0.0, 1.0}}},
      {std::sqrt(2),
       {{0.0, 0.0, 0.0}},
       {{1.0, 0.0, 1.0}},
       {{1.0, 0.0, 1.0}}},
      {3 * std::sqrt(2),
       {{0.0, 0.0, 0.0}},
       {{1.0, 0.0, 1.0}},
       {{3.0, 0.0, 3.0}}},
  };
  Geometry::Origin<dim, fptype> defOrigin;
  for(auto t : tests) {
    Geometry::Vector<dim, fptype> offset(t.offset);
    Geometry::Point<dim, fptype> intersect(defOrigin,
                                           offset);
    Geometry::Vector<dim, fptype> dir(t.dir);
    Geometry::Line<dim, fptype> line(intersect, dir);
    Geometry::Point<dim, fptype> pos =
        line.getPosAtDist(t.distance);
    Geometry::Vector<dim, fptype> off = pos.getOffset();
    for(unsigned i = 0; i < dim; i++) {
      EXPECT_NEAR(off(i), t.expected[i], eps);
    }
  }
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "dbmgr.hxx"
#include <sfx2/app.hxx>
#include <vcl/builder.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/settings.hxx>

#include <swwait.hxx>
#include <viewopt.hxx>

#include "wrtsh.hxx"
#include "cmdid.h"
#include "helpid.h"
#include "envfmt.hxx"
#include "envlop.hxx"
#include "envprt.hxx"
#include "fmtcol.hxx"
#include "poolfmt.hxx"
#include "view.hxx"

#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>

#include <unomid.h>

using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::rtl;

//impl in envimg.cxx
extern SW_DLLPUBLIC OUString MakeSender();

SwEnvPreview::SwEnvPreview(Window* pParent, WinBits nStyle)
    : Window(pParent, nStyle)
{
    SetMapMode(MapMode(MAP_PIXEL));
}

Size SwEnvPreview::GetOptimalSize() const
{
    return LogicToPixel(Size(84 , 63), MAP_APPFONT);
}

extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeSwEnvPreview(Window *pParent, VclBuilder::stringmap &)
{
    return new SwEnvPreview(pParent, 0);
}

void SwEnvPreview::DataChanged( const DataChangedEvent& rDCEvt )
{
    Window::DataChanged( rDCEvt );
    if ( DATACHANGED_SETTINGS == rDCEvt.GetType() )
        SetBackground( GetSettings().GetStyleSettings().GetDialogColor() );
}

void SwEnvPreview::Paint(const Rectangle &)
{
    const StyleSettings& rSettings = GetSettings().GetStyleSettings();

    const SwEnvItem& rItem =
        ((SwEnvDlg*) GetParentDialog())->aEnvItem;

    const long nPageW = std::max(rItem.lWidth, rItem.lHeight);
    const long nPageH = std::min(rItem.lWidth, rItem.lHeight);

    const float f = 0.8 * std::min(
        static_cast<float>(GetOutputSizePixel().Width())/static_cast<float>(nPageW),
        static_cast<float>(GetOutputSizePixel().Height())/static_cast<float>(nPageH));

    Color aBack = rSettings.GetWindowColor( );
    Color aFront = SwViewOption::GetFontColor();
    Color aMedium = Color(  ( aBack.GetRed() + aFront.GetRed() ) / 2,
                            ( aBack.GetGreen() + aFront.GetGreen() ) / 2,
                            ( aBack.GetBlue() + aFront.GetBlue() ) / 2
                        );

    SetLineColor( aFront );

    // Envelope
    const long nW = static_cast<long>(f * nPageW);
    const long nH = static_cast<long>(f * nPageH);
    const long nX = (GetOutputSizePixel().Width () - nW) / 2;
    const long nY = (GetOutputSizePixel().Height() - nH) / 2;
    SetFillColor( aBack );
    DrawRect(Rectangle(Point(nX, nY), Size(nW, nH)));

    // Sender
    if (rItem.bSend)
    {
        const long nSendX = nX + static_cast<long>(f * rItem.lSendFromLeft);
        const long nSendY = nY + static_cast<long>(f * rItem.lSendFromTop );
        const long nSendW = static_cast<long>(f * (rItem.lAddrFromLeft - rItem.lSendFromLeft));
        const long nSendH = static_cast<long>(f * (rItem.lAddrFromTop  - rItem.lSendFromTop  - 566));
        SetFillColor( aMedium );

        DrawRect(Rectangle(Point(nSendX, nSendY), Size(nSendW, nSendH)));
    }

    // Addressee
    const long nAddrX = nX + static_cast<long>(f * rItem.lAddrFromLeft);
    const long nAddrY = nY + static_cast<long>(f * rItem.lAddrFromTop );
    const long nAddrW = static_cast<long>(f * (nPageW - rItem.lAddrFromLeft - 566));
    const long nAddrH = static_cast<long>(f * (nPageH - rItem.lAddrFromTop  - 566));
    SetFillColor( aMedium );
    DrawRect(Rectangle(Point(nAddrX, nAddrY), Size(nAddrW, nAddrH)));

    // Stamp
    const long nStmpW = static_cast<long>(f * 1417 /* 2,5 cm */);
    const long nStmpH = static_cast<long>(f * 1701 /* 3,0 cm */);
    const long nStmpX = nX + nW - static_cast<long>(f * 566) - nStmpW;
    const long nStmpY = nY + static_cast<long>(f * 566);

    SetFillColor( aBack );
    DrawRect(Rectangle(Point(nStmpX, nStmpY), Size(nStmpW, nStmpH)));
}

SwEnvDlg::SwEnvDlg(Window* pParent, const SfxItemSet& rSet,
                    SwWrtShell* pWrtSh, Printer* pPrt, sal_Bool bInsert)
    : SfxTabDialog(pParent, "EnvDialog",
        "modules/swriter/ui/envdialog.ui", &rSet)
    , aEnvItem((const SwEnvItem&) rSet.Get(FN_ENVELOP))
    , pSh(pWrtSh)
    , pPrinter(pPrt)
    , pAddresseeSet(0)
    , pSenderSet(0)
    , m_nEnvPrintId(0)
{
    if (!bInsert)
    {
        GetUserButton()->SetText(get<PushButton>("modify")->GetText());
    }

    AddTabPage("envelope", SwEnvPage   ::Create, 0);
    AddTabPage("format", SwEnvFmtPage::Create, 0);
    m_nEnvPrintId = AddTabPage("printer", SwEnvPrtPage::Create, 0);
}

SwEnvDlg::~SwEnvDlg()
{
    delete pAddresseeSet;
    delete pSenderSet;
}

void SwEnvDlg::PageCreated(sal_uInt16 nId, SfxTabPage &rPage)
{
    if (nId == m_nEnvPrintId)
    {
        ((SwEnvPrtPage*)&rPage)->SetPrt(pPrinter);
    }
}

short SwEnvDlg::Ok()
{
    short nRet = SfxTabDialog::Ok();

    if (nRet == RET_OK || nRet == RET_USER)
    {
        if (pAddresseeSet)
        {
            SwTxtFmtColl* pColl = pSh->GetTxtCollFromPool(RES_POOLCOLL_JAKETADRESS);
            pColl->SetFmtAttr(*pAddresseeSet);
        }
        if (pSenderSet)
        {
            SwTxtFmtColl* pColl = pSh->GetTxtCollFromPool(RES_POOLCOLL_SENDADRESS);
            pColl->SetFmtAttr(*pSenderSet);
        }
    }

    return nRet;
}

SwEnvPage::SwEnvPage(Window* pParent, const SfxItemSet& rSet)
    : SfxTabPage(pParent, "EnvAddressPage",
        "modules/swriter/ui/envaddresspage.ui", rSet)
{
    get(m_pAddrEdit, "addredit");
    get(m_pDatabaseLB, "database");
    get(m_pTableLB, "table");
    get(m_pDBFieldLB, "field");
    get(m_pInsertBT, "insert");
    get(m_pSenderBox, "sender");
    get(m_pSenderEdit, "senderedit");
    get(m_pPreview, "preview");

    long nTextBoxHeight(m_pAddrEdit->GetTextHeight() * 10);
    long nTextBoxWidth(m_pAddrEdit->approximate_char_width() * 25);

    m_pAddrEdit->set_height_request(nTextBoxHeight);
    m_pAddrEdit->set_width_request(nTextBoxWidth);
    m_pSenderEdit->set_height_request(nTextBoxHeight);
    m_pSenderEdit->set_width_request(nTextBoxWidth);

    long nListBoxWidth = approximate_char_width() * 30;
    m_pTableLB->set_width_request(nListBoxWidth);
    m_pDatabaseLB->set_width_request(nListBoxWidth);
    m_pDBFieldLB->set_width_request(nListBoxWidth);

    SetExchangeSupport();
    pSh = GetParentSwEnvDlg()->pSh;

    // Install handlers
    m_pDatabaseLB->SetSelectHdl(LINK(this, SwEnvPage, DatabaseHdl     ));
    m_pTableLB->SetSelectHdl(LINK(this, SwEnvPage, DatabaseHdl     ));
    m_pInsertBT->SetClickHdl (LINK(this, SwEnvPage, FieldHdl        ));
    m_pSenderBox->SetClickHdl (LINK(this, SwEnvPage, SenderHdl       ));
    m_pPreview->SetBorderStyle( WINDOW_BORDER_MONO );

    SwDBData aData = pSh->GetDBData();
    sActDBName = aData.sDataSource + OUString(DB_DELIM) + aData.sCommand;
    InitDatabaseBox();
}

SwEnvPage::~SwEnvPage()
{
}

IMPL_LINK( SwEnvPage, DatabaseHdl, ListBox *, pListBox )
{
    SwWait aWait( *pSh->GetView().GetDocShell(), true );

    if (pListBox == m_pDatabaseLB)
    {
        sActDBName = pListBox->GetSelectEntry();
        pSh->GetNewDBMgr()->GetTableNames(m_pTableLB, sActDBName);
        sActDBName += OUString(DB_DELIM);
    }
    else
    {
        sActDBName = comphelper::string::setToken(sActDBName, 1, DB_DELIM, m_pTableLB->GetSelectEntry());
    }
    pSh->GetNewDBMgr()->GetColumnNames(m_pDBFieldLB, m_pDatabaseLB->GetSelectEntry(),
                                       m_pTableLB->GetSelectEntry());
    return 0;
}

IMPL_LINK_NOARG(SwEnvPage, FieldHdl)
{
    OUString aStr("<" + m_pDatabaseLB->GetSelectEntry() + "." +
                  m_pTableLB->GetSelectEntry() + "." +
                  OUString(m_pTableLB->GetEntryData(m_pTableLB->GetSelectEntryPos()) == 0 ? '0' : '1') + "." +
                  m_pDBFieldLB->GetSelectEntry() + ">");
    m_pAddrEdit->ReplaceSelected(aStr);
    Selection aSel = m_pAddrEdit->GetSelection();
    m_pAddrEdit->GrabFocus();
    m_pAddrEdit->SetSelection(aSel);
    return 0;
}

IMPL_LINK_NOARG(SwEnvPage, SenderHdl)
{
    const sal_Bool bEnable = m_pSenderBox->IsChecked();
    GetParentSwEnvDlg()->aEnvItem.bSend = bEnable;
    m_pSenderEdit->Enable(bEnable);
    if ( bEnable )
    {
        m_pSenderEdit->GrabFocus();
        if(m_pSenderEdit->GetText().isEmpty())
            m_pSenderEdit->SetText(MakeSender());
    }
    m_pPreview->Invalidate();
    return 0;
}

void SwEnvPage::InitDatabaseBox()
{
    if (pSh->GetNewDBMgr())
    {
        m_pDatabaseLB->Clear();
        Sequence<OUString> aDataNames = SwNewDBMgr::GetExistingDatabaseNames();
        const OUString* pDataNames = aDataNames.getConstArray();

        for (long i = 0; i < aDataNames.getLength(); i++)
            m_pDatabaseLB->InsertEntry(pDataNames[i]);

        OUString sDBName = sActDBName.getToken( 0, DB_DELIM );
        OUString sTableName = sActDBName.getToken( 1, DB_DELIM );
        m_pDatabaseLB->SelectEntry(sDBName);
        if (pSh->GetNewDBMgr()->GetTableNames(m_pTableLB, sDBName))
        {
            m_pTableLB->SelectEntry(sTableName);
            pSh->GetNewDBMgr()->GetColumnNames(m_pDBFieldLB, sDBName, sTableName);
        }
        else
            m_pDBFieldLB->Clear();

    }
}

SfxTabPage* SwEnvPage::Create(Window* pParent, const SfxItemSet& rSet)
{
    return new SwEnvPage(pParent, rSet);
}

void SwEnvPage::ActivatePage(const SfxItemSet& rSet)
{
    SfxItemSet aSet(rSet);
    aSet.Put(GetParentSwEnvDlg()->aEnvItem);
    Reset(aSet);
}

int SwEnvPage::DeactivatePage(SfxItemSet* _pSet)
{
    FillItem(GetParentSwEnvDlg()->aEnvItem);
    if( _pSet )
        FillItemSet(*_pSet);
    return SfxTabPage::LEAVE_PAGE;
}

void SwEnvPage::FillItem(SwEnvItem& rItem)
{
    rItem.aAddrText = m_pAddrEdit->GetText();
    rItem.bSend     = m_pSenderBox->IsChecked();
    rItem.aSendText = m_pSenderEdit->GetText();
}

bool SwEnvPage::FillItemSet(SfxItemSet& rSet)
{
    FillItem(GetParentSwEnvDlg()->aEnvItem);
    rSet.Put(GetParentSwEnvDlg()->aEnvItem);
    return true;
}

void SwEnvPage::Reset(const SfxItemSet& rSet)
{
    SwEnvItem aItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP);
    m_pAddrEdit->SetText(convertLineEnd(aItem.aAddrText, GetSystemLineEnd()));
    m_pSenderEdit->SetText(convertLineEnd(aItem.aSendText, GetSystemLineEnd()));
    m_pSenderBox->Check  (aItem.bSend);
    m_pSenderBox->GetClickHdl().Call(m_pSenderBox);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>long to sal_Int32 as index for Sequence<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "dbmgr.hxx"
#include <sfx2/app.hxx>
#include <vcl/builder.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/settings.hxx>

#include <swwait.hxx>
#include <viewopt.hxx>

#include "wrtsh.hxx"
#include "cmdid.h"
#include "helpid.h"
#include "envfmt.hxx"
#include "envlop.hxx"
#include "envprt.hxx"
#include "fmtcol.hxx"
#include "poolfmt.hxx"
#include "view.hxx"

#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>

#include <unomid.h>

using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::rtl;

//impl in envimg.cxx
extern SW_DLLPUBLIC OUString MakeSender();

SwEnvPreview::SwEnvPreview(Window* pParent, WinBits nStyle)
    : Window(pParent, nStyle)
{
    SetMapMode(MapMode(MAP_PIXEL));
}

Size SwEnvPreview::GetOptimalSize() const
{
    return LogicToPixel(Size(84 , 63), MAP_APPFONT);
}

extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeSwEnvPreview(Window *pParent, VclBuilder::stringmap &)
{
    return new SwEnvPreview(pParent, 0);
}

void SwEnvPreview::DataChanged( const DataChangedEvent& rDCEvt )
{
    Window::DataChanged( rDCEvt );
    if ( DATACHANGED_SETTINGS == rDCEvt.GetType() )
        SetBackground( GetSettings().GetStyleSettings().GetDialogColor() );
}

void SwEnvPreview::Paint(const Rectangle &)
{
    const StyleSettings& rSettings = GetSettings().GetStyleSettings();

    const SwEnvItem& rItem =
        ((SwEnvDlg*) GetParentDialog())->aEnvItem;

    const long nPageW = std::max(rItem.lWidth, rItem.lHeight);
    const long nPageH = std::min(rItem.lWidth, rItem.lHeight);

    const float f = 0.8 * std::min(
        static_cast<float>(GetOutputSizePixel().Width())/static_cast<float>(nPageW),
        static_cast<float>(GetOutputSizePixel().Height())/static_cast<float>(nPageH));

    Color aBack = rSettings.GetWindowColor( );
    Color aFront = SwViewOption::GetFontColor();
    Color aMedium = Color(  ( aBack.GetRed() + aFront.GetRed() ) / 2,
                            ( aBack.GetGreen() + aFront.GetGreen() ) / 2,
                            ( aBack.GetBlue() + aFront.GetBlue() ) / 2
                        );

    SetLineColor( aFront );

    // Envelope
    const long nW = static_cast<long>(f * nPageW);
    const long nH = static_cast<long>(f * nPageH);
    const long nX = (GetOutputSizePixel().Width () - nW) / 2;
    const long nY = (GetOutputSizePixel().Height() - nH) / 2;
    SetFillColor( aBack );
    DrawRect(Rectangle(Point(nX, nY), Size(nW, nH)));

    // Sender
    if (rItem.bSend)
    {
        const long nSendX = nX + static_cast<long>(f * rItem.lSendFromLeft);
        const long nSendY = nY + static_cast<long>(f * rItem.lSendFromTop );
        const long nSendW = static_cast<long>(f * (rItem.lAddrFromLeft - rItem.lSendFromLeft));
        const long nSendH = static_cast<long>(f * (rItem.lAddrFromTop  - rItem.lSendFromTop  - 566));
        SetFillColor( aMedium );

        DrawRect(Rectangle(Point(nSendX, nSendY), Size(nSendW, nSendH)));
    }

    // Addressee
    const long nAddrX = nX + static_cast<long>(f * rItem.lAddrFromLeft);
    const long nAddrY = nY + static_cast<long>(f * rItem.lAddrFromTop );
    const long nAddrW = static_cast<long>(f * (nPageW - rItem.lAddrFromLeft - 566));
    const long nAddrH = static_cast<long>(f * (nPageH - rItem.lAddrFromTop  - 566));
    SetFillColor( aMedium );
    DrawRect(Rectangle(Point(nAddrX, nAddrY), Size(nAddrW, nAddrH)));

    // Stamp
    const long nStmpW = static_cast<long>(f * 1417 /* 2,5 cm */);
    const long nStmpH = static_cast<long>(f * 1701 /* 3,0 cm */);
    const long nStmpX = nX + nW - static_cast<long>(f * 566) - nStmpW;
    const long nStmpY = nY + static_cast<long>(f * 566);

    SetFillColor( aBack );
    DrawRect(Rectangle(Point(nStmpX, nStmpY), Size(nStmpW, nStmpH)));
}

SwEnvDlg::SwEnvDlg(Window* pParent, const SfxItemSet& rSet,
                    SwWrtShell* pWrtSh, Printer* pPrt, sal_Bool bInsert)
    : SfxTabDialog(pParent, "EnvDialog",
        "modules/swriter/ui/envdialog.ui", &rSet)
    , aEnvItem((const SwEnvItem&) rSet.Get(FN_ENVELOP))
    , pSh(pWrtSh)
    , pPrinter(pPrt)
    , pAddresseeSet(0)
    , pSenderSet(0)
    , m_nEnvPrintId(0)
{
    if (!bInsert)
    {
        GetUserButton()->SetText(get<PushButton>("modify")->GetText());
    }

    AddTabPage("envelope", SwEnvPage   ::Create, 0);
    AddTabPage("format", SwEnvFmtPage::Create, 0);
    m_nEnvPrintId = AddTabPage("printer", SwEnvPrtPage::Create, 0);
}

SwEnvDlg::~SwEnvDlg()
{
    delete pAddresseeSet;
    delete pSenderSet;
}

void SwEnvDlg::PageCreated(sal_uInt16 nId, SfxTabPage &rPage)
{
    if (nId == m_nEnvPrintId)
    {
        ((SwEnvPrtPage*)&rPage)->SetPrt(pPrinter);
    }
}

short SwEnvDlg::Ok()
{
    short nRet = SfxTabDialog::Ok();

    if (nRet == RET_OK || nRet == RET_USER)
    {
        if (pAddresseeSet)
        {
            SwTxtFmtColl* pColl = pSh->GetTxtCollFromPool(RES_POOLCOLL_JAKETADRESS);
            pColl->SetFmtAttr(*pAddresseeSet);
        }
        if (pSenderSet)
        {
            SwTxtFmtColl* pColl = pSh->GetTxtCollFromPool(RES_POOLCOLL_SENDADRESS);
            pColl->SetFmtAttr(*pSenderSet);
        }
    }

    return nRet;
}

SwEnvPage::SwEnvPage(Window* pParent, const SfxItemSet& rSet)
    : SfxTabPage(pParent, "EnvAddressPage",
        "modules/swriter/ui/envaddresspage.ui", rSet)
{
    get(m_pAddrEdit, "addredit");
    get(m_pDatabaseLB, "database");
    get(m_pTableLB, "table");
    get(m_pDBFieldLB, "field");
    get(m_pInsertBT, "insert");
    get(m_pSenderBox, "sender");
    get(m_pSenderEdit, "senderedit");
    get(m_pPreview, "preview");

    long nTextBoxHeight(m_pAddrEdit->GetTextHeight() * 10);
    long nTextBoxWidth(m_pAddrEdit->approximate_char_width() * 25);

    m_pAddrEdit->set_height_request(nTextBoxHeight);
    m_pAddrEdit->set_width_request(nTextBoxWidth);
    m_pSenderEdit->set_height_request(nTextBoxHeight);
    m_pSenderEdit->set_width_request(nTextBoxWidth);

    long nListBoxWidth = approximate_char_width() * 30;
    m_pTableLB->set_width_request(nListBoxWidth);
    m_pDatabaseLB->set_width_request(nListBoxWidth);
    m_pDBFieldLB->set_width_request(nListBoxWidth);

    SetExchangeSupport();
    pSh = GetParentSwEnvDlg()->pSh;

    // Install handlers
    m_pDatabaseLB->SetSelectHdl(LINK(this, SwEnvPage, DatabaseHdl     ));
    m_pTableLB->SetSelectHdl(LINK(this, SwEnvPage, DatabaseHdl     ));
    m_pInsertBT->SetClickHdl (LINK(this, SwEnvPage, FieldHdl        ));
    m_pSenderBox->SetClickHdl (LINK(this, SwEnvPage, SenderHdl       ));
    m_pPreview->SetBorderStyle( WINDOW_BORDER_MONO );

    SwDBData aData = pSh->GetDBData();
    sActDBName = aData.sDataSource + OUString(DB_DELIM) + aData.sCommand;
    InitDatabaseBox();
}

SwEnvPage::~SwEnvPage()
{
}

IMPL_LINK( SwEnvPage, DatabaseHdl, ListBox *, pListBox )
{
    SwWait aWait( *pSh->GetView().GetDocShell(), true );

    if (pListBox == m_pDatabaseLB)
    {
        sActDBName = pListBox->GetSelectEntry();
        pSh->GetNewDBMgr()->GetTableNames(m_pTableLB, sActDBName);
        sActDBName += OUString(DB_DELIM);
    }
    else
    {
        sActDBName = comphelper::string::setToken(sActDBName, 1, DB_DELIM, m_pTableLB->GetSelectEntry());
    }
    pSh->GetNewDBMgr()->GetColumnNames(m_pDBFieldLB, m_pDatabaseLB->GetSelectEntry(),
                                       m_pTableLB->GetSelectEntry());
    return 0;
}

IMPL_LINK_NOARG(SwEnvPage, FieldHdl)
{
    OUString aStr("<" + m_pDatabaseLB->GetSelectEntry() + "." +
                  m_pTableLB->GetSelectEntry() + "." +
                  OUString(m_pTableLB->GetEntryData(m_pTableLB->GetSelectEntryPos()) == 0 ? '0' : '1') + "." +
                  m_pDBFieldLB->GetSelectEntry() + ">");
    m_pAddrEdit->ReplaceSelected(aStr);
    Selection aSel = m_pAddrEdit->GetSelection();
    m_pAddrEdit->GrabFocus();
    m_pAddrEdit->SetSelection(aSel);
    return 0;
}

IMPL_LINK_NOARG(SwEnvPage, SenderHdl)
{
    const sal_Bool bEnable = m_pSenderBox->IsChecked();
    GetParentSwEnvDlg()->aEnvItem.bSend = bEnable;
    m_pSenderEdit->Enable(bEnable);
    if ( bEnable )
    {
        m_pSenderEdit->GrabFocus();
        if(m_pSenderEdit->GetText().isEmpty())
            m_pSenderEdit->SetText(MakeSender());
    }
    m_pPreview->Invalidate();
    return 0;
}

void SwEnvPage::InitDatabaseBox()
{
    if (pSh->GetNewDBMgr())
    {
        m_pDatabaseLB->Clear();
        Sequence<OUString> aDataNames = SwNewDBMgr::GetExistingDatabaseNames();
        const OUString* pDataNames = aDataNames.getConstArray();

        for (sal_Int32 i = 0; i < aDataNames.getLength(); i++)
            m_pDatabaseLB->InsertEntry(pDataNames[i]);

        OUString sDBName = sActDBName.getToken( 0, DB_DELIM );
        OUString sTableName = sActDBName.getToken( 1, DB_DELIM );
        m_pDatabaseLB->SelectEntry(sDBName);
        if (pSh->GetNewDBMgr()->GetTableNames(m_pTableLB, sDBName))
        {
            m_pTableLB->SelectEntry(sTableName);
            pSh->GetNewDBMgr()->GetColumnNames(m_pDBFieldLB, sDBName, sTableName);
        }
        else
            m_pDBFieldLB->Clear();

    }
}

SfxTabPage* SwEnvPage::Create(Window* pParent, const SfxItemSet& rSet)
{
    return new SwEnvPage(pParent, rSet);
}

void SwEnvPage::ActivatePage(const SfxItemSet& rSet)
{
    SfxItemSet aSet(rSet);
    aSet.Put(GetParentSwEnvDlg()->aEnvItem);
    Reset(aSet);
}

int SwEnvPage::DeactivatePage(SfxItemSet* _pSet)
{
    FillItem(GetParentSwEnvDlg()->aEnvItem);
    if( _pSet )
        FillItemSet(*_pSet);
    return SfxTabPage::LEAVE_PAGE;
}

void SwEnvPage::FillItem(SwEnvItem& rItem)
{
    rItem.aAddrText = m_pAddrEdit->GetText();
    rItem.bSend     = m_pSenderBox->IsChecked();
    rItem.aSendText = m_pSenderEdit->GetText();
}

bool SwEnvPage::FillItemSet(SfxItemSet& rSet)
{
    FillItem(GetParentSwEnvDlg()->aEnvItem);
    rSet.Put(GetParentSwEnvDlg()->aEnvItem);
    return true;
}

void SwEnvPage::Reset(const SfxItemSet& rSet)
{
    SwEnvItem aItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP);
    m_pAddrEdit->SetText(convertLineEnd(aItem.aAddrText, GetSystemLineEnd()));
    m_pSenderEdit->SetText(convertLineEnd(aItem.aSendText, GetSystemLineEnd()));
    m_pSenderBox->Check  (aItem.bSend);
    m_pSenderBox->GetClickHdl().Call(m_pSenderBox);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>