<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "clustering/administration/stats/stat_manager.hpp"

#include <functional>

#include "concurrency/watchable.hpp"
#include "perfmon/collect.hpp"
#include "perfmon/filter.hpp"
#include "stl_utils.hpp"

stat_manager_t::stat_manager_t(mailbox_manager_t* mm) :
    mailbox_manager(mm),
    get_stats_mailbox(mailbox_manager,
                      std::bind(&stat_manager_t::on_stats_request,
                                this, ph::_1, ph::_2, ph::_3))
    { }

get_stats_mailbox_address_t stat_manager_t::get_address() {
    return get_stats_mailbox.get_address();
}

void stat_manager_t::on_stats_request(
        UNUSED signal_t *interruptor,
        const return_address_t& reply_address,
        const std::set<std::vector<stat_id_t> >& requested_stats) {
    perfmon_filter_t request(requested_stats);
    ql::datum_t perfmon_result(perfmon_get_stats());
    perfmon_result = request.filter(perfmon_result);
    send(mailbox_manager, reply_address, perfmon_result);
}

bool fetch_stats_from_server(
        mailbox_manager_t *mailbox_manager,
        const get_stats_mailbox_address_t &request_addr,
        const std::set<std::vector<stat_manager_t::stat_id_t> > &filter,
        signal_t *interruptor,
        ql::datum_t *stats_out,
        std::string *error_out) {
    cond_t done;
    mailbox_t<void(ql::datum_t)> return_mailbox(mailbox_manager,
        [&](signal_t *, ql::datum_t s) {
            *stats_out = s;
            done.pulse();
        });

    disconnect_watcher_t disconnect_watcher(mailbox_manager, request_addr.get_peer());

    send(mailbox_manager, request_addr, return_mailbox.get_address(), filter);

    signal_timer_t timeout;
    timeout.start(5000);

    wait_any_t waiter(&done, &disconnect_watcher, &timeout);
    wait_interruptible(&waiter, interruptor);

    if (disconnect_watcher.is_pulsed()) {
        *error_out = "Server disconnected.";
        return false;
    }

    if (timeout.is_pulsed()) {
        *error_out = "Stats request timed out.";
    }

    guarantee(done.is_pulsed());
    return true;
}

<commit_msg>fixing crash when a stats request times out<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "clustering/administration/stats/stat_manager.hpp"

#include <functional>

#include "concurrency/watchable.hpp"
#include "perfmon/collect.hpp"
#include "perfmon/filter.hpp"
#include "stl_utils.hpp"

stat_manager_t::stat_manager_t(mailbox_manager_t* mm) :
    mailbox_manager(mm),
    get_stats_mailbox(mailbox_manager,
                      std::bind(&stat_manager_t::on_stats_request,
                                this, ph::_1, ph::_2, ph::_3))
    { }

get_stats_mailbox_address_t stat_manager_t::get_address() {
    return get_stats_mailbox.get_address();
}

void stat_manager_t::on_stats_request(
        UNUSED signal_t *interruptor,
        const return_address_t& reply_address,
        const std::set<std::vector<stat_id_t> >& requested_stats) {
    perfmon_filter_t request(requested_stats);
    ql::datum_t perfmon_result(perfmon_get_stats());
    perfmon_result = request.filter(perfmon_result);
    send(mailbox_manager, reply_address, perfmon_result);
}

bool fetch_stats_from_server(
        mailbox_manager_t *mailbox_manager,
        const get_stats_mailbox_address_t &request_addr,
        const std::set<std::vector<stat_manager_t::stat_id_t> > &filter,
        signal_t *interruptor,
        ql::datum_t *stats_out,
        std::string *error_out) {
    cond_t done;
    mailbox_t<void(ql::datum_t)> return_mailbox(mailbox_manager,
        [&](signal_t *, ql::datum_t s) {
            *stats_out = s;
            done.pulse();
        });

    disconnect_watcher_t disconnect_watcher(mailbox_manager, request_addr.get_peer());

    send(mailbox_manager, request_addr, return_mailbox.get_address(), filter);

    signal_timer_t timeout;
    timeout.start(5000);

    wait_any_t waiter(&done, &disconnect_watcher, &timeout);
    wait_interruptible(&waiter, interruptor);

    if (disconnect_watcher.is_pulsed()) {
        *error_out = "Server disconnected.";
        return false;
    }

    if (timeout.is_pulsed()) {
        *error_out = "Stats request timed out.";
        return false;
    }

    guarantee(done.is_pulsed());
    return true;
}

<|endoftext|>


<commit_before>#include <cstdio>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <io/binary/StreamPutter.hpp>
#include <io/binary/StreamGetter.hpp>

#include <io/FileDescriptor.hpp>
#include <test.h>

using namespace io;
using namespace std;

#define TEST_SHORT 0xdead
#define TEST_INT   32
#define TEST_LONG  0xdeadbeefdeadbeefll
#define TEST_STRING "Hello, World!\n"

int test_fd() {
	int rc;

	int fd = ::open("testfifo", O_WRONLY | O_CREAT, 0600);
	TEST_BOOL( "Open", fd > 0 );

	FileDescriptor file(fd);
	rc = file.write((const byte*)"hello\n", 6);

	TEST_EQ_INT( "FileDescriptor", rc, 6 );
	return 0;
}

int write_file() {
	int fd = ::open("/tmp/mytestfile", O_WRONLY | O_CREAT, 0600);
	TEST_BOOL("Open", fd > 0);

	FileDescriptor file( fd );
	StreamPutter p( &file );

	int rc;

	rc = p.putInt16be( TEST_SHORT ) ||
	     p.putInt32be( TEST_INT   ) ||
	     p.putInt64be( TEST_LONG  )  ;

	TEST_EQ_INT("putIntegers", rc, 0);

	std::string str(TEST_STRING);
	rc = putObject(p, str);
	TEST_EQ_INT("putString", rc, 0);

	return 0;
}

int read_file() {
	int fd = ::open("/tmp/mytestfile", O_RDONLY, 0600);
	TEST_BOOL("Open", fd > 0);

	FileDescriptor file(fd);
	StreamGetter g( &file );

	uint16_t test16;
	uint32_t test32;
	uint64_t test64;

	int rc = g.getInt16be( test16 ) ||
			 g.getInt32be( test32 ) ||
			 g.getInt64be( test64 ) ;

	TEST_EQ( "getIntegers", rc, 0 );
	TEST_EQ( "getInt32be_value", test16, TEST_SHORT );
	TEST_EQ( "getInt32be_value", test32, TEST_INT );
	TEST_EQ( "getInt64be_value", test64, TEST_LONG );

	std::string str;
	rc = getObject(g, str);

	TEST_EQ  ( "getString", rc, 0 );
	TEST_BOOL( "getString_value", strcmp(str.c_str(), TEST_STRING) == 0 );

	return 0;
}

int main( int argc, char** argv ) {
	TEST_FN( test_fd() );
	TEST_FN( write_file() );
	TEST_FN( read_file() );

	return 0;
}
<commit_msg>updated tests to clean up<commit_after>#include <cstdio>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <io/binary/StreamPutter.hpp>
#include <io/binary/StreamGetter.hpp>

#include <io/FileDescriptor.hpp>
#include <test.h>

using namespace io;
using namespace std;

#define TEST_SHORT 0xdead
#define TEST_INT   32
#define TEST_LONG  0xdeadbeefdeadbeefll
#define TEST_STRING "Hello, World!\n"

int test_fd() {
	int rc;

	int fd = ::open("testfifo", O_WRONLY | O_CREAT, 0600);
	TEST_BOOL( "Open", fd > 0 );

	FileDescriptor file(fd);
	rc = file.write((const byte*)"hello\n", 6);

	TEST_EQ_INT( "FileDescriptor", rc, 6 );
	return 0;
}

int write_file() {
    char fpath[1024];
    char cwd[1024];
    static const char* testfile = "read_file_test";
    snprintf(fpath, 1024, "%s/%s", getcwd(cwd, 1024), testfile);

	int fd = ::open(fpath, O_WRONLY | O_CREAT, 0600);
	TEST_BOOL("Open", fd > 0);

	FileDescriptor file( fd );
	StreamPutter p( &file );

	int rc;

	rc = p.putInt16be( TEST_SHORT ) ||
	     p.putInt32be( TEST_INT   ) ||
	     p.putInt64be( TEST_LONG  )  ;

	TEST_EQ_INT("putIntegers", rc, 0);

	std::string str(TEST_STRING);
	rc = putObject(p, str);
	TEST_EQ_INT("putString", rc, 0);

	return 0;
}

int read_file() {
    char fpath[1024];
    char cwd[1024];
    static const char* testfile = "read_file_test";
    snprintf(fpath, 1024, "%s/%s", getcwd(cwd, 1024), testfile);

	int fd = ::open(fpath, O_RDONLY, 0600);
	TEST_BOOL("Open", fd > 0);

	FileDescriptor file(fd);
	StreamGetter g( &file );

	uint16_t test16;
	uint32_t test32;
	uint64_t test64;

	int rc = g.getInt16be( test16 ) ||
			 g.getInt32be( test32 ) ||
			 g.getInt64be( test64 ) ;

	TEST_EQ( "getIntegers", rc, 0 );
	TEST_EQ( "getInt32be_value", test16, TEST_SHORT );
	TEST_EQ( "getInt32be_value", test32, TEST_INT );
	TEST_EQ( "getInt64be_value", test64, TEST_LONG );

	std::string str;
	rc = getObject(g, str);

	TEST_EQ  ( "getString", rc, 0 );
	TEST_BOOL( "getString_value", strcmp(str.c_str(), TEST_STRING) == 0 );

    unlink(fpath);
	return 0;
}

int main( int argc, char** argv ) {
	TEST_FN( test_fd() );
	TEST_FN( write_file() );
	TEST_FN( read_file() );

	return 0;
}
<|endoftext|>


<commit_before>#include "chainerx/cuda/memory_pool.h"

#include <memory>

#include <gtest/gtest.h>

#include "chainerx/error.h"

namespace chainerx {
namespace cuda {
namespace cuda_internal {

class MemoryPoolTest {
public:
    static const std::vector<std::vector<void*>>& GetFreeBins(const MemoryPool& pool) { return pool.free_bins_; }
    static const Allocator* GetAllocator(const MemoryPool& pool) { return pool.allocator_.get(); }
};

}  // namespace cuda_internal

namespace {

// A dummy allocator to test OutOfMemoryError
class FixedCapacityDummyAllocator : public Allocator {
public:
    explicit FixedCapacityDummyAllocator(size_t capacity) : capacity_{capacity} {}

    MallocStatus Malloc(void** ptr, size_t bytesize) override {
        CHAINERX_ASSERT(bytesize > 0);
        ++malloc_called_;
        if (capacity_ < bytesize) {
            return MallocStatus::kErrorMemoryAllocation;
        }
        // bytesize is encoded in the dummy pointer.
        intptr_t i = static_cast<intptr_t>(bytesize);
        *ptr = reinterpret_cast<void*>(i);  // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
        capacity_ -= bytesize;
        return MallocStatus::kSuccess;
    }
    void Free(void* ptr) noexcept override {
        intptr_t i = reinterpret_cast<intptr_t>(ptr);  // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
        capacity_ += static_cast<size_t>(i);
    }

