<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: OStyle.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:28:04 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "OStyle.hxx"
#include "macros.hxx"

#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#include "com/sun/star/uno/RuntimeException.hpp"

using namespace ::com::sun::star;

using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Reference;
using ::rtl::OUString;
using ::osl::MutexGuard;

namespace property
{

OStyle::OStyle( const Reference< container::XNameAccess > & xStyleFamily,
                ::osl::Mutex & _rMutex ) :
        OPropertySet( _rMutex ),
        m_xStyleFamily( xStyleFamily ),
        m_bUserDefined( false ),
        m_rMutex( _rMutex )
{}

OStyle::~OStyle()
{}

::osl::Mutex & OStyle::GetMutex()
{
    return m_rMutex;
}

// ____ XStyle ____
sal_Bool SAL_CALL OStyle::isUserDefined()
    throw (uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );
    return m_bUserDefined;
    // \--
}

sal_Bool SAL_CALL OStyle::isInUse()
    throw (uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );

    // aBoundLC is a member of cppuhelper::OPropertySetHelper
    // it is assumed that a style is in use whenever some component is
    // registered here as listener
    return ( aBoundLC.getContainedTypes().getLength() > 0 );
    // \--
}

OUString SAL_CALL OStyle::getParentStyle()
    throw (uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );
    return m_aParentStyleName;
    // \--
}

void SAL_CALL OStyle::setParentStyle( const OUString& aParentStyle )
    throw (container::NoSuchElementException,
           uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );
    m_aParentStyleName = aParentStyle;
    // \--
}

// ____ XNamed (base of XStyle) ____

OUString SAL_CALL OStyle::getName()
    throw (uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );
    return m_aName;
    // \--
}

void SAL_CALL OStyle::setName( const ::rtl::OUString& aName )
    throw (uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );
    OSL_ASSERT( m_xStyleFamily.is() );

    // note: RuntimeException is not very apropriate for this, but I have no
    // other choice
    if( m_xStyleFamily->hasByName( aName ))
    {
        OSL_ENSURE( false, "Style name already exists!" );
        throw uno::RuntimeException(
            C2U( "Style name already exists: " ) + aName,
            static_cast< style::XStyle * >( this ));
    }
    else
    {
        // ToDo: Change the name in the container (XStyleFamiliy)
        m_aName = aName;
    }
    // \--
}

// ____ XInterface ____
uno::Any SAL_CALL OStyle::queryInterface( const uno::Type& aType )
    throw (uno::RuntimeException)
{
    uno::Any aResult = OPropertySet::queryInterface( aType );

    if( ! aResult.hasValue())
    {
        return ::cppu::queryInterface(
            aType,
            static_cast< style::XStyle * >( this ));
    }

    return aResult;
}

// void SAL_CALL OStyle::acquire() throw ()
// {
//     OPropertySet::acquire();
// }

// void SAL_CALL OStyle::release() throw ()
// {
//     OPropertySet::release();
// }

// ____ XServiceInfo ____
// OUString SAL_CALL
//     OStyle::getImplementationName()
//     throw (uno::RuntimeException)
// {
//     return OUString( RTL_CONSTASCII_USTRINGPARAM( "property::OStyle" ));
// }

// sal_Bool SAL_CALL
//     OStyle::supportsService( const OUString& ServiceName )
//     throw (uno::RuntimeException)
// {
//     Sequence< OUString > aServices( getSupportedServiceNames() );

//     sal_Int32 nI = aServices.getLength() - 1;
//     for( ; nI >= 0; --nI )
//     {
//         if( aServices[ nI ].equals( ServiceName ))
//             return sal_True;
//     }
//     return sal_False;
// }

// Sequence< OUString > SAL_CALL
//     OStyle::getSupportedServiceNames()
//     throw (uno::RuntimeException)
// {
//     Sequence< OUString > aServiceNames( 2 );
//     // from base OPropertySet
//     aServiceNames[ 0 ] = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.beans.PropertySet" ));
//     // new service
//     aServiceNames[ 1 ] = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.style.Style" ));
//     return aServiceNames;
// }

// ____ XTypeProvider ____
// Sequence< uno::Type > SAL_CALL
//     OStyle::getTypes()
//     throw (uno::RuntimeException)
// {
//     Sequence< uno::Type > aResult( OPropertySet::getTypes() );
//     aResult.realloc( aResult.getLength() + 1 );
//     aResult[ aResult.getLength() - 1 ] =
//         ::getCppuType( reinterpret_cast< const Reference< style::XStyle > *>(0));

//     return aResult;
// }

// Sequence< sal_Int8 > SAL_CALL
//     OStyle::getImplementationId()
//     throw (uno::RuntimeException)
// {
//  static uno::Sequence< sal_Int8 > aId;
//  if( aId.getLength() == 0 )
//  {
//      aId.realloc( 16 );
//      rtl_createUuid( (sal_uInt8 *)aId.getArray(), 0, sal_True );
//  }
//  return aId;
// }

} //  namespace property
<commit_msg>INTEGRATION: CWS chart2mst3 (1.3.12); FILE MERGED 2006/10/18 17:18:36 bm 1.3.12.2: RESYNC: (1.3-1.4); FILE MERGED 2006/03/07 12:35:35 bm 1.3.12.1: avoid variables starting with underscores. rMutex is a base-class member so use par_rMutex instead<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: OStyle.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 19:03:03 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "OStyle.hxx"
#include "macros.hxx"

#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#include "com/sun/star/uno/RuntimeException.hpp"

using namespace ::com::sun::star;

using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Reference;
using ::rtl::OUString;
using ::osl::MutexGuard;

namespace property
{

OStyle::OStyle( const Reference< container::XNameAccess > & xStyleFamily,
                ::osl::Mutex & par_rMutex ) :
        OPropertySet( par_rMutex ),
        m_xStyleFamily( xStyleFamily ),
        m_bUserDefined( false ),
        m_rMutex( par_rMutex )
{}

OStyle::~OStyle()
{}

::osl::Mutex & OStyle::GetMutex()
{
    return m_rMutex;
}

// ____ XStyle ____
sal_Bool SAL_CALL OStyle::isUserDefined()
    throw (uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );
    return m_bUserDefined;
    // \--
}

sal_Bool SAL_CALL OStyle::isInUse()
    throw (uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );

    // aBoundLC is a member of cppuhelper::OPropertySetHelper
    // it is assumed that a style is in use whenever some component is
    // registered here as listener
    return ( aBoundLC.getContainedTypes().getLength() > 0 );
    // \--
}

OUString SAL_CALL OStyle::getParentStyle()
    throw (uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );
    return m_aParentStyleName;
    // \--
}

void SAL_CALL OStyle::setParentStyle( const OUString& aParentStyle )
    throw (container::NoSuchElementException,
           uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );
    m_aParentStyleName = aParentStyle;
    // \--
}

// ____ XNamed (base of XStyle) ____

OUString SAL_CALL OStyle::getName()
    throw (uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );
    return m_aName;
    // \--
}

void SAL_CALL OStyle::setName( const ::rtl::OUString& aName )
    throw (uno::RuntimeException)
{
    // /--
    MutexGuard aGuard( GetMutex() );
    OSL_ASSERT( m_xStyleFamily.is() );

    // note: RuntimeException is not very apropriate for this, but I have no
    // other choice
    if( m_xStyleFamily->hasByName( aName ))
    {
        OSL_ENSURE( false, "Style name already exists!" );
        throw uno::RuntimeException(
            C2U( "Style name already exists: " ) + aName,
            static_cast< style::XStyle * >( this ));
    }
    else
    {
        // ToDo: Change the name in the container (XStyleFamiliy)
        m_aName = aName;
    }
    // \--
}

// ____ XInterface ____
uno::Any SAL_CALL OStyle::queryInterface( const uno::Type& aType )
    throw (uno::RuntimeException)
{
    uno::Any aResult = OPropertySet::queryInterface( aType );

    if( ! aResult.hasValue())
    {
        return ::cppu::queryInterface(
            aType,
            static_cast< style::XStyle * >( this ));
    }

    return aResult;
}

// void SAL_CALL OStyle::acquire() throw ()
// {
//     OPropertySet::acquire();
// }

// void SAL_CALL OStyle::release() throw ()
// {
//     OPropertySet::release();
// }

// ____ XServiceInfo ____
// OUString SAL_CALL
//     OStyle::getImplementationName()
//     throw (uno::RuntimeException)
// {
//     return OUString( RTL_CONSTASCII_USTRINGPARAM( "property::OStyle" ));
// }

