<commit_before>#include <osm/util/compressed_bitset.hpp>
#include <osm/util/quad_tile.hpp>
#include <iostream>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>

using namespace osm::util;
using std::set;
using std::ostream;
using std::cout;
using std::endl;

set<tile_t> random_set() {
  set<tile_t> s;
  for (int i = 0; i < 500; ++i) {
    tile_t tile = rand() & 0xffff;
    s.insert(tile);
  }
  return s;
}

set<tile_t> snake_set() {
  unsigned int x, y;
  x = rand() & 0xffff;
  y = rand() & 0xffff;
  set<tile_t> s;
  for (int i = 0; i < 500; ++i) {
    tile_t tile = xy2tile(x, y);
    s.insert(tile);
    int r = rand();
    if ((r & 1) > 0) { x += 1; } else { y += 1; }
  }
  return s;
}

BOOST_TEST_DONT_PRINT_LOG_VALUE( set<tile_t> )

BOOST_AUTO_TEST_SUITE(compressed_bitset)

BOOST_AUTO_TEST_CASE(single_entry_set) {
  set<tile_t> a;
  a.insert(0xaaaaaaaal); // nice pretty 10101010 pattern
  CompressedBitset c(a);
  set<tile_t> b = c.decompress();
  BOOST_CHECK_EQUAL(a, b);
}

BOOST_AUTO_TEST_CASE(double_entry_set) {
  set<tile_t> a;
  a.insert(0xaaaaaaaal); // nice pretty 10101010 pattern
  a.insert(0xaaaa5555l); // but this only shares half those bits
  CompressedBitset c(a);
  set<tile_t> b = c.decompress();
  BOOST_CHECK_EQUAL(a, b);
}

BOOST_AUTO_TEST_CASE(triple_entry_set) {
  set<tile_t> a;
  a.insert(0xaaaaaaaal);
  a.insert(0xaaaa5555l);
  a.insert(0xaaaa55aal);
  CompressedBitset c(a);
  set<tile_t> b = c.decompress();
  BOOST_CHECK_EQUAL(a, b);
}

BOOST_AUTO_TEST_CASE(random_test) {
  srand(12456);
  size_t set_bytes = 0, compressed_bytes = 0;

  for (int i = 0; i < 100; ++i) {
    set<tile_t> a = random_set();
    CompressedBitset c(a);

    set_bytes += a.size() * sizeof(tile_t);
    compressed_bytes += c.size();

    set<tile_t> b = c.decompress();
    BOOST_CHECK_EQUAL(a, b);
  }

  cout << "random: " << set_bytes << ", " << compressed_bytes << "\n";
}

BOOST_AUTO_TEST_CASE(snake_test) {
  srand(12456);
  size_t set_bytes = 0, compressed_bytes = 0;

  for (int i = 0; i < 100; ++i) {
    set<tile_t> a = snake_set();
    CompressedBitset c(a);

    set_bytes += a.size() * sizeof(tile_t);
    compressed_bytes += c.size();

    set<tile_t> b = c.decompress();
    BOOST_CHECK_EQUAL(a, b);
  }

  cout << "snake: " << set_bytes << ", " << compressed_bytes << "\n";
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Removed debug output from bitset tests.<commit_after>#include <osm/util/compressed_bitset.hpp>
#include <osm/util/quad_tile.hpp>
#include <iostream>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>

using namespace osm::util;
using std::set;
using std::ostream;
using std::cout;
using std::endl;

set<tile_t> random_set() {
  set<tile_t> s;
  for (int i = 0; i < 500; ++i) {
    tile_t tile = rand() & 0xffff;
    s.insert(tile);
  }
  return s;
}

set<tile_t> snake_set() {
  unsigned int x, y;
  x = rand() & 0xffff;
  y = rand() & 0xffff;
  set<tile_t> s;
  for (int i = 0; i < 500; ++i) {
    tile_t tile = xy2tile(x, y);
    s.insert(tile);
    int r = rand();
    if ((r & 1) > 0) { x += 1; } else { y += 1; }
  }
  return s;
}

BOOST_TEST_DONT_PRINT_LOG_VALUE( set<tile_t> )

BOOST_AUTO_TEST_SUITE(compressed_bitset)

BOOST_AUTO_TEST_CASE(single_entry_set) {
  set<tile_t> a;
  a.insert(0xaaaaaaaal); // nice pretty 10101010 pattern
  CompressedBitset c(a);
  set<tile_t> b = c.decompress();
  BOOST_CHECK_EQUAL(a, b);
}

BOOST_AUTO_TEST_CASE(double_entry_set) {
  set<tile_t> a;
  a.insert(0xaaaaaaaal); // nice pretty 10101010 pattern
  a.insert(0xaaaa5555l); // but this only shares half those bits
  CompressedBitset c(a);
  set<tile_t> b = c.decompress();
  BOOST_CHECK_EQUAL(a, b);
}

BOOST_AUTO_TEST_CASE(triple_entry_set) {
  set<tile_t> a;
  a.insert(0xaaaaaaaal);
  a.insert(0xaaaa5555l);
  a.insert(0xaaaa55aal);
  CompressedBitset c(a);
  set<tile_t> b = c.decompress();
  BOOST_CHECK_EQUAL(a, b);
}

BOOST_AUTO_TEST_CASE(random_test) {
  srand(12456);
  size_t set_bytes = 0, compressed_bytes = 0;

  for (int i = 0; i < 100; ++i) {
    set<tile_t> a = random_set();
    CompressedBitset c(a);

    set_bytes += a.size() * sizeof(tile_t);
    compressed_bytes += c.size();

    set<tile_t> b = c.decompress();
    BOOST_CHECK_EQUAL(a, b);
  }
}

BOOST_AUTO_TEST_CASE(snake_test) {
  srand(12456);
  size_t set_bytes = 0, compressed_bytes = 0;

  for (int i = 0; i < 100; ++i) {
    set<tile_t> a = snake_set();
    CompressedBitset c(a);

    set_bytes += a.size() * sizeof(tile_t);
    compressed_bytes += c.size();

    set<tile_t> b = c.decompress();
    BOOST_CHECK_EQUAL(a, b);
  }
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


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

#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif

#ifndef _CPPUHELPER_COMPBASE_EX_HXX_
#include <cppuhelper/compbase_ex.hxx>
#endif
/*
__DEF_COMPIMPLHELPER_EX( 5 )
*/

namespace cppu
{
    /** Implementation helper supporting ::com::sun::star::lang::XTypeProvider and
        ::com::sun::star::lang::XComponent.  Upon disposing objects of this class, sub-classes
        receive a disposing() call.  Objects of this class can be held weakly, i.e. by a
        ::com::sun::star::uno::WeakReference.

        @attention
        The life-cycle of the passed mutex reference has to be longer than objects of this class.

        @derive
        Inherit from this class giving your interface(s) to be implemented as template argument(s).
        Your sub class defines method implementations for these interface(s).
    */
    template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 >
    class SAL_NO_VTABLE WeakComponentImplHelper5
        : public WeakComponentImplHelperBase
        , public ::com::sun::star::lang::XTypeProvider
        , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5
    {
        /** @internal */
        struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, WeakComponentImplHelper5<Ifc1, Ifc2, Ifc3, Ifc4, Ifc5> > > {};
    public:
        inline WeakComponentImplHelper5( ::osl::Mutex & rMutex ) throw ()
            : WeakComponentImplHelperBase( rMutex )
            {}
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( ::com::sun::star::uno::Type const & rType ) throw (::com::sun::star::uno::RuntimeException)
            { return WeakComponentImplHelper_query( rType, cd::get(), this, (WeakComponentImplHelperBase *)this ); }
        virtual void SAL_CALL acquire() throw ()
            { WeakComponentImplHelperBase::acquire(); }
        virtual void SAL_CALL release() throw ()
            { WeakComponentImplHelperBase::release(); }
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException)
            { return WeakComponentImplHelper_getTypes( cd::get() ); }
        virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException)
            { return ImplHelper_getImplementationId( cd::get() ); }
    };
    /** Implementation helper supporting ::com::sun::star::lang::XTypeProvider and
        ::com::sun::star::lang::XComponent.  Upon disposing objects of this class, sub-classes
        receive a disposing() call.  Objects of this class can be held weakly, i.e. by a
        ::com::sun::star::uno::WeakReference.  Object of this class can be aggregated, i.e.
        incoming queryInterface() calls are delegated.

        @attention
        The life-cycle of the passed mutex reference has to be longer than objects of this class.

        @derive
        Inherit from this class giving your interface(s) to be implemented as template argument(s).
        Your sub class defines method implementations for these interface(s).
    */
    template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 >
    class SAL_NO_VTABLE WeakAggComponentImplHelper5
        : public WeakAggComponentImplHelperBase
        , public ::com::sun::star::lang::XTypeProvider
        , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5
    {
        /** @internal */
        struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, WeakAggComponentImplHelper5<Ifc1, Ifc2, Ifc3, Ifc4, Ifc5> > > {};
    public:
        inline WeakAggComponentImplHelper5( ::osl::Mutex & rMutex ) throw ()
            : WeakAggComponentImplHelperBase( rMutex )
            {}
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( ::com::sun::star::uno::Type const & rType ) throw (::com::sun::star::uno::RuntimeException)
            { return WeakAggComponentImplHelperBase::queryInterface( rType ); }
        virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( ::com::sun::star::uno::Type const & rType ) throw (::com::sun::star::uno::RuntimeException)
            { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, (WeakAggComponentImplHelperBase *)this ); }
        virtual void SAL_CALL acquire() throw ()
            { WeakAggComponentImplHelperBase::acquire(); }
        virtual void SAL_CALL release() throw ()
            { WeakAggComponentImplHelperBase::release(); }
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException)
            { return WeakAggComponentImplHelper_getTypes( cd::get() ); }
        virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException)
            { return ImplHelper_getImplementationId( cd::get() ); }
    };
}

#endif
<commit_msg>INTEGRATION: CWS skeletonmaker (1.10.36); FILE MERGED 2005/10/25 08:47:33 jsc 1.10.36.3: #i52170# adapt docu for autodoc 2005/10/14 15:41:37 jsc 1.10.36.2: RESYNC: (1.10-1.11); FILE MERGED 2005/07/19 13:07:00 jsc 1.10.36.1: #i51721# forward XComponent methods to base class to avoid ambigious error messages<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: compbase5.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2005-10-27 17:15:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CPPUHELPER_COMPBASE5_HXX_
#define _CPPUHELPER_COMPBASE5_HXX_

#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif

#ifndef _CPPUHELPER_COMPBASE_EX_HXX_
#include <cppuhelper/compbase_ex.hxx>
#endif
/*
__DEF_COMPIMPLHELPER_EX( 5 )
*/

