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

#ifndef _SVX_UNOMASTER_HXX
#define _SVX_UNOMASTER_HXX

#ifndef _COM_SUN_STAR_UNO_TYPE_H_
#include <com/sun/star/uno/Type.h>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif

/** this abstract class is the interface for an instance that likes to enhance
    the functionality of components implemented with derivations from SvxShape

    @see SvxShape::setMaster
*/
class SvxShapeMaster
{
public:
    virtual sal_Bool queryAggregation( const com::sun::star::uno::Type & rType, com::sun::star::uno::Any& aAny ) = 0;

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException) = 0;
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) = 0;
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) = 0;

    virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException) = 0;
    virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException) = 0;
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName )  throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) = 0;

    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException) = 0;

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException) = 0;

    virtual void dispose() = 0;
};

#endif

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

#ifndef _SVX_UNOMASTER_HXX
#define _SVX_UNOMASTER_HXX

#ifndef _COM_SUN_STAR_UNO_TYPE_H_
#include <com/sun/star/uno/Type.h>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif

/** this abstract class is the interface for an instance that likes to enhance
    the functionality of components implemented with derivations from SvxShape

    @see SvxShape::setMaster
*/
class SvxShapeMaster
{
public:
    virtual sal_Bool queryAggregation( const com::sun::star::uno::Type & rType, com::sun::star::uno::Any& aAny ) = 0;

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException) = 0;
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) = 0;
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) = 0;

    virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException) = 0;
    virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException) = 0;
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName )  throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) = 0;

    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException) = 0;

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException) = 0;

    virtual void dispose() = 0;
};

#endif

<|endoftext|>


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

#ifndef _SW_REWRITER_HXX
#define _SW_REWRITER_HXX

#include <vector>
#include <tools/string.hxx>

typedef std::pair<String, String> SwRewriteRule;

class SwRewriter
{
    std::vector<SwRewriteRule> mRules;

public:
    SwRewriter();
    SwRewriter(const SwRewriter & rSrc);
    ~SwRewriter();

    void AddRule(const String & rWhat, const String & rWith);

    String Apply(const String & rStr) const;
    std::vector<String> Apply(const std::vector<String> & rStrs) const;

    String ToString() const;
};

#endif // _SW_REWRITER_HXX
<commit_msg>INTEGRATION: CWS os94 (1.8.222); FILE MERGED 2007/03/12 08:07:27 os 1.8.222.1: #i75235# unused methods removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwRewriter.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-25 08:50:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SW_REWRITER_HXX
#define _SW_REWRITER_HXX

#include <vector>
#include <tools/string.hxx>

typedef std::pair<String, String> SwRewriteRule;

class SwRewriter
{
    std::vector<SwRewriteRule> mRules;

public:
    SwRewriter();
    SwRewriter(const SwRewriter & rSrc);
    ~SwRewriter();

    void AddRule(const String & rWhat, const String & rWith);

    String Apply(const String & rStr) const;
};

#endif // _SW_REWRITER_HXX
<|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 <prex.h>
#include <X11/Xatom.h>
#include <postx.h>

#include <unx/desktops.hxx>

#include "rtl/bootstrap.hxx"
#include "rtl/process.h"
#include "rtl/ustrbuf.hxx"
#include "osl/module.h"
#include "osl/thread.h"
#include "vcl/svapp.hxx"

#include "vclpluginapi.h"

#include <unistd.h>
#include <string.h>

static bool is_gnome_desktop( Display* pDisplay )
{
    bool ret = false;

    // warning: these checks are coincidental, GNOME does not
    // explicitly advertise itself
    if ( NULL != getenv( "GNOME_DESKTOP_SESSION_ID" ) )
        ret = true;

    if( ! ret )
    {
        Atom nAtom1 = XInternAtom( pDisplay, "GNOME_SM_PROXY", True );
        Atom nAtom2 = XInternAtom( pDisplay, "NAUTILUS_DESKTOP_WINDOW_ID", True );
        if( nAtom1 || nAtom2 )
        {
            int nProperties = 0;
            Atom* pProperties = XListProperties( pDisplay, DefaultRootWindow( pDisplay ), &nProperties );
            if( pProperties && nProperties )
            {
                for( int i = 0; i < nProperties; i++ )
                    if( pProperties[ i ] == nAtom1 ||
                        pProperties[ i ] == nAtom2 )
                {
                    ret = true;
                }
                XFree( pProperties );
            }
        }
    }

    if( ! ret )
    {
        Atom nUTFAtom       = XInternAtom( pDisplay, "UTF8_STRING", True );
        Atom nNetWMNameAtom = XInternAtom( pDisplay, "_NET_WM_NAME", True );
        if( nUTFAtom && nNetWMNameAtom )
        {
            // another, more expensive check: search for a gnome-panel
            ::Window aRoot, aParent, *pChildren = NULL;
            unsigned int nChildren = 0;
            XQueryTree( pDisplay, DefaultRootWindow( pDisplay ),
                        &aRoot, &aParent, &pChildren, &nChildren );
            if( pChildren && nChildren )
            {
                for( unsigned int i = 0; i < nChildren && ! ret; i++ )
                {
                    Atom nType = None;
                    int nFormat = 0;
                    unsigned long nItems = 0, nBytes = 0;
                    unsigned char* pProp = NULL;
                    XGetWindowProperty( pDisplay,
                                        pChildren[i],
                                        nNetWMNameAtom,
                                        0, 8,
                                        False,
                                        nUTFAtom,
                                        &nType,
                                        &nFormat,
                                        &nItems,
                                        &nBytes,
                                        &pProp );
                    if( pProp && nType == nUTFAtom )
                    {
                        OString aWMName( (sal_Char*)pProp );
                        if (
                            (aWMName.equalsIgnoreAsciiCase("gnome-shell")) ||
                            (aWMName.equalsIgnoreAsciiCase("gnome-panel"))
                           )
                        {
                            ret = true;
                        }
                    }
                    if( pProp )
                        XFree( pProp );
                }
                XFree( pChildren );
            }
        }
    }

    return ret;
}

static bool bWasXError = false;

static inline bool WasXError()
{
    bool bRet = bWasXError;
    bWasXError = false;
    return bRet;
}

extern "C"
{
    static int autodect_error_handler( Display*, XErrorEvent* )
    {
        bWasXError = true;
        return 0;
    }

    typedef int(* XErrorHandler)(Display*,XErrorEvent*);
}

static int TDEVersion( Display* pDisplay )
{
    int nRet = 0;

    Atom nFullSession = XInternAtom( pDisplay, "TDE_FULL_SESSION", True );
    Atom nTDEVersion  = XInternAtom( pDisplay, "TDE_SESSION_VERSION", True );

    if( nFullSession )
    {
        if( !nTDEVersion )
            return 14;

        Atom                aRealType   = None;
        int                 nFormat     = 8;
        unsigned long       nItems      = 0;
        unsigned long       nBytesLeft  = 0;
        unsigned char*  pProperty   = NULL;
        XGetWindowProperty( pDisplay,
                            DefaultRootWindow( pDisplay ),
                            nTDEVersion,
                            0, 1,
                            False,
                            AnyPropertyType,
                            &aRealType,
                            &nFormat,
                            &nItems,
                            &nBytesLeft,
                            &pProperty );
        if( !WasXError() && nItems != 0 && pProperty )
        {
            nRet = *reinterpret_cast< sal_Int32* >( pProperty );
        }
        if( pProperty )
        {
            XFree( pProperty );
            pProperty = NULL;
        }
    }
    return nRet;
}

static int KDEVersion( Display* pDisplay )
{
    int nRet = 0;

    Atom nFullSession = XInternAtom( pDisplay, "KDE_FULL_SESSION", True );
    Atom nKDEVersion  = XInternAtom( pDisplay, "KDE_SESSION_VERSION", True );

    if( nFullSession )
    {
        if( !nKDEVersion )
            return 3;

        Atom                aRealType   = None;
        int                 nFormat     = 8;
        unsigned long       nItems      = 0;
        unsigned long       nBytesLeft  = 0;
        unsigned char*  pProperty   = NULL;
        XGetWindowProperty( pDisplay,
                            DefaultRootWindow( pDisplay ),
                            nKDEVersion,
                            0, 1,
                            False,
                            AnyPropertyType,
                            &aRealType,
                            &nFormat,
                            &nItems,
                            &nBytesLeft,
                            &pProperty );
        if( !WasXError() && nItems != 0 && pProperty )
        {
            nRet = *reinterpret_cast< sal_Int32* >( pProperty );
        }
        if( pProperty )
        {
            XFree( pProperty );
            pProperty = NULL;
        }
    }
    return nRet;
}

static bool is_tde_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "TDE_FULL_SESSION" ) )
    {
        return true; // TDE
    }

    if ( TDEVersion( pDisplay ) >= 14 )
        return true;

    return false;
}

static bool is_kde_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "KDE_FULL_SESSION" ) )
    {
        const char *pVer = getenv( "KDE_SESSION_VERSION" );
        if ( !pVer || pVer[0] == '0' )
        {
            return true; // does not exist => KDE3
        }

        OUString aVer( "3" );
        if ( aVer.equalsIgnoreAsciiCaseAscii( pVer ) )
        {
            return true;
        }
    }

    if ( KDEVersion( pDisplay ) == 3 )
        return true;

    return false;
}

static bool is_kde4_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "KDE_FULL_SESSION" ) )
    {
        OUString aVer( "4" );

        const char *pVer = getenv( "KDE_SESSION_VERSION" );
        if ( pVer && aVer.equalsIgnoreAsciiCaseAscii( pVer ) )
            return true;
    }

    if ( KDEVersion( pDisplay ) == 4 )
        return true;

    return false;
}

static bool is_kde5_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "KDE_FULL_SESSION" ) )
    {
        OUString aVer( "5" );

        const char *pVer = getenv( "KDE_SESSION_VERSION" );
        if ( pVer && aVer.equalsIgnoreAsciiCaseAscii( pVer ) )
            return true;
    }

    if ( KDEVersion( pDisplay ) == 5 )
        return true;

    return false;
}