// sal_Bool SAL_CALL
//     OStyle::supportsService( const OUString& ServiceName )
//     throw (uno::RuntimeException)
// {
//     Sequence< OUString > aServices( getSupportedServiceNames() );

//     sal_Int32 nI = aServices.getLength() - 1;
//     for( ; nI >= 0; --nI )
//     {
//         if( aServices[ nI ].equals( ServiceName ))
//             return sal_True;
//     }
//     return sal_False;
// }

// Sequence< OUString > SAL_CALL
//     OStyle::getSupportedServiceNames()
//     throw (uno::RuntimeException)
// {
//     Sequence< OUString > aServiceNames( 2 );
//     // from base OPropertySet
//     aServiceNames[ 0 ] = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.beans.PropertySet" ));
//     // new service
//     aServiceNames[ 1 ] = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.style.Style" ));
//     return aServiceNames;
// }

// ____ XTypeProvider ____
// Sequence< uno::Type > SAL_CALL
//     OStyle::getTypes()
//     throw (uno::RuntimeException)
// {
//     Sequence< uno::Type > aResult( OPropertySet::getTypes() );
//     aResult.realloc( aResult.getLength() + 1 );
//     aResult[ aResult.getLength() - 1 ] =
//         ::getCppuType( reinterpret_cast< const Reference< style::XStyle > *>(0));

//     return aResult;
// }

// Sequence< sal_Int8 > SAL_CALL
//     OStyle::getImplementationId()
//     throw (uno::RuntimeException)
// {
//  static uno::Sequence< sal_Int8 > aId;
//  if( aId.getLength() == 0 )
//  {
//      aId.realloc( 16 );
//      rtl_createUuid( (sal_uInt8 *)aId.getArray(), 0, sal_True );
//  }
//  return aId;
// }

} //  namespace property
<|endoftext|>


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

#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#include <limits.h>

#include <sbx.hxx>

#include "svtdata.hxx"
#include "svarray.hxx"
#include "args.hxx"
#include "itempool.hxx"
#include "itemdel.hxx"

// STATIC DATA -----------------------------------------------------------

DBG_NAME(SfxItemDesruptor_Impl);

// -----------------------------------------------------------------------

class SfxItemDesruptor_Impl
{
    SfxPoolItem *pItem;
    Link         aLink;

private:
                 DECL_LINK( Delete, void * );
                 SfxItemDesruptor_Impl( const SfxItemDesruptor_Impl& ); // n.i.

public:
                 SfxItemDesruptor_Impl( SfxPoolItem *pItemToDesrupt );
                 ~SfxItemDesruptor_Impl();
};

SV_DECL_PTRARR( SfxItemDesruptorList_Impl, SfxItemDesruptor_Impl*, 4, 4 );

// ------------------------------------------------------------------------
SfxItemDesruptor_Impl::SfxItemDesruptor_Impl( SfxPoolItem *pItemToDesrupt ):
    pItem(pItemToDesrupt),
    aLink( LINK(this, SfxItemDesruptor_Impl, Delete) )
{
    DBG_CTOR(SfxItemDesruptor_Impl, 0);

    DBG_ASSERT( 0 == pItem->GetRefCount(), "desrupting pooled item" );
    pItem->SetKind( SFX_ITEMS_DELETEONIDLE );

    // im Idle abarbeiten
    GetpApp()->InsertIdleHdl( aLink, 1 );

    // und in Liste eintragen (damit geflusht werden kann)
    SfxItemDesruptorList_Impl* &rpList = ImpSvtData::GetSvtData().pItemDesruptList;
    if ( !rpList )
        rpList = new SfxItemDesruptorList_Impl;
    const SfxItemDesruptor_Impl *pThis = this;
    rpList->Insert( pThis, rpList->Count() );
}

// ------------------------------------------------------------------------
SfxItemDesruptor_Impl::~SfxItemDesruptor_Impl()
{
    DBG_DTOR(SfxItemDesruptor_Impl, 0);

    // aus Idle-Handler austragen
    GetpApp()->RemoveIdleHdl( aLink );

    // und aus Liste austragen
    SfxItemDesruptorList_Impl* &rpList = ImpSvtData::GetSvtData().pItemDesruptList;
    DBG_ASSERT( rpList, "no DesruptorList" );
    const SfxItemDesruptor_Impl *pThis = this;
    if ( rpList ) HACK(warum?)
        rpList->Remove( rpList->GetPos(pThis) );

    // reset RefCount (was set to SFX_ITEMS_SPECIAL before!)
    pItem->SetRefCount( 0 );
    DBG_CHKOBJ( pItem, SfxPoolItem, 0 );
    delete pItem;
}

// ------------------------------------------------------------------------
IMPL_LINK( SfxItemDesruptor_Impl, Delete, void *, pvoid )
{
    {DBG_CHKTHIS(SfxItemDesruptor_Impl, 0);}
    delete this;
    return 0;
}

// ------------------------------------------------------------------------
SfxPoolItem* DeleteItemOnIdle( SfxPoolItem* pItem )
{
    DBG_ASSERT( 0 == pItem->GetRefCount(), "deleting item in use" );
    new SfxItemDesruptor_Impl( pItem );
    return pItem;
}

// ------------------------------------------------------------------------
void DeleteOnIdleItems()
{
    SfxItemDesruptorList_Impl* &rpList
     = ImpSvtData::GetSvtData().pItemDesruptList;
    if ( rpList )
    {
        USHORT n;
        while ( 0 != ( n = rpList->Count() ) )
            // Remove ist implizit im Dtor
            delete rpList->GetObject( n-1 );
        DELETEZ(rpList);
    }
}

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

#include "itemdel.hxx"

#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#include <limits.h>

#include "svtdata.hxx"
#include "svarray.hxx"
#include "itempool.hxx"

// STATIC DATA -----------------------------------------------------------

DBG_NAME(SfxItemDesruptor_Impl);

// -----------------------------------------------------------------------

class SfxItemDesruptor_Impl
{
    SfxPoolItem *pItem;
    Link         aLink;

private:
                 DECL_LINK( Delete, void * );
                 SfxItemDesruptor_Impl( const SfxItemDesruptor_Impl& ); // n.i.

public:
                 SfxItemDesruptor_Impl( SfxPoolItem *pItemToDesrupt );
                 ~SfxItemDesruptor_Impl();
};

SV_DECL_PTRARR( SfxItemDesruptorList_Impl, SfxItemDesruptor_Impl*, 4, 4 );

// ------------------------------------------------------------------------
SfxItemDesruptor_Impl::SfxItemDesruptor_Impl( SfxPoolItem *pItemToDesrupt ):
    pItem(pItemToDesrupt),
    aLink( LINK(this, SfxItemDesruptor_Impl, Delete) )
{
    DBG_CTOR(SfxItemDesruptor_Impl, 0);

    DBG_ASSERT( 0 == pItem->GetRefCount(), "desrupting pooled item" );
    pItem->SetKind( SFX_ITEMS_DELETEONIDLE );

    // im Idle abarbeiten
    GetpApp()->InsertIdleHdl( aLink, 1 );

    // und in Liste eintragen (damit geflusht werden kann)
    SfxItemDesruptorList_Impl* &rpList = ImpSvtData::GetSvtData().pItemDesruptList;
    if ( !rpList )
        rpList = new SfxItemDesruptorList_Impl;
    const SfxItemDesruptor_Impl *pThis = this;
    rpList->Insert( pThis, rpList->Count() );
}

// ------------------------------------------------------------------------
SfxItemDesruptor_Impl::~SfxItemDesruptor_Impl()
{
    DBG_DTOR(SfxItemDesruptor_Impl, 0);

    // aus Idle-Handler austragen
    GetpApp()->RemoveIdleHdl( aLink );

    // und aus Liste austragen
    SfxItemDesruptorList_Impl* &rpList = ImpSvtData::GetSvtData().pItemDesruptList;
    DBG_ASSERT( rpList, "no DesruptorList" );
    const SfxItemDesruptor_Impl *pThis = this;
    if ( rpList ) HACK(warum?)
        rpList->Remove( rpList->GetPos(pThis) );

    // reset RefCount (was set to SFX_ITEMS_SPECIAL before!)
    pItem->SetRefCount( 0 );
    DBG_CHKOBJ( pItem, SfxPoolItem, 0 );
    delete pItem;
}

// ------------------------------------------------------------------------
IMPL_LINK( SfxItemDesruptor_Impl, Delete, void *, pvoid )
{
    {DBG_CHKTHIS(SfxItemDesruptor_Impl, 0);}
    delete this;
    return 0;
}

