<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: menubarmanager.hxx,v $
 *
 *  $Revision: 1.20 $
 *  last change: $Author: ihi $ $Date: 2007-07-10 15:07:44 $
 *
 *  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 __FRAMEWORK_UIELEMENT_MENUBARMANAGER_HXX_
#define __FRAMEWORK_UIELEMENT_MENUBARMANAGER_HXX_

/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
               with solaris headers ...
*/
#include <vector>

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_FEATURESTATEEVENT_HPP_
#include <com/sun/star/frame/FeatureStateEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_
#include <com/sun/star/frame/XFrameActionListener.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XPOPUPMENUCONTROLLER_HPP_
#include <com/sun/star/frame/XPopupMenuController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_
#include <com/sun/star/frame/XUIControllerRegistration.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONLISTENER_HPP_
#include <com/sun/star/ui/XUIConfigurationListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_
#include <com/sun/star/ui/XImageManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XACCELERATORCONFIGURATION_HPP_
#include <com/sun/star/ui/XAcceleratorConfiguration.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
#ifndef _SV_ACCEL_HXX
#include <vcl/accel.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _TOOLKIT_AWT_VCLXMENU_HXX_
#include <toolkit/awt/vclxmenu.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#include <classes/addonsoptions.hxx>

namespace framework
{

struct PopupControllerEntry
{
    ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XDispatchProvider > m_xDispatchProvider;
};

typedef std::hash_map< rtl::OUString, PopupControllerEntry, OUStringHashCode, ::std::equal_to< rtl::OUString > > PopupControllerCache;

class BmkMenu;
class AddonMenu;
class AddonPopupMenu;
class MenuBarManager : public com::sun::star::frame::XStatusListener                ,
                       public com::sun::star::frame::XFrameActionListener           ,
                       public com::sun::star::ui::XUIConfigurationListener          ,
                       public com::sun::star::lang::XComponent                      ,
                       public com::sun::star::awt::XSystemDependentMenuPeer         ,
                       public ThreadHelpBase                                        ,
                       public ::cppu::OWeakObject
{
    protected:
        // #110897#
        MenuBarManager(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            const ::com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
            AddonMenu*          pAddonMenu,
            sal_Bool            bDelete,
            sal_Bool            bDeleteChildren );

        // #110897#
        MenuBarManager(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            const ::com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
            AddonPopupMenu*     pAddonMenu,
            sal_Bool            bDelete,
            sal_Bool            bDeleteChildren );

    public:
        // #110897#
        MenuBarManager(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& rDispatchProvider,
            const rtl::OUString& aModuleIdentifier,
            Menu* pMenu,
            sal_Bool bDelete,
            sal_Bool bDeleteChildren );

        // #110897#
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& getServiceFactory();

        virtual ~MenuBarManager();

        // XInterface
        virtual void SAL_CALL acquire() throw();
        virtual void SAL_CALL release() throw();
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException );

        // XComponent
        virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

        // XStatusListener
        virtual void SAL_CALL statusChanged( const com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );

        // XFrameActionListener
        virtual void SAL_CALL frameAction( const com::sun::star::frame::FrameActionEvent& Action ) throw ( ::com::sun::star::uno::RuntimeException );

        // XEventListener
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );

        // XUIConfigurationListener
        virtual void SAL_CALL elementInserted( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementRemoved( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementReplaced( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);

        // XSystemDependentMenuPeer
        virtual ::com::sun::star::uno::Any SAL_CALL getMenuHandle( const ::com::sun::star::uno::Sequence< sal_Int8 >& ProcessId, sal_Int16 SystemType ) throw (::com::sun::star::uno::RuntimeException);

        DECL_LINK( Select, Menu * );

        Menu*   GetMenuBar() const { return m_pVCLMenu; }

        // Configuration methods
        static void FillMenuWithConfiguration( USHORT& nId, Menu* pMenu,
                                               const ::rtl::OUString& rModuleIdentifier,
                                               const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rItemContainer,
                                               const ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer >& rTransformer );
        static void FillMenu( USHORT& nId,
                              Menu* pMenu,
                              const ::rtl::OUString& rModuleIdentifier,
                              const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rItemContainer,
                              const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& rDispatchProvider );

        void FillMenuManager( Menu* pMenu,
                              const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                              const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& rDispatchProvider,
                              const rtl::OUString& rModuleIdentifier,
                              sal_Bool bDelete,
                              sal_Bool bDeleteChildren );
        void SetItemContainer( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rItemContainer );
        void GetPopupController( PopupControllerCache& rPopupController );

    protected:
        DECL_LINK( Highlight, Menu * );
        DECL_LINK( Activate, Menu * );
        DECL_LINK( Deactivate, Menu * );
        DECL_LINK( AsyncSettingsHdl, Timer * );

        void RemoveListener();
        void RequestImages();
        void RetrieveImageManagers();
        static sal_Bool MustBeHidden( PopupMenu* pPopupMenu, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer >& rTransformer );

    private:
        String RetrieveLabelFromCommand( const String& aCmdURL );
        void UpdateSpecialFileMenu( Menu* pMenu );
        void UpdateSpecialWindowMenu( Menu* pMenu );
        void Destroy();

        struct MenuItemHandler
        {
            MenuItemHandler( USHORT             aItemId,
                             ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xManager,
                             ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& rDispatch ) :
                             nItemId( aItemId ),
                             bCheckHide( sal_True ),
                             xSubMenuManager( xManager ),
                             xMenuItemDispatch( rDispatch ) {}

            USHORT                                                                                nItemId;
            sal_Bool                                                                                bCheckHide;
            ::rtl::OUString                                                                             aTargetFrame;
            ::rtl::OUString                                                                             aMenuItemURL;
            ::rtl::OUString                                                                             aFilter;
            ::rtl::OUString                                                                             aPassword;
            ::rtl::OUString                                                                             aTitle;
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >                xSubMenuManager;
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >                      xMenuItemDispatch;
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XPopupMenuController >           xPopupMenuController;
            ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu >                       xPopupMenu;
            KeyCode                                                                                aKeyCode;
        };

        void             RetrieveShortcuts( std::vector< MenuItemHandler* >& aMenuShortCuts );
        void             CreatePicklistArguments(
                            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgsList,
                            const MenuItemHandler* );
        void             CheckAndAddMenuExtension( Menu* pMenu );
        static void      impl_RetrieveShortcutsFromConfiguration( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration >& rAccelCfg,
                                                                  const ::com::sun::star::uno::Sequence< rtl::OUString >& rCommands,
                                                                  std::vector< MenuItemHandler* >& aMenuShortCuts );
        static void      MergeAddonMenus( Menu* pMenuBar, const MergeMenuInstructionContainer&, const ::rtl::OUString& aModuleIdentifier );

        MenuItemHandler* GetMenuItemHandler( USHORT nItemId );
        sal_Bool         CreatePopupMenuController( MenuItemHandler* pMenuItemHandler );

        sal_Bool                                                                               m_bDisposed : 1,
                                                                                m_bInitialized : 1,
                                                                                m_bDeleteMenu : 1,
                                                                                m_bDeleteChildren : 1,
                                                                                m_bActive : 1,
                                                                                m_bIsBookmarkMenu : 1,
                                                                                m_bWasHiContrast : 1,
                                                                                m_bShowMenuImages : 1;
        sal_Bool                                                                               m_bModuleIdentified : 1,
                                                                                m_bRetrieveImages : 1,
                                                                                m_bAcceleratorCfg : 1;
        ::rtl::OUString                                                                        m_aMenuItemCommand;
        ::rtl::OUString                                                                        m_aModuleIdentifier;
        Menu*                                                                                m_pVCLMenu;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >                    m_xFrame;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >           m_xUICommandLabels;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XUIControllerRegistration > m_xPopupMenuControllerRegistration;
        ::std::vector< MenuItemHandler* >                                                      m_aMenuItemHandlerVector;
        ::cppu::OMultiTypeInterfaceContainerHelper                                             m_aListenerContainer;   /// container for ALL Listener
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >         m_xDispatchProvider;
        ::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager >                m_xDocImageManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager >                m_xModuleImageManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration >    m_xDocAcceleratorManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration >    m_xModuleAcceleratorManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration >    m_xGlobalAcceleratorManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >       mxServiceFactory;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >          m_xDeferedItemContainer;
        sal_Int16                                                                              m_nSymbolsStyle;
        Timer                                                                                m_aAsyncSettingsTimer;
};

} // namespace

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.20.130); FILE MERGED 2008/04/01 15:18:28 thb 1.20.130.3: #i85898# Stripping all external header guards 2008/04/01 10:57:57 thb 1.20.130.2: #i85898# Stripping all external header guards 2008/03/28 15:34:57 rt 1.20.130.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: menubarmanager.hxx,v $
 * $Revision: 1.21 $
 *
 * 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 __FRAMEWORK_UIELEMENT_MENUBARMANAGER_HXX_
#define __FRAMEWORK_UIELEMENT_MENUBARMANAGER_HXX_

/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
               with solaris headers ...
*/
#include <vector>

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________
#include <threadhelp/threadhelpbase.hxx>
#include <macros/debug.hxx>
#include <stdtypes.h>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/XDispatch.hpp>
#include <com/sun/star/frame/XDispatchProvider.hpp>
#include <com/sun/star/frame/FeatureStateEvent.hpp>
#include <com/sun/star/frame/XFrameActionListener.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/frame/XPopupMenuController.hpp>
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/frame/XUIControllerRegistration.hpp>
#include <com/sun/star/ui/XUIConfigurationListener.hpp>
#include <com/sun/star/ui/XImageManager.hpp>
#include <com/sun/star/ui/XAcceleratorConfiguration.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________
#include <rtl/ustring.hxx>
#include <vcl/menu.hxx>
#include <vcl/accel.hxx>
#include <vcl/timer.hxx>
#include <toolkit/awt/vclxmenu.hxx>
#include <cppuhelper/weak.hxx>
#include <cppuhelper/interfacecontainer.hxx>
#include <classes/addonsoptions.hxx>

