<commit_before>/*************************************************************************
 *
 *  $RCSfile: interceptedinteraction.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: svesik $ $Date: 2004-04-21 12:34:38 $
 *
 *  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 _UCBHELPER_INTERCEPTEDINTERACTION_HXX_
#include <ucbhelper/interceptedinteraction.hxx>
#endif

//_______________________________________________
// includes

//_______________________________________________
// namespace

namespace ucbhelper{

namespace css = ::com::sun::star;

//_______________________________________________
// definitions

/*-----------------------------------------------
    17.03.2004 11:00
-----------------------------------------------*/
InterceptedInteraction::InterceptedInteraction()
{
}

/*-----------------------------------------------
    17.03.2004 14:55
-----------------------------------------------*/
void InterceptedInteraction::setInterceptedHandler(const css::uno::Reference< css::task::XInteractionHandler >& xInterceptedHandler)
{
    m_xInterceptedHandler = xInterceptedHandler;
}

/*-----------------------------------------------
    17.03.2004 14:55
-----------------------------------------------*/
void InterceptedInteraction::setInterceptions(const ::std::vector< InterceptedRequest >& lInterceptions)
{
    m_lInterceptions = lInterceptions;
}

/*-----------------------------------------------
    18.03.2004 10:10
-----------------------------------------------*/
InterceptedInteraction::EInterceptionState InterceptedInteraction::intercepted(const InterceptedRequest&                                                              rRequest   ,
                                                                               const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xOrgRequest)
{
    // default behaviour! see impl_interceptRequest() for further informations ...
    return E_NOT_INTERCEPTED;
}

/*-----------------------------------------------
    18.03.2004 09:46
-----------------------------------------------*/
css::uno::Reference< css::task::XInteractionContinuation > InterceptedInteraction::extractContinuation(const css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > >& lContinuations,
                                                                                const css::uno::Type&                                                                   aType         )
{
    const css::uno::Reference< css::task::XInteractionContinuation >* pContinuations = lContinuations.getConstArray();

    sal_Int32 c = lContinuations.getLength();
    sal_Int32 i = 0;

    for (i=0; i<c; ++i)
    {
        css::uno::Reference< css::uno::XInterface > xCheck(pContinuations[i], css::uno::UNO_QUERY);
        if (xCheck->queryInterface(aType).hasValue())
            return pContinuations[i];
    }

    return css::uno::Reference< css::task::XInteractionContinuation >();
}

/*-----------------------------------------------
    18.03.2004 10:03
-----------------------------------------------*/
void SAL_CALL InterceptedInteraction::handle(const css::uno::Reference< css::task::XInteractionRequest >& xRequest)
    throw(css::uno::RuntimeException)
{
    impl_handleDefault(xRequest);
}

/*-----------------------------------------------
    18.03.2004 10:02
-----------------------------------------------*/
void InterceptedInteraction::impl_handleDefault(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest)
{
    EInterceptionState eState = impl_interceptRequest(xRequest);

    switch(eState)
    {
        case E_NOT_INTERCEPTED:
        {
            // Non of the intercepted requests match to the given one.
            // => forward request to the internal wrapped handler - if there is one.
            if (m_xInterceptedHandler.is())
                m_xInterceptedHandler->handle(xRequest);
        }
        break;

        case E_NO_CONTINUATION_FOUND:
        {
            // Runtime error! The defined continuation could not be located
            // inside the set of available containuations of the incoming request.
            // Whats wrong - the interception list or the request?
            OSL_ENSURE(sal_False, "InterceptedInteraction::handle()\nCould intercept this interaction request - but cant locate the right continuation!");
        }
        break;

//      case E_INTERCEPTED:
    }
}

/*-----------------------------------------------
    18.03.2004 09:48
-----------------------------------------------*/
InterceptedInteraction::EInterceptionState InterceptedInteraction::impl_interceptRequest(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest)
{
    css::uno::Any                                                                    aRequest       = xRequest->getRequest();
    css::uno::Type                                                                   aRequestType   = aRequest.getValueType();
    css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > lContinuations = xRequest->getContinuations();

    // check against the list of static requests
    sal_Int32 nHandle = 0;
    ::std::vector< InterceptedRequest >::const_iterator pIt;
    for (  pIt  = m_lInterceptions.begin();
           pIt != m_lInterceptions.end()  ;
         ++pIt                            )
    {
        const InterceptedRequest& rInterception = *pIt;
        css::uno::Type aInterceptedType = rInterception.Request.getValueType();

        // check the request
        sal_Bool bMatch = sal_False;
        if (rInterception.MatchExact)
            bMatch = aInterceptedType.equals(aRequestType);
        else
            bMatch = aInterceptedType.isAssignableFrom(aRequestType); // dont change intercepted and request type here -> it will check the wrong direction!

        // intercepted ...
        // Call they might existing derived class, so they can handle that by its own.
        // If its not interested on that (may be its not overwritten and the default implementation
        // returns E_NOT_INTERCEPTED as default) -> break this loop and search for the right continuation.
        if (bMatch)
        {
            EInterceptionState eState = intercepted(rInterception, xRequest);
            if (eState == E_NOT_INTERCEPTED)
                break;
            return eState;
        }

        ++nHandle;
    }

    if (pIt != m_lInterceptions.end()) // => can be true only if bMatch=TRUE!
    {
        // match -> search required continuation
        const InterceptedRequest& rInterception = *pIt;
        css::uno::Reference< css::task::XInteractionContinuation > xContinuation = InterceptedInteraction::extractContinuation(lContinuations, rInterception.Continuation);
        if (xContinuation.is())
        {
            xContinuation->select();
            return E_INTERCEPTED;
        }

        // Can be reached only, if the request does not support the given continuation!
        // => RuntimeError!?
        return E_NO_CONTINUATION_FOUND;
    }

    return E_NOT_INTERCEPTED;
}

} // namespace ucbhelper
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.48); FILE MERGED 2005/09/05 13:13:52 rt 1.2.48.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: interceptedinteraction.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 16:34:47 $
 *
 *  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 _UCBHELPER_INTERCEPTEDINTERACTION_HXX_
#include <ucbhelper/interceptedinteraction.hxx>
#endif

//_______________________________________________
// includes

//_______________________________________________
// namespace

namespace ucbhelper{

namespace css = ::com::sun::star;

//_______________________________________________
// definitions

/*-----------------------------------------------
    17.03.2004 11:00
-----------------------------------------------*/
InterceptedInteraction::InterceptedInteraction()
{
}

/*-----------------------------------------------
    17.03.2004 14:55
-----------------------------------------------*/
void InterceptedInteraction::setInterceptedHandler(const css::uno::Reference< css::task::XInteractionHandler >& xInterceptedHandler)
{
    m_xInterceptedHandler = xInterceptedHandler;
}

/*-----------------------------------------------
    17.03.2004 14:55
-----------------------------------------------*/
void InterceptedInteraction::setInterceptions(const ::std::vector< InterceptedRequest >& lInterceptions)
{
    m_lInterceptions = lInterceptions;
}

/*-----------------------------------------------
    18.03.2004 10:10
-----------------------------------------------*/
InterceptedInteraction::EInterceptionState InterceptedInteraction::intercepted(const InterceptedRequest&                                                              rRequest   ,
                                                                               const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xOrgRequest)
{
    // default behaviour! see impl_interceptRequest() for further informations ...
    return E_NOT_INTERCEPTED;
}

/*-----------------------------------------------
    18.03.2004 09:46
-----------------------------------------------*/
css::uno::Reference< css::task::XInteractionContinuation > InterceptedInteraction::extractContinuation(const css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > >& lContinuations,
                                                                                const css::uno::Type&                                                                   aType         )
{
    const css::uno::Reference< css::task::XInteractionContinuation >* pContinuations = lContinuations.getConstArray();

    sal_Int32 c = lContinuations.getLength();
    sal_Int32 i = 0;

    for (i=0; i<c; ++i)
    {
        css::uno::Reference< css::uno::XInterface > xCheck(pContinuations[i], css::uno::UNO_QUERY);
        if (xCheck->queryInterface(aType).hasValue())
            return pContinuations[i];
    }

    return css::uno::Reference< css::task::XInteractionContinuation >();
}

/*-----------------------------------------------
    18.03.2004 10:03
-----------------------------------------------*/
void SAL_CALL InterceptedInteraction::handle(const css::uno::Reference< css::task::XInteractionRequest >& xRequest)
    throw(css::uno::RuntimeException)
{
    impl_handleDefault(xRequest);
}

/*-----------------------------------------------
    18.03.2004 10:02
-----------------------------------------------*/
void InterceptedInteraction::impl_handleDefault(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest)
{
    EInterceptionState eState = impl_interceptRequest(xRequest);

    switch(eState)
    {
        case E_NOT_INTERCEPTED:
        {
            // Non of the intercepted requests match to the given one.
            // => forward request to the internal wrapped handler - if there is one.
            if (m_xInterceptedHandler.is())
                m_xInterceptedHandler->handle(xRequest);
        }
        break;

        case E_NO_CONTINUATION_FOUND:
        {
            // Runtime error! The defined continuation could not be located
            // inside the set of available containuations of the incoming request.
            // Whats wrong - the interception list or the request?
            OSL_ENSURE(sal_False, "InterceptedInteraction::handle()\nCould intercept this interaction request - but cant locate the right continuation!");
        }
        break;

//      case E_INTERCEPTED:
    }
}

/*-----------------------------------------------
    18.03.2004 09:48
-----------------------------------------------*/
InterceptedInteraction::EInterceptionState InterceptedInteraction::impl_interceptRequest(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest)
{
    css::uno::Any                                                                    aRequest       = xRequest->getRequest();
    css::uno::Type                                                                   aRequestType   = aRequest.getValueType();
    css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > lContinuations = xRequest->getContinuations();

    // check against the list of static requests
    sal_Int32 nHandle = 0;
    ::std::vector< InterceptedRequest >::const_iterator pIt;
    for (  pIt  = m_lInterceptions.begin();
           pIt != m_lInterceptions.end()  ;
         ++pIt                            )
    {
        const InterceptedRequest& rInterception = *pIt;
        css::uno::Type aInterceptedType = rInterception.Request.getValueType();

        // check the request
        sal_Bool bMatch = sal_False;
        if (rInterception.MatchExact)
            bMatch = aInterceptedType.equals(aRequestType);
        else
            bMatch = aInterceptedType.isAssignableFrom(aRequestType); // dont change intercepted and request type here -> it will check the wrong direction!

        // intercepted ...
        // Call they might existing derived class, so they can handle that by its own.
        // If its not interested on that (may be its not overwritten and the default implementation
        // returns E_NOT_INTERCEPTED as default) -> break this loop and search for the right continuation.
        if (bMatch)
        {
            EInterceptionState eState = intercepted(rInterception, xRequest);
            if (eState == E_NOT_INTERCEPTED)
                break;
            return eState;
        }

        ++nHandle;
    }

    if (pIt != m_lInterceptions.end()) // => can be true only if bMatch=TRUE!
    {
        // match -> search required continuation
        const InterceptedRequest& rInterception = *pIt;
        css::uno::Reference< css::task::XInteractionContinuation > xContinuation = InterceptedInteraction::extractContinuation(lContinuations, rInterception.Continuation);
        if (xContinuation.is())
        {
            xContinuation->select();
            return E_INTERCEPTED;
        }

        // Can be reached only, if the request does not support the given continuation!
        // => RuntimeError!?
        return E_NO_CONTINUATION_FOUND;
    }

    return E_NOT_INTERCEPTED;
}

} // namespace ucbhelper
<|endoftext|>