extern "C"
{

DESKTOP_DETECTOR_PUBLIC DesktopType get_desktop_environment()
{
    static const char *pOverride = getenv( "OOO_FORCE_DESKTOP" );

    if ( pOverride && *pOverride )
    {
        OString aOver( pOverride );

        if ( aOver.equalsIgnoreAsciiCase( "tde" ) )
            return DESKTOP_TDE;
        if ( aOver.equalsIgnoreAsciiCase( "kde5" ) )
            return DESKTOP_KDE5;
        if ( aOver.equalsIgnoreAsciiCase( "kde4" ) )
            return DESKTOP_KDE4;
        if ( aOver.equalsIgnoreAsciiCase( "gnome" ) )
            return DESKTOP_GNOME;
        if ( aOver.equalsIgnoreAsciiCase( "unity" ) )
            return DESKTOP_UNITY;
        if ( aOver.equalsIgnoreAsciiCase( "xfce" ) )
            return DESKTOP_XFCE;
        if ( aOver.equalsIgnoreAsciiCase( "mate" ) )
            return DESKTOP_MATE;
        if ( aOver.equalsIgnoreAsciiCase( "kde" ) )
            return DESKTOP_KDE;
        if ( aOver.equalsIgnoreAsciiCase( "none" ) )
            return DESKTOP_UNKNOWN;
    }

    // get display to connect to
    const char* pDisplayStr = getenv( "DISPLAY" );

    OUString plugin;
    rtl::Bootstrap::get("SAL_USE_VCLPLUGIN", plugin);

    if (plugin == "svp" || Application::IsHeadlessModeRequested())
        pDisplayStr = NULL;
    else
    {
        int nParams = rtl_getAppCommandArgCount();
        OUString aParam;
        OString aBParm;
        for( int i = 0; i < nParams; i++ )
        {
            rtl_getAppCommandArg( i, &aParam.pData );
            if( i < nParams-1 && (aParam == "-display" || aParam == "--display" ) )
            {
                rtl_getAppCommandArg( i+1, &aParam.pData );
                aBParm = OUStringToOString( aParam, osl_getThreadTextEncoding() );
                pDisplayStr = aBParm.getStr();
                break;
            }
        }
    }

    // no server at all
    if( ! pDisplayStr || !*pDisplayStr )
        return DESKTOP_NONE;

    /* #i92121# workaround deadlocks in the X11 implementation
    */
    static const char* pNoXInitThreads = getenv( "SAL_NO_XINITTHREADS" );
    /* #i90094#
       from now on we know that an X connection will be
       established, so protect X against itself
    */
    if( ! ( pNoXInitThreads && *pNoXInitThreads ) )
        XInitThreads();

    Display* pDisplay = XOpenDisplay( pDisplayStr );
    if( pDisplay == NULL )
        return DESKTOP_NONE;

    DesktopType ret;

    XErrorHandler pOldHdl = XSetErrorHandler( autodect_error_handler );

    const char *pSession;
    OString aDesktopSession;
    if ( ( pSession = getenv( "DESKTOP_SESSION" ) ) )
        aDesktopSession = OString( pSession, strlen( pSession ) );

    const char *pDesktop;
    OString aCurrentDesktop;
    if ( ( pDesktop = getenv( "XDG_CURRENT_DESKTOP" ) ) )
        aCurrentDesktop = OString( pDesktop, strlen( pDesktop ) );

    // fast environment variable checks
    if ( aCurrentDesktop.equalsIgnoreAsciiCase( "unity" ) )
        ret = DESKTOP_UNITY;
    else if ( aDesktopSession.equalsIgnoreAsciiCase( "gnome" ) )
        ret = DESKTOP_GNOME;
    else if ( aDesktopSession.equalsIgnoreAsciiCase( "mate" ) )
        ret = DESKTOP_MATE;
    else if ( aDesktopSession.equalsIgnoreAsciiCase( "xfce" ) )
        ret = DESKTOP_XFCE;

    // these guys can be slower, with X property fetches,
    // round-trips etc. and so are done later.
    else if ( is_kde5_desktop( pDisplay ) )
        ret = DESKTOP_KDE5;
    else if ( is_kde4_desktop( pDisplay ) )
        ret = DESKTOP_KDE4;
    else if ( is_gnome_desktop( pDisplay ) )
        ret = DESKTOP_GNOME;
    else if ( is_kde_desktop( pDisplay ) )
        ret = DESKTOP_KDE;
    else if ( is_tde_desktop( pDisplay ) )
        ret = DESKTOP_TDE;
    else
        ret = DESKTOP_UNKNOWN;

    // set the default handler again
    XSetErrorHandler( pOldHdl );

    XCloseDisplay( pDisplay );

    return ret;
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>No need to re-check IsHeadlessModeRequested in get_desktop_environment<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 <prex.h>
#include <X11/Xatom.h>
#include <postx.h>

#include <unx/desktops.hxx>

#include "rtl/bootstrap.hxx"
#include "rtl/process.h"
#include "rtl/ustrbuf.hxx"
#include "osl/module.h"
#include "osl/thread.h"

#include "vclpluginapi.h"

#include <unistd.h>
#include <string.h>

static bool is_gnome_desktop( Display* pDisplay )
{
    bool ret = false;

    // warning: these checks are coincidental, GNOME does not
    // explicitly advertise itself
    if ( NULL != getenv( "GNOME_DESKTOP_SESSION_ID" ) )
        ret = true;

    if( ! ret )
    {
        Atom nAtom1 = XInternAtom( pDisplay, "GNOME_SM_PROXY", True );
        Atom nAtom2 = XInternAtom( pDisplay, "NAUTILUS_DESKTOP_WINDOW_ID", True );
        if( nAtom1 || nAtom2 )
        {
            int nProperties = 0;
            Atom* pProperties = XListProperties( pDisplay, DefaultRootWindow( pDisplay ), &nProperties );
            if( pProperties && nProperties )
            {
                for( int i = 0; i < nProperties; i++ )
                    if( pProperties[ i ] == nAtom1 ||
                        pProperties[ i ] == nAtom2 )
                {
                    ret = true;
                }
                XFree( pProperties );
            }
        }
    }

    if( ! ret )
    {
        Atom nUTFAtom       = XInternAtom( pDisplay, "UTF8_STRING", True );
        Atom nNetWMNameAtom = XInternAtom( pDisplay, "_NET_WM_NAME", True );
        if( nUTFAtom && nNetWMNameAtom )
        {
            // another, more expensive check: search for a gnome-panel
            ::Window aRoot, aParent, *pChildren = NULL;
            unsigned int nChildren = 0;
            XQueryTree( pDisplay, DefaultRootWindow( pDisplay ),
                        &aRoot, &aParent, &pChildren, &nChildren );
            if( pChildren && nChildren )
            {
                for( unsigned int i = 0; i < nChildren && ! ret; i++ )
                {
                    Atom nType = None;
                    int nFormat = 0;
                    unsigned long nItems = 0, nBytes = 0;
                    unsigned char* pProp = NULL;
                    XGetWindowProperty( pDisplay,
                                        pChildren[i],
                                        nNetWMNameAtom,
                                        0, 8,
                                        False,
                                        nUTFAtom,
                                        &nType,
                                        &nFormat,
                                        &nItems,
                                        &nBytes,
                                        &pProp );
                    if( pProp && nType == nUTFAtom )
                    {
                        OString aWMName( (sal_Char*)pProp );
                        if (
                            (aWMName.equalsIgnoreAsciiCase("gnome-shell")) ||
                            (aWMName.equalsIgnoreAsciiCase("gnome-panel"))
                           )
                        {
                            ret = true;
                        }
                    }
                    if( pProp )
                        XFree( pProp );
                }
                XFree( pChildren );
            }
        }
    }

    return ret;
}

static bool bWasXError = false;

static inline bool WasXError()
{
    bool bRet = bWasXError;
    bWasXError = false;
    return bRet;
}

extern "C"
{
    static int autodect_error_handler( Display*, XErrorEvent* )
    {
        bWasXError = true;
        return 0;
    }

    typedef int(* XErrorHandler)(Display*,XErrorEvent*);
}

static int TDEVersion( Display* pDisplay )
{
    int nRet = 0;

    Atom nFullSession = XInternAtom( pDisplay, "TDE_FULL_SESSION", True );
    Atom nTDEVersion  = XInternAtom( pDisplay, "TDE_SESSION_VERSION", True );

    if( nFullSession )
    {
        if( !nTDEVersion )
            return 14;

        Atom                aRealType   = None;
        int                 nFormat     = 8;
        unsigned long       nItems      = 0;
        unsigned long       nBytesLeft  = 0;
        unsigned char*  pProperty   = NULL;
        XGetWindowProperty( pDisplay,
                            DefaultRootWindow( pDisplay ),
                            nTDEVersion,
                            0, 1,
                            False,
                            AnyPropertyType,
                            &aRealType,
                            &nFormat,
                            &nItems,
                            &nBytesLeft,
                            &pProperty );
        if( !WasXError() && nItems != 0 && pProperty )
        {
            nRet = *reinterpret_cast< sal_Int32* >( pProperty );
        }
        if( pProperty )
        {
            XFree( pProperty );
            pProperty = NULL;
        }
    }
    return nRet;
}

static int KDEVersion( Display* pDisplay )
{
    int nRet = 0;

    Atom nFullSession = XInternAtom( pDisplay, "KDE_FULL_SESSION", True );
    Atom nKDEVersion  = XInternAtom( pDisplay, "KDE_SESSION_VERSION", True );

    if( nFullSession )
    {
        if( !nKDEVersion )
            return 3;

        Atom                aRealType   = None;
        int                 nFormat     = 8;
        unsigned long       nItems      = 0;
        unsigned long       nBytesLeft  = 0;
        unsigned char*  pProperty   = NULL;
        XGetWindowProperty( pDisplay,
                            DefaultRootWindow( pDisplay ),
                            nKDEVersion,
                            0, 1,
                            False,
                            AnyPropertyType,
                            &aRealType,
                            &nFormat,
                            &nItems,
                            &nBytesLeft,
                            &pProperty );
        if( !WasXError() && nItems != 0 && pProperty )
        {
            nRet = *reinterpret_cast< sal_Int32* >( pProperty );
        }
        if( pProperty )
        {
            XFree( pProperty );
            pProperty = NULL;
        }
    }
    return nRet;
}

static bool is_tde_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "TDE_FULL_SESSION" ) )
    {
        return true; // TDE
    }

    if ( TDEVersion( pDisplay ) >= 14 )
        return true;

    return false;
}

