<commit_before>/*************************************************************************
 *
 *  $RCSfile: AConnection.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2004-03-02 12:35:59 $
 *
 *  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 _CONNECTIVITY_ADO_ACONNECTION_HXX_
#define _CONNECTIVITY_ADO_ACONNECTION_HXX_

#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_
#include "OSubComponent.hxx"
#endif
#include <map>
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef _CONNECTIVITY_OTYPEINFO_HXX_
#include "OTypeInfo.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#include "ado/Awrapado.hxx"

namespace connectivity
{
    namespace ado
    {
        struct OExtendedTypeInfo
        {
            ::connectivity::OTypeInfo       aSimpleType;    // the general type info

            inline ::rtl::OUString getDBName() const { return aSimpleType.aTypeName; }
        };

        class WpADOConnection;
        class ODriver;
        class OCatalog;
        typedef ::std::multimap<DataTypeEnum, OExtendedTypeInfo*>       OTypeInfoMap;
        typedef connectivity::OMetaConnection                           OConnection_BASE;

        class OConnection : public OConnection_BASE,
                            public connectivity::OSubComponent<OConnection, OConnection_BASE>
        {
            friend class connectivity::OSubComponent<OConnection, OConnection_BASE>;

        protected:
            //====================================================================
            // Data attributes
            //====================================================================
            OTypeInfoMap                m_aTypeInfo;    //  vector containing an entry
                                                                                //  for each row returned by
                                                                                //  DatabaseMetaData.getTypeInfo.
            ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData >       m_xMetaData;

            connectivity::OWeakRefArray m_aStatements;  //  vector containing a list
                                                                                //  of all the Statement objects
                                                                                //  for this Connection
            ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier>      m_xCatalog;
            ODriver*                    m_pDriver;
        private:
            WpADOConnection*            m_pAdoConnection;
            OCatalog*                   m_pCatalog;
            sal_Int32                   m_nEngineType;
            sal_Bool                    m_bClosed;
            sal_Bool                    m_bAutocommit;

        protected:
            void buildTypeInfo() throw( ::com::sun::star::sdbc::SQLException);
        public:

            OConnection(const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info,
                    ODriver*        _pDriver) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            //  OConnection(const SQLHANDLE _pConnectionHandle);
            ~OConnection();
            void construct(const ::rtl::OUString& url,const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info);

            void closeAllStatements () throw( ::com::sun::star::sdbc::SQLException);

            //XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
            // XServiceInfo
            DECLARE_SERVICE_INFO();
            // OComponentHelper
            virtual void SAL_CALL disposing(void);
            // XInterface
            virtual void SAL_CALL release() throw(::com::sun::star::uno::RuntimeException);

            // XConnection
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL getAutoCommit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL commit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL rollback(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isClosed(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isReadOnly(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getCatalog(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getTransactionIsolation(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XCloseable
            virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XWarningsSupplier
            virtual ::com::sun::star::uno::Any SAL_CALL getWarnings(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearWarnings(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            //
            WpADOConnection* getConnection() { return m_pAdoConnection; }
            void setCatalog(const ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier>& _xCat) { m_xCatalog = _xCat; }
            void setCatalog(OCatalog* _pCatalog) { m_pCatalog = _pCatalog; }

            const OTypeInfoMap* getTypeInfo() const { return &m_aTypeInfo;}
            OCatalog* getAdoCatalog() const
            {
                if ( m_xCatalog.get().is() )
                    return m_pCatalog;
                return NULL;
            }

            sal_Int32 getEngineType()   const { return m_nEngineType; }
            ODriver*  getDriver()       const { return m_pDriver; }

            static const OExtendedTypeInfo* getTypeInfoFromType(const OTypeInfoMap& _rTypeInfo,
                               DataTypeEnum _nType,
                               const ::rtl::OUString& _sTypeName,
                               sal_Int32 _nPrecision,
                               sal_Int32 _nScale,
                               sal_Bool& _brForceToType);
        };
    }
}
#endif // _CONNECTIVITY_ADO_ACONNECTION_HXX_

<commit_msg>INTEGRATION: CWS insight01 (1.13.26); FILE MERGED 2004/06/01 13:27:56 oj 1.13.26.1: merge<commit_after>/*************************************************************************
 *
 *  $RCSfile: AConnection.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 17:11:23 $
 *
 *  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 _CONNECTIVITY_ADO_ACONNECTION_HXX_
#define _CONNECTIVITY_ADO_ACONNECTION_HXX_

#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_
#include "OSubComponent.hxx"
#endif
#include <map>
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef _CONNECTIVITY_OTYPEINFO_HXX_
#include "OTypeInfo.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#include "ado/Awrapado.hxx"

namespace connectivity
{
    namespace ado
    {
        struct OExtendedTypeInfo
        {
            ::connectivity::OTypeInfo       aSimpleType;    // the general type info
            DataTypeEnum                    eType;

            inline ::rtl::OUString getDBName() const { return aSimpleType.aTypeName; }
        };

        class WpADOConnection;
        class ODriver;
        class OCatalog;
        typedef ::std::multimap<DataTypeEnum, OExtendedTypeInfo*>       OTypeInfoMap;
        typedef connectivity::OMetaConnection                           OConnection_BASE;

        class OConnection : public OConnection_BASE,
                            public connectivity::OSubComponent<OConnection, OConnection_BASE>
        {
            friend class connectivity::OSubComponent<OConnection, OConnection_BASE>;

        protected:
            //====================================================================
            // Data attributes
            //====================================================================
            OTypeInfoMap                m_aTypeInfo;    //  vector containing an entry
                                                                                //  for each row returned by
                                                                                //  DatabaseMetaData.getTypeInfo.
            ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData >       m_xMetaData;

            connectivity::OWeakRefArray m_aStatements;  //  vector containing a list
                                                                                //  of all the Statement objects
                                                                                //  for this Connection
            ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier>      m_xCatalog;
            ODriver*                    m_pDriver;
        private:
            WpADOConnection*            m_pAdoConnection;
            OCatalog*                   m_pCatalog;
            sal_Int32                   m_nEngineType;
            sal_Bool                    m_bClosed;
            sal_Bool                    m_bAutocommit;

        protected:
            void buildTypeInfo() throw( ::com::sun::star::sdbc::SQLException);
        public:

            OConnection(const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info,
                    ODriver*        _pDriver) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            //  OConnection(const SQLHANDLE _pConnectionHandle);
            ~OConnection();
            void construct(const ::rtl::OUString& url,const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info);

            void closeAllStatements () throw( ::com::sun::star::sdbc::SQLException);

            //XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
            // XServiceInfo
            DECLARE_SERVICE_INFO();
            // OComponentHelper
            virtual void SAL_CALL disposing(void);
            // XInterface
            virtual void SAL_CALL release() throw(::com::sun::star::uno::RuntimeException);

            // XConnection
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL getAutoCommit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL commit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL rollback(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isClosed(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isReadOnly(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getCatalog(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getTransactionIsolation(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XCloseable
            virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XWarningsSupplier
            virtual ::com::sun::star::uno::Any SAL_CALL getWarnings(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearWarnings(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            //
            WpADOConnection* getConnection() { return m_pAdoConnection; }
            void setCatalog(const ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier>& _xCat) { m_xCatalog = _xCat; }
            void setCatalog(OCatalog* _pCatalog) { m_pCatalog = _pCatalog; }

            const OTypeInfoMap* getTypeInfo() const { return &m_aTypeInfo;}
            OCatalog* getAdoCatalog() const
            {
                if ( m_xCatalog.get().is() )
                    return m_pCatalog;
                return NULL;
            }

            sal_Int32 getEngineType()   const { return m_nEngineType; }
            ODriver*  getDriver()       const { return m_pDriver; }

            static const OExtendedTypeInfo* getTypeInfoFromType(const OTypeInfoMap& _rTypeInfo,
                               DataTypeEnum _nType,
                               const ::rtl::OUString& _sTypeName,
                               sal_Int32 _nPrecision,
                               sal_Int32 _nScale,
                               sal_Bool& _brForceToType);
        };
    }
}
#endif // _CONNECTIVITY_ADO_ACONNECTION_HXX_

<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : F2.cpp
 * Author  : Kazune Takahashi
 * Created : 6/15/2020, 11:46:33 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
    return true;
  }
  return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
    return true;
  }
  return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i{2LL}; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i{1LL}; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
constexpr int dx[4] = {1, 0, -1, 0};
constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- 2D, 3D, 4D vectors -----
// Referring to ymatsux-san's source code: https://atcoder.jp/contests/abc138/submissions/7018300

template <typename T>
vector<vector<T>> Make2DVector(size_t d0, size_t d1, T v = T{})
{
  return vector<vector<T>>(d0, vector<T>(d1, v));
}

template <typename T>
vector<vector<vector<T>>> Make3DVector(size_t d0, size_t d1, size_t d2, T v = T{})
{
  return vector<vector<vector<T>>>(d0, Make2DVector(d1, d2, v));
}

template <typename T>
vector<vector<vector<vector<T>>>> Make4DVector(size_t d0, size_t d1, size_t d2, size_t d3, T v = T{})
{
  return vector<vector<vector<vector<T>>>>(d0, Make3DVector(d1, d2, d3, v));
}

// ----- Solve -----

using Point = tuple<int, int>;

class Solve
{
  int H, W, K;
  vector<vector<int>> V;
  int sx, sy, gx, gy;

public:
  Solve(int H, int W) : H{H}, W{W}, V{Make2DVector(H, W, Infty<int>())}
  {
    cin >> K;
    cin >> sx >> sy >> gx >> gy;
    --sx;
    --sy;
    --gx;
    --gy;
    for (auto i{0}; i < H; ++i)
    {
      for (auto j{0}; j < W; ++j)
      {
        char c;
        cin >> c;
        if (c == '@')
        {
          V[i][j] = -1;
        }
      }
    }
  }

  void flush()
  {
    queue<Point> Q;
    Q.push(Point{sx, sy});
    V[sx][sy] = 0;
    while (!Q.empty())
    {
      auto p{Q.front()};
      auto [x, y] = p;
      Q.pop();
      for (auto k{0}; k < 4; ++k)
      {
        for (auto i{1}; i <= K; ++i)
        {
          auto nx{x + dx[k] * i};
          auto ny{y + dy[k] * i};
          if (!valid(nx, ny))
          {
            break;
          }
          else if (V[nx][ny] == Infty<int>())
          {
            V[nx][ny] = V[x][y] + 1;
            Q.push(Point{nx, ny});
          }
          else if (V[nx][ny] == V[x][y])
          {
            continue;
          }
        }
      }
    }
    auto ans{V[gx][gy]};
    if (ans == Infty<int>())
    {
      cout << -1 << endl;
    }
    else
    {
      cout << ans << endl;
    }
  }

private:
  bool valid(int x, int y)
  {
    return 0 <= x && x < H && 0 <= y && y < W && V[x][y] != -1;
  }
};

// ----- main() -----

int main()
{
  int H, W;
  cin >> H >> W;
  Solve solve(H, W);
  solve.flush();
}
<commit_msg>submit F2.cpp to 'F - Pond Skater' (abc170) [C++ (GCC 9.2.1)]<commit_after>#define DEBUG 1
/**
 * File    : F2.cpp
 * Author  : Kazune Takahashi
 * Created : 6/15/2020, 11:46:33 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
    return true;
  }
  return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
    return true;
  }
  return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i{2LL}; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i{1LL}; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
constexpr int dx[4] = {1, 0, -1, 0};
constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- 2D, 3D, 4D vectors -----
// Referring to ymatsux-san's source code: https://atcoder.jp/contests/abc138/submissions/7018300

template <typename T>
vector<vector<T>> Make2DVector(size_t d0, size_t d1, T v = T{})
{
  return vector<vector<T>>(d0, vector<T>(d1, v));
}

template <typename T>
vector<vector<vector<T>>> Make3DVector(size_t d0, size_t d1, size_t d2, T v = T{})
{
  return vector<vector<vector<T>>>(d0, Make2DVector(d1, d2, v));
}

template <typename T>
vector<vector<vector<vector<T>>>> Make4DVector(size_t d0, size_t d1, size_t d2, size_t d3, T v = T{})
{
  return vector<vector<vector<vector<T>>>>(d0, Make3DVector(d1, d2, d3, v));
}

// ----- Solve -----

using Point = tuple<int, int>;

class Solve
{
  int H, W, K;
  vector<vector<int>> V;
  int sx, sy, gx, gy;

public:
  Solve(int H, int W) : H{H}, W{W}, V{Make2DVector(H, W, Infty<int>())}
  {
    cin >> K;
    cin >> sx >> sy >> gx >> gy;
    --sx;
    --sy;
    --gx;
    --gy;
    for (auto i{0}; i < H; ++i)
    {
      for (auto j{0}; j < W; ++j)
      {
        char c;
        cin >> c;
        if (c == '@')
        {
          V[i][j] = -1;
        }
      }
    }
  }

  void flush()
  {
    queue<Point> Q;
    Q.push(Point{sx, sy});
    V[sx][sy] = 0;
    while (!Q.empty())
    {
      auto p{Q.front()};
      auto [x, y] = p;
      Q.pop();
      for (auto k{0}; k < 4; ++k)
      {
        for (auto i{1}; i <= K; ++i)
        {
          auto nx{x + dx[k] * i};
          auto ny{y + dy[k] * i};
          if (!valid(nx, ny))
          {
            break;
          }
          else if (V[nx][ny] == Infty<int>())
          {
            V[nx][ny] = V[x][y] + 1;
            Q.push(Point{nx, ny});
          }
          else if (V[nx][ny] <= V[x][y] + 1)
          {
            continue;
          }
        }
      }
    }
    auto ans{V[gx][gy]};
    if (ans == Infty<int>())
    {
      cout << -1 << endl;
    }
    else
    {
      cout << ans << endl;
    }
  }

private:
  bool valid(int x, int y)
  {
    return 0 <= x && x < H && 0 <= y && y < W && V[x][y] != -1;
  }
};

// ----- main() -----

int main()
{
  int H, W;
  cin >> H >> W;
  Solve solve(H, W);
  solve.flush();
}
<|endoftext|>


<commit_before>#include "game/apocresources/apocpalette.h"
#include "framework/palette.h"
#include "framework/data.h"
#include "framework/logger.h"

namespace OpenApoc
{

sp<Palette> loadApocPalette(Data &data, const UString fileName)
{
	auto f = data.fs.open(fileName);
	if (!f)
		return nullptr;
	auto numEntries = f.size() / 3;
	auto p = std::make_shared<Palette>(numEntries);
	for (unsigned int i = 0; i < numEntries; i++)
	{
		uint8_t colour[3];
		Colour c;

		f.read(reinterpret_cast<char *>(&colour), 3);
		if (!f)
			break;
		if (i == 0)
			c = {0, 0, 0, 0};
		else
		{
			/* Scale from 0-64 to 0-255 */
			uint8_t r = colour[0] << 2 | (colour[0] >> 4 & 0x3);
			uint8_t g = colour[1] << 2 | (colour[1] >> 4 & 0x3);
			uint8_t b = colour[2] << 2 | (colour[2] >> 4 & 0x3);
			uint8_t a = 255;
			c = {r, g, b, a};
		}
		p->SetColour(i, c);
	}

	return p;
}

