<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/common/include/p9_mc_scom_addresses_fld_fixes.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file mc_scom_addresses_fld_fixes.H
/// @brief The *scom_addresses_fld.H files are generated form figtree,
///        but the figree can be wrong.  This file is included in
///        *_scom_addresses_fld.H and allows incorrect constants to be
///        fixed manually.
///
// *HWP HWP Owner: Ben Gass <bgass@us.ibm.com>
// *HWP FW Owner: ? <?>
// *HWP Team: SAO
// *HWP Level: 1
// *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE

#ifndef __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H
#define __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H

//Example
//Copy the whole line from the *scom_addresses_fld.H file.  Then add FIX in front of REG
//and add another paramter that is the new value you want.
//
//FIXREG64_FLD( PU_ALTD_CMD_REG_FBC_WITH_TM_QUIESCE, 24, SH_UNT, SH_ACS_SCOM, SH_FLD_FBC_WITH_TM_QUIESCE,
//              12);

static const uint64_t SH_FLD_COMMAND_LIST_TIMEOUT_SPEC = 99990000;
static const uint64_t SH_FLD_CFG_PAUSE_ON_MCE = 99990001;

REG64_FLD( MCA_DDRPHY_DP16_SYSCLK_PR0_P0_0_01_ENABLE               , 48  , SH_UNT_MCA      , SH_ACS_SCOM_RW  ,
           0 );

REG64_FLD( MCA_DDRPHY_WC_RTT_WL_SWAP_ENABLE_P0                     , 48  , SH_UNT_MCA      , SH_ACS_SCOM_RW  ,
           0 );
REG64_FLD( MCA_DDRPHY_WC_RTT_WR_CTL_SWAP_ENABLE_P0                 , 49  , SH_UNT_MCA      , SH_ACS_SCOM_RW  ,
           0 );

REG64_FLD( MCBIST_MCBCFGQ_CFG_MCBIST_CFG_FORCE_PAUSE_AFTER_RANK    , 34  , SH_UNT_MCA      , SH_ACS_SCOM_RW  ,
           0 );

REG64_FLD( MCBIST_MBSTRQ_CFG_PAUSE_ON_MCE                          , 33  , SH_UNT_MCBIST   , SH_ACS_SCOM_RW  ,
           SH_FLD_CFG_PAUSE_ON_MCE );

#endif
<commit_msg>p9_mss_setup_bars -- customize interleave granularity<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/common/include/p9_mc_scom_addresses_fld_fixes.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file mc_scom_addresses_fld_fixes.H
/// @brief The *scom_addresses_fld.H files are generated form figtree,
///        but the figree can be wrong.  This file is included in
///        *_scom_addresses_fld.H and allows incorrect constants to be
///        fixed manually.
///
// *HWP HWP Owner: Ben Gass <bgass@us.ibm.com>
// *HWP FW Owner: ? <?>
// *HWP Team: SAO
// *HWP Level: 1
// *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE

#ifndef __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H
#define __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H

//Example
//Copy the whole line from the *scom_addresses_fld.H file.  Then add FIX in front of REG
//and add another paramter that is the new value you want.
//
//FIXREG64_FLD( PU_ALTD_CMD_REG_FBC_WITH_TM_QUIESCE, 24, SH_UNT, SH_ACS_SCOM, SH_FLD_FBC_WITH_TM_QUIESCE,
//              12);

static const uint64_t SH_FLD_COMMAND_LIST_TIMEOUT_SPEC = 99990000;
static const uint64_t SH_FLD_CFG_PAUSE_ON_MCE = 99990001;

REG64_FLD( MCA_DDRPHY_DP16_SYSCLK_PR0_P0_0_01_ENABLE               , 48  , SH_UNT_MCA      , SH_ACS_SCOM_RW  ,
           0 );

REG64_FLD( MCA_DDRPHY_WC_RTT_WL_SWAP_ENABLE_P0                     , 48  , SH_UNT_MCA      , SH_ACS_SCOM_RW  ,
           0 );
REG64_FLD( MCA_DDRPHY_WC_RTT_WR_CTL_SWAP_ENABLE_P0                 , 49  , SH_UNT_MCA      , SH_ACS_SCOM_RW  ,
           0 );

REG64_FLD( MCBIST_MCBCFGQ_CFG_MCBIST_CFG_FORCE_PAUSE_AFTER_RANK    , 34  , SH_UNT_MCA      , SH_ACS_SCOM_RW  ,
           0 );

REG64_FLD( MCBIST_MBSTRQ_CFG_PAUSE_ON_MCE                          , 33  , SH_UNT_MCBIST   , SH_ACS_SCOM_RW  ,
           SH_FLD_CFG_PAUSE_ON_MCE );

REG64_FLD( MCS_MCMODE0_GROUP_INTERLEAVE_GRANULARITY                , 52  , SH_UNT_MCS      , SH_ACS_SCOM_RW  ,
           0 );
REG64_FLD( MCS_MCMODE0_GROUP_INTERLEAVE_GRANULARITY_LEN            , 4   , SH_UNT_MCS      , SH_ACS_SCOM_RW  ,
           0 );

#endif
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/graph/function_impl.h"
#include "core/graph/graph_viewer.h"
#include "core/graph/model.h"
#include "onnx/shape_inference/implementation.h"

namespace onnxruntime {
void TypeConstraintHelper(const ONNX_NAMESPACE::FunctionProto* onnx_func_proto_,
                          std::unique_ptr<ONNX_NAMESPACE::OpSchema>& op_schema_,
                          /*out*/
                          std::unordered_map<std::string, int>& input_name_idx_map,
                          std::unordered_map<std::string, int>& output_name_idx_map) {
  std::vector<std::pair<std::string, std::string>> input_types_list(onnx_func_proto_->input_size());
  std::vector<std::pair<std::string, std::string>> output_types_list(onnx_func_proto_->output_size());
  std::unordered_map<std::string, std::vector<std::string>> type_constraint_map;
  for (int i = 0; i < onnx_func_proto_->input_size(); ++i) {
    input_name_idx_map[onnx_func_proto_->input().Get(i)] = i;
  }
  for (int i = 0; i < onnx_func_proto_->output_size(); ++i) {
    output_name_idx_map[onnx_func_proto_->output().Get(i)] = i;
  }
  auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
  for (auto& node : onnx_func_proto_->node()) {
    const auto node_op_schema = schema_registry->GetSchema(node.op_type(), (int)onnx_func_proto_->since_version(), node.domain());
    for (int i = 0; i < node.input_size(); ++i) {
      auto& in_name = node.input().Get(i);
      auto iter = input_name_idx_map.find(in_name);
      if (iter != input_name_idx_map.end()) {
        int idx = iter->second;
        const auto& p = node_op_schema->inputs().at(i);
        std::string type_str = p.GetTypeStr() + "in" + std::to_string(i);
        input_types_list[idx] = std::make_pair(in_name, type_str);
        if (!type_constraint_map.count(type_str)) {
          for (auto s : p.GetTypes()) {
            type_constraint_map[type_str].emplace_back(*s);
          }
        }
      }
    }
    for (int i = 0; i < node.output_size(); ++i) {
      auto& out_name = node.output().Get(i);
      auto iter = output_name_idx_map.find(out_name);
      if (iter != output_name_idx_map.end()) {
        int idx = iter->second;
        const auto& p = node_op_schema->outputs().at(i);
        std::string type_str = p.GetTypeStr() + "out" + std::to_string(i);
        output_types_list[idx] = std::make_pair(out_name, type_str);
        if (!type_constraint_map.count(type_str)) {
          for (auto s : p.GetTypes()) {
            type_constraint_map[type_str].emplace_back(*s);
          }
        }
      }
    }
  }

  int i = 0;
  for (auto& input : input_types_list) {
    op_schema_->Input(i, input.first, "", input.second);
    ++i;
  }
  i = 0;
  for (auto& output : output_types_list) {
    op_schema_->Output(i, output.first, "", output.second);
    ++i;
  }

  for (auto& tc : type_constraint_map) {
    op_schema_->TypeConstraint(tc.first, tc.second, "");
  }
}

FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
                           std::unique_ptr<IndexedSubGraph> customized_func)
    : parent_graph_(&graph), onnx_func_proto_{nullptr} {
  customized_func_body_ = std::move(customized_func);
  auto meta_def = customized_func_body_->GetMetaDef();
  op_schema_ = std::make_unique<ONNX_NAMESPACE::OpSchema>();
  op_schema_->SetName(meta_def->name);
  op_schema_->SetDomain(meta_def->domain);
  op_schema_->SetDoc(meta_def->doc_string);
  op_schema_->SinceVersion(meta_def->since_version);
  int i = 0;
  for (auto& input : meta_def->inputs) {
    auto input_type = parent_graph_->GetNodeArg(input)->Type();
    op_schema_->Input(i, input, "", *input_type);
    ++i;
  }
  i = 0;
  for (auto& output : meta_def->outputs) {
    auto output_type = parent_graph_->GetNodeArg(output)->Type();
    op_schema_->Output(i, output, "", *output_type);
    ++i;
  }
  op_schema_->Finalize();
  //construct body
  body_ = std::make_unique<onnxruntime::Model>("fused_function_subgraph", false, onnxruntime::ModelMetaData(),
                                               IOnnxRuntimeOpSchemaRegistryList({graph.GetSchemaRegistry()}),
                                               graph.DomainToVersionMap());

  auto& sub_graph = body_->MainGraph();
  //Add node and node args
  //TODO: for better performance, we could try to transfer the nodes in parent graph to sub-graph directly,
  //instead of create new nodes.
  for (auto& node_index : customized_func_body_->nodes) {
    auto node = parent_graph_->GetNode(node_index);
    std::vector<onnxruntime::NodeArg*> inputs, outputs;
    for (auto input : node->InputDefs()) {
      auto& n_input = sub_graph.GetOrCreateNodeArg(input->Name(), input->TypeAsProto());
      inputs.push_back(&n_input);
    }
    for (auto output : node->OutputDefs()) {
      auto& n_output = sub_graph.GetOrCreateNodeArg(output->Name(), output->TypeAsProto());
      outputs.push_back(&n_output);
    }
    sub_graph.AddNode(node->Name(), node->OpType(), node->Description(), inputs, outputs, &node->GetAttributes(), node->Domain());
  }
  //TODO: if we reuse the nodes in parent graph, maybe we don't need to resolve it.
  ORT_ENFORCE(sub_graph.Resolve().IsOK());
}

FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
                           const onnxruntime::NodeIndex& node_index,
                           const ONNX_NAMESPACE::FunctionProto* onnx_func_proto)
    : parent_graph_(&graph) {
  onnx_func_proto_ = onnx_func_proto;
  auto node_in_parent_graph = parent_graph_->GetNode(node_index);
  op_schema_ = std::make_unique<onnx::OpSchema>();
  op_schema_->SetName(onnx_func_proto_->name());
  op_schema_->SetDomain(onnx_func_proto_->node().Get(0).domain());
  op_schema_->SetDoc(onnx_func_proto_->doc_string());
  op_schema_->SinceVersion((ONNX_NAMESPACE::OperatorSetVersion)onnx_func_proto_->since_version());
  std::unordered_map<std::string, int> input_name_idx_map;
  std::unordered_map<std::string, int> output_name_idx_map;
  TypeConstraintHelper(onnx_func_proto_, this->op_schema_, input_name_idx_map, output_name_idx_map);

  op_schema_->TypeAndShapeInferenceFunction(
      [this](ONNX_NAMESPACE::InferenceContext& ctx) {
        auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
        const ONNX_NAMESPACE::FunctionProto* func_ptr = this->GetFuncProto();
        if (nullptr != func_ptr) {
          ONNX_NAMESPACE::shape_inference::InferShapeForFunctionNode(*func_ptr, schema_registry, ctx);
        }
      });

  op_schema_->Finalize();
  //construct body
  std::unordered_map<std::string, int> domain_to_version;
  //TODO: set correct domain and version
  domain_to_version[onnxruntime::kOnnxDomain] = (int)onnx_func_proto_->since_version();
  body_ = std::make_unique<onnxruntime::Model>(onnx_func_proto_->name(), false, onnxruntime::ModelMetaData(),
                                               IOnnxRuntimeOpSchemaRegistryList(), domain_to_version);
  auto& sub_graph = body_->MainGraph();
  // Add node and node args into subgraph
  // The subgraph preserved the input/output tensor names
  // in the parent graph for later inlining purpose
  auto attr_map = node_in_parent_graph->GetAttributes();
  for (auto& node : onnx_func_proto_->node()) {
    std::vector<onnxruntime::NodeArg*> inputs, outputs;
    for (int idx = 0; idx < node.input_size(); ++idx) {
      std::string tensor_name = node.input().Get(idx);
      auto iter = input_name_idx_map.find(tensor_name);
      if (iter != input_name_idx_map.end()) {
        // Preserving NodeArg and input/output names
        ONNX_NAMESPACE::NodeProto temp_node_proto;
        node_in_parent_graph->ToProto(temp_node_proto);
        const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.input().Get(input_name_idx_map[tensor_name]));
        auto& n_input = sub_graph.GetOrCreateNodeArg(
            temp_node_proto.input().Get(iter->second), node_arg->TypeAsProto());
        inputs.push_back(&n_input);
      } else {
        auto& n_input = sub_graph.GetOrCreateNodeArg(
            tensor_name + "_" + std::to_string(node_index), nullptr);
        inputs.push_back(&n_input);
      }
    }
    for (int idx = 0; idx < node.output_size(); ++idx) {
      std::string tensor_name = node.output().Get(idx);
      auto iter = output_name_idx_map.find(tensor_name);
      if (iter != output_name_idx_map.end()) {
        // Preserving NodeArg and input/output names
        ONNX_NAMESPACE::NodeProto temp_node_proto;
        node_in_parent_graph->ToProto(temp_node_proto);
        const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.output().Get(output_name_idx_map[tensor_name]));
        auto& n_output = sub_graph.GetOrCreateNodeArg(
            temp_node_proto.output().Get(iter->second), node_arg->TypeAsProto());
        outputs.push_back(&n_output);
      } else {
        auto& n_output = sub_graph.GetOrCreateNodeArg(
            tensor_name + "_" + std::to_string(node_index), nullptr);
        outputs.push_back(&n_output);
      }
    }

    onnxruntime::NodeAttributes new_attr_map;
    for (auto& attr : node.attribute()) {
      if (attr.has_ref_attr_name()) {
        if (attr_map.count(attr.ref_attr_name())) {
          new_attr_map[attr.name()] = attr_map[attr.ref_attr_name()];
        }
      } else {
        new_attr_map[attr.name()] = attr;
      }
    }
    sub_graph.AddNode(node.name() + "_" + std::to_string(node_index), node.op_type(), node.doc_string(), inputs, outputs, &new_attr_map, node.domain());
  }
  auto status = sub_graph.Resolve();
  ORT_ENFORCE(status.IsOK());
}

FunctionImpl::~FunctionImpl() = default;

const ONNX_NAMESPACE::OpSchema& FunctionImpl::OpSchema() const {
  return *op_schema_;
}

const onnxruntime::Graph& FunctionImpl::Body() const {
  return body_->MainGraph();
}

const IndexedSubGraph& FunctionImpl::GetIndexedSubGraph() const {
  return *customized_func_body_;
}

const ONNX_NAMESPACE::FunctionProto* FunctionImpl::GetFuncProto() const {
  return onnx_func_proto_;
}

