<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "GenericConstantRankTwoTensor.h"

registerMooseObject("MooseApp", GenericConstantRankTwoTensor);
registerMooseObject("MooseApp", ADGenericConstantRankTwoTensor);

template <bool is_ad>
InputParameters
GenericConstantRankTwoTensorTempl<is_ad>::validParams()
{
  InputParameters params = Material::validParams();
  params.addClassDescription(
      "Object for declaring a constant rank two tensor as a material property.");
  params.addRequiredParam<std::vector<Real>>(
      "tensor_values", "Vector of values defining the constant rank two tensor");
  params.addRequiredParam<MaterialPropertyName>(
      "tensor_name", "Name of the tensor material property to be created");
  params.set<MooseEnum>("constant_on") = "SUBDOMAIN";
  return params;
}

template <bool is_ad>
GenericConstantRankTwoTensorTempl<is_ad>::GenericConstantRankTwoTensorTempl(
    const InputParameters & parameters)
  : Material(parameters),
    _prop(
        declareGenericProperty<RankTwoTensor, is_ad>(getParam<MaterialPropertyName>("tensor_name")))
{
  _tensor.fillFromInputVector(getParam<std::vector<Real>>("tensor_values"));
}

template <bool is_ad>
void
GenericConstantRankTwoTensorTempl<is_ad>::initQpStatefulProperties()
{
  GenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties();
}

template <bool is_ad>
void
GenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties()
{
  _prop[_qp] = _tensor;
}

template class GenericConstantRankTwoTensorTempl<false>;
template class GenericConstantRankTwoTensorTempl<true>;<commit_msg>This should resolve #22619. Added an extra empty line at the end<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "GenericConstantRankTwoTensor.h"

registerMooseObject("MooseApp", GenericConstantRankTwoTensor);
registerMooseObject("MooseApp", ADGenericConstantRankTwoTensor);

template <bool is_ad>
InputParameters
GenericConstantRankTwoTensorTempl<is_ad>::validParams()
{
  InputParameters params = Material::validParams();
  params.addClassDescription(
      "Object for declaring a constant rank two tensor as a material property.");
  params.addRequiredParam<std::vector<Real>>(
      "tensor_values", "Vector of values defining the constant rank two tensor");
  params.addRequiredParam<MaterialPropertyName>(
      "tensor_name", "Name of the tensor material property to be created");
  params.set<MooseEnum>("constant_on") = "SUBDOMAIN";
  return params;
}

template <bool is_ad>
GenericConstantRankTwoTensorTempl<is_ad>::GenericConstantRankTwoTensorTempl(
    const InputParameters & parameters)
  : Material(parameters),
    _prop(
        declareGenericProperty<RankTwoTensor, is_ad>(getParam<MaterialPropertyName>("tensor_name")))
{
  _tensor.fillFromInputVector(getParam<std::vector<Real>>("tensor_values"));
}

template <bool is_ad>
void
GenericConstantRankTwoTensorTempl<is_ad>::initQpStatefulProperties()
{
  GenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties();
}

template <bool is_ad>
void
GenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties()
{
  _prop[_qp] = _tensor;
}

template class GenericConstantRankTwoTensorTempl<false>;
template class GenericConstantRankTwoTensorTempl<true>;
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/procedures/hwp/initfiles/p10_nmmu_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019,2020                        */
/* [+] 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                                                     */
#include "p10_nmmu_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

fapi2::ReturnCode p10_nmmu_scom(const fapi2::Target<fapi2::TARGET_TYPE_NMMU>& TGT0,
                                const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT2)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));
        fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE_Type l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE, TGT2, l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x2010c15ull, l_scom_buffer ));

            if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE != fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP))
            {
                constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON = 0x1;
                l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON );
            }
            else if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP))
            {
                constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF = 0x0;
                l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x2010c15ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>Enable epsilons in nmmu scom initfile<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/procedures/hwp/initfiles/p10_nmmu_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019,2020                        */
/* [+] 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                                                     */
#include "p10_nmmu_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_0x001 = 0x001;

fapi2::ReturnCode p10_nmmu_scom(const fapi2::Target<fapi2::TARGET_TYPE_NMMU>& TGT0,
                                const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT2)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));
        fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE_Type l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE, TGT2, l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE));
        fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T1_Type l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T1, TGT2, l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1));
        fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T2_Type l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T2, TGT2, l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x2010c15ull, l_scom_buffer ));

            if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE != fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP))
            {
                constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON = 0x1;
                l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON );
            }
            else if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP))
            {
                constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF = 0x0;
                l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x2010c15ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x2010c1dull, l_scom_buffer ));

            if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1 != literal_0))
            {
                l_scom_buffer.insert<0, 12, 52, uint64_t>(l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1 );
            }
            else if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1 == literal_0))
            {
                l_scom_buffer.insert<0, 12, 52, uint64_t>(literal_0x001 );
            }

            if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2 != literal_0))
            {
                l_scom_buffer.insert<16, 12, 52, uint64_t>(l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2 );
            }
            else if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2 == literal_0))
            {
                l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x001 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x2010c1dull, l_scom_buffer));
        }

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


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

#include "scheduling/request-pool-service.h"

#include <list>
#include <string>

#include "common/logging.h"
#include "rpc/thrift-util.h"
#include "util/jni-util.h"
#include "util/parse-util.h"

using namespace std;
using namespace impala;

DEFINE_string(fair_scheduler_allocation_path, "", "Path to the fair scheduler "
    "allocation file (fair-scheduler.xml).");
DEFINE_string(llama_site_path, "", "Path to the Llama configuration file "
    "(llama-site.xml). If set, fair_scheduler_allocation_path must also be set.");

// The default_pool parameters are used if fair scheduler allocation and Llama
// configuration files are not provided.
DEFINE_int64(default_pool_max_requests, -1, "Maximum number of concurrent outstanding "
    "requests allowed to run before queueing incoming requests. A negative value "
    "indicates no limit. 0 indicates no requests will be admitted. Ignored if "
    "fair_scheduler_config_path and llama_site_path are set.");
DEFINE_string(default_pool_mem_limit, "", "Maximum amount of memory that all "
    "outstanding requests in this pool may use before new requests to this pool"
    " are queued. Specified as a number of bytes ('<int>[bB]?'), megabytes "
    "('<float>[mM]'), gigabytes ('<float>[gG]'), or percentage of the physical memory "
    "('<int>%'). 0 or not setting indicates no limit. Defaults to bytes if no unit is "
    "given. Ignored if fair_scheduler_config_path and llama_site_path are set.");
DEFINE_int64(default_pool_max_queued, 0, "Maximum number of requests allowed to be "
    "queued before rejecting requests. A negative value or 0 indicates requests "
    "will always be rejected once the maximum number of concurrent requests are "
    "executing. Ignored if fair_scheduler_config_path and "
    "llama_site_path are set.");

// Flags to disable the pool limits for all pools.
DEFINE_bool(disable_pool_mem_limits, false, "Disables all per-pool mem limits.");
DEFINE_bool(disable_pool_max_requests, false, "Disables all per-pool limits on the "
    "maximum number of running requests.");

DECLARE_bool(enable_rm);

// Pool name used when the configuration files are not specified.
const string DEFAULT_POOL_NAME = "default-pool";

RequestPoolService::RequestPoolService() {
  if (FLAGS_fair_scheduler_allocation_path.empty() &&
      FLAGS_llama_site_path.empty()) {
    if (FLAGS_enable_rm) {
      LOG(ERROR) << "If resource management is enabled, -fair_scheduler_allocation_path "
                 << "is required.";
      exit(1);
    }
    default_pool_only_ = true;
    bool is_percent; // not used
    int64_t bytes_limit = ParseUtil::ParseMemSpec(FLAGS_default_pool_mem_limit,
        &is_percent);
    // -1 indicates an error occurred
    if (bytes_limit < 0) {
      LOG(ERROR) << "Unable to parse default pool mem limit from '"
                 << FLAGS_default_pool_mem_limit << "'.";
      exit(1);
    }
    // 0 indicates no limit or not set
    if (bytes_limit == 0) {
      default_pool_mem_limit_ = -1;
    } else {
      default_pool_mem_limit_ = bytes_limit;
    }
    return;
  }
  default_pool_only_ = false;

  jmethodID start_id; // RequestPoolService.start(), only called in this method.
  JniMethodDescriptor methods[] = {
    {"<init>", "(Ljava/lang/String;Ljava/lang/String;)V", &ctor_},
    {"start", "()V", &start_id},
    {"resolveRequestPool", "([B)[B", &resolve_request_pool_id_},
    {"getPoolConfig", "([B)[B", &get_pool_config_id_}};

  JNIEnv* jni_env = getJNIEnv();
  request_pool_service_class_ =
    jni_env->FindClass("com/cloudera/impala/util/RequestPoolService");
  EXIT_IF_EXC(jni_env);
  uint32_t num_methods = sizeof(methods) / sizeof(methods[0]);
  for (int i = 0; i < num_methods; ++i) {
    EXIT_IF_ERROR(JniUtil::LoadJniMethod(jni_env, request_pool_service_class_,
        &(methods[i])));
  }

  jstring fair_scheduler_config_path =
      jni_env->NewStringUTF(FLAGS_fair_scheduler_allocation_path.c_str());
  EXIT_IF_EXC(jni_env);
  jstring llama_site_path =
      jni_env->NewStringUTF(FLAGS_llama_site_path.c_str());
  EXIT_IF_EXC(jni_env);

  jobject request_pool_service = jni_env->NewObject(request_pool_service_class_, ctor_,
      fair_scheduler_config_path, llama_site_path);
  EXIT_IF_EXC(jni_env);
  EXIT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, request_pool_service,
      &request_pool_service_));
  jni_env->CallObjectMethod(request_pool_service_, start_id);
  EXIT_IF_EXC(jni_env);
}