static bool is_kde_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "KDE_FULL_SESSION" ) )
    {
        const char *pVer = getenv( "KDE_SESSION_VERSION" );
        if ( !pVer || pVer[0] == '0' )
        {
            return true; // does not exist => KDE3
        }

        OUString aVer( "3" );
        if ( aVer.equalsIgnoreAsciiCaseAscii( pVer ) )
        {
            return true;
        }
    }

    if ( KDEVersion( pDisplay ) == 3 )
        return true;

    return false;
}

static bool is_kde4_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "KDE_FULL_SESSION" ) )
    {
        OUString aVer( "4" );

        const char *pVer = getenv( "KDE_SESSION_VERSION" );
        if ( pVer && aVer.equalsIgnoreAsciiCaseAscii( pVer ) )
            return true;
    }

    if ( KDEVersion( pDisplay ) == 4 )
        return true;

    return false;
}

static bool is_kde5_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "KDE_FULL_SESSION" ) )
    {
        OUString aVer( "5" );

        const char *pVer = getenv( "KDE_SESSION_VERSION" );
        if ( pVer && aVer.equalsIgnoreAsciiCaseAscii( pVer ) )
            return true;
    }

    if ( KDEVersion( pDisplay ) == 5 )
        return true;

    return false;
}

extern "C"
{

DESKTOP_DETECTOR_PUBLIC DesktopType get_desktop_environment()
{
    static const char *pOverride = getenv( "OOO_FORCE_DESKTOP" );

    if ( pOverride && *pOverride )
    {
        OString aOver( pOverride );

        if ( aOver.equalsIgnoreAsciiCase( "tde" ) )
            return DESKTOP_TDE;
        if ( aOver.equalsIgnoreAsciiCase( "kde5" ) )
            return DESKTOP_KDE5;
        if ( aOver.equalsIgnoreAsciiCase( "kde4" ) )
            return DESKTOP_KDE4;
        if ( aOver.equalsIgnoreAsciiCase( "gnome" ) )
            return DESKTOP_GNOME;
        if ( aOver.equalsIgnoreAsciiCase( "unity" ) )
            return DESKTOP_UNITY;
        if ( aOver.equalsIgnoreAsciiCase( "xfce" ) )
            return DESKTOP_XFCE;
        if ( aOver.equalsIgnoreAsciiCase( "mate" ) )
            return DESKTOP_MATE;
        if ( aOver.equalsIgnoreAsciiCase( "kde" ) )
            return DESKTOP_KDE;
        if ( aOver.equalsIgnoreAsciiCase( "none" ) )
            return DESKTOP_UNKNOWN;
    }

    // get display to connect to
    const char* pDisplayStr = getenv( "DISPLAY" );

    OUString plugin;
    rtl::Bootstrap::get("SAL_USE_VCLPLUGIN", plugin);

    if (plugin == "svp")
        pDisplayStr = NULL;
    else
    {
        int nParams = rtl_getAppCommandArgCount();
        OUString aParam;
        OString aBParm;
        for( int i = 0; i < nParams; i++ )
        {
            rtl_getAppCommandArg( i, &aParam.pData );
            if( i < nParams-1 && (aParam == "-display" || aParam == "--display" ) )
            {
                rtl_getAppCommandArg( i+1, &aParam.pData );
                aBParm = OUStringToOString( aParam, osl_getThreadTextEncoding() );
                pDisplayStr = aBParm.getStr();
                break;
            }
        }
    }

    // no server at all
    if( ! pDisplayStr || !*pDisplayStr )
        return DESKTOP_NONE;

    /* #i92121# workaround deadlocks in the X11 implementation
    */
    static const char* pNoXInitThreads = getenv( "SAL_NO_XINITTHREADS" );
    /* #i90094#
       from now on we know that an X connection will be
       established, so protect X against itself
    */
    if( ! ( pNoXInitThreads && *pNoXInitThreads ) )
        XInitThreads();

    Display* pDisplay = XOpenDisplay( pDisplayStr );
    if( pDisplay == NULL )
        return DESKTOP_NONE;

    DesktopType ret;

    XErrorHandler pOldHdl = XSetErrorHandler( autodect_error_handler );

    const char *pSession;
    OString aDesktopSession;
    if ( ( pSession = getenv( "DESKTOP_SESSION" ) ) )
        aDesktopSession = OString( pSession, strlen( pSession ) );

    const char *pDesktop;
    OString aCurrentDesktop;
    if ( ( pDesktop = getenv( "XDG_CURRENT_DESKTOP" ) ) )
        aCurrentDesktop = OString( pDesktop, strlen( pDesktop ) );

    // fast environment variable checks
    if ( aCurrentDesktop.equalsIgnoreAsciiCase( "unity" ) )
        ret = DESKTOP_UNITY;
    else if ( aDesktopSession.equalsIgnoreAsciiCase( "gnome" ) )
        ret = DESKTOP_GNOME;
    else if ( aDesktopSession.equalsIgnoreAsciiCase( "mate" ) )
        ret = DESKTOP_MATE;
    else if ( aDesktopSession.equalsIgnoreAsciiCase( "xfce" ) )
        ret = DESKTOP_XFCE;

    // these guys can be slower, with X property fetches,
    // round-trips etc. and so are done later.
    else if ( is_kde5_desktop( pDisplay ) )
        ret = DESKTOP_KDE5;
    else if ( is_kde4_desktop( pDisplay ) )
        ret = DESKTOP_KDE4;
    else if ( is_gnome_desktop( pDisplay ) )
        ret = DESKTOP_GNOME;
    else if ( is_kde_desktop( pDisplay ) )
        ret = DESKTOP_KDE;
    else if ( is_tde_desktop( pDisplay ) )
        ret = DESKTOP_TDE;
    else
        ret = DESKTOP_UNKNOWN;

    // set the default handler again
    XSetErrorHandler( pOldHdl );

    XCloseDisplay( pDisplay );

    return ret;
}

}

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


<commit_before>#include "browser/views/inspectable_web_contents_view_views.h"

#include "browser/inspectable_web_contents_delegate.h"
#include "browser/inspectable_web_contents_impl.h"

#include "base/strings/utf_string_conversions.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"

namespace brightray {

namespace {

class DevToolsWindowDelegate : public views::ClientView,
                               public views::WidgetDelegate {
 public:
  DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
                         views::View* view,
                         views::Widget* widget)
      : views::ClientView(widget, view),
        shell_(shell),
        view_(view),
        widget_(widget),
        title_(base::ASCIIToUTF16("Developer Tools")) {
    // A WidgetDelegate should be deleted on DeleteDelegate.
    set_owned_by_client();

    InspectableWebContentsDelegate* delegate = shell->inspectable_web_contents()->GetDelegate();
    if (delegate)
      icon_ = delegate->GetDevToolsWindowIcon();
  }
  virtual ~DevToolsWindowDelegate() {}

  // views::WidgetDelegate:
  void DeleteDelegate() override { delete this; }
  views::View* GetInitiallyFocusedView() override { return view_; }
  bool CanResize() const override { return true; }
  bool CanMaximize() const override { return true; }
  base::string16 GetWindowTitle() const override { return title_; }
  gfx::ImageSkia GetWindowAppIcon() override { return GetWindowIcon(); }
  gfx::ImageSkia GetWindowIcon() override { return icon_; }
  views::Widget* GetWidget() override { return widget_; }
  const views::Widget* GetWidget() const override { return widget_; }
  views::View* GetContentsView() override { return view_; }
  views::ClientView* CreateClientView(views::Widget* widget) { return this; }

  // views::ClientView:
  bool CanClose() override {
    shell_->inspectable_web_contents()->CloseDevTools();
    return false;
  }

 private:
  InspectableWebContentsViewViews* shell_;
  views::View* view_;
  views::Widget* widget_;
  base::string16 title_;
  gfx::ImageSkia icon_;

  DISALLOW_COPY_AND_ASSIGN(DevToolsWindowDelegate);
};

}  // namespace

InspectableWebContentsView* CreateInspectableContentsView(
    InspectableWebContentsImpl* inspectable_web_contents) {
  return new InspectableWebContentsViewViews(inspectable_web_contents);
}

InspectableWebContentsViewViews::InspectableWebContentsViewViews(
    InspectableWebContentsImpl* inspectable_web_contents)
    : inspectable_web_contents_(inspectable_web_contents),
      devtools_window_web_view_(NULL),
      contents_web_view_(new views::WebView(NULL)),
      devtools_web_view_(new views::WebView(NULL)),
      devtools_visible_(false) {
  set_owned_by_client();

  devtools_web_view_->SetVisible(false);
  contents_web_view_->SetWebContents(inspectable_web_contents_->GetWebContents());
  AddChildView(devtools_web_view_);
  AddChildView(contents_web_view_);
}

InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
  if (devtools_window_)
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
}

views::View* InspectableWebContentsViewViews::GetView() {
  return this;
}

views::View* InspectableWebContentsViewViews::GetWebView() {
  return contents_web_view_;
}

void InspectableWebContentsViewViews::ShowDevTools() {
  if (devtools_visible_)
    return;

  devtools_visible_ = true;
  if (devtools_window_) {
    devtools_window_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
    devtools_window_->SetBounds(inspectable_web_contents()->GetDevToolsBounds());
    devtools_window_->Show();
  } else {
    devtools_web_view_->SetVisible(true);
    devtools_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
    devtools_web_view_->RequestFocus();
    Layout();
  }
}

void InspectableWebContentsViewViews::CloseDevTools() {
  if (!devtools_visible_)
    return;

  devtools_visible_ = false;
  if (devtools_window_) {
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
    devtools_window_.reset();
    devtools_window_web_view_ = NULL;
  } else {
    devtools_web_view_->SetVisible(false);
    devtools_web_view_->SetWebContents(NULL);
    Layout();
  }
}

bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
  return devtools_visible_;
}

void InspectableWebContentsViewViews::SetIsDocked(bool docked) {
  CloseDevTools();

  if (!docked) {
    devtools_window_.reset(new views::Widget);
    devtools_window_web_view_ = new views::WebView(NULL);

    views::Widget::InitParams params;
    params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
    params.delegate = new DevToolsWindowDelegate(this,
                                                 devtools_window_web_view_,
                                                 devtools_window_.get());
    params.bounds = inspectable_web_contents()->GetDevToolsBounds();

#if defined(USE_X11)
    params.wm_role_name = "devtools";
    InspectableWebContentsDelegate* delegate = inspectable_web_contents()->GetDelegate();
    if (delegate)
      delegate->GetDevToolsWindowWMClass(&params.wm_class_name, &params.wm_class_class);
#endif

    devtools_window_->Init(params);
    devtools_window_->UpdateWindowIcon();
  }

  ShowDevTools();
}