<commit_before>#include <iostream>
#include <sys/epoll.h>

int main ()
{
    epoll_ctl (0x66, 0x377, 0x323, NULL);

    return 0;
}
<commit_msg>fix a bug<commit_after><|endoftext|>


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

/*
 * $Log$
 * Revision 1.8  2003/05/29 11:18:37  gareth
 * Added macros in so we can determine whether to do things like iostream as opposed to iostream.h and whether to use std:: or not.
 *
 * Revision 1.7  2002/11/04 14:45:20  tng
 * C++ Namespace Support.
 *
 * Revision 1.6  2002/06/25 16:05:24  tng
 * DOM L3: move the operator delete to DOMDocumentImpl.hpp
 *
 * Revision 1.5  2002/05/28 12:57:17  tng
 * Fix typo.
 *
 * Revision 1.4  2002/05/27 18:02:40  tng
 * define XMLSize_t, XMLSSize_t and their associate MAX
 *
 * Revision 1.3  2002/05/21 19:45:53  tng
 * Define DOMSize_t and XMLSize_t
 *
 * Revision 1.2  2002/04/17 20:30:01  tng
 * [Bug 7583] Build warnings with MS Visual Studio .NET.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:19  peiyongz
 * sane_include
 *
 * Revision 1.13  2001/06/04 20:11:54  tng
 * IDOM: Complete IDNodeIterator, IDTreeWalker, IDNodeFilter.
 *
 * Revision 1.12  2001/06/04 13:45:06  tng
 * The "hash" argument clashes with STL hash.  Fixed by Pei Yong Zhang.
 *
 * Revision 1.11  2001/05/29 18:50:24  tng
 * IDOM: call allocate directly for array allocation to avoid overloading operator new[] which leads to compilation error on SUN CC 4.2
 *
 * Revision 1.10  2001/05/28 20:59:21  tng
 * IDOM: move operator new[] to VCPPDefs as only Windows VCPP requires its presense
 *
 * Revision 1.9  2001/05/23 20:35:03  tng
 * IDOM: Move operator delete to VCPPDefs.hpp as only VCPP needs a matching delete operator.
 *
 * Revision 1.8  2001/03/02 20:53:08  knoaman
 * Schema: Regular expression - misc. updates for error messages,
 * and additions of new functions to XMLString class.
 *
 * Revision 1.7  2000/06/16 21:13:23  rahulj
 * Add 'D' suffix to the library name for the 'DEBUG' build
 * configuration.
 *
 * Revision 1.6  2000/03/02 19:55:09  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.5  2000/02/06 07:48:18  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.4  2000/01/14 01:19:22  roddey
 * Added a define of XML_LSTRSUPPORT to indicate supoprt of L"" type
 * prefixes on this compiler.
 *
 * Revision 1.3  2000/01/14 00:51:30  roddey
 * Added the requested XMLStrL() macro to support some portable
 * optimization of DOM code. This still needs to be added to the other
 * per-compiler files.
 *
 * Revision 1.2  1999/11/10 21:26:14  abagchi
 * Changed the DLL name
 *
 * Revision 1.1.1.1  1999/11/09 01:07:41  twl
 * Initial checkin
 *
 * Revision 1.3  1999/11/08 20:45:25  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

#if !defined(VCPPDEFS_HPP)
#define VCPPDEFS_HPP

// ---------------------------------------------------------------------------
//  Include some runtime files that will be needed product wide
// ---------------------------------------------------------------------------
#include <sys/types.h>  // for size_t and ssize_t
#include <limits.h>  // for MAX of size_t and ssize_t

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT     __declspec(dllexport)
#define PLATFORM_IMPORT     __declspec(dllimport)

// ---------------------------------------------------------------------------
//  Indicate that we do not support native bools
//  If the compiler can handle boolean itself, do not define it
// ---------------------------------------------------------------------------
// #define NO_NATIVE_BOOL

// ---------------------------------------------------------------------------
//  Each compiler might support L"" prefixed constants. There are places
//  where it is advantageous to use the L"" where it supported, to avoid
//  unnecessary transcoding.
//  If your compiler does not support it, don't define this.
// ---------------------------------------------------------------------------
#define XML_LSTRSUPPORT

// ---------------------------------------------------------------------------
//  Indicate that we support C++ namespace
//  Do not define it if the compile cannot handle C++ namespace
// ---------------------------------------------------------------------------
#define XERCES_HAS_CPP_NAMESPACE

// ---------------------------------------------------------------------------
//  Define our version of the XML character
// ---------------------------------------------------------------------------
typedef unsigned short  XMLCh;

// ---------------------------------------------------------------------------
//  Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short  XMLUInt16;
typedef unsigned int    XMLUInt32;

// ---------------------------------------------------------------------------
//  Define signed 32 bits integers
// ---------------------------------------------------------------------------
typedef int             XMLInt32;

// ---------------------------------------------------------------------------
//  XMLSize_t is the unsigned integral type.
// ---------------------------------------------------------------------------
#if defined(_SIZE_T) && defined(SIZE_MAX) && defined(_SSIZE_T) && defined(SSIZE_MAX)
    typedef size_t              XMLSize_t;
    #define XML_SIZE_MAX        SIZE_MAX
    typedef ssize_t             XMLSSize_t;
    #define XML_SSIZE_MAX       SSIZE_MAX
#else
    typedef unsigned long       XMLSize_t;
    #define XML_SIZE_MAX        ULONG_MAX
    typedef long                XMLSSize_t;
    #define XML_SSIZE_MAX       LONG_MAX
#endif

// ---------------------------------------------------------------------------
//  Force on the Xerces debug token if it was on in the build environment
// ---------------------------------------------------------------------------
#if defined(_DEBUG)
#define XERCES_DEBUG
#endif

#if _MSV_VER > 1300
#define XERCES_NEW_IOSTREAMS
#define XERCES_STD_NAMESPACE
#endif

// ---------------------------------------------------------------------------
//  The name of the DLL that is built by the Visual C++ version of the
//  system. We append a previously defined token which holds the DLL
//  versioning string. This is defined in XercesDefs.hpp which is what this
//  file is included into.
// ---------------------------------------------------------------------------
#if defined(XERCES_DEBUG)
const char* const Xerces_DLLName = "xerces-c_" Xerces_DLLVersionStr "D";
#else
const char* const Xerces_DLLName = "xerces-c_" Xerces_DLLVersionStr;
#endif

#endif //VCPPDEFS_HPP

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

/*
 * $Log$
 * Revision 1.9  2003/05/29 13:52:36  gareth
 * fixed typo for version number
 *
 * Revision 1.8  2003/05/29 11:18:37  gareth
 * Added macros in so we can determine whether to do things like iostream as opposed to iostream.h and whether to use std:: or not.
 *
 * Revision 1.7  2002/11/04 14:45:20  tng
 * C++ Namespace Support.
 *
 * Revision 1.6  2002/06/25 16:05:24  tng
 * DOM L3: move the operator delete to DOMDocumentImpl.hpp
 *
 * Revision 1.5  2002/05/28 12:57:17  tng
 * Fix typo.
 *
 * Revision 1.4  2002/05/27 18:02:40  tng
 * define XMLSize_t, XMLSSize_t and their associate MAX
 *
 * Revision 1.3  2002/05/21 19:45:53  tng
 * Define DOMSize_t and XMLSize_t
 *
 * Revision 1.2  2002/04/17 20:30:01  tng
 * [Bug 7583] Build warnings with MS Visual Studio .NET.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:19  peiyongz
 * sane_include
 *
 * Revision 1.13  2001/06/04 20:11:54  tng
 * IDOM: Complete IDNodeIterator, IDTreeWalker, IDNodeFilter.
 *
 * Revision 1.12  2001/06/04 13:45:06  tng
 * The "hash" argument clashes with STL hash.  Fixed by Pei Yong Zhang.
 *
 * Revision 1.11  2001/05/29 18:50:24  tng
 * IDOM: call allocate directly for array allocation to avoid overloading operator new[] which leads to compilation error on SUN CC 4.2
 *
 * Revision 1.10  2001/05/28 20:59:21  tng
 * IDOM: move operator new[] to VCPPDefs as only Windows VCPP requires its presense
 *
 * Revision 1.9  2001/05/23 20:35:03  tng
 * IDOM: Move operator delete to VCPPDefs.hpp as only VCPP needs a matching delete operator.
 *
 * Revision 1.8  2001/03/02 20:53:08  knoaman
 * Schema: Regular expression - misc. updates for error messages,
 * and additions of new functions to XMLString class.
 *
 * Revision 1.7  2000/06/16 21:13:23  rahulj
 * Add 'D' suffix to the library name for the 'DEBUG' build
 * configuration.
 *
 * Revision 1.6  2000/03/02 19:55:09  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.5  2000/02/06 07:48:18  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.4  2000/01/14 01:19:22  roddey
 * Added a define of XML_LSTRSUPPORT to indicate supoprt of L"" type
 * prefixes on this compiler.
 *
 * Revision 1.3  2000/01/14 00:51:30  roddey
 * Added the requested XMLStrL() macro to support some portable
 * optimization of DOM code. This still needs to be added to the other
 * per-compiler files.
 *
 * Revision 1.2  1999/11/10 21:26:14  abagchi
 * Changed the DLL name
 *
 * Revision 1.1.1.1  1999/11/09 01:07:41  twl
 * Initial checkin
 *
 * Revision 1.3  1999/11/08 20:45:25  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

#if !defined(VCPPDEFS_HPP)
#define VCPPDEFS_HPP

// ---------------------------------------------------------------------------
//  Include some runtime files that will be needed product wide
// ---------------------------------------------------------------------------
#include <sys/types.h>  // for size_t and ssize_t
#include <limits.h>  // for MAX of size_t and ssize_t

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT     __declspec(dllexport)
#define PLATFORM_IMPORT     __declspec(dllimport)

// ---------------------------------------------------------------------------
//  Indicate that we do not support native bools
//  If the compiler can handle boolean itself, do not define it
// ---------------------------------------------------------------------------
// #define NO_NATIVE_BOOL

// ---------------------------------------------------------------------------
//  Each compiler might support L"" prefixed constants. There are places
//  where it is advantageous to use the L"" where it supported, to avoid
//  unnecessary transcoding.
//  If your compiler does not support it, don't define this.
// ---------------------------------------------------------------------------
#define XML_LSTRSUPPORT

// ---------------------------------------------------------------------------
//  Indicate that we support C++ namespace
//  Do not define it if the compile cannot handle C++ namespace
// ---------------------------------------------------------------------------
#define XERCES_HAS_CPP_NAMESPACE

// ---------------------------------------------------------------------------
//  Define our version of the XML character
// ---------------------------------------------------------------------------
typedef unsigned short  XMLCh;

// ---------------------------------------------------------------------------
//  Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short  XMLUInt16;
typedef unsigned int    XMLUInt32;

// ---------------------------------------------------------------------------
//  Define signed 32 bits integers
// ---------------------------------------------------------------------------
typedef int             XMLInt32;

// ---------------------------------------------------------------------------
//  XMLSize_t is the unsigned integral type.
// ---------------------------------------------------------------------------
#if defined(_SIZE_T) && defined(SIZE_MAX) && defined(_SSIZE_T) && defined(SSIZE_MAX)
    typedef size_t              XMLSize_t;
    #define XML_SIZE_MAX        SIZE_MAX
    typedef ssize_t             XMLSSize_t;
    #define XML_SSIZE_MAX       SSIZE_MAX
#else
    typedef unsigned long       XMLSize_t;
    #define XML_SIZE_MAX        ULONG_MAX
    typedef long                XMLSSize_t;
    #define XML_SSIZE_MAX       LONG_MAX
#endif

// ---------------------------------------------------------------------------
//  Force on the Xerces debug token if it was on in the build environment
// ---------------------------------------------------------------------------
#if defined(_DEBUG)
#define XERCES_DEBUG
#endif

#if _MSC_VER > 1300
#define XERCES_NEW_IOSTREAMS
#define XERCES_STD_NAMESPACE
#endif

// ---------------------------------------------------------------------------
//  The name of the DLL that is built by the Visual C++ version of the
//  system. We append a previously defined token which holds the DLL
//  versioning string. This is defined in XercesDefs.hpp which is what this
//  file is included into.
// ---------------------------------------------------------------------------
#if defined(XERCES_DEBUG)
const char* const Xerces_DLLName = "xerces-c_" Xerces_DLLVersionStr "D";
#else
const char* const Xerces_DLLName = "xerces-c_" Xerces_DLLVersionStr;
#endif

#endif //VCPPDEFS_HPP

<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////
// sect2.cpp -- Emit the Section2 Procedures
// Date: Sat Nov 30 13:50:35 2013
///////////////////////////////////////////////////////////////////////

#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include <iostream>
#include <sstream>

#include "glue.hpp"
#include "comp.hpp"
#include "config.hpp"

void
emit_section2() {
	char sgenset[32];
	std::fstream ads, adb;

	sprintf(sgenset,"%04d",config.section2.genset);

	std::cout << "Genset " << sgenset << " emit section2\n";

	if ( !gcc_open(ads,config.section2.genset,".ads") )
		exit(3);

	if ( !gcc_open(adb,config.section2.genset,".adb") )
		exit(3);

	for ( auto it=config.section2.funcs.begin(); it != config.section2.funcs.end(); ++it ) {
		s_config::s_section2::s_func& func = *it;
		std::stringstream proto;
		std::string binding_name = "UX_";

		binding_name += func.c_name;		// Default internal c binding name

		if ( func.alt_name != "" )
			binding_name = func.alt_name;

		proto << func.type;
		if ( func.type != "function" )
			proto << "procedure " << func.ada_name;
		else	proto << "function " << func.ada_name;

		if ( func.aargs.size() > 0 ) {
			proto << "(";

			bool f=true;

			for ( auto ait=func.aargs.begin(); ait != func.aargs.end(); ++ait ) {
				s_config::s_section2::s_func::s_aarg& arg = *ait;

				if ( !f ) {
					proto << "; ";
				} else	{
					f = false;
				}
				proto << arg.name << ": ";
				if ( arg.io != "in" )
					proto << arg.io << " ";
				proto << arg.type;
			}
			proto << ")";
			if ( func.type == "function" )
				proto << " return " << func.returns;
		}

		ads << "  " << proto.str() << ";\n";
		if ( func.finline )
			ads << "   pragma Inline(" << func.ada_name << ");\n\n";

		adb 	<< "   " << proto.str() << " is\n";

		// C Function Declaration
		if ( func.returns != "" )
			adb << "      function " << binding_name;
		else	adb << "      procedure " << binding_name;
		if ( func.cargs.size() > 0 ) {
			adb << "(";
			bool f = true;
			for ( auto cit=func.cargs.begin(); cit != func.cargs.end(); ++cit ) {
				const s_config::s_section2::s_func::s_carg& arg = *cit;
				if ( !f )
					adb << "; ";
				else	f = false;
				adb << arg.name << " : " << arg.type;
			}
			adb << ")";
		}

		if ( func.returns != "" )
			adb << " return " << func.returns << ";\n";
		else	adb << ";\n";

		//  pragma Import(C,UX_close,"close");
		adb << "      pragma Import(C," << binding_name << ",\"" << func.c_name << "\");\n";

		// Temporaries
		for ( auto ait=func.aargs.begin(); ait != func.aargs.end(); ++ait ) {
			s_config::s_section2::s_func::s_aarg& arg = *ait;

			if ( arg.io == "in" && arg.temp != "" ) {
				std::stringstream s;
				std::string tempname;

				s << "T" << arg.argno;
				tempname = s.str();

				adb << "      " << tempname << " : " << arg.type
				    << " := " << arg.tempval << ";\n";
			}
		}

		// Temporary variables
		for ( auto t=func.temps.begin(); t != func.temps.end(); ++t ) {
			s_config::s_section2::s_func::s_temp& temp = *t;

			adb << "      " << temp.name << " : " << temp.type;
			if ( temp.init != "" )
				adb << " := " << temp.init;
			adb << ";\n";
		}

		// Return value:
		if ( func.rname != "" ) {
			adb << "      " << func.rname << " : " << func.returns << ";\n";
		}

		adb	<< "   begin\n";

		if ( func.rname != "" ) {
			adb << "      " << func.rname << " := " << binding_name;
		} else	{
			adb << "      " << binding_name;
		}

		if ( func.cargs.size() > 0 ) {
			adb << "(";
			bool f = true;
			for ( auto fit=func.cargs.begin(); fit != func.cargs.end(); ++fit ) {
				s_config::s_section2::s_func::s_carg& arg = *fit;
				if ( f )
					f = false;
				else	adb << ",";
				adb << arg.from;
			}
			adb << ")";
		}
		adb 	<< ";\n";

		// Output values:
		for ( auto oit=func.aargs.begin(); oit != func.aargs.end(); ++oit ) {
			s_config::s_section2::s_func::s_aarg& arg = *oit;

			if ( arg.io == "out" || arg.io == "inout" ) {
				adb << "      " << arg.name << " := "
				    << arg.from << ";\n";
			}
		}

		adb	<< "   end " << func.ada_name << ";\n\n";
	}

	ads.close();
	adb.close();
}

// End sect2.cpp
<commit_msg>Fix indentation<commit_after>//////////////////////////////////////////////////////////////////////
// sect2.cpp -- Emit the Section2 Procedures
// Date: Sat Nov 30 13:50:35 2013
///////////////////////////////////////////////////////////////////////

#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include <iostream>
#include <sstream>

#include "glue.hpp"
#include "comp.hpp"
#include "config.hpp"

void
emit_section2() {
	char sgenset[32];
	std::fstream ads, adb;

	sprintf(sgenset,"%04d",config.section2.genset);

	std::cout << "Genset " << sgenset << " emit section2\n";

	if ( !gcc_open(ads,config.section2.genset,".ads") )
		exit(3);

	if ( !gcc_open(adb,config.section2.genset,".adb") )
		exit(3);

	for ( auto it=config.section2.funcs.begin(); it != config.section2.funcs.end(); ++it ) {
		s_config::s_section2::s_func& func = *it;
		std::stringstream proto;
		std::string binding_name = "UX_";

		binding_name += func.c_name;		// Default internal c binding name

		if ( func.alt_name != "" )
			binding_name = func.alt_name;

		proto << func.type;
		if ( func.type != "function" )
			proto << "procedure " << func.ada_name;
		else	proto << "function " << func.ada_name;

		if ( func.aargs.size() > 0 ) {
			proto << "(";

			bool f=true;

			for ( auto ait=func.aargs.begin(); ait != func.aargs.end(); ++ait ) {
				s_config::s_section2::s_func::s_aarg& arg = *ait;

				if ( !f ) {
					proto << "; ";
				} else	{
					f = false;
				}
				proto << arg.name << ": ";
				if ( arg.io != "in" )
					proto << arg.io << " ";
				proto << arg.type;
			}
			proto << ")";
			if ( func.type == "function" )
				proto << " return " << func.returns;
		}

		ads << "   " << proto.str() << ";\n";
		if ( func.finline )
			ads << "   pragma Inline(" << func.ada_name << ");\n\n";

		adb 	<< "   " << proto.str() << " is\n";

		// C Function Declaration
		if ( func.returns != "" )
			adb << "      function " << binding_name;
		else	adb << "      procedure " << binding_name;
		if ( func.cargs.size() > 0 ) {
			adb << "(";
			bool f = true;
			for ( auto cit=func.cargs.begin(); cit != func.cargs.end(); ++cit ) {
				const s_config::s_section2::s_func::s_carg& arg = *cit;
				if ( !f )
					adb << "; ";
				else	f = false;
				adb << arg.name << " : " << arg.type;
			}
			adb << ")";
		}

		if ( func.returns != "" )
			adb << " return " << func.returns << ";\n";
		else	adb << ";\n";

		//  pragma Import(C,UX_close,"close");
		adb << "      pragma Import(C," << binding_name << ",\"" << func.c_name << "\");\n";

		// Temporaries
		for ( auto ait=func.aargs.begin(); ait != func.aargs.end(); ++ait ) {
			s_config::s_section2::s_func::s_aarg& arg = *ait;

			if ( arg.io == "in" && arg.temp != "" ) {
				std::stringstream s;
				std::string tempname;

				s << "T" << arg.argno;
				tempname = s.str();

				adb << "      " << tempname << " : " << arg.type
				    << " := " << arg.tempval << ";\n";
			}
		}

		// Temporary variables
		for ( auto t=func.temps.begin(); t != func.temps.end(); ++t ) {
			s_config::s_section2::s_func::s_temp& temp = *t;

			adb << "      " << temp.name << " : " << temp.type;
			if ( temp.init != "" )
				adb << " := " << temp.init;
			adb << ";\n";
		}

		// Return value:
		if ( func.rname != "" ) {
			adb << "      " << func.rname << " : " << func.returns << ";\n";
		}

		adb	<< "   begin\n";

		if ( func.rname != "" ) {
			adb << "      " << func.rname << " := " << binding_name;
		} else	{
			adb << "      " << binding_name;
		}

		if ( func.cargs.size() > 0 ) {
			adb << "(";
			bool f = true;
			for ( auto fit=func.cargs.begin(); fit != func.cargs.end(); ++fit ) {
				s_config::s_section2::s_func::s_carg& arg = *fit;
				if ( f )
					f = false;
				else	adb << ",";
				adb << arg.from;
			}
			adb << ")";
		}
		adb 	<< ";\n";

		// Output values:
		for ( auto oit=func.aargs.begin(); oit != func.aargs.end(); ++oit ) {
			s_config::s_section2::s_func::s_aarg& arg = *oit;

			if ( arg.io == "out" || arg.io == "inout" ) {
				adb << "      " << arg.name << " := "
				    << arg.from << ";\n";
			}
		}

		adb	<< "   end " << func.ada_name << ";\n\n";
	}

	ads.close();
	adb.close();
}

// End sect2.cpp
<|endoftext|>


<commit_before>#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/core.hpp>
#include <wayfire/debug.hpp>
#include <wayfire/view.hpp>
#include <wayfire/view-transform.hpp>
#include <wayfire/render-manager.hpp>
#include <wayfire/workspace-manager.hpp>

#include <queue>
#include <linux/input.h>
#include <utility>
#include <set>
#include "view-change-viewport-signal.hpp"
#include "../wobbly/wobbly-signal.hpp"
#include <wayfire/util/duration.hpp>

class vswitch_view_transformer : public wf::view_2D
{
    public:
        static const std::string name;
        vswitch_view_transformer(wayfire_view view) : view_2D(view) {}
        virtual uint32_t get_z_order() override { return wf::TRANSFORMER_BLUR - 1; }
};
const std::string vswitch_view_transformer::name = "vswitch-transformer";

using namespace wf::animation;
class vswitch_animation_t : public duration_t
{
  public:
    using duration_t::duration_t;
    timed_transition_t dx{*this};
    timed_transition_t dy{*this};
};

class vswitch : public wf::plugin_interface_t
{
    private:
        wf::activator_callback callback_left, callback_right, callback_up, callback_down;
        wf::activator_callback callback_win_left, callback_win_right, callback_win_up, callback_win_down;

        wf::gesture_callback gesture_cb;
        vswitch_animation_t animation;
        wayfire_view grabbed_view = nullptr;

    public:
    wayfire_view get_top_view()
    {
        auto ws = output->workspace->get_current_workspace();
        auto views = output->workspace->get_views_on_workspace(ws,
            wf::LAYER_WORKSPACE | wf::LAYER_FULLSCREEN, true);

        return views.empty() ? nullptr : views[0];
    }

    void init()
    {
        grab_interface->name = "vswitch";
        grab_interface->capabilities = wf::CAPABILITY_MANAGE_DESKTOP;
        grab_interface->callbacks.cancel = [=] () {stop_switch();};

        callback_left  = [=] (wf::activator_source_t, uint32_t) { return add_direction(-1,  0); };
        callback_right = [=] (wf::activator_source_t, uint32_t) { return add_direction( 1,  0); };
        callback_up    = [=] (wf::activator_source_t, uint32_t) { return add_direction( 0, -1); };
        callback_down  = [=] (wf::activator_source_t, uint32_t) { return add_direction( 0,  1); };

        callback_win_left  = [=] (wf::activator_source_t, uint32_t) { return add_direction(-1,  0, get_top_view()); };
        callback_win_right = [=] (wf::activator_source_t, uint32_t) { return add_direction( 1,  0, get_top_view()); };
        callback_win_up    = [=] (wf::activator_source_t, uint32_t) { return add_direction( 0, -1, get_top_view()); };
        callback_win_down  = [=] (wf::activator_source_t, uint32_t) { return add_direction( 0,  1, get_top_view()); };

        wf::option_wrapper_t<wf::activatorbinding_t> binding_left{"vswitch/binding_left"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_right{"vswitch/binding_right"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_up{"vswitch/binding_up"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_down{"vswitch/binding_down"};

        wf::option_wrapper_t<wf::activatorbinding_t> binding_win_left{"vswitch/binding_win_left"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_win_right{"vswitch/binding_win_right"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_win_up{"vswitch/binding_win_up"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_win_down{"vswitch/binding_win_down"};

        output->add_activator(binding_left,  &callback_left);
        output->add_activator(binding_right, &callback_right);
        output->add_activator(binding_up,    &callback_up);
        output->add_activator(binding_down,  &callback_down);

        output->add_activator(binding_win_left,  &callback_win_left);
        output->add_activator(binding_win_right, &callback_win_right);
        output->add_activator(binding_win_up,    &callback_win_up);
        output->add_activator(binding_win_down,  &callback_win_down);

        animation = vswitch_animation_t{
            wf::option_wrapper_t<int> {"vswitch/duration"}.raw_option};
        output->connect_signal("set-workspace-request", &on_set_workspace_request);
    }

    inline bool is_active()
    {
        return output->is_plugin_active(grab_interface->name);
    }

    bool add_direction(int x, int y, wayfire_view view = nullptr)
    {
        if (!x && !y)
            return false;

        if (!is_active() && !start_switch())
            return false;

        if (view && view->role != wf::VIEW_ROLE_TOPLEVEL)
            view = nullptr;

        if (view && !grabbed_view)
            grabbed_view = view;

        /* Make sure that when we add this direction, we won't go outside
         * of the workspace grid */
        auto cws = output->workspace->get_current_workspace();
        auto wsize = output->workspace->get_workspace_grid_size();
        int tvx = wf::clamp(cws.x + animation.dx.end + x, 0.0, wsize.width - 1.0);
        int tvy = wf::clamp(cws.y + animation.dy.end + y, 0.0, wsize.height - 1.0);

        animation.dx.restart_with_end(1.0 * tvx - cws.x);
        animation.dy.restart_with_end(1.0 * tvy - cws.y);
        animation.start();
        return true;
    }

    wf::signal_callback_t on_set_workspace_request = [=] (wf::signal_data_t *data)
    {
        if (is_active())
            return;

        auto ev = static_cast<change_viewport_signal*> (data);
        ev->carried_out = true;
        add_direction(ev->new_viewport.x - ev->old_viewport.x,
            ev->new_viewport.y - ev->old_viewport.y);
    };

    std::vector<wayfire_view> get_ws_views()
    {
        std::vector<wayfire_view> views;
        for (auto& view : output->workspace->get_views_in_layer(wf::MIDDLE_LAYERS))
        {
            if (view != grabbed_view)
                views.push_back(view);
        }

        return views;
    }

    void ensure_transformer(wayfire_view view)
    {
        if (!view->get_transformer(vswitch_view_transformer::name))
        {
            view->add_transformer(
                std::make_unique<vswitch_view_transformer>(view),
                vswitch_view_transformer::name);
        }
    }

    bool start_switch()
    {
        if (!output->activate_plugin(grab_interface))
            return false;

        output->render->add_effect(&update_animation, wf::OUTPUT_EFFECT_PRE);
        output->render->set_redraw_always();

        animation.dx.set(0, 0);
        animation.dy.set(0, 0);
        animation.start();
        return true;
    }

    wf::effect_hook_t update_animation = [=] ()
    {
        if (!animation.running())
            return stop_switch();

        auto screen_size = output->get_screen_size();
        for (auto view : get_ws_views())
        {
            ensure_transformer(view);
            auto tr = dynamic_cast<vswitch_view_transformer*> (
                view->get_transformer(vswitch_view_transformer::name).get());

            view->damage();
            tr->translation_x = -animation.dx * screen_size.width;
            tr->translation_y = -animation.dy * screen_size.height;
            view->damage();
        }
    };

    void slide_done()
    {
        auto cws = output->workspace->get_current_workspace();
        auto old_ws = cws;

        cws.x += animation.dx.end;
        cws.y += animation.dy.end;

        auto output_g = output->get_relative_geometry();
        output->workspace->set_workspace(cws);

        if (grabbed_view)
        {
            auto wm = grabbed_view->get_wm_geometry();
            grabbed_view->move(wm.x + animation.dx.end * output_g.width,
                wm.y + animation.dy.end * output_g.height);

            output->focus_view(grabbed_view);
            output->workspace->bring_to_front(grabbed_view);

            view_change_viewport_signal data;
            data.view = grabbed_view;
            data.from = old_ws;
            data.to = output->workspace->get_current_workspace();
            output->emit_signal("view-change-viewport", &data);
        }
    }

    void stop_switch()
    {
        slide_done();
        grabbed_view = nullptr;

        for (auto view : get_ws_views())
            view->pop_transformer(vswitch_view_transformer::name);

        output->deactivate_plugin(grab_interface);
        output->render->rem_effect(&update_animation);
        output->render->set_redraw_always(false);
    }

    void fini()
    {
        if (!is_active())
            stop_switch();

        output->rem_binding(&callback_left);
        output->rem_binding(&callback_right);
        output->rem_binding(&callback_up);
        output->rem_binding(&callback_down);

        output->rem_binding(&callback_win_left);
        output->rem_binding(&callback_win_right);
        output->rem_binding(&callback_win_up);
        output->rem_binding(&callback_win_down);

        output->rem_binding(&gesture_cb);
        output->disconnect_signal("set-workspace-request",
            &on_set_workspace_request);
    }
};