namespace cppu
{
    /** Implementation helper supporting ::com::sun::star::lang::XTypeProvider and
        ::com::sun::star::lang::XComponent.

        Upon disposing objects of this class, sub-classes receive a disposing()
        call.  Objects of this class can be held weakly, i.e. by a
        ::com::sun::star::uno::WeakReference.

        @attention
        The life-cycle of the passed mutex reference has to be longer than objects of this class.

        @derive
        Inherit from this class giving your interface(s) to be implemented as template argument(s).
        Your sub class defines method implementations for these interface(s).
    */
    template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 >
    class SAL_NO_VTABLE WeakComponentImplHelper5
        : public WeakComponentImplHelperBase
        , public ::com::sun::star::lang::XTypeProvider
        , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5
    {
        /** @internal */
        struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, WeakComponentImplHelper5<Ifc1, Ifc2, Ifc3, Ifc4, Ifc5> > > {};
    public:
        inline WeakComponentImplHelper5( ::osl::Mutex & rMutex ) throw ()
            : WeakComponentImplHelperBase( rMutex )
            {}
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( ::com::sun::star::uno::Type const & rType ) throw (::com::sun::star::uno::RuntimeException)
            { return WeakComponentImplHelper_query( rType, cd::get(), this, (WeakComponentImplHelperBase *)this ); }
        virtual void SAL_CALL acquire() throw ()
            { WeakComponentImplHelperBase::acquire(); }
        virtual void SAL_CALL release() throw ()
            { WeakComponentImplHelperBase::release(); }
        virtual void SAL_CALL dispose()throw (::com::sun::star::uno::RuntimeException)
            { WeakComponentImplHelperBase::dispose(); }
        virtual void SAL_CALL addEventListener(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > & xListener)throw (::com::sun::star::uno::RuntimeException)
            { WeakComponentImplHelperBase::addEventListener(xListener); }
        virtual void SAL_CALL removeEventListener(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > & xListener)throw (::com::sun::star::uno::RuntimeException)
            { WeakComponentImplHelperBase::removeEventListener(xListener); }
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException)
            { return WeakComponentImplHelper_getTypes( cd::get() ); }
        virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException)
            { return ImplHelper_getImplementationId( cd::get() ); }
    };
    /** Implementation helper supporting ::com::sun::star::lang::XTypeProvider and
        ::com::sun::star::lang::XComponent.

        Upon disposing objects of this class, sub-classes receive a disposing()
        call.  Objects of this class can be held weakly, i.e. by a
        ::com::sun::star::uno::WeakReference.  Object of this class can be
        aggregated, i.e. incoming queryInterface() calls are delegated.

        @attention
        The life-cycle of the passed mutex reference has to be longer than objects of this class.

        @derive
        Inherit from this class giving your interface(s) to be implemented as template argument(s).
        Your sub class defines method implementations for these interface(s).

        @deprecated
    */
    template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 >
    class SAL_NO_VTABLE WeakAggComponentImplHelper5
        : public WeakAggComponentImplHelperBase
        , public ::com::sun::star::lang::XTypeProvider
        , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5
    {
        /** @internal */
        struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, WeakAggComponentImplHelper5<Ifc1, Ifc2, Ifc3, Ifc4, Ifc5> > > {};
    public:
        inline WeakAggComponentImplHelper5( ::osl::Mutex & rMutex ) throw ()
            : WeakAggComponentImplHelperBase( rMutex )
            {}
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( ::com::sun::star::uno::Type const & rType ) throw (::com::sun::star::uno::RuntimeException)
            { return WeakAggComponentImplHelperBase::queryInterface( rType ); }
        virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( ::com::sun::star::uno::Type const & rType ) throw (::com::sun::star::uno::RuntimeException)
            { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, (WeakAggComponentImplHelperBase *)this ); }
        virtual void SAL_CALL acquire() throw ()
            { WeakAggComponentImplHelperBase::acquire(); }
        virtual void SAL_CALL release() throw ()
            { WeakAggComponentImplHelperBase::release(); }
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException)
            { return WeakAggComponentImplHelper_getTypes( cd::get() ); }
        virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException)
            { return ImplHelper_getImplementationId( cd::get() ); }
    };
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: unxcrashres.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2003-12-17 19:29:00 $
 *
 *  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 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
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/#include <tools/config.hxx>
#include <rtl/string.hxx>
#include <osl/thread.h>
#include <tools/l2txtenc.hxx>

#include <hash_map>
#include <string>
#include <cstdio>
#include <cerrno>

using namespace std;
using namespace rtl;

void filterValue( ByteString& rValue, const OString& rGroup, const ByteString& rKey )
{
    USHORT nStartPos = rValue.Search( '"' );
    USHORT nStopPos = rValue.SearchBackward( '"' );
    if( nStartPos == STRING_NOTFOUND || nStopPos == STRING_NOTFOUND )
    {
        fprintf( stderr, "Error: invalid key in [%s] in key \"%s\"\n",
                 rGroup.getStr(),
                 rKey.GetBuffer() );
        exit( 1 );
    }
    rValue.Erase( nStopPos );
    rValue.Erase( 0, nStartPos+1 );
}

int main( int argc, char** argv )
{
    if( argc != 3 )
    {
        fprintf( stderr, "USAGE: unxcrashres <in_lng_file> <out_file_prefix>\n" );
        exit( 1 );
    }

    ByteString tmp_argv1( argv[1] );
    Config aConfig( String( tmp_argv1, osl_getThreadTextEncoding() ) );
    hash_map< int, hash_map< OString, OString, OStringHash > > aFiles;

    for( USHORT i = 0; i < aConfig.GetGroupCount(); i++ )
    {
        aConfig.SetGroup( aConfig.GetGroupName( i ) );
        OString aGroup = aConfig.GetGroupName( i );
        USHORT nKeys = aConfig.GetKeyCount();
        for( USHORT n = 0; n < nKeys; n++ )
        {
            ByteString aKey = aConfig.GetKeyName( n );
            ByteString aValue = aConfig.ReadKey( aKey );
            int nRes = aKey.ToInt32();
            // tailor key
            filterValue( aValue, aGroup, aKey );

            aFiles[nRes][aGroup] = ByteString( String( aValue, Langcode2TextEncoding( (USHORT)nRes ) ), RTL_TEXTENCODING_UTF8 );
        }
    }

    for( hash_map< int, hash_map< OString, OString, OStringHash > >::const_iterator lang_it = aFiles.begin(); lang_it != aFiles.end(); ++lang_it )
    {
        ByteString aFile( argv[2] );
        aFile.Append( '.' );
        if( lang_it->first < 10 )
            aFile.Append( '0' );
        aFile.Append( ByteString::CreateFromInt32( lang_it->first ) );
        FILE* fp = fopen( aFile.GetBuffer(), "w" );
        if( ! fp )
        {
            fprintf( stderr, "Error: could not open \"%s\" for writing: %s\n",
                     aFile.GetBuffer(), strerror( errno ) );
            exit(1);
        }
        for( hash_map< OString, OString, OStringHash >::const_iterator line_it = lang_it->second.begin(); line_it != lang_it->second.end(); ++line_it )
        {
            fprintf( fp, "%s=%s\n", line_it->first.getStr(), line_it->second.getStr() );
        }
        fclose( fp );
    }

    return 0;
}
<commit_msg>INTEGRATION: CWS mergebuild (1.1.36); FILE MERGED 2004/04/20 16:37:01 hjs 1.1.36.2: RESYNC: (1.1-1.2); FILE MERGED 2003/10/29 17:19:38 hjs 1.1.36.1: #i8252# telnr. to iso code; switch to ulf<commit_after>/*************************************************************************
 *
 *  $RCSfile: unxcrashres.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-26 03:10:37 $
 *
 *  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 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
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/#include <tools/config.hxx>
#include <rtl/string.hxx>
#include <osl/thread.h>

#include <hash_map>
#include <string>
#include <cstdio>
#include <cerrno>

using namespace std;
using namespace rtl;

void filterValue( ByteString& rValue, const OString& rGroup, const ByteString& rKey )
{
    USHORT nStartPos = rValue.Search( '"' );
    USHORT nStopPos = rValue.SearchBackward( '"' );
    if( nStartPos == STRING_NOTFOUND || nStopPos == STRING_NOTFOUND )
    {
        fprintf( stderr, "Error: invalid key in [%s] in key \"%s\"\n",
                 rGroup.getStr(),
                 rKey.GetBuffer() );
        exit( 1 );
    }
    rValue.Erase( nStopPos );
    rValue.Erase( 0, nStartPos+1 );
}

int main( int argc, char** argv )
{
    if( argc != 3 )
    {
        fprintf( stderr, "USAGE: unxcrashres <in_lng_file> <out_file_prefix>\n" );
        exit( 1 );
    }

    ByteString tmp_argv1( argv[1] );
    Config aConfig( String( tmp_argv1, osl_getThreadTextEncoding() ) );
    hash_map< ByteString, hash_map< OString, OString, OStringHash >, OStringHash > aFiles;

    for( USHORT i = 0; i < aConfig.GetGroupCount(); i++ )
    {
        aConfig.SetGroup( aConfig.GetGroupName( i ) );
        OString aGroup = aConfig.GetGroupName( i );
        USHORT nKeys = aConfig.GetKeyCount();
        for( USHORT n = 0; n < nKeys; n++ )
        {
            ByteString aKey = aConfig.GetKeyName( n );
            ByteString aValue = aConfig.ReadKey( aKey );
            // tailor key
            filterValue( aValue, aGroup, aKey );

            aFiles[aKey][aGroup] = ByteString( aValue );
        }
    }

    for( hash_map< ByteString, hash_map< OString, OString, OStringHash >, OStringHash >::const_iterator lang_it = aFiles.begin(); lang_it != aFiles.end(); ++lang_it )
    {
        ByteString aFile( argv[2] );
        aFile.Append( '.' );
        aFile.Append( lang_it->first );
        FILE* fp = fopen( aFile.GetBuffer(), "w" );
        if( ! fp )
        {
            fprintf( stderr, "Error: could not open \"%s\" for writing: %s\n",
                     aFile.GetBuffer(), strerror( errno ) );
            exit(1);
        }
        for( hash_map< OString, OString, OStringHash >::const_iterator line_it = lang_it->second.begin(); line_it != lang_it->second.end(); ++line_it )
        {
            fprintf( fp, "%s=%s\n", line_it->first.getStr(), line_it->second.getStr() );
        }
        fclose( fp );
    }

    return 0;
}
<|endoftext|>


<commit_before>/*!
	@file
	@author		Albert Semenov
	@date		08/2008
*/

#include "precompiled.h"
#include "BaseManager.h"
#include <MyGUI_OgrePlatform.h>

#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
#	include <windows.h>
#endif

namespace base
{

#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
#include <CoreFoundation/CoreFoundation.h>
	// This function will locate the path to our application on OS X,
	// unlike windows you can not rely on the curent working directory
	// for locating your configuration files and resources.
	std::string macBundlePath()
	{
		char path[1024];
		CFBundleRef mainBundle = CFBundleGetMainBundle();    assert(mainBundle);
		CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);    assert(mainBundleURL);
		CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle);    assert(cfStringRef);
		CFStringGetCString(cfStringRef, path, 1024, kCFStringEncodingASCII);
		CFRelease(mainBundleURL);
		CFRelease(cfStringRef);
		return std::string(path);
	}