namespace framework
{

struct PopupControllerEntry
{
    ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XDispatchProvider > m_xDispatchProvider;
};

typedef std::hash_map< rtl::OUString, PopupControllerEntry, OUStringHashCode, ::std::equal_to< rtl::OUString > > PopupControllerCache;

class BmkMenu;
class AddonMenu;
class AddonPopupMenu;
class MenuBarManager : public com::sun::star::frame::XStatusListener                ,
                       public com::sun::star::frame::XFrameActionListener           ,
                       public com::sun::star::ui::XUIConfigurationListener          ,
                       public com::sun::star::lang::XComponent                      ,
                       public com::sun::star::awt::XSystemDependentMenuPeer         ,
                       public ThreadHelpBase                                        ,
                       public ::cppu::OWeakObject
{
    protected:
        // #110897#
        MenuBarManager(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            const ::com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
            AddonMenu*          pAddonMenu,
            sal_Bool            bDelete,
            sal_Bool            bDeleteChildren );

        // #110897#
        MenuBarManager(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            const ::com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
            AddonPopupMenu*     pAddonMenu,
            sal_Bool            bDelete,
            sal_Bool            bDeleteChildren );

    public:
        // #110897#
        MenuBarManager(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
            const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& rDispatchProvider,
            const rtl::OUString& aModuleIdentifier,
            Menu* pMenu,
            sal_Bool bDelete,
            sal_Bool bDeleteChildren );

        // #110897#
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& getServiceFactory();

        virtual ~MenuBarManager();

        // XInterface
        virtual void SAL_CALL acquire() throw();
        virtual void SAL_CALL release() throw();
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException );

        // XComponent
        virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

        // XStatusListener
        virtual void SAL_CALL statusChanged( const com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );

        // XFrameActionListener
        virtual void SAL_CALL frameAction( const com::sun::star::frame::FrameActionEvent& Action ) throw ( ::com::sun::star::uno::RuntimeException );

        // XEventListener
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );

        // XUIConfigurationListener
        virtual void SAL_CALL elementInserted( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementRemoved( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementReplaced( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);

        // XSystemDependentMenuPeer
        virtual ::com::sun::star::uno::Any SAL_CALL getMenuHandle( const ::com::sun::star::uno::Sequence< sal_Int8 >& ProcessId, sal_Int16 SystemType ) throw (::com::sun::star::uno::RuntimeException);

        DECL_LINK( Select, Menu * );

        Menu*   GetMenuBar() const { return m_pVCLMenu; }

        // Configuration methods
        static void FillMenuWithConfiguration( USHORT& nId, Menu* pMenu,
                                               const ::rtl::OUString& rModuleIdentifier,
                                               const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rItemContainer,
                                               const ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer >& rTransformer );
        static void FillMenu( USHORT& nId,
                              Menu* pMenu,
                              const ::rtl::OUString& rModuleIdentifier,
                              const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rItemContainer,
                              const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& rDispatchProvider );

        void FillMenuManager( Menu* pMenu,
                              const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                              const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& rDispatchProvider,
                              const rtl::OUString& rModuleIdentifier,
                              sal_Bool bDelete,
                              sal_Bool bDeleteChildren );
        void SetItemContainer( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rItemContainer );
        void GetPopupController( PopupControllerCache& rPopupController );

    protected:
        DECL_LINK( Highlight, Menu * );
        DECL_LINK( Activate, Menu * );
        DECL_LINK( Deactivate, Menu * );
        DECL_LINK( AsyncSettingsHdl, Timer * );

        void RemoveListener();
        void RequestImages();
        void RetrieveImageManagers();
        static sal_Bool MustBeHidden( PopupMenu* pPopupMenu, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer >& rTransformer );

    private:
        String RetrieveLabelFromCommand( const String& aCmdURL );
        void UpdateSpecialFileMenu( Menu* pMenu );
        void UpdateSpecialWindowMenu( Menu* pMenu );
        void Destroy();

        struct MenuItemHandler
        {
            MenuItemHandler( USHORT             aItemId,
                             ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xManager,
                             ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& rDispatch ) :
                             nItemId( aItemId ),
                             bCheckHide( sal_True ),
                             xSubMenuManager( xManager ),
                             xMenuItemDispatch( rDispatch ) {}

            USHORT                                                                                nItemId;
            sal_Bool                                                                                bCheckHide;
            ::rtl::OUString                                                                             aTargetFrame;
            ::rtl::OUString                                                                             aMenuItemURL;
            ::rtl::OUString                                                                             aFilter;
            ::rtl::OUString                                                                             aPassword;
            ::rtl::OUString                                                                             aTitle;
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >                xSubMenuManager;
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >                      xMenuItemDispatch;
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XPopupMenuController >           xPopupMenuController;
            ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu >                       xPopupMenu;
            KeyCode                                                                                aKeyCode;
        };

        void             RetrieveShortcuts( std::vector< MenuItemHandler* >& aMenuShortCuts );
        void             CreatePicklistArguments(
                            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgsList,
                            const MenuItemHandler* );
        void             CheckAndAddMenuExtension( Menu* pMenu );
        static void      impl_RetrieveShortcutsFromConfiguration( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration >& rAccelCfg,
                                                                  const ::com::sun::star::uno::Sequence< rtl::OUString >& rCommands,
                                                                  std::vector< MenuItemHandler* >& aMenuShortCuts );
        static void      MergeAddonMenus( Menu* pMenuBar, const MergeMenuInstructionContainer&, const ::rtl::OUString& aModuleIdentifier );

        MenuItemHandler* GetMenuItemHandler( USHORT nItemId );
        sal_Bool         CreatePopupMenuController( MenuItemHandler* pMenuItemHandler );

        sal_Bool                                                                               m_bDisposed : 1,
                                                                                m_bInitialized : 1,
                                                                                m_bDeleteMenu : 1,
                                                                                m_bDeleteChildren : 1,
                                                                                m_bActive : 1,
                                                                                m_bIsBookmarkMenu : 1,
                                                                                m_bWasHiContrast : 1,
                                                                                m_bShowMenuImages : 1;
        sal_Bool                                                                               m_bModuleIdentified : 1,
                                                                                m_bRetrieveImages : 1,
                                                                                m_bAcceleratorCfg : 1;
        ::rtl::OUString                                                                        m_aMenuItemCommand;
        ::rtl::OUString                                                                        m_aModuleIdentifier;
        Menu*                                                                                m_pVCLMenu;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >                    m_xFrame;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >           m_xUICommandLabels;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XUIControllerRegistration > m_xPopupMenuControllerRegistration;
        ::std::vector< MenuItemHandler* >                                                      m_aMenuItemHandlerVector;
        ::cppu::OMultiTypeInterfaceContainerHelper                                             m_aListenerContainer;   /// container for ALL Listener
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >         m_xDispatchProvider;
        ::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager >                m_xDocImageManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager >                m_xModuleImageManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration >    m_xDocAcceleratorManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration >    m_xModuleAcceleratorManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration >    m_xGlobalAcceleratorManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >       mxServiceFactory;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >          m_xDeferedItemContainer;
        sal_Int16                                                                              m_nSymbolsStyle;
        Timer                                                                                m_aAsyncSettingsTimer;
};

} // namespace

#endif
<|endoftext|>


<commit_before>// Displays the contents of a single address book

#include <StdAfx.h>
#include <UI/Dialogs/ContentsTable/ABDlg.h>
#include <UI/Controls/ContentsTableListCtrl.h>
#include <MAPI/Cache/MapiObjects.h>
#include <MAPI/ColumnTags.h>
#include <UI/Dialogs/MFCUtilityFunctions.h>
#include <UI/UIFunctions.h>
#include <UI/Dialogs/Editors/Editor.h>
#include <MAPI/MAPIABFunctions.h>
#include <MAPI/MAPIProgress.h>
#include <MAPI/MAPIFunctions.h>
#include <MAPI/Cache/GlobalCache.h>

namespace dialog
{
	static std::wstring CLASS = L"CAbDlg";

	CAbDlg::CAbDlg(
		_In_ ui::CParentWnd* pParentWnd,
		_In_ cache::CMapiObjects* lpMapiObjects,
		_In_ LPMAPIPROP lpUnk
	) :
		CContentsTableDlg(
			pParentWnd,
			lpMapiObjects,
			IDS_AB,
			mfcmapiDO_NOT_CALL_CREATE_DIALOG,
			nullptr,
			LPSPropTagArray(&columns::sptABCols),
			columns::ABColumns,
			IDR_MENU_AB_VIEW_POPUP,
			MENU_CONTEXT_AB_CONTENTS)
	{
		TRACE_CONSTRUCTOR(CLASS);
		m_lpContainer = mapi::safe_cast<LPMAPICONTAINER>(lpUnk);
		m_lpAbCont = mapi::safe_cast<LPABCONT>(lpUnk);

		m_bIsAB = true;

		CAbDlg::CreateDialogAndMenu(IDR_MENU_AB_VIEW);
	}

	CAbDlg::~CAbDlg()
	{
		TRACE_DESTRUCTOR(CLASS);
	}

	BEGIN_MESSAGE_MAP(CAbDlg, CContentsTableDlg)
		ON_COMMAND(ID_DELETESELECTEDITEM, OnDeleteSelectedItem)
		ON_COMMAND(ID_DISPLAYDETAILS, OnDisplayDetails)
		ON_COMMAND(ID_OPENCONTACT, OnOpenContact)
		ON_COMMAND(ID_OPENMANAGER, OnOpenManager)
		ON_COMMAND(ID_OPENOWNER, OnOpenOwner)
	END_MESSAGE_MAP()