DECLARE_WAYFIRE_PLUGIN(vswitch);
<commit_msg>vswitch: do not create dangling pointer by moving raw_option out of the wrapper<commit_after>#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/core.hpp>
#include <wayfire/debug.hpp>
#include <wayfire/view.hpp>
#include <wayfire/view-transform.hpp>
#include <wayfire/render-manager.hpp>
#include <wayfire/workspace-manager.hpp>

#include <queue>
#include <linux/input.h>
#include <utility>
#include <set>
#include "view-change-viewport-signal.hpp"
#include "../wobbly/wobbly-signal.hpp"
#include <wayfire/util/duration.hpp>

class vswitch_view_transformer : public wf::view_2D
{
    public:
        static const std::string name;
        vswitch_view_transformer(wayfire_view view) : view_2D(view) {}
        virtual uint32_t get_z_order() override { return wf::TRANSFORMER_BLUR - 1; }
};
const std::string vswitch_view_transformer::name = "vswitch-transformer";

using namespace wf::animation;
class vswitch_animation_t : public duration_t
{
  public:
    using duration_t::duration_t;
    timed_transition_t dx{*this};
    timed_transition_t dy{*this};
};

class vswitch : public wf::plugin_interface_t
{
    private:
        wf::activator_callback callback_left, callback_right, callback_up, callback_down;
        wf::activator_callback callback_win_left, callback_win_right, callback_win_up, callback_win_down;