void InspectableWebContentsViewViews::SetContentsResizingStrategy(
    const DevToolsContentsResizingStrategy& strategy) {
  strategy_.CopyFrom(strategy);
  Layout();
}

void InspectableWebContentsViewViews::Layout() {
  if (!devtools_web_view_->visible()) {
    contents_web_view_->SetBoundsRect(GetContentsBounds());
    return;
  }

  gfx::Size container_size(width(), height());
  gfx::Rect new_devtools_bounds;
  gfx::Rect new_contents_bounds;
  ApplyDevToolsContentsResizingStrategy(strategy_, container_size,
      &new_devtools_bounds, &new_contents_bounds);

  // DevTools cares about the specific position, so we have to compensate RTL
  // layout here.
  new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
  new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));

  devtools_web_view_->SetBoundsRect(new_devtools_bounds);
  contents_web_view_->SetBoundsRect(new_contents_bounds);
}

}  // namespace brightray
<commit_msg>Fix devtools window can not minimize<commit_after>#include "browser/views/inspectable_web_contents_view_views.h"

#include "browser/inspectable_web_contents_delegate.h"
#include "browser/inspectable_web_contents_impl.h"

#include "base/strings/utf_string_conversions.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"

namespace brightray {

namespace {

class DevToolsWindowDelegate : public views::ClientView,
                               public views::WidgetDelegate {
 public:
  DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
                         views::View* view,
                         views::Widget* widget)
      : views::ClientView(widget, view),
        shell_(shell),
        view_(view),
        widget_(widget),
        title_(base::ASCIIToUTF16("Developer Tools")) {
    // A WidgetDelegate should be deleted on DeleteDelegate.
    set_owned_by_client();

    InspectableWebContentsDelegate* delegate = shell->inspectable_web_contents()->GetDelegate();
    if (delegate)
      icon_ = delegate->GetDevToolsWindowIcon();
  }
  virtual ~DevToolsWindowDelegate() {}

  // views::WidgetDelegate:
  void DeleteDelegate() override { delete this; }
  views::View* GetInitiallyFocusedView() override { return view_; }
  bool CanResize() const override { return true; }
  bool CanMaximize() const override { return true; }
  bool CanMinimize() const override { return true; }
  base::string16 GetWindowTitle() const override { return title_; }
  gfx::ImageSkia GetWindowAppIcon() override { return GetWindowIcon(); }
  gfx::ImageSkia GetWindowIcon() override { return icon_; }
  views::Widget* GetWidget() override { return widget_; }
  const views::Widget* GetWidget() const override { return widget_; }
  views::View* GetContentsView() override { return view_; }
  views::ClientView* CreateClientView(views::Widget* widget) { return this; }

  // views::ClientView:
  bool CanClose() override {
    shell_->inspectable_web_contents()->CloseDevTools();
    return false;
  }

 private:
  InspectableWebContentsViewViews* shell_;
  views::View* view_;
  views::Widget* widget_;
  base::string16 title_;
  gfx::ImageSkia icon_;

  DISALLOW_COPY_AND_ASSIGN(DevToolsWindowDelegate);
};

}  // namespace

InspectableWebContentsView* CreateInspectableContentsView(
    InspectableWebContentsImpl* inspectable_web_contents) {
  return new InspectableWebContentsViewViews(inspectable_web_contents);
}

InspectableWebContentsViewViews::InspectableWebContentsViewViews(
    InspectableWebContentsImpl* inspectable_web_contents)
    : inspectable_web_contents_(inspectable_web_contents),
      devtools_window_web_view_(NULL),
      contents_web_view_(new views::WebView(NULL)),
      devtools_web_view_(new views::WebView(NULL)),
      devtools_visible_(false) {
  set_owned_by_client();

  devtools_web_view_->SetVisible(false);
  contents_web_view_->SetWebContents(inspectable_web_contents_->GetWebContents());
  AddChildView(devtools_web_view_);
  AddChildView(contents_web_view_);
}

InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
  if (devtools_window_)
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
}

views::View* InspectableWebContentsViewViews::GetView() {
  return this;
}

views::View* InspectableWebContentsViewViews::GetWebView() {
  return contents_web_view_;
}

void InspectableWebContentsViewViews::ShowDevTools() {
  if (devtools_visible_)
    return;

  devtools_visible_ = true;
  if (devtools_window_) {
    devtools_window_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
    devtools_window_->SetBounds(inspectable_web_contents()->GetDevToolsBounds());
    devtools_window_->Show();
  } else {
    devtools_web_view_->SetVisible(true);
    devtools_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
    devtools_web_view_->RequestFocus();
    Layout();
  }
}

void InspectableWebContentsViewViews::CloseDevTools() {
  if (!devtools_visible_)
    return;

  devtools_visible_ = false;
  if (devtools_window_) {
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
    devtools_window_.reset();
    devtools_window_web_view_ = NULL;
  } else {
    devtools_web_view_->SetVisible(false);
    devtools_web_view_->SetWebContents(NULL);
    Layout();
  }
}

bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
  return devtools_visible_;
}

void InspectableWebContentsViewViews::SetIsDocked(bool docked) {
  CloseDevTools();

  if (!docked) {
    devtools_window_.reset(new views::Widget);
    devtools_window_web_view_ = new views::WebView(NULL);

    views::Widget::InitParams params;
    params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
    params.delegate = new DevToolsWindowDelegate(this,
                                                 devtools_window_web_view_,
                                                 devtools_window_.get());
    params.bounds = inspectable_web_contents()->GetDevToolsBounds();

#if defined(USE_X11)
    params.wm_role_name = "devtools";
    InspectableWebContentsDelegate* delegate = inspectable_web_contents()->GetDelegate();
    if (delegate)
      delegate->GetDevToolsWindowWMClass(&params.wm_class_name, &params.wm_class_class);
#endif

    devtools_window_->Init(params);
    devtools_window_->UpdateWindowIcon();
  }

  ShowDevTools();
}

void InspectableWebContentsViewViews::SetContentsResizingStrategy(
    const DevToolsContentsResizingStrategy& strategy) {
  strategy_.CopyFrom(strategy);
  Layout();
}

void InspectableWebContentsViewViews::Layout() {
  if (!devtools_web_view_->visible()) {
    contents_web_view_->SetBoundsRect(GetContentsBounds());
    return;
  }

  gfx::Size container_size(width(), height());
  gfx::Rect new_devtools_bounds;
  gfx::Rect new_contents_bounds;
  ApplyDevToolsContentsResizingStrategy(strategy_, container_size,
      &new_devtools_bounds, &new_contents_bounds);

  // DevTools cares about the specific position, so we have to compensate RTL
  // layout here.
  new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
  new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));

  devtools_web_view_->SetBoundsRect(new_devtools_bounds);
  contents_web_view_->SetBoundsRect(new_contents_bounds);
}

}  // namespace brightray
<|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 .
 */
#ifndef INCLUDED_CHART2_SOURCE_CONTROLLER_DIALOGS_TP_SERIESTOAXIS_HXX
#define INCLUDED_CHART2_SOURCE_CONTROLLER_DIALOGS_TP_SERIESTOAXIS_HXX

#include <sfx2/tabdlg.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/field.hxx>

namespace chart
{

class SchOptionTabPage : public SfxTabPage
{
public:
    SchOptionTabPage(vcl::Window* pParent, const SfxItemSet& rInAttrs);
    virtual ~SchOptionTabPage();
    virtual void dispose() SAL_OVERRIDE;

    static VclPtr<SfxTabPage> Create(vcl::Window* pParent, const SfxItemSet* rInAttrs);
    virtual bool FillItemSet(SfxItemSet* rOutAttrs) SAL_OVERRIDE;
    virtual void Reset(const SfxItemSet* rInAttrs) SAL_OVERRIDE;

    void Init( bool bProvidesSecondaryYAxis, bool bProvidesOverlapAndGapWidth, bool bProvidesBarConnectors );

private: //methods
    void AdaptControlPositionsAndVisibility();

private: //member
    VclPtr<VclFrame>    m_pGrpAxis;
    VclPtr<RadioButton> m_pRbtAxis1;
    VclPtr<RadioButton> m_pRbtAxis2;

    VclPtr<VclFrame>    m_pGrpBar;
    VclPtr<MetricField> m_pMTGap;
    VclPtr<MetricField> m_pMTOverlap;
    VclPtr<CheckBox>    m_pCBConnect;
    VclPtr<CheckBox>    m_pCBAxisSideBySide;

    VclPtr<VclGrid>     m_pGrpPlotOptions;
    VclPtr<VclGrid>     m_pGridPlotOptions;
    VclPtr<RadioButton> m_pRB_DontPaint;
    VclPtr<RadioButton> m_pRB_AssumeZero;
    VclPtr<RadioButton> m_pRB_ContinueLine;

    VclPtr<CheckBox>    m_pCBIncludeHiddenCells;

    DECL_LINK(EnableHdl, void * );

    sal_Int32   m_nAllSeriesAxisIndex;

    bool m_bProvidesSecondaryYAxis;
    bool m_bProvidesOverlapAndGapWidth;
    bool m_bProvidesBarConnectors;
};

} //namespace chart

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix regression from 1c4025babd7037a3292aa530c7d45ab8d6ef6dcb<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 .
 */
#ifndef INCLUDED_CHART2_SOURCE_CONTROLLER_DIALOGS_TP_SERIESTOAXIS_HXX
#define INCLUDED_CHART2_SOURCE_CONTROLLER_DIALOGS_TP_SERIESTOAXIS_HXX

#include <sfx2/tabdlg.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/field.hxx>

namespace chart
{

class SchOptionTabPage : public SfxTabPage
{
public:
    SchOptionTabPage(vcl::Window* pParent, const SfxItemSet& rInAttrs);
    virtual ~SchOptionTabPage();
    virtual void dispose() SAL_OVERRIDE;