struct PcxHeader
{
	uint8_t Identifier;      /* PCX Id Number (Always 0x0A) */
	uint8_t Version;         /* Version Number */
	uint8_t Encoding;        /* Encoding Format */
	uint8_t BitsPerPixel;    /* Bits per Pixel */
	uint16_t XStart;         /* Left of image */
	uint16_t YStart;         /* Top of Image */
	uint16_t XEnd;           /* Right of Image */
	uint16_t YEnd;           /* Bottom of image */
	uint16_t HorzRes;        /* Horizontal Resolution */
	uint16_t VertRes;        /* Vertical Resolution */
	uint8_t Palette[48];     /* 16-Color EGA Palette */
	uint8_t Reserved1;       /* Reserved (Always 0) */
	uint8_t NumBitPlanes;    /* Number of Bit Planes */
	uint16_t BytesPerLine;   /* Bytes per Scan-line */
	uint16_t PaletteType;    /* Palette Type */
	uint16_t HorzScreenSize; /* Horizontal Screen Size */
	uint16_t VertScreenSize; /* Vertical Screen Size */
	uint8_t Reserved2[54];   /* Reserved (Always 0) */
};

static const uint8_t PcxIdentifier = 0x0A;

static_assert(sizeof(struct PcxHeader) == 128, "PcxHeader unexpected size");

sp<Palette> loadPCXPalette(Data &data, const UString fileName)
{
	auto length = fileName.length();
	if (length < 4 || fileName.substr(length - 4, 4).toUpper() != ".PCX")
	{
		LogInfo("Skipping file \"%s\" as it doesn't look like a .pcx", fileName.c_str());
		return nullptr;
	}

	auto file = data.fs.open(fileName);
	if (!file)
	{
		LogInfo("File \"%s\" failed to be opened", fileName.c_str());
		return nullptr;
	}

	// We only support images with 256-colour palettes, so even if it has a pcx header supported
	// files will never be smaller than sizeof(header) + sizeof(palette)
	if (file.size() < sizeof(PcxHeader) + 256 * 3)
	{
		LogInfo("File \"%s\" has size %zu - too small for header and palette", fileName.c_str(),
		        file.size());
		return nullptr;
	}

	PcxHeader header;

	file.read(reinterpret_cast<char *>(&header), sizeof(header));
	if (!file)
	{
		LogInfo("File \"%s\" failed to read PCX header", fileName.c_str());
		return nullptr;
	}

	if (header.Identifier != PcxIdentifier)
	{
		LogInfo("File \"%s\" doesn't have PCX header magic", fileName.c_str());
		return nullptr;
	}

	if (header.BitsPerPixel != 8)
	{
		LogInfo("File \"%s\" has non-8-bit image", fileName.c_str());
		return nullptr;
	}

	file.seekg(file.size() - (256 * 3));

	auto p = std::make_shared<Palette>(256);

	for (unsigned int i = 0; i < 256; i++)
	{
		uint8_t colour[3];
		Colour c;

		file.read(reinterpret_cast<char *>(&colour), 3);
		if (!file)
		{
			LogWarning("Unexpected EOF at index %u", i);
			return nullptr;
		}
		if (i == 0)
			c = {0, 0, 0, 0};
		else
			c = {static_cast<uint8_t>(colour[0]), static_cast<uint8_t>(colour[1]),
			     static_cast<uint8_t>(colour[2]), 255};
		p->SetColour(i, c);
	}

	return p;
}

}; // namespace OpenApoc
<commit_msg>Fix typo in comment<commit_after>#include "game/apocresources/apocpalette.h"
#include "framework/palette.h"
#include "framework/data.h"
#include "framework/logger.h"