        wf::gesture_callback gesture_cb;
        vswitch_animation_t animation;
        wayfire_view grabbed_view = nullptr;

    public:
    wayfire_view get_top_view()
    {
        auto ws = output->workspace->get_current_workspace();
        auto views = output->workspace->get_views_on_workspace(ws,
            wf::LAYER_WORKSPACE | wf::LAYER_FULLSCREEN, true);

        return views.empty() ? nullptr : views[0];
    }

    void init()
    {
        grab_interface->name = "vswitch";
        grab_interface->capabilities = wf::CAPABILITY_MANAGE_DESKTOP;
        grab_interface->callbacks.cancel = [=] () {stop_switch();};

        callback_left  = [=] (wf::activator_source_t, uint32_t) { return add_direction(-1,  0); };
        callback_right = [=] (wf::activator_source_t, uint32_t) { return add_direction( 1,  0); };
        callback_up    = [=] (wf::activator_source_t, uint32_t) { return add_direction( 0, -1); };
        callback_down  = [=] (wf::activator_source_t, uint32_t) { return add_direction( 0,  1); };

        callback_win_left  = [=] (wf::activator_source_t, uint32_t) { return add_direction(-1,  0, get_top_view()); };
        callback_win_right = [=] (wf::activator_source_t, uint32_t) { return add_direction( 1,  0, get_top_view()); };
        callback_win_up    = [=] (wf::activator_source_t, uint32_t) { return add_direction( 0, -1, get_top_view()); };
        callback_win_down  = [=] (wf::activator_source_t, uint32_t) { return add_direction( 0,  1, get_top_view()); };

        wf::option_wrapper_t<wf::activatorbinding_t> binding_left{"vswitch/binding_left"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_right{"vswitch/binding_right"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_up{"vswitch/binding_up"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_down{"vswitch/binding_down"};

        wf::option_wrapper_t<wf::activatorbinding_t> binding_win_left{"vswitch/binding_win_left"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_win_right{"vswitch/binding_win_right"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_win_up{"vswitch/binding_win_up"};
        wf::option_wrapper_t<wf::activatorbinding_t> binding_win_down{"vswitch/binding_win_down"};

        output->add_activator(binding_left,  &callback_left);
        output->add_activator(binding_right, &callback_right);
        output->add_activator(binding_up,    &callback_up);
        output->add_activator(binding_down,  &callback_down);

        output->add_activator(binding_win_left,  &callback_win_left);
        output->add_activator(binding_win_right, &callback_win_right);
        output->add_activator(binding_win_up,    &callback_win_up);
        output->add_activator(binding_win_down,  &callback_win_down);

        animation = vswitch_animation_t{
            wf::option_wrapper_t<int> {"vswitch/duration"}};
        output->connect_signal("set-workspace-request", &on_set_workspace_request);
    }

    inline bool is_active()
    {
        return output->is_plugin_active(grab_interface->name);
    }

    bool add_direction(int x, int y, wayfire_view view = nullptr)
    {
        if (!x && !y)
            return false;

        if (!is_active() && !start_switch())
            return false;

        if (view && view->role != wf::VIEW_ROLE_TOPLEVEL)
            view = nullptr;

        if (view && !grabbed_view)
            grabbed_view = view;

        /* Make sure that when we add this direction, we won't go outside
         * of the workspace grid */
        auto cws = output->workspace->get_current_workspace();
        auto wsize = output->workspace->get_workspace_grid_size();
        int tvx = wf::clamp(cws.x + animation.dx.end + x, 0.0, wsize.width - 1.0);
        int tvy = wf::clamp(cws.y + animation.dy.end + y, 0.0, wsize.height - 1.0);

        animation.dx.restart_with_end(1.0 * tvx - cws.x);
        animation.dy.restart_with_end(1.0 * tvy - cws.y);
        animation.start();
        return true;
    }

    wf::signal_callback_t on_set_workspace_request = [=] (wf::signal_data_t *data)
    {
        if (is_active())
            return;

        auto ev = static_cast<change_viewport_signal*> (data);
        ev->carried_out = true;
        add_direction(ev->new_viewport.x - ev->old_viewport.x,
            ev->new_viewport.y - ev->old_viewport.y);
    };

    std::vector<wayfire_view> get_ws_views()
    {
        std::vector<wayfire_view> views;
        for (auto& view : output->workspace->get_views_in_layer(wf::MIDDLE_LAYERS))
        {
            if (view != grabbed_view)
                views.push_back(view);
        }

        return views;
    }

    void ensure_transformer(wayfire_view view)
    {
        if (!view->get_transformer(vswitch_view_transformer::name))
        {
            view->add_transformer(
                std::make_unique<vswitch_view_transformer>(view),
                vswitch_view_transformer::name);
        }
    }

    bool start_switch()
    {
        if (!output->activate_plugin(grab_interface))
            return false;

        output->render->add_effect(&update_animation, wf::OUTPUT_EFFECT_PRE);
        output->render->set_redraw_always();

        animation.dx.set(0, 0);
        animation.dy.set(0, 0);
        animation.start();
        return true;
    }

    wf::effect_hook_t update_animation = [=] ()
    {
        if (!animation.running())
            return stop_switch();

        auto screen_size = output->get_screen_size();
        for (auto view : get_ws_views())
        {
            ensure_transformer(view);
            auto tr = dynamic_cast<vswitch_view_transformer*> (
                view->get_transformer(vswitch_view_transformer::name).get());

            view->damage();
            tr->translation_x = -animation.dx * screen_size.width;
            tr->translation_y = -animation.dy * screen_size.height;
            view->damage();
        }
    };

    void slide_done()
    {
        auto cws = output->workspace->get_current_workspace();
        auto old_ws = cws;

        cws.x += animation.dx.end;
        cws.y += animation.dy.end;

        auto output_g = output->get_relative_geometry();
        output->workspace->set_workspace(cws);

        if (grabbed_view)
        {
            auto wm = grabbed_view->get_wm_geometry();
            grabbed_view->move(wm.x + animation.dx.end * output_g.width,
                wm.y + animation.dy.end * output_g.height);

            output->focus_view(grabbed_view);
            output->workspace->bring_to_front(grabbed_view);

            view_change_viewport_signal data;
            data.view = grabbed_view;
            data.from = old_ws;
            data.to = output->workspace->get_current_workspace();
            output->emit_signal("view-change-viewport", &data);
        }
    }

    void stop_switch()
    {
        slide_done();
        grabbed_view = nullptr;

        for (auto view : get_ws_views())
            view->pop_transformer(vswitch_view_transformer::name);

        output->deactivate_plugin(grab_interface);
        output->render->rem_effect(&update_animation);
        output->render->set_redraw_always(false);
    }

    void fini()
    {
        if (!is_active())
            stop_switch();

        output->rem_binding(&callback_left);
        output->rem_binding(&callback_right);
        output->rem_binding(&callback_up);
        output->rem_binding(&callback_down);

        output->rem_binding(&callback_win_left);
        output->rem_binding(&callback_win_right);
        output->rem_binding(&callback_win_up);
        output->rem_binding(&callback_win_down);

        output->rem_binding(&gesture_cb);
        output->disconnect_signal("set-workspace-request",
            &on_set_workspace_request);
    }
};

DECLARE_WAYFIRE_PLUGIN(vswitch);
<|endoftext|>


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

#include "cc/layers/video_frame_provider_client_impl.h"

#include "cc/base/math_util.h"
#include "cc/layers/video_layer_impl.h"
#include "media/base/video_frame.h"

namespace cc {

// static
scoped_refptr<VideoFrameProviderClientImpl>
    VideoFrameProviderClientImpl::Create(
        VideoFrameProvider* provider) {
  return make_scoped_refptr(
      new VideoFrameProviderClientImpl(provider));
}

VideoFrameProviderClientImpl::~VideoFrameProviderClientImpl() {}

VideoFrameProviderClientImpl::VideoFrameProviderClientImpl(
    VideoFrameProvider* provider)
    : active_video_layer_(NULL), provider_(provider) {
  // This only happens during a commit on the compositor thread while the main
  // thread is blocked. That makes this a thread-safe call to set the video
  // frame provider client that does not require a lock. The same is true of
  // the call to Stop().
  provider_->SetVideoFrameProviderClient(this);

  // This matrix is the default transformation for stream textures, and flips
  // on the Y axis.
  stream_texture_matrix_ = gfx::Transform(
      1.0, 0.0, 0.0, 0.0,
      0.0, -1.0, 0.0, 1.0,
      0.0, 0.0, 1.0, 0.0,
      0.0, 0.0, 0.0, 1.0);
}

void VideoFrameProviderClientImpl::Stop() {
  if (!provider_)
    return;
  provider_->SetVideoFrameProviderClient(NULL);
  provider_ = NULL;
}

scoped_refptr<media::VideoFrame>
VideoFrameProviderClientImpl::AcquireLockAndCurrentFrame() {
  provider_lock_.Acquire();  // Balanced by call to ReleaseLock().
  if (!provider_)
    return NULL;

  return provider_->GetCurrentFrame();
}

void VideoFrameProviderClientImpl::PutCurrentFrame(
    const scoped_refptr<media::VideoFrame>& frame) {
  provider_lock_.AssertAcquired();
  provider_->PutCurrentFrame(frame);
}

void VideoFrameProviderClientImpl::ReleaseLock() {
  provider_lock_.AssertAcquired();
  provider_lock_.Release();
}

void VideoFrameProviderClientImpl::StopUsingProvider() {
  // Block the provider from shutting down until this client is done
  // using the frame.
  base::AutoLock locker(provider_lock_);
  provider_ = NULL;
}

void VideoFrameProviderClientImpl::DidReceiveFrame() {
  if (active_video_layer_)
    active_video_layer_->SetNeedsRedraw();
}

void VideoFrameProviderClientImpl::DidUpdateMatrix(const float* matrix) {
  stream_texture_matrix_ = gfx::Transform(
      matrix[0], matrix[4], matrix[8], matrix[12],
      matrix[1], matrix[5], matrix[9], matrix[13],
      matrix[2], matrix[6], matrix[10], matrix[14],
      matrix[3], matrix[7], matrix[11], matrix[15]);
  if (active_video_layer_)
    active_video_layer_->SetNeedsRedraw();
}

}  // namespace cc
<commit_msg>cc: Add a trace event in VideoFrameProviderClientImpl::DidReceiveFrame.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "cc/layers/video_frame_provider_client_impl.h"

#include "base/debug/trace_event.h"
#include "cc/base/math_util.h"
#include "cc/layers/video_layer_impl.h"
#include "media/base/video_frame.h"

namespace cc {

// static
scoped_refptr<VideoFrameProviderClientImpl>
    VideoFrameProviderClientImpl::Create(
        VideoFrameProvider* provider) {
  return make_scoped_refptr(
      new VideoFrameProviderClientImpl(provider));
}

VideoFrameProviderClientImpl::~VideoFrameProviderClientImpl() {}

VideoFrameProviderClientImpl::VideoFrameProviderClientImpl(
    VideoFrameProvider* provider)
    : active_video_layer_(NULL), provider_(provider) {
  // This only happens during a commit on the compositor thread while the main
  // thread is blocked. That makes this a thread-safe call to set the video
  // frame provider client that does not require a lock. The same is true of
  // the call to Stop().
  provider_->SetVideoFrameProviderClient(this);

  // This matrix is the default transformation for stream textures, and flips
  // on the Y axis.
  stream_texture_matrix_ = gfx::Transform(
      1.0, 0.0, 0.0, 0.0,
      0.0, -1.0, 0.0, 1.0,
      0.0, 0.0, 1.0, 0.0,
      0.0, 0.0, 0.0, 1.0);
}

void VideoFrameProviderClientImpl::Stop() {
  if (!provider_)
    return;
  provider_->SetVideoFrameProviderClient(NULL);
  provider_ = NULL;
}

scoped_refptr<media::VideoFrame>
VideoFrameProviderClientImpl::AcquireLockAndCurrentFrame() {
  provider_lock_.Acquire();  // Balanced by call to ReleaseLock().
  if (!provider_)
    return NULL;

  return provider_->GetCurrentFrame();
}

void VideoFrameProviderClientImpl::PutCurrentFrame(
    const scoped_refptr<media::VideoFrame>& frame) {
  provider_lock_.AssertAcquired();
  provider_->PutCurrentFrame(frame);
}

void VideoFrameProviderClientImpl::ReleaseLock() {
  provider_lock_.AssertAcquired();
  provider_lock_.Release();
}

void VideoFrameProviderClientImpl::StopUsingProvider() {
  // Block the provider from shutting down until this client is done
  // using the frame.
  base::AutoLock locker(provider_lock_);
  provider_ = NULL;
}

void VideoFrameProviderClientImpl::DidReceiveFrame() {
  TRACE_EVENT1("cc",
               "VideoFrameProviderClientImpl::DidReceiveFrame",
               "active_video_layer",
               !!active_video_layer_);
  if (active_video_layer_)
    active_video_layer_->SetNeedsRedraw();
}

void VideoFrameProviderClientImpl::DidUpdateMatrix(const float* matrix) {
  stream_texture_matrix_ = gfx::Transform(
      matrix[0], matrix[4], matrix[8], matrix[12],
      matrix[1], matrix[5], matrix[9], matrix[13],
      matrix[2], matrix[6], matrix[10], matrix[14],
      matrix[3], matrix[7], matrix[11], matrix[15]);
  if (active_video_layer_)
    active_video_layer_->SetNeedsRedraw();
}

}  // namespace cc
<|endoftext|>


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

#include "test_utils/ANGLETest.h"

#include <cstdint>
#include "com_utils.h"
#include "OSWindow.h"
#include <d3d11.h>

using namespace angle;

class EGLPresentPathD3D11 : public testing::TestWithParam<PlatformParameters>
{
  protected:
    EGLPresentPathD3D11()
        : mDisplay(EGL_NO_DISPLAY),
          mContext(EGL_NO_CONTEXT),
          mSurface(EGL_NO_SURFACE),
          mOffscreenSurfaceD3D11Texture(nullptr),
          mConfig(0),
          mOSWindow(nullptr),
          mWindowWidth(0)
    {
    }

    void SetUp() override
    {
        mOSWindow    = CreateOSWindow();
        mWindowWidth = 64;
        mOSWindow->initialize("EGLPresentPathD3D11", mWindowWidth, mWindowWidth);
    }

    void initializeEGL(bool usePresentPathFast)
    {
        int clientVersion = GetParam().majorVersion;

        const char *extensionString =
            static_cast<const char *>(eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS));
        ASSERT_NE(nullptr, strstr(extensionString, "EGL_ANGLE_experimental_present_path"));

        PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT =
            reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(
                eglGetProcAddress("eglGetPlatformDisplayEXT"));
        ASSERT_NE(nullptr, eglGetPlatformDisplayEXT);

        // Set up EGL Display
        EGLint displayAttribs[] = {
            EGL_PLATFORM_ANGLE_TYPE_ANGLE, GetParam().getRenderer(),
            EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, GetParam().eglParameters.majorVersion,
            EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, GetParam().eglParameters.majorVersion,
            EGL_EXPERIMENTAL_PRESENT_PATH_ANGLE,
            usePresentPathFast ? EGL_EXPERIMENTAL_PRESENT_PATH_FAST_ANGLE
                               : EGL_EXPERIMENTAL_PRESENT_PATH_COPY_ANGLE,
            EGL_NONE};
        mDisplay =
            eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, displayAttribs);
        ASSERT_TRUE(EGL_NO_DISPLAY != mDisplay);
        ASSERT_EGL_TRUE(eglInitialize(mDisplay, NULL, NULL));

        // Choose the EGL config
        EGLint numConfigs;
        EGLint configAttribs[] = {EGL_RED_SIZE,
                                  8,
                                  EGL_GREEN_SIZE,
                                  8,
                                  EGL_BLUE_SIZE,
                                  8,
                                  EGL_ALPHA_SIZE,
                                  8,
                                  EGL_RENDERABLE_TYPE,
                                  clientVersion == 3 ? EGL_OPENGL_ES3_BIT : EGL_OPENGL_ES2_BIT,
                                  EGL_SURFACE_TYPE,
                                  EGL_PBUFFER_BIT,
                                  EGL_NONE};
        ASSERT_EGL_TRUE(eglChooseConfig(mDisplay, configAttribs, &mConfig, 1, &numConfigs));
        ASSERT_EQ(1, numConfigs);

        // Set up the EGL context
        EGLint contextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, clientVersion, EGL_NONE};
        mContext = eglCreateContext(mDisplay, mConfig, NULL, contextAttribs);
        ASSERT_TRUE(EGL_NO_CONTEXT != mContext);
    }

    void createWindowSurface()
    {
        mSurface = eglCreateWindowSurface(mDisplay, mConfig, mOSWindow->getNativeWindow(), nullptr);
    }

    void createPbufferFromClientBufferSurface()
    {
        EGLAttrib device      = 0;
        EGLAttrib angleDevice = 0;

        PFNEGLQUERYDISPLAYATTRIBEXTPROC queryDisplayAttribEXT;
        PFNEGLQUERYDEVICEATTRIBEXTPROC queryDeviceAttribEXT;

        const char *extensionString =
            static_cast<const char *>(eglQueryString(mDisplay, EGL_EXTENSIONS));
        EXPECT_TRUE(strstr(extensionString, "EGL_EXT_device_query"));

        queryDisplayAttribEXT =
            (PFNEGLQUERYDISPLAYATTRIBEXTPROC)eglGetProcAddress("eglQueryDisplayAttribEXT");
        queryDeviceAttribEXT =
            (PFNEGLQUERYDEVICEATTRIBEXTPROC)eglGetProcAddress("eglQueryDeviceAttribEXT");
        ASSERT_NE(nullptr, queryDisplayAttribEXT);
        ASSERT_NE(nullptr, queryDeviceAttribEXT);

        ASSERT_EGL_TRUE(queryDisplayAttribEXT(mDisplay, EGL_DEVICE_EXT, &angleDevice));
        ASSERT_EGL_TRUE(queryDeviceAttribEXT(reinterpret_cast<EGLDeviceEXT>(angleDevice),
                                             EGL_D3D11_DEVICE_ANGLE, &device));
        ID3D11Device *d3d11Device = reinterpret_cast<ID3D11Device *>(device);

        D3D11_TEXTURE2D_DESC textureDesc = {0};
        textureDesc.Width                = mWindowWidth;
        textureDesc.Height               = mWindowWidth;
        textureDesc.Format               = DXGI_FORMAT_B8G8R8A8_UNORM;
        textureDesc.MipLevels            = 1;
        textureDesc.ArraySize            = 1;
        textureDesc.SampleDesc.Count     = 1;
        textureDesc.SampleDesc.Quality   = 0;
        textureDesc.Usage                = D3D11_USAGE_DEFAULT;
        textureDesc.BindFlags            = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
        textureDesc.CPUAccessFlags       = 0;
        textureDesc.MiscFlags            = D3D11_RESOURCE_MISC_SHARED;

        ASSERT_TRUE(SUCCEEDED(
            d3d11Device->CreateTexture2D(&textureDesc, nullptr, &mOffscreenSurfaceD3D11Texture)));

        IDXGIResource *dxgiResource =
            DynamicCastComObject<IDXGIResource>(mOffscreenSurfaceD3D11Texture);
        ASSERT_NE(nullptr, dxgiResource);

        HANDLE sharedHandle = 0;
        ASSERT_TRUE(SUCCEEDED(dxgiResource->GetSharedHandle(&sharedHandle)));
        SafeRelease(dxgiResource);

        EGLint pBufferAttributes[] = {EGL_WIDTH,          mWindowWidth,       EGL_HEIGHT,
                                      mWindowWidth,       EGL_TEXTURE_TARGET, EGL_TEXTURE_2D,
                                      EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA,   EGL_NONE};

        mSurface = eglCreatePbufferFromClientBuffer(mDisplay, EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE,
                                                    sharedHandle, mConfig, pBufferAttributes);
        ASSERT_TRUE(EGL_NO_SURFACE != mSurface);
    }

    void makeCurrent() { ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, mSurface, mSurface, mContext)); }

