text:
//---------------------------------------------------------------------------//
//!
//! \file   DataGen_ElasticElectronMomentsEvaluator.hpp
//! \author Luke Kersting
//! \brief  Elastic electron cross section moments evaluator declaration
//!
//---------------------------------------------------------------------------//

#ifndef DATA_GEN_ELASTIC_ELECTRON_MOMENTS_EVALUATOR_HPP
#define DATA_GEN_ELASTIC_ELECTRON_MOMENTS_EVALUATOR_HPP

// Boost Includes
#include <boost/multiprecision/cpp_dec_float.hpp>

// FRENSIE Includes
#include "Data_ElectronPhotonRelaxationDataContainer.hpp"
#include "Utility_GaussKronrodIntegrator.hpp"
#include "Utility_SloanRadauQuadrature.hpp"
#include "MonteCarlo_CoupledElasticElectronScatteringDistribution.hpp"
#include "MonteCarlo_CoupledElasticElectroatomicReaction.hpp"
#include "MonteCarlo_TwoDInterpolationType.hpp"
#include "MonteCarlo_TwoDGridType.hpp"

namespace DataGen{

//! The elastic electron cross section moments class
class ElasticElectronMomentsEvaluator
{

public:

  //! Typedef for the elastic distribution
  typedef Utility::GaussKronrodIntegrator<Utility::long_float>
  Integrator;

  // Typedef for elastic electron traits
  typedef MonteCarlo::ElasticElectronTraits ElasticTraits;

  //! Constructor
  ElasticElectronMomentsEvaluator(
    const Data::ElectronPhotonRelaxationDataContainer& data_container,
    const MonteCarlo::TwoDInterpolationType two_d_interp,
    const MonteCarlo::TwoDGridType two_d_grid,
    const double cutoff_angle_cosine,
    const double tabular_evaluation_tol );

  //! Constructor (without data container)
  ElasticElectronMomentsEvaluator(
    const std::map<double,std::vector<double> >& cutoff_elastic_angles,
    const std::shared_ptr<const std::vector<double> >& incoming_energy_grid,
    const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >&
     grid_searcher,
    const std::shared_ptr<const std::vector<double> >& cutoff_cross_section,
    const std::shared_ptr<const std::vector<double> >& total_elastic_cross_section,
    const unsigned screened_rutherford_threshold_energy_index,
    const std::shared_ptr<const MonteCarlo::CoupledElasticElectronScatteringDistribution>
        coupled_distribution,
    const std::shared_ptr<const ElasticTraits>& elastic_traits,
    const double cutoff_angle_cosine );

  //! Destructor
  ~ElasticElectronMomentsEvaluator()
  { /* ... */ }

  //! Evaluate the Legendre Polynomial expansion of the screened rutherford pdf
  double evaluateLegendreExpandedRutherford(
            const double scattering_angle_cosine,
            const double incoming_energy,
            const int polynomial_order = 0 ) const;

  //! Evaluate the Legendre Polynomial expansion of the screened rutherford pdf
  double evaluateLegendreExpandedRutherford(
            const double scattering_angle_cosine,
            const double incoming_energy,
            const double eta,
            const int polynomial_order = 0 ) const;

  //! Evaluate the Legendre Polynomial expansion of the differential hard elastic pdf
  double evaluateLegendreExpandedPDF(
            const double scattering_angle_cosine,
            const double incoming_energy,
            const int polynomial_order = 0) const;

  //! Evaluate the nth cross section moment of the elastic cutoff distribution at the energy
  void evaluateCutoffMoment(
            Utility::long_float& cutoff_moment,
            const std::vector<double>& angular_grid,
            const Integrator& integrator,
            const double energy,
            const int n ) const;

  //! Evaluate the nth cross section moment of the screened Rutherford peak distribution at the energy
  void evaluateScreenedRutherfordMoment(
            Utility::long_float& rutherford_moment,
            const double& energy,
            const int& n ) const;

  //! Evaluate the first n moments of the elastic scattering distribution at a given energy
  void evaluateElasticMoment(
            std::vector<Utility::long_float>& legendre_moments,
            const double energy,
            const int n,
            const double precision ) const;

protected:

  // Evaluate the nth PDF moment of the cutoff distribution at the energy
  void evaluateCutoffPDFMoment(
            Utility::long_float& cutoff_moment,
            const std::vector<double>& angular_grid,
            const Integrator& integrator,
            const double energy,
            const int n ) const;

  // Evaluate the nth PDF moment of the screened Rutherford peak distribution at the energy
  void evaluateScreenedRutherfordPDFMoment(
            Utility::long_float& rutherford_moment,
            const double& energy,
            const int& n ) const;

  /* Evaluate the nth PDF moment of the screened Rutherford peak distribution
   * at the eta using the recursion relationship
   */
  void evaluateScreenedRutherfordPDFMomentByRecursion(
            Utility::long_float& rutherford_moment,
            const Utility::long_float& eta,
            const int& n ) const;

  /* Evaluate the nth PDF moment of the screened Rutherford peak distribution
   * at the energy using numerical integration
   */
  void evaluateScreenedRutherfordPDFMomentByNumericalIntegration(
            Utility::long_float& rutherford_moment,
            const double energy,
            const int n,
            const double tolerance = 1e-13,
            const unsigned number_of_iterations = 1000 ) const;

  /* Evaluate the nth PDF moment of the screened Rutherford peak distribution
   * at the energy using numerical integration
   */
  void evaluateScreenedRutherfordPDFMomentByNumericalIntegration(
            Utility::long_float& rutherford_moment,
            const Utility::long_float& eta,
            const double energy,
            const int n,
            const double tolerance = 1e-13,
            const unsigned number_of_iterations = 1000 ) const;

private:

  // Return the angular integration points
  void getAngularIntegrationPoints(
        std::vector<double>& angular_integration_points,
        const double energy ) const;

  // Grid searcher for the energy grid
  std::shared_ptr<const Utility::HashBasedGridSearcher<double> > d_grid_searcher;

  // The screened rutherford elastic threshold_energy_index
  unsigned d_screened_rutherford_threshold_energy_index;

  // The coupled distribution
  std::shared_ptr<const MonteCarlo::CoupledElasticElectronScatteringDistribution>
    d_coupled_distribution;

  // The cutoff elastic reaction
  std::shared_ptr<const MonteCarlo::ElectroatomicReaction>
    d_cutoff_reaction;

  // The total elastic reaction
  std::shared_ptr<const MonteCarlo::ElectroatomicReaction>
    d_total_reaction;

  // The map of the cutoff angles
  std::map<double,std::vector<double> > d_cutoff_elastic_angles;

  // The angle cosine cutoff between hard and soft scattering
  double d_cutoff_angle_cosine;

  // Elastic electron traits
  std::shared_ptr<const ElasticTraits> d_elastic_traits;
};

} // end DataGen namespace

#endif // end DATA_GEN_ELASTIC_ELECTRON_MOMENTS_EVALUATOR_HPP

//---------------------------------------------------------------------------//
// end DataGen_ElasticElectronMomentsEvaluator.hpp
//---------------------------------------------------------------------------//