    int malloc_called() const { return malloc_called_; }

private:
    size_t capacity_;
    int malloc_called_{0};
};

class MemoryPoolTestForEachAllocator : public ::testing::TestWithParam<std::shared_ptr<MemoryPool>> {};

TEST_P(MemoryPoolTestForEachAllocator, MallocAndFree) {
    MemoryPool& memory_pool = *GetParam();

    void* ptr1 = memory_pool.Malloc(1);
    void* ptr2 = memory_pool.Malloc(1);
    EXPECT_NE(ptr1, ptr2);

    memory_pool.Free(ptr2);

    void* ptr3 = memory_pool.Malloc(1);
    EXPECT_EQ(ptr2, ptr3);
    memory_pool.Free(ptr3);

    memory_pool.Free(ptr1);
}

TEST_P(MemoryPoolTestForEachAllocator, MallocAllocationUnitSize) {
    MemoryPool& memory_pool = *GetParam();

    void* ptr1 = memory_pool.Malloc(100);
    memory_pool.Free(ptr1);

    void* ptr2 = memory_pool.Malloc(100 + kAllocationUnitSize);
    EXPECT_NE(ptr1, ptr2);

    memory_pool.Free(ptr2);
}

TEST_P(MemoryPoolTestForEachAllocator, MallocZeroByte) {
    MemoryPool& memory_pool = *GetParam();
    void* ptr = memory_pool.Malloc(0);
    EXPECT_EQ(nullptr, ptr);
    memory_pool.Free(ptr);  // no throw
}

TEST_P(MemoryPoolTestForEachAllocator, FreeTwice) {
    MemoryPool& memory_pool = *GetParam();
    void* ptr = memory_pool.Malloc(1);
    memory_pool.Free(ptr);
    EXPECT_THROW(memory_pool.Free(ptr), ChainerxError);
}

TEST_P(MemoryPoolTestForEachAllocator, FreeForeignPointer) {
    MemoryPool& memory_pool = *GetParam();
    void* ptr = &memory_pool;
    EXPECT_THROW(memory_pool.Free(ptr), ChainerxError);
}

TEST_P(MemoryPoolTestForEachAllocator, FreeUnusedBlocks) {
    MemoryPool& memory_pool = *GetParam();
    const std::vector<std::vector<void*>>& free_bins = cuda_internal::MemoryPoolTest::GetFreeBins(memory_pool);

    void* ptr1 = memory_pool.Malloc(1);
    memory_pool.Free(ptr1);
    EXPECT_FALSE(free_bins.empty());

    memory_pool.FreeUnusedBlocks();
    EXPECT_TRUE(free_bins.empty());
}

INSTANTIATE_TEST_CASE_P(
        ForEachAllocator,
        MemoryPoolTestForEachAllocator,
        ::testing::Values(
                std::make_shared<MemoryPool>(0, std::make_unique<DeviceMemoryAllocator>()),
                std::make_shared<MemoryPool>(0, std::make_unique<PinnedMemoryAllocator>())));

TEST(MemoryPoolTest, MallocThrowOutOfMemory) {
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(0U)};
    EXPECT_THROW(memory_pool.Malloc(1), OutOfMemoryError);
}

TEST(MemoryPoolTest, MallocRetryOutOfMemory) {
    static constexpr size_t kCapacity = cuda::kAllocationUnitSize * 4;
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(kCapacity)};
    auto allocator = dynamic_cast<const FixedCapacityDummyAllocator*>(cuda_internal::MemoryPoolTest::GetAllocator(memory_pool));

    size_t size1 = kCapacity;
    size_t size2 = 1U;

    void* ptr1 = memory_pool.Malloc(size1);  // no throw
    memory_pool.Free(ptr1);

    void* ptr2 = memory_pool.Malloc(size2);  // no throw
    memory_pool.Free(ptr2);

    EXPECT_EQ(allocator->malloc_called(), 3);
}

}  // namespace
}  // namespace cuda
}  // namespace chainerx
<commit_msg>Update chainerx_cc/chainerx/cuda/memory_pool_test.cc<commit_after>#include "chainerx/cuda/memory_pool.h"

#include <memory>

#include <gtest/gtest.h>

#include "chainerx/error.h"

namespace chainerx {
namespace cuda {
namespace cuda_internal {

class MemoryPoolTest {
public:
    static const std::vector<std::vector<void*>>& GetFreeBins(const MemoryPool& pool) { return pool.free_bins_; }
    static const Allocator* GetAllocator(const MemoryPool& pool) { return pool.allocator_.get(); }
};

}  // namespace cuda_internal

namespace {

// A dummy allocator to test OutOfMemoryError
class FixedCapacityDummyAllocator : public Allocator {
public:
    explicit FixedCapacityDummyAllocator(size_t capacity) : capacity_{capacity} {}

    MallocStatus Malloc(void** ptr, size_t bytesize) override {
        CHAINERX_ASSERT(bytesize > 0);
        ++malloc_called_;
        if (capacity_ < bytesize) {
            return MallocStatus::kErrorMemoryAllocation;
        }
        // bytesize is encoded in the dummy pointer.
        auto i = static_cast<intptr_t>(bytesize);
        *ptr = reinterpret_cast<void*>(i);  // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
        capacity_ -= bytesize;
        return MallocStatus::kSuccess;
    }
    void Free(void* ptr) noexcept override {
        intptr_t i = reinterpret_cast<intptr_t>(ptr);  // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
        capacity_ += static_cast<size_t>(i);
    }

    int malloc_called() const { return malloc_called_; }

private:
    size_t capacity_;
    int malloc_called_{0};
};

class MemoryPoolTestForEachAllocator : public ::testing::TestWithParam<std::shared_ptr<MemoryPool>> {};

TEST_P(MemoryPoolTestForEachAllocator, MallocAndFree) {
    MemoryPool& memory_pool = *GetParam();

    void* ptr1 = memory_pool.Malloc(1);
    void* ptr2 = memory_pool.Malloc(1);
    EXPECT_NE(ptr1, ptr2);

    memory_pool.Free(ptr2);

    void* ptr3 = memory_pool.Malloc(1);
    EXPECT_EQ(ptr2, ptr3);
    memory_pool.Free(ptr3);

    memory_pool.Free(ptr1);
}

TEST_P(MemoryPoolTestForEachAllocator, MallocAllocationUnitSize) {
    MemoryPool& memory_pool = *GetParam();

    void* ptr1 = memory_pool.Malloc(100);
    memory_pool.Free(ptr1);

    void* ptr2 = memory_pool.Malloc(100 + kAllocationUnitSize);
    EXPECT_NE(ptr1, ptr2);

    memory_pool.Free(ptr2);
}

TEST_P(MemoryPoolTestForEachAllocator, MallocZeroByte) {
    MemoryPool& memory_pool = *GetParam();
    void* ptr = memory_pool.Malloc(0);
    EXPECT_EQ(nullptr, ptr);
    memory_pool.Free(ptr);  // no throw
}

TEST_P(MemoryPoolTestForEachAllocator, FreeTwice) {
    MemoryPool& memory_pool = *GetParam();
    void* ptr = memory_pool.Malloc(1);
    memory_pool.Free(ptr);
    EXPECT_THROW(memory_pool.Free(ptr), ChainerxError);
}

TEST_P(MemoryPoolTestForEachAllocator, FreeForeignPointer) {
    MemoryPool& memory_pool = *GetParam();
    void* ptr = &memory_pool;
    EXPECT_THROW(memory_pool.Free(ptr), ChainerxError);
}

TEST_P(MemoryPoolTestForEachAllocator, FreeUnusedBlocks) {
    MemoryPool& memory_pool = *GetParam();
    const std::vector<std::vector<void*>>& free_bins = cuda_internal::MemoryPoolTest::GetFreeBins(memory_pool);

    void* ptr1 = memory_pool.Malloc(1);
    memory_pool.Free(ptr1);
    EXPECT_FALSE(free_bins.empty());

    memory_pool.FreeUnusedBlocks();
    EXPECT_TRUE(free_bins.empty());
}

INSTANTIATE_TEST_CASE_P(
        ForEachAllocator,
        MemoryPoolTestForEachAllocator,
        ::testing::Values(
                std::make_shared<MemoryPool>(0, std::make_unique<DeviceMemoryAllocator>()),
                std::make_shared<MemoryPool>(0, std::make_unique<PinnedMemoryAllocator>())));

TEST(MemoryPoolTest, MallocThrowOutOfMemory) {
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(0U)};
    EXPECT_THROW(memory_pool.Malloc(1), OutOfMemoryError);
}

TEST(MemoryPoolTest, MallocRetryOutOfMemory) {
    static constexpr size_t kCapacity = cuda::kAllocationUnitSize * 4;
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(kCapacity)};
    auto allocator = dynamic_cast<const FixedCapacityDummyAllocator*>(cuda_internal::MemoryPoolTest::GetAllocator(memory_pool));

    size_t size1 = kCapacity;
    size_t size2 = 1U;

    void* ptr1 = memory_pool.Malloc(size1);  // no throw
    memory_pool.Free(ptr1);

    void* ptr2 = memory_pool.Malloc(size2);  // no throw
    memory_pool.Free(ptr2);

    EXPECT_EQ(allocator->malloc_called(), 3);
}

}  // namespace
}  // namespace cuda
}  // namespace chainerx
<|endoftext|>


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

#include "apps/shell_window_geometry_cache.h"
#include "chrome/browser/apps/app_browsertest_util.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/extensions/application_launch.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/test_utils.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"

using apps::ShellWindowGeometryCache;

// This helper class can be used to wait for changes in the shell window
// geometry cache registry for a specific window in a specific extension.
class GeometryCacheChangeHelper : ShellWindowGeometryCache::Observer {
 public:
  GeometryCacheChangeHelper(ShellWindowGeometryCache* cache,
                            const std::string& extension_id,
                            const std::string& window_id,
                            const gfx::Rect& bounds)
      : cache_(cache),
        extension_id_(extension_id),
        window_id_(window_id),
        bounds_(bounds) {
    cache_->AddObserver(this);
  }

  // This method will block until the shell window geometry cache registry will
  // provide a bound for |window_id_| that is entirely different (as in x/y/w/h)
  // from the initial |bounds_|.
  void WaitForEntirelyChanged() {
    content::RunMessageLoop();
  }

  // Implements the content::NotificationObserver interface.
  virtual void OnGeometryCacheChanged(const std::string& extension_id,
                                      const std::string& window_id,
                                      const gfx::Rect& bounds)
      OVERRIDE {
    if (extension_id != extension_id_ || window_id != window_id_)
      return;

    if (bounds_.x() != bounds.x() &&
        bounds_.y() != bounds.y() &&
        bounds_.width() != bounds.width() &&
        bounds_.height() != bounds.height()) {
      cache_->RemoveObserver(this);
      base::MessageLoopForUI::current()->Quit();
    }
  }

 private:
  ShellWindowGeometryCache* cache_;
  std::string extension_id_;
  std::string window_id_;
  gfx::Rect bounds_;
};

// Helper class for tests related to the Apps Window API (chrome.app.window).
class AppWindowAPI : public extensions::PlatformAppBrowserTest {
 public:
  bool RunAppWindowAPITest(const char* testName) {
    ExtensionTestMessageListener launched_listener("Launched", true);
    LoadAndLaunchPlatformApp("window_api");
    if (!launched_listener.WaitUntilSatisfied()) {
      message_ = "Did not get the 'Launched' message.";
      return false;
    }

    ResultCatcher catcher;
    launched_listener.Reply(testName);

    if (!catcher.GetNextResult()) {
      message_ = catcher.message();
      return false;
    }

    return true;
  }
};