#endif

	BaseManager::BaseManager() :
		mGUI(nullptr),
		mPlatform(nullptr),
		mInfo(nullptr),
		mFocusInfo(nullptr),
		mRoot(nullptr),
		mCamera(nullptr),
		mSceneManager(nullptr),
		mWindow(nullptr),
		mExit(false),
		mPluginCfgName("plugins.cfg"),
		mResourceXMLName("resources.xml"),
		mResourceFileName("core.xml"),
		mNode(nullptr)
	{
		#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
			mResourcePath = macBundlePath() + "/Contents/Resources/";
		#else
			mResourcePath = "";
		#endif
	}

	BaseManager::~BaseManager()
	{
	}

	bool BaseManager::create()
	{
		Ogre::String pluginsPath;

		#ifndef OGRE_STATIC_LIB
			pluginsPath = mResourcePath + mPluginCfgName;
		#endif

		mRoot = new Ogre::Root(pluginsPath, mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log");

		setupResources();

		//
		if (!mRoot->restoreConfig())
		{
			//   ,
			if (!mRoot->showConfigDialog()) return false;
		}

		mWindow = mRoot->initialise(true);

	#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
		//
		size_t hWnd = 0;
		mWindow->getCustomAttribute("WINDOW", &hWnd);
		//
		char buf[MAX_PATH];
		::GetModuleFileNameA(0, (LPCH)&buf, MAX_PATH);
		//
		HINSTANCE instance = ::GetModuleHandleA(buf);
		//
		HICON hIcon = ::LoadIcon(instance, MAKEINTRESOURCE(1001));
		if (hIcon)
		{
			::SendMessageA((HWND)hWnd, WM_SETICON, 1, (LPARAM)hIcon);
			::SendMessageA((HWND)hWnd, WM_SETICON, 0, (LPARAM)hIcon);
		}
	#endif

		mSceneManager = mRoot->createSceneManager(Ogre::ST_GENERIC, "BaseSceneManager");

		mCamera = mSceneManager->createCamera("BaseCamera");
		mCamera->setNearClipDistance(5);
		mCamera->setPosition(400, 400, 400);
		mCamera->lookAt(0, 150, 0);

		// Create one viewport, entire window
		Ogre::Viewport* vp = mWindow->addViewport(mCamera);
		// Alter the camera aspect ratio to match the viewport
		mCamera->setAspectRatio((float)vp->getActualWidth() / (float)vp->getActualHeight());

		// Set default mipmap level (NB some APIs ignore this)
		Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

		mSceneManager->setAmbientLight(Ogre::ColourValue::White);
		Ogre::Light* l = mSceneManager->createLight("MainLight");
        l->setType(Ogre::Light::LT_DIRECTIONAL);
		Ogre::Vector3 vec(-0.3, -0.3, -0.3);
		vec.normalise();
        l->setDirection(vec);

		// Load resources
		Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

		mRoot->addFrameListener(this);
		Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);

		size_t handle = 0;
		mWindow->getCustomAttribute("WINDOW", &handle);

		createInput(handle);

		windowResized(mWindow);

		createGui();

		createPointerManager(handle);

		createScene();

		return true;
	}

	void BaseManager::run()
	{
		//
		mRoot->getRenderSystem()->_initRenderTargets();

		//
		while (true)
		{
			Ogre::WindowEventUtilities::messagePump();

			if (mWindow->isActive() == false)
				mWindow->setActive(true);
			if (!mRoot->renderOneFrame())
				break;

//  ,
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
			::Sleep(0);
#endif

		};
	}

	void BaseManager::destroy()
	{
		destroyScene();

		destroyPointerManager();

		destroyInput();

		destroyGui();

		//
		if (mSceneManager)
		{
			mSceneManager->clearScene();
			mSceneManager->destroyAllCameras();
			mSceneManager = nullptr;
			mCamera = nullptr;
		}

		if (mWindow)
		{
			mWindow->destroy();
			mWindow = nullptr;
		}

		if (mRoot)
		{
			Ogre::RenderWindow* window = mRoot->getAutoCreatedWindow();
			if (window)
				window->removeAllViewports();
			delete mRoot;
			mRoot = nullptr;
		}

	}

	void BaseManager::createGui()
	{
		mPlatform = new MyGUI::OgrePlatform();
		mPlatform->initialise(mWindow, mSceneManager);
		mGUI = new MyGUI::Gui();
		mGUI->initialise(mResourceFileName);

		mInfo = new diagnostic::StatisticInfo();
	}

	void BaseManager::destroyGui()
	{
		if (mGUI)
		{
			if (mInfo)
			{
				delete mInfo;
				mInfo = nullptr;
			}

			if (mFocusInfo)
			{
				delete mFocusInfo;
				mFocusInfo = nullptr;
			}

			mGUI->shutdown();
			delete mGUI;
			mGUI = nullptr;
		}

		if (mPlatform)
		{
			mPlatform->shutdown();
			delete mPlatform;
			mPlatform = nullptr;
		}
	}

	void BaseManager::setupResources()
	{
		MyGUI::xml::Document doc;

		if (!doc.open(mResourceXMLName))
			doc.getLastError();

		MyGUI::xml::ElementPtr root = doc.getRoot();
		if (root == nullptr || root->getName() != "Paths")
			return;

		MyGUI::xml::ElementEnumerator node = root->getElementEnumerator();
		while (node.next())
		{
			if (node->getName() == "Path")
			{
				bool rootAttr = false;
				if (node->findAttribute("root") != "")
				{
					rootAttr = MyGUI::utility::parseBool(node->findAttribute("root"));
					if (rootAttr) mRootMedia = node->getContent();
				}
				addResourceLocation(node->getContent());
			}
		}
	}

	bool BaseManager::frameStarted(const Ogre::FrameEvent& evt)
	{
		if (mExit)
			return false;

		if (!mGUI)
			return true;

		captureInput();

		if (mInfo)
		{
			static float time = 0;
			time += evt.timeSinceLastFrame;
			if (time > 1)
			{
				time -= 1;
				try
				{
					const Ogre::RenderTarget::FrameStats& stats = mWindow->getStatistics();
					mInfo->change("FPS", (int)stats.lastFPS);
					mInfo->change("triangle", stats.triangleCount);
					mInfo->change("batch", stats.batchCount);
					//mInfo->change("batch gui", MyGUI::RenderManager::getInstance().getBatch());
					mInfo->update();
				}
				catch (...)
				{
				}
			}
		}

		//
		if (mNode)
		{
			mNode->yaw(Ogre::Radian(Ogre::Degree(evt.timeSinceLastFrame * 10)));
		}

		return true;
	}

	bool BaseManager::frameEnded(const Ogre::FrameEvent& evt)
	{
		return true;
	}

	void BaseManager::windowResized(Ogre::RenderWindow* _rw)
	{
		int width = (int)_rw->getWidth();
		int height = (int)_rw->getHeight();

		//
		if (mCamera)
		{
			mCamera->setAspectRatio((float)width / (float)height);

			setInputViewSize(width, height);
		}
	}

	void BaseManager::windowClosed(Ogre::RenderWindow* _rw)
	{
		mExit = true;
		destroyInput();
	}

	void BaseManager::setWindowCaption(const std::string& _text)
	{
	#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
		size_t handle = 0;
		mWindow->getCustomAttribute("WINDOW", &handle);
		::SetWindowTextA((HWND)handle, _text.c_str());
	#endif
	}

	void BaseManager::prepare(int argc, char **argv)
	{
	}

	void BaseManager::addResourceLocation(const std::string& _name, const std::string& _group, const std::string& _type, bool _recursive)
	{
		#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
			// OS X does not set the working directory relative to the app, In order to make things portable on OS X we need to provide the loading with it's own bundle path location
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Ogre::String(macBundlePath() + "/" + _name), _type, _group, _recursive);
		#else
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(_name, _type, _group, _recursive);
		#endif
	}

	void BaseManager::addResourceLocation(const std::string & _name, bool _recursive)
	{
		addResourceLocation(_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "FileSystem", false);
	}

	void BaseManager::createDefaultScene()
	{
		try
		{
			Ogre::Entity* entity = mSceneManager->createEntity("Mikki.mesh", "Mikki.mesh");
			mNode = mSceneManager->getRootSceneNode()->createChildSceneNode();
			mNode->attachObject(entity);
		}
		catch (Ogre::FileNotFoundException&)
		{
			return;
		}

		try
		{
			Ogre::MeshManager::getSingleton().createPlane(
				"FloorPlane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
				Ogre::Plane(Ogre::Vector3::UNIT_Y, 0), 1000, 1000, 1, 1, true, 1, 1, 1, Ogre::Vector3::UNIT_Z);

			Ogre::Entity* entity = getSceneManager()->createEntity("FloorPlane", "FloorPlane");
			entity->setMaterialName("Ground");
			mNode->attachObject(entity);
		}
		catch (Ogre::FileNotFoundException&)
		{
			return;
		}
	}

	void BaseManager::injectMouseMove(int _absx, int _absy, int _absz)
	{
		if (!mGUI)
			return;

		mGUI->injectMouseMove(_absx, _absy, _absz);
	}

	void BaseManager::injectMousePress(int _absx, int _absy, MyGUI::MouseButton _id)
	{
		if (!mGUI)
			return;

		mGUI->injectMousePress(_absx, _absy, _id);
	}

	void BaseManager::injectMouseRelease(int _absx, int _absy, MyGUI::MouseButton _id)
	{
		if (!mGUI)
			return;

		mGUI->injectMouseRelease(_absx, _absy, _id);
	}

	void BaseManager::injectKeyPress(MyGUI::KeyCode _key, MyGUI::Char _text)
	{
		if (!mGUI)
			return;

		if (_key == MyGUI::KeyCode::Escape)
		{
			mExit = true;
			return;
		}
		else if (_key == MyGUI::KeyCode::SysRq)
		{
			std::ifstream stream;
			std::string file;
			do
			{
				stream.close();
				static size_t num = 0;
				const size_t max_shot = 100;
				if (num == max_shot)
				{
					MYGUI_LOG(Info, "The limit of screenshots is exceeded : " << max_shot);
					return;
				}
				file = MyGUI::utility::toString("screenshot_", ++num, ".png");
				stream.open(file.c_str());
			}
			while (stream.is_open());
			mWindow->writeContentsToFile(file);
			return;
		}
		else if (_key == MyGUI::KeyCode::F12)
		{
			if (mFocusInfo == nullptr)
				mFocusInfo = new diagnostic::InputFocusInfo();

			bool visible = mFocusInfo->getFocusVisible();
			mFocusInfo->setFocusVisible(!visible);
		}
		else if (_key == MyGUI::KeyCode::F11)
		{
			MyGUI::LayerManager::getInstance().dumpStatisticToLog();
		}

		// change polygon more
		else if (_key == MyGUI::KeyCode::F5)
		{
			getCamera()->setPolygonMode(Ogre::PM_SOLID);
		}
		else if (_key == MyGUI::KeyCode::F6)
		{
			getCamera()->setPolygonMode(Ogre::PM_WIREFRAME);
		}
		else if (_key == MyGUI::KeyCode::F7)
		{
			getCamera()->setPolygonMode(Ogre::PM_POINTS);
		}

		mGUI->injectKeyPress(_key, _text);
	}

	void BaseManager::injectKeyRelease(MyGUI::KeyCode _key)
	{
		if (!mGUI)
			return;

		mGUI->injectKeyRelease(_key);
	}

} // namespace base
<commit_msg>add key for rotate<commit_after>/*!
	@file
	@author		Albert Semenov
	@date		08/2008
*/

#include "precompiled.h"
#include "BaseManager.h"
#include <MyGUI_OgrePlatform.h>

#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
#	include <windows.h>
#endif