Status RequestPoolService::ResolveRequestPool(const string& requested_pool_name,
    const string& user, TResolveRequestPoolResult* resolved_pool) {
  if (default_pool_only_) {
    resolved_pool->__set_resolved_pool(DEFAULT_POOL_NAME);
    resolved_pool->__set_has_access(true);
    return Status::OK;
  }

  TResolveRequestPoolParams params;
  params.__set_user(user);
  params.__set_requested_pool(requested_pool_name);
  return JniUtil::CallJniMethod(request_pool_service_, resolve_request_pool_id_, params,
      resolved_pool);
}

Status RequestPoolService::GetPoolConfig(const string& pool_name,
    TPoolConfigResult* pool_config) {
  if (default_pool_only_) {
    pool_config->__set_max_requests(
        FLAGS_disable_pool_max_requests ? -1 : FLAGS_default_pool_max_requests);
    pool_config->__set_mem_limit(
        FLAGS_disable_pool_mem_limits ? -1 : default_pool_mem_limit_);
    pool_config->__set_max_queued(FLAGS_default_pool_max_queued);
    return Status::OK;
  }

  TPoolConfigParams params;
  params.__set_pool(pool_name);
  RETURN_IF_ERROR(JniUtil::CallJniMethod(
        request_pool_service_, get_pool_config_id_, params, pool_config));
  if (FLAGS_disable_pool_max_requests) pool_config->__set_max_requests(-1);
  if (FLAGS_disable_pool_mem_limits) pool_config->__set_mem_limit(-1);
  return Status::OK;
}
<commit_msg>Admission controller: Change default values for the "default pool"<commit_after>// Copyright 2014 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "scheduling/request-pool-service.h"

#include <list>
#include <string>

#include "common/logging.h"
#include "rpc/thrift-util.h"
#include "util/jni-util.h"
#include "util/parse-util.h"

using namespace std;
using namespace impala;

DEFINE_string(fair_scheduler_allocation_path, "", "Path to the fair scheduler "
    "allocation file (fair-scheduler.xml).");
DEFINE_string(llama_site_path, "", "Path to the Llama configuration file "
    "(llama-site.xml). If set, fair_scheduler_allocation_path must also be set.");

// The default_pool parameters are used if fair scheduler allocation and Llama
// configuration files are not provided. The default values for this 'default pool'
// are the same as the default values for pools defined via the fair scheduler
// allocation file and Llama configurations.
DEFINE_int64(default_pool_max_requests, 20, "Maximum number of concurrent outstanding "
    "requests allowed to run before queueing incoming requests. A negative value "
    "indicates no limit. 0 indicates no requests will be admitted. Ignored if "
    "fair_scheduler_config_path and llama_site_path are set.");
DEFINE_string(default_pool_mem_limit, "", "Maximum amount of memory that all "
    "outstanding requests in this pool may use before new requests to this pool"
    " are queued. Specified as a number of bytes ('<int>[bB]?'), megabytes "
    "('<float>[mM]'), gigabytes ('<float>[gG]'), or percentage of the physical memory "
    "('<int>%'). 0 or not setting indicates no limit. Defaults to bytes if no unit is "
    "given. Ignored if fair_scheduler_config_path and llama_site_path are set.");
DEFINE_int64(default_pool_max_queued, 50, "Maximum number of requests allowed to be "
    "queued before rejecting requests. A negative value or 0 indicates requests "
    "will always be rejected once the maximum number of concurrent requests are "
    "executing. Ignored if fair_scheduler_config_path and "
    "llama_site_path are set.");

// Flags to disable the pool limits for all pools.
DEFINE_bool(disable_pool_mem_limits, false, "Disables all per-pool mem limits.");
DEFINE_bool(disable_pool_max_requests, false, "Disables all per-pool limits on the "
    "maximum number of running requests.");

DECLARE_bool(enable_rm);

// Pool name used when the configuration files are not specified.
const string DEFAULT_POOL_NAME = "default-pool";

RequestPoolService::RequestPoolService() {
  if (FLAGS_fair_scheduler_allocation_path.empty() &&
      FLAGS_llama_site_path.empty()) {
    if (FLAGS_enable_rm) {
      LOG(ERROR) << "If resource management is enabled, -fair_scheduler_allocation_path "
                 << "is required.";
      exit(1);
    }
    default_pool_only_ = true;
    bool is_percent; // not used
    int64_t bytes_limit = ParseUtil::ParseMemSpec(FLAGS_default_pool_mem_limit,
        &is_percent);
    // -1 indicates an error occurred
    if (bytes_limit < 0) {
      LOG(ERROR) << "Unable to parse default pool mem limit from '"
                 << FLAGS_default_pool_mem_limit << "'.";
      exit(1);
    }
    // 0 indicates no limit or not set
    if (bytes_limit == 0) {
      default_pool_mem_limit_ = -1;
    } else {
      default_pool_mem_limit_ = bytes_limit;
    }
    return;
  }
  default_pool_only_ = false;

  jmethodID start_id; // RequestPoolService.start(), only called in this method.
  JniMethodDescriptor methods[] = {
    {"<init>", "(Ljava/lang/String;Ljava/lang/String;)V", &ctor_},
    {"start", "()V", &start_id},
    {"resolveRequestPool", "([B)[B", &resolve_request_pool_id_},
    {"getPoolConfig", "([B)[B", &get_pool_config_id_}};

  JNIEnv* jni_env = getJNIEnv();
  request_pool_service_class_ =
    jni_env->FindClass("com/cloudera/impala/util/RequestPoolService");
  EXIT_IF_EXC(jni_env);
  uint32_t num_methods = sizeof(methods) / sizeof(methods[0]);
  for (int i = 0; i < num_methods; ++i) {
    EXIT_IF_ERROR(JniUtil::LoadJniMethod(jni_env, request_pool_service_class_,
        &(methods[i])));
  }

  jstring fair_scheduler_config_path =
      jni_env->NewStringUTF(FLAGS_fair_scheduler_allocation_path.c_str());
  EXIT_IF_EXC(jni_env);
  jstring llama_site_path =
      jni_env->NewStringUTF(FLAGS_llama_site_path.c_str());
  EXIT_IF_EXC(jni_env);

  jobject request_pool_service = jni_env->NewObject(request_pool_service_class_, ctor_,
      fair_scheduler_config_path, llama_site_path);
  EXIT_IF_EXC(jni_env);
  EXIT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, request_pool_service,
      &request_pool_service_));
  jni_env->CallObjectMethod(request_pool_service_, start_id);
  EXIT_IF_EXC(jni_env);
}

Status RequestPoolService::ResolveRequestPool(const string& requested_pool_name,
    const string& user, TResolveRequestPoolResult* resolved_pool) {
  if (default_pool_only_) {
    resolved_pool->__set_resolved_pool(DEFAULT_POOL_NAME);
    resolved_pool->__set_has_access(true);
    return Status::OK;
  }

  TResolveRequestPoolParams params;
  params.__set_user(user);
  params.__set_requested_pool(requested_pool_name);
  return JniUtil::CallJniMethod(request_pool_service_, resolve_request_pool_id_, params,
      resolved_pool);
}

Status RequestPoolService::GetPoolConfig(const string& pool_name,
    TPoolConfigResult* pool_config) {
  if (default_pool_only_) {
    pool_config->__set_max_requests(
        FLAGS_disable_pool_max_requests ? -1 : FLAGS_default_pool_max_requests);
    pool_config->__set_mem_limit(
        FLAGS_disable_pool_mem_limits ? -1 : default_pool_mem_limit_);
    pool_config->__set_max_queued(FLAGS_default_pool_max_queued);
    return Status::OK;
  }

  TPoolConfigParams params;
  params.__set_pool(pool_name);
  RETURN_IF_ERROR(JniUtil::CallJniMethod(
        request_pool_service_, get_pool_config_id_, params, pool_config));
  if (FLAGS_disable_pool_max_requests) pool_config->__set_max_requests(-1);
  if (FLAGS_disable_pool_mem_limits) pool_config->__set_mem_limit(-1);
  return Status::OK;
}
<|endoftext|>


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

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD

#include "scitems.hxx"      // fuer tbxctrls etc.
#include "scmod.hxx"
#include "scresid.hxx"
#include "sc.hrc"
#include "cfgids.hxx"

//! die Registrierung wird wegen CLOOKs in ein eigenes File wandern muessen...

// Interface-Registrierung
#include "docsh.hxx"
#include "tabvwsh.hxx"
#include "prevwsh.hxx"
#include "drawsh.hxx"
#include "drformsh.hxx"
#include "drtxtob.hxx"
#include "editsh.hxx"
#include "pivotsh.hxx"
#include "auditsh.hxx"
#include "cellsh.hxx"
#include "oleobjsh.hxx"
#include "chartsh.hxx"
#include "graphsh.hxx"
#include "pgbrksh.hxx"

