<commit_before>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// 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 <climits>
#include <random>

#include "gtest/gtest.h"

#include "ngraph/runtime/aligned_buffer.hpp"
#include "ngraph/type/bfloat16.hpp"
#include "util/float_util.hpp"

using namespace std;
using namespace ngraph;

template <typename T>
std::string to_hex(T value)
{
    std::stringstream ss;
    ss << "0x" << std::hex << std::setw(sizeof(T) * 2) << std::setfill('0') << value;
    return ss.str();
}

//***********************
// NOTE
//***********************
// This test uses exact comparisons of floating point values. It is testing for bit-exact
// creation and truncation/rounding of bfloat16 values.
TEST(bfloat16, conversions)
{
    bfloat16 bf;
    const char* source_string;
    std::string bf_string;

    // 1.f, the ground-truth value
    source_string = "0  01111111  000 0000";
    bf = test::bits_to_bfloat16(source_string);
    EXPECT_EQ(bf, bfloat16(1.0));
    bf_string = test::bfloat16_to_bits(bf);
    EXPECT_STREQ(source_string, bf_string.c_str());

    // 1.03125f, the exact upper bound
    source_string = "0  01111111  000 0100";
    bf = test::bits_to_bfloat16(source_string);
    EXPECT_EQ(bf, bfloat16(1.03125));
    bf_string = test::bfloat16_to_bits(bf);
    EXPECT_STREQ(source_string, bf_string.c_str());
}

TEST(bfloat16, round_to_nearest)
{
    const char* fstring;
    std::string expected;
    float fvalue;
    uint16_t bf_round;

    fstring = "0  01111111  000 0100 1000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest(fvalue);
    EXPECT_EQ(bf_round, 0x3F85);

    fstring = "0  01111111  000 0100 0000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest(fvalue);
    EXPECT_EQ(bf_round, 0x3F84);

    fstring = "0  01111111  111 1111 1000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest(fvalue);
    EXPECT_EQ(bf_round, 0x4000);

    // 1.9921875f, the next representable number which should not round up
    fstring = "0  01111111  111 1111 0000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest(fvalue);
    EXPECT_EQ(bf_round, 0x3FFF);
}

TEST(bfloat16, round_to_nearest_even)
{
    const char* fstring;
    float fvalue;
    uint16_t bf_round;

    fstring = "0  01111111  000 0100 1000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest_even(fvalue);
    EXPECT_EQ(bf_round, 0x3F84);

    fstring = "0  01111111  000 0101 1000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest_even(fvalue);
    EXPECT_EQ(bf_round, 0x3F86);

    fstring = "0  01111111  000 0101 0000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest_even(fvalue);
    EXPECT_EQ(bf_round, 0x3F85);

    fstring = "0  01111111  111 1111 1000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest_even(fvalue);
    EXPECT_EQ(bf_round, 0x4000);

    fstring = "0  01111111  111 1111 0000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest_even(fvalue);
    EXPECT_EQ(bf_round, 0x3FFF);
}

TEST(bfloat16, to_float)
{
    bfloat16 bf;
    const char* source_string;

    // 1.f, the ground-truth value
    source_string = "0  01111111  000 0000";
    bf = test::bits_to_bfloat16(source_string);
    float f = static_cast<float>(bf);
    EXPECT_EQ(f, 1.0f);

    // 1.03125f, the exact upper bound
    source_string = "0  01111111  000 0100";
    bf = test::bits_to_bfloat16(source_string);
    f = static_cast<float>(bf);
    EXPECT_EQ(f, 1.03125f);
}

TEST(bfloat16, numeric_limits)
{
    bfloat16 infinity = numeric_limits<bfloat16>::infinity();
    bfloat16 neg_infinity = -numeric_limits<bfloat16>::infinity();
    bfloat16 quiet_nan = numeric_limits<bfloat16>::quiet_NaN();
    bfloat16 signaling_nan = numeric_limits<bfloat16>::signaling_NaN();

    EXPECT_TRUE(isinf(infinity));
    EXPECT_TRUE(isinf(neg_infinity));
    EXPECT_TRUE(isnan(quiet_nan));
    EXPECT_TRUE(isnan(signaling_nan));
}

TEST(benchmark, bfloat16)
{
    size_t buffer_size = 128 * 3 * 224 * 224;
    ngraph::runtime::AlignedBuffer data(buffer_size * sizeof(float), 4096);
    float* f = static_cast<float*>(data.get_ptr());
    // vector<float> data(buffer_size);
    std::mt19937 rng(2112);
    std::uniform_real_distribution<float> distribution(-300, 300);
    for (size_t i = 0; i < buffer_size; ++i)
    {
        f[i] = distribution(rng);
    }
    NGRAPH_INFO << "buffer size " << buffer_size << " floats or " << data.size() << " bytes";

    {
        ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);
        bfloat16* p = static_cast<bfloat16*>(bf_data.get_ptr());
        stopwatch timer;
        timer.start();
        for (size_t i = 0; i < buffer_size; ++i)
        {
            p[i] = bfloat16(f[i]);
        }
        timer.stop();
        NGRAPH_INFO << "float to bfloat16 ctor                  " << timer.get_milliseconds()
                    << "ms";
    }

    {
        ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);
        bfloat16* p = static_cast<bfloat16*>(bf_data.get_ptr());
        stopwatch timer;
        timer.start();
        for (size_t i = 0; i < buffer_size; ++i)
        {
            p[i] = bfloat16::truncate(f[i]);
        }
        timer.stop();
        NGRAPH_INFO << "float to bfloat16 truncate              " << timer.get_milliseconds()
                    << "ms";
    }

    {
        ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);
        bfloat16* p = static_cast<bfloat16*>(bf_data.get_ptr());
        stopwatch timer;
        timer.start();
        for (size_t i = 0; i < buffer_size; ++i)
        {
            p[i] = bfloat16::round_to_nearest(f[i]);
        }
        timer.stop();
        NGRAPH_INFO << "float to bfloat16 round to nearest      " << timer.get_milliseconds()
                    << "ms";
    }

    {
        ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);
        bfloat16* p = static_cast<bfloat16*>(bf_data.get_ptr());
        stopwatch timer;
        timer.start();
        for (size_t i = 0; i < buffer_size; ++i)
        {
            p[i] = bfloat16::round_to_nearest_even(f[i]);
        }
        timer.stop();
        NGRAPH_INFO << "float to bfloat16 round to nearest even " << timer.get_milliseconds()
                    << "ms";
    }
}
<commit_msg>Work around problem with AppleClang's isinf (#2820)<commit_after>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// 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 <climits>
#include <random>

#include "gtest/gtest.h"

#include "ngraph/runtime/aligned_buffer.hpp"
#include "ngraph/type/bfloat16.hpp"
#include "util/float_util.hpp"

using namespace std;
using namespace ngraph;

template <typename T>
std::string to_hex(T value)
{
    std::stringstream ss;
    ss << "0x" << std::hex << std::setw(sizeof(T) * 2) << std::setfill('0') << value;
    return ss.str();
}

//***********************
// NOTE
//***********************
// This test uses exact comparisons of floating point values. It is testing for bit-exact
// creation and truncation/rounding of bfloat16 values.
TEST(bfloat16, conversions)
{
    bfloat16 bf;
    const char* source_string;
    std::string bf_string;

    // 1.f, the ground-truth value
    source_string = "0  01111111  000 0000";
    bf = test::bits_to_bfloat16(source_string);
    EXPECT_EQ(bf, bfloat16(1.0));
    bf_string = test::bfloat16_to_bits(bf);
    EXPECT_STREQ(source_string, bf_string.c_str());

    // 1.03125f, the exact upper bound
    source_string = "0  01111111  000 0100";
    bf = test::bits_to_bfloat16(source_string);
    EXPECT_EQ(bf, bfloat16(1.03125));
    bf_string = test::bfloat16_to_bits(bf);
    EXPECT_STREQ(source_string, bf_string.c_str());
}

TEST(bfloat16, round_to_nearest)
{
    const char* fstring;
    std::string expected;
    float fvalue;
    uint16_t bf_round;

    fstring = "0  01111111  000 0100 1000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest(fvalue);
    EXPECT_EQ(bf_round, 0x3F85);

    fstring = "0  01111111  000 0100 0000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest(fvalue);
    EXPECT_EQ(bf_round, 0x3F84);

    fstring = "0  01111111  111 1111 1000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest(fvalue);
    EXPECT_EQ(bf_round, 0x4000);

    // 1.9921875f, the next representable number which should not round up
    fstring = "0  01111111  111 1111 0000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest(fvalue);
    EXPECT_EQ(bf_round, 0x3FFF);
}

TEST(bfloat16, round_to_nearest_even)
{
    const char* fstring;
    float fvalue;
    uint16_t bf_round;

    fstring = "0  01111111  000 0100 1000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest_even(fvalue);
    EXPECT_EQ(bf_round, 0x3F84);

    fstring = "0  01111111  000 0101 1000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest_even(fvalue);
    EXPECT_EQ(bf_round, 0x3F86);

    fstring = "0  01111111  000 0101 0000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest_even(fvalue);
    EXPECT_EQ(bf_round, 0x3F85);

    fstring = "0  01111111  111 1111 1000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest_even(fvalue);
    EXPECT_EQ(bf_round, 0x4000);

    fstring = "0  01111111  111 1111 0000 0000 0000 0000";
    fvalue = test::bits_to_float(fstring);
    bf_round = bfloat16::round_to_nearest_even(fvalue);
    EXPECT_EQ(bf_round, 0x3FFF);
}

