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

#include "PropertyMapper.hxx"

#include <vector>
//for auto_ptr
#include <memory>
#include <com/sun/star/chart2/DataPointLabel.hpp>
#include <com/sun/star/chart2/Symbol.hpp>
#include <com/sun/star/chart2/StackingDirection.hpp>
#include <com/sun/star/chart2/data/XLabeledDataSequence.hpp>
#include <com/sun/star/chart2/XChartType.hpp>
#include <com/sun/star/chart2/XDataSeries.hpp>
#include <com/sun/star/drawing/HomogenMatrix.hpp>
#include <com/sun/star/drawing/PolyPolygonShape3D.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/drawing/XShapes.hpp>
#include <cppuhelper/weakref.hxx>

namespace chart
{

class VDataSequence
{
public:
    void init( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XDataSequence >& xModel );
    bool is() const;
    void clear();
    double getValue( sal_Int32 index ) const;
    sal_Int32 detectNumberFormatKey( sal_Int32 index ) const;
    sal_Int32 getLength() const;

    ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XDataSequence >     Model;

    mutable ::com::sun::star::uno::Sequence< double > Doubles;
};

class VDataSeries
{
public:
    VDataSeries( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XDataSeries >& xDataSeries );
    virtual ~VDataSeries();

    ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >
        getModel() const;

    void setCategoryXAxis();
    void setXValues( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XDataSequence >& xValues );
    void setXValuesIfNone( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XDataSequence >& xValues );
    void setParticle( const rtl::OUString& rSeriesParticle );
    void setGlobalSeriesIndex( sal_Int32 nGlobalSeriesIndex );
    void setPageReferenceSize( const ::com::sun::star::awt::Size & rPageRefSize );

    sal_Int32   getTotalPointCount() const;
    double      getXValue( sal_Int32 index ) const;
    double      getYValue( sal_Int32 index ) const;

    double      getY_Min( sal_Int32 index ) const;
    double      getY_Max( sal_Int32 index ) const;
    double      getY_First( sal_Int32 index ) const;
    double      getY_Last( sal_Int32 index ) const;

    double      getBubble_Size( sal_Int32 index ) const;

    double      getMinimumofAllDifferentYValues( sal_Int32 index ) const;
    double      getMaximumofAllDifferentYValues( sal_Int32 index ) const;

    ::com::sun::star::uno::Sequence< double > getAllX() const;
    ::com::sun::star::uno::Sequence< double > getAllY() const;

    double getXMeanValue() const;
    double getYMeanValue() const;

    bool        hasExplicitNumberFormat( sal_Int32 nPointIndex, bool bForPercentage ) const;
    sal_Int32   getExplicitNumberFormat( sal_Int32 nPointIndex, bool bForPercentage ) const;
    sal_Int32   detectNumberFormatKey( sal_Int32 nPointIndex ) const;
    bool        shouldLabelNumberFormatKeyBeDetectedFromYAxis() const;

    sal_Int32   getLabelPlacement( sal_Int32 nPointIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType
                        , sal_Int32 nDimensionCount, sal_Bool bSwapXAndY ) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        getPropertiesOfPoint( sal_Int32 index ) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        getPropertiesOfSeries() const;

    ::com::sun::star::chart2::Symbol*
                        getSymbolProperties( sal_Int32 index ) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        getXErrorBarProperties( sal_Int32 index ) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        getYErrorBarProperties( sal_Int32 index ) const;

    bool hasPointOwnColor( sal_Int32 index ) const;

    ::com::sun::star::chart2::StackingDirection getStackingDirection() const;
    sal_Int32 getAttachedAxisIndex() const;
    void setAttachedAxisIndex( sal_Int32 nAttachedAxisIndex );

    void doSortByXValues();

    void setConnectBars( sal_Bool bConnectBars );
    sal_Bool getConnectBars() const;

    void setGroupBarsPerAxis( sal_Bool bGroupBarsPerAxis );
    sal_Bool getGroupBarsPerAxis() const;

    void setStartingAngle( sal_Int32 nStartingAngle );
    sal_Int32 getStartingAngle() const;

    void setRoleOfSequenceForDataLabelNumberFormatDetection( const rtl::OUString& rRole );

    //this is only temporarily here for area chart:
    ::com::sun::star::drawing::PolyPolygonShape3D       m_aPolyPolygonShape3D;
    sal_Int32   m_nPolygonIndex;
    double m_fLogicMinX;
    double m_fLogicMaxX;

    //this is here for deep stacking:
    double m_fLogicZPos;//from 0 to series count -1

    rtl::OUString       getCID() const;
    rtl::OUString       getSeriesParticle() const;
    rtl::OUString       getPointCID_Stub() const;
    rtl::OUString       getErrorBarsCID( bool bYError ) const;
    rtl::OUString       getLabelsCID() const;
    rtl::OUString       getLabelCID_Stub() const;
    rtl::OUString       getDataCurveCID( sal_Int32 nCurveIndex, bool bAverageLine ) const;

    ::com::sun::star::chart2::DataPointLabel*
                        getDataPointLabelIfLabel( sal_Int32 index ) const;
    bool    getTextLabelMultiPropertyLists( sal_Int32 index, tNameSequence*& pPropNames, tAnySequence*& pPropValues ) const;

    rtl::OUString       getDataCurveEquationCID( sal_Int32 nCurveIndex ) const;
    bool    isAttributedDataPoint( sal_Int32 index ) const;

    bool    isVaryColorsByPoint() const;

    void releaseShapes();

    void setMissingValueTreatment( sal_Int32 nMissingValueTreatment );
    sal_Int32 getMissingValueTreatment() const;

private: //methods
    ::com::sun::star::chart2::DataPointLabel*
                        getDataPointLabel( sal_Int32 index ) const;
    void adaptPointCache( sal_Int32 nNewPointIndex ) const;

public: //member
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xGroupShape;
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xLabelsGroupShape;
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xErrorXBarsGroupShape;
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xErrorYBarsGroupShape;

    //the following group shapes will be created as children of m_xGroupShape on demand
    //they can be used to assure that some parts of a series shape are always in front of others (e.g. symbols in front of lines)
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xFrontSubGroupShape;
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xBackSubGroupShape;

private: //member
    ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDataSeries >       m_xDataSeries;
    ::com::sun::star::uno::Sequence<
        ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::data::XLabeledDataSequence > >   m_aDataSequences;

    //all points given by the model data (here are not only the visible points meant)
    sal_Int32       m_nPointCount;

    VDataSequence   m_aValues_X;
    VDataSequence   m_aValues_Y;
    VDataSequence   m_aValues_Z;

    VDataSequence   m_aValues_Y_Min;
    VDataSequence   m_aValues_Y_Max;
    VDataSequence   m_aValues_Y_First;
    VDataSequence   m_aValues_Y_Last;

    VDataSequence   m_aValues_Bubble_Size;

    VDataSequence*  m_pValueSequenceForDataLabelNumberFormatDetection;

    mutable double m_fXMeanValue;
    mutable double m_fYMeanValue;

    ::com::sun::star::uno::Sequence< sal_Int32 >    m_aAttributedDataPointIndexList;

    ::com::sun::star::chart2::StackingDirection     m_eStackingDirection;

    sal_Int32               m_nAxisIndex;//indicates whether this is attached to a main or secondary axis

    sal_Bool                m_bConnectBars;

    sal_Bool                m_bGroupBarsPerAxis;

    sal_Int32               m_nStartingAngle;

    rtl::OUString           m_aSeriesParticle;
    rtl::OUString           m_aCID;
    rtl::OUString           m_aPointCID_Stub;
    rtl::OUString           m_aLabelCID_Stub;

    sal_Int32               m_nGlobalSeriesIndex;

    //some cached values for data labels as they are very expensive
    SAL_WNODEPRECATED_DECLARATIONS_PUSH
    mutable ::std::auto_ptr< ::com::sun::star::chart2::DataPointLabel >
                                                    m_apLabel_Series;
    mutable ::std::auto_ptr< tNameSequence >        m_apLabelPropNames_Series;
    mutable ::std::auto_ptr< tAnySequence >         m_apLabelPropValues_Series;
    mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol >
                                                    m_apSymbolProperties_Series;