#include "docpool.hxx"
#include "appoptio.hxx"

// Controls

#include <svx/tbxalign.hxx>
#include <svx/tbxctl.hxx>
#include <svx/fillctrl.hxx>
#include <svx/linectrl.hxx>
#include <svx/tbcontrl.hxx>
#include <svx/selctrl.hxx>
#include <svx/insctrl.hxx>
#include <svx/zoomctrl.hxx>
#include <svx/flditem.hxx>
#include <svx/modctrl.hxx>
#include <svx/pszctrl.hxx>
#include <svx/fntctl.hxx>
#include <svx/fntszctl.hxx>

#include "tbinsert.hxx"

// Child-Windows
#include "reffact.hxx"
#include "navipi.hxx"
#include "inputwin.hxx"
#include <svx/fontwork.hxx>
#include <svx/srchdlg.hxx>
#include <offmgr/hyprlink.hxx>
#include <svx/imapdlg.hxx>

#include "editutil.hxx"
#include <svx/svdfield.hxx>     //  SdrRegisterFieldClasses

#include "dwfunctr.hxx"
#include "acredlin.hxx"

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

ScResId::ScResId( USHORT nId ) :
    ResId( nId, SC_MOD()->GetResMgr() )
{
}

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

void ScDLL::Init()
{
    // called directly after loading the DLL
    // do whatever you want, you may use Sxx-DLL too

    ScDocumentPool::InitVersionMaps();  // wird im ScModule ctor gebraucht

    // the ScModule must be created
    ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC);
#ifndef SO3
    SvFactory *pFact = (*ppShlPtr)->pScDocShellFactory;
#else
    SvFactory *pFact = (SvFactory*)(*ppShlPtr)->pScDocShellFactory;
#endif
    ScLibSignalFunc pFunc = (*ppShlPtr)->pSignalFunc;
    delete (*ppShlPtr);
    ScModule* pMod = new ScModule((SfxObjectFactory*)pFact);
    (*ppShlPtr) = pMod;
    (*ppShlPtr)->pScDocShellFactory = pFact;
    (*ppShlPtr)->pSignalFunc = pFunc;

    ScGlobal::Init();       // erst wenn der ResManager initialisiert ist
                            //  erst nach ScGlobal::Init duerfen die App-Optionen
                            //  initialisiert werden

    // register your view-factories here

    ScTabViewShell      ::RegisterFactory(1);
    ScPreviewShell      ::RegisterFactory(2);

    // register your shell-interfaces here

    ScModule            ::RegisterInterface(pMod);
    ScDocShell          ::RegisterInterface(pMod);
    ScTabViewShell      ::RegisterInterface(pMod);
    ScPreviewShell      ::RegisterInterface(pMod);
    ScDrawShell         ::RegisterInterface(pMod);
    ScDrawFormShell     ::RegisterInterface(pMod);
    ScDrawTextObjectBar ::RegisterInterface(pMod);
    ScEditShell         ::RegisterInterface(pMod);
    ScPivotShell        ::RegisterInterface(pMod);
    ScAuditingShell     ::RegisterInterface(pMod);
    ScFormatShell       ::RegisterInterface(pMod);
    ScCellShell         ::RegisterInterface(pMod);
    ScOleObjectShell    ::RegisterInterface(pMod);
    ScChartShell        ::RegisterInterface(pMod);
    ScGraphicShell      ::RegisterInterface(pMod);
    ScPageBreakShell    ::RegisterInterface(pMod);

    // register your controllers here

    ScDocShell::Factory().RegisterMenuBar( ScResId(SCCFG_MENUBAR) );
    ScDocShell::Factory().RegisterPluginMenuBar( ScResId(SCCFG_PLUGINMENU) );
    ScDocShell::Factory().RegisterAccel( ScResId(SCCFG_ACCELERATOR) );

    //  eigene Controller
    ScTbxInsertCtrl     ::RegisterControl(SID_TBXCTL_INSERT, pMod);
    ScTbxInsertCtrl     ::RegisterControl(SID_TBXCTL_INSCELLS, pMod);
    ScTbxInsertCtrl     ::RegisterControl(SID_TBXCTL_INSOBJ, pMod);

    //  Svx-Toolbox-Controller
    SvxTbxCtlDraw                   ::RegisterControl(SID_INSERT_DRAW, pMod);
    SvxTbxCtlAlign                  ::RegisterControl(SID_OBJECT_ALIGN, pMod);
    SvxFillToolBoxControl           ::RegisterControl(0, pMod);
    SvxLineStyleToolBoxControl      ::RegisterControl(0, pMod);
    SvxLineWidthToolBoxControl      ::RegisterControl(0, pMod);
    SvxLineColorToolBoxControl      ::RegisterControl(0, pMod);
    SvxLineEndToolBoxControl        ::RegisterControl(SID_ATTR_LINEEND_STYLE,   pMod);
    SvxStyleToolBoxControl          ::RegisterControl(SID_STYLE_APPLY,          pMod);
    SvxFontNameToolBoxControl       ::RegisterControl(SID_ATTR_CHAR_FONT,       pMod);
    SvxFontHeightToolBoxControl     ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod);
    SvxFontColorToolBoxControl      ::RegisterControl(SID_ATTR_CHAR_COLOR,      pMod);
    SvxColorToolBoxControl          ::RegisterControl(SID_BACKGROUND_COLOR,     pMod);
    SvxFrameToolBoxControl          ::RegisterControl(SID_ATTR_BORDER,          pMod);
    SvxFrameLineStyleToolBoxControl ::RegisterControl(SID_FRAME_LINESTYLE,      pMod);
    SvxFrameLineColorToolBoxControl ::RegisterControl(SID_FRAME_LINECOLOR,      pMod);

    // Svx-StatusBar-Controller
    SvxInsertStatusBarControl       ::RegisterControl(SID_ATTR_INSERT,      pMod);
    SvxSelectionModeControl         ::RegisterControl(SID_STATUS_SELMODE,   pMod);
    SvxZoomStatusBarControl         ::RegisterControl(SID_ATTR_ZOOM,        pMod);
    SvxModifyControl                ::RegisterControl(SID_DOC_MODIFIED,     pMod);
    SvxPosSizeStatusBarControl      ::RegisterControl(SID_ATTR_SIZE,        pMod);

    // Svx-Menue-Controller
    SvxFontMenuControl              ::RegisterControl(SID_ATTR_CHAR_FONT,       pMod);
    SvxFontSizeMenuControl          ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod);

    //  Child-Windows

    // Hack: Eingabezeile mit 42 registrieren, damit sie im PlugIn immer sichtbar ist
    ScInputWindowWrapper        ::RegisterChildWindow(42, pMod, SFX_CHILDWIN_TASK);
    ScNavigatorDialogWrapper    ::RegisterChildWindowContext(pMod);
    ScSolverDlgWrapper          ::RegisterChildWindow(FALSE, pMod);
    ScNameDlgWrapper            ::RegisterChildWindow(FALSE, pMod);
    ScPivotLayoutWrapper        ::RegisterChildWindow(FALSE, pMod);
    ScTabOpDlgWrapper           ::RegisterChildWindow(FALSE, pMod);
    ScFilterDlgWrapper          ::RegisterChildWindow(FALSE, pMod);
    ScSpecialFilterDlgWrapper   ::RegisterChildWindow(FALSE, pMod);
    ScDbNameDlgWrapper          ::RegisterChildWindow(FALSE, pMod);
    ScConsolidateDlgWrapper     ::RegisterChildWindow(FALSE, pMod);
    ScChartDlgWrapper           ::RegisterChildWindow(FALSE, pMod);
    ScPrintAreasDlgWrapper      ::RegisterChildWindow(FALSE, pMod);
    ScCondFormatDlgWrapper      ::RegisterChildWindow(FALSE, pMod);
    ScColRowNameRangesDlgWrapper::RegisterChildWindow(FALSE, pMod);
    ScFormulaDlgWrapper         ::RegisterChildWindow(FALSE, pMod);

    // First docking Window for Calc
    ScFunctionChildWindow       ::RegisterChildWindow(FALSE, pMod);

    // Redlining- Window
    ScAcceptChgDlgWrapper       ::RegisterChildWindow(FALSE, pMod);
    ScSimpleRefDlgWrapper       ::RegisterChildWindow(FALSE, pMod);
    ScHighlightChgDlgWrapper    ::RegisterChildWindow(FALSE, pMod);

    SvxFontWorkChildWindow      ::RegisterChildWindow(FALSE, pMod);
    SvxHyperlinkDlgWrapper      ::RegisterChildWindow(FALSE, pMod);
    SvxIMapDlgChildWindow       ::RegisterChildWindow(FALSE, pMod);

    //  Edit-Engine-Felder, soweit nicht schon in OfficeApplication::Init

    SvClassManager& rClassManager = SvxFieldItem::GetClassManager();
//  rClassManager.SV_CLASS_REGISTER( SvxURLField );
//  rClassManager.SV_CLASS_REGISTER( SvxDateField );
//  rClassManager.SV_CLASS_REGISTER( SvxPageField );
    rClassManager.SV_CLASS_REGISTER( SvxPagesField );
//  rClassManager.SV_CLASS_REGISTER( SvxTimeField );
    rClassManager.SV_CLASS_REGISTER( SvxFileField );
