<commit_before>/***************************************************************************
 *   Copyright (c) 2011 Juergen Riegel <FreeCAD@juergen-riegel.net>        *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <Standard_Failure.hxx>
# include <TopoDS_Solid.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS.hxx>
# include <BRep_Tool.hxx>
# include <gp_Pnt.hxx>
# include <gp_Pln.hxx>
# include <BRepBuilderAPI_MakeFace.hxx>
#endif

#include <Base/Exception.h>
#include "App/Document.h"
#include "App/Plane.h"
#include <App/Line.h>
#include "Body.h"
#include "Feature.h"
#include "Mod/Part/App/DatumFeature.h"

#include <Base/Console.h>

namespace PartDesign {

PROPERTY_SOURCE(PartDesign::Feature,Part::Feature)

Feature::Feature()
{
    ADD_PROPERTY(BaseFeature,(0));
    Placement.StatusBits.set(2, true);
}

short Feature::mustExecute() const
{
    if (BaseFeature.isTouched())
        return 1;
    return Part::Feature::mustExecute();
}

TopoDS_Shape Feature::getSolid(const TopoDS_Shape& shape)
{
    if (shape.IsNull())
        Standard_Failure::Raise("Shape is null");
    TopExp_Explorer xp;
    xp.Init(shape,TopAbs_SOLID);
    for (;xp.More(); xp.Next()) {
        return xp.Current();
    }

    return TopoDS_Shape();
}

const gp_Pnt Feature::getPointFromFace(const TopoDS_Face& f)
{
    if (!f.Infinite()) {
        TopExp_Explorer exp;
        exp.Init(f, TopAbs_VERTEX);
        if (exp.More())
            return BRep_Tool::Pnt(TopoDS::Vertex(exp.Current()));
        // Else try the other method
    }

    // TODO: Other method, e.g. intersect X,Y,Z axis with the (unlimited?) face?
    // Or get a "corner" point if the face is limited?
    throw Base::Exception("getPointFromFace(): Not implemented yet for this case");
}

const Part::Feature* Feature::getBaseObject() const {
    App::DocumentObject* BaseLink = BaseFeature.getValue();
    if (BaseLink == NULL) throw Base::Exception("Base property not set");
    Part::Feature* BaseObject = NULL;
    if (BaseLink->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
        BaseObject = static_cast<Part::Feature*>(BaseLink);

    if (BaseObject == NULL)
        throw Base::Exception("No base feature linked");

    return BaseObject;
}

const TopoDS_Shape& Feature::getBaseShape() const {
    const Part::Feature* BaseObject = getBaseObject();

    const TopoDS_Shape& result = BaseObject->Shape.getValue();
    if (result.IsNull())
        throw Base::Exception("Base feature's shape is invalid");
    TopExp_Explorer xp (result, TopAbs_SOLID);
    if (!xp.More())
        throw Base::Exception("Base feature's shape is not a solid");

    return result;
}

const Part::TopoShape Feature::getBaseTopoShape() const {
    const Part::Feature* BaseObject = getBaseObject();

    const Part::TopoShape& result = BaseObject->Shape.getShape();
    if (result._Shape.IsNull())
        throw Base::Exception("Base feature's TopoShape is invalid");

    return result;
}

bool Feature::isDatum(const App::DocumentObject* feature)
{
    return feature->getTypeId().isDerivedFrom(App::Plane::getClassTypeId()) ||
           feature->getTypeId().isDerivedFrom(App::Line::getClassTypeId()) ||
           feature->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId());
}

gp_Pln Feature::makePlnFromPlane(const App::DocumentObject* obj)
{
    const App::Plane* plane = static_cast<const App::Plane*>(obj);
    if (plane == NULL)
        throw Base::Exception("Feature: Null object");

    Base::Rotation rot = plane->Placement.getValue().getRotation();
    Base::Vector3d normal(0,0,1);
    rot.multVec(normal, normal);
    return gp_Pln(gp_Pnt(0,0,0), gp_Dir(normal.x,normal.y,normal.z));
}

TopoDS_Shape Feature::makeShapeFromPlane(const App::DocumentObject* obj)
{
    BRepBuilderAPI_MakeFace builder(makePlnFromPlane(obj));
    if (!builder.IsDone())
        throw Base::Exception("Feature: Could not create shape from base plane");

    return builder.Shape();
}

}
<commit_msg>don't show placement for part design features<commit_after>/***************************************************************************
 *   Copyright (c) 2011 Juergen Riegel <FreeCAD@juergen-riegel.net>        *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <Standard_Failure.hxx>
# include <TopoDS_Solid.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS.hxx>
# include <BRep_Tool.hxx>
# include <gp_Pnt.hxx>
# include <gp_Pln.hxx>
# include <BRepBuilderAPI_MakeFace.hxx>
#endif

#include <Base/Exception.h>
#include "App/Document.h"
#include "App/Plane.h"
#include <App/Line.h>
#include "Body.h"
#include "Feature.h"
#include "Mod/Part/App/DatumFeature.h"

#include <Base/Console.h>

namespace PartDesign {

PROPERTY_SOURCE(PartDesign::Feature,Part::Feature)

Feature::Feature()
{
    ADD_PROPERTY(BaseFeature,(0));
    Placement.StatusBits.set(3, true);
}

short Feature::mustExecute() const
{
    if (BaseFeature.isTouched())
        return 1;
    return Part::Feature::mustExecute();
}

TopoDS_Shape Feature::getSolid(const TopoDS_Shape& shape)
{
    if (shape.IsNull())
        Standard_Failure::Raise("Shape is null");
    TopExp_Explorer xp;
    xp.Init(shape,TopAbs_SOLID);
    for (;xp.More(); xp.Next()) {
        return xp.Current();
    }

    return TopoDS_Shape();
}

const gp_Pnt Feature::getPointFromFace(const TopoDS_Face& f)
{
    if (!f.Infinite()) {
        TopExp_Explorer exp;
        exp.Init(f, TopAbs_VERTEX);
        if (exp.More())
            return BRep_Tool::Pnt(TopoDS::Vertex(exp.Current()));
        // Else try the other method
    }

    // TODO: Other method, e.g. intersect X,Y,Z axis with the (unlimited?) face?
    // Or get a "corner" point if the face is limited?
    throw Base::Exception("getPointFromFace(): Not implemented yet for this case");
}

const Part::Feature* Feature::getBaseObject() const {
    App::DocumentObject* BaseLink = BaseFeature.getValue();
    if (BaseLink == NULL) throw Base::Exception("Base property not set");
    Part::Feature* BaseObject = NULL;
    if (BaseLink->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
        BaseObject = static_cast<Part::Feature*>(BaseLink);

    if (BaseObject == NULL)
        throw Base::Exception("No base feature linked");

    return BaseObject;
}

const TopoDS_Shape& Feature::getBaseShape() const {
    const Part::Feature* BaseObject = getBaseObject();

    const TopoDS_Shape& result = BaseObject->Shape.getValue();
    if (result.IsNull())
        throw Base::Exception("Base feature's shape is invalid");
    TopExp_Explorer xp (result, TopAbs_SOLID);
    if (!xp.More())
        throw Base::Exception("Base feature's shape is not a solid");

    return result;
}

const Part::TopoShape Feature::getBaseTopoShape() const {
    const Part::Feature* BaseObject = getBaseObject();

    const Part::TopoShape& result = BaseObject->Shape.getShape();
    if (result._Shape.IsNull())
        throw Base::Exception("Base feature's TopoShape is invalid");

    return result;
}

bool Feature::isDatum(const App::DocumentObject* feature)
{
    return feature->getTypeId().isDerivedFrom(App::Plane::getClassTypeId()) ||
           feature->getTypeId().isDerivedFrom(App::Line::getClassTypeId()) ||
           feature->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId());
}

gp_Pln Feature::makePlnFromPlane(const App::DocumentObject* obj)
{
    const App::Plane* plane = static_cast<const App::Plane*>(obj);
    if (plane == NULL)
        throw Base::Exception("Feature: Null object");

    Base::Rotation rot = plane->Placement.getValue().getRotation();
    Base::Vector3d normal(0,0,1);
    rot.multVec(normal, normal);
    return gp_Pln(gp_Pnt(0,0,0), gp_Dir(normal.x,normal.y,normal.z));
}

TopoDS_Shape Feature::makeShapeFromPlane(const App::DocumentObject* obj)
{
    BRepBuilderAPI_MakeFace builder(makePlnFromPlane(obj));
    if (!builder.IsDone())
        throw Base::Exception("Feature: Could not create shape from base plane");

    return builder.Shape();
}

}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/common/utils/imageProcs/common_ringId.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#ifndef _COMMON_RINGID_H_
#define _COMMON_RINGID_H_

#include <stdint.h>
#include <stddef.h>

////////////////////////////////////////////////////////////////////////////////
// Declare assumptions - Begin
//

// Various data type defs for enums. Serves following purposes:
// - Reduces space since enum defaults to an int type.
// - Enables using these types without the scope operator for
//   those enums that are namespaced, e.g. RingID.
// NB! DO NOT CHANGE THESE DEFS W/O EXPLICIT CONSENT FROM
//     INFRASTRUCT TEAM. (These defs affect packing assumptions
//     of ring structures that go into the image ringSections.)
typedef uint16_t  RingId_t;         // Type for RingID enum
typedef uint8_t   ChipletType_t;    // Type for CHIPLET_TYPE enum
typedef uint8_t   PpeType_t;        // Type for PpeType
typedef uint8_t   ChipType_t;       // Type for ChipType enum
typedef uint8_t   RingType_t;       // Type for RingType enum
typedef uint8_t   RingVariant_t;    // Type for RingVariant enum
typedef uint32_t  TorCpltOffset_t;  // Type for offset value to chiplet's CMN or INST section

#define  UNDEFINED_RING_ID      (RingId_t)0xffff
#define  INVALID_RING_TYPE      (RingType_t)0xff
#define  INVALID_CHIPLET_TYPE   (ChipletType_t)0xff
#define  UNDEFINED_CHIP_TYPE    (ChipType_t)0xff
#define  MAX_TOR_RING_OFFSET    (uint16_t)(256*256-1) // Max val of uint16
#define  MAX_RING_NAME_LENGTH   (uint8_t)50
#define  UNDEFINED_DD_LEVEL     (uint8_t)0xff

//
// Declare assumptions - End
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// TOR layout definitions - Begin
//

//
// TOR header field (appears in top of every HW, SBE, CEN, OVRD, etc ring section)
//
typedef struct
{
    uint32_t   magic;
    uint8_t    version;
    ChipType_t chipType;    // Value from ChipType enum
    uint8_t    ddLevel;     // =0xff if MAGIC_HW, >0 all other MAGICs
    uint8_t    numDdLevels; // >0 if MAGIC_HW, =1 all other MAGICs
    uint32_t   size;        // Size of the TOR ringSection.
} TorHeader_t;

//
// Subsequent TOR fields (listed in order they appear in TOR ringSections)
//
typedef struct
{
    uint32_t offset;
    uint32_t size;
    uint8_t  ddLevel;
    uint8_t  reserved[3];
} TorDdBlock_t;

typedef struct
{
    uint32_t offset;
    uint32_t size;
} TorPpeBlock_t;

typedef struct
{
    TorCpltOffset_t cmnOffset;
    TorCpltOffset_t instOffset;
} TorCpltBlock_t;

typedef uint16_t TorRingOffset_t;  // Offset value to actual ring

//
// TOR layout definitions - End
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// Key TOR constants - Begin
//

#define  TOR_VERSION  4

// TOR Magic values for top-level TOR ringSection and sub-ringSections
enum TorMagicNum
{
    TOR_MAGIC       = (uint32_t)0x544F52  ,   // "TOR"
    TOR_MAGIC_HW    = (uint32_t)0x544F5248,   // "TORH"
    TOR_MAGIC_SBE   = (uint32_t)0x544F5242,   // "TORB"
    TOR_MAGIC_SGPE  = (uint32_t)0x544F5247,   // "TORG"
    TOR_MAGIC_CME   = (uint32_t)0x544F524D,   // "TORM"
    TOR_MAGIC_OVRD  = (uint32_t)0x544F5252,   // "TORR"
    TOR_MAGIC_OVLY  = (uint32_t)0x544F524C,   // "TORL"
    TOR_MAGIC_CEN   = (uint32_t)0x544F524E,   // "TORN"
};

//
// Key TOR constants - End
///////////////////////////////////////////////////////////////////////////////

//
// Chip types and List to represent p9n, p9c, p9a, cen (centaur)
// NB! There's a matching CHIP_TYPE_LIST definition in common_ringId.C
//
enum ChipType
{
    CT_P9N,  // ==P9 for now
    CT_P9C,  // ==P9 for now
    CT_P9A,
    CT_CEN,
    NUM_CHIP_TYPES
};

typedef struct
{
    const char*  name;
    ChipType_t   type;
} ChipTypeList_t;

static const ChipTypeList_t CHIP_TYPE_LIST[] =
{
    {"p9n", CT_P9N},
    {"p9c", CT_P9C},
    {"p9a", CT_P9A},
    {"cen", CT_CEN},
};

//
// Ring related data structs and types
//
typedef enum RingClass
{
    EKB_RING,
    EKB_FSM_RING,
    EKB_STUMPED_RING,
    EKB_CMSK_RING,
    EKB_NONFLUSH_RING,
    VPD_RING,
    CEN_RING,
    NUM_RING_CLASSES
} RingClass_t;

//
// General Ring ID list structure
//
typedef struct
{
    const char*  ringName;
    RingId_t     ringId;
    uint8_t      instanceIdMin;
    uint8_t      instanceIdMax;
    RingClass_t  ringClass;
    uint32_t     scanScomAddress;
} GenRingIdList;

// PPE types supported. Note that this enum also reflects the
//   order with which they appear in the HW image's .rings section.
enum PpeType
{
    PT_SBE           = 0x00,
    PT_CME           = 0x01,
    PT_SGPE          = 0x02,
    NUM_PPE_TYPES = 0x03
};

// Do  NOT  make changes to the values or order of this enum. Some user
// codes, like xip_tool, make assumptions about range and order.
enum RingVariant
{
    BASE     = 0x00,
    CC       = 0x01,
    RL       = 0x02,
    OVERRIDE = 0x03,
    OVERLAY  = 0x04,
    NUM_RING_VARIANTS = 0x05,
    NOT_VALID = 0xff
};

extern const char* ppeTypeName[];
extern const char* ringVariantName[];

typedef struct
{
    RingVariant_t  variant[3];
} RingVariantOrder;

enum RingType
{
    COMMON_RING = 0,
    INSTANCE_RING = 1,
    ALLRING = 2
};

typedef struct
{
    // This is the chiplet-ID of the first instance of the Chiplet
    uint8_t iv_base_chiplet_number;

    // The no.of common rings for the Chiplet
    uint8_t iv_num_common_rings;

    // The no.of instance rings for the Chiplet (w/different ringId values)
    uint8_t iv_num_instance_rings;

    // The no.of instance rings for the Chiplet (w/different ringId values
    // AND different scanAddress values)
    uint8_t iv_num_instance_rings_scan_addrs;

    // The no.of ring variants
    uint8_t iv_num_ring_variants;
} ChipletData_t;

// This is used to Set (Mark) the left-most bit
#define  INSTANCE_RING_MARK  (uint8_t)0x80
//
// This is used to Set (Mark) the left-most bit
#define  INSTANCE_RING_MASK  (uint8_t)0x7F

// This is used to mark an invalid ring in the ring properties list
#define INVALID_RING_OFFSET  (uint8_t)0xFF

// This structure is needed for mapping a RingID to it's corresponding name.
// The names will be used by the build scripts when generating the TOR.
typedef struct
{
    uint8_t       iv_torOffSet;
#ifndef __PPE__
    char          iv_name[50];
#endif
    ChipletType_t iv_type;
} RingProperties_t;

//
// Universal infrastructure error codes
//
#define INFRASTRUCT_RC_SUCCESS                0
#define INFRASTRUCT_RC_FAILURE                1
#define INFRASTRUCT_RC_CODE_BUG               2
#define INFRASTRUCT_RC_USER_ERROR             3
#define INFRASTRUCT_RC_NOOF_CODES             5 // Do not use as RC code
//
// TOR specific error codes
//
#define TOR_SUCCESS                           INFRASTRUCT_RC_SUCCESS
#define TOR_FAILURE                           INFRASTRUCT_RC_FAILURE
#define TOR_CODE_BUG                          INFRASTRUCT_RC_CODE_BUG
#define TOR_USER_ERROR                        INFRASTRUCT_RC_USER_ERROR
#define TOR_INVALID_MAGIC_NUMBER              INFRASTRUCT_RC_NOOF_CODES + 1
#define TOR_INVALID_CHIPTYPE                  INFRASTRUCT_RC_NOOF_CODES + 3
#define TOR_INVALID_CHIPLET                   INFRASTRUCT_RC_NOOF_CODES + 4
#define TOR_INVALID_VARIANT                   INFRASTRUCT_RC_NOOF_CODES + 5
#define TOR_INVALID_RING_ID                   INFRASTRUCT_RC_NOOF_CODES + 6
#define TOR_INVALID_INSTANCE_ID               INFRASTRUCT_RC_NOOF_CODES + 7
#define TOR_INVALID_RING_BLOCK_TYPE           INFRASTRUCT_RC_NOOF_CODES + 8
#define TOR_UNSUPPORTED_RING_SECTION          INFRASTRUCT_RC_NOOF_CODES + 9
#define TOR_RING_NOT_FOUND                    INFRASTRUCT_RC_NOOF_CODES + 10
#define TOR_AMBIGUOUS_API_PARMS               INFRASTRUCT_RC_NOOF_CODES + 11
#define TOR_SECTION_NOT_FOUND                 INFRASTRUCT_RC_NOOF_CODES + 12
#define TOR_DD_LEVEL_NOT_FOUND                INFRASTRUCT_RC_NOOF_CODES + 13
#define TOR_OP_BUFFER_INVALID                 INFRASTRUCT_RC_NOOF_CODES + 14
#define TOR_OP_BUFFER_SIZE_EXCEEDED           INFRASTRUCT_RC_NOOF_CODES + 15
#define TOR_IMAGE_DOES_NOT_SUPPORT_CME        INFRASTRUCT_RC_NOOF_CODES + 16
#define TOR_IMAGE_DOES_NOT_SUPPORT_SGPE       INFRASTRUCT_RC_NOOF_CODES + 17
#define TOR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL   INFRASTRUCT_RC_NOOF_CODES + 18
#define TOR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL  INFRASTRUCT_RC_NOOF_CODES + 19
#define TOR_RING_AVAILABLE_IN_RINGSECTION     INFRASTRUCT_RC_NOOF_CODES + 20
#define TOR_BUFFER_TOO_SMALL                  INFRASTRUCT_RC_NOOF_CODES + 21
#define TOR_TOO_MANY_DD_LEVELS                INFRASTRUCT_RC_NOOF_CODES + 22
#define TOR_OFFSET_TOO_BIG                    INFRASTRUCT_RC_NOOF_CODES + 23

int ringid_get_noof_chiplets( ChipType_t  i_chipType,
                              uint32_t    i_torMagic,
                              uint8_t*    o_numChiplets );

int ringid_get_properties( ChipType_t         i_chipType,
                           uint32_t           i_torMagic,
                           ChipletType_t      i_chiplet,
                           ChipletData_t**    o_chipletData,
                           GenRingIdList**    o_ringIdListCommon,
                           GenRingIdList**    o_ringIdListInstance,
                           RingVariantOrder** o_ringVariantOrder,
                           RingProperties_t** o_ringProps,
                           uint8_t*           o_numVariants );

#endif  // _COMMON_RINGID_H_
<commit_msg>Revert "Adding p9a support."<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/common/utils/imageProcs/common_ringId.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#ifndef _COMMON_RINGID_H_
#define _COMMON_RINGID_H_

#include <stdint.h>
#include <stddef.h>

////////////////////////////////////////////////////////////////////////////////
// Declare assumptions - Begin
//

// Various data type defs for enums. Serves following purposes:
// - Reduces space since enum defaults to an int type.
// - Enables using these types without the scope operator for
//   those enums that are namespaced, e.g. RingID.
// NB! DO NOT CHANGE THESE DEFS W/O EXPLICIT CONSENT FROM
//     INFRASTRUCT TEAM. (These defs affect packing assumptions
//     of ring structures that go into the image ringSections.)
typedef uint16_t  RingId_t;         // Type for RingID enum
typedef uint8_t   ChipletType_t;    // Type for CHIPLET_TYPE enum
typedef uint8_t   PpeType_t;        // Type for PpeType
typedef uint8_t   ChipType_t;       // Type for ChipType enum
typedef uint8_t   RingType_t;       // Type for RingType enum
typedef uint8_t   RingVariant_t;    // Type for RingVariant enum
typedef uint32_t  TorCpltOffset_t;  // Type for offset value to chiplet's CMN or INST section

#define  UNDEFINED_RING_ID      (RingId_t)0xffff
#define  INVALID_RING_TYPE      (RingType_t)0xff
#define  INVALID_CHIPLET_TYPE   (ChipletType_t)0xff
#define  UNDEFINED_CHIP_TYPE    (ChipType_t)0xff
#define  MAX_TOR_RING_OFFSET    (uint16_t)(256*256-1) // Max val of uint16
#define  MAX_RING_NAME_LENGTH   (uint8_t)50
#define  UNDEFINED_DD_LEVEL     (uint8_t)0xff

//
// Declare assumptions - End
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// TOR layout definitions - Begin
//

//
// TOR header field (appears in top of every HW, SBE, CEN, OVRD, etc ring section)
//
typedef struct
{
    uint32_t   magic;
    uint8_t    version;
    ChipType_t chipType;    // Value from ChipType enum
    uint8_t    ddLevel;     // =0xff if MAGIC_HW, >0 all other MAGICs
    uint8_t    numDdLevels; // >0 if MAGIC_HW, =1 all other MAGICs
    uint32_t   size;        // Size of the TOR ringSection.
} TorHeader_t;

//
// Subsequent TOR fields (listed in order they appear in TOR ringSections)
//
typedef struct
{
    uint32_t offset;
    uint32_t size;
    uint8_t  ddLevel;
    uint8_t  reserved[3];
} TorDdBlock_t;

typedef struct
{
    uint32_t offset;
    uint32_t size;
} TorPpeBlock_t;

typedef struct
{
    TorCpltOffset_t cmnOffset;
    TorCpltOffset_t instOffset;
} TorCpltBlock_t;

typedef uint16_t TorRingOffset_t;  // Offset value to actual ring

//
// TOR layout definitions - End
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// Key TOR constants - Begin
//

#define  TOR_VERSION  4

// TOR Magic values for top-level TOR ringSection and sub-ringSections
enum TorMagicNum
{
    TOR_MAGIC       = (uint32_t)0x544F52  ,   // "TOR"
    TOR_MAGIC_HW    = (uint32_t)0x544F5248,   // "TORH"
    TOR_MAGIC_SBE   = (uint32_t)0x544F5242,   // "TORB"
    TOR_MAGIC_SGPE  = (uint32_t)0x544F5247,   // "TORG"
    TOR_MAGIC_CME   = (uint32_t)0x544F524D,   // "TORM"
    TOR_MAGIC_OVRD  = (uint32_t)0x544F5252,   // "TORR"
    TOR_MAGIC_OVLY  = (uint32_t)0x544F524C,   // "TORL"
    TOR_MAGIC_CEN   = (uint32_t)0x544F524E,   // "TORN"
};

//
// Key TOR constants - End
///////////////////////////////////////////////////////////////////////////////

//
// Chip types and List to represent p9n, p9c, cen (centaur)
// NB! There's a matching CHIP_TYPE_LIST definition in common_ringId.C
//
enum ChipType
{
    CT_P9N,  // ==P9 for now
    CT_P9C,  // ==P9 for now
    CT_CEN,
    NUM_CHIP_TYPES
};

typedef struct
{
    const char*  name;
    ChipType_t   type;
} ChipTypeList_t;

static const ChipTypeList_t CHIP_TYPE_LIST[] =
{
    {"p9n", CT_P9N},
    {"p9c", CT_P9C},
    {"cen", CT_CEN},
};

//
// Ring related data structs and types
//
typedef enum RingClass
{
    EKB_RING,
    EKB_FSM_RING,
    EKB_STUMPED_RING,
    EKB_CMSK_RING,
    EKB_NONFLUSH_RING,
    VPD_RING,
    CEN_RING,
    NUM_RING_CLASSES
} RingClass_t;

//
// General Ring ID list structure
//
typedef struct
{
    const char*  ringName;
    RingId_t     ringId;
    uint8_t      instanceIdMin;
    uint8_t      instanceIdMax;
    RingClass_t  ringClass;
    uint32_t     scanScomAddress;
} GenRingIdList;

// PPE types supported. Note that this enum also reflects the
//   order with which they appear in the HW image's .rings section.
enum PpeType
{
    PT_SBE           = 0x00,
    PT_CME           = 0x01,
    PT_SGPE          = 0x02,
    NUM_PPE_TYPES = 0x03
};

// Do  NOT  make changes to the values or order of this enum. Some user
// codes, like xip_tool, make assumptions about range and order.
enum RingVariant
{
    BASE     = 0x00,
    CC       = 0x01,
    RL       = 0x02,
    OVERRIDE = 0x03,
    OVERLAY  = 0x04,
    NUM_RING_VARIANTS = 0x05,
    NOT_VALID = 0xff
};

extern const char* ppeTypeName[];
extern const char* ringVariantName[];

typedef struct
{
    RingVariant_t  variant[3];
} RingVariantOrder;

enum RingType
{
    COMMON_RING = 0,
    INSTANCE_RING = 1,
    ALLRING = 2
};

typedef struct
{
    // This is the chiplet-ID of the first instance of the Chiplet
    uint8_t iv_base_chiplet_number;

    // The no.of common rings for the Chiplet
    uint8_t iv_num_common_rings;

    // The no.of instance rings for the Chiplet (w/different ringId values)
    uint8_t iv_num_instance_rings;

    // The no.of instance rings for the Chiplet (w/different ringId values
    // AND different scanAddress values)
    uint8_t iv_num_instance_rings_scan_addrs;

    // The no.of ring variants
    uint8_t iv_num_ring_variants;
} ChipletData_t;

// This is used to Set (Mark) the left-most bit
#define  INSTANCE_RING_MARK  (uint8_t)0x80
//
// This is used to Set (Mark) the left-most bit
#define  INSTANCE_RING_MASK  (uint8_t)0x7F

// This is used to mark an invalid ring in the ring properties list
#define INVALID_RING_OFFSET  (uint8_t)0xFF

// This structure is needed for mapping a RingID to it's corresponding name.
// The names will be used by the build scripts when generating the TOR.
typedef struct
{
    uint8_t       iv_torOffSet;
#ifndef __PPE__
    char          iv_name[50];
#endif
    ChipletType_t iv_type;
} RingProperties_t;

//
// Universal infrastructure error codes
//
#define INFRASTRUCT_RC_SUCCESS                0
#define INFRASTRUCT_RC_FAILURE                1
#define INFRASTRUCT_RC_CODE_BUG               2
#define INFRASTRUCT_RC_USER_ERROR             3
#define INFRASTRUCT_RC_NOOF_CODES             5 // Do not use as RC code
//
// TOR specific error codes
//
#define TOR_SUCCESS                           INFRASTRUCT_RC_SUCCESS
#define TOR_FAILURE                           INFRASTRUCT_RC_FAILURE
#define TOR_CODE_BUG                          INFRASTRUCT_RC_CODE_BUG
#define TOR_USER_ERROR                        INFRASTRUCT_RC_USER_ERROR
#define TOR_INVALID_MAGIC_NUMBER              INFRASTRUCT_RC_NOOF_CODES + 1
#define TOR_INVALID_CHIPTYPE                  INFRASTRUCT_RC_NOOF_CODES + 3
#define TOR_INVALID_CHIPLET                   INFRASTRUCT_RC_NOOF_CODES + 4
#define TOR_INVALID_VARIANT                   INFRASTRUCT_RC_NOOF_CODES + 5
#define TOR_INVALID_RING_ID                   INFRASTRUCT_RC_NOOF_CODES + 6
#define TOR_INVALID_INSTANCE_ID               INFRASTRUCT_RC_NOOF_CODES + 7
#define TOR_INVALID_RING_BLOCK_TYPE           INFRASTRUCT_RC_NOOF_CODES + 8
#define TOR_UNSUPPORTED_RING_SECTION          INFRASTRUCT_RC_NOOF_CODES + 9
#define TOR_RING_NOT_FOUND                    INFRASTRUCT_RC_NOOF_CODES + 10
#define TOR_AMBIGUOUS_API_PARMS               INFRASTRUCT_RC_NOOF_CODES + 11
#define TOR_SECTION_NOT_FOUND                 INFRASTRUCT_RC_NOOF_CODES + 12
#define TOR_DD_LEVEL_NOT_FOUND                INFRASTRUCT_RC_NOOF_CODES + 13
#define TOR_OP_BUFFER_INVALID                 INFRASTRUCT_RC_NOOF_CODES + 14
#define TOR_OP_BUFFER_SIZE_EXCEEDED           INFRASTRUCT_RC_NOOF_CODES + 15
#define TOR_IMAGE_DOES_NOT_SUPPORT_CME        INFRASTRUCT_RC_NOOF_CODES + 16
#define TOR_IMAGE_DOES_NOT_SUPPORT_SGPE       INFRASTRUCT_RC_NOOF_CODES + 17
#define TOR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL   INFRASTRUCT_RC_NOOF_CODES + 18
#define TOR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL  INFRASTRUCT_RC_NOOF_CODES + 19
#define TOR_RING_AVAILABLE_IN_RINGSECTION     INFRASTRUCT_RC_NOOF_CODES + 20
#define TOR_BUFFER_TOO_SMALL                  INFRASTRUCT_RC_NOOF_CODES + 21
#define TOR_TOO_MANY_DD_LEVELS                INFRASTRUCT_RC_NOOF_CODES + 22
#define TOR_OFFSET_TOO_BIG                    INFRASTRUCT_RC_NOOF_CODES + 23

int ringid_get_noof_chiplets( ChipType_t  i_chipType,
                              uint32_t    i_torMagic,
                              uint8_t*    o_numChiplets );

int ringid_get_properties( ChipType_t         i_chipType,
                           uint32_t           i_torMagic,
                           ChipletType_t      i_chiplet,
                           ChipletData_t**    o_chipletData,
                           GenRingIdList**    o_ringIdListCommon,
                           GenRingIdList**    o_ringIdListInstance,
                           RingVariantOrder** o_ringVariantOrder,
                           RingProperties_t** o_ringProps,
                           uint8_t*           o_numVariants );

#endif  // _COMMON_RINGID_H_
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_scrub.C $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_scrub.C
/// @brief Begin background scrub
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <p9_mss_scrub.H>

#include <lib/dimm/rank.H>
#include <lib/mcbist/address.H>
#include <lib/mcbist/mcbist.H>
#include <lib/mcbist/patterns.H>
#include <lib/mcbist/memdiags.H>
#include <lib/mcbist/sim.H>
#include <lib/utils/count_dimm.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::FAPI2_RC_SUCCESS;

///
/// @brief Begin background scrub
/// @param[in] i_target MCBIST
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_scrub( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
    FAPI_INF("Start mss scrub");

    // If we're running in the simulator, we want to only touch the addresses which training touched
    uint8_t is_sim = 0;

    // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
    // attributes for the PHY, etc.
    if (mss::count_dimm(i_target) == 0)
    {
        FAPI_INF("... skipping scrub for %s - no DIMM ...", mss::c_str(i_target));
        return fapi2::FAPI2_RC_SUCCESS;
    }

    FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_IS_SIMULATION, fapi2::Target<TARGET_TYPE_SYSTEM>(), is_sim) );

    if (is_sim)
    {
        // Use some sort of pattern in sim in case the verification folks need to look for something
        // TK. Need a verification pattern. This is a not-good pattern for verification ... We don't really
        // have a good pattern for verification defined.
        FAPI_INF("running mss sim init in place of scrub");
        return mss::mcbist::sim::sf_init(i_target, mss::mcbist::PATTERN_2);
    }

    // TK do we want these to be arguments to the wrapper?
    return memdiags::background_scrub(i_target, mss::mcbist::stop_conditions(),
                                      mss::mcbist::speed::LUDICROUS, mss::mcbist::address());

fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>Change p9_mss_scrub to do a sf_write/sf_read on hardware<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_scrub.C $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_scrub.C
/// @brief Begin background scrub
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <p9_mss_scrub.H>

#include <lib/dimm/rank.H>
#include <lib/mcbist/address.H>
#include <lib/mcbist/mcbist.H>
#include <lib/mcbist/patterns.H>
#include <lib/mcbist/memdiags.H>
#include <lib/mcbist/sim.H>
#include <lib/utils/count_dimm.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::FAPI2_RC_SUCCESS;

///
/// @brief Begin background scrub
/// @param[in] i_target MCBIST
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_scrub( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
    FAPI_INF("Start mss scrub");

    // If we're running in the simulator, we want to only touch the addresses which training touched
    uint8_t is_sim = 0;

    // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
    // attributes for the PHY, etc.
    if (mss::count_dimm(i_target) == 0)
    {
        FAPI_INF("... skipping scrub for %s - no DIMM ...", mss::c_str(i_target));
        return fapi2::FAPI2_RC_SUCCESS;
    }

    FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_IS_SIMULATION, fapi2::Target<TARGET_TYPE_SYSTEM>(), is_sim) );

    if (is_sim)
    {
        // Use some sort of pattern in sim in case the verification folks need to look for something
        // TK. Need a verification pattern. This is a not-good pattern for verification ... We don't really
        // have a good pattern for verification defined.
        FAPI_INF("running mss sim init in place of scrub");
        return mss::mcbist::sim::sf_init(i_target, mss::mcbist::PATTERN_0);
    }

    // In Cronus on hardware (which is how we got here - f/w doesn't call this) we want
    // to call sf_init (0's) and then a sf_read.
    // TK we need to check FIR given the way this is right now, we should adjust with better stop
    // conditions when we learn more about what we want to find in the lab
    FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) );
    return memdiags::sf_read(i_target, mss::mcbist::stop_conditions(), mss::mcbist::end_boundary::STOP_AFTER_ADDRESS);

fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_attr_update.C $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_attr_update.C
///
/// @brief Stub HWP for FW to override attributes programmatically
///

//
// *HWP HW Owner : Michael Dye <dyem@us.ibm.com>
// *HWP FW Owner : Thi N. Tran <thi@us.ibm.com>
// *HWP Team : Nest
// *HWP Level : 1
// *HWP Consumed by : HB
//

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "p9_attr_update.H"

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

fapi2::ReturnCode
p9_attr_update(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_DBG("Entering ...");

    FAPI_DBG("Exiting ...");

//fapi_try_exit:
    return fapi2::current_err;

}
<commit_msg>Checking in change of HWP level from 1 to 2<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_attr_update.C $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_attr_update.C
///
/// @brief Stub HWP for FW to override attributes programmatically
///

//
// *HWP HW Owner : Michael Dye <dyem@us.ibm.com>
// *HWP FW Owner : Thi N. Tran <thi@us.ibm.com>
// *HWP Team : Nest
// *HWP Level : 2
// *HWP Consumed by : HB
//

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "p9_attr_update.H"

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

fapi2::ReturnCode
p9_attr_update(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_DBG("Entering ...");

    FAPI_DBG("Exiting ...");

//fapi_try_exit:
    return fapi2::current_err;

}
<|endoftext|>


<commit_before>#include "ImGuiEntitySelectorSystem.hpp"

#include "data/ImGuiComponent.hpp"
#include "data/ImGuiToolComponent.hpp"
#include "data/NameComponent.hpp"
#include "data/SelectedComponent.hpp"

#include "helpers/typeHelper.hpp"
#include "helpers/sortHelper.hpp"
#include "meta/Has.hpp"
#include "meta/MatchString.hpp"

#include "helpers/imguiHelper.hpp"
#include "imgui.h"

#include "string.hpp"
#include "to_string.hpp"

namespace kengine {
#pragma region declarations
	static bool matches(const Entity & e, const char * str, EntityManager & em);
#pragma endregion
	EntityCreatorFunctor<64> ImGuiEntitySelectorSystem(EntityManager & em) {
		return [&](Entity & e) {
			e += NameComponent{ "Entity selector" };
			auto & tool = e.attach<ImGuiToolComponent>();
			tool.enabled = true;

			e += ImGuiComponent([&] {
				if (!tool.enabled)
					return;

				if (ImGui::Begin("Entity selector", &tool.enabled)) {
					static char nameSearch[1024];
					ImGui::InputText("Search", nameSearch, sizeof(nameSearch));
					ImGui::SameLine();
					if (ImGui::Button("New"))
						em += [](Entity & e) { e += SelectedComponent{}; };
					ImGui::Separator();

					ImGui::BeginChild("child");
					for (auto & e : em.getEntities())
						if (matches(e, nameSearch, em)) {
							if (e.has<SelectedComponent>())
								e.detach<SelectedComponent>();
							else
								e.attach<SelectedComponent>();
						}
					ImGui::EndChild();
				}
				ImGui::End();
			});
		};
	}

	static bool matches(const Entity & e, const char * str, EntityManager & em) {
		putils::string<1024> displayText("[%d]", e.id);

		if (strlen(str) != 0) {
			displayText += " Matches in ";

			bool matches = false;
			if (str[0] >= '0' && str[0] <= '9' && putils::parse<Entity::ID>(str) == e.id) {
				matches = true;
				displayText += "ID";
			}
			else {
				const auto types = sortHelper::getNameSortedEntities<KENGINE_COMPONENT_COUNT,
					meta::Has, meta::MatchString
				>(em);

				for (const auto & [_, type, has, matchFunc] : types) {
					if (!has->call(e) || !matchFunc->call(e, str))
						continue;

					if (displayText.size() + type->name.size() + 2 < decltype(displayText)::max_size) {
						if (matches) // Isn't the first time
							displayText += ", ";
						displayText += type->name;
					}
					matches = true;
				}
			}

			if (!matches)
				return false;
		}

		bool ret = false;
		if (ImGui::Button(putils::string<64>("Select##") + e.id))
			ret = true;
		ImGui::SameLine();
		if (ImGui::Button(putils::string<64>("Remove##") + e.id)) {
			em.removeEntity(e);
			return false;
		}

		if (ImGui::TreeNode(displayText + "##" + e.id)) {
			imguiHelper::displayEntity(em, e);
			ImGui::TreePop();
		}

		return ret;
	}
}<commit_msg>improve imgui entity selector layout<commit_after>#include "ImGuiEntitySelectorSystem.hpp"

#include "data/ImGuiComponent.hpp"
#include "data/ImGuiToolComponent.hpp"
#include "data/NameComponent.hpp"
#include "data/SelectedComponent.hpp"

#include "helpers/typeHelper.hpp"
#include "helpers/sortHelper.hpp"
#include "meta/Has.hpp"
#include "meta/MatchString.hpp"

#include "helpers/imguiHelper.hpp"
#include "imgui.h"

#include "string.hpp"
#include "to_string.hpp"

namespace kengine {
#pragma region declarations
	static bool matches(const Entity & e, const char * str, EntityManager & em);
#pragma endregion
	EntityCreatorFunctor<64> ImGuiEntitySelectorSystem(EntityManager & em) {
		return [&](Entity & e) {
			e += NameComponent{ "Entity selector" };
			auto & tool = e.attach<ImGuiToolComponent>();
			tool.enabled = true;

			e += ImGuiComponent([&] {
				if (!tool.enabled)
					return;

				if (ImGui::Begin("Entity selector", &tool.enabled)) {
					static char nameSearch[1024];
					ImGui::InputText("Search", nameSearch, sizeof(nameSearch));

					ImGui::Separator();

					ImGui::BeginChild("child");
					for (auto & e : em.getEntities())
						if (matches(e, nameSearch, em)) {
							if (e.has<SelectedComponent>())
								e.detach<SelectedComponent>();
							else
								e.attach<SelectedComponent>();
						}
					ImGui::EndChild();
				}
				ImGui::End();
			});
		};
	}

	static bool matches(const Entity & e, const char * str, EntityManager & em) {
		putils::string<1024> displayText("[%d]", e.id);;
		if (e.has<NameComponent>()) {
			displayText += " ";
			displayText += e.get<NameComponent>().name;
		}

		if (strlen(str) != 0) {
			displayText += " -- ";

			bool matches = false;
			if (str[0] >= '0' && str[0] <= '9' && putils::parse<Entity::ID>(str) == e.id) {
				matches = true;
				displayText += "ID";
			}
			else {
				const auto types = sortHelper::getNameSortedEntities<KENGINE_COMPONENT_COUNT,
					meta::Has, meta::MatchString
				>(em);

				for (const auto & [_, type, has, matchFunc] : types) {
					if (!has->call(e) || !matchFunc->call(e, str))
						continue;

					if (displayText.size() + type->name.size() + 2 < decltype(displayText)::max_size) {
						if (matches) // Isn't the first time
							displayText += ", ";
						displayText += type->name;
					}
					matches = true;
				}
			}

			if (!matches)
				return false;
		}

		bool ret = false;
		const auto openTreeNode = ImGui::TreeNode(displayText + "##" + e.id);
		if (ImGui::BeginPopupContextItem()) {
			if (ImGui::MenuItem("Select"))
				ret = true;
			if (ImGui::MenuItem("Remove")) {
				em.removeEntity(e);
				return false;
			}
			ImGui::EndPopup();
		}
		if (openTreeNode) {
			imguiHelper::displayEntity(em, e);
			ImGui::TreePop();
		}

		return ret;
	}
}<|endoftext|>


<commit_before>// Copyright 2020 Open Source Robotics Foundation, Inc.
//
// 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.

#include <gtest/gtest.h>

#include "rcutils/allocator.h"

#include "rosidl_typesupport_cpp/message_type_support.hpp"

#include "rmw/rmw.h"
#include "rmw/error_handling.h"

#include "test_msgs/msg/basic_types.h"
#include "test_msgs/msg/basic_types.hpp"

#include "./allocator_testing_utils.h"

#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif

class CLASSNAME (TestSerializeDeserialize, RMW_IMPLEMENTATION) : public ::testing::Test
{
};

TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), serialize_with_bad_arguments) {
  const rosidl_message_type_support_t * ts{
    ROSIDL_GET_MSG_TYPE_SUPPORT(test_msgs, msg, BasicTypes)};
  test_msgs__msg__BasicTypes input_message{};
  ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&input_message));
  rcutils_allocator_t failing_allocator = get_failing_allocator();
  rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
  ASSERT_EQ(
    RMW_RET_OK, rmw_serialized_message_init(
      &serialized_message, 0lu, &failing_allocator)) << rmw_get_error_string().str;

  EXPECT_NE(RMW_RET_OK, rmw_serialize(&input_message, ts, &serialized_message));
  rmw_reset_error();

  EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
    rmw_get_error_string().str;
}

TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), clean_round_trip_for_c_message) {
  const rosidl_message_type_support_t * ts{
    ROSIDL_GET_MSG_TYPE_SUPPORT(test_msgs, msg, BasicTypes)};
  test_msgs__msg__BasicTypes input_message{};
  test_msgs__msg__BasicTypes output_message{};
  ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&input_message));
  ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&output_message));
  rcutils_allocator_t default_allocator = rcutils_get_default_allocator();
  rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
  ASSERT_EQ(
    RMW_RET_OK, rmw_serialized_message_init(
      &serialized_message, 0lu, &default_allocator)) << rmw_get_error_string().str;

  // Make input_message not equal to output_message.
  input_message.bool_value = !output_message.bool_value;
  input_message.int16_value = output_message.int16_value - 1;
  input_message.uint32_value = output_message.uint32_value + 1000000;

  rmw_ret_t ret = rmw_serialize(&input_message, ts, &serialized_message);
  EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
  EXPECT_NE(nullptr, serialized_message.buffer);
  EXPECT_GT(serialized_message.buffer_length, 0lu);

  ret = rmw_deserialize(&serialized_message, ts, &output_message);
  EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
  EXPECT_EQ(input_message.bool_value, output_message.bool_value);
  EXPECT_EQ(input_message.int16_value, output_message.int16_value);
  EXPECT_EQ(input_message.uint32_value, output_message.uint32_value);

  EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
    rmw_get_error_string().str;
}

TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), clean_round_trip_for_cpp_message) {
  const rosidl_message_type_support_t * ts =
    rosidl_typesupport_cpp::get_message_type_support_handle<test_msgs::msg::BasicTypes>();
  test_msgs::msg::BasicTypes input_message{};
  test_msgs::msg::BasicTypes output_message{};
  rcutils_allocator_t default_allocator = rcutils_get_default_allocator();
  rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
  ASSERT_EQ(
    RMW_RET_OK, rmw_serialized_message_init(
      &serialized_message, 0lu, &default_allocator)) << rmw_get_error_string().str;

  // Make input_message not equal to output_message.
  input_message.bool_value = !output_message.bool_value;
  input_message.int16_value = output_message.int16_value - 1;
  input_message.uint32_value = output_message.uint32_value + 1000000;

  rmw_ret_t ret = rmw_serialize(&input_message, ts, &serialized_message);
  EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
  EXPECT_NE(nullptr, serialized_message.buffer);
  EXPECT_GT(serialized_message.buffer_length, 0lu);

  ret = rmw_deserialize(&serialized_message, ts, &output_message);
  EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
  EXPECT_EQ(input_message, output_message);

  EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
    rmw_get_error_string().str;
}
<commit_msg>Add rmw_get_serialization_format() smoke test. (#133)<commit_after>// Copyright 2020 Open Source Robotics Foundation, Inc.
//
// 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.

#include <gtest/gtest.h>

#include "rcutils/allocator.h"

#include "rosidl_typesupport_cpp/message_type_support.hpp"

#include "rmw/rmw.h"
#include "rmw/error_handling.h"

#include "test_msgs/msg/basic_types.h"
#include "test_msgs/msg/basic_types.hpp"

#include "./allocator_testing_utils.h"

#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif

class CLASSNAME (TestSerializeDeserialize, RMW_IMPLEMENTATION) : public ::testing::Test
{
};

TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), get_serialization_format) {
  const char * serialization_format = rmw_get_serialization_format();
  EXPECT_NE(nullptr, serialization_format);
  EXPECT_STREQ(serialization_format, rmw_get_serialization_format());
}

TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), serialize_with_bad_arguments) {
  const rosidl_message_type_support_t * ts{
    ROSIDL_GET_MSG_TYPE_SUPPORT(test_msgs, msg, BasicTypes)};
  test_msgs__msg__BasicTypes input_message{};
  ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&input_message));
  rcutils_allocator_t failing_allocator = get_failing_allocator();
  rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
  ASSERT_EQ(
    RMW_RET_OK, rmw_serialized_message_init(
      &serialized_message, 0lu, &failing_allocator)) << rmw_get_error_string().str;

  EXPECT_NE(RMW_RET_OK, rmw_serialize(&input_message, ts, &serialized_message));
  rmw_reset_error();

  EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
    rmw_get_error_string().str;
}

TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), clean_round_trip_for_c_message) {
  const rosidl_message_type_support_t * ts{
    ROSIDL_GET_MSG_TYPE_SUPPORT(test_msgs, msg, BasicTypes)};
  test_msgs__msg__BasicTypes input_message{};
  test_msgs__msg__BasicTypes output_message{};
  ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&input_message));
  ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&output_message));
  rcutils_allocator_t default_allocator = rcutils_get_default_allocator();
  rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
  ASSERT_EQ(
    RMW_RET_OK, rmw_serialized_message_init(
      &serialized_message, 0lu, &default_allocator)) << rmw_get_error_string().str;

  // Make input_message not equal to output_message.
  input_message.bool_value = !output_message.bool_value;
  input_message.int16_value = output_message.int16_value - 1;
  input_message.uint32_value = output_message.uint32_value + 1000000;

  rmw_ret_t ret = rmw_serialize(&input_message, ts, &serialized_message);
  EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
  EXPECT_NE(nullptr, serialized_message.buffer);
  EXPECT_GT(serialized_message.buffer_length, 0lu);

  ret = rmw_deserialize(&serialized_message, ts, &output_message);
  EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
  EXPECT_EQ(input_message.bool_value, output_message.bool_value);
  EXPECT_EQ(input_message.int16_value, output_message.int16_value);
  EXPECT_EQ(input_message.uint32_value, output_message.uint32_value);

  EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
    rmw_get_error_string().str;
}

TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), clean_round_trip_for_cpp_message) {
  const rosidl_message_type_support_t * ts =
    rosidl_typesupport_cpp::get_message_type_support_handle<test_msgs::msg::BasicTypes>();
  test_msgs::msg::BasicTypes input_message{};
  test_msgs::msg::BasicTypes output_message{};
  rcutils_allocator_t default_allocator = rcutils_get_default_allocator();
  rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
  ASSERT_EQ(
    RMW_RET_OK, rmw_serialized_message_init(
      &serialized_message, 0lu, &default_allocator)) << rmw_get_error_string().str;

  // Make input_message not equal to output_message.
  input_message.bool_value = !output_message.bool_value;
  input_message.int16_value = output_message.int16_value - 1;
  input_message.uint32_value = output_message.uint32_value + 1000000;

  rmw_ret_t ret = rmw_serialize(&input_message, ts, &serialized_message);
  EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
  EXPECT_NE(nullptr, serialized_message.buffer);
  EXPECT_GT(serialized_message.buffer_length, 0lu);

  ret = rmw_deserialize(&serialized_message, ts, &output_message);
  EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
  EXPECT_EQ(input_message, output_message);

  EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
    rmw_get_error_string().str;
}
<|endoftext|>


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

#ifndef INCLUDED_LIBLASREADER_HPP
#define INCLUDED_LIBLASREADER_HPP

#include "libpc/Reader.hpp"

#include <iostream>

#include "header.hpp"

// fwd decls
namespace liblas
{
    class Reader;
    enum PointFormatName;
}

namespace libpc
{

class LIBPC_DLL LiblasReader : public Reader
{
public:
    LiblasReader(std::istream&);
    ~LiblasReader();

    virtual boost::uint32_t readPoints(PointData&);

    // default is to reset() and then read N points manually
    // override this if you can
    virtual void seekToPoint(boost::uint64_t pointNum);

    // default just resets the point index
    virtual void reset();

    const LiblasHeader& getLiblasHeader() const;

private:
    LiblasHeader& getLiblasHeader();
    void setLiblasHeader(const LiblasHeader&);
    void processExternalHeader();
    void registerFields();

    std::istream& m_istream;

    liblas::Reader *m_externalReader;

    // LAS header properties of interest to us
    boost::uint8_t m_versionMajor;
    boost::uint8_t m_versionMinor;
    double m_scaleX;
    double m_scaleY;
    double m_scaleZ;
    double m_offsetX;
    double m_offsetY;
    double m_offsetZ;
    bool m_isCompressed;

    liblas::PointFormatName m_pointFormat;
    bool m_hasTimeData;
    bool m_hasColorData;
    bool m_hasWaveData;

    LiblasReader& operator=(const LiblasReader&); // not implemented
    LiblasReader(const LiblasReader&); // not implemented
};

} // namespace libpc

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

#ifndef INCLUDED_LIBLASREADER_HPP
#define INCLUDED_LIBLASREADER_HPP

#include "libpc/Reader.hpp"

#include <iostream>

#include "header.hpp"

#include <liblas/version.hpp>

// fwd decls
namespace liblas
{
    class Reader;
    // enum PointFormatName;
}

namespace libpc
{

class LIBPC_DLL LiblasReader : public Reader
{
public:
    LiblasReader(std::istream&);
    ~LiblasReader();

    virtual boost::uint32_t readPoints(PointData&);

    // default is to reset() and then read N points manually
    // override this if you can
    virtual void seekToPoint(boost::uint64_t pointNum);

    // default just resets the point index
    virtual void reset();

    const LiblasHeader& getLiblasHeader() const;

private:
    LiblasHeader& getLiblasHeader();
    void setLiblasHeader(const LiblasHeader&);
    void processExternalHeader();
    void registerFields();

    std::istream& m_istream;

    liblas::Reader *m_externalReader;

    // LAS header properties of interest to us
    boost::uint8_t m_versionMajor;
    boost::uint8_t m_versionMinor;
    double m_scaleX;
    double m_scaleY;
    double m_scaleZ;
    double m_offsetX;
    double m_offsetY;
    double m_offsetZ;
    bool m_isCompressed;

    liblas::PointFormatName m_pointFormat;
    bool m_hasTimeData;
    bool m_hasColorData;
    bool m_hasWaveData;

    LiblasReader& operator=(const LiblasReader&); // not implemented
    LiblasReader(const LiblasReader&); // not implemented
};

} // namespace libpc

#endif
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.3.30); FILE MERGED 2006/01/25 20:57:58 sb 1.3.30.4: RESYNC: (1.3-1.5); FILE MERGED 2005/12/22 11:44:53 fs 1.3.30.3: #i57457# warning-free code 2005/11/21 10:07:53 fs 1.3.30.2: #i57457# warning-free code on unx* 2005/11/07 14:43:49 fs 1.3.30.1: #i57457# warning-free code<commit_after><|endoftext|>


<commit_before>/* Copyright 2017 Istio Authors. All Rights Reserved.
 *
 * 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.
 */