namespace base
{

#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
#include <CoreFoundation/CoreFoundation.h>
	// This function will locate the path to our application on OS X,
	// unlike windows you can not rely on the curent working directory
	// for locating your configuration files and resources.
	std::string macBundlePath()
	{
		char path[1024];
		CFBundleRef mainBundle = CFBundleGetMainBundle();    assert(mainBundle);
		CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);    assert(mainBundleURL);
		CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle);    assert(cfStringRef);
		CFStringGetCString(cfStringRef, path, 1024, kCFStringEncodingASCII);
		CFRelease(mainBundleURL);
		CFRelease(cfStringRef);
		return std::string(path);
	}
#endif

	BaseManager::BaseManager() :
		mGUI(nullptr),
		mPlatform(nullptr),
		mInfo(nullptr),
		mFocusInfo(nullptr),
		mRoot(nullptr),
		mCamera(nullptr),
		mSceneManager(nullptr),
		mWindow(nullptr),
		mExit(false),
		mPluginCfgName("plugins.cfg"),
		mResourceXMLName("resources.xml"),
		mResourceFileName("core.xml"),
		mNode(nullptr)
	{
		#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
			mResourcePath = macBundlePath() + "/Contents/Resources/";
		#else
			mResourcePath = "";
		#endif
	}

	BaseManager::~BaseManager()
	{
	}

	bool BaseManager::create()
	{
		Ogre::String pluginsPath;

		#ifndef OGRE_STATIC_LIB
			pluginsPath = mResourcePath + mPluginCfgName;
		#endif

		mRoot = new Ogre::Root(pluginsPath, mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log");

		setupResources();

		//
		if (!mRoot->restoreConfig())
		{
			//   ,
			if (!mRoot->showConfigDialog()) return false;
		}

		mWindow = mRoot->initialise(true);

	#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
		//
		size_t hWnd = 0;
		mWindow->getCustomAttribute("WINDOW", &hWnd);
		//
		char buf[MAX_PATH];
		::GetModuleFileNameA(0, (LPCH)&buf, MAX_PATH);
		//
		HINSTANCE instance = ::GetModuleHandleA(buf);
		//
		HICON hIcon = ::LoadIcon(instance, MAKEINTRESOURCE(1001));
		if (hIcon)
		{
			::SendMessageA((HWND)hWnd, WM_SETICON, 1, (LPARAM)hIcon);
			::SendMessageA((HWND)hWnd, WM_SETICON, 0, (LPARAM)hIcon);
		}
	#endif

		mSceneManager = mRoot->createSceneManager(Ogre::ST_GENERIC, "BaseSceneManager");

		mCamera = mSceneManager->createCamera("BaseCamera");
		mCamera->setNearClipDistance(5);
		mCamera->setPosition(400, 400, 400);
		mCamera->lookAt(0, 150, 0);

		// Create one viewport, entire window
		Ogre::Viewport* vp = mWindow->addViewport(mCamera);
		// Alter the camera aspect ratio to match the viewport
		mCamera->setAspectRatio((float)vp->getActualWidth() / (float)vp->getActualHeight());

		// Set default mipmap level (NB some APIs ignore this)
		Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

		mSceneManager->setAmbientLight(Ogre::ColourValue::White);
		Ogre::Light* l = mSceneManager->createLight("MainLight");
        l->setType(Ogre::Light::LT_DIRECTIONAL);
		Ogre::Vector3 vec(-0.3, -0.3, -0.3);
		vec.normalise();
        l->setDirection(vec);

		// Load resources
		Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

		mRoot->addFrameListener(this);
		Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);

		size_t handle = 0;
		mWindow->getCustomAttribute("WINDOW", &handle);

		createInput(handle);

		windowResized(mWindow);

		createGui();

		createPointerManager(handle);

		createScene();

		return true;
	}

	void BaseManager::run()
	{
		//
		mRoot->getRenderSystem()->_initRenderTargets();

		//
		while (true)
		{
			Ogre::WindowEventUtilities::messagePump();

			if (mWindow->isActive() == false)
				mWindow->setActive(true);
			if (!mRoot->renderOneFrame())
				break;

//  ,
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
			::Sleep(0);
#endif

		};
	}

	void BaseManager::destroy()
	{
		destroyScene();

		destroyPointerManager();

		destroyInput();

		destroyGui();

		//
		if (mSceneManager)
		{
			mSceneManager->clearScene();
			mSceneManager->destroyAllCameras();
			mSceneManager = nullptr;
			mCamera = nullptr;
		}

		if (mWindow)
		{
			mWindow->destroy();
			mWindow = nullptr;
		}

		if (mRoot)
		{
			Ogre::RenderWindow* window = mRoot->getAutoCreatedWindow();
			if (window)
				window->removeAllViewports();
			delete mRoot;
			mRoot = nullptr;
		}

	}

	void BaseManager::createGui()
	{
		mPlatform = new MyGUI::OgrePlatform();
		mPlatform->initialise(mWindow, mSceneManager);
		mGUI = new MyGUI::Gui();
		mGUI->initialise(mResourceFileName);

		mInfo = new diagnostic::StatisticInfo();
	}

	void BaseManager::destroyGui()
	{
		if (mGUI)
		{
			if (mInfo)
			{
				delete mInfo;
				mInfo = nullptr;
			}

			if (mFocusInfo)
			{
				delete mFocusInfo;
				mFocusInfo = nullptr;
			}

			mGUI->shutdown();
			delete mGUI;
			mGUI = nullptr;
		}

		if (mPlatform)
		{
			mPlatform->shutdown();
			delete mPlatform;
			mPlatform = nullptr;
		}
	}

	void BaseManager::setupResources()
	{
		MyGUI::xml::Document doc;

		if (!doc.open(mResourceXMLName))
			doc.getLastError();

		MyGUI::xml::ElementPtr root = doc.getRoot();
		if (root == nullptr || root->getName() != "Paths")
			return;

		MyGUI::xml::ElementEnumerator node = root->getElementEnumerator();
		while (node.next())
		{
			if (node->getName() == "Path")
			{
				bool rootAttr = false;
				if (node->findAttribute("root") != "")
				{
					rootAttr = MyGUI::utility::parseBool(node->findAttribute("root"));
					if (rootAttr) mRootMedia = node->getContent();
				}
				addResourceLocation(node->getContent());
			}
		}
	}

	bool BaseManager::frameStarted(const Ogre::FrameEvent& evt)
	{
		if (mExit)
			return false;

		if (!mGUI)
			return true;

		captureInput();

		if (mInfo)
		{
			static float time = 0;
			time += evt.timeSinceLastFrame;
			if (time > 1)
			{
				time -= 1;
				try
				{
					const Ogre::RenderTarget::FrameStats& stats = mWindow->getStatistics();
					mInfo->change("FPS", (int)stats.lastFPS);
					mInfo->change("triangle", stats.triangleCount);
					mInfo->change("batch", stats.batchCount);
					//mInfo->change("batch gui", MyGUI::RenderManager::getInstance().getBatch());
					mInfo->update();
				}
				catch (...)
				{
				}
			}
		}

		//
		if (mNode)
		{
			mNode->yaw(Ogre::Radian(Ogre::Degree(evt.timeSinceLastFrame * 10)));
		}

		return true;
	}

	bool BaseManager::frameEnded(const Ogre::FrameEvent& evt)
	{
		return true;
	}

	void BaseManager::windowResized(Ogre::RenderWindow* _rw)
	{
		int width = (int)_rw->getWidth();
		int height = (int)_rw->getHeight();

		//
		if (mCamera)
		{
			mCamera->setAspectRatio((float)width / (float)height);

			setInputViewSize(width, height);
		}
	}

	void BaseManager::windowClosed(Ogre::RenderWindow* _rw)
	{
		mExit = true;
		destroyInput();
	}

	void BaseManager::setWindowCaption(const std::string& _text)
	{
	#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
		size_t handle = 0;
		mWindow->getCustomAttribute("WINDOW", &handle);
		::SetWindowTextA((HWND)handle, _text.c_str());
	#endif
	}

	void BaseManager::prepare(int argc, char **argv)
	{
	}

	void BaseManager::addResourceLocation(const std::string& _name, const std::string& _group, const std::string& _type, bool _recursive)
	{
		#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
			// OS X does not set the working directory relative to the app, In order to make things portable on OS X we need to provide the loading with it's own bundle path location
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Ogre::String(macBundlePath() + "/" + _name), _type, _group, _recursive);
		#else
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(_name, _type, _group, _recursive);
		#endif
	}

	void BaseManager::addResourceLocation(const std::string & _name, bool _recursive)
	{
		addResourceLocation(_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "FileSystem", false);
	}

	void BaseManager::createDefaultScene()
	{
		try
		{
			Ogre::Entity* entity = mSceneManager->createEntity("Mikki.mesh", "Mikki.mesh");
			mNode = mSceneManager->getRootSceneNode()->createChildSceneNode();
			mNode->attachObject(entity);
		}
		catch (Ogre::FileNotFoundException&)
		{
			return;
		}

		try
		{
			Ogre::MeshManager::getSingleton().createPlane(
				"FloorPlane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
				Ogre::Plane(Ogre::Vector3::UNIT_Y, 0), 1000, 1000, 1, 1, true, 1, 1, 1, Ogre::Vector3::UNIT_Z);

			Ogre::Entity* entity = getSceneManager()->createEntity("FloorPlane", "FloorPlane");
			entity->setMaterialName("Ground");
			mNode->attachObject(entity);
		}
		catch (Ogre::FileNotFoundException&)
		{
			return;
		}
	}

	void BaseManager::injectMouseMove(int _absx, int _absy, int _absz)
	{
		if (!mGUI)
			return;

		mGUI->injectMouseMove(_absx, _absy, _absz);
	}

	void BaseManager::injectMousePress(int _absx, int _absy, MyGUI::MouseButton _id)
	{
		if (!mGUI)
			return;

		mGUI->injectMousePress(_absx, _absy, _id);
	}

	void BaseManager::injectMouseRelease(int _absx, int _absy, MyGUI::MouseButton _id)
	{
		if (!mGUI)
			return;

		mGUI->injectMouseRelease(_absx, _absy, _id);
	}

	void BaseManager::injectKeyPress(MyGUI::KeyCode _key, MyGUI::Char _text)
	{
		if (!mGUI)
			return;

		if (_key == MyGUI::KeyCode::Escape)
		{
			mExit = true;
			return;
		}
		else if (_key == MyGUI::KeyCode::SysRq)
		{
			std::ifstream stream;
			std::string file;
			do
			{
				stream.close();
				static size_t num = 0;
				const size_t max_shot = 100;
				if (num == max_shot)
				{
					MYGUI_LOG(Info, "The limit of screenshots is exceeded : " << max_shot);
					return;
				}
				file = MyGUI::utility::toString("screenshot_", ++num, ".png");
				stream.open(file.c_str());
			}
			while (stream.is_open());
			mWindow->writeContentsToFile(file);
			return;
		}
		else if (_key == MyGUI::KeyCode::F12)
		{
			if (mFocusInfo == nullptr)
				mFocusInfo = new diagnostic::InputFocusInfo();

			bool visible = mFocusInfo->getFocusVisible();
			mFocusInfo->setFocusVisible(!visible);
		}
		else if (_key == MyGUI::KeyCode::F11)
		{
			MyGUI::LayerManager::getInstance().dumpStatisticToLog();
		}

		// change polygon more
		else if (_key == MyGUI::KeyCode::F5)
		{
			getCamera()->setPolygonMode(Ogre::PM_SOLID);
		}
		else if (_key == MyGUI::KeyCode::F6)
		{
			getCamera()->setPolygonMode(Ogre::PM_WIREFRAME);
		}
		else if (_key == MyGUI::KeyCode::F7)
		{
			getCamera()->setPolygonMode(Ogre::PM_POINTS);
		}
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0
		else if (_key == MyGUI::KeyCode::F1)
		{
			mWindow->getViewport(0)->setOrientationMode(Ogre::OR_DEGREE_0, false);
			mPlatform->getRenderManagerPtr()->setRenderWindow(mWindow);
		}
		else if (_key == MyGUI::KeyCode::F2)
		{
			mWindow->getViewport(0)->setOrientationMode(Ogre::OR_DEGREE_90, false);
			mPlatform->getRenderManagerPtr()->setRenderWindow(mWindow);
		}
		else if (_key == MyGUI::KeyCode::F3)
		{
			mWindow->getViewport(0)->setOrientationMode(Ogre::OR_DEGREE_180, false);
			mPlatform->getRenderManagerPtr()->setRenderWindow(mWindow);
		}
		else if (_key == MyGUI::KeyCode::F4)
		{
			mWindow->getViewport(0)->setOrientationMode(Ogre::OR_DEGREE_270, false);
			mPlatform->getRenderManagerPtr()->setRenderWindow(mWindow);
		}
#endif
		mGUI->injectKeyPress(_key, _text);
	}

	void BaseManager::injectKeyRelease(MyGUI::KeyCode _key)
	{
		if (!mGUI)
			return;

		mGUI->injectKeyRelease(_key);
	}

} // namespace base
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Config.h"
#include <CDAPI.h>