text:
/**************************************************************
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#include "svx/sidebar/PopupContainer.hxx"
#include "AreaTransparencyGradientControl.hxx"

#include <sfx2/sidebar/ResourceDefinitions.hrc>
#include <sfx2/sidebar/Theme.hxx>
#include <sfx2/sidebar/ControlFactory.hxx>
#include <sfx2/sidebar/Layouter.hxx>
#include <AreaPropertyPanel.hxx>
#include <AreaPropertyPanel.hrc>
#include <svx/dialogs.hrc>
#include <svx/dialmgr.hxx>
#include <sfx2/objsh.hxx>
#include <svx/xfltrit.hxx>
#include <svx/xflftrit.hxx>
#include <svx/xtable.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/bindings.hxx>
#include <helpid.hrc>
#include <svtools/valueset.hxx>
#include <unotools/pathoptions.hxx>
#include <svx/svxitems.hrc>
#include <vcl/toolbox.hxx>
#include <svtools/toolbarmenu.hxx>
#include <svx/sidebar/ColorControl.hxx>

#include <boost/bind.hpp>

using namespace css;
using namespace cssu;
using ::sfx2::sidebar::Layouter;
using ::sfx2::sidebar::Theme;

#define A2S(pString) (::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(pString)))

namespace svx { namespace sidebar {

const sal_Int32 AreaPropertyPanel::DEFAULT_CENTERX = 50;
const sal_Int32 AreaPropertyPanel::DEFAULT_CENTERY = 50;
const sal_Int32 AreaPropertyPanel::DEFAULT_ANGLE = 0;
const sal_Int32 AreaPropertyPanel::DEFAULT_STARTVALUE = 0;
const sal_Int32 AreaPropertyPanel::DEFAULT_ENDVALUE = 16777215;
const sal_Int32 AreaPropertyPanel::DEFAULT_BORDER = 0;

AreaPropertyPanel::AreaPropertyPanel(
    Window* pParent,
    const cssu::Reference<css::frame::XFrame>& rxFrame,
    SfxBindings* pBindings)
    : Control(pParent, SVX_RES(RID_SIDEBAR_AREA_PANEL)),
      meLastXFS(-1),
      maLastColor(Color(COL_DEFAULT_SHAPE_FILLING)),
      mnLastPosGradient(0),
      mnLastPosHatch(0),
      mnLastPosBitmap(0),
      mnLastTransSolid(50),
      maGradientLinear(),
      maGradientAxial(),
      maGradientRadial(),
      maGradientElliptical(),
      maGradientSquare(),
      maGradientRect(),
      mpColorTextFT(new FixedText(this, SVX_RES(FT_COLOR_LIST))),
      mpLbFillType(new SvxFillTypeBox(this)),
      mpLbFillAttr(new SvxFillAttrBox(this)),
      mpToolBoxColorBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)),
      mpToolBoxColor(sfx2::sidebar::ControlFactory::CreateToolBox(mpToolBoxColorBackground.get(), SVX_RES(TB_COLOR))),
      mpTrspTextFT(new FixedText(this, SVX_RES(FL_TRSP_TEXT))),
      mpLBTransType(new ListBox(this, SVX_RES(LB_TRGR_TYPES))),
      mpMTRTransparent(new MetricField(this, SVX_RES(MTR_TRANSPARENT))),
      mpBTNGradientBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)),
      mpBTNGradient(sfx2::sidebar::ControlFactory::CreateToolBox(mpBTNGradientBackground.get(), SVX_RES(BTN_GRADIENT))),
      mpColorUpdater(new ::svx::ToolboxButtonColorUpdater(SID_ATTR_FILL_COLOR, TBI_COLOR, mpToolBoxColor.get(), TBX_UPDATER_MODE_CHAR_COLOR_NEW)),
      mpStyleItem(),
      mpColorItem(),
      mpFillGradientItem(),
      mpHatchItem(),
      mpBitmapItem(),
      maStyleControl(SID_ATTR_FILL_STYLE, *pBindings, *this),
      maColorControl(SID_ATTR_FILL_COLOR, *pBindings, *this),
      maGradientControl(SID_ATTR_FILL_GRADIENT, *pBindings, *this),
      maHatchControl(SID_ATTR_FILL_HATCH, *pBindings, *this),
      maBitmapControl(SID_ATTR_FILL_BITMAP, *pBindings, *this),
      maColorTableControl(SID_COLOR_TABLE, *pBindings, *this),
      maGradientListControl(SID_GRADIENT_LIST, *pBindings, *this),
      maHatchListControl(SID_HATCH_LIST, *pBindings, *this),
      maBitmapListControl(SID_BITMAP_LIST, *pBindings, *this),
      maFillTransparenceController(SID_ATTR_FILL_TRANSPARENCE, *pBindings, *this),
      maFillFloatTransparenceController(SID_ATTR_FILL_FLOATTRANSPARENCE, *pBindings, *this),
      maImgAxial(SVX_RES(IMG_AXIAL)),
      maImgElli(SVX_RES(IMG_ELLI)),
      maImgQuad(SVX_RES(IMG_QUAD)),
      maImgRadial(SVX_RES(IMG_RADIAL)),
      maImgSquare(SVX_RES(IMG_SQUARE)),
      maImgLinear(SVX_RES(IMG_LINEAR)),
      maImgColor(SVX_RES(IMG_COLOR)),
      maImgAxialH(SVX_RES(IMG_AXIAL_H)),
      maImgElliH(SVX_RES(IMG_ELLI_H)),
      maImgQuadH(SVX_RES(IMG_QUAD_H)),
      maImgRadialH(SVX_RES(IMG_RADIAL_H)),
      maImgSquareH(SVX_RES(IMG_SQUARE_H)),
      maImgLinearH(SVX_RES(IMG_LINEAR_H)),
      maImgColorH(SVX_RES(IMG_COLOR_H)),
      msHelpFillType(SVX_RES(STR_HELP_TYPE)),
      msHelpFillAttr(SVX_RES(STR_HELP_ATTR)),
      maTrGrPopup(this, ::boost::bind(&AreaPropertyPanel::CreateTransparencyGradientControl, this, _1)),
      maColorPopup(this, ::boost::bind(&AreaPropertyPanel::CreateColorPopupControl, this, _1)),
      mpFloatTransparenceItem(),
      mpTransparanceItem(),
      mxFrame(rxFrame),
      mpBindings(pBindings),
      mbColorAvail(true),
      maLayouter(*this)
{
    Initialize();
    FreeResource();

    // Setup the grid layouter.
    const sal_Int32 nMappedMboxWidth (Layouter::MapWidth(*this, MBOX_WIDTH));

    maLayouter.GetCell(0,0).SetControl(*mpColorTextFT).SetGridWidth(3);
    maLayouter.GetCell(1,0).SetControl(*mpLbFillType);
    maLayouter.GetCell(1,2,0).SetControl(*mpToolBoxColorBackground).SetFixedWidth();
    maLayouter.GetCell(1,2,1).SetControl(*mpLbFillAttr);

    maLayouter.GetCell(2,0).SetControl(*mpTrspTextFT).SetGridWidth(3);
    maLayouter.GetCell(3,0).SetControl(*mpLBTransType);
    maLayouter.GetCell(3,2,0).SetControl(*mpMTRTransparent);
    maLayouter.GetCell(3,2,1).SetControl(*mpBTNGradient);

    maLayouter.GetColumn(0)
        .SetWeight(1)
        .SetLeftPadding(Layouter::MapWidth(*this,SECTIONPAGE_MARGIN_HORIZONTAL))
        .SetMinimumWidth(nMappedMboxWidth);
    maLayouter.GetColumn(1)
        .SetWeight(0)
        .SetMinimumWidth(Layouter::MapWidth(*this, CONTROL_SPACING_HORIZONTAL));
    maLayouter.GetColumn(2)
        .SetWeight(1)
        .SetMinimumWidth(nMappedMboxWidth)
        .SetRightPadding(Layouter::MapWidth(*this,SECTIONPAGE_MARGIN_HORIZONTAL));

    // Make controls that display text handle short widths more
    // graceful.
    Layouter::PrepareForLayouting(*mpColorTextFT);
    Layouter::PrepareForLayouting(*mpTrspTextFT);
}

AreaPropertyPanel::~AreaPropertyPanel()
{
    // Destroy the toolboxes, then their background windows.
    mpToolBoxColor.reset();
    mpBTNGradient.reset();
    mpToolBoxColorBackground.reset();
    mpBTNGradientBackground.reset();
}

void AreaPropertyPanel::Initialize()
{
    mpColorTextFT->SetBackground(Wallpaper());
    mpTrspTextFT->SetBackground(Wallpaper());

    maGradientLinear.SetXOffset(DEFAULT_CENTERX);
    maGradientLinear.SetYOffset(DEFAULT_CENTERY);
    maGradientLinear.SetAngle(DEFAULT_ANGLE);
    maGradientLinear.SetStartColor(Color(DEFAULT_STARTVALUE));
    maGradientLinear.SetEndColor(Color(DEFAULT_ENDVALUE));
    maGradientLinear.SetBorder(DEFAULT_BORDER);
    maGradientLinear.SetGradientStyle(XGRAD_LINEAR);

    maGradientAxial = maGradientLinear;
    maGradientAxial.SetGradientStyle(XGRAD_AXIAL);

    maGradientRadial = maGradientLinear;
    maGradientRadial.SetGradientStyle(XGRAD_RADIAL);

    maGradientElliptical = maGradientLinear;
    maGradientElliptical.SetGradientStyle(XGRAD_ELLIPTICAL);

    maGradientSquare = maGradientLinear;
    maGradientSquare.SetGradientStyle(XGRAD_SQUARE);

    maGradientRect = maGradientLinear;
    maGradientRect.SetGradientStyle(XGRAD_RECT);

    Size aLogicalFillSize(MBOX_WIDTH,LISTBOX_HEIGHT);
    Size aLogicalAttrSize(MBOX_WIDTH + 1,LISTBOX_HEIGHT);

    Point aPoint(SECTIONPAGE_MARGIN_HORIZONTAL,SECTIONPAGE_MARGIN_VERTICAL_TOP + FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL);
    Point aPoint_Picker(SECTIONPAGE_MARGIN_HORIZONTAL + MBOX_WIDTH + CONTROL_SPACING_HORIZONTAL,SECTIONPAGE_MARGIN_VERTICAL_TOP + FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL);

    Size aTypeSize(LogicToPixel(aLogicalFillSize, MAP_APPFONT));
    Size aAttrSize(LogicToPixel(aLogicalAttrSize, MAP_APPFONT));

    Point aTypePoint(LogicToPixel(aPoint, MAP_APPFONT));
    Point aAttrPoint(LogicToPixel(aPoint_Picker, MAP_APPFONT));

    mpLbFillType->SetPosSizePixel(aTypePoint,aTypeSize);
    mpLbFillAttr->SetPosSizePixel(aAttrPoint,aAttrSize);

    mpLbFillType->SetHelpId(HID_PPROPERTYPANEL_AREA_LB_FILL_TYPES);
    mpLbFillAttr->SetHelpId(HID_PPROPERTYPANEL_AREA_LB_FILL_ATTR);

    mpLbFillType->SetQuickHelpText(msHelpFillType);
    mpLbFillAttr->SetQuickHelpText(msHelpFillAttr);

    mpLbFillType->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Fill")));    //wj acc
    mpLbFillAttr->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Fill")));    //wj acc

    Link aLink = LINK( this, AreaPropertyPanel, SelectFillTypeHdl );
    mpLbFillType->SetSelectHdl( aLink );

    aLink = LINK( this, AreaPropertyPanel, SelectFillAttrHdl );
    mpLbFillAttr->SetSelectHdl( aLink );

    //add  for new color picker
    mpLbFillAttr->Hide();
    mpToolBoxColor->SetItemImage(TBI_COLOR, GetDisplayBackground().GetColor().IsDark()? maImgColorH : maImgColor);
    Size aTbxSize( mpToolBoxColor->CalcWindowSizePixel() );
    mpToolBoxColor->SetOutputSizePixel( aTbxSize );
    mpToolBoxColor->SetItemBits( TBI_COLOR, mpToolBoxColor->GetItemBits( TBI_COLOR ) | TIB_DROPDOWNONLY );
    mpToolBoxColor->SetBackground(Wallpaper());
    mpToolBoxColor->SetPaintTransparent(true);
    mpToolBoxColor->SetQuickHelpText(TBI_COLOR, String(SVX_RES(STR_HELP_COLOR)));    //wj acc
    //mpToolBoxColor->SetItemText(TBI_COLOR, msHelpFillAttr);

    long aHeightLBStyle = mpLbFillType->GetSizePixel().getHeight();
    long aLBPosY = mpLbFillType->GetPosPixel().getY();
    long aHeightTBAttr = mpToolBoxColor->GetSizePixel().getHeight();
    Point aPointTBAttr = mpToolBoxColor->GetPosPixel();
    aPointTBAttr.setY( aLBPosY + aHeightLBStyle / 2 - aHeightTBAttr / 2);
    mpToolBoxColor->SetPosPixel(aPointTBAttr);

    aLink = LINK(this, AreaPropertyPanel, ToolBoxColorDropHdl);
    mpToolBoxColor->SetDropdownClickHdl ( aLink );
    mpToolBoxColor->SetSelectHdl ( aLink );

    //add end
    mpLBTransType->SetSelectHdl(LINK(this, AreaPropertyPanel, ChangeTrgrTypeHdl_Impl));
    mpLBTransType->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Transparency")));    //wj acc

    mpMTRTransparent->SetValue( 50 );
    mpMTRTransparent->SetModifyHdl(LINK(this, AreaPropertyPanel, ModifyTransparentHdl_Impl));
    mpMTRTransparent->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Transparency")));    //wj acc

    mpBTNGradient->SetItemBits( TBI_BTX_GRADIENT, mpBTNGradient->GetItemBits( TBI_BTX_GRADIENT ) | TIB_DROPDOWNONLY );
    aLink = LINK( this, AreaPropertyPanel, ClickTrGrHdl_Impl );
    mpBTNGradient->SetDropdownClickHdl( aLink );
    mpBTNGradient->SetSelectHdl( aLink );
    aTbxSize = mpBTNGradient->CalcWindowSizePixel();
    mpBTNGradient->SetOutputSizePixel( aTbxSize );
    mpBTNGradient->SetItemImage(TBI_BTX_GRADIENT,maImgLinear);
    mpBTNGradient->SetQuickHelpText(TBI_BTX_GRADIENT, String(SVX_RES(STR_HELP_GRADIENT)));    //wj acc
    mpBTNGradient->Hide();

    long aHeightLBTrans = mpLBTransType->GetSizePixel().getHeight();
    Point aPointLB = mpLBTransType->GetPosPixel();
    long aPosY = aPointLB.getY();

    Point aPointMetric = mpMTRTransparent->GetPosPixel();
    Point aPointTB = mpMTRTransparent->GetPosPixel();
    long aHeightMetric = mpMTRTransparent->GetSizePixel().getHeight();
    long aHeightTool = mpBTNGradient->GetSizePixel().getHeight();
    aPointMetric.setY(aPosY+aHeightLBTrans/2-aHeightMetric/2);
    aPointTB.setY(aPosY+aHeightLBTrans/2-aHeightTool/2);
    aPointTB.setX(aPointTB.getX()+3);
    mpMTRTransparent->SetPosPixel(aPointMetric);
    mpBTNGradient->SetPosPixel(aPointTB);

    mpLbFillType->SetAccessibleRelationLabeledBy(mpColorTextFT.get());
    mpLbFillAttr->SetAccessibleRelationLabeledBy(mpLbFillAttr.get());
    mpToolBoxColor->SetAccessibleRelationLabeledBy(mpToolBoxColor.get());
    mpLBTransType->SetAccessibleRelationLabeledBy(mpTrspTextFT.get());
    mpMTRTransparent->SetAccessibleRelationLabeledBy(mpMTRTransparent.get());
    mpBTNGradient->SetAccessibleRelationLabeledBy(mpBTNGradient.get());

    SetupIcons();
}

IMPL_LINK( AreaPropertyPanel, SelectFillTypeHdl, ListBox *, pToolBox )
{
    const XFillStyle eXFS = (XFillStyle)mpLbFillType->GetSelectEntryPos();

    if((XFillStyle)meLastXFS != eXFS)
    {
        mpLbFillAttr->Clear();
        SfxObjectShell* pSh = SfxObjectShell::Current();
        const XFillStyleItem aXFillStyleItem(eXFS);

        // #122676# Do no longer trigger two Execute calls, one for SID_ATTR_FILL_STYLE
        // and one for setting the fill attribute itself, but add two SfxPoolItems to the
        // call to get just one action at the SdrObject and to create only one Undo action, too.
        // Checked that this works in all apps.
        switch( eXFS )
        {
            case XFILL_NONE:
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();
                mpLbFillType->Selected();
                mpLbFillAttr->Disable();

                // #122676# need to call a single SID_ATTR_FILL_STYLE change
                GetBindings()->GetDispatcher()->Execute(
                    SID_ATTR_FILL_STYLE, SFX_CALLMODE_RECORD, &aXFillStyleItem, 0L);
                break;
            }
            case XFILL_SOLID:
            {
                mpLbFillAttr->Hide();
                mpToolBoxColor->Show();
                const String aTmpStr;
                const Color aColor = maLastColor;
                const XFillColorItem aXFillColorItem( aTmpStr, aColor );

                // #122676# change FillStyle and Color in one call
                GetBindings()->GetDispatcher()->Execute(
                    SID_ATTR_FILL_COLOR, SFX_CALLMODE_RECORD, &aXFillColorItem, &aXFillStyleItem, 0L);
                break;
            }
            case XFILL_GRADIENT:
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();

                if(pSh && pSh->GetItem(SID_GRADIENT_LIST))
                {
                    if(!mpLbFillAttr->GetEntryCount())
                    {
                        const SvxGradientListItem aItem(*(const SvxGradientListItem*)(pSh->GetItem(SID_GRADIENT_LIST)));
                        mpLbFillAttr->Enable();
                        mpLbFillAttr->Clear();
                        mpLbFillAttr->Fill(aItem.GetGradientList());
                    }

                    mpLbFillAttr->AdaptDropDownLineCountToMaximum();

                    if(LISTBOX_ENTRY_NOTFOUND != mnLastPosGradient)
                    {
                        const SvxGradientListItem aItem(*(const SvxGradientListItem*)(pSh->GetItem(SID_GRADIENT_LIST)));

                        if(mnLastPosGradient < aItem.GetGradientList()->Count())
                        {
                            const XGradient aGradient = aItem.GetGradientList()->GetGradient(mnLastPosGradient)->GetGradient();
                            const XFillGradientItem aXFillGradientItem(mpLbFillAttr->GetEntry(mnLastPosGradient), aGradient);

                            // #122676# change FillStyle and Gradient in one call
                            GetBindings()->GetDispatcher()->Execute(
                                SID_ATTR_FILL_GRADIENT, SFX_CALLMODE_RECORD, &aXFillGradientItem, &aXFillStyleItem, 0L);
                            mpLbFillAttr->SelectEntryPos(mnLastPosGradient);
                        }
                    }
                }
                else
                {
                    mpLbFillAttr->Disable();
                }
                break;
            }
            case XFILL_HATCH:
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();

                if(pSh && pSh->GetItem(SID_HATCH_LIST))
                {
                    if(!mpLbFillAttr->GetEntryCount())
                    {
                        const SvxHatchListItem aItem( *(const SvxHatchListItem*)(pSh->GetItem(SID_HATCH_LIST)));
                        mpLbFillAttr->Enable();
                        mpLbFillAttr->Clear();
                        mpLbFillAttr->Fill(aItem.GetHatchList());
                    }

                    mpLbFillAttr->AdaptDropDownLineCountToMaximum();

                    if(LISTBOX_ENTRY_NOTFOUND != mnLastPosHatch)
                    {
                        const SvxHatchListItem aItem(*(const SvxHatchListItem*)(pSh->GetItem(SID_HATCH_LIST)));

                        if(mnLastPosHatch < aItem.GetHatchList()->Count())
                        {
                            const XHatch aHatch = aItem.GetHatchList()->GetHatch(mnLastPosHatch)->GetHatch();
                            const XFillHatchItem aXFillHatchItem(mpLbFillAttr->GetSelectEntry(), aHatch);

                            // #122676# change FillStyle and Hatch in one call
                            GetBindings()->GetDispatcher()->Execute(
                                SID_ATTR_FILL_HATCH, SFX_CALLMODE_RECORD, &aXFillHatchItem, &aXFillStyleItem, 0L);
                            mpLbFillAttr->SelectEntryPos(mnLastPosHatch);
                        }
                    }
                }
                else
                {
                    mpLbFillAttr->Disable();
                }
                break;
            }
            case XFILL_BITMAP:
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();

                if(pSh && pSh->GetItem(SID_BITMAP_LIST))
                {
                    if(!mpLbFillAttr->GetEntryCount())
                    {
                        const SvxBitmapListItem aItem( *(const SvxBitmapListItem*)(pSh->GetItem(SID_BITMAP_LIST)));
                        mpLbFillAttr->Enable();
                        mpLbFillAttr->Clear();
                        mpLbFillAttr->Fill(aItem.GetBitmapList());
                    }

                    mpLbFillAttr->AdaptDropDownLineCountToMaximum();

                    if(LISTBOX_ENTRY_NOTFOUND != mnLastPosBitmap)
                    {
                        const SvxBitmapListItem aItem(*(const SvxBitmapListItem*)(pSh->GetItem(SID_BITMAP_LIST)));

                        if(mnLastPosBitmap < aItem.GetBitmapList()->Count())
                        {
                            const XBitmapEntry* pXBitmapEntry = aItem.GetBitmapList()->GetBitmap(mnLastPosBitmap);
                            const XFillBitmapItem aXFillBitmapItem(mpLbFillAttr->GetSelectEntry(), pXBitmapEntry->GetGraphicObject());

                            // #122676# change FillStyle and Bitmap in one call
                            GetBindings()->GetDispatcher()->Execute(
                                SID_ATTR_FILL_BITMAP, SFX_CALLMODE_RECORD, &aXFillBitmapItem, &aXFillStyleItem, 0L);
                            mpLbFillAttr->SelectEntryPos(mnLastPosBitmap);
                        }
                    }
                }
                else
                {
                    mpLbFillAttr->Disable();
                }
                break;
            }
        }

        meLastXFS = (sal_uInt16)eXFS;

        if(XFILL_NONE != eXFS)
        {
            if(pToolBox)
            {
                mpLbFillType->Selected();
            }
        }

        maLayouter.Layout();
    }

    return 0;
}

IMPL_LINK( AreaPropertyPanel, SelectFillAttrHdl, ListBox*, pToolBox )
{
    const XFillStyle eXFS = (XFillStyle)mpLbFillType->GetSelectEntryPos();
    const XFillStyleItem aXFillStyleItem(eXFS);
    SfxObjectShell* pSh = SfxObjectShell::Current();

    if(pToolBox)
    {
        // #122676# dependent from bFillStyleChange, do execute a single or two
        // changes in one Execute call
        const bool bFillStyleChange((XFillStyle) meLastXFS != eXFS);

        switch(eXFS)
        {
            case XFILL_SOLID:
            {
                if(bFillStyleChange)
                {
                    // #122676# Single FillStyle change call needed here
                    GetBindings()->GetDispatcher()->Execute(SID_ATTR_FILL_STYLE, SFX_CALLMODE_RECORD, &aXFillStyleItem, 0L);
                }
                break;
            }
            case XFILL_GRADIENT:
            {
                sal_uInt16 nPos = mpLbFillAttr->GetSelectEntryPos();

                if(LISTBOX_ENTRY_NOTFOUND == nPos)
                {
                    nPos = mnLastPosGradient;
                }

                if(LISTBOX_ENTRY_NOTFOUND != nPos && pSh && pSh->GetItem(SID_GRADIENT_LIST))
                {
                    const SvxGradientListItem aItem(*(const SvxGradientListItem*)(pSh->GetItem(SID_GRADIENT_LIST)));

                    if(nPos < aItem.GetGradientList()->Count())
                    {
                        const XGradient aGradient = aItem.GetGradientList()->GetGradient(nPos)->GetGradient();
                        const XFillGradientItem aXFillGradientItem(mpLbFillAttr->GetSelectEntry(), aGradient);

                        // #122676# Change FillStale and Gradinet in one call
                        GetBindings()->GetDispatcher()->Execute(
                            SID_ATTR_FILL_GRADIENT, SFX_CALLMODE_RECORD, &aXFillGradientItem,
                            bFillStyleChange ? &aXFillStyleItem : 0L, 0L);
                    }
                }

                if(LISTBOX_ENTRY_NOTFOUND != nPos)
                {
                    mnLastPosGradient = nPos;
                }
                break;
            }
            case XFILL_HATCH:
            {
                sal_uInt16 nPos = mpLbFillAttr->GetSelectEntryPos();

                if(LISTBOX_ENTRY_NOTFOUND == nPos)
                {
                    nPos = mnLastPosHatch;
                }

                if(LISTBOX_ENTRY_NOTFOUND != nPos && pSh && pSh->GetItem(SID_HATCH_LIST))
                {
                    const SvxHatchListItem aItem(*(const SvxHatchListItem*)(pSh->GetItem(SID_HATCH_LIST)));

                    if(nPos < aItem.GetHatchList()->Count())
                    {
                        const XHatch aHatch = aItem.GetHatchList()->GetHatch(nPos)->GetHatch();
                        const XFillHatchItem aXFillHatchItem( mpLbFillAttr->GetSelectEntry(), aHatch);

                        // #122676# Change FillStale and Hatch in one call
                        GetBindings()->GetDispatcher()->Execute(
                            SID_ATTR_FILL_HATCH, SFX_CALLMODE_RECORD, &aXFillHatchItem,
                            bFillStyleChange ? &aXFillStyleItem : 0L, 0L);
                    }
                }

                if(LISTBOX_ENTRY_NOTFOUND != nPos)
                {
                    mnLastPosHatch = nPos;
                }
                break;
            }
            case XFILL_BITMAP:
            {
                sal_uInt16 nPos = mpLbFillAttr->GetSelectEntryPos();

                if(LISTBOX_ENTRY_NOTFOUND == nPos)
                {
                    nPos = mnLastPosBitmap;
                }

                if(LISTBOX_ENTRY_NOTFOUND != nPos && pSh && pSh->GetItem(SID_BITMAP_LIST))
                {
                    const SvxBitmapListItem aItem(*(const SvxBitmapListItem*)(pSh->GetItem(SID_BITMAP_LIST)));

                    if(nPos < aItem.GetBitmapList()->Count())
                    {
                        const XBitmapEntry* pXBitmapEntry = aItem.GetBitmapList()->GetBitmap(nPos);
                        const XFillBitmapItem aXFillBitmapItem(mpLbFillAttr->GetSelectEntry(), pXBitmapEntry->GetGraphicObject());

                        // #122676# Change FillStale and Bitmap in one call
                        GetBindings()->GetDispatcher()->Execute(
                            SID_ATTR_FILL_BITMAP, SFX_CALLMODE_RECORD, &aXFillBitmapItem,
                            bFillStyleChange ? &aXFillStyleItem : 0L, 0L);
                    }
                }

                if(LISTBOX_ENTRY_NOTFOUND != nPos)
                {
                    mnLastPosBitmap = nPos;
                }
                break;
            }
            default: break;
        }
    }

    return 0;
}

IMPL_LINK(AreaPropertyPanel, ToolBoxColorDropHdl, ToolBox*, pToolBox)
{
    const sal_uInt16 nId = pToolBox->GetCurItemId();

    if(TBI_COLOR == nId)
    {
        maColorPopup.Show(*pToolBox);

        if (mpColorItem)
        {
            maColorPopup.SetCurrentColor(mpColorItem->GetColorValue(), mbColorAvail);
        }
        else
        {
            maColorPopup.SetCurrentColor(COL_WHITE, false);
        }
    }

    return 0;
}

void AreaPropertyPanel::SetColor (
    const String& rsColorName,
    const Color aColor)
{
    const XFillColorItem aXFillColorItem(rsColorName, aColor);
    mpBindings->GetDispatcher()->Execute(SID_ATTR_FILL_COLOR, SFX_CALLMODE_RECORD, &aXFillColorItem, 0L);
    maLastColor = aColor;
}

PopupControl* AreaPropertyPanel::CreateTransparencyGradientControl (PopupContainer* pParent)
{
    return new AreaTransparencyGradientControl(pParent, *this);
}

PopupControl* AreaPropertyPanel::CreateColorPopupControl (PopupContainer* pParent)
{
    return new ColorControl(
        pParent,
        mpBindings,
        SVX_RES(RID_POPUPPANEL_AERAPAGE_COLOR),
        SVX_RES(VS_COLOR),
        ::boost::bind(&AreaPropertyPanel::GetLastColor, this),
        ::boost::bind(&AreaPropertyPanel::SetColor, this, _1,_2),
        pParent,
        0);
}

void AreaPropertyPanel::SetupIcons(void)
{
    if(Theme::GetBoolean(Theme::Bool_UseSymphonyIcons))
    {
        // todo
    }
    else
    {
        // todo
    }
}

AreaPropertyPanel* AreaPropertyPanel::Create (
    Window* pParent,
    const cssu::Reference<css::frame::XFrame>& rxFrame,
    SfxBindings* pBindings)
{
    if (pParent == NULL)
        throw lang::IllegalArgumentException(A2S("no parent Window given to AreaPropertyPanel::Create"), NULL, 0);
    if ( ! rxFrame.is())
        throw lang::IllegalArgumentException(A2S("no XFrame given to AreaPropertyPanel::Create"), NULL, 1);
    if (pBindings == NULL)
        throw lang::IllegalArgumentException(A2S("no SfxBindings given to AreaPropertyPanel::Create"), NULL, 2);

    return new AreaPropertyPanel(
        pParent,
        rxFrame,
        pBindings);
}

void AreaPropertyPanel::DataChanged(
    const DataChangedEvent& rEvent)
{
    (void)rEvent;

    SetupIcons();
}

void AreaPropertyPanel::ImpUpdateTransparencies()
{
    if(mpTransparanceItem.get() && mpFloatTransparenceItem.get())
    {
        bool bZeroValue(false);

        if(mpTransparanceItem.get())
        {
            const sal_uInt16 nValue(mpTransparanceItem->GetValue());

            if(!nValue)
            {
                bZeroValue = true;
            }
            else if(nValue <= 100)
            {
                mpLBTransType->Enable();
                mpTrspTextFT->Enable();
                mpLBTransType->SelectEntryPos(1);
                mpBTNGradient->Hide();
                mpMTRTransparent->Show();
                mpMTRTransparent->Enable();
                mpMTRTransparent->SetValue(nValue);
            }

            if(!bZeroValue)
            {
                maTrGrPopup.Hide();
            }
        }

        if(bZeroValue && mpFloatTransparenceItem.get())
        {
            if(mpFloatTransparenceItem->IsEnabled())
            {
                const XGradient& rGradient = mpFloatTransparenceItem->GetGradientValue();
                const bool bHighContrast(GetSettings().GetStyleSettings().GetHighContrastMode());
                sal_uInt16 nEntryPos(0);
                Image* pImage = 0;

                mpLBTransType->Enable();
                mpTrspTextFT->Enable();
                mpMTRTransparent->Hide();
                mpBTNGradient->Enable();
                mpBTNGradient->Show();

                switch(rGradient.GetGradientStyle())
                {
                    case XGRAD_LINEAR:
                    {
                        nEntryPos = 2;
                        pImage = bHighContrast ? &maImgLinearH : &maImgLinear;
                        break;
                    }
                    case XGRAD_AXIAL:
                    {
                        nEntryPos = 3;
                        pImage = bHighContrast ? &maImgAxialH : &maImgAxial;
                        break;
                    }
                    case XGRAD_RADIAL:
                    {
                        nEntryPos = 4;
                        pImage = bHighContrast ? &maImgRadialH : &maImgRadial;
                        break;
                    }
                    case XGRAD_ELLIPTICAL:
                    {
                        nEntryPos = 5;
                        pImage = bHighContrast ? &maImgElliH : &maImgElli;
                        break;
                    }
                    case XGRAD_SQUARE:
                    {
                        nEntryPos = 6;
                        pImage = bHighContrast ? &maImgQuadH : &maImgQuad;
                        break;
                    }
                    case XGRAD_RECT:
                    {
                        nEntryPos = 7;
                        pImage = bHighContrast ? &maImgSquareH : &maImgSquare;
                        break;
                    }
                }

                mpLBTransType->SelectEntryPos(nEntryPos);
                mpBTNGradient->SetItemImage(TBI_BTX_GRADIENT, *pImage);
                bZeroValue = false;
            }
            else
            {
                bZeroValue = true;
            }
        }

        if(bZeroValue)
        {
            mpLBTransType->Enable();
            mpTrspTextFT->Enable();
            mpLBTransType->SelectEntryPos(0);
            mpBTNGradient->Hide();
            mpMTRTransparent->Enable();
            mpMTRTransparent->Show();
            mpMTRTransparent->SetValue(0);
        }
    }
    else
    {
        // no transparency at all
        mpLBTransType->SetNoSelection();
        mpLBTransType->Disable();
        mpTrspTextFT->Disable();
        mpMTRTransparent->Disable();
        mpMTRTransparent->Show();
        mpBTNGradient->Disable();
        mpBTNGradient->Hide();
    }
}

void AreaPropertyPanel::NotifyItemUpdate(
    sal_uInt16 nSID,
    SfxItemState eState,
    const SfxPoolItem* pState,
    const bool bIsEnabled)
{
    (void)bIsEnabled;
    const bool bDisabled(SFX_ITEM_DISABLED == eState);

    switch(nSID)
    {
        case SID_ATTR_FILL_TRANSPARENCE:
        case SID_ATTR_FILL_FLOATTRANSPARENCE:
        {
            bool bFillTransparenceChanged(false);

            if(SID_ATTR_FILL_TRANSPARENCE == nSID)
            {
                bFillTransparenceChanged = true;

                if(eState >= SFX_ITEM_AVAILABLE)
                {
                    const SfxUInt16Item* pItem = dynamic_cast< const SfxUInt16Item* >(pState);

                    if(pItem && (!mpTransparanceItem || *pItem != *mpTransparanceItem))
                    {
                        mpTransparanceItem.reset((SfxUInt16Item*)pItem->Clone());
                    }
                    else
                    {
                        mpTransparanceItem.reset();
                    }
                }
                else
                {
                    mpTransparanceItem.reset();
                }
            }
            else // if(SID_ATTR_FILL_FLOATTRANSPARENCE == nSID)
            {
                bFillTransparenceChanged = true;

                if(eState >= SFX_ITEM_AVAILABLE)
                {
                    const XFillFloatTransparenceItem* pItem = dynamic_cast< const XFillFloatTransparenceItem* >(pState);

                    if(pItem && (!mpFloatTransparenceItem || *pItem != *mpFloatTransparenceItem))
                    {
                        mpFloatTransparenceItem.reset((XFillFloatTransparenceItem*)pItem->Clone());
                    }
                    else
                    {
                        mpFloatTransparenceItem.reset();
                    }
                }
                else
                {
                    mpFloatTransparenceItem.reset();
                }
            }

            if(bFillTransparenceChanged)
            {
                // update transparency settings dependent of mpTransparanceItem and mpFloatTransparenceItem
                ImpUpdateTransparencies();
            }
            break;
        }
        case SID_ATTR_FILL_STYLE:
        {
            if(bDisabled)
            {
                mpLbFillType->Disable();
                mpColorTextFT->Disable();
                mpLbFillType->SetNoSelection();
                mpLbFillAttr->Show();
                mpLbFillAttr->Disable();
                mpLbFillAttr->SetNoSelection();
                mpToolBoxColor->Hide();
                meLastXFS = -1;
                mpStyleItem.reset();
            }

            if(eState >= SFX_ITEM_AVAILABLE)
            {
                const XFillStyleItem* pItem = dynamic_cast< const XFillStyleItem* >(pState);

                if(pItem)
                {
                    mpStyleItem.reset(dynamic_cast< XFillStyleItem* >(pItem->Clone()));
                    mpLbFillType->Enable();
                    mpColorTextFT->Enable();
                    XFillStyle eXFS = (XFillStyle)mpStyleItem->GetValue();
                    meLastXFS = eXFS;
                    mpLbFillType->SelectEntryPos(sal::static_int_cast< sal_uInt16 >(eXFS));

                    if(XFILL_NONE == eXFS)
                    {
                        mpLbFillAttr->SetNoSelection();
                        mpLbFillAttr->Disable();
                    }

                    Update();
                    break;
                }
            }

            mpLbFillType->SetNoSelection();
            mpLbFillAttr->Show();
            mpLbFillAttr->Disable();
            mpLbFillAttr->SetNoSelection();
            mpToolBoxColor->Hide();
            meLastXFS = -1;
            mpStyleItem.reset();
            break;
        }
        case SID_ATTR_FILL_COLOR:
        {
            if(SFX_ITEM_AVAILABLE == eState)
            {
                mpColorItem.reset(pState ? (XFillColorItem*)pState->Clone() : 0);
            }

            if(mpStyleItem && XFILL_SOLID == (XFillStyle)mpStyleItem->GetValue())
            {
                mpLbFillAttr->Hide();
                mpToolBoxColor->Show();

                if(SFX_ITEM_AVAILABLE == eState)
                {
                    mpToolBoxColor->Enable();
                    mbColorAvail = true;
                    // maLastColor = mpColorItem->GetColorValue();
                    Update();
                }
                else if(SFX_ITEM_DISABLED == eState)
                {
                    mpToolBoxColor->Disable();
                    mbColorAvail = false;
                    mpColorUpdater->Update(COL_WHITE);
                }
                else
                {
                    mbColorAvail = false;
                    mpColorUpdater->Update(COL_WHITE);
                }
            }
            break;
        }
        case SID_ATTR_FILL_GRADIENT:
        {
            if(SFX_ITEM_AVAILABLE == eState)
            {
                mpFillGradientItem.reset(pState ? (XFillGradientItem*)pState->Clone() : 0);
            }

            if(mpStyleItem && XFILL_GRADIENT == (XFillStyle)mpStyleItem->GetValue())
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();

                if(SFX_ITEM_AVAILABLE == eState)
                {
                    mpLbFillAttr->Enable();
                    Update();
                }
                else if(SFX_ITEM_DISABLED == eState )
                {
                    mpLbFillAttr->Disable();
                    mpLbFillAttr->SetNoSelection();
                }
                else
                {
                    mpLbFillAttr->SetNoSelection();
                }
            }
            break;
        }
        case SID_ATTR_FILL_HATCH:
        {
            if(SFX_ITEM_AVAILABLE == eState)
            {
                mpHatchItem.reset(pState ? (XFillHatchItem*)pState->Clone() : 0);
            }

            if(mpStyleItem && XFILL_HATCH == (XFillStyle)mpStyleItem->GetValue())
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();

                if(SFX_ITEM_AVAILABLE == eState)
                {
                    mpLbFillAttr->Enable();
                    Update();
                }
                else if(SFX_ITEM_DISABLED == eState )
                {
                    mpLbFillAttr->Disable();
                    mpLbFillAttr->SetNoSelection();
                }
                else
                {
                    mpLbFillAttr->SetNoSelection();
                }
            }
            break;
        }
        case SID_ATTR_FILL_BITMAP:
        {
            if(SFX_ITEM_AVAILABLE == eState)
            {
                mpBitmapItem.reset(pState ? (XFillBitmapItem*)pState->Clone() : 0);
            }

            if(mpStyleItem && XFILL_BITMAP == (XFillStyle)mpStyleItem->GetValue())
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();

                if(SFX_ITEM_AVAILABLE == eState)
                {
                    mpLbFillAttr->Enable();
                    Update();
                }
                else if(SFX_ITEM_DISABLED == eState )
                {
                    mpLbFillAttr->Disable();
                    mpLbFillAttr->SetNoSelection();
                }
                else
                {
                    mpLbFillAttr->SetNoSelection();
                }
            }
            break;
        }
        case SID_COLOR_TABLE:
        {
            if(SFX_ITEM_AVAILABLE == eState)
            {
                if(mpStyleItem && XFILL_SOLID == (XFillStyle)mpStyleItem->GetValue())
                {
                    if(mpColorItem)
                    {
                        const Color aColor = mpColorItem->GetColorValue();
                        const SfxObjectShell* pSh = SfxObjectShell::Current();
                        const SvxColorTableItem aItem(*(const SvxColorTableItem*)(pSh->GetItem(SID_COLOR_TABLE)));

                        mpLbFillAttr->Clear();
                        mpLbFillAttr->Enable();
                        mpLbFillAttr->Fill(aItem.GetColorTable());
                        mpLbFillAttr->SelectEntry(aColor);
                    }
                    else
                    {
                        mpLbFillAttr->SetNoSelection();
                    }
                }
            }
            break;
        }
        case SID_GRADIENT_LIST:
        {
            if(SFX_ITEM_AVAILABLE == eState)
            {
                if(mpStyleItem && XFILL_GRADIENT == (XFillStyle)mpStyleItem->GetValue())
                {
                    if(mpFillGradientItem)
                    {
                        const String aString( mpFillGradientItem->GetName() );
                        const SfxObjectShell* pSh = SfxObjectShell::Current();
                        const SvxGradientListItem aItem( *(const SvxGradientListItem*)(pSh->GetItem(SID_GRADIENT_LIST)));

                        mpLbFillAttr->Clear();
                        mpLbFillAttr->Enable();
                        mpLbFillAttr->Fill(aItem.GetGradientList());
                        mpLbFillAttr->SelectEntry(aString);
                    }
                    else
                    {
                        mpLbFillAttr->SetNoSelection();
                    }
                }
            }
            break;
        }
        case SID_HATCH_LIST:
        {
            if(SFX_ITEM_AVAILABLE == eState)
            {
                if(mpStyleItem && XFILL_HATCH == (XFillStyle)mpStyleItem->GetValue())
                {
                    if(mpHatchItem)
                    {
                        const String aString( mpHatchItem->GetName() );
                        const SfxObjectShell* pSh = SfxObjectShell::Current();
                        const SvxHatchListItem aItem(*(const SvxHatchListItem*)(pSh->GetItem(SID_HATCH_LIST)));

                        mpLbFillAttr->Clear();
                        mpLbFillAttr->Enable();
                        mpLbFillAttr->Fill(aItem.GetHatchList());
                        mpLbFillAttr->SelectEntry(aString);
                    }
                    else
                    {
                        mpLbFillAttr->SetNoSelection();
                    }
                }
            }
            break;
        }
        case SID_BITMAP_LIST:
        {
            if(SFX_ITEM_AVAILABLE == eState)
            {
                if(mpStyleItem && XFILL_BITMAP == (XFillStyle)mpStyleItem->GetValue())
                {
                    if(mpBitmapItem)
                    {
                        const String aString( mpBitmapItem->GetName() );
                        const SfxObjectShell* pSh = SfxObjectShell::Current();
                        const SvxBitmapListItem aItem(*(const SvxBitmapListItem*)(pSh->GetItem(SID_BITMAP_LIST)));

                        mpLbFillAttr->Clear();
                        mpLbFillAttr->Enable();
                        mpLbFillAttr->Fill(aItem.GetBitmapList());
                        mpLbFillAttr->SelectEntry(aString);
                    }
                    else
                    {
                        mpLbFillAttr->SetNoSelection();
                    }
                }
            }
            break;
        }
    }

    maLayouter.Layout();
}

SfxBindings* AreaPropertyPanel::GetBindings()
{
    return mpBindings;
}

void AreaPropertyPanel::Update()
{
    if(mpStyleItem)
    {
        const XFillStyle eXFS = (XFillStyle)mpStyleItem->GetValue();
        SfxObjectShell* pSh = SfxObjectShell::Current();

        switch( eXFS )
        {
            case XFILL_NONE:
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();
                break;
            }
            case XFILL_SOLID:
            {
                if(mpColorItem)
                {
                    mpLbFillAttr->Hide();
                    mpToolBoxColor->Show();
                    mpColorUpdater->Update(mpColorItem->GetColorValue());
                }
                else
                {
                    mpColorUpdater->Update(COL_WHITE);
                }
                break;
            }
            case XFILL_GRADIENT:
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();

                if(pSh && pSh->GetItem(SID_GRADIENT_LIST))
                {
                    const SvxGradientListItem aItem(*(const SvxGradientListItem*)(pSh->GetItem(SID_GRADIENT_LIST)));
                    mpLbFillAttr->Enable();
                    mpLbFillAttr->Clear();
                    mpLbFillAttr->Fill(aItem.GetGradientList());

                    if(mpFillGradientItem)
                    {
                        const String aString(mpFillGradientItem->GetName());

                        mpLbFillAttr->SelectEntry(aString);
                    }
                    else
                    {
                        mpLbFillAttr->SetNoSelection();
                    }
                }
                else
                {
                    mpLbFillAttr->SetNoSelection();
                }
                break;
            }
            case XFILL_HATCH:
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();

                if(pSh && pSh->GetItem(SID_HATCH_LIST))
                {
                    const SvxHatchListItem aItem(*(const SvxHatchListItem*)(pSh->GetItem(SID_HATCH_LIST)));
                    mpLbFillAttr->Enable();
                    mpLbFillAttr->Clear();
                    mpLbFillAttr->Fill(aItem.GetHatchList());

                    if(mpHatchItem)
                    {
                        const String aString(mpHatchItem->GetName());

                        mpLbFillAttr->SelectEntry( aString );
                    }
                    else
                    {
                        mpLbFillAttr->SetNoSelection();
                    }
                }
                else
                {
                    mpLbFillAttr->SetNoSelection();
                }
                break;
            }
            case XFILL_BITMAP:
            {
                mpLbFillAttr->Show();
                mpToolBoxColor->Hide();

                if(pSh && pSh->GetItem(SID_BITMAP_LIST))
                {
                    const SvxBitmapListItem aItem(*(const SvxBitmapListItem*)(pSh->GetItem(SID_BITMAP_LIST)));
                    mpLbFillAttr->Enable();
                    mpLbFillAttr->Clear();
                    mpLbFillAttr->Fill(aItem.GetBitmapList());

                    if(mpBitmapItem)
                    {
                        const String aString(mpBitmapItem->GetName());

                        mpLbFillAttr->SelectEntry(aString);
                    }
                    else
                    {
                        mpLbFillAttr->SetNoSelection();
                    }
                }
                else
                {
                    mpLbFillAttr->SetNoSelection();
                }
                break;
            }
            default:
                DBG_ERROR( "Non supported FillType (!)" );
            break;
        }
    }
}

IMPL_LINK( AreaPropertyPanel, ImplPopupModeEndHdl, FloatingWindow*, EMPTYARG )
{
    return 0;
}

IMPL_LINK( AreaPropertyPanel, ClickTrGrHdl_Impl, ToolBox*, pToolBox )
{
    maTrGrPopup.Rearrange(mpFloatTransparenceItem.get());
    OSL_ASSERT(pToolBox->GetCurItemId() == TBI_BTX_GRADIENT);
    maTrGrPopup.Show(*pToolBox);

    return (0L);
}

IMPL_LINK(AreaPropertyPanel, ChangeTrgrTypeHdl_Impl, void *, EMPTYARG)
{
    sal_uInt16 nSelectType = mpLBTransType->GetSelectEntryPos();
    bool bGradient = false;
    sal_uInt16 nTrans = 0;

    if(!nSelectType)
    {
        mpBTNGradient->Hide();
        mpMTRTransparent->Show();
        mpMTRTransparent->Enable();
        mpMTRTransparent->SetValue(0);
    }
    else if(1 == nSelectType)
    {
        mpBTNGradient->Hide();
        mpMTRTransparent->Show();
        nTrans = mnLastTransSolid;
        mpMTRTransparent->SetValue(nTrans);
        mpLBTransType->SelectEntryPos(1);
        mpMTRTransparent->Enable();
    }
    else
    {
        mpBTNGradient->Show();

        switch (nSelectType)
        {
            case 2:
                mpBTNGradient->SetItemImage(TBI_BTX_GRADIENT,GetSettings().GetStyleSettings().GetHighContrastMode()? maImgLinearH : maImgLinear);
                break;
            case 3:
                mpBTNGradient->SetItemImage(TBI_BTX_GRADIENT,GetSettings().GetStyleSettings().GetHighContrastMode()? maImgAxialH : maImgAxial);
                break;
            case 4:
                mpBTNGradient->SetItemImage(TBI_BTX_GRADIENT,GetSettings().GetStyleSettings().GetHighContrastMode()? maImgRadialH : maImgRadial);
                break;
            case 5:
                mpBTNGradient->SetItemImage(TBI_BTX_GRADIENT,GetSettings().GetStyleSettings().GetHighContrastMode()? maImgElliH : maImgElli );
                break;
            case 6:
                mpBTNGradient->SetItemImage(TBI_BTX_GRADIENT,GetSettings().GetStyleSettings().GetHighContrastMode()? maImgQuadH : maImgQuad );
                break;
            case 7:
                mpBTNGradient->SetItemImage(TBI_BTX_GRADIENT,GetSettings().GetStyleSettings().GetHighContrastMode()? maImgSquareH : maImgSquare);
                break;
        }

        mpMTRTransparent->Hide();
        mpBTNGradient->Enable();
        bGradient = true;
    }

    const XFillTransparenceItem aLinearItem(nTrans);
    GetBindings()->GetDispatcher()->Execute( SID_ATTR_FILL_TRANSPARENCE, SFX_CALLMODE_RECORD, &aLinearItem, 0L );

    if(nSelectType > 1)
    {
        nSelectType -= 2;
    }

    XGradient aTmpGradient;

    switch(nSelectType)
    {
        case XGRAD_LINEAR:
            aTmpGradient = maGradientLinear;
            break;
        case XGRAD_AXIAL:
            aTmpGradient = maGradientAxial;
            break;
        case XGRAD_RADIAL:
            aTmpGradient = maGradientRadial;
            break;
        case XGRAD_ELLIPTICAL:
            aTmpGradient = maGradientElliptical;
            break;
        case XGRAD_SQUARE:
            aTmpGradient = maGradientSquare;
            break;
        case XGRAD_RECT:
            aTmpGradient = maGradientRect;
            break;
    }

    SfxItemPool* pPool = 0;
    const XFillFloatTransparenceItem aGradientItem(pPool, aTmpGradient, sal_Bool(bGradient));
    GetBindings()->GetDispatcher()->Execute( SID_ATTR_FILL_FLOATTRANSPARENCE, SFX_CALLMODE_RECORD, &aGradientItem, 0L );

    return( 0L );
}

IMPL_LINK(AreaPropertyPanel, ModifyTransparentHdl_Impl, void*, EMPTYARG)
{
    const sal_uInt16 nTrans = (sal_uInt16)mpMTRTransparent->GetValue();
    mnLastTransSolid = nTrans;
    const sal_uInt16 nSelectType = mpLBTransType->GetSelectEntryPos();

    if(nTrans && !nSelectType)
    {
        mpLBTransType->SelectEntryPos(1);
    }

    const XFillTransparenceItem aLinearItem(nTrans);
    GetBindings()->GetDispatcher()->Execute( SID_ATTR_FILL_TRANSPARENCE, SFX_CALLMODE_RECORD, &aLinearItem, 0L );

    return 0L;
}

Color AreaPropertyPanel::GetLastColor (void) const
{
    return maLastColor;
}

XGradient AreaPropertyPanel::GetGradient (const XGradientStyle eStyle) const
{
    switch (eStyle)
    {
        default:
        case XGRAD_LINEAR:
            return maGradientLinear;
        case XGRAD_AXIAL:
            return maGradientAxial;
        case XGRAD_RADIAL:
            return maGradientRadial;
        case XGRAD_ELLIPTICAL:
            return maGradientElliptical;
        case XGRAD_SQUARE:
            return maGradientSquare;
        case XGRAD_RECT:
            return maGradientRect;
    }
}

void AreaPropertyPanel::SetGradient (const XGradient& rGradient)
{
    switch (rGradient.GetGradientStyle())
    {
        case XGRAD_LINEAR:
            maGradientLinear = rGradient;
            break;
        case XGRAD_AXIAL:
            maGradientAxial = rGradient;
            break;
        case XGRAD_RADIAL:
            maGradientRadial = rGradient;
            break;
        case XGRAD_ELLIPTICAL:
            maGradientElliptical = rGradient;
            break;
        case XGRAD_SQUARE:
            maGradientSquare = rGradient;
            break;
        case XGRAD_RECT:
            maGradientRect = rGradient;
            break;
    }
}

sal_Int32 AreaPropertyPanel::GetSelectedTransparencyTypeIndex (void) const
{
    return mpLBTransType->GetSelectEntryPos();
}

void AreaPropertyPanel::Resize (void)
{
    maLayouter.Layout();
}

} } // end of namespace svx::sidebar

// eof

ext: cxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
//main.cpp
//Fly By Knight - Chess Engine
//Created by Edward Sandor 2011-2012.
//Read the README for more.

#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>
#include <queue>
#include <boost/thread.hpp>
#include <ctime>
#include "game.hpp"
#include "main.hpp"
#include "board.hpp"
#include "moveTree.hpp"

using namespace std;

int eColor = WHITE;
queue<string> inputQueue;
queue<string> pings;

Game * currentGame = new Game();
bool editMode = false;

bool ponder = false;
bool analyze = false;
bool pondB4 = false;

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

	handleOutput("feature myname=\"Fly By Knight 0.3.5\" sigint=0 sigterm=0 ping=1 time=0 colors=0");

	boost::thread inputQueuerThread(inputQueuer);

	string input = "";
	string last = input;

	for(;;){
		currentGame->updateClocks();
		if(inputQueue.size() > 0){
			input = inputQueue.front();

			if(input.length() == 0)
				input = last;
			else
				last = input;
			inputQueue.pop();
		}
		handleInput(input);
		input = "";
	}

	return 0;
}
void inputQueuer(){
	for(;;){
		string input;
		getline(cin, input);
		inputQueue.push(input);
	}
}

bool handleInput(string input){

	//cin.rdbuf()->in_avail();
	// if(input.length() > 0 && input.at(input.length()-1) == '\n')
	//   input = input.substr(0,input.length()-1);

	if(!editMode){
		if(input.size() == 0);
		else if(input.find("quit") == 0)                                  //exits program
			exit(0);
		else if(input.find("new") == 0)                         //reset the board play white
			currentGame->resetGame();
		else if(input.find("print") == 0)                         //draws a board
			currentGame->getBoard()->printBoard();
		else if(input.find("help") == 0)                          //dislays list of commands
			handleOutput("\nquit\nprint\nnew\ngo\nforce\nundo\nremove\nredo\nreplace\nhelp\n");
		else if(input.find("go") == 0){                             //move right now
			currentGame->playAs = currentGame->moveTree->actual->turn%2;
			currentGame->searchClock = clock();
		}
		else if(input.find("force") == 0 || input.find("result") == 0)                         //turn on force mode or stop play.
			currentGame->playAs = NONE;
		else if(input.find("undo") == 0){                        //go back 1 move; play same color
			currentGame->moveBack();
				currentGame->commitMove();
		}
		else if(input.find("remove") == 0){                    //go back 2 moves; play same color
			currentGame->moveBack(2);
				currentGame->commitMove();
		}
		else if(input.find("redo") == 0){                        //go foreward 1 move; play same color
			currentGame->moveForward();
				currentGame->commitMove();
		}
		else if(input.find("replace") == 0){                         //go foreward 2 move; play same color
			currentGame->moveForward(2);
				currentGame->commitMove();
		}
		else if(input.find("edit") == 0){
			currentGame->goActualLayout();
			editMode = true;
			eColor = WHITE;
		}
		else if(input.find("ping") == 0){
			if(input.length() > 5)
				pings.push(input.substr(5));
			else
				pings.push("");
		}
		else if(input.find("hard") == 0){
			ponder = true;
		}
		else if(input.find("easy") == 0){
			ponder = false;
		}
		else if(input.find("post") == 0){
			currentGame->post = true;
		}
		else if(input.find("nopost") == 0){
			currentGame->post = false;
		}
		else if(input.find("analyze") == 0){
			analyze = true;
			pondB4 = ponder;
			ponder = true;
			currentGame->playAs = NONE;
		}
		else if(input.find("exit") == 0){                              //exits program or analyze
			if(!analyze)
				exit(0);
			else{
				ponder = pondB4;
				analyze = false;
			}
		}
		else if(input.find(".") == 0){
				if(currentGame->analysisQueue.size() > 0){
					string stat01 = "stat01: 0 ";
					stat01.append(std::to_string((long double)currentGame->nodes));
					stat01.append(" ");
					int depth = currentGame->analysisQueue[0]->turn - currentGame->moveTree->actual->turn;
					stat01.append(to_string((long double)depth));
					stat01.append(" ");
					int left = 0;
					for(unsigned int i = 0; i < currentGame->analysisQueue.size(); i++){
						if(currentGame->analysisQueue[0]->turn == currentGame->analysisQueue[i]->turn)
							left++;
					}
					stat01.append(to_string((long double)left));
					stat01.append(" ");
					stat01.append(to_string((long double)currentGame->analysisQueue.size()));
					stat01.append(" ");
					stat01.append(currentGame->analysisQueue[0]->id);
					handleOutput(stat01);
				}
		}
		else if(Board::moveFormat(input)){                   //move piece
			currentGame->goActualLayout();
			if(currentGame->move(input)){
				currentGame->commitMove();
				currentGame->endGame();
			}
			else{
				handleOutput("Illegal move: " + input);
			}
		}
		else if(input.find("?") == 0 && currentGame->playAs == currentGame->moveTree->actual->turn%2){
			Move * tmp = currentGame->moveTree->actual->getBest();
				if(tmp != NULL){
					handleOutput("move " + tmp->id);
					currentGame->move(tmp);
					currentGame->commitMove();
				}
			currentGame->endGame();
		}
		else if(input.find("hint") == 0){
			Move * tmp = currentGame->moveTree->actual->getBest();
				if(tmp != NULL){
					handleOutput("Hint: " + tmp->id);
				}
		}
		else if(input.find("stepp") == 0){
			currentGame->stepAnalysis();
			currentGame->getBoard()->printBoard();
		}
		else{                                                                     //handle unknown commands
			handleOutput("Error (unknown command): " + input);
		}

		if(ponder)
			currentGame->stepAnalysis();
		else if(currentGame->playAs == currentGame->moveTree->actual->turn%2)
			currentGame->stepAnalysis();

		if(currentGame->playAs == currentGame->moveTree->actual->turn%2 && currentGame->analysisQueue.size() > 0 && currentGame->analysisQueue[0]->turn - currentGame->moveTree->actual->turn >= DEPTH){
			Move * tmp = currentGame->moveTree->actual->getBest();
			if(tmp != NULL){
				handleOutput("move " + tmp->id);
				currentGame->move(tmp);
				currentGame->commitMove();
			}
			currentGame->endGame();
		}
		if(currentGame->playAs != currentGame->moveTree->actual->turn%2){
			while(pings.size() > 0){
				handleOutput("pong " + pings.front());
				pings.pop();
			}
		}
		/*string str = currentGame->chooseMove();
		if(str.find("...---...") != 0){
			currentGame->goActualLayout();
			currentGame->move(str);
			handleOutput("move " + str);
			currentGame->commitMove();
			currentGame->endGame();
		}*/
	}
	else{
		if(input.find(".") == 0)
			editMode = false;
		else if(input.find("#") == 0)
			currentGame->clear();
		else if(input.find("print") == 0)
			currentGame->getBoard()->printBoard();
		else if(input.find("c") == 0)
			eColor = eColor == WHITE? BLACK:WHITE;
		else{
			if(!currentGame->modSquare(input, eColor))
				handleOutput("Error (edit mode): " + input);
		}
	}

	return true;
}
bool handleOutput(string output){
	//cout.flush();

	cout << output << endl;
	return true;
}