#include "common/common/enum_to_int.h"
#include "common/common/logger.h"
#include "envoy/network/connection.h"
#include "envoy/network/filter.h"
#include "envoy/registry/registry.h"
#include "envoy/server/instance.h"
#include "server/config/network/http_connection_manager.h"
#include "src/envoy/mixer/config.h"
#include "src/envoy/mixer/mixer_control.h"

using ::google::protobuf::util::Status;
using StatusCode = ::google::protobuf::util::error::Code;

namespace Envoy {
namespace Http {
namespace Mixer {

class TcpConfig : public Logger::Loggable<Logger::Id::filter> {
 private:
  Upstream::ClusterManager& cm_;
  MixerConfig mixer_config_;
  ThreadLocal::SlotPtr tls_;

 public:
  TcpConfig(const Json::Object& config,
            Server::Configuration::FactoryContext& context)
      : cm_(context.clusterManager()),
        tls_(context.threadLocal().allocateSlot()) {
    mixer_config_.Load(config);
    Runtime::RandomGenerator& random = context.random();
    tls_->set(
        [this, &random](Event::Dispatcher& dispatcher)
            -> ThreadLocal::ThreadLocalObjectSharedPtr {
              return ThreadLocal::ThreadLocalObjectSharedPtr(
                  new MixerControl(mixer_config_, cm_, dispatcher, random));
            });
  }