TEST(bfloat16, to_float)
{
    bfloat16 bf;
    const char* source_string;

    // 1.f, the ground-truth value
    source_string = "0  01111111  000 0000";
    bf = test::bits_to_bfloat16(source_string);
    float f = static_cast<float>(bf);
    EXPECT_EQ(f, 1.0f);

    // 1.03125f, the exact upper bound
    source_string = "0  01111111  000 0100";
    bf = test::bits_to_bfloat16(source_string);
    f = static_cast<float>(bf);
    EXPECT_EQ(f, 1.03125f);
}

TEST(bfloat16, numeric_limits)
{
    bfloat16 infinity = numeric_limits<bfloat16>::infinity();
    bfloat16 neg_infinity = -numeric_limits<bfloat16>::infinity();
    bfloat16 quiet_nan = numeric_limits<bfloat16>::quiet_NaN();
    bfloat16 signaling_nan = numeric_limits<bfloat16>::signaling_NaN();

    // Would be nice if we could have bfloat16 overloads for these, but it would require adding
    // overloads into ::std. So we just cast to float here. We can't rely on an implicit cast
    // because it fails with some versions of AppleClang.
    EXPECT_TRUE(isinf(static_cast<float>(infinity)));
    EXPECT_TRUE(isinf(static_cast<float>(neg_infinity)));
    EXPECT_TRUE(isnan(static_cast<float>(quiet_nan)));
    EXPECT_TRUE(isnan(static_cast<float>(signaling_nan)));
}

TEST(benchmark, bfloat16)
{
    size_t buffer_size = 128 * 3 * 224 * 224;
    ngraph::runtime::AlignedBuffer data(buffer_size * sizeof(float), 4096);
    float* f = static_cast<float*>(data.get_ptr());
    // vector<float> data(buffer_size);
    std::mt19937 rng(2112);
    std::uniform_real_distribution<float> distribution(-300, 300);
    for (size_t i = 0; i < buffer_size; ++i)
    {
        f[i] = distribution(rng);
    }
    NGRAPH_INFO << "buffer size " << buffer_size << " floats or " << data.size() << " bytes";

    {
        ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);
        bfloat16* p = static_cast<bfloat16*>(bf_data.get_ptr());
        stopwatch timer;
        timer.start();
        for (size_t i = 0; i < buffer_size; ++i)
        {
            p[i] = bfloat16(f[i]);
        }
        timer.stop();
        NGRAPH_INFO << "float to bfloat16 ctor                  " << timer.get_milliseconds()
                    << "ms";
    }

    {
        ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);
        bfloat16* p = static_cast<bfloat16*>(bf_data.get_ptr());
        stopwatch timer;
        timer.start();
        for (size_t i = 0; i < buffer_size; ++i)
        {
            p[i] = bfloat16::truncate(f[i]);
        }
        timer.stop();
        NGRAPH_INFO << "float to bfloat16 truncate              " << timer.get_milliseconds()
                    << "ms";
    }

    {
        ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);
        bfloat16* p = static_cast<bfloat16*>(bf_data.get_ptr());
        stopwatch timer;
        timer.start();
        for (size_t i = 0; i < buffer_size; ++i)
        {
            p[i] = bfloat16::round_to_nearest(f[i]);
        }
        timer.stop();
        NGRAPH_INFO << "float to bfloat16 round to nearest      " << timer.get_milliseconds()
                    << "ms";
    }

    {
        ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);
        bfloat16* p = static_cast<bfloat16*>(bf_data.get_ptr());
        stopwatch timer;
        timer.start();
        for (size_t i = 0; i < buffer_size; ++i)
        {
            p[i] = bfloat16::round_to_nearest_even(f[i]);
        }
        timer.stop();
        NGRAPH_INFO << "float to bfloat16 round to nearest even " << timer.get_milliseconds()
                    << "ms";
    }
}
<|endoftext|>


<commit_before>#include <iostream>

#include <gtest/gtest.h>

#include <Unittests/unittests_common.hh>

namespace {

class OpenMeshMeshCastTest: public testing::Test {
};

struct TriTraits1: public OpenMesh::DefaultTraits {
        typedef OpenMesh::Vec3d Point;
};
struct TriTraits2: public OpenMesh::DefaultTraits {
        typedef OpenMesh::Vec3d Point;
};

TEST_F(OpenMeshMeshCastTest, PerformCast) {
    OpenMesh::TriMesh_ArrayKernelT<TriTraits1> a;
    OpenMesh::TriMesh_ArrayKernelT<TriTraits2> &b =
            OpenMesh::mesh_cast<OpenMesh::TriMesh_ArrayKernelT<TriTraits2>&>(a);
    /*
    OpenMesh::TriMesh_ArrayKernelT < TriTraits2 > &b =
            OpenMesh::MeshCast<
                TriMesh_ArrayKernelT<TriTraits2>&,
                OpenMesh::TriMesh_ArrayKernelT<TriTraits1>&
            >::cast(a);
    */
}

}
<commit_msg>Fixed cppcheck unused variable<commit_after>#include <iostream>

#include <gtest/gtest.h>

#include <Unittests/unittests_common.hh>

namespace {

class OpenMeshMeshCastTest: public testing::Test {
};

struct TriTraits1: public OpenMesh::DefaultTraits {
        typedef OpenMesh::Vec3d Point;
};
struct TriTraits2: public OpenMesh::DefaultTraits {
        typedef OpenMesh::Vec3d Point;
};

TEST_F(OpenMeshMeshCastTest, PerformCast) {
    OpenMesh::TriMesh_ArrayKernelT<TriTraits1> a;
    OpenMesh::TriMesh_ArrayKernelT<TriTraits2> &b =
            OpenMesh::mesh_cast<OpenMesh::TriMesh_ArrayKernelT<TriTraits2>&>(a);
    b.reserve(10,10,10);
    /*
    OpenMesh::TriMesh_ArrayKernelT < TriTraits2 > &b =
            OpenMesh::MeshCast<
                TriMesh_ArrayKernelT<TriTraits2>&,
                OpenMesh::TriMesh_ArrayKernelT<TriTraits1>&
            >::cast(a);
    */
}

}
<|endoftext|>


<commit_before><commit_msg>It was depthMask!<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/api/frame_subscriber.h"

#include "atom/common/native_mate_converters/gfx_converter.h"
#include "base/bind.h"
#include "content/public/browser/render_widget_host.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"

#include "atom/common/node_includes.h"

namespace atom {

namespace {

void CopyPixelsToBuffer(const SkBitmap& bitmap,
                        const v8::Local<v8::Object>& buffer) {
  size_t rgb_arr_size = bitmap.width() * bitmap.height() *
      bitmap.bytesPerPixel();

  memcpy(node::Buffer::Data(buffer), bitmap.getPixels(), rgb_arr_size);
}

}  // namespace

namespace api {

FrameSubscriber::FrameSubscriber(v8::Isolate* isolate,
                                 content::RenderWidgetHostView* view,
                                 const FrameCaptureCallback& callback,
                                 bool only_dirty)
    : isolate_(isolate),
      view_(view),
      callback_(callback),
      only_dirty_(only_dirty),
      source_id_for_copy_request_(base::UnguessableToken::Create()),
      weak_factory_(this) {
}

bool FrameSubscriber::ShouldCaptureFrame(
    const gfx::Rect& dirty_rect,
    base::TimeTicks present_time,
    scoped_refptr<media::VideoFrame>* storage,
    DeliverFrameCallback* callback) {
  if (!view_)
    return false;

  if (dirty_rect.IsEmpty())
    return false;

  gfx::Rect rect = gfx::Rect(view_->GetVisibleViewportSize());
  if (only_dirty_)
    rect = dirty_rect;

  gfx::Size view_size = rect.size();
  gfx::Size bitmap_size = view_size;
  gfx::NativeView native_view = view_->GetNativeView();
  const float scale =
      display::Screen::GetScreen()->GetDisplayNearestView(native_view)
      .device_scale_factor();
  if (scale > 1.0f)
    bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);

  rect = gfx::Rect(rect.origin(), bitmap_size);

  view_->CopyFromSurface(
      rect,
      rect.size(),
      base::Bind(&FrameSubscriber::OnFrameDelivered,
                 weak_factory_.GetWeakPtr(), callback_, rect),
      kBGRA_8888_SkColorType);

  return false;
}

const base::UnguessableToken& FrameSubscriber::GetSourceIdForCopyRequest() {
  return source_id_for_copy_request_;
}

void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback,
                                       const gfx::Rect& damage_rect,
                                       const SkBitmap& bitmap,
                                       content::ReadbackResponse response) {
  if (response != content::ReadbackResponse::READBACK_SUCCESS)
    return;

  v8::Locker locker(isolate_);
  v8::HandleScope handle_scope(isolate_);

  size_t rgb_arr_size = bitmap.width() * bitmap.height() *
    bitmap.bytesPerPixel();
  v8::MaybeLocal<v8::Object> buffer = node::Buffer::New(isolate_, rgb_arr_size);
  if (buffer.IsEmpty())
    return;

  CopyPixelsToBuffer(bitmap, buffer.ToLocalChecked());

  v8::Local<v8::Value> damage =
      mate::Converter<gfx::Rect>::ToV8(isolate_, damage_rect);

  callback_.Run(buffer.ToLocalChecked(), damage);
}

}  // namespace api

}  // namespace atom
<commit_msg>Lock pixels before calling `SkBitmap::getPixels` and copy bitmap row-wise in case (stride != width)<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/api/frame_subscriber.h"