// These tests are flaky after https://codereview.chromium.org/57433010/.
// See http://crbug.com/319613.

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestCreate) {
  ASSERT_TRUE(RunAppWindowAPITest("testCreate")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestSingleton) {
  ASSERT_TRUE(RunAppWindowAPITest("testSingleton")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestBounds) {
  ASSERT_TRUE(RunAppWindowAPITest("testBounds")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestCloseEvent) {
  ASSERT_TRUE(RunAppWindowAPITest("testCloseEvent")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestMaximize) {
  ASSERT_TRUE(RunAppWindowAPITest("testMaximize")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestRestore) {
  ASSERT_TRUE(RunAppWindowAPITest("testRestore")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestRestoreAfterClose) {
  ASSERT_TRUE(RunAppWindowAPITest("testRestoreAfterClose")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, TestRestoreGeometryCacheChange) {
  // This test is similar to the other AppWindowAPI tests except that at some
  // point the app will send a 'ListenGeometryChange' message at which point the
  // test will check if the geometry cache entry for the test window has
  // changed. When the change happens, the test will let the app know so it can
  // continue running.
  ExtensionTestMessageListener launched_listener("Launched", true);

  content::WindowedNotificationObserver app_loaded_observer(
      content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
      content::NotificationService::AllSources());

  const extensions::Extension* extension = LoadExtension(
      test_data_dir_.AppendASCII("platform_apps").AppendASCII("window_api"));
  EXPECT_TRUE(extension);

  OpenApplication(AppLaunchParams(
      browser()->profile(), extension, extensions::LAUNCH_NONE, NEW_WINDOW));

  ExtensionTestMessageListener geometry_listener("ListenGeometryChange", true);

  ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
  launched_listener.Reply("testRestoreAfterGeometryCacheChange");

  ASSERT_TRUE(geometry_listener.WaitUntilSatisfied());

  GeometryCacheChangeHelper geo_change_helper(
      ShellWindowGeometryCache::Get(browser()->profile()), extension->id(),
      // The next line has information that has to stay in sync with the app.
      "test-ps", gfx::Rect(200, 200, 200, 200));

  // This call will block until the shell window geometry cache will be changed.
  geo_change_helper.WaitForEntirelyChanged();

  ResultCatcher catcher;
  geometry_listener.Reply("");
  ASSERT_TRUE(catcher.GetNextResult());
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestSizeConstraints) {
  ASSERT_TRUE(RunAppWindowAPITest("testSizeConstraints")) << message_;
}
<commit_msg>Disable AppWindowAPI.TestRestoreGeometryCacheChange on Mac<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "apps/shell_window_geometry_cache.h"
#include "chrome/browser/apps/app_browsertest_util.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/extensions/application_launch.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/test_utils.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"

using apps::ShellWindowGeometryCache;

// This helper class can be used to wait for changes in the shell window
// geometry cache registry for a specific window in a specific extension.
class GeometryCacheChangeHelper : ShellWindowGeometryCache::Observer {
 public:
  GeometryCacheChangeHelper(ShellWindowGeometryCache* cache,
                            const std::string& extension_id,
                            const std::string& window_id,
                            const gfx::Rect& bounds)
      : cache_(cache),
        extension_id_(extension_id),
        window_id_(window_id),
        bounds_(bounds) {
    cache_->AddObserver(this);
  }

  // This method will block until the shell window geometry cache registry will
  // provide a bound for |window_id_| that is entirely different (as in x/y/w/h)
  // from the initial |bounds_|.
  void WaitForEntirelyChanged() {
    content::RunMessageLoop();
  }

  // Implements the content::NotificationObserver interface.
  virtual void OnGeometryCacheChanged(const std::string& extension_id,
                                      const std::string& window_id,
                                      const gfx::Rect& bounds)
      OVERRIDE {
    if (extension_id != extension_id_ || window_id != window_id_)
      return;

    if (bounds_.x() != bounds.x() &&
        bounds_.y() != bounds.y() &&
        bounds_.width() != bounds.width() &&
        bounds_.height() != bounds.height()) {
      cache_->RemoveObserver(this);
      base::MessageLoopForUI::current()->Quit();
    }
  }

 private:
  ShellWindowGeometryCache* cache_;
  std::string extension_id_;
  std::string window_id_;
  gfx::Rect bounds_;
};

// Helper class for tests related to the Apps Window API (chrome.app.window).
class AppWindowAPI : public extensions::PlatformAppBrowserTest {
 public:
  bool RunAppWindowAPITest(const char* testName) {
    ExtensionTestMessageListener launched_listener("Launched", true);
    LoadAndLaunchPlatformApp("window_api");
    if (!launched_listener.WaitUntilSatisfied()) {
      message_ = "Did not get the 'Launched' message.";
      return false;
    }

    ResultCatcher catcher;
    launched_listener.Reply(testName);

    if (!catcher.GetNextResult()) {
      message_ = catcher.message();
      return false;
    }

    return true;
  }
};

// These tests are flaky after https://codereview.chromium.org/57433010/.
// See http://crbug.com/319613.

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestCreate) {
  ASSERT_TRUE(RunAppWindowAPITest("testCreate")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestSingleton) {
  ASSERT_TRUE(RunAppWindowAPITest("testSingleton")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestBounds) {
  ASSERT_TRUE(RunAppWindowAPITest("testBounds")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestCloseEvent) {
  ASSERT_TRUE(RunAppWindowAPITest("testCloseEvent")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestMaximize) {
  ASSERT_TRUE(RunAppWindowAPITest("testMaximize")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestRestore) {
  ASSERT_TRUE(RunAppWindowAPITest("testRestore")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestRestoreAfterClose) {
  ASSERT_TRUE(RunAppWindowAPITest("testRestoreAfterClose")) << message_;
}

// Flaky failures on mac_rel, see http://crbug.com/324915
#if defined(OS_MACOSX)
#define MAYBE_TestRestoreGeometryCacheChange DISABLED_TestRestoreGeometryCacheChange
#else
#define MAYBE_TestRestoreGeometryCacheChange TestRestoreGeometryCacheChange
#endif
IN_PROC_BROWSER_TEST_F(AppWindowAPI, MAYBE_TestRestoreGeometryCacheChange) {
  // This test is similar to the other AppWindowAPI tests except that at some
  // point the app will send a 'ListenGeometryChange' message at which point the
  // test will check if the geometry cache entry for the test window has
  // changed. When the change happens, the test will let the app know so it can
  // continue running.
  ExtensionTestMessageListener launched_listener("Launched", true);

  content::WindowedNotificationObserver app_loaded_observer(
      content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
      content::NotificationService::AllSources());

  const extensions::Extension* extension = LoadExtension(
      test_data_dir_.AppendASCII("platform_apps").AppendASCII("window_api"));
  EXPECT_TRUE(extension);

  OpenApplication(AppLaunchParams(
      browser()->profile(), extension, extensions::LAUNCH_NONE, NEW_WINDOW));

  ExtensionTestMessageListener geometry_listener("ListenGeometryChange", true);

  ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
  launched_listener.Reply("testRestoreAfterGeometryCacheChange");

  ASSERT_TRUE(geometry_listener.WaitUntilSatisfied());

  GeometryCacheChangeHelper geo_change_helper(
      ShellWindowGeometryCache::Get(browser()->profile()), extension->id(),
      // The next line has information that has to stay in sync with the app.
      "test-ps", gfx::Rect(200, 200, 200, 200));

  // This call will block until the shell window geometry cache will be changed.
  geo_change_helper.WaitForEntirelyChanged();

  ResultCatcher catcher;
  geometry_listener.Reply("");
  ASSERT_TRUE(catcher.GetNextResult());
}

IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestSizeConstraints) {
  ASSERT_TRUE(RunAppWindowAPITest("testSizeConstraints")) << message_;
}
<|endoftext|>


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

#include "chrome/browser/chromeos/cros/power_library.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "third_party/cros/chromeos_resume.h"

namespace chromeos {

class PowerLibraryImpl : public PowerLibrary {
 public:
  PowerLibraryImpl()
      : power_status_connection_(NULL),
        status_(chromeos::PowerStatus()) {
    if (CrosLibrary::Get()->EnsureLoaded()) {
      Init();
    }
  }

  ~PowerLibraryImpl() {
    if (power_status_connection_) {
      chromeos::DisconnectPowerStatus(power_status_connection_);
      power_status_connection_ = NULL;
    }
    if (resume_status_connection_) {
      chromeos::DisconnectResume(resume_status_connection_);
      resume_status_connection_ = NULL;
    }
  }

  void AddObserver(Observer* observer) {
    observers_.AddObserver(observer);
  }

  void RemoveObserver(Observer* observer) {
    observers_.RemoveObserver(observer);
  }

  bool line_power_on() const {
    return status_.line_power_on;
  }

  bool battery_is_present() const {
    return status_.battery_is_present;
  }

  bool battery_fully_charged() const {
    return status_.battery_state == chromeos::BATTERY_STATE_FULLY_CHARGED;
  }

  double battery_percentage() const {
    return status_.battery_percentage;
  }

  base::TimeDelta battery_time_to_empty() const {
    return base::TimeDelta::FromSeconds(status_.battery_time_to_empty);
  }

  base::TimeDelta battery_time_to_full() const {
    return base::TimeDelta::FromSeconds(status_.battery_time_to_full);
  }

  virtual void EnableScreenLock(bool enable) {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;

    // Make sure we run on FILE thread becuase chromeos::EnableScreenLock
    // would write power manager config file to disk.
    if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
      BrowserThread::PostTask(
          BrowserThread::FILE, FROM_HERE,
          NewRunnableMethod(this, &PowerLibraryImpl::EnableScreenLock, enable));
      return;
    }

    chromeos::EnableScreenLock(enable);
  }

  virtual void RequestRestart() {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;
    chromeos::RequestRestart();
  }

  virtual void RequestShutdown() {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;
    chromeos::RequestShutdown();
  }

 private:
  static void PowerStatusChangedHandler(void* object,
      const chromeos::PowerStatus& status) {
    PowerLibraryImpl* power = static_cast<PowerLibraryImpl*>(object);
    power->UpdatePowerStatus(status);
  }

  static void SystemResumedHandler(void* object) {
    PowerLibraryImpl* power = static_cast<PowerLibraryImpl*>(object);
    power->SystemResumed();
  }

  void Init() {
    power_status_connection_ = chromeos::MonitorPowerStatus(
        &PowerStatusChangedHandler, this);
    resume_status_connection_ =
        chromeos::MonitorResume(&SystemResumedHandler, this);
  }

  void UpdatePowerStatus(const chromeos::PowerStatus& status) {
    // Make sure we run on UI thread.
    if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          NewRunnableMethod(
              this, &PowerLibraryImpl::UpdatePowerStatus, status));
      return;
    }

    DVLOG(1) << "Power lpo=" << status.line_power_on
             << " sta=" << status.battery_state
             << " per=" << status.battery_percentage
             << " tte=" << status.battery_time_to_empty
             << " ttf=" << status.battery_time_to_full;
    status_ = status;
    FOR_EACH_OBSERVER(Observer, observers_, PowerChanged(this));
  }

  void SystemResumed() {
    // Make sure we run on the UI thread.
    if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          NewRunnableMethod(this, &PowerLibraryImpl::SystemResumed));
      return;
    }

    FOR_EACH_OBSERVER(Observer, observers_, SystemResumed());
  }

  ObserverList<Observer> observers_;

  // A reference to the battery power api, to allow callbacks when the battery
  // status changes.
  chromeos::PowerStatusConnection power_status_connection_;

  // A reference to the resume alerts.
  chromeos::ResumeConnection resume_status_connection_;

  // The latest power status.
  chromeos::PowerStatus status_;

  DISALLOW_COPY_AND_ASSIGN(PowerLibraryImpl);
};

class PowerLibraryStubImpl : public PowerLibrary {
 public:
  PowerLibraryStubImpl() {}
  ~PowerLibraryStubImpl() {}
  void AddObserver(Observer* observer) {}
  void RemoveObserver(Observer* observer) {}
  bool line_power_on() const { return false; }
  bool battery_is_present() const { return false; }
  bool battery_fully_charged() const { return false; }
  double battery_percentage() const { return false; }
  base::TimeDelta battery_time_to_empty() const {
    return base::TimeDelta::FromSeconds(0);
  }
  base::TimeDelta battery_time_to_full() const {
    return base::TimeDelta::FromSeconds(0);
  }
  virtual void EnableScreenLock(bool enable) {}
  virtual void RequestRestart() {}
  virtual void RequestShutdown() {}
};

// static
PowerLibrary* PowerLibrary::GetImpl(bool stub) {
  if (stub)
    return new PowerLibraryStubImpl();
  else
    return new PowerLibraryImpl();
}

}  // namespace chromeos

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::PowerLibraryImpl);
<commit_msg>Crash fix in chromeos tests BUG=chromium-os:11121 TEST=none<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/cros/power_library.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "third_party/cros/chromeos_resume.h"

namespace chromeos {

class PowerLibraryImpl : public PowerLibrary {
 public:
  PowerLibraryImpl()
      : power_status_connection_(NULL),
        resume_status_connection_(NULL),
        status_(chromeos::PowerStatus()) {
    if (CrosLibrary::Get()->EnsureLoaded()) {
      Init();
    }
  }

  ~PowerLibraryImpl() {
    if (power_status_connection_) {
      chromeos::DisconnectPowerStatus(power_status_connection_);
      power_status_connection_ = NULL;
    }
    if (resume_status_connection_) {
      chromeos::DisconnectResume(resume_status_connection_);
      resume_status_connection_ = NULL;
    }
  }

  void AddObserver(Observer* observer) {
    observers_.AddObserver(observer);
  }

  void RemoveObserver(Observer* observer) {
    observers_.RemoveObserver(observer);
  }

  bool line_power_on() const {
    return status_.line_power_on;
  }

  bool battery_is_present() const {
    return status_.battery_is_present;
  }

  bool battery_fully_charged() const {
    return status_.battery_state == chromeos::BATTERY_STATE_FULLY_CHARGED;
  }

  double battery_percentage() const {
    return status_.battery_percentage;
  }

  base::TimeDelta battery_time_to_empty() const {
    return base::TimeDelta::FromSeconds(status_.battery_time_to_empty);
  }

  base::TimeDelta battery_time_to_full() const {
    return base::TimeDelta::FromSeconds(status_.battery_time_to_full);
  }

  virtual void EnableScreenLock(bool enable) {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;

    // Make sure we run on FILE thread becuase chromeos::EnableScreenLock
    // would write power manager config file to disk.
    if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
      BrowserThread::PostTask(
          BrowserThread::FILE, FROM_HERE,
          NewRunnableMethod(this, &PowerLibraryImpl::EnableScreenLock, enable));
      return;
    }

    chromeos::EnableScreenLock(enable);
  }

  virtual void RequestRestart() {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;
    chromeos::RequestRestart();
  }

  virtual void RequestShutdown() {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;
    chromeos::RequestShutdown();
  }

 private:
  static void PowerStatusChangedHandler(void* object,
      const chromeos::PowerStatus& status) {
    PowerLibraryImpl* power = static_cast<PowerLibraryImpl*>(object);
    power->UpdatePowerStatus(status);
  }

  static void SystemResumedHandler(void* object) {
    PowerLibraryImpl* power = static_cast<PowerLibraryImpl*>(object);
    power->SystemResumed();
  }

  void Init() {
    power_status_connection_ = chromeos::MonitorPowerStatus(
        &PowerStatusChangedHandler, this);
    resume_status_connection_ =
        chromeos::MonitorResume(&SystemResumedHandler, this);
  }

  void UpdatePowerStatus(const chromeos::PowerStatus& status) {
    // Make sure we run on UI thread.
    if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          NewRunnableMethod(
              this, &PowerLibraryImpl::UpdatePowerStatus, status));
      return;
    }

    DVLOG(1) << "Power lpo=" << status.line_power_on
             << " sta=" << status.battery_state
             << " per=" << status.battery_percentage
             << " tte=" << status.battery_time_to_empty
             << " ttf=" << status.battery_time_to_full;
    status_ = status;
    FOR_EACH_OBSERVER(Observer, observers_, PowerChanged(this));
  }

  void SystemResumed() {
    // Make sure we run on the UI thread.
    if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          NewRunnableMethod(this, &PowerLibraryImpl::SystemResumed));
      return;
    }

    FOR_EACH_OBSERVER(Observer, observers_, SystemResumed());
  }

  ObserverList<Observer> observers_;

  // A reference to the battery power api, to allow callbacks when the battery
  // status changes.
  chromeos::PowerStatusConnection power_status_connection_;

  // A reference to the resume alerts.
  chromeos::ResumeConnection resume_status_connection_;

  // The latest power status.
  chromeos::PowerStatus status_;

  DISALLOW_COPY_AND_ASSIGN(PowerLibraryImpl);
};

class PowerLibraryStubImpl : public PowerLibrary {
 public:
  PowerLibraryStubImpl() {}
  ~PowerLibraryStubImpl() {}
  void AddObserver(Observer* observer) {}
  void RemoveObserver(Observer* observer) {}
  bool line_power_on() const { return false; }
  bool battery_is_present() const { return false; }
  bool battery_fully_charged() const { return false; }
  double battery_percentage() const { return false; }
  base::TimeDelta battery_time_to_empty() const {
    return base::TimeDelta::FromSeconds(0);
  }
  base::TimeDelta battery_time_to_full() const {
    return base::TimeDelta::FromSeconds(0);
  }
  virtual void EnableScreenLock(bool enable) {}
  virtual void RequestRestart() {}
  virtual void RequestShutdown() {}
};

// static
PowerLibrary* PowerLibrary::GetImpl(bool stub) {
  if (stub)
    return new PowerLibraryStubImpl();
  else
    return new PowerLibraryImpl();
}

}  // namespace chromeos

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::PowerLibraryImpl);
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkTranslationTransformTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2000 National Library of Medicine
  All rights reserved.

  See COPYRIGHT.txt for copyright details.

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