//  rClassManager.SV_CLASS_REGISTER( SvxExtFileField );
    rClassManager.SV_CLASS_REGISTER( SvxTableField );

    SdrRegisterFieldClasses();      // SvDraw-Felder registrieren

    pMod->PutItem( SfxUInt16Item( SID_ATTR_METRIC, pMod->GetAppOptions().GetAppMetric() ) );

    //  StarOne Services are now handled in the registry
}

void ScDLL::Exit()
{
    // called directly befor unloading the DLL
    // do whatever you want, Sxx-DLL is accessible

    // the SxxModule must be destroyed
    ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC);
    delete (*ppShlPtr);
    (*ppShlPtr) = NULL;

    //  auf keinen Fall ein neues ScModuleDummy anlegen, weil dessen vtable sonst
    //  in der DLL waere und das Loeschen im LibExit schiefgehen wuerde

    //  ScGlobal::Clear ist schon im Module-dtor
}

//------------------------------------------------------------------
//  Statusbar
//------------------------------------------------------------------

#define TEXT_WIDTH(s)   rStatusBar.GetTextWidth((s))

void ScDLL::FillStatusBar(StatusBar &rStatusBar)
{
    // Dokumentposition (Tabelle x / y)
    rStatusBar.InsertItem( SID_STATUS_DOCPOS,
                            TEXT_WIDTH( String().Fill( 10, 'X' ) ),
                            SIB_LEFT|SIB_AUTOSIZE );

    // Seitenvorlage
    rStatusBar.InsertItem( SID_STATUS_PAGESTYLE,
                            TEXT_WIDTH( String().Fill( 15, 'X' ) ),
                            SIB_LEFT|SIB_AUTOSIZE );

    // Ma"sstab
    rStatusBar.InsertItem(  SID_ATTR_ZOOM,
                            SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar),
                            SIB_CENTER );

    // Einfuege-/Ueberschreibmodus
    rStatusBar.InsertItem( SID_ATTR_INSERT,
                            SvxInsertStatusBarControl::GetDefItemWidth(rStatusBar),
                            SIB_CENTER );

    // Selektionsmodus
    rStatusBar.InsertItem( SID_STATUS_SELMODE,
                            SvxSelectionModeControl::GetDefItemWidth(rStatusBar),
                            SIB_CENTER );

    // Dokument geaendert
    rStatusBar.InsertItem( SID_DOC_MODIFIED,
                            SvxModifyControl::GetDefItemWidth(rStatusBar));

    // Mail
    rStatusBar.InsertItem( SID_MAIL_NOTIFY,
                            TEXT_WIDTH( String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("Mail")) ),
                            SIB_CENTER );

    // den aktuellen Kontext anzeigen Uhrzeit / FramePos / TabellenInfo / Errors
    rStatusBar.InsertItem( SID_ATTR_SIZE,
                            SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar),
                            SIB_AUTOSIZE|SIB_LEFT|SIB_USERDRAW);
}

#undef TEXT_WIDTH

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

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD

#include "scitems.hxx"      // fuer tbxctrls etc.
#include "scmod.hxx"
#include "scresid.hxx"
#include "sc.hrc"
#include "cfgids.hxx"

//! die Registrierung wird wegen CLOOKs in ein eigenes File wandern muessen...

// Interface-Registrierung
#include "docsh.hxx"
#include "tabvwsh.hxx"
#include "prevwsh.hxx"
#include "drawsh.hxx"
#include "drformsh.hxx"
#include "drtxtob.hxx"
#include "editsh.hxx"
#include "pivotsh.hxx"
#include "auditsh.hxx"
#include "cellsh.hxx"
#include "oleobjsh.hxx"
#include "chartsh.hxx"
#include "graphsh.hxx"
#include "pgbrksh.hxx"

#include "docpool.hxx"
#include "appoptio.hxx"

// Controls

#include <svx/tbxalign.hxx>
#include <svx/tbxctl.hxx>
#include <svx/fillctrl.hxx>
#include <svx/linectrl.hxx>
#include <svx/tbcontrl.hxx>
#include <svx/selctrl.hxx>
#include <svx/insctrl.hxx>
#include <svx/zoomctrl.hxx>
#include <svx/flditem.hxx>
#include <svx/modctrl.hxx>
#include <svx/pszctrl.hxx>
#include <svx/fntctl.hxx>
#include <svx/fntszctl.hxx>
#include <svx/grafctrl.hxx>

#include "tbinsert.hxx"

// Child-Windows
#include "reffact.hxx"
#include "navipi.hxx"
#include "inputwin.hxx"
#include <svx/fontwork.hxx>
#include <svx/srchdlg.hxx>
#include <offmgr/hyprlink.hxx>
#include <svx/imapdlg.hxx>

#include "editutil.hxx"
#include <svx/svdfield.hxx>     //  SdrRegisterFieldClasses

#include "dwfunctr.hxx"
#include "acredlin.hxx"

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

ScResId::ScResId( USHORT nId ) :
    ResId( nId, SC_MOD()->GetResMgr() )
{
}

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

void ScDLL::Init()
{
    // called directly after loading the DLL
    // do whatever you want, you may use Sxx-DLL too

    ScDocumentPool::InitVersionMaps();  // wird im ScModule ctor gebraucht

    // the ScModule must be created
    ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC);
#ifndef SO3
    SvFactory *pFact = (*ppShlPtr)->pScDocShellFactory;
#else
    SvFactory *pFact = (SvFactory*)(*ppShlPtr)->pScDocShellFactory;