    mutable ::std::auto_ptr< ::com::sun::star::chart2::DataPointLabel >
                                                    m_apLabel_AttributedPoint;
    mutable ::std::auto_ptr< tNameSequence >        m_apLabelPropNames_AttributedPoint;
    mutable ::std::auto_ptr< tAnySequence >         m_apLabelPropValues_AttributedPoint;
    mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol >
                                                    m_apSymbolProperties_AttributedPoint;
    mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol >
                                                    m_apSymbolProperties_InvisibleSymbolForSelection;
    SAL_WNODEPRECATED_DECLARATIONS_POP
    mutable sal_Int32                               m_nCurrentAttributedPoint;
    ::com::sun::star::awt::Size                     m_aReferenceSize;

    sal_Int32   m_nMissingValueTreatment;
    bool        m_bAllowPercentValueInDataLabel;
};

} //namespace chart
#endif

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

#include "PropertyMapper.hxx"

#include <vector>
//for auto_ptr
#include <memory>
#include <com/sun/star/chart2/DataPointLabel.hpp>
#include <com/sun/star/chart2/Symbol.hpp>
#include <com/sun/star/chart2/StackingDirection.hpp>
#include <com/sun/star/chart2/data/XLabeledDataSequence.hpp>
#include <com/sun/star/chart2/XChartType.hpp>
#include <com/sun/star/chart2/XDataSeries.hpp>
#include <com/sun/star/drawing/HomogenMatrix.hpp>
#include <com/sun/star/drawing/PolyPolygonShape3D.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/drawing/XShapes.hpp>
#include <cppuhelper/weakref.hxx>

#include <boost/noncopyable.hpp>

namespace chart
{

class VDataSequence : boost::noncopyable
{
public:
    void init( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XDataSequence >& xModel );
    bool is() const;
    void clear();
    double getValue( sal_Int32 index ) const;
    sal_Int32 detectNumberFormatKey( sal_Int32 index ) const;
    sal_Int32 getLength() const;

    ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XDataSequence >     Model;

    mutable ::com::sun::star::uno::Sequence< double > Doubles;
};

class VDataSeries : boost::noncopyable
{
public:
    VDataSeries( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XDataSeries >& xDataSeries );
    virtual ~VDataSeries();

    ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >
        getModel() const;

    void setCategoryXAxis();
    void setXValues( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XDataSequence >& xValues );
    void setXValuesIfNone( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XDataSequence >& xValues );
    void setParticle( const rtl::OUString& rSeriesParticle );
    void setGlobalSeriesIndex( sal_Int32 nGlobalSeriesIndex );
    void setPageReferenceSize( const ::com::sun::star::awt::Size & rPageRefSize );

    sal_Int32   getTotalPointCount() const;
    double      getXValue( sal_Int32 index ) const;
    double      getYValue( sal_Int32 index ) const;

    double      getY_Min( sal_Int32 index ) const;
    double      getY_Max( sal_Int32 index ) const;
    double      getY_First( sal_Int32 index ) const;
    double      getY_Last( sal_Int32 index ) const;

    double      getBubble_Size( sal_Int32 index ) const;

    double      getMinimumofAllDifferentYValues( sal_Int32 index ) const;
    double      getMaximumofAllDifferentYValues( sal_Int32 index ) const;

    ::com::sun::star::uno::Sequence< double > getAllX() const;
    ::com::sun::star::uno::Sequence< double > getAllY() const;

    double getXMeanValue() const;
    double getYMeanValue() const;

    bool        hasExplicitNumberFormat( sal_Int32 nPointIndex, bool bForPercentage ) const;
    sal_Int32   getExplicitNumberFormat( sal_Int32 nPointIndex, bool bForPercentage ) const;
    sal_Int32   detectNumberFormatKey( sal_Int32 nPointIndex ) const;
    bool        shouldLabelNumberFormatKeyBeDetectedFromYAxis() const;

    sal_Int32   getLabelPlacement( sal_Int32 nPointIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType
                        , sal_Int32 nDimensionCount, sal_Bool bSwapXAndY ) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        getPropertiesOfPoint( sal_Int32 index ) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        getPropertiesOfSeries() const;

    ::com::sun::star::chart2::Symbol*
                        getSymbolProperties( sal_Int32 index ) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        getXErrorBarProperties( sal_Int32 index ) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        getYErrorBarProperties( sal_Int32 index ) const;

    bool hasPointOwnColor( sal_Int32 index ) const;

    ::com::sun::star::chart2::StackingDirection getStackingDirection() const;
    sal_Int32 getAttachedAxisIndex() const;
    void setAttachedAxisIndex( sal_Int32 nAttachedAxisIndex );

    void doSortByXValues();

    void setConnectBars( sal_Bool bConnectBars );
    sal_Bool getConnectBars() const;

    void setGroupBarsPerAxis( sal_Bool bGroupBarsPerAxis );
    sal_Bool getGroupBarsPerAxis() const;

    void setStartingAngle( sal_Int32 nStartingAngle );
    sal_Int32 getStartingAngle() const;

    void setRoleOfSequenceForDataLabelNumberFormatDetection( const rtl::OUString& rRole );

    //this is only temporarily here for area chart:
    ::com::sun::star::drawing::PolyPolygonShape3D       m_aPolyPolygonShape3D;
    sal_Int32   m_nPolygonIndex;
    double m_fLogicMinX;
    double m_fLogicMaxX;

    //this is here for deep stacking:
    double m_fLogicZPos;//from 0 to series count -1

    rtl::OUString       getCID() const;
    rtl::OUString       getSeriesParticle() const;
    rtl::OUString       getPointCID_Stub() const;
    rtl::OUString       getErrorBarsCID( bool bYError ) const;
    rtl::OUString       getLabelsCID() const;
    rtl::OUString       getLabelCID_Stub() const;
    rtl::OUString       getDataCurveCID( sal_Int32 nCurveIndex, bool bAverageLine ) const;

    ::com::sun::star::chart2::DataPointLabel*
                        getDataPointLabelIfLabel( sal_Int32 index ) const;
    bool    getTextLabelMultiPropertyLists( sal_Int32 index, tNameSequence*& pPropNames, tAnySequence*& pPropValues ) const;

    rtl::OUString       getDataCurveEquationCID( sal_Int32 nCurveIndex ) const;
    bool    isAttributedDataPoint( sal_Int32 index ) const;

    bool    isVaryColorsByPoint() const;

    void releaseShapes();

    void setMissingValueTreatment( sal_Int32 nMissingValueTreatment );
    sal_Int32 getMissingValueTreatment() const;

private: //methods
    ::com::sun::star::chart2::DataPointLabel*
                        getDataPointLabel( sal_Int32 index ) const;
    void adaptPointCache( sal_Int32 nNewPointIndex ) const;

public: //member
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xGroupShape;
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xLabelsGroupShape;
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xErrorXBarsGroupShape;
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xErrorYBarsGroupShape;

    //the following group shapes will be created as children of m_xGroupShape on demand
    //they can be used to assure that some parts of a series shape are always in front of others (e.g. symbols in front of lines)
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xFrontSubGroupShape;
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xBackSubGroupShape;

private: //member
    ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDataSeries >       m_xDataSeries;
    ::com::sun::star::uno::Sequence<
        ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::data::XLabeledDataSequence > >   m_aDataSequences;

    //all points given by the model data (here are not only the visible points meant)
    sal_Int32       m_nPointCount;

    VDataSequence   m_aValues_X;
    VDataSequence   m_aValues_Y;
    VDataSequence   m_aValues_Z;

    VDataSequence   m_aValues_Y_Min;
    VDataSequence   m_aValues_Y_Max;
    VDataSequence   m_aValues_Y_First;
    VDataSequence   m_aValues_Y_Last;

    VDataSequence   m_aValues_Bubble_Size;

