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

Program:   Visualization Toolkit
Module:    vtkTemporalStreamTracer.cxx

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkTemporalStreamTracer.h"
#include "vtkPTemporalStreamTracer.h"

#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkCompositeDataIterator.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkDataSetAttributes.h"
#include "vtkDoubleArray.h"
#include "vtkExecutive.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"
#include "vtkCharArray.h"
#include "vtkMath.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkPolyData.h"
#include "vtkPolyLine.h"
#include "vtkRungeKutta2.h"
#include "vtkRungeKutta4.h"
#include "vtkRungeKutta45.h"
#include "vtkSmartPointer.h"
#include "vtkTemporalInterpolatedVelocityField.h"
#include "vtkOutputWindow.h"
#include "vtkAbstractParticleWriter.h"
#include "vtkToolkits.h"
#include <cassert>
#include "vtkMPIController.h"

using namespace vtkTemporalStreamTracerNamespace;

//---------------------------------------------------------------------------
vtkStandardNewMacro(vtkPTemporalStreamTracer);
vtkCxxSetObjectMacro(vtkPTemporalStreamTracer, Controller, vtkMultiProcessController);
//---------------------------------------------------------------------------
vtkPTemporalStreamTracer::vtkPTemporalStreamTracer()
{
  this->Controller = NULL;
  this->SetController(vtkMultiProcessController::GetGlobalController());
}
//---------------------------------------------------------------------------
vtkPTemporalStreamTracer::~vtkPTemporalStreamTracer()
{
  this->SetController(NULL);
  this->SetParticleWriter(NULL);
}
//---------------------------------------------------------------------------
void vtkPTemporalStreamTracer::AssignSeedsToProcessors(
  vtkDataSet *source, int sourceID, int ptId,
  ParticleVector &LocalSeedPoints, int &LocalAssignedCount)
{
  if(!this->Controller)
    {
    return Superclass::AssignSeedsToProcessors(source, sourceID, ptId,
                                               LocalSeedPoints, LocalAssignedCount);
    }

  ParticleVector candidates;
  //
  // take points from the source object and create a particle list
  //
  int numSeeds = source->GetNumberOfPoints();
#ifndef NDEBUG
  int numTested = numSeeds;
#endif
  candidates.resize(numSeeds);
  //
  for (int i=0; i<numSeeds; i++) {
    ParticleInformation &info = candidates[i];
    memcpy(&(info.CurrentPosition.x[0]), source->GetPoint(i), sizeof(double)*3);
    info.CurrentPosition.x[3] = this->CurrentTimeSteps[0];
    info.LocationState        = 0;
    info.CachedCellId[0]      =-1;
    info.CachedCellId[1]      =-1;
    info.CachedDataSetId[0]   = 0;
    info.CachedDataSetId[1]   = 0;
    info.SourceID             = sourceID;
    info.InjectedPointId      = i+ptId;
    info.InjectedStepId       = this->ReinjectionCounter;
    info.TimeStepAge          = 0;
    info.UniqueParticleId     =-1;
    info.rotation             = 0.0;
    info.angularVel           = 0.0;
    info.time                 = 0.0;
    info.age                  = 0.0;
    info.speed                = 0.0;
    info.ErrorCode            = 0;
  }
  //
  // Gather all Seeds to all processors for classification
  //
  // TODO : can we just use the same array here for send and receive
  ParticleVector allCandidates;
  if (this->UpdateNumPieces>1) {
    // Gather all seed particles to all processes
    this->TransmitReceiveParticles(candidates, allCandidates, false);
#ifndef NDEBUG
    numTested = static_cast<int>(allCandidates.size());
#endif
    vtkDebugMacro(<< "Local Particles " << numSeeds << " TransmitReceive Total " << numTested);
    // Test to see which ones belong to us
    this->TestParticles(allCandidates, LocalSeedPoints, LocalAssignedCount);
  }
  else {
#ifndef NDEBUG
    numTested = static_cast<int>(candidates.size());
#endif
    this->TestParticles(candidates, LocalSeedPoints, LocalAssignedCount);
  }
  int TotalAssigned = 0;
  this->Controller->Reduce(&LocalAssignedCount, &TotalAssigned, 1, vtkCommunicator::SUM_OP, 0);

  // Assign unique identifiers taking into account uneven distribution
  // across processes and seeds which were rejected
  this->AssignUniqueIds(LocalSeedPoints);
  //
  vtkDebugMacro(<< "Tested " << numTested << " LocallyAssigned " << LocalAssignedCount);
  if (this->UpdatePiece==0) {
    vtkDebugMacro(<< "Total Assigned to all processes " << TotalAssigned);
  }
}
//---------------------------------------------------------------------------
void vtkPTemporalStreamTracer::AssignUniqueIds(
  vtkTemporalStreamTracerNamespace::ParticleVector &LocalSeedPoints)
{
  if(!this->Controller)
    {
    return Superclass::AssignUniqueIds(LocalSeedPoints);
    }

  vtkIdType ParticleCountOffset = 0;
  vtkIdType numParticles = LocalSeedPoints.size();
  if (this->UpdateNumPieces>1) {
    vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast(
      this->Controller->GetCommunicator());
    if (com == 0) {
      vtkErrorMacro("MPICommunicator needed for this operation.");
      return;
    }
    // everyone starts with the master index
    com->Broadcast(&this->UniqueIdCounter, 1, 0);
//    vtkErrorMacro("UniqueIdCounter " << this->UniqueIdCounter);
    // setup arrays used by the AllGather call.
    std::vector<vtkIdType> recvNumParticles(this->UpdateNumPieces, 0);
    // Broadcast and receive count to/from all other processes.
    com->AllGather(&numParticles, &recvNumParticles[0], 1);
    // Each process is allocating a certain number.
    // start our indices from sum[0,this->UpdatePiece](numparticles)
    for (int i=0; i<this->UpdatePiece; ++i) {
      ParticleCountOffset += recvNumParticles[i];
    }
    for (vtkIdType i=0; i<numParticles; i++) {
      LocalSeedPoints[i].UniqueParticleId =
        this->UniqueIdCounter + ParticleCountOffset + i;
    }
    for (int i=0; i<this->UpdateNumPieces; ++i) {
      this->UniqueIdCounter += recvNumParticles[i];
    }
  }
  else {
    for (vtkIdType i=0; i<numParticles; i++) {
      LocalSeedPoints[i].UniqueParticleId =
        this->UniqueIdCounter + ParticleCountOffset + i;
    }
    this->UniqueIdCounter += numParticles;
  }
}
//---------------------------------------------------------------------------
void vtkPTemporalStreamTracer::TransmitReceiveParticles(
  ParticleVector &sending, ParticleVector &received, bool removeself)
{
  vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast(
    this->Controller->GetCommunicator());
  if (com == 0) {
    vtkErrorMacro("MPICommunicator needed for this operation.");
    return;
  }
  //
  // We must allocate buffers for all processor particles
  //
  vtkIdType OurParticles = sending.size();
  vtkIdType TotalParticles = 0;
  // setup arrays used by the AllGatherV call.
  std::vector<vtkIdType> recvLengths(this->UpdateNumPieces, 0);
  std::vector<vtkIdType> recvOffsets(this->UpdateNumPieces, 0);
  // Broadcast and receive size to/from all other processes.
  com->AllGather(&OurParticles, &recvLengths[0], 1);
  // Compute the displacements.
  const vtkIdType TypeSize = sizeof(ParticleInformation);
  for (int i=0; i<this->UpdateNumPieces; ++i)
  {
    //  << i << ": " << recvLengths[i] << "   ";
    recvOffsets[i] = TotalParticles*TypeSize;
    TotalParticles += recvLengths[i];
    recvLengths[i] *= TypeSize;
  }
  //  << '\n';
  // Allocate the space for all particles
  received.resize(TotalParticles);
  if (TotalParticles==0) return;
  // Gather the data from all procs.
  char *sendbuf = (char*) ((sending.size()>0) ? &(sending[0]) : NULL);
  char *recvbuf = (char*) (&(received[0]));
  com->AllGatherV(sendbuf, recvbuf,
    OurParticles*TypeSize, &recvLengths[0], &recvOffsets[0]);
  // Now all particles from all processors are in one big array
  // remove any from ourself that we have already tested
  if (removeself) {
    std::vector<ParticleInformation>::iterator first =
      received.begin() + recvOffsets[this->UpdatePiece]/TypeSize;
    std::vector<ParticleInformation>::iterator last =
      first + recvLengths[this->UpdatePiece]/TypeSize;
    received.erase(first, last);
  }
  if (received.size()>0) {
    TotalParticles=TotalParticles; // brkpnt
  }
}
//---------------------------------------------------------------------------
int vtkPTemporalStreamTracer::RequestData(
  vtkInformation *request,
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  int rvalue = this->Superclass::RequestData(request, inputVector, outputVector);

  if(this->Controller)
    {
    this->Controller->Barrier();
    }

  return rvalue;
}
//---------------------------------------------------------------------------
void vtkPTemporalStreamTracer::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Controller: " << this->Controller << endl;
}
//---------------------------------------------------------------------------
void vtkPTemporalStreamTracer::AddParticleToMPISendList(ParticleInformation &info)
{
  double eps = (this->CurrentTimeSteps[1]-this->CurrentTimeSteps[0])/100;
  if (info.CurrentPosition.x[3]<(this->CurrentTimeSteps[0]-eps) ||
      info.CurrentPosition.x[3]>(this->CurrentTimeSteps[1]+eps)) {
    vtkDebugMacro(<< "Unexpected time value in MPISendList - expected ("
      << this->CurrentTimeSteps[0] << "-" << this->CurrentTimeSteps[1] << ") got "
      << info.CurrentPosition.x[3]);
  }
  if (this->MPISendList.capacity()<(this->MPISendList.size()+1)) {
    this->MPISendList.reserve(static_cast<int>(this->MPISendList.size()*1.5));
  }
  this->MPISendList.push_back(info);
}
<commit_msg>vtkPTemporalStreamTracer: remove useless code<commit_after>/*=========================================================================

Program:   Visualization Toolkit
Module:    vtkTemporalStreamTracer.cxx

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkTemporalStreamTracer.h"
#include "vtkPTemporalStreamTracer.h"

#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkCompositeDataIterator.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkDataSetAttributes.h"
#include "vtkDoubleArray.h"
#include "vtkExecutive.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"
#include "vtkCharArray.h"
#include "vtkMath.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkPolyData.h"
#include "vtkPolyLine.h"
#include "vtkRungeKutta2.h"
#include "vtkRungeKutta4.h"
#include "vtkRungeKutta45.h"
#include "vtkSmartPointer.h"
#include "vtkTemporalInterpolatedVelocityField.h"
#include "vtkOutputWindow.h"
#include "vtkAbstractParticleWriter.h"
#include "vtkToolkits.h"
#include <cassert>
#include "vtkMPIController.h"

using namespace vtkTemporalStreamTracerNamespace;

//---------------------------------------------------------------------------
vtkStandardNewMacro(vtkPTemporalStreamTracer);
vtkCxxSetObjectMacro(vtkPTemporalStreamTracer, Controller, vtkMultiProcessController);
//---------------------------------------------------------------------------
vtkPTemporalStreamTracer::vtkPTemporalStreamTracer()
{
  this->Controller = NULL;
  this->SetController(vtkMultiProcessController::GetGlobalController());
}
//---------------------------------------------------------------------------
vtkPTemporalStreamTracer::~vtkPTemporalStreamTracer()
{
  this->SetController(NULL);
  this->SetParticleWriter(NULL);
}
//---------------------------------------------------------------------------
void vtkPTemporalStreamTracer::AssignSeedsToProcessors(
  vtkDataSet *source, int sourceID, int ptId,
  ParticleVector &LocalSeedPoints, int &LocalAssignedCount)
{
  if(!this->Controller)
    {
    return Superclass::AssignSeedsToProcessors(source, sourceID, ptId,
                                               LocalSeedPoints, LocalAssignedCount);
    }

  ParticleVector candidates;
  //
  // take points from the source object and create a particle list
  //
  int numSeeds = source->GetNumberOfPoints();
#ifndef NDEBUG
  int numTested = numSeeds;
#endif
  candidates.resize(numSeeds);
  //
  for (int i=0; i<numSeeds; i++) {
    ParticleInformation &info = candidates[i];
    memcpy(&(info.CurrentPosition.x[0]), source->GetPoint(i), sizeof(double)*3);
    info.CurrentPosition.x[3] = this->CurrentTimeSteps[0];
    info.LocationState        = 0;
    info.CachedCellId[0]      =-1;
    info.CachedCellId[1]      =-1;
    info.CachedDataSetId[0]   = 0;
    info.CachedDataSetId[1]   = 0;
    info.SourceID             = sourceID;
    info.InjectedPointId      = i+ptId;
    info.InjectedStepId       = this->ReinjectionCounter;
    info.TimeStepAge          = 0;
    info.UniqueParticleId     =-1;
    info.rotation             = 0.0;
    info.angularVel           = 0.0;
    info.time                 = 0.0;
    info.age                  = 0.0;
    info.speed                = 0.0;
    info.ErrorCode            = 0;
  }
  //
  // Gather all Seeds to all processors for classification
  //
  // TODO : can we just use the same array here for send and receive
  ParticleVector allCandidates;
  if (this->UpdateNumPieces>1) {
    // Gather all seed particles to all processes
    this->TransmitReceiveParticles(candidates, allCandidates, false);
#ifndef NDEBUG
    numTested = static_cast<int>(allCandidates.size());
#endif
    vtkDebugMacro(<< "Local Particles " << numSeeds << " TransmitReceive Total " << numTested);
    // Test to see which ones belong to us
    this->TestParticles(allCandidates, LocalSeedPoints, LocalAssignedCount);
  }
  else {
#ifndef NDEBUG
    numTested = static_cast<int>(candidates.size());
#endif
    this->TestParticles(candidates, LocalSeedPoints, LocalAssignedCount);
  }
  int TotalAssigned = 0;
  this->Controller->Reduce(&LocalAssignedCount, &TotalAssigned, 1, vtkCommunicator::SUM_OP, 0);

  // Assign unique identifiers taking into account uneven distribution
  // across processes and seeds which were rejected
  this->AssignUniqueIds(LocalSeedPoints);
  //
  vtkDebugMacro(<< "Tested " << numTested << " LocallyAssigned " << LocalAssignedCount);
  if (this->UpdatePiece==0) {
    vtkDebugMacro(<< "Total Assigned to all processes " << TotalAssigned);
  }
}
//---------------------------------------------------------------------------
void vtkPTemporalStreamTracer::AssignUniqueIds(
  vtkTemporalStreamTracerNamespace::ParticleVector &LocalSeedPoints)
{
  if(!this->Controller)
    {
    return Superclass::AssignUniqueIds(LocalSeedPoints);
    }

  vtkIdType ParticleCountOffset = 0;
  vtkIdType numParticles = LocalSeedPoints.size();
  if (this->UpdateNumPieces>1) {
    vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast(
      this->Controller->GetCommunicator());
    if (com == 0) {
      vtkErrorMacro("MPICommunicator needed for this operation.");
      return;
    }
    // everyone starts with the master index
    com->Broadcast(&this->UniqueIdCounter, 1, 0);
//    vtkErrorMacro("UniqueIdCounter " << this->UniqueIdCounter);
    // setup arrays used by the AllGather call.
    std::vector<vtkIdType> recvNumParticles(this->UpdateNumPieces, 0);
    // Broadcast and receive count to/from all other processes.
    com->AllGather(&numParticles, &recvNumParticles[0], 1);
    // Each process is allocating a certain number.
    // start our indices from sum[0,this->UpdatePiece](numparticles)
    for (int i=0; i<this->UpdatePiece; ++i) {
      ParticleCountOffset += recvNumParticles[i];
    }
    for (vtkIdType i=0; i<numParticles; i++) {
      LocalSeedPoints[i].UniqueParticleId =
        this->UniqueIdCounter + ParticleCountOffset + i;
    }
    for (int i=0; i<this->UpdateNumPieces; ++i) {
      this->UniqueIdCounter += recvNumParticles[i];
    }
  }
  else {
    for (vtkIdType i=0; i<numParticles; i++) {
      LocalSeedPoints[i].UniqueParticleId =
        this->UniqueIdCounter + ParticleCountOffset + i;
    }
    this->UniqueIdCounter += numParticles;
  }
}
//---------------------------------------------------------------------------
void vtkPTemporalStreamTracer::TransmitReceiveParticles(
  ParticleVector &sending, ParticleVector &received, bool removeself)
{
  vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast(
    this->Controller->GetCommunicator());
  if (com == 0) {
    vtkErrorMacro("MPICommunicator needed for this operation.");
    return;
  }
  //
  // We must allocate buffers for all processor particles
  //
  vtkIdType OurParticles = sending.size();
  vtkIdType TotalParticles = 0;
  // setup arrays used by the AllGatherV call.
  std::vector<vtkIdType> recvLengths(this->UpdateNumPieces, 0);
  std::vector<vtkIdType> recvOffsets(this->UpdateNumPieces, 0);
  // Broadcast and receive size to/from all other processes.
  com->AllGather(&OurParticles, &recvLengths[0], 1);
  // Compute the displacements.
  const vtkIdType TypeSize = sizeof(ParticleInformation);
  for (int i=0; i<this->UpdateNumPieces; ++i)
  {
    //  << i << ": " << recvLengths[i] << "   ";
    recvOffsets[i] = TotalParticles*TypeSize;
    TotalParticles += recvLengths[i];
    recvLengths[i] *= TypeSize;
  }
  //  << '\n';
  // Allocate the space for all particles
  received.resize(TotalParticles);
  if (TotalParticles==0) return;
  // Gather the data from all procs.
  char *sendbuf = (char*) ((sending.size()>0) ? &(sending[0]) : NULL);
  char *recvbuf = (char*) (&(received[0]));
  com->AllGatherV(sendbuf, recvbuf,
    OurParticles*TypeSize, &recvLengths[0], &recvOffsets[0]);
  // Now all particles from all processors are in one big array
  // remove any from ourself that we have already tested
  if (removeself) {
    std::vector<ParticleInformation>::iterator first =
      received.begin() + recvOffsets[this->UpdatePiece]/TypeSize;
    std::vector<ParticleInformation>::iterator last =
      first + recvLengths[this->UpdatePiece]/TypeSize;
    received.erase(first, last);
  }
}
//---------------------------------------------------------------------------
int vtkPTemporalStreamTracer::RequestData(
  vtkInformation *request,
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  int rvalue = this->Superclass::RequestData(request, inputVector, outputVector);

  if(this->Controller)
    {
    this->Controller->Barrier();
    }

  return rvalue;
}
//---------------------------------------------------------------------------
void vtkPTemporalStreamTracer::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Controller: " << this->Controller << endl;
}
//---------------------------------------------------------------------------
void vtkPTemporalStreamTracer::AddParticleToMPISendList(ParticleInformation &info)
{
  double eps = (this->CurrentTimeSteps[1]-this->CurrentTimeSteps[0])/100;
  if (info.CurrentPosition.x[3]<(this->CurrentTimeSteps[0]-eps) ||
      info.CurrentPosition.x[3]>(this->CurrentTimeSteps[1]+eps)) {
    vtkDebugMacro(<< "Unexpected time value in MPISendList - expected ("
      << this->CurrentTimeSteps[0] << "-" << this->CurrentTimeSteps[1] << ") got "
      << info.CurrentPosition.x[3]);
  }
  if (this->MPISendList.capacity()<(this->MPISendList.size()+1)) {
    this->MPISendList.reserve(static_cast<int>(this->MPISendList.size()*1.5));
  }
  this->MPISendList.push_back(info);
}
<|endoftext|>


<commit_before>#include "pel_values.hpp"

#include <algorithm>

namespace openpower
{
namespace pels
{
namespace pel_values
{

// Note: The description fields will be filled in as part of the
//       PEL parser work.

/**
 * The possible values for the subsystem field  in the User Header.
 */