#include "atom/common/native_mate_converters/gfx_converter.h"
#include "base/bind.h"
#include "content/public/browser/render_widget_host.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"

#include "atom/common/node_includes.h"

namespace atom {

namespace api {

FrameSubscriber::FrameSubscriber(v8::Isolate* isolate,
                                 content::RenderWidgetHostView* view,
                                 const FrameCaptureCallback& callback,
                                 bool only_dirty)
    : isolate_(isolate),
      view_(view),
      callback_(callback),
      only_dirty_(only_dirty),
      source_id_for_copy_request_(base::UnguessableToken::Create()),
      weak_factory_(this) {
}

bool FrameSubscriber::ShouldCaptureFrame(
    const gfx::Rect& dirty_rect,
    base::TimeTicks present_time,
    scoped_refptr<media::VideoFrame>* storage,
    DeliverFrameCallback* callback) {
  if (!view_)
    return false;

  if (dirty_rect.IsEmpty())
    return false;

  gfx::Rect rect = gfx::Rect(view_->GetVisibleViewportSize());
  if (only_dirty_)
    rect = dirty_rect;

  gfx::Size view_size = rect.size();
  gfx::Size bitmap_size = view_size;
  gfx::NativeView native_view = view_->GetNativeView();
  const float scale =
      display::Screen::GetScreen()->GetDisplayNearestView(native_view)
      .device_scale_factor();
  if (scale > 1.0f)
    bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);

  rect = gfx::Rect(rect.origin(), bitmap_size);

  view_->CopyFromSurface(
      rect,
      rect.size(),
      base::Bind(&FrameSubscriber::OnFrameDelivered,
                 weak_factory_.GetWeakPtr(), callback_, rect),
      kBGRA_8888_SkColorType);

  return false;
}

const base::UnguessableToken& FrameSubscriber::GetSourceIdForCopyRequest() {
  return source_id_for_copy_request_;
}

void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback,
                                       const gfx::Rect& damage_rect,
                                       const SkBitmap& bitmap,
                                       content::ReadbackResponse response) {
  if (response != content::ReadbackResponse::READBACK_SUCCESS)
    return;

  v8::Locker locker(isolate_);
  v8::HandleScope handle_scope(isolate_);

  size_t rgb_row_size = bitmap.width() * bitmap.bytesPerPixel();

  v8::MaybeLocal<v8::Object> buffer =
      node::Buffer::New(isolate_, rgb_row_size * bitmap.height());

  if (buffer.IsEmpty())
    return;

  auto local_buffer = buffer.ToLocalChecked();

  {
    SkAutoLockPixels lock(bitmap);
    auto source = static_cast<const unsigned char*>(bitmap.getPixels());
    auto target = node::Buffer::Data(local_buffer);

    for (int y = 0; y < bitmap.height(); ++y) {
      memcpy(target, source, rgb_row_size);
      source += bitmap.rowBytes();
      target += rgb_row_size;
    }
  }

  v8::Local<v8::Value> damage =
      mate::Converter<gfx::Rect>::ToV8(isolate_, damage_rect);

  callback_.Run(local_buffer, damage);
}

}  // namespace api

}  // namespace atom
<|endoftext|>