// ------------------------------------------------------------------------
SfxPoolItem* DeleteItemOnIdle( SfxPoolItem* pItem )
{
    DBG_ASSERT( 0 == pItem->GetRefCount(), "deleting item in use" );
    new SfxItemDesruptor_Impl( pItem );
    return pItem;
}

// ------------------------------------------------------------------------
void DeleteOnIdleItems()
{
    SfxItemDesruptorList_Impl* &rpList
     = ImpSvtData::GetSvtData().pItemDesruptList;
    if ( rpList )
    {
        USHORT n;
        while ( 0 != ( n = rpList->Count() ) )
            // Remove ist implizit im Dtor
            delete rpList->GetObject( n-1 );
        DELETEZ(rpList);
    }
}

<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    topScene = new QGraphicsScene(this);
    ui->topView->setScene(topScene);
    rightScene = new QGraphicsScene(this);
    ui->rightView->setScene(rightScene);
    bottomScene = new QGraphicsScene(this);
    ui->bottomView->setScene(bottomScene);
    leftScene = new QGraphicsScene(this);
    ui->leftView->setScene(leftScene);
    diffuseScene = new QGraphicsScene(this);
    ui->diffuseView->setScene(diffuseScene);
    resultScene = new QGraphicsScene(this);
    ui->resultView->setScene(resultScene);
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), ui->oglWidget, SLOT(update()));
    timer->start(40);
}

MainWindow::~MainWindow()
{
    delete ui;
}

QFileInfo MainWindow::OpenFile(QPushButton* button, QImage& image, QGraphicsScene* scene, QGraphicsView* view)
{

    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "/", "Image File (*.png)");
    QFileInfo fi(filename);

    if(fi.exists())
    {
        button->setText(fi.fileName());
        image.load(fi.absoluteFilePath());
        scene->clear();
        scene->addPixmap(QPixmap::fromImage(image.scaled(QSize(100, 100))));
        view->show();
    }
    return fi;
}

void MainWindow::EnableGenerateButton(bool topPresent, bool rightPresent, bool bottomPresent, bool leftPresent)
{
    if(topPresent && rightPresent && bottomPresent && leftPresent)
    {
        ui->generateButton->setEnabled(true);
    }
}

void MainWindow::on_topFileButton_clicked()
{
    OpenFile(ui->topFileButton, topImage, topScene, ui->topView);
    EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());
}

void MainWindow::on_rightFileButton_clicked()
{
    OpenFile(ui->rightFileButton, rightImage, rightScene, ui->rightView);
    EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());
}

void MainWindow::on_bottomFileButton_clicked()
{
   OpenFile(ui->bottomFileButton, bottomImage, bottomScene, ui->bottomView);
   EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());
}

void MainWindow::on_leftFileButton_clicked()
{
    OpenFile(ui->leftFileButton, leftImage, leftScene, ui->leftView);
    EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());
}

void MainWindow::on_diffuseFileButton_clicked()
{
    QFileInfo fi = OpenFile(ui->diffuseFileButton, diffuseImage, diffuseScene, ui->diffuseView);
    ui->oglWidget->SetDiffuse(diffuseImage);
}

bool MainWindow::SameSize(QImage first, QImage second, QImage third, QImage fourth)
{
    QSize k = first.size();
    return k == second.size() && k == third.size() && k == fourth.size();
}

void MainWindow::ProcessNormals(QImage image, int imagetype)
{
    for(int y = 0; y < image.height(); y++)
    {
        for(int x = 0; x < image.width(); x++)
        {
            QColor color = image.pixel(x, y);
            double normal = color.valueF();
            normal -= 0.5;
            normal *= 2.0;
            if(imagetype == IMAGE::TOP)
            {
                QVector3D vector(0.0, normal, 0.0);
                normals[image.width() * y + x] = normals[image.width() * y + x] + vector;
            }

            if(imagetype == IMAGE::RIGHT)
            {
                QVector3D vector(normal, 0.0, 0.0);
                normals[image.width() * y + x] = normals[image.width() * y + x] + vector;
            }

            if(imagetype == IMAGE::BOTTOM)
            {
                QVector3D vector(0.0, -normal, 0.0);
                normals[image.width() * y + x] = normals[image.width() * y + x] + vector;
            }

            if(imagetype == IMAGE::LEFT)
            {
                QVector3D vector(-normal, 0.0, 0.0);
                normals[image.width() * y + x] = normals[image.width() * y + x] + vector;
            }
        }
    }
}

void MainWindow::on_generateButton_clicked()
{
    //Ensure all images are the same size
    if(!SameSize(topImage, rightImage, leftImage, bottomImage))
    {
        QMessageBox msgBox;
        msgBox.setText("Images are not the same size!");
        msgBox.exec();
        return;
    }

    int normalMapSize = topImage.size().width()*topImage.size().height();
    normals = new QVector3D[normalMapSize];

    for(int i = 0; i < normalMapSize; i++)
    {
        //Point all vectors -z
        normals[i].setZ(-1.0);
        normals[i].setY(0);
        normals[i].setX(0);
    }

    ProcessNormals(topImage, IMAGE::TOP);
    ProcessNormals(rightImage, IMAGE::RIGHT);
    ProcessNormals(bottomImage, IMAGE::BOTTOM);
    ProcessNormals(leftImage, IMAGE::LEFT);

    resultImage = QImage(topImage.width(), topImage.height(), QImage::Format_RGB32);

    for(int i = 0; i < normalMapSize; i++)
    {
        normals[i].normalize();
        QColor normColor;
        normColor.setRedF((normals[i].x()+1.0)/2.0);
        normColor.setGreenF((normals[i].y()+1.0)/2.0);
        normColor.setBlueF((-normals[i].z()+1.0)/2.0);
        int yCoord = i / topImage.width();
        int xCoord = i % topImage.width();
        resultImage.setPixel(QPoint(xCoord, yCoord), normColor.rgb());
    }
    resultScene->addPixmap(QPixmap::fromImage(resultImage.scaled(QSize(100, 100))));
    ui->resultView->show();
    ui->oglWidget->SetNormalMap(resultImage);
}
<commit_msg>Near-lossless optimize of generation<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <algorithm>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    topScene = new QGraphicsScene(this);
    ui->topView->setScene(topScene);
    rightScene = new QGraphicsScene(this);
    ui->rightView->setScene(rightScene);
    bottomScene = new QGraphicsScene(this);
    ui->bottomView->setScene(bottomScene);
    leftScene = new QGraphicsScene(this);
    ui->leftView->setScene(leftScene);
    diffuseScene = new QGraphicsScene(this);
    ui->diffuseView->setScene(diffuseScene);
    resultScene = new QGraphicsScene(this);
    ui->resultView->setScene(resultScene);
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), ui->oglWidget, SLOT(update()));
    timer->start(40);
}

MainWindow::~MainWindow()
{
    delete ui;
}

QFileInfo MainWindow::OpenFile(QPushButton* button, QImage& image, QGraphicsScene* scene, QGraphicsView* view)
{

    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "/", "Image File (*.png)");
    QFileInfo fi(filename);

    if(fi.exists())
    {
        button->setText(fi.fileName());
        image.load(fi.absoluteFilePath());
        scene->clear();
        scene->addPixmap(QPixmap::fromImage(image.scaled(QSize(100, 100))));
        view->show();
    }
    return fi;
}

void MainWindow::EnableGenerateButton(bool topPresent, bool rightPresent, bool bottomPresent, bool leftPresent)
{
    if(topPresent && rightPresent && bottomPresent && leftPresent)
    {
        ui->generateButton->setEnabled(true);
    }
}

void MainWindow::on_topFileButton_clicked()
{
    OpenFile(ui->topFileButton, topImage, topScene, ui->topView);
    EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());
}

void MainWindow::on_rightFileButton_clicked()
{
    OpenFile(ui->rightFileButton, rightImage, rightScene, ui->rightView);
    EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());
}

void MainWindow::on_bottomFileButton_clicked()
{
   OpenFile(ui->bottomFileButton, bottomImage, bottomScene, ui->bottomView);
   EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());
}

void MainWindow::on_leftFileButton_clicked()
{
    OpenFile(ui->leftFileButton, leftImage, leftScene, ui->leftView);
    EnableGenerateButton(!topImage.isNull(), !rightImage.isNull(), !bottomImage.isNull(), !leftImage.isNull());
}

void MainWindow::on_diffuseFileButton_clicked()
{
    QFileInfo fi = OpenFile(ui->diffuseFileButton, diffuseImage, diffuseScene, ui->diffuseView);
    ui->oglWidget->SetDiffuse(diffuseImage);
}

bool MainWindow::SameSize(QImage first, QImage second, QImage third, QImage fourth)
{
    QSize k = first.size();
    return k == second.size() && k == third.size() && k == fourth.size();
}