const PELValues subsystemValues = {{0x10, "processor", "TODO"},
                                   {0x11, "processor_fru", "TODO"},
                                   {0x12, "processor_chip", "TODO"},
                                   {0x13, "processor_unit", "TODO"},
                                   {0x14, "processor_bus", "TODO"},

                                   {0x20, "memory", "TODO"},
                                   {0x21, "memory_ctlr", "TODO"},
                                   {0x22, "memory_bus", "TODO"},
                                   {0x23, "memory_dimm", "TODO"},
                                   {0x24, "memory_fru", "TODO"},
                                   {0x25, "external_cache", "TODO"},

                                   {0x30, "io", "TODO"},
                                   {0x31, "io_hub", "TODO"},
                                   {0x32, "io_bridge", "TODO"},
                                   {0x33, "io_bus", "TODO"},
                                   {0x34, "io_processor", "TODO"},
                                   {0x35, "io_hub_other", "TODO"},
                                   {0x38, "phb", "TODO"},

                                   {0x40, "io_adapter", "TODO"},
                                   {0x41, "io_adapter_comm", "TODO"},
                                   {0x46, "io_device", "TODO"},
                                   {0x47, "io_device_dasd", "TODO"},
                                   {0x4C, "io_external_general", "TODO"},
                                   {0x4D, "io_external_workstation", "TODO"},
                                   {0x4E, "io_storage_mezz", "TODO"},

                                   {0x50, "cec_hardware", "TODO"},
                                   {0x51, "cec_sp_a", "TODO"},
                                   {0x52, "cec_sp_b", "TODO"},
                                   {0x53, "cec_node_controller", "TODO"},
                                   {0x55, "cec_vpd", "TODO"},
                                   {0x56, "cec_i2c", "TODO"},
                                   {0x57, "cec_chip_iface", "TODO"},
                                   {0x58, "cec_clocks", "TODO"},
                                   {0x59, "cec_op_panel", "TODO"},
                                   {0x5A, "cec_tod", "TODO"},
                                   {0x5B, "cec_storage_device", "TODO"},
                                   {0x5C, "cec_sp_hyp_iface", "TODO"},
                                   {0x5D, "cec_service_network", "TODO"},
                                   {0x5E, "cec_sp_hostboot_iface", "TODO"},

                                   {0x60, "power", "TODO"},
                                   {0x61, "power_supply", "TODO"},
                                   {0x62, "power_control_hw", "TODO"},
                                   {63, "power_fans", "TODO"},
                                   {0x64, "power_sequencer", "TODO"},

                                   {0x70, "others", "TODO"},
                                   {0x71, "other_hmc", "TODO"},
                                   {0x72, "other_test_tool", "TODO"},
                                   {0x73, "other_media", "TODO"},
                                   {0x74, "other_multiple_subsystems", "TODO"},
                                   {0x75, "other_na", "TODO"},
                                   {0x76, "other_info_src", "TODO"},

                                   {0x7A, "surv_hyp_lost_sp", "TODO"},
                                   {0x7B, "surv_sp_lost_hyp", "TODO"},
                                   {0x7C, "surv_sp_lost_hmc", "TODO"},
                                   {0x7D, "surv_hmc_lost_lpar", "TODO"},
                                   {0x7E, "surv_hmc_lost_bpa", "TODO"},
                                   {0x7F, "surv_hmc_lost_hmc", "TODO"},

                                   {0x80, "platform_firmware", "TODO"},
                                   {0x81, "sp_firmware", "TODO"},
                                   {0x82, "hyp_firmware", "TODO"},
                                   {0x83, "partition_firmware", "TODO"},
                                   {0x84, "slic_firmware", "TODO"},
                                   {0x85, "spcn_firmware", "TODO"},
                                   {0x86, "bulk_power_firmware_side_a", "TODO"},
                                   {0x87, "hmc_code_firmware", "TODO"},
                                   {0x88, "bulk_power_firmware_side_b", "TODO"},
                                   {0x89, "virtual_sp", "TODO"},
                                   {0x8A, "hostboot", "TODO"},
                                   {0x8B, "occ", "TODO"},
                                   {0x8D, "bmc_firmware", "TODO"},

                                   {0x90, "software", "TODO"},
                                   {0x91, "os_software", "TODO"},
                                   {0x92, "xpf_software", "TODO"},
                                   {0x93, "app_software", "TODO"},

                                   {0xA0, "ext_env", "TODO"},
                                   {0xA1, "input_power_source", "TODO"},
                                   {0xA2, "ambient_temp", "TODO"},
                                   {0xA3, "user_error", "TODO"},
                                   {0xA4, "corrosion", "TODO"}};