#include <iostream>

#include "itkTranslationTransform.h"
#include "itkPhysicalImage.h"
#include "vnl/vnl_vector_fixed.h"

typedef  itk::Vector<double,2>     VectorType;

void PrintVector( const VectorType & v )
{
  for( unsigned int i=0; i<VectorType::VectorDimension; i++)
  {
    std::cout << v[i] << ", ";
  }
  std::cout << std::endl;
}

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

    int any = 0;       // Any errors detected in testing?

    VectorType                   vector2;

    int i;

    /* FIXME: This code exercises most of the methods but doesn't
       actually check that the results are correct. */
    any = 0;
    std::cout << "The TranslationTransform class is still being implemented"
              << std::endl;

    /* Create a 2D identity transformation and show its parameters */
    itk::TranslationTransform<double,2> id2;
    vector2 = id2.GetOffset();
        std::cout << "Vector from instantiating an identity transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Create and show a simple 2D transform from given parameters */
    vector2[0] = 5;
    vector2[1] = 6;
    itk::TranslationTransform<double,2> aff2(vector2);
    for (i = 0; i < 2; i++)
    {
        vector2[i]    = 0.0;
    }
    std::cout << "Instantiation of a given 2D transform:"
              << std::endl;
    aff2.PrintSelf( std::cout );

    itk::TranslationTransform<double,2> inverse2;
    inverse2 = aff2.Inverse();
    std::cout << "Inverse of the given transform:"
              << std::endl;
    inverse2.PrintSelf( std::cout );

    /* Set parameters of a 2D transform */
    vector2[0] = 2;
    vector2[1] = 1;
    aff2.SetOffset(vector2);
    for (i = 0; i < 2; i++)
    {
        vector2[i]    = 0.0;
    }

    vector2 = aff2.GetOffset();
    std::cout << "Setting the offset in an existing  transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Try composition of two transformations */
    aff2.Compose(aff2);
    std::cout << "Result of a composition:"
              << std::endl;
    aff2.PrintSelf( std::cout );

    /* Compose with a translation */
    VectorType trans;
    trans[0] = 1;
    trans[1] = 2;
    aff2.Translate(trans);
    std::cout << "Result of a translation:"
              << std::endl;
    aff2.PrintSelf( std::cout );

        /* Transform a point */
    itk::Point<double, 2> u2, v2;
    u2[0] = 3;
    u2[1] = 5;
    v2 = aff2.Transform(u2);
    std::cout << "Transform a point:" << std::endl
              << v2[0] << " , " << v2[1] << std::endl;

    /* Back transform a point */
    v2 = aff2.BackTransform(u2);
    std::cout << "Back transform a point:" << std::endl
              << v2[0] << " , " << v2[1] << std::endl;

    /* Transform a vnl_vector */
    vnl_vector_fixed<double, 2> x2, y2;
    x2[0] = 1;
    x2[1] = 2;
    y2 = aff2.Transform(x2);
    std::cout << "Transform a vnl_vector:" << std::endl
              << y2[0] << " , " << y2[1] << std::endl;

    /* Back transform a vector */
    y2 = aff2.BackTransform(x2);
    std::cout << "Back transform a vnl_vector:" << std::endl
              << y2[0] << " , " << y2[1] << std::endl;

    /* Transform a vector */
    itk::Vector<double, 2> u3, v3;
    u3[0] = 3;
    u3[1] = 5;
    v3 = aff2.Transform(u3);
    std::cout << "Transform a vector:" << std::endl
              << v3[0] << " , " << v3[1] << std::endl;

    /* Back transform a vector */
    v3 = aff2.BackTransform(u3);
    std::cout << "Back transform a vector :" << std::endl
              << v3[0] << " , " << v3[1] << std::endl;

    /* Transform a Covariant vector */
    itk::Vector<double, 2> u4, v4;
    u4[0] = 3;
    u4[1] = 5;
    v4 = aff2.Transform(u4);
    std::cout << "Transform a Covariant vector:" << std::endl
              << v4[0] << " , " << v4[1] << std::endl;

    /* Back transform a vector */
    v4 = aff2.BackTransform(u4);
    std::cout << "Back transform a vector :" << std::endl
              << v4[0] << " , " << v4[1] << std::endl;

    return any;
}
<commit_msg>ENH: The operator<< ostream can be used again. ICE was solved<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkTranslationTransformTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2000 National Library of Medicine
  All rights reserved.

  See COPYRIGHT.txt for copyright details.

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

#include <iostream>

#include "itkTranslationTransform.h"
#include "itkPhysicalImage.h"
#include "vnl/vnl_vector_fixed.h"

typedef  itk::Vector<double,2>     VectorType;

void PrintVector( const VectorType & v )
{
  for( unsigned int i=0; i<VectorType::VectorDimension; i++)
  {
    std::cout << v[i] << ", ";
  }
  std::cout << std::endl;
}

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

    int any = 0;       // Any errors detected in testing?

    VectorType                   vector2;

    int i;

    /* FIXME: This code exercises most of the methods but doesn't
       actually check that the results are correct. */
    any = 0;
    std::cout << "The TranslationTransform class is still being implemented"
              << std::endl;

    /* Create a 2D identity transformation and show its parameters */
    itk::TranslationTransform<double,2> id2;
    vector2 = id2.GetOffset();
        std::cout << "Vector from instantiating an identity transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Create and show a simple 2D transform from given parameters */
    vector2[0] = 5;
    vector2[1] = 6;
    itk::TranslationTransform<double,2> aff2(vector2);
    for (i = 0; i < 2; i++)
    {
        vector2[i]    = 0.0;
    }
    std::cout << "Instantiation of a given 2D transform:"
              << std::endl << aff2;

    itk::TranslationTransform<double,2> inverse2;
    inverse2 = aff2.Inverse();
    std::cout << "Inverse of the given transform:"
              << std::endl << inverse2;

    /* Set parameters of a 2D transform */
    vector2[0] = 2;
    vector2[1] = 1;
    aff2.SetOffset(vector2);
    for (i = 0; i < 2; i++)
    {
        vector2[i]    = 0.0;
    }

    vector2 = aff2.GetOffset();
    std::cout << "Setting the offset in an existing  transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Try composition of two transformations */
    aff2.Compose(aff2);
    std::cout << "Result of a composition:"
              << std::endl << aff2;

    /* Compose with a translation */
    VectorType trans;
    trans[0] = 1;
    trans[1] = 2;
    aff2.Translate(trans);
    std::cout << "Result of a translation:"
              << std::endl << aff2;

        /* Transform a point */
    itk::Point<double, 2> u2, v2;
    u2[0] = 3;
    u2[1] = 5;
    v2 = aff2.Transform(u2);
    std::cout << "Transform a point:" << std::endl
              << v2[0] << " , " << v2[1] << std::endl;

    /* Back transform a point */
    v2 = aff2.BackTransform(u2);
    std::cout << "Back transform a point:" << std::endl
              << v2[0] << " , " << v2[1] << std::endl;

    /* Transform a vnl_vector */
    vnl_vector_fixed<double, 2> x2, y2;
    x2[0] = 1;
    x2[1] = 2;
    y2 = aff2.Transform(x2);
    std::cout << "Transform a vnl_vector:" << std::endl
              << y2[0] << " , " << y2[1] << std::endl;

    /* Back transform a vector */
    y2 = aff2.BackTransform(x2);
    std::cout << "Back transform a vnl_vector:" << std::endl
              << y2[0] << " , " << y2[1] << std::endl;

    /* Transform a vector */
    itk::Vector<double, 2> u3, v3;
    u3[0] = 3;
    u3[1] = 5;
    v3 = aff2.Transform(u3);
    std::cout << "Transform a vector:" << std::endl
              << v3[0] << " , " << v3[1] << std::endl;

    /* Back transform a vector */
    v3 = aff2.BackTransform(u3);
    std::cout << "Back transform a vector :" << std::endl
              << v3[0] << " , " << v3[1] << std::endl;

    /* Transform a Covariant vector */
    itk::Vector<double, 2> u4, v4;
    u4[0] = 3;
    u4[1] = 5;
    v4 = aff2.Transform(u4);
    std::cout << "Transform a Covariant vector:" << std::endl
              << v4[0] << " , " << v4[1] << std::endl;

    /* Back transform a vector */
    v4 = aff2.BackTransform(u4);
    std::cout << "Back transform a vector :" << std::endl
              << v4[0] << " , " << v4[1] << std::endl;

    return any;
}
<|endoftext|>


<commit_before>#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>