    void TearDown() override
    {
        if (mDisplay != EGL_NO_DISPLAY)
        {
            eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

            if (mSurface != EGL_NO_SURFACE)
            {
                eglDestroySurface(mDisplay, mSurface);
                mSurface = EGL_NO_SURFACE;
            }

            if (mContext != EGL_NO_CONTEXT)
            {
                eglDestroyContext(mDisplay, mContext);
                mContext = EGL_NO_CONTEXT;
            }

            eglTerminate(mDisplay);
            mDisplay = EGL_NO_DISPLAY;
        }

        mOSWindow->destroy();
        SafeDelete(mOSWindow);

        SafeRelease(mOffscreenSurfaceD3D11Texture);
    }

    void drawQuadUsingGL()
    {
        GLuint m2DProgram;
        GLint mTexture2DUniformLocation;

        const std::string vertexShaderSource =
            SHADER_SOURCE(precision highp float; attribute vec4 position; varying vec2 texcoord;

                          void main()
                          {
                              gl_Position = vec4(position.xy, 0.0, 1.0);
                              texcoord = (position.xy * 0.5) + 0.5;
                          });

        const std::string fragmentShaderSource2D =
            SHADER_SOURCE(precision highp float; uniform sampler2D tex; varying vec2 texcoord;

                          void main()
                          {
                              gl_FragColor = texture2D(tex, texcoord);
                          });

        m2DProgram                = CompileProgram(vertexShaderSource, fragmentShaderSource2D);
        mTexture2DUniformLocation = glGetUniformLocation(m2DProgram, "tex");

        uint8_t textureInitData[16] = {
            255, 0,   0,   255,  // Red
            0,   255, 0,   255,  // Green
            0,   0,   255, 255,  // Blue
            255, 255, 0,   255   // Red + Green
        };

        // Create a simple RGBA texture
        GLuint tex = 0;
        glGenTextures(1, &tex);
        glBindTexture(GL_TEXTURE_2D, tex);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE,
                     textureInitData);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        ASSERT_GL_NO_ERROR();