	void CAbDlg::CreateDialogAndMenu(UINT nIDMenuResource)
	{
		output::DebugPrintEx(DBGCreateDialog, CLASS, L"CreateDialogAndMenu", L"id = 0x%X\n", nIDMenuResource);
		CContentsTableDlg::CreateDialogAndMenu(nIDMenuResource);

		ui::UpdateMenuString(
			m_hWnd,
			ID_CREATEPROPERTYSTRINGRESTRICTION,
			IDS_ABRESMENU);
	}

	void CAbDlg::OnInitMenu(_In_ CMenu* pMenu)
	{
		if (pMenu && m_lpContentsTableListCtrl)
		{
			const auto ulStatus = cache::CGlobalCache::getInstance().GetBufferStatus();
			pMenu->EnableMenuItem(ID_PASTE, DIM(ulStatus & BUFFER_ABENTRIES));

			const int iNumSel = m_lpContentsTableListCtrl->GetSelectedCount();
			pMenu->EnableMenuItem(ID_COPY, DIMMSOK(iNumSel));
			pMenu->EnableMenuItem(ID_DELETESELECTEDITEM, DIMMSOK(iNumSel));
			pMenu->EnableMenuItem(ID_DISPLAYDETAILS, DIMMSOK(iNumSel));
			pMenu->EnableMenuItem(ID_OPENCONTACT, DIMMSNOK(iNumSel));
			pMenu->EnableMenuItem(ID_OPENMANAGER, DIMMSOK(iNumSel));
			pMenu->EnableMenuItem(ID_OPENOWNER, DIMMSOK(iNumSel));
		}

		CContentsTableDlg::OnInitMenu(pMenu);
	}

	void CAbDlg::OnDisplayDetails()
	{
		output::DebugPrintEx(DBGGeneric, CLASS, L"OnDisplayDetails", L"displaying Address Book entry details\n");

		auto hRes = S_OK;
		if (!m_lpMapiObjects) return;
		auto lpAddrBook = m_lpMapiObjects->GetAddrBook(false); // do not release
		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		if (lpAddrBook)
		{
			LPENTRYLIST lpEIDs = nullptr;
			EC_H(m_lpContentsTableListCtrl->GetSelectedItemEIDs(&lpEIDs));

			if (lpEIDs && lpEIDs->cValues && lpEIDs->lpbin)
			{

				for (ULONG i = 0; i < lpEIDs->cValues; i++)
				{
					auto ulUIParam = reinterpret_cast<ULONG_PTR>(static_cast<void*>(m_hWnd));

					// Have to pass DIALOG_MODAL according to
					// http://support.microsoft.com/kb/171637
					EC_H_CANCEL(lpAddrBook->Details(
						&ulUIParam,
						NULL,
						NULL,
						lpEIDs->lpbin[i].cb,
						reinterpret_cast<LPENTRYID>(lpEIDs->lpbin[i].lpb),
						NULL,
						NULL,
						NULL,
						DIALOG_MODAL)); // API doesn't like Unicode
					if (lpEIDs->cValues > i + 1 && bShouldCancel(this, hRes)) break;
					hRes = S_OK;
				}
			}

			MAPIFreeBuffer(lpEIDs);
		}
	}

	void CAbDlg::OnOpenContact()
	{
		auto hRes = S_OK;
		LPENTRYLIST lpEntryList = nullptr;
		LPMAPIPROP lpProp = nullptr;

		if (!m_lpMapiObjects || !m_lpContentsTableListCtrl || !m_lpPropDisplay) return;
		const auto lpSession = m_lpMapiObjects->GetSession(); // do not release
		if (!lpSession) return;

		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		EC_H(m_lpContentsTableListCtrl->GetSelectedItemEIDs(&lpEntryList));

		if (SUCCEEDED(hRes) && lpEntryList && 1 == lpEntryList->cValues)
		{
			ULONG cb = 0;
			LPBYTE lpb = nullptr;
			if (mapi::UnwrapContactEntryID(lpEntryList->lpbin[0].cb, lpEntryList->lpbin[0].lpb, &cb, &lpb))
			{
				EC_H(mapi::CallOpenEntry(
					NULL,
					NULL,
					NULL,
					lpSession,
					cb,
					reinterpret_cast<LPENTRYID>(lpb),
					NULL,
					NULL,
					NULL,
					reinterpret_cast<LPUNKNOWN*>(&lpProp)));
			}
		}

		if (lpProp)
		{
			EC_H(DisplayObject(lpProp, NULL, otDefault, this));
			if (lpProp) lpProp->Release();
		}

		MAPIFreeBuffer(lpEntryList);
	}

	void CAbDlg::OnOpenManager()
	{
		LPMAILUSER lpMailUser = nullptr;
		auto iItem = -1;
		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		if (!m_lpContentsTableListCtrl) return;

		do
		{
			auto hRes = S_OK;
			if (lpMailUser) lpMailUser->Release();
			lpMailUser = nullptr;
			EC_H(m_lpContentsTableListCtrl->OpenNextSelectedItemProp(
				&iItem,
				mfcmapiREQUEST_MODIFY,
				reinterpret_cast<LPMAPIPROP*>(&lpMailUser)));

			if (lpMailUser)
			{
				EC_H(DisplayTable(
					lpMailUser,
					PR_EMS_AB_MANAGER_O,
					otDefault, // oType,
					this));
			}
		} while (iItem != -1);

		if (lpMailUser) lpMailUser->Release();
	}

	void CAbDlg::OnOpenOwner()
	{
		LPMAILUSER lpMailUser = nullptr;
		auto iItem = -1;
		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		if (!m_lpContentsTableListCtrl) return;

		do
		{
			auto hRes = S_OK;
			if (lpMailUser) lpMailUser->Release();
			lpMailUser = nullptr;
			EC_H(m_lpContentsTableListCtrl->OpenNextSelectedItemProp(
				&iItem,
				mfcmapiREQUEST_MODIFY,
				reinterpret_cast<LPMAPIPROP*>(&lpMailUser)));

			if (lpMailUser)
			{
				EC_H(DisplayTable(
					lpMailUser,
					PR_EMS_AB_OWNER_O,
					otDefault, // oType,
					this));
			}
		} while (iItem != -1);

		if (lpMailUser) lpMailUser->Release();
	}

	void CAbDlg::OnDeleteSelectedItem()
	{
		if (!m_lpAbCont) return;

		auto hRes = S_OK;
		editor::CEditor Query(
			this,
			IDS_DELETEABENTRY,
			IDS_DELETEABENTRYPROMPT,
			CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);
		WC_H(Query.DisplayDialog());
		if (S_OK == hRes)
		{
			output::DebugPrintEx(DBGGeneric, CLASS, L"OnDeleteSelectedItem", L"deleting address Book entries\n");
			CWaitCursor Wait; // Change the mouse to an hourglass while we work.
			LPENTRYLIST lpEIDs = nullptr;

			EC_H(m_lpContentsTableListCtrl->GetSelectedItemEIDs(&lpEIDs));

			EC_MAPI(m_lpAbCont->DeleteEntries(lpEIDs, NULL));

			MAPIFreeBuffer(lpEIDs);
		}
	}

	void CAbDlg::HandleCopy()
	{
		auto hRes = S_OK;
		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		output::DebugPrintEx(DBGGeneric, CLASS, L"HandleCopy", L"\n");
		if (!m_lpContentsTableListCtrl) return;

		LPENTRYLIST lpEIDs = nullptr;

		EC_H(m_lpContentsTableListCtrl->GetSelectedItemEIDs(&lpEIDs));

		// CGlobalCache takes over ownership of lpEIDs - don't free now
		cache::CGlobalCache::getInstance().SetABEntriesToCopy(lpEIDs);
	}

	_Check_return_ bool CAbDlg::HandlePaste()
	{
		if (CBaseDialog::HandlePaste()) return true;

		auto hRes = S_OK;
		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		output::DebugPrintEx(DBGGeneric, CLASS, L"HandlePaste", L"pasting address Book entries\n");
		if (!m_lpAbCont) return false;

		const auto lpEIDs = cache::CGlobalCache::getInstance().GetABEntriesToCopy();

		if (lpEIDs)
		{
			editor::CEditor MyData(
				this,
				IDS_CALLCOPYENTRIES,
				IDS_CALLCOPYENTRIESPROMPT,
				CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);

			MyData.InitPane(0, viewpane::TextPane::CreateSingleLinePane(IDS_FLAGS, false));
			MyData.SetHex(0, CREATE_CHECK_DUP_STRICT);

			WC_H(MyData.DisplayDialog());
			if (S_OK == hRes)
			{
				LPMAPIPROGRESS lpProgress = mapi::mapiui::GetMAPIProgress(L"IABContainer::CopyEntries", m_hWnd); // STRING_OK

				EC_MAPI(m_lpAbCont->CopyEntries(
					lpEIDs,
					lpProgress ? reinterpret_cast<ULONG_PTR>(m_hWnd) : NULL,
					lpProgress,
					MyData.GetHex(0)));

				if (lpProgress)
					lpProgress->Release();
			}

			return true; // handled pasted
		}

		return false; // did not handle paste
	}

	void CAbDlg::OnCreatePropertyStringRestriction()
	{
		auto hRes = S_OK;
		LPSRestriction lpRes = nullptr;

		if (!m_lpContentsTableListCtrl) return;

		editor::CEditor MyData(
			this,
			IDS_SEARCHCRITERIA,
			IDS_ABSEARCHCRITERIAPROMPT,
			CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);

		MyData.InitPane(0, viewpane::TextPane::CreateSingleLinePane(IDS_NAME, false));

		WC_H(MyData.DisplayDialog());
		if (S_OK != hRes) return;

		// Allocate and create our SRestriction
		EC_H(mapi::ab::CreateANRRestriction(
			PR_ANR_W,
			MyData.GetStringW(0),
			NULL,
			&lpRes));

		m_lpContentsTableListCtrl->SetRestriction(lpRes);

		SetRestrictionType(mfcmapiNORMAL_RESTRICTION);

		if (FAILED(hRes)) MAPIFreeBuffer(lpRes);
	}

