<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: genericpropertyhandler.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: ihi $ $Date: 2008-01-14 14:59:13 $
 *
 *  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 EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX

#ifndef EXTENSIONS_SOURCE_PROPCTRLR_PROPERTYHANDLER_HXX
#include "propertyhandler.hxx"
#endif
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_PCRCOMMONTYPES_HXX
#include "pcrcommontypes.hxx"
#endif
#ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_
#include "pcrcommon.hxx"
#endif
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_PCROMPONENTCONTEXT_HXX
#include "pcrcomponentcontext.hxx"
#endif

/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XINTROSPECTIONACCESS_HPP_
#include <com/sun/star/beans/XIntrospectionAccess.hpp>
#endif
/** === end UNO includes === **/

#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#include <map>

//........................................................................
namespace pcr
{
//........................................................................

    struct TypeLess : ::std::binary_function< ::com::sun::star::uno::Type, ::com::sun::star::uno::Type, bool >
    {
        bool operator()( const ::com::sun::star::uno::Type& _rLHS, const ::com::sun::star::uno::Type& _rRHS ) const
        {
            return _rLHS.getTypeName() < _rRHS.getTypeName();
        }
    };

    class IPropertyInfoService;
    class IPropertyEnumRepresentation;
    //====================================================================
    //= GenericPropertyHandler
    //====================================================================
    typedef ::cppu::WeakComponentImplHelper2    <   ::com::sun::star::inspection::XPropertyHandler
                                                ,   ::com::sun::star::lang::XServiceInfo
                                                >   GenericPropertyHandler_Base;
    class GenericPropertyHandler : public GenericPropertyHandler_Base
    {
    private:
        mutable ::osl::Mutex    m_aMutex;

    private:
        /// the service factory for creating services
        ComponentContext                                                                    m_aContext;
        /// need this to keep alive as long as m_xComponent lives
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess >   m_xComponentIntrospectionAccess;
        /// the properties of the object we're handling
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >           m_xComponent;
        /// cached interface of ->m_xComponent
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState >         m_xPropertyState;
        /// type converter, needed on various occasions
        ::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter >        m_xTypeConverter;
        /// cache of our supported properties
        PropertyMap                                                                         m_aProperties;
        /// property change listeners
        ::cppu::OInterfaceContainerHelper                                                   m_aPropertyListeners;
        ::std::map< ::com::sun::star::uno::Type, ::rtl::Reference< IPropertyEnumRepresentation >, TypeLess >
                                                                                m_aEnumConverters;

        /// has ->m_aProperties been initialized?
        bool    m_bPropertyMapInitialized : 1;