    static VclPtr<SfxTabPage> Create(vcl::Window* pParent, const SfxItemSet* rInAttrs);
    virtual bool FillItemSet(SfxItemSet* rOutAttrs) SAL_OVERRIDE;
    virtual void Reset(const SfxItemSet* rInAttrs) SAL_OVERRIDE;

    void Init( bool bProvidesSecondaryYAxis, bool bProvidesOverlapAndGapWidth, bool bProvidesBarConnectors );

private: //methods
    void AdaptControlPositionsAndVisibility();

private: //member
    VclPtr<VclFrame>    m_pGrpAxis;
    VclPtr<RadioButton> m_pRbtAxis1;
    VclPtr<RadioButton> m_pRbtAxis2;

    VclPtr<VclFrame>    m_pGrpBar;
    VclPtr<MetricField> m_pMTGap;
    VclPtr<MetricField> m_pMTOverlap;
    VclPtr<CheckBox>    m_pCBConnect;
    VclPtr<CheckBox>    m_pCBAxisSideBySide;

    VclPtr<VclFrame>    m_pGrpPlotOptions;
    VclPtr<VclGrid>     m_pGridPlotOptions;
    VclPtr<RadioButton> m_pRB_DontPaint;
    VclPtr<RadioButton> m_pRB_AssumeZero;
    VclPtr<RadioButton> m_pRB_ContinueLine;

    VclPtr<CheckBox>    m_pCBIncludeHiddenCells;

    DECL_LINK(EnableHdl, void * );

    sal_Int32   m_nAllSeriesAxisIndex;

    bool m_bProvidesSecondaryYAxis;
    bool m_bProvidesOverlapAndGapWidth;
    bool m_bProvidesBarConnectors;
};

} //namespace chart

#endif

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


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

// This file implements a mock location provider and the factory functions for
// various ways of creating it.

#include "chrome/browser/geolocation/mock_location_provider.h"

#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/task.h"

MockLocationProvider* MockLocationProvider::instance_ = NULL;

MockLocationProvider::MockLocationProvider(MockLocationProvider** self_ref)
    : started_count_(0),
      self_ref_(self_ref) {
  CHECK(self_ref_);
  CHECK(*self_ref_ == NULL);
  *self_ref_ = this;
}

MockLocationProvider::~MockLocationProvider() {
  CHECK(*self_ref_ == this);
  *self_ref_ = NULL;
}

bool MockLocationProvider::StartProvider() {
  ++started_count_;
  return true;
}

void MockLocationProvider::GetPosition(Geoposition* position) {
  *position = position_;
}

void MockLocationProvider::OnPermissionGranted(const GURL& requesting_frame) {
  permission_granted_url_ = requesting_frame;
}

// Mock location provider that automatically calls back it's client when
// StartProvider is called.
class AutoMockLocationProvider : public MockLocationProvider {
 public:
  AutoMockLocationProvider(bool has_valid_location,
                           bool requires_permission_to_start)
      : MockLocationProvider(&instance_),
        ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)),
        requires_permission_to_start_(requires_permission_to_start) {
    if (has_valid_location) {
      position_.accuracy = 3;
      position_.latitude = 4.3;
      position_.longitude = -7.8;
      position_.timestamp = base::Time::FromDoubleT(4567.8);
    } else {
      position_.error_code = Geoposition::ERROR_CODE_POSITION_UNAVAILABLE;
    }
  }
  virtual bool StartProvider() {
    MockLocationProvider::StartProvider();
    if (!requires_permission_to_start_) {
      MessageLoop::current()->PostTask(
          FROM_HERE, task_factory_.NewRunnableMethod(
              &MockLocationProvider::UpdateListeners));
    }
    return true;
  }

  void OnPermissionGranted(const GURL& requesting_frame) {
    MockLocationProvider::OnPermissionGranted(requesting_frame);
    if (requires_permission_to_start_) {
      MessageLoop::current()->PostTask(
          FROM_HERE, task_factory_.NewRunnableMethod(
              &MockLocationProvider::UpdateListeners));
    }
  }

  ScopedRunnableMethodFactory<MockLocationProvider> task_factory_;
  const bool requires_permission_to_start_;
};

LocationProviderBase* NewMockLocationProvider() {
  return new MockLocationProvider(&MockLocationProvider::instance_);
}

LocationProviderBase* NewAutoSuccessMockLocationProvider() {
  return new AutoMockLocationProvider(true, false);
}

LocationProviderBase* NewAutoFailMockLocationProvider() {
  return new AutoMockLocationProvider(false, false);
}

LocationProviderBase* NewAutoSuccessMockNetworkLocationProvider() {
  return new AutoMockLocationProvider(true, true);
}
<commit_msg>Removes spurious JS callback triggered by MockLocationProvider::OnPermissionGranted. (this generated an extra alert, which is closed when test finishes on gtk/win, but hangs on mac).<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file implements a mock location provider and the factory functions for
// various ways of creating it.

#include "chrome/browser/geolocation/mock_location_provider.h"

#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/task.h"

MockLocationProvider* MockLocationProvider::instance_ = NULL;

MockLocationProvider::MockLocationProvider(MockLocationProvider** self_ref)
    : started_count_(0),
      self_ref_(self_ref) {
  CHECK(self_ref_);
  CHECK(*self_ref_ == NULL);
  *self_ref_ = this;
}

MockLocationProvider::~MockLocationProvider() {
  CHECK(*self_ref_ == this);
  *self_ref_ = NULL;
}

bool MockLocationProvider::StartProvider() {
  ++started_count_;
  return true;
}

void MockLocationProvider::GetPosition(Geoposition* position) {
  *position = position_;
}

void MockLocationProvider::OnPermissionGranted(const GURL& requesting_frame) {
  permission_granted_url_ = requesting_frame;
}

// Mock location provider that automatically calls back it's client at most
// once, when StartProvider or OnPermissionGranted is called. Use
// |requires_permission_to_start| to select which event triggers the callback.
class AutoMockLocationProvider : public MockLocationProvider {
 public:
  AutoMockLocationProvider(bool has_valid_location,
                           bool requires_permission_to_start)
      : MockLocationProvider(&instance_),
        ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)),
        requires_permission_to_start_(requires_permission_to_start),
        listeners_updated_(false) {
    if (has_valid_location) {
      position_.accuracy = 3;
      position_.latitude = 4.3;
      position_.longitude = -7.8;
      position_.timestamp = base::Time::FromDoubleT(4567.8);
    } else {
      position_.error_code = Geoposition::ERROR_CODE_POSITION_UNAVAILABLE;
    }
  }
  virtual bool StartProvider() {
    MockLocationProvider::StartProvider();
    if (!requires_permission_to_start_) {
      UpdateListenersIfNeeded();
    }
    return true;
  }

  void OnPermissionGranted(const GURL& requesting_frame) {
    MockLocationProvider::OnPermissionGranted(requesting_frame);
    if (requires_permission_to_start_) {
      UpdateListenersIfNeeded();
    }
  }

  void UpdateListenersIfNeeded() {
    if (!listeners_updated_) {
      listeners_updated_ = true;
      MessageLoop::current()->PostTask(
          FROM_HERE, task_factory_.NewRunnableMethod(
              &MockLocationProvider::UpdateListeners));
    }
  }

  ScopedRunnableMethodFactory<MockLocationProvider> task_factory_;
  const bool requires_permission_to_start_;
  bool listeners_updated_;
};

LocationProviderBase* NewMockLocationProvider() {
  return new MockLocationProvider(&MockLocationProvider::instance_);
}

LocationProviderBase* NewAutoSuccessMockLocationProvider() {
  return new AutoMockLocationProvider(true, false);
}

LocationProviderBase* NewAutoFailMockLocationProvider() {
  return new AutoMockLocationProvider(false, false);
}

LocationProviderBase* NewAutoSuccessMockNetworkLocationProvider() {
  return new AutoMockLocationProvider(true, true);
}
<|endoftext|>


<commit_before>#include <QCoreApplication>
#include <QTime>
#include <QDebug>
#include <iostream>

#include "residutil.h"
#include "strdef.h"
#include "testcase.h"
#include "msgout.h"

//using namespace std;

void test_all()
{

}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    g_messageVerbose = false;
    qInstallMessageHandler(myMessageOutput);
    qDebug() << "string resid testing...";

    if (argc > 1 && strcmp(argv[1],"-v")==0) {
        std::cout << "verbose mode on\n";
        g_messageVerbose = true;
    }

    test_cache();

    return 0;
}
<commit_msg>update resid, test initialization of QList<commit_after>#include <QCoreApplication>
#include <QList>
#include <QDebug>
#include <iostream>

#include "residutil.h"
#include "strdef.h"
#include "testcase.h"
#include "msgout.h"

//using namespace std;

QList<QString> namelist = {
    "alpha", "bravo", "charlie", "delta", "echo"
};

