<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "fieldmappingimpl.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#include <com/sun/star/ui/AddressBookSourceDialog.hpp>
#include <com/sun/star/awt/XWindow.hpp>
#include <com/sun/star/sdb/CommandType.hpp>
#include <tools/debug.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <vcl/stdtext.hxx>
#include <com/sun/star/util/AliasProgrammaticPair.hpp>
#include "abpresid.hrc"
#include "componentmodule.hxx"
#include <unotools/confignode.hxx>
#include "sal/macros.h"

namespace abp
{

    using namespace ::utl;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star::util;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::ui;
    using namespace ::com::sun::star::ui::dialogs;

    static const char sDriverSettingsNodeName[] = "/org.openoffice.Office.DataAccess/DriverSettings/com.sun.star.comp.sdbc.MozabDriver";
    static const char sAddressBookNodeName[] = "/org.openoffice.Office.DataAccess/AddressBook";

    namespace fieldmapping
    {

        bool invokeDialog( const Reference< XComponentContext >& _rxORB, class vcl::Window* _pParent,
            const Reference< XPropertySet >& _rxDataSource, AddressSettings& _rSettings )
        {
            _rSettings.aFieldMapping.clear();

            DBG_ASSERT( _rxORB.is(), "fieldmapping::invokeDialog: invalid service factory!" );
            DBG_ASSERT( _rxDataSource.is(), "fieldmapping::invokeDialog: invalid data source!" );
            if ( !_rxORB.is() || !_rxDataSource.is() )
                return false;

            try
            {

                // create an instance of the dialog service
                Reference< XWindow > xDialogParent = VCLUnoHelper::GetInterface( _pParent );
                OUString sTitle(ModuleRes(RID_STR_FIELDDIALOGTITLE).toString());
                Reference< XExecutableDialog > xDialog = AddressBookSourceDialog::createWithDataSource(_rxORB,
                                                           // the parent window
                                                           xDialogParent,
                                                           _rxDataSource,
                                                           _rSettings.bRegisterDataSource ? _rSettings.sRegisteredDataSourceName : _rSettings.sDataSourceName,
                                                           // the table to use
                                                           _rSettings.sSelectedTable,
                                                           sTitle);

                // execute the dialog
                if ( xDialog->execute() )
                {
                    // retrieve the field mapping as set by he user
                    Reference< XPropertySet > xDialogProps( xDialog, UNO_QUERY );

                    Sequence< AliasProgrammaticPair > aMapping;
#ifdef DBG_UTIL
                    bool bSuccess =
#endif
                    xDialogProps->getPropertyValue("FieldMapping") >>= aMapping;
                    DBG_ASSERT( bSuccess, "fieldmapping::invokeDialog: invalid property type for FieldMapping!" );

                    // and copy it into the map
                    const AliasProgrammaticPair* pMapping = aMapping.getConstArray();
                    const AliasProgrammaticPair* pMappingEnd = pMapping + aMapping.getLength();
                    for (;pMapping != pMappingEnd; ++pMapping)
                        _rSettings.aFieldMapping[ pMapping->ProgrammaticName ] = pMapping->Alias;

                    return true;
                }

            }
            catch(const Exception&)
            {
                OSL_FAIL("fieldmapping::invokeDialog: caught an exception while executing the dialog!");
            }
            return false;
        }

        void defaultMapping(  const Reference< XComponentContext >& _rxContext, MapString2String& _rFieldAssignment )
        {
            _rFieldAssignment.clear();

            try
            {
                // what we have:
                // a) For the address data source, we need a mapping from programmatic names (1) to real column names
                // b) The SDBC driver has a fixed set of columns, which, when returned, are named according to
                //    some configuration entries. E.g., the driver displays the field which it knows contains
                //    the first name as "First Name" - the latter string is stored in the config.
                //    For this, the driver uses programmatic names, too, but they differ from the programmatic names the
                //    template documents have.
                // So what we need first is a mapping from programmatic names (1) to programmatic names (2)
                const sal_Char* pMappingProgrammatics[] =
                {
                    "FirstName",            "FirstName",
                    "LastName",             "LastName",
                    "Street",               "HomeAddress",
                    "Zip",                  "HomeZipCode",
                    "City",                 "HomeCity",
                    "State",                "HomeState",
                    "Country",              "HomeCountry",
                    "PhonePriv",            "HomePhone",
                    "PhoneComp",            "WorkPhone",
                    "PhoneCell",            "CellularNumber",
                    "Pager",                "PagerNumber",
                    "Fax",                  "FaxNumber",
                    "EMail",                "PrimaryEmail",
                    "URL",                  "WebPage1",
                    "Note",                 "Notes",
                    "Altfield1",            "Custom1",
                    "Altfield2",            "Custom2",
                    "Altfield3",            "Custom3",
                    "Altfield4",            "Custom4",
                    "Title",                "JobTitle",
                    "Company",              "Company",
                    "Department",           "Department"
                };
                    // (this list is not complete: both lists of programmatic names are larger in real,
                    // but this list above is the intersection)

                // access the configuration information which the driver uses for determining it's column names
                OUString sDriverAliasesNodeName = sDriverSettingsNodeName;
                sDriverAliasesNodeName += OUString( "/ColumnAliases" );

                // create a config node for this
                OConfigurationTreeRoot aDriverFieldAliasing = OConfigurationTreeRoot::createWithComponentContext(
                    _rxContext, sDriverAliasesNodeName, -1, OConfigurationTreeRoot::CM_READONLY);

                // loop through all programmatic pairs
                DBG_ASSERT( 0 == SAL_N_ELEMENTS( pMappingProgrammatics ) % 2,
                    "fieldmapping::defaultMapping: invalid programmatic map!" );
                // number of pairs
                sal_Int32 nIntersectedProgrammatics = SAL_N_ELEMENTS( pMappingProgrammatics ) / 2;

                const sal_Char** pProgrammatic = pMappingProgrammatics;
                OUString sAddressProgrammatic;
                OUString sDriverProgrammatic;
                OUString sDriverUI;
                for (   sal_Int32 i=0;
                        i < nIntersectedProgrammatics;
                        ++i
                    )
                {
                    sAddressProgrammatic = OUString::createFromAscii( *pProgrammatic++ );
                    sDriverProgrammatic = OUString::createFromAscii( *pProgrammatic++ );

                    if ( aDriverFieldAliasing.hasByName( sDriverProgrammatic ) )
                    {
                        aDriverFieldAliasing.getNodeValue( sDriverProgrammatic ) >>= sDriverUI;
                        if ( 0 == sDriverUI.getLength() )
                        {
                            OSL_FAIL( "fieldmapping::defaultMapping: invalid driver UI column name!");
                        }
                        else
                            _rFieldAssignment[ sAddressProgrammatic ] = sDriverUI;
                    }
                    else
                    {
                        OSL_FAIL( "fieldmapping::defaultMapping: invalid driver programmatic name!" );
                    }
                }
            }
            catch( const Exception& )
            {
                OSL_FAIL("fieldmapping::defaultMapping: code is assumed to throw no exceptions!");
                    // the config nodes we're using herein should not do this ....
            }
        }

