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

#ifndef DBA_XMLEXPORT_HXX
#define DBA_XMLEXPORT_HXX

#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _UNOTOOLS_TEMPFILE_HXX
#include <unotools/tempfile.hxx>
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif
#ifndef _UNTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif

#include <memory>

namespace dbaxml
{
using namespace ::xmloff::token;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::xml::sax;
// -------------
// - ODBExport -
// -------------
#define PROGRESS_BAR_STEP 20

class ODBExport : public SvXMLExport
{
    typedef ::std::pair< ::rtl::OUString ,::rtl::OUString> TStringPair;
    struct TDelimiter
    {
        ::rtl::OUString sText;
        ::rtl::OUString sField;
        ::rtl::OUString sDecimal;
        ::rtl::OUString sThousand;
        bool            bUsed;

        TDelimiter() : bUsed( false ) { }
    };
    typedef ::std::map< Reference<XPropertySet> ,::rtl::OUString > TPropertyStyleMap;

    ::std::auto_ptr< TStringPair >                  m_aAutoIncrement;
    ::std::auto_ptr< TDelimiter >                   m_aDelimiter;
    ::std::vector< Any>                             m_aDataSourceSettings;
    TPropertyStyleMap                               m_aAutoStyleNames;
    ::rtl::OUString                                 m_sCharSet;
    UniReference < SvXMLExportPropertyMapper>       m_xExportHelper;
    UniReference < SvXMLExportPropertyMapper>       m_xColumnExportHelper;

    mutable UniReference < XMLPropertySetMapper >   m_xTableStylesPropertySetMapper;
    mutable UniReference < XMLPropertySetMapper >   m_xColumnStylesPropertySetMapper;
    Reference<XPropertySet>                         m_xDataSource;
    sal_Bool                                        m_bAllreadyFilled;

    void                    exportDataSource();
    void                    exportLogin();
    void                    exportSequence(const Sequence< ::rtl::OUString>& _aValue
                                        ,::xmloff::token::XMLTokenEnum _eTokenFilter
                                        ,::xmloff::token::XMLTokenEnum _eTokenType);
    void                    exportDelimiter();
    void                    exportAutoIncrement();
    void                    exportCharSet();
    void                    exportDataSourceSettings();
    void                    exportForms();
    void                    exportReports();
    void                    exportQueries(sal_Bool _bExportContext);
    void                    exportTables(sal_Bool _bExportContext);
    void                    exportStyleName(XPropertySet* _xProp,SvXMLAttributeList& _rAtt);
    void                    exportCollection(const Reference< XNameAccess >& _xCollection
                                            ,enum ::xmloff::token::XMLTokenEnum _eComponents
                                            ,enum ::xmloff::token::XMLTokenEnum _eSubComponents
                                            ,sal_Bool _bExportContext
                                            ,const ::comphelper::mem_fun1_t<ODBExport,XPropertySet* >& _aMemFunc);
    void                    exportComponent(XPropertySet* _xProp);
    void                    exportQuery(XPropertySet* _xProp);
    void                    exportTable(XPropertySet* _xProp);
    void                    exportFilter(XPropertySet* _xProp
                                        ,const ::rtl::OUString& _sProp
                                        ,enum ::xmloff::token::XMLTokenEnum _eStatementType);
    void                    exportTableName(XPropertySet* _xProp,sal_Bool _bUpdate);
    void                    exportAutoStyle(XPropertySet* _xProp);
    void                    exportColumns(const Reference<XColumnsSupplier>& _xColSup);
    void                    collectComponentStyles();

    ::rtl::OUString         implConvertAny(const Any& _rValue);

    UniReference < XMLPropertySetMapper > GetTableStylesPropertySetMapper() const;

private:
                            ODBExport();
protected:

    virtual void                    _ExportStyles( BOOL bUsed );
    virtual void                    _ExportAutoStyles();
    virtual void                    _ExportContent();
    virtual void                    _ExportMasterStyles();
    virtual void                    _ExportFontDecls();
    virtual sal_uInt32              exportDoc( enum ::xmloff::token::XMLTokenEnum eClass );
    virtual SvXMLAutoStylePoolP*    CreateAutoStylePool();

    virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps);
    virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps);

    virtual                 ~ODBExport(){};
public:

    ODBExport(const Reference< XMultiServiceFactory >& _rxMSF, sal_uInt16 nExportFlag = EXPORT_CONTENT | EXPORT_AUTOSTYLES | EXPORT_PRETTY|EXPORT_FONTDECLS);
    // XServiceInfo
    DECLARE_SERVICE_INFO_STATIC( );

    UniReference < XMLPropertySetMapper > GetColumnStylesPropertySetMapper() const;

    // XExporter
    virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    inline Reference<XPropertySet> getDataSource() const { return m_xDataSource; }
};

// -----------------------------------------------------------------------------
} // dbaxml
// -----------------------------------------------------------------------------
#endif // DBA_XMLEXPORT_HXX
<commit_msg>INTEGRATION: CWS dbodf11 (1.7.86); FILE MERGED 2008/01/31 07:47:45 oj 1.7.86.3: #i85757# as odf 1.2 form 2007/10/22 13:03:09 oj 1.7.86.2: RESYNC: (1.7-1.8); FILE MERGED 2007/02/02 12:09:14 oj 1.7.86.1: export ODF format<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlExport.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 16:48:18 $
 *
 *  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 DBA_XMLEXPORT_HXX
#define DBA_XMLEXPORT_HXX

#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _UNOTOOLS_TEMPFILE_HXX
#include <unotools/tempfile.hxx>
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif
#ifndef _UNTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#include "dsntypes.hxx"
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif

#include <memory>

namespace dbaxml
{
using namespace ::xmloff::token;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::xml::sax;
// -------------
// - ODBExport -
// -------------
#define PROGRESS_BAR_STEP 20

class ODBExport : public SvXMLExport
{
    typedef ::std::map< ::xmloff::token::XMLTokenEnum, ::rtl::OUString> TSettingsMap;

    typedef ::std::pair< ::rtl::OUString ,::rtl::OUString> TStringPair;
    struct TDelimiter
    {
        ::rtl::OUString sText;
        ::rtl::OUString sField;
        ::rtl::OUString sDecimal;
        ::rtl::OUString sThousand;
        bool            bUsed;

        TDelimiter() : bUsed( false ) { }
    };
    typedef ::std::map< Reference<XPropertySet> ,::rtl::OUString > TPropertyStyleMap;

    ::std::auto_ptr< TStringPair >                  m_aAutoIncrement;
    ::std::auto_ptr< TDelimiter >                   m_aDelimiter;
    ::std::vector< Any>                             m_aDataSourceSettings;
    TPropertyStyleMap                               m_aAutoStyleNames;
    TPropertyStyleMap                               m_aCellAutoStyleNames;
    TPropertyStyleMap                               m_aRowAutoStyleNames;
    ::rtl::OUString                                 m_sCharSet;
    UniReference < SvXMLExportPropertyMapper>       m_xExportHelper;
    UniReference < SvXMLExportPropertyMapper>       m_xColumnExportHelper;
    UniReference < SvXMLExportPropertyMapper>       m_xCellExportHelper;
    UniReference < SvXMLExportPropertyMapper>       m_xRowExportHelper;

    mutable UniReference < XMLPropertySetMapper >   m_xTableStylesPropertySetMapper;
    mutable UniReference < XMLPropertySetMapper >   m_xColumnStylesPropertySetMapper;
    mutable UniReference < XMLPropertySetMapper >   m_xCellStylesPropertySetMapper;
    mutable UniReference < XMLPropertySetMapper >   m_xRowStylesPropertySetMapper;

    Reference<XPropertySet>                         m_xDataSource;
    ::dbaui::ODsnTypeCollection                     m_aTypeCollection;
    sal_Bool                                        m_bAllreadyFilled;

    void                    exportDataSource();
    void                    exportConnectionData();
    void                    exportDriverSettings(const TSettingsMap& _aSettings);
    void                    exportJavaClassPath(const TSettingsMap& _aSettings);
    void                    exportApplicationConnectionSettings(const TSettingsMap& _aSettings);
    void                    exportLogin();
    void                    exportSequence(const Sequence< ::rtl::OUString>& _aValue
                                        ,::xmloff::token::XMLTokenEnum _eTokenFilter
                                        ,::xmloff::token::XMLTokenEnum _eTokenType);
    void                    exportDelimiter();
    void                    exportAutoIncrement();
    void                    exportCharSet();
    void                    exportDataSourceSettings();
    void                    exportForms();
    void                    exportReports();
    void                    exportQueries(sal_Bool _bExportContext);
    void                    exportTables(sal_Bool _bExportContext);
    void                    exportStyleName(XPropertySet* _xProp,SvXMLAttributeList& _rAtt);
    void                    exportStyleName(const ::xmloff::token::XMLTokenEnum _eToken,const Reference<XPropertySet>& _xProp,SvXMLAttributeList& _rAtt,TPropertyStyleMap& _rMap);
    void                    exportCollection(const Reference< XNameAccess >& _xCollection
                                            ,enum ::xmloff::token::XMLTokenEnum _eComponents
                                            ,enum ::xmloff::token::XMLTokenEnum _eSubComponents
                                            ,sal_Bool _bExportContext
                                            ,const ::comphelper::mem_fun1_t<ODBExport,XPropertySet* >& _aMemFunc);
    void                    exportComponent(XPropertySet* _xProp);
    void                    exportQuery(XPropertySet* _xProp);
    void                    exportTable(XPropertySet* _xProp);
    void                    exportFilter(XPropertySet* _xProp
                                        ,const ::rtl::OUString& _sProp
                                        ,enum ::xmloff::token::XMLTokenEnum _eStatementType);
    void                    exportTableName(XPropertySet* _xProp,sal_Bool _bUpdate);
    void                    exportAutoStyle(XPropertySet* _xProp);
    void                    exportColumns(const Reference<XColumnsSupplier>& _xColSup);
    void                    collectComponentStyles();

    ::rtl::OUString         implConvertAny(const Any& _rValue);

    UniReference < XMLPropertySetMapper > GetTableStylesPropertySetMapper() const;

private:
                            ODBExport();
protected:

    virtual void                    _ExportStyles( BOOL bUsed );
    virtual void                    _ExportAutoStyles();
    virtual void                    _ExportContent();
    virtual void                    _ExportMasterStyles();
    virtual void                    _ExportFontDecls();
    virtual sal_uInt32              exportDoc( enum ::xmloff::token::XMLTokenEnum eClass );
    virtual SvXMLAutoStylePoolP*    CreateAutoStylePool();

    virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps);
    virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps);

    virtual                 ~ODBExport(){};
public:

    ODBExport(const Reference< XMultiServiceFactory >& _rxMSF, sal_uInt16 nExportFlag = EXPORT_CONTENT | EXPORT_AUTOSTYLES | EXPORT_PRETTY|EXPORT_FONTDECLS);
    // XServiceInfo
    DECLARE_SERVICE_INFO_STATIC( );

    UniReference < XMLPropertySetMapper > GetColumnStylesPropertySetMapper() const;
    UniReference < XMLPropertySetMapper > GetCellStylesPropertySetMapper() const;

    // XExporter
    virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    inline Reference<XPropertySet> getDataSource() const { return m_xDataSource; }
};