        // Draw a quad using the texture
        glClear(GL_COLOR_BUFFER_BIT);
        glUseProgram(m2DProgram);
        glUniform1i(mTexture2DUniformLocation, 0);

        GLint positionLocation = glGetAttribLocation(m2DProgram, "position");
        glUseProgram(m2DProgram);
        const GLfloat vertices[] =
        {
            -1.0f,  1.0f, 0.5f,
            -1.0f, -1.0f, 0.5f,
             1.0f, -1.0f, 0.5f,
            -1.0f,  1.0f, 0.5f,
             1.0f, -1.0f, 0.5f,
             1.0f,  1.0f, 0.5f,
        };

        glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, 0, vertices);
        glEnableVertexAttribArray(positionLocation);

        glDrawArrays(GL_TRIANGLES, 0, 6);
        ASSERT_GL_NO_ERROR();

        glDeleteProgram(m2DProgram);
    }

    void checkPixelsUsingGL()
    {
        // Note that the texture is in BGRA format
        EXPECT_PIXEL_EQ(0, 0, 255, 0, 0, 255);                                  // Red
        EXPECT_PIXEL_EQ(mWindowWidth - 1, 0, 0, 255, 0, 255);                   // Green
        EXPECT_PIXEL_EQ(0, mWindowWidth - 1, 0, 0, 255, 255);                   // Blue
        EXPECT_PIXEL_EQ(mWindowWidth - 1, mWindowWidth - 1, 255, 255, 0, 255);  // Red + green
    }

    void checkPixelsUsingD3D(bool usingPresentPathFast)
    {
        ASSERT_NE(nullptr, mOffscreenSurfaceD3D11Texture);

        D3D11_TEXTURE2D_DESC textureDesc = {0};
        ID3D11Device *device;
        ID3D11DeviceContext *context;
        mOffscreenSurfaceD3D11Texture->GetDesc(&textureDesc);
        mOffscreenSurfaceD3D11Texture->GetDevice(&device);
        device->GetImmediateContext(&context);
        ASSERT_NE(nullptr, device);
        ASSERT_NE(nullptr, context);

        textureDesc.CPUAccessFlags  = D3D11_CPU_ACCESS_READ;
        textureDesc.Usage           = D3D11_USAGE_STAGING;
        textureDesc.BindFlags       = 0;
        textureDesc.MiscFlags       = 0;
        ID3D11Texture2D *cpuTexture = nullptr;
        ASSERT_TRUE(SUCCEEDED(device->CreateTexture2D(&textureDesc, nullptr, &cpuTexture)));

        context->CopyResource(cpuTexture, mOffscreenSurfaceD3D11Texture);

        D3D11_MAPPED_SUBRESOURCE mappedSubresource;
        context->Map(cpuTexture, 0, D3D11_MAP_READ, 0, &mappedSubresource);
        ASSERT_EQ(static_cast<UINT>(mWindowWidth * 4), mappedSubresource.RowPitch);
        ASSERT_EQ(static_cast<UINT>(mWindowWidth * mWindowWidth * 4), mappedSubresource.DepthPitch);

        angle::GLColor *byteData = reinterpret_cast<angle::GLColor *>(mappedSubresource.pData);

        // Note that the texture is in BGRA format, although the GLColor struct is RGBA
        GLColor expectedTopLeftPixel     = GLColor(0,   0, 255, 255);  // Red
        GLColor expectedTopRightPixel    = GLColor(0, 255,   0, 255);  // Green
        GLColor expectedBottomLeftPixel  = GLColor(255, 0,   0, 255);  // Blue
        GLColor expectedBottomRightPixel = GLColor(0, 255, 255, 255);  // Red + Green

        if (usingPresentPathFast)
        {
            // Invert the expected values
            GLColor tempTopLeft      = expectedTopLeftPixel;
            GLColor tempTopRight     = expectedTopRightPixel;
            expectedTopLeftPixel     = expectedBottomLeftPixel;
            expectedTopRightPixel    = expectedBottomRightPixel;
            expectedBottomLeftPixel  = tempTopLeft;
            expectedBottomRightPixel = tempTopRight;
        }

        EXPECT_EQ(expectedTopLeftPixel, byteData[0]);
        EXPECT_EQ(expectedTopRightPixel, byteData[(mWindowWidth - 1)]);
        EXPECT_EQ(expectedBottomLeftPixel, byteData[(mWindowWidth - 1) * mWindowWidth]);
        EXPECT_EQ(expectedBottomRightPixel,
                  byteData[(mWindowWidth - 1) * mWindowWidth + (mWindowWidth - 1)]);

        context->Unmap(cpuTexture, 0);
        SafeRelease(cpuTexture);
        SafeRelease(device);
        SafeRelease(context);
    }

    EGLDisplay mDisplay;
    EGLContext mContext;
    EGLSurface mSurface;
    ID3D11Texture2D *mOffscreenSurfaceD3D11Texture;
    EGLConfig mConfig;
    OSWindow *mOSWindow;
    GLint mWindowWidth;
};