        void writeTemplateAddressFieldMapping( const Reference< XComponentContext >& _rxContext, const MapString2String& _rFieldAssignment )
        {
            // want to have a non-const map for easier handling
            MapString2String aFieldAssignment( _rFieldAssignment );

            // access the configuration information which the driver uses for determining it's column names

            // create a config node for this
            OConfigurationTreeRoot aAddressBookSettings = OConfigurationTreeRoot::createWithComponentContext(
                _rxContext, sAddressBookNodeName, -1, OConfigurationTreeRoot::CM_UPDATABLE);

            OConfigurationNode aFields = aAddressBookSettings.openNode( OUString( "Fields" ) );

            // loop through all existent fields
            Sequence< OUString > aExistentFields = aFields.getNodeNames();
            const OUString* pExistentFields = aExistentFields.getConstArray();
            const OUString* pExistentFieldsEnd = pExistentFields + aExistentFields.getLength();

            const OUString sProgrammaticNodeName( "ProgrammaticFieldName" );
            const OUString sAssignedNodeName( "AssignedFieldName" );

            for ( ; pExistentFields != pExistentFieldsEnd; ++pExistentFields )
            {
#ifdef DBG_UTIL
                OUString sRedundantProgrammaticName;
                aFields.openNode( *pExistentFields ).getNodeValue( sProgrammaticNodeName ) >>= sRedundantProgrammaticName;
#endif
                DBG_ASSERT( sRedundantProgrammaticName == *pExistentFields,
                    "fieldmapping::writeTemplateAddressFieldMapping: inconsistent config data!" );
                    // there should be a redundancy in the config data .... if this asserts, there isn't anymore!

                // do we have a new alias for the programmatic?
                MapString2String::iterator aPos = aFieldAssignment.find( *pExistentFields );
                if ( aFieldAssignment.end() != aPos )
                {   // yes
                    // -> set a new value
                    OConfigurationNode aExistentField = aFields.openNode( *pExistentFields );
                    aExistentField.setNodeValue( sAssignedNodeName, makeAny( aPos->second ) );
                    // and remove the mapping entry
                    aFieldAssignment.erase( *pExistentFields );
                }
                else
                {   // no
                    // -> remove it
                    aFields.removeNode( *pExistentFields );
                }
            }

            // now everything remaining in aFieldAssignment marks a mapping entry which was not present
            // in the config before
            for (   MapString2String::const_iterator aNewMapping = aFieldAssignment.begin();
                    aNewMapping != aFieldAssignment.end();
                    ++aNewMapping
                )
            {
                DBG_ASSERT( !aFields.hasByName( aNewMapping->first ),
                    "fieldmapping::writeTemplateAddressFieldMapping: inconsistence!" );
                    // in case the config node for the fields already has the node named <aNewMapping->first>,
                    // the entry should have been removed from aNewMapping (in the above loop)
                OConfigurationNode aNewField =  aFields.createNode( aNewMapping->first );
                aNewField.setNodeValue( sProgrammaticNodeName, makeAny( aNewMapping->first ) );
                aNewField.setNodeValue( sAssignedNodeName, makeAny( aNewMapping->second ) );
            }

            // commit the changes done
            aAddressBookSettings.commit();
        }

    }   // namespace fieldmapping

    namespace addressconfig
    {

        void writeTemplateAddressSource( const Reference< XComponentContext >& _rxContext,
            const OUString& _rDataSourceName, const OUString& _rTableName )
        {
            // access the configuration information which the driver uses for determining it's column names

            // create a config node for this
            OConfigurationTreeRoot aAddressBookSettings = OConfigurationTreeRoot::createWithComponentContext(
                _rxContext, sAddressBookNodeName, -1, OConfigurationTreeRoot::CM_UPDATABLE);

            aAddressBookSettings.setNodeValue( OUString( "DataSourceName" ), makeAny( _rDataSourceName ) );
            aAddressBookSettings.setNodeValue( OUString( "Command" ), makeAny( _rTableName ) );
            aAddressBookSettings.setNodeValue( OUString( "CommandType" ), makeAny( (sal_Int32)CommandType::TABLE ) );

            // commit the changes done
            aAddressBookSettings.commit();
        }

        void markPilotSuccess( const Reference< XComponentContext >& _rxContext )
        {
            // access the configuration information which the driver uses for determining it's column names

            // create a config node for this
            OConfigurationTreeRoot aAddressBookSettings = OConfigurationTreeRoot::createWithComponentContext(
                _rxContext, sAddressBookNodeName, -1, OConfigurationTreeRoot::CM_UPDATABLE);

            // set the flag
            aAddressBookSettings.setNodeValue( OUString( "AutoPilotCompleted" ), makeAny( true ) );

            // commit the changes done
            aAddressBookSettings.commit();
        }

    }   // namespace addressconfig

}   // namespace abp

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>loplugin:stringconstant: handle OUString+=OUString(literal)<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "fieldmappingimpl.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#include <com/sun/star/ui/AddressBookSourceDialog.hpp>
#include <com/sun/star/awt/XWindow.hpp>
#include <com/sun/star/sdb/CommandType.hpp>
#include <tools/debug.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <vcl/stdtext.hxx>
#include <com/sun/star/util/AliasProgrammaticPair.hpp>
#include "abpresid.hrc"
#include "componentmodule.hxx"
#include <unotools/confignode.hxx>
#include "sal/macros.h"

namespace abp
{

    using namespace ::utl;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star::util;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::ui;
    using namespace ::com::sun::star::ui::dialogs;

    static const char sDriverSettingsNodeName[] = "/org.openoffice.Office.DataAccess/DriverSettings/com.sun.star.comp.sdbc.MozabDriver";
    static const char sAddressBookNodeName[] = "/org.openoffice.Office.DataAccess/AddressBook";

    namespace fieldmapping
    {

        bool invokeDialog( const Reference< XComponentContext >& _rxORB, class vcl::Window* _pParent,
            const Reference< XPropertySet >& _rxDataSource, AddressSettings& _rSettings )
        {
            _rSettings.aFieldMapping.clear();

            DBG_ASSERT( _rxORB.is(), "fieldmapping::invokeDialog: invalid service factory!" );
            DBG_ASSERT( _rxDataSource.is(), "fieldmapping::invokeDialog: invalid data source!" );
            if ( !_rxORB.is() || !_rxDataSource.is() )
                return false;

            try
            {

                // create an instance of the dialog service
                Reference< XWindow > xDialogParent = VCLUnoHelper::GetInterface( _pParent );
                OUString sTitle(ModuleRes(RID_STR_FIELDDIALOGTITLE).toString());
                Reference< XExecutableDialog > xDialog = AddressBookSourceDialog::createWithDataSource(_rxORB,
                                                           // the parent window
                                                           xDialogParent,
                                                           _rxDataSource,
                                                           _rSettings.bRegisterDataSource ? _rSettings.sRegisteredDataSourceName : _rSettings.sDataSourceName,
                                                           // the table to use
                                                           _rSettings.sSelectedTable,
                                                           sTitle);

                // execute the dialog
                if ( xDialog->execute() )
                {
                    // retrieve the field mapping as set by he user
                    Reference< XPropertySet > xDialogProps( xDialog, UNO_QUERY );

                    Sequence< AliasProgrammaticPair > aMapping;
#ifdef DBG_UTIL
                    bool bSuccess =
#endif
                    xDialogProps->getPropertyValue("FieldMapping") >>= aMapping;
                    DBG_ASSERT( bSuccess, "fieldmapping::invokeDialog: invalid property type for FieldMapping!" );

                    // and copy it into the map
                    const AliasProgrammaticPair* pMapping = aMapping.getConstArray();
                    const AliasProgrammaticPair* pMappingEnd = pMapping + aMapping.getLength();
                    for (;pMapping != pMappingEnd; ++pMapping)
                        _rSettings.aFieldMapping[ pMapping->ProgrammaticName ] = pMapping->Alias;

                    return true;
                }

            }
            catch(const Exception&)
            {
                OSL_FAIL("fieldmapping::invokeDialog: caught an exception while executing the dialog!");
            }
            return false;
        }