/**
 * The possible values for the severity field in the User Header.
 */
const PELValues severityValues = {
    {0x00, "non_error", "TODO"},

    {0x10, "recovered", "TODO"},
    {0x20, "predictive", "TODO"},
    {0x21, "predictive_degraded_perf", "TODO"},
    {0x22, "predictive_reboot", "TODO"},
    {0x23, "predictive_reboot_degraded", "TODO"},
    {0x24, "predictive_redundancy_loss", "TODO"},

    {0x40, "unrecoverable", "TODO"},
    {0x41, "unrecoverable_degraded_perf", "TODO"},
    {0x44, "unrecoverable_redundancy_loss", "TODO"},
    {0x45, "unrecoverable_redundancy_loss_perf", "TODO"},
    {0x48, "unrecoverable_loss_of_function", "TODO"},

    {0x50, "critical", "TODO"},
    {0x51, "critical_system_term", "TODO"},
    {0x52, "critical_imminent_failure", "TODO"},
    {0x53, "critical_partition_term", "TODO"},
    {0x54, "critical_partition_imminent_failure", "TODO"},

    {0x60, "diagnostic_error", "TODO"},
    {0x61, "diagnostic_error_incorrect_results", "TODO"},

    {0x71, "symptom_recovered", "TODO"},
    {0x72, "symptom_predictive", "TODO"},
    {0x74, "symptom_unrecoverable", "TODO"},
    {0x75, "symptom_critical", "TODO"},
    {0x76, "symptom_diag_err", "TODO"}};

/**
 * The possible values for the Event Type field in the User Header.
 */
const PELValues eventTypeValues = {{0x00, "na", "TODO"},
                                   {0x01, "misc_information_only", "TODO"},
                                   {0x02, "tracing_event", "TODO"},
                                   {0x08, "dump_notification", "TODO"}};

/**
 * The possible values for the Event Scope field in the User Header.
 */
const PELValues eventScopeValues = {
    {0x01, "single_partition", "TODO"},
    {0x02, "multiple_partitions", "TODO"},
    {0x03, "entire_platform", "TODO"},
    {0x04, "possibly_multiple_platforms", "TODO"}};

/**
 * The possible values for the Action Flags field in the User Header.
 */
const PELValues actionFlagsValues = {
    {0x8000, "service_action", "TODO"}, {0x4000, "hidden", "TODO"},
    {0x2000, "report", "TODO"},         {0x1000, "dont_report", "TODO"},
    {0x0800, "call_home", "TODO"},      {0x0100, "termination", "TODO"}};

/**
 * The possible values for the Callout Priority field in the SRC.
 */
const PELValues calloutPriorityValues = {
    {'H', "high", "TODO"},           {'M', "medium", "TODO"},
    {'A', "medium_group_a", "TODO"}, {'B', "medium_group_b", "TODO"},
    {'C', "medium_group_c", "TODO"}, {'L', "low", "TODO"}};

PELValues::const_iterator findByValue(uint32_t value, const PELValues& fields)
{
    return std::find_if(fields.begin(), fields.end(),
                        [value](const auto& entry) {
                            return value == std::get<fieldValuePos>(entry);
                        });
}

PELValues::const_iterator findByName(const std::string& name,
                                     const PELValues& fields)

{
    return std::find_if(fields.begin(), fields.end(),
                        [&name](const auto& entry) {
                            return name == std::get<registryNamePos>(entry);
                        });
}

} // namespace pel_values

} // namespace pels
} // namespace openpower
<commit_msg>PEL: Fix typo in subsystem ID list<commit_after>#include "pel_values.hpp"

#include <algorithm>

namespace openpower
{
namespace pels
{
namespace pel_values
{

// Note: The description fields will be filled in as part of the
//       PEL parser work.

/**
 * The possible values for the subsystem field  in the User Header.
 */
const PELValues subsystemValues = {{0x10, "processor", "TODO"},
                                   {0x11, "processor_fru", "TODO"},
                                   {0x12, "processor_chip", "TODO"},
                                   {0x13, "processor_unit", "TODO"},
                                   {0x14, "processor_bus", "TODO"},

                                   {0x20, "memory", "TODO"},
                                   {0x21, "memory_ctlr", "TODO"},
                                   {0x22, "memory_bus", "TODO"},
                                   {0x23, "memory_dimm", "TODO"},
                                   {0x24, "memory_fru", "TODO"},
                                   {0x25, "external_cache", "TODO"},

                                   {0x30, "io", "TODO"},
                                   {0x31, "io_hub", "TODO"},
                                   {0x32, "io_bridge", "TODO"},
                                   {0x33, "io_bus", "TODO"},
                                   {0x34, "io_processor", "TODO"},
                                   {0x35, "io_hub_other", "TODO"},
                                   {0x38, "phb", "TODO"},

                                   {0x40, "io_adapter", "TODO"},
                                   {0x41, "io_adapter_comm", "TODO"},
                                   {0x46, "io_device", "TODO"},
                                   {0x47, "io_device_dasd", "TODO"},
                                   {0x4C, "io_external_general", "TODO"},
                                   {0x4D, "io_external_workstation", "TODO"},
                                   {0x4E, "io_storage_mezz", "TODO"},

                                   {0x50, "cec_hardware", "TODO"},
                                   {0x51, "cec_sp_a", "TODO"},
                                   {0x52, "cec_sp_b", "TODO"},
                                   {0x53, "cec_node_controller", "TODO"},
                                   {0x55, "cec_vpd", "TODO"},
                                   {0x56, "cec_i2c", "TODO"},
                                   {0x57, "cec_chip_iface", "TODO"},
                                   {0x58, "cec_clocks", "TODO"},
                                   {0x59, "cec_op_panel", "TODO"},
                                   {0x5A, "cec_tod", "TODO"},
                                   {0x5B, "cec_storage_device", "TODO"},
                                   {0x5C, "cec_sp_hyp_iface", "TODO"},
                                   {0x5D, "cec_service_network", "TODO"},
                                   {0x5E, "cec_sp_hostboot_iface", "TODO"},

                                   {0x60, "power", "TODO"},
                                   {0x61, "power_supply", "TODO"},
                                   {0x62, "power_control_hw", "TODO"},
                                   {0x63, "power_fans", "TODO"},
                                   {0x64, "power_sequencer", "TODO"},

                                   {0x70, "others", "TODO"},
                                   {0x71, "other_hmc", "TODO"},
                                   {0x72, "other_test_tool", "TODO"},
                                   {0x73, "other_media", "TODO"},
                                   {0x74, "other_multiple_subsystems", "TODO"},
                                   {0x75, "other_na", "TODO"},
                                   {0x76, "other_info_src", "TODO"},

                                   {0x7A, "surv_hyp_lost_sp", "TODO"},
                                   {0x7B, "surv_sp_lost_hyp", "TODO"},
                                   {0x7C, "surv_sp_lost_hmc", "TODO"},
                                   {0x7D, "surv_hmc_lost_lpar", "TODO"},
                                   {0x7E, "surv_hmc_lost_bpa", "TODO"},
                                   {0x7F, "surv_hmc_lost_hmc", "TODO"},

                                   {0x80, "platform_firmware", "TODO"},
                                   {0x81, "sp_firmware", "TODO"},
                                   {0x82, "hyp_firmware", "TODO"},
                                   {0x83, "partition_firmware", "TODO"},
                                   {0x84, "slic_firmware", "TODO"},
                                   {0x85, "spcn_firmware", "TODO"},
                                   {0x86, "bulk_power_firmware_side_a", "TODO"},
                                   {0x87, "hmc_code_firmware", "TODO"},
                                   {0x88, "bulk_power_firmware_side_b", "TODO"},
                                   {0x89, "virtual_sp", "TODO"},
                                   {0x8A, "hostboot", "TODO"},
                                   {0x8B, "occ", "TODO"},
                                   {0x8D, "bmc_firmware", "TODO"},

                                   {0x90, "software", "TODO"},
                                   {0x91, "os_software", "TODO"},
                                   {0x92, "xpf_software", "TODO"},
                                   {0x93, "app_software", "TODO"},

                                   {0xA0, "ext_env", "TODO"},
                                   {0xA1, "input_power_source", "TODO"},
                                   {0xA2, "ambient_temp", "TODO"},
                                   {0xA3, "user_error", "TODO"},
                                   {0xA4, "corrosion", "TODO"}};

/**
 * The possible values for the severity field in the User Header.
 */
const PELValues severityValues = {
    {0x00, "non_error", "TODO"},

    {0x10, "recovered", "TODO"},
    {0x20, "predictive", "TODO"},
    {0x21, "predictive_degraded_perf", "TODO"},
    {0x22, "predictive_reboot", "TODO"},
    {0x23, "predictive_reboot_degraded", "TODO"},
    {0x24, "predictive_redundancy_loss", "TODO"},

    {0x40, "unrecoverable", "TODO"},
    {0x41, "unrecoverable_degraded_perf", "TODO"},
    {0x44, "unrecoverable_redundancy_loss", "TODO"},
    {0x45, "unrecoverable_redundancy_loss_perf", "TODO"},
    {0x48, "unrecoverable_loss_of_function", "TODO"},

    {0x50, "critical", "TODO"},
    {0x51, "critical_system_term", "TODO"},
    {0x52, "critical_imminent_failure", "TODO"},
    {0x53, "critical_partition_term", "TODO"},
    {0x54, "critical_partition_imminent_failure", "TODO"},

    {0x60, "diagnostic_error", "TODO"},
    {0x61, "diagnostic_error_incorrect_results", "TODO"},

    {0x71, "symptom_recovered", "TODO"},
    {0x72, "symptom_predictive", "TODO"},
    {0x74, "symptom_unrecoverable", "TODO"},
    {0x75, "symptom_critical", "TODO"},
    {0x76, "symptom_diag_err", "TODO"}};

/**
 * The possible values for the Event Type field in the User Header.
 */
const PELValues eventTypeValues = {{0x00, "na", "TODO"},
                                   {0x01, "misc_information_only", "TODO"},
                                   {0x02, "tracing_event", "TODO"},
                                   {0x08, "dump_notification", "TODO"}};

/**
 * The possible values for the Event Scope field in the User Header.
 */
const PELValues eventScopeValues = {
    {0x01, "single_partition", "TODO"},
    {0x02, "multiple_partitions", "TODO"},
    {0x03, "entire_platform", "TODO"},
    {0x04, "possibly_multiple_platforms", "TODO"}};

/**
 * The possible values for the Action Flags field in the User Header.
 */
const PELValues actionFlagsValues = {
    {0x8000, "service_action", "TODO"}, {0x4000, "hidden", "TODO"},
    {0x2000, "report", "TODO"},         {0x1000, "dont_report", "TODO"},
    {0x0800, "call_home", "TODO"},      {0x0100, "termination", "TODO"}};

/**
 * The possible values for the Callout Priority field in the SRC.
 */
const PELValues calloutPriorityValues = {
    {'H', "high", "TODO"},           {'M', "medium", "TODO"},
    {'A', "medium_group_a", "TODO"}, {'B', "medium_group_b", "TODO"},
    {'C', "medium_group_c", "TODO"}, {'L', "low", "TODO"}};

PELValues::const_iterator findByValue(uint32_t value, const PELValues& fields)
{
    return std::find_if(fields.begin(), fields.end(),
                        [value](const auto& entry) {
                            return value == std::get<fieldValuePos>(entry);
                        });
}

PELValues::const_iterator findByName(const std::string& name,
                                     const PELValues& fields)

{
    return std::find_if(fields.begin(), fields.end(),
                        [&name](const auto& entry) {
                            return name == std::get<registryNamePos>(entry);
                        });
}

} // namespace pel_values

} // namespace pels
} // namespace openpower
<|endoftext|>