<commit_before>
/*
 * Copyright (c) 2015-2020 Agalmic Ventures LLC (www.agalmicventures.com)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "CommandManager.hpp"

#include <boost/algorithm/string.hpp>

#include "Command.hpp"

namespace werk
{

bool CommandManager::execute(const std::string &commandLine)
{
	//History is only added here, from human executions. This enables neat stuff like the redo
	//command and allows the command system to still be used in an automated fashion.
	_commandHistory.emplace_back(_clock.time(), commandLine);

	//Parse the arguments, ignoring extra whitespace
	std::vector<std::string> arguments;
	boost::split(arguments, boost::trim_copy(commandLine), boost::is_any_of(" \t"), boost::token_compress_on);
	return arguments[0] == "" ? false : execute(arguments);
}

bool CommandManager::execute(const std::vector<std::string> &arguments)
{
	if (arguments.empty()) {
		_log->logRaw(LogLevel::CRITICAL, "Got zero-length arguments to CommandManager::execute");
		return false;
	}

	const std::string &commandName = arguments[0];
	auto commandIter = _commands.find(commandName);
	if (commandIter == _commands.end()) {
		_log->log(LogLevel::ERROR, "Command not found: %s", commandName.c_str());
		return false;
	}

	Command *command = commandIter->second;
	return command->execute(arguments);
}

CommandAction *CommandManager::newCommandAction(const std::string &name, const std::string &commandLine)
{
	std::vector<std::string> arguments;
	boost::split(arguments, commandLine, boost::is_any_of(" \t"));
	const std::string &commandName = arguments[0];
	auto commandIter = _commands.find(commandName);
	if (commandIter == _commands.end()) {
		_log->log(LogLevel::ERROR, "Command not found for action: %s", commandName.c_str());
		return nullptr;
	}

	Command *command = commandIter->second;
	CommandAction *commandAction = new CommandAction(name, command);
	commandAction->arguments() = arguments;
	return commandAction;
}

void CommandManager::logTo(Log *log) const
{
	log->log(LogLevel::INFO, "<CommandManager> Commands (%zu):", _commands.size());
	for (const auto &i : _commands) {
		_log->log(LogLevel::INFO, "  %16s   %s", i.first.c_str(), i.second->help().c_str());
	}
}

}
<commit_msg>Fix build error on some linux distributions<commit_after>
/*
 * Copyright (c) 2015-2020 Agalmic Ventures LLC (www.agalmicventures.com)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "CommandManager.hpp"

#include <boost/algorithm/string.hpp>

#include "Command.hpp"

namespace werk
{

bool CommandManager::execute(const std::string &commandLine)
{
	//History is only added here, from human executions. This enables neat stuff like the redo
	//command and allows the command system to still be used in an automated fashion.
	_commandHistory.emplace_back(_clock.time(), commandLine);

	//Parse the arguments, ignoring extra whitespace
	std::string trimmedCommandLine = boost::trim_copy(commandLine);
	std::vector<std::string> arguments;
	boost::split(arguments, trimmedCommandLine, boost::is_any_of(" \t"), boost::token_compress_on);
	return arguments[0] == "" ? false : execute(arguments);
}

bool CommandManager::execute(const std::vector<std::string> &arguments)
{
	if (arguments.empty()) {
		_log->logRaw(LogLevel::CRITICAL, "Got zero-length arguments to CommandManager::execute");
		return false;
	}

	const std::string &commandName = arguments[0];
	auto commandIter = _commands.find(commandName);
	if (commandIter == _commands.end()) {
		_log->log(LogLevel::ERROR, "Command not found: %s", commandName.c_str());
		return false;
	}

	Command *command = commandIter->second;
	return command->execute(arguments);
}

CommandAction *CommandManager::newCommandAction(const std::string &name, const std::string &commandLine)
{
	std::vector<std::string> arguments;
	boost::split(arguments, commandLine, boost::is_any_of(" \t"));
	const std::string &commandName = arguments[0];
	auto commandIter = _commands.find(commandName);
	if (commandIter == _commands.end()) {
		_log->log(LogLevel::ERROR, "Command not found for action: %s", commandName.c_str());
		return nullptr;
	}

	Command *command = commandIter->second;
	CommandAction *commandAction = new CommandAction(name, command);
	commandAction->arguments() = arguments;
	return commandAction;
}

void CommandManager::logTo(Log *log) const
{
	log->log(LogLevel::INFO, "<CommandManager> Commands (%zu):", _commands.size());
	for (const auto &i : _commands) {
		_log->log(LogLevel::INFO, "  %16s   %s", i.first.c_str(), i.second->help().c_str());
	}
}

}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name:      process.cpp
// Purpose:   Implementation of class wxExProcess
// Author:    Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/utils.h> // for wxGetEnv
#include <wx/extension/process.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/shell.h>
#include <wx/extension/util.h> // for wxExConfigFirstOf

BEGIN_EVENT_TABLE(wxExProcess, wxProcess)
  EVT_MENU(ID_SHELL_COMMAND, wxExProcess::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND_STOP, wxExProcess::OnCommand)
  EVT_TIMER(-1, wxExProcess::OnTimer)
END_EVENT_TABLE()

wxExSTCEntryDialog* wxExProcess::m_Dialog = NULL;
wxString wxExProcess::m_WorkingDirKey = _("Process folder");

wxExProcess::wxExProcess()
  : wxProcess(wxPROCESS_REDIRECT)
  , m_Timer(new wxTimer(this))
  , m_Busy(false)
  , m_Error(false)
  , m_Sync(false)
{
  m_Command = wxExConfigFirstOf(_("Process"));
}

wxExProcess::~wxExProcess()
{
  delete m_Timer;
}

wxExProcess::wxExProcess(const wxExProcess& process)
{
  *this = process;
}

wxExProcess& wxExProcess::operator=(const wxExProcess& p)
{
  m_Busy = p.m_Busy;
  m_Error = p.m_Error;
  m_Output = p.m_Output;
  m_Sync = p.m_Sync;
  m_Timer = new wxTimer(this);

  return *this;
}

bool wxExProcess::CheckInput()
{
  if (m_Busy)
  {
    return false;
  }

  m_Busy = true;

  wxString output;

  if (IsInputAvailable())
  {
    wxTextInputStream tis(*GetInputStream());

    while (IsInputAvailable())
    {
      const wxChar c = tis.GetChar();

      if (c != 0)
      {
        output << c;
      }
    }
  }

  if (IsErrorAvailable())
  {
    wxTextInputStream tis(*GetErrorStream());

    while (IsErrorAvailable())
    {
      const wxChar c = tis.GetChar();

      if (c != 0)
      {
        output << c;
      }
    }
  }

  m_Busy = false;

  if (!output.empty())
  {
    m_Dialog->GetSTCShell()->AddText(output);

    return true;
  }
  else
  {
    return false;
  }
}

int wxExProcess::ConfigDialog(
  wxWindow* parent,
  const wxString& title,
  bool modal)
{
  std::vector<wxExConfigItem> v;

  v.push_back(wxExConfigItem(
    _("Process"),
    CONFIG_COMBOBOX,
    wxEmptyString,
    true));

  v.push_back(wxExConfigItem(
    m_WorkingDirKey,
    CONFIG_COMBOBOXDIR,
    wxEmptyString,
    true,
    1000));

  if (modal)
  {
    return wxExConfigDialog(parent,
      v,
      title).ShowModal();
  }
  else
  {
    wxExConfigDialog* dlg = new wxExConfigDialog(
      parent,
      v,
      title);

    return dlg->Show();
  }
}

bool wxExProcess::Execute(
  const wxString& command_to_execute,
  int flags,
  const wxString& wd)
{
  m_Error = false;

  struct wxExecuteEnv env;

  if (command_to_execute.empty())
  {
    if (wxExConfigFirstOf(_("Process")).empty())
    {
      if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL)
      {
        return false;
      }
    }

    m_Command = wxExConfigFirstOf(_("Process"));
    env.cwd = wxExConfigFirstOf(m_WorkingDirKey);
  }
  else
  {
    m_Command = command_to_execute;
    env.cwd = wd;
  }

  m_Sync = (flags & wxEXEC_SYNC);

  // Construct the dialog.
  // This is necessary both in sync and async mode,
  // as for sync mode the dialog is used for presenting the
  // output member.
  if (m_Dialog == NULL)
  {
    m_Dialog = new wxExSTCEntryDialog(
      wxTheApp->GetTopWindow(),
      wxEmptyString,
      wxEmptyString,
      wxEmptyString,
      wxOK,
      true); // use_shell to force STCShell

    m_Dialog->SetProcess(this);
    m_Dialog->GetSTCShell()->SetEventHandler(this);
  }

  m_Dialog->GetSTCShell()->EnableShell(!m_Sync);

  if (!m_Sync)
  {
    m_Dialog->SetTitle(m_Command);
    m_Dialog->GetSTCShell()->ClearAll();

    // If we have entered a shell, then the shell
    // itself has no prompt. So put one here.
    if (m_Command == "bash" ||
        m_Command == "csh" ||
        m_Command == "ksh" ||
        m_Command == "tcsh" ||
        m_Command == "sh")
    {
      wxString host;
      wxGetEnv("HOST", &host);
      m_Dialog->GetSTCShell()->SetPrompt(host + ">");
    }
    else
    {
      m_Dialog->GetSTCShell()->SetPrompt("");
    }

    // For asynchronous execution the return value is the process id and zero
    // value indicates that the command could not be executed.
    if (wxExecute(m_Command, flags, this, &env) > 0)
    {
      m_Dialog->Show();

      if (!CheckInput())
      {
        m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);
      }

      m_Timer->Start(100); // each 100 milliseconds
    }
    else
    {
      m_Dialog->Hide();

      m_Error = true;
    }
  }
  else
  {
    wxArrayString output;
    wxArrayString errors;

    // Call wxExecute to execute the command and
    // collect the output and the errors.
    if (wxExecute(
      m_Command,
      output,
      errors,
      flags,
      &env) == -1)
    {
      m_Output.clear();
      m_Error = true;
    }
    else
    {
      // Set output by converting array strings into normal strings.
      m_Output = wxJoin(errors, '\n', '\n') + wxJoin(output, '\n', '\n');
    }
  }

  return !m_Error;
}

bool wxExProcess::IsRunning() const
{
  if (
    // If we executed a sync process, then it always ended,
    // so it is not running.
    m_Sync ||
    GetPid() <= 0)
  {
    return false;
  }

  return Exists(GetPid());
}

wxKillError wxExProcess::Kill(wxSignal sig)
{
  if (!IsRunning())
  {
    return wxKILL_NO_PROCESS;
  }

  const wxKillError result = wxProcess::Kill(GetPid(), sig);

  switch (result)
  {
    case wxKILL_OK:
      wxLogStatus(_("Stopped"));
      DeletePendingEvents();
      m_Timer->Stop();
      m_Dialog->Hide();
      break;

    case wxKILL_BAD_SIGNAL:
      wxLogStatus("no such signal");
      break;

    case wxKILL_ACCESS_DENIED:
    	wxLogStatus("permission denied");
      break;

    case wxKILL_NO_PROCESS:
      wxLogStatus("no such process");
      break;

    case wxKILL_ERROR:
      wxLogStatus("another, unspecified error");
      break;

    default: wxFAIL;
  }

  return result;
}

void wxExProcess::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
  case ID_SHELL_COMMAND:
    m_Timer->Stop();
    m_Dialog->GetSTCShell()->LineEnd();

    if (m_Command != "cmd")
    {
      m_Dialog->GetSTCShell()->AddText(m_Dialog->GetSTCShell()->GetEOL());
    }

    if (IsRunning())
    {
      // send command to process
      wxOutputStream* os = GetOutputStream();

      if (os != NULL)
      {
        wxTextOutputStream os(*GetOutputStream());
        os.WriteString(event.GetString() + "\n");
      }

      if (CheckInput())
      {
        m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);
      }

      m_Timer->Start();
    }
    else
    {
      wxLogStatus("Process is not running");
    }
    break;

  case ID_SHELL_COMMAND_STOP:
    if (IsRunning())
    {
      Kill();
    }
    break;

  default: wxFAIL; break;
  }
}

void wxExProcess::OnTerminate(int pid, int status)
{
  m_Timer->Stop();

  wxLogStatus(_("Ready"));
  wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);
  wxPostEvent(wxTheApp->GetTopWindow(), event);

  // Collect remaining input.
  CheckInput();
}

void wxExProcess::OnTimer(wxTimerEvent& event)
{
  CheckInput();
}

#if wxUSE_GUI
void wxExProcess::ShowOutput(const wxString& caption) const
{
  if (!m_Sync)
  {
    wxLogStatus("Output only available for sync processes");
  }
  else if (!m_Error)
  {
    if (m_Dialog != NULL)
    {
      m_Dialog->GetSTC()->SetText(m_Output);
      m_Dialog->SetTitle(caption.empty() ? m_Command: caption);
      m_Dialog->Show();
    }
    else if (!m_Output.empty())
    {
      wxLogMessage(m_Output);
    }
    else
    {
      wxLogStatus("No output available");
    }
  }
  else
  {
    // Executing command failed, so no output,
    // show failing command.
    wxLogError("Could not execute: " + m_Command);
  }
}
#endif
<commit_msg>more process updates<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name:      process.cpp
// Purpose:   Implementation of class wxExProcess
// Author:    Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/utils.h> // for wxGetEnv
#include <wx/extension/process.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/shell.h>
#include <wx/extension/util.h> // for wxExConfigFirstOf

BEGIN_EVENT_TABLE(wxExProcess, wxProcess)
  EVT_MENU(ID_SHELL_COMMAND, wxExProcess::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND_STOP, wxExProcess::OnCommand)
  EVT_TIMER(-1, wxExProcess::OnTimer)
END_EVENT_TABLE()

wxExSTCEntryDialog* wxExProcess::m_Dialog = NULL;
wxString wxExProcess::m_WorkingDirKey = _("Process folder");

wxExProcess::wxExProcess()
  : wxProcess(wxPROCESS_REDIRECT)
  , m_Timer(new wxTimer(this))
  , m_Busy(false)
  , m_Error(false)
  , m_Sync(false)
{
  m_Command = wxExConfigFirstOf(_("Process"));
}

wxExProcess::~wxExProcess()
{
  delete m_Timer;
}

wxExProcess::wxExProcess(const wxExProcess& process)
{
  *this = process;
}

wxExProcess& wxExProcess::operator=(const wxExProcess& p)
{
  m_Busy = p.m_Busy;
  m_Error = p.m_Error;
  m_Output = p.m_Output;
  m_Sync = p.m_Sync;
  m_Timer = new wxTimer(this);

  return *this;
}

bool wxExProcess::CheckInput()
{
  if (m_Busy)
  {
    return false;
  }

  m_Busy = true;

  wxString output;

  if (IsInputAvailable())
  {
    wxTextInputStream tis(*GetInputStream());

    while (IsInputAvailable())
    {
      const wxChar c = tis.GetChar();

      if (c != 0)
      {
        output << c;
      }
    }
  }

  if (IsErrorAvailable())
  {
    wxTextInputStream tis(*GetErrorStream());

    while (IsErrorAvailable())
    {
      const wxChar c = tis.GetChar();

      if (c != 0)
      {
        output << c;
      }
    }
  }

  m_Busy = false;

  if (!output.empty())
  {
    m_Dialog->GetSTCShell()->AddText(output);
    m_Dialog->GetSTCShell()->EnsureCaretVisible();

    return true;
  }
  else
  {
    return false;
  }
}

int wxExProcess::ConfigDialog(
  wxWindow* parent,
  const wxString& title,
  bool modal)
{
  std::vector<wxExConfigItem> v;

  v.push_back(wxExConfigItem(
    _("Process"),
    CONFIG_COMBOBOX,
    wxEmptyString,
    true));

  v.push_back(wxExConfigItem(
    m_WorkingDirKey,
    CONFIG_COMBOBOXDIR,
    wxEmptyString,
    true,
    1000));

  if (modal)
  {
    return wxExConfigDialog(parent,
      v,
      title).ShowModal();
  }
  else
  {
    wxExConfigDialog* dlg = new wxExConfigDialog(
      parent,
      v,
      title);

    return dlg->Show();
  }
}

bool wxExProcess::Execute(
  const wxString& command_to_execute,
  int flags,
  const wxString& wd)
{
  m_Error = false;

  struct wxExecuteEnv env;

  if (command_to_execute.empty())
  {
    if (wxExConfigFirstOf(_("Process")).empty())
    {
      if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL)
      {
        return false;
      }
    }

    m_Command = wxExConfigFirstOf(_("Process"));
    env.cwd = wxExConfigFirstOf(m_WorkingDirKey);
  }
  else
  {
    m_Command = command_to_execute;
    env.cwd = wd;
  }

  m_Sync = (flags & wxEXEC_SYNC);

  // Construct the dialog.
  // This is necessary both in sync and async mode,
  // as for sync mode the dialog is used for presenting the
  // output member.
  if (m_Dialog == NULL)
  {
    m_Dialog = new wxExSTCEntryDialog(
      wxTheApp->GetTopWindow(),
      wxEmptyString,
      wxEmptyString,
      wxEmptyString,
      wxOK,
      true); // use_shell to force STCShell

    m_Dialog->SetProcess(this);
    m_Dialog->GetSTCShell()->SetEventHandler(this);
  }

  m_Dialog->GetSTCShell()->EnableShell(!m_Sync);

  if (!m_Sync)
  {
    m_Dialog->SetTitle(m_Command);
    m_Dialog->GetSTCShell()->ClearAll();

    // If we have entered a shell, then the shell
    // itself has no prompt. So put one here.
    if (m_Command == "bash" ||
        m_Command == "csh" ||
        m_Command == "ksh" ||
        m_Command == "tcsh" ||
        m_Command == "sh")
    {
      wxString host;
      wxGetEnv("HOST", &host);
      m_Dialog->GetSTCShell()->SetPrompt(host + ">", false);
    }
    else
    {
      m_Dialog->GetSTCShell()->SetPrompt("");
    }

    // For asynchronous execution the return value is the process id and zero
    // value indicates that the command could not be executed.
    if (wxExecute(m_Command, flags, this, &env) > 0)
    {
      m_Dialog->Show();

      if (!CheckInput())
      {
        m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);
      }

      if (IsRunning())
      {
        m_Timer->Start(100); // each 100 milliseconds
      }
    }
    else
    {
      m_Dialog->Hide();

      m_Error = true;
    }
  }
  else
  {
    wxArrayString output;
    wxArrayString errors;

    // Call wxExecute to execute the command and
    // collect the output and the errors.
    if (wxExecute(
      m_Command,
      output,
      errors,
      flags,
      &env) == -1)
    {
      m_Output.clear();
      m_Error = true;
    }
    else
    {
      // Set output by converting array strings into normal strings.
      m_Output = wxJoin(errors, '\n', '\n') + wxJoin(output, '\n', '\n');
    }
  }

  return !m_Error;
}

bool wxExProcess::IsRunning() const
{
  if (
    // If we executed a sync process, then it always ended,
    // so it is not running.
    m_Sync ||
    GetPid() <= 0)
  {
    return false;
  }

  return Exists(GetPid());
}

wxKillError wxExProcess::Kill(wxSignal sig)
{
  if (!IsRunning())
  {
    return wxKILL_NO_PROCESS;
  }

  const wxKillError result = wxProcess::Kill(GetPid(), sig);

  switch (result)
  {
    case wxKILL_OK:
      wxLogStatus(_("Stopped"));
      DeletePendingEvents();
      m_Timer->Stop();
      m_Dialog->Hide();
      break;

    case wxKILL_BAD_SIGNAL:
      wxLogStatus("no such signal");
      break;

    case wxKILL_ACCESS_DENIED:
    	wxLogStatus("permission denied");
      break;

    case wxKILL_NO_PROCESS:
      wxLogStatus("no such process");
      break;

    case wxKILL_ERROR:
      wxLogStatus("another, unspecified error");
      break;

    default: wxFAIL;
  }

  return result;
}

void wxExProcess::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
  case ID_SHELL_COMMAND:
    m_Timer->Stop();
    m_Dialog->GetSTCShell()->LineEnd();

    if (m_Command != "cmd")
    {
      m_Dialog->GetSTCShell()->AddText(m_Dialog->GetSTCShell()->GetEOL());
    }

    if (IsRunning())
    {
      // send command to process
      wxOutputStream* os = GetOutputStream();

      if (os != NULL)
      {
        wxTextOutputStream os(*GetOutputStream());
        os.WriteString(event.GetString() + "\n");
      }

      m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);

      m_Timer->Start();
    }
    else
    {
      wxLogStatus("Process is not running");
    }
    break;

  case ID_SHELL_COMMAND_STOP:
    if (IsRunning())
    {
      Kill();
    }
    break;

  default: wxFAIL; break;
  }
}

void wxExProcess::OnTerminate(int pid, int status)
{
  m_Timer->Stop();

  wxLogStatus(_("Ready"));
  wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);
  wxPostEvent(wxTheApp->GetTopWindow(), event);

  // Collect remaining input.
  CheckInput();
}

void wxExProcess::OnTimer(wxTimerEvent& event)
{
  CheckInput();
}

#if wxUSE_GUI
void wxExProcess::ShowOutput(const wxString& caption) const
{
  if (!m_Sync)
  {
    wxLogStatus("Output only available for sync processes");
  }
  else if (!m_Error)
  {
    if (m_Dialog != NULL)
    {
      m_Dialog->GetSTC()->SetText(m_Output);
      m_Dialog->SetTitle(caption.empty() ? m_Command: caption);
      m_Dialog->Show();
    }
    else if (!m_Output.empty())
    {
      wxLogMessage(m_Output);
    }
    else
    {
      wxLogStatus("No output available");
    }
  }
  else
  {
    // Executing command failed, so no output,
    // show failing command.
    wxLogError("Could not execute: " + m_Command);
  }
}
#endif
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name:      stcfile.cpp
// Purpose:   Implementation of class wxExSTCFile
// Author:    Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/stcfile.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/filename.h>
#include <wx/extension/stc.h>
#include <wx/extension/util.h> // for STAT_ etc.

#if wxUSE_GUI
wxExSTCFile::wxExSTCFile(wxExSTC* stc)
  : m_STC(stc)
  , m_PreviousLength(0)
{
}

bool wxExSTCFile::DoFileLoad(bool synced)
{
  if (GetContentsChanged())
  {
    wxExFileDialog dlg(m_STC, this);
    if (dlg.ShowModalIfChanged() == wxID_CANCEL) return false;
  }

  // Synchronizing by appending only new data only works for log files.
  // Other kind of files might get new data anywhere inside the file,
  // we cannot sync that by keeping pos.
  // Also only do it for reasonably large files.
  const bool isLog = (GetFileName().GetExt().CmpNoCase("log") == 0);

  m_STC->UseModificationMarkers(false);

  ReadFromFile(
    synced &&
    isLog &&
    m_STC->GetTextLength() > 1024);

  m_STC->UseModificationMarkers(true);

  if (!synced)
  {
    m_STC->SetLexer(GetFileName().GetLexer().GetDisplayLexer(), true);

    // No edges for log files.
    if (isLog)
    {
      m_STC->SetEdgeMode(wxSTC_EDGE_NONE);
    }

    wxLogStatus(_("Opened") + ": " + GetFileName().GetFullPath());
  }

  m_STC->PropertiesMessage(synced ? STAT_SYNC: STAT_DEFAULT);

  return true;
}

void wxExSTCFile::DoFileNew()
{
  m_STC->SetName(GetFileName().GetFullPath());
  m_STC->PropertiesMessage();
  m_STC->ClearDocument();
  m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());
}

void wxExSTCFile::DoFileSave(bool save_as)
{
  size_t size;

  if (m_STC->HexMode())
  {
    // TODO: Does this allow NULLs?
    size = Write(m_STC->m_HexBuffer, m_STC->m_HexBuffer.size());
  }
  else
  {
    const wxCharBuffer& buffer = m_STC->GetTextRaw();
    size = Write(buffer.data(), buffer.length());
  }

  if (size == 0)
  {
    wxLogStatus("could not save file");
    return;
  }

  if (save_as)
  {
    m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());
    m_STC->SetName(GetFileName().GetFullPath());
  }

  m_STC->MarkerDeleteAllChange();

  wxLogStatus(_("Saved") + ": " + GetFileName().GetFullPath());
}

bool wxExSTCFile::GetContentsChanged() const
{
  return m_STC->GetModify();
}

bool wxExSTCFile::Read(const wxString& name) const
{
  wxFileName fn(name);

  if (fn.IsRelative())
  {
    fn.Normalize(wxPATH_NORM_ALL, GetFileName().GetPath());
  }

  wxExFile file;

  if (file.Exists(fn.GetFullPath()))
  {
    if (file.Open(fn.GetFullPath()))
    {
      const int SCI_ADDTEXT = 2001;
      const wxCharBuffer& buffer = file.Read();
      m_STC->SendMsg(
        SCI_ADDTEXT, buffer.length(), (wxIntPtr)(const char *)buffer.data());

      return true;
    }
  }

  wxLogStatus(_("file: %s does not exist"), name);

  return false;
}

void wxExSTCFile::ReadFromFile(bool get_only_new_data)
{
  // Be sure we can add text.
  m_STC->SetReadOnly(false);

  const bool pos_at_end = (m_STC->GetCurrentPos() >= m_STC->GetTextLength() - 1);

  int startPos, endPos;
  m_STC->GetSelection(&startPos, &endPos);

  wxFileOffset offset = 0;

  if (m_PreviousLength < Length() && get_only_new_data)
  {
    offset = m_PreviousLength;
  }

  if (offset == 0)
  {
    m_STC->ClearDocument();
  }

  m_PreviousLength = Length();

  const wxCharBuffer& buffer = wxExFile::Read(offset);

  if (!m_STC->HexMode())
  {
    // At least for toggling between hex and non-hex this is necessary to
    // reshow the edge line.
    m_STC->ConfigGet();

    m_STC->SetControlCharSymbol(0);

    const int SCI_ADDTEXT = 2001;
    const int SCI_APPENDTEXT = 2282;
    const int message = (get_only_new_data ? SCI_APPENDTEXT: SCI_ADDTEXT);

    // README: The stc.h equivalents AddText, AddTextRaw, InsertText,
    // InsertTextRaw do not add the length.
    // So for binary files this is the only way for opening.
    m_STC->SendMsg(message, buffer.length(), (wxIntPtr)(const char *)buffer.data());
  }
  else
  {
    m_STC->AppendTextHexMode(buffer);
  }

  if (get_only_new_data)
  {
    if (pos_at_end)
    {
      m_STC->DocumentEnd();
    }
  }
  else
  {
    m_STC->GuessType();
    m_STC->DocumentStart();
  }

  if (startPos != endPos)
  {
    m_STC->SetSelection(startPos, endPos);
  }

  if (m_STC->GetFlags() & m_STC->STC_WIN_READ_ONLY ||
      GetFileName().GetStat().IsReadOnly())
  {
    m_STC->SetReadOnly(true);
  }

  m_STC->EmptyUndoBuffer();
}

void wxExSTCFile::ResetContentsChanged()
{
  m_STC->SetSavePoint();
}

#endif // wxUSE_GUI
<commit_msg>use IsFileWritable<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name:      stcfile.cpp
// Purpose:   Implementation of class wxExSTCFile
// Author:    Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/stcfile.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/filename.h>
#include <wx/extension/stc.h>
#include <wx/extension/util.h> // for STAT_ etc.

#if wxUSE_GUI
wxExSTCFile::wxExSTCFile(wxExSTC* stc)
  : m_STC(stc)
  , m_PreviousLength(0)
{
}

bool wxExSTCFile::DoFileLoad(bool synced)
{
  if (GetContentsChanged())
  {
    wxExFileDialog dlg(m_STC, this);
    if (dlg.ShowModalIfChanged() == wxID_CANCEL) return false;
  }

  // Synchronizing by appending only new data only works for log files.
  // Other kind of files might get new data anywhere inside the file,
  // we cannot sync that by keeping pos.
  // Also only do it for reasonably large files.
  const bool isLog = (GetFileName().GetExt().CmpNoCase("log") == 0);

  m_STC->UseModificationMarkers(false);

  ReadFromFile(
    synced &&
    isLog &&
    m_STC->GetTextLength() > 1024);

  m_STC->UseModificationMarkers(true);

  if (!synced)
  {
    m_STC->SetLexer(GetFileName().GetLexer().GetDisplayLexer(), true);

    // No edges for log files.
    if (isLog)
    {
      m_STC->SetEdgeMode(wxSTC_EDGE_NONE);
    }

    wxLogStatus(_("Opened") + ": " + GetFileName().GetFullPath());
  }

  m_STC->PropertiesMessage(synced ? STAT_SYNC: STAT_DEFAULT);

  return true;
}

void wxExSTCFile::DoFileNew()
{
  m_STC->SetName(GetFileName().GetFullPath());
  m_STC->PropertiesMessage();
  m_STC->ClearDocument();
  m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());
}

void wxExSTCFile::DoFileSave(bool save_as)
{
  size_t size;

  if (m_STC->HexMode())
  {
    // TODO: Does this allow NULLs?
    size = Write(m_STC->m_HexBuffer, m_STC->m_HexBuffer.size());
  }
  else
  {
    const wxCharBuffer& buffer = m_STC->GetTextRaw();
    size = Write(buffer.data(), buffer.length());
  }

  if (size == 0)
  {
    wxLogStatus("could not save file");
    return;
  }

  if (save_as)
  {
    m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());
    m_STC->SetName(GetFileName().GetFullPath());
  }

  m_STC->MarkerDeleteAllChange();

  wxLogStatus(_("Saved") + ": " + GetFileName().GetFullPath());
}

bool wxExSTCFile::GetContentsChanged() const
{
  return m_STC->GetModify();
}

bool wxExSTCFile::Read(const wxString& name) const
{
  wxFileName fn(name);

  if (fn.IsRelative())
  {
    fn.Normalize(wxPATH_NORM_ALL, GetFileName().GetPath());
  }

  wxExFile file;

  if (file.Exists(fn.GetFullPath()))
  {
    if (file.Open(fn.GetFullPath()))
    {
      const int SCI_ADDTEXT = 2001;
      const wxCharBuffer& buffer = file.Read();
      m_STC->SendMsg(
        SCI_ADDTEXT, buffer.length(), (wxIntPtr)(const char *)buffer.data());

      return true;
    }
  }

  wxLogStatus(_("file: %s does not exist"), name);

  return false;
}

void wxExSTCFile::ReadFromFile(bool get_only_new_data)
{
  // Be sure we can add text.
  m_STC->SetReadOnly(false);

  const bool pos_at_end = (m_STC->GetCurrentPos() >= m_STC->GetTextLength() - 1);

  int startPos, endPos;
  m_STC->GetSelection(&startPos, &endPos);

  wxFileOffset offset = 0;

  if (m_PreviousLength < Length() && get_only_new_data)
  {
    offset = m_PreviousLength;
  }

  if (offset == 0)
  {
    m_STC->ClearDocument();
  }

  m_PreviousLength = Length();

  const wxCharBuffer& buffer = wxExFile::Read(offset);

  if (!m_STC->HexMode())
  {
    // At least for toggling between hex and non-hex this is necessary to
    // reshow the edge line.
    m_STC->ConfigGet();

    m_STC->SetControlCharSymbol(0);

    const int SCI_ADDTEXT = 2001;
    const int SCI_APPENDTEXT = 2282;
    const int message = (get_only_new_data ? SCI_APPENDTEXT: SCI_ADDTEXT);

    // README: The stc.h equivalents AddText, AddTextRaw, InsertText,
    // InsertTextRaw do not add the length.
    // So for binary files this is the only way for opening.
    m_STC->SendMsg(message, buffer.length(), (wxIntPtr)(const char *)buffer.data());
  }
  else
  {
    m_STC->AppendTextHexMode(buffer);
  }

  if (get_only_new_data)
  {
    if (pos_at_end)
    {
      m_STC->DocumentEnd();
    }
  }
  else
  {
    m_STC->GuessType();
    m_STC->DocumentStart();
  }

  if (startPos != endPos)
  {
    m_STC->SetSelection(startPos, endPos);
  }

  if (( m_STC->GetFlags() & m_STC->STC_WIN_READ_ONLY) ||
       !GetFileName().IsFileWritable())
  {
    m_STC->SetReadOnly(true);
  }

  m_STC->EmptyUndoBuffer();
}

void wxExSTCFile::ResetContentsChanged()
{
  m_STC->SetSavePoint();
}

#endif // wxUSE_GUI
<|endoftext|>


<commit_before>#include "common/common.h"
#include "common/random_utils.h"
#include "common/cmd_options.h"

#include "common/graph/dot_graph.h"
#include "common/graph/dot_parser.h"

#include "clustering.h"
#include "metrics.h"

#include <memory>

void PrepareCMDOptions(int argc, char** argv, CMDOptions& args)
{
	string msg;
	msg += "Usage: kmeans [options] input_file\n";
	msg += "When input_file is not supplied, the program reads from stdin.\n";
	args.SetUsageMessage(msg);

	args.AddAllowedOption("", "", "Input file name (stdin, if no input file is supplied)");
	args.AddAllowedOption("-o", "", "Output file name (stdout, if no output file is supplied)");

	args.AddAllowedOption("-action", "The program either computes a clustering for a given graph or calculates a set of quality measures (aesthetics)");
	args.AddAllowedValue("-action", "clustering");
	args.AddAllowedValue("-action", "metrics");

	args.AddAllowedOption("-C", "Type of clustering");
	args.AddAllowedValue("-C", "geometrickmeans");
	args.AddAllowedValue("-C", "graphkmeans");
	args.AddAllowedValue("-C", "geometrichierarchical");
	args.AddAllowedValue("-C", "graphhierarchical");
	args.AddAllowedValue("-C", "infomap");
	args.AddAllowedValue("-C", "modularity");
	args.AddAllowedValue("-C", "modularity-cont");

	args.AddAllowedOption("-K", "", "Desired number of clusters (selected automatically, if no value is supplied)");

	args.Parse(argc, argv);
}

void MetricsAction(const CMDOptions& options)
{
	DotReader parser;
	DotGraph g = parser.ReadGraph(options.getOption(""));

	Metrics m;
	m.Compute(g);
	m.Output(options.getOption("-o"));
}

void ClusteringAction(const CMDOptions& options)
{
	DotReader parser;
	DotGraph g = parser.ReadGraph(options.getOption(""));

	string algoName = options.getOption("-C");
	ClusterAlgorithm* algo = NULL;

	if (algoName == "geometrickmeans")
		algo = new GeometricKMeans();
	else if (algoName == "graphkmeans")
		algo = new GraphKMeans();
	else if (algoName == "geometrichierarchical")
		algo = new GeometricHierarchical();
	else if (algoName == "graphhierarchical")
		algo = new GraphHierarchical();
	else if (algoName == "infomap")
		algo = new InfoMap();
	else if (algoName == "modularity")
		algo = new Modularity(false);
	else if (algoName == "modularity-cont")
		algo = new Modularity(true);

	string numberOfClusters = options.getOption("-K");
	if (numberOfClusters == "graph")
	{
		int k = g.ClusterCount();
		algo->cluster(g, k);
	}
	else if (numberOfClusters == "")
	{
		algo->cluster(g);
	}
	else
	{
		int k = toInt(numberOfClusters);
		algo->cluster(g, k);
	}

	delete algo;

	DotWriter writer;
	writer.WriteGraph(options.getOption("-o"), g);
}

int main(int argc, char **argv)
{
	InitRand(123);

	auto options = CMDOptions::Create();

	int returnCode = 0;
	try
	{
		PrepareCMDOptions(argc, argv, *options);
		string action = options->getOption("-action");
		if (action == "clustering")
		{
			ClusteringAction(*options);
		}
		else if (action == "metrics")
		{
			MetricsAction(*options);
		}
	}
	catch (int code)
	{
		returnCode = code;
	}

	return returnCode;
}
<commit_msg>compute cluster-based and not embedding-based metrics<commit_after>#include "common/common.h"
#include "common/random_utils.h"
#include "common/cmd_options.h"

#include "common/graph/dot_graph.h"
#include "common/graph/dot_parser.h"

#include "clustering.h"
#include "metrics.h"

#include <memory>

void PrepareCMDOptions(int argc, char** argv, CMDOptions& args)
{
	string msg;
	msg += "Usage: kmeans [options] input_file\n";
	msg += "When input_file is not supplied, the program reads from stdin.\n";
	args.SetUsageMessage(msg);

	args.AddAllowedOption("", "", "Input file name (stdin, if no input file is supplied)");
	args.AddAllowedOption("-o", "", "Output file name (stdout, if no output file is supplied)");

	args.AddAllowedOption("-action", "The program either computes a clustering for a given graph or calculates a set of quality measures (aesthetics)");
	args.AddAllowedValue("-action", "clustering");
	args.AddAllowedValue("-action", "metrics");

	args.AddAllowedOption("-C", "Type of clustering");
	args.AddAllowedValue("-C", "geometrickmeans");
	args.AddAllowedValue("-C", "graphkmeans");
	args.AddAllowedValue("-C", "geometrichierarchical");
	args.AddAllowedValue("-C", "graphhierarchical");
	args.AddAllowedValue("-C", "infomap");
	args.AddAllowedValue("-C", "modularity");
	args.AddAllowedValue("-C", "modularity-cont");

	args.AddAllowedOption("-K", "", "Desired number of clusters (selected automatically, if no value is supplied)");

	args.Parse(argc, argv);
}

void MetricsAction(const CMDOptions& options)
{
	DotReader parser;
	DotGraph g = parser.ReadGraph(options.getOption(""));

	Metrics m;
	m.ComputeCluster(g);
	m.Output(options.getOption("-o"));
}

void ClusteringAction(const CMDOptions& options)
{
	DotReader parser;
	DotGraph g = parser.ReadGraph(options.getOption(""));

	string algoName = options.getOption("-C");
	ClusterAlgorithm* algo = NULL;

	if (algoName == "geometrickmeans")
		algo = new GeometricKMeans();
	else if (algoName == "graphkmeans")
		algo = new GraphKMeans();
	else if (algoName == "geometrichierarchical")
		algo = new GeometricHierarchical();
	else if (algoName == "graphhierarchical")
		algo = new GraphHierarchical();
	else if (algoName == "infomap")
		algo = new InfoMap();
	else if (algoName == "modularity")
		algo = new Modularity(false);
	else if (algoName == "modularity-cont")
		algo = new Modularity(true);

	string numberOfClusters = options.getOption("-K");
	if (numberOfClusters == "graph")
	{
		int k = g.ClusterCount();
		algo->cluster(g, k);
	}
	else if (numberOfClusters == "")
	{
		algo->cluster(g);
	}
	else
	{
		int k = toInt(numberOfClusters);
		algo->cluster(g, k);
	}

	delete algo;

	DotWriter writer;
	writer.WriteGraph(options.getOption("-o"), g);
}

int main(int argc, char **argv)
{
	InitRand(123);

	auto options = CMDOptions::Create();

	int returnCode = 0;
	try
	{
		PrepareCMDOptions(argc, argv, *options);
		string action = options->getOption("-action");
		if (action == "clustering")
		{
			ClusteringAction(*options);
		}
		else if (action == "metrics")
		{
			MetricsAction(*options);
		}
	}
	catch (int code)
	{
		returnCode = code;
	}

	return returnCode;
}
<|endoftext|>


<commit_before>/*
 * VehicleControlDeviceImplementation.cpp
 *
 *  Created on: 10/04/2010
 *      Author: victor
 */