    VDataSequence*  m_pValueSequenceForDataLabelNumberFormatDetection;

    mutable double m_fXMeanValue;
    mutable double m_fYMeanValue;

    ::com::sun::star::uno::Sequence< sal_Int32 >    m_aAttributedDataPointIndexList;

    ::com::sun::star::chart2::StackingDirection     m_eStackingDirection;

    sal_Int32               m_nAxisIndex;//indicates whether this is attached to a main or secondary axis

    sal_Bool                m_bConnectBars;

    sal_Bool                m_bGroupBarsPerAxis;

    sal_Int32               m_nStartingAngle;

    rtl::OUString           m_aSeriesParticle;
    rtl::OUString           m_aCID;
    rtl::OUString           m_aPointCID_Stub;
    rtl::OUString           m_aLabelCID_Stub;

    sal_Int32               m_nGlobalSeriesIndex;

    //some cached values for data labels as they are very expensive
    SAL_WNODEPRECATED_DECLARATIONS_PUSH
    mutable ::std::auto_ptr< ::com::sun::star::chart2::DataPointLabel >
                                                    m_apLabel_Series;
    mutable ::std::auto_ptr< tNameSequence >        m_apLabelPropNames_Series;
    mutable ::std::auto_ptr< tAnySequence >         m_apLabelPropValues_Series;
    mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol >
                                                    m_apSymbolProperties_Series;

    mutable ::std::auto_ptr< ::com::sun::star::chart2::DataPointLabel >
                                                    m_apLabel_AttributedPoint;
    mutable ::std::auto_ptr< tNameSequence >        m_apLabelPropNames_AttributedPoint;
    mutable ::std::auto_ptr< tAnySequence >         m_apLabelPropValues_AttributedPoint;
    mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol >
                                                    m_apSymbolProperties_AttributedPoint;
    mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol >
                                                    m_apSymbolProperties_InvisibleSymbolForSelection;
    SAL_WNODEPRECATED_DECLARATIONS_POP
    mutable sal_Int32                               m_nCurrentAttributedPoint;
    ::com::sun::star::awt::Size                     m_aReferenceSize;

    sal_Int32   m_nMissingValueTreatment;
    bool        m_bAllowPercentValueInDataLabel;
};

} //namespace chart
#endif

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


<commit_before>#include <ph.h>
#include <chef.h>
#include <phstream.h>
#include <phInput.h>
#include <phBC.h>
#include <phRestart.h>
#include <phAdapt.h>
#include <phOutput.h>
#include <phPartition.h>
#include <phFilterMatching.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfPartition.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <PCU.h>
#include <pcu_io.h>
#include <string>
#include <stdlib.h>

#define SIZET(a) static_cast<size_t>(a)

namespace {

void balanceAndReorder(apf::Mesh2* m, ph::Input& in, int numMasters)
{
  /* check if the mesh changed at all */
  if ((PCU_Comm_Peers()!=numMasters) || in.adaptFlag || in.tetrahedronize) {
    if (in.parmaPtn && PCU_Comm_Peers() > 1)
      ph::balance(in,m);
    apf::reorderMdsMesh(m);
  }
}

void switchToMasters(int splitFactor)
{
  int self = PCU_Comm_Self();
  int groupRank = self / splitFactor;
  int group = self % splitFactor;
  MPI_Comm groupComm;
  MPI_Comm_split(MPI_COMM_WORLD, group, groupRank, &groupComm);
  PCU_Switch_Comm(groupComm);
}

void switchToAll()
{
  MPI_Comm prevComm = PCU_Get_Comm();
  PCU_Switch_Comm(MPI_COMM_WORLD);
  MPI_Comm_free(&prevComm);
  PCU_Barrier();
}

void loadCommon(ph::Input& in, ph::BCs& bcs, gmi_model*& g)
{
  ph::readBCs(in.attributeFileName.c_str(), bcs);
  if(!g)
    g = gmi_load(in.modelFileName.c_str());
}

void originalMain(apf::Mesh2*& m, ph::Input& in,
    gmi_model* g, apf::Migration*& plan)
{
  if(!m)
    m = apf::loadMdsMesh(g, in.meshFileName.c_str());
  else
    apf::printStats(m);
  m->verify();
  if (in.solutionMigration)
    ph::readAndAttachFields(in, m);
  else
    ph::attachZeroSolution(in, m);
  if (in.buildMapping)
    ph::buildMapping(m);
  apf::setMigrationLimit(SIZET(in.elementsPerMigration));
  if (in.adaptFlag)
    ph::adapt(in, m);
  if (in.tetrahedronize)
    ph::tetrahedronize(in, m);
  plan = ph::split(in, m);
}

}//end namespace

namespace ph {
  void preprocess(apf::Mesh2* m, Input& in, Output& out, BCs& bcs) {
    if (in.adaptFlag)
      ph::goToStepDir(in.timeStepNumber);
    std::string path = ph::setupOutputDir();
    ph::setupOutputSubdir(path);
    ph::enterFilteredMatching(m, in, bcs);
    ph::generateOutput(in, bcs, m, out);
    ph::exitFilteredMatching(m);
    // a path is not needed for inmem
    ph::detachAndWriteSolution(in,out,m,path); //write restart
    ph::writeGeomBC(out, path); //write geombc
    ph::writeAuxiliaryFiles(path, in.timeStepNumber);
    if ( ! in.outMeshFileName.empty() )
      m->writeNative(in.outMeshFileName.c_str());
    m->verify();
    if (in.adaptFlag)
      ph::goToParentDir();
  }
  void preprocess(apf::Mesh2* m, Input& in, Output& out) {
    BCs bcs;
    ph::readBCs(in.attributeFileName.c_str(), bcs);
    preprocess(m,in,out,bcs);
  }
}

namespace chef {
  static FILE* openfile_read(ph::Input&, const char* path) {
    return pcu_group_open(path, false);
  }

  static FILE* openfile_write(ph::Output&, const char* path) {
    return pcu_group_open(path, true);
  }

  static FILE* openstream_write(ph::Output& out, const char* path) {
    return openGRStreamWrite(out.grs, path);
  }

  static FILE* openstream_read(ph::Input& in, const char* path) {
    std::string fname(path);
    std::string restartStr("restart");
    FILE* f = NULL;
    if( fname.find(restartStr) != std::string::npos )
      f = openRStreamRead(in.rs);
    else {
      fprintf(stderr,
        "ERROR %s type of stream %s is unknown... exiting\n",
        __func__, fname.c_str());
      exit(1);
    }
    return f;
  }
  void bake(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& in, ph::Output& out) {
    apf::Migration* plan = 0;
    ph::BCs bcs;
    loadCommon(in, bcs, g);
    const int worldRank = PCU_Comm_Self();
    switchToMasters(in.splitFactor);
    const int numMasters = PCU_Comm_Peers();
    if ((worldRank % in.splitFactor) == 0)
      originalMain(m, in, g, plan);
    switchToAll();
    m = repeatMdsMesh(m, g, plan, in.splitFactor);
    balanceAndReorder(m,in,numMasters);
    ph::preprocess(m,in,out,bcs);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m) {
    ph::Input in;
    in.load("adapt.inp");
    in.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,in,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, GRStream* grs) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
    return;
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs, GRStream* grs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
    return;
  }

  void readAndAttachFields(ph::Input& ctrl, apf::Mesh2*& m) {
    ph::readAndAttachFields(ctrl, m);
  }

  void preprocess(apf::Mesh2*& m, ph::Input& in) {
    ph::Output out;
    out.openfile_write = chef::openfile_write;
    ph::preprocess(m,in,out);
  }

  void preprocess(apf::Mesh2*& m, ph::Input& in, GRStream* grs) {
    ph::Output out;
    out.openfile_write = chef::openstream_write;
    out.grs = grs;
    ph::preprocess(m,in,out);
  }
}