        void defaultMapping(  const Reference< XComponentContext >& _rxContext, MapString2String& _rFieldAssignment )
        {
            _rFieldAssignment.clear();

            try
            {
                // what we have:
                // a) For the address data source, we need a mapping from programmatic names (1) to real column names
                // b) The SDBC driver has a fixed set of columns, which, when returned, are named according to
                //    some configuration entries. E.g., the driver displays the field which it knows contains
                //    the first name as "First Name" - the latter string is stored in the config.
                //    For this, the driver uses programmatic names, too, but they differ from the programmatic names the
                //    template documents have.
                // So what we need first is a mapping from programmatic names (1) to programmatic names (2)
                const sal_Char* pMappingProgrammatics[] =
                {
                    "FirstName",            "FirstName",
                    "LastName",             "LastName",
                    "Street",               "HomeAddress",
                    "Zip",                  "HomeZipCode",
                    "City",                 "HomeCity",
                    "State",                "HomeState",
                    "Country",              "HomeCountry",
                    "PhonePriv",            "HomePhone",
                    "PhoneComp",            "WorkPhone",
                    "PhoneCell",            "CellularNumber",
                    "Pager",                "PagerNumber",
                    "Fax",                  "FaxNumber",
                    "EMail",                "PrimaryEmail",
                    "URL",                  "WebPage1",
                    "Note",                 "Notes",
                    "Altfield1",            "Custom1",
                    "Altfield2",            "Custom2",
                    "Altfield3",            "Custom3",
                    "Altfield4",            "Custom4",
                    "Title",                "JobTitle",
                    "Company",              "Company",
                    "Department",           "Department"
                };
                    // (this list is not complete: both lists of programmatic names are larger in real,
                    // but this list above is the intersection)

                // access the configuration information which the driver uses for determining it's column names
                OUString sDriverAliasesNodeName(
                    OUStringLiteral(sDriverSettingsNodeName)
                    + "/ColumnAliases");

                // create a config node for this
                OConfigurationTreeRoot aDriverFieldAliasing = OConfigurationTreeRoot::createWithComponentContext(
                    _rxContext, sDriverAliasesNodeName, -1, OConfigurationTreeRoot::CM_READONLY);

                // loop through all programmatic pairs
                DBG_ASSERT( 0 == SAL_N_ELEMENTS( pMappingProgrammatics ) % 2,
                    "fieldmapping::defaultMapping: invalid programmatic map!" );
                // number of pairs
                sal_Int32 nIntersectedProgrammatics = SAL_N_ELEMENTS( pMappingProgrammatics ) / 2;

                const sal_Char** pProgrammatic = pMappingProgrammatics;
                OUString sAddressProgrammatic;
                OUString sDriverProgrammatic;
                OUString sDriverUI;
                for (   sal_Int32 i=0;
                        i < nIntersectedProgrammatics;
                        ++i
                    )
                {
                    sAddressProgrammatic = OUString::createFromAscii( *pProgrammatic++ );
                    sDriverProgrammatic = OUString::createFromAscii( *pProgrammatic++ );

                    if ( aDriverFieldAliasing.hasByName( sDriverProgrammatic ) )
                    {
                        aDriverFieldAliasing.getNodeValue( sDriverProgrammatic ) >>= sDriverUI;
                        if ( 0 == sDriverUI.getLength() )
                        {
                            OSL_FAIL( "fieldmapping::defaultMapping: invalid driver UI column name!");
                        }
                        else
                            _rFieldAssignment[ sAddressProgrammatic ] = sDriverUI;
                    }
                    else
                    {
                        OSL_FAIL( "fieldmapping::defaultMapping: invalid driver programmatic name!" );
                    }
                }
            }
            catch( const Exception& )
            {
                OSL_FAIL("fieldmapping::defaultMapping: code is assumed to throw no exceptions!");
                    // the config nodes we're using herein should not do this ....
            }
        }

        void writeTemplateAddressFieldMapping( const Reference< XComponentContext >& _rxContext, const MapString2String& _rFieldAssignment )
        {
            // want to have a non-const map for easier handling
            MapString2String aFieldAssignment( _rFieldAssignment );

            // access the configuration information which the driver uses for determining it's column names

            // create a config node for this
            OConfigurationTreeRoot aAddressBookSettings = OConfigurationTreeRoot::createWithComponentContext(
                _rxContext, sAddressBookNodeName, -1, OConfigurationTreeRoot::CM_UPDATABLE);

            OConfigurationNode aFields = aAddressBookSettings.openNode( OUString( "Fields" ) );

            // loop through all existent fields
            Sequence< OUString > aExistentFields = aFields.getNodeNames();
            const OUString* pExistentFields = aExistentFields.getConstArray();
            const OUString* pExistentFieldsEnd = pExistentFields + aExistentFields.getLength();

            const OUString sProgrammaticNodeName( "ProgrammaticFieldName" );
            const OUString sAssignedNodeName( "AssignedFieldName" );

            for ( ; pExistentFields != pExistentFieldsEnd; ++pExistentFields )
            {
#ifdef DBG_UTIL
                OUString sRedundantProgrammaticName;
                aFields.openNode( *pExistentFields ).getNodeValue( sProgrammaticNodeName ) >>= sRedundantProgrammaticName;
#endif
                DBG_ASSERT( sRedundantProgrammaticName == *pExistentFields,
                    "fieldmapping::writeTemplateAddressFieldMapping: inconsistent config data!" );
                    // there should be a redundancy in the config data .... if this asserts, there isn't anymore!

                // do we have a new alias for the programmatic?
                MapString2String::iterator aPos = aFieldAssignment.find( *pExistentFields );
                if ( aFieldAssignment.end() != aPos )
                {   // yes
                    // -> set a new value
                    OConfigurationNode aExistentField = aFields.openNode( *pExistentFields );
                    aExistentField.setNodeValue( sAssignedNodeName, makeAny( aPos->second ) );
                    // and remove the mapping entry
                    aFieldAssignment.erase( *pExistentFields );
                }
                else
                {   // no
                    // -> remove it
                    aFields.removeNode( *pExistentFields );
                }
            }

            // now everything remaining in aFieldAssignment marks a mapping entry which was not present
            // in the config before
            for (   MapString2String::const_iterator aNewMapping = aFieldAssignment.begin();
                    aNewMapping != aFieldAssignment.end();
                    ++aNewMapping
                )
            {
                DBG_ASSERT( !aFields.hasByName( aNewMapping->first ),
                    "fieldmapping::writeTemplateAddressFieldMapping: inconsistence!" );
                    // in case the config node for the fields already has the node named <aNewMapping->first>,
                    // the entry should have been removed from aNewMapping (in the above loop)
                OConfigurationNode aNewField =  aFields.createNode( aNewMapping->first );
                aNewField.setNodeValue( sProgrammaticNodeName, makeAny( aNewMapping->first ) );
                aNewField.setNodeValue( sAssignedNodeName, makeAny( aNewMapping->second ) );
            }

            // commit the changes done
            aAddressBookSettings.commit();
        }

    }   // namespace fieldmapping

    namespace addressconfig
    {

        void writeTemplateAddressSource( const Reference< XComponentContext >& _rxContext,
            const OUString& _rDataSourceName, const OUString& _rTableName )
        {
            // access the configuration information which the driver uses for determining it's column names

            // create a config node for this
            OConfigurationTreeRoot aAddressBookSettings = OConfigurationTreeRoot::createWithComponentContext(
                _rxContext, sAddressBookNodeName, -1, OConfigurationTreeRoot::CM_UPDATABLE);

            aAddressBookSettings.setNodeValue( OUString( "DataSourceName" ), makeAny( _rDataSourceName ) );
            aAddressBookSettings.setNodeValue( OUString( "Command" ), makeAny( _rTableName ) );
            aAddressBookSettings.setNodeValue( OUString( "CommandType" ), makeAny( (sal_Int32)CommandType::TABLE ) );

            // commit the changes done
            aAddressBookSettings.commit();
        }

        void markPilotSuccess( const Reference< XComponentContext >& _rxContext )
        {
            // access the configuration information which the driver uses for determining it's column names

            // create a config node for this
            OConfigurationTreeRoot aAddressBookSettings = OConfigurationTreeRoot::createWithComponentContext(
                _rxContext, sAddressBookNodeName, -1, OConfigurationTreeRoot::CM_UPDATABLE);

            // set the flag
            aAddressBookSettings.setNodeValue( OUString( "AutoPilotCompleted" ), makeAny( true ) );

            // commit the changes done
            aAddressBookSettings.commit();
        }

    }   // namespace addressconfig

}   // namespace abp

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


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

#include "classes/framelistanalyzer.hxx"

//_______________________________________________
//  my own includes

#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_TARGETS_H_
#include <targets.h>
#endif

#ifndef __FRAMEWORK_PROPERTIES_H_
#include <properties.h>
#endif

//_______________________________________________
//  interface includes

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

//_______________________________________________
//  includes of other projects

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//_______________________________________________
//  namespace