#endif
    ScLibSignalFunc pFunc = (*ppShlPtr)->pSignalFunc;
    delete (*ppShlPtr);
    ScModule* pMod = new ScModule((SfxObjectFactory*)pFact);
    (*ppShlPtr) = pMod;
    (*ppShlPtr)->pScDocShellFactory = pFact;
    (*ppShlPtr)->pSignalFunc = pFunc;

    ScGlobal::Init();       // erst wenn der ResManager initialisiert ist
                            //  erst nach ScGlobal::Init duerfen die App-Optionen
                            //  initialisiert werden

    // register your view-factories here

    ScTabViewShell      ::RegisterFactory(1);
    ScPreviewShell      ::RegisterFactory(2);

    // register your shell-interfaces here

    ScModule            ::RegisterInterface(pMod);
    ScDocShell          ::RegisterInterface(pMod);
    ScTabViewShell      ::RegisterInterface(pMod);
    ScPreviewShell      ::RegisterInterface(pMod);
    ScDrawShell         ::RegisterInterface(pMod);
    ScDrawFormShell     ::RegisterInterface(pMod);
    ScDrawTextObjectBar ::RegisterInterface(pMod);
    ScEditShell         ::RegisterInterface(pMod);
    ScPivotShell        ::RegisterInterface(pMod);
    ScAuditingShell     ::RegisterInterface(pMod);
    ScFormatShell       ::RegisterInterface(pMod);
    ScCellShell         ::RegisterInterface(pMod);
    ScOleObjectShell    ::RegisterInterface(pMod);
    ScChartShell        ::RegisterInterface(pMod);
    ScGraphicShell      ::RegisterInterface(pMod);
    ScPageBreakShell    ::RegisterInterface(pMod);

    // register your controllers here

    ScDocShell::Factory().RegisterMenuBar( ScResId(SCCFG_MENUBAR) );
    ScDocShell::Factory().RegisterPluginMenuBar( ScResId(SCCFG_PLUGINMENU) );
    ScDocShell::Factory().RegisterAccel( ScResId(SCCFG_ACCELERATOR) );

    //  eigene Controller
    ScTbxInsertCtrl     ::RegisterControl(SID_TBXCTL_INSERT, pMod);
    ScTbxInsertCtrl     ::RegisterControl(SID_TBXCTL_INSCELLS, pMod);
    ScTbxInsertCtrl     ::RegisterControl(SID_TBXCTL_INSOBJ, pMod);

    //  Svx-Toolbox-Controller
    SvxTbxCtlDraw                   ::RegisterControl(SID_INSERT_DRAW, pMod);
    SvxTbxCtlAlign                  ::RegisterControl(SID_OBJECT_ALIGN, pMod);
    SvxFillToolBoxControl           ::RegisterControl(0, pMod);
    SvxLineStyleToolBoxControl      ::RegisterControl(0, pMod);
    SvxLineWidthToolBoxControl      ::RegisterControl(0, pMod);
    SvxLineColorToolBoxControl      ::RegisterControl(0, pMod);
    SvxLineEndToolBoxControl        ::RegisterControl(SID_ATTR_LINEEND_STYLE,   pMod);
    SvxStyleToolBoxControl          ::RegisterControl(SID_STYLE_APPLY,          pMod);
    SvxFontNameToolBoxControl       ::RegisterControl(SID_ATTR_CHAR_FONT,       pMod);
    SvxFontHeightToolBoxControl     ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod);
    SvxFontColorToolBoxControl      ::RegisterControl(SID_ATTR_CHAR_COLOR,      pMod);
    SvxColorToolBoxControl          ::RegisterControl(SID_BACKGROUND_COLOR,     pMod);
    SvxFrameToolBoxControl          ::RegisterControl(SID_ATTR_BORDER,          pMod);
    SvxFrameLineStyleToolBoxControl ::RegisterControl(SID_FRAME_LINESTYLE,      pMod);
    SvxFrameLineColorToolBoxControl ::RegisterControl(SID_FRAME_LINECOLOR,      pMod);

    SvxGrafModeToolBoxControl       ::RegisterControl(SID_ATTR_GRAF_MODE,       pMod);
    SvxGrafRedToolBoxControl        ::RegisterControl(SID_ATTR_GRAF_RED,        pMod);
    SvxGrafGreenToolBoxControl      ::RegisterControl(SID_ATTR_GRAF_GREEN,      pMod);
    SvxGrafBlueToolBoxControl       ::RegisterControl(SID_ATTR_GRAF_BLUE,       pMod);
    SvxGrafLuminanceToolBoxControl  ::RegisterControl(SID_ATTR_GRAF_LUMINANCE,  pMod);
    SvxGrafContrastToolBoxControl   ::RegisterControl(SID_ATTR_GRAF_CONTRAST,   pMod);
    SvxGrafGammaToolBoxControl      ::RegisterControl(SID_ATTR_GRAF_GAMMA,      pMod);
    SvxGrafTransparenceToolBoxControl::RegisterControl(SID_ATTR_GRAF_TRANSPARENCE, pMod);

    // Svx-StatusBar-Controller
    SvxInsertStatusBarControl       ::RegisterControl(SID_ATTR_INSERT,      pMod);
    SvxSelectionModeControl         ::RegisterControl(SID_STATUS_SELMODE,   pMod);
    SvxZoomStatusBarControl         ::RegisterControl(SID_ATTR_ZOOM,        pMod);
    SvxModifyControl                ::RegisterControl(SID_DOC_MODIFIED,     pMod);
    SvxPosSizeStatusBarControl      ::RegisterControl(SID_ATTR_SIZE,        pMod);

    // Svx-Menue-Controller
    SvxFontMenuControl              ::RegisterControl(SID_ATTR_CHAR_FONT,       pMod);
    SvxFontSizeMenuControl          ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod);

    //  Child-Windows

    // Hack: Eingabezeile mit 42 registrieren, damit sie im PlugIn immer sichtbar ist
    ScInputWindowWrapper        ::RegisterChildWindow(42, pMod, SFX_CHILDWIN_TASK);
    ScNavigatorDialogWrapper    ::RegisterChildWindowContext(pMod);
    ScSolverDlgWrapper          ::RegisterChildWindow(FALSE, pMod);
    ScNameDlgWrapper            ::RegisterChildWindow(FALSE, pMod);
    ScPivotLayoutWrapper        ::RegisterChildWindow(FALSE, pMod);
    ScTabOpDlgWrapper           ::RegisterChildWindow(FALSE, pMod);
    ScFilterDlgWrapper          ::RegisterChildWindow(FALSE, pMod);
    ScSpecialFilterDlgWrapper   ::RegisterChildWindow(FALSE, pMod);
    ScDbNameDlgWrapper          ::RegisterChildWindow(FALSE, pMod);
    ScConsolidateDlgWrapper     ::RegisterChildWindow(FALSE, pMod);
    ScChartDlgWrapper           ::RegisterChildWindow(FALSE, pMod);
    ScPrintAreasDlgWrapper      ::RegisterChildWindow(FALSE, pMod);
    ScCondFormatDlgWrapper      ::RegisterChildWindow(FALSE, pMod);
    ScColRowNameRangesDlgWrapper::RegisterChildWindow(FALSE, pMod);
    ScFormulaDlgWrapper         ::RegisterChildWindow(FALSE, pMod);

    // First docking Window for Calc
    ScFunctionChildWindow       ::RegisterChildWindow(FALSE, pMod);

    // Redlining- Window
    ScAcceptChgDlgWrapper       ::RegisterChildWindow(FALSE, pMod);
    ScSimpleRefDlgWrapper       ::RegisterChildWindow(FALSE, pMod);
    ScHighlightChgDlgWrapper    ::RegisterChildWindow(FALSE, pMod);

    SvxFontWorkChildWindow      ::RegisterChildWindow(FALSE, pMod);
    SvxHyperlinkDlgWrapper      ::RegisterChildWindow(FALSE, pMod);
    SvxIMapDlgChildWindow       ::RegisterChildWindow(FALSE, pMod);

    //  Edit-Engine-Felder, soweit nicht schon in OfficeApplication::Init

    SvClassManager& rClassManager = SvxFieldItem::GetClassManager();
//  rClassManager.SV_CLASS_REGISTER( SvxURLField );
//  rClassManager.SV_CLASS_REGISTER( SvxDateField );
//  rClassManager.SV_CLASS_REGISTER( SvxPageField );
    rClassManager.SV_CLASS_REGISTER( SvxPagesField );
//  rClassManager.SV_CLASS_REGISTER( SvxTimeField );
    rClassManager.SV_CLASS_REGISTER( SvxFileField );
//  rClassManager.SV_CLASS_REGISTER( SvxExtFileField );
    rClassManager.SV_CLASS_REGISTER( SvxTableField );

    SdrRegisterFieldClasses();      // SvDraw-Felder registrieren

    pMod->PutItem( SfxUInt16Item( SID_ATTR_METRIC, pMod->GetAppOptions().GetAppMetric() ) );

    //  StarOne Services are now handled in the registry
}

void ScDLL::Exit()
{
    // called directly befor unloading the DLL
    // do whatever you want, Sxx-DLL is accessible

    // the SxxModule must be destroyed
    ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC);
    delete (*ppShlPtr);
    (*ppShlPtr) = NULL;

    //  auf keinen Fall ein neues ScModuleDummy anlegen, weil dessen vtable sonst
    //  in der DLL waere und das Loeschen im LibExit schiefgehen wuerde

    //  ScGlobal::Clear ist schon im Module-dtor
}

//------------------------------------------------------------------
//  Statusbar
//------------------------------------------------------------------

#define TEXT_WIDTH(s)   rStatusBar.GetTextWidth((s))

void ScDLL::FillStatusBar(StatusBar &rStatusBar)
{
    // Dokumentposition (Tabelle x / y)
    rStatusBar.InsertItem( SID_STATUS_DOCPOS,
                            TEXT_WIDTH( String().Fill( 10, 'X' ) ),
                            SIB_LEFT|SIB_AUTOSIZE );

    // Seitenvorlage
    rStatusBar.InsertItem( SID_STATUS_PAGESTYLE,
                            TEXT_WIDTH( String().Fill( 15, 'X' ) ),
                            SIB_LEFT|SIB_AUTOSIZE );

    // Ma"sstab
    rStatusBar.InsertItem(  SID_ATTR_ZOOM,
                            SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar),
                            SIB_CENTER );

    // Einfuege-/Ueberschreibmodus
    rStatusBar.InsertItem( SID_ATTR_INSERT,
                            SvxInsertStatusBarControl::GetDefItemWidth(rStatusBar),
                            SIB_CENTER );

    // Selektionsmodus
    rStatusBar.InsertItem( SID_STATUS_SELMODE,
                            SvxSelectionModeControl::GetDefItemWidth(rStatusBar),
                            SIB_CENTER );

    // Dokument geaendert
    rStatusBar.InsertItem( SID_DOC_MODIFIED,
                            SvxModifyControl::GetDefItemWidth(rStatusBar));

    // Mail
    rStatusBar.InsertItem( SID_MAIL_NOTIFY,
                            TEXT_WIDTH( String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("Mail")) ),
                            SIB_CENTER );

    // den aktuellen Kontext anzeigen Uhrzeit / FramePos / TabellenInfo / Errors
    rStatusBar.InsertItem( SID_ATTR_SIZE,
                            SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar),
                            SIB_AUTOSIZE|SIB_LEFT|SIB_USERDRAW);
}

#undef TEXT_WIDTH

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "BitmapImage.h"

#if PLATFORM(CG)

#include "AffineTransform.h"
#include "FloatConversion.h"
#include "FloatRect.h"
#include "GraphicsContext.h"
#include "ImageObserver.h"
#include "PDFDocumentImage.h"
#include "PlatformString.h"
#include <ApplicationServices/ApplicationServices.h>
#include "WebCoreSystemInterface.h"

#if PLATFORM(WIN)
#include <WebKitSystemInterface/WebKitSystemInterface.h>
#endif

namespace WebCore {

void FrameData::clear()
{
    if (m_frame) {
        CGImageRelease(m_frame);
        m_frame = 0;
        m_duration = 0.0f;
        m_hasAlpha = true;
    }
}

// ================================================
// Image Class
// ================================================

// Drawing Routines

void BitmapImage::checkForSolidColor()
{
    if (frameCount() > 1)
        m_isSolidColor = false;
    else {
        CGImageRef image = frameAtIndex(0);

        // Currently we only check for solid color in the important special case of a 1x1 image.
        if (image && CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) {
            unsigned char pixel[4]; // RGBA
            CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
            CGContextRef bmap = CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), space,
                kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
            if (bmap) {
                GraphicsContext(bmap).setCompositeOperation(CompositeCopy);
                CGRect dst = { {0, 0}, {1, 1} };
                CGContextDrawImage(bmap, dst, image);
                if (pixel[3] == 0)
                    m_solidColor = Color(0, 0, 0, 0);
                else
                    m_solidColor = Color(pixel[0] * 255 / pixel[3], pixel[1] * 255 / pixel[3], pixel[2] * 255 / pixel[3], pixel[3]);
                m_isSolidColor = true;
                CFRelease(bmap);
            }
            CFRelease(space);
        }
    }
}