<commit_msg>chef reorders with parma<commit_after>#include <ph.h>
#include <chef.h>
#include <phstream.h>
#include <phInput.h>
#include <phBC.h>
#include <phRestart.h>
#include <phAdapt.h>
#include <phOutput.h>
#include <phPartition.h>
#include <phFilterMatching.h>
#include <parma.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfPartition.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <PCU.h>
#include <pcu_io.h>
#include <string>
#include <stdlib.h>

#define SIZET(a) static_cast<size_t>(a)

namespace {

void balanceAndReorder(apf::Mesh2* m, ph::Input& in, int numMasters)
{
  /* check if the mesh changed at all */
  if ( (PCU_Comm_Peers()!=numMasters) ||
       in.adaptFlag ||
       in.tetrahedronize ||
       in.isReorder )
  {
    if (in.parmaPtn && PCU_Comm_Peers() > 1)
      ph::balance(in,m);
    apf::MeshTag* order = NULL;
    if (PCU_Comm_Peers() > 1)
      order = Parma_BfsReorder(m);
    apf::reorderMdsMesh(m,order);
  }
}

void switchToMasters(int splitFactor)
{
  int self = PCU_Comm_Self();
  int groupRank = self / splitFactor;
  int group = self % splitFactor;
  MPI_Comm groupComm;
  MPI_Comm_split(MPI_COMM_WORLD, group, groupRank, &groupComm);
  PCU_Switch_Comm(groupComm);
}

void switchToAll()
{
  MPI_Comm prevComm = PCU_Get_Comm();
  PCU_Switch_Comm(MPI_COMM_WORLD);
  MPI_Comm_free(&prevComm);
  PCU_Barrier();
}

void loadCommon(ph::Input& in, ph::BCs& bcs, gmi_model*& g)
{
  ph::readBCs(in.attributeFileName.c_str(), bcs);
  if(!g)
    g = gmi_load(in.modelFileName.c_str());
}

void originalMain(apf::Mesh2*& m, ph::Input& in,
    gmi_model* g, apf::Migration*& plan)
{
  if(!m)
    m = apf::loadMdsMesh(g, in.meshFileName.c_str());
  else
    apf::printStats(m);
  m->verify();
  if (in.solutionMigration)
    ph::readAndAttachFields(in, m);
  else
    ph::attachZeroSolution(in, m);
  if (in.buildMapping)
    ph::buildMapping(m);
  apf::setMigrationLimit(SIZET(in.elementsPerMigration));
  if (in.adaptFlag)
    ph::adapt(in, m);
  if (in.tetrahedronize)
    ph::tetrahedronize(in, m);
  plan = ph::split(in, m);
}

}//end namespace

namespace ph {
  void preprocess(apf::Mesh2* m, Input& in, Output& out, BCs& bcs) {
    if (in.adaptFlag)
      ph::goToStepDir(in.timeStepNumber);
    std::string path = ph::setupOutputDir();
    ph::setupOutputSubdir(path);
    ph::enterFilteredMatching(m, in, bcs);
    ph::generateOutput(in, bcs, m, out);
    ph::exitFilteredMatching(m);
    // a path is not needed for inmem
    ph::detachAndWriteSolution(in,out,m,path); //write restart
    ph::writeGeomBC(out, path); //write geombc
    ph::writeAuxiliaryFiles(path, in.timeStepNumber);
    if ( ! in.outMeshFileName.empty() )
      m->writeNative(in.outMeshFileName.c_str());
    m->verify();
    if (in.adaptFlag)
      ph::goToParentDir();
  }
  void preprocess(apf::Mesh2* m, Input& in, Output& out) {
    BCs bcs;
    ph::readBCs(in.attributeFileName.c_str(), bcs);
    preprocess(m,in,out,bcs);
  }
}

namespace chef {
  static FILE* openfile_read(ph::Input&, const char* path) {
    return pcu_group_open(path, false);
  }

  static FILE* openfile_write(ph::Output&, const char* path) {
    return pcu_group_open(path, true);
  }

  static FILE* openstream_write(ph::Output& out, const char* path) {
    return openGRStreamWrite(out.grs, path);
  }

  static FILE* openstream_read(ph::Input& in, const char* path) {
    std::string fname(path);
    std::string restartStr("restart");
    FILE* f = NULL;
    if( fname.find(restartStr) != std::string::npos )
      f = openRStreamRead(in.rs);
    else {
      fprintf(stderr,
        "ERROR %s type of stream %s is unknown... exiting\n",
        __func__, fname.c_str());
      exit(1);
    }
    return f;
  }
  void bake(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& in, ph::Output& out) {
    apf::Migration* plan = 0;
    ph::BCs bcs;
    loadCommon(in, bcs, g);
    const int worldRank = PCU_Comm_Self();
    switchToMasters(in.splitFactor);
    const int numMasters = PCU_Comm_Peers();
    if ((worldRank % in.splitFactor) == 0)
      originalMain(m, in, g, plan);
    switchToAll();
    m = repeatMdsMesh(m, g, plan, in.splitFactor);
    balanceAndReorder(m,in,numMasters);
    ph::preprocess(m,in,out,bcs);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m) {
    ph::Input in;
    in.load("adapt.inp");
    in.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,in,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, GRStream* grs) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
    return;
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs, GRStream* grs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
    return;
  }

  void readAndAttachFields(ph::Input& ctrl, apf::Mesh2*& m) {
    ph::readAndAttachFields(ctrl, m);
  }

  void preprocess(apf::Mesh2*& m, ph::Input& in) {
    ph::Output out;
    out.openfile_write = chef::openfile_write;
    ph::preprocess(m,in,out);
  }

  void preprocess(apf::Mesh2*& m, ph::Input& in, GRStream* grs) {
    ph::Output out;
    out.openfile_write = chef::openstream_write;
    out.grs = grs;
    ph::preprocess(m,in,out);
  }
}

<|endoftext|>


<commit_before>#include "openconnection.h"
#include "../core/string.h"
#include "upnp/openconnect.h"
#include "../parser/gttpacket.h"
#include "listener.h"
namespace Epyx {
    namespace DirectConnection {
        // In this protocol, the client is stupid and just obey orders
        OpenConnection::OpenConnection(N2NP::Node &node, N2NP::NodeId &remoteHost, bool clients)
        :remoteHost(remoteHost), etat(STATE_SERVER), client_tried(false), server_tried(false),
        tested_method(DIRECT), node(&node), socket(NULL)
        {
            if (clients){
                etat = STATE_CLIENT;
            }
        }
        void OpenConnection::getMessage(const std::string& command, const std::map<std::string, std::string>& headers){
            if (command == "SEND" && etat == STATE_CLIENT){
                std::string message;
                std::map<std::string, std::string>::const_iterator headAddr = headers.find("Address");
                if (headAddr == headers.end())
                    throw ParserException("OpenConnection", "No address in headers");
                std::map<std::string, std::string>::const_iterator headMessage = headers.find("Message");
                if (headMessage == headers.end())
                    throw ParserException("OpenConnection", "No message in headers");

                Address addr(headAddr->second);
                socket = new TCPSocket(addr);
                if (socket->send(headMessage->second.c_str(), headMessage->second.size()) != 0){
                    //Success, Do nothing and wait for N2NP confirmation
                }else{
                    //Failed
                    //Send Did Not Work Message
                    GTTPacket pkt;
                    pkt.method ="DID_NOT_WORK";
                    this->node->send(this->remoteHost,"DIRECTCONNECTION",pkt);
                    this->getMessage("DID_NOT_WORK", std::map<std::string, std::string>());
                }
            }else if (command == "DID_NOT_WORK"){
                if (etat == STATE_SERVER && client_tried == false) // If we played the server, we now play the client. Easy Case.
                    server_tried = true;
                else if (etat == STATE_SERVER){
                    if (tested_method == DIRECT){
                        tested_method = UPNP;
                        client_tried = false;
                        server_tried = false;
                        etat = STATE_CLIENT;
                    }
                }else if(etat == STATE_CLIENT && server_tried == false){
                    etat = STATE_SERVER;
                    serverStateOpen();
                }else if (STATE_CLIENT){
                    if (tested_method == DIRECT){
                        tested_method = UPNP;
                        client_tried = false;
                        server_tried = false;
                        etat = STATE_SERVER;
                    }
                    serverStateOpen();
                }
            }else if (command == "ESTABLISHED") {
                //Do Shit, and register the socket to the N2NP module
                node->offerDirectConn(this->remoteHost,this->socket);
/*            }else if (command == "FAILED" ){ // No Useful yet

              }//*/
            }
        }