// -----------------------------------------------------------------------------
} // dbaxml
// -----------------------------------------------------------------------------
#endif // DBA_XMLEXPORT_HXX
<|endoftext|>


<commit_before><commit_msg>patch for xmlfilter.cxx<commit_after><|endoftext|>


<commit_before>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

#include <EveBase/AliEveConfigManager.h>

#include <TInterpreter.h>
#include <TRint.h>
#include <TROOT.h>
#include <TPRegexp.h>
#include <TSystem.h>
#include <TError.h>
#include <RVersion.h>

#include <AliLog.h>

#include <TEveUtil.h>
#include <TEveManager.h>
#include <TEveSelection.h>
#include <TEveBrowser.h>

#include <Getline.h>

int main(int argc, char **argv)
{
  static const TEveException kEH("alihlteve::main");

  if (gSystem->Getenv("ALICE_ROOT") == 0)
  {
    Error(kEH.Data(), "ALICE_ROOT is not defined, aborting.");
    gSystem->Exit(1);
  }

  TString evedir(Form("%s/EVE", gSystem->Getenv("ALICE_ROOT")));

  if (gSystem->AccessPathName(evedir) == kTRUE)
  {
    Error(kEH.Data(), "Directory $ALICE_ROOT/EVE does not exist.");
    gSystem->Exit(1);
  }

  TString macPath(gROOT->GetMacroPath());
  macPath += Form(":%s/macros", evedir.Data());
  gInterpreter->AddIncludePath(evedir);
  if (gSystem->Getenv("ALICE_ROOT") != 0)
  {
    macPath += Form(":%s/alice-macros", evedir.Data());
    gInterpreter->AddIncludePath(Form("%s/EVE", gSystem->Getenv("ALICE_ROOT")));
    gInterpreter->AddIncludePath(Form("%s/PWG0", gSystem->Getenv("ALICE_ROOT")));
    gInterpreter->AddIncludePath(Form("%s/include", gSystem->Getenv("ALICE_ROOT")));
    gInterpreter->AddIncludePath(gSystem->Getenv("ALICE_ROOT"));
  }
  {
    // TabCom fails on double-colon in macro-path.
    // I fixed this in ROOT sometime ago ... could be removed
    // when we go to 5.26.
    TPMERegexp doubleColon(":{2,}", "og");
    doubleColon.Substitute(macPath, ":");
  }
  gROOT->SetMacroPath(macPath);

  // get a logger instance
  //  AliLog *log =  // JMT to fix warning
  AliLog::GetRootLogger();
  TRint  *app = new TRint("App", &argc, argv);

#if ROOT_VERSION_CODE >= ROOT_VERSION(5,25,4) || defined XXX_LATEST_ROOT
  // Waiting for update by Pawel. Now GED in ROOT is better again :)
  // Uncomment when fixed in AliEveGedXXX.
  // TEveGListTreeEditorFrame::SetEditorClass("AliEveGedEditor");
#endif

  TEveManager::Create();
  gEve->GetSelection()->SetPickToSelect(TEveSelection::kPS_PableCompound);
  gEve->GetHighlight()->SetPickToSelect(TEveSelection::kPS_PableCompound);

  gEve->RegisterGeometryAlias("Default", Form("%s/alice-data/default_geo.root", evedir.Data()));

  AliEveConfigManager::InitializeMaster();

  app->Run(kTRUE);

  if (gEve && gEve->GetBrowser())
    gEve->GetBrowser()->UnmapWindow();
  TEveManager::Terminate();

  app->Terminate(0);

  //  delete log;

  return 0;
}
<commit_msg>Coverity fix<commit_after>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

#include <EveBase/AliEveConfigManager.h>

#include <TInterpreter.h>
#include <TRint.h>
#include <TROOT.h>
#include <TPRegexp.h>
#include <TSystem.h>
#include <TError.h>
#include <RVersion.h>

#include <AliLog.h>

#include <TEveUtil.h>
#include <TEveManager.h>
#include <TEveSelection.h>
#include <TEveBrowser.h>

#include <Getline.h>