	void CAbDlg::HandleAddInMenuSingle(
		_In_ LPADDINMENUPARAMS lpParams,
		_In_ LPMAPIPROP lpMAPIProp,
		_In_ LPMAPICONTAINER /*lpContainer*/)
	{
		if (lpParams)
		{
			lpParams->lpAbCont = m_lpAbCont;
			lpParams->lpMailUser = mapi::safe_cast<LPMAILUSER>(lpMAPIProp);
		}

		addin::InvokeAddInMenu(lpParams);

		if (lpParams && lpParams->lpMailUser)
		{
			lpParams->lpMailUser->Release();
			lpParams->lpMailUser = nullptr;
		}
	}
}<commit_msg>Missing release<commit_after>// Displays the contents of a single address book

#include <StdAfx.h>
#include <UI/Dialogs/ContentsTable/ABDlg.h>
#include <UI/Controls/ContentsTableListCtrl.h>
#include <MAPI/Cache/MapiObjects.h>
#include <MAPI/ColumnTags.h>
#include <UI/Dialogs/MFCUtilityFunctions.h>
#include <UI/UIFunctions.h>
#include <UI/Dialogs/Editors/Editor.h>
#include <MAPI/MAPIABFunctions.h>
#include <MAPI/MAPIProgress.h>
#include <MAPI/MAPIFunctions.h>
#include <MAPI/Cache/GlobalCache.h>

namespace dialog
{
	static std::wstring CLASS = L"CAbDlg";

	CAbDlg::CAbDlg(
		_In_ ui::CParentWnd* pParentWnd,
		_In_ cache::CMapiObjects* lpMapiObjects,
		_In_ LPMAPIPROP lpUnk
	) :
		CContentsTableDlg(
			pParentWnd,
			lpMapiObjects,
			IDS_AB,
			mfcmapiDO_NOT_CALL_CREATE_DIALOG,
			nullptr,
			LPSPropTagArray(&columns::sptABCols),
			columns::ABColumns,
			IDR_MENU_AB_VIEW_POPUP,
			MENU_CONTEXT_AB_CONTENTS)
	{
		TRACE_CONSTRUCTOR(CLASS);
		m_lpContainer = mapi::safe_cast<LPMAPICONTAINER>(lpUnk);
		m_lpAbCont = mapi::safe_cast<LPABCONT>(lpUnk);

		m_bIsAB = true;

		CAbDlg::CreateDialogAndMenu(IDR_MENU_AB_VIEW);
	}

	CAbDlg::~CAbDlg()
	{
		TRACE_DESTRUCTOR(CLASS);
		if (m_lpAbCont) m_lpAbCont->Release();
	}

	BEGIN_MESSAGE_MAP(CAbDlg, CContentsTableDlg)
		ON_COMMAND(ID_DELETESELECTEDITEM, OnDeleteSelectedItem)
		ON_COMMAND(ID_DISPLAYDETAILS, OnDisplayDetails)
		ON_COMMAND(ID_OPENCONTACT, OnOpenContact)
		ON_COMMAND(ID_OPENMANAGER, OnOpenManager)
		ON_COMMAND(ID_OPENOWNER, OnOpenOwner)
	END_MESSAGE_MAP()

	void CAbDlg::CreateDialogAndMenu(UINT nIDMenuResource)
	{
		output::DebugPrintEx(DBGCreateDialog, CLASS, L"CreateDialogAndMenu", L"id = 0x%X\n", nIDMenuResource);
		CContentsTableDlg::CreateDialogAndMenu(nIDMenuResource);

		ui::UpdateMenuString(
			m_hWnd,
			ID_CREATEPROPERTYSTRINGRESTRICTION,
			IDS_ABRESMENU);
	}

	void CAbDlg::OnInitMenu(_In_ CMenu* pMenu)
	{
		if (pMenu && m_lpContentsTableListCtrl)
		{
			const auto ulStatus = cache::CGlobalCache::getInstance().GetBufferStatus();
			pMenu->EnableMenuItem(ID_PASTE, DIM(ulStatus & BUFFER_ABENTRIES));

			const int iNumSel = m_lpContentsTableListCtrl->GetSelectedCount();
			pMenu->EnableMenuItem(ID_COPY, DIMMSOK(iNumSel));
			pMenu->EnableMenuItem(ID_DELETESELECTEDITEM, DIMMSOK(iNumSel));
			pMenu->EnableMenuItem(ID_DISPLAYDETAILS, DIMMSOK(iNumSel));
			pMenu->EnableMenuItem(ID_OPENCONTACT, DIMMSNOK(iNumSel));
			pMenu->EnableMenuItem(ID_OPENMANAGER, DIMMSOK(iNumSel));
			pMenu->EnableMenuItem(ID_OPENOWNER, DIMMSOK(iNumSel));
		}

		CContentsTableDlg::OnInitMenu(pMenu);
	}

	void CAbDlg::OnDisplayDetails()
	{
		output::DebugPrintEx(DBGGeneric, CLASS, L"OnDisplayDetails", L"displaying Address Book entry details\n");

		auto hRes = S_OK;
		if (!m_lpMapiObjects) return;
		auto lpAddrBook = m_lpMapiObjects->GetAddrBook(false); // do not release
		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		if (lpAddrBook)
		{
			LPENTRYLIST lpEIDs = nullptr;
			EC_H(m_lpContentsTableListCtrl->GetSelectedItemEIDs(&lpEIDs));

			if (lpEIDs && lpEIDs->cValues && lpEIDs->lpbin)
			{

				for (ULONG i = 0; i < lpEIDs->cValues; i++)
				{
					auto ulUIParam = reinterpret_cast<ULONG_PTR>(static_cast<void*>(m_hWnd));

					// Have to pass DIALOG_MODAL according to
					// http://support.microsoft.com/kb/171637
					EC_H_CANCEL(lpAddrBook->Details(
						&ulUIParam,
						NULL,
						NULL,
						lpEIDs->lpbin[i].cb,
						reinterpret_cast<LPENTRYID>(lpEIDs->lpbin[i].lpb),
						NULL,
						NULL,
						NULL,
						DIALOG_MODAL)); // API doesn't like Unicode
					if (lpEIDs->cValues > i + 1 && bShouldCancel(this, hRes)) break;
					hRes = S_OK;
				}
			}

			MAPIFreeBuffer(lpEIDs);
		}
	}

	void CAbDlg::OnOpenContact()
	{
		auto hRes = S_OK;
		LPENTRYLIST lpEntryList = nullptr;
		LPMAPIPROP lpProp = nullptr;

		if (!m_lpMapiObjects || !m_lpContentsTableListCtrl || !m_lpPropDisplay) return;
		const auto lpSession = m_lpMapiObjects->GetSession(); // do not release
		if (!lpSession) return;

		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		EC_H(m_lpContentsTableListCtrl->GetSelectedItemEIDs(&lpEntryList));

		if (SUCCEEDED(hRes) && lpEntryList && 1 == lpEntryList->cValues)
		{
			ULONG cb = 0;
			LPBYTE lpb = nullptr;
			if (mapi::UnwrapContactEntryID(lpEntryList->lpbin[0].cb, lpEntryList->lpbin[0].lpb, &cb, &lpb))
			{
				EC_H(mapi::CallOpenEntry(
					NULL,
					NULL,
					NULL,
					lpSession,
					cb,
					reinterpret_cast<LPENTRYID>(lpb),
					NULL,
					NULL,
					NULL,
					reinterpret_cast<LPUNKNOWN*>(&lpProp)));
			}
		}

		if (lpProp)
		{
			EC_H(DisplayObject(lpProp, NULL, otDefault, this));
			if (lpProp) lpProp->Release();
		}

		MAPIFreeBuffer(lpEntryList);
	}

	void CAbDlg::OnOpenManager()
	{
		LPMAILUSER lpMailUser = nullptr;
		auto iItem = -1;
		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		if (!m_lpContentsTableListCtrl) return;

		do
		{
			auto hRes = S_OK;
			if (lpMailUser) lpMailUser->Release();
			lpMailUser = nullptr;
			EC_H(m_lpContentsTableListCtrl->OpenNextSelectedItemProp(
				&iItem,
				mfcmapiREQUEST_MODIFY,
				reinterpret_cast<LPMAPIPROP*>(&lpMailUser)));

			if (lpMailUser)
			{
				EC_H(DisplayTable(
					lpMailUser,
					PR_EMS_AB_MANAGER_O,
					otDefault, // oType,
					this));
			}
		} while (iItem != -1);

		if (lpMailUser) lpMailUser->Release();
	}

	void CAbDlg::OnOpenOwner()
	{
		LPMAILUSER lpMailUser = nullptr;
		auto iItem = -1;
		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		if (!m_lpContentsTableListCtrl) return;

		do
		{
			auto hRes = S_OK;
			if (lpMailUser) lpMailUser->Release();
			lpMailUser = nullptr;
			EC_H(m_lpContentsTableListCtrl->OpenNextSelectedItemProp(
				&iItem,
				mfcmapiREQUEST_MODIFY,
				reinterpret_cast<LPMAPIPROP*>(&lpMailUser)));

			if (lpMailUser)
			{
				EC_H(DisplayTable(
					lpMailUser,
					PR_EMS_AB_OWNER_O,
					otDefault, // oType,
					this));
			}
		} while (iItem != -1);

		if (lpMailUser) lpMailUser->Release();
	}