        void OpenConnection::serverStateOpen(){
            //First we open a listening socket on an available port
            Listener sockListen(new TCPServer(Address("0.0.0.0:0"),20));
            sockListen.start();
            Address addr = Address (node->getNodeAddress().getIp(),sockListen.getLocalAddress().getPort());
            //If we're using UPNP, we open a port mapping
            if (tested_method == UPNP){
                Epyx::UPNP::Natpunch nat;
                //log::fatal << "nat.openMapPort(addr.getPort(),remotePort); not yet implemented" << log::endl;
                addr = nat.openMapPort(addr.getPort());
            }
            //Now, Ask to open a connection.
            GTTPacket pkt;
            pkt.method = "SEND";
            pkt.headers["Address"] = addr.toString();

        }
        void OpenConnection::run(){
            if (etat == STATE_SERVER){
                serverStateOpen();
            }else if (etat == STATE_CLIENT){

            }
        }
    } // namespace DirectConnection
} // namespace Epyx
<commit_msg>Added a missing part in managing the establishment of the direct connection<commit_after>#include "openconnection.h"
#include "../core/string.h"
#include "upnp/openconnect.h"
#include "../parser/gttpacket.h"
#include "listener.h"
namespace Epyx {
    namespace DirectConnection {
        // In this protocol, the client is stupid and just obey orders
        OpenConnection::OpenConnection(N2NP::Node &node, N2NP::NodeId &remoteHost, bool clients)
        :remoteHost(remoteHost), etat(STATE_SERVER), client_tried(false), server_tried(false),
        tested_method(DIRECT), node(&node), socket(NULL)
        {
            if (clients){
                etat = STATE_CLIENT;
            }
        }
        void OpenConnection::getMessage(const std::string& command, const std::map<std::string, std::string>& headers){
            if (command == "SEND" && etat == STATE_CLIENT){
                std::string message;
                std::map<std::string, std::string>::const_iterator headAddr = headers.find("Address");
                if (headAddr == headers.end())
                    throw ParserException("OpenConnection", "No address in headers");
                std::map<std::string, std::string>::const_iterator headMessage = headers.find("Message");
                if (headMessage == headers.end())
                    throw ParserException("OpenConnection", "No message in headers");

                Address addr(headAddr->second);
                socket = new TCPSocket(addr);
                if (socket->send(headMessage->second.c_str(), headMessage->second.size()) != 0){
                    //Success, Do nothing and wait for N2NP confirmation
                }else{
                    //Failed
                    //Send Did Not Work Message
                    GTTPacket pkt;
                    pkt.method ="DID_NOT_WORK";
                    this->node->send(this->remoteHost,"DIRECTCONNECTION",pkt);
                    this->getMessage("DID_NOT_WORK", std::map<std::string, std::string>());
                }
            }else if (command == "DID_NOT_WORK"){
                if (etat == STATE_SERVER && client_tried == false) // If we played the server, we now play the client. Easy Case.
                    server_tried = true;
                else if (etat == STATE_SERVER){
                    if (tested_method == DIRECT){
                        tested_method = UPNP;
                        client_tried = false;
                        server_tried = false;
                        etat = STATE_CLIENT;
                    }
                }else if(etat == STATE_CLIENT && server_tried == false){
                    etat = STATE_SERVER;
                    serverStateOpen();
                }else if (STATE_CLIENT){
                    if (tested_method == DIRECT){
                        tested_method = UPNP;
                        client_tried = false;
                        server_tried = false;
                        etat = STATE_SERVER;
                    }
                    serverStateOpen();
                }
            }else if (command == "ESTABLISHED") {
                //Do Shit, and register the socket to the N2NP module
                node->offerDirectConn(this->remoteHost,this->socket);
/*            }else if (command == "FAILED" ){ // No Useful yet

              }//*/
            }
        }

        void OpenConnection::serverStateOpen(){
            std::string testMessage ="Test";
            //First we open a listening socket on an available port
            Listener sockListen(new TCPServer(Address("0.0.0.0:0"),20));
            sockListen.start();
            Address addr = Address (node->getNodeAddress().getIp(),sockListen.getLocalAddress().getPort());
            //If we're using UPNP, we open a port mapping
            if (tested_method == UPNP){
                Epyx::UPNP::Natpunch nat;
                //log::fatal << "nat.openMapPort(addr.getPort(),remotePort); not yet implemented" << log::endl;
                addr = nat.openMapPort(addr.getPort());
            }
            //Now, Ask to open a connection.
            GTTPacket pkt;
            pkt.method = "SEND";
            pkt.headers["Address"] = addr.toString();
            pkt.headers["Message"] = testMessage;
            this->node->send(this->remoteHost,"DIRECTCONNECTION",pkt);
            char[10] data;
            sockListen.getSocket()->recv((void *) data,10);
            if (std::string(data) == testMessage){
                pkt.method="ESTABLISHED";
                node->offerDirectConn(this->remoteHost,sockListen.getSocket());
                node->send(this->remoteHost,"DIRECTCONNECTION",pkt);
            }else{
                pkt.method="DID_NOT_WORK";
                sockListen.getSocket()->close();
                sockListen.term();
                node->send(this->remoteHost,"DIRECTCONNECTION",pkt);
                this->getMessage("DID_NOT_WORK", std::map<std::string, std::string>());
            }

        }
        void OpenConnection::run(){
            if (etat == STATE_SERVER){
                GTTPacket pkt;
                pkt.method = "SEND";

                serverStateOpen();
            }else if (etat == STATE_CLIENT){

            }
        }
    } // namespace DirectConnection
} // namespace Epyx
<|endoftext|>


<commit_before>#include "render/RenderTarget.h"

#include <glad/glad.h>

#include "base/basedef.h"
#include "math/mathdef.h"
#include "render/Render.h"

using fei::RenderTarget;

std::vector<GLfloat> RenderTarget::computeBuffer_;

RenderTarget::RenderTarget()
: _renderbuffer(0),
  _framebuffer(0),
  _width(0),
  _height(0),
  _tmpBind(false)
{
}

RenderTarget::~RenderTarget()
{
	deleteBuffers();
}

RenderTarget::RenderTarget(const fei::Vec2& size)
: RenderTarget()
{
	setSize(size);
}

RenderTarget::RenderTarget(GLsizei width, GLsizei height)
: RenderTarget()
{
	setSize(width, height);
}

fei::Texture* RenderTarget::getTexture()
{
	return &_texture;
}

void RenderTarget::setSize(const fei::Vec2& size, fei::Texture::Format format)
{
	setSize(static_cast<GLsizei>(size.x), static_cast<GLsizei>(size.y), format);
}

void RenderTarget::setSize(GLsizei width, GLsizei height, fei::Texture::Format format)
{
	if (width == 0 || height == 0) {
		return;
	}
	if (width != _width || height != _height) {
		_width = width;
		_height = height;
		_texture.load(nullptr, width, height, format);
		genBuffers();

		glBindRenderbuffer(GL_RENDERBUFFER, _renderbuffer);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
		glBindRenderbuffer(GL_RENDERBUFFER, 0);
		tmpBind();
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, getTexture()->getId(), 0);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _renderbuffer);
		tmpUnbind();
	}
}

void RenderTarget::bindColorAttachment(fei::Texture* texture, int attachIndex)
{
	GLuint texId = 0;
	if (texture != nullptr) {
		texId = texture->getId();
	}
	tmpBind();
	glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachIndex, GL_TEXTURE_2D, texId, 0);
	tmpUnbind();
}