int main(int argc, char **argv)
{
  static const TEveException kEH("alihlteve::main");

  if (gSystem->Getenv("ALICE_ROOT") == 0)
  {
    Error(kEH.Data(), "ALICE_ROOT is not defined, aborting.");
    gSystem->Exit(1);
  }

  TString evedir(Form("%s/EVE", gSystem->Getenv("ALICE_ROOT")));

  if (gSystem->AccessPathName(evedir) == kTRUE)
  {
    Error(kEH.Data(), "Directory $ALICE_ROOT/EVE does not exist.");
    gSystem->Exit(1);
  }

  TString macPath(gROOT->GetMacroPath());
  macPath += Form(":%s/macros", evedir.Data());
  gInterpreter->AddIncludePath(evedir);
  if (gSystem->Getenv("ALICE_ROOT") != 0)
  {
    macPath += Form(":%s/alice-macros", evedir.Data());
    gInterpreter->AddIncludePath(Form("%s/EVE", gSystem->Getenv("ALICE_ROOT")));
    gInterpreter->AddIncludePath(Form("%s/PWG0", gSystem->Getenv("ALICE_ROOT")));
    gInterpreter->AddIncludePath(Form("%s/include", gSystem->Getenv("ALICE_ROOT")));
    gInterpreter->AddIncludePath(gSystem->Getenv("ALICE_ROOT"));
  }
  {
    // TabCom fails on double-colon in macro-path.
    // I fixed this in ROOT sometime ago ... could be removed
    // when we go to 5.26.
    TPMERegexp doubleColon(":{2,}", "og");
    doubleColon.Substitute(macPath, ":");
  }
  gROOT->SetMacroPath(macPath);

  // get a logger instance
  //  AliLog *log =  // JMT to fix warning
  AliLog::GetRootLogger();
  TRint  *app = new TRint("App", &argc, argv);

#if ROOT_VERSION_CODE >= ROOT_VERSION(5,25,4) || defined XXX_LATEST_ROOT
  // Waiting for update by Pawel. Now GED in ROOT is better again :)
  // Uncomment when fixed in AliEveGedXXX.
  // TEveGListTreeEditorFrame::SetEditorClass("AliEveGedEditor");
#endif

  TEveManager::Create();
  gEve->GetSelection()->SetPickToSelect(TEveSelection::kPS_PableCompound);
  gEve->GetHighlight()->SetPickToSelect(TEveSelection::kPS_PableCompound);

  gEve->RegisterGeometryAlias("Default", Form("%s/alice-data/default_geo.root", evedir.Data()));

	try {AliEveConfigManager::InitializeMaster();}
	catch (TEveException exc) {
		AliErrorGeneral("alihlteve_main",exc.Data());
	}

  app->Run(kTRUE);

  if (gEve && gEve->GetBrowser())
    gEve->GetBrowser()->UnmapWindow();
  TEveManager::Terminate();

  app->Terminate(0);

  //  delete log;

  return 0;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2017, EPL-Vizards
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the EPL-Vizards nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL EPL-Vizards BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*!
 * \file TimeLineModel.cpp
 */

#include "TimeLineModel.hpp"
#include "MainWindow.hpp"
#include "PlotCreator.hpp"
#include "TimeLineWidget.hpp"
using namespace EPL_Viz;
using namespace EPL_DataCollect;

TimeLineModel::TimeLineModel(MainWindow *mw, QwtPlot *widget) : QwtBaseModel(mw, widget) {
  (void)mw;
  (void)widget;
  scrollbar = mw->findChild<QScrollBar *>("scrBarTimeline");

  widget->setAxisScale(QwtPlot::yLeft, 0, 10);
  widget->setAxisAutoScale(QwtPlot::yLeft, true);

  widget->setAxisScale(QwtPlot::xTop, 0, DEF_VIEWPORT_SIZE);
  widget->setAxisAutoScale(QwtPlot::xTop, true);

  magnifier = std::make_unique<TimeLineMagnifier>(scrollbar, this, &maxXValue, widget->canvas());
  magnifier->setAxisEnabled(QwtPlot::xTop, true);
  magnifier->setAxisEnabled(QwtPlot::yLeft, false);
  /*
    panner = std::make_unique<QwtPlotPanner>(widget->canvas());
    panner->setAxisEnabled(QwtPlot::yLeft, false);
    panner->setAxisEnabled(QwtPlot::xTop, true);
    oldPanValue = DEF_VIEWPORT_SIZE / 2;
  */
  // resetAxes();
}

TimeLineModel::~TimeLineModel() {}

void TimeLineModel::init() {
  markers.clear();

  curCycleMarker.setLineStyle(QwtPlotMarker::VLine);
  curCycleMarker.setLinePen(QColor(0, 0, 0), 2, Qt::PenStyle::DotLine);
  curCycleMarker.setXAxis(QwtPlot::xTop);
  curCycleMarker.setXValue(static_cast<double>(0));
  curCycleMarker.setLabel(QwtText("View"));
  curCycleMarker.attach(plot);

  newestCycleMarker.setLineStyle(QwtPlotMarker::VLine);
  newestCycleMarker.setLinePen(QColor(255, 0, 0), 2, Qt::PenStyle::DotLine);
  newestCycleMarker.setXAxis(QwtPlot::xTop);
  newestCycleMarker.setXValue(static_cast<double>(0));
  newestCycleMarker.setLabel(QwtText("Backend"));
  newestCycleMarker.attach(plot);

  log   = getMainWindow()->getCaptureInstance()->getEventLog();
  appid = log->getAppID();

  QwtBaseModel::init();
}

void TimeLineModel::update(ProtectedCycle &cycle) {
  // Change cyclemarker position
  uint32_t cycleNum = window->getCycleNum();
  if (cycleNum == UINT32_MAX)
    cycleNum = cycle->getCycleNum();
  curCycleMarker.setXValue(static_cast<double>(cycleNum));

  // Set newest Cycle marker
  uint32_t newest = window->getCaptureInstance()->getCycleContainer()->pollCycle().getCycleNum();
  newestCycleMarker.setXValue(static_cast<double>(newest));
  maxXValue = newest;
  emit maxValueChanged(0, static_cast<int>(maxXValue - getViewportSize()));
  scrollbar->setMaximum(static_cast<int>(maxXValue));

  // Add new markers
  std::vector<EventBase *> nEvents = log->pollEvents(appid);
  if (nEvents.size() > 0)
    qDebug() << "Number of new Events adding to timeline: " + QString::number(nEvents.size());
  for (EventBase *ev : nEvents) {

    std::shared_ptr<QwtPlotMarker> marker =
          std::make_shared<QwtPlotMarker>(QString::fromStdString(ev->getDescription()));

    marker->setLineStyle(QwtPlotMarker::VLine);

    QColor col;
    switch (ev->getType()) {
      case EvType::ERROR: col   = QColor(200, 0, 0); break;
      case EvType::WARNING: col = QColor(250, 250, 0); break;
      case EvType::INFO: col    = QColor(0, 200, 0); break;
      default: col              = QColor(0, 0, 0);
    }
    marker->setLinePen(col);

    uint32_t x;
    ev->getCycleRange(&x);
    marker->setXValue(static_cast<double>(x));

    marker->attach(plot);
    markers.append(marker);
  }

  QwtBaseModel::update(cycle);
}

void TimeLineModel::updateViewport(int value) {
  QwtScaleDiv scale = plot->axisScaleDiv(QwtPlot::xTop);
  double      upper = scale.upperBound();
  double      lower = scale.lowerBound();

  double viewportSize = upper - lower;

  if (viewportSize < 1)
    return;

  double min = static_cast<double>(value);
  double max = min + viewportSize;

  qDebug() << "Changing viewport to [" + QString::number(min) + "-" + QString::number(max) + "]";

  plot->setAxisScale(QwtPlot::xTop, min, max);
  replot();
}

void TimeLineModel::resetAxes() {
  qDebug() << "============ reset Axis, do you really want to do? ==========";
  postToThread([&] { plot->setAxisMaxMinor(QwtPlot::xTop, 0); }, plot);
  postToThread([&] { plot->setAxisScale(QwtPlot::xTop, 0, maxXValue); }, plot);
}
<commit_msg>Made the marker labels better readable<commit_after>/* Copyright (c) 2017, EPL-Vizards
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the EPL-Vizards nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL EPL-Vizards BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*!
 * \file TimeLineModel.cpp
 */

#include "TimeLineModel.hpp"
#include "MainWindow.hpp"
#include "PlotCreator.hpp"
#include "TimeLineWidget.hpp"
using namespace EPL_Viz;
using namespace EPL_DataCollect;

TimeLineModel::TimeLineModel(MainWindow *mw, QwtPlot *widget) : QwtBaseModel(mw, widget) {
  (void)mw;
  (void)widget;
  scrollbar = mw->findChild<QScrollBar *>("scrBarTimeline");

  widget->setAxisScale(QwtPlot::yLeft, 0, 10);
  widget->setAxisAutoScale(QwtPlot::yLeft, true);

  widget->setAxisScale(QwtPlot::xTop, 0, DEF_VIEWPORT_SIZE);
  widget->setAxisAutoScale(QwtPlot::xTop, true);

  magnifier = std::make_unique<TimeLineMagnifier>(scrollbar, this, &maxXValue, widget->canvas());
  magnifier->setAxisEnabled(QwtPlot::xTop, true);
  magnifier->setAxisEnabled(QwtPlot::yLeft, false);
  /*
    panner = std::make_unique<QwtPlotPanner>(widget->canvas());
    panner->setAxisEnabled(QwtPlot::yLeft, false);
    panner->setAxisEnabled(QwtPlot::xTop, true);
    oldPanValue = DEF_VIEWPORT_SIZE / 2;
  */
  // resetAxes();
}

TimeLineModel::~TimeLineModel() {}

void TimeLineModel::init() {
  markers.clear();

  curCycleMarker.setLineStyle(QwtPlotMarker::VLine);
  curCycleMarker.setLinePen(QColor(0, 0, 0), 2, Qt::PenStyle::DotLine);
  curCycleMarker.setXAxis(QwtPlot::xTop);
  curCycleMarker.setXValue(static_cast<double>(0));
  curCycleMarker.setLabel(QwtText("View"));
  curCycleMarker.setLabelAlignment(Qt::AlignTop | Qt::AlignLeft);
  curCycleMarker.attach(plot);

  newestCycleMarker.setLineStyle(QwtPlotMarker::VLine);
  newestCycleMarker.setLinePen(QColor(255, 0, 0), 2, Qt::PenStyle::DotLine);
  newestCycleMarker.setXAxis(QwtPlot::xTop);
  newestCycleMarker.setXValue(static_cast<double>(0));
  newestCycleMarker.setLabel(QwtText("Backend"));
  newestCycleMarker.setLabelAlignment(Qt::AlignLeft);
  newestCycleMarker.attach(plot);

  log   = getMainWindow()->getCaptureInstance()->getEventLog();
  appid = log->getAppID();

  QwtBaseModel::init();
}

void TimeLineModel::update(ProtectedCycle &cycle) {
  // Change cyclemarker position
  uint32_t cycleNum = window->getCycleNum();
  if (cycleNum == UINT32_MAX)
    cycleNum = cycle->getCycleNum();
  curCycleMarker.setXValue(static_cast<double>(cycleNum));

  // Set newest Cycle marker
  uint32_t newest = window->getCaptureInstance()->getCycleContainer()->pollCycle().getCycleNum();
  newestCycleMarker.setXValue(static_cast<double>(newest));
  maxXValue = newest;
  emit maxValueChanged(0, static_cast<int>(maxXValue - getViewportSize()));
  scrollbar->setMaximum(static_cast<int>(maxXValue));

  // Add new markers
  std::vector<EventBase *> nEvents = log->pollEvents(appid);
  if (nEvents.size() > 0)
    qDebug() << "Number of new Events adding to timeline: " + QString::number(nEvents.size());
  for (EventBase *ev : nEvents) {

    std::shared_ptr<QwtPlotMarker> marker =
          std::make_shared<QwtPlotMarker>(QString::fromStdString(ev->getDescription()));

    marker->setLineStyle(QwtPlotMarker::VLine);

    QColor col;
    switch (ev->getType()) {
      case EvType::ERROR: col   = QColor(200, 0, 0); break;
      case EvType::WARNING: col = QColor(250, 250, 0); break;
      case EvType::INFO: col    = QColor(0, 200, 0); break;
      default: col              = QColor(0, 0, 0);
    }
    marker->setLinePen(col);

    uint32_t x;
    ev->getCycleRange(&x);
    marker->setXValue(static_cast<double>(x));

    marker->attach(plot);
    markers.append(marker);
  }

  QwtBaseModel::update(cycle);
}

void TimeLineModel::updateViewport(int value) {
  QwtScaleDiv scale = plot->axisScaleDiv(QwtPlot::xTop);
  double      upper = scale.upperBound();
  double      lower = scale.lowerBound();

  double viewportSize = upper - lower;

  if (viewportSize < 1)
    return;

  double min = static_cast<double>(value);
  double max = min + viewportSize;

  qDebug() << "Changing viewport to [" + QString::number(min) + "-" + QString::number(max) + "]";

  plot->setAxisScale(QwtPlot::xTop, min, max);
  replot();
}
<|endoftext|>


<commit_before>#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <unistd.h>

#include <cstdio>
#include <iostream>

#include <logger/logger.hpp>

#include "bme280.hpp"

BME280::BME280( const int id, const std::string &port )
  : Device( Device::BME280, id )
  , _port( port )
  , _address( 0x77 )
{
  Logger::debug("[bme280] Configuration:");
  Logger::debug("[bme280]   - id: " + std::to_string( id ));
  Logger::debug("[bme280]   - port: " + port);
}

std::string BME280::port() const
{
  return _port;
}

bool BME280::get( Data::THP &thp ) const
{
  // https://github.com/ControlEverythingCommunity/BME280
  //
  Logger::debug("[bme280] Reading data...");

  thp = {-1, -1, -1};

  // open fd descriptor
  int fd;
  char bus[BUFSIZ];
  sprintf(bus, "/dev/%s", _port.c_str());

  if((fd = open(bus, O_RDWR)) < 0)
  {
    Logger::error( "[bme280] Failed to open the bus." );
    return true;
  }

  // get I2C device
  ioctl(fd, I2C_SLAVE, _address);

  // read 24 bytes of data from register(0x88)
  unsigned char reg[1] = {0x88};
  write(fd, reg, 1);
  char b1[24] = {0};

  if(read(fd, b1, 24) != 24)
  {
    Logger::error( "[bme280] Input/Output error." );
    return true;
  }

  // temperature coefficients
  int dig_T1 = (b1[0] + b1[1] * 256);
  int dig_T2 = (b1[2] + b1[3] * 256);
  if(dig_T2 > 32767)
  {
    dig_T2 -= 65536;
  }
  int dig_T3 = (b1[4] + b1[5] * 256);
  if(dig_T3 > 32767)
  {
    dig_T3 -= 65536;
  }

  // pressure coefficents
  int dig_P1 = (b1[6] + b1[7] * 256);
  int dig_P2 = (b1[8] + b1[9] * 256);
  if(dig_P2 > 32767)
  {
    dig_P2 -= 65536;
  }
  int dig_P3 = (b1[10] + b1[11] * 256);
  if(dig_P3 > 32767)
  {
    dig_P3 -= 65536;
  }
  int dig_P4 = (b1[12] + b1[13] * 256);
  if(dig_P4 > 32767)
  {
    dig_P4 -= 65536;
  }
  int dig_P5 = (b1[14] + b1[15] * 256);
  if(dig_P5 > 32767)
  {
    dig_P5 -= 65536;
  }
  int dig_P6 = (b1[16] + b1[17] * 256);
  if(dig_P6 > 32767)
  {
    dig_P6 -= 65536;
  }
  int dig_P7 = (b1[18] + b1[19] * 256);
  if(dig_P7 > 32767)
  {
    dig_P7 -= 65536;
  }
  int dig_P8 = (b1[20] + b1[21] * 256);
  if(dig_P8 > 32767)
  {
    dig_P8 -= 65536;
  }
  int dig_P9 = (b1[22] + b1[23] * 256);
  if(dig_P9 > 32767)
  {
    dig_P9 -= 65536;
  }

  // read 1 byte of data from register(0xA1)
  reg[0] = 0xA1;
  write(fd, reg, 1);
  char data[8] = {0};
  read(fd, data, 1);
  int dig_H1 = data[0];

  // Read 7 bytes of data from register(0xE1)
  reg[0] = 0xE1;
  write(fd, reg, 1);
  read(fd, b1, 7);

  // Convert the data
  // humidity coefficents
  int dig_H2 = (b1[0] + b1[1] * 256);
  if(dig_H2 > 32767)
  {
    dig_H2 -= 65536;
  }
  int dig_H3 = b1[2] & 0xFF ;
  int dig_H4 = (b1[3] * 16 + (b1[4] & 0xF));
  if(dig_H4 > 32767)
  {
    dig_H4 -= 65536;
  }
  int dig_H5 = (b1[4] / 16) + (b1[5] * 16);
  if(dig_H5 > 32767)
  {
    dig_H5 -= 65536;
  }
  int dig_H6 = b1[6];
  if(dig_H6 > 127)
  {
    dig_H6 -= 256;
  }

  // Select control humidity register(0xF2)
  // Humidity over sampling rate = 1(0x01)
  char config[2] = {0};
  config[0] = 0xF2;
  config[1] = 0x01;
  write(fd, config, 2);
  // Select control measurement register(0xF4)
  // Normal mode, temp and pressure over sampling rate = 1(0x27)
  config[0] = 0xF4;
  config[1] = 0x27;
  write(fd, config, 2);
  // Select config register(0xF5)
  // Stand_by time = 1000 ms(0xA0)
  config[0] = 0xF5;
  config[1] = 0xA0;
  write(fd, config, 2);

  // Read 8 bytes of data from register(0xF7)
  // pressure msb1, pressure msb, pressure lsb, temp msb1, temp msb, temp lsb, humidity lsb, humidity msb
  reg[0] = 0xF7;
  write(fd, reg, 1);
  read(fd, data, 8);

  // Convert pressure and temperature data to 19-bits
  long adc_p = ((long)(data[0] * 65536 + ((long)(data[1] * 256) + (long)(data[2] & 0xF0)))) / 16;
  long adc_t = ((long)(data[3] * 65536 + ((long)(data[4] * 256) + (long)(data[5] & 0xF0)))) / 16;
  // Convert the humidity data
  long adc_h = (data[6] * 256 + data[7]);

  // Temperature offset calculations
  float var1 = (((float)adc_t) / 16384.0 - ((float)dig_T1) / 1024.0) * ((float)dig_T2);
  float var2 = ((((float)adc_t) / 131072.0 - ((float)dig_T1) / 8192.0) *
      (((float)adc_t)/131072.0 - ((float)dig_T1)/8192.0)) * ((float)dig_T3);
  float t_fine = (long)(var1 + var2);
  float cTemp = (var1 + var2) / 5120.0;
  float fTemp = cTemp * 1.8 + 32;

  // Pressure offset calculations
  var1 = ((float)t_fine / 2.0) - 64000.0;
  var2 = var1 * var1 * ((float)dig_P6) / 32768.0;
  var2 = var2 + var1 * ((float)dig_P5) * 2.0;
  var2 = (var2 / 4.0) + (((float)dig_P4) * 65536.0);
  var1 = (((float) dig_P3) * var1 * var1 / 524288.0 + ((float) dig_P2) * var1) / 524288.0;
  var1 = (1.0 + var1 / 32768.0) * ((float)dig_P1);
  float p = 1048576.0 - (float)adc_p;
  p = (p - (var2 / 4096.0)) * 6250.0 / var1;
  var1 = ((float) dig_P9) * p * p / 2147483648.0;
  var2 = p * ((float) dig_P8) / 32768.0;
  float pressure = (p + (var1 + var2 + ((float)dig_P7)) / 16.0) / 100;

  // Humidity offset calculations
  float var_H = (((float)t_fine) - 76800.0);
  var_H = (adc_h - (dig_H4 * 64.0 + dig_H5 / 16384.0 * var_H)) * (dig_H2 / 65536.0 * (1.0 + dig_H6 / 67108864.0 * var_H * (1.0 + dig_H3 / 67108864.0 * var_H)));
  float humidity = var_H * (1.0 -  dig_H1 * var_H / 524288.0);
  if(humidity > 100.0)
  {
    humidity = 100.0;
  }
  else if(humidity < 0.0)
  {
    humidity = 0.0;
  }

  thp.humidity = humidity;
  thp.pressure = pressure;
  thp.temperature = cTemp;

  return false;
}
<commit_msg>Close bme280 file descriptor when done<commit_after>#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <unistd.h>

#include <cstdio>
#include <iostream>

#include <logger/logger.hpp>

#include "bme280.hpp"

BME280::BME280( const int id, const std::string &port )
  : Device( Device::BME280, id )
  , _port( port )
  , _address( 0x77 )
{
  Logger::debug("[bme280] Configuration:");
  Logger::debug("[bme280]   - id: " + std::to_string( id ));
  Logger::debug("[bme280]   - port: " + port);
}

std::string BME280::port() const
{
  return _port;
}

bool BME280::get( Data::THP &thp ) const
{
  // https://github.com/ControlEverythingCommunity/BME280
  //
  Logger::debug("[bme280] Reading data...");

  thp = {-1, -1, -1};

  // open fd descriptor
  int fd;
  char bus[BUFSIZ];
  sprintf(bus, "/dev/%s", _port.c_str());

  if((fd = open(bus, O_RDWR)) < 0)
  {
    Logger::error( "[bme280] Failed to open the bus." );
    return true;
  }

  // get I2C device
  ioctl(fd, I2C_SLAVE, _address);

  // read 24 bytes of data from register(0x88)
  unsigned char reg[1] = {0x88};
  write(fd, reg, 1);
  char b1[24] = {0};

  if(read(fd, b1, 24) != 24)
  {
    Logger::error( "[bme280] Input/Output error." );
    close(fd);
    return true;
  }

  // temperature coefficients
  int dig_T1 = (b1[0] + b1[1] * 256);
  int dig_T2 = (b1[2] + b1[3] * 256);
  if(dig_T2 > 32767)
  {
    dig_T2 -= 65536;
  }
  int dig_T3 = (b1[4] + b1[5] * 256);
  if(dig_T3 > 32767)
  {
    dig_T3 -= 65536;
  }

  // pressure coefficents
  int dig_P1 = (b1[6] + b1[7] * 256);
  int dig_P2 = (b1[8] + b1[9] * 256);
  if(dig_P2 > 32767)
  {
    dig_P2 -= 65536;
  }
  int dig_P3 = (b1[10] + b1[11] * 256);
  if(dig_P3 > 32767)
  {
    dig_P3 -= 65536;
  }
  int dig_P4 = (b1[12] + b1[13] * 256);
  if(dig_P4 > 32767)
  {
    dig_P4 -= 65536;
  }
  int dig_P5 = (b1[14] + b1[15] * 256);
  if(dig_P5 > 32767)
  {
    dig_P5 -= 65536;
  }
  int dig_P6 = (b1[16] + b1[17] * 256);
  if(dig_P6 > 32767)
  {
    dig_P6 -= 65536;
  }
  int dig_P7 = (b1[18] + b1[19] * 256);
  if(dig_P7 > 32767)
  {
    dig_P7 -= 65536;
  }
  int dig_P8 = (b1[20] + b1[21] * 256);
  if(dig_P8 > 32767)
  {
    dig_P8 -= 65536;
  }
  int dig_P9 = (b1[22] + b1[23] * 256);
  if(dig_P9 > 32767)
  {
    dig_P9 -= 65536;
  }

  // read 1 byte of data from register(0xA1)
  reg[0] = 0xA1;
  write(fd, reg, 1);
  char data[8] = {0};
  read(fd, data, 1);
  int dig_H1 = data[0];

  // Read 7 bytes of data from register(0xE1)
  reg[0] = 0xE1;
  write(fd, reg, 1);
  read(fd, b1, 7);

  // Convert the data
  // humidity coefficents
  int dig_H2 = (b1[0] + b1[1] * 256);
  if(dig_H2 > 32767)
  {
    dig_H2 -= 65536;
  }
  int dig_H3 = b1[2] & 0xFF ;
  int dig_H4 = (b1[3] * 16 + (b1[4] & 0xF));
  if(dig_H4 > 32767)
  {
    dig_H4 -= 65536;
  }
  int dig_H5 = (b1[4] / 16) + (b1[5] * 16);
  if(dig_H5 > 32767)
  {
    dig_H5 -= 65536;
  }
  int dig_H6 = b1[6];
  if(dig_H6 > 127)
  {
    dig_H6 -= 256;
  }

  // Select control humidity register(0xF2)
  // Humidity over sampling rate = 1(0x01)
  char config[2] = {0};
  config[0] = 0xF2;
  config[1] = 0x01;
  write(fd, config, 2);
  // Select control measurement register(0xF4)
  // Normal mode, temp and pressure over sampling rate = 1(0x27)
  config[0] = 0xF4;
  config[1] = 0x27;
  write(fd, config, 2);
  // Select config register(0xF5)
  // Stand_by time = 1000 ms(0xA0)
  config[0] = 0xF5;
  config[1] = 0xA0;
  write(fd, config, 2);

  // Read 8 bytes of data from register(0xF7)
  // pressure msb1, pressure msb, pressure lsb, temp msb1, temp msb, temp lsb, humidity lsb, humidity msb
  reg[0] = 0xF7;
  write(fd, reg, 1);
  read(fd, data, 8);

  // Convert pressure and temperature data to 19-bits
  long adc_p = ((long)(data[0] * 65536 + ((long)(data[1] * 256) + (long)(data[2] & 0xF0)))) / 16;
  long adc_t = ((long)(data[3] * 65536 + ((long)(data[4] * 256) + (long)(data[5] & 0xF0)))) / 16;
  // Convert the humidity data
  long adc_h = (data[6] * 256 + data[7]);

  // Temperature offset calculations
  float var1 = (((float)adc_t) / 16384.0 - ((float)dig_T1) / 1024.0) * ((float)dig_T2);
  float var2 = ((((float)adc_t) / 131072.0 - ((float)dig_T1) / 8192.0) *
      (((float)adc_t)/131072.0 - ((float)dig_T1)/8192.0)) * ((float)dig_T3);
  float t_fine = (long)(var1 + var2);
  float cTemp = (var1 + var2) / 5120.0;
  float fTemp = cTemp * 1.8 + 32;

  // Pressure offset calculations
  var1 = ((float)t_fine / 2.0) - 64000.0;
  var2 = var1 * var1 * ((float)dig_P6) / 32768.0;
  var2 = var2 + var1 * ((float)dig_P5) * 2.0;
  var2 = (var2 / 4.0) + (((float)dig_P4) * 65536.0);
  var1 = (((float) dig_P3) * var1 * var1 / 524288.0 + ((float) dig_P2) * var1) / 524288.0;
  var1 = (1.0 + var1 / 32768.0) * ((float)dig_P1);
  float p = 1048576.0 - (float)adc_p;
  p = (p - (var2 / 4096.0)) * 6250.0 / var1;
  var1 = ((float) dig_P9) * p * p / 2147483648.0;
  var2 = p * ((float) dig_P8) / 32768.0;
  float pressure = (p + (var1 + var2 + ((float)dig_P7)) / 16.0) / 100;

  // Humidity offset calculations
  float var_H = (((float)t_fine) - 76800.0);
  var_H = (adc_h - (dig_H4 * 64.0 + dig_H5 / 16384.0 * var_H)) * (dig_H2 / 65536.0 * (1.0 + dig_H6 / 67108864.0 * var_H * (1.0 + dig_H3 / 67108864.0 * var_H)));
  float humidity = var_H * (1.0 -  dig_H1 * var_H / 524288.0);
  if(humidity > 100.0)
  {
    humidity = 100.0;
  }
  else if(humidity < 0.0)
  {
    humidity = 0.0;
  }

  thp.humidity = humidity;
  thp.pressure = pressure;
  thp.temperature = cTemp;

  close(fd);

  return false;
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  DebugText.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Render/RenderFacade.h"
#include "Debug/DebugFacade.h"
#include "glm/gtc/random.hpp"

using namespace Oryol;
using namespace Oryol::Core;
using namespace Oryol::Render;
using namespace Oryol::Debug;

// derived application class
class DebugTextApp : public App {
public:
    virtual AppState::Code OnInit();
    virtual AppState::Code OnRunning();
    virtual AppState::Code OnCleanup();

private:
    void dropChar();
    void moveChars();
    void drawText();

    RenderFacade* render;
    DebugFacade* debug;
    int32 width;
    int32 height;
    uint8* buffer = nullptr;
    Core::StringBuilder strBuilder;
};
OryolMain(DebugTextApp);

//------------------------------------------------------------------------------
AppState::Code
DebugTextApp::OnInit() {
    this->render = RenderFacade::CreateSingle(RenderSetup::Windowed(800, 600, "Oryol DebugText Sample"));
    this->debug  = DebugFacade::CreateSingle();
    this->debug->SetTextScale(glm::vec2(2.0f, 2.0f));

    this->width = this->render->GetDisplayAttrs().FramebufferWidth / 16;
    this->height = this->render->GetDisplayAttrs().FramebufferHeight / 16;
    this->buffer = (uint8*) Memory::Alloc(this->width * this->height);
    Memory::Clear(this->buffer, this->width * this->height);

    this->strBuilder.Reserve(this->width * 2);

    return App::OnInit();
}

//------------------------------------------------------------------------------
//  Drop a random new character at row 0
//
void
DebugTextApp::dropChar() {
    int chr = (int) glm::linearRand(33.0f, 255.0f);
    int col = (int) glm::linearRand(0.0f, float(this->width));
    this->buffer[col] = chr;
}

//------------------------------------------------------------------------------
//  Scan character buffer from bottom to top and move characters toward
//  bottom which have an empty cell below them.
//
void
DebugTextApp::moveChars() {
    bool isFull = true;
    for (int y = this->height - 1; y >= 1; y--) {
        int yOffset = y * this->width;
        for (int x = 0; x < this->width; x++) {
            int offset = yOffset + x;
            int above  = offset - this->width;
            if (this->buffer[offset] == 0) {
                isFull = false;
                if (this->buffer[above] != 0) {
                    this->buffer[offset] = this->buffer[above];
                    this->buffer[above] = 0;
                }
            }
        }
    }
    if (isFull) {
        Memory::Clear(this->buffer, this->width * this->height);
    }
}

//------------------------------------------------------------------------------
//  Draw the character buffer into a string.
//
void
DebugTextApp::drawText() {

    glm::vec4 color[3] = {
        glm::vec4(1.0f, 0.0f, 0.0f, 1.0f),
        glm::vec4(0.0f, 1.0f, 0.0f, 1.0f),
        glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)
    };

    for (int y = 0; y < this->height; y++) {
        this->strBuilder.Clear();
        int yOffset = y * this->width;
        for (int x = 0; x < this->width; x++) {
            char c = this->buffer[yOffset + x];
            if (0 == c) {
                strBuilder.Append(0x09);    // cursor right
            }
            else {
                strBuilder.Append(c);
            }
        }
        strBuilder.Append("\r\n");
        this->debug->TextColor(color[y % 3]);
        this->debug->Print(strBuilder.AsCStr());
    }
}

//------------------------------------------------------------------------------
AppState::Code
DebugTextApp::OnRunning() {
    // render one frame
    if (this->render->BeginFrame()) {

        this->dropChar();
        this->moveChars();
        this->drawText();

        // clear, apply mesh and shader program, and draw
        this->render->ApplyState(Render::State::ClearColor, 0.5f, 0.5f, 0.5f, 0.0f);
        this->render->Clear(true, false, false);

        // the text buffer must be rendered within BeginFrame()/EndFrame() though...
        this->debug->DrawTextBuffer();

        this->render->EndFrame();
    }

    // continue running or quit?
    return render->QuitRequested() ? AppState::Cleanup : AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
DebugTextApp::OnCleanup() {
    Memory::Free(this->buffer);
    this->buffer = nullptr;
    this->render = nullptr;
    this->debug  = nullptr;
    DebugFacade::DestroySingle();
    RenderFacade::DestroySingle();
    return App::OnCleanup();
}
<commit_msg>Missing ApplyDefaultRenderTarget in DebugText sample<commit_after>//------------------------------------------------------------------------------
//  DebugText.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Render/RenderFacade.h"
#include "Debug/DebugFacade.h"
#include "glm/gtc/random.hpp"

using namespace Oryol;
using namespace Oryol::Core;
using namespace Oryol::Render;
using namespace Oryol::Debug;

// derived application class
class DebugTextApp : public App {
public:
    virtual AppState::Code OnInit();
    virtual AppState::Code OnRunning();
    virtual AppState::Code OnCleanup();

private:
    void dropChar();
    void moveChars();
    void drawText();

    RenderFacade* render;
    DebugFacade* debug;
    int32 width;
    int32 height;
    uint8* buffer = nullptr;
    Core::StringBuilder strBuilder;
};
OryolMain(DebugTextApp);

//------------------------------------------------------------------------------
AppState::Code
DebugTextApp::OnInit() {
    this->render = RenderFacade::CreateSingle(RenderSetup::Windowed(800, 600, "Oryol DebugText Sample"));
    this->debug  = DebugFacade::CreateSingle();
    this->debug->SetTextScale(glm::vec2(2.0f, 2.0f));

    this->width = this->render->GetDisplayAttrs().FramebufferWidth / 16;
    this->height = this->render->GetDisplayAttrs().FramebufferHeight / 16;
    this->buffer = (uint8*) Memory::Alloc(this->width * this->height);
    Memory::Clear(this->buffer, this->width * this->height);

    this->strBuilder.Reserve(this->width * 2);

    return App::OnInit();
}

//------------------------------------------------------------------------------
//  Drop a random new character at row 0
//
void
DebugTextApp::dropChar() {
    int chr = (int) glm::linearRand(33.0f, 255.0f);
    int col = (int) glm::linearRand(0.0f, float(this->width));
    this->buffer[col] = chr;
}

//------------------------------------------------------------------------------
//  Scan character buffer from bottom to top and move characters toward
//  bottom which have an empty cell below them.
//
void
DebugTextApp::moveChars() {
    bool isFull = true;
    for (int y = this->height - 1; y >= 1; y--) {
        int yOffset = y * this->width;
        for (int x = 0; x < this->width; x++) {
            int offset = yOffset + x;
            int above  = offset - this->width;
            if (this->buffer[offset] == 0) {
                isFull = false;
                if (this->buffer[above] != 0) {
                    this->buffer[offset] = this->buffer[above];
                    this->buffer[above] = 0;
                }
            }
        }
    }
    if (isFull) {
        Memory::Clear(this->buffer, this->width * this->height);
    }
}

//------------------------------------------------------------------------------
//  Draw the character buffer into a string.
//
void
DebugTextApp::drawText() {

    glm::vec4 color[3] = {
        glm::vec4(1.0f, 0.0f, 0.0f, 1.0f),
        glm::vec4(0.0f, 1.0f, 0.0f, 1.0f),
        glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)
    };

    for (int y = 0; y < this->height; y++) {
        this->strBuilder.Clear();
        int yOffset = y * this->width;
        for (int x = 0; x < this->width; x++) {
            char c = this->buffer[yOffset + x];
            if (0 == c) {
                strBuilder.Append(0x09);    // cursor right
            }
            else {
                strBuilder.Append(c);
            }
        }
        strBuilder.Append("\r\n");
        this->debug->TextColor(color[y % 3]);
        this->debug->Print(strBuilder.AsCStr());
    }
}

//------------------------------------------------------------------------------
AppState::Code
DebugTextApp::OnRunning() {
    // render one frame
    if (this->render->BeginFrame()) {

        this->dropChar();
        this->moveChars();
        this->drawText();

        // clear, apply mesh and shader program, and draw
        this->render->ApplyDefaultRenderTarget();
        this->render->ApplyState(Render::State::ClearColor, 0.5f, 0.5f, 0.5f, 0.0f);
        this->render->Clear(true, false, false);

        // the text buffer must be rendered within BeginFrame()/EndFrame() though...
        this->debug->DrawTextBuffer();

        this->render->EndFrame();
    }

    // continue running or quit?
    return render->QuitRequested() ? AppState::Cleanup : AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
DebugTextApp::OnCleanup() {
    Memory::Free(this->buffer);
    this->buffer = nullptr;
    this->render = nullptr;
    this->debug  = nullptr;
    DebugFacade::DestroySingle();
    RenderFacade::DestroySingle();
    return App::OnCleanup();
}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#ifndef __mitkNrrdTbssRoiImageWriter__cpp
#define __mitkNrrdTbssRoiImageWriter__cpp

#include "mitkNrrdTbssRoiImageWriter.h"
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.h"
#include "itkNrrdImageIO.h"
//#include "itkNiftiImageIO.h"
#include "itkImageFileWriter.h"
#include "itksys/SystemTools.hxx"

#include <iostream>
#include <fstream>

mitk::NrrdTbssRoiImageWriter::NrrdTbssRoiImageWriter()
  : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false)
{
  this->SetNumberOfRequiredInputs( 1 );
}

mitk::NrrdTbssRoiImageWriter::~NrrdTbssRoiImageWriter()
{}

void mitk::NrrdTbssRoiImageWriter::GenerateData()
{
  m_Success = false;
  InputType* input = this->GetInput();

  if (input == nullptr)
  {
    itkWarningMacro(<<"Sorry, input to NrrdTbssImageWriter is NULL!")
    return;
  }
  if ( m_FileName == "" )
  {
    itkWarningMacro( << "Sorry, filename has not been set!" )
    return ;
  }

  char keybuffer[512];
  char valbuffer[512];

  std::vector< itk::Index<3> > roi = input->GetRoi();

  auto it = roi.begin();

  int i=0;
  while(it != roi.end())
  {
    itk::Index<3> ix = *it;

    sprintf( keybuffer, "ROI_index_%04d", i );
    sprintf( valbuffer, "%ld %ld %ld", ix[0],ix[1],ix[2]);

    std::cout << valbuffer << std::endl;

    //input->GetImage()->GetMetaDataDictionary();

    itk::EncapsulateMetaData< std::string >(input->GetImage()->GetMetaDataDictionary(), std::string(keybuffer), std::string(valbuffer));

    it++;
    ++i;
  }

  std::string structure = input->GetStructure();
  itk::EncapsulateMetaData< std::string >(input->GetImage()->GetMetaDataDictionary(), "structure", structure);

  typedef itk::Image<unsigned char,3> ImageType;
  ImageType::Pointer img = input->GetImage();

  itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
  io->SetFileType( itk::ImageIOBase::Binary );
  io->UseCompressionOn();

  typedef itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer nrrdWriter = WriterType::New();
  nrrdWriter->UseInputMetaDataDictionaryOn();
  nrrdWriter->SetInput( img );
  nrrdWriter->SetImageIO(io);
  nrrdWriter->SetFileName(m_FileName);
  // nrrdWriter->UseCompressionOn();
  nrrdWriter->SetImageIO(io);
  try
  {
    nrrdWriter->Update();
  }
  catch (itk::ExceptionObject e)
  {
    std::cout << e << std::endl;
  }

  m_Success = true;
}

void mitk::NrrdTbssRoiImageWriter::SetInput( InputType* tbssVol )
{
  this->ProcessObject::SetNthInput( 0, tbssVol );
}

mitk::TbssRoiImage* mitk::NrrdTbssRoiImageWriter::GetInput()
{
  if ( this->GetNumberOfInputs() < 1 )
  {
    return nullptr;
  }
  else
  {
    return dynamic_cast<InputType*> ( this->ProcessObject::GetInput( 0 ) );
  }
}

std::vector<std::string> mitk::NrrdTbssRoiImageWriter::GetPossibleFileExtensions()
{
  std::vector<std::string> possibleFileExtensions;
  possibleFileExtensions.push_back(".roi");
  return possibleFileExtensions;
}

std::string mitk::NrrdTbssRoiImageWriter::GetSupportedBaseData() const
{
  return TbssRoiImage::GetStaticNameOfClass();
}

#endif //__mitkNrrdTbssRoiImageWriter__cpp
<commit_msg>Change char array to stringstream to fix windows compile errors<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#ifndef __mitkNrrdTbssRoiImageWriter__cpp
#define __mitkNrrdTbssRoiImageWriter__cpp

#include "mitkNrrdTbssRoiImageWriter.h"
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.h"
#include "itkNrrdImageIO.h"
//#include "itkNiftiImageIO.h"
#include "itkImageFileWriter.h"
#include "itksys/SystemTools.hxx"

#include <iostream>
#include <fstream>

mitk::NrrdTbssRoiImageWriter::NrrdTbssRoiImageWriter()
  : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false)
{
  this->SetNumberOfRequiredInputs( 1 );
}