ext: cpp

max_stars_repo_name: ewsandor/fly-by-knight

max_issues_repo_name: ewsandor/fly-by-knight

max_forks_repo_name: ewsandor/flyByKnight


text:
/*
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/format.hpp>
#include <boost/regex.hpp>

#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/tables.h>

#include "osquery/core/conversions.h"
#include "osquery/tables/system/system_utils.h"

namespace fs = boost::filesystem;
namespace alg = boost::algorithm;

namespace osquery {
namespace tables {

/// Set of registers, x86 and x64, that we collect from crash logs
const std::set<std::string> kRegisters = {
    "eax", "edi", "ss", "ds", "rax", "rdi", "r8", "r12", "rip", "x0", "x4"};
/// Location of the system application crash logs in OS X
const std::string kDiagnosticReportsPath = "/Library/Logs/DiagnosticReports";
/// Location of the user mobile devices crash logs in OS X
const std::string kMobileDiagnosticReportsPath =
    "/Library/Logs/CrashReporter/MobileDevice";
/// Map of the values we currently parse out of the log file
const std::map<std::string, std::string> kCrashDumpKeys = {
    {"Process", "pid"},
    {"Path", "path"},
    {"Log Location", "crash_path"},
    {"Identifier", "identifier"},
    {"Version", "version"},
    {"Parent Process", "parent"},
    {"Responsible", "responsible"},
    {"User ID", "uid"},
    {"Date/Time", "datetime"},
    {"Crashed Thread", "crashed_thread"},
    {"Exception Type", "exception_type"},
    {"Exception Codes", "exception_codes"},
    {"Exception Note", "exception_notes"},
    {"Triggered by Thread", "crashed_thread"},
};

void readCrashDump(const std::string& app_log, Row& r) {
  r["crash_path"] = app_log;
  std::string content;

  if (!readFile(app_log, content).ok()) {
    return;
  }

  // Variables for capturing the stack trace
  boost::format crashed_thread_format("Thread %1% Crashed");
  auto crashed_thread_seen = false;

  auto lines = split(content, "\n");
  for (auto it = lines.begin(); it != lines.end(); it++) {
    auto line = *it;
    // Tokenize first by colons
    auto toks = split(line, ":");

    if (toks.size() == 0) {
      continue;
    }

    // Grab the most recent stack trace line of the crashed thread.
    if (crashed_thread_seen && toks[0] == crashed_thread_format.str()) {
      if (std::next(it) != lines.end()) {
        r["stack_trace"] = *(++it);
      }
      crashed_thread_seen = false;
      continue;
    }

    if (kCrashDumpKeys.count(toks[0]) == 0 && kRegisters.count(toks[0]) == 0) {
      continue;
    }

    // Process and grab all register values
    if (kRegisters.count(toks[0]) > 0) {
      boost::trim(line);

      boost::regex rx_spaces("\\s+");
      boost::regex rx_spaces_colon(":\\s+");

      line = boost::regex_replace(line, rx_spaces, " ");
      line = boost::regex_replace(line, rx_spaces_colon, ":");

      r["registers"] +=
          (r["registers"].empty()) ? std::move(line) : " " + std::move(line);

    } else if (toks[0] == "Date/Time" && toks.size() >= 3) {
      // Reconstruct split date/time
      r[kCrashDumpKeys.at(toks[0])] = toks[1] + ":" + toks[2] + ":" + toks[3];
    } else if (toks[0] == "Crashed Thread" ||
               toks[0] == "Triggered by Thread") {
      // If the token is the Crashed thread, update the format string so
      // we can grab the stack trace later.
      auto t = split(toks[1], " ");
      if (t.size() == 0) {
        continue;
      }
      r[kCrashDumpKeys.at(toks[0])] = t[0];
      crashed_thread_format % r[kCrashDumpKeys.at(toks[0])];
      crashed_thread_seen = true;
    } else if (toks[0] == "Process" || toks[0] == "Parent Process") {
      // Use a regex to extract out the PID value
      const boost::regex e{"\\[\\d+\\]"};
      boost::smatch results;
      if (boost::regex_search(line, results, e)) {
        auto pid_str = std::string(results[0].first, results[0].second);
        auto pid = pid_str.substr(1, pid_str.size() - 2);
        r[kCrashDumpKeys.at(toks[0])] = pid;
      }
    } else if (toks[0] == "User ID") {
      r[kCrashDumpKeys.at(toks[0])] = toks[1];
    } else {
      // otherwise, process the line normally.
      r[kCrashDumpKeys.at(toks[0])] = toks[1];
    }
  }
}

QueryData genCrashLogs(QueryContext& context) {
  QueryData results;

  auto process_crash_logs = [&results](const fs::path& path,
                                       const std::string type) {
    std::vector<std::string> files;
    if (listFilesInDirectory(path, files)) {
      for (const auto& lf : files) {
        if (alg::ends_with(lf, ".crash") &&
            lf.find("LowBattery") == std::string::npos) {
          Row r;
          r["type"] = type;
          readCrashDump(lf, r);
          results.push_back(r);
        }
      }
    }
  };

  // Process system logs
  if (context.constraints["uid"].notExistsOrMatches("0")) {
    process_crash_logs(kDiagnosticReportsPath, "application");
  }

  // Process user logs
  auto users = usersFromContext(context);
  for (const auto& user : users) {
    auto user_home = fs::path(user.at("directory")) / kDiagnosticReportsPath;
    process_crash_logs(user_home, "application");

    // Process mobile crash logs
    auto user_mobile_root =
        fs::path(user.at("directory")) / kMobileDiagnosticReportsPath;
    std::vector<std::string> mobile_paths;
    if (listDirectoriesInDirectory(user_mobile_root, mobile_paths)) {
      for (const auto& mobile_device : mobile_paths) {
        process_crash_logs(mobile_device, "mobile");
      }
    }
  }

  return results;
}
}
}

max_stars_repo_name: Akhilpakanati/osquery

max_issues_repo_name: Akhilpakanati/osquery

max_forks_repo_name: Akhilpakanati/osquery


text:
/********************************************************************************
 *
 * This file is part of the Geneva library collection. The following license
 * applies to this file:
 *
 * ------------------------------------------------------------------------------
 * Licensed 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ------------------------------------------------------------------------------
 *
 * Note that other files in the Geneva library collection may use a different
 * license. Please see the licensing information in each file.
 *
 ********************************************************************************
 *
 * Geneva was started by Dr. Rüdiger Berlich and was later maintained together
 * with Dr. Ariel Garcia under the auspices of Gemfony scientific. For further
 * information on Gemfony scientific, see http://www.gemfomy.eu .
 *
 * The majority of files in Geneva was released under the Apache license v2.0
 * in February 2020.
 *
 * See the NOTICE file in the top-level directory of the Geneva library
 * collection for a list of contributors and copyright information.
 *
 ********************************************************************************/