void RenderTarget::setDrawBuffers(const std::vector<GLenum>& buffers)
{
	tmpBind();
	glDrawBuffers(static_cast<GLsizei>(buffers.size()), &(buffers[0]));
	tmpUnbind();
}

void RenderTarget::bind()
{
	if (!isBind()) {
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _framebuffer);
		fei::Render::getInstance()->setCurrentRenderTarget(this);
	}
}

void RenderTarget::unbind()
{
	if (isBind()) {
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
		fei::Render::getInstance()->setCurrentRenderTarget(nullptr);
	}
}

bool RenderTarget::isBind()
{
	return fei::Render::getInstance()->getCurrentRenderTarget() == this;
}

float RenderTarget::getHDRLw()
{
	float ret = 0.0f;
	auto size = _texture.getSize();
	GLuint w = static_cast<GLuint>(size.x);
	GLuint h = static_cast<GLuint>(size.y);
	computeBuffer_.reserve(w * h * 4);
	auto buffer = computeBuffer_.data();
	glBindFramebuffer(GL_READ_FRAMEBUFFER, _framebuffer);
	glReadPixels(0, 0, w, h, GL_RGBA, GL_FLOAT, buffer);
	glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
	float sum = 0.0f;
	for (int i = 0; i < int(w * h * 4); i += 4) {
		float l = buffer[i + 3] * 0.2126f + buffer[i + 2] * 0.7152f + buffer[i + 1] * 0.0722f;
		sum += std::log(fei::epsf + l);
	}
	ret = std::exp(sum / (size.x * size.y));
	return ret;
}

void RenderTarget::genBuffers()
{
	if (_renderbuffer == 0) {
		glGenRenderbuffers(1, &_renderbuffer);
	}
	if (_framebuffer == 0) {
		glGenFramebuffers(1, &_framebuffer);
	}
}

void RenderTarget::deleteBuffers()
{
	if (isBind()) {
		unbind();
	}
	if (_framebuffer != 0) {
		glDeleteFramebuffers(1, &_framebuffer);
		_framebuffer = 0;
	}
	if (_renderbuffer != 0) {
		glDeleteRenderbuffers(1, &_renderbuffer);
		_renderbuffer = 0;
	}
}

void RenderTarget::tmpBind()
{
	if (!isBind()) {
		bind();
		_tmpBind = true;
	}
}

void RenderTarget::tmpUnbind()
{
	if (_tmpBind) {
		unbind();
		_tmpBind = false;
	}
}
<commit_msg>update RenderTarget::getHDRLw<commit_after>#include "render/RenderTarget.h"

#include <glad/glad.h>

#include "base/basedef.h"
#include "math/mathdef.h"
#include "render/Render.h"

using fei::RenderTarget;

std::vector<GLfloat> RenderTarget::computeBuffer_;

RenderTarget::RenderTarget()
: _renderbuffer(0),
  _framebuffer(0),
  _width(0),
  _height(0),
  _tmpBind(false)
{
}

RenderTarget::~RenderTarget()
{
	deleteBuffers();
}

RenderTarget::RenderTarget(const fei::Vec2& size)
: RenderTarget()
{
	setSize(size);
}

RenderTarget::RenderTarget(GLsizei width, GLsizei height)
: RenderTarget()
{
	setSize(width, height);
}

fei::Texture* RenderTarget::getTexture()
{
	return &_texture;
}

void RenderTarget::setSize(const fei::Vec2& size, fei::Texture::Format format)
{
	setSize(static_cast<GLsizei>(size.x), static_cast<GLsizei>(size.y), format);
}

void RenderTarget::setSize(GLsizei width, GLsizei height, fei::Texture::Format format)
{
	if (width == 0 || height == 0) {
		return;
	}
	if (width != _width || height != _height) {
		_width = width;
		_height = height;
		_texture.load(nullptr, width, height, format);
		genBuffers();

		glBindRenderbuffer(GL_RENDERBUFFER, _renderbuffer);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
		glBindRenderbuffer(GL_RENDERBUFFER, 0);
		tmpBind();
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, getTexture()->getId(), 0);
		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _renderbuffer);
		tmpUnbind();
	}
}

void RenderTarget::bindColorAttachment(fei::Texture* texture, int attachIndex)
{
	GLuint texId = 0;
	if (texture != nullptr) {
		texId = texture->getId();
	}
	tmpBind();
	glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachIndex, GL_TEXTURE_2D, texId, 0);
	tmpUnbind();
}

void RenderTarget::setDrawBuffers(const std::vector<GLenum>& buffers)
{
	tmpBind();
	glDrawBuffers(static_cast<GLsizei>(buffers.size()), &(buffers[0]));
	tmpUnbind();
}

void RenderTarget::bind()
{
	if (!isBind()) {
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _framebuffer);
		fei::Render::getInstance()->setCurrentRenderTarget(this);
	}
}

void RenderTarget::unbind()
{
	if (isBind()) {
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
		fei::Render::getInstance()->setCurrentRenderTarget(nullptr);
	}
}

bool RenderTarget::isBind()
{
	return fei::Render::getInstance()->getCurrentRenderTarget() == this;
}

float RenderTarget::getHDRLw()
{
	auto size = _texture.getSize();
	GLuint w = static_cast<GLuint>(size.x);
	GLuint h = static_cast<GLuint>(size.y);
	computeBuffer_.reserve(w * h * 4);
	auto buffer = computeBuffer_.data();
	glBindFramebuffer(GL_READ_FRAMEBUFFER, _framebuffer);
	glReadPixels(0, 0, w, h, GL_RGBA, GL_FLOAT, buffer);
	glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
	float sum = 0.0f;
	int num = 0;
	for (int i = 0; i < int(w * h * 4); i += 4) {
		if (buffer[i] == 0.0f) continue;
		float l = buffer[i + 3] * 0.2126f + buffer[i + 2] * 0.7152f + buffer[i + 1] * 0.0722f;
		sum += std::log(fei::epsf + l);
		num++;
	}
	if (num == 0) return 0.0f;
	return std::exp(sum / num);
}

void RenderTarget::genBuffers()
{
	if (_renderbuffer == 0) {
		glGenRenderbuffers(1, &_renderbuffer);
	}
	if (_framebuffer == 0) {
		glGenFramebuffers(1, &_framebuffer);
	}
}

void RenderTarget::deleteBuffers()
{
	if (isBind()) {
		unbind();
	}
	if (_framebuffer != 0) {
		glDeleteFramebuffers(1, &_framebuffer);
		_framebuffer = 0;
	}
	if (_renderbuffer != 0) {
		glDeleteRenderbuffers(1, &_renderbuffer);
		_renderbuffer = 0;
	}
}

void RenderTarget::tmpBind()
{
	if (!isBind()) {
		bind();
		_tmpBind = true;
	}
}

void RenderTarget::tmpUnbind()
{
	if (_tmpBind) {
		unbind();
		_tmpBind = false;
	}
}
<|endoftext|>


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

//------------------------------------------------------
// testcomponent - Loads a service and its testcomponent from dlls performs a test.
// Expands the dll-names depending on the actual environment.
// Example : testcomponent stardiv.uno.io.Pipe stm
//
// Therefor the testcode must exist in teststm and the testservice must be named test.stardiv.uno.io.Pipe
//

#include <stdio.h>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#include <com/sun/star/test/XSimpleTest.hpp>

#include <cppuhelper/servicefactory.hxx>

#include <osl/diagnose.h>

using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::test;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;

// Needed to switch on solaris threads
#ifdef SOLARIS
extern "C" void ChangeGlobalInit();
#endif