namespace OpenApoc
{

sp<Palette> loadApocPalette(Data &data, const UString fileName)
{
	auto f = data.fs.open(fileName);
	if (!f)
		return nullptr;
	auto numEntries = f.size() / 3;
	auto p = std::make_shared<Palette>(numEntries);
	for (unsigned int i = 0; i < numEntries; i++)
	{
		uint8_t colour[3];
		Colour c;

		f.read(reinterpret_cast<char *>(&colour), 3);
		if (!f)
			break;
		if (i == 0)
			c = {0, 0, 0, 0};
		else
		{
			/* Scale from 0-63 to 0-255 */
			uint8_t r = colour[0] << 2 | (colour[0] >> 4 & 0x3);
			uint8_t g = colour[1] << 2 | (colour[1] >> 4 & 0x3);
			uint8_t b = colour[2] << 2 | (colour[2] >> 4 & 0x3);
			uint8_t a = 255;
			c = {r, g, b, a};
		}
		p->SetColour(i, c);
	}

	return p;
}

struct PcxHeader
{
	uint8_t Identifier;      /* PCX Id Number (Always 0x0A) */
	uint8_t Version;         /* Version Number */
	uint8_t Encoding;        /* Encoding Format */
	uint8_t BitsPerPixel;    /* Bits per Pixel */
	uint16_t XStart;         /* Left of image */
	uint16_t YStart;         /* Top of Image */
	uint16_t XEnd;           /* Right of Image */
	uint16_t YEnd;           /* Bottom of image */
	uint16_t HorzRes;        /* Horizontal Resolution */
	uint16_t VertRes;        /* Vertical Resolution */
	uint8_t Palette[48];     /* 16-Color EGA Palette */
	uint8_t Reserved1;       /* Reserved (Always 0) */
	uint8_t NumBitPlanes;    /* Number of Bit Planes */
	uint16_t BytesPerLine;   /* Bytes per Scan-line */
	uint16_t PaletteType;    /* Palette Type */
	uint16_t HorzScreenSize; /* Horizontal Screen Size */
	uint16_t VertScreenSize; /* Vertical Screen Size */
	uint8_t Reserved2[54];   /* Reserved (Always 0) */
};

static const uint8_t PcxIdentifier = 0x0A;

static_assert(sizeof(struct PcxHeader) == 128, "PcxHeader unexpected size");

sp<Palette> loadPCXPalette(Data &data, const UString fileName)
{
	auto length = fileName.length();
	if (length < 4 || fileName.substr(length - 4, 4).toUpper() != ".PCX")
	{
		LogInfo("Skipping file \"%s\" as it doesn't look like a .pcx", fileName.c_str());
		return nullptr;
	}

	auto file = data.fs.open(fileName);
	if (!file)
	{
		LogInfo("File \"%s\" failed to be opened", fileName.c_str());
		return nullptr;
	}

	// We only support images with 256-colour palettes, so even if it has a pcx header supported
	// files will never be smaller than sizeof(header) + sizeof(palette)
	if (file.size() < sizeof(PcxHeader) + 256 * 3)
	{
		LogInfo("File \"%s\" has size %zu - too small for header and palette", fileName.c_str(),
		        file.size());
		return nullptr;
	}

	PcxHeader header;

	file.read(reinterpret_cast<char *>(&header), sizeof(header));
	if (!file)
	{
		LogInfo("File \"%s\" failed to read PCX header", fileName.c_str());
		return nullptr;
	}

	if (header.Identifier != PcxIdentifier)
	{
		LogInfo("File \"%s\" doesn't have PCX header magic", fileName.c_str());
		return nullptr;
	}

	if (header.BitsPerPixel != 8)
	{
		LogInfo("File \"%s\" has non-8-bit image", fileName.c_str());
		return nullptr;
	}

	file.seekg(file.size() - (256 * 3));

	auto p = std::make_shared<Palette>(256);

	for (unsigned int i = 0; i < 256; i++)
	{
		uint8_t colour[3];
		Colour c;

		file.read(reinterpret_cast<char *>(&colour), 3);
		if (!file)
		{
			LogWarning("Unexpected EOF at index %u", i);
			return nullptr;
		}
		if (i == 0)
			c = {0, 0, 0, 0};
		else
			c = {static_cast<uint8_t>(colour[0]), static_cast<uint8_t>(colour[1]),
			     static_cast<uint8_t>(colour[2]), 255};
		p->SetColour(i, c);
	}

	return p;
}

}; // namespace OpenApoc
<|endoftext|>


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

// Get basic type definitions.
#define IPC_MESSAGE_IMPL
#include "content/common/content_message_generator.h"

// Generate constructors.
#include "ipc/struct_constructor_macros.h"
#include "content/common/content_message_generator.h"

// Generate destructors.
#include "ipc/struct_destructor_macros.h"
#include "content/common/content_message_generator.h"

#if defined(USE_AURA) && defined(OS_WIN)
#include "ui/gfx/native_widget_types.h"

namespace IPC {
// TODO(beng): Figure out why this is needed, fix that issue and remove
//             this. Brett and I were unable to figure out why, but he
//             thought this should be harmless.
template <>
struct ParamTraits<gfx::PluginWindowHandle> {
  typedef gfx::PluginWindowHandle param_type;
  static void Write(Message* m, const param_type& p) {
    m->WriteUInt32(reinterpret_cast<uint32>(p));
  }
  static bool Read(const Message* m, void** iter, param_type* r) {
    DCHECK_EQ(sizeof(param_type), sizeof(uint32));
    return m->ReadUInt32(iter, reinterpret_cast<uint32*>(r));
  }
  static void Log(const param_type& p, std::string* l) {
    l->append(StringPrintf("0x%X", p));
  }
};
}  // namespace IPC
#endif

// Generate param traits write methods.
#include "ipc/param_traits_write_macros.h"
namespace IPC {
#include "content/common/content_message_generator.h"
}  // namespace IPC

// Generate param traits read methods.
#include "ipc/param_traits_read_macros.h"
namespace IPC {
#include "content/common/content_message_generator.h"
}  // namespace IPC

// Generate param traits log methods.
#include "ipc/param_traits_log_macros.h"
namespace IPC {
#include "content/common/content_message_generator.h"
}  // namespace IPC
<commit_msg>fix win_aura TBR=akalin<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Get basic type definitions.
#define IPC_MESSAGE_IMPL
#include "content/common/content_message_generator.h"

// Generate constructors.
#include "ipc/struct_constructor_macros.h"
#include "content/common/content_message_generator.h"

// Generate destructors.
#include "ipc/struct_destructor_macros.h"
#include "content/common/content_message_generator.h"

#if defined(USE_AURA) && defined(OS_WIN)
#include "ui/gfx/native_widget_types.h"

namespace IPC {
// TODO(beng): Figure out why this is needed, fix that issue and remove
//             this. Brett and I were unable to figure out why, but he
//             thought this should be harmless.
template <>
struct ParamTraits<gfx::PluginWindowHandle> {
  typedef gfx::PluginWindowHandle param_type;
  static void Write(Message* m, const param_type& p) {
    m->WriteUInt32(reinterpret_cast<uint32>(p));
  }
  static bool Read(const Message* m, PickleIterator* iter, param_type* r) {
    DCHECK_EQ(sizeof(param_type), sizeof(uint32));
    return m->ReadUInt32(iter, reinterpret_cast<uint32*>(r));
  }
  static void Log(const param_type& p, std::string* l) {
    l->append(StringPrintf("0x%X", p));
  }
};
}  // namespace IPC
#endif

// Generate param traits write methods.
#include "ipc/param_traits_write_macros.h"
namespace IPC {
#include "content/common/content_message_generator.h"
}  // namespace IPC

// Generate param traits read methods.
#include "ipc/param_traits_read_macros.h"
namespace IPC {
#include "content/common/content_message_generator.h"
}  // namespace IPC

// Generate param traits log methods.
#include "ipc/param_traits_log_macros.h"
namespace IPC {
#include "content/common/content_message_generator.h"
}  // namespace IPC
<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "base/string_util.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/webui/ntp/new_tab_ui.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"

using content::WebContents;

class ExtensionInstallUIBrowserTest : public ExtensionBrowserTest {
 public:
  // Checks that a theme info bar is currently visible and issues an undo to
  // revert to the previous theme.
  void VerifyThemeInfoBarAndUndoInstall() {
    TabContentsWrapper* tab = browser()->GetSelectedTabContentsWrapper();
    ASSERT_TRUE(tab);
    InfoBarTabHelper* infobar_helper = tab->infobar_tab_helper();
    ASSERT_EQ(1U, infobar_helper->infobar_count());
    ConfirmInfoBarDelegate* delegate = infobar_helper->
        GetInfoBarDelegateAt(0)->AsConfirmInfoBarDelegate();
    ASSERT_TRUE(delegate);
    delegate->Cancel();
    ASSERT_EQ(0U, infobar_helper->infobar_count());
  }