void test_list()
{
    foreach (const QString &item, namelist) {
        qDebug() << item;
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // default to on
    g_messageVerbose = true;
    qInstallMessageHandler(myMessageOutput);
    qDebug() << "string resid testing...";

    if (argc > 1 && strcmp(argv[1],"-v")==0) {
        std::cout << "verbose mode on\n";
        g_messageVerbose = true;
    }

    //test_cache();
    test_list();

    return 0;
}
<|endoftext|>


<commit_before>#include "src/tmc/locationdb.h"

#include "config.h"
#ifdef ENABLE_TMC

#include <climits>
#include <deque>
#include <fstream>
#include <sstream>
#include <string>
#include <utility>

#include "iconvpp/iconv.hpp"
#include <json/json.h>

#include "src/tmc/event_list.h"
#include "src/util.h"

namespace redsea {

namespace tmc {

namespace {

std::string utf8(std::string input, iconvpp::converter* conv) {
  std::string converted;
  conv->convert(input, converted);
  return converted;
}

}  // namespace

LocationDatabase loadLocationDatabase(std::string directory) {
  LocationDatabase locdb;
  std::string encoding("UTF-8");

  for (std::vector<std::string> fields :
       readCSV(directory + "/README.DAT", ';')) {
    try {
      encoding = fields.at(4);
    } catch (const std::exception& e) {
      continue;
    }
  }

  // Misspelled encodings in the wild
  if (encoding.compare("ISO 8859-1") == 0)
    encoding = "ISO-8859-1";

  iconvpp::converter conv("UTF-8", encoding);

  for (CSVRow row : readCSVWithTitles(directory + "/NAMES.DAT", ';')) {
    try {
      int nid = std::stoi(row.at("NID"));
      locdb.names[nid] = utf8(row.at("NAME"), &conv);
    } catch (const std::exception& e) {
      continue;
    }
  }

  for (CSVRow row : readCSVWithTitles(directory + "/ROADS.DAT", ';')) {
    try {
      Road road;
      road.lcd = std::stoi(row.at("LCD"));
      road.road_number = row.at("ROADNUMBER");
      int rnid = 0;
      if (!row.at("RNID").empty())
        rnid = std::stoi(row.at("RNID"));
      if (locdb.names.count(rnid) > 0)
        road.name = locdb.names[rnid];
      locdb.roads[road.lcd] = road;
    } catch (const std::exception& e) {
      continue;
    }
  }

  for (CSVRow row : readCSVWithTitles(directory + "/SEGMENTS.DAT", ';')) {
    try {
      Segment seg;
      seg.lcd = std::stoi(row.at("LCD"));
      seg.roa_lcd = std::stoi(row.at("ROA_LCD"));
      locdb.segments[seg.lcd] = seg;
    } catch (const std::exception& e) {
      continue;
    }
  }

  for (CSVRow row : readCSVWithTitles(directory + "/POINTS.DAT", ';')) {
    try {
      locdb.ltn = std::stoi(row.at("TABCD"));
      Point point;
      point.lcd = std::stoi(row.at("LCD"));
      int n1id = 0;
      if (!row.at("N1ID").empty())
        std::stoi(row.at("N1ID"));
      if (locdb.names.count(n1id) > 0)
        point.name1 = locdb.names[n1id];
      if (!row.at("XCOORD").empty())
        point.lon = std::stoi(row.at("XCOORD")) * 1e-5f;
      if (!row.at("YCOORD").empty())
        point.lat = std::stoi(row.at("YCOORD")) * 1e-5f;
      if (!row.at("ROA_LCD").empty())
        point.roa_lcd = std::stoi(row.at("ROA_LCD"));
      if (!row.at("SEG_LCD").empty())
        point.seg_lcd = std::stoi(row.at("SEG_LCD"));

      int rnid = 0;
      if (!row.at("RNID").empty())
        std::stoi(row.at("RNID"));
      if (locdb.names.count(rnid) > 0)
        point.road_name = locdb.names[rnid];

      if (point.roa_lcd == 0 && locdb.segments.count(point.seg_lcd) > 0) {
        point.roa_lcd = locdb.segments.at(point.seg_lcd).roa_lcd;
        point.road_name = locdb.roads.at(point.roa_lcd).name;
        point.road_name = locdb.names[rnid];
      }

      locdb.points[point.lcd] = point;
    } catch (const std::exception& e) {
      continue;
    }
  }

  for (CSVRow row : readCSVWithTitles(directory + "/POFFSETS.DAT", ';')) {
    try {
      int lcd = std::stoi(row.at("LCD"));
      int neg = std::stoi(row.at("NEG_OFF_LCD"));
      int pos = std::stoi(row.at("POS_OFF_LCD"));
      if (locdb.points.count(lcd) > 0) {
        locdb.points[lcd].neg_off = neg;
        locdb.points[lcd].pos_off = pos;
      }
    } catch (const std::exception& e) {
      continue;
    }
  }

  printf("{\"location_table_info\":{\"ltn\":%d,\"num_points\":%ld,"
         "\"num_roads\":%ld,\"num_names\":%ld}}\n", locdb.ltn,
         locdb.points.size(), locdb.roads.size(), locdb.names.size());

  return locdb;
}

}  // namespace tmc
}  // namespace redsea

#endif  // ENABLE_TMC
<commit_msg>replace misspelled encodings<commit_after>#include "src/tmc/locationdb.h"

#include "config.h"
#ifdef ENABLE_TMC

#include <climits>
#include <deque>
#include <fstream>
#include <regex>
#include <sstream>
#include <string>
#include <utility>

#include "iconvpp/iconv.hpp"
#include <json/json.h>

#include "src/tmc/event_list.h"
#include "src/util.h"

namespace redsea {

namespace tmc {

namespace {

std::string utf8(std::string input, iconvpp::converter* conv) {
  std::string converted;
  conv->convert(input, converted);
  return converted;
}

}  // namespace

LocationDatabase loadLocationDatabase(std::string directory) {
  LocationDatabase locdb;
  std::string encoding("UTF-8");

  for (std::vector<std::string> fields :
       readCSV(directory + "/README.DAT", ';')) {
    try {
      encoding = fields.at(4);
    } catch (const std::exception& e) {
      continue;
    }
  }

  // Misspelled encodings in the wild (TODO a better way to do this)
  if (std::regex_match(encoding, std::regex("^ISO.8859-1\\b")))
    encoding = "ISO-8859-1";
  if (std::regex_match(encoding, std::regex("^ISO.8859-15\\b")))
    encoding = "ISO-8859-15";

  iconvpp::converter conv("UTF-8", encoding);

  for (CSVRow row : readCSVWithTitles(directory + "/NAMES.DAT", ';')) {
    try {
      int nid = std::stoi(row.at("NID"));
      locdb.names[nid] = utf8(row.at("NAME"), &conv);
    } catch (const std::exception& e) {
      continue;
    }
  }

  for (CSVRow row : readCSVWithTitles(directory + "/ROADS.DAT", ';')) {
    try {
      Road road;
      road.lcd = std::stoi(row.at("LCD"));
      road.road_number = row.at("ROADNUMBER");
      int rnid = 0;
      if (!row.at("RNID").empty())
        rnid = std::stoi(row.at("RNID"));
      if (locdb.names.count(rnid) > 0)
        road.name = locdb.names[rnid];
      locdb.roads[road.lcd] = road;
    } catch (const std::exception& e) {
      continue;
    }
  }

  for (CSVRow row : readCSVWithTitles(directory + "/SEGMENTS.DAT", ';')) {
    try {
      Segment seg;
      seg.lcd = std::stoi(row.at("LCD"));
      seg.roa_lcd = std::stoi(row.at("ROA_LCD"));
      locdb.segments[seg.lcd] = seg;
    } catch (const std::exception& e) {
      continue;
    }
  }

  for (CSVRow row : readCSVWithTitles(directory + "/POINTS.DAT", ';')) {
    try {
      locdb.ltn = std::stoi(row.at("TABCD"));
      Point point;
      point.lcd = std::stoi(row.at("LCD"));
      int n1id = 0;
      if (!row.at("N1ID").empty())
        std::stoi(row.at("N1ID"));
      if (locdb.names.count(n1id) > 0)
        point.name1 = locdb.names[n1id];
      if (!row.at("XCOORD").empty())
        point.lon = std::stoi(row.at("XCOORD")) * 1e-5f;
      if (!row.at("YCOORD").empty())
        point.lat = std::stoi(row.at("YCOORD")) * 1e-5f;
      if (!row.at("ROA_LCD").empty())
        point.roa_lcd = std::stoi(row.at("ROA_LCD"));
      if (!row.at("SEG_LCD").empty())
        point.seg_lcd = std::stoi(row.at("SEG_LCD"));

      int rnid = 0;
      if (!row.at("RNID").empty())
        std::stoi(row.at("RNID"));
      if (locdb.names.count(rnid) > 0)
        point.road_name = locdb.names[rnid];

      if (point.roa_lcd == 0 && locdb.segments.count(point.seg_lcd) > 0) {
        point.roa_lcd = locdb.segments.at(point.seg_lcd).roa_lcd;
        point.road_name = locdb.roads.at(point.roa_lcd).name;
        point.road_name = locdb.names[rnid];
      }

      locdb.points[point.lcd] = point;
    } catch (const std::exception& e) {
      continue;
    }
  }

  for (CSVRow row : readCSVWithTitles(directory + "/POFFSETS.DAT", ';')) {
    try {
      int lcd = std::stoi(row.at("LCD"));
      int neg = std::stoi(row.at("NEG_OFF_LCD"));
      int pos = std::stoi(row.at("POS_OFF_LCD"));
      if (locdb.points.count(lcd) > 0) {
        locdb.points[lcd].neg_off = neg;
        locdb.points[lcd].pos_off = pos;
      }
    } catch (const std::exception& e) {
      continue;
    }
  }

  printf("{\"location_table_info\":{\"ltn\":%d,\"num_points\":%ld,"
         "\"num_roads\":%ld,\"num_names\":%ld}}\n", locdb.ltn,
         locdb.points.size(), locdb.roads.size(), locdb.names.size());

  return locdb;
}

}  // namespace tmc
}  // namespace redsea

#endif  // ENABLE_TMC
<|endoftext|>


<commit_before>#ifndef RINGBUFFER_H
#define RINGBUFFER_H

#include <cassert>

#include <boost/circular_buffer.hpp>
#include "contrib/pa_ringbuffer.h"
#include "errors.hpp"

/**
 * Abstraction over a ring buffer.
 *
 * This generic abstract class represents a general concept of a ring buffer
 * for samples.  It can be implemented, for example, by adapters over the
 * PortAudio or Boost ring buffers.
 *
 * Note that all quantities are represented in terms of sample counts, not
 * the underlying representation RepT.  Implementations should ensure that they
 * implement the virtual methods of this class in terms of the former and not
 * the latter.
 */
template <typename RepT, typename SampleCountT>
class RingBuffer {
public:
	/**
	 * The current write capacity.
	 *
	 * @return The number of samples this ring buffer has space to store.
	 */
	virtual SampleCountT WriteCapacity() const = 0;

	/**
	 * The current read capacity.
	 *
	 * @return The number of samples available in this ring buffer.
	 */
	virtual SampleCountT ReadCapacity() const = 0;

	/**
	 * Writes samples from an array into the ring buffer.
	 *
	 * To write one sample, pass a count of 1 and take a pointer to the
	 * sample variable.
	 *
	 * Note that start pointer is not constant.  This is because the
	 * underlying implementation of the ring buffer might not guarantee
	 * that the array is left untouched.
	 *
	 * @param start The start of the array buffer from which we write
	 *              samples.  Must not be nullptr.
	 * @param count The number of samples to write.  This must not exceed
	 *              the minimum of WriteCapacity() and the length of the
	 *              array.
	 *
	 * @return The number of samples written, which should not exceed count.
	 */
	virtual SampleCountT Write(RepT *start, SampleCountT count) = 0;

	/**
	 * Reads samples from the ring buffer into an array.
	 *
	 * To read one sample, pass a count of 1 and take a pointer to the
	 * sample variable.
	 *
	 * @param start The start of the array buffer to which we write samples.
	 *              Must not be nullptr.
	 * @param count The number of samples to read.  This must not exceed the
	 *              minimum of ReadCapacity() and the length of the array.
	 *
	 * @return The number of samples read, which should not exceed count.
	 */
	virtual SampleCountT Read(RepT *start, SampleCountT count) = 0;

	/**
	 * Empties the ring buffer.
	 */
	virtual void Flush() = 0;
};

/**
 * Implementation of RingBuffer using the Boost circular buffer.
 *
 * This is currently experimental and has known audio glitches when used.
 * Here be undiscovered bugs.
 */
template <typename T1, typename T2, int P>
class BoostRingBuffer : public RingBuffer<T1, T2> {
public:
	BoostRingBuffer(int size = sizeof(T1))
	{
		this->rb = new boost::circular_buffer<char>((1 << P) * size);
		this->size = size;
	}

	~BoostRingBuffer()
	{
		assert(this->rb != nullptr);
		delete this->rb;
	}

	T2 WriteCapacity() const
	{
		return static_cast<T2>(this->rb->reserve() / this->size);
	}

	T2 ReadCapacity() const
	{
		return static_cast<T2>(this->rb->size() / this->size);
	}

	T2 Write(T1 *start, T2 count)
	{
		T2 i;

		for (i = 0; i < count * this->size; i++) {
			this->rb->push_back(start[i]);
		}

		return (i + 1) / this->size;
	}

	T2 Read(T1 *start, T2 count)
	{
		T2 i;

		for (i = 0; i < count * this->size; i++) {
			start[i] = this->rb->front();
			this->rb->pop_front();
		}

		return (i + 1) / this->size;
	}

	void Flush()
	{
		this->rb->clear();
	}

private:
	boost::circular_buffer<char> *rb; ///< The internal Boost ring buffer.
	int size;                         ///< The size of one sample, in bytes.
};

/**
 * Implementation of RingBuffer using the PortAudio C ring buffer.
 *
 * This is stable and performs well, but, as it is C code, necessitates some
 * hoop jumping to integrate and could do with being replaced with a native
 * solution.
 *
 * The PortAudio ring buffer is provided in the contrib/ directory.
 */
template <typename T1, typename T2, int P>
class PaRingBuffer : public RingBuffer<T1, T2> {
public:
	/**
	 * Constructs a PaRingBuffer.
	 * @param size  The size of one element in the ring buffer.
	 */
	PaRingBuffer(int size = sizeof(T1))
	{
		this->rb = new PaUtilRingBuffer;
		this->buffer = new char[(1 << P) * size];

		if (PaUtil_InitializeRingBuffer(
		                    this->rb, size,
		                    static_cast<ring_buffer_size_t>(1 << P),
		                    this->buffer) != 0) {
			throw Error(ErrorCode::INTERNAL_ERROR,
			            "ringbuf failed to init");
		}
	}

	~PaRingBuffer()
	{
		assert(this->rb != nullptr);
		delete this->rb;

		assert(this->buffer != nullptr);
		delete[] this->buffer;
	}

	T2 WriteCapacity() const
	{
		return static_cast<T2>(
		                PaUtil_GetRingBufferWriteAvailable(this->rb));
	}

	T2 ReadCapacity() const
	{
		return static_cast<T2>(
		                PaUtil_GetRingBufferReadAvailable(this->rb));
	}

	T2 Write(T1 *start, T2 count)
	{
		return static_cast<T2>(PaUtil_WriteRingBuffer(
		                this->rb, start,
		                static_cast<ring_buffer_size_t>(count)));
	}

	T2 Read(T1 *start, T2 count)
	{
		return static_cast<T2>(PaUtil_ReadRingBuffer(
		                this->rb, start,
		                static_cast<ring_buffer_size_t>(count)));
	}

	void Flush()
	{
		PaUtil_FlushRingBuffer(this->rb);
	}

private:
	char *buffer;         ///< The array used by the ringbuffer.
	PaUtilRingBuffer *rb; ///< The internal PortAudio ringbuffer.
};

#endif // RINGBUFFER_H
<commit_msg>Factor out CountCast.<commit_after>#ifndef RINGBUFFER_H
#define RINGBUFFER_H

#include <cassert>

#include <boost/circular_buffer.hpp>
#include "contrib/pa_ringbuffer.h"
#include "errors.hpp"

/**
 * Abstraction over a ring buffer.
 *
 * This generic abstract class represents a general concept of a ring buffer
 * for samples.  It can be implemented, for example, by adapters over the
 * PortAudio or Boost ring buffers.
 *
 * Note that all quantities are represented in terms of sample counts, not
 * the underlying representation RepT.  Implementations should ensure that they
 * implement the virtual methods of this class in terms of the former and not
 * the latter.
 */
template <typename RepT, typename SampleCountT>
class RingBuffer {
public:
	/**
	 * The current write capacity.
	 *
	 * @return The number of samples this ring buffer has space to store.
	 */
	virtual SampleCountT WriteCapacity() const = 0;

	/**
	 * The current read capacity.
	 *
	 * @return The number of samples available in this ring buffer.
	 */
	virtual SampleCountT ReadCapacity() const = 0;

	/**
	 * Writes samples from an array into the ring buffer.
	 *
	 * To write one sample, pass a count of 1 and take a pointer to the
	 * sample variable.
	 *
	 * Note that start pointer is not constant.  This is because the
	 * underlying implementation of the ring buffer might not guarantee
	 * that the array is left untouched.
	 *
	 * @param start The start of the array buffer from which we write
	 *              samples.  Must not be nullptr.
	 * @param count The number of samples to write.  This must not exceed
	 *              the minimum of WriteCapacity() and the length of the
	 *              array.
	 *
	 * @return The number of samples written, which should not exceed count.
	 */
	virtual SampleCountT Write(RepT *start, SampleCountT count) = 0;

	/**
	 * Reads samples from the ring buffer into an array.
	 *
	 * To read one sample, pass a count of 1 and take a pointer to the
	 * sample variable.
	 *
	 * @param start The start of the array buffer to which we write samples.
	 *              Must not be nullptr.
	 * @param count The number of samples to read.  This must not exceed the
	 *              minimum of ReadCapacity() and the length of the array.
	 *
	 * @return The number of samples read, which should not exceed count.
	 */
	virtual SampleCountT Read(RepT *start, SampleCountT count) = 0;

	/**
	 * Empties the ring buffer.
	 */
	virtual void Flush() = 0;
};

/**
 * Implementation of RingBuffer using the Boost circular buffer.
 *
 * This is currently experimental and has known audio glitches when used.
 * Here be undiscovered bugs.
 */
template <typename T1, typename T2, int P>
class BoostRingBuffer : public RingBuffer<T1, T2> {
public:
	BoostRingBuffer(int size = sizeof(T1))
	{
		this->rb = new boost::circular_buffer<char>((1 << P) * size);
		this->size = size;
	}

	~BoostRingBuffer()
	{
		assert(this->rb != nullptr);
		delete this->rb;
	}

	T2 WriteCapacity() const
	{
		return static_cast<T2>(this->rb->reserve() / this->size);
	}

	T2 ReadCapacity() const
	{
		return static_cast<T2>(this->rb->size() / this->size);
	}

	T2 Write(T1 *start, T2 count)
	{
		T2 i;

		for (i = 0; i < count * this->size; i++) {
			this->rb->push_back(start[i]);
		}

		return (i + 1) / this->size;
	}

	T2 Read(T1 *start, T2 count)
	{
		T2 i;

		for (i = 0; i < count * this->size; i++) {
			start[i] = this->rb->front();
			this->rb->pop_front();
		}

		return (i + 1) / this->size;
	}

	void Flush()
	{
		this->rb->clear();
	}

private:
	boost::circular_buffer<char> *rb; ///< The internal Boost ring buffer.
	int size;                         ///< The size of one sample, in bytes.
};

/**
 * Implementation of RingBuffer using the PortAudio C ring buffer.
 *
 * This is stable and performs well, but, as it is C code, necessitates some
 * hoop jumping to integrate and could do with being replaced with a native
 * solution.
 *
 * The PortAudio ring buffer is provided in the contrib/ directory.
 */
template <typename T1, typename T2, int P>
class PaRingBuffer : public RingBuffer<T1, T2> {
public:
	/**
	 * Constructs a PaRingBuffer.
	 * @param size  The size of one element in the ring buffer.
	 */
	PaRingBuffer(int size = sizeof(T1))
	{
		this->rb = new PaUtilRingBuffer;
		this->buffer = new char[(1 << P) * size];

		if (PaUtil_InitializeRingBuffer(
		                    this->rb, size,
		                    static_cast<ring_buffer_size_t>(1 << P),
		                    this->buffer) != 0) {
			throw Error(ErrorCode::INTERNAL_ERROR,
			            "ringbuf failed to init");
		}
	}

	~PaRingBuffer()
	{
		assert(this->rb != nullptr);
		delete this->rb;

		assert(this->buffer != nullptr);
		delete[] this->buffer;
	}

	T2 WriteCapacity() const
	{
		return CountCast(PaUtil_GetRingBufferWriteAvailable(this->rb));
	}

	T2 ReadCapacity() const
	{
		return CountCast(PaUtil_GetRingBufferReadAvailable(this->rb));
	}

	T2 Write(T1 *start, T2 count)
	{
		return CountCast(PaUtil_WriteRingBuffer(
		                this->rb, start,
		                static_cast<ring_buffer_size_t>(count)));
	}

	T2 Read(T1 *start, T2 count)
	{
		return CountCast(PaUtil_ReadRingBuffer(
		                this->rb, start,
		                static_cast<ring_buffer_size_t>(count)));
	}

	void Flush()
	{
		PaUtil_FlushRingBuffer(this->rb);
	}

private:
	char *buffer;         ///< The array used by the ringbuffer.
	PaUtilRingBuffer *rb; ///< The internal PortAudio ringbuffer.

	/**
	 * Converts a ring buffer size into an external size.
	 * @param count  The size/count in PortAudio form.
	 * @return       The size/count after casting to T2.
	 */
	T2 CountCast(ring_buffer_size_t count) const
	{
		return static_cast<T2>(count);
	}
};

#endif // RINGBUFFER_H
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@gmail.com>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"

template<int OtherSize> struct symm_extra {
  template<typename M1, typename M2, typename Scalar>
  static void run(M1& m1, M1& m2, M2& rhs2, M2& rhs22, M2& rhs23, Scalar s1, Scalar s2)
  {
    m2 = m1.template triangularView<Lower>();
    VERIFY_IS_APPROX(rhs22 = (rhs2) * (m2).template selfadjointView<Lower>(),
                    rhs23 = (rhs2) * (m1));
    VERIFY_IS_APPROX(rhs22 = (s2*rhs2) * (s1*m2).template selfadjointView<Lower>(),
                    rhs23 = (s2*rhs2) * (s1*m1));
  }
};

template<> struct symm_extra<1> {
  template<typename M1, typename M2, typename Scalar>
  static void run(M1&, M1&, M2&, M2&, M2&, Scalar, Scalar) {}
};

template<typename Scalar, int Size, int OtherSize> void symm(int size = Size, int othersize = OtherSize)
{
  typedef typename NumTraits<Scalar>::Real RealScalar;

  typedef Matrix<Scalar, Size, Size> MatrixType;
  typedef Matrix<Scalar, Size, OtherSize> Rhs1;
  typedef Matrix<Scalar, OtherSize, Size> Rhs2;
  enum { order = OtherSize==1 ? 0 : RowMajor };
  typedef Matrix<Scalar, Size, OtherSize,order> Rhs3;
  typedef MatrixType::Index Index;

  Index rows = size;
  Index cols = size;

  MatrixType m1 = MatrixType::Random(rows, cols),
             m2 = MatrixType::Random(rows, cols), m3;

  m1 = (m1+m1.adjoint()).eval();

  Rhs1 rhs1 = Rhs1::Random(cols, othersize), rhs12(cols, othersize), rhs13(cols, othersize);
  Rhs2 rhs2 = Rhs2::Random(othersize, rows), rhs22(othersize, rows), rhs23(othersize, rows);
  Rhs3 rhs3 = Rhs3::Random(cols, othersize), rhs32(cols, othersize), rhs33(cols, othersize);

  Scalar s1 = ei_random<Scalar>(),
         s2 = ei_random<Scalar>();

  m2 = m1.template triangularView<Lower>();
  m3 = m2.template selfadjointView<Lower>();
  VERIFY_IS_EQUAL(m1, m3);
  VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Lower>() * (s2*rhs1),
                   rhs13 = (s1*m1) * (s2*rhs1));

  m2 = m1.template triangularView<Upper>(); rhs12.setRandom(); rhs13 = rhs12;
  m3 = m2.template selfadjointView<Upper>();
  VERIFY_IS_EQUAL(m1, m3);
  VERIFY_IS_APPROX(rhs12 += (s1*m2).template selfadjointView<Upper>() * (s2*rhs1),
                   rhs13 += (s1*m1) * (s2*rhs1));

  m2 = m1.template triangularView<Lower>();
  VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Lower>() * (s2*rhs2.adjoint()),
                   rhs13 = (s1*m1) * (s2*rhs2.adjoint()));

  m2 = m1.template triangularView<Upper>();
  VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Upper>() * (s2*rhs2.adjoint()),
                   rhs13 = (s1*m1) * (s2*rhs2.adjoint()));

  m2 = m1.template triangularView<Upper>();
  VERIFY_IS_APPROX(rhs12 = (s1*m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs2.adjoint()),
                   rhs13 = (s1*m1.adjoint()) * (s2*rhs2.adjoint()));

  // test row major = <...>
  m2 = m1.template triangularView<Lower>(); rhs12.setRandom(); rhs13 = rhs12;
  VERIFY_IS_APPROX(rhs12 -= (s1*m2).template selfadjointView<Lower>() * (s2*rhs3),
                   rhs13 -= (s1*m1) * (s2 * rhs3));

  m2 = m1.template triangularView<Upper>();
  VERIFY_IS_APPROX(rhs12 = (s1*m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs3).conjugate(),
                   rhs13 = (s1*m1.adjoint()) * (s2*rhs3).conjugate());

  m2 = m1.template triangularView<Upper>(); rhs13 = rhs12;
  VERIFY_IS_APPROX(rhs12.noalias() += s1 * ((m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs3).conjugate()),
                   rhs13 += (s1*m1.adjoint()) * (s2*rhs3).conjugate());

  // test matrix * selfadjoint
  symm_extra<OtherSize>::run(m1,m2,rhs2,rhs22,rhs23,s1,s2);

}