mitk::NrrdTbssRoiImageWriter::~NrrdTbssRoiImageWriter()
{}

void mitk::NrrdTbssRoiImageWriter::GenerateData()
{
  m_Success = false;
  InputType* input = this->GetInput();

  if (input == nullptr)
  {
    itkWarningMacro(<<"Sorry, input to NrrdTbssImageWriter is NULL!")
    return;
  }
  if ( m_FileName == "" )
  {
    itkWarningMacro( << "Sorry, filename has not been set!" )
    return ;
  }

  char keybuffer[512];
  std::stringstream valbuffer;

  std::vector< itk::Index<3> > roi = input->GetRoi();

  auto it = roi.begin();

  int i=0;
  while(it != roi.end())
  {
    itk::Index<3> ix = *it;

    sprintf( keybuffer, "ROI_index_%04d", i );
    valbuffer << ix[0] << " " << ix[1] << " " << ix[2];

    std::cout << valbuffer.str() << std::endl;

    //input->GetImage()->GetMetaDataDictionary();

    itk::EncapsulateMetaData< std::string >(input->GetImage()->GetMetaDataDictionary(), std::string(keybuffer), valbuffer.str());

    it++;
    ++i;
  }

  std::string structure = input->GetStructure();
  itk::EncapsulateMetaData< std::string >(input->GetImage()->GetMetaDataDictionary(), "structure", structure);

  typedef itk::Image<unsigned char,3> ImageType;
  ImageType::Pointer img = input->GetImage();

  itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
  io->SetFileType( itk::ImageIOBase::Binary );
  io->UseCompressionOn();

  typedef itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer nrrdWriter = WriterType::New();
  nrrdWriter->UseInputMetaDataDictionaryOn();
  nrrdWriter->SetInput( img );
  nrrdWriter->SetImageIO(io);
  nrrdWriter->SetFileName(m_FileName);
  // nrrdWriter->UseCompressionOn();
  nrrdWriter->SetImageIO(io);
  try
  {
    nrrdWriter->Update();
  }
  catch (itk::ExceptionObject e)
  {
    std::cout << e << std::endl;
  }

  m_Success = true;
}