<commit_before>//! \file
//! \brief Module aggregates routines that are control execution flow on the host platform.
//!
#ifndef THE_CORE_HOST_PLATFORM_EXECUTION_HPP_
#define THE_CORE_HOST_PLATFORM_EXECUTION_HPP_

#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <thread>
#include <chrono>

namespace ecl
{

//! \brief Aborts execution of currently running code. Never return.
static inline void abort()
{
    abort();
}

//! \brief Performs a dummy busy wait for specified amount of milliseconds.
//! \param ms number of milliseconds to wait.
//!
//! This function is useful for a short delays.
//!
//! \return None.
static inline void spin_wait(unsigned ms)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}

} // namespace ecl

#endif // THE_CORE_HOST_PLATFORM_EXECUTION_HPP_
<commit_msg>>#282 host: fix infinite recursion when abort() is called<commit_after>//! \file
//! \brief Module aggregates routines that are control execution flow on the host platform.
//!
#ifndef THE_CORE_HOST_PLATFORM_EXECUTION_HPP_
#define THE_CORE_HOST_PLATFORM_EXECUTION_HPP_

#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <thread>
#include <chrono>

namespace ecl
{

//! \brief Aborts execution of currently running code. Never return.
static inline void abort()
{
    ::abort();
}

//! \brief Performs a dummy busy wait for specified amount of milliseconds.
//! \param ms number of milliseconds to wait.
//!
//! This function is useful for a short delays.
//!
//! \return None.
static inline void spin_wait(unsigned ms)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}

} // namespace ecl

#endif // THE_CORE_HOST_PLATFORM_EXECUTION_HPP_
<|endoftext|>


<commit_before>#include "generated.hpp"
#include "impl_test_interface.hpp"
#include "checkpoint.hpp"
#include <boost/mpl/back.hpp>

namespace warpcoil
{
    namespace
    {
        template <class Handler, class TotalResult>
        struct wait_for_all_state
        {
            Handler handler;
            TotalResult total_result;
            std::size_t completed = 0;
            bool errored = false;

            template <class CompletionToken>
            wait_for_all_state(CompletionToken &&token)
                : handler(std::forward<CompletionToken>(token))
            {
            }
        };

        template <std::size_t Index, std::size_t MethodCount, class Method, class State>
        void start_method(Method &&method, std::shared_ptr<State> const &state)
        {
            method.start([state](boost::system::error_code ec, typename std::decay<Method>::type::result element)
                         {
                             if (!ec)
                             {
                                 std::get<Index>(state->total_result) = std::move(element);
                                 ++state->completed;
                                 if (state->completed == MethodCount)
                                 {
                                     state->handler(ec, std::move(state->total_result));
                                 }
                             }
                             else if (!Si::exchange(state->errored, true))
                             {
                                 state->handler(ec, {});
                             }
                         });
        }

        template <class State, class... Methods, std::size_t... Indices>
        void start_methods(std::shared_ptr<State> state, std::integer_sequence<std::size_t, Indices...>,
                           Methods &&... methods)
        {
            Si::unit dummy[] = {(start_method<Indices, sizeof...(Methods)>(methods, state), Si::unit())...};
            Si::ignore_unused_variable_warning(dummy);
        }

        template <class... Methods, class CompletionToken>
        auto wait_for_all(CompletionToken &&token, Methods &&... methods)
        {
            BOOST_STATIC_ASSERT(sizeof...(Methods) >= 1);
            using total_result = std::tuple<typename std::decay<Methods>::type::result...>;
            using handler_type = typename boost::asio::handler_type<decltype(token), void(boost::system::error_code,
                                                                                total_result)>::type;
            auto state =
                std::make_shared<wait_for_all_state<handler_type, total_result>>(std::forward<CompletionToken>(token));
            boost::asio::async_result<handler_type> result(state->handler);
            start_methods(std::move(state), std::make_integer_sequence<std::size_t, sizeof...(Methods)>(),
                          std::forward<Methods>(methods)...);
            return result.get();
        }

        template <class Callback>
        struct result_of_callback;

        template <class Result>
        struct result_of_callback<std::function<void(boost::system::error_code, Result)>>
        {
            using type = Result;
        };

        template <class Result, class Start>
        struct method_holder
        {
            using result = Result;
            Start start;
        };

        template <typename F, typename Tuple, size_t... S>
        decltype(auto) apply_tuple_impl(F &&fn, Tuple &&t, std::index_sequence<S...>)
        {
            return std::forward<F>(fn)(std::get<S>(std::forward<Tuple>(t))...);
        }

        template <typename F, typename Tuple>
        decltype(auto) apply_from_tuple(F &&fn, Tuple &&t)
        {
            std::size_t constexpr tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value;
            return apply_tuple_impl(std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>());
        }

        template <class Interface, class Parameter0, class... Parameters, class... Arguments>
        auto method(Interface &callee, void (Interface::*method_ptr)(Parameter0, Parameters...),
                    Arguments &&... arguments)
        {
            auto start = [&callee, method_ptr, arguments = std::make_tuple(std::forward<Arguments>(arguments)...) ](
                auto &&callback) mutable
            {
                auto &&callback2 = std::forward<decltype(callback)>(callback);
                apply_from_tuple(
                    [&callback2, &callee, method_ptr](auto &&... arguments)
                    {
                        (callee.*method_ptr)(std::forward<decltype(arguments)>(arguments)...,
                                             std::forward<decltype(callback2)>(callback2));
                    },
                    std::move(arguments));
            };
            using std_function_callback = typename boost::mpl::back<boost::mpl::vector<Parameters...>>::type;
            using result = typename result_of_callback<std_function_callback>::type;
            return method_holder<result, decltype(start)>{std::move(start)};
        }
    }
}

BOOST_AUTO_TEST_CASE(wait_for_all_1)
{
    warpcoil::impl_test_interface server;
    warpcoil::checkpoint got_result;
    got_result.enable();
    warpcoil::wait_for_all(
        [&got_result](boost::system::error_code ec, std::tuple<std::string> result)
        {
            got_result.enter();
            BOOST_CHECK(!ec);
            BOOST_CHECK_EQUAL("Hello123", std::get<0>(result));
        },
        warpcoil::method(server, &warpcoil::impl_test_interface::utf8, "Hello"));
}

BOOST_AUTO_TEST_CASE(wait_for_all_2)
{
    warpcoil::impl_test_interface server;
    warpcoil::checkpoint got_result;
    got_result.enable();
    warpcoil::wait_for_all(
        [&got_result](boost::system::error_code ec, std::tuple<std::string, std::uint16_t> result)
        {
            got_result.enter();
            BOOST_CHECK(!ec);
            BOOST_CHECK_EQUAL("Hello123", std::get<0>(result));
            BOOST_CHECK_EQUAL(123u, std::get<1>(result));
        },
        warpcoil::method(server, &warpcoil::impl_test_interface::utf8, "Hello"),
        warpcoil::method(server, &warpcoil::impl_test_interface::atypical_int, static_cast<boost::uint16_t>(123)));
}
<commit_msg>avoid decltype bug in GCC 4.9<commit_after>#include "generated.hpp"
#include "impl_test_interface.hpp"
#include "checkpoint.hpp"
#include <boost/mpl/back.hpp>

namespace warpcoil
{
    namespace
    {
        template <class Handler, class TotalResult>
        struct wait_for_all_state
        {
            Handler handler;
            TotalResult total_result;
            std::size_t completed = 0;
            bool errored = false;

            template <class CompletionToken>
            wait_for_all_state(CompletionToken &&token)
                : handler(std::forward<CompletionToken>(token))
            {
            }
        };

        template <std::size_t Index, std::size_t MethodCount, class Method, class State>
        void start_method(Method &&method, std::shared_ptr<State> const &state)
        {
            method.start([state](boost::system::error_code ec, typename std::decay<Method>::type::result element)
                         {
                             if (!ec)
                             {
                                 std::get<Index>(state->total_result) = std::move(element);
                                 ++state->completed;
                                 if (state->completed == MethodCount)
                                 {
                                     state->handler(ec, std::move(state->total_result));
                                 }
                             }
                             else if (!Si::exchange(state->errored, true))
                             {
                                 state->handler(ec, {});
                             }
                         });
        }

        template <class State, class... Methods, std::size_t... Indices>
        void start_methods(std::shared_ptr<State> state, std::integer_sequence<std::size_t, Indices...>,
                           Methods &&... methods)
        {
            Si::unit dummy[] = {(start_method<Indices, sizeof...(Methods)>(methods, state), Si::unit())...};
            Si::ignore_unused_variable_warning(dummy);
        }

        template <class... Methods, class CompletionToken>
        auto wait_for_all(CompletionToken &&token, Methods &&... methods)
        {
            BOOST_STATIC_ASSERT(sizeof...(Methods) >= 1);
            using total_result = std::tuple<typename std::decay<Methods>::type::result...>;
            using handler_type = typename boost::asio::handler_type<decltype(token), void(boost::system::error_code,
                                                                                total_result)>::type;
            auto state =
                std::make_shared<wait_for_all_state<handler_type, total_result>>(std::forward<CompletionToken>(token));
            boost::asio::async_result<handler_type> result(state->handler);
            start_methods(std::move(state), std::make_integer_sequence<std::size_t, sizeof...(Methods)>(),
                          std::forward<Methods>(methods)...);
            return result.get();
        }

        template <class Callback>
        struct result_of_callback;

        template <class Result>
        struct result_of_callback<std::function<void(boost::system::error_code, Result)>>
        {
            using type = Result;
        };

        template <class Result, class Start>
        struct method_holder
        {
            using result = Result;
            Start start;
        };

        template <typename F, typename Tuple, size_t... S>
        decltype(auto) apply_tuple_impl(F &&fn, Tuple &&t, std::index_sequence<S...>)
        {
            return std::forward<F>(fn)(std::get<S>(std::forward<Tuple>(t))...);
        }

        template <typename F, typename Tuple>
        decltype(auto) apply_from_tuple(F &&fn, Tuple &&t)
        {
            std::size_t constexpr tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value;
            return apply_tuple_impl(std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>());
        }