CGImageRef BitmapImage::getCGImageRef()
{
    return frameAtIndex(0);
}

void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp)
{
    if (!m_source.initialized())
        return;

    CGRect fr = ctxt->roundToDevicePixels(srcRect);
    CGRect ir = ctxt->roundToDevicePixels(dstRect);

    CGImageRef image = frameAtIndex(m_currentFrame);
    if (!image) // If it's too early we won't have an image yet.
        return;

    if (mayFillWithSolidColor()) {
        fillWithSolidColor(ctxt, ir, solidColor(), compositeOp);
        return;
    }

    CGContextRef context = ctxt->platformContext();
    ctxt->save();

    // Get the height (in adjusted, i.e. scaled, coords) of the portion of the image
    // that is currently decoded.  This could be less that the actual height.
    CGSize selfSize = size();                          // full image size, in pixels
    float curHeight = CGImageGetHeight(image);         // height of loaded portion, in pixels

    CGSize adjustedSize = selfSize;
    if (curHeight < selfSize.height) {
        adjustedSize.height *= curHeight / selfSize.height;

        // Is the amount of available bands less than what we need to draw?  If so,
        // we may have to clip 'fr' if it goes outside the available bounds.
        if (CGRectGetMaxY(fr) > adjustedSize.height) {
            float frHeight = adjustedSize.height - fr.origin.y; // clip fr to available bounds
            if (frHeight <= 0)
                return;                                             // clipped out entirely
            ir.size.height *= (frHeight / fr.size.height);    // scale ir proportionally to fr
            fr.size.height = frHeight;
        }
    }

    // Flip the coords.
    ctxt->setCompositeOperation(compositeOp);
    CGContextTranslateCTM(context, ir.origin.x, ir.origin.y);
    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -ir.size.height);

    // Translated to origin, now draw at 0,0.
    ir.origin.x = ir.origin.y = 0;

    // If we're drawing a sub portion of the image then create
    // a image for the sub portion and draw that.
    // Test using example site at http://www.meyerweb.com/eric/css/edge/complexspiral/demo.html
    if (fr.size.width != adjustedSize.width || fr.size.height != adjustedSize.height) {
        // Convert ft to image pixel coords:
        float xscale = adjustedSize.width / selfSize.width;
        float yscale = adjustedSize.height / curHeight;     // yes, curHeight, not selfSize.height!
        fr.origin.x /= xscale;
        fr.origin.y /= yscale;
        fr.size.width /= xscale;
        fr.size.height /= yscale;

        image = CGImageCreateWithImageInRect(image, fr);
        if (image) {
            CGContextDrawImage(context, ir, image);
            CFRelease(image);
        }
    } else // Draw the whole image.
        CGContextDrawImage(context, ir, image);

    ctxt->restore();

    startAnimation();

    if (imageObserver())
        imageObserver()->didDraw(this);
}

struct ImageInfo {
    ImageInfo(const FloatPoint& point, Image* i)
    : tilePoint(point)
    , image(i)
    {}

    FloatPoint tilePoint;
    Image* image;
};

void Image::drawPatternCallback(void* info, CGContextRef context)
{
    ImageInfo* data = (ImageInfo*)info;
    CGImageRef image = data->image->nativeImageForCurrentFrame();
    CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(data->tilePoint.x(), data->tilePoint.y(), CGImageGetWidth(image), CGImageGetHeight(image))), image);
}

void Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform,
                        const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect)
{
    CGContextRef context = ctxt->platformContext();
    ctxt->save();
    CGContextClipToRect(context, destRect);
    ctxt->setCompositeOperation(op);
    CGContextTranslateCTM(context, destRect.x(), destRect.y());
    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -destRect.height());

    // Compute the scaled tile size.
    float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d());

    // We have to adjust the phase to deal with the fact we're in Cartesian space now (with the bottom left corner of destRect being
    // the origin).
    float adjustedX = phase.x() - destRect.x() + tileRect.x() * narrowPrecisionToFloat(patternTransform.a()); // We translated the context so that destRect.x() is the origin, so subtract it out.
    float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight);

    CGImageRef tileImage = nativeImageForCurrentFrame();
    float h = CGImageGetHeight(tileImage);

#ifndef BUILDING_ON_TIGER
    // Leopard has an optimized call for the tiling of image patterns, but we can only use it if the image has been decoded enough that
    // its buffer is the same size as the overall image.  Because a partially decoded CGImageRef with a smaller width or height than the
    // overall image buffer needs to tile with "gaps", we can't use the optimized tiling call in that case.  We also avoid this optimization
    // when tiling portions of an image, since until we can actually cache the subimage we want to tile, this code won't be any faster.
    // FIXME: Could create WebKitSystemInterface SPI for CGCreatePatternWithImage2 and probably make Tiger tile faster as well.
    float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a());
    float w = CGImageGetWidth(tileImage);
    if (w == size().width() && h == size().height() && tileRect.size() == size())
        CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), tileImage);
    else {
#endif

    // On Leopard, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image or for
    // tiling a portion of an image (i.e., a subimage like the ones used by CSS border-image).
    // On Tiger this code runs all the time.  This code is suboptimal because the pattern does not reference the image directly, and the
    // pattern is destroyed before exiting the function.  This means any decoding the pattern does doesn't end up cached anywhere, so we
    // redecode every time we paint.
    static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL };
    CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY);
    matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context));

    // If we're painting a subimage, store the offset to the image.
    ImageInfo info(FloatPoint(-tileRect.x(), tileRect.y() + tileRect.height() - h), this);
    CGPatternRef pattern = CGPatternCreate(&info, CGRectMake(0, 0, tileRect.width(), tileRect.height()),
                                           matrix, tileRect.width(), tileRect.height(),
                                           kCGPatternTilingConstantSpacing, true, &patternCallbacks);
    if (pattern == NULL) {
        ctxt->restore();
        return;
    }

    CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL);

    CGFloat alpha = 1;
    CGColorRef color = CGColorCreateWithPattern(patternSpace, pattern, &alpha);
    CGContextSetFillColorSpace(context, patternSpace);
    CGColorSpaceRelease(patternSpace);
    CGPatternRelease(pattern);

    // FIXME: Really want a public API for this.  It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy).
    wkSetPatternBaseCTM(context, CGAffineTransformIdentity);
    CGContextSetPatternPhase(context, CGSizeZero);

    CGContextSetFillColorWithColor(context, color);
    CGContextFillRect(context, CGContextGetClipBoundingBox(context));

    CGColorRelease(color);

    ctxt->restore();

#ifndef BUILDING_ON_TIGER
    }
#endif

    if (imageObserver())
        imageObserver()->didDraw(this);
}

}