// Test that rendering basic content onto a window surface when present path fast
// is enabled works as expected
TEST_P(EGLPresentPathD3D11, WindowPresentPathFast)
{
    initializeEGL(true);
    createWindowSurface();
    makeCurrent();

    drawQuadUsingGL();

    checkPixelsUsingGL();
}

// Test that rendering basic content onto a client buffer surface when present path fast
// works as expected, and is also oriented the correct way around
TEST_P(EGLPresentPathD3D11, ClientBufferPresentPathFast)
{
    initializeEGL(true);
    createPbufferFromClientBufferSurface();
    makeCurrent();

    drawQuadUsingGL();

    checkPixelsUsingGL();
    checkPixelsUsingD3D(true);
}

// Test that rendering basic content onto a window surface when present path fast
// is disabled works as expected
TEST_P(EGLPresentPathD3D11, WindowPresentPathCopy)
{
    initializeEGL(false);
    createWindowSurface();
    makeCurrent();

    drawQuadUsingGL();

    checkPixelsUsingGL();
}

// Test that rendering basic content onto a client buffer surface when present path
// fast is disabled works as expected, and is also oriented the correct way around
TEST_P(EGLPresentPathD3D11, ClientBufferPresentPathCopy)
{
    initializeEGL(false);
    createPbufferFromClientBufferSurface();
    makeCurrent();

    drawQuadUsingGL();

    checkPixelsUsingGL();
    checkPixelsUsingD3D(false);
}

ANGLE_INSTANTIATE_TEST(EGLPresentPathD3D11, ES2_D3D11(), ES2_D3D11_FL9_3());<commit_msg>Fix a bug in EGLPresentPathD3D11Test<commit_after>//
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

#include "test_utils/ANGLETest.h"

#include <cstdint>
#include "com_utils.h"
#include "OSWindow.h"
#include <d3d11.h>

using namespace angle;

class EGLPresentPathD3D11 : public testing::TestWithParam<PlatformParameters>
{
  protected:
    EGLPresentPathD3D11()
        : mDisplay(EGL_NO_DISPLAY),
          mContext(EGL_NO_CONTEXT),
          mSurface(EGL_NO_SURFACE),
          mOffscreenSurfaceD3D11Texture(nullptr),
          mConfig(0),
          mOSWindow(nullptr),
          mWindowWidth(0)
    {
    }

    void SetUp() override
    {
        mOSWindow    = CreateOSWindow();
        mWindowWidth = 64;
        mOSWindow->initialize("EGLPresentPathD3D11", mWindowWidth, mWindowWidth);
    }

    void initializeEGL(bool usePresentPathFast)
    {
        int clientVersion = GetParam().majorVersion;

        const char *extensionString =
            static_cast<const char *>(eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS));
        ASSERT_NE(nullptr, strstr(extensionString, "EGL_ANGLE_experimental_present_path"));

        PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT =
            reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(
                eglGetProcAddress("eglGetPlatformDisplayEXT"));
        ASSERT_NE(nullptr, eglGetPlatformDisplayEXT);