void mitk::NrrdTbssRoiImageWriter::SetInput( InputType* tbssVol )
{
  this->ProcessObject::SetNthInput( 0, tbssVol );
}

mitk::TbssRoiImage* mitk::NrrdTbssRoiImageWriter::GetInput()
{
  if ( this->GetNumberOfInputs() < 1 )
  {
    return nullptr;
  }
  else
  {
    return dynamic_cast<InputType*> ( this->ProcessObject::GetInput( 0 ) );
  }
}

std::vector<std::string> mitk::NrrdTbssRoiImageWriter::GetPossibleFileExtensions()
{
  std::vector<std::string> possibleFileExtensions;
  possibleFileExtensions.push_back(".roi");
  return possibleFileExtensions;
}

std::string mitk::NrrdTbssRoiImageWriter::GetSupportedBaseData() const
{
  return TbssRoiImage::GetStaticNameOfClass();
}

#endif //__mitkNrrdTbssRoiImageWriter__cpp
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program 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 program 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 program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Binding_BaseContext.h"
#include "Binding_Base.h"
#include "Binding_Vector.h"
#include "PythonFactory.h"
#include "PythonToSofa.inl"

#include <sofa/defaulttype/Vec3Types.h>
using namespace sofa::defaulttype;
#include <sofa/core/ObjectFactory.h>
using namespace sofa::core;
#include <sofa/core/objectmodel/BaseContext.h>
using namespace sofa::core::objectmodel;
#include <sofa/simulation/Node.h>
using namespace sofa::simulation;
using namespace sofa::defaulttype;