#pragma once

// Global checks, defines and includes needed for all of Geneva
#include "common/GGlobalDefines.hpp"

// Standard header files go here
#include <sstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <type_traits>

// Boost header files go here

#include <boost/lexical_cast.hpp>
#include <boost/logic/tribool.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/assume_abstract.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/export.hpp>

// Geneva headers go here

#include "common/GExceptions.hpp"
#include "common/GCommonHelperFunctionsT.hpp"
#include "common/GLogger.hpp"
#include "common/GErrorStreamer.hpp"
#include "common/GExpectationChecksT.hpp"

// Forward declaration
class GEqualityPrinter;

namespace Gem {
namespace Common {

/******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/**
 * This class implements most important functions of the std::vector
 * class. It is intended to hold basic types or types that can treated
 * like simple types.
 */
template<typename T>
class GPODVectorT
{
    ///////////////////////////////////////////////////////////////////////
    friend class boost::serialization::access;

    template<typename Archive>
    void serialize(Archive &ar, const unsigned int) {
        using boost::serialization::make_nvp;

#if BOOST_VERSION <= 105800
        // Some preparation needed if this is a load operation.
		// This is needed to work around a problem in Boost 1.58
		if (Archive::is_loading::value) {
			data.clear();
		}
#endif

        ar & BOOST_SERIALIZATION_NVP(m_data_cnt);
    }
    ///////////////////////////////////////////////////////////////////////