namespace framework{

//_______________________________________________
//  non exported const

//_______________________________________________
//  non exported definitions

//_______________________________________________
//  declarations

//_______________________________________________

/**
 */

FrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier       ,
                                      const css::uno::Reference< css::frame::XFrame >&          xReferenceFrame ,
                                            sal_uInt32                                          eDetectMode     )
    : m_xSupplier      (xSupplier      )
    , m_xReferenceFrame(xReferenceFrame)
    , m_eDetectMode    (eDetectMode    )
{
    impl_analyze();
}

//_______________________________________________

/**
 */

FrameListAnalyzer::~FrameListAnalyzer()
{
}

//_______________________________________________

/** returns an analyzed list of all currently opened (top!) frames inside the desktop tree.

    We try to get a snapshot of all opened frames, which are part of the desktop frame container.
    Of course we can't access frames, which stands outside of this tree.
    But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last
    frame wrong. Further we analyze this list and split into different parts.
    E.g. for "CloseDoc" we must know, which frames of the given list referr to the same model.
    These frames must be closed then. But all other frames must be untouched.
    In case the request was "CloseWin" these splitted lists can be used too, to decide if the last window
    or document was closed. Then we have to initialize the backing window ...
    Last but not least we must know something about our special help frame. It must be handled
    seperatly. And last but not least - the backing component frame must be detected too.
*/

void FrameListAnalyzer::impl_analyze()
{
    // reset all members to get a consistent state
    m_bReferenceIsHidden  = sal_False;
    m_bReferenceIsHelp    = sal_False;
    m_bReferenceIsBacking = sal_False;
    m_xHelp               = css::uno::Reference< css::frame::XFrame >();
    m_xBackingComponent   = css::uno::Reference< css::frame::XFrame >();

    // try to get the task container by using the given supplier
    css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY);

    // All return list get an initial size to include all possible frames.
    // They will be packed at the end of this method ... using the actual step positions then.
    sal_Int32 nVisibleStep = 0;
    sal_Int32 nHiddenStep  = 0;
    sal_Int32 nModelStep   = 0;
    sal_Int32 nCount       = xFrameContainer->getCount();

    m_lOtherVisibleFrames.realloc(nCount);
    m_lOtherHiddenFrames.realloc(nCount);
    m_lModelFrames.realloc(nCount);

    // ask for the model of the given reference frame.
    // It must be compared with the model of every frame of the container
    // to sort it into the list of frames with the same model.
    // Supress this step, if right detect mode isn't set.
    css::uno::Reference< css::frame::XModel > xReferenceModel;
    if ((m_eDetectMode & E_MODEL) == E_MODEL )
    {
        css::uno::Reference< css::frame::XController > xReferenceController = m_xReferenceFrame->getController();
        if (xReferenceController.is())
            xReferenceModel = xReferenceController->getModel();
    }

    // check, if the reference frame is in hidden mode.
    // But look, if this analyze step is realy needed.
    css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY);
    if (
        ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) &&
        (xSet.is()                             )
       )
    {
        css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);
        aValue >>= m_bReferenceIsHidden;
    }

    // check, if the reference frame includes the backing component.
    // But look, if this analyze step is realy needed.
    if (
        ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) &&
        (xSet.is()                                                 )
       )
    {
        css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISBACKINGMODE);
        aValue >>= m_bReferenceIsBacking;
    }

    // check, if the reference frame includes the help module.
    // But look, if this analyze step is realy needed.
    if (
        ((m_eDetectMode & E_HELP)     == E_HELP                ) &&
        (m_xReferenceFrame.is()                                ) &&
        (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK)
       )
    {
        m_bReferenceIsHelp = sal_True;
    }

    try
    {
        // Step over all frames of the desktop frame container and analyze it.
        for (sal_Int32 i=0; i<nCount; ++i)
        {
            // Ignore invalid items ... and of course the reference frame.
            // It will be a member of the given frame list too - but it was already
            // analyzed before!
            css::uno::Reference< css::frame::XFrame > xFrame;
            if (
                !(xFrameContainer->getByIndex(i) >>= xFrame) ||
                !(xFrame.is()                              ) ||
                 (xFrame==m_xReferenceFrame                )
               )
                continue;

            #ifdef ENABLE_WARNINGS
            if (
                ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) &&
                (
                 (!xFrame->getContainerWindow().is()) ||
                 (!xFrame->getComponentWindow().is())
                )
               )
            {
                LOG_WARNING("FrameListAnalyzer::impl_analyze()", "ZOMBIE!")
            }
            #endif

            // -------------------------------------------------
            // a) Is it the special help task?
            //    Return it seperated from any return list.
            if (
                ((m_eDetectMode & E_HELP) == E_HELP      ) &&
                (xFrame->getName()==SPECIALTARGET_HELPTASK)
               )
            {
                m_xHelp = xFrame;
                continue;
            }

            // -------------------------------------------------
            // b) Or is includes this task the special backing component?
            //    Return it seperated from any return list.
            //    But check if the reference task itself is the backing frame.
            //    Our user mst know it to decide right.
            if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT)
            {
                xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);
                sal_Bool bIsBacking;

                if (
                    (xSet.is()                                                        ) &&
                    (xSet->getPropertyValue(FRAME_PROPNAME_ISBACKINGMODE)>>=bIsBacking) &&
                    (bIsBacking                                                       )
                   )
                {
                    m_xBackingComponent = xFrame;
                    continue;
                }
            }

            // -------------------------------------------------
            // c) Or is it the a task, which uses the specified model?
            //    Add it to the list of "model frames".
            if ((m_eDetectMode & E_MODEL) == E_MODEL)
            {
                css::uno::Reference< css::frame::XController > xController = xFrame->getController();
                css::uno::Reference< css::frame::XModel >      xModel      ;
                if (xController.is())
                    xModel = xController->getModel();
                if (xModel==xReferenceModel)
                {
                    m_lModelFrames[nModelStep] = xFrame;
                    ++nModelStep;
                    continue;
                }
            }

            // -------------------------------------------------
            // d) Or is it the a task, which use another or no model at all?
            //    Add it to the list of "other frames". But look for it's
            //    visible state ... if it's allowed to do so.
            // -------------------------------------------------
            sal_Bool bHidden = sal_False;
            if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN )
            {
                xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);
                if (xSet.is())
                {
                    css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);
                    aValue >>= bHidden;
                }
            }

            if (bHidden)
            {
                m_lOtherHiddenFrames[nHiddenStep] = xFrame;
                ++nHiddenStep;
            }
            else
            {
                m_lOtherVisibleFrames[nVisibleStep] = xFrame;
                ++nVisibleStep;
            }
        }
    }
    catch(css::lang::IndexOutOfBoundsException)
    {
        // stop copying if index seams to be wrong.
        // This interface can't realy guarantee its count for multithreaded
        // environments. So it can occure!
    }

    // Pack both lists by using the actual step positions.
    // All empty or ignorable items should exist at the end of these lists
    // behind the position pointers. So they will be removed by a reallocation.
    m_lOtherVisibleFrames.realloc(nVisibleStep);
    m_lOtherHiddenFrames.realloc(nHiddenStep);
    m_lModelFrames.realloc(nModelStep);
}

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

#include "classes/framelistanalyzer.hxx"

//_______________________________________________
//  my own includes

#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_TARGETS_H_
#include <targets.h>
#endif

#ifndef __FRAMEWORK_PROPERTIES_H_
#include <properties.h>
#endif

#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif

//_______________________________________________
//  interface includes

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _DRAFTS_COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <drafts/com/sun/star/frame/XModuleManager.hpp>
#endif

//_______________________________________________
//  includes of other projects

#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <unotools/processfactory.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//_______________________________________________
//  namespace

namespace framework{

//_______________________________________________
//  non exported const

//_______________________________________________
//  non exported definitions

//_______________________________________________
//  declarations

//_______________________________________________

/**
 */

FrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier       ,
                                      const css::uno::Reference< css::frame::XFrame >&          xReferenceFrame ,
                                            sal_uInt32                                          eDetectMode     )
    : m_xSupplier      (xSupplier      )
    , m_xReferenceFrame(xReferenceFrame)
    , m_eDetectMode    (eDetectMode    )
{
    impl_analyze();
}

//_______________________________________________

/**
 */