static PyObject * BaseContext_setGravity(PyObject *self, PyObject * args)
{
    BaseContext* obj = get_basecontext( self );
    PyPtr<Vector3>* pyVec;
    if (!PyArg_ParseTuple(args, "O",&pyVec))
        Py_RETURN_NONE;
    obj->setGravity(*pyVec->object);
    Py_RETURN_NONE;
}

static PyObject * BaseContext_getGravity(PyObject *self, PyObject * /*args*/)
{
    BaseContext* obj = get_basecontext( self );
    return SP_BUILD_PYPTR(Vector3,Vector3,new Vector3(obj->getGravity()),true); // "true", because I manage the deletion myself
}

static PyObject * BaseContext_getTime(PyObject *self, PyObject * /*args*/)
{
    BaseContext* obj = get_basecontext( self );
    return PyFloat_FromDouble(obj->getTime());
}

static PyObject * BaseContext_getDt(PyObject *self, PyObject * /*args*/)
{
    BaseContext* obj = get_basecontext( self );
    return PyFloat_FromDouble(obj->getDt());
}

static PyObject * BaseContext_getRootContext(PyObject *self, PyObject * /*args*/)
{
    BaseContext* obj = get_basecontext( self );
    return sofa::PythonFactory::toPython(obj->getRootContext());
}

/// This function converts an PyObject into a sofa string.
/// string that can be safely parsed in helper::vector<int> or helper::vector<double>
static std::ostream& pythonToSofaDataString(PyObject* value, std::ostream& out)
{
    /// String are just returned as string.
    if (PyString_Check(value))
    {
        return out << PyString_AsString(value) ;
    }

    if( PySequence_Check(value) )
    {
        /// It is a sequence...so we can iterate over it.
        PyObject *iterator = PyObject_GetIter(value);
        if(iterator)
        {
            bool first = true;
            while(PyObject* next = PyIter_Next(iterator))
            {
                if(first) first = false;
                else out << ' ';

                pythonToSofaDataString(next, out);
                Py_DECREF(next);
            }
            Py_DECREF(iterator);

            if (PyErr_Occurred())
            {
                msg_error("SofaPython") << "error while iterating." << msgendl
                                        << PythonEnvironment::getStackAsString() ;
            }
            return out;
        }
    }

    /// Check if the object has an explicit conversion to a Sofa path. If this is the case
    /// we use it.
    if( PyObject_HasAttrString(value, "getAsACreateObjectParameter") ){
       PyObject* retvalue = PyObject_CallMethod(value, (char*)"getAsACreateObjectParameter", nullptr) ;
       return pythonToSofaDataString(retvalue, out);
    }

    /// Default conversion for standard type:
    if( !(PyInt_Check(value) || PyLong_Check(value) || PyFloat_Check(value) || PyBool_Check(value) ))
    {
        msg_warning("SofaPython") << "You are trying to convert a non primitive type to Sofa using the 'str' operator." << msgendl
                                  << "Automatic conversion is provided for: String, Integer, Long, Float and Bool and Sequences." << msgendl
                                  << "Other objects should implement the method getAsACreateObjectParameter(). " << msgendl
                                  << "This function should return a string usable as a parameter in createObject()." << msgendl
                                  << "So to remove this message you must add a method getAsCreateObjectParameter(self) "
                                     "to the object you are passing the createObject function." << msgendl
                                  << PythonEnvironment::getStackAsString() ;
    }

    PyObject* tmpstr=PyObject_Str(value);
    out << PyString_AsString(tmpstr) ;
    Py_DECREF(tmpstr) ;
    return out ;
}

// object factory
static PyObject * BaseContext_createObject_Impl(PyObject * self, PyObject * args, PyObject * kw, bool printWarnings)
{
    BaseContext* context = get_basecontext( self );

    char *type;
    if (!PyArg_ParseTuple(args, "s",&type))
    {
        PyErr_BadArgument();
        return NULL;
    }

    // temporarily, the name is set to the type name.
    // if a "name" parameter is provided, it will overwrite it.
    BaseObjectDescription desc(type,type);

    bool warning = printWarnings;
    if (kw && PyDict_Size(kw)>0)
    {
        PyObject* keys = PyDict_Keys(kw);
        PyObject* values = PyDict_Values(kw);
        for (int i=0; i<PyDict_Size(kw); i++)
        {
            PyObject *key = PyList_GetItem(keys,i);
            PyObject *value = PyList_GetItem(values,i);

            if( !strcmp( PyString_AsString(key), "warning") )
            {
                if PyBool_Check(value)
                        warning = (value==Py_True);
            }
            else
            {
                std::stringstream s;
                pythonToSofaDataString(value, s) ;
                desc.setAttribute(PyString_AsString(key),s.str().c_str());
            }
        }
        Py_DecRef(keys);
        Py_DecRef(values);
    }

    BaseObject::SPtr obj = ObjectFactory::getInstance()->createObject(context,&desc);
    if (obj==0)
    {
        SP_MESSAGE_ERROR( "createObject: component '" << desc.getName() << "' of type '" << desc.getAttribute("type","")<< "' in node '"<<context->getName()<<"'" );
        for (std::vector< std::string >::const_iterator it = desc.getErrors().begin(); it != desc.getErrors().end(); ++it)
            SP_MESSAGE_ERROR(*it);
        PyErr_BadArgument();
        return NULL;
    }

    if( warning )
    {
        for( auto it : desc.getAttributeMap() )
        {
            if (!it.second.isAccessed())
            {
                obj->serr <<"Unused Attribute: \""<<it.first <<"\" with value: \"" <<(std::string)it.second<<"\" (" << obj->getPathName() << ")" << obj->sendl;
            }
        }

        Node *node = static_cast<Node*>(context);
        if (node && node->isInitialized())
            SP_MESSAGE_WARNING( "Sofa.Node.createObject("<<type<<") called on a node("<<node->getName()<<") that is already initialized" )
    }

    return sofa::PythonFactory::toPython(obj.get());
}
static PyObject * BaseContext_createObject(PyObject * self, PyObject * args, PyObject * kw)
{
    return BaseContext_createObject_Impl( self, args, kw, true );
}
static PyObject * BaseContext_createObject_noWarning(PyObject * self, PyObject * args, PyObject * kw)
{
    SP_MESSAGE_DEPRECATED("BaseContext_createObject_noWarning is deprecated, use the keyword warning=False in BaseContext_createObject instead.")
            return BaseContext_createObject_Impl( self, args, kw, false );
}