int main (int argc, char **argv)
{

    if( argc < 3) {
        printf( "usage : testcomponent service dll [additional dlls]\n" );
        exit( 0 );
    }
#ifdef SOLARIS
    // switch on threads in solaris
    ChangeGlobalInit();
#endif

    // create service manager
    Reference< XMultiServiceFactory > xSMgr =
        createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb")) );

    Reference < XImplementationRegistration > xReg;
    Reference < XSimpleRegistry > xSimpleReg;

    try
    {
        // Create registration service
        Reference < XInterface > x = xSMgr->createInstance(
            OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.registry.ImplementationRegistration")) );
        xReg = Reference<  XImplementationRegistration > ( x , UNO_QUERY );
    }
    catch( Exception & ) {
        printf( "Couldn't create ImplementationRegistration service\n" );
        exit(1);
    }

    sal_Char szBuf[1024];
    OString sTestName;

    try
    {
        // Load dll for the tested component
        for( int n = 2 ; n <argc ; n ++ ) {
#ifdef SAL_W32
            OUString aDllName = OStringToOUString( argv[n] , RTL_TEXTENCODING_ASCII_US );
#else
            OUString aDllName = OUString( RTL_CONSTASCII_USTRINGPARAM("lib"));
            aDllName += OStringToOUString( argv[n] , RTL_TEXTENCODING_ASCII_US );
            aDllName += OUString( RTL_CONSTASCII_USTRINGPARAM(".so"));
#endif
            xReg->registerImplementation(
                OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.loader.SharedLibrary")),
                aDllName,
                xSimpleReg );
        }
    }
    catch( Exception &e ) {
        printf( "Couldn't reach dll %s\n" , szBuf );
        printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() );

        exit(1);
    }

    try
    {
        // Load dll for the test component
        sTestName = "test";
        sTestName += argv[2];

#ifdef SAL_W32
        OUString aDllName = OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US );
#else
        OUString aDllName = OUString( RTL_CONSTASCII_USTRINGPARAM("lib"));
        aDllName += OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US );
        aDllName += OUString( RTL_CONSTASCII_USTRINGPARAM(".so"));
#endif

        xReg->registerImplementation(
            OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.loader.SharedLibrary")) ,
            aDllName,
            xSimpleReg );
    }
    catch( Exception & e )
    {
        printf( "Couldn't reach dll %s\n" , szBuf );
        exit(1);
    }

    // Instantiate test service
    sTestName = "test.";
    sTestName += argv[1];

    Reference < XInterface > xIntTest =
        xSMgr->createInstance( OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US ) );
    Reference< XSimpleTest > xTest( xIntTest , UNO_QUERY );

    if( ! xTest.is() ) {
        printf( "Couldn't instantiate test service \n" );
        exit( 1 );
    }

    sal_Int32 nHandle = 0;
    sal_Int32 nNewHandle;
    sal_Int32 nErrorCount = 0;
    sal_Int32 nWarningCount = 0;

    // loop until all test are performed
    while( nHandle != -1 )
    {
        // Instantiate serivce
        Reference< XInterface > x =
            xSMgr->createInstance( OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) );
        if( ! x.is() )
        {
            printf( "Couldn't instantiate service !\n" );
            exit( 1 );
        }

        // do the test
        try
        {
            nNewHandle = xTest->test(
                OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) , x , nHandle );
        }
        catch( Exception & e ) {
            OString o  = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
            printf( "testcomponent : uncaught exception %s\n" , o.getStr() );
            exit(1);
        }
        catch( ... )
        {
            printf( "testcomponent : uncaught unknown exception\n"  );
            exit(1);
        }

        // print errors and warning
        Sequence<OUString> seqErrors = xTest->getErrors();
        Sequence<OUString> seqWarnings = xTest->getWarnings();
        if( seqWarnings.getLength() > nWarningCount )
        {
            printf( "Warnings during test %" SAL_PRIxUINT32 "!\n" , nHandle );
            for( ; nWarningCount < seqWarnings.getLength() ; nWarningCount ++ )
            {
                OString o = OUStringToOString(
                    seqWarnings.getArray()[nWarningCount], RTL_TEXTENCODING_ASCII_US );
                printf( "Warning\n%s\n---------\n" , o.getStr() );
            }
        }

        if( seqErrors.getLength() > nErrorCount ) {
            printf( "Errors during test %" SAL_PRIxUINT32 "!\n" , nHandle );
            for( ; nErrorCount < seqErrors.getLength() ; nErrorCount ++ ) {
                OString o = OUStringToOString(
                    seqErrors.getArray()[nErrorCount], RTL_TEXTENCODING_ASCII_US );
                printf( "%s\n" , o.getStr() );
            }
        }

        nHandle = nNewHandle;
    }

    if( xTest->testPassed() ) {
        printf( "Test passed !\n" );
    }
    else {
        printf( "Test failed !\n" );
    }

    Reference <XComponent >  rComp( xSMgr , UNO_QUERY );
    rComp->dispose();
    return 0;
}

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

//------------------------------------------------------
// testcomponent - Loads a service and its testcomponent from dlls performs a test.
// Expands the dll-names depending on the actual environment.
// Example : testcomponent stardiv.uno.io.Pipe stm
//
// Therefor the testcode must exist in teststm and the testservice must be named test.stardiv.uno.io.Pipe
//

#include <stdio.h>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#include <com/sun/star/test/XSimpleTest.hpp>

#include <cppuhelper/servicefactory.hxx>

#include <osl/diagnose.h>

using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::test;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;

// Needed to switch on solaris threads
#ifdef SOLARIS
extern "C" void ChangeGlobalInit();
#endif

int main (int argc, char **argv)
{

    if( argc < 3) {
        printf( "usage : testcomponent service dll [additional dlls]\n" );
        exit( 0 );
    }
#ifdef SOLARIS
    // switch on threads in solaris
    ChangeGlobalInit();
#endif

    // create service manager
    Reference< XMultiServiceFactory > xSMgr =
        createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb")) );

    Reference < XImplementationRegistration > xReg;
    Reference < XSimpleRegistry > xSimpleReg;

    try
    {
        // Create registration service
        Reference < XInterface > x = xSMgr->createInstance(
            OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.registry.ImplementationRegistration")) );
        xReg = Reference<  XImplementationRegistration > ( x , UNO_QUERY );
    }
    catch (const Exception&)
    {
        printf( "Couldn't create ImplementationRegistration service\n" );
        exit(1);
    }

    sal_Char szBuf[1024];
    OString sTestName;

    try
    {
        // Load dll for the tested component
        for( int n = 2 ; n <argc ; n ++ ) {
#ifdef SAL_W32
            OUString aDllName = OStringToOUString( argv[n] , RTL_TEXTENCODING_ASCII_US );
#else
            OUString aDllName = OUString( RTL_CONSTASCII_USTRINGPARAM("lib"));
            aDllName += OStringToOUString( argv[n] , RTL_TEXTENCODING_ASCII_US );
            aDllName += OUString( RTL_CONSTASCII_USTRINGPARAM(".so"));
#endif
            xReg->registerImplementation(
                OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.loader.SharedLibrary")),
                aDllName,
                xSimpleReg );
        }
    }
    catch (const Exception &e)
    {
        printf( "Couldn't reach dll %s\n" , szBuf );
        printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() );

        exit(1);
    }

    try
    {
        // Load dll for the test component
        sTestName = "test";
        sTestName += argv[2];

#ifdef SAL_W32
        OUString aDllName = OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US );
#else
        OUString aDllName = OUString( RTL_CONSTASCII_USTRINGPARAM("lib"));
        aDllName += OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US );
        aDllName += OUString( RTL_CONSTASCII_USTRINGPARAM(".so"));