std::unique_ptr<Function> MakeFunction(const onnxruntime::Graph& graph,
                                       std::unique_ptr<IndexedSubGraph> customized_func) {
  return std::make_unique<FunctionImpl>(graph, std::move(customized_func));
}
}  // namespace onnxruntime
<commit_msg>add initializer for sub-graph. (#269)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/graph/function_impl.h"
#include "core/graph/graph_viewer.h"
#include "core/graph/model.h"
#include "onnx/shape_inference/implementation.h"

namespace onnxruntime {
void TypeConstraintHelper(const ONNX_NAMESPACE::FunctionProto* onnx_func_proto_,
                          std::unique_ptr<ONNX_NAMESPACE::OpSchema>& op_schema_,
                          /*out*/
                          std::unordered_map<std::string, int>& input_name_idx_map,
                          std::unordered_map<std::string, int>& output_name_idx_map) {
  std::vector<std::pair<std::string, std::string>> input_types_list(onnx_func_proto_->input_size());
  std::vector<std::pair<std::string, std::string>> output_types_list(onnx_func_proto_->output_size());
  std::unordered_map<std::string, std::vector<std::string>> type_constraint_map;
  for (int i = 0; i < onnx_func_proto_->input_size(); ++i) {
    input_name_idx_map[onnx_func_proto_->input().Get(i)] = i;
  }
  for (int i = 0; i < onnx_func_proto_->output_size(); ++i) {
    output_name_idx_map[onnx_func_proto_->output().Get(i)] = i;
  }
  auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
  for (auto& node : onnx_func_proto_->node()) {
    const auto node_op_schema = schema_registry->GetSchema(node.op_type(), (int)onnx_func_proto_->since_version(), node.domain());
    for (int i = 0; i < node.input_size(); ++i) {
      auto& in_name = node.input().Get(i);
      auto iter = input_name_idx_map.find(in_name);
      if (iter != input_name_idx_map.end()) {
        int idx = iter->second;
        const auto& p = node_op_schema->inputs().at(i);
        std::string type_str = p.GetTypeStr() + "in" + std::to_string(i);
        input_types_list[idx] = std::make_pair(in_name, type_str);
        if (!type_constraint_map.count(type_str)) {
          for (auto s : p.GetTypes()) {
            type_constraint_map[type_str].emplace_back(*s);
          }
        }
      }
    }
    for (int i = 0; i < node.output_size(); ++i) {
      auto& out_name = node.output().Get(i);
      auto iter = output_name_idx_map.find(out_name);
      if (iter != output_name_idx_map.end()) {
        int idx = iter->second;
        const auto& p = node_op_schema->outputs().at(i);
        std::string type_str = p.GetTypeStr() + "out" + std::to_string(i);
        output_types_list[idx] = std::make_pair(out_name, type_str);
        if (!type_constraint_map.count(type_str)) {
          for (auto s : p.GetTypes()) {
            type_constraint_map[type_str].emplace_back(*s);
          }
        }
      }
    }
  }

  int i = 0;
  for (auto& input : input_types_list) {
    op_schema_->Input(i, input.first, "", input.second);
    ++i;
  }
  i = 0;
  for (auto& output : output_types_list) {
    op_schema_->Output(i, output.first, "", output.second);
    ++i;
  }

  for (auto& tc : type_constraint_map) {
    op_schema_->TypeConstraint(tc.first, tc.second, "");
  }
}

FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
                           std::unique_ptr<IndexedSubGraph> customized_func)
    : parent_graph_(&graph), onnx_func_proto_{nullptr} {
  customized_func_body_ = std::move(customized_func);
  auto meta_def = customized_func_body_->GetMetaDef();
  op_schema_ = std::make_unique<ONNX_NAMESPACE::OpSchema>();
  op_schema_->SetName(meta_def->name);
  op_schema_->SetDomain(meta_def->domain);
  op_schema_->SetDoc(meta_def->doc_string);
  op_schema_->SinceVersion(meta_def->since_version);
  int i = 0;
  for (auto& input : meta_def->inputs) {
    auto input_type = parent_graph_->GetNodeArg(input)->Type();
    op_schema_->Input(i, input, "", *input_type);
    ++i;
  }
  i = 0;
  for (auto& output : meta_def->outputs) {
    auto output_type = parent_graph_->GetNodeArg(output)->Type();
    op_schema_->Output(i, output, "", *output_type);
    ++i;
  }
  op_schema_->Finalize();
  //construct body
  body_ = std::make_unique<onnxruntime::Model>("fused_function_subgraph", false, onnxruntime::ModelMetaData(),
                                               IOnnxRuntimeOpSchemaRegistryList({graph.GetSchemaRegistry()}),
                                               graph.DomainToVersionMap());

  auto& sub_graph = body_->MainGraph();
  //Add node and node args
  //TODO: for better performance, we could try to transfer the nodes in parent graph to sub-graph directly,
  //instead of create new nodes.
  for (auto& node_index : customized_func_body_->nodes) {
    auto node = parent_graph_->GetNode(node_index);
    std::vector<onnxruntime::NodeArg*> inputs, outputs;
    for (auto input : node->InputDefs()) {
      auto& n_input = sub_graph.GetOrCreateNodeArg(input->Name(), input->TypeAsProto());
      inputs.push_back(&n_input);
    }
    for (auto output : node->OutputDefs()) {
      auto& n_output = sub_graph.GetOrCreateNodeArg(output->Name(), output->TypeAsProto());
      outputs.push_back(&n_output);
    }
    sub_graph.AddNode(node->Name(), node->OpType(), node->Description(), inputs, outputs, &node->GetAttributes(), node->Domain());
  }

  for (auto input : meta_def->inputs) {
    const onnx::TensorProto* initializer = nullptr;
    if (graph.GetInitializedTensor(input, initializer)) {
      sub_graph.AddInitializedTensor(*initializer);
    }
  }

  //TODO: if we reuse the nodes in parent graph, maybe we don't need to resolve it.
  ORT_ENFORCE(sub_graph.Resolve().IsOK());
}

FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
                           const onnxruntime::NodeIndex& node_index,
                           const ONNX_NAMESPACE::FunctionProto* onnx_func_proto)
    : parent_graph_(&graph) {
  onnx_func_proto_ = onnx_func_proto;
  auto node_in_parent_graph = parent_graph_->GetNode(node_index);
  op_schema_ = std::make_unique<onnx::OpSchema>();
  op_schema_->SetName(onnx_func_proto_->name());
  op_schema_->SetDomain(onnx_func_proto_->node().Get(0).domain());
  op_schema_->SetDoc(onnx_func_proto_->doc_string());
  op_schema_->SinceVersion((ONNX_NAMESPACE::OperatorSetVersion)onnx_func_proto_->since_version());
  std::unordered_map<std::string, int> input_name_idx_map;
  std::unordered_map<std::string, int> output_name_idx_map;
  TypeConstraintHelper(onnx_func_proto_, this->op_schema_, input_name_idx_map, output_name_idx_map);

  op_schema_->TypeAndShapeInferenceFunction(
      [this](ONNX_NAMESPACE::InferenceContext& ctx) {
        auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
        const ONNX_NAMESPACE::FunctionProto* func_ptr = this->GetFuncProto();
        if (nullptr != func_ptr) {
          ONNX_NAMESPACE::shape_inference::InferShapeForFunctionNode(*func_ptr, schema_registry, ctx);
        }
      });

  op_schema_->Finalize();
  //construct body
  std::unordered_map<std::string, int> domain_to_version;
  //TODO: set correct domain and version
  domain_to_version[onnxruntime::kOnnxDomain] = (int)onnx_func_proto_->since_version();
  body_ = std::make_unique<onnxruntime::Model>(onnx_func_proto_->name(), false, onnxruntime::ModelMetaData(),
                                               IOnnxRuntimeOpSchemaRegistryList(), domain_to_version);
  auto& sub_graph = body_->MainGraph();
  // Add node and node args into subgraph
  // The subgraph preserved the input/output tensor names
  // in the parent graph for later inlining purpose
  auto attr_map = node_in_parent_graph->GetAttributes();
  for (auto& node : onnx_func_proto_->node()) {
    std::vector<onnxruntime::NodeArg*> inputs, outputs;
    for (int idx = 0; idx < node.input_size(); ++idx) {
      std::string tensor_name = node.input().Get(idx);
      auto iter = input_name_idx_map.find(tensor_name);
      if (iter != input_name_idx_map.end()) {
        // Preserving NodeArg and input/output names
        ONNX_NAMESPACE::NodeProto temp_node_proto;
        node_in_parent_graph->ToProto(temp_node_proto);
        const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.input().Get(input_name_idx_map[tensor_name]));
        auto& n_input = sub_graph.GetOrCreateNodeArg(
            temp_node_proto.input().Get(iter->second), node_arg->TypeAsProto());
        inputs.push_back(&n_input);
      } else {
        auto& n_input = sub_graph.GetOrCreateNodeArg(
            tensor_name + "_" + std::to_string(node_index), nullptr);
        inputs.push_back(&n_input);
      }
    }
    for (int idx = 0; idx < node.output_size(); ++idx) {
      std::string tensor_name = node.output().Get(idx);
      auto iter = output_name_idx_map.find(tensor_name);
      if (iter != output_name_idx_map.end()) {
        // Preserving NodeArg and input/output names
        ONNX_NAMESPACE::NodeProto temp_node_proto;
        node_in_parent_graph->ToProto(temp_node_proto);
        const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.output().Get(output_name_idx_map[tensor_name]));
        auto& n_output = sub_graph.GetOrCreateNodeArg(
            temp_node_proto.output().Get(iter->second), node_arg->TypeAsProto());
        outputs.push_back(&n_output);
      } else {
        auto& n_output = sub_graph.GetOrCreateNodeArg(
            tensor_name + "_" + std::to_string(node_index), nullptr);
        outputs.push_back(&n_output);
      }
    }

    onnxruntime::NodeAttributes new_attr_map;
    for (auto& attr : node.attribute()) {
      if (attr.has_ref_attr_name()) {
        if (attr_map.count(attr.ref_attr_name())) {
          new_attr_map[attr.name()] = attr_map[attr.ref_attr_name()];
        }
      } else {
        new_attr_map[attr.name()] = attr;
      }
    }
    sub_graph.AddNode(node.name() + "_" + std::to_string(node_index), node.op_type(), node.doc_string(), inputs, outputs, &new_attr_map, node.domain());
  }
  auto status = sub_graph.Resolve();
  ORT_ENFORCE(status.IsOK());
}

FunctionImpl::~FunctionImpl() = default;

const ONNX_NAMESPACE::OpSchema& FunctionImpl::OpSchema() const {
  return *op_schema_;
}

const onnxruntime::Graph& FunctionImpl::Body() const {
  return body_->MainGraph();
}

const IndexedSubGraph& FunctionImpl::GetIndexedSubGraph() const {
  return *customized_func_body_;
}

const ONNX_NAMESPACE::FunctionProto* FunctionImpl::GetFuncProto() const {
  return onnx_func_proto_;
}

std::unique_ptr<Function> MakeFunction(const onnxruntime::Graph& graph,
                                       std::unique_ptr<IndexedSubGraph> customized_func) {
  return std::make_unique<FunctionImpl>(graph, std::move(customized_func));
}
}  // namespace onnxruntime
<|endoftext|>


<commit_before>#include <b9.hpp>
#include <b9/loader.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

/// B9run's usage string. Printed when run with -help.
static const char* usage =
    "Usage: b9run [<option>...] [--] [<module> [<main>]]\n"
    "   Or: b9run -help\n"
    "Options:\n"
    "  -callstyle <style>: Set the calling style. One of:\n"
    "      interpreter:   Calls are made through the interpreter\n"
    "      direct:        Calls are made directly, but parameters are on the "
    "operand stack\n"
    "      passparameter: Direct calls, with parameters passed in CPU "
    "registers\n"
    "      operandstack:  Like passparam, but will keep the VM operand stack "
    "updated\n"
    "  -loop <n>:   Run the program <n> times\n"
    "  -inline <n>: Enable inlining\n"
    "  -debug:      Enable debug code\n"
    "  -verbose:    Run with verbose printing\n"
    "  -help:       Print this help message";

/// The b9run program's global configuration.
struct RunConfig {
  b9::VirtualMachineConfig vm;
  const char* module = "program.so";
  const char* mainFunction = "b9main";
  std::size_t loopCount = 1;
  bool verbose = false;
};