Config g_config;

Config::Config()
{
	LoadConfig((cd::GetPluginDir() + L"\\Data\\DesktopBrowser.ini").c_str());
}

void Config::LoadConfig(LPCWSTR path)
{
	m_homePage.resize(2083);
	GetPrivateProfileStringW(APPNAME, L"HomePage", L"https://github.com/xfgryujk/WinCustomDesktop", (LPWSTR)m_homePage.c_str(),
		(DWORD)m_homePage.size(), path);
	m_homePage.resize(wcslen(m_homePage.c_str()));
}
<commit_msg>改掉脑残写法<commit_after>#include "stdafx.h"
#include "Config.h"
#include <CDAPI.h>

Config g_config;

Config::Config()
{
	LoadConfig((cd::GetPluginDir() + L"\\Data\\DesktopBrowser.ini").c_str());
}

void Config::LoadConfig(LPCWSTR path)
{
	m_homePage.resize(2083);
	GetPrivateProfileStringW(APPNAME, L"HomePage", L"https://github.com/xfgryujk/WinCustomDesktop", &m_homePage.front(),
		static_cast<DWORD>(m_homePage.size()), path);
	m_homePage.resize(wcslen(m_homePage.c_str()));
}
<|endoftext|>


<commit_before>#ifndef ___INANITY_GRAPHICS_SHADERS_FUNCTIONS_HPP___
#define ___INANITY_GRAPHICS_SHADERS_FUNCTIONS_HPP___

#include "Value.hpp"
#include "OperationNode.hpp"
#include "FragmentNode.hpp"

BEGIN_INANITY_SHADERS

#define OP0(op) ptr<Node>(NEW(OperationNode(OperationNode::operation ## op)))
#define OP1(op) ptr<Node>(NEW(OperationNode(OperationNode::operation ## op, a.GetNode())))
#define OP2(op) ptr<Node>(NEW(OperationNode(OperationNode::operation ## op, a.GetNode(), b.GetNode())))
#define OP3(op) ptr<Node>(NEW(OperationNode(OperationNode::operation ## op, a.GetNode(), b.GetNode(), c.GetNode())))
#define OP4(op) ptr<Node>(NEW(OperationNode(OperationNode::operation ## op, a.GetNode(), b.GetNode(), c.GetNode(), d.GetNode())))

// construction values
inline Value<vec2> newvec2(Value<float> a, Value<float> b) { return OP2(Float11to2); }
inline Value<vec3> newvec3(Value<float> a, Value<float> b, Value<float> c) { return OP3(Float111to3); }
inline Value<vec4> newvec4(Value<float> a, Value<float> b, Value<float> c, Value<float> d) { return OP4(Float1111to4); }
inline Value<vec4> newvec4(Value<vec3> a, Value<float> b) { return OP2(Float31to4); }
inline Value<vec4> newvec4(Value<vec2> a, Value<float> b, Value<float> c) { return OP3(Float211to4); }

// setPosition
inline Expression setPosition(Value<vec4> a) { return OP1(SetPosition); }
// getInstanceID
inline Value<uint> getInstanceID() { return OP0(GetInstanceID); }

// output fragment
inline Expression fragment(int target, Value<vec4> f)
{
	return ptr<Node>(NEW(FragmentNode(target, f.GetNode())));
}

// screenToTexture
inline Value<vec2> screenToTexture(Value<vec2> a) { return OP1(ScreenToTexture); }

// dot
template <typename T, int n>
inline Value<T> dot(Value<xvec<T, n> > a, Value<xvec<T, n> > b) { return OP2(Dot); }

// cross
template <typename T>
inline Value<xvec<T, 3> > cross(Value<xvec<T, 3> > a, Value<xvec<T, 3> > b) { return OP2(Cross); }

// mul
template <typename T, int n, int m, int k>
inline Value<xmat<T, n, k> > mul(Value<xmat<T, n, m> > a, Value<xmat<T, m, k> > b) { return OP2(Mul); }
template <typename T, int n, int m>
inline Value<xvec<T, m> > mul(Value<xvec<T, n> > a, Value<xmat<T, n, m> > b) { return OP2(Mul); }
template <typename T, int n, int m>
inline Value<xvec<T, n> > mul(Value<xmat<T, n, m> > a, Value<xvec<T, m> > b) { return OP2(Mul); }

// length
template <typename T, int n>
inline Value<T> length(Value<xvec<T, n> > a) { return OP1(Length); }
// normalize
template <typename T, int n>
inline Value<xvec<T, n> > normalize(Value<xvec<T, n> > a) { return OP1(Normalize); }

// pow
template <typename T>
inline Value<T> pow(Value<T> a, Value<T> b) { return OP2(Pow); }
template <typename T, int n>
inline Value<xvec<T, n> > pow(Value<xvec<T, n> > a, Value<T> b) { return OP2(Pow); }
template <typename T, int n>
inline Value<xvec<T, n> > pow(Value<xvec<T, n> > a, Value<xvec<T, n> > b) { return OP2(Pow); }

// min
template <typename T>
inline Value<T> min(Value<T> a, Value<T> b) { return OP2(Min); }
// max
template <typename T>
inline Value<T> max(Value<T> a, Value<T> b) { return OP2(Max); }

// abs
inline Value<float> abs(Value<float> a) { return OP1(Abs); }

// sin
inline Value<float> sin(Value<float> a) { return OP1(Sin); }
// cos
inline Value<float> cos(Value<float> a) { return OP1(Cos); }

// exp
inline Value<float> exp(Value<float> a) { return OP1(Exp); }
// exp2 (возведение 2 в степень)
inline Value<float> exp2(Value<float> a) { return OP1(Exp2); }
// log
inline Value<float> log(Value<float> a) { return OP1(Log); }

// saturate
inline Value<float> saturate(Value<float> a) { return OP1(Saturate); }
template <typename T, int n>
inline Value<xvec<T, n> > saturate(Value<xvec<T, n> > a) { return OP1(Saturate); }

// ddx
inline Value<float> ddx(Value<float> a) { return OP1(Ddx); }
template <typename T, int n>
inline Value<xvec<T, n> > ddx(Value<xvec<T, n> > a) { return OP1(Ddx); }
// ddy
inline Value<float> ddy(Value<float> a) { return OP1(Ddy); }
template <typename T, int n>
inline Value<xvec<T, n> > ddy(Value<xvec<T, n> > a) { return OP1(Ddy); }

// clip
inline Expression clip(Value<float> a) { return OP1(Clip); }

#undef OP2

END_INANITY_SHADERS

#endif
<commit_msg>shader function pow now accepts scalar power for vectors (even for glsl)<commit_after>#ifndef ___INANITY_GRAPHICS_SHADERS_FUNCTIONS_HPP___
#define ___INANITY_GRAPHICS_SHADERS_FUNCTIONS_HPP___

#include "Value.hpp"
#include "OperationNode.hpp"
#include "FragmentNode.hpp"

BEGIN_INANITY_SHADERS

#define OP0(op) ptr<Node>(NEW(OperationNode(OperationNode::operation ## op)))
#define OP1(op) ptr<Node>(NEW(OperationNode(OperationNode::operation ## op, a.GetNode())))
#define OP2(op) ptr<Node>(NEW(OperationNode(OperationNode::operation ## op, a.GetNode(), b.GetNode())))
#define OP3(op) ptr<Node>(NEW(OperationNode(OperationNode::operation ## op, a.GetNode(), b.GetNode(), c.GetNode())))
#define OP4(op) ptr<Node>(NEW(OperationNode(OperationNode::operation ## op, a.GetNode(), b.GetNode(), c.GetNode(), d.GetNode())))

// construction values
inline Value<vec2> newvec2(Value<float> a, Value<float> b) { return OP2(Float11to2); }
inline Value<vec3> newvec3(Value<float> a, Value<float> b, Value<float> c) { return OP3(Float111to3); }
inline Value<vec4> newvec4(Value<float> a, Value<float> b, Value<float> c, Value<float> d) { return OP4(Float1111to4); }
inline Value<vec4> newvec4(Value<vec3> a, Value<float> b) { return OP2(Float31to4); }
inline Value<vec4> newvec4(Value<vec2> a, Value<float> b, Value<float> c) { return OP3(Float211to4); }

// setPosition
inline Expression setPosition(Value<vec4> a) { return OP1(SetPosition); }
// getInstanceID
inline Value<uint> getInstanceID() { return OP0(GetInstanceID); }

// output fragment
inline Expression fragment(int target, Value<vec4> f)
{
	return ptr<Node>(NEW(FragmentNode(target, f.GetNode())));
}

// screenToTexture
inline Value<vec2> screenToTexture(Value<vec2> a) { return OP1(ScreenToTexture); }

// dot
template <typename T, int n>
inline Value<T> dot(Value<xvec<T, n> > a, Value<xvec<T, n> > b) { return OP2(Dot); }

// cross
template <typename T>
inline Value<xvec<T, 3> > cross(Value<xvec<T, 3> > a, Value<xvec<T, 3> > b) { return OP2(Cross); }

// mul
template <typename T, int n, int m, int k>
inline Value<xmat<T, n, k> > mul(Value<xmat<T, n, m> > a, Value<xmat<T, m, k> > b) { return OP2(Mul); }
template <typename T, int n, int m>
inline Value<xvec<T, m> > mul(Value<xvec<T, n> > a, Value<xmat<T, n, m> > b) { return OP2(Mul); }
template <typename T, int n, int m>
inline Value<xvec<T, n> > mul(Value<xmat<T, n, m> > a, Value<xvec<T, m> > b) { return OP2(Mul); }

// length
template <typename T, int n>
inline Value<T> length(Value<xvec<T, n> > a) { return OP1(Length); }
// normalize
template <typename T, int n>
inline Value<xvec<T, n> > normalize(Value<xvec<T, n> > a) { return OP1(Normalize); }