#endif // PLATFORM(CG)
<commit_msg>Fix unbalanced save/restore on Leopard only.<commit_after>/*
 * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "BitmapImage.h"

#if PLATFORM(CG)

#include "AffineTransform.h"
#include "FloatConversion.h"
#include "FloatRect.h"
#include "GraphicsContext.h"
#include "ImageObserver.h"
#include "PDFDocumentImage.h"
#include "PlatformString.h"
#include <ApplicationServices/ApplicationServices.h>
#include "WebCoreSystemInterface.h"

#if PLATFORM(WIN)
#include <WebKitSystemInterface/WebKitSystemInterface.h>
#endif

namespace WebCore {

void FrameData::clear()
{
    if (m_frame) {
        CGImageRelease(m_frame);
        m_frame = 0;
        m_duration = 0.0f;
        m_hasAlpha = true;
    }
}

// ================================================
// Image Class
// ================================================

// Drawing Routines

void BitmapImage::checkForSolidColor()
{
    if (frameCount() > 1)
        m_isSolidColor = false;
    else {
        CGImageRef image = frameAtIndex(0);

        // Currently we only check for solid color in the important special case of a 1x1 image.
        if (image && CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) {
            unsigned char pixel[4]; // RGBA
            CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
            CGContextRef bmap = CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), space,
                kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
            if (bmap) {
                GraphicsContext(bmap).setCompositeOperation(CompositeCopy);
                CGRect dst = { {0, 0}, {1, 1} };
                CGContextDrawImage(bmap, dst, image);
                if (pixel[3] == 0)
                    m_solidColor = Color(0, 0, 0, 0);
                else
                    m_solidColor = Color(pixel[0] * 255 / pixel[3], pixel[1] * 255 / pixel[3], pixel[2] * 255 / pixel[3], pixel[3]);
                m_isSolidColor = true;
                CFRelease(bmap);
            }
            CFRelease(space);
        }
    }
}

CGImageRef BitmapImage::getCGImageRef()
{
    return frameAtIndex(0);
}

void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp)
{
    if (!m_source.initialized())
        return;

    CGRect fr = ctxt->roundToDevicePixels(srcRect);
    CGRect ir = ctxt->roundToDevicePixels(dstRect);

    CGImageRef image = frameAtIndex(m_currentFrame);
    if (!image) // If it's too early we won't have an image yet.
        return;

    if (mayFillWithSolidColor()) {
        fillWithSolidColor(ctxt, ir, solidColor(), compositeOp);
        return;
    }

    CGContextRef context = ctxt->platformContext();
    ctxt->save();

    // Get the height (in adjusted, i.e. scaled, coords) of the portion of the image
    // that is currently decoded.  This could be less that the actual height.
    CGSize selfSize = size();                          // full image size, in pixels
    float curHeight = CGImageGetHeight(image);         // height of loaded portion, in pixels

    CGSize adjustedSize = selfSize;
    if (curHeight < selfSize.height) {
        adjustedSize.height *= curHeight / selfSize.height;

        // Is the amount of available bands less than what we need to draw?  If so,
        // we may have to clip 'fr' if it goes outside the available bounds.
        if (CGRectGetMaxY(fr) > adjustedSize.height) {
            float frHeight = adjustedSize.height - fr.origin.y; // clip fr to available bounds
            if (frHeight <= 0)
                return;                                             // clipped out entirely
            ir.size.height *= (frHeight / fr.size.height);    // scale ir proportionally to fr
            fr.size.height = frHeight;
        }
    }

    // Flip the coords.
    ctxt->setCompositeOperation(compositeOp);
    CGContextTranslateCTM(context, ir.origin.x, ir.origin.y);
    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -ir.size.height);

    // Translated to origin, now draw at 0,0.
    ir.origin.x = ir.origin.y = 0;

    // If we're drawing a sub portion of the image then create
    // a image for the sub portion and draw that.
    // Test using example site at http://www.meyerweb.com/eric/css/edge/complexspiral/demo.html
    if (fr.size.width != adjustedSize.width || fr.size.height != adjustedSize.height) {
        // Convert ft to image pixel coords:
        float xscale = adjustedSize.width / selfSize.width;
        float yscale = adjustedSize.height / curHeight;     // yes, curHeight, not selfSize.height!
        fr.origin.x /= xscale;
        fr.origin.y /= yscale;
        fr.size.width /= xscale;
        fr.size.height /= yscale;

        image = CGImageCreateWithImageInRect(image, fr);
        if (image) {
            CGContextDrawImage(context, ir, image);
            CFRelease(image);
        }
    } else // Draw the whole image.
        CGContextDrawImage(context, ir, image);

    ctxt->restore();

    startAnimation();

    if (imageObserver())
        imageObserver()->didDraw(this);
}

struct ImageInfo {
    ImageInfo(const FloatPoint& point, Image* i)
    : tilePoint(point)
    , image(i)
    {}

    FloatPoint tilePoint;
    Image* image;
};

void Image::drawPatternCallback(void* info, CGContextRef context)
{
    ImageInfo* data = (ImageInfo*)info;
    CGImageRef image = data->image->nativeImageForCurrentFrame();
    CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(data->tilePoint.x(), data->tilePoint.y(), CGImageGetWidth(image), CGImageGetHeight(image))), image);
}

void Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform,
                        const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect)
{
    CGContextRef context = ctxt->platformContext();
    ctxt->save();
    CGContextClipToRect(context, destRect);
    ctxt->setCompositeOperation(op);
    CGContextTranslateCTM(context, destRect.x(), destRect.y());
    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -destRect.height());

    // Compute the scaled tile size.
    float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d());

    // We have to adjust the phase to deal with the fact we're in Cartesian space now (with the bottom left corner of destRect being
    // the origin).
    float adjustedX = phase.x() - destRect.x() + tileRect.x() * narrowPrecisionToFloat(patternTransform.a()); // We translated the context so that destRect.x() is the origin, so subtract it out.
    float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight);

    CGImageRef tileImage = nativeImageForCurrentFrame();
    float h = CGImageGetHeight(tileImage);

#ifndef BUILDING_ON_TIGER
    // Leopard has an optimized call for the tiling of image patterns, but we can only use it if the image has been decoded enough that
    // its buffer is the same size as the overall image.  Because a partially decoded CGImageRef with a smaller width or height than the
    // overall image buffer needs to tile with "gaps", we can't use the optimized tiling call in that case.  We also avoid this optimization
    // when tiling portions of an image, since until we can actually cache the subimage we want to tile, this code won't be any faster.
    // FIXME: Could create WebKitSystemInterface SPI for CGCreatePatternWithImage2 and probably make Tiger tile faster as well.
    float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a());
    float w = CGImageGetWidth(tileImage);
    if (w == size().width() && h == size().height() && tileRect.size() == size())
        CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), tileImage);
    else {
#endif

    // On Leopard, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image or for
    // tiling a portion of an image (i.e., a subimage like the ones used by CSS border-image).
    // On Tiger this code runs all the time.  This code is suboptimal because the pattern does not reference the image directly, and the
    // pattern is destroyed before exiting the function.  This means any decoding the pattern does doesn't end up cached anywhere, so we
    // redecode every time we paint.
    static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL };
    CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY);
    matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context));

    // If we're painting a subimage, store the offset to the image.
    ImageInfo info(FloatPoint(-tileRect.x(), tileRect.y() + tileRect.height() - h), this);
    CGPatternRef pattern = CGPatternCreate(&info, CGRectMake(0, 0, tileRect.width(), tileRect.height()),
                                           matrix, tileRect.width(), tileRect.height(),
                                           kCGPatternTilingConstantSpacing, true, &patternCallbacks);
    if (pattern == NULL) {
        ctxt->restore();
        return;
    }

    CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL);

    CGFloat alpha = 1;
    CGColorRef color = CGColorCreateWithPattern(patternSpace, pattern, &alpha);
    CGContextSetFillColorSpace(context, patternSpace);
    CGColorSpaceRelease(patternSpace);
    CGPatternRelease(pattern);

    // FIXME: Really want a public API for this.  It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy).
    wkSetPatternBaseCTM(context, CGAffineTransformIdentity);
    CGContextSetPatternPhase(context, CGSizeZero);

    CGContextSetFillColorWithColor(context, color);
    CGContextFillRect(context, CGContextGetClipBoundingBox(context));

    CGColorRelease(color);

#ifndef BUILDING_ON_TIGER
    }
#endif

    ctxt->restore();

    if (imageObserver())
        imageObserver()->didDraw(this);
}

}

#endif // PLATFORM(CG)
<|endoftext|>


<commit_before>#include "dsa/network.h"
#include "dsa/requester.h"
#include "dsa/responder.h"
#include "dsa/stream.h"

#include <chrono>
#include <ctime>
#include <iostream>
#include "core/client.h"
#include "module/logger.h"
#include "network/tcp/tcp_server.h"
#include "util/date_time.h"

#include <atomic>

#include <boost/program_options.hpp>

using high_resolution_clock = std::chrono::high_resolution_clock;
using time_point = std::chrono::high_resolution_clock::time_point;

namespace opts = boost::program_options;

using namespace dsa;

namespace broker_benchmark {

class BenchmarkNodeValue : public NodeModel {
public:
  explicit BenchmarkNodeValue(LinkStrandRef strand)
    : NodeModel(std::move(strand)){};
};
class BenchmarkNodeRoot : public NodeModel {
public:
  explicit BenchmarkNodeRoot(LinkStrandRef strand, int num_point)
    : NodeModel(std::move(strand)) {
    for (int i = 0; i < num_point; ++i) {
      add_list_child("v" + std::to_string(i),
                     make_ref_<BenchmarkNodeValue>(_strand));
    }
  };
  int64_t sub_value = 0;
  void new_value() {
    sub_value++;
    auto msg = make_ref_<SubscribeResponseMessage>();
    msg->set_value(MessageValue(Var(sub_value), DateTime::get_ts()));
    for (auto it : _list_children) {
      it.second->set_subscribe_response(msg->get_ref());
    }
  }
};
}

WrapperStrand get_client_wrapper_strand(shared_ptr_<App>& app,
                                        const string_& dsid_prefix) {
  WrapperStrand client_strand;
  client_strand.tcp_host = "127.0.0.1";
  client_strand.tcp_port = 4120;

  client_strand.strand = EditableStrand::make_default(app);
  client_strand.client_connection_maker =
    [
      dsid_prefix = dsid_prefix, tcp_host = client_strand.tcp_host,
      tcp_port = client_strand.tcp_port
    ](LinkStrandRef & strand, const string_& previous_session_id,
      int32_t last_ack_id)
      ->shared_ptr_<Connection> {
      return make_shared_<TcpClientConnection>(strand, dsid_prefix, tcp_host,
                                               tcp_port);
    };
  return std::move(client_strand);
}

int main(int argc, const char* argv[]) {
  typedef broker_benchmark::BenchmarkNodeRoot BenchmarkNodeRoot;

  opts::options_description desc{"Options"};
  desc.add_options()("help,h", "Help screen")  //
    ("client,c", opts::value<int>()->default_value(2),
     "Number of Clients")  //
    ("point,p", opts::value<int>()->default_value(2),
     "Number of Points per Client")  //
    ("num-message,n", opts::value<int>()->default_value(100),
     "Message per second per Point")  //
    ("encode-value,e", opts::bool_switch(),
     "Encode value before sending")  //
    ("decode-value,d", opts::bool_switch(),
     "Decode value after receiving")  //
    ;

  opts::variables_map variables;
  opts::store(opts::parse_command_line(argc, argv, desc), variables);
  opts::notify(variables);

  if (variables.count("help")) {
    std::cout << desc << '\n';
    return 0;
  }

  int client_count = variables["client"].as<int>();
  int point_count = variables["point"].as<int>();
  int num_message = variables["num-message"].as<int>();
  bool encode_value = variables["encode-value"].as<bool>();
  bool decode_value = variables["decode-value"].as<bool>();

  auto app = std::make_shared<App>(8);

  std::vector<shared_ptr_<Client>> clients;
  std::vector<ref_<EditableStrand>> strands;
  std::vector<ref_<BenchmarkNodeRoot>> root_nodes;
  std::vector<int64_t> message_receive_count;
  clients.reserve(client_count);
  message_receive_count.reserve(client_count);

  for (int i = 0; i < client_count; ++i) {
    message_receive_count.emplace_back(0);

    WrapperStrand strand =
      get_client_wrapper_strand(app, "benchmark" + std::to_string(i));
    auto client = make_shared_<Client>(strand);
    auto root_node = make_ref_<BenchmarkNodeRoot>(strand.strand, point_count);
    root_nodes.emplace_back(root_node);
    strand.strand->set_responder_model(std::move(root_node));
    clients.emplace_back(client);

    client->connect([
                      =, &count = message_receive_count[i], &client = clients[i]
                    ](const shared_ptr_<Connection>&) {

      SubscribeOptions options;
      options.qos = QosLevel::_1;
      for (int a = 0; a < client_count; ++a) {
        string_ node_path = "downstream/benchmark" + std::to_string(a);
        for (int b = 0; b < point_count; ++b) {
          string_ point_path = node_path + "/v" + std::to_string(b);
          client->get_session().requester.subscribe(
            point_path,
            [&count](IncomingSubscribeStream&,
                     ref_<const SubscribeResponseMessage>&&) { ++count; },
            options);
        }
      }
    });

    strands.emplace_back(strand.strand);
  }

  int interval_ms = 5;
  int msg_per_interval = num_message * interval_ms / 1000;

  if (msg_per_interval == 0) {
    msg_per_interval = 1;
    interval_ms = 1000 / num_message;
  }
  boost::posix_time::milliseconds interval(interval_ms);
  boost::asio::deadline_timer timer(app->io_service(), interval);

  int64_t last_count = 0;
  int64_t last_time = DateTime::time_since_epoch();
  std::function<void(const boost::system::error_code&)> timer_callback =
    [&](const boost::system::error_code& error) {
      try {
        int64_t current_time = DateTime::time_since_epoch();
        int64_t count = 0;
        for (int i = 0; i < client_count; ++i) {
          count += message_receive_count[i];
        }
        if (current_time - last_time > 1000) {
          std::cout << std::endl
                    << "per second: "
                    << (count - last_count) * 1000 / (current_time - last_time)
                    << " total: " << count;
          last_time = current_time;
          last_count = count;
        }
        for (int i = 0; i < client_count; ++i) {
          strands[i]->dispatch([&,i]() {
            auto& node = root_nodes[i];
            for (int j = 0; j < msg_per_interval; ++j) {
              node->new_value();
            }
          });
        }

      } catch (std::exception& e) {
        std::cout << std::endl << e.what();
      }
      timer.expires_from_now(interval);
      timer.async_wait(timer_callback);
    };
  timer.async_wait(timer_callback);
  app->wait();
}
<commit_msg>fix broker_throughput<commit_after>#include "dsa/network.h"
#include "dsa/requester.h"
#include "dsa/responder.h"
#include "dsa/stream.h"

#include <chrono>
#include <ctime>
#include <iostream>
#include "core/client.h"
#include "module/logger.h"
#include "network/tcp/tcp_server.h"
#include "util/date_time.h"

#include <math.h>
#include <atomic>

#include <boost/program_options.hpp>

using high_resolution_clock = std::chrono::high_resolution_clock;
using time_point = std::chrono::high_resolution_clock::time_point;

namespace opts = boost::program_options;

using namespace dsa;

namespace broker_benchmark {

class BenchmarkNodeValue : public NodeModel {
 public:
  explicit BenchmarkNodeValue(LinkStrandRef strand)
      : NodeModel(std::move(strand)) {
    update_property("$type", Var("number"));
  };
};
class BenchmarkNodeRoot : public NodeModel {
 public:
  explicit BenchmarkNodeRoot(LinkStrandRef strand, int num_point)
      : NodeModel(std::move(strand)) {
    for (int i = 0; i < num_point; ++i) {
      add_list_child("v" + std::to_string(i),
                     make_ref_<BenchmarkNodeValue>(_strand));
    }
  };
  int64_t sub_value = 0;
  void new_value() {
    sub_value++;
    auto msg = make_ref_<SubscribeResponseMessage>();
    msg->set_value(MessageValue(Var(sub_value), DateTime::get_ts()));
    for (auto it : _list_children) {
      it.second->set_subscribe_response(msg->get_ref());
    }
  }
};
}

WrapperStrand get_client_wrapper_strand(shared_ptr_<App>& app,
                                        const string_& dsid_prefix) {
  WrapperStrand client_strand;
  client_strand.tcp_host = "127.0.0.1";
  client_strand.tcp_port = 4120;

  client_strand.strand = EditableStrand::make_default(app);
  client_strand.client_connection_maker =
      [
        dsid_prefix = dsid_prefix, tcp_host = client_strand.tcp_host,
        tcp_port = client_strand.tcp_port
      ](LinkStrandRef & strand, const string_& previous_session_id,
        int32_t last_ack_id)
          ->shared_ptr_<Connection> {
    return make_shared_<TcpClientConnection>(strand, dsid_prefix, tcp_host,
                                             tcp_port);
  };
  return std::move(client_strand);
}

int main(int argc, const char* argv[]) {
  typedef broker_benchmark::BenchmarkNodeRoot BenchmarkNodeRoot;

  opts::options_description desc{"Options"};
  desc.add_options()("help,h", "Help screen")  //
      ("client,c", opts::value<int>()->default_value(1),
       "Number of Clients")  //
      ("point,p", opts::value<int>()->default_value(1),
       "Number of Points per Client")  //
      ("num-message,n", opts::value<int>()->default_value(1),
       "Message per second per Point")  //
      ("encode-value,e", opts::bool_switch(),
       "Encode value before sending")  //
      ("decode-value,d", opts::bool_switch(),
       "Decode value after receiving")  //
      ;

  opts::variables_map variables;
  opts::store(opts::parse_command_line(argc, argv, desc), variables);
  opts::notify(variables);

  if (variables.count("help")) {
    std::cout << desc << '\n';
    return 0;
  }

  int client_count = variables["client"].as<int>();
  int point_count = variables["point"].as<int>();
  int num_message = variables["num-message"].as<int>();
  bool encode_value = variables["encode-value"].as<bool>();
  bool decode_value = variables["decode-value"].as<bool>();

  auto app = std::make_shared<App>(8);

  std::vector<shared_ptr_<Client>> clients;
  std::vector<ref_<EditableStrand>> strands;
  std::vector<ref_<BenchmarkNodeRoot>> root_nodes;
  std::vector<int64_t> message_receive_count;
  clients.reserve(client_count);
  message_receive_count.reserve(client_count);

  for (int i = 0; i < client_count; ++i) {
    message_receive_count.emplace_back(0);

    WrapperStrand strand =
        get_client_wrapper_strand(app, "benchmark" + std::to_string(i));
    auto client = make_shared_<Client>(strand);
    auto root_node = make_ref_<BenchmarkNodeRoot>(strand.strand, point_count);
    root_nodes.emplace_back(root_node);
    strand.strand->set_responder_model(std::move(root_node));
    clients.emplace_back(client);

    client->connect([
      =, &count = message_receive_count[i], &client = clients[i]
    ](const shared_ptr_<Connection>&) {

      SubscribeOptions options;
      options.qos = QosLevel::_1;
      for (int a = 0; a < client_count; ++a) {
        string_ node_path = "downstream/benchmark" + std::to_string(a);
        for (int b = 0; b < point_count; ++b) {
          string_ point_path = node_path + "/v" + std::to_string(b);
          client->get_session().requester.subscribe(
              point_path,
              [&count](IncomingSubscribeStream&,
                       ref_<const SubscribeResponseMessage>&&) { ++count; },
              options);
        }
      }
    });

    strands.emplace_back(strand.strand);
  }

  int interval_ms = 5;
  int msg_per_interval = num_message * interval_ms / 1000;

  if (msg_per_interval == 0) {
    msg_per_interval = 1;
    interval_ms = 1000 / num_message;
  }
  boost::posix_time::milliseconds interval(interval_ms);
  boost::asio::deadline_timer timer(app->io_service(), interval);

  int64_t last_count = 0;
  int64_t last_time = DateTime::time_since_epoch();
  std::function<void(const boost::system::error_code&)> timer_callback =
      [&](const boost::system::error_code& error) {
        try {
          int64_t current_time = DateTime::time_since_epoch();
          int64_t count = 0;
          for (int i = 0; i < client_count; ++i) {
            count += message_receive_count[i];
          }
          if (current_time - last_time > 1000) {
            std::cout << std::endl
                      << "per second: " << ceil((count - last_count) * 1000.0 /
                                                (current_time - last_time))
                      << " total: " << count;
            last_time = current_time;
            last_count = count;
          }
          for (int i = 0; i < client_count; ++i) {
            strands[i]->dispatch([&, i]() {
              auto& node = root_nodes[i];
              for (int j = 0; j < msg_per_interval; ++j) {
                node->new_value();
              }
            });
          }

        } catch (std::exception& e) {
          std::cout << std::endl << e.what();
        }
        timer.expires_from_now(interval);
        timer.async_wait(timer_callback);
      };
  timer.async_wait(timer_callback);
  app->wait();
}
<|endoftext|>