        template <class Interface, class Parameter0, class... Parameters, class... Arguments>
        auto method(Interface &callee, void (Interface::*method_ptr)(Parameter0, Parameters...),
                    Arguments &&... arguments)
        {
            auto start = [&callee, method_ptr, arguments = std::make_tuple(std::forward<Arguments>(arguments)...) ](
                auto &&callback) mutable
            {
                using callback_type = decltype(callback);
                apply_from_tuple(
                    [&callback, &callee, method_ptr](auto &&... arguments)
                    {
                        (callee.*method_ptr)(std::forward<decltype(arguments)>(arguments)...,
                                             std::forward<callback_type>(callback));
                    },
                    std::move(arguments));
            };
            using std_function_callback = typename boost::mpl::back<boost::mpl::vector<Parameters...>>::type;
            using result = typename result_of_callback<std_function_callback>::type;
            return method_holder<result, decltype(start)>{std::move(start)};
        }
    }
}

BOOST_AUTO_TEST_CASE(wait_for_all_1)
{
    warpcoil::impl_test_interface server;
    warpcoil::checkpoint got_result;
    got_result.enable();
    warpcoil::wait_for_all(
        [&got_result](boost::system::error_code ec, std::tuple<std::string> result)
        {
            got_result.enter();
            BOOST_CHECK(!ec);
            BOOST_CHECK_EQUAL("Hello123", std::get<0>(result));
        },
        warpcoil::method(server, &warpcoil::impl_test_interface::utf8, "Hello"));
}

BOOST_AUTO_TEST_CASE(wait_for_all_2)
{
    warpcoil::impl_test_interface server;
    warpcoil::checkpoint got_result;
    got_result.enable();
    warpcoil::wait_for_all(
        [&got_result](boost::system::error_code ec, std::tuple<std::string, std::uint16_t> result)
        {
            got_result.enter();
            BOOST_CHECK(!ec);
            BOOST_CHECK_EQUAL("Hello123", std::get<0>(result));
            BOOST_CHECK_EQUAL(123u, std::get<1>(result));
        },
        warpcoil::method(server, &warpcoil::impl_test_interface::utf8, "Hello"),
        warpcoil::method(server, &warpcoil::impl_test_interface::atypical_int, static_cast<boost::uint16_t>(123)));
}
<|endoftext|>


<commit_before>// @(#)root/ged:$Name:  $:$Id: TGedFrame.cxx,v 1.15 2006/09/26 08:05:44 rdm Exp $
// Author: Ilka Antcheva   10/05/04

/*************************************************************************
 * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
//  TGedFrame                                                           //
//                                                                      //
//  Base frame for implementing GUI - a service class.                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGedFrame.h"
#include "TGedEditor.h"
#include "TGClient.h"
#include "TG3DLine.h"
#include "TCanvas.h"
#include "TGLabel.h"
#include "TGToolTip.h"
#include "TGCanvas.h"
#include "TGScrollBar.h"
#include <snprintf.h>

ClassImp(TGedFrame)

//______________________________________________________________________________
TGedFrame::TGedFrame(const TGWindow *p, Int_t width,
                     Int_t height, UInt_t options, Pixel_t back)
      : TGCompositeFrame(p, width, height, options, back),
        fInit(kTRUE),
        fGedEditor(0),
        fModelClass(0),
        fLayoutHints(0),
        fAvoidSignal(kFALSE),
        fExtraTabs(0),
        fPriority(50)
{
   // Constructor of the base GUI attribute frame.

   fName = "";
   fGedEditor = TGedEditor::GetFrameCreator();
   SetCleanup(kDeepCleanup);
}

//______________________________________________________________________________
TGedFrame::~TGedFrame()
{
   // Destructor of the base GUI attribute frame.

   if (fExtraTabs) {
      TGedSubFrame* sf;
      TIter next(fExtraTabs);
      while ((sf = (TGedSubFrame*) next()) != 0) {
         delete sf->fFrame;
         fExtraTabs->Remove(sf);
         delete sf;
      }
      delete fExtraTabs;
   }
   delete fLayoutHints;

   // Destructor of TGCompositeFrame will do the rest.
}

//______________________________________________________________________________
void TGedFrame::Update()
{
   // Update the current pad when an attribute is changed via GUI.

   fGedEditor->Update(this);
}

//______________________________________________________________________________
Option_t *TGedFrame::GetDrawOption() const
{
   // Get draw options of the selected object.

   if (!fGedEditor->GetPad()) return "";

   TListIter next(fGedEditor->GetPad()->GetListOfPrimitives());
   TObject *obj;
   while ((obj = next())) {
      if (obj == fGedEditor->GetModel()) return next.GetOption();
   }
   return "";
}

//______________________________________________________________________________
TGLayoutHints* TGedFrame::GetLayoutHints()
{
   // Get layout hints with which is added to TGedEditor frame.

   if (fLayoutHints == 0){
      fLayoutHints = new TGLayoutHints(kLHintsTop | kLHintsExpandX, 2, 2, 2, 2);
      fLayoutHints->AddReference();
   }
   return fLayoutHints;
}

//______________________________________________________________________________
void TGedFrame::MakeTitle(const char *title)
{
   // Create attribute frame title.

   TGCompositeFrame *f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame |
                                                              kLHintsExpandX |
                                                              kFixedWidth |
                                                              kOwnBackground);
   f1->AddFrame(new TGLabel(f1, title),
                new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0));
   f1->AddFrame(new TGHorizontal3DLine(f1),
                new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7));
   AddFrame(f1, new TGLayoutHints(kLHintsTop, 0, 0, 2, 0));
}

//______________________________________________________________________________
void TGedFrame::AddExtraTab(TGedSubFrame* sf)
{
  // Adds tab container to list of extra tabs.

   if (fExtraTabs == 0) fExtraTabs = new TList();
   fExtraTabs->Add(sf);
   sf->fFrame->SetCleanup(kDeepCleanup);
}

//______________________________________________________________________________
TGVerticalFrame* TGedFrame::CreateEditorTabSubFrame(const Text_t* name)
{
   // Create a vertical frame to be used by 'owner' in extra tab 'name'.
   // The new frame is registered into the sub-frame list.

   TGCompositeFrame* tabcont  = fGedEditor->GetEditorTab(name);

   TGVerticalFrame* newframe = new TGVerticalFrame(tabcont);
   AddExtraTab(new TGedFrame::TGedSubFrame(TString(name), newframe));
   return newframe;
}

//______________________________________________________________________________
void TGedFrame::Refresh(TObject* model)
{
   // Refresh the GUI info about the object attributes.

   SetModel(model);
}

//______________________________________________________________________________
void TGedFrame::SetDrawOption(Option_t *option)
{
   // Set drawing option for object. This option only affects
   // the drawing style and is stored in the option field of the
   // TObjOptLink supporting a TPad's primitive list (TList).

   if (!fGedEditor->GetPad() || !option) return;

   TListIter next(fGedEditor->GetPad()->GetListOfPrimitives());
   delete fGedEditor->GetPad()->FindObject("Tframe");
   TObject *obj;
   while ((obj = next())) {
      if (obj == fGedEditor->GetModel()) {
         next.SetOption(option);
         fGedEditor->GetPad()->Modified();
         fGedEditor->GetPad()->Update();
         return;
      }
   }
}

//______________________________________________________________________________
void TGedFrame::ActivateBaseClassEditors(TClass* cl)
{
   // Provide list of editors for base-classes.
   // In this class we return all classed with editors found via recursive
   // descent into list of base classes.
   // Override to control which editors are actually shown (see TH2Editor).

   // printf("%s::FillListOfBaseEditors %s\n", IsA()->GetName(), cl->GetName());
   if (cl->GetListOfBases()->IsEmpty() == kFALSE) {
      fGedEditor->ActivateEditors(cl->GetListOfBases(), kTRUE);
   }
}

//______________________________________________________________________________
TGedNameFrame::TGedNameFrame(const TGWindow *p, Int_t width,
                              Int_t height, UInt_t options, Pixel_t back)
   : TGedFrame(p, width, height, options | kVerticalFrame, back)
{
   // Create the frame containing the selected object name.

   fPriority = 0;

   f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame |
                                            kFixedWidth      |
                                            kOwnBackground);
   f1->AddFrame(new TGLabel(f1,"Name"),
                new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0));
   f1->AddFrame(new TGHorizontal3DLine(f1),
                new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7));
   AddFrame(f1, new TGLayoutHints(kLHintsTop));

   f2 = new TGCompositeFrame(this, 80, 20, kHorizontalFrame | kFixedWidth);
   fLabel = new TGLabel(f2, "");
   f2->AddFrame(fLabel, new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0));
   AddFrame(f2, new TGLayoutHints(kLHintsTop, 1, 1, 0, 0));

   // Set red color for the name.
   Pixel_t color;
   gClient->GetColorByName("#ff0000", color);
   fLabel->SetTextColor(color, kFALSE);

   // create tool tip with delay 300 ms
   fTip = new TGToolTip(fClient->GetDefaultRoot(), this, "TGedNameFrame", 500);

   AddInput(kEnterWindowMask | kLeaveWindowMask | kKeyPressMask | kButtonPressMask);
}

//______________________________________________________________________________
TGedNameFrame::~TGedNameFrame()
{
   // Destructor.

   delete fTip;
}

//______________________________________________________________________________
Bool_t TGedNameFrame::HandleCrossing(Event_t *event)
{
   // Handle mouse crossing event for tooltip.

   if (event->fType == kEnterNotify)
      fTip->Reset();
   else
      fTip->Hide();

   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGedNameFrame::HandleButton(Event_t */*event*/)
{
   // Handle mouse button event.

   if (fTip) fTip->Hide();

   return kFALSE;
}

//______________________________________________________________________________
void TGedNameFrame::SetModel(TObject* obj)
{
   // Sets text for the label.

   TString string;

   if (obj == 0) {
      fLabel->SetText(new TGString("Object not selected"));
      return;
   }
   string.Append(obj->GetName());
   string.Append("::");
   string.Append(obj->ClassName());

   fLabel->SetText(new TGString(string));
   string = Form("Name: '%s'; Title: '%s'; Class: '%s'", obj->GetName(), obj->GetTitle(), obj->ClassName());
   fTip->SetText(string);

   // Resize label-frame to a reasonable width.
   {
      TGCanvas     *canvas = fGedEditor->GetTGCanvas();
      TGVScrollBar *vsb    = canvas->GetVScrollbar();

      Int_t hscrollw = (vsb && vsb->IsMapped()) ? vsb->GetWidth() : 0;
      Int_t labwidth = TMath::Min(fLabel->GetDefaultSize().fWidth,
                                  canvas->GetWidth() - 10 - hscrollw);
      f2->SetWidth(TMath::Max(labwidth, 80));
   }
}
<commit_msg>From Matevz: patch that fixes the double deletion of TGedNameFrame's layout hints.<commit_after>// @(#)root/ged:$Name:  $:$Id: TGedFrame.cxx,v 1.16 2006/09/27 08:45:42 rdm Exp $
// Author: Ilka Antcheva   10/05/04