  const Extension* GetTheme() const {
    return ThemeServiceFactory::GetThemeForProfile(browser()->profile());
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       TestThemeInstallUndoResetsToDefault) {
  // Install theme once and undo to verify we go back to default theme.
  FilePath theme_crx = PackExtension(test_data_dir_.AppendASCII("theme"));
  ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 1));
  const Extension* theme = GetTheme();
  ASSERT_TRUE(theme);
  std::string theme_id = theme->id();
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, GetTheme());

  // Set the same theme twice and undo to verify we go back to default theme.
  // We set the |expected_change| to zero in these 'InstallExtensionWithUI'
  // calls since the theme has already been installed above and this is an
  // overinstall to set the active theme.
  ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 0));
  theme = GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_id, theme->id());
  ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 0));
  theme = GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_id, theme->id());
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, GetTheme());
}

IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       TestThemeInstallUndoResetsToPreviousTheme) {
  // Install first theme.
  FilePath theme_path = test_data_dir_.AppendASCII("theme");
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 1));
  const Extension* theme = GetTheme();
  ASSERT_TRUE(theme);
  std::string theme_id = theme->id();

  // Then install second theme.
  FilePath theme_path2 = test_data_dir_.AppendASCII("theme2");
  ASSERT_TRUE(InstallExtensionWithUI(theme_path2, 1));
  const Extension* theme2 = GetTheme();
  ASSERT_TRUE(theme2);
  EXPECT_FALSE(theme_id == theme2->id());

  // Undo second theme will revert to first theme.
  VerifyThemeInfoBarAndUndoInstall();
  EXPECT_EQ(theme, GetTheme());
}

IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       AppInstallConfirmation) {
  int num_tabs = browser()->tab_count();

  FilePath app_dir = test_data_dir_.AppendASCII("app");
  ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(app_dir, 1,
                                                browser()->profile()));

  if (NewTabUI::ShouldShowApps()) {
    EXPECT_EQ(num_tabs + 1, browser()->tab_count());
    WebContents* web_contents = browser()->GetSelectedWebContents();
    ASSERT_TRUE(web_contents);
    EXPECT_TRUE(StartsWithASCII(web_contents->GetURL().spec(),
                                "chrome://newtab/", false));
  } else {
    // TODO(xiyuan): Figure out how to test extension installed bubble?
  }
}

IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       AppInstallConfirmation_Incognito) {
  Profile* incognito_profile = browser()->profile()->GetOffTheRecordProfile();
  Browser* incognito_browser = Browser::GetOrCreateTabbedBrowser(
      incognito_profile);

  int num_incognito_tabs = incognito_browser->tab_count();
  int num_normal_tabs = browser()->tab_count();

  FilePath app_dir = test_data_dir_.AppendASCII("app");
  ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(app_dir, 1,
                                                incognito_profile));

  EXPECT_EQ(num_incognito_tabs, incognito_browser->tab_count());
  if (NewTabUI::ShouldShowApps()) {
    EXPECT_EQ(num_normal_tabs + 1, browser()->tab_count());
    WebContents* web_contents = browser()->GetSelectedWebContents();
    ASSERT_TRUE(web_contents);
    EXPECT_TRUE(StartsWithASCII(web_contents->GetURL().spec(),
                                "chrome://newtab/", false));
  } else {
    // TODO(xiyuan): Figure out how to test extension installed bubble?
  }
}
<commit_msg>Disable failing test (ExtensionInstallUIBrowserTest.TestThemeInstallUndoResetsToDefault) on Linux due to persistent failures on bot chromium.chromiumos : Linux.<commit_after>// Copyright (c) 2012 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 "base/string_util.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/webui/ntp/new_tab_ui.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"

using content::WebContents;

class ExtensionInstallUIBrowserTest : public ExtensionBrowserTest {
 public:
  // Checks that a theme info bar is currently visible and issues an undo to
  // revert to the previous theme.
  void VerifyThemeInfoBarAndUndoInstall() {
    TabContentsWrapper* tab = browser()->GetSelectedTabContentsWrapper();
    ASSERT_TRUE(tab);
    InfoBarTabHelper* infobar_helper = tab->infobar_tab_helper();
    ASSERT_EQ(1U, infobar_helper->infobar_count());
    ConfirmInfoBarDelegate* delegate = infobar_helper->
        GetInfoBarDelegateAt(0)->AsConfirmInfoBarDelegate();
    ASSERT_TRUE(delegate);
    delegate->Cancel();
    ASSERT_EQ(0U, infobar_helper->infobar_count());
  }

  const Extension* GetTheme() const {
    return ThemeServiceFactory::GetThemeForProfile(browser()->profile());
  }
};

#if defined(OS_LINUX)
// Fails consistently on bot chromium.chromiumos \ Linux.
// See: http://crbug.com/120647.
#define MAYBE_TestThemeInstallUndoResetsToDefault DISABLED_TestThemeInstallUndoResetsToDefault
#else
#define MAYBE_TestThemeInstallUndoResetsToDefault TestThemeInstallUndoResetsToDefault
#endif

IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       MAYBE_TestThemeInstallUndoResetsToDefault) {
  // Install theme once and undo to verify we go back to default theme.
  FilePath theme_crx = PackExtension(test_data_dir_.AppendASCII("theme"));
  ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 1));
  const Extension* theme = GetTheme();
  ASSERT_TRUE(theme);
  std::string theme_id = theme->id();
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, GetTheme());

  // Set the same theme twice and undo to verify we go back to default theme.
  // We set the |expected_change| to zero in these 'InstallExtensionWithUI'
  // calls since the theme has already been installed above and this is an
  // overinstall to set the active theme.
  ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 0));
  theme = GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_id, theme->id());
  ASSERT_TRUE(InstallExtensionWithUI(theme_crx, 0));
  theme = GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_id, theme->id());
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, GetTheme());
}

IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       TestThemeInstallUndoResetsToPreviousTheme) {
  // Install first theme.
  FilePath theme_path = test_data_dir_.AppendASCII("theme");
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 1));
  const Extension* theme = GetTheme();
  ASSERT_TRUE(theme);
  std::string theme_id = theme->id();

  // Then install second theme.
  FilePath theme_path2 = test_data_dir_.AppendASCII("theme2");
  ASSERT_TRUE(InstallExtensionWithUI(theme_path2, 1));
  const Extension* theme2 = GetTheme();
  ASSERT_TRUE(theme2);
  EXPECT_FALSE(theme_id == theme2->id());

  // Undo second theme will revert to first theme.
  VerifyThemeInfoBarAndUndoInstall();
  EXPECT_EQ(theme, GetTheme());
}

IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       AppInstallConfirmation) {
  int num_tabs = browser()->tab_count();

  FilePath app_dir = test_data_dir_.AppendASCII("app");
  ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(app_dir, 1,
                                                browser()->profile()));

  if (NewTabUI::ShouldShowApps()) {
    EXPECT_EQ(num_tabs + 1, browser()->tab_count());
    WebContents* web_contents = browser()->GetSelectedWebContents();
    ASSERT_TRUE(web_contents);
    EXPECT_TRUE(StartsWithASCII(web_contents->GetURL().spec(),
                                "chrome://newtab/", false));
  } else {
    // TODO(xiyuan): Figure out how to test extension installed bubble?
  }
}

IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       AppInstallConfirmation_Incognito) {
  Profile* incognito_profile = browser()->profile()->GetOffTheRecordProfile();
  Browser* incognito_browser = Browser::GetOrCreateTabbedBrowser(
      incognito_profile);

  int num_incognito_tabs = incognito_browser->tab_count();
  int num_normal_tabs = browser()->tab_count();

  FilePath app_dir = test_data_dir_.AppendASCII("app");
  ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(app_dir, 1,
                                                incognito_profile));

  EXPECT_EQ(num_incognito_tabs, incognito_browser->tab_count());
  if (NewTabUI::ShouldShowApps()) {
    EXPECT_EQ(num_normal_tabs + 1, browser()->tab_count());
    WebContents* web_contents = browser()->GetSelectedWebContents();
    ASSERT_TRUE(web_contents);
    EXPECT_TRUE(StartsWithASCII(web_contents->GetURL().spec(),
                                "chrome://newtab/", false));
  } else {
    // TODO(xiyuan): Figure out how to test extension installed bubble?
  }
}
<|endoftext|>


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

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

#include <vector>

#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "chrome/browser/geolocation/wifi_data_provider_common.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {
class MockWlanApi : public Win32WifiDataProvider::WlanApiInterface {
 public:
  MockWlanApi() : calls_(0), bool_return_(true) {
  }
  virtual bool GetAccessPointData(WifiData::AccessPointDataSet* data) {
    ++calls_;
    *data = data_out_;
    return bool_return_;
  }
  int calls_;
  bool bool_return_;
  WifiData::AccessPointDataSet data_out_;
};

class MockPollingPolicy : public PollingPolicyInterface {
 public:
  virtual void UpdatePollingInterval(bool scan_results_differ) {
    results_differed_.push_back(scan_results_differ);
  }
  virtual int PollingInterval() { return 1; }
  std::vector<bool> results_differed_;
};