static inline int linearGray(QRgb rgb)
{
    return std::max({qRed(rgb), qGreen(rgb), qBlue(rgb)});
}

void MainWindow::ProcessNormals(QImage image, int imagetype)
{
    for(int y = 0; y < image.height(); y++)
    {
        for(int x = 0; x < image.width(); x++)
        {
            double normal = (double)linearGray(image.pixel(x, y)) / 255.0;
            normal -= 0.5;
            normal *= 2.0;
            if(imagetype == IMAGE::TOP)
            {
                QVector3D vector(0.0, normal, 0.0);
                normals[image.width() * y + x] = normals[image.width() * y + x] + vector;
            }

            if(imagetype == IMAGE::RIGHT)
            {
                QVector3D vector(normal, 0.0, 0.0);
                normals[image.width() * y + x] = normals[image.width() * y + x] + vector;
            }

            if(imagetype == IMAGE::BOTTOM)
            {
                QVector3D vector(0.0, -normal, 0.0);
                normals[image.width() * y + x] = normals[image.width() * y + x] + vector;
            }

            if(imagetype == IMAGE::LEFT)
            {
                QVector3D vector(-normal, 0.0, 0.0);
                normals[image.width() * y + x] = normals[image.width() * y + x] + vector;
            }
        }
    }
}

void MainWindow::on_generateButton_clicked()
{
    //Ensure all images are the same size
    if(!SameSize(topImage, rightImage, leftImage, bottomImage))
    {
        QMessageBox msgBox;
        msgBox.setText("Images are not the same size!");
        msgBox.exec();
        return;
    }

    int normalMapSize = topImage.size().width()*topImage.size().height();
    normals = new QVector3D[normalMapSize];

    for(int i = 0; i < normalMapSize; i++)
    {
        //Point all vectors -z
        normals[i].setZ(-1.0);
        normals[i].setY(0);
        normals[i].setX(0);
    }

    ProcessNormals(topImage, IMAGE::TOP);
    ProcessNormals(rightImage, IMAGE::RIGHT);
    ProcessNormals(bottomImage, IMAGE::BOTTOM);
    ProcessNormals(leftImage, IMAGE::LEFT);

    resultImage = QImage(topImage.width(), topImage.height(), QImage::Format_RGB32);

    for(int i = 0; i < normalMapSize; i++)
    {
        normals[i].normalize();
        QColor normColor;
        normColor.setRgbF((normals[i].x()+1.0)/2.0,
                          (normals[i].y()+1.0)/2.0,
                          (-normals[i].z()+1.0)/2.0);
        int yCoord = i / topImage.width();
        int xCoord = i % topImage.width();
        resultImage.setPixel(QPoint(xCoord, yCoord), normColor.rgb());
    }
    resultScene->addPixmap(QPixmap::fromImage(resultImage.scaled(QSize(100, 100))));
    ui->resultView->show();
    ui->oglWidget->SetNormalMap(resultImage);
}
<|endoftext|>


<commit_before>/*
 * ContextMerge.cpp
 *
 *  Created on: Mar 26, 2014
 *      Author: nek3d
 */

#include "ContextMerge.h"

ContextMerge::ContextMerge()
{
	setUseMergedIntervals(true);
	setColumnOpsMethods(true);

	//merge has no default columnOps the way map does, so we'll need to clear those.
	_keyListOps->setColumns("");
	_keyListOps->setOperations("");

}

ContextMerge::~ContextMerge()
{

}

bool ContextMerge::parseCmdArgs(int argc, char **argv, int skipFirstArgs)
{
	_argc = argc;
	_argv = argv;
	_skipFirstArgs = skipFirstArgs;
	if (_argc < 2) {
		setShowHelp(true);
		return false;
	}

	setProgram(_programNames[argv[0]]);

	_argsProcessed.resize(_argc - _skipFirstArgs, false);

	for (_i=_skipFirstArgs; _i < argc; _i++) {
		if (isUsed(_i - _skipFirstArgs)) {
			continue;
		}
		else if (strcmp(_argv[_i], "-n") == 0) {
			if (!handle_n()) return false;
		}
		else if (strcmp(_argv[_i], "-nms") == 0) {
			if (!handle_nms()) return false;
		}
		else if (strcmp(_argv[_i], "-scores") == 0) {
			if (!handle_scores()) return false;
		}
		else if (strcmp(_argv[_i], "-delim") == 0) {
			if (!handle_delim()) return false;
		}
		else if (strcmp(_argv[_i], "-d") == 0) {
			if (!handle_d()) return false;
		}
		else if (strcmp(_argv[_i], "-s") == 0) {
			if (!handle_s()) return false;
		}
		else if (strcmp(_argv[_i], "-S") == 0) {
			if (!handle_S()) return false;
		}
	}
	return ContextBase::parseCmdArgs(argc, argv, _skipFirstArgs);
}

bool ContextMerge::isValidState()
{
	// Special: The merge program does not have default
	//column operations, so if none were entered, disable column ops.
	if (_keyListOps->getColumns().empty() && _keyListOps->getOperations().empty()) {
		setColumnOpsMethods(false);
		delete _keyListOps;
		_keyListOps = NULL;
	}
	if (!ContextBase::isValidState()) {
		return false;
	}
	if (_files.size() != 1) {
		_errorMsg = "\n***** ERROR: input file not specified. *****";
		// Allow only one input file for now
		return false;
	}

	//
	// Tests for stranded merge
	//
	if (_desiredStrand != FileRecordMergeMgr::ANY_STRAND) { // requested stranded merge
		// make sure file has strand.
		if (!getFile(0)->recordsHaveStrand()) {
			_errorMsg = "\n***** ERROR: stranded merge requested, but input file records do not have strand. *****";
			return false;
		}
		//make sure file is not VCF.
		if (getFile(0)->getFileType() == FileRecordTypeChecker::VCF_FILE_TYPE) {
			_errorMsg = "\n***** ERROR: stranded merge not supported for VCF files. *****";
			return false;
		}
	}

	//column operations not allowed with BAM input
	if (hasColumnOpsMethods() &&
			getFile(0)->getFileType() == FileRecordTypeChecker::BAM_FILE_TYPE) {
		_errorMsg = "\n***** ERROR: stranded merge not supported for VCF files. *****";
		return false;
	}
	return true;
}

bool ContextMerge::handle_d() {
    if ((_i+1) < _argc) {
    	if (isNumeric(_argv[_i+1])) {
			int dist = str2chrPos(_argv[_i+1]);
			if (dist >=0 ) {
				_maxDistance = dist;
		    	markUsed(_i - _skipFirstArgs);
		        _i++;
		        markUsed(_i - _skipFirstArgs);
				return true;
			}
    	}
    }
	_errorMsg = "\n***** ERROR: -d option must be followed by an integer value *****";
	return false;
}

bool ContextMerge::handle_n()
{
	markUsed(_i - _skipFirstArgs);
	_errorMsg = "\n***** ERROR: -n option is deprecated. Please see the documentation for the -c and -o column operation options. *****";
    return false;
}

bool ContextMerge::handle_nms()
{
	markUsed(_i - _skipFirstArgs);
	_errorMsg = "\n***** ERROR: -nms option is deprecated. Please see the documentation for the -c and -o column operation options. *****";
    return false;

}

bool ContextMerge::handle_scores()
{
	// No longer supporting this deprecated option.
	markUsed(_i - _skipFirstArgs);
	_errorMsg = "\n***** ERROR: -scores option is deprecated. Please see the documentation for the -c and -o column operation options. *****";
    return false;
}

bool ContextMerge::handle_s() {
	_desiredStrand = FileRecordMergeMgr::SAME_STRAND_EITHER;
	markUsed(_i - _skipFirstArgs);
	return true;
}

bool ContextMerge::handle_S() {
    if ((_i+1) < _argc) {
    	bool validChar = false;
    	if (_argv[_i+1][0] == '+') {
			_desiredStrand = FileRecordMergeMgr::SAME_STRAND_FORWARD;
			validChar = true;
    	} else if (_argv[_i+1][0] == '-') {
    		validChar = true;
			_desiredStrand = FileRecordMergeMgr::SAME_STRAND_REVERSE;
    	}
    	if (validChar) {
			markUsed(_i - _skipFirstArgs);
			_i++;
			markUsed(_i - _skipFirstArgs);
			return true;
    	}
    }
	_errorMsg = "\n***** ERROR: -S option must be followed by + or -. *****";
	return false;
}
<commit_msg>allow merge -d to have negative values for minimum overlap.<commit_after>/*
 * ContextMerge.cpp
 *
 *  Created on: Mar 26, 2014
 *      Author: nek3d
 */