FrameListAnalyzer::~FrameListAnalyzer()
{
}

//_______________________________________________

/** returns an analyzed list of all currently opened (top!) frames inside the desktop tree.

    We try to get a snapshot of all opened frames, which are part of the desktop frame container.
    Of course we can't access frames, which stands outside of this tree.
    But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last
    frame wrong. Further we analyze this list and split into different parts.
    E.g. for "CloseDoc" we must know, which frames of the given list referr to the same model.
    These frames must be closed then. But all other frames must be untouched.
    In case the request was "CloseWin" these splitted lists can be used too, to decide if the last window
    or document was closed. Then we have to initialize the backing window ...
    Last but not least we must know something about our special help frame. It must be handled
    seperatly. And last but not least - the backing component frame must be detected too.
*/

void FrameListAnalyzer::impl_analyze()
{
    // reset all members to get a consistent state
    m_bReferenceIsHidden  = sal_False;
    m_bReferenceIsHelp    = sal_False;
    m_bReferenceIsBacking = sal_False;
    m_xHelp               = css::uno::Reference< css::frame::XFrame >();
    m_xBackingComponent   = css::uno::Reference< css::frame::XFrame >();

    // try to get the task container by using the given supplier
    css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY);

    // All return list get an initial size to include all possible frames.
    // They will be packed at the end of this method ... using the actual step positions then.
    sal_Int32 nVisibleStep = 0;
    sal_Int32 nHiddenStep  = 0;
    sal_Int32 nModelStep   = 0;
    sal_Int32 nCount       = xFrameContainer->getCount();

    m_lOtherVisibleFrames.realloc(nCount);
    m_lOtherHiddenFrames.realloc(nCount);
    m_lModelFrames.realloc(nCount);

    // ask for the model of the given reference frame.
    // It must be compared with the model of every frame of the container
    // to sort it into the list of frames with the same model.
    // Supress this step, if right detect mode isn't set.
    css::uno::Reference< css::frame::XModel > xReferenceModel;
    if ((m_eDetectMode & E_MODEL) == E_MODEL )
    {
        css::uno::Reference< css::frame::XController > xReferenceController = m_xReferenceFrame->getController();
        if (xReferenceController.is())
            xReferenceModel = xReferenceController->getModel();
    }

    // check, if the reference frame is in hidden mode.
    // But look, if this analyze step is realy needed.
    css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY);
    if (
        ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) &&
        (xSet.is()                             )
       )
    {
        css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);
        aValue >>= m_bReferenceIsHidden;
    }

    // check, if the reference frame includes the backing component.
    // But look, if this analyze step is realy needed.
    if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT)
    {
        try
        {
            css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory();
            css::uno::Reference< dcss::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY);
            ::rtl::OUString sModule = xModuleMgr->identify(m_xReferenceFrame);
            m_bReferenceIsBacking = (sModule.equals(SERVICENAME_STARTMODULE));
        }
        catch(const css::uno::Exception&)
            {}
    }

    // check, if the reference frame includes the help module.
    // But look, if this analyze step is realy needed.
    if (
        ((m_eDetectMode & E_HELP)     == E_HELP                ) &&
        (m_xReferenceFrame.is()                                ) &&
        (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK)
       )
    {
        m_bReferenceIsHelp = sal_True;
    }

    try
    {
        // Step over all frames of the desktop frame container and analyze it.
        for (sal_Int32 i=0; i<nCount; ++i)
        {
            // Ignore invalid items ... and of course the reference frame.
            // It will be a member of the given frame list too - but it was already
            // analyzed before!
            css::uno::Reference< css::frame::XFrame > xFrame;
            if (
                !(xFrameContainer->getByIndex(i) >>= xFrame) ||
                !(xFrame.is()                              ) ||
                 (xFrame==m_xReferenceFrame                )
               )
                continue;

            #ifdef ENABLE_WARNINGS
            if (
                ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) &&
                (
                 (!xFrame->getContainerWindow().is()) ||
                 (!xFrame->getComponentWindow().is())
                )
               )
            {
                LOG_WARNING("FrameListAnalyzer::impl_analyze()", "ZOMBIE!")
            }
            #endif

            // -------------------------------------------------
            // a) Is it the special help task?
            //    Return it seperated from any return list.
            if (
                ((m_eDetectMode & E_HELP) == E_HELP      ) &&
                (xFrame->getName()==SPECIALTARGET_HELPTASK)
               )
            {
                m_xHelp = xFrame;
                continue;
            }

            // -------------------------------------------------
            // b) Or is includes this task the special backing component?
            //    Return it seperated from any return list.
            //    But check if the reference task itself is the backing frame.
            //    Our user mst know it to decide right.
            if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT)
            {
                try
                {
                    css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory();
                    css::uno::Reference< dcss::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY);
                    ::rtl::OUString sModule = xModuleMgr->identify(xFrame);
                    if (sModule.equals(SERVICENAME_STARTMODULE))
                    {
                        m_xBackingComponent = xFrame;
                        continue;
                    }
                }
                catch(const css::uno::Exception&)
                    {}
            }

            // -------------------------------------------------
            // c) Or is it the a task, which uses the specified model?
            //    Add it to the list of "model frames".
            if ((m_eDetectMode & E_MODEL) == E_MODEL)
            {
                css::uno::Reference< css::frame::XController > xController = xFrame->getController();
                css::uno::Reference< css::frame::XModel >      xModel      ;
                if (xController.is())
                    xModel = xController->getModel();
                if (xModel==xReferenceModel)
                {
                    m_lModelFrames[nModelStep] = xFrame;
                    ++nModelStep;
                    continue;
                }
            }

            // -------------------------------------------------
            // d) Or is it the a task, which use another or no model at all?
            //    Add it to the list of "other frames". But look for it's
            //    visible state ... if it's allowed to do so.
            // -------------------------------------------------
            sal_Bool bHidden = sal_False;
            if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN )
            {
                xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);
                if (xSet.is())
                {
                    css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);
                    aValue >>= bHidden;
                }
            }

            if (bHidden)
            {
                m_lOtherHiddenFrames[nHiddenStep] = xFrame;
                ++nHiddenStep;
            }
            else
            {
                m_lOtherVisibleFrames[nVisibleStep] = xFrame;
                ++nVisibleStep;
            }
        }
    }
    catch(css::lang::IndexOutOfBoundsException)
    {
        // stop copying if index seams to be wrong.
        // This interface can't realy guarantee its count for multithreaded
        // environments. So it can occure!
    }

    // Pack both lists by using the actual step positions.
    // All empty or ignorable items should exist at the end of these lists
    // behind the position pointers. So they will be removed by a reallocation.
    m_lOtherVisibleFrames.realloc(nVisibleStep);
    m_lOtherHiddenFrames.realloc(nHiddenStep);
    m_lModelFrames.realloc(nModelStep);
}

} //  namespace framework
<|endoftext|>


<commit_before>//
// Functions to process built-in commands for ccons.
//
// Part of ccons, the interactive console for the C programming language.
//
// Copyright (c) 2009 Alexei Svitkine. This file is distributed under the
// terms of MIT Open Source License. See file LICENSE for details.
//

#include "InternalCommands.h"
#include "StringUtils.h"

#include <string.h>

#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/Path.h>