/// Print the configuration summary.
std::ostream& operator<<(std::ostream& out, const RunConfig& cfg) {
  return out << "Loading:      " << cfg.module << std::endl
             << "Executing:    " << cfg.mainFunction << std::endl
             << "Call Style:   " << cfg.vm.jit.callStyle << std::endl
             << "Looping:      " << cfg.loopCount << " times" << std::endl
             << "Inline depth: " << cfg.vm.jit.maxInlineDepth;
}

/// Parse CLI arguments and set up the config.
static bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) {
  std::size_t i = 1;

  for (; i < argc; i++) {
    const char* arg = argv[i];

    if (strcmp(arg, "-help") == 0) {
      std::cout << usage << std::endl;
      exit(EXIT_SUCCESS);
    } else if (strcmp(arg, "-loop") == 0) {
      cfg.loopCount = atoi(argv[++i]);
    } else if (strcmp(arg, "-inline") == 0) {
      cfg.vm.jit.maxInlineDepth = atoi(argv[++i]);
    } else if (strcmp(arg, "-verbose") == 0) {
      cfg.verbose = true;
      cfg.vm.verbose = true;
      cfg.vm.jit.verbose = true;
    } else if (strcmp(arg, "-debug") == 0) {
      cfg.vm.debug = true;
      cfg.vm.jit.debug = true;
    } else if (strcmp(arg, "-callstyle") == 0) {
      i += 1;
      auto callStyle = argv[i];
      if (strcmp("interpreter", callStyle) == 0) {
        cfg.vm.jit.callStyle = b9::CallStyle::interpreter;
      } else if (strcmp("direct", callStyle) == 0) {
        cfg.vm.jit.callStyle = b9::CallStyle::direct;
      } else if (strcmp("passparameter", callStyle) == 0) {
        cfg.vm.jit.callStyle = b9::CallStyle::passParameter;
      } else if (strcmp("operandstack", callStyle) == 0) {
        cfg.vm.jit.callStyle = b9::CallStyle::operandStack;
      }
    } else if (strcmp(arg, "--") == 0) {
      i++;
      break;
    } else if (strcmp(arg, "-") == 0) {
      std::cerr << "Unrecognized option: " << arg << std::endl;
      return false;
    } else {
      break;
    }
  }

  // positional

  if (i < argc) {
    cfg.module = argv[i++];

    if (i < argc) {
      cfg.mainFunction = argv[i++];
    }
  }

  return true;
}

static void run(const RunConfig& cfg) {
  b9::VirtualMachine vm{cfg.vm};
  vm.initialize();

  b9::DlLoader loader{true};
  auto module = loader.loadModule(cfg.module);

  if (module->functions.size() == 0) {
    throw b9::DlException{"Empty module"};
  }

  vm.load(module);

  for (std::size_t i = 0; i < cfg.loopCount; i++) {
    vm.run(cfg.mainFunction);
  }
}

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

  if (!parseArguments(cfg, argc, argv)) {
    exit(EXIT_FAILURE);
  }

  if (cfg.verbose) {
    std::cout << cfg << std::endl;
  }

  try {
    run(cfg);
  } catch (const b9::DlException& e) {
    std::cerr << "Failed to load module: " << e.what() << std::endl;
    exit(EXIT_FAILURE);
  } catch (const b9::FunctionNotFoundException& e) {
    std::cerr << "Failed to find function: " << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }

  exit(EXIT_SUCCESS);
}
<commit_msg>Move call to findFunction for -loop option<commit_after>#include <b9.hpp>
#include <b9/loader.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

/// B9run's usage string. Printed when run with -help.
static const char* usage =
    "Usage: b9run [<option>...] [--] [<module> [<main>]]\n"
    "   Or: b9run -help\n"
    "Options:\n"
    "  -callstyle <style>: Set the calling style. One of:\n"
    "      interpreter:   Calls are made through the interpreter\n"
    "      direct:        Calls are made directly, but parameters are on the "
    "operand stack\n"
    "      passparameter: Direct calls, with parameters passed in CPU "
    "registers\n"
    "      operandstack:  Like passparam, but will keep the VM operand stack "
    "updated\n"
    "  -loop <n>:   Run the program <n> times\n"
    "  -inline <n>: Enable inlining\n"
    "  -debug:      Enable debug code\n"
    "  -verbose:    Run with verbose printing\n"
    "  -help:       Print this help message";

/// The b9run program's global configuration.
struct RunConfig {
  b9::VirtualMachineConfig vm;
  const char* module = "program.so";
  const char* mainFunction = "b9main";
  std::size_t loopCount = 1;
  bool verbose = false;
};

/// Print the configuration summary.
std::ostream& operator<<(std::ostream& out, const RunConfig& cfg) {
  return out << "Loading:      " << cfg.module << std::endl
             << "Executing:    " << cfg.mainFunction << std::endl
             << "Call Style:   " << cfg.vm.jit.callStyle << std::endl
             << "Looping:      " << cfg.loopCount << " times" << std::endl
             << "Inline depth: " << cfg.vm.jit.maxInlineDepth;
}

/// Parse CLI arguments and set up the config.
static bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) {
  std::size_t i = 1;

  for (; i < argc; i++) {
    const char* arg = argv[i];

    if (strcmp(arg, "-help") == 0) {
      std::cout << usage << std::endl;
      exit(EXIT_SUCCESS);
    } else if (strcmp(arg, "-loop") == 0) {
      cfg.loopCount = atoi(argv[++i]);
    } else if (strcmp(arg, "-inline") == 0) {
      cfg.vm.jit.maxInlineDepth = atoi(argv[++i]);
    } else if (strcmp(arg, "-verbose") == 0) {
      cfg.verbose = true;
      cfg.vm.verbose = true;
      cfg.vm.jit.verbose = true;
    } else if (strcmp(arg, "-debug") == 0) {
      cfg.vm.debug = true;
      cfg.vm.jit.debug = true;
    } else if (strcmp(arg, "-callstyle") == 0) {
      i += 1;
      auto callStyle = argv[i];
      if (strcmp("interpreter", callStyle) == 0) {
        cfg.vm.jit.callStyle = b9::CallStyle::interpreter;
      } else if (strcmp("direct", callStyle) == 0) {
        cfg.vm.jit.callStyle = b9::CallStyle::direct;
      } else if (strcmp("passparameter", callStyle) == 0) {
        cfg.vm.jit.callStyle = b9::CallStyle::passParameter;
      } else if (strcmp("operandstack", callStyle) == 0) {
        cfg.vm.jit.callStyle = b9::CallStyle::operandStack;
      }
    } else if (strcmp(arg, "--") == 0) {
      i++;
      break;
    } else if (strcmp(arg, "-") == 0) {
      std::cerr << "Unrecognized option: " << arg << std::endl;
      return false;
    } else {
      break;
    }
  }

  // positional

  if (i < argc) {
    cfg.module = argv[i++];

    if (i < argc) {
      cfg.mainFunction = argv[i++];
    }
  }

  return true;
}

static void run(const RunConfig& cfg) {
  b9::VirtualMachine vm{cfg.vm};
  vm.initialize();

  b9::DlLoader loader{true};
  auto module = loader.loadModule(cfg.module);

  if (module->functions.size() == 0) {
    throw b9::DlException{"Empty module"};
  }

  vm.load(module);

  size_t functionIndex = module->findFunction(cfg.mainFunction);
  for (std::size_t i = 0; i < cfg.loopCount; i++) {
    vm.run(functionIndex);
  }
}

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

  if (!parseArguments(cfg, argc, argv)) {
    exit(EXIT_FAILURE);
  }

  if (cfg.verbose) {
    std::cout << cfg << std::endl;
  }

  try {
    run(cfg);
  } catch (const b9::DlException& e) {
    std::cerr << "Failed to load module: " << e.what() << std::endl;
    exit(EXIT_FAILURE);
  } catch (const b9::FunctionNotFoundException& e) {
    std::cerr << "Failed to find function: " << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }

  exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"
#include <typeinfo>

template<typename Dst, typename Src>
bool test_assign(const Dst&, const Src&, int vectorization, int unrolling)
{
  return ei_assign_traits<Dst,Src>::Vectorization==vectorization
    && ei_assign_traits<Dst,Src>::Unrolling==unrolling;
}

template<typename Xpr>
bool test_sum(const Xpr&, int vectorization, int unrolling)
{
  return ei_sum_traits<Xpr>::Vectorization==vectorization
    && ei_sum_traits<Xpr>::Unrolling==unrolling;
}