#include "ContextMerge.h"

ContextMerge::ContextMerge()
{
	setUseMergedIntervals(true);
	setColumnOpsMethods(true);

	//merge has no default columnOps the way map does, so we'll need to clear those.
	_keyListOps->setColumns("");
	_keyListOps->setOperations("");

}

ContextMerge::~ContextMerge()
{

}

bool ContextMerge::parseCmdArgs(int argc, char **argv, int skipFirstArgs)
{
	_argc = argc;
	_argv = argv;
	_skipFirstArgs = skipFirstArgs;
	if (_argc < 2) {
		setShowHelp(true);
		return false;
	}

	setProgram(_programNames[argv[0]]);

	_argsProcessed.resize(_argc - _skipFirstArgs, false);

	for (_i=_skipFirstArgs; _i < argc; _i++) {
		if (isUsed(_i - _skipFirstArgs)) {
			continue;
		}
		else if (strcmp(_argv[_i], "-n") == 0) {
			if (!handle_n()) return false;
		}
		else if (strcmp(_argv[_i], "-nms") == 0) {
			if (!handle_nms()) return false;
		}
		else if (strcmp(_argv[_i], "-scores") == 0) {
			if (!handle_scores()) return false;
		}
		else if (strcmp(_argv[_i], "-delim") == 0) {
			if (!handle_delim()) return false;
		}
		else if (strcmp(_argv[_i], "-d") == 0) {
			if (!handle_d()) return false;
		}
		else if (strcmp(_argv[_i], "-s") == 0) {
			if (!handle_s()) return false;
		}
		else if (strcmp(_argv[_i], "-S") == 0) {
			if (!handle_S()) return false;
		}
	}
	return ContextBase::parseCmdArgs(argc, argv, _skipFirstArgs);
}

bool ContextMerge::isValidState()
{
	// Special: The merge program does not have default
	//column operations, so if none were entered, disable column ops.
	if (_keyListOps->getColumns().empty() && _keyListOps->getOperations().empty()) {
		setColumnOpsMethods(false);
		delete _keyListOps;
		_keyListOps = NULL;
	}
	if (!ContextBase::isValidState()) {
		return false;
	}
	if (_files.size() != 1) {
		_errorMsg = "\n***** ERROR: input file not specified. *****";
		// Allow only one input file for now
		return false;
	}

	//
	// Tests for stranded merge
	//
	if (_desiredStrand != FileRecordMergeMgr::ANY_STRAND) { // requested stranded merge
		// make sure file has strand.
		if (!getFile(0)->recordsHaveStrand()) {
			_errorMsg = "\n***** ERROR: stranded merge requested, but input file records do not have strand. *****";
			return false;
		}
		//make sure file is not VCF.
		if (getFile(0)->getFileType() == FileRecordTypeChecker::VCF_FILE_TYPE) {
			_errorMsg = "\n***** ERROR: stranded merge not supported for VCF files. *****";
			return false;
		}
	}

	//column operations not allowed with BAM input
	if (hasColumnOpsMethods() &&
			getFile(0)->getFileType() == FileRecordTypeChecker::BAM_FILE_TYPE) {
		_errorMsg = "\n***** ERROR: stranded merge not supported for VCF files. *****";
		return false;
	}
	return true;
}

bool ContextMerge::handle_d() {
    if ((_i+1) < _argc) {
    	if (isNumeric(_argv[_i+1])) {
			int dist = str2chrPos(_argv[_i+1]);

			_maxDistance = dist;
	    	markUsed(_i - _skipFirstArgs);
	        _i++;
	        markUsed(_i - _skipFirstArgs);
			return true;
    	}
    }
	_errorMsg = "\n***** ERROR: -d option must be followed by an integer value *****";
	return false;
}

bool ContextMerge::handle_n()
{
	markUsed(_i - _skipFirstArgs);
	_errorMsg = "\n***** ERROR: -n option is deprecated. Please see the documentation for the -c and -o column operation options. *****";
    return false;
}

bool ContextMerge::handle_nms()
{
	markUsed(_i - _skipFirstArgs);
	_errorMsg = "\n***** ERROR: -nms option is deprecated. Please see the documentation for the -c and -o column operation options. *****";
    return false;

}

bool ContextMerge::handle_scores()
{
	// No longer supporting this deprecated option.
	markUsed(_i - _skipFirstArgs);
	_errorMsg = "\n***** ERROR: -scores option is deprecated. Please see the documentation for the -c and -o column operation options. *****";
    return false;
}

bool ContextMerge::handle_s() {
	_desiredStrand = FileRecordMergeMgr::SAME_STRAND_EITHER;
	markUsed(_i - _skipFirstArgs);
	return true;
}

bool ContextMerge::handle_S() {
    if ((_i+1) < _argc) {
    	bool validChar = false;
    	if (_argv[_i+1][0] == '+') {
			_desiredStrand = FileRecordMergeMgr::SAME_STRAND_FORWARD;
			validChar = true;
    	} else if (_argv[_i+1][0] == '-') {
    		validChar = true;
			_desiredStrand = FileRecordMergeMgr::SAME_STRAND_REVERSE;
    	}
    	if (validChar) {
			markUsed(_i - _skipFirstArgs);
			_i++;
			markUsed(_i - _skipFirstArgs);
			return true;
    	}
    }
	_errorMsg = "\n***** ERROR: -S option must be followed by + or -. *****";
	return false;
}
<|endoftext|>


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

#pragma hdrstop

#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif

#include "hint.hxx"
#include "smplhint.hxx"
#include "lstner.hxx"

SV_DECL_PTRARR( SfxListenerArr_Impl, SfxListener*, 0, 2 );

#define _SFX_BRDCST_CXX
#include "brdcst.hxx"

//====================================================================
DBG_NAME(SfxBroadcaster);
TYPEINIT0(SfxBroadcaster);

//====================================================================

//====================================================================
// broadcast immedeately

void SfxBroadcaster::Broadcast( const SfxHint &rHint )
{
    DBG_CHKTHIS(SfxBroadcaster, 0);

    // is anybody to notify?
    if ( aListeners.Count() /*! || aGlobListeners.Count() */ )
    {
        // determine the type only once, because of its expensiveness
        const TypeId& rBCType = Type();
        const TypeId& rHintType = rHint.Type();

        // notify all registered listeners exactly once
        for ( USHORT n = 0; n < aListeners.Count(); ++n )
        {
            SfxListener* pListener = aListeners[n];
            if ( pListener )
                pListener->SFX_NOTIFY( *this, rBCType, rHint, rHintType );
        }
    }
}

//--------------------------------------------------------------------

// broadcast after a timeout

void SfxBroadcaster::BroadcastDelayed( const SfxHint& rHint )
{
    DBG_WARNING( "not implemented" );
    Broadcast(rHint);
}
//--------------------------------------------------------------------

// broadcast in idle-handler

void SfxBroadcaster::BroadcastInIdle( const SfxHint& rHint )
{
    DBG_WARNING( "not implemented" );
    Broadcast(rHint);
}
//--------------------------------------------------------------------

// unregister all listeners

SfxBroadcaster::~SfxBroadcaster()
{
    DBG_DTOR(SfxBroadcaster, 0);

    Broadcast( SfxSimpleHint(SFX_HINT_DYING) );

    // remove all still registered listeners
    for ( USHORT nPos = 0; nPos < aListeners.Count(); ++nPos )
    {
        SfxListener *pListener = aListeners[nPos];
        if ( pListener )
            pListener->RemoveBroadcaster_Impl(*this);
    }
}

//--------------------------------------------------------------------

// simple ctor of class SfxBroadcaster

SfxBroadcaster::SfxBroadcaster()
{
    DBG_CTOR(SfxBroadcaster, 0);
}

//--------------------------------------------------------------------

// copy ctor of class SfxBroadcaster

SfxBroadcaster::SfxBroadcaster( const SfxBroadcaster &rBC )
{
    DBG_CTOR(SfxBroadcaster, 0);

    for ( USHORT n = 0; n < rBC.aListeners.Count(); ++n )
    {
        SfxListener *pListener = rBC.aListeners[n];
        if ( pListener )
            pListener->StartListening( *this );
    }
}

//--------------------------------------------------------------------

// add a new SfxListener to the list