	void CAbDlg::OnDeleteSelectedItem()
	{
		if (!m_lpAbCont) return;

		auto hRes = S_OK;
		editor::CEditor Query(
			this,
			IDS_DELETEABENTRY,
			IDS_DELETEABENTRYPROMPT,
			CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);
		WC_H(Query.DisplayDialog());
		if (S_OK == hRes)
		{
			output::DebugPrintEx(DBGGeneric, CLASS, L"OnDeleteSelectedItem", L"deleting address Book entries\n");
			CWaitCursor Wait; // Change the mouse to an hourglass while we work.
			LPENTRYLIST lpEIDs = nullptr;

			EC_H(m_lpContentsTableListCtrl->GetSelectedItemEIDs(&lpEIDs));

			EC_MAPI(m_lpAbCont->DeleteEntries(lpEIDs, NULL));

			MAPIFreeBuffer(lpEIDs);
		}
	}

	void CAbDlg::HandleCopy()
	{
		auto hRes = S_OK;
		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		output::DebugPrintEx(DBGGeneric, CLASS, L"HandleCopy", L"\n");
		if (!m_lpContentsTableListCtrl) return;

		LPENTRYLIST lpEIDs = nullptr;

		EC_H(m_lpContentsTableListCtrl->GetSelectedItemEIDs(&lpEIDs));

		// CGlobalCache takes over ownership of lpEIDs - don't free now
		cache::CGlobalCache::getInstance().SetABEntriesToCopy(lpEIDs);
	}

	_Check_return_ bool CAbDlg::HandlePaste()
	{
		if (CBaseDialog::HandlePaste()) return true;

		auto hRes = S_OK;
		CWaitCursor Wait; // Change the mouse to an hourglass while we work.

		output::DebugPrintEx(DBGGeneric, CLASS, L"HandlePaste", L"pasting address Book entries\n");
		if (!m_lpAbCont) return false;

		const auto lpEIDs = cache::CGlobalCache::getInstance().GetABEntriesToCopy();

		if (lpEIDs)
		{
			editor::CEditor MyData(
				this,
				IDS_CALLCOPYENTRIES,
				IDS_CALLCOPYENTRIESPROMPT,
				CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);

			MyData.InitPane(0, viewpane::TextPane::CreateSingleLinePane(IDS_FLAGS, false));
			MyData.SetHex(0, CREATE_CHECK_DUP_STRICT);

			WC_H(MyData.DisplayDialog());
			if (S_OK == hRes)
			{
				LPMAPIPROGRESS lpProgress = mapi::mapiui::GetMAPIProgress(L"IABContainer::CopyEntries", m_hWnd); // STRING_OK

				EC_MAPI(m_lpAbCont->CopyEntries(
					lpEIDs,
					lpProgress ? reinterpret_cast<ULONG_PTR>(m_hWnd) : NULL,
					lpProgress,
					MyData.GetHex(0)));

				if (lpProgress)
					lpProgress->Release();
			}

			return true; // handled pasted
		}

		return false; // did not handle paste
	}

	void CAbDlg::OnCreatePropertyStringRestriction()
	{
		auto hRes = S_OK;
		LPSRestriction lpRes = nullptr;

		if (!m_lpContentsTableListCtrl) return;

		editor::CEditor MyData(
			this,
			IDS_SEARCHCRITERIA,
			IDS_ABSEARCHCRITERIAPROMPT,
			CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);

		MyData.InitPane(0, viewpane::TextPane::CreateSingleLinePane(IDS_NAME, false));

		WC_H(MyData.DisplayDialog());
		if (S_OK != hRes) return;

		// Allocate and create our SRestriction
		EC_H(mapi::ab::CreateANRRestriction(
			PR_ANR_W,
			MyData.GetStringW(0),
			NULL,
			&lpRes));

		m_lpContentsTableListCtrl->SetRestriction(lpRes);

		SetRestrictionType(mfcmapiNORMAL_RESTRICTION);

		if (FAILED(hRes)) MAPIFreeBuffer(lpRes);
	}

	void CAbDlg::HandleAddInMenuSingle(
		_In_ LPADDINMENUPARAMS lpParams,
		_In_ LPMAPIPROP lpMAPIProp,
		_In_ LPMAPICONTAINER /*lpContainer*/)
	{
		if (lpParams)
		{
			lpParams->lpAbCont = m_lpAbCont;
			lpParams->lpMailUser = mapi::safe_cast<LPMAILUSER>(lpMAPIProp);
		}

		addin::InvokeAddInMenu(lpParams);

		if (lpParams && lpParams->lpMailUser)
		{
			lpParams->lpMailUser->Release();
			lpParams->lpMailUser = nullptr;
		}
	}
}<|endoftext|>


<commit_before>#include <cstring>
#include <sstream>
#include "VolumeTools.h"

UINTVECTOR2 VolumeTools::Fit1DIndexTo2DArray(uint64_t iMax1DIndex,
                                             uint32_t iMax2DArraySize) {
  // check if 1D index exceeds given 2D array
  if (iMax1DIndex > uint64_t(iMax2DArraySize) * uint64_t(iMax2DArraySize)) {
    std::stringstream ss;
    ss << "element count of " << iMax1DIndex << " exceeds the addressable indices "
       << "of a " << iMax2DArraySize << "x" << iMax2DArraySize << " array";
    throw std::runtime_error(ss.str().c_str());
  }

  // 1D index fits into a row
  if (iMax1DIndex <= uint64_t(iMax2DArraySize))
    return UINTVECTOR2(iMax1DIndex, 1);

  // fit 1D index into the smallest possible square
  UINTVECTOR2 v2DArraySize;
  v2DArraySize.x = uint32_t(std::ceil(std::sqrt(double(iMax1DIndex))));
  v2DArraySize.y = uint32_t(std::ceil(double(iMax1DIndex)/double(v2DArraySize.x)));

  return v2DArraySize;
}

/*
 RemoveBoundary:

 This function takes a brick in 3D format and removes iRemove
 voxels in each dimension. The function changes the given
 brick in-place.
 */
void VolumeTools::RemoveBoundary(uint8_t *pBrickData,
                                 const UINT64VECTOR3& vBrickSize,
                                 size_t iVoxelSize, uint32_t iRemove) {
  const UINT64VECTOR3 vTargetBrickSize = vBrickSize-iRemove*2;

  for (uint32_t z = 0;z<vBrickSize.z-2*iRemove;++z) {
    for (uint32_t y = 0;y<vBrickSize.y-2*iRemove;++y) {
      // below is just the usual 3D to 1D conversion where
      // we skip iRemove elements in each input dimension
      // for the output we simply use the smaller size
      size_t inOffset = size_t(iVoxelSize * ( iRemove +
                                     (y+iRemove) * vBrickSize.x +
                                     (z+iRemove) * vBrickSize.x*vBrickSize.y));
      size_t outOffset = size_t(iVoxelSize * (y*vTargetBrickSize.x +
                                       z*vTargetBrickSize.x*vTargetBrickSize.y));
      memcpy(pBrickData+outOffset, pBrickData+inOffset,
             size_t(iVoxelSize*vTargetBrickSize.x));
    }
  }
}

void VolumeTools::Atalasify(size_t iSizeInBytes,
                             const UINT64VECTOR3& vMaxBrickSize,
                             const UINT64VECTOR3& vCurrBrickSize,
                             const UINTVECTOR2& atlasSize,
                             uint8_t* pDataSource,
                             uint8_t* pDataTarget) {

  // can't do in-place conversion
  if (pDataSource == pDataTarget) {
    uint8_t* temp = new uint8_t[iSizeInBytes];
    memcpy(temp, pDataTarget, iSizeInBytes);
    Atalasify(iSizeInBytes, vMaxBrickSize,
               vCurrBrickSize, atlasSize, temp, pDataTarget);
    delete [] temp;
    return;
  }

  // do the actual atlasify
  const size_t iSizePerElement = size_t(iSizeInBytes/vCurrBrickSize.volume());
  const unsigned int iTilesPerRow = (unsigned int)(atlasSize.x / vMaxBrickSize.x);
  uint8_t* pDataSourceIter = pDataSource;
  for (unsigned int z = 0;z<vCurrBrickSize.z;++z) {
    const unsigned int iTileX = z % iTilesPerRow;
    const unsigned int iTileY = z / iTilesPerRow;
    for (unsigned int y = 0;y<vCurrBrickSize.y;++y) {
      memcpy(pDataTarget+(iSizePerElement*(iTileX*vMaxBrickSize.x+(iTileY*vMaxBrickSize.y+y)*atlasSize.x)),
             pDataSourceIter,
             size_t(vCurrBrickSize.x*iSizePerElement));
      pDataSourceIter += vCurrBrickSize.x*iSizePerElement;
    }
  }

}

void VolumeTools::DeAtalasify(size_t iSizeInBytes,
                               const UINTVECTOR2& vCurrentAtlasSize,
                               const UINT64VECTOR3& vMaxBrickSize,
                               const UINT64VECTOR3& vCurrBrickSize,
                               uint8_t* pDataSource,
                               uint8_t* pDataTarget) {

  // can't do in-place conversion
  if (pDataSource == pDataTarget) {
    uint8_t* temp = new uint8_t[iSizeInBytes];
    memcpy(temp, pDataTarget, iSizeInBytes);
    DeAtalasify(iSizeInBytes, vCurrentAtlasSize, vMaxBrickSize,
                 vCurrBrickSize, temp, pDataTarget);
    delete [] temp;
    return;
  }

  // do the actual de-atlasify
  const size_t iSizePerElement = size_t(iSizeInBytes/vCurrBrickSize.volume());
  const unsigned int iTilesPerRow = (unsigned int)(vCurrentAtlasSize.x /
                                                   vMaxBrickSize.x);
  uint8_t* pDataTargetIter = pDataTarget;
  for (unsigned int z = 0;z<vCurrBrickSize.z;++z) {
    const unsigned int iTileX = z % iTilesPerRow;
    const unsigned int iTileY = z / iTilesPerRow;
    for (unsigned int y = 0;y<vCurrBrickSize.y;++y) {
      memcpy(pDataTargetIter,
             pDataSource+(iSizePerElement*(iTileX*vMaxBrickSize.x+(iTileY*vMaxBrickSize.y+y)*vCurrentAtlasSize.x)),
             size_t(vCurrBrickSize.x*iSizePerElement));
      pDataTargetIter += vCurrBrickSize.x*iSizePerElement;
    }
  }
}