#include "VehicleControlDevice.h"
#include "VehicleControlObserver.h"
#include "server/zone/managers/objectcontroller/ObjectController.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/creature/VehicleObject.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/Zone.h"
#include "tasks/CallMountTask.h"
#include "server/zone/objects/region/CityRegion.h"
#include "server/zone/objects/player/sessions/TradeSession.h"

void VehicleControlDeviceImplementation::generateObject(CreatureObject* player) {
	if (player->getParent() != NULL)
		return;

	if (!isASubChildOf(player))
		return;

	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL)
		return;

	if (controlledObject->isInQuadTree())
		return;

	if (player->isInCombat() || player->isDead() || player->isIncapacitated())
		return;

	ManagedReference<TradeSession*> tradeContainer = dynamic_cast<TradeSession*>(player->getActiveSession(SessionFacadeType::TRADE));

	if (tradeContainer != NULL) {
		return;
	}

	if(player->getPendingTask("call_mount") != NULL) {
		StringIdChatParameter waitTime("pet/pet_menu", "call_delay_finish_vehicle");
		Time nextExecution;
		Core::getTaskManager()->getNextExecutionTime(player->getPendingTask("call_mount"), nextExecution);
		int timeLeft = (nextExecution.getMiliTime() / 1000) - System::getTime();
		waitTime.setDI(timeLeft);

		player->sendSystemMessage(waitTime);
		return;
	}

	ManagedReference<SceneObject*> datapad = player->getSlottedObject("datapad");

	if (datapad == NULL)
		return;

	int currentlySpawned = 0;

	for (int i = 0; i < datapad->getContainerObjectsSize(); ++i) {
		ManagedReference<SceneObject*> object = datapad->getContainerObject(i);

		if (object->isControlDevice()) {
			ControlDevice* device = cast<ControlDevice*>( object.get());

			ManagedReference<SceneObject*> vehicle = device->getControlledObject();

			if (vehicle != NULL && vehicle->isInQuadTree()) {
				if (++currentlySpawned > 2)
					player->sendSystemMessage("@pet/pet_menu:has_max_vehicle");

				return;
			}
		}
	}

	if(player->getCurrentCamp() == NULL && player->getCityRegion() == NULL) {

		Reference<CallMountTask*> callMount = new CallMountTask(_this.get(), player, "call_mount");

		StringIdChatParameter message("pet/pet_menu", "call_vehicle_delay");
		message.setDI(15);
		player->sendSystemMessage(message);

		player->addPendingTask("call_mount", callMount, 15 * 1000);

		if (vehicleControlObserver == NULL) {
			vehicleControlObserver = new VehicleControlObserver(_this.get());
			vehicleControlObserver->deploy();
		}

		player->registerObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);

	} else {

		Locker clocker(controlledObject, player);
		spawnObject(player);
	}

}