    friend class GEqualityPrinter;

    static_assert(
        std::is_trivial<T>::value && std::is_standard_layout<T>::value
        , "T is no POD"
    );

public:
    /***************************************************************************/
    /**
     * Initialization with a number of items of defined value
     *
     * @param nval The number of items to be added to the collection
     * @param val  The value to be assigned to each position
     */
    GPODVectorT(const std::size_t &nval, const T &val)
        :m_data_cnt(nval, val)
    { /* nothing */ }

    /***************************************************************************/
    /**
     * The destructor -- purely virtual to make this an abstract base class
     */
    virtual ~GPODVectorT() BASE = 0;

    /***************************************************************************/
    /**
     * The default constructor
     */
    GPODVectorT() = default;
    GPODVectorT(GPODVectorT<T> const&) = default;
    GPODVectorT(GPODVectorT<T> &&) noexcept = default;

    GPODVectorT<T>& operator=(GPODVectorT<T> const&) = default;
    GPODVectorT<T>& operator=(GPODVectorT<T> &&) noexcept = default;

    /***************************************************************************/
    // Deleted comparison operators

    bool operator==(const GPODVectorT<T> &cp) const = delete;
    bool operator!=(const GPODVectorT<T> &cp) const = delete;
    bool operator==(const std::vector<T> &cp_data) const = delete;
    bool operator!=(const std::vector<T> &cp_data) const = delete;