#include <cppunit/TestRunner.h>

#include "Suite.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"

INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{

    setUpSuite();

    // Create the event manager and test controller
    CPPUNIT_NS::TestResult controller;

    // Add a listener that colllects test result
    CPPUNIT_NS::TestResultCollector result;
    controller.addListener( &result );

    // Add a listener that print dots as test run.
    CPPUNIT_NS::BriefTestProgressListener progress;
    controller.addListener( &progress );

    // Add the top suite to the test runner
    CPPUNIT_NS::TestRunner runner;
    runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
    runner.run( controller );

    // Print test in a compiler compatible format.
    CPPUNIT_NS::CompilerOutputter* outputter =
        CPPUNIT_NS::CompilerOutputter::defaultOutputter(&result, std::cout);
    outputter->write();
    delete outputter;

    tearDownSuite();

    return result.wasSuccessful() ? 0 : 1;

}
<commit_msg>Write test results to a file for easier examination<commit_after>#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>

#include <cppunit/TestRunner.h>

#include "Suite.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"

INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{

    setUpSuite();

    // Create the event manager and test controller
    CPPUNIT_NS::TestResult controller;

    // Add a listener that colllects test result
    CPPUNIT_NS::TestResultCollector result;
    controller.addListener( &result );

    // Add a listener that print dots as test run.
    CPPUNIT_NS::BriefTestProgressListener progress;
    controller.addListener( &progress );

    // Add the top suite to the test runner
    CPPUNIT_NS::TestRunner runner;
    runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
    runner.run( controller );

    // Print test results to a file
	std::ofstream ofile("OgreTestResults.log");

    CPPUNIT_NS::CompilerOutputter* outputter =
        CPPUNIT_NS::CompilerOutputter::defaultOutputter(&result, ofile);
    outputter->write();
    delete outputter;

    tearDownSuite();

    return result.wasSuccessful() ? 0 : 1;

}
<|endoftext|>


<commit_before>//===--- InefficientAlgorithmCheck.cpp - clang-tidy------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "InefficientAlgorithmCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace misc {

static bool areTypesCompatible(QualType Left, QualType Right) {
  if (const auto *LeftRefType = Left->getAs<ReferenceType>())
    Left = LeftRefType->getPointeeType();
  if (const auto *RightRefType = Right->getAs<ReferenceType>())
    Right = RightRefType->getPointeeType();
  return Left->getCanonicalTypeUnqualified() ==
         Right->getCanonicalTypeUnqualified();
}

void InefficientAlgorithmCheck::registerMatchers(MatchFinder *Finder) {
  // Only register the matchers for C++; the functionality currently does not
  // provide any benefit to other languages, despite being benign.
  if (!getLangOpts().CPlusPlus)
    return;

  const std::string Algorithms =
      "^::std::(find|count|equal_range|lower_bound|upper_bound)$";
  const auto ContainerMatcher = classTemplateSpecializationDecl(
      matchesName("^::std::(unordered_)?(multi)?(set|map)$"));
  const auto Matcher =
      callExpr(
          callee(functionDecl(matchesName(Algorithms))),
          hasArgument(
              0, cxxConstructExpr(has(cxxMemberCallExpr(
                     callee(cxxMethodDecl(hasName("begin"))),
                     on(declRefExpr(
                            hasDeclaration(decl().bind("IneffContObj")),
                            anyOf(hasType(ContainerMatcher.bind("IneffCont")),
                                  hasType(pointsTo(
                                      ContainerMatcher.bind("IneffContPtr")))))
                            .bind("IneffContExpr")))))),
          hasArgument(1, cxxConstructExpr(has(cxxMemberCallExpr(
                             callee(cxxMethodDecl(hasName("end"))),
                             on(declRefExpr(hasDeclaration(
                                 equalsBoundNode("IneffContObj")))))))),
          hasArgument(2, expr().bind("AlgParam")),
          unless(isInTemplateInstantiation()))
          .bind("IneffAlg");

  Finder->addMatcher(Matcher, this);
}

void InefficientAlgorithmCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *AlgCall = Result.Nodes.getNodeAs<CallExpr>("IneffAlg");
  const auto *IneffCont =
      Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("IneffCont");
  bool PtrToContainer = false;
  if (!IneffCont) {
    IneffCont =
        Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("IneffContPtr");
    PtrToContainer = true;
  }
  const llvm::StringRef IneffContName = IneffCont->getName();
  const bool Unordered =
      IneffContName.find("unordered") != llvm::StringRef::npos;
  const bool Maplike = IneffContName.find("map") != llvm::StringRef::npos;

  // Store if the key type of the container is compatible with the value
  // that is searched for.
  QualType ValueType = AlgCall->getArg(2)->getType();
  QualType KeyType =
      IneffCont->getTemplateArgs()[0].getAsType().getCanonicalType();
  const bool CompatibleTypes = areTypesCompatible(KeyType, ValueType);

  // Check if the comparison type for the algorithm and the container matches.
  if (AlgCall->getNumArgs() == 4 && !Unordered) {
    const Expr *Arg = AlgCall->getArg(3);
    const QualType AlgCmp =
        Arg->getType().getUnqualifiedType().getCanonicalType();
    const unsigned CmpPosition =
        (IneffContName.find("map") == llvm::StringRef::npos) ? 1 : 2;
    const QualType ContainerCmp = IneffCont->getTemplateArgs()[CmpPosition]
                                      .getAsType()
                                      .getUnqualifiedType()
                                      .getCanonicalType();
    if (AlgCmp != ContainerCmp) {
      diag(Arg->getLocStart(),
           "different comparers used in the algorithm and the container");
      return;
    }
  }

  const auto *AlgDecl = AlgCall->getDirectCallee();
  if (!AlgDecl)
    return;

  if (Unordered && AlgDecl->getName().find("bound") != llvm::StringRef::npos)
    return;

  const auto *AlgParam = Result.Nodes.getNodeAs<Expr>("AlgParam");
  const auto *IneffContExpr = Result.Nodes.getNodeAs<Expr>("IneffContExpr");
  FixItHint Hint;

  SourceManager &SM = *Result.SourceManager;
  LangOptions LangOpts = Result.Context->getLangOpts();

  CharSourceRange CallRange =
      CharSourceRange::getTokenRange(AlgCall->getSourceRange());

  // FIXME: Create a common utility to extract a file range that the given token
  // sequence is exactly spelled at (without macro argument expansions etc.).
  // We can't use Lexer::makeFileCharRange here, because for
  //
  //   #define F(x) x
  //   x(a b c);
  //
  // it will return "x(a b c)", when given the range "a"-"c". It makes sense for
  // removals, but not for replacements.
  //
  // This code is over-simplified, but works for many real cases.
  if (SM.isMacroArgExpansion(CallRange.getBegin()) &&
      SM.isMacroArgExpansion(CallRange.getEnd())) {
    CallRange.setBegin(SM.getSpellingLoc(CallRange.getBegin()));
    CallRange.setEnd(SM.getSpellingLoc(CallRange.getEnd()));
  }

  if (!CallRange.getBegin().isMacroID() && !Maplike && CompatibleTypes) {
    StringRef ContainerText = Lexer::getSourceText(
        CharSourceRange::getTokenRange(IneffContExpr->getSourceRange()), SM,
        LangOpts);
    StringRef ParamText = Lexer::getSourceText(
        CharSourceRange::getTokenRange(AlgParam->getSourceRange()), SM,
        LangOpts);
    std::string ReplacementText =
        (llvm::Twine(ContainerText) + (PtrToContainer ? "->" : ".") +
         AlgDecl->getName() + "(" + ParamText + ")")
            .str();
    Hint = FixItHint::CreateReplacement(CallRange, ReplacementText);
  }

  diag(AlgCall->getLocStart(),
       "this STL algorithm call should be replaced with a container method")
      << Hint;
}

} // namespace misc
} // namespace tidy
} // namespace clang
<commit_msg>[clang-tidy] Use hasAnyName() instead of matchesName().<commit_after>//===--- InefficientAlgorithmCheck.cpp - clang-tidy------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "InefficientAlgorithmCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace misc {

static bool areTypesCompatible(QualType Left, QualType Right) {
  if (const auto *LeftRefType = Left->getAs<ReferenceType>())
    Left = LeftRefType->getPointeeType();
  if (const auto *RightRefType = Right->getAs<ReferenceType>())
    Right = RightRefType->getPointeeType();
  return Left->getCanonicalTypeUnqualified() ==
         Right->getCanonicalTypeUnqualified();
}

void InefficientAlgorithmCheck::registerMatchers(MatchFinder *Finder) {
  // Only register the matchers for C++; the functionality currently does not
  // provide any benefit to other languages, despite being benign.
  if (!getLangOpts().CPlusPlus)
    return;

  const auto Algorithms =
      hasAnyName("::std::find", "::std::count", "::std::equal_range",
                 "::std::lower_bound", "::std::upper_bound");
  const auto ContainerMatcher = classTemplateSpecializationDecl(hasAnyName(
      "::std::set", "::std::map", "::std::multiset", "::std::multimap",
      "::std::unordered_set", "::std::unordered_map"));

  const auto Matcher =
      callExpr(
          callee(functionDecl(Algorithms)),
          hasArgument(
              0, cxxConstructExpr(has(cxxMemberCallExpr(
                     callee(cxxMethodDecl(hasName("begin"))),
                     on(declRefExpr(
                            hasDeclaration(decl().bind("IneffContObj")),
                            anyOf(hasType(ContainerMatcher.bind("IneffCont")),
                                  hasType(pointsTo(
                                      ContainerMatcher.bind("IneffContPtr")))))
                            .bind("IneffContExpr")))))),
          hasArgument(1, cxxConstructExpr(has(cxxMemberCallExpr(
                             callee(cxxMethodDecl(hasName("end"))),
                             on(declRefExpr(hasDeclaration(
                                 equalsBoundNode("IneffContObj")))))))),
          hasArgument(2, expr().bind("AlgParam")),
          unless(isInTemplateInstantiation()))
          .bind("IneffAlg");

  Finder->addMatcher(Matcher, this);
}

void InefficientAlgorithmCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *AlgCall = Result.Nodes.getNodeAs<CallExpr>("IneffAlg");
  const auto *IneffCont =
      Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("IneffCont");
  bool PtrToContainer = false;
  if (!IneffCont) {
    IneffCont =
        Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("IneffContPtr");
    PtrToContainer = true;
  }
  const llvm::StringRef IneffContName = IneffCont->getName();
  const bool Unordered =
      IneffContName.find("unordered") != llvm::StringRef::npos;
  const bool Maplike = IneffContName.find("map") != llvm::StringRef::npos;

  // Store if the key type of the container is compatible with the value
  // that is searched for.
  QualType ValueType = AlgCall->getArg(2)->getType();
  QualType KeyType =
      IneffCont->getTemplateArgs()[0].getAsType().getCanonicalType();
  const bool CompatibleTypes = areTypesCompatible(KeyType, ValueType);

  // Check if the comparison type for the algorithm and the container matches.
  if (AlgCall->getNumArgs() == 4 && !Unordered) {
    const Expr *Arg = AlgCall->getArg(3);
    const QualType AlgCmp =
        Arg->getType().getUnqualifiedType().getCanonicalType();
    const unsigned CmpPosition =
        (IneffContName.find("map") == llvm::StringRef::npos) ? 1 : 2;
    const QualType ContainerCmp = IneffCont->getTemplateArgs()[CmpPosition]
                                      .getAsType()
                                      .getUnqualifiedType()
                                      .getCanonicalType();
    if (AlgCmp != ContainerCmp) {
      diag(Arg->getLocStart(),
           "different comparers used in the algorithm and the container");
      return;
    }
  }

  const auto *AlgDecl = AlgCall->getDirectCallee();
  if (!AlgDecl)
    return;

  if (Unordered && AlgDecl->getName().find("bound") != llvm::StringRef::npos)
    return;

  const auto *AlgParam = Result.Nodes.getNodeAs<Expr>("AlgParam");
  const auto *IneffContExpr = Result.Nodes.getNodeAs<Expr>("IneffContExpr");
  FixItHint Hint;

  SourceManager &SM = *Result.SourceManager;
  LangOptions LangOpts = Result.Context->getLangOpts();

  CharSourceRange CallRange =
      CharSourceRange::getTokenRange(AlgCall->getSourceRange());

  // FIXME: Create a common utility to extract a file range that the given token
  // sequence is exactly spelled at (without macro argument expansions etc.).
  // We can't use Lexer::makeFileCharRange here, because for
  //
  //   #define F(x) x
  //   x(a b c);
  //
  // it will return "x(a b c)", when given the range "a"-"c". It makes sense for
  // removals, but not for replacements.
  //
  // This code is over-simplified, but works for many real cases.
  if (SM.isMacroArgExpansion(CallRange.getBegin()) &&
      SM.isMacroArgExpansion(CallRange.getEnd())) {
    CallRange.setBegin(SM.getSpellingLoc(CallRange.getBegin()));
    CallRange.setEnd(SM.getSpellingLoc(CallRange.getEnd()));
  }

  if (!CallRange.getBegin().isMacroID() && !Maplike && CompatibleTypes) {
    StringRef ContainerText = Lexer::getSourceText(
        CharSourceRange::getTokenRange(IneffContExpr->getSourceRange()), SM,
        LangOpts);
    StringRef ParamText = Lexer::getSourceText(
        CharSourceRange::getTokenRange(AlgParam->getSourceRange()), SM,
        LangOpts);
    std::string ReplacementText =
        (llvm::Twine(ContainerText) + (PtrToContainer ? "->" : ".") +
         AlgDecl->getName() + "(" + ParamText + ")")
            .str();
    Hint = FixItHint::CreateReplacement(CallRange, ReplacementText);
  }

  diag(AlgCall->getLocStart(),
       "this STL algorithm call should be replaced with a container method")
      << Hint;
}

} // namespace misc
} // namespace tidy
} // namespace clang
<|endoftext|>