void VehicleControlDeviceImplementation::spawnObject(CreatureObject* player) {
	ZoneServer* zoneServer = getZoneServer();

	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL)
		return;

	if (!isASubChildOf(player))
		return;

	ManagedReference<TradeSession*> tradeContainer = dynamic_cast<TradeSession*>(player->getActiveSession(SessionFacadeType::TRADE));

	if (tradeContainer != NULL) {
		return;
	}

	controlledObject->initializePosition(player->getPositionX(), player->getPositionZ(), player->getPositionY());
	ManagedReference<CreatureObject*> vehicle = NULL;

	if (controlledObject->isCreatureObject())
	{

		vehicle = cast<CreatureObject*>(controlledObject.get());
		vehicle->setCreatureLink(player);
		vehicle->setControlDevice(_this.get());

	}

	Zone* zone = player->getZone();

	if (zone == NULL)
		return;

	//controlledObject->insertToZone(player->getZone());
	zone->transferObject(controlledObject, -1, true);
	controlledObject->inflictDamage(player, 0, System::random(50), true);

	if (vehicle != NULL && controlledObject->getServerObjectCRC() == 0x32F87A54) // Jetpack
	{

		controlledObject->setCustomizationVariable("/private/index_hover_height", 40, true); // Illusion of flying.
		player->executeObjectControllerAction(String("mount").hashCode(), controlledObject->getObjectID(), ""); // Auto mount.

	}

	updateStatus(1);

	if (vehicleControlObserver != NULL)
		player->dropObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);
}