  MixerControl& mixer_control() { return tls_->getTyped<MixerControl>(); }
};

typedef std::shared_ptr<TcpConfig> TcpConfigPtr;

class TcpInstance : public Network::Filter,
                    public Network::ConnectionCallbacks,
                    public Logger::Loggable<Logger::Id::filter> {
 private:
  enum class State { NotStarted, Calling, Completed, Closed };

  istio::mixer_client::CancelFunc cancel_check_;
  MixerControl& mixer_control_;
  std::shared_ptr<HttpRequestData> request_data_;
  Network::ReadFilterCallbacks* filter_callbacks_{};
  State state_{State::NotStarted};
  bool calling_check_{};
  uint64_t received_bytes_{};
  uint64_t send_bytes_{};
  int check_status_code_{};
  std::chrono::time_point<std::chrono::system_clock> start_time_;

 public:
  TcpInstance(TcpConfigPtr config) : mixer_control_(config->mixer_control()) {
    ENVOY_LOG(debug, "Called TcpInstance: {}", __func__);
  }

  ~TcpInstance() {
    if (state_ != State::Calling) {
      cancel_check_ = nullptr;
    }
    state_ = State::Closed;
    if (cancel_check_) {
      ENVOY_LOG(debug, "Cancelling check call");
      cancel_check_();
    }
    ENVOY_LOG(debug, "Called TcpInstance : {}", __func__);
  }

  void initializeReadFilterCallbacks(
      Network::ReadFilterCallbacks& callbacks) override {
    ENVOY_LOG(debug, "Called TcpInstance: {}", __func__);
    filter_callbacks_ = &callbacks;
    filter_callbacks_->connection().addConnectionCallbacks(*this);
    start_time_ = std::chrono::system_clock::now();
  }

  // Network::ReadFilter
  Network::FilterStatus onData(Buffer::Instance& data) override {
    ENVOY_CONN_LOG(debug, "Called TcpInstance onRead bytes: {}",
                   filter_callbacks_->connection(), data.length());
    received_bytes_ += data.length();
    return Network::FilterStatus::Continue;
  }

  // Network::WriteFilter
  Network::FilterStatus onWrite(Buffer::Instance& data) override {
    ENVOY_CONN_LOG(debug, "Called TcpInstance onWrite bytes: {}",
                   filter_callbacks_->connection(), data.length());
    send_bytes_ += data.length();
    return Network::FilterStatus::Continue;
  }

  Network::FilterStatus onNewConnection() override {
    ENVOY_CONN_LOG(debug,
                   "Called TcpInstance onNewConnection: remote {}, local {}",
                   filter_callbacks_->connection(),
                   filter_callbacks_->connection().remoteAddress().asString(),
                   filter_callbacks_->connection().localAddress().asString());

    // Reports are always enabled.. And TcpReport uses attributes
    // extracted by BuildTcpCheck
    request_data_ = std::make_shared<HttpRequestData>();

    std::string origin_user;
    Ssl::Connection* ssl = filter_callbacks_->connection().ssl();
    if (ssl != nullptr) {
      origin_user = ssl->uriSanPeerCertificate();
    }
    mixer_control_.BuildTcpCheck(request_data_, filter_callbacks_->connection(),
                                 origin_user);

    if (state_ == State::NotStarted &&
        !mixer_control_.MixerTcpCheckDisabled()) {
      state_ = State::Calling;
      filter_callbacks_->connection().readDisable(true);
      calling_check_ = true;
      cancel_check_ = mixer_control_.SendCheck(
          request_data_, nullptr,
          [this](const Status& status) { completeCheck(status); });
      calling_check_ = false;
    }
    return state_ == State::Calling ? Network::FilterStatus::StopIteration
                                    : Network::FilterStatus::Continue;
  }

  void completeCheck(const Status& status) {
    ENVOY_LOG(debug, "Called TcpInstance completeCheck: {}", status.ToString());
    if (state_ == State::Closed) {
      return;
    }
    state_ = State::Completed;
    filter_callbacks_->connection().readDisable(false);

    if (!status.ok()) {
      check_status_code_ = status.error_code();
      filter_callbacks_->connection().close(
          Network::ConnectionCloseType::NoFlush);
    } else {
      if (!calling_check_) {
        filter_callbacks_->continueReading();
      }
    }
  }

  // Network::ConnectionCallbacks
  void onEvent(Network::ConnectionEvent event) override {
    if (filter_callbacks_->upstreamHost()) {
      ENVOY_LOG(debug, "Called TcpInstance onEvent: {} upstream {}",
                enumToInt(event),
                filter_callbacks_->upstreamHost()->address()->asString());
    } else {
      ENVOY_LOG(debug, "Called TcpInstance onEvent: {}", enumToInt(event));
    }

    if (event == Network::ConnectionEvent::RemoteClose ||
        event == Network::ConnectionEvent::LocalClose) {
      if (state_ != State::Closed && request_data_) {
        mixer_control_.BuildTcpReport(
            request_data_, received_bytes_, send_bytes_, check_status_code_,
            std::chrono::duration_cast<std::chrono::nanoseconds>(
                std::chrono::system_clock::now() - start_time_),
            filter_callbacks_->upstreamHost());
        mixer_control_.SendReport(request_data_);
      }
      state_ = State::Closed;
    }
  }

  void onAboveWriteBufferHighWatermark() override {}
  void onBelowWriteBufferLowWatermark() override {}
};

}  // namespace Mixer
}  // namespace Http

namespace Server {
namespace Configuration {

class TcpMixerFilterFactory : public NamedNetworkFilterConfigFactory {
 public:
  NetworkFilterFactoryCb createFilterFactory(const Json::Object& config,
                                             FactoryContext& context) override {
    Http::Mixer::TcpConfigPtr tcp_config(
        new Http::Mixer::TcpConfig(config, context));
    return [tcp_config](Network::FilterManager& filter_manager) -> void {
      std::shared_ptr<Http::Mixer::TcpInstance> instance =
          std::make_shared<Http::Mixer::TcpInstance>(tcp_config);
      filter_manager.addReadFilter(Network::ReadFilterSharedPtr(instance));
      filter_manager.addWriteFilter(Network::WriteFilterSharedPtr(instance));
    };
  }
  std::string name() override { return "mixer"; }
  NetworkFilterType type() override { return NetworkFilterType::Both; }
};

static Registry::RegisterFactory<TcpMixerFilterFactory,
                                 NamedNetworkFilterConfigFactory>
    register_;

}  // namespace Configuration
}  // namespace Server
}  // namespace Envoy
<commit_msg>Fix a tcp filter crash. (#460)<commit_after>/* Copyright 2017 Istio Authors. All Rights Reserved.
 *
 * 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.
 */

#include "common/common/enum_to_int.h"
#include "common/common/logger.h"
#include "envoy/network/connection.h"
#include "envoy/network/filter.h"
#include "envoy/registry/registry.h"
#include "envoy/server/instance.h"
#include "server/config/network/http_connection_manager.h"
#include "src/envoy/mixer/config.h"
#include "src/envoy/mixer/mixer_control.h"

using ::google::protobuf::util::Status;
using StatusCode = ::google::protobuf::util::error::Code;

namespace Envoy {
namespace Http {
namespace Mixer {

class TcpConfig : public Logger::Loggable<Logger::Id::filter> {
 private:
  Upstream::ClusterManager& cm_;
  MixerConfig mixer_config_;
  ThreadLocal::SlotPtr tls_;

 public:
  TcpConfig(const Json::Object& config,
            Server::Configuration::FactoryContext& context)
      : cm_(context.clusterManager()),
        tls_(context.threadLocal().allocateSlot()) {
    mixer_config_.Load(config);
    Runtime::RandomGenerator& random = context.random();
    tls_->set(
        [this, &random](Event::Dispatcher& dispatcher)
            -> ThreadLocal::ThreadLocalObjectSharedPtr {
              return ThreadLocal::ThreadLocalObjectSharedPtr(
                  new MixerControl(mixer_config_, cm_, dispatcher, random));
            });
  }

  MixerControl& mixer_control() { return tls_->getTyped<MixerControl>(); }
};

typedef std::shared_ptr<TcpConfig> TcpConfigPtr;

class TcpInstance : public Network::Filter,
                    public Network::ConnectionCallbacks,
                    public Logger::Loggable<Logger::Id::filter> {
 private:
  enum class State { NotStarted, Calling, Completed, Closed };

  istio::mixer_client::CancelFunc cancel_check_;
  MixerControl& mixer_control_;
  std::shared_ptr<HttpRequestData> request_data_;
  Network::ReadFilterCallbacks* filter_callbacks_{};
  State state_{State::NotStarted};
  bool calling_check_{};
  uint64_t received_bytes_{};
  uint64_t send_bytes_{};
  int check_status_code_{};
  std::chrono::time_point<std::chrono::system_clock> start_time_;

 public:
  TcpInstance(TcpConfigPtr config) : mixer_control_(config->mixer_control()) {
    ENVOY_LOG(debug, "Called TcpInstance: {}", __func__);
  }

  void cancelCheck() {
    if (state_ != State::Calling) {
      cancel_check_ = nullptr;
    }
    state_ = State::Closed;
    if (cancel_check_) {
      ENVOY_LOG(debug, "Cancelling check call");
      cancel_check_();
      cancel_check_ = nullptr;
    }
  }

  ~TcpInstance() {
    cancelCheck();
    ENVOY_LOG(debug, "Called TcpInstance : {}", __func__);
  }

  void initializeReadFilterCallbacks(
      Network::ReadFilterCallbacks& callbacks) override {
    ENVOY_LOG(debug, "Called TcpInstance: {}", __func__);
    filter_callbacks_ = &callbacks;
    filter_callbacks_->connection().addConnectionCallbacks(*this);
    start_time_ = std::chrono::system_clock::now();
  }

  // Network::ReadFilter
  Network::FilterStatus onData(Buffer::Instance& data) override {
    ENVOY_CONN_LOG(debug, "Called TcpInstance onRead bytes: {}",
                   filter_callbacks_->connection(), data.length());
    received_bytes_ += data.length();
    return Network::FilterStatus::Continue;
  }

  // Network::WriteFilter
  Network::FilterStatus onWrite(Buffer::Instance& data) override {
    ENVOY_CONN_LOG(debug, "Called TcpInstance onWrite bytes: {}",
                   filter_callbacks_->connection(), data.length());
    send_bytes_ += data.length();
    return Network::FilterStatus::Continue;
  }

  Network::FilterStatus onNewConnection() override {
    ENVOY_CONN_LOG(debug,
                   "Called TcpInstance onNewConnection: remote {}, local {}",
                   filter_callbacks_->connection(),
                   filter_callbacks_->connection().remoteAddress().asString(),
                   filter_callbacks_->connection().localAddress().asString());

    // Reports are always enabled.. And TcpReport uses attributes
    // extracted by BuildTcpCheck
    request_data_ = std::make_shared<HttpRequestData>();

    std::string origin_user;
    Ssl::Connection* ssl = filter_callbacks_->connection().ssl();
    if (ssl != nullptr) {
      origin_user = ssl->uriSanPeerCertificate();
    }
    mixer_control_.BuildTcpCheck(request_data_, filter_callbacks_->connection(),
                                 origin_user);

    if (state_ == State::NotStarted &&
        !mixer_control_.MixerTcpCheckDisabled()) {
      state_ = State::Calling;
      filter_callbacks_->connection().readDisable(true);
      calling_check_ = true;
      cancel_check_ = mixer_control_.SendCheck(
          request_data_, nullptr,
          [this](const Status& status) { completeCheck(status); });
      calling_check_ = false;
    }
    return state_ == State::Calling ? Network::FilterStatus::StopIteration
                                    : Network::FilterStatus::Continue;
  }

  void completeCheck(const Status& status) {
    ENVOY_LOG(debug, "Called TcpInstance completeCheck: {}", status.ToString());
    cancel_check_ = nullptr;
    if (state_ == State::Closed) {
      return;
    }
    state_ = State::Completed;
    filter_callbacks_->connection().readDisable(false);

    if (!status.ok()) {
      check_status_code_ = status.error_code();
      filter_callbacks_->connection().close(
          Network::ConnectionCloseType::NoFlush);
    } else {
      if (!calling_check_) {
        filter_callbacks_->continueReading();
      }
    }
  }

  // Network::ConnectionCallbacks
  void onEvent(Network::ConnectionEvent event) override {
    if (filter_callbacks_->upstreamHost()) {
      ENVOY_LOG(debug, "Called TcpInstance onEvent: {} upstream {}",
                enumToInt(event),
                filter_callbacks_->upstreamHost()->address()->asString());
    } else {
      ENVOY_LOG(debug, "Called TcpInstance onEvent: {}", enumToInt(event));
    }

    if (event == Network::ConnectionEvent::RemoteClose ||
        event == Network::ConnectionEvent::LocalClose) {
      if (state_ != State::Closed && request_data_) {
        mixer_control_.BuildTcpReport(
            request_data_, received_bytes_, send_bytes_, check_status_code_,
            std::chrono::duration_cast<std::chrono::nanoseconds>(
                std::chrono::system_clock::now() - start_time_),
            filter_callbacks_->upstreamHost());
        mixer_control_.SendReport(request_data_);
      }
      cancelCheck();
    }
  }

  void onAboveWriteBufferHighWatermark() override {}
  void onBelowWriteBufferLowWatermark() override {}
};

}  // namespace Mixer
}  // namespace Http

namespace Server {
namespace Configuration {

class TcpMixerFilterFactory : public NamedNetworkFilterConfigFactory {
 public:
  NetworkFilterFactoryCb createFilterFactory(const Json::Object& config,
                                             FactoryContext& context) override {
    Http::Mixer::TcpConfigPtr tcp_config(
        new Http::Mixer::TcpConfig(config, context));
    return [tcp_config](Network::FilterManager& filter_manager) -> void {
      std::shared_ptr<Http::Mixer::TcpInstance> instance =
          std::make_shared<Http::Mixer::TcpInstance>(tcp_config);
      filter_manager.addReadFilter(Network::ReadFilterSharedPtr(instance));
      filter_manager.addWriteFilter(Network::WriteFilterSharedPtr(instance));
    };
  }
  std::string name() override { return "mixer"; }
  NetworkFilterType type() override { return NetworkFilterType::Both; }
};

static Registry::RegisterFactory<TcpMixerFilterFactory,
                                 NamedNetworkFilterConfigFactory>
    register_;

}  // namespace Configuration
}  // namespace Server
}  // namespace Envoy
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2015 Felix Rieseberg <feriese@microsoft.com> and Jason Poon <jason.poon@microsoft.com>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "browser/win/notification_presenter_win.h"

#include "base/files/file_util.h"
#include "base/md5.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "browser/win/windows_toast_notification.h"
#include "content/public/browser/desktop_notification_delegate.h"
#include "content/public/common/platform_notification_data.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"

#pragma comment(lib, "runtimeobject.lib")

namespace brightray {

namespace {

bool SaveIconToPath(const SkBitmap& bitmap, const base::FilePath& path) {
  std::vector<unsigned char> png_data;
  if (!gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &png_data))
    return false;

  char* data = reinterpret_cast<char*>(&png_data[0]);
  int size = static_cast<int>(png_data.size());
  return base::WriteFile(path, data, size) == size;
}

}  // namespace

// static
NotificationPresenter* NotificationPresenter::Create() {
  if (!WindowsToastNotification::Initialize())
    return nullptr;
  std::unique_ptr<NotificationPresenterWin> presenter(new NotificationPresenterWin);
  if (!presenter->Init())
    return nullptr;
  return presenter.release();
}

NotificationPresenterWin::NotificationPresenterWin() {
}

NotificationPresenterWin::~NotificationPresenterWin() {
}

bool NotificationPresenterWin::Init() {
  return temp_dir_.CreateUniqueTempDir();
}

base::string16 NotificationPresenterWin::SaveIconToFilesystem(
    const SkBitmap& icon, const GURL& origin) {
  std::string filename = base::MD5String(origin.spec()) + ".png";
  base::FilePath path = temp_dir_.path().Append(base::UTF8ToUTF16(filename));
  if (base::PathExists(path))
    return path.value();
  if (SaveIconToPath(icon, path))
    return path.value();
  return base::UTF8ToUTF16(origin.spec());
}

}  // namespace brightray
<commit_msg>Apply changes to "//base: Make ScopedTempDir::path() a GetPath() with a DCHECK" https://chromium.googlesource.com/chromium/src.git/+/411f4fc60df3a256dd2d15ab39c540228ed66e7f<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2015 Felix Rieseberg <feriese@microsoft.com> and Jason Poon <jason.poon@microsoft.com>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "browser/win/notification_presenter_win.h"