// Stops the specified (nested) message loop when the listener is called back.
class MessageLoopQuitListener
    : public Win32WifiDataProvider::ListenerInterface {
 public:
  explicit MessageLoopQuitListener(MessageLoop* message_loop)
      : message_loop_to_quit_(message_loop) {
    assert(message_loop_to_quit_ != NULL);
  }
  // ListenerInterface
  virtual void DeviceDataUpdateAvailable(
      DeviceDataProvider<WifiData>* provider) {
    // We expect the callback to come from the provider's internal worker
    // thread. This is not a strict requirement, just a lot of the complexity
    // here is predicated on the need to cope with this scenario!
    EXPECT_NE(MessageLoop::current(), message_loop_to_quit_);
    provider_ = provider;
    // Can't call Quit() directly on another thread's message loop.
    message_loop_to_quit_->PostTask(FROM_HERE, new MessageLoop::QuitTask);
  }
  MessageLoop* message_loop_to_quit_;
  DeviceDataProvider<WifiData>* provider_;
};

// Main test fixture
class Win32WifiDataProviderTest : public testing::Test {
 public:
  static Win32WifiDataProvider* CreateWin32WifiDataProvider(
      MockWlanApi** wlan_api_out) {
    Win32WifiDataProvider* provider = new Win32WifiDataProvider;
    *wlan_api_out = new MockWlanApi;
    provider->inject_mock_wlan_api(*wlan_api_out);  // Takes ownership.
    provider->inject_mock_polling_policy(new MockPollingPolicy);  // ditto
    return provider;
  }
  virtual void SetUp() {
    provider_.reset(CreateWin32WifiDataProvider(&wlan_api_));
  }
  virtual void TearDown() {
    provider_.reset(NULL);
  }

 protected:
  MessageLoop main_message_loop_;
  scoped_ptr<Win32WifiDataProvider> provider_;
  MockWlanApi* wlan_api_;
};

WifiDataProviderImplBase* CreateWin32WifiDataProviderStatic() {
  MockWlanApi* wlan_api;
  return Win32WifiDataProviderTest::CreateWin32WifiDataProvider(&wlan_api);
}
}  // namespace

TEST_F(Win32WifiDataProviderTest, CreateDestroy) {
  // Test fixture members were SetUp correctly.
  EXPECT_EQ(&main_message_loop_, MessageLoop::current());
  EXPECT_TRUE(NULL != provider_.get());
  EXPECT_TRUE(NULL != wlan_api_);
}

TEST_F(Win32WifiDataProviderTest, StartThread) {
  EXPECT_TRUE(provider_->StartDataProvider());
  provider_.reset(NULL);  // Stop()s the thread.
  SUCCEED();
}

TEST_F(Win32WifiDataProviderTest, DoAnEmptyScan) {
  MessageLoopQuitListener quit_listener(&main_message_loop_);
  provider_->AddListener(&quit_listener);
  EXPECT_TRUE(provider_->StartDataProvider());
  main_message_loop_.Run();
  EXPECT_EQ(1, wlan_api_->calls_);
  WifiData data;
  EXPECT_TRUE(provider_->GetData(&data));
  EXPECT_EQ(0, data.access_point_data.size());
}

TEST_F(Win32WifiDataProviderTest, DoScanWithResults) {
  MessageLoopQuitListener quit_listener(&main_message_loop_);
  provider_->AddListener(&quit_listener);
  AccessPointData single_access_point;
  single_access_point.age = 1;
  single_access_point.channel = 2;
  single_access_point.mac_address = 3;
  single_access_point.radio_signal_strength = 4;
  single_access_point.signal_to_noise = 5;
  single_access_point.ssid = L"foossid";
  wlan_api_->data_out_.insert(single_access_point);

  EXPECT_TRUE(provider_->StartDataProvider());
  main_message_loop_.Run();
  EXPECT_EQ(1, wlan_api_->calls_);
  WifiData data;
  EXPECT_TRUE(provider_->GetData(&data));
  EXPECT_EQ(1, data.access_point_data.size());
  EXPECT_EQ(single_access_point.age, data.access_point_data.begin()->age);
  EXPECT_EQ(single_access_point.ssid, data.access_point_data.begin()->ssid);
}

TEST_F(Win32WifiDataProviderTest, StartThreadViaDeviceDataProvider) {
  MessageLoopQuitListener quit_listener(&main_message_loop_);
  DeviceDataProvider<WifiData>::SetFactory(CreateWin32WifiDataProviderStatic);
  DeviceDataProvider<WifiData>::Register(&quit_listener);
  main_message_loop_.Run();
  DeviceDataProvider<WifiData>::Unregister(&quit_listener);
  DeviceDataProvider<WifiData>::ResetFactory();
}
<commit_msg>Fix flaky test causing tree to go red<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

#include <vector>

#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "chrome/browser/geolocation/wifi_data_provider_common.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {
class MockWlanApi : public Win32WifiDataProvider::WlanApiInterface {
 public:
  MockWlanApi() : calls_(0), bool_return_(true) {
  }
  virtual bool GetAccessPointData(WifiData::AccessPointDataSet* data) {
    ++calls_;
    *data = data_out_;
    return bool_return_;
  }
  int calls_;
  bool bool_return_;
  WifiData::AccessPointDataSet data_out_;
};

class MockPollingPolicy : public PollingPolicyInterface {
 public:
  virtual void UpdatePollingInterval(bool scan_results_differ) {
    results_differed_.push_back(scan_results_differ);
  }
  virtual int PollingInterval() { return 1; }
  std::vector<bool> results_differed_;
};

// Stops the specified (nested) message loop when the listener is called back.
class MessageLoopQuitListener
    : public Win32WifiDataProvider::ListenerInterface {
 public:
  explicit MessageLoopQuitListener(MessageLoop* message_loop)
      : message_loop_to_quit_(message_loop) {
    assert(message_loop_to_quit_ != NULL);
  }
  // ListenerInterface
  virtual void DeviceDataUpdateAvailable(
      DeviceDataProvider<WifiData>* provider) {
    // We expect the callback to come from the provider's internal worker
    // thread. This is not a strict requirement, just a lot of the complexity
    // here is predicated on the need to cope with this scenario!
    EXPECT_NE(MessageLoop::current(), message_loop_to_quit_);
    provider_ = provider;
    // Can't call Quit() directly on another thread's message loop.
    message_loop_to_quit_->PostTask(FROM_HERE, new MessageLoop::QuitTask);
  }
  MessageLoop* message_loop_to_quit_;
  DeviceDataProvider<WifiData>* provider_;
};

// Main test fixture
class Win32WifiDataProviderTest : public testing::Test {
 public:
  static Win32WifiDataProvider* CreateWin32WifiDataProvider(
      MockWlanApi** wlan_api_out) {
    Win32WifiDataProvider* provider = new Win32WifiDataProvider;
    *wlan_api_out = new MockWlanApi;
    provider->inject_mock_wlan_api(*wlan_api_out);  // Takes ownership.
    provider->inject_mock_polling_policy(new MockPollingPolicy);  // ditto
    return provider;
  }
  virtual void SetUp() {
    provider_.reset(CreateWin32WifiDataProvider(&wlan_api_));
  }
  virtual void TearDown() {
    provider_.reset(NULL);
  }

 protected:
  MessageLoop main_message_loop_;
  scoped_ptr<Win32WifiDataProvider> provider_;
  MockWlanApi* wlan_api_;
};

WifiDataProviderImplBase* CreateWin32WifiDataProviderStatic() {
  MockWlanApi* wlan_api;
  return Win32WifiDataProviderTest::CreateWin32WifiDataProvider(&wlan_api);
}
}  // namespace

TEST_F(Win32WifiDataProviderTest, CreateDestroy) {
  // Test fixture members were SetUp correctly.
  EXPECT_EQ(&main_message_loop_, MessageLoop::current());
  EXPECT_TRUE(NULL != provider_.get());
  EXPECT_TRUE(NULL != wlan_api_);
}

TEST_F(Win32WifiDataProviderTest, StartThread) {
  EXPECT_TRUE(provider_->StartDataProvider());
  provider_.reset(NULL);  // Stop()s the thread.
  SUCCEED();
}

TEST_F(Win32WifiDataProviderTest, DoAnEmptyScan) {
  MessageLoopQuitListener quit_listener(&main_message_loop_);
  provider_->AddListener(&quit_listener);
  EXPECT_TRUE(provider_->StartDataProvider());
  main_message_loop_.Run();
  // Check we had at least one call. The worker thread may have raced ahead
  // and made multiple calls.
  EXPECT_GT(wlan_api_->calls_, 0);
  WifiData data;
  EXPECT_TRUE(provider_->GetData(&data));
  EXPECT_EQ(0, data.access_point_data.size());
  provider_->RemoveListener(&quit_listener);
}

TEST_F(Win32WifiDataProviderTest, DoScanWithResults) {
  MessageLoopQuitListener quit_listener(&main_message_loop_);
  provider_->AddListener(&quit_listener);
  AccessPointData single_access_point;
  single_access_point.age = 1;
  single_access_point.channel = 2;
  single_access_point.mac_address = 3;
  single_access_point.radio_signal_strength = 4;
  single_access_point.signal_to_noise = 5;
  single_access_point.ssid = L"foossid";
  wlan_api_->data_out_.insert(single_access_point);

  EXPECT_TRUE(provider_->StartDataProvider());
  main_message_loop_.Run();
  EXPECT_GT(wlan_api_->calls_, 0);
  WifiData data;
  EXPECT_TRUE(provider_->GetData(&data));
  EXPECT_EQ(1, data.access_point_data.size());
  EXPECT_EQ(single_access_point.age, data.access_point_data.begin()->age);
  EXPECT_EQ(single_access_point.ssid, data.access_point_data.begin()->ssid);
  provider_->RemoveListener(&quit_listener);
}