void VehicleControlDeviceImplementation::cancelSpawnObject(CreatureObject* player) {

	if(player->getPendingTask("call_mount")) {
		player->getPendingTask("call_mount")->cancel();
		player->removePendingTask("call_mount");
	}

	if (vehicleControlObserver != NULL)
		player->dropObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);
}

void VehicleControlDeviceImplementation::storeObject(CreatureObject* player) {
	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL)
		return;

	/*if (!controlledObject->isInQuadTree())
		return;*/

	if (player->isRidingMount() && player->getParent() == controlledObject) {

		if (!player->checkCooldownRecovery("mount_dismount"))
			return;

		player->executeObjectControllerAction(String("dismount").hashCode());

		if (player->isRidingMount())
			return;
	}

	controlledObject->destroyObjectFromWorld(true);

	if (controlledObject->isCreatureObject())
		(cast<CreatureObject*>(controlledObject.get()))->setCreatureLink(NULL);

	updateStatus(0);
}

void VehicleControlDeviceImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {
	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject != NULL) {
		Locker locker(controlledObject);

		//ManagedReference<CreatureObject*> object = controlledObject.castTo<CreatureObject*>()->getLinkedCreature();
		ManagedReference<CreatureObject*> object = cast<CreatureObject*>(controlledObject->getSlottedObject("rider"));

		if (object != NULL) {
			Locker clocker(object, controlledObject);

			object->executeObjectControllerAction(String("dismount").hashCode());

			object = cast<CreatureObject*>(controlledObject->getSlottedObject("rider"));

			if (object != NULL) {
				controlledObject->removeObject(object, NULL, true);

				Zone* zone = getZone();

				if (zone != NULL)
					zone->transferObject(object, -1, false);
			}
		}

		controlledObject->destroyObjectFromDatabase(true);
	}

	IntangibleObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);
}