/*
 The MIT License

 Copyright (c) 2011 Interactive Visualization and Data Analysis Group

 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
 to deal in the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included
 in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 DEALINGS IN THE SOFTWARE.
 */

<commit_msg>forgot stdexcept include<commit_after>#include <cstring>
#include <sstream>
#include <stdexcept>
#include "VolumeTools.h"

UINTVECTOR2 VolumeTools::Fit1DIndexTo2DArray(uint64_t iMax1DIndex,
                                             uint32_t iMax2DArraySize) {
  // check if 1D index exceeds given 2D array
  if (iMax1DIndex > uint64_t(iMax2DArraySize) * uint64_t(iMax2DArraySize)) {
    std::stringstream ss;
    ss << "element count of " << iMax1DIndex << " exceeds the addressable indices "
       << "of a " << iMax2DArraySize << "x" << iMax2DArraySize << " array";
    throw std::runtime_error(ss.str().c_str());
  }

  // 1D index fits into a row
  if (iMax1DIndex <= uint64_t(iMax2DArraySize))
    return UINTVECTOR2(iMax1DIndex, 1);

  // fit 1D index into the smallest possible square
  UINTVECTOR2 v2DArraySize;
  v2DArraySize.x = uint32_t(std::ceil(std::sqrt(double(iMax1DIndex))));
  v2DArraySize.y = uint32_t(std::ceil(double(iMax1DIndex)/double(v2DArraySize.x)));

  return v2DArraySize;
}

/*
 RemoveBoundary:

 This function takes a brick in 3D format and removes iRemove
 voxels in each dimension. The function changes the given
 brick in-place.
 */
void VolumeTools::RemoveBoundary(uint8_t *pBrickData,
                                 const UINT64VECTOR3& vBrickSize,
                                 size_t iVoxelSize, uint32_t iRemove) {
  const UINT64VECTOR3 vTargetBrickSize = vBrickSize-iRemove*2;

  for (uint32_t z = 0;z<vBrickSize.z-2*iRemove;++z) {
    for (uint32_t y = 0;y<vBrickSize.y-2*iRemove;++y) {
      // below is just the usual 3D to 1D conversion where
      // we skip iRemove elements in each input dimension
      // for the output we simply use the smaller size
      size_t inOffset = size_t(iVoxelSize * ( iRemove +
                                     (y+iRemove) * vBrickSize.x +
                                     (z+iRemove) * vBrickSize.x*vBrickSize.y));
      size_t outOffset = size_t(iVoxelSize * (y*vTargetBrickSize.x +
                                       z*vTargetBrickSize.x*vTargetBrickSize.y));
      memcpy(pBrickData+outOffset, pBrickData+inOffset,
             size_t(iVoxelSize*vTargetBrickSize.x));
    }
  }
}

void VolumeTools::Atalasify(size_t iSizeInBytes,
                             const UINT64VECTOR3& vMaxBrickSize,
                             const UINT64VECTOR3& vCurrBrickSize,
                             const UINTVECTOR2& atlasSize,
                             uint8_t* pDataSource,
                             uint8_t* pDataTarget) {

  // can't do in-place conversion
  if (pDataSource == pDataTarget) {
    uint8_t* temp = new uint8_t[iSizeInBytes];
    memcpy(temp, pDataTarget, iSizeInBytes);
    Atalasify(iSizeInBytes, vMaxBrickSize,
               vCurrBrickSize, atlasSize, temp, pDataTarget);
    delete [] temp;
    return;
  }

  // do the actual atlasify
  const size_t iSizePerElement = size_t(iSizeInBytes/vCurrBrickSize.volume());
  const unsigned int iTilesPerRow = (unsigned int)(atlasSize.x / vMaxBrickSize.x);
  uint8_t* pDataSourceIter = pDataSource;
  for (unsigned int z = 0;z<vCurrBrickSize.z;++z) {
    const unsigned int iTileX = z % iTilesPerRow;
    const unsigned int iTileY = z / iTilesPerRow;
    for (unsigned int y = 0;y<vCurrBrickSize.y;++y) {
      memcpy(pDataTarget+(iSizePerElement*(iTileX*vMaxBrickSize.x+(iTileY*vMaxBrickSize.y+y)*atlasSize.x)),
             pDataSourceIter,
             size_t(vCurrBrickSize.x*iSizePerElement));
      pDataSourceIter += vCurrBrickSize.x*iSizePerElement;
    }
  }

}

void VolumeTools::DeAtalasify(size_t iSizeInBytes,
                               const UINTVECTOR2& vCurrentAtlasSize,
                               const UINT64VECTOR3& vMaxBrickSize,
                               const UINT64VECTOR3& vCurrBrickSize,
                               uint8_t* pDataSource,
                               uint8_t* pDataTarget) {

  // can't do in-place conversion
  if (pDataSource == pDataTarget) {
    uint8_t* temp = new uint8_t[iSizeInBytes];
    memcpy(temp, pDataTarget, iSizeInBytes);
    DeAtalasify(iSizeInBytes, vCurrentAtlasSize, vMaxBrickSize,
                 vCurrBrickSize, temp, pDataTarget);
    delete [] temp;
    return;
  }

  // do the actual de-atlasify
  const size_t iSizePerElement = size_t(iSizeInBytes/vCurrBrickSize.volume());
  const unsigned int iTilesPerRow = (unsigned int)(vCurrentAtlasSize.x /
                                                   vMaxBrickSize.x);
  uint8_t* pDataTargetIter = pDataTarget;
  for (unsigned int z = 0;z<vCurrBrickSize.z;++z) {
    const unsigned int iTileX = z % iTilesPerRow;
    const unsigned int iTileY = z / iTilesPerRow;
    for (unsigned int y = 0;y<vCurrBrickSize.y;++y) {
      memcpy(pDataTargetIter,
             pDataSource+(iSizePerElement*(iTileX*vMaxBrickSize.x+(iTileY*vMaxBrickSize.y+y)*vCurrentAtlasSize.x)),
             size_t(vCurrBrickSize.x*iSizePerElement));
      pDataTargetIter += vCurrBrickSize.x*iSizePerElement;
    }
  }
}

/*
 The MIT License

 Copyright (c) 2011 Interactive Visualization and Data Analysis Group

 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
 to deal in the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included
 in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 DEALINGS IN THE SOFTWARE.
 */

<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2013 Juergen Riegel                                     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <QContextMenuEvent>
# include <QMenu>
#endif

#include <Base/Console.h>
#include <Base/Quantity.h>
#include <Base/Exception.h>
#include <App/Application.h>

#include "InputField.h"

using namespace Gui;
using namespace Base;

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

InputField::InputField ( QWidget * parent )
  : QLineEdit(parent),
  StepSize(1.0),
  Maximum(DOUBLE_MAX),
  Minimum(-DOUBLE_MAX),
  HistorySize(5),
  SaveSize(5)
{
    this->setContextMenuPolicy(Qt::DefaultContextMenu);

    QObject::connect(this, SIGNAL(textChanged  (QString)),
                     this, SLOT(newInput(QString)));
}

InputField::~InputField()
{
}

void InputField::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu *editMenu = createStandardContextMenu();
    editMenu->setTitle(tr("Edit"));
    QMenu* menu = new QMenu(QString::fromAscii("InputFieldContextmenu"));

    menu->addMenu(editMenu);
    menu->addSeparator();

    // datastructure to remember actions for values
    std::vector<std::string> values;
    std::vector<QAction *> actions;

    // add the history menu part...
    std::vector<std::string> history = getHistory();

    for(std::vector<std::string>::const_iterator it = history.begin();it!= history.end();++it){
        actions.push_back(menu->addAction(QString::fromAscii(it->c_str())));
        values.push_back(*it);
    }

    // add the save value portion of the menu
    menu->addSeparator();
    QAction *SaveValueAction = menu->addAction(tr("Save value"));
    std::vector<std::string> savedValues = getSavedValues();

    for(std::vector<std::string>::const_iterator it = savedValues.begin();it!= savedValues.end();++it){
        actions.push_back(menu->addAction(QString::fromAscii(it->c_str())));
        values.push_back(*it);
    }

    // call the menu and wait until its back
    QAction *saveAction = menu->exec(event->globalPos());

    // look what the user has choosen
    if(saveAction == SaveValueAction)
        pushToSavedValues();
    else{
        int i=0;
        for(std::vector<QAction *>::const_iterator it = actions.begin();it!=actions.end();++it,i++)
            if(*it == saveAction)
                this->setText(QString::fromAscii(values[i].c_str()));
    }

    delete menu;
}

void InputField::newInput(const QString & text)
{
    Quantity res;
    try{
        res = Quantity::parse(text.toAscii());
    }catch(Base::Exception &e){
        ErrorText = e.what();
        this->setToolTip(QString::fromAscii(ErrorText.c_str()));
        QPalette palette;
        palette.setColor(QPalette::Base,QColor(255,200,200));
        setPalette(palette);
        parseError(QString::fromAscii(ErrorText.c_str()));
        return;
    }
    QPalette palette;
    palette.setColor(QPalette::Base,QColor(200,255,200));
    setPalette(palette);
    ErrorText = "";
    this->setToolTip(QString::fromAscii(ErrorText.c_str()));
    // signaling
    valueChanged(res);

}