TEST_F(Win32WifiDataProviderTest, StartThreadViaDeviceDataProvider) {
  MessageLoopQuitListener quit_listener(&main_message_loop_);
  DeviceDataProvider<WifiData>::SetFactory(CreateWin32WifiDataProviderStatic);
  DeviceDataProvider<WifiData>::Register(&quit_listener);
  main_message_loop_.Run();
  DeviceDataProvider<WifiData>::Unregister(&quit_listener);
  DeviceDataProvider<WifiData>::ResetFactory();
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef SMDLL_HXX
#define SMDLL_HXX

#include <tools/resid.hxx>
#include <sfx2/sfxdefs.hxx>
#include "smmod.hxx"

class SmData;
class SfxMedium;
class SfxFilter;

class SmDLL
{
    static bool bInitialized;
public:
    static void Init();
    static void Exit();

    static sal_uLong DetectFilter( SfxMedium& rMedium, const SfxFilter **ppFilter,
                               SfxFilterFlags nMust, SfxFilterFlags nDont );
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>DetectFilter declared but not defined<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef SMDLL_HXX
#define SMDLL_HXX

#include <tools/resid.hxx>
#include <sfx2/sfxdefs.hxx>
#include "smmod.hxx"

class SmData;
class SfxMedium;
class SfxFilter;

class SmDLL
{
    static bool bInitialized;
public:
    static void Init();
    static void Exit();
};

#endif

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


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

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#include "mitkBoundingShapeVtkMapper3D.h"
#include "../DataManagement/mitkBoundingShapeUtil.h"
#include <mitkBaseProperty.h>
#include <vtkAppendPolyData.h>
#include <vtkCamera.h>
#include <vtkCubeSource.h>
#include <vtkDataSetMapper.h>
#include <vtkMath.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkSphereSource.h>
#include <vtkTransformFilter.h>

namespace mitk
{
  class BoundingShapeVtkMapper3D::Impl
  {
    class LocalStorage : public Mapper::BaseLocalStorage
    {
    public:
      LocalStorage();
      ~LocalStorage();

      LocalStorage(const LocalStorage &) = delete;
      LocalStorage &operator=(const LocalStorage &) = delete;

      std::vector<vtkSmartPointer<vtkSphereSource>> Handles;
      vtkSmartPointer<vtkActor> Actor;
      vtkSmartPointer<vtkActor> HandleActor;
      vtkSmartPointer<vtkActor> SelectedHandleActor;
      vtkSmartPointer<vtkPropAssembly> PropAssembly;
    };

  public:
    Impl() : DistanceFromCam(1.0)
    {
      Point3D initialPoint;
      initialPoint.Fill(0);

      for (int i = 0; i < 6; ++i)
        HandlePropertyList.push_back(Handle(initialPoint, i, GetHandleIndices(i)));
    }

    double DistanceFromCam;
    std::vector<Handle> HandlePropertyList;
    mitk::LocalStorageHandler<LocalStorage> LocalStorageHandler;
  };
}

mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::LocalStorage()
  : Actor(vtkSmartPointer<vtkActor>::New()),
    HandleActor(vtkSmartPointer<vtkActor>::New()),
    SelectedHandleActor(vtkSmartPointer<vtkActor>::New()),
    PropAssembly(vtkSmartPointer<vtkPropAssembly>::New())
{
  for (int i = 0; i < 6; i++)
    Handles.push_back(vtkSmartPointer<vtkSphereSource>::New());
}

mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::~LocalStorage()
{
}

void mitk::BoundingShapeVtkMapper3D::SetDefaultProperties(DataNode *node, BaseRenderer *renderer, bool overwrite)
{
  Superclass::SetDefaultProperties(node, renderer, overwrite);
}

mitk::BoundingShapeVtkMapper3D::BoundingShapeVtkMapper3D() : m_Impl(new Impl)
{
}

mitk::BoundingShapeVtkMapper3D::~BoundingShapeVtkMapper3D()
{
  delete m_Impl;
}

void mitk::BoundingShapeVtkMapper3D::ApplyColorAndOpacityProperties(BaseRenderer *renderer, vtkActor *actor)
{
  Superclass::ApplyColorAndOpacityProperties(renderer, actor);
}

void mitk::BoundingShapeVtkMapper3D::ApplyBoundingShapeProperties(BaseRenderer *renderer, vtkActor *actor)
{
  if (actor == nullptr)
    return;

  auto dataNode = this->GetDataNode();

  if (dataNode == nullptr)
    return;

  bool isVisible = false;
  dataNode->GetBoolProperty("Bounding Shape.3D Rendering", isVisible, renderer);

  actor->SetVisibility(isVisible);

  float lineWidth = 1.0f;
  dataNode->GetFloatProperty("Bounding Shape.Line.Width", lineWidth, renderer);

  auto property = actor->GetProperty();
  property->SetLineWidth(lineWidth);
}

void mitk::BoundingShapeVtkMapper3D::GenerateDataForRenderer(BaseRenderer *renderer)
{
  auto dataNode = this->GetDataNode();

  if (dataNode == nullptr)
    return;

  vtkCamera *camera = renderer->GetVtkRenderer()->GetActiveCamera();

  auto localStorage = m_Impl->LocalStorageHandler.GetLocalStorage(renderer);
  bool needGenerateData = localStorage->GetLastGenerateDataTime() < dataNode->GetMTime();
  double distance = camera->GetDistance();

  if (std::abs(distance - m_Impl->DistanceFromCam) > mitk::eps)
  {
    m_Impl->DistanceFromCam = distance;
    needGenerateData = true;
  }

  if (needGenerateData)
  {
    bool isVisible = true;
    dataNode->GetVisibility(isVisible, renderer);

    if (!isVisible)
    {
      localStorage->Actor->VisibilityOff();
      return;
    }

    // set the input-object at time t for the mapper
    GeometryData *geometryData = dynamic_cast<GeometryData *>(dataNode->GetData());
    if (geometryData == nullptr)
      return;

    mitk::BaseGeometry::Pointer geometry = geometryData->GetGeometry();
    mitk::Vector3D spacing = geometry->GetSpacing();

    // calculate cornerpoints from geometry
    std::vector<Point3D> cornerPoints = GetCornerPoints(geometry, true);

    Point3D p0 = cornerPoints[0];
    Point3D p1 = cornerPoints[1];
    Point3D p2 = cornerPoints[2];
    Point3D p4 = cornerPoints[4];

    Point3D extent;
    extent[0] =
      sqrt((p0[0] - p4[0]) * (p0[0] - p4[0]) + (p0[1] - p4[1]) * (p0[1] - p4[1]) + (p0[2] - p4[2]) * (p0[2] - p4[2]));
    extent[1] =
      sqrt((p0[0] - p2[0]) * (p0[0] - p2[0]) + (p0[1] - p2[1]) * (p0[1] - p2[1]) + (p0[2] - p2[2]) * (p0[2] - p2[2]));
    extent[2] =
      sqrt((p0[0] - p1[0]) * (p0[0] - p1[0]) + (p0[1] - p1[1]) * (p0[1] - p1[1]) + (p0[2] - p1[2]) * (p0[2] - p1[2]));

    // calculate center based on half way of the distance between two opposing cornerpoints
    mitk::Point3D center = CalcAvgPoint(cornerPoints[7], cornerPoints[0]);

    if (m_Impl->HandlePropertyList.size() == 6)
    {
      // set handle positions
      Point3D pointLeft = CalcAvgPoint(cornerPoints[5], cornerPoints[6]);
      Point3D pointRight = CalcAvgPoint(cornerPoints[1], cornerPoints[2]);
      Point3D pointTop = CalcAvgPoint(cornerPoints[0], cornerPoints[6]);
      Point3D pointBottom = CalcAvgPoint(cornerPoints[7], cornerPoints[1]);
      Point3D pointFront = CalcAvgPoint(cornerPoints[2], cornerPoints[7]);
      Point3D pointBack = CalcAvgPoint(cornerPoints[4], cornerPoints[1]);

      m_Impl->HandlePropertyList[0].SetPosition(pointLeft);
      m_Impl->HandlePropertyList[1].SetPosition(pointRight);
      m_Impl->HandlePropertyList[2].SetPosition(pointTop);
      m_Impl->HandlePropertyList[3].SetPosition(pointBottom);
      m_Impl->HandlePropertyList[4].SetPosition(pointFront);
      m_Impl->HandlePropertyList[5].SetPosition(pointBack);
    }

    auto cube = vtkCubeSource::New();
    cube->SetXLength(extent[0] / spacing[0]);
    cube->SetYLength(extent[1] / spacing[1]);
    cube->SetZLength(extent[2] / spacing[2]);

    // calculates translation based on offset+extent not on the transformation matrix
    vtkSmartPointer<vtkMatrix4x4> imageTransform = geometry->GetVtkTransform()->GetMatrix();
    auto translation = vtkSmartPointer<vtkTransform>::New();
    translation->Translate(center[0] - imageTransform->GetElement(0, 3),
                           center[1] - imageTransform->GetElement(1, 3),
                           center[2] - imageTransform->GetElement(2, 3));

    auto transform = vtkSmartPointer<vtkTransform>::New();
    transform->SetMatrix(imageTransform);
    transform->PostMultiply();
    transform->Concatenate(translation);
    transform->Update();
    cube->Update();

    auto transformFilter = vtkSmartPointer<vtkTransformFilter>::New();
    transformFilter->SetInputData(cube->GetOutput());
    transformFilter->SetTransform(transform);
    transformFilter->Update();
    cube->Delete();

    vtkSmartPointer<vtkPolyData> polydata = transformFilter->GetPolyDataOutput();
    if (polydata == nullptr)
    {
      localStorage->Actor->VisibilityOff();
      return;
    }

    mitk::DoubleProperty::Pointer handleSizeProperty =
      dynamic_cast<mitk::DoubleProperty *>(this->GetDataNode()->GetProperty("Bounding Shape.Handle Size Factor"));

    ScalarType initialHandleSize;
    if (handleSizeProperty != nullptr)
      initialHandleSize = handleSizeProperty->GetValue();
    else
      initialHandleSize = 1.0 / 40.0;

    double handlesize =
      ((camera->GetDistance() * std::tan(vtkMath::RadiansFromDegrees(camera->GetViewAngle()))) / 2.0) *
      initialHandleSize;

    if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->HandleActor))
      localStorage->PropAssembly->RemovePart(localStorage->HandleActor);
    if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->Actor))
      localStorage->PropAssembly->RemovePart(localStorage->Actor);

    auto selectedhandlemapper = vtkSmartPointer<vtkPolyDataMapper>::New();
    auto appendPoly = vtkSmartPointer<vtkAppendPolyData>::New();

    mitk::IntProperty::Pointer activeHandleId =
      dynamic_cast<mitk::IntProperty *>(dataNode->GetProperty("Bounding Shape.Active Handle ID"));

    int i = 0;
    for (auto &handle : localStorage->Handles)
    {
      Point3D handlecenter = m_Impl->HandlePropertyList[i].GetPosition();
      handle->SetCenter(handlecenter[0], handlecenter[1], handlecenter[2]);
      handle->SetRadius(handlesize);
      handle->Update();
      if (activeHandleId == nullptr)
      {
        appendPoly->AddInputConnection(handle->GetOutputPort());
      }
      else
      {
        if (activeHandleId->GetValue() != m_Impl->HandlePropertyList[i].GetIndex())
        {
          appendPoly->AddInputConnection(handle->GetOutputPort());
        }
        else
        {
          selectedhandlemapper->SetInputData(handle->GetOutput());
          localStorage->SelectedHandleActor->SetMapper(selectedhandlemapper);
          localStorage->SelectedHandleActor->GetProperty()->SetColor(0, 1, 0);
          localStorage->SelectedHandleActor->GetMapper()->SetInputDataObject(handle->GetOutput());
          localStorage->PropAssembly->AddPart(localStorage->SelectedHandleActor);
        }
      }
      i++;
    }
    appendPoly->Update();

    auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
    mapper->SetInputData(polydata);

    auto handlemapper = vtkSmartPointer<vtkPolyDataMapper>::New();
    handlemapper->SetInputData(appendPoly->GetOutput());

    localStorage->Actor->SetMapper(mapper);
    localStorage->Actor->GetMapper()->SetInputDataObject(polydata);
    localStorage->Actor->GetProperty()->SetOpacity(0.3);

    mitk::ColorProperty::Pointer selectedColor = dynamic_cast<mitk::ColorProperty *>(dataNode->GetProperty("color"));
    if (selectedColor != nullptr)
    {
      mitk::Color color = selectedColor->GetColor();
      localStorage->Actor->GetProperty()->SetColor(color[0], color[1], color[2]);
    }

    localStorage->HandleActor->SetMapper(handlemapper);
    if (activeHandleId == nullptr)
    {
      localStorage->HandleActor->GetProperty()->SetColor(1, 1, 1);
    }
    else
    {
      localStorage->HandleActor->GetProperty()->SetColor(1, 0, 0);
    }

    localStorage->HandleActor->GetMapper()->SetInputDataObject(appendPoly->GetOutput());

    this->ApplyColorAndOpacityProperties(renderer, localStorage->Actor);
    this->ApplyBoundingShapeProperties(renderer, localStorage->Actor);

    this->ApplyColorAndOpacityProperties(renderer, localStorage->HandleActor);
    this->ApplyBoundingShapeProperties(renderer, localStorage->HandleActor);

    this->ApplyColorAndOpacityProperties(renderer, localStorage->SelectedHandleActor);
    this->ApplyBoundingShapeProperties(renderer, localStorage->SelectedHandleActor);

    // apply properties read from the PropertyList
    // this->ApplyProperties(localStorage->m_Actor, renderer);
    // this->ApplyProperties(localStorage->m_HandleActor, renderer);
    // this->ApplyProperties(localStorage->m_SelectedHandleActor, renderer);

    localStorage->Actor->VisibilityOn();
    localStorage->HandleActor->VisibilityOn();
    localStorage->SelectedHandleActor->VisibilityOn();

    localStorage->PropAssembly->AddPart(localStorage->Actor);
    localStorage->PropAssembly->AddPart(localStorage->HandleActor);
    localStorage->PropAssembly->VisibilityOn();

    localStorage->UpdateGenerateDataTime();
  }
}
vtkProp *mitk::BoundingShapeVtkMapper3D::GetVtkProp(BaseRenderer *renderer)
{
  return m_Impl->LocalStorageHandler.GetLocalStorage(renderer)->PropAssembly;
}
<commit_msg>removed Superclass call to visualize colored handles<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#include "mitkBoundingShapeVtkMapper3D.h"
#include "../DataManagement/mitkBoundingShapeUtil.h"
#include <mitkBaseProperty.h>
#include <vtkAppendPolyData.h>
#include <vtkCamera.h>
#include <vtkCubeSource.h>
#include <vtkDataSetMapper.h>
#include <vtkMath.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkSphereSource.h>
#include <vtkTransformFilter.h>