BOOL SfxBroadcaster::AddListener( SfxListener& rListener )
{
    DBG_CHKTHIS(SfxBroadcaster, 0);
    const SfxListener *pListener = &rListener;
    const SfxListener *pNull = 0;
    USHORT nFreePos = aListeners.GetPos( pNull );
    if ( nFreePos < aListeners.Count() )
        aListeners.GetData()[nFreePos] = pListener;
    else if ( aListeners.Count() < (USHRT_MAX-1) )
        aListeners.Insert( pListener, aListeners.Count() );
    else
    {
        DBG_ERROR( "array overflow" );
        return FALSE;
    }

    DBG_ASSERT( USHRT_MAX != aListeners.GetPos(pListener),
                "AddListener failed" );
    return TRUE;
}

//--------------------------------------------------------------------

// called, if no more listeners exists

void SfxBroadcaster::ListenersGone()
{
    DBG_CHKTHIS(SfxBroadcaster,0);
}

//--------------------------------------------------------------------

// forward a notification to all registered listeners

void SfxBroadcaster::SFX_FORWARD(SfxBroadcaster& rBC, const TypeId& rBCType,
                               const SfxHint& rHint, const TypeId& rHintType)
{
    const USHORT nCount = aListeners.Count();
    for ( USHORT i = 0; i < nCount; ++i )
    {
        SfxListener *pListener = aListeners[i];
        if ( pListener )
            pListener->SFX_NOTIFY( rBC, rBCType, rHint, rHintType);
    }
}

//--------------------------------------------------------------------

// remove one SfxListener from the list

void SfxBroadcaster::RemoveListener( SfxListener& rListener )
{
    {DBG_CHKTHIS(SfxBroadcaster, 0);}
    const SfxListener *pListener = &rListener;
    USHORT nPos = aListeners.GetPos(pListener);
    DBG_ASSERT( nPos != USHRT_MAX, "RemoveListener: Listener unknown" );
    aListeners.GetData()[nPos] = 0;
    if ( !HasListeners() )
        ListenersGone();
}

//--------------------------------------------------------------------

BOOL SfxBroadcaster::HasListeners() const
{
    for ( USHORT n = 0; n < aListeners.Count(); ++n )
        if ( aListeners.GetObject(n) != 0 )
            return TRUE;
    return FALSE;
}

//--------------------------------------------------------------------

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

#ifndef GCC
#pragma hdrstop
#endif

#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif

#include "hint.hxx"
#include "smplhint.hxx"
#include "lstner.hxx"

SV_DECL_PTRARR( SfxListenerArr_Impl, SfxListener*, 0, 2 );

#define _SFX_BRDCST_CXX
#include "brdcst.hxx"

//====================================================================
DBG_NAME(SfxBroadcaster);
TYPEINIT0(SfxBroadcaster);

//====================================================================

//====================================================================
// broadcast immediately

void SfxBroadcaster::Broadcast( const SfxHint &rHint )
{
    DBG_CHKTHIS(SfxBroadcaster, 0);

    // is anybody to notify?
    if ( aListeners.Count() /*! || aGlobListeners.Count() */ )
    {
        // determine the type only once, because of its expensiveness
        const TypeId& rBCType = Type();
        const TypeId& rHintType = rHint.Type();

        // notify all registered listeners exactly once
        for ( USHORT n = 0; n < aListeners.Count(); ++n )
        {
            SfxListener* pListener = aListeners[n];
            if ( pListener )
                pListener->SFX_NOTIFY( *this, rBCType, rHint, rHintType );
        }
    }
}

//--------------------------------------------------------------------

// broadcast after a timeout

void SfxBroadcaster::BroadcastDelayed( const SfxHint& rHint )
{
    DBG_WARNING( "not implemented" );
    Broadcast(rHint);
}
//--------------------------------------------------------------------

// broadcast in idle-handler

void SfxBroadcaster::BroadcastInIdle( const SfxHint& rHint )
{
    DBG_WARNING( "not implemented" );
    Broadcast(rHint);
}
//--------------------------------------------------------------------

// unregister all listeners

SfxBroadcaster::~SfxBroadcaster()
{
    DBG_DTOR(SfxBroadcaster, 0);

    Broadcast( SfxSimpleHint(SFX_HINT_DYING) );

    // remove all still registered listeners
    for ( USHORT nPos = 0; nPos < aListeners.Count(); ++nPos )
    {
        SfxListener *pListener = aListeners[nPos];
        if ( pListener )
            pListener->RemoveBroadcaster_Impl(*this);
    }
}

//--------------------------------------------------------------------

// simple ctor of class SfxBroadcaster

SfxBroadcaster::SfxBroadcaster()
{
    DBG_CTOR(SfxBroadcaster, 0);
}

//--------------------------------------------------------------------

// copy ctor of class SfxBroadcaster

SfxBroadcaster::SfxBroadcaster( const SfxBroadcaster &rBC )
{
    DBG_CTOR(SfxBroadcaster, 0);

    for ( USHORT n = 0; n < rBC.aListeners.Count(); ++n )
    {
        SfxListener *pListener = rBC.aListeners[n];
        if ( pListener )
            pListener->StartListening( *this );
    }
}

//--------------------------------------------------------------------

// add a new SfxListener to the list

BOOL SfxBroadcaster::AddListener( SfxListener& rListener )
{
    DBG_CHKTHIS(SfxBroadcaster, 0);
    const SfxListener *pListener = &rListener;
    const SfxListener *pNull = 0;
    USHORT nFreePos = aListeners.GetPos( pNull );
    if ( nFreePos < aListeners.Count() )
        aListeners.GetData()[nFreePos] = pListener;
    else if ( aListeners.Count() < (USHRT_MAX-1) )
        aListeners.Insert( pListener, aListeners.Count() );
    else
    {
        DBG_ERROR( "array overflow" );
        return FALSE;
    }

    DBG_ASSERT( USHRT_MAX != aListeners.GetPos(pListener),
                "AddListener failed" );
    return TRUE;
}

//--------------------------------------------------------------------

// called, if no more listeners exists

void SfxBroadcaster::ListenersGone()
{
    DBG_CHKTHIS(SfxBroadcaster,0);
}

//--------------------------------------------------------------------

// forward a notification to all registered listeners

void SfxBroadcaster::SFX_FORWARD(SfxBroadcaster& rBC, const TypeId& rBCType,
                               const SfxHint& rHint, const TypeId& rHintType)
{
    const USHORT nCount = aListeners.Count();
    for ( USHORT i = 0; i < nCount; ++i )
    {
        SfxListener *pListener = aListeners[i];
        if ( pListener )
            pListener->SFX_NOTIFY( rBC, rBCType, rHint, rHintType);
    }
}

//--------------------------------------------------------------------

// remove one SfxListener from the list

void SfxBroadcaster::RemoveListener( SfxListener& rListener )
{
    {DBG_CHKTHIS(SfxBroadcaster, 0);}
    const SfxListener *pListener = &rListener;
    USHORT nPos = aListeners.GetPos(pListener);
    DBG_ASSERT( nPos != USHRT_MAX, "RemoveListener: Listener unknown" );
    aListeners.GetData()[nPos] = 0;
    if ( !HasListeners() )
        ListenersGone();
}

//--------------------------------------------------------------------

BOOL SfxBroadcaster::HasListeners() const
{
    for ( USHORT n = 0; n < aListeners.Count(); ++n )
        if ( aListeners.GetObject(n) != 0 )
            return TRUE;
    return FALSE;
}

//--------------------------------------------------------------------
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS presenterscreen (1.2.4); FILE MERGED 2008/04/23 11:59:53 af 1.2.4.4: #i18486# Fixed mixup of uno/rtl References and boost::shared_ptrs. 2008/04/22 08:36:00 af 1.2.4.3: #i18486# Split initialization off the PresenterToolBar constructor. 2008/04/22 08:24:53 af 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2008/04/16 16:11:13 af 1.2.4.1: #i18486# Tool bar entries can be vertical stacks of other entries.<commit_after><|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "core/models.h"
#include <QDebug>
#include <QObject>
#include <QString>
#include <QPushButton>
#include <QSignalMapper>
#include <QKeyEvent>
#include <QClipboard>

struct named_model {
    const char *name;
    const bitNames_t *model;
};
const struct named_model models[] = {
    { "eflags", &x86_eflags, },
    { "cr0",    &x86_cr0, },
    { "cr4",    &x86_cr4, },
};

const QChar MainWindow::kFillChar('0');
const uint  MainWindow::kBitCount = 32;