namespace ccons {

// Prints the help text.
static void HandleHelpCommand(const char *arg, bool debugMode,
                              std::ostream& out, std::ostream& err)
{
	oprintf(out, "The following commands are available:\n");
	oprintf(out, "  :help - displays this message\n");
	oprintf(out, "  :load <library path> - dynamically loads specified library\n");
	oprintf(out, "  :version - displays ccons version information\n");
}

// Prints the version text.
static void HandleVersionCommand(const char *arg, bool debugMode,
                                std::ostream& out, std::ostream& err)
{
	PrintVersionInformation(out);
}

// Loads the library that was specified.
static void HandleLoadCommand(const char *arg, bool debugMode,
                              std::ostream& out, std::ostream& err)
{
	if (debugMode)
		oprintf(err, "Attempting to load external library '%s'.\n", arg);

	llvm::sys::Path path(arg);
	if (path.isDynamicLibrary()) {
		std::string errMsg;
		llvm::sys::DynamicLibrary::LoadLibraryPermanently(arg, &errMsg);
		if (!errMsg.empty()) {
			oprintf(err, "Error: %s\n", errMsg.c_str());
		} else {
			oprintf(out, "Dynamic library loaded.\n");
		}
	} else {
		oprintf(out, "No dynamic library found at the specified path.\n");
	}
}

// Handle an internal command if it was specified. If handled, returns
// true; otherwise the input did not correspond to an internal command.
bool HandleInternalCommand(const char *input, bool debugMode,
                           std::ostream& out, std::ostream& err)
{
	while (isspace(*input)) input++;

	if (*input == ':') {
		struct {
			const char *name;
			void (*handler)(const char *arg, bool debugMode,
			                std::ostream& out, std::ostream& err);
		}	commands[] = {
			{ "help",    HandleHelpCommand    },
			{ "version", HandleVersionCommand },
			{ "load",    HandleLoadCommand    },
		};
		const unsigned commandCount = sizeof(commands)/sizeof(commands[0]);
		input++;
		for (unsigned i = 0; i < commandCount; i++) {
			const unsigned nameLength = strlen(commands[i].name);
			if (!strncmp(input, commands[i].name, nameLength) &&
			    (input[nameLength] == '\0' || isspace(input[nameLength]))) {
				int index = nameLength + 1;
				while (isspace(input[index])) index++;
				int length = strlen(input + index);
				while (length > 0 && isspace(input[index + length - 1]))
					length--;
				std::string args(&input[index], length);
				commands[i].handler(args.c_str(), debugMode, out, err);
				return true;
			}
		}
	}
	return false;
}

// Prints ccons version information to the specified ostream.
void PrintVersionInformation(std::ostream& out)
{
	oprintf(out, "ccons version 0.1 by Alexei Svitkine\n");
	oprintf(out, "Interactive Console for the C Programming Language\n");
	oprintf(out, "http://code.google.com/p/ccons\n");
}

// Prints ccons version information to std::out.
void PrintVersionInformation()
{
	PrintVersionInformation(std::cout);
}

} // namespace ccons
<commit_msg>fix build with new llvm<commit_after>//
// Functions to process built-in commands for ccons.
//
// Part of ccons, the interactive console for the C programming language.
//
// Copyright (c) 2009 Alexei Svitkine. This file is distributed under the
// terms of MIT Open Source License. See file LICENSE for details.
//

#include "InternalCommands.h"
#include "StringUtils.h"

#include <string.h>

#include <llvm/ADT/StringRef.h>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/Path.h>

namespace ccons {

// Prints the help text.
static void HandleHelpCommand(const char *arg, bool debugMode,
                              std::ostream& out, std::ostream& err)
{
	oprintf(out, "The following commands are available:\n");
	oprintf(out, "  :help - displays this message\n");
	oprintf(out, "  :load <library path> - dynamically loads specified library\n");
	oprintf(out, "  :version - displays ccons version information\n");
}

// Prints the version text.
static void HandleVersionCommand(const char *arg, bool debugMode,
                                std::ostream& out, std::ostream& err)
{
	PrintVersionInformation(out);
}

// Loads the library that was specified.
static void HandleLoadCommand(const char *arg, bool debugMode,
                              std::ostream& out, std::ostream& err)
{
	if (debugMode)
		oprintf(err, "Attempting to load external library '%s'.\n", arg);

	llvm::sys::Path path(arg);
	if (path.isDynamicLibrary()) {
		std::string errMsg;
		llvm::sys::DynamicLibrary::LoadLibraryPermanently(arg, &errMsg);
		if (!errMsg.empty()) {
			oprintf(err, "Error: %s\n", errMsg.c_str());
		} else {
			oprintf(out, "Dynamic library loaded.\n");
		}
	} else {
		oprintf(out, "No dynamic library found at the specified path.\n");
	}
}

// Handle an internal command if it was specified. If handled, returns
// true; otherwise the input did not correspond to an internal command.
bool HandleInternalCommand(const char *input, bool debugMode,
                           std::ostream& out, std::ostream& err)
{
	while (isspace(*input)) input++;

	if (*input == ':') {
		struct {
			const char *name;
			void (*handler)(const char *arg, bool debugMode,
			                std::ostream& out, std::ostream& err);
		}	commands[] = {
			{ "help",    HandleHelpCommand    },
			{ "version", HandleVersionCommand },
			{ "load",    HandleLoadCommand    },
		};
		const unsigned commandCount = sizeof(commands)/sizeof(commands[0]);
		input++;
		for (unsigned i = 0; i < commandCount; i++) {
			const unsigned nameLength = strlen(commands[i].name);
			if (!strncmp(input, commands[i].name, nameLength) &&
			    (input[nameLength] == '\0' || isspace(input[nameLength]))) {
				int index = nameLength + 1;
				while (isspace(input[index])) index++;
				int length = strlen(input + index);
				while (length > 0 && isspace(input[index + length - 1]))
					length--;
				std::string args(&input[index], length);
				commands[i].handler(args.c_str(), debugMode, out, err);
				return true;
			}
		}
	}
	return false;
}

// Prints ccons version information to the specified ostream.
void PrintVersionInformation(std::ostream& out)
{
	oprintf(out, "ccons version 0.1 by Alexei Svitkine\n");
	oprintf(out, "Interactive Console for the C Programming Language\n");
	oprintf(out, "http://code.google.com/p/ccons\n");
}

// Prints ccons version information to std::out.
void PrintVersionInformation()
{
	PrintVersionInformation(std::cout);
}

} // namespace ccons
<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed in accordance with the terms specified in
 *  the LICENSE file found in the root directory of this source tree.
 */

#ifdef __linux__
// Needed for linux specific RUSAGE_THREAD, before including anything else
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#endif

#include <cerrno>
#include <cstdint>
#include <cstring>

#include <sys/resource.h>
#include <sys/time.h>

#include <boost/format.hpp>
#include <boost/io/detail/quoted_manip.hpp>

#include <osquery/killswitch.h>
#include <osquery/logger.h>
#include <osquery/numeric_monitoring.h>
#include <osquery/profiler/code_profiler.h>

namespace osquery {
namespace {

void record(const std::vector<std::string>& names,
            const std::string& metricName,
            monitoring::ValueType measurement) {
  for (const std::string& name : names) {
    const std::string entity = name + "." + metricName;
    monitoring::record(
        entity, measurement, monitoring::PreAggregationType::Min, true);

    monitoring::record(
        entity, measurement, monitoring::PreAggregationType::Sum, true);
  }
}

int getRusageWho() {
  return
#ifdef __linux__
      RUSAGE_THREAD; // Linux supports more granular profiling
#else
      RUSAGE_SELF;
#endif
}

enum class RusageError { FatalError = 1 };

static Expected<struct rusage, RusageError> callRusage() {
  struct rusage stats;
  const int who = getRusageWho();
  auto rusage_status = getrusage(who, &stats);
  if (rusage_status != -1) {
    return stats;
  } else {
    return createError(RusageError::FatalError)
           << "Linux query profiling failed. error code: " << rusage_status
           << " message: " << boost::io::quoted(strerror(errno));
  }
}

void recordRusageStatDifference(const std::vector<std::string>& names,
                                const std::string& stat_name,
                                int64_t start_stat,
                                int64_t end_stat) {
  if (end_stat == 0) {
    TLOG << "rusage field " << boost::io::quoted(stat_name)
         << " is not supported";
  } else if (start_stat <= end_stat) {
    record(names, stat_name, end_stat - start_stat);
  } else {
    LOG(WARNING) << "Possible overflow detected in rusage field: "
                 << boost::io::quoted(stat_name);
  }
}

void recordRusageStatDifference(const std::vector<std::string>& names,
                                const std::string& stat_name,
                                const struct timeval& start_stat,
                                const struct timeval& end_stat) {
  recordRusageStatDifference(
      names,
      stat_name + ".millis",
      std::chrono::duration_cast<std::chrono::milliseconds>(
          std::chrono::seconds(start_stat.tv_sec) +
          std::chrono::microseconds(start_stat.tv_usec))
          .count(),
      std::chrono::duration_cast<std::chrono::milliseconds>(
          std::chrono::seconds(end_stat.tv_sec) +
          std::chrono::microseconds(end_stat.tv_usec))
          .count());
}

void recordRusageStatDifference(const std::vector<std::string>& names,
                                const struct rusage& start_stats,
                                const struct rusage& end_stats) {
  recordRusageStatDifference(names, "rss.max.kb", 0, end_stats.ru_maxrss);

  recordRusageStatDifference(
      names, "rss.increase.kb", start_stats.ru_maxrss, end_stats.ru_maxrss);

  recordRusageStatDifference(
      names, "input.load", start_stats.ru_inblock, end_stats.ru_inblock);

  recordRusageStatDifference(
      names, "output.load", start_stats.ru_oublock, end_stats.ru_oublock);

  recordRusageStatDifference(
      names, "time.user", start_stats.ru_utime, end_stats.ru_utime);

  recordRusageStatDifference(
      names, "time.system", start_stats.ru_stime, end_stats.ru_stime);
}

} // namespace

class CodeProfiler::CodeProfilerData {
 public:
  CodeProfilerData()
      : rusage_data_(callRusage()),
        wall_time_(std::chrono::steady_clock::now()) {}