#endif

        xReg->registerImplementation(
            OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.loader.SharedLibrary")) ,
            aDllName,
            xSimpleReg );
    }
    catch (const Exception&)
    {
        printf( "Couldn't reach dll %s\n" , szBuf );
        exit(1);
    }

    // Instantiate test service
    sTestName = "test.";
    sTestName += argv[1];

    Reference < XInterface > xIntTest =
        xSMgr->createInstance( OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US ) );
    Reference< XSimpleTest > xTest( xIntTest , UNO_QUERY );

    if( ! xTest.is() ) {
        printf( "Couldn't instantiate test service \n" );
        exit( 1 );
    }

    sal_Int32 nHandle = 0;
    sal_Int32 nNewHandle;
    sal_Int32 nErrorCount = 0;
    sal_Int32 nWarningCount = 0;

    // loop until all test are performed
    while( nHandle != -1 )
    {
        // Instantiate serivce
        Reference< XInterface > x =
            xSMgr->createInstance( OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) );
        if( ! x.is() )
        {
            printf( "Couldn't instantiate service !\n" );
            exit( 1 );
        }

        // do the test
        try
        {
            nNewHandle = xTest->test(
                OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) , x , nHandle );
        }
        catch (const Exception &e)
        {
            OString o  = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
            printf( "testcomponent : uncaught exception %s\n" , o.getStr() );
            exit(1);
        }
        catch (...)
        {
            printf( "testcomponent : uncaught unknown exception\n"  );
            exit(1);
        }

        // print errors and warning
        Sequence<OUString> seqErrors = xTest->getErrors();
        Sequence<OUString> seqWarnings = xTest->getWarnings();
        if( seqWarnings.getLength() > nWarningCount )
        {
            printf( "Warnings during test %" SAL_PRIxUINT32 "!\n" , nHandle );
            for( ; nWarningCount < seqWarnings.getLength() ; nWarningCount ++ )
            {
                OString o = OUStringToOString(
                    seqWarnings.getArray()[nWarningCount], RTL_TEXTENCODING_ASCII_US );
                printf( "Warning\n%s\n---------\n" , o.getStr() );
            }
        }

        if( seqErrors.getLength() > nErrorCount ) {
            printf( "Errors during test %" SAL_PRIxUINT32 "!\n" , nHandle );
            for( ; nErrorCount < seqErrors.getLength() ; nErrorCount ++ ) {
                OString o = OUStringToOString(
                    seqErrors.getArray()[nErrorCount], RTL_TEXTENCODING_ASCII_US );
                printf( "%s\n" , o.getStr() );
            }
        }

        nHandle = nNewHandle;
    }

    if( xTest->testPassed() ) {
        printf( "Test passed !\n" );
    }
    else {
        printf( "Test failed !\n" );
    }

    Reference <XComponent >  rComp( xSMgr , UNO_QUERY );
    rComp->dispose();
    return 0;
}

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


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

#ifndef SC_CRDLG_HXX
#define SC_CRDLG_HXX

#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/imagebtn.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#include "scui_def.hxx" //CHINA001

//CHINA001 #define SCRET_COLS 0x42
//CHINA001 #define SCRET_ROWS 0x43

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

class ScColOrRowDlg : public ModalDialog
{
public:
            ScColOrRowDlg( Window*          pParent,
                           const String&    rStrTitle,
                           const String&    rStrLabel,
                           BOOL             bColDefault = TRUE );
            ~ScColOrRowDlg();

private:
    FixedLine       aFlFrame;
    RadioButton     aBtnRows;
    RadioButton     aBtnCols;
    OKButton        aBtnOk;
    CancelButton    aBtnCancel;
    HelpButton      aBtnHelp;

    DECL_LINK( OkHdl, OKButton * );
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.460); FILE MERGED 2005/09/05 15:05:11 rt 1.3.460.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: crdlg.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:16:55 $
 *
 *  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 SC_CRDLG_HXX
#define SC_CRDLG_HXX

#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/imagebtn.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#include "scui_def.hxx" //CHINA001

//CHINA001 #define SCRET_COLS 0x42
//CHINA001 #define SCRET_ROWS 0x43

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

class ScColOrRowDlg : public ModalDialog
{
public:
            ScColOrRowDlg( Window*          pParent,
                           const String&    rStrTitle,
                           const String&    rStrLabel,
                           BOOL             bColDefault = TRUE );
            ~ScColOrRowDlg();

private:
    FixedLine       aFlFrame;
    RadioButton     aBtnRows;
    RadioButton     aBtnCols;
    OKButton        aBtnOk;
    CancelButton    aBtnCancel;
    HelpButton      aBtnHelp;

    DECL_LINK( OkHdl, OKButton * );
};

#endif

<|endoftext|>


<commit_before>#include "bitcoinaddressvalidator.h"

/* Base58 characters are:
     "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

  This is:
  - All numbers except for '0'
  - All uppercase letters except for 'I' and 'O'
  - All lowercase letters except for 'l'

  User friendly Base58 input can map
  - 'l' and 'I' to '1'
  - '0' and 'O' to 'o'
*/

BitcoinAddressValidator::BitcoinAddressValidator(QObject *parent) :
    QValidator(parent)
{
}

QValidator::State BitcoinAddressValidator::validate(QString &input, int &pos) const
{
    // Correction
    for(int idx=0; idx<input.size();)
    {
        bool removeChar = false;
        QChar ch = input.at(idx);
        // Transform characters that are visually close
        switch(ch.unicode())
        {
        case 'l':
        case 'I':
            input[idx] = QChar('1');
            break;
        case '0':
        case 'O':
            input[idx] = QChar('o');
            break;
        // Qt categorizes these as "Other_Format" not "Separator_Space"
        case 0x200B: // ZERO WIDTH SPACE
        case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE
            removeChar = true;
            break;
        default:
            break;
        }
        // Remove whitespace
        if(ch.isSpace())
            removeChar = true;
        // To next character
        if(removeChar)
            input.remove(idx, 1);
        else
            ++idx;
    }

    // Validation
    QValidator::State state = QValidator::Acceptable;
    for(int idx=0; idx<input.size(); ++idx)
    {
        int ch = input.at(idx).unicode();

        if(((ch >= '0' && ch<='9') ||
           (ch >= 'a' && ch<='z') ||
           (ch >= 'A' && ch<='Z')) &&
           ch != 'l' && ch != 'I' && ch != '0' && ch != 'O')
        {
            // Alphanumeric and not a 'forbidden' character
        }
        else
        {
            state = QValidator::Invalid;
        }
    }

    // Empty address is "intermediate" input
    if(input.isEmpty())
    {
        state = QValidator::Intermediate;
    }

    return state;
}
<commit_msg>Remove autocorrection of 0/i in addresses in UI<commit_after>#include "bitcoinaddressvalidator.h"

/* Base58 characters are:
     "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

  This is:
  - All numbers except for '0'
  - All uppercase letters except for 'I' and 'O'
  - All lowercase letters except for 'l'

  User friendly Base58 input can map
  - 'l' and 'I' to '1'
  - '0' and 'O' to 'o'
*/

BitcoinAddressValidator::BitcoinAddressValidator(QObject *parent) :
    QValidator(parent)
{
}

QValidator::State BitcoinAddressValidator::validate(QString &input, int &pos) const
{
    // Correction
    for(int idx=0; idx<input.size();)
    {
        bool removeChar = false;
        QChar ch = input.at(idx);
        // Corrections made are very conservative on purpose, to avoid
        // users unexpectedly getting away with typos that would normally
        // be detected, and thus sending to the wrong address.
        switch(ch.unicode())
        {
        // Qt categorizes these as "Other_Format" not "Separator_Space"
        case 0x200B: // ZERO WIDTH SPACE
        case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE
            removeChar = true;
            break;
        default:
            break;
        }
        // Remove whitespace
        if(ch.isSpace())
            removeChar = true;
        // To next character
        if(removeChar)
            input.remove(idx, 1);
        else
            ++idx;
    }

    // Validation
    QValidator::State state = QValidator::Acceptable;
    for(int idx=0; idx<input.size(); ++idx)
    {
        int ch = input.at(idx).unicode();

        if(((ch >= '0' && ch<='9') ||
           (ch >= 'a' && ch<='z') ||
           (ch >= 'A' && ch<='Z')) &&
           ch != 'l' && ch != 'I' && ch != '0' && ch != 'O')
        {
            // Alphanumeric and not a 'forbidden' character
        }
        else
        {
            state = QValidator::Invalid;
        }
    }

    // Empty address is "intermediate" input
    if(input.isEmpty())
    {
        state = QValidator::Intermediate;
    }

    return state;
}
<|endoftext|>