void test_product_symm()
{
  for(int i = 0; i < g_repeat ; i++)
  {
    CALL_SUBTEST_1(( symm<float,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));
    CALL_SUBTEST_2(( symm<double,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));
    CALL_SUBTEST_3(( symm<std::complex<double>,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));

    CALL_SUBTEST_4(( symm<float,Dynamic,1>(ei_random<int>(10,320)) ));
    CALL_SUBTEST_5(( symm<double,Dynamic,1>(ei_random<int>(10,320)) ));
    CALL_SUBTEST_6(( symm<std::complex<double>,Dynamic,1>(ei_random<int>(10,320)) ));
  }
}
<commit_msg>add missing typename<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@gmail.com>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"

template<int OtherSize> struct symm_extra {
  template<typename M1, typename M2, typename Scalar>
  static void run(M1& m1, M1& m2, M2& rhs2, M2& rhs22, M2& rhs23, Scalar s1, Scalar s2)
  {
    m2 = m1.template triangularView<Lower>();
    VERIFY_IS_APPROX(rhs22 = (rhs2) * (m2).template selfadjointView<Lower>(),
                    rhs23 = (rhs2) * (m1));
    VERIFY_IS_APPROX(rhs22 = (s2*rhs2) * (s1*m2).template selfadjointView<Lower>(),
                    rhs23 = (s2*rhs2) * (s1*m1));
  }
};