  const std::chrono::time_point<std::chrono::steady_clock>& getWallTime() {
    return wall_time_;
  }
  Expected<struct rusage, RusageError> takeRusageData() {
    return std::move(rusage_data_);
  }

 private:
  Expected<struct rusage, RusageError> rusage_data_;
  std::chrono::time_point<std::chrono::steady_clock> wall_time_;
};

CodeProfiler::CodeProfiler(const std::initializer_list<std::string>& names)
    : names_(names), code_profiler_data_(new CodeProfilerData()) {}

CodeProfiler::~CodeProfiler() {
  if (Killswitch::get().isPosixProfilingEnabled()) {
    CodeProfilerData code_profiler_data_end;

    auto rusage_start = code_profiler_data_->takeRusageData();
    if (!rusage_start) {
      LOG(ERROR) << "rusage_start error: "
                 << rusage_start.getError().getMessage();
    } else {
      auto rusage_end = code_profiler_data_end.takeRusageData();
      if (!rusage_end) {
        LOG(ERROR) << "rusage_end error: "
                   << rusage_end.getError().getMessage();
      } else {
        recordRusageStatDifference(names_, *rusage_start, *rusage_end);
      }
    }

    const auto query_duration =
        std::chrono::duration_cast<std::chrono::milliseconds>(
            code_profiler_data_end.getWallTime() -
            code_profiler_data_->getWallTime());
    record(names_, "time.wall.millis", query_duration.count());
  }
}

} // namespace osquery
<commit_msg>Total(user+kernel) time ODS timeseries<commit_after>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed in accordance with the terms specified in
 *  the LICENSE file found in the root directory of this source tree.
 */

#ifdef __linux__
// Needed for linux specific RUSAGE_THREAD, before including anything else
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#endif

#include <cerrno>
#include <cstdint>
#include <cstring>

#include <sys/resource.h>
#include <sys/time.h>

#include <boost/format.hpp>
#include <boost/io/detail/quoted_manip.hpp>

#include <osquery/killswitch.h>
#include <osquery/logger.h>
#include <osquery/numeric_monitoring.h>
#include <osquery/profiler/code_profiler.h>

namespace osquery {
namespace {

void record(const std::vector<std::string>& names,
            const std::string& metricName,
            monitoring::ValueType measurement) {
  for (const std::string& name : names) {
    const std::string entity = name + "." + metricName;
    monitoring::record(
        entity, measurement, monitoring::PreAggregationType::Min, true);

    monitoring::record(
        entity, measurement, monitoring::PreAggregationType::Sum, true);
  }
}

int getRusageWho() {
  return
#ifdef __linux__
      RUSAGE_THREAD; // Linux supports more granular profiling
#else
      RUSAGE_SELF;
#endif
}

enum class RusageError { FatalError = 1 };

static Expected<struct rusage, RusageError> callRusage() {
  struct rusage stats;
  const int who = getRusageWho();
  auto rusage_status = getrusage(who, &stats);
  if (rusage_status != -1) {
    return stats;
  } else {
    return createError(RusageError::FatalError)
           << "Linux query profiling failed. error code: " << rusage_status
           << " message: " << boost::io::quoted(strerror(errno));
  }
}

void recordRusageStatDifference(const std::vector<std::string>& names,
                                const std::string& stat_name,
                                int64_t start_stat,
                                int64_t end_stat) {
  if (end_stat == 0) {
    TLOG << "rusage field " << boost::io::quoted(stat_name)
         << " is not supported";
  } else if (start_stat <= end_stat) {
    record(names, stat_name, end_stat - start_stat);
  } else {
    LOG(WARNING) << "Possible overflow detected in rusage field: "
                 << boost::io::quoted(stat_name);
  }
}

int64_t covertToMilliseconds(const struct timeval& timepoint) {
  return std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::seconds(timepoint.tv_sec) +
             std::chrono::microseconds(timepoint.tv_usec))
      .count();
}

void recordRusageStatDifference(const std::vector<std::string>& names,
                                const std::string& stat_name,
                                const struct timeval& start_stat,
                                const struct timeval& end_stat) {
  recordRusageStatDifference(names,
                             stat_name + ".millis",
                             covertToMilliseconds(start_stat),
                             covertToMilliseconds(end_stat));
}

void recordRusageStatDifference(const std::vector<std::string>& names,
                                const struct rusage& start_stats,
                                const struct rusage& end_stats) {
  recordRusageStatDifference(names, "rss.max.kb", 0, end_stats.ru_maxrss);

  recordRusageStatDifference(
      names, "rss.increase.kb", start_stats.ru_maxrss, end_stats.ru_maxrss);

  recordRusageStatDifference(
      names, "input.load", start_stats.ru_inblock, end_stats.ru_inblock);

  recordRusageStatDifference(
      names, "output.load", start_stats.ru_oublock, end_stats.ru_oublock);

  recordRusageStatDifference(
      names, "time.user", start_stats.ru_utime, end_stats.ru_utime);

  recordRusageStatDifference(
      names, "time.system", start_stats.ru_stime, end_stats.ru_stime);

  recordRusageStatDifference(names,
                             "time.total.millis",
                             covertToMilliseconds(start_stats.ru_utime) +
                                 covertToMilliseconds(start_stats.ru_stime),
                             covertToMilliseconds(end_stats.ru_utime) +
                                 covertToMilliseconds(end_stats.ru_stime));
}

} // namespace

class CodeProfiler::CodeProfilerData {
 public:
  CodeProfilerData()
      : rusage_data_(callRusage()),
        wall_time_(std::chrono::steady_clock::now()) {}

  const std::chrono::time_point<std::chrono::steady_clock>& getWallTime() {
    return wall_time_;
  }
  Expected<struct rusage, RusageError> takeRusageData() {
    return std::move(rusage_data_);
  }

 private:
  Expected<struct rusage, RusageError> rusage_data_;
  std::chrono::time_point<std::chrono::steady_clock> wall_time_;
};

CodeProfiler::CodeProfiler(const std::initializer_list<std::string>& names)
    : names_(names), code_profiler_data_(new CodeProfilerData()) {}

CodeProfiler::~CodeProfiler() {
  if (Killswitch::get().isPosixProfilingEnabled()) {
    CodeProfilerData code_profiler_data_end;

    auto rusage_start = code_profiler_data_->takeRusageData();
    if (!rusage_start) {
      LOG(ERROR) << "rusage_start error: "
                 << rusage_start.getError().getMessage();
    } else {
      auto rusage_end = code_profiler_data_end.takeRusageData();
      if (!rusage_end) {
        LOG(ERROR) << "rusage_end error: "
                   << rusage_end.getError().getMessage();
      } else {
        recordRusageStatDifference(names_, *rusage_start, *rusage_end);
      }
    }

    const auto query_duration =
        std::chrono::duration_cast<std::chrono::milliseconds>(
            code_profiler_data_end.getWallTime() -
            code_profiler_data_->getWallTime());
    record(names_, "time.wall.millis", query_duration.count());
  }
}

} // namespace osquery
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: comm_bas.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 00:26:33 $
 *
 *  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 _COMM_BAS_HXX