#include "base/files/file_util.h"
#include "base/md5.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "browser/win/windows_toast_notification.h"
#include "content/public/browser/desktop_notification_delegate.h"
#include "content/public/common/platform_notification_data.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"

#pragma comment(lib, "runtimeobject.lib")

namespace brightray {

namespace {

bool SaveIconToPath(const SkBitmap& bitmap, const base::FilePath& path) {
  std::vector<unsigned char> png_data;
  if (!gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &png_data))
    return false;

  char* data = reinterpret_cast<char*>(&png_data[0]);
  int size = static_cast<int>(png_data.size());
  return base::WriteFile(path, data, size) == size;
}

}  // namespace

// static
NotificationPresenter* NotificationPresenter::Create() {
  if (!WindowsToastNotification::Initialize())
    return nullptr;
  std::unique_ptr<NotificationPresenterWin> presenter(new NotificationPresenterWin);
  if (!presenter->Init())
    return nullptr;
  return presenter.release();
}

NotificationPresenterWin::NotificationPresenterWin() {
}

NotificationPresenterWin::~NotificationPresenterWin() {
}

bool NotificationPresenterWin::Init() {
  return temp_dir_.CreateUniqueTempDir();
}

base::string16 NotificationPresenterWin::SaveIconToFilesystem(
    const SkBitmap& icon, const GURL& origin) {
  std::string filename = base::MD5String(origin.spec()) + ".png";
  base::FilePath path = temp_dir_.GetPath().Append(base::UTF8ToUTF16(filename));
  if (base::PathExists(path))
    return path.value();
  if (SaveIconToPath(icon, path))
    return path.value();
  return base::UTF8ToUTF16(origin.spec());
}

}  // namespace brightray
<|endoftext|>


<commit_before><commit_msg>Bug Hunting<commit_after><|endoftext|>