        // Set up EGL Display
        EGLint displayAttribs[] = {
            EGL_PLATFORM_ANGLE_TYPE_ANGLE, GetParam().getRenderer(),
            EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, GetParam().eglParameters.majorVersion,
            EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, GetParam().eglParameters.majorVersion,
            EGL_EXPERIMENTAL_PRESENT_PATH_ANGLE,
            usePresentPathFast ? EGL_EXPERIMENTAL_PRESENT_PATH_FAST_ANGLE
                               : EGL_EXPERIMENTAL_PRESENT_PATH_COPY_ANGLE,
            EGL_NONE};
        mDisplay =
            eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, displayAttribs);
        ASSERT_TRUE(EGL_NO_DISPLAY != mDisplay);
        ASSERT_EGL_TRUE(eglInitialize(mDisplay, NULL, NULL));

        // Choose the EGL config
        EGLint numConfigs;
        EGLint configAttribs[] = {EGL_RED_SIZE,
                                  8,
                                  EGL_GREEN_SIZE,
                                  8,
                                  EGL_BLUE_SIZE,
                                  8,
                                  EGL_ALPHA_SIZE,
                                  8,
                                  EGL_RENDERABLE_TYPE,
                                  clientVersion == 3 ? EGL_OPENGL_ES3_BIT : EGL_OPENGL_ES2_BIT,
                                  EGL_SURFACE_TYPE,
                                  EGL_PBUFFER_BIT,
                                  EGL_NONE};
        ASSERT_EGL_TRUE(eglChooseConfig(mDisplay, configAttribs, &mConfig, 1, &numConfigs));
        ASSERT_EQ(1, numConfigs);

        // Set up the EGL context
        EGLint contextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, clientVersion, EGL_NONE};
        mContext = eglCreateContext(mDisplay, mConfig, NULL, contextAttribs);
        ASSERT_TRUE(EGL_NO_CONTEXT != mContext);
    }

    void createWindowSurface()
    {
        mSurface = eglCreateWindowSurface(mDisplay, mConfig, mOSWindow->getNativeWindow(), nullptr);
    }

    void createPbufferFromClientBufferSurface()
    {
        EGLAttrib device      = 0;
        EGLAttrib angleDevice = 0;

        PFNEGLQUERYDISPLAYATTRIBEXTPROC queryDisplayAttribEXT;
        PFNEGLQUERYDEVICEATTRIBEXTPROC queryDeviceAttribEXT;

        const char *extensionString =
            static_cast<const char *>(eglQueryString(mDisplay, EGL_EXTENSIONS));
        EXPECT_TRUE(strstr(extensionString, "EGL_EXT_device_query"));

        queryDisplayAttribEXT =
            (PFNEGLQUERYDISPLAYATTRIBEXTPROC)eglGetProcAddress("eglQueryDisplayAttribEXT");
        queryDeviceAttribEXT =
            (PFNEGLQUERYDEVICEATTRIBEXTPROC)eglGetProcAddress("eglQueryDeviceAttribEXT");
        ASSERT_NE(nullptr, queryDisplayAttribEXT);
        ASSERT_NE(nullptr, queryDeviceAttribEXT);

        ASSERT_EGL_TRUE(queryDisplayAttribEXT(mDisplay, EGL_DEVICE_EXT, &angleDevice));
        ASSERT_EGL_TRUE(queryDeviceAttribEXT(reinterpret_cast<EGLDeviceEXT>(angleDevice),
                                             EGL_D3D11_DEVICE_ANGLE, &device));
        ID3D11Device *d3d11Device = reinterpret_cast<ID3D11Device *>(device);

        D3D11_TEXTURE2D_DESC textureDesc = {0};
        textureDesc.Width                = mWindowWidth;
        textureDesc.Height               = mWindowWidth;
        textureDesc.Format               = DXGI_FORMAT_B8G8R8A8_UNORM;
        textureDesc.MipLevels            = 1;
        textureDesc.ArraySize            = 1;
        textureDesc.SampleDesc.Count     = 1;
        textureDesc.SampleDesc.Quality   = 0;
        textureDesc.Usage                = D3D11_USAGE_DEFAULT;
        textureDesc.BindFlags            = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
        textureDesc.CPUAccessFlags       = 0;
        textureDesc.MiscFlags            = D3D11_RESOURCE_MISC_SHARED;

        ASSERT_TRUE(SUCCEEDED(
            d3d11Device->CreateTexture2D(&textureDesc, nullptr, &mOffscreenSurfaceD3D11Texture)));

        IDXGIResource *dxgiResource =
            DynamicCastComObject<IDXGIResource>(mOffscreenSurfaceD3D11Texture);
        ASSERT_NE(nullptr, dxgiResource);

        HANDLE sharedHandle = 0;
        ASSERT_TRUE(SUCCEEDED(dxgiResource->GetSharedHandle(&sharedHandle)));
        SafeRelease(dxgiResource);

        EGLint pBufferAttributes[] = {EGL_WIDTH,          mWindowWidth,       EGL_HEIGHT,
                                      mWindowWidth,       EGL_TEXTURE_TARGET, EGL_TEXTURE_2D,
                                      EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA,   EGL_NONE};

        mSurface = eglCreatePbufferFromClientBuffer(mDisplay, EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE,
                                                    sharedHandle, mConfig, pBufferAttributes);
        ASSERT_TRUE(EGL_NO_SURFACE != mSurface);
    }

    void makeCurrent() { ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, mSurface, mSurface, mContext)); }

    void TearDown() override
    {
        SafeRelease(mOffscreenSurfaceD3D11Texture);

        if (mDisplay != EGL_NO_DISPLAY)
        {
            eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

            if (mSurface != EGL_NO_SURFACE)
            {
                eglDestroySurface(mDisplay, mSurface);
                mSurface = EGL_NO_SURFACE;
            }

            if (mContext != EGL_NO_CONTEXT)
            {
                eglDestroyContext(mDisplay, mContext);
                mContext = EGL_NO_CONTEXT;
            }

            eglTerminate(mDisplay);
            mDisplay = EGL_NO_DISPLAY;
        }

        mOSWindow->destroy();
        SafeDelete(mOSWindow);
    }

    void drawQuadUsingGL()
    {
        GLuint m2DProgram;
        GLint mTexture2DUniformLocation;

        const std::string vertexShaderSource =
            SHADER_SOURCE(precision highp float; attribute vec4 position; varying vec2 texcoord;

                          void main()
                          {
                              gl_Position = vec4(position.xy, 0.0, 1.0);
                              texcoord = (position.xy * 0.5) + 0.5;
                          });

        const std::string fragmentShaderSource2D =
            SHADER_SOURCE(precision highp float; uniform sampler2D tex; varying vec2 texcoord;

                          void main()
                          {
                              gl_FragColor = texture2D(tex, texcoord);
                          });

        m2DProgram                = CompileProgram(vertexShaderSource, fragmentShaderSource2D);
        mTexture2DUniformLocation = glGetUniformLocation(m2DProgram, "tex");

        uint8_t textureInitData[16] = {
            255, 0,   0,   255,  // Red
            0,   255, 0,   255,  // Green
            0,   0,   255, 255,  // Blue
            255, 255, 0,   255   // Red + Green
        };

        // Create a simple RGBA texture
        GLuint tex = 0;
        glGenTextures(1, &tex);
        glBindTexture(GL_TEXTURE_2D, tex);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE,
                     textureInitData);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        ASSERT_GL_NO_ERROR();

        // Draw a quad using the texture
        glClear(GL_COLOR_BUFFER_BIT);
        glUseProgram(m2DProgram);
        glUniform1i(mTexture2DUniformLocation, 0);

        GLint positionLocation = glGetAttribLocation(m2DProgram, "position");
        glUseProgram(m2DProgram);
        const GLfloat vertices[] =
        {
            -1.0f,  1.0f, 0.5f,
            -1.0f, -1.0f, 0.5f,
             1.0f, -1.0f, 0.5f,
            -1.0f,  1.0f, 0.5f,
             1.0f, -1.0f, 0.5f,
             1.0f,  1.0f, 0.5f,
        };

        glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, 0, vertices);
        glEnableVertexAttribArray(positionLocation);

        glDrawArrays(GL_TRIANGLES, 0, 6);
        ASSERT_GL_NO_ERROR();

        glDeleteProgram(m2DProgram);
    }

    void checkPixelsUsingGL()
    {
        // Note that the texture is in BGRA format
        EXPECT_PIXEL_EQ(0, 0, 255, 0, 0, 255);                                  // Red
        EXPECT_PIXEL_EQ(mWindowWidth - 1, 0, 0, 255, 0, 255);                   // Green
        EXPECT_PIXEL_EQ(0, mWindowWidth - 1, 0, 0, 255, 255);                   // Blue
        EXPECT_PIXEL_EQ(mWindowWidth - 1, mWindowWidth - 1, 255, 255, 0, 255);  // Red + green
    }

    void checkPixelsUsingD3D(bool usingPresentPathFast)
    {
        ASSERT_NE(nullptr, mOffscreenSurfaceD3D11Texture);

        D3D11_TEXTURE2D_DESC textureDesc = {0};
        ID3D11Device *device;
        ID3D11DeviceContext *context;
        mOffscreenSurfaceD3D11Texture->GetDesc(&textureDesc);
        mOffscreenSurfaceD3D11Texture->GetDevice(&device);
        device->GetImmediateContext(&context);
        ASSERT_NE(nullptr, device);
        ASSERT_NE(nullptr, context);

        textureDesc.CPUAccessFlags  = D3D11_CPU_ACCESS_READ;
        textureDesc.Usage           = D3D11_USAGE_STAGING;
        textureDesc.BindFlags       = 0;
        textureDesc.MiscFlags       = 0;
        ID3D11Texture2D *cpuTexture = nullptr;
        ASSERT_TRUE(SUCCEEDED(device->CreateTexture2D(&textureDesc, nullptr, &cpuTexture)));

        context->CopyResource(cpuTexture, mOffscreenSurfaceD3D11Texture);

        D3D11_MAPPED_SUBRESOURCE mappedSubresource;
        context->Map(cpuTexture, 0, D3D11_MAP_READ, 0, &mappedSubresource);
        ASSERT_EQ(static_cast<UINT>(mWindowWidth * 4), mappedSubresource.RowPitch);
        ASSERT_EQ(static_cast<UINT>(mWindowWidth * mWindowWidth * 4), mappedSubresource.DepthPitch);

        angle::GLColor *byteData = reinterpret_cast<angle::GLColor *>(mappedSubresource.pData);

        // Note that the texture is in BGRA format, although the GLColor struct is RGBA
        GLColor expectedTopLeftPixel     = GLColor(0,   0, 255, 255);  // Red
        GLColor expectedTopRightPixel    = GLColor(0, 255,   0, 255);  // Green
        GLColor expectedBottomLeftPixel  = GLColor(255, 0,   0, 255);  // Blue
        GLColor expectedBottomRightPixel = GLColor(0, 255, 255, 255);  // Red + Green

        if (usingPresentPathFast)
        {
            // Invert the expected values
            GLColor tempTopLeft      = expectedTopLeftPixel;
            GLColor tempTopRight     = expectedTopRightPixel;
            expectedTopLeftPixel     = expectedBottomLeftPixel;
            expectedTopRightPixel    = expectedBottomRightPixel;
            expectedBottomLeftPixel  = tempTopLeft;
            expectedBottomRightPixel = tempTopRight;
        }

        EXPECT_EQ(expectedTopLeftPixel, byteData[0]);
        EXPECT_EQ(expectedTopRightPixel, byteData[(mWindowWidth - 1)]);
        EXPECT_EQ(expectedBottomLeftPixel, byteData[(mWindowWidth - 1) * mWindowWidth]);
        EXPECT_EQ(expectedBottomRightPixel,
                  byteData[(mWindowWidth - 1) * mWindowWidth + (mWindowWidth - 1)]);

        context->Unmap(cpuTexture, 0);
        SafeRelease(cpuTexture);
        SafeRelease(device);
        SafeRelease(context);
    }

    EGLDisplay mDisplay;
    EGLContext mContext;
    EGLSurface mSurface;
    ID3D11Texture2D *mOffscreenSurfaceD3D11Texture;
    EGLConfig mConfig;
    OSWindow *mOSWindow;
    GLint mWindowWidth;
};

// Test that rendering basic content onto a window surface when present path fast
// is enabled works as expected
TEST_P(EGLPresentPathD3D11, WindowPresentPathFast)
{
    initializeEGL(true);
    createWindowSurface();
    makeCurrent();

    drawQuadUsingGL();

    checkPixelsUsingGL();
}

// Test that rendering basic content onto a client buffer surface when present path fast
// works as expected, and is also oriented the correct way around
TEST_P(EGLPresentPathD3D11, ClientBufferPresentPathFast)
{
    initializeEGL(true);
    createPbufferFromClientBufferSurface();
    makeCurrent();

    drawQuadUsingGL();

    checkPixelsUsingGL();
    checkPixelsUsingD3D(true);
}

// Test that rendering basic content onto a window surface when present path fast
// is disabled works as expected
TEST_P(EGLPresentPathD3D11, WindowPresentPathCopy)
{
    initializeEGL(false);
    createWindowSurface();
    makeCurrent();

    drawQuadUsingGL();

    checkPixelsUsingGL();
}

// Test that rendering basic content onto a client buffer surface when present path
// fast is disabled works as expected, and is also oriented the correct way around
TEST_P(EGLPresentPathD3D11, ClientBufferPresentPathCopy)
{
    initializeEGL(false);
    createPbufferFromClientBufferSurface();
    makeCurrent();

    drawQuadUsingGL();

    checkPixelsUsingGL();
    checkPixelsUsingD3D(false);
}

ANGLE_INSTANTIATE_TEST(EGLPresentPathD3D11, ES2_D3D11(), ES2_D3D11_FL9_3());<|endoftext|>