void test_vectorization_logic()
{

#ifdef EIGEN_VECTORIZE

  VERIFY(test_assign(Vector4f(),Vector4f(),
    InnerVectorization,CompleteUnrolling));
  VERIFY(test_assign(Vector4f(),Vector4f()+Vector4f(),
    InnerVectorization,CompleteUnrolling));
  VERIFY(test_assign(Vector4f(),Vector4f().cwise() * Vector4f(),
    InnerVectorization,CompleteUnrolling));

  VERIFY(test_assign(Matrix4f(),Matrix4f(),
    InnerVectorization,CompleteUnrolling));
  VERIFY(test_assign(Matrix4f(),Matrix4f()+Matrix4f(),
    InnerVectorization,CompleteUnrolling));
  VERIFY(test_assign(Matrix4f(),Matrix4f().cwise() * Matrix4f(),
    InnerVectorization,CompleteUnrolling));

  VERIFY(test_assign(Matrix<float,16,16>(),Matrix<float,16,16>()+Matrix<float,16,16>(),
    InnerVectorization,InnerUnrolling));

  VERIFY(test_assign(Matrix<float,16,16,DontAlign>(),Matrix<float,16,16>()+Matrix<float,16,16>(),
    NoVectorization,InnerUnrolling));

  VERIFY(test_assign(Matrix<float,6,2>(),Matrix<float,6,2>().cwise() / Matrix<float,6,2>(),
    LinearVectorization,CompleteUnrolling));

  VERIFY(test_assign(Matrix<float,17,17>(),Matrix<float,17,17>()+Matrix<float,17,17>(),
    NoVectorization,InnerUnrolling));

  VERIFY(test_assign(Matrix<float,4,4>(),Matrix<float,17,17>().block<4,4>(2,3)+Matrix<float,17,17>().block<4,4>(10,4),
    NoVectorization,CompleteUnrolling));

  VERIFY(test_assign(MatrixXf(10,10),MatrixXf(20,20).block(10,10,2,3),
    SliceVectorization,NoUnrolling));

  VERIFY(test_sum(VectorXf(10),
    LinearVectorization,NoUnrolling));

  VERIFY(test_sum(Matrix<float,5,2>(),
    NoVectorization,CompleteUnrolling));

  VERIFY(test_sum(Matrix<float,6,2>(),
    LinearVectorization,CompleteUnrolling));

  VERIFY(test_sum(Matrix<float,16,16>(),
    LinearVectorization,NoUnrolling));

  VERIFY(test_sum(Matrix<float,16,16>().block<4,4>(1,2),
    NoVectorization,CompleteUnrolling));

  VERIFY(test_sum(Matrix<float,16,16>().block<8,1>(1,2),
    LinearVectorization,CompleteUnrolling));

  VERIFY(test_sum(Matrix<double,7,3>(),
    NoVectorization,CompleteUnrolling));

#endif // EIGEN_VECTORIZE

}
<commit_msg>update vectorization_logic unit test wrt previous sum/redux change<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"
#include <typeinfo>

template<typename Dst, typename Src>
bool test_assign(const Dst&, const Src&, int vectorization, int unrolling)
{
  return ei_assign_traits<Dst,Src>::Vectorization==vectorization
    && ei_assign_traits<Dst,Src>::Unrolling==unrolling;
}

template<typename Xpr>
bool test_redux(const Xpr&, int vectorization, int unrolling)
{
  typedef ei_redux_traits<ei_scalar_sum_op<typename Xpr::Scalar>,Xpr> traits;
  return traits::Vectorization==vectorization && traits::Unrolling==unrolling;
}

void test_vectorization_logic()
{

#ifdef EIGEN_VECTORIZE

  VERIFY(test_assign(Vector4f(),Vector4f(),
    InnerVectorization,CompleteUnrolling));
  VERIFY(test_assign(Vector4f(),Vector4f()+Vector4f(),
    InnerVectorization,CompleteUnrolling));
  VERIFY(test_assign(Vector4f(),Vector4f().cwise() * Vector4f(),
    InnerVectorization,CompleteUnrolling));

  VERIFY(test_assign(Matrix4f(),Matrix4f(),
    InnerVectorization,CompleteUnrolling));
  VERIFY(test_assign(Matrix4f(),Matrix4f()+Matrix4f(),
    InnerVectorization,CompleteUnrolling));
  VERIFY(test_assign(Matrix4f(),Matrix4f().cwise() * Matrix4f(),
    InnerVectorization,CompleteUnrolling));

  VERIFY(test_assign(Matrix<float,16,16>(),Matrix<float,16,16>()+Matrix<float,16,16>(),
    InnerVectorization,InnerUnrolling));

  VERIFY(test_assign(Matrix<float,16,16,DontAlign>(),Matrix<float,16,16>()+Matrix<float,16,16>(),
    NoVectorization,InnerUnrolling));

  VERIFY(test_assign(Matrix<float,6,2>(),Matrix<float,6,2>().cwise() / Matrix<float,6,2>(),
    LinearVectorization,CompleteUnrolling));

  VERIFY(test_assign(Matrix<float,17,17>(),Matrix<float,17,17>()+Matrix<float,17,17>(),
    NoVectorization,InnerUnrolling));

  VERIFY(test_assign(Matrix<float,4,4>(),Matrix<float,17,17>().block<4,4>(2,3)+Matrix<float,17,17>().block<4,4>(10,4),
    NoVectorization,CompleteUnrolling));

  VERIFY(test_assign(MatrixXf(10,10),MatrixXf(20,20).block(10,10,2,3),
    SliceVectorization,NoUnrolling));

  VERIFY(test_redux(VectorXf(10),
    LinearVectorization,NoUnrolling));

  VERIFY(test_redux(Matrix<float,5,2>(),
    NoVectorization,CompleteUnrolling));

  VERIFY(test_redux(Matrix<float,6,2>(),
    LinearVectorization,CompleteUnrolling));

  VERIFY(test_redux(Matrix<float,16,16>(),
    LinearVectorization,NoUnrolling));

  VERIFY(test_redux(Matrix<float,16,16>().block<4,4>(1,2),
    NoVectorization,CompleteUnrolling));

  VERIFY(test_redux(Matrix<float,16,16>().block<8,1>(1,2),
    LinearVectorization,CompleteUnrolling));

  VERIFY(test_redux(Matrix<double,7,3>(),
    NoVectorization,CompleteUnrolling));

#endif // EIGEN_VECTORIZE

}
<|endoftext|>


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

#include "ozone/ui/events/event_converter_in_process.h"

#include <sys/mman.h>

#include "base/bind.h"
#include "base/thread_task_runner_handle.h"
#include "ozone/ui/events/event_factory_ozone_wayland.h"
#include "ozone/ui/events/ime_change_observer.h"
#include "ozone/ui/events/output_change_observer.h"
#include "ozone/ui/events/window_change_observer.h"
#include "ozone/ui/public/messages.h"
#include "ui/events/event_utils.h"
#include "ui/events/ozone/layout/keyboard_layout_engine_manager.h"
#include "ui/ozone/platform/drm/host/drm_gpu_platform_support_host.h"

namespace ui {

EventConverterInProcess::EventConverterInProcess(
    DrmGpuPlatformSupportHost* proxy)
    : EventConverterOzoneWayland(),
      proxy_(proxy),
      keyboard_(&modifiers_,
                KeyboardLayoutEngineManager::GetKeyboardLayoutEngine(),
                base::Bind(&EventConverterInProcess::PostUiEvent,
                           base::Unretained(this))),
      weak_ptr_factory_(this) {
  proxy_->RegisterHandler(this);
}

EventConverterInProcess::~EventConverterInProcess() {
}

void EventConverterInProcess::OnChannelEstablished(
  int host_id, scoped_refptr<base::SingleThreadTaskRunner> send_runner,
      const base::Callback<void(IPC::Message*)>& send_callback) {
}

void EventConverterInProcess::OnChannelDestroyed(int host_id) {
}

bool EventConverterInProcess::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(EventConverterInProcess, message)
  IPC_MESSAGE_HANDLER(WaylandInput_MotionNotify, MotionNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_ButtonNotify, ButtonNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_TouchNotify, TouchNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_AxisNotify, AxisNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_PointerEnter, PointerEnter)
  IPC_MESSAGE_HANDLER(WaylandInput_PointerLeave, PointerLeave)
  IPC_MESSAGE_HANDLER(WaylandInput_KeyNotify, KeyNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_VirtualKeyNotify, VirtualKeyNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_OutputSize, OutputSizeChanged)
  IPC_MESSAGE_HANDLER(WaylandInput_CloseWidget, CloseWidget)
  IPC_MESSAGE_HANDLER(WaylandWindow_Resized, WindowResized)
  IPC_MESSAGE_HANDLER(WaylandWindow_Activated, WindowActivated)
  IPC_MESSAGE_HANDLER(WaylandWindow_DeActivated, WindowDeActivated)
  IPC_MESSAGE_HANDLER(WaylandWindow_Unminimized, WindowUnminimized)
  IPC_MESSAGE_HANDLER(WaylandInput_Commit, Commit)
  IPC_MESSAGE_HANDLER(WaylandInput_PreeditChanged, PreeditChanged)
  IPC_MESSAGE_HANDLER(WaylandInput_PreeditEnd, PreeditEnd)
  IPC_MESSAGE_HANDLER(WaylandInput_PreeditStart, PreeditStart)
  IPC_MESSAGE_HANDLER(WaylandInput_InitializeXKB, InitializeXKB)
  IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void EventConverterInProcess::MotionNotify(float x, float y) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyMotion,
          weak_ptr_factory_.GetWeakPtr(), x, y));
}

void EventConverterInProcess::ButtonNotify(unsigned handle,
                                           ui::EventType type,
                                           ui::EventFlags flags,
                                           float x,
                                           float y) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyButtonPress,
          weak_ptr_factory_.GetWeakPtr(), handle, type, flags, x, y));
}

void EventConverterInProcess::AxisNotify(float x,
                                         float y,
                                         int xoffset,
                                         int yoffset) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyAxis,
          weak_ptr_factory_.GetWeakPtr(), x, y, xoffset, yoffset));
}

void EventConverterInProcess::PointerEnter(unsigned handle,
                                           float x,
                                           float y) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyPointerEnter,
          weak_ptr_factory_.GetWeakPtr(), handle, x, y));
}

void EventConverterInProcess::PointerLeave(unsigned handle,
                                           float x,
                                           float y) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyPointerLeave,
          weak_ptr_factory_.GetWeakPtr(), handle, x, y));
}