static inline int
hexLength(uint bits)
{
    switch (bits) {
    case  8: return 2;
    case 16: return 4;
    case 32: return 8;
    };
    return 16;
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    signalMapper(new QSignalMapper(this)),
    valueWidth(kBitCount)
{
    modelInit();
    uiInit();

    setValueWidth(kBitCount);
    namesChanged(0);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void
MainWindow::modelInit(uint64_t initialValue)
{
    model.setValue(initialValue);
}

void
MainWindow::uiInit()
{
    ui->setupUi(this);

    digitFont.setStyleHint(QFont::Monospace);
#ifdef _WIN32
    digitFont.setFamily(QStringLiteral("Courier New"));
    digitFont.setPointSize(11);
#elif __APPLE__
    digitFont.setFamily("Menlo-Regular");
#endif
    ui->valueEdit->setFont(digitFont);
    ui->nameSummary->setFont(digitFont);

    uint64_t bit = 1ULL;
    for (uint i = 0; i < kBitCount; ++i) {
        int value = !!(model.value() & bit);
        QWidget *w;

        w = createBit(i, value);
        getBitLayout(i)->insertWidget(0, w);

        w = createName(i, value);
        ui->gridLayout->addWidget(w, i / 4, i % 4);

        bit <<= 1;
    }
    for (uint b = 8; b <= kBitCount; b <<= 1) {
        ui->bitComboBox->addItem(QString::number(b));
    }
    ui->bitComboBox->setCurrentIndex(ui->bitComboBox->count()-1);

    for (size_t i = 0; i < sizeof(models)/sizeof(models[0]); i++) {
        ui->comboBox->addItem(QString(models[i].name));
    }

    connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(bitClicked(int)));
    connect(ui->valueEdit, SIGNAL(textEdited(QString)), this, SLOT(valueChanged(QString)));
    connect(ui->bitComboBox, SIGNAL(activated(int)), this, SLOT(valueWidthChanged(int)));
    connect(ui->comboBox, SIGNAL(activated(int)), this, SLOT(namesChanged(int)));
}

void
MainWindow::setNames(const bitNames_t names)
{
    model.setNames(names);
    updateBitNames();
    updateSummary();
}

void
MainWindow::setValueWidth(uint width)
{
    switch (width) {
    case 8: case 16: case 32: case 64:
        break;
    default:
        return;
    }
    for (uint i = valueWidth; i < width; i++) {
        ui->gridLayout->itemAt(i)->widget()->show();
    }
    for (uint i = width; i < kBitCount; i++) {
        ui->gridLayout->itemAt(i)->widget()->hide();
    }
    if (width > 16)
        ui->highWord->show();
    else
        ui->highWord->hide();
    if (width > 8) {
        for (int i = 0; i < ui->ahBits->count(); i++) {
            ui->ahBits->itemAt(i)->widget()->show();
        }
    } else {
        for (int i = 0; i < ui->ahBits->count(); i++) {
            ui->ahBits->itemAt(i)->widget()->hide();
        }
    }
    valueWidth = width;
    ui->valueEdit->setMaxLength(hexLength(valueWidth));
    ui->valueEdit->setInputMask(QString(hexLength(valueWidth), QChar('H')));
    updateValueEdit();
}

QHBoxLayout *
MainWindow::getBitLayout(uint i){
    if (i >= 24)
        return ui->ehBits;
    if (i >= 16)
        return ui->elBits;
    if (i >=  8)
        return ui->ahBits;
    return ui->alBits;
}

QWidget *
MainWindow::getBitWidget(uint i)
{
    if (i >= 32)
        return 0;
    if (i >= 24)
        return ui->ehBits->itemAt(32-1-i)->widget();
    if (i >= 16)
        return ui->elBits->itemAt(24-1-i)->widget();
    if (i >=  8)
        return ui->ahBits->itemAt(16-1-i)->widget();
    return ui->alBits->itemAt(8-1-i)->widget();
}

QWidget *
MainWindow::createBit(uint i, int value)
{
    QPushButton *pushButton = new QPushButton(this);
    pushButton->setObjectName(QString("bitBtn%1").arg(i, 2, 10, kFillChar));
    pushButton->setFont(digitFont);
    pushButton->setFlat(true);

    pushButton->setMinimumSize(QSize(20, 26));
    pushButton->setMaximumSize(QSize(20, 26));

    pushButton->setText(QString::number(value));
    pushButton->setToolTip(QString::number(i));

    signalMapper->setMapping(pushButton, i);
    connect(pushButton, SIGNAL(clicked()), signalMapper, SLOT(map()));

    return pushButton;
}

void
MainWindow::toggleBit(uint i, int value)
{
    QPushButton * b;
    b = qobject_cast<QPushButton*>(getBitWidget(i));
    b->setText(QString::number(value));

    b = qobject_cast<QPushButton*>(ui->gridLayout->itemAt(i)->widget());
    b->setChecked(value);
}

QWidget *
MainWindow::createName(uint i, int value)
{
    QPushButton *b = new QPushButton(getName(i));
    b->setObjectName(QString("nameBtn%1").arg(i, 2, 10, kFillChar));
    b->setCheckable(true);
    b->setFlat(true);
    b->setChecked(value);
    b->setToolTip(getNameTip(i));

    signalMapper->setMapping(b, i);
    connect(b, SIGNAL(clicked()), signalMapper, SLOT(map()));

    return b;
}

QString
MainWindow::getName(uint i) const
{
    return model.bitName(i) ?
                QString(model.bitName(i)) :
                QString::number(i);
}

QString
MainWindow::getNameTip(uint i) const
{
    return hexToString(1ULL << i);
}

QString
MainWindow::hexToString(uint64_t v) const
{
    return QString("0x%1").arg(v, hexLength(valueWidth), 16, kFillChar);
}

void
MainWindow::updateBitNames()
{
    for (uint i = 0; i < valueWidth; i++) {
        QPushButton *b = qobject_cast<QPushButton*>(ui->gridLayout->itemAt(i)->widget());
        b->setText(getName(i));
    }
}

void
MainWindow::updateSummary()
{
    QString summary;
    uint64_t rest = 0, bit = 1ULL;
    for (uint i = 0; i < valueWidth; i++) {
        if (model[i]) {
            if (model.bitName(i)) {
                summary.append('|').append(model.bitName(i));
            } else
                rest |= bit;
        }
        bit <<= 1;
    }
    summary.prepend(hexToString(rest));
    ui->nameSummary->setText(summary);
}

void
MainWindow::bitClicked(int b)
{
    model.toggleBit(b);
    updateValueEdit();
    toggleBit(b, model[b]);
}

void
MainWindow::updateValueEdit()
{
    int pos = ui->valueEdit->cursorPosition();
    ui->valueEdit->setText(QString("%1").arg(model.value(), hexLength(valueWidth), 16, kFillChar));
    if (pos < 0 || pos >= hexLength(valueWidth))
        pos = 0;
    ui->valueEdit->setCursorPosition(pos);
    updateSummary();
}

void
MainWindow::updateBits()
{
    uint64_t bit = 1UL;
    for (uint i = 0; i < valueWidth; i++) {
        toggleBit(i, !!(model.value() & bit));
        bit <<= 1;
    }
}

void
MainWindow::valueChanged(QString)
{
    if (ui->valueEdit->cursorPosition() >= hexLength(valueWidth))
        ui->valueEdit->setCursorPosition(hexLength(valueWidth)-1);

    bool ok = true;
    uint64_t v = ui->valueEdit->text().toULongLong(&ok, 16);
    if (!ok)
        return;
    model.setValue(v);
    updateBits();
    updateSummary();
}

void
MainWindow::namesChanged(int index)
{
    if (index >= 0 && index < (int)(sizeof(models)/sizeof(models[0])))
        setNames(*models[index].model);
    updateSummary();
}

void
MainWindow::valueWidthChanged(int index)
{
    if (index < 0)
        return;
    setValueWidth(8 << index);
}

void
MainWindow::keyPressEvent(QKeyEvent *event)
{
   if (event->matches(QKeySequence::Paste)) {
       event->ignore();
       QClipboard *clipboard = QApplication::clipboard();
       QString originalText = clipboard->text();
       bool ok = false;
       uint64_t v = originalText.toULongLong(&ok, 16);
       if (!ok)
           v = originalText.toULongLong(&ok, 10);

       if (ok) {
           model.setValue(v);
           updateValueEdit();
           updateBits();
       }
   }
   else return QMainWindow::keyPressEvent(event);
}
<commit_msg>Fix wrong high bit names after changing bit set while less than 32 bits<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "core/models.h"
#include <QDebug>
#include <QObject>
#include <QString>
#include <QPushButton>
#include <QSignalMapper>
#include <QKeyEvent>
#include <QClipboard>

struct named_model {
    const char *name;
    const bitNames_t *model;
};
const struct named_model models[] = {
    { "eflags", &x86_eflags, },
    { "cr0",    &x86_cr0, },
    { "cr4",    &x86_cr4, },
};

const QChar MainWindow::kFillChar('0');
const uint  MainWindow::kBitCount = 32;

static inline int
hexLength(uint bits)
{
    switch (bits) {
    case  8: return 2;
    case 16: return 4;
    case 32: return 8;
    };
    return 16;
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    signalMapper(new QSignalMapper(this)),
    valueWidth(kBitCount)
{
    modelInit();
    uiInit();

    setValueWidth(kBitCount);
    namesChanged(0);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void
MainWindow::modelInit(uint64_t initialValue)
{
    model.setValue(initialValue);
}

void
MainWindow::uiInit()
{
    ui->setupUi(this);

    digitFont.setStyleHint(QFont::Monospace);
#ifdef _WIN32
    digitFont.setFamily(QStringLiteral("Courier New"));
    digitFont.setPointSize(11);
#elif __APPLE__
    digitFont.setFamily("Menlo-Regular");
#endif
    ui->valueEdit->setFont(digitFont);
    ui->nameSummary->setFont(digitFont);

    uint64_t bit = 1ULL;
    for (uint i = 0; i < kBitCount; ++i) {
        int value = !!(model.value() & bit);
        QWidget *w;

        w = createBit(i, value);
        getBitLayout(i)->insertWidget(0, w);

        w = createName(i, value);
        ui->gridLayout->addWidget(w, i / 4, i % 4);

        bit <<= 1;
    }
    for (uint b = 8; b <= kBitCount; b <<= 1) {
        ui->bitComboBox->addItem(QString::number(b));
    }
    ui->bitComboBox->setCurrentIndex(ui->bitComboBox->count()-1);

    for (size_t i = 0; i < sizeof(models)/sizeof(models[0]); i++) {
        ui->comboBox->addItem(QString(models[i].name));
    }

    connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(bitClicked(int)));
    connect(ui->valueEdit, SIGNAL(textEdited(QString)), this, SLOT(valueChanged(QString)));
    connect(ui->bitComboBox, SIGNAL(activated(int)), this, SLOT(valueWidthChanged(int)));
    connect(ui->comboBox, SIGNAL(activated(int)), this, SLOT(namesChanged(int)));
}

void
MainWindow::setNames(const bitNames_t names)
{
    model.setNames(names);
    updateBitNames();
    updateSummary();
}

void
MainWindow::setValueWidth(uint width)
{
    switch (width) {
    case 8: case 16: case 32: case 64:
        break;
    default:
        return;
    }
    for (uint i = valueWidth; i < width; i++) {
        ui->gridLayout->itemAt(i)->widget()->show();
    }
    for (uint i = width; i < kBitCount; i++) {
        ui->gridLayout->itemAt(i)->widget()->hide();
    }
    if (width > 16)
        ui->highWord->show();
    else
        ui->highWord->hide();
    if (width > 8) {
        for (int i = 0; i < ui->ahBits->count(); i++) {
            ui->ahBits->itemAt(i)->widget()->show();
        }
    } else {
        for (int i = 0; i < ui->ahBits->count(); i++) {
            ui->ahBits->itemAt(i)->widget()->hide();
        }
    }
    valueWidth = width;
    ui->valueEdit->setMaxLength(hexLength(valueWidth));
    ui->valueEdit->setInputMask(QString(hexLength(valueWidth), QChar('H')));
    updateValueEdit();
}

QHBoxLayout *
MainWindow::getBitLayout(uint i){
    if (i >= 24)
        return ui->ehBits;
    if (i >= 16)
        return ui->elBits;
    if (i >=  8)
        return ui->ahBits;
    return ui->alBits;
}

QWidget *
MainWindow::getBitWidget(uint i)
{
    if (i >= 32)
        return 0;
    if (i >= 24)
        return ui->ehBits->itemAt(32-1-i)->widget();
    if (i >= 16)
        return ui->elBits->itemAt(24-1-i)->widget();
    if (i >=  8)
        return ui->ahBits->itemAt(16-1-i)->widget();
    return ui->alBits->itemAt(8-1-i)->widget();
}

QWidget *
MainWindow::createBit(uint i, int value)
{
    QPushButton *pushButton = new QPushButton(this);
    pushButton->setObjectName(QString("bitBtn%1").arg(i, 2, 10, kFillChar));
    pushButton->setFont(digitFont);
    pushButton->setFlat(true);

    pushButton->setMinimumSize(QSize(20, 26));
    pushButton->setMaximumSize(QSize(20, 26));

    pushButton->setText(QString::number(value));
    pushButton->setToolTip(QString::number(i));

    signalMapper->setMapping(pushButton, i);
    connect(pushButton, SIGNAL(clicked()), signalMapper, SLOT(map()));

    return pushButton;
}

void
MainWindow::toggleBit(uint i, int value)
{
    QPushButton * b;
    b = qobject_cast<QPushButton*>(getBitWidget(i));
    b->setText(QString::number(value));

    b = qobject_cast<QPushButton*>(ui->gridLayout->itemAt(i)->widget());
    b->setChecked(value);
}

QWidget *
MainWindow::createName(uint i, int value)
{
    QPushButton *b = new QPushButton(getName(i));
    b->setObjectName(QString("nameBtn%1").arg(i, 2, 10, kFillChar));
    b->setCheckable(true);
    b->setFlat(true);
    b->setChecked(value);
    b->setToolTip(getNameTip(i));

    signalMapper->setMapping(b, i);
    connect(b, SIGNAL(clicked()), signalMapper, SLOT(map()));

    return b;
}

QString
MainWindow::getName(uint i) const
{
    return model.bitName(i) ?
                QString(model.bitName(i)) :
                QString::number(i);
}

QString
MainWindow::getNameTip(uint i) const
{
    return hexToString(1ULL << i);
}

QString
MainWindow::hexToString(uint64_t v) const
{
    return QString("0x%1").arg(v, hexLength(valueWidth), 16, kFillChar);
}

void
MainWindow::updateBitNames()
{
    for (uint i = 0; i < kBitCount; i++) {
        QPushButton *b = qobject_cast<QPushButton*>(ui->gridLayout->itemAt(i)->widget());
        b->setText(getName(i));
    }
}

void
MainWindow::updateSummary()
{
    QString summary;
    uint64_t rest = 0, bit = 1ULL;
    for (uint i = 0; i < valueWidth; i++) {
        if (model[i]) {
            if (model.bitName(i)) {
                summary.append('|').append(model.bitName(i));
            } else
                rest |= bit;
        }
        bit <<= 1;
    }
    summary.prepend(hexToString(rest));
    ui->nameSummary->setText(summary);
}

void
MainWindow::bitClicked(int b)
{
    model.toggleBit(b);
    updateValueEdit();
    toggleBit(b, model[b]);
}

void
MainWindow::updateValueEdit()
{
    int pos = ui->valueEdit->cursorPosition();
    ui->valueEdit->setText(QString("%1").arg(model.value(), hexLength(valueWidth), 16, kFillChar));
    if (pos < 0 || pos >= hexLength(valueWidth))
        pos = 0;
    ui->valueEdit->setCursorPosition(pos);
    updateSummary();
}

void
MainWindow::updateBits()
{
    uint64_t bit = 1UL;
    for (uint i = 0; i < valueWidth; i++) {
        toggleBit(i, !!(model.value() & bit));
        bit <<= 1;
    }
}

void
MainWindow::valueChanged(QString)
{
    if (ui->valueEdit->cursorPosition() >= hexLength(valueWidth))
        ui->valueEdit->setCursorPosition(hexLength(valueWidth)-1);

    bool ok = true;
    uint64_t v = ui->valueEdit->text().toULongLong(&ok, 16);
    if (!ok)
        return;
    model.setValue(v);
    updateBits();
    updateSummary();
}

void
MainWindow::namesChanged(int index)
{
    if (index >= 0 && index < (int)(sizeof(models)/sizeof(models[0])))
        setNames(*models[index].model);
    updateSummary();
}

void
MainWindow::valueWidthChanged(int index)
{
    if (index < 0)
        return;
    setValueWidth(8 << index);
}

void
MainWindow::keyPressEvent(QKeyEvent *event)
{
   if (event->matches(QKeySequence::Paste)) {
       event->ignore();
       QClipboard *clipboard = QApplication::clipboard();
       QString originalText = clipboard->text();
       bool ok = false;
       uint64_t v = originalText.toULongLong(&ok, 16);
       if (!ok)
           v = originalText.toULongLong(&ok, 10);

       if (ok) {
           model.setValue(v);
           updateValueEdit();
           updateBits();
       }
   }
   else return QMainWindow::keyPressEvent(event);
}
<|endoftext|>


<commit_before><commit_msg>changed memopt SA struct<commit_after><|endoftext|>