// pow
template <typename T>
inline Value<T> pow(Value<T> a, Value<T> b) { return OP2(Pow); }
template <typename T, int n>
inline Value<xvec<T, n> > pow(Value<xvec<T, n> > a, Value<T> b1)
{
	Value<xvec<T, n> > b = b1.Cast<xvec<T, n> >();
	return OP2(Pow);
}
template <typename T, int n>
inline Value<xvec<T, n> > pow(Value<xvec<T, n> > a, Value<xvec<T, n> > b) { return OP2(Pow); }

// min
template <typename T>
inline Value<T> min(Value<T> a, Value<T> b) { return OP2(Min); }
// max
template <typename T>
inline Value<T> max(Value<T> a, Value<T> b) { return OP2(Max); }

// abs
inline Value<float> abs(Value<float> a) { return OP1(Abs); }

// sin
inline Value<float> sin(Value<float> a) { return OP1(Sin); }
// cos
inline Value<float> cos(Value<float> a) { return OP1(Cos); }

// exp
inline Value<float> exp(Value<float> a) { return OP1(Exp); }
// exp2 (возведение 2 в степень)
inline Value<float> exp2(Value<float> a) { return OP1(Exp2); }
// log
inline Value<float> log(Value<float> a) { return OP1(Log); }

// saturate
inline Value<float> saturate(Value<float> a) { return OP1(Saturate); }
template <typename T, int n>
inline Value<xvec<T, n> > saturate(Value<xvec<T, n> > a) { return OP1(Saturate); }

// ddx
inline Value<float> ddx(Value<float> a) { return OP1(Ddx); }
template <typename T, int n>
inline Value<xvec<T, n> > ddx(Value<xvec<T, n> > a) { return OP1(Ddx); }
// ddy
inline Value<float> ddy(Value<float> a) { return OP1(Ddy); }
template <typename T, int n>
inline Value<xvec<T, n> > ddy(Value<xvec<T, n> > a) { return OP1(Ddy); }

// clip
inline Expression clip(Value<float> a) { return OP1(Clip); }

#undef OP2

END_INANITY_SHADERS

#endif
<|endoftext|>


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

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QApplication>
#include <QTimer>

// CTK includes
#include "ctkColorDialog.h"
#include "ctkColorPickerButton.h"

// STD includes
#include <cstdlib>
#include <iostream>

//-----------------------------------------------------------------------------
int ctkColorDialogTest1(int argc, char * argv [] )
{
  QApplication app(argc, argv);

  ctkColorDialog colorDialog;
  ctkColorDialog colorDialog1(Qt::red);

  ctkColorPickerButton* extraPanel = new ctkColorPickerButton;
  QObject::connect(extraPanel, SIGNAL(colorChanged(QColor)),
                   &colorDialog, SLOT(setColor(QColor)));
  colorDialog.addTab(extraPanel, "Extra");
  int index = colorDialog.indexOf(extraPanel);
  if (index != 0 ||
      extraPanel != colorDialog.widget(index) ||
      colorDialog.widget(-1) != 0)
    {
    std::cerr << "ctkColorDialog::addTab failed" << std::endl;
    return EXIT_FAILURE;
    }

  // fake removeTab
  colorDialog.removeTab(-1);
  index = colorDialog.indexOf(extraPanel);
  if (index != 0 ||
      colorDialog.widget(0) != extraPanel)
    {
    std::cerr << "ctkColorDialog::removeTab failed" << std::endl;
    return EXIT_FAILURE;
    }

  // true removeTab
  colorDialog.removeTab(index);
  index = colorDialog.indexOf(extraPanel);
  if (index != -1 ||
      colorDialog.widget(0) != 0)
    {
    std::cerr << "ctkColorDialog::removeTab failed" << std::endl;
    return EXIT_FAILURE;
    }

  // Add the panel back
  colorDialog.addTab(extraPanel, "Extra chooser");
  extraPanel->setColor(Qt::darkBlue);

  if (colorDialog.currentColor() != Qt::darkBlue)
    {
    std::cerr << "ctkColorDialog::setColor failed" << std::endl;
    return EXIT_FAILURE;
    }

  colorDialog.open();

  // the following is only in interactive mode
  if (argc < 2 || QString(argv[1]) != "-I" )
    {
    QTimer::singleShot(200, &colorDialog, SLOT(accept()));
    }

  return app.exec();

  ctkColorDialog::addDefaultTab(extraPanel, "Extra");
  QColor color = ctkColorDialog::getColor(Qt::black,0 , "", 0);
  return EXIT_SUCCESS;

}
<commit_msg>Default color panel is taken into account with the indexes<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QApplication>
#include <QTimer>

// CTK includes
#include "ctkColorDialog.h"
#include "ctkColorPickerButton.h"

// STD includes
#include <cstdlib>
#include <iostream>

//-----------------------------------------------------------------------------
int ctkColorDialogTest1(int argc, char * argv [] )
{
  QApplication app(argc, argv);

  ctkColorDialog colorDialog;
  ctkColorDialog colorDialog1(Qt::red);

  ctkColorPickerButton* extraPanel = new ctkColorPickerButton;
  QObject::connect(extraPanel, SIGNAL(colorChanged(QColor)),
                   &colorDialog, SLOT(setColor(QColor)));
  colorDialog.addTab(extraPanel, "Extra");
  int index = colorDialog.indexOf(extraPanel);
  if (index != 1 ||
      extraPanel != colorDialog.widget(index) ||
      colorDialog.widget(-1) != 0)
    {
    std::cerr << "ctkColorDialog::addTab failed:" << index << std::endl;
    return EXIT_FAILURE;
    }

  // fake removeTab
  colorDialog.removeTab(-1);
  index = colorDialog.indexOf(extraPanel);
  if (index != 1 ||
      colorDialog.widget(1) != extraPanel)
    {
    std::cerr << "ctkColorDialog::removeTab failed:" << index << std::endl;
    return EXIT_FAILURE;
    }

  // true removeTab
  colorDialog.removeTab(index);
  index = colorDialog.indexOf(extraPanel);
  if (index != -1 ||
      // still the default tab
      colorDialog.widget(0) == 0 ||
      // extra panel doesn't exist anymore
      colorDialog.widget(1) != 0)
    {
    std::cerr << "ctkColorDialog::removeTab failed" << std::endl;
    return EXIT_FAILURE;
    }

  // Add the panel back
  colorDialog.addTab(extraPanel, "Extra chooser");
  extraPanel->setColor(Qt::darkBlue);

  if (colorDialog.currentColor() != Qt::darkBlue)
    {
    std::cerr << "ctkColorDialog::setColor failed" << std::endl;
    return EXIT_FAILURE;
    }

  colorDialog.open();

  // the following is only in interactive mode
  if (argc < 2 || QString(argv[1]) != "-I" )
    {
    QTimer::singleShot(200, &colorDialog, SLOT(accept()));
    }

  return app.exec();

  ctkColorDialog::addDefaultTab(extraPanel, "Extra");
  QColor color = ctkColorDialog::getColor(Qt::black,0 , "", 0);
  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2022 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <node/blockstorage.h>

#include <blockdb.h>
#include <chain.h>
#include <chainparams.h>
#include <config.h>
#include <consensus/validation.h>
#include <flatfile.h>
#include <fs.h>
#include <pow/pow.h>
#include <shutdown.h>
#include <streams.h>
#include <util/system.h>
#include <validation.h>

// From validation. TODO move here
bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight,
                  CChain &active_chain, uint64_t nTime, bool fKnown = false);

static bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos,
                             const CMessageHeader::MessageMagic &messageStart) {
    // Open history file to append
    CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
    if (fileout.IsNull()) {
        return error("WriteBlockToDisk: OpenBlockFile failed");
    }

    // Write index header
    unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
    fileout << messageStart << nSize;

    // Write block
    long fileOutPos = ftell(fileout.Get());
    if (fileOutPos < 0) {
        return error("WriteBlockToDisk: ftell failed");
    }

    pos.nPos = (unsigned int)fileOutPos;
    fileout << block;

    return true;
}

bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos,
                       const Consensus::Params &params) {
    block.SetNull();

    // Open history file to read
    CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
    if (filein.IsNull()) {
        return error("ReadBlockFromDisk: OpenBlockFile failed for %s",
                     pos.ToString());
    }

    // Read block
    try {
        filein >> block;
    } catch (const std::exception &e) {
        return error("%s: Deserialize or I/O error - %s at %s", __func__,
                     e.what(), pos.ToString());
    }

    // Check the header
    if (!CheckProofOfWork(block.GetHash(), block.nBits, params)) {
        return error("ReadBlockFromDisk: Errors in block header at %s",
                     pos.ToString());
    }

    return true;
}

bool ReadBlockFromDisk(CBlock &block, const CBlockIndex *pindex,
                       const Consensus::Params &params) {
    FlatFilePos blockPos;
    {
        LOCK(cs_main);
        blockPos = pindex->GetBlockPos();
    }

    if (!ReadBlockFromDisk(block, blockPos, params)) {
        return false;
    }

    if (block.GetHash() != pindex->GetBlockHash()) {
        return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() "
                     "doesn't match index for %s at %s",
                     pindex->ToString(), pindex->GetBlockPos().ToString());
    }

    return true;
}

/**
 * Store block on disk. If dbp is non-nullptr, the file is known to already
 * reside on disk.
 */
FlatFilePos SaveBlockToDisk(const CBlock &block, int nHeight,
                            CChain &active_chain,
                            const CChainParams &chainparams,
                            const FlatFilePos *dbp) {
    unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
    FlatFilePos blockPos;
    if (dbp != nullptr) {
        blockPos = *dbp;
    }
    if (!FindBlockPos(blockPos, nBlockSize + 8, nHeight, active_chain,
                      block.GetBlockTime(), dbp != nullptr)) {
        error("%s: FindBlockPos failed", __func__);
        return FlatFilePos();
    }
    if (dbp == nullptr) {
        if (!WriteBlockToDisk(block, blockPos, chainparams.DiskMagic())) {
            AbortNode("Failed to write block");
            return FlatFilePos();
        }
    }
    return blockPos;
}

struct CImportingNow {
    CImportingNow() {
        assert(fImporting == false);
        fImporting = true;
    }

    ~CImportingNow() {
        assert(fImporting == true);
        fImporting = false;
    }
};