    /***************************************************************************/
    /**
     * Searches for compliance with expectations with respect to another object
     * of the same type
     *
     * @param cp A constant reference to another GStdSimpleVectorInterfaceT object
     * @param e The expected outcome of the comparison
     * @param limit The maximum deviation for floating point values (important for similarity checks)
     */
    virtual void compare_base(
        const GPODVectorT<T> &cp, const Gem::Common::expectation &e, const double &limit
    ) const BASE {
        Gem::Common::GToken token(
            "GBaseEA::GEAOptimizationMonitor"
            , e
        );
        Gem::Common::compare_t(
            IDENTITY(this->m_data_cnt, cp.m_data_cnt)
            , token
        );
        token.evaluate();
    }

    /***************************************************************************/
    // Typedefs
    using value_type = typename std::vector<T>::value_type;
    using reference = typename std::vector<T>::reference;
    using const_reference = typename std::vector<T>::const_reference;

    using iterator = typename std::vector<T>::iterator;
    using const_iterator = typename std::vector<T>::const_iterator;
    using reverse_iterator = typename std::vector<T>::reverse_iterator;
    using const_reverse_iterator = typename std::vector<T>::const_reverse_iterator;

    using size_type = typename std::vector<T>::size_type;
    using difference_type = typename std::vector<T>::difference_type;