namespace mitk
{
  class BoundingShapeVtkMapper3D::Impl
  {
    class LocalStorage : public Mapper::BaseLocalStorage
    {
    public:
      LocalStorage();
      ~LocalStorage();

      LocalStorage(const LocalStorage &) = delete;
      LocalStorage &operator=(const LocalStorage &) = delete;

      std::vector<vtkSmartPointer<vtkSphereSource>> Handles;
      vtkSmartPointer<vtkActor> Actor;
      vtkSmartPointer<vtkActor> HandleActor;
      vtkSmartPointer<vtkActor> SelectedHandleActor;
      vtkSmartPointer<vtkPropAssembly> PropAssembly;
    };

  public:
    Impl() : DistanceFromCam(1.0)
    {
      Point3D initialPoint;
      initialPoint.Fill(0);

      for (int i = 0; i < 6; ++i)
        HandlePropertyList.push_back(Handle(initialPoint, i, GetHandleIndices(i)));
    }

    double DistanceFromCam;
    std::vector<Handle> HandlePropertyList;
    mitk::LocalStorageHandler<LocalStorage> LocalStorageHandler;
  };
}

mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::LocalStorage()
  : Actor(vtkSmartPointer<vtkActor>::New()),
    HandleActor(vtkSmartPointer<vtkActor>::New()),
    SelectedHandleActor(vtkSmartPointer<vtkActor>::New()),
    PropAssembly(vtkSmartPointer<vtkPropAssembly>::New())
{
  for (int i = 0; i < 6; i++)
    Handles.push_back(vtkSmartPointer<vtkSphereSource>::New());
}

mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::~LocalStorage()
{
}

void mitk::BoundingShapeVtkMapper3D::SetDefaultProperties(DataNode *node, BaseRenderer *renderer, bool overwrite)
{
  Superclass::SetDefaultProperties(node, renderer, overwrite);
}

mitk::BoundingShapeVtkMapper3D::BoundingShapeVtkMapper3D() : m_Impl(new Impl)
{
}

mitk::BoundingShapeVtkMapper3D::~BoundingShapeVtkMapper3D()
{
  delete m_Impl;
}

void mitk::BoundingShapeVtkMapper3D::ApplyColorAndOpacityProperties(BaseRenderer *renderer, vtkActor *actor)
{
  //Superclass::ApplyColorAndOpacityProperties(renderer, actor);
}

void mitk::BoundingShapeVtkMapper3D::ApplyBoundingShapeProperties(BaseRenderer *renderer, vtkActor *actor)
{
  if (actor == nullptr)
    return;

  auto dataNode = this->GetDataNode();

  if (dataNode == nullptr)
    return;

  bool isVisible = false;
  dataNode->GetBoolProperty("Bounding Shape.3D Rendering", isVisible, renderer);

  actor->SetVisibility(isVisible);

  float lineWidth = 1.0f;
  dataNode->GetFloatProperty("Bounding Shape.Line.Width", lineWidth, renderer);

  auto property = actor->GetProperty();
  property->SetLineWidth(lineWidth);
}