void ThreadImport(const Config &config, ChainstateManager &chainman,
                  std::vector<fs::path> vImportFiles, const ArgsManager &args) {
    ScheduleBatchPriority();

    {
        const CChainParams &chainParams = config.GetChainParams();

        CImportingNow imp;

        // -reindex
        if (fReindex) {
            int nFile = 0;
            while (true) {
                FlatFilePos pos(nFile, 0);
                if (!fs::exists(GetBlockPosFilename(pos))) {
                    // No block files left to reindex
                    break;
                }
                FILE *file = OpenBlockFile(pos, true);
                if (!file) {
                    // This error is logged in OpenBlockFile
                    break;
                }
                LogPrintf("Reindexing block file blk%05u.dat...\n",
                          (unsigned int)nFile);
                ::ChainstateActive().LoadExternalBlockFile(config, file, &pos);
                if (ShutdownRequested()) {
                    LogPrintf("Shutdown requested. Exit %s\n", __func__);
                    return;
                }
                nFile++;
            }
            pblocktree->WriteReindexing(false);
            fReindex = false;
            LogPrintf("Reindexing finished\n");
            // To avoid ending up in a situation without genesis block, re-try
            // initializing (no-op if reindexing worked):
            ::ChainstateActive().LoadGenesisBlock(chainParams);
        }

        // -loadblock=
        for (const fs::path &path : vImportFiles) {
            FILE *file = fsbridge::fopen(path, "rb");
            if (file) {
                LogPrintf("Importing blocks file %s...\n",
                          fs::PathToString(path));
                ::ChainstateActive().LoadExternalBlockFile(config, file);
                if (ShutdownRequested()) {
                    LogPrintf("Shutdown requested. Exit %s\n", __func__);
                    return;
                }
            } else {
                LogPrintf("Warning: Could not open blocks file %s\n",
                          fs::PathToString(path));
            }
        }

        // Reconsider blocks we know are valid. They may have been marked
        // invalid by, for instance, running an outdated version of the node
        // software.
        const MapCheckpoints &checkpoints =
            chainParams.Checkpoints().mapCheckpoints;
        for (const MapCheckpoints::value_type &i : checkpoints) {
            const BlockHash &hash = i.second;

            LOCK(cs_main);
            CBlockIndex *pblockindex =
                g_chainman.m_blockman.LookupBlockIndex(hash);
            if (pblockindex && !pblockindex->nStatus.isValid()) {
                LogPrintf("Reconsidering checkpointed block %s ...\n",
                          hash.GetHex());
                ::ChainstateActive().ResetBlockFailureFlags(pblockindex);
            }
        }

        // scan for better chains in the block chain database, that are not yet
        // connected in the active best chain

        // We can't hold cs_main during ActivateBestChain even though we're
        // accessing the chainman unique_ptrs since ABC requires us not to be
        // holding cs_main, so retrieve the relevant pointers before the ABC
        // call.
        for (CChainState *chainstate :
             WITH_LOCK(::cs_main, return chainman.GetAll())) {
            BlockValidationState state;
            if (!chainstate->ActivateBestChain(config, state, nullptr)) {
                LogPrintf("Failed to connect best block (%s)\n",
                          state.ToString());
                StartShutdown();
                return;
            }
        }

        if (args.GetBoolArg("-stopafterblockimport",
                            DEFAULT_STOPAFTERBLOCKIMPORT)) {
            LogPrintf("Stopping after block import\n");
            StartShutdown();
            return;
        }
    } // End scope of CImportingNow
    chainman.ActiveChainstate().LoadMempool(config, args);
}
<commit_msg>blockstorage: [refactor] Use chainman reference where possible<commit_after>// Copyright (c) 2011-2022 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <node/blockstorage.h>

#include <blockdb.h>
#include <chain.h>
#include <chainparams.h>
#include <config.h>
#include <consensus/validation.h>
#include <flatfile.h>
#include <fs.h>
#include <pow/pow.h>
#include <shutdown.h>
#include <streams.h>
#include <util/system.h>
#include <validation.h>

// From validation. TODO move here
bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight,
                  CChain &active_chain, uint64_t nTime, bool fKnown = false);

static bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos,
                             const CMessageHeader::MessageMagic &messageStart) {
    // Open history file to append
    CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
    if (fileout.IsNull()) {
        return error("WriteBlockToDisk: OpenBlockFile failed");
    }

    // Write index header
    unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
    fileout << messageStart << nSize;

    // Write block
    long fileOutPos = ftell(fileout.Get());
    if (fileOutPos < 0) {
        return error("WriteBlockToDisk: ftell failed");
    }

    pos.nPos = (unsigned int)fileOutPos;
    fileout << block;

    return true;
}

bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos,
                       const Consensus::Params &params) {
    block.SetNull();

    // Open history file to read
    CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
    if (filein.IsNull()) {
        return error("ReadBlockFromDisk: OpenBlockFile failed for %s",
                     pos.ToString());
    }

    // Read block
    try {
        filein >> block;
    } catch (const std::exception &e) {
        return error("%s: Deserialize or I/O error - %s at %s", __func__,
                     e.what(), pos.ToString());
    }

    // Check the header
    if (!CheckProofOfWork(block.GetHash(), block.nBits, params)) {
        return error("ReadBlockFromDisk: Errors in block header at %s",
                     pos.ToString());
    }

    return true;
}

bool ReadBlockFromDisk(CBlock &block, const CBlockIndex *pindex,
                       const Consensus::Params &params) {
    FlatFilePos blockPos;
    {
        LOCK(cs_main);
        blockPos = pindex->GetBlockPos();
    }

    if (!ReadBlockFromDisk(block, blockPos, params)) {
        return false;
    }

    if (block.GetHash() != pindex->GetBlockHash()) {
        return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() "
                     "doesn't match index for %s at %s",
                     pindex->ToString(), pindex->GetBlockPos().ToString());
    }

    return true;
}

/**
 * Store block on disk. If dbp is non-nullptr, the file is known to already
 * reside on disk.
 */
FlatFilePos SaveBlockToDisk(const CBlock &block, int nHeight,
                            CChain &active_chain,
                            const CChainParams &chainparams,
                            const FlatFilePos *dbp) {
    unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
    FlatFilePos blockPos;
    if (dbp != nullptr) {
        blockPos = *dbp;
    }
    if (!FindBlockPos(blockPos, nBlockSize + 8, nHeight, active_chain,
                      block.GetBlockTime(), dbp != nullptr)) {
        error("%s: FindBlockPos failed", __func__);
        return FlatFilePos();
    }
    if (dbp == nullptr) {
        if (!WriteBlockToDisk(block, blockPos, chainparams.DiskMagic())) {
            AbortNode("Failed to write block");
            return FlatFilePos();
        }
    }
    return blockPos;
}

struct CImportingNow {
    CImportingNow() {
        assert(fImporting == false);
        fImporting = true;
    }

    ~CImportingNow() {
        assert(fImporting == true);
        fImporting = false;
    }
};

void ThreadImport(const Config &config, ChainstateManager &chainman,
                  std::vector<fs::path> vImportFiles, const ArgsManager &args) {
    ScheduleBatchPriority();

    {
        const CChainParams &chainParams = config.GetChainParams();

        CImportingNow imp;

        // -reindex
        if (fReindex) {
            int nFile = 0;
            while (true) {
                FlatFilePos pos(nFile, 0);
                if (!fs::exists(GetBlockPosFilename(pos))) {
                    // No block files left to reindex
                    break;
                }
                FILE *file = OpenBlockFile(pos, true);
                if (!file) {
                    // This error is logged in OpenBlockFile
                    break;
                }
                LogPrintf("Reindexing block file blk%05u.dat...\n",
                          (unsigned int)nFile);
                chainman.ActiveChainstate().LoadExternalBlockFile(config, file,
                                                                  &pos);
                if (ShutdownRequested()) {
                    LogPrintf("Shutdown requested. Exit %s\n", __func__);
                    return;
                }
                nFile++;
            }
            pblocktree->WriteReindexing(false);
            fReindex = false;
            LogPrintf("Reindexing finished\n");
            // To avoid ending up in a situation without genesis block, re-try
            // initializing (no-op if reindexing worked):
            chainman.ActiveChainstate().LoadGenesisBlock(chainParams);
        }

        // -loadblock=
        for (const fs::path &path : vImportFiles) {
            FILE *file = fsbridge::fopen(path, "rb");
            if (file) {
                LogPrintf("Importing blocks file %s...\n",
                          fs::PathToString(path));
                chainman.ActiveChainstate().LoadExternalBlockFile(config, file);
                if (ShutdownRequested()) {
                    LogPrintf("Shutdown requested. Exit %s\n", __func__);
                    return;
                }
            } else {
                LogPrintf("Warning: Could not open blocks file %s\n",
                          fs::PathToString(path));
            }
        }

        // Reconsider blocks we know are valid. They may have been marked
        // invalid by, for instance, running an outdated version of the node
        // software.
        const MapCheckpoints &checkpoints =
            chainParams.Checkpoints().mapCheckpoints;
        for (const MapCheckpoints::value_type &i : checkpoints) {
            const BlockHash &hash = i.second;

            LOCK(cs_main);
            CBlockIndex *pblockindex =
                g_chainman.m_blockman.LookupBlockIndex(hash);
            if (pblockindex && !pblockindex->nStatus.isValid()) {
                LogPrintf("Reconsidering checkpointed block %s ...\n",
                          hash.GetHex());
                ::ChainstateActive().ResetBlockFailureFlags(pblockindex);
            }
        }

        // scan for better chains in the block chain database, that are not yet
        // connected in the active best chain

        // We can't hold cs_main during ActivateBestChain even though we're
        // accessing the chainman unique_ptrs since ABC requires us not to be
        // holding cs_main, so retrieve the relevant pointers before the ABC
        // call.
        for (CChainState *chainstate :
             WITH_LOCK(::cs_main, return chainman.GetAll())) {
            BlockValidationState state;
            if (!chainstate->ActivateBestChain(config, state, nullptr)) {
                LogPrintf("Failed to connect best block (%s)\n",
                          state.ToString());
                StartShutdown();
                return;
            }
        }

        if (args.GetBoolArg("-stopafterblockimport",
                            DEFAULT_STOPAFTERBLOCKIMPORT)) {
            LogPrintf("Stopping after block import\n");
            StartShutdown();
            return;
        }
    } // End scope of CImportingNow
    chainman.ActiveChainstate().LoadMempool(config, args);
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 Plenluno All rights reserved.

#include <gtest/gtest.h>
#include <libj/js_typed_array.h>
#include <libj/typed_array_list.h>

namespace libj {

TEST(GTestJsTypedArray, TestCreate) {
    JsTypedArray<Int>::Ptr a = JsTypedArray<Int>::create();
    ASSERT_TRUE(a);
}

TEST(GTestJsTypedArray, TestAdd) {
    JsTypedArray<Int>::Ptr a = JsTypedArray<Int>::create();
    ASSERT_TRUE(a->add(5));
    ASSERT_FALSE(a->add(5.5));
    ASSERT_TRUE(a->add(7));
    ASSERT_EQ(2, a->length());
}

TEST(GTestJsTypedArray, TestGet) {
    JsTypedArray<Int>::Ptr a = JsTypedArray<Int>::create();
    ASSERT_TRUE(a->add(5));
    ASSERT_TRUE(a->add(7));
    ASSERT_TRUE(a->get(0).equals(5));
    ASSERT_TRUE(a->get(1).equals(7));
}

TEST(GTestJsTypedArray, TestJsProperty) {
    JsTypedArray<Int>::Ptr a = JsTypedArray<Int>::create();
    a->setProperty(String::create("abc"), 7);
    ASSERT_TRUE(a->hasProperty(String::create("abc")));
    ASSERT_TRUE(a->getProperty(String::create("abc")).equals(7));

    a->deleteProperty(String::create("abc"));
    ASSERT_FALSE(a->hasProperty(String::create("abc")));
}

}  // namespace libj
<commit_msg>fix a gtest error<commit_after>// Copyright (c) 2012 Plenluno All rights reserved.

#include <gtest/gtest.h>
#include <libj/js_typed_array.h>
#include <libj/typed_array_list.h>

namespace libj {

TEST(GTestJsTypedArray, TestCreate) {
    JsTypedArray<Int>::Ptr a = JsTypedArray<Int>::create();
    ASSERT_TRUE(a);
}

TEST(GTestJsTypedArray, TestAdd) {
    JsTypedArray<Int>::Ptr a = JsTypedArray<Int>::create();
    ASSERT_TRUE(a->add(5));
#ifdef LIBJ_USE_EXCEPTION
    ASSERT_ANY_THROW(a->add(5.5));
#else
    ASSERT_FALSE(a->add(5.5));
#endif  // LIBJ_USE_EXCEPTION
    ASSERT_TRUE(a->add(7));
    ASSERT_EQ(2, a->length());
}

TEST(GTestJsTypedArray, TestGet) {
    JsTypedArray<Int>::Ptr a = JsTypedArray<Int>::create();
    ASSERT_TRUE(a->add(5));
    ASSERT_TRUE(a->add(7));
    ASSERT_TRUE(a->get(0).equals(5));
    ASSERT_TRUE(a->get(1).equals(7));
}

TEST(GTestJsTypedArray, TestJsProperty) {
    JsTypedArray<Int>::Ptr a = JsTypedArray<Int>::create();
    a->setProperty(String::create("abc"), 7);
    ASSERT_TRUE(a->hasProperty(String::create("abc")));
    ASSERT_TRUE(a->getProperty(String::create("abc")).equals(7));

    a->deleteProperty(String::create("abc"));
    ASSERT_FALSE(a->hasProperty(String::create("abc")));
}

}  // namespace libj
<|endoftext|>


<commit_before>/*************************************************************************/
/*  context_gl_x11.cpp                                                   */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "context_gl_x11.h"

#ifdef X11_ENABLED
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#include <GL/glx.h>

#define GLX_CONTEXT_MAJOR_VERSION_ARB		0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB		0x2092

typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display*, GLXFBConfig, GLXContext, Bool, const int*);