    /***************************************************************************/
    // Non modifying access
    size_type size() const { return m_data_cnt.size(); } // Used/tested in GDoubleCollection::fillWithData()
    bool empty() const { return m_data_cnt.empty(); } // Used/tested in GDoubleCollection::fillWithData()
    size_type max_size() const { return m_data_cnt.max_size(); } // Used/tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()

    size_type capacity() const { return m_data_cnt.capacity(); } // Used/tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
    void reserve(size_type amount) {
        m_data_cnt.reserve(amount);
    } // Used/tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()

    /***************************************************************************/
    /**
     * Counts the elements whose content is equal to item.
    *
     * @param item The item to be counted in the collection
     * @return The number of items found
     */
    size_type count(const T &item) const {
        return boost::numeric_cast<size_type>(
            std::count(
                m_data_cnt.begin()
                , m_data_cnt.end()
                , item
            ));
    }

    /* ----------------------------------------------------------------------------
     * Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
     * ----------------------------------------------------------------------------
     */

    /***************************************************************************/
    /**
     * Searches for item in the entire range of the vector.
     */
    const_iterator /* decltype(auto) */ find(const T &item) const {
        return std::find(
            m_data_cnt.begin()
            , m_data_cnt.end()
            , item
        );
    }

    /* ----------------------------------------------------------------------------
     * Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
     * ----------------------------------------------------------------------------
     */