#define _COMM_BAS_HXX

#ifndef __SBX_SBX_FACTORY_HXX //autogen
#include <basic/sbxfac.hxx>
#endif
#ifndef __SBX_SBXVARIABLE_HXX //autogen
#include <basic/sbxvar.hxx>
#endif
#ifndef _SBX_SBXOBJECT_HXX //autogen
#include <basic/sbxobj.hxx>
#endif

class CommunicationManagerClientViaSocket;
class CommunicationLink;

class CommunicationWrapper : public SbxObject   // Einer fr Manager und Links
{
    // Definition eines Tabelleneintrags. Dies wird hier gemacht,
    // da dadurch die Methoden und Properties als private deklariert
    // werden koennen.
#if defined ( ICC ) || defined ( HPUX ) || defined ( C50 ) || defined ( C52 )
public:
#endif
    typedef void( CommunicationWrapper::*pMeth )
        ( SbxVariable* pThis, SbxArray* pArgs, BOOL bWrite );
#if defined ( ICC ) || defined ( HPUX )
private:
#endif

    struct Methods {
        const char* pName;      // Name des Eintrags
        SbxDataType eType;      // Datentyp
        short nArgs;            // Argumente und Flags
        pMeth pFunc;            // Function Pointer
    };
    static Methods aManagerMethods[];   // Methodentabelle
    static Methods aLinkMethods[];      // Methodentabelle
    Methods *m_pMethods;    // Aktuelle Methodentabelle

    // Methoden
    //      Manager
    void MStartCommunication( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void MStopAllCommunication( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void MIsCommunicationRunning( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void MGetMyName( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void MIsLinkValid( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void MSetCommunicationEventHandler( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );

    //      Link
    void LStopCommunication( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void LGetMyName( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void LGetHostName( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void LSend( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void LGetString( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );

    // Interne Member und Methoden
    CommunicationManagerClientViaSocket *m_pManager;
    CommunicationLink *m_pLink;
    BOOL m_bIsManager;  // Ist es kein Manager, so ist es ein Link

    // Kram fr Manager
    DECL_LINK( Open, CommunicationLink* );
    DECL_LINK( Close, CommunicationLink* );
    DECL_LINK( Data, CommunicationLink* );
    void Events( String aType, CommunicationLink* pLink );
    BOOL m_bCatchOpen;
    CommunicationLink *m_pNewLink;
    String m_aEventHandlerName;

    using SbxVariable::GetInfo;
    // Infoblock auffuellen
    SbxInfo* GetInfo( short nIdx );

    // Broadcaster Notification
    virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
                             const SfxHint& rHint, const TypeId& rHintType );
public:
    CommunicationWrapper( const String& );
    CommunicationWrapper( CommunicationLink *pThisLink );
    ~CommunicationWrapper();
    // Suchen eines Elements
    virtual SbxVariable* Find( const String&, SbxClassType );

    CommunicationLink* GetCommunicationLink() { return m_pLink; }
};

// Die dazugehoerige Factory:

class CommunicationFactory : public SbxFactory
{
public:
    virtual SbxObject* CreateObject( const String& );
};

#endif
<commit_msg>INTEGRATION: CWS sb59 (1.4.12); FILE MERGED 2006/08/16 14:46:07 sb 1.4.12.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: comm_bas.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 11:18:45 $
 *
 *  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 _COMM_BAS_HXX
#define _COMM_BAS_HXX

#ifndef __SBX_SBX_FACTORY_HXX //autogen
#include <basic/sbxfac.hxx>
#endif
#ifndef __SBX_SBXVARIABLE_HXX //autogen
#include <basic/sbxvar.hxx>
#endif
#ifndef _SBX_SBXOBJECT_HXX //autogen
#include <basic/sbxobj.hxx>
#endif

class CommunicationManagerClientViaSocket;
class CommunicationLink;

class CommunicationWrapper : public SbxObject   // Einer fr Manager und Links
{
    // Definition eines Tabelleneintrags. Dies wird hier gemacht,
    // da dadurch die Methoden und Properties als private deklariert
    // werden koennen.
#if defined ( ICC ) || defined ( HPUX ) || defined ( C50 ) || defined ( C52 )
public:
#endif
    typedef void( CommunicationWrapper::*pMeth )
        ( SbxVariable* pThis, SbxArray* pArgs, BOOL bWrite );
#if defined ( ICC ) || defined ( HPUX )
private:
#endif

    struct Methods {
        const char* pName;      // Name des Eintrags
        SbxDataType eType;      // Datentyp
        pMeth pFunc;            // Function Pointer
        short nArgs;            // Argumente und Flags
    };
    static Methods aManagerMethods[];   // Methodentabelle
    static Methods aLinkMethods[];      // Methodentabelle
    Methods *m_pMethods;    // Aktuelle Methodentabelle

    // Methoden
    //      Manager
    void MStartCommunication( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void MStopAllCommunication( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void MIsCommunicationRunning( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void MGetMyName( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void MIsLinkValid( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void MSetCommunicationEventHandler( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );

    //      Link
    void LStopCommunication( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void LGetMyName( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void LGetHostName( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void LSend( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );
    void LGetString( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite );

    // Interne Member und Methoden
    CommunicationManagerClientViaSocket *m_pManager;
    CommunicationLink *m_pLink;
    BOOL m_bIsManager;  // Ist es kein Manager, so ist es ein Link

    // Kram fr Manager
    DECL_LINK( Open, CommunicationLink* );
    DECL_LINK( Close, CommunicationLink* );
    DECL_LINK( Data, CommunicationLink* );
    void Events( String aType, CommunicationLink* pLink );
    BOOL m_bCatchOpen;
    CommunicationLink *m_pNewLink;
    String m_aEventHandlerName;

    using SbxVariable::GetInfo;
    // Infoblock auffuellen
    SbxInfo* GetInfo( short nIdx );

    // Broadcaster Notification
    virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
                             const SfxHint& rHint, const TypeId& rHintType );
public:
    CommunicationWrapper( const String& );
    CommunicationWrapper( CommunicationLink *pThisLink );
    ~CommunicationWrapper();
    // Suchen eines Elements
    virtual SbxVariable* Find( const String&, SbxClassType );

    CommunicationLink* GetCommunicationLink() { return m_pLink; }
};

// Die dazugehoerige Factory:

class CommunicationFactory : public SbxFactory
{
public:
    virtual SbxObject* CreateObject( const String& );
};

#endif
<|endoftext|>


<commit_before>/// PrecompData_test.cpp

/** Test the PrecompData class
 */

#include "PrecompData.h"
#include <cmath>
#include <vector>

using namespace std;

float TestFunc(float y) {
	return sin(y);
}

int main()
{
	using namespace Utilities;

	const std::string funcName = "TestFunc";

	PrecompData<float> itp1("TestFunc");
	PrecompData<float> itp2(funcName);
	//itp.SetComment("TestFunc approximation");

	//itp.Set(&TestFunc, 0.0, 6.28, 10);

	return 0;
}

<commit_msg>- Added Test 1.<commit_after>/// PrecompData_test.cpp

/** Test the PrecompData class
 */

#include "PrecompData.h"
#include <cmath>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

float TestFunc(float x) {
	return sin(x);
}

int main()
{
	using namespace Utilities;

	{ // Test 1
		const string funcName = "TestFunc";
		PrecompData<float> itp(funcName);
		itp.SetComment("TestFunc approximation");
		const float x0 = 0.0f, x1 = 6.28f;
		const int nValues = 10;
		const float step = (x1 - x0)/nValues;
		itp.Set(&TestFunc, x0, x1, nValues);
		float x = x0;
		for(int i = 0; i < nValues; ++i) {
			cout << i << ":\t" << funcName << "(" << x << ") = " << TestFunc(x) << " ~ " << itp(x) << endl;
			x += step;
		}
	}

	return 0;
}

<|endoftext|>