struct ContextGL_X11_Private {

	::GLXContext glx_context;
};

void ContextGL_X11::release_current() {

	glXMakeCurrent(x11_display, None, NULL);
}

void ContextGL_X11::make_current() {

	glXMakeCurrent(x11_display, x11_window, p->glx_context);
}
void ContextGL_X11::swap_buffers() {

	glXSwapBuffers(x11_display,x11_window);
}
/*
static GLWrapperFuncPtr wrapper_get_proc_address(const char* p_function) {

	//print_line(String()+"getting proc of: "+p_function);
	GLWrapperFuncPtr func=(GLWrapperFuncPtr)glXGetProcAddress( (const GLubyte*) p_function);
	if (!func) {
		print_line("Couldn't find function: "+String(p_function));
	}

	return func;

}*/

Error ContextGL_X11::initialize() {

	GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = NULL;

//	const char *extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display));

	glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");

	ERR_FAIL_COND_V( !glXCreateContextAttribsARB, ERR_UNCONFIGURED );

	static int visual_attribs[] = {
	    GLX_RENDER_TYPE, GLX_RGBA_BIT,
	    GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
	    GLX_DOUBLEBUFFER, true,
	    GLX_RED_SIZE, 1,
	    GLX_GREEN_SIZE, 1,
	    GLX_BLUE_SIZE, 1,
	    GLX_DEPTH_SIZE,0,
	    None
	};

	int fbcount;
	GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount);
	ERR_FAIL_COND_V(!fbc,ERR_UNCONFIGURED);

	XVisualInfo *vi = glXGetVisualFromFBConfig(x11_display, fbc[0]);

	XSetWindowAttributes swa;

	swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone);
	swa.border_pixel = 0;
	swa.event_mask = StructureNotifyMask;

	/*
	char* windowid = getenv("GODOT_WINDOWID");
	if (windowid) {

		//freopen("/home/punto/stdout", "w", stdout);
		//reopen("/home/punto/stderr", "w", stderr);
		x11_window = atol(windowid);
	} else {
	*/
		x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa);
		ERR_FAIL_COND_V(!x11_window,ERR_UNCONFIGURED);
		XMapWindow(x11_display, x11_window);
		while(true) {
			// wait for mapnotify (window created)
			XEvent e;
			XNextEvent(x11_display, &e);
			if (e.type == MapNotify)
				break;
		}
		//};

	if (!OS::get_singleton()->get_video_mode().resizable) {
		XSizeHints *xsh;
		xsh = XAllocSizeHints();
		xsh->flags = PMinSize | PMaxSize;
		xsh->min_width = OS::get_singleton()->get_video_mode().width;
		xsh->max_width = OS::get_singleton()->get_video_mode().width;
		xsh->min_height = OS::get_singleton()->get_video_mode().height;
		xsh->max_height = OS::get_singleton()->get_video_mode().height;
		XSetWMNormalHints(x11_display, x11_window, xsh);
	}

	if (!opengl_3_context) {
		//oldstyle context:
		p->glx_context = glXCreateContext(x11_display, vi, 0, GL_TRUE);
	} else {
		static int context_attribs[] = {
			GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
			GLX_CONTEXT_MINOR_VERSION_ARB, 0,
			None
		};

		p->glx_context = glXCreateContextAttribsARB(x11_display, fbc[0], NULL, true, context_attribs);
		ERR_FAIL_COND_V(!p->glx_context,ERR_UNCONFIGURED);
	}

	glXMakeCurrent(x11_display, x11_window, p->glx_context);

	/*
	glWrapperInit(wrapper_get_proc_address);
	glFlush();

	glXSwapBuffers(x11_display,x11_window);
*/
	//glXMakeCurrent(x11_display, None, NULL);

	return OK;
}

int ContextGL_X11::get_window_width() {

	XWindowAttributes xwa;
	XGetWindowAttributes(x11_display,x11_window,&xwa);

	return xwa.width;
}
int ContextGL_X11::get_window_height() {
	XWindowAttributes xwa;
	XGetWindowAttributes(x11_display,x11_window,&xwa);

	return xwa.height;

}

ContextGL_X11::ContextGL_X11(::Display *p_x11_display,::Window &p_x11_window,const OS::VideoMode& p_default_video_mode,bool p_opengl_3_context) : x11_window(p_x11_window) {

	default_video_mode=p_default_video_mode;
	x11_display=p_x11_display;

	opengl_3_context=p_opengl_3_context;

	double_buffer=false;
	direct_render=false;
	glx_minor=glx_major=0;
	p = memnew( ContextGL_X11_Private );
	p->glx_context=0;
}

ContextGL_X11::~ContextGL_X11() {

	memdelete( p );
}

#endif
#endif
<commit_msg>fix z-buffer issues on x11/mesa<commit_after>/*************************************************************************/
/*  context_gl_x11.cpp                                                   */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "context_gl_x11.h"

#ifdef X11_ENABLED
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#include <GL/glx.h>

#define GLX_CONTEXT_MAJOR_VERSION_ARB		0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB		0x2092

typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display*, GLXFBConfig, GLXContext, Bool, const int*);

struct ContextGL_X11_Private {

	::GLXContext glx_context;
};

void ContextGL_X11::release_current() {

	glXMakeCurrent(x11_display, None, NULL);
}

void ContextGL_X11::make_current() {

	glXMakeCurrent(x11_display, x11_window, p->glx_context);
}
void ContextGL_X11::swap_buffers() {

	glXSwapBuffers(x11_display,x11_window);
}
/*
static GLWrapperFuncPtr wrapper_get_proc_address(const char* p_function) {

	//print_line(String()+"getting proc of: "+p_function);
	GLWrapperFuncPtr func=(GLWrapperFuncPtr)glXGetProcAddress( (const GLubyte*) p_function);
	if (!func) {
		print_line("Couldn't find function: "+String(p_function));
	}

	return func;

}*/

Error ContextGL_X11::initialize() {

	GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = NULL;

//	const char *extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display));

	glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");

	ERR_FAIL_COND_V( !glXCreateContextAttribsARB, ERR_UNCONFIGURED );

	static int visual_attribs[] = {
	    GLX_RENDER_TYPE, GLX_RGBA_BIT,
	    GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
	    GLX_DOUBLEBUFFER, true,
	    GLX_RED_SIZE, 1,
	    GLX_GREEN_SIZE, 1,
	    GLX_BLUE_SIZE, 1,
	    GLX_DEPTH_SIZE, 24,
	    None
	};

	int fbcount;
	GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount);
	ERR_FAIL_COND_V(!fbc,ERR_UNCONFIGURED);

	XVisualInfo *vi = glXGetVisualFromFBConfig(x11_display, fbc[0]);

	XSetWindowAttributes swa;

	swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone);
	swa.border_pixel = 0;
	swa.event_mask = StructureNotifyMask;

	/*
	char* windowid = getenv("GODOT_WINDOWID");
	if (windowid) {

		//freopen("/home/punto/stdout", "w", stdout);
		//reopen("/home/punto/stderr", "w", stderr);
		x11_window = atol(windowid);
	} else {
	*/
		x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa);
		ERR_FAIL_COND_V(!x11_window,ERR_UNCONFIGURED);
		XMapWindow(x11_display, x11_window);
		while(true) {
			// wait for mapnotify (window created)
			XEvent e;
			XNextEvent(x11_display, &e);
			if (e.type == MapNotify)
				break;
		}
		//};

	if (!OS::get_singleton()->get_video_mode().resizable) {
		XSizeHints *xsh;
		xsh = XAllocSizeHints();
		xsh->flags = PMinSize | PMaxSize;
		xsh->min_width = OS::get_singleton()->get_video_mode().width;
		xsh->max_width = OS::get_singleton()->get_video_mode().width;
		xsh->min_height = OS::get_singleton()->get_video_mode().height;
		xsh->max_height = OS::get_singleton()->get_video_mode().height;
		XSetWMNormalHints(x11_display, x11_window, xsh);
	}

	if (!opengl_3_context) {
		//oldstyle context:
		p->glx_context = glXCreateContext(x11_display, vi, 0, GL_TRUE);
	} else {
		static int context_attribs[] = {
			GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
			GLX_CONTEXT_MINOR_VERSION_ARB, 0,
			None
		};

		p->glx_context = glXCreateContextAttribsARB(x11_display, fbc[0], NULL, true, context_attribs);
		ERR_FAIL_COND_V(!p->glx_context,ERR_UNCONFIGURED);
	}

	glXMakeCurrent(x11_display, x11_window, p->glx_context);

	/*
	glWrapperInit(wrapper_get_proc_address);
	glFlush();

	glXSwapBuffers(x11_display,x11_window);
*/
	//glXMakeCurrent(x11_display, None, NULL);

	return OK;
}

int ContextGL_X11::get_window_width() {

	XWindowAttributes xwa;
	XGetWindowAttributes(x11_display,x11_window,&xwa);

	return xwa.width;
}
int ContextGL_X11::get_window_height() {
	XWindowAttributes xwa;
	XGetWindowAttributes(x11_display,x11_window,&xwa);

	return xwa.height;

}

ContextGL_X11::ContextGL_X11(::Display *p_x11_display,::Window &p_x11_window,const OS::VideoMode& p_default_video_mode,bool p_opengl_3_context) : x11_window(p_x11_window) {

	default_video_mode=p_default_video_mode;
	x11_display=p_x11_display;

	opengl_3_context=p_opengl_3_context;

	double_buffer=false;
	direct_render=false;
	glx_minor=glx_major=0;
	p = memnew( ContextGL_X11_Private );
	p->glx_context=0;
}

ContextGL_X11::~ContextGL_X11() {

	memdelete( p );
}

#endif
#endif
<|endoftext|>