template<> struct symm_extra<1> {
  template<typename M1, typename M2, typename Scalar>
  static void run(M1&, M1&, M2&, M2&, M2&, Scalar, Scalar) {}
};

template<typename Scalar, int Size, int OtherSize> void symm(int size = Size, int othersize = OtherSize)
{
  typedef typename NumTraits<Scalar>::Real RealScalar;

  typedef Matrix<Scalar, Size, Size> MatrixType;
  typedef Matrix<Scalar, Size, OtherSize> Rhs1;
  typedef Matrix<Scalar, OtherSize, Size> Rhs2;
  enum { order = OtherSize==1 ? 0 : RowMajor };
  typedef Matrix<Scalar, Size, OtherSize,order> Rhs3;
  typedef typename MatrixType::Index Index;

  Index rows = size;
  Index cols = size;

  MatrixType m1 = MatrixType::Random(rows, cols),
             m2 = MatrixType::Random(rows, cols), m3;

  m1 = (m1+m1.adjoint()).eval();

  Rhs1 rhs1 = Rhs1::Random(cols, othersize), rhs12(cols, othersize), rhs13(cols, othersize);
  Rhs2 rhs2 = Rhs2::Random(othersize, rows), rhs22(othersize, rows), rhs23(othersize, rows);
  Rhs3 rhs3 = Rhs3::Random(cols, othersize), rhs32(cols, othersize), rhs33(cols, othersize);

  Scalar s1 = ei_random<Scalar>(),
         s2 = ei_random<Scalar>();

  m2 = m1.template triangularView<Lower>();
  m3 = m2.template selfadjointView<Lower>();
  VERIFY_IS_EQUAL(m1, m3);
  VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Lower>() * (s2*rhs1),
                   rhs13 = (s1*m1) * (s2*rhs1));

  m2 = m1.template triangularView<Upper>(); rhs12.setRandom(); rhs13 = rhs12;
  m3 = m2.template selfadjointView<Upper>();
  VERIFY_IS_EQUAL(m1, m3);
  VERIFY_IS_APPROX(rhs12 += (s1*m2).template selfadjointView<Upper>() * (s2*rhs1),
                   rhs13 += (s1*m1) * (s2*rhs1));

  m2 = m1.template triangularView<Lower>();
  VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Lower>() * (s2*rhs2.adjoint()),
                   rhs13 = (s1*m1) * (s2*rhs2.adjoint()));

  m2 = m1.template triangularView<Upper>();
  VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Upper>() * (s2*rhs2.adjoint()),
                   rhs13 = (s1*m1) * (s2*rhs2.adjoint()));

  m2 = m1.template triangularView<Upper>();
  VERIFY_IS_APPROX(rhs12 = (s1*m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs2.adjoint()),
                   rhs13 = (s1*m1.adjoint()) * (s2*rhs2.adjoint()));

  // test row major = <...>
  m2 = m1.template triangularView<Lower>(); rhs12.setRandom(); rhs13 = rhs12;
  VERIFY_IS_APPROX(rhs12 -= (s1*m2).template selfadjointView<Lower>() * (s2*rhs3),
                   rhs13 -= (s1*m1) * (s2 * rhs3));

  m2 = m1.template triangularView<Upper>();
  VERIFY_IS_APPROX(rhs12 = (s1*m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs3).conjugate(),
                   rhs13 = (s1*m1.adjoint()) * (s2*rhs3).conjugate());

  m2 = m1.template triangularView<Upper>(); rhs13 = rhs12;
  VERIFY_IS_APPROX(rhs12.noalias() += s1 * ((m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs3).conjugate()),
                   rhs13 += (s1*m1.adjoint()) * (s2*rhs3).conjugate());

  // test matrix * selfadjoint
  symm_extra<OtherSize>::run(m1,m2,rhs2,rhs22,rhs23,s1,s2);

}

void test_product_symm()
{
  for(int i = 0; i < g_repeat ; i++)
  {
    CALL_SUBTEST_1(( symm<float,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));
    CALL_SUBTEST_2(( symm<double,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));
    CALL_SUBTEST_3(( symm<std::complex<double>,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));

    CALL_SUBTEST_4(( symm<float,Dynamic,1>(ei_random<int>(10,320)) ));
    CALL_SUBTEST_5(( symm<double,Dynamic,1>(ei_random<int>(10,320)) ));
    CALL_SUBTEST_6(( symm<std::complex<double>,Dynamic,1>(ei_random<int>(10,320)) ));
  }
}
<|endoftext|>