/// the complete relative path to the object must be given
/// returns None with a warning if the object is not found
static PyObject * BaseContext_getObject(PyObject * self, PyObject * args, PyObject * kw)
{
    BaseContext* context = get_basecontext( self );
    char *path;
    if (!PyArg_ParseTuple(args, "s",&path))
    {
        SP_MESSAGE_WARNING( "BaseContext_getObject: wrong argument, should be a string (the complete relative path)" )
        return NULL;
    }

    bool warning = true;
    if (kw && PyDict_Size(kw)>0)
    {
        PyObject* keys = PyDict_Keys(kw);
        PyObject* values = PyDict_Values(kw);
        for (int i=0; i<PyDict_Size(kw); i++)
        {
            PyObject *key = PyList_GetItem(keys,i);
            PyObject *value = PyList_GetItem(values,i);
            if( !strcmp(PyString_AsString(key),"warning") )
            {
                if PyBool_Check(value)
                        warning = (value==Py_True);
                break;
            }
        }
        Py_DecRef(keys);
        Py_DecRef(values);
    }

    if (!context || !path)
    {
        PyErr_BadArgument();
        return NULL;
    }
    BaseObject::SPtr sptr;
    context->get<BaseObject>(sptr,path);
    if (!sptr)
    {
        if(warning) SP_MESSAGE_WARNING( "BaseContext_getObject: component "<<path<<" not found (the complete relative path is needed)" )
        return NULL;
    }

    return sofa::PythonFactory::toPython(sptr.get());
}

/// the complete relative path to the object must be given
/// returns None if the object is not found
static PyObject * BaseContext_getObject_noWarning(PyObject * self, PyObject * args)
{
    SP_MESSAGE_DEPRECATED("BaseContext_getObject_noWarning is deprecated, use the keyword warning=False in BaseContext_getObject instead.")
    BaseContext* context = get_basecontext( self );
    char *path;
    if (!PyArg_ParseTuple(args, "s",&path))
    {
        SP_MESSAGE_WARNING( "BaseContext_getObject_noWarning: wrong argument, should be a string (the complete relative path)" )
        return NULL;
    }
    if (!context || !path)
    {
        PyErr_BadArgument();
        return NULL;
    }
    BaseObject::SPtr sptr;
    context->get<BaseObject>(sptr,path);
    if (!sptr) Py_RETURN_NONE;

    return sofa::PythonFactory::toPython(sptr.get());
}

// @TODO: pass keyword arguments rather than optional arguments?
static PyObject * BaseContext_getObjects(PyObject * self, PyObject * args)
{
    BaseContext* context = get_basecontext( self );
    char* search_direction= NULL;
    char* type_name= NULL;
    char* name= NULL;
    if ( !PyArg_ParseTuple ( args, "|sss", &search_direction, &type_name, &name ) ) {
        SP_MESSAGE_WARNING( "BaseContext_getObjects: wrong arguments! Expected format: getObjects ( OPTIONAL STRING searchDirection, OPTIONAL STRING typeName, OPTIONAL STRING name )" )
        return NULL;
    }

    if (!context)
    {
        PyErr_BadArgument();
        return NULL;
    }

    sofa::core::objectmodel::BaseContext::SearchDirection search_direction_enum= sofa::core::objectmodel::BaseContext::Local;
    if ( search_direction )
    {
        std::string search_direction_str ( search_direction );
        if ( search_direction_str == "SearchUp" )
        {
            search_direction_enum= sofa::core::objectmodel::BaseContext::SearchUp;
        }
        else if ( search_direction_str == "Local" )
        {
            search_direction_enum= sofa::core::objectmodel::BaseContext::Local;
        }
        else if ( search_direction_str == "SearchDown" )
        {
            search_direction_enum= sofa::core::objectmodel::BaseContext::SearchDown;
        }
        else if ( search_direction_str == "SearchRoot" )
        {
            search_direction_enum= sofa::core::objectmodel::BaseContext::SearchRoot;
        }
        else if ( search_direction_str == "SearchParents" )
        {
            search_direction_enum= sofa::core::objectmodel::BaseContext::SearchParents;
        }
        else
        {
            SP_MESSAGE_WARNING( "BaseContext_getObjects: Invalid search direction, using 'Local'. Expected: 'SearchUp', 'Local', 'SearchDown', 'SearchRoot', or 'SearchParents'." )
        }
    }

    sofa::helper::vector< boost::intrusive_ptr<BaseObject> > list;
    context->get<BaseObject>(&list,search_direction_enum);

    PyObject *pyList = PyList_New(0);
    for (size_t i=0; i<list.size(); i++)
    {
        BaseObject* o = list[i].get();

        if( !type_name || o->getClass()->hasParent( type_name ) )
        {
            if ( !name || name == o->getName() )
            {
                PyObject* obj=sofa::PythonFactory::toPython(o); // ref 1
                PyList_Append(pyList,obj); // ref 2
                Py_DECREF(obj); // ref 1 (now owned by list)
            }
        }
    }

    return pyList;
}

SP_CLASS_METHODS_BEGIN(BaseContext)
SP_CLASS_METHOD(BaseContext,getRootContext)
SP_CLASS_METHOD(BaseContext,getTime)
SP_CLASS_METHOD(BaseContext,getDt)
SP_CLASS_METHOD(BaseContext,getGravity)
SP_CLASS_METHOD(BaseContext,setGravity)
SP_CLASS_METHOD_KW(BaseContext,createObject)
SP_CLASS_METHOD_KW(BaseContext,createObject_noWarning) // deprecated
SP_CLASS_METHOD_KW(BaseContext,getObject)
SP_CLASS_METHOD(BaseContext,getObject_noWarning) // deprecated
SP_CLASS_METHOD(BaseContext,getObjects)
SP_CLASS_METHODS_END

static PyObject * BaseContext_getAttr_animate(PyObject *self, void*)
{
    BaseContext* obj = get_basecontext( self );
    return PyBool_FromLong(obj->getAnimate());
}
static int BaseContext_setAttr_animate(PyObject *self, PyObject * args, void*)
{
    BaseContext* obj = get_basecontext( self );
    if (!PyBool_Check(args))
    {
        PyErr_BadArgument();
        return -1;
    }
    obj->setAnimate(args==Py_True);
    return 0;
}

static PyObject * BaseContext_getAttr_active(PyObject *self, void*)
{
    BaseContext* obj = get_basecontext( self );
    return PyBool_FromLong(obj->isActive());
}

static int BaseContext_setAttr_active(PyObject *self, PyObject * args, void*)
{
    BaseContext* obj = get_basecontext( self );
    if (!PyBool_Check(args))
    {
        PyErr_BadArgument();
        return -1;
    }
    obj->setActive(args==Py_True);
    return 0;
}

SP_CLASS_ATTRS_BEGIN(BaseContext)
SP_CLASS_ATTR(BaseContext,active)
SP_CLASS_ATTR(BaseContext,animate)
//SP_CLASS_ATTR(BaseContext,gravity) // attribut objets = problème... le setter ne fonctionne pas
SP_CLASS_ATTRS_END

SP_CLASS_TYPE_SPTR_ATTR(BaseContext,BaseContext,Base)
<commit_msg>[SofaPyton] error handling<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program 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 program 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 program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Binding_BaseContext.h"
#include "Binding_Base.h"
#include "Binding_Vector.h"
#include "PythonFactory.h"
#include "PythonToSofa.inl"

#include <sofa/defaulttype/Vec3Types.h>
using namespace sofa::defaulttype;
#include <sofa/core/ObjectFactory.h>
using namespace sofa::core;
#include <sofa/core/objectmodel/BaseContext.h>
using namespace sofa::core::objectmodel;
#include <sofa/simulation/Node.h>
using namespace sofa::simulation;
using namespace sofa::defaulttype;

static PyObject * BaseContext_setGravity(PyObject *self, PyObject * args)
{
    BaseContext* obj = get_basecontext( self );
    PyPtr<Vector3>* pyVec;
    if (!PyArg_ParseTuple(args, "O",&pyVec)) {
        return NULL;
    }

    obj->setGravity(*pyVec->object);
    Py_RETURN_NONE;
}

static PyObject * BaseContext_getGravity(PyObject *self, PyObject * /*args*/)
{
    BaseContext* obj = get_basecontext( self );
    return SP_BUILD_PYPTR(Vector3,Vector3,new Vector3(obj->getGravity()),true); // "true", because I manage the deletion myself
}

static PyObject * BaseContext_getTime(PyObject *self, PyObject * /*args*/)
{
    BaseContext* obj = get_basecontext( self );
    return PyFloat_FromDouble(obj->getTime());
}

static PyObject * BaseContext_getDt(PyObject *self, PyObject * /*args*/)
{
    BaseContext* obj = get_basecontext( self );
    return PyFloat_FromDouble(obj->getDt());
}

static PyObject * BaseContext_getRootContext(PyObject *self, PyObject * /*args*/)
{
    BaseContext* obj = get_basecontext( self );
    return sofa::PythonFactory::toPython(obj->getRootContext());
}

/// This function converts an PyObject into a sofa string.
/// string that can be safely parsed in helper::vector<int> or helper::vector<double>
static std::ostream& pythonToSofaDataString(PyObject* value, std::ostream& out)
{
    /// String are just returned as string.
    if (PyString_Check(value))
    {
        return out << PyString_AsString(value) ;
    }

    if( PySequence_Check(value) )
    {
        /// It is a sequence...so we can iterate over it.
        PyObject *iterator = PyObject_GetIter(value);
        if(iterator)
        {
            bool first = true;
            while(PyObject* next = PyIter_Next(iterator))
            {
                if(first) first = false;
                else out << ' ';

                pythonToSofaDataString(next, out);
                Py_DECREF(next);
            }
            Py_DECREF(iterator);

            if (PyErr_Occurred())
            {
                msg_error("SofaPython") << "error while iterating." << msgendl
                                        << PythonEnvironment::getStackAsString() ;
            }
            return out;
        }
    }

    /// Check if the object has an explicit conversion to a Sofa path. If this is the case
    /// we use it.
    if( PyObject_HasAttrString(value, "getAsACreateObjectParameter") ){
       PyObject* retvalue = PyObject_CallMethod(value, (char*)"getAsACreateObjectParameter", nullptr) ;
       return pythonToSofaDataString(retvalue, out);
    }

    /// Default conversion for standard type:
    if( !(PyInt_Check(value) || PyLong_Check(value) || PyFloat_Check(value) || PyBool_Check(value) ))
    {
        msg_warning("SofaPython") << "You are trying to convert a non primitive type to Sofa using the 'str' operator." << msgendl
                                  << "Automatic conversion is provided for: String, Integer, Long, Float and Bool and Sequences." << msgendl
                                  << "Other objects should implement the method getAsACreateObjectParameter(). " << msgendl
                                  << "This function should return a string usable as a parameter in createObject()." << msgendl
                                  << "So to remove this message you must add a method getAsCreateObjectParameter(self) "
                                     "to the object you are passing the createObject function." << msgendl
                                  << PythonEnvironment::getStackAsString() ;
    }

    PyObject* tmpstr=PyObject_Str(value);
    out << PyString_AsString(tmpstr) ;
    Py_DECREF(tmpstr) ;
    return out ;
}