/*************************************************************************
 * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
//  TGedFrame                                                           //
//                                                                      //
//  Base frame for implementing GUI - a service class.                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGedFrame.h"
#include "TGedEditor.h"
#include "TGClient.h"
#include "TG3DLine.h"
#include "TCanvas.h"
#include "TGLabel.h"
#include "TGToolTip.h"
#include "TGCanvas.h"
#include "TGScrollBar.h"
#include <snprintf.h>

ClassImp(TGedFrame)

//______________________________________________________________________________
TGedFrame::TGedFrame(const TGWindow *p, Int_t width,
                     Int_t height, UInt_t options, Pixel_t back)
      : TGCompositeFrame(p, width, height, options, back),
        fInit(kTRUE),
        fGedEditor(0),
        fModelClass(0),
        fLayoutHints(0),
        fAvoidSignal(kFALSE),
        fExtraTabs(0),
        fPriority(50)
{
   // Constructor of the base GUI attribute frame.

   fName = "";
   fGedEditor = TGedEditor::GetFrameCreator();
   SetCleanup(kDeepCleanup);
}

//______________________________________________________________________________
TGedFrame::~TGedFrame()
{
   // Destructor of the base GUI attribute frame.

   if (fExtraTabs) {
      TGedSubFrame* sf;
      TIter next(fExtraTabs);
      while ((sf = (TGedSubFrame*) next()) != 0) {
         delete sf->fFrame;
         fExtraTabs->Remove(sf);
         delete sf;
      }
      delete fExtraTabs;
   }
   delete fLayoutHints;

   // Destructor of TGCompositeFrame will do the rest.
}

//______________________________________________________________________________
void TGedFrame::Update()
{
   // Update the current pad when an attribute is changed via GUI.

   fGedEditor->Update(this);
}

//______________________________________________________________________________
Option_t *TGedFrame::GetDrawOption() const
{
   // Get draw options of the selected object.

   if (!fGedEditor->GetPad()) return "";

   TListIter next(fGedEditor->GetPad()->GetListOfPrimitives());
   TObject *obj;
   while ((obj = next())) {
      if (obj == fGedEditor->GetModel()) return next.GetOption();
   }
   return "";
}

//______________________________________________________________________________
TGLayoutHints* TGedFrame::GetLayoutHints()
{
   // Get layout hints with which is added to TGedEditor frame.

   if (fLayoutHints == 0){
      fLayoutHints = new TGLayoutHints(kLHintsTop | kLHintsExpandX, 2, 2, 2, 2);
      fLayoutHints->AddReference();
   }
   return fLayoutHints;
}

//______________________________________________________________________________
void TGedFrame::MakeTitle(const char *title)
{
   // Create attribute frame title.

   TGCompositeFrame *f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame |
                                                              kLHintsExpandX |
                                                              kFixedWidth |
                                                              kOwnBackground);
   f1->AddFrame(new TGLabel(f1, title),
                new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0));
   f1->AddFrame(new TGHorizontal3DLine(f1),
                new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7));
   AddFrame(f1, new TGLayoutHints(kLHintsTop, 0, 0, 2, 0));
}

//______________________________________________________________________________
void TGedFrame::AddExtraTab(TGedSubFrame* sf)
{
  // Adds tab container to list of extra tabs.

   if (fExtraTabs == 0) fExtraTabs = new TList();
   fExtraTabs->Add(sf);
   sf->fFrame->SetCleanup(kDeepCleanup);
}

//______________________________________________________________________________
TGVerticalFrame* TGedFrame::CreateEditorTabSubFrame(const Text_t* name)
{
   // Create a vertical frame to be used by 'owner' in extra tab 'name'.
   // The new frame is registered into the sub-frame list.

   TGCompositeFrame* tabcont  = fGedEditor->GetEditorTab(name);

   TGVerticalFrame* newframe = new TGVerticalFrame(tabcont);
   AddExtraTab(new TGedFrame::TGedSubFrame(TString(name), newframe));
   return newframe;
}

//______________________________________________________________________________
void TGedFrame::Refresh(TObject* model)
{
   // Refresh the GUI info about the object attributes.

   SetModel(model);
}

//______________________________________________________________________________
void TGedFrame::SetDrawOption(Option_t *option)
{
   // Set drawing option for object. This option only affects
   // the drawing style and is stored in the option field of the
   // TObjOptLink supporting a TPad's primitive list (TList).

   if (!fGedEditor->GetPad() || !option) return;

   TListIter next(fGedEditor->GetPad()->GetListOfPrimitives());
   delete fGedEditor->GetPad()->FindObject("Tframe");
   TObject *obj;
   while ((obj = next())) {
      if (obj == fGedEditor->GetModel()) {
         next.SetOption(option);
         fGedEditor->GetPad()->Modified();
         fGedEditor->GetPad()->Update();
         return;
      }
   }
}

//______________________________________________________________________________
void TGedFrame::ActivateBaseClassEditors(TClass* cl)
{
   // Provide list of editors for base-classes.
   // In this class we return all classed with editors found via recursive
   // descent into list of base classes.
   // Override to control which editors are actually shown (see TH2Editor).

   // printf("%s::FillListOfBaseEditors %s\n", IsA()->GetName(), cl->GetName());
   if (cl->GetListOfBases()->IsEmpty() == kFALSE) {
      fGedEditor->ActivateEditors(cl->GetListOfBases(), kTRUE);
   }
}

//______________________________________________________________________________
TGedNameFrame::TGedNameFrame(const TGWindow *p, Int_t width,
                              Int_t height, UInt_t options, Pixel_t back)
   : TGedFrame(p, width, height, options | kVerticalFrame, back)
{
   // Create the frame containing the selected object name.

   fPriority = 0;

   f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame |
                                            kFixedWidth      |
                                            kOwnBackground);
   f1->AddFrame(new TGLabel(f1,"Name"),
                new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0));
   f1->AddFrame(new TGHorizontal3DLine(f1),
                new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7));
   AddFrame(f1, new TGLayoutHints(kLHintsTop));

   f2 = new TGCompositeFrame(this, 80, 20, kHorizontalFrame | kFixedWidth);
   fLabel = new TGLabel(f2, "");
   f2->AddFrame(fLabel, new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0));
   AddFrame(f2, new TGLayoutHints(kLHintsTop, 1, 1, 0, 0));

   // Set red color for the name.
   Pixel_t color;
   gClient->GetColorByName("#ff0000", color);
   fLabel->SetTextColor(color, kFALSE);

   // create tool tip with delay 300 ms
   fTip = new TGToolTip(fClient->GetDefaultRoot(), this, "TGedNameFrame", 500);

   AddInput(kEnterWindowMask | kLeaveWindowMask | kKeyPressMask | kButtonPressMask);
}

//______________________________________________________________________________
TGedNameFrame::~TGedNameFrame()
{
   // Destructor.

   fLayoutHints = 0; // will be deleted via deep-cleanup of tab-containers
   delete fTip;
}

//______________________________________________________________________________
Bool_t TGedNameFrame::HandleCrossing(Event_t *event)
{
   // Handle mouse crossing event for tooltip.

   if (event->fType == kEnterNotify)
      fTip->Reset();
   else
      fTip->Hide();

   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGedNameFrame::HandleButton(Event_t */*event*/)
{
   // Handle mouse button event.

   if (fTip) fTip->Hide();

   return kFALSE;
}

//______________________________________________________________________________
void TGedNameFrame::SetModel(TObject* obj)
{
   // Sets text for the label.

   TString string;

   if (obj == 0) {
      fLabel->SetText(new TGString("Object not selected"));
      return;
   }
   string.Append(obj->GetName());
   string.Append("::");
   string.Append(obj->ClassName());

   fLabel->SetText(new TGString(string));
   string = Form("Name: '%s'; Title: '%s'; Class: '%s'", obj->GetName(), obj->GetTitle(), obj->ClassName());
   fTip->SetText(string);

   // Resize label-frame to a reasonable width.
   {
      TGCanvas     *canvas = fGedEditor->GetTGCanvas();
      TGVScrollBar *vsb    = canvas->GetVScrollbar();

      Int_t hscrollw = (vsb && vsb->IsMapped()) ? vsb->GetWidth() : 0;
      Int_t labwidth = TMath::Min(fLabel->GetDefaultSize().fWidth,
                                  canvas->GetWidth() - 10 - hscrollw);
      f2->SetWidth(TMath::Max(labwidth, 80));
   }
}
<|endoftext|>


<commit_before>

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

    ^XNǗ(?)

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

#include <cassert>
#include <algorithm>
#include <typeinfo>
#include "task.h"

namespace GTF
{
    using namespace std;

    CTaskManager::CTaskManager()
    {
        exNext = nullptr;

        // _~[f[^}
		const auto it = tasks.emplace(tasks.end(), make_shared<CTaskBase>());
		ex_stack.emplace(exNext, it);
    }

    void CTaskManager::Destroy()
    {
        TaskList::iterator i, ied;

        //ʏ^XNTerminate
        i = tasks.begin();
        ied = tasks.end();
        for (; i != ied; ++i){
            (*i)->Terminate();
        }
        tasks.clear();

        //obNOEh^XNTerminate
        i = bg_tasks.begin();
        ied = bg_tasks.end();
        for (; i != ied; ++i){
            (*i)->Terminate();
        }
        bg_tasks.clear();

        //r^XNTerminate
        while (ex_stack.size() != 0 && ex_stack.top().value){
            ex_stack.top().value->Terminate();
            ex_stack.pop();
        }
    }

    CTaskManager::TaskPtr CTaskManager::AddTask(CTaskBase *newTask)
    {
        assert(newTask);

        CExclusiveTaskBase *pext = dynamic_cast<CExclusiveTaskBase*>(newTask);
        if (pext){
            //r^XNƂAdd
            return AddTask(pext);
        }

        if (newTask->GetID() != 0){
            RemoveTaskByID(newTask->GetID());
        }

        CBackgroundTaskBase *pbgt = dynamic_cast<CBackgroundTaskBase*>(newTask);
        if (pbgt){
            //풓^XNƂAdd
            return AddTask(pbgt);
        }

        //ʏ^XNƂAdd
        tasks.emplace_back(newTask);
        auto& pnew = tasks.back();
        newTask->Initialize();
        if (newTask->GetID() != 0)
            indices[newTask->GetID()] = pnew;
        if (pnew->GetDrawPriority() >= 0)
            ex_stack.top().drawList.emplace(pnew->GetDrawPriority(), pnew);
        return pnew;
    }

    CTaskManager::ExTaskPtr CTaskManager::AddTask(CExclusiveTaskBase *newTask)
    {
        //r^XNƂAdd
        //ExecuteȂ̂ŁA|C^ۑ̂
        if (exNext){
            OutputLog("ALERT r^XN2ȏAddꂽ : %s / %s",
                typeid(*exNext).name(), typeid(*newTask).name());
        }
        exNext = shared_ptr<CExclusiveTaskBase>(newTask);

        return exNext;
    }

    CTaskManager::BgTaskPtr CTaskManager::AddTask(CBackgroundTaskBase *newTask)
    {
        if (newTask->GetID() != 0){
            RemoveTaskByID(newTask->GetID());
        }

        bg_tasks.emplace_back(newTask);
        // bIȌ^ϊ
        auto& pbgt = static_pointer_cast<CBackgroundTaskBase>(bg_tasks.back());
        assert(dynamic_pointer_cast<CBackgroundTaskBase>(pbgt).get());

        //풓^XNƂAdd
        pbgt->Initialize();
        if (newTask->GetID() != 0)
            bg_indices[newTask->GetID()] = pbgt;
        if (pbgt->GetDrawPriority() >= 0)
            drawListBG.emplace(pbgt->GetDrawPriority(), pbgt);
        return pbgt;
    }