int VehicleControlDeviceImplementation::canBeDestroyed(CreatureObject* player) {
	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject != NULL) {
		if (controlledObject->isInQuadTree())
			return 1;
	}

	return IntangibleObjectImplementation::canBeDestroyed(player);
}
<commit_msg>[fixed] trade bug<commit_after>/*
 * VehicleControlDeviceImplementation.cpp
 *
 *  Created on: 10/04/2010
 *      Author: victor
 */

#include "VehicleControlDevice.h"
#include "VehicleControlObserver.h"
#include "server/zone/managers/objectcontroller/ObjectController.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/creature/VehicleObject.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/Zone.h"
#include "tasks/CallMountTask.h"
#include "server/zone/objects/region/CityRegion.h"
#include "server/zone/objects/player/sessions/TradeSession.h"
#include "server/zone/managers/player/PlayerManager.h"

void VehicleControlDeviceImplementation::generateObject(CreatureObject* player) {
	if (player->getParent() != NULL)
		return;

	if (!isASubChildOf(player))
		return;

	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL)
		return;

	if (controlledObject->isInQuadTree())
		return;

	if (player->isInCombat() || player->isDead() || player->isIncapacitated())
		return;

	ManagedReference<TradeSession*> tradeContainer = dynamic_cast<TradeSession*>(player->getActiveSession(SessionFacadeType::TRADE));

	if (tradeContainer != NULL) {
		server->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(player);
	}

	if(player->getPendingTask("call_mount") != NULL) {
		StringIdChatParameter waitTime("pet/pet_menu", "call_delay_finish_vehicle");
		Time nextExecution;
		Core::getTaskManager()->getNextExecutionTime(player->getPendingTask("call_mount"), nextExecution);
		int timeLeft = (nextExecution.getMiliTime() / 1000) - System::getTime();
		waitTime.setDI(timeLeft);

		player->sendSystemMessage(waitTime);
		return;
	}

	ManagedReference<SceneObject*> datapad = player->getSlottedObject("datapad");

	if (datapad == NULL)
		return;

	int currentlySpawned = 0;

	for (int i = 0; i < datapad->getContainerObjectsSize(); ++i) {
		ManagedReference<SceneObject*> object = datapad->getContainerObject(i);

		if (object->isControlDevice()) {
			ControlDevice* device = cast<ControlDevice*>( object.get());

			ManagedReference<SceneObject*> vehicle = device->getControlledObject();

			if (vehicle != NULL && vehicle->isInQuadTree()) {
				if (++currentlySpawned > 2)
					player->sendSystemMessage("@pet/pet_menu:has_max_vehicle");

				return;
			}
		}
	}

	if(player->getCurrentCamp() == NULL && player->getCityRegion() == NULL) {

		Reference<CallMountTask*> callMount = new CallMountTask(_this.get(), player, "call_mount");

		StringIdChatParameter message("pet/pet_menu", "call_vehicle_delay");
		message.setDI(15);
		player->sendSystemMessage(message);

		player->addPendingTask("call_mount", callMount, 15 * 1000);

		if (vehicleControlObserver == NULL) {
			vehicleControlObserver = new VehicleControlObserver(_this.get());
			vehicleControlObserver->deploy();
		}

		player->registerObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);

	} else {

		Locker clocker(controlledObject, player);
		spawnObject(player);
	}

}

void VehicleControlDeviceImplementation::spawnObject(CreatureObject* player) {
	ZoneServer* zoneServer = getZoneServer();

	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL)
		return;

	if (!isASubChildOf(player))
		return;

	ManagedReference<TradeSession*> tradeContainer = dynamic_cast<TradeSession*>(player->getActiveSession(SessionFacadeType::TRADE));

	if (tradeContainer != NULL) {
		server->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(player);
	}

	controlledObject->initializePosition(player->getPositionX(), player->getPositionZ(), player->getPositionY());
	ManagedReference<CreatureObject*> vehicle = NULL;

	if (controlledObject->isCreatureObject())
	{

		vehicle = cast<CreatureObject*>(controlledObject.get());
		vehicle->setCreatureLink(player);
		vehicle->setControlDevice(_this.get());

	}

	Zone* zone = player->getZone();

	if (zone == NULL)
		return;

	//controlledObject->insertToZone(player->getZone());
	zone->transferObject(controlledObject, -1, true);
	controlledObject->inflictDamage(player, 0, System::random(50), true);

	if (vehicle != NULL && controlledObject->getServerObjectCRC() == 0x32F87A54) // Jetpack
	{

		controlledObject->setCustomizationVariable("/private/index_hover_height", 40, true); // Illusion of flying.
		player->executeObjectControllerAction(String("mount").hashCode(), controlledObject->getObjectID(), ""); // Auto mount.

	}

	updateStatus(1);

	if (vehicleControlObserver != NULL)
		player->dropObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);
}

void VehicleControlDeviceImplementation::cancelSpawnObject(CreatureObject* player) {

	if(player->getPendingTask("call_mount")) {
		player->getPendingTask("call_mount")->cancel();
		player->removePendingTask("call_mount");
	}

	if (vehicleControlObserver != NULL)
		player->dropObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);
}

void VehicleControlDeviceImplementation::storeObject(CreatureObject* player) {
	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL)
		return;

	/*if (!controlledObject->isInQuadTree())
		return;*/

	if (player->isRidingMount() && player->getParent() == controlledObject) {

		if (!player->checkCooldownRecovery("mount_dismount"))
			return;

		player->executeObjectControllerAction(String("dismount").hashCode());

		if (player->isRidingMount())
			return;
	}

	controlledObject->destroyObjectFromWorld(true);

	if (controlledObject->isCreatureObject())
		(cast<CreatureObject*>(controlledObject.get()))->setCreatureLink(NULL);

	updateStatus(0);
}

void VehicleControlDeviceImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {
	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject != NULL) {
		Locker locker(controlledObject);

		//ManagedReference<CreatureObject*> object = controlledObject.castTo<CreatureObject*>()->getLinkedCreature();
		ManagedReference<CreatureObject*> object = cast<CreatureObject*>(controlledObject->getSlottedObject("rider"));

		if (object != NULL) {
			Locker clocker(object, controlledObject);

			object->executeObjectControllerAction(String("dismount").hashCode());

			object = cast<CreatureObject*>(controlledObject->getSlottedObject("rider"));

			if (object != NULL) {
				controlledObject->removeObject(object, NULL, true);

				Zone* zone = getZone();

				if (zone != NULL)
					zone->transferObject(object, -1, false);
			}
		}

		controlledObject->destroyObjectFromDatabase(true);
	}

	IntangibleObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);
}

int VehicleControlDeviceImplementation::canBeDestroyed(CreatureObject* player) {
	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject != NULL) {
		if (controlledObject->isInQuadTree())
			return 1;
	}

	return IntangibleObjectImplementation::canBeDestroyed(player);
}
<|endoftext|>


<commit_before><commit_msg>adds tcl binding for packet header<commit_after>int protoname_pkt::offset_;

static class ProtonameHeaderClass : public PacketHeaderClass {
	public:
	ProtonameHeaderClass() : PacketHeaderClass("PacketHeader/Adian",
	sizeof(hdr_protoname_pkt)) {
		bind_offset(&hdr_protoname_pkt::offset_);
	}
} class_rtProtoProtoname_hdr;<|endoftext|>