void EventConverterInProcess::KeyNotify(ui::EventType type,
                                        unsigned code,
                                        int device_id) {
  VirtualKeyNotify(type, code, device_id);
}

void EventConverterInProcess::VirtualKeyNotify(ui::EventType type,
                                               uint32_t key,
                                               int device_id) {
  keyboard_.OnKeyChange(key,
                        type != ui::ET_KEY_RELEASED,
                        ui::EventTimeForNow(),
                        device_id);
}

void EventConverterInProcess::TouchNotify(ui::EventType type,
                                          float x,
                                          float y,
                                          int32_t touch_id,
                                          uint32_t time_stamp) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyTouchEvent,
          weak_ptr_factory_.GetWeakPtr(), type, x, y, touch_id, time_stamp));
}

void EventConverterInProcess::CloseWidget(unsigned handle) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyCloseWidget,
          weak_ptr_factory_.GetWeakPtr(), handle));
}

void EventConverterInProcess::OutputSizeChanged(unsigned width,
                                                unsigned height) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyOutputSizeChanged,
          weak_ptr_factory_.GetWeakPtr(), width, height));
}

void EventConverterInProcess::WindowResized(unsigned handle,
                                            unsigned width,
                                            unsigned height) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyWindowResized,
          weak_ptr_factory_.GetWeakPtr(), handle, width, height));
}

void EventConverterInProcess::WindowUnminimized(unsigned handle) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyWindowUnminimized,
          weak_ptr_factory_.GetWeakPtr(), handle));
}

void EventConverterInProcess::WindowDeActivated(unsigned windowhandle) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyWindowDeActivated,
          weak_ptr_factory_.GetWeakPtr(), windowhandle));
}

void EventConverterInProcess::WindowActivated(unsigned windowhandle) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyWindowActivated,
          weak_ptr_factory_.GetWeakPtr(), windowhandle));
}

void EventConverterInProcess::Commit(unsigned handle, const std::string& text) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyCommit,
          weak_ptr_factory_.GetWeakPtr(), handle, text));
}

void EventConverterInProcess::PreeditChanged(unsigned handle,
                                             const std::string& text,
                                             const std::string& commit) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyPreeditChanged,
          weak_ptr_factory_.GetWeakPtr(), handle, text, commit));
}

void EventConverterInProcess::PreeditEnd() {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyPreeditEnd,
          weak_ptr_factory_.GetWeakPtr()));
}

void EventConverterInProcess::PreeditStart() {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyPreeditStart,
          weak_ptr_factory_.GetWeakPtr()));
}

void EventConverterInProcess::InitializeXKB(base::SharedMemoryHandle fd,
                                            uint32_t size) {
  char* map_str =
      reinterpret_cast<char*>(mmap(NULL,
                                   size,
                                   PROT_READ,
                                   MAP_SHARED,
                                   fd.fd,
                                   0));
  if (map_str == MAP_FAILED)
    return;

  KeyboardLayoutEngineManager::GetKeyboardLayoutEngine()->
      SetCurrentLayoutByName(map_str);
  munmap(map_str, size);
  close(fd.fd);
}

void EventConverterInProcess::PostUiEvent(Event* event) {
  DispatchEvent(event);
}

void EventConverterInProcess::DispatchUiEventTask(scoped_ptr<Event> event) {
  DispatchEvent(event.get());
}

void EventConverterInProcess::OnDispatcherListChanged() {
}

void EventConverterInProcess::NotifyMotion(float x,
                                           float y) {
  gfx::Point position(x, y);
  ui::MouseEvent mouseev(ui::ET_MOUSE_MOVED,
                         position,
                         position,
                         ui::EventTimeForNow(),
                         0,
                         0);
  DispatchEvent(&mouseev);
}

void EventConverterInProcess::NotifyButtonPress(unsigned handle,
                                                ui::EventType type,
                                                ui::EventFlags flags,
                                                float x,
                                                float y) {
  gfx::Point position(x, y);
  ui::MouseEvent mouseev(type,
                         position,
                         position,
                         ui::EventTimeForNow(),
                         flags,
                         flags);

  DispatchEvent(&mouseev);

  if (type == ui::ET_MOUSE_RELEASED) {
    ui::WindowChangeObserver* observer =
        ui::EventFactoryOzoneWayland::GetInstance()->
            GetWindowChangeObserver();
    if (observer)
      observer->OnWindowFocused(handle);
  }
}

void EventConverterInProcess::NotifyAxis(float x,
                                         float y,
                                         int xoffset,
                                         int yoffset) {
  gfx::Point position(x, y);
  ui::MouseEvent mouseev(ui::ET_MOUSEWHEEL,
                         position,
                         position,
                         ui::EventTimeForNow(),
                         0,
                         0);

  ui::MouseWheelEvent wheelev(mouseev, xoffset, yoffset);

  DispatchEvent(&wheelev);
}

void EventConverterInProcess::NotifyPointerEnter(unsigned handle,
                                                 float x,
                                                 float y) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowEnter(handle);

  gfx::Point position(x, y);
  ui::MouseEvent mouseev(ui::ET_MOUSE_ENTERED,
                         position,
                         position,
                         ui::EventTimeForNow(),
                         0,
                         0);

  DispatchEvent(&mouseev);
}

void EventConverterInProcess::NotifyPointerLeave(unsigned handle,
                                                 float x,
                                                 float y) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowLeave(handle);

  gfx::Point position(x, y);
  ui::MouseEvent mouseev(ui::ET_MOUSE_EXITED,
                         position,
                         position,
                         ui::EventTimeForNow(),
                         0,
                         0);

  DispatchEvent(&mouseev);
}

void EventConverterInProcess::NotifyTouchEvent(ui::EventType type,
                                               float x,
                                               float y,
                                               int32_t touch_id,
                                               uint32_t time_stamp) {
  gfx::Point position(x, y);
  base::TimeDelta time_delta = base::TimeDelta::FromMilliseconds(time_stamp);
  ui::TouchEvent touchev(type, position, touch_id, time_delta);
  DispatchEvent(&touchev);
}

void EventConverterInProcess::NotifyCloseWidget(unsigned handle) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowClose(handle);
}

void EventConverterInProcess::NotifyOutputSizeChanged(unsigned width,
                                                      unsigned height) {
  ui::OutputChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetOutputChangeObserver();
  if (observer)
    observer->OnOutputSizeChanged(width, height);
}

void EventConverterInProcess::NotifyWindowResized(unsigned handle,
                                                  unsigned width,
                                                  unsigned height) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowResized(handle, width, height);
}

void EventConverterInProcess::NotifyWindowUnminimized(unsigned handle) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowUnminimized(handle);
}

void EventConverterInProcess::NotifyWindowDeActivated(unsigned handle) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowDeActivated(handle);
}

void EventConverterInProcess::NotifyWindowActivated(unsigned handle) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowActivated(handle);
}

void EventConverterInProcess::NotifyCommit(unsigned handle,
                                           const std::string& text) {
  ui::IMEChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetIMEChangeObserver();
  if (observer)
    observer->OnCommit(handle, text);
}

void EventConverterInProcess::NotifyPreeditChanged(unsigned handle,
                                                   const std::string& text,
                                                   const std::string& commit) {
  ui::IMEChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetIMEChangeObserver();
  if (observer)
    observer->OnPreeditChanged(handle, text, commit);
}

void EventConverterInProcess::NotifyPreeditEnd() {
}

void EventConverterInProcess::NotifyPreeditStart() {
}

}  // namespace ui
<commit_msg>Gardening: Adopt to  https://codereview.chromium.org/1166113003/<commit_after>// Copyright 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ozone/ui/events/event_converter_in_process.h"

#include <sys/mman.h>

#include "base/bind.h"
#include "base/thread_task_runner_handle.h"
#include "ozone/ui/events/event_factory_ozone_wayland.h"
#include "ozone/ui/events/ime_change_observer.h"
#include "ozone/ui/events/output_change_observer.h"
#include "ozone/ui/events/window_change_observer.h"
#include "ozone/ui/public/messages.h"
#include "ui/events/event_utils.h"
#include "ui/events/ozone/layout/keyboard_layout_engine_manager.h"
#include "ui/ozone/platform/drm/host/drm_gpu_platform_support_host.h"