    /***************************************************************************/

    // Modifying functions
    void swap(std::vector<T> &cont) {
        std::swap(
            m_data_cnt
            , cont
        );
    } // untested (likely irrelevant)

    // Access to elements (unchecked / checked)
    reference operator[](
        std::size_t pos
    ) { return m_data_cnt[pos]; } // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
    const_reference operator[](std::size_t pos) const { return m_data_cnt[pos]; }

    reference at(std::size_t pos) {
        return m_data_cnt.at(pos);
    } // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
    const_reference at(std::size_t pos) const { return m_data_cnt.at(pos); }

    reference front() { return m_data_cnt.front(); } // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
    const_reference front() const { return m_data_cnt.front(); }

    reference back() { return m_data_cnt.back(); } // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
    const_reference back() const { return m_data_cnt.back(); }

    // Iterators
    iterator begin() { return m_data_cnt.begin(); }

    const_iterator begin() const { return m_data_cnt.begin(); } // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()

    iterator end() { return m_data_cnt.end(); } // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
    const_iterator end() const { return m_data_cnt.end(); }

    reverse_iterator rbegin() { return m_data_cnt.rbegin(); } // untested (likely irrelevant)
    const_reverse_iterator rbegin() const { return m_data_cnt.rbegin(); }

    reverse_iterator rend() { return m_data_cnt.rend(); } // untested (likely irrelevant)
    const_reverse_iterator rend() const { return m_data_cnt.rend(); }

    /***************************************************************************/
    // Insertion and removal

    /**
     * Inserts a given item at position pos. Checks whether the item actually points
     * somewhere.
     */
    iterator insert(iterator pos, const T &item) {
        return m_data_cnt.insert(
            pos
            , item
        );
    }

    /* ----------------------------------------------------------------------------
     * Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
     * ----------------------------------------------------------------------------
     */

    /***************************************************************************/
    /**
     * Inserts a given amount of items after position pos.
     */
    void insert(iterator pos, size_type amount, const T &item) {
        m_data_cnt.insert(
            pos
            , amount
            , item
        );
    }

    /* ----------------------------------------------------------------------------
     * Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
     * ----------------------------------------------------------------------------
     */

    /***************************************************************************/
    // Adding simple items to the  back of the vector
    void push_back(const T &item) { m_data_cnt.push_back(item); } // Used/tested in GDoubleCollection::fillWithData()

    /***************************************************************************/

    // Removal at a given position or in a range
    iterator erase(iterator pos) {
        return m_data_cnt.erase(pos);
    } // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
    iterator erase(iterator from, iterator to) {
        return m_data_cnt.erase(
            from
            , to
        );
    } // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()

    // Removing an element from the end of the vector
    void pop_back() { m_data_cnt.pop_back(); } // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()

    /***************************************************************************/
    /**
     * Resizing the vector, initialization with item. This function does nothing
     * if amount is the same as data.size(). We assume in this function that
     * T is copy-constructible.
     *
     * @param amount The new desired size of the vector
     * @param item An item that should be used for initialization of new items, if any
     */
    void resize(size_type amount, const T &item) {
        m_data_cnt.resize(
            amount
            , item
        );
    } // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()

    /***************************************************************************/
    /**
     * Resize the vector without "template" items. This essentially means that
     * T will be default-constructed. For numeric values this will usually mean
     * T(0).
     */
    void resize(size_type amount) { m_data_cnt.resize(amount); }

    /***************************************************************************/
    /** @brief Clearing the data vector */
    void clear() { m_data_cnt.clear(); } // Used/tested in GDoubleCollection::fillWithData()

    /***************************************************************************/
    /**
     * Assignment of a std::vector<T>
     *
     * @param cp A constant reference to another std::vector<T>
     * @return The argument of this function (a std::vector<T>)
     */
    GPODVectorT& operator=(const std::vector<T> &cp) {
        m_data_cnt = cp;
        return *this;
    }

    /* ----------------------------------------------------------------------------
     * Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()
     * ----------------------------------------------------------------------------
     */

    /***************************************************************************/
    /**
     * Creates a copy of the data vector. It is assumed that cp is empty or that
     * all data in it can be deleted.
     *
     * @param cp A reference to a vector that will hold a copy of our local data vector
     */
    void getDataCopy(
        std::vector<T> &cp
    ) const { cp = m_data_cnt; }  // Tested in GDoubleCollection::specificTestsNoFailureExpected_GUnitTests()

    /***************************************************************************/
    /**
     * Performs a cross-over operation at a given position. Note: We do NOT require
     * the two vectors to be of the same size
     *
     * @param cp A copy of another GStdSimpleVectorInterfaceT<T> object
     * @param pos The position as of which the cross-over should be performed
     */
    void crossOver(GPODVectorT<T> &cp, const std::size_t &pos) {
        // Find out the minimum size of both vectors
        std::size_t minSize = (std::min)(
            this->size()
            , cp.size());

#ifdef DEBUG
        // Do some error checking
        if (pos >= minSize) {
            throw gemfony_exception(
                g_error_streamer(
                    DO_LOG
                    , time_and_place
                )
                    << "In GPODVectorT::crossOver(cp,pos): Error!" << std::endl
                    << "Invalid position " << pos << " / " << this->size() << " / " << cp.size() << std::endl
            );
        }
#endif /* DEBUG */

        // Swap the elements
        for (std::size_t i = pos; i < minSize; i++) {
            std::swap(
                this->at(i)
                , cp.at(i));
        }

        // Move the elements of the longer vector over to the other
        // and remove the elements from the other vector
        if (this->size() > cp.size()) {
            // Attach elements to the other vector
            for (std::size_t i = cp.size(); i < this->size(); i++) {
                cp.push_back(this->at(i));
            }

            // Remove the surplus elements from this vector
            this->erase(
                this->begin() + minSize
                , this->end());
        } else if (cp.size() > this->size()) {
            // Attach elements to the other vector
            for (std::size_t i = this->size(); i < cp.size(); i++) {
                this->push_back(cp.at(i));
            }

            // Remove the surplus elements from this vector
            cp.erase(
                cp.begin() + minSize
                , cp.end());
        }

        // Nothing to do if both vectors have the same size
    }

protected:
    /** @brief Applies modifications to this object. This is needed for testing purposes */
    virtual bool modify_GUnitTests_() BASE { /* nothing here yet */ return false; }
    /** @brief Performs self tests that are expected to succeed. This is needed for testing purposes */
    virtual void specificTestsNoFailureExpected_GUnitTests_() BASE { /* nothing here yet */ }
    /** @brief Performs self tests that are expected to fail. This is needed for testing purposes */
    virtual void specificTestsFailuresExpected_GUnitTests_() BASE { /* nothing here yet */  }

    std::vector<T> m_data_cnt;
};

/******************************************************************************/
/**
 * The destructor -- purely virtual to make this an abstract base class
 */
template<typename T>
inline GPODVectorT<T>::~GPODVectorT() {
    m_data_cnt.clear();
}

/******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/

} /* namespace Common */
} /* namespace Gem */

/******************************************************************************/
/**
 * @brief The content of the BOOST_SERIALIZATION_ASSUME_ABSTRACT(T) macro. Needed for Boost.Serialization
 */
namespace boost {
namespace serialization {

template<typename T>
struct is_abstract<Gem::Common::GPODVectorT<T>> :
    public boost::true_type
{ /* nothing */ };
template<typename T>
struct is_abstract<const Gem::Common::GPODVectorT<T>> :
    public boost::true_type
{ /* nothing */ };

} /* namespace serialization */
} /* namespace boost */

/******************************************************************************/

ext: hpp

max_stars_repo_name: denisbertini/geneva

max_issues_repo_name: denisbertini/geneva

max_forks_repo_name: denisbertini/geneva


text:
/** bidswitch_filters_test.cc                                 -*- C++ -*-
    JS Bejeau, 10 Jul 2014
    Copyright (c) 2013 Datacratic.  All rights reserved.

    Tests for the bidswitch filters.

    Note that these tests assume that the generic filters work properly so we
    don't waste time constructing complicated set of include/exclude statements.
 */

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include "rtbkit/core/router/filters/testing/utils.h"
#include "rtbkit/core/router/filters/static_filters.h"
#include "rtbkit/core/agent_configuration/agent_config.h"
#include "rtbkit/common/bid_request.h"
#include "rtbkit/common/exchange_connector.h"
#include "jml/utils/vector_utils.h"

#include "rtbkit/plugins/exchange/bidswitch_exchange_connector.h"

#include <boost/test/unit_test.hpp>

using namespace std;
using namespace ML;
using namespace Datacratic;

/** Simple test to check that all a config will fail if one of its segment
    fails. Nothing to interesting really.
 */
BOOST_AUTO_TEST_CASE( bidswitch_wseat_filter )
{
    BidSwitchWSeatFilter filter;
    CreativeMatrix creatives;

    // AgentConfigs
    auto doAgentConfigInit = [&] (AgentConfig & ac, const std::string & providerConfigStr) {
        ac.creatives.push_back(Creative());
        ac.providerConfig = Json::parse(providerConfigStr);
    };

    AgentConfig c0, c1, c2;
    doAgentConfigInit(c0, "{ \"bidswitch\": { \"seat\": \"123\" }}");
    doAgentConfigInit(c1, "{ \"bidswitch\": { \"seat\": \"1\" }}");
    doAgentConfigInit(c2, "{}");

    auto doBidRequestInit = [&] (BidRequest & br, const std::vector<string> & wseat) {
        // add at least one Impression
        addImp(br, OpenRTB::AdPosition::ABOVE, "{\"flight_ids\": [1200] }");
        br.segments.addStrings("openrtb-wseat", wseat );

    };

    // BidRequests
    BidRequest r0, r1, r2, r3;
    doBidRequestInit(r0, { "aaa",  "1" } );
    doBidRequestInit(r1, { "123", "aaa" } );
    doBidRequestInit(r2, { "bbb", "aaa" });
    doBidRequestInit(r3, { "1", "123" });

    // Test 1
    title("Bidswtich-wseat-1");
    addConfig(filter, 0, c0, creatives);
    addConfig(filter, 1, c1, creatives);

    check(filter, r0, creatives, 0, { {1}  });
    check(filter, r1, creatives, 0, { {0}  });
    check(filter, r2, creatives, 0, { {}  });
    check(filter, r3, creatives, 0, { {0,1}  });

    removeConfig(filter, 0, c0, creatives);
    removeConfig(filter, 1, c1, creatives);

    // Test 2
    title("Bidswtich-wseat-2");
    addConfig(filter, 0, c2, creatives);
    check(filter, r0, creatives, 0, { {0}  });
    check(filter, r1, creatives, 0, { {0}  });
    check(filter, r2, creatives, 0, { {0}  });
    check(filter, r3, creatives, 0, { {0}  });

}

ext: cc


text:
#include <boost/fusion/include/deque.hpp>
#include <boost/fusion/include/make_deque.hpp>
#include <boost/fusion/sequence/intrinsic/at_c.hpp>

#define ZI_TUPLE      boost::fusion::deque
#define ZI_MAKE_TUPLE boost::fusion::make_deque
#define ZI_TUPLE_GET(n) boost::fusion::at_c<n>

#include "detail/zip_iterator_test_original.ipp"