void InputField::pushToHistory(std::string value)
{
    if(value == "")
        value = this->text().toAscii();
    if(_handle.isValid()){
        char hist1[21];
        char hist0[21];
        for(int i = HistorySize -1 ; i>=0 ;i--){
            snprintf(hist1,20,"Hist%i",i+1);
            snprintf(hist0,20,"Hist%i",i);
            std::string tHist = _handle->GetASCII(hist0,"");
            if(tHist != "")
                _handle->SetASCII(hist1,tHist.c_str());
        }
        _handle->SetASCII("Hist0",value.c_str());
    }
}

std::vector<std::string> InputField::getHistory(void)
{
    std::vector<std::string> res;

    if(_handle.isValid()){
        std::string tmp;
        char hist[21];
        for(int i = 0 ; i< HistorySize ;i++){
            snprintf(hist,20,"Hist%i",i);
            tmp = _handle->GetASCII(hist,"");
            if( tmp != "")
                res.push_back(tmp);
            else
                break; // end of history reached
        }
    }
    return res;
}

void InputField::pushToSavedValues(std::string value)
{
    if(value == "")
        value = this->text().toAscii();
    if(_handle.isValid()){
        char hist1[21];
        char hist0[21];
        for(int i = SaveSize -1 ; i>=0 ;i--){
            snprintf(hist1,20,"Save%i",i+1);
            snprintf(hist0,20,"Save%i",i);
            std::string tHist = _handle->GetASCII(hist0,"");
            if(tHist != "")
                _handle->SetASCII(hist1,tHist.c_str());
        }
        _handle->SetASCII("Save0",value.c_str());
    }
}

std::vector<std::string> InputField::getSavedValues(void)
{
    std::vector<std::string> res;

    if(_handle.isValid()){
        std::string tmp;
        char hist[21];
        for(int i = 0 ; i< SaveSize ;i++){
            snprintf(hist,20,"Save%i",i);
            tmp = _handle->GetASCII(hist,"");
            if( tmp != "")
                res.push_back(tmp);
            else
                break; // end of history reached
        }
    }
    return res;
}

/** Sets the preference path to \a path. */
void InputField::setParamGrpPath( const QByteArray& path )
{

  _handle = App::GetApplication().GetParameterGroupByPath( path);
  if (_handle.isValid())
      sGroupString = (const char*)path;
}

/** Returns the widget's preferences path. */
QByteArray InputField::paramGrpPath() const
{
    if(_handle.isValid())
        return sGroupString.c_str();
    return QByteArray();
}

/// sets the field with a quantity
void InputField::setValue(const Base::Quantity& quant)
{
    actQuantity = quant;
    if(!quant.getUnit().isEmpty())
        actUnit = quant.getUnit();

    setText(quant.getUserString());
}

void InputField::setUnit(const Base::Unit& unit)
{
    actUnit = unit;
}

/// get the value of the singleStep property
double InputField::singleStep(void)const
{
    return StepSize;
}

/// set the value of the singleStep property
void InputField::setSingleStep(double s)
{
    StepSize = s;
}

/// get the value of the maximum property
double InputField::maximum(void)const
{
    return Maximum;
}

/// set the value of the maximum property
void InputField::setMaximum(double m)
{
    Maximum = m;
}

/// get the value of the minimum property
double InputField::minimum(void)const
{
    return Minimum;
}

/// set the value of the minimum property
void InputField::setMinimum(double m)
{
    Minimum = m;
}

// get the value of the minimum property
int InputField::historySize(void)const
{
    return HistorySize;
}
// set the value of the minimum property
void InputField::setHistorySize(int i)
{
    assert(i>=0);
    assert(i<100);

    HistorySize = i;
}

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

#include "moc_InputField.cpp"
<commit_msg>+ Fix gcc build error<commit_after>/***************************************************************************
 *   Copyright (c) 2013 Juergen Riegel                                     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <QContextMenuEvent>
# include <QMenu>
#endif

#include <Base/Console.h>
#include <Base/Quantity.h>
#include <Base/Exception.h>
#include <App/Application.h>

#include "InputField.h"

using namespace Gui;
using namespace Base;

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

InputField::InputField ( QWidget * parent )
  : QLineEdit(parent),
  StepSize(1.0),
  Maximum(DOUBLE_MAX),
  Minimum(-DOUBLE_MAX),
  HistorySize(5),
  SaveSize(5)
{
    this->setContextMenuPolicy(Qt::DefaultContextMenu);

    QObject::connect(this, SIGNAL(textChanged  (QString)),
                     this, SLOT(newInput(QString)));
}

InputField::~InputField()
{
}

void InputField::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu *editMenu = createStandardContextMenu();
    editMenu->setTitle(tr("Edit"));
    QMenu* menu = new QMenu(QString::fromAscii("InputFieldContextmenu"));

    menu->addMenu(editMenu);
    menu->addSeparator();

    // datastructure to remember actions for values
    std::vector<std::string> values;
    std::vector<QAction *> actions;

    // add the history menu part...
    std::vector<std::string> history = getHistory();

    for(std::vector<std::string>::const_iterator it = history.begin();it!= history.end();++it){
        actions.push_back(menu->addAction(QString::fromAscii(it->c_str())));
        values.push_back(*it);
    }

    // add the save value portion of the menu
    menu->addSeparator();
    QAction *SaveValueAction = menu->addAction(tr("Save value"));
    std::vector<std::string> savedValues = getSavedValues();

    for(std::vector<std::string>::const_iterator it = savedValues.begin();it!= savedValues.end();++it){
        actions.push_back(menu->addAction(QString::fromAscii(it->c_str())));
        values.push_back(*it);
    }

    // call the menu and wait until its back
    QAction *saveAction = menu->exec(event->globalPos());

    // look what the user has choosen
    if(saveAction == SaveValueAction)
        pushToSavedValues();
    else{
        int i=0;
        for(std::vector<QAction *>::const_iterator it = actions.begin();it!=actions.end();++it,i++)
            if(*it == saveAction)
                this->setText(QString::fromAscii(values[i].c_str()));
    }

    delete menu;
}

void InputField::newInput(const QString & text)
{
    Quantity res;
    try{
        res = Quantity::parse(text.toAscii());
    }catch(Base::Exception &e){
        ErrorText = e.what();
        this->setToolTip(QString::fromAscii(ErrorText.c_str()));
        QPalette palette;
        palette.setColor(QPalette::Base,QColor(255,200,200));
        setPalette(palette);
        parseError(QString::fromAscii(ErrorText.c_str()));
        return;
    }
    QPalette palette;
    palette.setColor(QPalette::Base,QColor(200,255,200));
    setPalette(palette);
    ErrorText = "";
    this->setToolTip(QString::fromAscii(ErrorText.c_str()));
    // signaling
    valueChanged(res);

}

void InputField::pushToHistory(std::string value)
{
    if(value == "")
        value = (const char*)this->text().toAscii();
    if(_handle.isValid()){
        char hist1[21];
        char hist0[21];
        for(int i = HistorySize -1 ; i>=0 ;i--){
            snprintf(hist1,20,"Hist%i",i+1);
            snprintf(hist0,20,"Hist%i",i);
            std::string tHist = _handle->GetASCII(hist0,"");
            if(tHist != "")
                _handle->SetASCII(hist1,tHist.c_str());
        }
        _handle->SetASCII("Hist0",value.c_str());
    }
}

std::vector<std::string> InputField::getHistory(void)
{
    std::vector<std::string> res;

    if(_handle.isValid()){
        std::string tmp;
        char hist[21];
        for(int i = 0 ; i< HistorySize ;i++){
            snprintf(hist,20,"Hist%i",i);
            tmp = _handle->GetASCII(hist,"");
            if( tmp != "")
                res.push_back(tmp);
            else
                break; // end of history reached
        }
    }
    return res;
}

void InputField::pushToSavedValues(std::string value)
{
    if(value == "")
        value = (const char*)this->text().toAscii();
    if(_handle.isValid()){
        char hist1[21];
        char hist0[21];
        for(int i = SaveSize -1 ; i>=0 ;i--){
            snprintf(hist1,20,"Save%i",i+1);
            snprintf(hist0,20,"Save%i",i);
            std::string tHist = _handle->GetASCII(hist0,"");
            if(tHist != "")
                _handle->SetASCII(hist1,tHist.c_str());
        }
        _handle->SetASCII("Save0",value.c_str());
    }
}

std::vector<std::string> InputField::getSavedValues(void)
{
    std::vector<std::string> res;

    if(_handle.isValid()){
        std::string tmp;
        char hist[21];
        for(int i = 0 ; i< SaveSize ;i++){
            snprintf(hist,20,"Save%i",i);
            tmp = _handle->GetASCII(hist,"");
            if( tmp != "")
                res.push_back(tmp);
            else
                break; // end of history reached
        }
    }
    return res;
}

/** Sets the preference path to \a path. */
void InputField::setParamGrpPath( const QByteArray& path )
{

  _handle = App::GetApplication().GetParameterGroupByPath( path);
  if (_handle.isValid())
      sGroupString = (const char*)path;
}

/** Returns the widget's preferences path. */
QByteArray InputField::paramGrpPath() const
{
    if(_handle.isValid())
        return sGroupString.c_str();
    return QByteArray();
}

/// sets the field with a quantity
void InputField::setValue(const Base::Quantity& quant)
{
    actQuantity = quant;
    if(!quant.getUnit().isEmpty())
        actUnit = quant.getUnit();

    setText(quant.getUserString());
}

void InputField::setUnit(const Base::Unit& unit)
{
    actUnit = unit;
}

/// get the value of the singleStep property
double InputField::singleStep(void)const
{
    return StepSize;
}

/// set the value of the singleStep property
void InputField::setSingleStep(double s)
{
    StepSize = s;
}

/// get the value of the maximum property
double InputField::maximum(void)const
{
    return Maximum;
}

/// set the value of the maximum property
void InputField::setMaximum(double m)
{
    Maximum = m;
}