    public:
        // XServiceInfo - static versions
        static ::rtl::OUString SAL_CALL getImplementationName_static(  ) throw (::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_static(  ) throw (::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > Create( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext );

    protected:
        GenericPropertyHandler(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext
        );

        ~GenericPropertyHandler();

    protected:
        // XPropertyHandler overridables
        virtual void                                                SAL_CALL inspect( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxIntrospectee ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any                          SAL_CALL getPropertyValue( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual void                                                SAL_CALL setPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any                          SAL_CALL convertToPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rControlValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any                          SAL_CALL convertToControlValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rPropertyValue, const ::com::sun::star::uno::Type& _rControlValueType ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::beans::PropertyState              SAL_CALL getPropertyState( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual void                                                SAL_CALL addPropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void                                                SAL_CALL removePropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >
                                                                    SAL_CALL getSupportedProperties() throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >
                                                                    SAL_CALL getSupersededProperties() throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >  SAL_CALL getActuatingProperties() throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::inspection::LineDescriptor        SAL_CALL describePropertyLine( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool                                          SAL_CALL isComposable( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::inspection::InteractiveSelectionResult
                                                                    SAL_CALL onInteractivePropertySelection( const ::rtl::OUString& _rPropertyName, sal_Bool _bPrimary, ::com::sun::star::uno::Any& _rData, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual void                                                SAL_CALL actuatingPropertyChanged( const ::rtl::OUString& _rActuatingPropertyName, const ::com::sun::star::uno::Any& _rNewValue, const ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI, sal_Bool _bFirstTimeInit ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool                                            SAL_CALL suspend( sal_Bool _bSuspend ) throw (::com::sun::star::uno::RuntimeException);

        // XComponent
        DECLARE_XCOMPONENT()
        virtual void                                                SAL_CALL disposing();

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);

    private:
        /** ensures that ->m_aProperties is initialized
            @precond
                our mutex is locked
        */
        void    impl_ensurePropertyMap();

        /** retrieves the enum converter for the given ENUM type
        */
        ::rtl::Reference< IPropertyEnumRepresentation >
                impl_getEnumConverter( const ::com::sun::star::uno::Type& _rEnumType );

    private:
        GenericPropertyHandler();                                           // never implemented
        GenericPropertyHandler( const GenericPropertyHandler& );            // never implemented
        GenericPropertyHandler& operator=( const GenericPropertyHandler& ); // never implemented
    };

//........................................................................
} // namespace pcr
//........................................................................

#endif // EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.4.48); FILE MERGED 2008/04/01 15:15:18 thb 1.4.48.3: #i85898# Stripping all external header guards 2008/04/01 12:29:50 thb 1.4.48.2: #i85898# Stripping all external header guards 2008/03/31 12:31:44 rt 1.4.48.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: genericpropertyhandler.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX

#include "propertyhandler.hxx"
#include "pcrcommontypes.hxx"
#include "pcrcommon.hxx"
#include "pcrcomponentcontext.hxx"

/** === begin UNO includes === **/
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XIntrospectionAccess.hpp>
/** === end UNO includes === **/
#include <cppuhelper/compbase2.hxx>
#include <cppuhelper/interfacecontainer.hxx>
#include <rtl/ref.hxx>

#include <map>

//........................................................................
namespace pcr
{
//........................................................................

    struct TypeLess : ::std::binary_function< ::com::sun::star::uno::Type, ::com::sun::star::uno::Type, bool >
    {
        bool operator()( const ::com::sun::star::uno::Type& _rLHS, const ::com::sun::star::uno::Type& _rRHS ) const
        {
            return _rLHS.getTypeName() < _rRHS.getTypeName();
        }
    };

    class IPropertyInfoService;
    class IPropertyEnumRepresentation;
    //====================================================================
    //= GenericPropertyHandler
    //====================================================================
    typedef ::cppu::WeakComponentImplHelper2    <   ::com::sun::star::inspection::XPropertyHandler
                                                ,   ::com::sun::star::lang::XServiceInfo
                                                >   GenericPropertyHandler_Base;
    class GenericPropertyHandler : public GenericPropertyHandler_Base
    {
    private:
        mutable ::osl::Mutex    m_aMutex;

    private:
        /// the service factory for creating services
        ComponentContext                                                                    m_aContext;
        /// need this to keep alive as long as m_xComponent lives
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess >   m_xComponentIntrospectionAccess;
        /// the properties of the object we're handling
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >           m_xComponent;
        /// cached interface of ->m_xComponent
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState >         m_xPropertyState;
        /// type converter, needed on various occasions
        ::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter >        m_xTypeConverter;
        /// cache of our supported properties
        PropertyMap                                                                         m_aProperties;
        /// property change listeners
        ::cppu::OInterfaceContainerHelper                                                   m_aPropertyListeners;
        ::std::map< ::com::sun::star::uno::Type, ::rtl::Reference< IPropertyEnumRepresentation >, TypeLess >
                                                                                m_aEnumConverters;

        /// has ->m_aProperties been initialized?
        bool    m_bPropertyMapInitialized : 1;

    public:
        // XServiceInfo - static versions
        static ::rtl::OUString SAL_CALL getImplementationName_static(  ) throw (::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_static(  ) throw (::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > Create( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext );

    protected:
        GenericPropertyHandler(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext
        );

        ~GenericPropertyHandler();

    protected:
        // XPropertyHandler overridables
        virtual void                                                SAL_CALL inspect( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxIntrospectee ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any                          SAL_CALL getPropertyValue( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual void                                                SAL_CALL setPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any                          SAL_CALL convertToPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rControlValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any                          SAL_CALL convertToControlValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rPropertyValue, const ::com::sun::star::uno::Type& _rControlValueType ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::beans::PropertyState              SAL_CALL getPropertyState( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual void                                                SAL_CALL addPropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void                                                SAL_CALL removePropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >
                                                                    SAL_CALL getSupportedProperties() throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >
                                                                    SAL_CALL getSupersededProperties() throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >  SAL_CALL getActuatingProperties() throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::inspection::LineDescriptor        SAL_CALL describePropertyLine( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool                                          SAL_CALL isComposable( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::inspection::InteractiveSelectionResult
                                                                    SAL_CALL onInteractivePropertySelection( const ::rtl::OUString& _rPropertyName, sal_Bool _bPrimary, ::com::sun::star::uno::Any& _rData, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual void                                                SAL_CALL actuatingPropertyChanged( const ::rtl::OUString& _rActuatingPropertyName, const ::com::sun::star::uno::Any& _rNewValue, const ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI, sal_Bool _bFirstTimeInit ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool                                            SAL_CALL suspend( sal_Bool _bSuspend ) throw (::com::sun::star::uno::RuntimeException);

        // XComponent
        DECLARE_XCOMPONENT()
        virtual void                                                SAL_CALL disposing();

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);

    private:
        /** ensures that ->m_aProperties is initialized
            @precond
                our mutex is locked
        */
        void    impl_ensurePropertyMap();

        /** retrieves the enum converter for the given ENUM type
        */
        ::rtl::Reference< IPropertyEnumRepresentation >
                impl_getEnumConverter( const ::com::sun::star::uno::Type& _rEnumType );

    private:
        GenericPropertyHandler();                                           // never implemented
        GenericPropertyHandler( const GenericPropertyHandler& );            // never implemented
        GenericPropertyHandler& operator=( const GenericPropertyHandler& ); // never implemented
    };

//........................................................................
} // namespace pcr
//........................................................................

#endif // EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX

<|endoftext|>


<commit_before><commit_msg>Be precise here, maximum value means it is still allowed to have<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: EnhancedPDFExportHelper.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _ENHANCEDPDFEXPORTHELPER_HXX
#define _ENHANCEDPDFEXPORTHELPER_HXX

#include <vcl/pdfextoutdevdata.hxx>
#include <i18npool/lang.h>
#include <swrect.hxx>
#include <swtypes.hxx>

#include <map>
#include <vector>
#include <set>

class vcl::PDFExtOutDevData;
class OutputDevice;
class SwFrm;
class SwLinePortion;
class SwTxtPainter;
class SwEditShell;
class rtl::OUString;
class MultiSelection;
class SwTxtNode;
class SwNumRule;
class SwTable;
class SwNumberTreeNode;
class String;
class SvxLanguageItem;

/*
 * Mapping of OOo elements to tagged pdf elements:
 *
 * OOo element                              tagged pdf element
 * -----------                              ------------------
 *
 * Grouping elements:
 *
 * SwRootFrm                                Document
 *                                          Part
 *                                          Art
 * SwSection                                Sect
 * SwFtnContFrm and SwFlyFrm                Div
 * SwFmt "Quotations"                       BlockQuote
 * SwFmt "Caption"                          Caption
 * SwSection (TOC)                          TOC
 * SwTxtNode in TOC                         TOCI
 * SwSection (Index)                        Index
 *
 * Block-Level Structure Elements:
 *
 * SwTxtNode                                P
 * SwFmt "Heading"                          H
 * SwTxtNode with Outline                   H1 - H6
 * SwTxtNode with NumRule                   L, LI, LBody
 * SwTable                                  Table
 * SwRowFrm                                 TR
 * SwCellFrm in Headline row or
 * SwFtm "Table Heading"                    TH
 * SwCellFrm                                TD
 *
 * Inline-Level Structure Elements:
 *
 * SwTxtPortion                             Span
 * SwFmt "Quotation"                        Quote
 * SwFtnFrm                                 Note
 *                                          Form
 *                                          Reference
 * SwFldPortion (AuthorityField)            BibEntry
 * SwFmt "Source Text"                      Code
 * SwFtnPortion, SwFldPortion (RefField)    Link
 *
 * Illustration elements:
 *
 * SwFlyFrm with SwNoTxtFrm                 Figure
 * SwFlyFrm with Math OLE Object            Formula
 *
 */

struct Num_Info
{
    const SwFrm& mrFrm;
    Num_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};
};

struct Frm_Info
{
    const SwFrm& mrFrm;
    Frm_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};
};

struct Por_Info
{
    const SwLinePortion& mrPor;
    const SwTxtPainter& mrTxtPainter;
    Por_Info( const SwLinePortion& rPor, const SwTxtPainter& rTxtPainer )
            : mrPor( rPor ), mrTxtPainter( rTxtPainer ) {};
};

struct lt_TableColumn
{
    bool operator()( long nVal1, long nVal2 ) const
    {
        return nVal1 + ( MINLAY - 1 ) < nVal2;
    }
};

/*************************************************************************
 *                class SwTaggedPDFHelper
 * Analyses a given frame during painting and generates the appropriate
 * structure elements.
 *************************************************************************/

class SwTaggedPDFHelper
{
    private:

    // This will be incremented for each BeginTag() call.
    // It denotes the number of tags to close during EndStructureElements();
    BYTE nEndStructureElement;

    //  If an already existing tag is reopened for follows of flow frames,
    // this value stores the tag id which has to be restored.
    sal_Int32 nRestoreCurrentTag;

    vcl::PDFExtOutDevData* mpPDFExtOutDevData;

    const Num_Info* mpNumInfo;
    const Frm_Info* mpFrmInfo;
    const Por_Info* mpPorInfo;

    void BeginTag( vcl::PDFWriter::StructElement, const String* pUserDefined = 0 );
    void EndTag();

    void SetAttributes( vcl::PDFWriter::StructElement eType );

    // These functions are called by the c'tor, d'tor
    void BeginNumberedListStructureElements();
    void BeginBlockStructureElements();
    void BeginInlineStructureElements();
    void EndStructureElements();

    bool CheckReopenTag();
    bool CheckRestoreTag() const;

    public:

    // pFrmInfo != 0 => BeginBlockStructureElement
    // pPorInfo != 0 => BeginInlineStructureElement
    // pFrmInfo, pPorInfo = 0 => BeginNonStructureElement
    SwTaggedPDFHelper( const Num_Info* pNumInfo, const Frm_Info* pFrmInfo, const Por_Info* pPorInfo,
                       OutputDevice& rOut );
    ~SwTaggedPDFHelper();

    static bool IsExportTaggedPDF( const OutputDevice& rOut );
};

/*************************************************************************
 *                class SwEnhancedPDFExportHelper
 * Analyses the document structure and export Notes, Hyperlinks, References,
 * and Outline. Link ids created during pdf export are stored in
 * aReferenceIdMap and aHyperlinkIdMap, in order to use them during
 * tagged pdf output. Therefore the SwEnhancedPDFExportHelper is used
 * before painting. Unfortunately links from the EditEngine into the
 * Writer document require to be exported after they have been painted.
 * Therefore SwEnhancedPDFExportHelper also has to be used after the
 * painting process, the parameter bEditEngineOnly indicated that only
 * the bookmarks from the EditEngine have to be processed.
 *************************************************************************/

typedef std::set< long, lt_TableColumn > TableColumnsMapEntry;
typedef std::pair< SwRect, sal_Int32 > IdMapEntry;
typedef std::vector< IdMapEntry > LinkIdMap;
typedef std::map< const SwTable*, TableColumnsMapEntry > TableColumnsMap;
typedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListIdMap;
typedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListBodyIdMap;
typedef std::map< const void*, sal_Int32 > FrmTagIdMap;

class SwEnhancedPDFExportHelper
{
    private:

    SwEditShell& mrSh;
    OutputDevice& mrOut;

    MultiSelection* pPageRange;

    bool mbSkipEmptyPages;
    bool mbEditEngineOnly;

    static TableColumnsMap aTableColumnsMap;
    static LinkIdMap aLinkIdMap;
    static NumListIdMap aNumListIdMap;
    static NumListBodyIdMap aNumListBodyIdMap;
    static FrmTagIdMap aFrmTagIdMap;

    static LanguageType eLanguageDefault;

    void EnhancedPDFExport();
    sal_Int32 CalcOutputPageNum( const SwRect& rRect ) const;

    void MakeHeaderFooterLinks( vcl::PDFExtOutDevData& rPDFExtOutDevData,
                                const SwTxtNode& rTNd, const SwRect& rLinkRect,
                                sal_Int32 nDestId, const String& rURL, bool bIntern ) const;

    public:

    SwEnhancedPDFExportHelper( SwEditShell& rSh,
                               OutputDevice& rOut,
                               const rtl::OUString& rPageRange,
                               bool bSkipEmptyPages,
                               bool bEditEngineOnly );

    ~SwEnhancedPDFExportHelper();

    static TableColumnsMap& GetTableColumnsMap() {return aTableColumnsMap; }
    static LinkIdMap& GetLinkIdMap() { return aLinkIdMap; }
    static NumListIdMap& GetNumListIdMap() {return aNumListIdMap; }
    static NumListBodyIdMap& GetNumListBodyIdMap() {return aNumListBodyIdMap; }
    static FrmTagIdMap& GetFrmTagIdMap() { return aFrmTagIdMap; }

    static const LanguageType GetDefaultLanguage() {return eLanguageDefault; }
};

#endif
<commit_msg>INTEGRATION: CWS c17v003_DEV300 (1.7.1068.1.22); FILE MERGED 2008/04/17 20:25:27 fme 1.7.1068.1.22.1: #b6688018# #b6688132# Interrupted and restart lists in tagged pdf / better caption handling<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: EnhancedPDFExportHelper.hxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _ENHANCEDPDFEXPORTHELPER_HXX
#define _ENHANCEDPDFEXPORTHELPER_HXX

#include <vcl/pdfextoutdevdata.hxx>
#include <i18npool/lang.h>
#include <swrect.hxx>
#include <swtypes.hxx>

#include <map>
#include <vector>
#include <set>

class vcl::PDFExtOutDevData;
class OutputDevice;
class SwFrm;
class SwLinePortion;
class SwTxtPainter;
class SwEditShell;
class rtl::OUString;
class MultiSelection;
class SwTxtNode;
class SwNumRule;
class SwTable;
class SwNumberTreeNode;
class String;
class SvxLanguageItem;

/*
 * Mapping of OOo elements to tagged pdf elements:
 *
 * OOo element                              tagged pdf element
 * -----------                              ------------------
 *
 * Grouping elements:
 *
 * SwRootFrm                                Document
 *                                          Part
 *                                          Art
 * SwSection                                Sect
 * SwFtnContFrm and SwFlyFrm                Div
 * SwFmt "Quotations"                       BlockQuote
 * SwFmt "Caption"                          Caption
 * SwSection (TOC)                          TOC
 * SwTxtNode in TOC                         TOCI
 * SwSection (Index)                        Index
 *
 * Block-Level Structure Elements:
 *
 * SwTxtNode                                P
 * SwFmt "Heading"                          H
 * SwTxtNode with Outline                   H1 - H6
 * SwTxtNode with NumRule                   L, LI, LBody
 * SwTable                                  Table
 * SwRowFrm                                 TR
 * SwCellFrm in Headline row or
 * SwFtm "Table Heading"                    TH
 * SwCellFrm                                TD
 *
 * Inline-Level Structure Elements:
 *
 * SwTxtPortion                             Span
 * SwFmt "Quotation"                        Quote
 * SwFtnFrm                                 Note
 *                                          Form
 *                                          Reference
 * SwFldPortion (AuthorityField)            BibEntry
 * SwFmt "Source Text"                      Code
 * SwFtnPortion, SwFldPortion (RefField)    Link
 *
 * Illustration elements:
 *
 * SwFlyFrm with SwNoTxtFrm                 Figure
 * SwFlyFrm with Math OLE Object            Formula
 *
 */

struct Num_Info
{
    const SwFrm& mrFrm;
    Num_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};
};

struct Frm_Info
{
    const SwFrm& mrFrm;
    Frm_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};
};

struct Por_Info
{
    const SwLinePortion& mrPor;
    const SwTxtPainter& mrTxtPainter;
    Por_Info( const SwLinePortion& rPor, const SwTxtPainter& rTxtPainer )
            : mrPor( rPor ), mrTxtPainter( rTxtPainer ) {};
};

struct lt_TableColumn
{
    bool operator()( long nVal1, long nVal2 ) const
    {
        return nVal1 + ( MINLAY - 1 ) < nVal2;
    }
};

/*************************************************************************
 *                class SwTaggedPDFHelper
 * Analyses a given frame during painting and generates the appropriate
 * structure elements.
 *************************************************************************/

class SwTaggedPDFHelper
{
    private:

    // This will be incremented for each BeginTag() call.
    // It denotes the number of tags to close during EndStructureElements();
    BYTE nEndStructureElement;

    //  If an already existing tag is reopened for follows of flow frames,
    // this value stores the tag id which has to be restored.
    sal_Int32 nRestoreCurrentTag;

    vcl::PDFExtOutDevData* mpPDFExtOutDevData;

    const Num_Info* mpNumInfo;
    const Frm_Info* mpFrmInfo;
    const Por_Info* mpPorInfo;

    void BeginTag( vcl::PDFWriter::StructElement aTagRole, const String& rTagName );
    void EndTag();

    void SetAttributes( vcl::PDFWriter::StructElement eType );

    // These functions are called by the c'tor, d'tor
    void BeginNumberedListStructureElements();
    void BeginBlockStructureElements();
    void BeginInlineStructureElements();
    void EndStructureElements();

    bool CheckReopenTag();
    bool CheckRestoreTag() const;

    public:

    // pFrmInfo != 0 => BeginBlockStructureElement
    // pPorInfo != 0 => BeginInlineStructureElement
    // pFrmInfo, pPorInfo = 0 => BeginNonStructureElement
    SwTaggedPDFHelper( const Num_Info* pNumInfo, const Frm_Info* pFrmInfo, const Por_Info* pPorInfo,
                       OutputDevice& rOut );
    ~SwTaggedPDFHelper();

    static bool IsExportTaggedPDF( const OutputDevice& rOut );
};

/*************************************************************************
 *                class SwEnhancedPDFExportHelper
 * Analyses the document structure and export Notes, Hyperlinks, References,
 * and Outline. Link ids created during pdf export are stored in
 * aReferenceIdMap and aHyperlinkIdMap, in order to use them during
 * tagged pdf output. Therefore the SwEnhancedPDFExportHelper is used
 * before painting. Unfortunately links from the EditEngine into the
 * Writer document require to be exported after they have been painted.
 * Therefore SwEnhancedPDFExportHelper also has to be used after the
 * painting process, the parameter bEditEngineOnly indicated that only
 * the bookmarks from the EditEngine have to be processed.
 *************************************************************************/

typedef std::set< long, lt_TableColumn > TableColumnsMapEntry;
typedef std::pair< SwRect, sal_Int32 > IdMapEntry;
typedef std::vector< IdMapEntry > LinkIdMap;
typedef std::map< const SwTable*, TableColumnsMapEntry > TableColumnsMap;
typedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListIdMap;
typedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListBodyIdMap;
typedef std::map< const void*, sal_Int32 > FrmTagIdMap;

class SwEnhancedPDFExportHelper
{
    private:

    SwEditShell& mrSh;
    OutputDevice& mrOut;

    MultiSelection* pPageRange;

    bool mbSkipEmptyPages;
    bool mbEditEngineOnly;

    static TableColumnsMap aTableColumnsMap;
    static LinkIdMap aLinkIdMap;
    static NumListIdMap aNumListIdMap;
    static NumListBodyIdMap aNumListBodyIdMap;
    static FrmTagIdMap aFrmTagIdMap;

    static LanguageType eLanguageDefault;

    void EnhancedPDFExport();
    sal_Int32 CalcOutputPageNum( const SwRect& rRect ) const;

    void MakeHeaderFooterLinks( vcl::PDFExtOutDevData& rPDFExtOutDevData,
                                const SwTxtNode& rTNd, const SwRect& rLinkRect,
                                sal_Int32 nDestId, const String& rURL, bool bIntern ) const;

    public:

    SwEnhancedPDFExportHelper( SwEditShell& rSh,
                               OutputDevice& rOut,
                               const rtl::OUString& rPageRange,
                               bool bSkipEmptyPages,
                               bool bEditEngineOnly );

    ~SwEnhancedPDFExportHelper();

    static TableColumnsMap& GetTableColumnsMap() {return aTableColumnsMap; }
    static LinkIdMap& GetLinkIdMap() { return aLinkIdMap; }
    static NumListIdMap& GetNumListIdMap() {return aNumListIdMap; }
    static NumListBodyIdMap& GetNumListBodyIdMap() {return aNumListBodyIdMap; }
    static FrmTagIdMap& GetFrmTagIdMap() { return aFrmTagIdMap; }

    static const LanguageType GetDefaultLanguage() {return eLanguageDefault; }
};

#endif
<|endoftext|>


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

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

#include <hintids.hxx>
#include <tools/poly.hxx>
#include <svl/stritem.hxx>
#include <svx/contdlg.hxx>
#include <vcl/svapp.hxx>
#include <docary.hxx>
#include <doc.hxx>
#include <fmtcol.hxx>
#include <ndnotxt.hxx>
#include <ndgrf.hxx>
#include <ndole.hxx>
#include <ndindex.hxx>
#include <hints.hxx>            // fuer SwFmtChg
#include <istyleaccess.hxx>
#include <SwStyleNameMapper.hxx>

// --> OD 2009-07-13 #i73249#
#include <frmfmt.hxx>
// <--

SwNoTxtNode::SwNoTxtNode( const SwNodeIndex & rWhere,
                  const sal_uInt8 nNdType,
                  SwGrfFmtColl *pGrfColl,
                  SwAttrSet* pAutoAttr ) :
    SwCntntNode( rWhere, nNdType, pGrfColl ),
    pContour( 0 ),
    bAutomaticContour( sal_False ),
    bContourMapModeValid( sal_True ),
    bPixelContour( sal_False )
{
    // soll eine Harte-Attributierung gesetzt werden?
    if( pAutoAttr )
        SetAttr( *pAutoAttr );
}

SwNoTxtNode::~SwNoTxtNode()
{
    delete pContour;
}

// erzeugt fuer alle Ableitungen einen AttrSet mit Bereichen
// fuer Frame- und Grafik-Attributen
void SwNoTxtNode::NewAttrSet( SwAttrPool& rPool )
{
    ASSERT( !mpAttrSet.get(), "AttrSet ist doch gesetzt" );
    SwAttrSet aNewAttrSet( rPool, aNoTxtNodeSetRange );

    // put names of parent style and conditional style:
    const SwFmtColl* pFmtColl = GetFmtColl();
    String sVal;
    SwStyleNameMapper::FillProgName( pFmtColl->GetName(), sVal, nsSwGetPoolIdFromName::GET_POOLID_TXTCOLL, sal_True );
    SfxStringItem aFmtColl( RES_FRMATR_STYLE_NAME, sVal );
    aNewAttrSet.Put( aFmtColl );

    aNewAttrSet.SetParent( &GetFmtColl()->GetAttrSet() );
    mpAttrSet = GetDoc()->GetIStyleAccess().getAutomaticStyle( aNewAttrSet, IStyleAccess::AUTO_STYLE_NOTXT );
}

// Dummies fuer das Laden/Speichern von persistenten Daten
// bei Grafiken und OLE-Objekten

sal_Bool SwNoTxtNode::RestorePersistentData()
{
    return sal_True;
}

sal_Bool SwNoTxtNode::SavePersistentData()
{
    return sal_True;
}

void SwNoTxtNode::SetContour( const PolyPolygon *pPoly, sal_Bool bAutomatic )
{
    delete pContour;
    if ( pPoly )
        pContour = new PolyPolygon( *pPoly );
    else
        pContour = 0;
    bAutomaticContour = bAutomatic;
    bContourMapModeValid = sal_True;
    bPixelContour = sal_False;
}

void SwNoTxtNode::CreateContour()
{
    ASSERT( !pContour, "Contour available." );
    pContour = new PolyPolygon(SvxContourDlg::CreateAutoContour(GetGraphic()));
    bAutomaticContour = sal_True;
    bContourMapModeValid = sal_True;
    bPixelContour = sal_False;
}

const PolyPolygon *SwNoTxtNode::HasContour() const
{
    if( !bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        sal_Bool bPixelGrf = aGrfMap.GetMapUnit() == MAP_PIXEL;
        const MapMode aContourMap( bPixelGrf ? MAP_PIXEL : MAP_100TH_MM );
        if( bPixelGrf ? !bPixelContour : aGrfMap != aContourMap )
        {
            ASSERT( !bPixelGrf || aGrfMap == aContourMap,
                    "scale factor for pixel unsupported" );
            OutputDevice* pOutDev =
                (bPixelGrf || bPixelContour) ? Application::GetDefaultDevice()
                                             : 0;
            sal_uInt16 nPolyCount = pContour->Count();
            for( sal_uInt16 j=0; j<nPolyCount; j++ )
            {
                Polygon& rPoly = (*pContour)[j];

                sal_uInt16 nCount = rPoly.GetSize();
                for( sal_uInt16 i=0 ; i<nCount; i++ )
                {
                    if( bPixelGrf )
                        rPoly[i] = pOutDev->LogicToPixel( rPoly[i],
                                                          aContourMap );
                    else if( bPixelContour )
                        rPoly[i] = pOutDev->PixelToLogic( rPoly[i], aGrfMap );
                    else
                        rPoly[i] = OutputDevice::LogicToLogic( rPoly[i],
                                                                 aContourMap,
                                                                 aGrfMap );
                }
            }
        }
        ((SwNoTxtNode *)this)->bContourMapModeValid = sal_True;
        ((SwNoTxtNode *)this)->bPixelContour = sal_False;
    }

    return pContour;
}

void SwNoTxtNode::GetContour( PolyPolygon &rPoly ) const
{
    ASSERT( pContour, "Contour not available." );
    rPoly = *HasContour();
}

void SwNoTxtNode::SetContourAPI( const PolyPolygon *pPoly )
{
    delete pContour;
    if ( pPoly )
        pContour = new PolyPolygon( *pPoly );
    else
        pContour = 0;
    bContourMapModeValid = sal_False;
}

sal_Bool SwNoTxtNode::GetContourAPI( PolyPolygon &rContour ) const
{
    if( !pContour )
        return sal_False;

    rContour = *pContour;
    if( bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        const MapMode aContourMap( MAP_100TH_MM );
        ASSERT( aGrfMap.GetMapUnit() != MAP_PIXEL ||
                aGrfMap == MapMode( MAP_PIXEL ),
                    "scale factor for pixel unsupported" );
        if( aGrfMap.GetMapUnit() != MAP_PIXEL &&
            aGrfMap != aContourMap )
        {
            sal_uInt16 nPolyCount = rContour.Count();
            for( sal_uInt16 j=0; j<nPolyCount; j++ )
            {
                Polygon& rPoly = (*pContour)[j];

                sal_uInt16 nCount = rPoly.GetSize();
                for( sal_uInt16 i=0 ; i<nCount; i++ )
                {
                    rPoly[i] = OutputDevice::LogicToLogic( rPoly[i], aGrfMap,
                                                           aContourMap );
                }
            }
        }
    }

    return sal_True;
}

sal_Bool SwNoTxtNode::IsPixelContour() const
{
    sal_Bool bRet;
    if( bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        bRet = aGrfMap.GetMapUnit() == MAP_PIXEL;
    }
    else
    {
        bRet = bPixelContour;
    }

    return bRet;
}

Graphic SwNoTxtNode::GetGraphic() const
{
    Graphic aRet;
    if ( GetGrfNode() )
    {
        ((SwGrfNode*)this)->SwapIn( sal_True );
        aRet = ((SwGrfNode*)this)->GetGrf();
    }
    else
    {
        ASSERT( GetOLENode(), "new type of Node?" );
        aRet = *((SwOLENode*)this)->SwOLENode::GetGraphic();
    }
    return aRet;
}

// --> OD 2009-07-14 #i73249#
void SwNoTxtNode::SetTitle( const String& rTitle, bool bBroadcast )
{
    // Title attribute of <SdrObject> replaces own AlternateText attribute
    SwFlyFrmFmt* pFlyFmt = dynamic_cast<SwFlyFrmFmt*>(GetFlyFmt());
    ASSERT( pFlyFmt,
            "<SwNoTxtNode::SetTitle(..)> - missing <SwFlyFrmFmt> instance" );
    if ( !pFlyFmt )
    {
        return;
    }

    pFlyFmt->SetObjTitle( rTitle, bBroadcast );
}

const String SwNoTxtNode::GetTitle() const
{
    const SwFlyFrmFmt* pFlyFmt = dynamic_cast<const SwFlyFrmFmt*>(GetFlyFmt());
    ASSERT( pFlyFmt,
            "<SwNoTxtNode::GetTitle(..)> - missing <SwFlyFrmFmt> instance" );
    if ( !pFlyFmt )
    {
        return aEmptyStr;
    }

    return pFlyFmt->GetObjTitle();
}

void SwNoTxtNode::SetDescription( const String& rDescription, bool bBroadcast )
{
    SwFlyFrmFmt* pFlyFmt = dynamic_cast<SwFlyFrmFmt*>(GetFlyFmt());
    ASSERT( pFlyFmt,
            "<SwNoTxtNode::SetDescription(..)> - missing <SwFlyFrmFmt> instance" );
    if ( !pFlyFmt )
    {
        return;
    }

    pFlyFmt->SetObjDescription( rDescription, bBroadcast );
}

const String SwNoTxtNode::GetDescription() const
{
    const SwFlyFrmFmt* pFlyFmt = dynamic_cast<const SwFlyFrmFmt*>(GetFlyFmt());
    ASSERT( pFlyFmt,
            "<SwNoTxtNode::GetDescription(..)> - missing <SwFlyFrmFmt> instance" );
    if ( !pFlyFmt )
    {
        return aEmptyStr;
    }

    return pFlyFmt->GetObjDescription();
}
// <--
<commit_msg>sw34bf05: #i102238# - correct contour polypolygon conversion in case that graphic's map made is not MAP_PIXEL<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <hintids.hxx>
#include <tools/poly.hxx>
#include <svl/stritem.hxx>
#include <svx/contdlg.hxx>
#include <vcl/svapp.hxx>
#include <docary.hxx>
#include <doc.hxx>
#include <fmtcol.hxx>
#include <ndnotxt.hxx>
#include <ndgrf.hxx>
#include <ndole.hxx>
#include <ndindex.hxx>
#include <hints.hxx>            // fuer SwFmtChg
#include <istyleaccess.hxx>
#include <SwStyleNameMapper.hxx>

// --> OD 2009-07-13 #i73249#
#include <frmfmt.hxx>
// <--

SwNoTxtNode::SwNoTxtNode( const SwNodeIndex & rWhere,
                  const sal_uInt8 nNdType,
                  SwGrfFmtColl *pGrfColl,
                  SwAttrSet* pAutoAttr ) :
    SwCntntNode( rWhere, nNdType, pGrfColl ),
    pContour( 0 ),
    bAutomaticContour( sal_False ),
    bContourMapModeValid( sal_True ),
    bPixelContour( sal_False )
{
    // soll eine Harte-Attributierung gesetzt werden?
    if( pAutoAttr )
        SetAttr( *pAutoAttr );
}

SwNoTxtNode::~SwNoTxtNode()
{
    delete pContour;
}

// erzeugt fuer alle Ableitungen einen AttrSet mit Bereichen
// fuer Frame- und Grafik-Attributen
void SwNoTxtNode::NewAttrSet( SwAttrPool& rPool )
{
    ASSERT( !mpAttrSet.get(), "AttrSet ist doch gesetzt" );
    SwAttrSet aNewAttrSet( rPool, aNoTxtNodeSetRange );

    // put names of parent style and conditional style:
    const SwFmtColl* pFmtColl = GetFmtColl();
    String sVal;
    SwStyleNameMapper::FillProgName( pFmtColl->GetName(), sVal, nsSwGetPoolIdFromName::GET_POOLID_TXTCOLL, sal_True );
    SfxStringItem aFmtColl( RES_FRMATR_STYLE_NAME, sVal );
    aNewAttrSet.Put( aFmtColl );

    aNewAttrSet.SetParent( &GetFmtColl()->GetAttrSet() );
    mpAttrSet = GetDoc()->GetIStyleAccess().getAutomaticStyle( aNewAttrSet, IStyleAccess::AUTO_STYLE_NOTXT );
}

// Dummies fuer das Laden/Speichern von persistenten Daten
// bei Grafiken und OLE-Objekten

sal_Bool SwNoTxtNode::RestorePersistentData()
{
    return sal_True;
}

sal_Bool SwNoTxtNode::SavePersistentData()
{
    return sal_True;
}

void SwNoTxtNode::SetContour( const PolyPolygon *pPoly, sal_Bool bAutomatic )
{
    delete pContour;
    if ( pPoly )
        pContour = new PolyPolygon( *pPoly );
    else
        pContour = 0;
    bAutomaticContour = bAutomatic;
    bContourMapModeValid = sal_True;
    bPixelContour = sal_False;
}

void SwNoTxtNode::CreateContour()
{
    ASSERT( !pContour, "Contour available." );
    pContour = new PolyPolygon(SvxContourDlg::CreateAutoContour(GetGraphic()));
    bAutomaticContour = sal_True;
    bContourMapModeValid = sal_True;
    bPixelContour = sal_False;
}

const PolyPolygon *SwNoTxtNode::HasContour() const
{
    if( !bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        sal_Bool bPixelGrf = aGrfMap.GetMapUnit() == MAP_PIXEL;
        const MapMode aContourMap( bPixelGrf ? MAP_PIXEL : MAP_100TH_MM );
        if( bPixelGrf ? !bPixelContour : aGrfMap != aContourMap )
        {
            // --> OD #i102238#
            double nGrfDPIx = 0.0;
            double nGrfDPIy = 0.0;
            {
                if ( !bPixelGrf && bPixelContour )
                {
                    const Size aGrfPixelSize( GetGraphic().GetSizePixel() );
                    const Size aGrfPrefMapModeSize( GetGraphic().GetPrefSize() );
                    if ( aGrfMap.GetMapUnit() == MAP_INCH )
                    {
                        nGrfDPIx = aGrfPixelSize.Width() / ( (double)aGrfMap.GetScaleX() * aGrfPrefMapModeSize.Width() );
                        nGrfDPIy = aGrfPixelSize.Height() / ( (double)aGrfMap.GetScaleY() * aGrfPrefMapModeSize.Height() );
                    }
                    else
                    {
                        const Size aGrf1000thInchSize =
                            OutputDevice::LogicToLogic( aGrfPrefMapModeSize,
                                                        aGrfMap, MAP_1000TH_INCH );
                        nGrfDPIx = 1000.0 * aGrfPixelSize.Width() / aGrf1000thInchSize.Width();
                        nGrfDPIy = 1000.0 * aGrfPixelSize.Height() / aGrf1000thInchSize.Height();
                    }
                }
            }
            // <--
            ASSERT( !bPixelGrf || aGrfMap == aContourMap,
                    "scale factor for pixel unsupported" );
            OutputDevice* pOutDev =
                (bPixelGrf || bPixelContour) ? Application::GetDefaultDevice()
                                             : 0;
            sal_uInt16 nPolyCount = pContour->Count();
            for( sal_uInt16 j=0; j<nPolyCount; j++ )
            {
                Polygon& rPoly = (*pContour)[j];

                sal_uInt16 nCount = rPoly.GetSize();
                for( sal_uInt16 i=0 ; i<nCount; i++ )
                {
                    if( bPixelGrf )
                        rPoly[i] = pOutDev->LogicToPixel( rPoly[i],
                                                          aContourMap );
                    else if( bPixelContour )
                    {
                        rPoly[i] = pOutDev->PixelToLogic( rPoly[i], aGrfMap );
                        // --> OD #i102238#
                        if ( nGrfDPIx != 0 && nGrfDPIy != 0 )
                        {
                            rPoly[i] = Point( rPoly[i].X() * pOutDev->ImplGetDPIX() / nGrfDPIx,
                                              rPoly[i].Y() * pOutDev->ImplGetDPIY() / nGrfDPIy );
                        }
                        // <--
                    }
                    else
                        rPoly[i] = OutputDevice::LogicToLogic( rPoly[i],
                                                                 aContourMap,
                                                                 aGrfMap );
                }
            }
        }
        ((SwNoTxtNode *)this)->bContourMapModeValid = sal_True;
        ((SwNoTxtNode *)this)->bPixelContour = sal_False;
    }

    return pContour;
}

void SwNoTxtNode::GetContour( PolyPolygon &rPoly ) const
{
    ASSERT( pContour, "Contour not available." );
    rPoly = *HasContour();
}

void SwNoTxtNode::SetContourAPI( const PolyPolygon *pPoly )
{
    delete pContour;
    if ( pPoly )
        pContour = new PolyPolygon( *pPoly );
    else
        pContour = 0;
    bContourMapModeValid = sal_False;
}

sal_Bool SwNoTxtNode::GetContourAPI( PolyPolygon &rContour ) const
{
    if( !pContour )
        return sal_False;

    rContour = *pContour;
    if( bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        const MapMode aContourMap( MAP_100TH_MM );
        ASSERT( aGrfMap.GetMapUnit() != MAP_PIXEL ||
                aGrfMap == MapMode( MAP_PIXEL ),
                    "scale factor for pixel unsupported" );
        if( aGrfMap.GetMapUnit() != MAP_PIXEL &&
            aGrfMap != aContourMap )
        {
            sal_uInt16 nPolyCount = rContour.Count();
            for( sal_uInt16 j=0; j<nPolyCount; j++ )
            {
                // --> OD #i102238# - use the right <PolyPolygon> instance
                Polygon& rPoly = rContour[j];
                // <--

                sal_uInt16 nCount = rPoly.GetSize();
                for( sal_uInt16 i=0 ; i<nCount; i++ )
                {
                    rPoly[i] = OutputDevice::LogicToLogic( rPoly[i], aGrfMap,
                                                           aContourMap );
                }
            }
        }
    }

    return sal_True;
}

sal_Bool SwNoTxtNode::IsPixelContour() const
{
    sal_Bool bRet;
    if( bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        bRet = aGrfMap.GetMapUnit() == MAP_PIXEL;
    }
    else
    {
        bRet = bPixelContour;
    }

    return bRet;
}

Graphic SwNoTxtNode::GetGraphic() const
{
    Graphic aRet;
    if ( GetGrfNode() )
    {
        ((SwGrfNode*)this)->SwapIn( sal_True );
        aRet = ((SwGrfNode*)this)->GetGrf();
    }
    else
    {
        ASSERT( GetOLENode(), "new type of Node?" );
        aRet = *((SwOLENode*)this)->SwOLENode::GetGraphic();
    }
    return aRet;
}

// --> OD 2009-07-14 #i73249#
void SwNoTxtNode::SetTitle( const String& rTitle, bool bBroadcast )
{
    // Title attribute of <SdrObject> replaces own AlternateText attribute
    SwFlyFrmFmt* pFlyFmt = dynamic_cast<SwFlyFrmFmt*>(GetFlyFmt());
    ASSERT( pFlyFmt,
            "<SwNoTxtNode::SetTitle(..)> - missing <SwFlyFrmFmt> instance" );
    if ( !pFlyFmt )
    {
        return;
    }

    pFlyFmt->SetObjTitle( rTitle, bBroadcast );
}

const String SwNoTxtNode::GetTitle() const
{
    const SwFlyFrmFmt* pFlyFmt = dynamic_cast<const SwFlyFrmFmt*>(GetFlyFmt());
    ASSERT( pFlyFmt,
            "<SwNoTxtNode::GetTitle(..)> - missing <SwFlyFrmFmt> instance" );
    if ( !pFlyFmt )
    {
        return aEmptyStr;
    }

    return pFlyFmt->GetObjTitle();
}

void SwNoTxtNode::SetDescription( const String& rDescription, bool bBroadcast )
{
    SwFlyFrmFmt* pFlyFmt = dynamic_cast<SwFlyFrmFmt*>(GetFlyFmt());
    ASSERT( pFlyFmt,
            "<SwNoTxtNode::SetDescription(..)> - missing <SwFlyFrmFmt> instance" );
    if ( !pFlyFmt )
    {
        return;
    }

    pFlyFmt->SetObjDescription( rDescription, bBroadcast );
}

const String SwNoTxtNode::GetDescription() const
{
    const SwFlyFrmFmt* pFlyFmt = dynamic_cast<const SwFlyFrmFmt*>(GetFlyFmt());
    ASSERT( pFlyFmt,
            "<SwNoTxtNode::GetDescription(..)> - missing <SwFlyFrmFmt> instance" );
    if ( !pFlyFmt )
    {
        return aEmptyStr;
    }

    return pFlyFmt->GetObjDescription();
}
// <--
<|endoftext|>


<commit_before><commit_msg>coverity#704880 Dereference after null check<commit_after><|endoftext|>


<commit_before><commit_msg>sw: unused includes in calcmove<commit_after><|endoftext|>


<commit_before><commit_msg>sw: SwLayHelper should not consider the page after first page a first page<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#include <algorithm>
#include "simple_strategy.hh"
#include "utils/class_registrator.hh"
#include <boost/algorithm/string.hpp>
#include "utils/sequenced_set.hh"

namespace locator {

simple_strategy::simple_strategy(const sstring& keyspace_name, token_metadata& token_metadata, snitch_ptr& snitch, const std::map<sstring, sstring>& config_options) :
        abstract_replication_strategy(keyspace_name, token_metadata, snitch, config_options, replication_strategy_type::simple) {
    for (auto& config_pair : config_options) {
        auto& key = config_pair.first;
        auto& val = config_pair.second;

        if (boost::iequals(key, "replication_factor")) {
            _replication_factor = std::stol(val);

            break;
        }
    }
}

std::vector<inet_address> simple_strategy::calculate_natural_endpoints(const token& t) {
    const std::vector<token>& tokens = _token_metadata.sorted_tokens();

    if (tokens.empty()) {
        return std::vector<inet_address>();
    }

    size_t replicas = get_replication_factor();
    utils::sequenced_set<inet_address> endpoints;
    endpoints.reserve(replicas);

    for (auto& token : _token_metadata.ring_range(t)) {
        auto ep = _token_metadata.get_endpoint(token);
        assert(ep);

        endpoints.push_back(*ep);
    }

    return std::move(endpoints.get_vector());
}

size_t simple_strategy::get_replication_factor() const {
    return _replication_factor;
}

using registry = class_registrator<abstract_replication_strategy, simple_strategy, const sstring&, token_metadata&, snitch_ptr&, const std::map<sstring, sstring>&>;
static registry registrator("org.apache.cassandra.locator.SimpleStrategy");
static registry registrator_short_name("SimpleStrategy");

}
<commit_msg>calculate_natural_endpoints limit retuned ips by replication factor<commit_after>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#include <algorithm>
#include "simple_strategy.hh"
#include "utils/class_registrator.hh"
#include <boost/algorithm/string.hpp>
#include "utils/sequenced_set.hh"

namespace locator {

simple_strategy::simple_strategy(const sstring& keyspace_name, token_metadata& token_metadata, snitch_ptr& snitch, const std::map<sstring, sstring>& config_options) :
        abstract_replication_strategy(keyspace_name, token_metadata, snitch, config_options, replication_strategy_type::simple) {
    for (auto& config_pair : config_options) {
        auto& key = config_pair.first;
        auto& val = config_pair.second;

        if (boost::iequals(key, "replication_factor")) {
            _replication_factor = std::stol(val);

            break;
        }
    }
}

std::vector<inet_address> simple_strategy::calculate_natural_endpoints(const token& t) {
    const std::vector<token>& tokens = _token_metadata.sorted_tokens();

    if (tokens.empty()) {
        return std::vector<inet_address>();
    }

    size_t replicas = get_replication_factor();
    utils::sequenced_set<inet_address> endpoints;
    endpoints.reserve(replicas);

    for (auto& token : _token_metadata.ring_range(t)) {
        auto ep = _token_metadata.get_endpoint(token);
        assert(ep);

        endpoints.push_back(*ep);
        if (endpoints.size() == replicas) break;
    }

    return std::move(endpoints.get_vector());
}

size_t simple_strategy::get_replication_factor() const {
    return _replication_factor;
}

using registry = class_registrator<abstract_replication_strategy, simple_strategy, const sstring&, token_metadata&, snitch_ptr&, const std::map<sstring, sstring>&>;
static registry registrator("org.apache.cassandra.locator.SimpleStrategy");
static registry registrator_short_name("SimpleStrategy");

}
<|endoftext|>


<commit_before>/*=============================================================*/
/* SECTION: Includes                                           */
/*=============================================================*/

#define _WIN32_WINNT 0x0600
#include <windows.h>
#include <psapi.h>
#include <QDesktopWidget>

#include <Qt>

#include <QKeyEvent>
#include <QMessageBox>
#include <QShortcut>
#include <QHash>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "cmdformatter.h"

/*=============================================================*/
/* SECTION: Local Data                                         */
/*=============================================================*/

/// Stores saved alias windows.
QHash<HWND, QString> gSavedWins;

/// The application version string.
QString gVerStr("0.5.0-alpha");

/*=============================================================*/
/* SECTION: Local Prototypes                                   */
/*=============================================================*/

static BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam);
static BOOL IsAltTabWindow(HWND hwnd);

/*=============================================================*/
/* SECTION: Function Definitions                               */
/*=============================================================*/

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        proxy(new QSortFilterProxyModel(parent)),
        model(new QStandardItemModel(0, 4, parent))
{
    // Set the window style.
    Qt::WindowFlags flags = windowFlags();
    setWindowFlags(flags | Qt::WindowStaysOnTopHint | Qt::ToolTip);

    // Set up system tray.
    trayIconMenu = new QMenu(this);
    aboutAction = new QAction(tr("&About"), this);
    quitAction = new QAction(tr("&Quit"), this);
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutMain()));
    connect(quitAction, SIGNAL(triggered()), this, SLOT(quitMain()));
    trayIconMenu->addAction(aboutAction);
    trayIconMenu->addAction(quitAction);
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->setToolTip(QString("QuickWin"));
    trayIcon->setIcon(QIcon("icon.png"));
    trayIcon->show();

    // Set up UI items.
    ui->setupUi(this);
    proxy->setSourceModel(model);
    ui->winView->setModel(proxy);
    proxy->setFilterKeyColumn(1);
    ui->winView->setSortingEnabled(true);
    ui->winView->sortByColumn(0, Qt::AscendingOrder);
    ui->winView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    model->setHeaderData(0, Qt::Horizontal, QObject::tr("Number"));
    model->setHeaderData(1, Qt::Horizontal, QObject::tr("Title"));
    model->setHeaderData(2, Qt::Horizontal, QObject::tr("Executable"));
    model->setHeaderData(3, Qt::Horizontal, QObject::tr("Alias"));
    sizePosMain();

    connect(ui->cmdText, SIGNAL(returnPressed()),
            this,SLOT(onTextEnter()));
    connect(ui->cmdText, SIGNAL(textChanged(const QString &)),
            this, SLOT(onTextChanged(const QString &)));
    connect(ui->winView, SIGNAL(activated(QModelIndex)),
            this, SLOT(onWitemActivate(QModelIndex)));

    // Register system-wide hotkey.
    HWND hwnd = (HWND)this->winId();
    RegisterHotKey(hwnd, 100, MOD_CONTROL | MOD_ALT, VK_SPACE);

    updateWinList(true);
}

void MainWindow::sizePosMain(void) {
    // Center window.
    QDesktopWidget *desktop = QApplication::desktop();
    int width = desktop->width() * 0.6;
    int height = desktop->height() * 0.6;
    setFixedSize(width, height);
    move((desktop->width() - width) / 2, (desktop->height() - height) / 2);

    ui->winView->header()->resizeSection(0, width * 0.08);
    ui->winView->header()->resizeSection(1, width * 0.7);
}

void MainWindow::aboutMain(void) {
    QMessageBox::about(this,
            "About QuickWin",
            "QuickWin version `" + gVerStr + "`.\nVisit 'github.com/jeffrimko/QuickWin' for more information.");
}

void MainWindow::quitMain(void) {
    exit(0);
}

void MainWindow::updateWinList(bool clear_note) {
    model->removeRows(0, model->rowCount());
    witems.clear();
    EnumWindows(EnumWindowsProc, (LPARAM)this);
    for(int i = 0; i < witems.size(); i++) {
        model->insertRow(i);
        model->setData(model->index(i, 0), QString::number(witems[i].num));
        model->setData(model->index(i, 1), witems[i].title);
        model->setData(model->index(i, 2), witems[i].exec);
        model->setData(model->index(i, 3), gSavedWins[witems[i].handle]);
    }
    ui->winView->setCurrentIndex(proxy->index(0,0));
    if(clear_note) {
        ui->noteText->clear();
        ui->noteText->append("QuickWin " + gVerStr + " found " + QString::number(witems.size()) + " windows.");
    }
}

void MainWindow::checkSavedWins(void) {
    if(gSavedWins.size()) {
        QHashIterator<HWND, QString> i(gSavedWins);
        while (i.hasNext()) {
            i.next();
            bool win_okay = false;
            for(int j = 0; j < witems.size(); j++) {
                if(witems[j].handle == i.key()) {
                    win_okay = true;
                    break;
                }
            }
            if(false == win_okay) {
                gSavedWins.remove(i.key());
            }
        }
    }
}

void MainWindow::onTextChanged(const QString &text) {
    static QString prev_ptrn = "";
    cmds_t cmds;
    QString ptrn = "";
    format_cmds(cmds, text.toStdString());
    if("" != cmds["number"]) {
        proxy->setFilterKeyColumn(0);
        ptrn = QString::fromStdString(cmds["number"]);
    } else if("" != cmds["executable"]) {
        proxy->setFilterKeyColumn(2);
        ptrn = QString::fromStdString(cmds["executable"]);
    } else if(cmds.find("get") != cmds.end()) {
        proxy->setFilterKeyColumn(3);
        if("" != cmds["get"]) {
            ptrn = QString::fromStdString(cmds["get"]);
        } else {
            ptrn = "?";
        }
    } else {
        proxy->setFilterKeyColumn(1);
        ptrn = QString::fromStdString(cmds["title"]);
    }
    if(prev_ptrn != ptrn) {
        proxy->setFilterRegExp(QRegExp(ptrn, Qt::CaseInsensitive, QRegExp::Wildcard));
        ui->winView->setCurrentIndex(proxy->index(0,0));
    }
    prev_ptrn = ptrn;
}

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

void MainWindow::keyPressEvent(QKeyEvent *event) {
    bool hide_win = (event->key() == Qt::Key_Escape);
    bool quit_app = false;

    SelMove mv = SELMOVE_NO;
    if(event->modifiers() && Qt::ControlModifier) {
        switch(event->key()) {
            case Qt::Key_H: mv = SELMOVE_TOP; break;
            case Qt::Key_L: mv = SELMOVE_BTM; break;
            case Qt::Key_K: mv = SELMOVE_UP; break;
            case Qt::Key_J: mv = SELMOVE_DWN; break;
            case Qt::Key_M: mv = SELMOVE_MID; break;
            case Qt::Key_E: mv = SELMOVE_EXE; break;
            case Qt::Key_S: onWitemActivate(ui->winView->currentIndex());
            case Qt::Key_C: hide_win = true; break;
#ifndef QT_NO_DEBUG
            case Qt::Key_X: quit_app = true; break;
#endif
        }
    } else {
        switch(event->key()) {
            case Qt::Key_Home: mv = SELMOVE_TOP; break;
            case Qt::Key_End: mv = SELMOVE_BTM; break;
            case Qt::Key_Up: mv = SELMOVE_UP; break;
            case Qt::Key_Down: mv = SELMOVE_DWN; break;
        }
    }
    moveSel(mv);

    if(hide_win) {
        hide();
    }
    // TODO: Debug only! Remove later...
    if(quit_app) {
        quitMain();
    }
}

void MainWindow::moveSel(SelMove mv) {
    // Handle selection movement.
    int row = ui->winView->currentIndex().row();
    if((SELMOVE_UP == mv) | (SELMOVE_DWN == mv)) {
        if(SELMOVE_UP == mv) {
            if(row == 0) {
                row = proxy->rowCount() - 1;
            } else {
                row -= 1;
            }
        } else {
            row += 1;
            if(row >= proxy->rowCount()) {
                row = 0;
            }
        }
        ui->winView->setCurrentIndex(proxy->index(row,0));
    } else if(SELMOVE_TOP == mv) {
        ui->winView->setCurrentIndex(proxy->index(0,0));
    } else if(SELMOVE_MID == mv) {
        ui->winView->setCurrentIndex(proxy->index(proxy->rowCount()/2,0));
    } else if(SELMOVE_BTM == mv) {
        ui->winView->setCurrentIndex(proxy->index(proxy->rowCount()-1,0));
    } else if(SELMOVE_EXE == mv) {
        QString exec = witems[row].exec;
        int idx = row + 1;
        while(idx != row) {
            if(idx >= witems.size()) {
                idx = 0;
            }
            if(exec == witems[idx].exec) {
                break;
            }
            idx++;
        }
        ui->winView->setCurrentIndex(proxy->index(idx,0));
    }
}

void MainWindow::showWin(HWND handle) {
    if(IsIconic(handle)) {
        ShowWindow(handle, SW_RESTORE);
    }
    SetForegroundWindow(handle);
}

void MainWindow::onWitemActivate(QModelIndex index) {
    if(proxy->rowCount() == 0)
        return;
    showWin(witems[getSelWinNum()].handle);
}

uint MainWindow::getSelWinNum(void) {
    uint row = ui->winView->currentIndex().row();
    uint num = proxy->data(proxy->index(row, 0)).toInt() - 1;
    return(num);
}

void MainWindow::onTextEnter()
{
    bool stay = false;
    cmds_t cmds;
    QString text = ui->cmdText->text();
    format_cmds(cmds, text.toStdString());

    if(cmds.find("help") != cmds.end()) {
        QString help = "Commands: ";
        for(std::string cmd : list_cmd_types()) {
            help += QString::fromStdString(cmd);
            help += " ";
        }
        ui->noteText->append(help);
        stay = true;
    }
    if(cmds.find("delete") != cmds.end()) {
        gSavedWins.clear();
        ui->noteText->append("Aliases deleted.");
        stay = true;
    }
    if(cmds.find("set") != cmds.end()) {
        uint num = getSelWinNum();
        if("" != cmds["set"]) {
            QString name = QString::fromStdString(cmds["set"]);
            gSavedWins[witems[num].handle] = name;
            ui->noteText->append("Set " + QString::number(num+1) + " to alias '" + name + "'.");
        } else {
            gSavedWins.remove(witems[num].handle);
            ui->noteText->append("Removed alias from " + QString::number(num+1) + ".");
        }
        stay = true;
    }

    if(!stay) {
        onWitemActivate(ui->winView->currentIndex());
    } else {
        ui->cmdText->clear();
        updateWinList(false);
    }
}

bool MainWindow::winEvent( MSG * message, long * result )  {
    if(message->message == 786) {
        onHotkey();
    }
    return(false);
}

void MainWindow::onHotkey(void) {
    if((HWND)this->winId() == GetActiveWindow()) {
        // Already active window.
        moveSel(SELMOVE_DWN);
    }
    else {
        showMain();
    }
}

void MainWindow::showMain(void) {
    sizePosMain();
    show();
    setWindowState( (windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
    raise();  // for MacOS
    activateWindow(); // for Windows
    ui->cmdText->clear();
    ui->cmdText->setFocus();
}

// Callback for `EnumWindows` that lists out all window names.
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
    WinItem witem;
    MainWindow *mainwin = (MainWindow*)lParam;
    DWORD pid;

    LPWSTR buff[1024];
    if( (IsWindowVisible(hWnd)) &&
        (IsAltTabWindow(hWnd)) &&
        ((HWND)mainwin->winId() != hWnd) )
    {
        GetWindowText(hWnd, (LPWSTR)buff, sizeof(buff));
        witem.title = QString::fromWCharArray((const LPWSTR)buff);
        witem.handle = hWnd;
        witem.num = mainwin->witems.size() + 1;
        GetWindowThreadProcessId(hWnd, &pid);
        // NOTE: This call is needed to allow access to metadata of the
        // process. If original handle is used to for metadata read attempt, it
        // will likely result in an error.
        HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
        // NOTE: Using `GetProcessImageFileName()` here fixes the 32/64-bit
        // error.
        if(GetProcessImageFileName(handle, (LPWSTR)buff, sizeof(buff))) {
            witem.exec = QString::fromWCharArray((const LPWSTR)buff);
            witem.exec = witem.exec.mid(witem.exec.lastIndexOf("\\") + 1);
        } else {
            witem.exec = QString("NA");
        }
        mainwin->witems.append(witem);
    }
    return TRUE;
}

void MainWindow::windowActivationChange(bool state) {
    if(state) {
        // Lost focus.
        hide();
    } else {
        // In focus.
        updateWinList(true);
        checkSavedWins();
        showMain();
    }
}

BOOL IsAltTabWindow(HWND hwnd)
{
    long wndStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
    if(GetWindowTextLength(hwnd) == 0)
        return false;

    // Ignore desktop window.
    if (hwnd == GetShellWindow())
        return(false);

    if(wndStyle & WS_EX_TOOLWINDOW)
        return(false);

    // Start at the root owner
    HWND hwndWalk = GetAncestor(hwnd, GA_ROOTOWNER);

    // See if we are the last active visible popup
    HWND hwndTry;
    while ((hwndTry = GetLastActivePopup(hwndWalk)) != hwndTry)
    {
        if (IsWindowVisible(hwndTry))
            break;
        hwndWalk = hwndTry;
    }
    return hwndWalk == hwnd;
}

<commit_msg>Will only display on the primary monitor now.<commit_after>/*=============================================================*/
/* SECTION: Includes                                           */
/*=============================================================*/

#define _WIN32_WINNT 0x0600
#include <windows.h>
#include <psapi.h>
#include <QDesktopWidget>

#include <Qt>

#include <QKeyEvent>
#include <QMessageBox>
#include <QShortcut>
#include <QHash>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "cmdformatter.h"

/*=============================================================*/
/* SECTION: Local Data                                         */
/*=============================================================*/

/// Stores saved alias windows.
QHash<HWND, QString> gSavedWins;

/// The application version string.
QString gVerStr("0.5.0-alpha");

/*=============================================================*/
/* SECTION: Local Prototypes                                   */
/*=============================================================*/

static BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam);
static BOOL IsAltTabWindow(HWND hwnd);

/*=============================================================*/
/* SECTION: Function Definitions                               */
/*=============================================================*/

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        proxy(new QSortFilterProxyModel(parent)),
        model(new QStandardItemModel(0, 4, parent))
{
    // Set the window style.
    Qt::WindowFlags flags = windowFlags();
    setWindowFlags(flags | Qt::WindowStaysOnTopHint | Qt::ToolTip);

    // Set up system tray.
    trayIconMenu = new QMenu(this);
    aboutAction = new QAction(tr("&About"), this);
    quitAction = new QAction(tr("&Quit"), this);
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutMain()));
    connect(quitAction, SIGNAL(triggered()), this, SLOT(quitMain()));
    trayIconMenu->addAction(aboutAction);
    trayIconMenu->addAction(quitAction);
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->setToolTip(QString("QuickWin"));
    trayIcon->setIcon(QIcon("icon.png"));
    trayIcon->show();

    // Set up UI items.
    ui->setupUi(this);
    proxy->setSourceModel(model);
    ui->winView->setModel(proxy);
    proxy->setFilterKeyColumn(1);
    ui->winView->setSortingEnabled(true);
    ui->winView->sortByColumn(0, Qt::AscendingOrder);
    ui->winView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    model->setHeaderData(0, Qt::Horizontal, QObject::tr("Number"));
    model->setHeaderData(1, Qt::Horizontal, QObject::tr("Title"));
    model->setHeaderData(2, Qt::Horizontal, QObject::tr("Executable"));
    model->setHeaderData(3, Qt::Horizontal, QObject::tr("Alias"));
    sizePosMain();

    connect(ui->cmdText, SIGNAL(returnPressed()),
            this,SLOT(onTextEnter()));
    connect(ui->cmdText, SIGNAL(textChanged(const QString &)),
            this, SLOT(onTextChanged(const QString &)));
    connect(ui->winView, SIGNAL(activated(QModelIndex)),
            this, SLOT(onWitemActivate(QModelIndex)));

    // Register system-wide hotkey.
    HWND hwnd = (HWND)this->winId();
    RegisterHotKey(hwnd, 100, MOD_CONTROL | MOD_ALT, VK_SPACE);

    updateWinList(true);
}

void MainWindow::sizePosMain(void) {
    // Center window.
    QDesktopWidget *desktop = QApplication::desktop();
    int width = desktop->screenGeometry(desktop->primaryScreen()).width() * 0.6;
    int height = desktop->screenGeometry(desktop->primaryScreen()).height() * 0.6;
    setFixedSize(width, height);
    move(
            (desktop->screenGeometry(desktop->primaryScreen()).width() - width) / 2,
            (desktop->screenGeometry(desktop->primaryScreen()).height() - height) / 2
        );

    ui->winView->header()->resizeSection(0, width * 0.08);
    ui->winView->header()->resizeSection(1, width * 0.7);
}

void MainWindow::aboutMain(void) {
    QMessageBox::about(this,
            "About QuickWin",
            "QuickWin version `" + gVerStr + "`.\nVisit 'github.com/jeffrimko/QuickWin' for more information.");
}

void MainWindow::quitMain(void) {
    exit(0);
}

void MainWindow::updateWinList(bool clear_note) {
    model->removeRows(0, model->rowCount());
    witems.clear();
    EnumWindows(EnumWindowsProc, (LPARAM)this);
    for(int i = 0; i < witems.size(); i++) {
        model->insertRow(i);
        model->setData(model->index(i, 0), QString::number(witems[i].num));
        model->setData(model->index(i, 1), witems[i].title);
        model->setData(model->index(i, 2), witems[i].exec);
        model->setData(model->index(i, 3), gSavedWins[witems[i].handle]);
    }
    ui->winView->setCurrentIndex(proxy->index(0,0));
    if(clear_note) {
        ui->noteText->clear();
        ui->noteText->append("QuickWin " + gVerStr + " found " + QString::number(witems.size()) + " windows.");
    }
}

void MainWindow::checkSavedWins(void) {
    if(gSavedWins.size()) {
        QHashIterator<HWND, QString> i(gSavedWins);
        while (i.hasNext()) {
            i.next();
            bool win_okay = false;
            for(int j = 0; j < witems.size(); j++) {
                if(witems[j].handle == i.key()) {
                    win_okay = true;
                    break;
                }
            }
            if(false == win_okay) {
                gSavedWins.remove(i.key());
            }
        }
    }
}

void MainWindow::onTextChanged(const QString &text) {
    static QString prev_ptrn = "";
    cmds_t cmds;
    QString ptrn = "";
    format_cmds(cmds, text.toStdString());
    if("" != cmds["number"]) {
        proxy->setFilterKeyColumn(0);
        ptrn = QString::fromStdString(cmds["number"]);
    } else if("" != cmds["executable"]) {
        proxy->setFilterKeyColumn(2);
        ptrn = QString::fromStdString(cmds["executable"]);
    } else if(cmds.find("get") != cmds.end()) {
        proxy->setFilterKeyColumn(3);
        if("" != cmds["get"]) {
            ptrn = QString::fromStdString(cmds["get"]);
        } else {
            ptrn = "?";
        }
    } else {
        proxy->setFilterKeyColumn(1);
        ptrn = QString::fromStdString(cmds["title"]);
    }
    if(prev_ptrn != ptrn) {
        proxy->setFilterRegExp(QRegExp(ptrn, Qt::CaseInsensitive, QRegExp::Wildcard));
        ui->winView->setCurrentIndex(proxy->index(0,0));
    }
    prev_ptrn = ptrn;
}

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

void MainWindow::keyPressEvent(QKeyEvent *event) {
    bool hide_win = (event->key() == Qt::Key_Escape);
    bool quit_app = false;

    SelMove mv = SELMOVE_NO;
    if(event->modifiers() && Qt::ControlModifier) {
        switch(event->key()) {
            case Qt::Key_H: mv = SELMOVE_TOP; break;
            case Qt::Key_L: mv = SELMOVE_BTM; break;
            case Qt::Key_K: mv = SELMOVE_UP; break;
            case Qt::Key_J: mv = SELMOVE_DWN; break;
            case Qt::Key_M: mv = SELMOVE_MID; break;
            case Qt::Key_E: mv = SELMOVE_EXE; break;
            case Qt::Key_S: onWitemActivate(ui->winView->currentIndex());
            case Qt::Key_C: hide_win = true; break;
#ifndef QT_NO_DEBUG
            case Qt::Key_X: quit_app = true; break;
#endif
        }
    } else {
        switch(event->key()) {
            case Qt::Key_Home: mv = SELMOVE_TOP; break;
            case Qt::Key_End: mv = SELMOVE_BTM; break;
            case Qt::Key_Up: mv = SELMOVE_UP; break;
            case Qt::Key_Down: mv = SELMOVE_DWN; break;
        }
    }
    moveSel(mv);

    if(hide_win) {
        hide();
    }
    // TODO: Debug only! Remove later...
    if(quit_app) {
        quitMain();
    }
}

void MainWindow::moveSel(SelMove mv) {
    // Handle selection movement.
    int row = ui->winView->currentIndex().row();
    if((SELMOVE_UP == mv) | (SELMOVE_DWN == mv)) {
        if(SELMOVE_UP == mv) {
            if(row == 0) {
                row = proxy->rowCount() - 1;
            } else {
                row -= 1;
            }
        } else {
            row += 1;
            if(row >= proxy->rowCount()) {
                row = 0;
            }
        }
        ui->winView->setCurrentIndex(proxy->index(row,0));
    } else if(SELMOVE_TOP == mv) {
        ui->winView->setCurrentIndex(proxy->index(0,0));
    } else if(SELMOVE_MID == mv) {
        ui->winView->setCurrentIndex(proxy->index(proxy->rowCount()/2,0));
    } else if(SELMOVE_BTM == mv) {
        ui->winView->setCurrentIndex(proxy->index(proxy->rowCount()-1,0));
    } else if(SELMOVE_EXE == mv) {
        QString exec = witems[row].exec;
        int idx = row + 1;
        while(idx != row) {
            if(idx >= witems.size()) {
                idx = 0;
            }
            if(exec == witems[idx].exec) {
                break;
            }
            idx++;
        }
        ui->winView->setCurrentIndex(proxy->index(idx,0));
    }
}

void MainWindow::showWin(HWND handle) {
    if(IsIconic(handle)) {
        ShowWindow(handle, SW_RESTORE);
    }
    SetForegroundWindow(handle);
}

void MainWindow::onWitemActivate(QModelIndex index) {
    if(proxy->rowCount() == 0)
        return;
    showWin(witems[getSelWinNum()].handle);
}

uint MainWindow::getSelWinNum(void) {
    uint row = ui->winView->currentIndex().row();
    uint num = proxy->data(proxy->index(row, 0)).toInt() - 1;
    return(num);
}

void MainWindow::onTextEnter()
{
    bool stay = false;
    cmds_t cmds;
    QString text = ui->cmdText->text();
    format_cmds(cmds, text.toStdString());

    if(cmds.find("help") != cmds.end()) {
        QString help = "Commands: ";
        for(std::string cmd : list_cmd_types()) {
            help += QString::fromStdString(cmd);
            help += " ";
        }
        ui->noteText->append(help);
        stay = true;
    }
    if(cmds.find("delete") != cmds.end()) {
        gSavedWins.clear();
        ui->noteText->append("Aliases deleted.");
        stay = true;
    }
    if(cmds.find("set") != cmds.end()) {
        uint num = getSelWinNum();
        if("" != cmds["set"]) {
            QString name = QString::fromStdString(cmds["set"]);
            gSavedWins[witems[num].handle] = name;
            ui->noteText->append("Set " + QString::number(num+1) + " to alias '" + name + "'.");
        } else {
            gSavedWins.remove(witems[num].handle);
            ui->noteText->append("Removed alias from " + QString::number(num+1) + ".");
        }
        stay = true;
    }

    if(!stay) {
        onWitemActivate(ui->winView->currentIndex());
    } else {
        ui->cmdText->clear();
        updateWinList(false);
    }
}

bool MainWindow::winEvent( MSG * message, long * result )  {
    if(message->message == 786) {
        onHotkey();
    }
    return(false);
}

void MainWindow::onHotkey(void) {
    if((HWND)this->winId() == GetActiveWindow()) {
        // Already active window.
        moveSel(SELMOVE_DWN);
    }
    else {
        showMain();
    }
}

void MainWindow::showMain(void) {
    sizePosMain();
    show();
    setWindowState( (windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
    raise();  // for MacOS
    activateWindow(); // for Windows
    ui->cmdText->clear();
    ui->cmdText->setFocus();
}

// Callback for `EnumWindows` that lists out all window names.
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
    WinItem witem;
    MainWindow *mainwin = (MainWindow*)lParam;
    DWORD pid;

    LPWSTR buff[1024];
    if( (IsWindowVisible(hWnd)) &&
        (IsAltTabWindow(hWnd)) &&
        ((HWND)mainwin->winId() != hWnd) )
    {
        GetWindowText(hWnd, (LPWSTR)buff, sizeof(buff));
        witem.title = QString::fromWCharArray((const LPWSTR)buff);
        witem.handle = hWnd;
        witem.num = mainwin->witems.size() + 1;
        GetWindowThreadProcessId(hWnd, &pid);
        // NOTE: This call is needed to allow access to metadata of the
        // process. If original handle is used to for metadata read attempt, it
        // will likely result in an error.
        HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
        // NOTE: Using `GetProcessImageFileName()` here fixes the 32/64-bit
        // error.
        if(GetProcessImageFileName(handle, (LPWSTR)buff, sizeof(buff))) {
            witem.exec = QString::fromWCharArray((const LPWSTR)buff);
            witem.exec = witem.exec.mid(witem.exec.lastIndexOf("\\") + 1);
        } else {
            witem.exec = QString("NA");
        }
        mainwin->witems.append(witem);
    }
    return TRUE;
}

void MainWindow::windowActivationChange(bool state) {
    if(state) {
        // Lost focus.
        hide();
    } else {
        // In focus.
        updateWinList(true);
        checkSavedWins();
        showMain();
    }
}

BOOL IsAltTabWindow(HWND hwnd)
{
    long wndStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
    if(GetWindowTextLength(hwnd) == 0)
        return false;

    // Ignore desktop window.
    if (hwnd == GetShellWindow())
        return(false);

    if(wndStyle & WS_EX_TOOLWINDOW)
        return(false);

    // Start at the root owner
    HWND hwndWalk = GetAncestor(hwnd, GA_ROOTOWNER);

    // See if we are the last active visible popup
    HWND hwndTry;
    while ((hwndTry = GetLastActivePopup(hwndWalk)) != hwndTry)
    {
        if (IsWindowVisible(hwndTry))
            break;
        hwndWalk = hwndTry;
    }
    return hwndWalk == hwnd;
}

<|endoftext|>