namespace ui {

EventConverterInProcess::EventConverterInProcess(
    DrmGpuPlatformSupportHost* proxy)
    : EventConverterOzoneWayland(),
      proxy_(proxy),
      keyboard_(&modifiers_,
                KeyboardLayoutEngineManager::GetKeyboardLayoutEngine(),
                base::Bind(&EventConverterInProcess::PostUiEvent,
                           base::Unretained(this))),
      weak_ptr_factory_(this) {
  proxy_->RegisterHandler(this);
}

EventConverterInProcess::~EventConverterInProcess() {
}

void EventConverterInProcess::OnChannelEstablished(
  int host_id, scoped_refptr<base::SingleThreadTaskRunner> send_runner,
      const base::Callback<void(IPC::Message*)>& send_callback) {
}

void EventConverterInProcess::OnChannelDestroyed(int host_id) {
}

bool EventConverterInProcess::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(EventConverterInProcess, message)
  IPC_MESSAGE_HANDLER(WaylandInput_MotionNotify, MotionNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_ButtonNotify, ButtonNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_TouchNotify, TouchNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_AxisNotify, AxisNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_PointerEnter, PointerEnter)
  IPC_MESSAGE_HANDLER(WaylandInput_PointerLeave, PointerLeave)
  IPC_MESSAGE_HANDLER(WaylandInput_KeyNotify, KeyNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_VirtualKeyNotify, VirtualKeyNotify)
  IPC_MESSAGE_HANDLER(WaylandInput_OutputSize, OutputSizeChanged)
  IPC_MESSAGE_HANDLER(WaylandInput_CloseWidget, CloseWidget)
  IPC_MESSAGE_HANDLER(WaylandWindow_Resized, WindowResized)
  IPC_MESSAGE_HANDLER(WaylandWindow_Activated, WindowActivated)
  IPC_MESSAGE_HANDLER(WaylandWindow_DeActivated, WindowDeActivated)
  IPC_MESSAGE_HANDLER(WaylandWindow_Unminimized, WindowUnminimized)
  IPC_MESSAGE_HANDLER(WaylandInput_Commit, Commit)
  IPC_MESSAGE_HANDLER(WaylandInput_PreeditChanged, PreeditChanged)
  IPC_MESSAGE_HANDLER(WaylandInput_PreeditEnd, PreeditEnd)
  IPC_MESSAGE_HANDLER(WaylandInput_PreeditStart, PreeditStart)
  IPC_MESSAGE_HANDLER(WaylandInput_InitializeXKB, InitializeXKB)
  IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void EventConverterInProcess::MotionNotify(float x, float y) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyMotion,
          weak_ptr_factory_.GetWeakPtr(), x, y));
}

void EventConverterInProcess::ButtonNotify(unsigned handle,
                                           ui::EventType type,
                                           ui::EventFlags flags,
                                           float x,
                                           float y) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyButtonPress,
          weak_ptr_factory_.GetWeakPtr(), handle, type, flags, x, y));
}

void EventConverterInProcess::AxisNotify(float x,
                                         float y,
                                         int xoffset,
                                         int yoffset) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyAxis,
          weak_ptr_factory_.GetWeakPtr(), x, y, xoffset, yoffset));
}

void EventConverterInProcess::PointerEnter(unsigned handle,
                                           float x,
                                           float y) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyPointerEnter,
          weak_ptr_factory_.GetWeakPtr(), handle, x, y));
}

void EventConverterInProcess::PointerLeave(unsigned handle,
                                           float x,
                                           float y) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyPointerLeave,
          weak_ptr_factory_.GetWeakPtr(), handle, x, y));
}

void EventConverterInProcess::KeyNotify(ui::EventType type,
                                        unsigned code,
                                        int device_id) {
  VirtualKeyNotify(type, code, device_id);
}

void EventConverterInProcess::VirtualKeyNotify(ui::EventType type,
                                               uint32_t key,
                                               int device_id) {
  keyboard_.OnKeyChange(key,
                        type != ui::ET_KEY_RELEASED,
                        false,
                        ui::EventTimeForNow(),
                        device_id);
}

void EventConverterInProcess::TouchNotify(ui::EventType type,
                                          float x,
                                          float y,
                                          int32_t touch_id,
                                          uint32_t time_stamp) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyTouchEvent,
          weak_ptr_factory_.GetWeakPtr(), type, x, y, touch_id, time_stamp));
}

void EventConverterInProcess::CloseWidget(unsigned handle) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyCloseWidget,
          weak_ptr_factory_.GetWeakPtr(), handle));
}

void EventConverterInProcess::OutputSizeChanged(unsigned width,
                                                unsigned height) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyOutputSizeChanged,
          weak_ptr_factory_.GetWeakPtr(), width, height));
}

void EventConverterInProcess::WindowResized(unsigned handle,
                                            unsigned width,
                                            unsigned height) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyWindowResized,
          weak_ptr_factory_.GetWeakPtr(), handle, width, height));
}

void EventConverterInProcess::WindowUnminimized(unsigned handle) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyWindowUnminimized,
          weak_ptr_factory_.GetWeakPtr(), handle));
}

void EventConverterInProcess::WindowDeActivated(unsigned windowhandle) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyWindowDeActivated,
          weak_ptr_factory_.GetWeakPtr(), windowhandle));
}

void EventConverterInProcess::WindowActivated(unsigned windowhandle) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyWindowActivated,
          weak_ptr_factory_.GetWeakPtr(), windowhandle));
}

void EventConverterInProcess::Commit(unsigned handle, const std::string& text) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyCommit,
          weak_ptr_factory_.GetWeakPtr(), handle, text));
}

void EventConverterInProcess::PreeditChanged(unsigned handle,
                                             const std::string& text,
                                             const std::string& commit) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyPreeditChanged,
          weak_ptr_factory_.GetWeakPtr(), handle, text, commit));
}

void EventConverterInProcess::PreeditEnd() {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyPreeditEnd,
          weak_ptr_factory_.GetWeakPtr()));
}

void EventConverterInProcess::PreeditStart() {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&EventConverterInProcess::NotifyPreeditStart,
          weak_ptr_factory_.GetWeakPtr()));
}

void EventConverterInProcess::InitializeXKB(base::SharedMemoryHandle fd,
                                            uint32_t size) {
  char* map_str =
      reinterpret_cast<char*>(mmap(NULL,
                                   size,
                                   PROT_READ,
                                   MAP_SHARED,
                                   fd.fd,
                                   0));
  if (map_str == MAP_FAILED)
    return;

  KeyboardLayoutEngineManager::GetKeyboardLayoutEngine()->
      SetCurrentLayoutByName(map_str);
  munmap(map_str, size);
  close(fd.fd);
}

void EventConverterInProcess::PostUiEvent(Event* event) {
  DispatchEvent(event);
}

void EventConverterInProcess::DispatchUiEventTask(scoped_ptr<Event> event) {
  DispatchEvent(event.get());
}

void EventConverterInProcess::OnDispatcherListChanged() {
}

void EventConverterInProcess::NotifyMotion(float x,
                                           float y) {
  gfx::Point position(x, y);
  ui::MouseEvent mouseev(ui::ET_MOUSE_MOVED,
                         position,
                         position,
                         ui::EventTimeForNow(),
                         0,
                         0);
  DispatchEvent(&mouseev);
}

void EventConverterInProcess::NotifyButtonPress(unsigned handle,
                                                ui::EventType type,
                                                ui::EventFlags flags,
                                                float x,
                                                float y) {
  gfx::Point position(x, y);
  ui::MouseEvent mouseev(type,
                         position,
                         position,
                         ui::EventTimeForNow(),
                         flags,
                         flags);

  DispatchEvent(&mouseev);

  if (type == ui::ET_MOUSE_RELEASED) {
    ui::WindowChangeObserver* observer =
        ui::EventFactoryOzoneWayland::GetInstance()->
            GetWindowChangeObserver();
    if (observer)
      observer->OnWindowFocused(handle);
  }
}

void EventConverterInProcess::NotifyAxis(float x,
                                         float y,
                                         int xoffset,
                                         int yoffset) {
  gfx::Point position(x, y);
  ui::MouseEvent mouseev(ui::ET_MOUSEWHEEL,
                         position,
                         position,
                         ui::EventTimeForNow(),
                         0,
                         0);

  ui::MouseWheelEvent wheelev(mouseev, xoffset, yoffset);

  DispatchEvent(&wheelev);
}

void EventConverterInProcess::NotifyPointerEnter(unsigned handle,
                                                 float x,
                                                 float y) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowEnter(handle);

  gfx::Point position(x, y);
  ui::MouseEvent mouseev(ui::ET_MOUSE_ENTERED,
                         position,
                         position,
                         ui::EventTimeForNow(),
                         0,
                         0);

  DispatchEvent(&mouseev);
}

void EventConverterInProcess::NotifyPointerLeave(unsigned handle,
                                                 float x,
                                                 float y) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowLeave(handle);

  gfx::Point position(x, y);
  ui::MouseEvent mouseev(ui::ET_MOUSE_EXITED,
                         position,
                         position,
                         ui::EventTimeForNow(),
                         0,
                         0);

  DispatchEvent(&mouseev);
}

void EventConverterInProcess::NotifyTouchEvent(ui::EventType type,
                                               float x,
                                               float y,
                                               int32_t touch_id,
                                               uint32_t time_stamp) {
  gfx::Point position(x, y);
  base::TimeDelta time_delta = base::TimeDelta::FromMilliseconds(time_stamp);
  ui::TouchEvent touchev(type, position, touch_id, time_delta);
  DispatchEvent(&touchev);
}

void EventConverterInProcess::NotifyCloseWidget(unsigned handle) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowClose(handle);
}

void EventConverterInProcess::NotifyOutputSizeChanged(unsigned width,
                                                      unsigned height) {
  ui::OutputChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetOutputChangeObserver();
  if (observer)
    observer->OnOutputSizeChanged(width, height);
}

void EventConverterInProcess::NotifyWindowResized(unsigned handle,
                                                  unsigned width,
                                                  unsigned height) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowResized(handle, width, height);
}

void EventConverterInProcess::NotifyWindowUnminimized(unsigned handle) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowUnminimized(handle);
}

void EventConverterInProcess::NotifyWindowDeActivated(unsigned handle) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowDeActivated(handle);
}

void EventConverterInProcess::NotifyWindowActivated(unsigned handle) {
  ui::WindowChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
  if (observer)
    observer->OnWindowActivated(handle);
}

void EventConverterInProcess::NotifyCommit(unsigned handle,
                                           const std::string& text) {
  ui::IMEChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetIMEChangeObserver();
  if (observer)
    observer->OnCommit(handle, text);
}