/// get the value of the minimum property
double InputField::minimum(void)const
{
    return Minimum;
}

/// set the value of the minimum property
void InputField::setMinimum(double m)
{
    Minimum = m;
}

// get the value of the minimum property
int InputField::historySize(void)const
{
    return HistorySize;
}
// set the value of the minimum property
void InputField::setHistorySize(int i)
{
    assert(i>=0);
    assert(i<100);

    HistorySize = i;
}

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

#include "moc_InputField.cpp"
<|endoftext|>


<commit_before><?hh //partial

use typesafety\Result;
use typesafety\TextReporter;

describe(TextReporter::class, function() {
  beforeEach(function() {
    $content = file_get_contents(__DIR__ . '/fixtures/failed/output.json');
    $content = str_replace('{$rootDirectory}', realpath(__DIR__ . '/../') , $content);
    $json = json_decode($content);
    $this->result = Result::fromObject($json);
    $this->reporter = new TextReporter();
  });
  describe('onStop()', function() {
    it('display type check report', function () {
      $this->reporter->onStop($this->result);
    });
  });
});
<commit_msg>fix root directory<commit_after><?hh //partial

use typesafety\Result;
use typesafety\TextReporter;

describe(TextReporter::class, function() {
  beforeEach(function() {
    $content = file_get_contents(__DIR__ . '/fixtures/failed/output.json');
    $content = str_replace('{$rootDirectory}', realpath(__DIR__ . '/fixtures/failed') , $content);
    $json = json_decode($content);
    $this->result = Result::fromObject($json);
    $this->reporter = new TextReporter();
  });
  describe('onStop()', function() {
    it('display type check report', function () {
      $this->reporter->onStop($this->result);
    });
  });
});
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
**
**  SysStat is a Qt-based interface to system statistics
**
**  Authors:
**       Copyright (c) 2009 - 2012 Kuzma Shapran <Kuzma.Shapran@gmail.com>
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  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.,
**  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
** END_COMMON_COPYRIGHT_HEADER */

#include <fcntl.h>
#include <unistd.h>

#include <cstddef>

#include "basestat.h"
#include "basestat_p.h"

namespace SysStat {

BaseStatPrivate::BaseStatPrivate(BaseStat* parent)
    : QObject(parent)
    , mTimer(new QTimer(this))
    , mSynchroTimer(new QTimer(this))
{
    mTimer->setSingleShot(false);

    mSynchroTimer->setSingleShot(false);
    connect(mSynchroTimer, SIGNAL(timeout()), SLOT(synchroTimeout()));
}

BaseStatPrivate::~BaseStatPrivate()
{
}

bool BaseStatPrivate::timerIsActive() const
{
    return mTimer->isActive();
}

int BaseStatPrivate::updateInterval() const
{
    return mTimer->interval();
}

void BaseStatPrivate::intervalChanged()
{
}

void BaseStatPrivate::sourceChanged()
{
}

void BaseStatPrivate::setUpdateInterval(int msec)
{
    mTimer->stop();
    mTimer->setInterval(msec);
    this->intervalChanged();
    mSynchroTimer->setInterval(msec / 10);
    if (msec > 0)
    {
        mLastSynchro = 0;
        mSynchroTimer->start();
    }
}

void BaseStatPrivate::synchroTimeout()
{
    QTime now(QTime::currentTime());
    int synchro = ((now.minute() * 60 + now.second()) * 1000 + now.msec() ) / mTimer->interval();
    if ((mLastSynchro != 0) && (mLastSynchro != synchro))
    {
        mSynchroTimer->stop();
        mTimer->start();
    }
    mLastSynchro = synchro;
}

void BaseStatPrivate::stopUpdating()
{
    mTimer->stop();
}

QString BaseStatPrivate::monitoredSource() const
{
    return mSource;
}

void BaseStatPrivate::setMonitoredSource(const QString &Source)
{
    mSource = Source;
    this->sourceChanged();
}

void BaseStatPrivate::monitorDefaultSource()
{
    mSource = defaultSource();
}

QString BaseStatPrivate::readAllFile(const char *filename)
{
    QString result;

    static const size_t bufferSize = 1 << 12; // 4096
    static char buffer[bufferSize];

    int fd = ::open(filename, O_RDONLY);
    if (fd > 0)
    {
        ssize_t size = ::read(fd, buffer, bufferSize);
        ::close(fd);
        if (size > 0)
            result = QString::fromLatin1(buffer, size);
    }

    return result;
}

QStringList BaseStatPrivate::sources() const
{
    return mSources;
}

BaseStat::BaseStat(QObject *parent)
    : QObject(parent)
{
}

BaseStat::~BaseStat()
{
}

QStringList BaseStat::sources() const
{
    return baseimpl->sources();
}

int BaseStat::updateInterval() const
{
    return baseimpl->updateInterval();
}

void BaseStat::setUpdateInterval(int msec)
{
    if ((updateInterval() != msec) || (!baseimpl->timerIsActive()))
    {
        baseimpl->setUpdateInterval(msec);
        emit updateIntervalChanged(msec);
    }
}

void BaseStat::stopUpdating()
{
    if (updateInterval() != 0)
    {
        baseimpl->stopUpdating();
        emit updateIntervalChanged(0);
    }
}

QString BaseStat::monitoredSource() const
{
    return baseimpl->monitoredSource();
}

void BaseStat::setMonitoredSource(const QString &source)
{
    if (monitoredSource() != source)
    {
        baseimpl->setMonitoredSource(source);
        emit monitoredSourceChanged(source);
    }
}

void BaseStat::monitorDefaultSource()
{
    QString oldSource = monitoredSource();
    baseimpl->monitorDefaultSource();
    if (monitoredSource() != oldSource)
        emit monitoredSourceChanged(monitoredSource());
}

}
<commit_msg>Fix rare file descriptor leak in readAllFile()<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
**
**  SysStat is a Qt-based interface to system statistics
**
**  Authors:
**       Copyright (c) 2009 - 2012 Kuzma Shapran <Kuzma.Shapran@gmail.com>
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  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.,
**  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
** END_COMMON_COPYRIGHT_HEADER */

#include <fcntl.h>
#include <unistd.h>

#include <cstddef>

#include "basestat.h"
#include "basestat_p.h"

namespace SysStat {

BaseStatPrivate::BaseStatPrivate(BaseStat* parent)
    : QObject(parent)
    , mTimer(new QTimer(this))
    , mSynchroTimer(new QTimer(this))
{
    mTimer->setSingleShot(false);

    mSynchroTimer->setSingleShot(false);
    connect(mSynchroTimer, SIGNAL(timeout()), SLOT(synchroTimeout()));
}

BaseStatPrivate::~BaseStatPrivate()
{
}

bool BaseStatPrivate::timerIsActive() const
{
    return mTimer->isActive();
}

int BaseStatPrivate::updateInterval() const
{
    return mTimer->interval();
}

void BaseStatPrivate::intervalChanged()
{
}

void BaseStatPrivate::sourceChanged()
{
}

void BaseStatPrivate::setUpdateInterval(int msec)
{
    mTimer->stop();
    mTimer->setInterval(msec);
    this->intervalChanged();
    mSynchroTimer->setInterval(msec / 10);
    if (msec > 0)
    {
        mLastSynchro = 0;
        mSynchroTimer->start();
    }
}

void BaseStatPrivate::synchroTimeout()
{
    QTime now(QTime::currentTime());
    int synchro = ((now.minute() * 60 + now.second()) * 1000 + now.msec() ) / mTimer->interval();
    if ((mLastSynchro != 0) && (mLastSynchro != synchro))
    {
        mSynchroTimer->stop();
        mTimer->start();
    }
    mLastSynchro = synchro;
}

void BaseStatPrivate::stopUpdating()
{
    mTimer->stop();
}

QString BaseStatPrivate::monitoredSource() const
{
    return mSource;
}

void BaseStatPrivate::setMonitoredSource(const QString &Source)
{
    mSource = Source;
    this->sourceChanged();
}

void BaseStatPrivate::monitorDefaultSource()
{
    mSource = defaultSource();
}

QString BaseStatPrivate::readAllFile(const char *filename)
{
    QString result;

    static const size_t bufferSize = 1 << 12; // 4096
    static char buffer[bufferSize];

    int fd = ::open(filename, O_RDONLY);
    if (fd > -1)
    {
        ssize_t size = ::read(fd, buffer, bufferSize);
        ::close(fd);
        if (size > 0)
            result = QString::fromLatin1(buffer, size);
    }

    return result;
}

QStringList BaseStatPrivate::sources() const
{
    return mSources;
}

BaseStat::BaseStat(QObject *parent)
    : QObject(parent)
{
}

BaseStat::~BaseStat()
{
}

QStringList BaseStat::sources() const
{
    return baseimpl->sources();
}

int BaseStat::updateInterval() const
{
    return baseimpl->updateInterval();
}

void BaseStat::setUpdateInterval(int msec)
{
    if ((updateInterval() != msec) || (!baseimpl->timerIsActive()))
    {
        baseimpl->setUpdateInterval(msec);
        emit updateIntervalChanged(msec);
    }
}

void BaseStat::stopUpdating()
{
    if (updateInterval() != 0)
    {
        baseimpl->stopUpdating();
        emit updateIntervalChanged(0);
    }
}

QString BaseStat::monitoredSource() const
{
    return baseimpl->monitoredSource();
}

void BaseStat::setMonitoredSource(const QString &source)
{
    if (monitoredSource() != source)
    {
        baseimpl->setMonitoredSource(source);
        emit monitoredSourceChanged(source);
    }
}

void BaseStat::monitorDefaultSource()
{
    QString oldSource = monitoredSource();
    baseimpl->monitorDefaultSource();
    if (monitoredSource() != oldSource)
        emit monitoredSourceChanged(monitoredSource());
}

}
<|endoftext|>