    void CTaskManager::Execute(double elapsedTime)
    {
        // ^XNExecute
        auto taskExecute = [this, elapsedTime](TaskList::iterator i, TaskList::iterator ied){
            deque<TaskList::iterator> deleteList;
            deque<TaskList::iterator>::iterator idl, idl_ed;

            for (; i != ied; ++i){
#ifdef _CATCH_WHILE_EXEC
                try{
#endif
                    if ((*i)->Execute(elapsedTime) == false)
                    {
                        deleteList.push_back(i);
                    }
#ifdef _CATCH_WHILE_EXEC
        }
                catch (...){
                    if (*i == NULL)OutputLog("catch while execute1 : NULL", SYSLOG_ERROR);
                    else OutputLog("catch while execute1 : %X , %s", *i, typeid(**i).name());
                    break;
                }
#endif
    }
            //^XNfalseԂ̂
            if (deleteList.size() != 0){
                idl = deleteList.begin();
                idl_ed = deleteList.end();
                for (; idl != idl_ed; ++idl){
                    i = *idl;
                    (*i)->Terminate();
                    tasks.erase(i);
                }
            }
        };

#ifdef ARRAYBOUNDARY_DEBUG
        if(!AfxCheckMemory()){
            OutputLog("AfxCheckMemory() failed");
            return;
        }
#endif

        //r^XNAtop̂Execute
        assert(ex_stack.size() != 0);
        shared_ptr<CExclusiveTaskBase> exTsk = ex_stack.top().value;

        if (exTsk)
        {
            bool ex_ret = true;
#ifdef _CATCH_WHILE_EXEC
            try{
#endif
                ex_ret = exTsk->Execute(elapsedTime);
#ifdef _CATCH_WHILE_EXEC
            }catch(...){
                if (ex_stack.top() == NULL)OutputLog("catch while execute3 : NULL", SYSLOG_ERROR);
                else OutputLog("catch while execute3 : %X %s",ex_stack.top(),typeid(*ex_stack.top()).name());
            }
#endif

            if (!ex_ret)
            {
                if (!exNext){
                    //ݔr^XN̕ύX

#ifdef _CATCH_WHILE_EXEC
                    try{
#endif

                        //ʏ^XNSĔj
                        CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos);

#ifdef _CATCH_WHILE_EXEC
                    }catch(...){
                        if ((*i) == NULL)OutputLog("catch while terminate1 : NULL", SYSLOG_ERROR);
                        else OutputLog("catch while terminate1 : %X %s", (*i), typeid(*(*i)).name());
                    }
#endif

                    unsigned int prvID;

#ifdef _CATCH_WHILE_EXEC
                    try{
#endif

                        //ݔr^XN̔j
                        prvID = exTsk->GetID();
                        exTsk->Terminate();
                        exTsk = nullptr;
                        ex_stack.pop();

#ifdef _CATCH_WHILE_EXEC
                    }catch(...){
                        if (exTsk == NULL)OutputLog("catch while terminate2 : NULL", SYSLOG_ERROR);
                        else OutputLog("catch while terminate : %X %s", exTsk, typeid(*exTsk).name());
                    }
#endif

#ifdef _CATCH_WHILE_EXEC
                    try{
#endif

                        //̔r^XNActivate
                        assert(ex_stack.size() != 0);
                        exTsk = ex_stack.top().value;
                        if (exTsk)
                            exTsk->Activate(prvID);

#ifdef _CATCH_WHILE_EXEC
                    }catch(...){
                        if (exTsk == NULL)OutputLog("catch while activate : NULL", SYSLOG_ERROR);
                        else OutputLog("catch while activate : %X %s", exTsk, typeid(*exTsk).name());
                    }
#endif

                    return;
                }
            }
        }

        //ʏ^XNExecute
        assert(!ex_stack.empty());
        taskExecute(ex_stack.top().SubTaskStartPos, tasks.end());

        //풓^XNExecute
        taskExecute(bg_tasks.begin(), bg_tasks.end());

        // V^XNꍇ
        if (exNext){
            //ݔr^XNInactivate
            assert(ex_stack.size() != 0);
            auto& exTsk = ex_stack.top().value;
            if (exTsk && !exTsk->Inactivate(exNext->GetID())){
                //ʏ^XNSĔj
                CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos);

                exTsk->Terminate();
                ex_stack.pop();
            }

            //Addꂽ^XNInitializeē˂
            const auto it = tasks.emplace(tasks.end(), make_shared<CTaskBase>());				// _~[^XN}
            ex_stack.emplace(move(exNext), it);
            ex_stack.top().value->Initialize();

            exNext = nullptr;
        }
    }

    void CTaskManager::Draw()
    {
        TaskList::iterator i, ied;
        shared_ptr<CExclusiveTaskBase> pex;
        auto& drawList = ex_stack.top().drawList;

        //r^XN擾
        assert(ex_stack.size() != 0);
        if (ex_stack.top().value && ex_stack.top().value->GetDrawPriority() >= 0){
            pex = ex_stack.top().value;
        }

        auto iv = drawList.begin();
        auto iedv = pex ? drawList.upper_bound(pex->GetDrawPriority()) : drawList.end();
        auto ivBG = drawListBG.begin();
        const auto iedvBG = drawListBG.end();
        auto DrawAndProceed = [&](DrawPriorityMap::iterator& iv)
        {
                    auto is = iv->second.lock();

                    if (is)
                    {
                        is->Draw();
                        ++iv;
                    }
                    else
                        drawList.erase(iv++);
        };
        auto DrawAll = [&]()		// `֐
        {
            while (iv != iedv)
            {
#ifdef _CATCH_WHILE_RENDER
                try{
#endif
                    while (ivBG != iedvBG && ivBG->first <= iv->first)
                        DrawAndProceed(ivBG);
                    DrawAndProceed(iv);
#ifdef _CATCH_WHILE_RENDER
                }catch(...){
                    OutputLog("catch while draw : %X %s", *iv, typeid(*(*iv).lock()).name());
                }
#endif
            }
        };
        //`
        DrawAll();

        // r^XNDraw
        if (pex)
            pex->Draw();

        //`
        assert(iv == iedv);
        iedv = drawList.end();
        DrawAll();

        // c풓^XN
        while (ivBG != iedvBG)
            DrawAndProceed(ivBG);
    }

    void CTaskManager::RemoveTaskByID(unsigned int id)
    {
        TaskList::iterator i, ied;

        //ʏ^XN`FbN
        if (indices.find(id) != indices.end())
        {
            i = tasks.begin();
            ied = tasks.end();
            for (; i != ied; ++i){
                if (id == (*i)->GetID()){
                    (*i)->Terminate();
                    tasks.erase(i);
                    return;
                }
            }
        }

        //obNOEh^XNTerminate
        if (bg_indices.find(id) != bg_indices.end())
        {
            i = bg_tasks.begin();
            ied = bg_tasks.end();
            for (; i != ied; ++i){
                if (id == (*i)->GetID()){
                    (*i)->Terminate();
                    bg_tasks.erase(i);
                    return;
                }
            }
        }
    }

    //ŏʂɂGNXN[Vu^XNQg
    CTaskManager::ExTaskPtr CTaskManager::GetTopExclusiveTask()
    {
        return ex_stack.top().value;
    }

    //wID̔r^XN܂Terminate/pop
    void CTaskManager::RevertExclusiveTaskByID(unsigned int id)
    {
        bool act = false;
        unsigned int previd = 0;

        assert(ex_stack.size() != 0);
        while (ex_stack.top().value){
            const shared_ptr<CExclusiveTaskBase>& task = ex_stack.top().value;
            if (task->GetID() == id){
                if (act){
                    task->Activate(previd);
                }
                return;
            }
            else{
                previd = task->GetID();
                act = true;
                CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos);
                task->Terminate();
                ex_stack.pop();
                assert(ex_stack.size() != 0);
            }
        }
    }

    //ʏ^XNꕔj
    void CTaskManager::CleanupPartialSubTasks(TaskList::iterator it_task)
    {
        TaskList::iterator i, ied;

        i = it_task;
        ied = tasks.end();
        for (; i != ied; ++i){
            shared_ptr<CTaskBase>& delTgt = (*i);
            delTgt->Terminate();
        }
        tasks.erase(it_task, ied);
    }

    //fobOE^XNꗗ\
    void CTaskManager::DebugOutputTaskList()
    {
        OutputLog("\n\nCTaskManager::DebugOutputTaskList() - start");

        TaskList::iterator i, ied;

        OutputLog("ʏ^XNꗗ");
        //ʏ^XN
        i = tasks.begin();
        ied = tasks.end();
        for (; i != ied; ++i){
            OutputLog(typeid(**i).name());
        }

        OutputLog("풓^XNꗗ");
        //obNOEh^XN
        i = bg_tasks.begin();
        ied = bg_tasks.end();
        for (; i != ied; ++i){
            OutputLog(typeid(**i).name());
        }

        //r^XN
        OutputLog("\n");
        OutputLog("݂̃^XNF");
        if (ex_stack.empty())
            OutputLog("Ȃ");
        else
            OutputLog(typeid(*ex_stack.top().value).name());

        OutputLog("\n\nCTaskManager::DebugOutputTaskList() - end\n\n");
    }
}
<commit_msg>untabify<commit_after>

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

    ^XNǗ(?)

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

#include <cassert>
#include <algorithm>
#include <typeinfo>
#include "task.h"

namespace GTF
{
    using namespace std;

    CTaskManager::CTaskManager()
    {
        exNext = nullptr;

        // _~[f[^}
        const auto it = tasks.emplace(tasks.end(), make_shared<CTaskBase>());
        ex_stack.emplace(exNext, it);
    }

    void CTaskManager::Destroy()
    {
        TaskList::iterator i, ied;

        //ʏ^XNTerminate
        i = tasks.begin();
        ied = tasks.end();
        for (; i != ied; ++i){
            (*i)->Terminate();
        }
        tasks.clear();

        //obNOEh^XNTerminate
        i = bg_tasks.begin();
        ied = bg_tasks.end();
        for (; i != ied; ++i){
            (*i)->Terminate();
        }
        bg_tasks.clear();

        //r^XNTerminate
        while (ex_stack.size() != 0 && ex_stack.top().value){
            ex_stack.top().value->Terminate();
            ex_stack.pop();
        }
    }

    CTaskManager::TaskPtr CTaskManager::AddTask(CTaskBase *newTask)
    {
        assert(newTask);

        CExclusiveTaskBase *pext = dynamic_cast<CExclusiveTaskBase*>(newTask);
        if (pext){
            //r^XNƂAdd
            return AddTask(pext);
        }

        if (newTask->GetID() != 0){
            RemoveTaskByID(newTask->GetID());
        }

        CBackgroundTaskBase *pbgt = dynamic_cast<CBackgroundTaskBase*>(newTask);
        if (pbgt){
            //풓^XNƂAdd
            return AddTask(pbgt);
        }

        //ʏ^XNƂAdd
        tasks.emplace_back(newTask);
        auto& pnew = tasks.back();
        newTask->Initialize();
        if (newTask->GetID() != 0)
            indices[newTask->GetID()] = pnew;
        if (pnew->GetDrawPriority() >= 0)
            ex_stack.top().drawList.emplace(pnew->GetDrawPriority(), pnew);
        return pnew;
    }

    CTaskManager::ExTaskPtr CTaskManager::AddTask(CExclusiveTaskBase *newTask)
    {
        //r^XNƂAdd
        //ExecuteȂ̂ŁA|C^ۑ̂
        if (exNext){
            OutputLog("ALERT r^XN2ȏAddꂽ : %s / %s",
                typeid(*exNext).name(), typeid(*newTask).name());
        }
        exNext = shared_ptr<CExclusiveTaskBase>(newTask);

        return exNext;
    }

    CTaskManager::BgTaskPtr CTaskManager::AddTask(CBackgroundTaskBase *newTask)
    {
        if (newTask->GetID() != 0){
            RemoveTaskByID(newTask->GetID());
        }

        bg_tasks.emplace_back(newTask);
        // bIȌ^ϊ
        auto& pbgt = static_pointer_cast<CBackgroundTaskBase>(bg_tasks.back());
        assert(dynamic_pointer_cast<CBackgroundTaskBase>(pbgt).get());

        //풓^XNƂAdd
        pbgt->Initialize();
        if (newTask->GetID() != 0)
            bg_indices[newTask->GetID()] = pbgt;
        if (pbgt->GetDrawPriority() >= 0)
            drawListBG.emplace(pbgt->GetDrawPriority(), pbgt);
        return pbgt;
    }