void EventConverterInProcess::NotifyPreeditChanged(unsigned handle,
                                                   const std::string& text,
                                                   const std::string& commit) {
  ui::IMEChangeObserver* observer =
      ui::EventFactoryOzoneWayland::GetInstance()->GetIMEChangeObserver();
  if (observer)
    observer->OnPreeditChanged(handle, text, commit);
}

void EventConverterInProcess::NotifyPreeditEnd() {
}

void EventConverterInProcess::NotifyPreeditStart() {
}

}  // namespace ui
<|endoftext|>


<commit_before>// Copyright 2021 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "open_spiel/bots/human/human_bot.h"

#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>

#include "open_spiel/abseil-cpp/absl/strings/numbers.h"

namespace open_spiel {
namespace {

const int kMaxWidth = 80;
const int kPadding = 2;

void PrintColumns(const std::vector<std::string> &strings) {
  std::string padding_string(kPadding, ' ');

  int longest_string_length = 0;
  for (const std::string &string : strings) {
    if (string.length() > longest_string_length) {
      longest_string_length = string.length();
    }
  }

  int max_columns = (kMaxWidth - 1) / (longest_string_length + 2 * kPadding);
  int rows = ceil((float)strings.size() / (float)max_columns);
  int columns = ceil((float)strings.size() / (float)rows);
  for (int row = 0; row < rows; ++row) {
    for (int column = 0; column < columns; ++column) {
      int index = row + column * rows;
      if (index < strings.size()) {
        std::cout << std::left << std::setw(longest_string_length + kPadding)
                  << padding_string << strings[index];
      }
    }
    std::cout << std::endl;
  }
}

}  // namespace

Action HumanBot::Step(const State &state) {
  std::vector<Action> legal_actions = state.LegalActions(state.CurrentPlayer());

  if (legal_actions.empty()) {
    return kInvalidAction;
  }

  std::unordered_map<std::string, Action> action_map;
  for (Action legal_action : legal_actions) {
    action_map[state.ActionToString(legal_action)] = legal_action;
  }

  while (true) {
    Action action;
    std::string action_string = "";

    std::cout << "Choose an action (empty to print legal actions): ";
    std::getline(std::cin, action_string);

    // Print the legal actions if no action is given.
    if (action_string.empty()) {
      std::cout << "Legal action(s):" << std::endl;

      std::vector<std::string> legal_action_strings;
      std::vector<std::pair<std::string, Action>> sorted_action_map(
          action_map.begin(), action_map.end());

      std::sort(sorted_action_map.begin(), sorted_action_map.end(),
                [](const auto &left, const auto &right) {
                  return left.first.compare(right.first);
                });

      int longest_action_length = 0;
      for (const Action &legal_action : legal_actions) {
        int action_length = std::to_string(legal_action).length();
        if (action_length > longest_action_length) {
          longest_action_length = action_length;
        }
      }

      for (const auto &string_action_pair : sorted_action_map) {
        std::string action_string = string_action_pair.first;
        std::string action_int_string =
            std::to_string(string_action_pair.second);
        std::string action_padding(
            longest_action_length - action_int_string.length(), ' ');
        legal_action_strings.push_back(absl::StrCat(
            action_padding, action_int_string, ": ", action_string));
      }
      PrintColumns(legal_action_strings);
      continue;
    }

    // Return the action if a valid string is given.
    if (action_map.find(action_string) != action_map.end()) {
      return action_map[action_string];
    }

    // Return the action if a valid integer is given.
    bool parse_succeeded = absl::SimpleAtoi(action_string, &action);
    if (!parse_succeeded) {
      std::cout << "Could not parse the action: " << action_string << std::endl;
      continue;
    }

    for (Action legal_action : legal_actions) {
      if (action == legal_action) {
        return action;
      }
    }

    // The input was not valid.
    std::cout << "Illegal action selected: " << action_string << std::endl;
  }
}

}  // namespace open_spiel
<commit_msg>Fix comparator, std::basic_string::compare returns an int, not bool.<commit_after>// Copyright 2021 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "open_spiel/bots/human/human_bot.h"

#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>

#include "open_spiel/abseil-cpp/absl/strings/numbers.h"

namespace open_spiel {
namespace {

const int kMaxWidth = 80;
const int kPadding = 2;

void PrintColumns(const std::vector<std::string> &strings) {
  std::string padding_string(kPadding, ' ');

  int longest_string_length = 0;
  for (const std::string &string : strings) {
    if (string.length() > longest_string_length) {
      longest_string_length = string.length();
    }
  }

  int max_columns = (kMaxWidth - 1) / (longest_string_length + 2 * kPadding);
  int rows = ceil((float)strings.size() / (float)max_columns);
  int columns = ceil((float)strings.size() / (float)rows);
  for (int row = 0; row < rows; ++row) {
    for (int column = 0; column < columns; ++column) {
      int index = row + column * rows;
      if (index < strings.size()) {
        std::cout << std::left << std::setw(longest_string_length + kPadding)
                  << padding_string << strings[index];
      }
    }
    std::cout << std::endl;
  }
}

}  // namespace

Action HumanBot::Step(const State &state) {
  std::vector<Action> legal_actions = state.LegalActions(state.CurrentPlayer());

  if (legal_actions.empty()) {
    return kInvalidAction;
  }

  std::unordered_map<std::string, Action> action_map;
  for (Action legal_action : legal_actions) {
    action_map[state.ActionToString(legal_action)] = legal_action;
  }

  while (true) {
    Action action;
    std::string action_string = "";

    std::cout << "Choose an action (empty to print legal actions): ";
    std::getline(std::cin, action_string);

    // Print the legal actions if no action is given.
    if (action_string.empty()) {
      std::cout << "Legal action(s):" << std::endl;

      std::vector<std::string> legal_action_strings;
      std::vector<std::pair<std::string, Action>> sorted_action_map(
          action_map.begin(), action_map.end());

      std::sort(sorted_action_map.begin(), sorted_action_map.end(),
                [](const auto &left, const auto &right) {
                  return left.first < right.first;
                });

      int longest_action_length = 0;
      for (const Action &legal_action : legal_actions) {
        int action_length = std::to_string(legal_action).length();
        if (action_length > longest_action_length) {
          longest_action_length = action_length;
        }
      }

      for (const auto &string_action_pair : sorted_action_map) {
        std::string action_string = string_action_pair.first;
        std::string action_int_string =
            std::to_string(string_action_pair.second);
        std::string action_padding(
            longest_action_length - action_int_string.length(), ' ');
        legal_action_strings.push_back(absl::StrCat(
            action_padding, action_int_string, ": ", action_string));
      }
      PrintColumns(legal_action_strings);
      continue;
    }

    // Return the action if a valid string is given.
    if (action_map.find(action_string) != action_map.end()) {
      return action_map[action_string];
    }

    // Return the action if a valid integer is given.
    bool parse_succeeded = absl::SimpleAtoi(action_string, &action);
    if (!parse_succeeded) {
      std::cout << "Could not parse the action: " << action_string << std::endl;
      continue;
    }

    for (Action legal_action : legal_actions) {
      if (action == legal_action) {
        return action;
      }
    }

    // The input was not valid.
    std::cout << "Illegal action selected: " << action_string << std::endl;
  }
}

}  // namespace open_spiel
<|endoftext|>


<commit_before>// A fuzzer for floating-point formatter.
// For the license information refer to format.h.

#include <cstdint>
#include <cstdlib>
#include <stdexcept>
#include <limits>
#include <fmt/format.h>

#include "fuzzer-common.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  if (size <= sizeof(double) || !std::numeric_limits<double>::is_iec559)
    return 0;

  auto value = assign_from_buf<double>(data);
  auto buffer = fmt::memory_buffer();
  fmt::format_to(buffer, "{}", value);

  // Check a round trip.
  if (std::isnan(value)) {
    auto nan = std::signbit(value) ? "-nan" : "nan";
    if (fmt::string_view(buffer.data(), buffer.size()) != nan)
      throw std::runtime_error("round trip failure");
    return 0;
  }
  buffer.push_back('\0');
  char* ptr = nullptr;
  if (std::strtod(buffer.data(), &ptr) != value)
    throw std::runtime_error("round trip failure");
  if (ptr != buffer.end())
    throw std::runtime_error("unparsed output");
  return 0;
}
<commit_msg>Fix float fuzzer<commit_after>// A fuzzer for floating-point formatter.
// For the license information refer to format.h.

#include <cstdint>
#include <cstdlib>
#include <stdexcept>
#include <limits>
#include <fmt/format.h>

#include "fuzzer-common.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  if (size <= sizeof(double) || !std::numeric_limits<double>::is_iec559)
    return 0;

  auto value = assign_from_buf<double>(data);
  auto buffer = fmt::memory_buffer();
  fmt::format_to(buffer, "{}", value);

  // Check a round trip.
  if (std::isnan(value)) {
    auto nan = std::signbit(value) ? "-nan" : "nan";
    if (fmt::string_view(buffer.data(), buffer.size()) != nan)
      throw std::runtime_error("round trip failure");
    return 0;
  }
  buffer.push_back('\0');
  char* ptr = nullptr;
  if (std::strtod(buffer.data(), &ptr) != value)
    throw std::runtime_error("round trip failure");
  if (ptr + 1 != buffer.end())
    throw std::runtime_error("unparsed output");
  return 0;
}
<|endoftext|>