<commit_before>/*
sound.cpp: sound handling class.
 * By 2MB Solutions: https//2mb.solutions
 * Released under the MIT license. See license.txt for details.
 * Billy: https://stormdragon.tk/
 * Michael: https://michaeltaboada.me
 * */
#include "sound.h"
int sound::sounds=0;
ALLEGRO_VOICE* sound::voice = NULL;
map<string, ALLEGRO_MIXER*> sound::mixers;
map<string, ALLEGRO_SAMPLE*> sound::samples;

sound::sound(void)
{
	if(!al_is_audio_installed()) {
		al_install_audio();
		al_init_acodec_addon();
	}
	sounds++;
	si = NULL;
	looping = false;
	panval=0;
	gainval=0;
	pitchval=100;
	paused=false;
	active=false;
	if(mixers.find("default")==mixers.end()) {
		ALLEGRO_MIXER* m = NULL;
		m = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
		if(!m) {
			log("Default mixer could not be created!\n");
		return;
		}
		mixers.insert(pair<string, ALLEGRO_MIXER*>("default", m));
		if(voice) {
			if(!al_attach_mixer_to_voice(mixers.find("default")->second, voice)) {
				log("Could not attach default mixer to default voice!\n");
			}
		}
	}
	if(!voice) {
		ALLEGRO_VOICE* v = NULL;
		v = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
		if(!v) {
			log("Default voice could not be created!\n");
			return;
		}
		voice=v;
		if(!al_attach_mixer_to_voice(mixers.find("default")->second, voice)) {
			log("Could not attach default mixer to default voice!\n");
			return;
		}
	}
}

sound::~sound(void)
{
	sounds--;
	stop();
	if(si) {
		al_destroy_sample_instance(si);
	}
	if(sounds==0) {
		map<string, ALLEGRO_SAMPLE*>::iterator it= samples.begin();
		while(it!=samples.end()) {
			al_destroy_sample(it->second);
			samples.erase(it++);
		}
		map<string, ALLEGRO_MIXER*>::iterator it2= mixers.begin();
		while(it2!=mixers.end()) {
			al_destroy_mixer(it2->second);
			mixers.erase(it2++);
		}
		if(voice) {
			al_destroy_voice(voice);
			voice=NULL;
		}
	}
}

void sound::log(string s) {
//	printf(s.c_str());
}

/**
*Stop the sound.
*@return Whether the sound was successfully stopped.
**/
bool sound::stop() {
	if(si) {
		return al_stop_sample_instance(si);
	}
	else {
		return false;
	}
	return false;
}

/**
*Load a file into the sound.
*@return Whether the sound was successfully loaded.
**/
bool sound::load(string file/**< [in] The file to load.**/, string mixer/**< [in] The mixer name to put  the sound on, can be excluded, which adds it to the default mixer.**/) {
	if(mixers.find(mixer)==mixers.end()) {
		ALLEGRO_MIXER* m = NULL;
		m = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
		if(!m) {
			log("Could not create mixer "+mixer+"!\n");
			return false;
		}
		mixers.insert(pair<string, ALLEGRO_MIXER*>(mixer, m));
	}
	if(!voice) {
		ALLEGRO_VOICE* v = NULL;
		v=al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
		if(!v) {
			log("Could not create default voice!\n");
			return false;
		}
		voice=v;
		if(!al_attach_mixer_to_voice(mixers.find(mixer)->second, voice)) {
			log("Could not attach mixer "+mixer+" to default voice!\n");
			return false;
		}
	}
	if(samples.find(file)==samples.end()) {
		ALLEGRO_SAMPLE* s=NULL;
		s = al_load_sample(((string)(al_path_cstr(al_get_standard_path(ALLEGRO_RESOURCES_PATH), '/'))+file).c_str());
		if(!s) {
			log("Could not load file "+file+"!\n");
			return false;
		}
		samples.insert(pair<string, ALLEGRO_SAMPLE*>(file, s));
	}
	if(si) {
		al_destroy_sample_instance(si);
	}
	si = al_create_sample_instance(samples.find(file)->second);
	if(!si) {
		log("could not create sample instance!\n");
		return false;
	}
	if(!al_attach_sample_instance_to_mixer(si, mixers.find(mixer)->second)) {
		log("Could not attach the sample instance to the "+mixer+" mixer!\n");
		return false;
	}
	active=true;
	return true;
}

double sound::dB2lin( double dB ) {
	static const double DB_2_LOG = 0.11512925464970228420089957273422; // ln( 10 ) / 20
	return exp( dB * DB_2_LOG );
}

double sound::pan(double doubleval)
{
	float new_pan=doubleval;
	if(new_pan<-100)
		new_pan=-100;
	if(new_pan>100)
		new_pan=100;
	new_pan=0-(fabs(new_pan));
	new_pan=dB2lin(new_pan);
	new_pan=1.0-new_pan;
	if(doubleval<0)
		new_pan=0-new_pan;
	else
		new_pan=fabs(new_pan);
	if(new_pan<-1)
		new_pan=-1;
	if(new_pan>1)
		new_pan=1;
	return new_pan;
}

/**
*Gets the pan.
*@return The pan in decibel.
**/
double sound::get_pan() {
	return panval;
}

/**
*Sets the pan in decibel.
*@return Whether the pan was successfully set.
**/
bool sound::set_pan(double pan_value/**< [in] The pan in decibel.**/) {
	if(pan_value < -100) {
		pan_value = -100;
	}
	else if(pan_value >100) {
		pan_value=100;
	}
	double linpan = pan(pan_value);
	if(si) {
		if(!al_set_sample_instance_pan(si, linpan)) {
			return false;
		}
	}
	else {
		return false;
	}
	panval=pan_value;
	return true;
}

/**
*Check the gain of the sound.
*@return The gain.
**/
double sound::get_gain() {
	return gainval;
}

/**
*Set the gain of the sound in decibel.
*@return Whether the gain was successfully set.
**/
bool sound::set_gain(double gain/**< [in] The gain in decibel.**/) {
	if(gain < -100) {
		gain = -100;
	}
	else if(gain > 0) {
		gain = 0;
	}
	if(si) {
		double new_gain = dB2lin(gain);
		if(al_get_channel_count(al_get_sample_instance_channels(si)) == 1) {
		new_gain = new_gain*sqrt(2);
		}
		if(!al_set_sample_instance_gain(si, new_gain)) {
			return false;
		}
	}
	else {
		return false;
	}
	gainval=gain;
	return true;
}

/**
*Get the pitch in decibel.
*@return The pitch.
**/
double sound::get_pitch() {
	return pitchval;
}

/**
*Set the pitch.
*@return Whether the pitch was successfully set.
**/
bool sound::set_pitch(double pitch/**< [in] The pitch in decibel.**/) {
	if(pitch < 1) {
		pitch=1;
	}
	if(si) {
		if(!al_set_sample_instance_speed(si, pitch/100.0)) {
			return false;
		}
	}
	else {
		return false;
	}
	pitchval=pitch;
	return true;
}

/**
*Check whether the sound loops.
*@return Whether hte file loops.
**/
bool sound::get_loop() {
	return looping;
}

/**
*Set the file to loop or not.
*@return Whether the looping value was successfully set.
**/
bool sound::set_loop(bool loop/**< [in] Should the file loop?**/) {
	if(si) {
		if(loop) {
			if(!al_set_sample_instance_playmode(si, ALLEGRO_PLAYMODE_LOOP)) {
				return false;
			}
		}
		else {
			if(!al_set_sample_instance_playmode(si, ALLEGRO_PLAYMODE_ONCE)) {
				return false;
			}
		}
	}
	else {
		return false;
	}
	looping=loop;
	return true;
}

/**
*Play the file.
*@return Whether the file was successfully started playing.
**/
bool sound::play() {
	if(si) {
		if(paused) {
			paused = !al_set_sample_instance_playing(si, true);
			return !paused;
		}
		bool p =  al_play_sample_instance(si);
this->set_gain(gainval);
	      	return p;
	}
	else {
		return false;
	}
	return false;
}

/**
*Check whether the sound is playing.
*@return Whether the sound is playing.
**/
bool sound::is_playing() {
	if(si) {
		return al_get_sample_instance_playing(si);
	}
	else {
		return false;
	}
	return false;
}

/**
*Pause the sound.
*@return Whether the sound is paused.
**/
bool sound::pause() {
	if(si) {
		if(paused) {
			return true;
		}
		else {
			paused = !al_set_sample_instance_playing(si, false);
			return !paused;
		}
	}
	else {
		return false;
	}
	return false;
}

/**
*Check whether the sound is paused.
*@return Whether the sound is paused.
**/
bool sound::get_paused() {
	return paused;
}

/**
*Check whether the sound has a file loaded into it.
*@return Whether the sound is active.
**/
bool sound::get_active() {
	return active;
}
<commit_msg>Hopefully updated sound.cpp for windows.<commit_after>/*
sound.cpp: sound handling class.
 * By 2MB Solutions: https//2mb.solutions
 * Released under the MIT license. See license.txt for details.
 * Billy: https://stormdragon.tk/
 * Michael: https://michaeltaboada.me
 * */
#include "sound.h"
int sound::sounds=0;
ALLEGRO_VOICE* sound::voice = NULL;
map<string, ALLEGRO_MIXER*> sound::mixers;
map<string, ALLEGRO_SAMPLE*> sound::samples;

sound::sound(void)
{
	if(!al_is_audio_installed()) {
		al_install_audio();
		al_init_acodec_addon();
	}
	sounds++;
	si = NULL;
	looping = false;
	panval=0;
	gainval=0;
	pitchval=100;
	paused=false;
	active=false;
	if(mixers.find("default")==mixers.end()) {
		ALLEGRO_MIXER* m = NULL;
		m = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
		if(!m) {
			log("Default mixer could not be created!\n");
		return;
		}
		mixers.insert(pair<string, ALLEGRO_MIXER*>("default", m));
		if(voice) {
			if(!al_attach_mixer_to_voice(mixers.find("default")->second, voice)) {
				log("Could not attach default mixer to default voice!\n");
			}
		}
	}
	if(!voice) {
		ALLEGRO_VOICE* v = NULL;
		v = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
		if(!v) {
			log("Default voice could not be created!\n");
			return;
		}
		voice=v;
		if(!al_attach_mixer_to_voice(mixers.find("default")->second, voice)) {
			log("Could not attach default mixer to default voice!\n");
			return;
		}
	}
}

sound::~sound(void)
{
	sounds--;
	stop();
	if(si) {
		al_destroy_sample_instance(si);
	}
	if(sounds==0) {
		map<string, ALLEGRO_SAMPLE*>::iterator it= samples.begin();
		while(it!=samples.end()) {
			al_destroy_sample(it->second);
			samples.erase(it++);
		}
		map<string, ALLEGRO_MIXER*>::iterator it2= mixers.begin();
		while(it2!=mixers.end()) {
			al_destroy_mixer(it2->second);
			mixers.erase(it2++);
		}
		if(voice) {
			al_destroy_voice(voice);
			voice=NULL;
		}
	}
}