    void CTaskManager::Execute(double elapsedTime)
    {
        // ^XNExecute
        auto taskExecute = [this, elapsedTime](TaskList::iterator i, TaskList::iterator ied){
            deque<TaskList::iterator> deleteList;
            deque<TaskList::iterator>::iterator idl, idl_ed;

            for (; i != ied; ++i){
#ifdef _CATCH_WHILE_EXEC
                try{
#endif
                    if ((*i)->Execute(elapsedTime) == false)
                    {
                        deleteList.push_back(i);
                    }
#ifdef _CATCH_WHILE_EXEC
        }
                catch (...){
                    if (*i == NULL)OutputLog("catch while execute1 : NULL", SYSLOG_ERROR);
                    else OutputLog("catch while execute1 : %X , %s", *i, typeid(**i).name());
                    break;
                }
#endif
    }
            //^XNfalseԂ̂
            if (deleteList.size() != 0){
                idl = deleteList.begin();
                idl_ed = deleteList.end();
                for (; idl != idl_ed; ++idl){
                    i = *idl;
                    (*i)->Terminate();
                    tasks.erase(i);
                }
            }
        };

#ifdef ARRAYBOUNDARY_DEBUG
        if(!AfxCheckMemory()){
            OutputLog("AfxCheckMemory() failed");
            return;
        }
#endif

        //r^XNAtop̂Execute
        assert(ex_stack.size() != 0);
        shared_ptr<CExclusiveTaskBase> exTsk = ex_stack.top().value;

        if (exTsk)
        {
            bool ex_ret = true;
#ifdef _CATCH_WHILE_EXEC
            try{
#endif
                ex_ret = exTsk->Execute(elapsedTime);
#ifdef _CATCH_WHILE_EXEC
            }catch(...){
                if (ex_stack.top() == NULL)OutputLog("catch while execute3 : NULL", SYSLOG_ERROR);
                else OutputLog("catch while execute3 : %X %s",ex_stack.top(),typeid(*ex_stack.top()).name());
            }
#endif

            if (!ex_ret)
            {
                if (!exNext){
                    //ݔr^XN̕ύX

#ifdef _CATCH_WHILE_EXEC
                    try{
#endif

                        //ʏ^XNSĔj
                        CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos);

#ifdef _CATCH_WHILE_EXEC
                    }catch(...){
                        if ((*i) == NULL)OutputLog("catch while terminate1 : NULL", SYSLOG_ERROR);
                        else OutputLog("catch while terminate1 : %X %s", (*i), typeid(*(*i)).name());
                    }
#endif

                    unsigned int prvID;

#ifdef _CATCH_WHILE_EXEC
                    try{
#endif

                        //ݔr^XN̔j
                        prvID = exTsk->GetID();
                        exTsk->Terminate();
                        exTsk = nullptr;
                        ex_stack.pop();

#ifdef _CATCH_WHILE_EXEC
                    }catch(...){
                        if (exTsk == NULL)OutputLog("catch while terminate2 : NULL", SYSLOG_ERROR);
                        else OutputLog("catch while terminate : %X %s", exTsk, typeid(*exTsk).name());
                    }
#endif

#ifdef _CATCH_WHILE_EXEC
                    try{
#endif

                        //̔r^XNActivate
                        assert(ex_stack.size() != 0);
                        exTsk = ex_stack.top().value;
                        if (exTsk)
                            exTsk->Activate(prvID);

#ifdef _CATCH_WHILE_EXEC
                    }catch(...){
                        if (exTsk == NULL)OutputLog("catch while activate : NULL", SYSLOG_ERROR);
                        else OutputLog("catch while activate : %X %s", exTsk, typeid(*exTsk).name());
                    }
#endif

                    return;
                }
            }
        }

        //ʏ^XNExecute
        assert(!ex_stack.empty());
        taskExecute(ex_stack.top().SubTaskStartPos, tasks.end());

        //풓^XNExecute
        taskExecute(bg_tasks.begin(), bg_tasks.end());

        // V^XNꍇ
        if (exNext){
            //ݔr^XNInactivate
            assert(ex_stack.size() != 0);
            auto& exTsk = ex_stack.top().value;
            if (exTsk && !exTsk->Inactivate(exNext->GetID())){
                //ʏ^XNSĔj
                CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos);

                exTsk->Terminate();
                ex_stack.pop();
            }

            //Addꂽ^XNInitializeē˂
            const auto it = tasks.emplace(tasks.end(), make_shared<CTaskBase>());				// _~[^XN}
            ex_stack.emplace(move(exNext), it);
            ex_stack.top().value->Initialize();

            exNext = nullptr;
        }
    }

    void CTaskManager::Draw()
    {
        TaskList::iterator i, ied;
        shared_ptr<CExclusiveTaskBase> pex;
        auto& drawList = ex_stack.top().drawList;

        //r^XN擾
        assert(ex_stack.size() != 0);
        if (ex_stack.top().value && ex_stack.top().value->GetDrawPriority() >= 0){
            pex = ex_stack.top().value;
        }

        auto iv = drawList.begin();
        auto iedv = pex ? drawList.upper_bound(pex->GetDrawPriority()) : drawList.end();
        auto ivBG = drawListBG.begin();
        const auto iedvBG = drawListBG.end();
        auto DrawAndProceed = [&](DrawPriorityMap::iterator& iv)
        {
                    auto is = iv->second.lock();

                    if (is)
                    {
                        is->Draw();
                        ++iv;
                    }
                    else
                        drawList.erase(iv++);
        };
        auto DrawAll = [&]()		// `֐
        {
            while (iv != iedv)
            {
#ifdef _CATCH_WHILE_RENDER
                try{
#endif
                    while (ivBG != iedvBG && ivBG->first <= iv->first)
                        DrawAndProceed(ivBG);
                    DrawAndProceed(iv);
#ifdef _CATCH_WHILE_RENDER
                }catch(...){
                    OutputLog("catch while draw : %X %s", *iv, typeid(*(*iv).lock()).name());
                }
#endif
            }
        };
        //`
        DrawAll();

        // r^XNDraw
        if (pex)
            pex->Draw();

        //`
        assert(iv == iedv);
        iedv = drawList.end();
        DrawAll();

        // c풓^XN
        while (ivBG != iedvBG)
            DrawAndProceed(ivBG);
    }

    void CTaskManager::RemoveTaskByID(unsigned int id)
    {
        TaskList::iterator i, ied;

        //ʏ^XN`FbN
        if (indices.find(id) != indices.end())
        {
            i = tasks.begin();
            ied = tasks.end();
            for (; i != ied; ++i){
                if (id == (*i)->GetID()){
                    (*i)->Terminate();
                    tasks.erase(i);
                    return;
                }
            }
        }

        //obNOEh^XNTerminate
        if (bg_indices.find(id) != bg_indices.end())
        {
            i = bg_tasks.begin();
            ied = bg_tasks.end();
            for (; i != ied; ++i){
                if (id == (*i)->GetID()){
                    (*i)->Terminate();
                    bg_tasks.erase(i);
                    return;
                }
            }
        }
    }

    //ŏʂɂGNXN[Vu^XNQg
    CTaskManager::ExTaskPtr CTaskManager::GetTopExclusiveTask()
    {
        return ex_stack.top().value;
    }

    //wID̔r^XN܂Terminate/pop
    void CTaskManager::RevertExclusiveTaskByID(unsigned int id)
    {
        bool act = false;
        unsigned int previd = 0;

        assert(ex_stack.size() != 0);
        while (ex_stack.top().value){
            const shared_ptr<CExclusiveTaskBase>& task = ex_stack.top().value;
            if (task->GetID() == id){
                if (act){
                    task->Activate(previd);
                }
                return;
            }
            else{
                previd = task->GetID();
                act = true;
                CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos);
                task->Terminate();
                ex_stack.pop();
                assert(ex_stack.size() != 0);
            }
        }
    }

    //ʏ^XNꕔj
    void CTaskManager::CleanupPartialSubTasks(TaskList::iterator it_task)
    {
        TaskList::iterator i, ied;

        i = it_task;
        ied = tasks.end();
        for (; i != ied; ++i){
            shared_ptr<CTaskBase>& delTgt = (*i);
            delTgt->Terminate();
        }
        tasks.erase(it_task, ied);
    }

    //fobOE^XNꗗ\
    void CTaskManager::DebugOutputTaskList()
    {
        OutputLog("\n\nCTaskManager::DebugOutputTaskList() - start");

        TaskList::iterator i, ied;

        OutputLog("ʏ^XNꗗ");
        //ʏ^XN
        i = tasks.begin();
        ied = tasks.end();
        for (; i != ied; ++i){
            OutputLog(typeid(**i).name());
        }

        OutputLog("풓^XNꗗ");
        //obNOEh^XN
        i = bg_tasks.begin();
        ied = bg_tasks.end();
        for (; i != ied; ++i){
            OutputLog(typeid(**i).name());
        }

        //r^XN
        OutputLog("\n");
        OutputLog("݂̃^XNF");
        if (ex_stack.empty())
            OutputLog("Ȃ");
        else
            OutputLog(typeid(*ex_stack.top().value).name());

        OutputLog("\n\nCTaskManager::DebugOutputTaskList() - end\n\n");
    }
}
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/profiles/avatar_menu.h"

#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "ui/base/resource/resource_bundle.h"

// static
void AvatarMenu::GetImageForMenuButton(Profile* profile,
                                       gfx::Image* image,
                                       bool* is_rectangle) {
  ProfileInfoCache& cache =
      g_browser_process->profile_manager()->GetProfileInfoCache();
  size_t index = cache.GetIndexOfProfileWithPath(profile->GetPath());
  if (index == std::string::npos) {
    NOTREACHED();
    return;
  }

  // Ensure we are using the default resource, not the downloaded high-res one.
  const size_t icon_index = cache.GetAvatarIconIndexOfProfileAtIndex(index);
  const int resource_id =
      profiles::GetDefaultAvatarIconResourceIDAtIndex(icon_index);
  *image = ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
  *is_rectangle =
      cache.IsUsingGAIAPictureOfProfileAtIndex(index) &&
      cache.GetGAIAPictureOfProfileAtIndex(index);
}
<commit_msg>[Profiles] Unbreak using the Gaia avatar in the old avatar button.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/profiles/avatar_menu.h"

#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "ui/base/resource/resource_bundle.h"

// static
void AvatarMenu::GetImageForMenuButton(Profile* profile,
                                       gfx::Image* image,
                                       bool* is_rectangle) {
  ProfileInfoCache& cache =
      g_browser_process->profile_manager()->GetProfileInfoCache();
  size_t index = cache.GetIndexOfProfileWithPath(profile->GetPath());
  if (index == std::string::npos) {
    NOTREACHED();
    return;
  }

  // If there is a Gaia image available, try to use that.
  if (cache.IsUsingGAIAPictureOfProfileAtIndex(index)) {
    const gfx::Image* gaia_image = cache.GetGAIAPictureOfProfileAtIndex(index);
    if (gaia_image) {
      *image = *gaia_image;
      *is_rectangle = true;
      return;
    }
  }

  // Otherwise, use the default resource, not the downloaded high-res one.
  const size_t icon_index = cache.GetAvatarIconIndexOfProfileAtIndex(index);
  const int resource_id =
      profiles::GetDefaultAvatarIconResourceIDAtIndex(icon_index);
  *image = ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
  *is_rectangle = false;
}
<|endoftext|>