// object factory
static PyObject * BaseContext_createObject_Impl(PyObject * self, PyObject * args, PyObject * kw, bool printWarnings)
{
    BaseContext* context = get_basecontext( self );

    char *type;
    if (!PyArg_ParseTuple(args, "s",&type))
    {
        return NULL;
    }

    // temporarily, the name is set to the type name.
    // if a "name" parameter is provided, it will overwrite it.
    BaseObjectDescription desc(type,type);

    bool warning = printWarnings;
    if (kw && PyDict_Size(kw)>0)
    {
        PyObject* keys = PyDict_Keys(kw);
        PyObject* values = PyDict_Values(kw);
        for (int i=0; i<PyDict_Size(kw); i++)
        {
            PyObject *key = PyList_GetItem(keys,i);
            PyObject *value = PyList_GetItem(values,i);

            if( !strcmp( PyString_AsString(key), "warning") )
            {
                if PyBool_Check(value)
                        warning = (value==Py_True);
            }
            else
            {
                std::stringstream s;
                pythonToSofaDataString(value, s) ;
                desc.setAttribute(PyString_AsString(key),s.str().c_str());
            }
        }
        Py_DecRef(keys);
        Py_DecRef(values);
    }

    BaseObject::SPtr obj = ObjectFactory::getInstance()->createObject(context,&desc);
    if (obj==0)
    {
        SP_MESSAGE_ERROR( "createObject: component '" << desc.getName() << "' of type '" << desc.getAttribute("type","")<< "' in node '"<<context->getName()<<"'" );
        for (std::vector< std::string >::const_iterator it = desc.getErrors().begin(); it != desc.getErrors().end(); ++it)
            SP_MESSAGE_ERROR(*it);
        PyErr_BadArgument();
        return NULL;
    }

    if( warning )
    {
        for( auto it : desc.getAttributeMap() )
        {
            if (!it.second.isAccessed())
            {
                obj->serr <<"Unused Attribute: \""<<it.first <<"\" with value: \"" <<(std::string)it.second<<"\" (" << obj->getPathName() << ")" << obj->sendl;
            }
        }

        Node *node = static_cast<Node*>(context);
        if (node && node->isInitialized())
            SP_MESSAGE_WARNING( "Sofa.Node.createObject("<<type<<") called on a node("<<node->getName()<<") that is already initialized" )
    }

    return sofa::PythonFactory::toPython(obj.get());
}
static PyObject * BaseContext_createObject(PyObject * self, PyObject * args, PyObject * kw)
{
    return BaseContext_createObject_Impl( self, args, kw, true );
}
static PyObject * BaseContext_createObject_noWarning(PyObject * self, PyObject * args, PyObject * kw)
{
    SP_MESSAGE_DEPRECATED("BaseContext_createObject_noWarning is deprecated, use the keyword warning=False in BaseContext_createObject instead.")
            return BaseContext_createObject_Impl( self, args, kw, false );
}

/// the complete relative path to the object must be given
/// returns None with a warning if the object is not found
static PyObject * BaseContext_getObject(PyObject * self, PyObject * args, PyObject * kw)
{
    BaseContext* context = get_basecontext( self );
    char *path;
    if (!PyArg_ParseTuple(args, "s",&path))
    {
        SP_MESSAGE_WARNING( "BaseContext_getObject: wrong argument, should be a string (the complete relative path)" )
        return NULL;
    }

    bool warning = true;
    if (kw && PyDict_Size(kw)>0)
    {
        PyObject* keys = PyDict_Keys(kw);
        PyObject* values = PyDict_Values(kw);
        for (int i=0; i<PyDict_Size(kw); i++)
        {
            PyObject *key = PyList_GetItem(keys,i);
            PyObject *value = PyList_GetItem(values,i);
            if( !strcmp(PyString_AsString(key),"warning") )
            {
                if PyBool_Check(value)
                        warning = (value==Py_True);
                break;
            }
        }
        Py_DecRef(keys);
        Py_DecRef(values);
    }

    if (!context || !path)
    {
        PyErr_BadArgument();
        return NULL;
    }
    BaseObject::SPtr sptr;
    context->get<BaseObject>(sptr,path);
    if (!sptr)
    {
        if(warning) SP_MESSAGE_WARNING( "BaseContext_getObject: component "<<path<<" not found (the complete relative path is needed)" )
        return NULL;
    }

    return sofa::PythonFactory::toPython(sptr.get());
}

/// the complete relative path to the object must be given
/// returns None if the object is not found
static PyObject * BaseContext_getObject_noWarning(PyObject * self, PyObject * args)
{
    SP_MESSAGE_DEPRECATED("BaseContext_getObject_noWarning is deprecated, use the keyword warning=False in BaseContext_getObject instead.")
    BaseContext* context = get_basecontext( self );
    char *path;
    if (!PyArg_ParseTuple(args, "s",&path))
    {
        SP_MESSAGE_WARNING( "BaseContext_getObject_noWarning: wrong argument, should be a string (the complete relative path)" )
        return NULL;
    }
    if (!context || !path)
    {
        PyErr_BadArgument();
        return NULL;
    }
    BaseObject::SPtr sptr;
    context->get<BaseObject>(sptr,path);
    if (!sptr) Py_RETURN_NONE;

    return sofa::PythonFactory::toPython(sptr.get());
}

// @TODO: pass keyword arguments rather than optional arguments?
static PyObject * BaseContext_getObjects(PyObject * self, PyObject * args)
{
    BaseContext* context = get_basecontext( self );
    char* search_direction= NULL;
    char* type_name= NULL;
    char* name= NULL;
    if ( !PyArg_ParseTuple ( args, "|sss", &search_direction, &type_name, &name ) ) {
        SP_MESSAGE_WARNING( "BaseContext_getObjects: wrong arguments! Expected format: getObjects ( OPTIONAL STRING searchDirection, OPTIONAL STRING typeName, OPTIONAL STRING name )" )
        return NULL;
    }

    if (!context)
    {
        PyErr_BadArgument();
        return NULL;
    }

    sofa::core::objectmodel::BaseContext::SearchDirection search_direction_enum= sofa::core::objectmodel::BaseContext::Local;
    if ( search_direction )
    {
        std::string search_direction_str ( search_direction );
        if ( search_direction_str == "SearchUp" )
        {
            search_direction_enum= sofa::core::objectmodel::BaseContext::SearchUp;
        }
        else if ( search_direction_str == "Local" )
        {
            search_direction_enum= sofa::core::objectmodel::BaseContext::Local;
        }
        else if ( search_direction_str == "SearchDown" )
        {
            search_direction_enum= sofa::core::objectmodel::BaseContext::SearchDown;
        }
        else if ( search_direction_str == "SearchRoot" )
        {
            search_direction_enum= sofa::core::objectmodel::BaseContext::SearchRoot;
        }
        else if ( search_direction_str == "SearchParents" )
        {
            search_direction_enum= sofa::core::objectmodel::BaseContext::SearchParents;
        }
        else
        {
            SP_MESSAGE_WARNING( "BaseContext_getObjects: Invalid search direction, using 'Local'. Expected: 'SearchUp', 'Local', 'SearchDown', 'SearchRoot', or 'SearchParents'." )
        }
    }

    sofa::helper::vector< boost::intrusive_ptr<BaseObject> > list;
    context->get<BaseObject>(&list,search_direction_enum);

    PyObject *pyList = PyList_New(0);
    for (size_t i=0; i<list.size(); i++)
    {
        BaseObject* o = list[i].get();

        if( !type_name || o->getClass()->hasParent( type_name ) )
        {
            if ( !name || name == o->getName() )
            {
                PyObject* obj=sofa::PythonFactory::toPython(o); // ref 1
                PyList_Append(pyList,obj); // ref 2
                Py_DECREF(obj); // ref 1 (now owned by list)
            }
        }
    }

    return pyList;
}

SP_CLASS_METHODS_BEGIN(BaseContext)
SP_CLASS_METHOD(BaseContext,getRootContext)
SP_CLASS_METHOD(BaseContext,getTime)
SP_CLASS_METHOD(BaseContext,getDt)
SP_CLASS_METHOD(BaseContext,getGravity)
SP_CLASS_METHOD(BaseContext,setGravity)
SP_CLASS_METHOD_KW(BaseContext,createObject)
SP_CLASS_METHOD_KW(BaseContext,createObject_noWarning) // deprecated
SP_CLASS_METHOD_KW(BaseContext,getObject)
SP_CLASS_METHOD(BaseContext,getObject_noWarning) // deprecated
SP_CLASS_METHOD(BaseContext,getObjects)
SP_CLASS_METHODS_END

static PyObject * BaseContext_getAttr_animate(PyObject *self, void*)
{
    BaseContext* obj = get_basecontext( self );
    return PyBool_FromLong(obj->getAnimate());
}
static int BaseContext_setAttr_animate(PyObject *self, PyObject * args, void*)
{
    BaseContext* obj = get_basecontext( self );
    if (!PyBool_Check(args))
    {
        PyErr_BadArgument();
        return -1;
    }
    obj->setAnimate(args==Py_True);
    return 0;
}

static PyObject * BaseContext_getAttr_active(PyObject *self, void*)
{
    BaseContext* obj = get_basecontext( self );
    return PyBool_FromLong(obj->isActive());
}

static int BaseContext_setAttr_active(PyObject *self, PyObject * args, void*)
{
    BaseContext* obj = get_basecontext( self );
    if (!PyBool_Check(args))
    {
        PyErr_BadArgument();
        return -1;
    }
    obj->setActive(args==Py_True);
    return 0;
}

SP_CLASS_ATTRS_BEGIN(BaseContext)
SP_CLASS_ATTR(BaseContext,active)
SP_CLASS_ATTR(BaseContext,animate)
//SP_CLASS_ATTR(BaseContext,gravity) // attribut objets = problème... le setter ne fonctionne pas
SP_CLASS_ATTRS_END

SP_CLASS_TYPE_SPTR_ATTR(BaseContext,BaseContext,Base)
<|endoftext|>