void sound::log(string s) {
//	printf(s.c_str());
}

/**
*Stop the sound.
*@return Whether the sound was successfully stopped.
**/
bool sound::stop() {
	if(si) {
		return al_stop_sample_instance(si);
	}
	else {
		return false;
	}
	return false;
}

/**
*Load a file into the sound.
*@return Whether the sound was successfully loaded.
**/
bool sound::load(string file/**< [in] The file to load.**/, string mixer/**< [in] The mixer name to put  the sound on, can be excluded, which adds it to the default mixer.**/) {
	if(mixers.find(mixer)==mixers.end()) {
		ALLEGRO_MIXER* m = NULL;
		m = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
		if(!m) {
			log("Could not create mixer "+mixer+"!\n");
			return false;
		}
		mixers.insert(pair<string, ALLEGRO_MIXER*>(mixer, m));
	}
	if(!voice) {
		ALLEGRO_VOICE* v = NULL;
		v=al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
		if(!v) {
			log("Could not create default voice!\n");
			return false;
		}
		voice=v;
		if(!al_attach_mixer_to_voice(mixers.find(mixer)->second, voice)) {
			log("Could not attach mixer "+mixer+" to default voice!\n");
			return false;
		}
	}
	if(samples.find(file)==samples.end()) {
		ALLEGRO_SAMPLE* s=NULL;
		s = al_load_sample(((string)(al_path_cstr(al_get_standard_path(ALLEGRO_RESOURCES_PATH), '/'))+file).c_str());
		if(!s) {
			log("Could not load file "+file+"!\n");
			return false;
		}
		samples.insert(pair<string, ALLEGRO_SAMPLE*>(file, s));
	}
	if(si) {
		al_destroy_sample_instance(si);
	}
	si = al_create_sample_instance(samples.find(file)->second);
	if(!si) {
		log("could not create sample instance!\n");
		return false;
	}
	if(!al_attach_sample_instance_to_mixer(si, mixers.find(mixer)->second)) {
		log("Could not attach the sample instance to the "+mixer+" mixer!\n");
		return false;
	}
	active=true;
	return true;
}

double sound::dB2lin( double dB ) {
	static const double DB_2_LOG = 0.11512925464970228420089957273422; // ln( 10 ) / 20
	return exp( dB * DB_2_LOG );
}

double sound::pan(double doubleval)
{
	float new_pan=doubleval;
	if(new_pan<-100)
		new_pan=-100;
	if(new_pan>100)
		new_pan=100;
	new_pan=0-(fabs(new_pan));
	new_pan=dB2lin(new_pan);
	new_pan=1.0-new_pan;
	if(doubleval<0)
		new_pan=0-new_pan;
	else
		new_pan=fabs(new_pan);
	if(new_pan<-1)
		new_pan=-1;
	if(new_pan>1)
		new_pan=1;
	return new_pan;
}

/**
*Gets the pan.
*@return The pan in decibel.
**/
double sound::get_pan() {
	return panval;
}

/**
*Sets the pan in decibel.
*@return Whether the pan was successfully set.
**/
bool sound::set_pan(double pan_value/**< [in] The pan in decibel.**/) {
	if(pan_value < -100) {
		pan_value = -100;
	}
	else if(pan_value >100) {
		pan_value=100;
	}
	double linpan = pan(pan_value);
	if(si) {
		if(!al_set_sample_instance_pan(si, linpan)) {
			return false;
		}
	}
	else {
		return false;
	}
	panval=pan_value;
	return true;
}

/**
*Check the gain of the sound.
*@return The gain.
**/
double sound::get_gain() {
	return gainval;
}

/**
*Set the gain of the sound in decibel.
*@return Whether the gain was successfully set.
**/
bool sound::set_gain(double gain/**< [in] The gain in decibel.**/) {
	if(gain < -100) {
		gain = -100;
	}
	else if(gain > 0) {
		gain = 0;
	}
	if(si) {
		double new_gain = dB2lin(gain);
#ifdef __gnu_linux__
		if(al_get_channel_count(al_get_sample_instance_channels(si)) == 1) {
		new_gain = new_gain*sqrt(2);
		}
#endif
		if(!al_set_sample_instance_gain(si, new_gain)) {
			return false;
		}
	}
	else {
		return false;
	}
	gainval=gain;
	return true;
}

/**
*Get the pitch in decibel.
*@return The pitch.
**/
double sound::get_pitch() {
	return pitchval;
}

/**
*Set the pitch.
*@return Whether the pitch was successfully set.
**/
bool sound::set_pitch(double pitch/**< [in] The pitch in decibel.**/) {
	if(pitch < 1) {
		pitch=1;
	}
	if(si) {
		if(!al_set_sample_instance_speed(si, pitch/100.0)) {
			return false;
		}
	}
	else {
		return false;
	}
	pitchval=pitch;
	return true;
}

/**
*Check whether the sound loops.
*@return Whether hte file loops.
**/
bool sound::get_loop() {
	return looping;
}

/**
*Set the file to loop or not.
*@return Whether the looping value was successfully set.
**/
bool sound::set_loop(bool loop/**< [in] Should the file loop?**/) {
	if(si) {
		if(loop) {
			if(!al_set_sample_instance_playmode(si, ALLEGRO_PLAYMODE_LOOP)) {
				return false;
			}
		}
		else {
			if(!al_set_sample_instance_playmode(si, ALLEGRO_PLAYMODE_ONCE)) {
				return false;
			}
		}
	}
	else {
		return false;
	}
	looping=loop;
	return true;
}

/**
*Play the file.
*@return Whether the file was successfully started playing.
**/
bool sound::play() {
	if(si) {
		if(paused) {
			paused = !al_set_sample_instance_playing(si, true);
			return !paused;
		}
		bool p =  al_play_sample_instance(si);
this->set_gain(gainval);
	      	return p;
	}
	else {
		return false;
	}
	return false;
}

/**
*Check whether the sound is playing.
*@return Whether the sound is playing.
**/
bool sound::is_playing() {
	if(si) {
		return al_get_sample_instance_playing(si);
	}
	else {
		return false;
	}
	return false;
}

/**
*Pause the sound.
*@return Whether the sound is paused.
**/
bool sound::pause() {
	if(si) {
		if(paused) {
			return true;
		}
		else {
			paused = !al_set_sample_instance_playing(si, false);
			return !paused;
		}
	}
	else {
		return false;
	}
	return false;
}

/**
*Check whether the sound is paused.
*@return Whether the sound is paused.
**/
bool sound::get_paused() {
	return paused;
}

/**
*Check whether the sound has a file loaded into it.
*@return Whether the sound is active.
**/
bool sound::get_active() {
	return active;
}
<|endoftext|>


<commit_before><commit_msg>sw: export fieldmark of postit fields if possible<commit_after><|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      main.cpp
  \authors     (rdo@rk9.bmstu.ru)
  \authors     (lord.tiran@gmail.com)
  \authors     (robot.xet@gmail.com)
  \date      13.07.2009
  \brief       RDOValue
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <iostream>
#include <boost/regex.hpp>
#define BOOST_TEST_MODULE RDOValue_Test
#include <boost/test/included/unit_test.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_runtime.h"
#include "simulator/runtime/rdo_res_type.h"
// --------------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE(RDOValue_Test)

BOOST_AUTO_TEST_CASE(RDOValue_String)
{
	const tstring str1 = _T("qqq");
	rdoRuntime::RDOValue value1(str1);
	BOOST_CHECK(value1.getString  () == str1);
	BOOST_CHECK(value1.getAsString() == str1);

	rdoRuntime::RDOValue value2 = value1;
	BOOST_CHECK(value2.getString  () == str1);
	BOOST_CHECK(value2.getAsString() == str1);
	BOOST_CHECK(value2 == value1);

	const tstring str2 = _T("aaa");
	value2 += str2;
	BOOST_CHECK(value2.getString  () == str1 + str2);
	BOOST_CHECK(value2.getAsString() == str1 + str2);
}