void mitk::BoundingShapeVtkMapper3D::GenerateDataForRenderer(BaseRenderer *renderer)
{
  auto dataNode = this->GetDataNode();

  if (dataNode == nullptr)
    return;

  vtkCamera *camera = renderer->GetVtkRenderer()->GetActiveCamera();

  auto localStorage = m_Impl->LocalStorageHandler.GetLocalStorage(renderer);
  bool needGenerateData = localStorage->GetLastGenerateDataTime() < dataNode->GetMTime();
  double distance = camera->GetDistance();

  if (std::abs(distance - m_Impl->DistanceFromCam) > mitk::eps)
  {
    m_Impl->DistanceFromCam = distance;
    needGenerateData = true;
  }

  if (needGenerateData)
  {
    bool isVisible = true;
    dataNode->GetVisibility(isVisible, renderer);

    if (!isVisible)
    {
      localStorage->Actor->VisibilityOff();
      return;
    }

    // set the input-object at time t for the mapper
    GeometryData *geometryData = dynamic_cast<GeometryData *>(dataNode->GetData());
    if (geometryData == nullptr)
      return;

    mitk::BaseGeometry::Pointer geometry = geometryData->GetGeometry();
    mitk::Vector3D spacing = geometry->GetSpacing();

    // calculate cornerpoints from geometry
    std::vector<Point3D> cornerPoints = GetCornerPoints(geometry, true);

    Point3D p0 = cornerPoints[0];
    Point3D p1 = cornerPoints[1];
    Point3D p2 = cornerPoints[2];
    Point3D p4 = cornerPoints[4];

    Point3D extent;
    extent[0] =
      sqrt((p0[0] - p4[0]) * (p0[0] - p4[0]) + (p0[1] - p4[1]) * (p0[1] - p4[1]) + (p0[2] - p4[2]) * (p0[2] - p4[2]));
    extent[1] =
      sqrt((p0[0] - p2[0]) * (p0[0] - p2[0]) + (p0[1] - p2[1]) * (p0[1] - p2[1]) + (p0[2] - p2[2]) * (p0[2] - p2[2]));
    extent[2] =
      sqrt((p0[0] - p1[0]) * (p0[0] - p1[0]) + (p0[1] - p1[1]) * (p0[1] - p1[1]) + (p0[2] - p1[2]) * (p0[2] - p1[2]));

    // calculate center based on half way of the distance between two opposing cornerpoints
    mitk::Point3D center = CalcAvgPoint(cornerPoints[7], cornerPoints[0]);

    if (m_Impl->HandlePropertyList.size() == 6)
    {
      // set handle positions
      Point3D pointLeft = CalcAvgPoint(cornerPoints[5], cornerPoints[6]);
      Point3D pointRight = CalcAvgPoint(cornerPoints[1], cornerPoints[2]);
      Point3D pointTop = CalcAvgPoint(cornerPoints[0], cornerPoints[6]);
      Point3D pointBottom = CalcAvgPoint(cornerPoints[7], cornerPoints[1]);
      Point3D pointFront = CalcAvgPoint(cornerPoints[2], cornerPoints[7]);
      Point3D pointBack = CalcAvgPoint(cornerPoints[4], cornerPoints[1]);

      m_Impl->HandlePropertyList[0].SetPosition(pointLeft);
      m_Impl->HandlePropertyList[1].SetPosition(pointRight);
      m_Impl->HandlePropertyList[2].SetPosition(pointTop);
      m_Impl->HandlePropertyList[3].SetPosition(pointBottom);
      m_Impl->HandlePropertyList[4].SetPosition(pointFront);
      m_Impl->HandlePropertyList[5].SetPosition(pointBack);
    }

    auto cube = vtkCubeSource::New();
    cube->SetXLength(extent[0] / spacing[0]);
    cube->SetYLength(extent[1] / spacing[1]);
    cube->SetZLength(extent[2] / spacing[2]);

    // calculates translation based on offset+extent not on the transformation matrix
    vtkSmartPointer<vtkMatrix4x4> imageTransform = geometry->GetVtkTransform()->GetMatrix();
    auto translation = vtkSmartPointer<vtkTransform>::New();
    translation->Translate(center[0] - imageTransform->GetElement(0, 3),
                           center[1] - imageTransform->GetElement(1, 3),
                           center[2] - imageTransform->GetElement(2, 3));

    auto transform = vtkSmartPointer<vtkTransform>::New();
    transform->SetMatrix(imageTransform);
    transform->PostMultiply();
    transform->Concatenate(translation);
    transform->Update();
    cube->Update();

    auto transformFilter = vtkSmartPointer<vtkTransformFilter>::New();
    transformFilter->SetInputData(cube->GetOutput());
    transformFilter->SetTransform(transform);
    transformFilter->Update();
    cube->Delete();

    vtkSmartPointer<vtkPolyData> polydata = transformFilter->GetPolyDataOutput();
    if (polydata == nullptr)
    {
      localStorage->Actor->VisibilityOff();
      return;
    }

    mitk::DoubleProperty::Pointer handleSizeProperty =
      dynamic_cast<mitk::DoubleProperty *>(this->GetDataNode()->GetProperty("Bounding Shape.Handle Size Factor"));

    ScalarType initialHandleSize;
    if (handleSizeProperty != nullptr)
      initialHandleSize = handleSizeProperty->GetValue();
    else
      initialHandleSize = 1.0 / 40.0;

    double handlesize =
      ((camera->GetDistance() * std::tan(vtkMath::RadiansFromDegrees(camera->GetViewAngle()))) / 2.0) *
      initialHandleSize;

    if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->HandleActor))
      localStorage->PropAssembly->RemovePart(localStorage->HandleActor);
    if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->Actor))
      localStorage->PropAssembly->RemovePart(localStorage->Actor);

    auto selectedhandlemapper = vtkSmartPointer<vtkPolyDataMapper>::New();
    auto appendPoly = vtkSmartPointer<vtkAppendPolyData>::New();

    mitk::IntProperty::Pointer activeHandleId =
      dynamic_cast<mitk::IntProperty *>(dataNode->GetProperty("Bounding Shape.Active Handle ID"));

    int i = 0;
    for (auto &handle : localStorage->Handles)
    {
      Point3D handlecenter = m_Impl->HandlePropertyList[i].GetPosition();
      handle->SetCenter(handlecenter[0], handlecenter[1], handlecenter[2]);
      handle->SetRadius(handlesize);
      handle->Update();
      if (activeHandleId == nullptr)
      {
        appendPoly->AddInputConnection(handle->GetOutputPort());
      }
      else
      {
        if (activeHandleId->GetValue() != m_Impl->HandlePropertyList[i].GetIndex())
        {
          appendPoly->AddInputConnection(handle->GetOutputPort());
        }
        else
        {
          selectedhandlemapper->SetInputData(handle->GetOutput());
          localStorage->SelectedHandleActor->SetMapper(selectedhandlemapper);
          localStorage->SelectedHandleActor->GetProperty()->SetColor(0, 1, 0);
          localStorage->SelectedHandleActor->GetMapper()->SetInputDataObject(handle->GetOutput());
          localStorage->PropAssembly->AddPart(localStorage->SelectedHandleActor);
        }
      }
      i++;
    }
    appendPoly->Update();

    auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
    mapper->SetInputData(polydata);

    auto handlemapper = vtkSmartPointer<vtkPolyDataMapper>::New();
    handlemapper->SetInputData(appendPoly->GetOutput());

    localStorage->Actor->SetMapper(mapper);
    localStorage->Actor->GetMapper()->SetInputDataObject(polydata);
    localStorage->Actor->GetProperty()->SetOpacity(0.3);

    mitk::ColorProperty::Pointer selectedColor = dynamic_cast<mitk::ColorProperty *>(dataNode->GetProperty("color"));
    if (selectedColor != nullptr)
    {
      mitk::Color color = selectedColor->GetColor();
      localStorage->Actor->GetProperty()->SetColor(color[0], color[1], color[2]);
    }

    localStorage->HandleActor->SetMapper(handlemapper);
    if (activeHandleId == nullptr)
    {
      localStorage->HandleActor->GetProperty()->SetColor(1, 1, 1);
    }
    else
    {
      localStorage->HandleActor->GetProperty()->SetColor(1, 0, 0);
    }

    localStorage->HandleActor->GetMapper()->SetInputDataObject(appendPoly->GetOutput());

    this->ApplyColorAndOpacityProperties(renderer, localStorage->Actor);
    this->ApplyBoundingShapeProperties(renderer, localStorage->Actor);

    this->ApplyColorAndOpacityProperties(renderer, localStorage->HandleActor);
    this->ApplyBoundingShapeProperties(renderer, localStorage->HandleActor);

    this->ApplyColorAndOpacityProperties(renderer, localStorage->SelectedHandleActor);
    this->ApplyBoundingShapeProperties(renderer, localStorage->SelectedHandleActor);

    // apply properties read from the PropertyList
    // this->ApplyProperties(localStorage->m_Actor, renderer);
    // this->ApplyProperties(localStorage->m_HandleActor, renderer);
    // this->ApplyProperties(localStorage->m_SelectedHandleActor, renderer);

    localStorage->Actor->VisibilityOn();
    localStorage->HandleActor->VisibilityOn();
    localStorage->SelectedHandleActor->VisibilityOn();

    localStorage->PropAssembly->AddPart(localStorage->Actor);
    localStorage->PropAssembly->AddPart(localStorage->HandleActor);
    localStorage->PropAssembly->VisibilityOn();

    localStorage->UpdateGenerateDataTime();
  }
}
vtkProp *mitk::BoundingShapeVtkMapper3D::GetVtkProp(BaseRenderer *renderer)
{
  return m_Impl->LocalStorageHandler.GetLocalStorage(renderer)->PropAssembly;
}
<|endoftext|>