BOOST_AUTO_TEST_CASE(RDOValue_Rsint_Arifmethic)
{
	const rsint val1 = 30;
	rdoRuntime::RDOValue value1(val1);
	BOOST_CHECK(value1.getInt() == val1);

	rdoRuntime::RDOValue value2 = value1;
	BOOST_CHECK(value2 == val1);
	BOOST_CHECK(value2 == value1);

	const rsint val2 = 20;
	value1 += val2;
	BOOST_CHECK(value1 == val1 + val2);

	const rsint val3 = 10;
	value1 -= val3;
	BOOST_CHECK(value1 == val1 + val2 - val3);

	const rsint val4 = 2;
	value2 = value1;
	value2 *= val4;
	BOOST_CHECK(value2 == (val1 + val2 - val3) * val4);

	const rsint val5 = 5;
	value2 = value1;
	value2 /= val5;
	BOOST_CHECK(value2 == ((val1 + val2 - val3) * val4) / val5);

	value2 = value1;
	value2 --;
	BOOST_CHECK(value2 == value1 - 1);
	value2 ++;
	BOOST_CHECK(value2 == value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Rsint_Compare)
{
	const rsint val1 = 30;
	const rsint val2 = 20;
	rdoRuntime::RDOValue value1(val1);
	rdoRuntime::RDOValue value2(val2);

	BOOST_CHECK(value1 != value2);
	BOOST_CHECK(value1 > value2);
	BOOST_CHECK(value2 < value1);
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
	value2 = val1;
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Ruint_Arifmethic)
{
	const ruint val1 = 30;
	rdoRuntime::RDOValue value1(val1);
	BOOST_CHECK(value1 == val1);
	//BOOST_CHECK(value1.getUInt() == val1);

	rdoRuntime::RDOValue value2 = value1;
	BOOST_CHECK(value2 == val1);
	BOOST_CHECK(value2 == value1);

	const ruint val2 = 20;
	value1 += val2;
	BOOST_CHECK(value1 == val1 + val2);

	const ruint val3 = 10;
	value1 -= val3;
	BOOST_CHECK(value1 == val1 + val2 - val3);

	const ruint val4 = 2;
	value2 = value1;
	value2 *= val4;
	BOOST_CHECK(value2 == (val1 + val2 - val3) * val4);

	const ruint val5 = 5;
	value2 = value1;
	value2 /= val5;
	BOOST_CHECK(value2 == ((val1 + val2 - val3) * val4) / val5);

	value2 = value1;
	value2 --;
	BOOST_CHECK(value2 == value1 - 1);
	value2 ++;
	BOOST_CHECK(value2 == value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Ruint_Compare)
{
	const ruint val1 = 30;
	const ruint val2 = 20;
	rdoRuntime::RDOValue value1(val1);
	rdoRuntime::RDOValue value2(val2);

	BOOST_CHECK(value1 != value2);
	BOOST_CHECK(value1 > value2);
	BOOST_CHECK(value2 < value1);
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
	value2 = val1;
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Double_Arifmethic)
{
	const double doub1 = 30.2;
	rdoRuntime::RDOValue value1(doub1);
	BOOST_CHECK(value1 == doub1);
	//BOOST_CHECK(value1.getDouble() == doub1);

	rdoRuntime::RDOValue value2 = value1;
	BOOST_CHECK(value2 == doub1);
	BOOST_CHECK(value2 == value1);

	const double doub2 = 20.5;
	value1 += doub2;
	BOOST_CHECK(value1 == doub1 + doub2);

	const double doub3 = 10.3;
	value1 -= doub3;
	BOOST_CHECK(value1 == doub1 + doub2 - doub3);

	const double doub4 = 2.5;
	value2 = value1;
	value2 *= doub4;
	BOOST_CHECK(value2 == (doub1 + doub2 - doub3) * doub4);

	const double doub5 = 5;
	value2 = value1;
	value2 /= doub5;
	BOOST_CHECK(value2 == ((doub1 + doub2 - doub3) * doub4) / doub5);

	value2 = value1;
	value2 --;
	BOOST_CHECK(value2 == value1 - 1);
	value2 ++;
	BOOST_CHECK(value2 == value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Double_Compare)
{
	const double doub1 = 30.2;
	const double doub2 = 20.5;
	rdoRuntime::RDOValue value1(doub1);
	rdoRuntime::RDOValue value2(doub2);

	BOOST_CHECK(value1 != value2);
	BOOST_CHECK(value1 > value2);
	BOOST_CHECK(value2 < value1);
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
	value2 = doub1;
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Bool)
{
	rbool bool1 = true;
	rbool bool2 = false;
	rbool bool3 = true;
	rbool bool4 = false;

	rdoRuntime::RDOValue value1(bool1);
	rdoRuntime::RDOValue value2(bool2);
	rdoRuntime::RDOValue value3(bool3);
	rdoRuntime::RDOValue value4(bool4);

	BOOST_CHECK(value1.getBool());
	BOOST_CHECK(!value2);
	BOOST_CHECK(value2 == value4);
	BOOST_CHECK(value1 != value2);
	BOOST_CHECK(!(value1 == value2));
	BOOST_CHECK(value1 && value3);
	BOOST_CHECK(!(value2 && value3));
	BOOST_CHECK(value1 || value2);
	BOOST_CHECK(!(value2 || value4));
}

BOOST_AUTO_TEST_CASE(RDOValue_Char)
{
	tchar ch1 = 'a';
	tchar ch2 = 'b';
	rdoRuntime::RDOValue value1 = ch1;
	rdoRuntime::RDOValue value2 = ch2;
	BOOST_CHECK(value1 == ch1);
	BOOST_CHECK(value1 < value2);
	BOOST_CHECK(value2 > value1);
	BOOST_CHECK(value1 != value2);
	value1 = value2;
	BOOST_CHECK(value1 == value2);
}
/*
BOOST_AUTO_TEST_CASE(RDOValue_Enum)
{
	using namespace rdoRuntime;

	LPRDOEnumType pEnum = rdo::Factory<RDOEnumType>::create();
	BOOST_CHECK(pEnum);

}
*/
/*
BOOST_AUTO_TEST_CASE(RDOValue_Identificator)
{

}
*/
BOOST_AUTO_TEST_CASE(RDOValue_Resource)
{
	using namespace rdoRuntime;

	LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create();
	BOOST_CHECK(pRuntime);

	LPRDOResourceType pResourceType = rdo::Factory<RDOResourceType>::create(0);
	BOOST_CHECK(pResourceType);
	LPIResourceType pResourceFactory = pResourceType.interface_cast<IResourceType>();
	BOOST_CHECK(pResourceFactory);

	std::vector<RDOValue> paramList;
	paramList.push_back(RDOValue(1      ));
	paramList.push_back(RDOValue(2.2    ));
	paramList.push_back(RDOValue(_T("3")));

	LPRDOResource pResource = pResourceFactory->createRes(pRuntime, pRuntime->getResourceId(), paramList, true, true);
	BOOST_CHECK(pResource);

	RDOValue value1(pResourceType, pResource);

	LPRDOResourceType pType = value1.type().object_dynamic_cast<RDOResourceType>();
	BOOST_CHECK(pType);

	LPRDOResource pResource1 = value1.getPointer<RDOResource>();

	pRuntime   = NULL;
	value1     = RDOValue();
	pResource1 = NULL;

	BOOST_CHECK(pResource.owner());

	pResource = NULL;
}

BOOST_AUTO_TEST_SUITE_END() //RDOValue_Resource
<commit_msg> - исправлена ошибка в тестах rsint, ruint, double<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      main.cpp
  \authors     (rdo@rk9.bmstu.ru)
  \authors     (lord.tiran@gmail.com)
  \authors     (robot.xet@gmail.com)
  \date      13.07.2009
  \brief       RDOValue
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <iostream>
#include <boost/regex.hpp>
#define BOOST_TEST_MODULE RDOValue_Test
#include <boost/test/included/unit_test.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_runtime.h"
#include "simulator/runtime/rdo_res_type.h"
// --------------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE(RDOValue_Test)

BOOST_AUTO_TEST_CASE(RDOValue_String)
{
	const tstring str1 = _T("qqq");
	rdoRuntime::RDOValue value1(str1);
	BOOST_CHECK(value1.getString  () == str1);
	BOOST_CHECK(value1.getAsString() == str1);

	rdoRuntime::RDOValue value2 = value1;
	BOOST_CHECK(value2.getString  () == str1);
	BOOST_CHECK(value2.getAsString() == str1);
	BOOST_CHECK(value2 == value1);

	const tstring str2 = _T("aaa");
	value2 += str2;
	BOOST_CHECK(value2.getString  () == str1 + str2);
	BOOST_CHECK(value2.getAsString() == str1 + str2);
}

BOOST_AUTO_TEST_CASE(RDOValue_Rsint_Arifmethic)
{
	const rsint val1 = 30;
	rdoRuntime::RDOValue value1(val1);
	BOOST_CHECK(value1.getInt() == val1);

	rdoRuntime::RDOValue value2 = value1;
	BOOST_CHECK(value2 == val1);
	BOOST_CHECK(value2 == value1);

	const rsint val2 = 20;
	value1 += val2;
	BOOST_CHECK(value1 == val1 + val2);

	const rsint val3 = 10;
	value1 -= val3;
	BOOST_CHECK(value1 == val1 + val2 - val3);

	const rsint val4 = 2;
	value2 = value1;
	value2 *= val4;
	BOOST_CHECK(value2 == (val1 + val2 - val3) * val4);

	const rsint val5 = 5;
	value2 = value1;
	value2 /= val5;
	BOOST_CHECK(value2 == ((val1 + val2 - val3) / val5));

	value2 = value1;
	value2 --;
	BOOST_CHECK(value2 == value1 - 1);
	value2 ++;
	BOOST_CHECK(value2 == value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Rsint_Compare)
{
	const rsint val1 = 30;
	const rsint val2 = 20;
	rdoRuntime::RDOValue value1(val1);
	rdoRuntime::RDOValue value2(val2);

	BOOST_CHECK(value1 != value2);
	BOOST_CHECK(value1 > value2);
	BOOST_CHECK(value2 < value1);
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
	value2 = val1;
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Ruint_Arifmethic)
{
	const ruint val1 = 30;
	rdoRuntime::RDOValue value1(val1);
	BOOST_CHECK(value1 == val1);
	//BOOST_CHECK(value1.getUInt() == val1);

	rdoRuntime::RDOValue value2 = value1;
	BOOST_CHECK(value2 == val1);
	BOOST_CHECK(value2 == value1);

	const ruint val2 = 20;
	value1 += val2;
	BOOST_CHECK(value1 == val1 + val2);

	const ruint val3 = 10;
	value1 -= val3;
	BOOST_CHECK(value1 == val1 + val2 - val3);

	const ruint val4 = 2;
	value2 = value1;
	value2 *= val4;
	BOOST_CHECK(value2 == (val1 + val2 - val3) * val4);

	const ruint val5 = 5;
	value2 = value1;
	value2 /= val5;
	BOOST_CHECK(value2 == ((val1 + val2 - val3) / val5));

	value2 = value1;
	value2 --;
	BOOST_CHECK(value2 == value1 - 1);
	value2 ++;
	BOOST_CHECK(value2 == value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Ruint_Compare)
{
	const ruint val1 = 30;
	const ruint val2 = 20;
	rdoRuntime::RDOValue value1(val1);
	rdoRuntime::RDOValue value2(val2);

	BOOST_CHECK(value1 != value2);
	BOOST_CHECK(value1 > value2);
	BOOST_CHECK(value2 < value1);
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
	value2 = val1;
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Double_Arifmethic)
{
	const double doub1 = 30.2;
	rdoRuntime::RDOValue value1(doub1);
	BOOST_CHECK(value1 == doub1);
	//BOOST_CHECK(value1.getDouble() == doub1);

	rdoRuntime::RDOValue value2 = value1;
	BOOST_CHECK(value2 == doub1);
	BOOST_CHECK(value2 == value1);

	const double doub2 = 20.5;
	value1 += doub2;
	BOOST_CHECK(value1 == doub1 + doub2);

	const double doub3 = 10.3;
	value1 -= doub3;
	BOOST_CHECK(value1 == doub1 + doub2 - doub3);

	const double doub4 = 2.5;
	value2 = value1;
	value2 *= doub4;
	BOOST_CHECK(value2 == (doub1 + doub2 - doub3) * doub4);

	const double doub5 = 5;
	value2 = value1;
	value2 /= doub5;
	BOOST_CHECK(value2 == ((doub1 + doub2 - doub3) / doub5));

	value2 = value1;
	value2 --;
	BOOST_CHECK(value2 == value1 - 1);
	value2 ++;
	BOOST_CHECK(value2 == value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Double_Compare)
{
	const double doub1 = 30.2;
	const double doub2 = 20.5;
	rdoRuntime::RDOValue value1(doub1);
	rdoRuntime::RDOValue value2(doub2);

	BOOST_CHECK(value1 != value2);
	BOOST_CHECK(value1 > value2);
	BOOST_CHECK(value2 < value1);
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
	value2 = doub1;
	BOOST_CHECK(value1 >= value2);
	BOOST_CHECK(value2 <= value1);
}

BOOST_AUTO_TEST_CASE(RDOValue_Bool)
{
	rbool bool1 = true;
	rbool bool2 = false;
	rbool bool3 = true;
	rbool bool4 = false;

	rdoRuntime::RDOValue value1(bool1);
	rdoRuntime::RDOValue value2(bool2);
	rdoRuntime::RDOValue value3(bool3);
	rdoRuntime::RDOValue value4(bool4);

	BOOST_CHECK(value1.getBool());
	BOOST_CHECK(!value2);
	BOOST_CHECK(value2 == value4);
	BOOST_CHECK(value1 != value2);
	BOOST_CHECK(!(value1 == value2));
	BOOST_CHECK(value1 && value3);
	BOOST_CHECK(!(value2 && value3));
	BOOST_CHECK(value1 || value2);
	BOOST_CHECK(!(value2 || value4));
}

BOOST_AUTO_TEST_CASE(RDOValue_Char)
{
	tchar ch1 = 'a';
	tchar ch2 = 'b';
	rdoRuntime::RDOValue value1 = ch1;
	rdoRuntime::RDOValue value2 = ch2;
	BOOST_CHECK(value1 == ch1);
	BOOST_CHECK(value1 < value2);
	BOOST_CHECK(value2 > value1);
	BOOST_CHECK(value1 != value2);
	value1 = value2;
	BOOST_CHECK(value1 == value2);
}

BOOST_AUTO_TEST_CASE(RDOValue_Enum)
{
	using namespace rdoRuntime;
	RDOEnumType::EnumItem item1 = "test1";
	BOOST_CHECK(item1 == "test1");
	RDOEnumType::Enums enum1;
	enum1.push_back(item1);
	BOOST_CHECK(enum1[0] == item1);

	LPRDOEnumType pEnum = rdo::Factory<RDOEnumType>::create();
	BOOST_CHECK(pEnum);
	BOOST_CHECK(pEnum->empty());

}

/*
BOOST_AUTO_TEST_CASE(RDOValue_Identificator)
{

}
*/
BOOST_AUTO_TEST_CASE(RDOValue_Resource)
{
	using namespace rdoRuntime;

	LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create();
	BOOST_CHECK(pRuntime);

	LPRDOResourceType pResourceType = rdo::Factory<RDOResourceType>::create(0);
	BOOST_CHECK(pResourceType);
	LPIResourceType pResourceFactory = pResourceType.interface_cast<IResourceType>();
	BOOST_CHECK(pResourceFactory);

	std::vector<RDOValue> paramList;
	paramList.push_back(RDOValue(1      ));
	paramList.push_back(RDOValue(2.2    ));
	paramList.push_back(RDOValue(_T("3")));

	LPRDOResource pResource = pResourceFactory->createRes(pRuntime, pRuntime->getResourceId(), paramList, true, true);
	BOOST_CHECK(pResource);

	RDOValue value1(pResourceType, pResource);

	LPRDOResourceType pType = value1.type().object_dynamic_cast<RDOResourceType>();
	BOOST_CHECK(pType);

	LPRDOResource pResource1 = value1.getPointer<RDOResource>();

	pRuntime   = NULL;
	value1     = RDOValue();
	pResource1 = NULL;

	BOOST_CHECK(pResource.owner());

	pResource = NULL;
}

BOOST_AUTO_TEST_SUITE_END() //RDOValue_Resource
<|endoftext|>