text stringlengths 54 60.6k |
|---|
<commit_before>// Copyright (c) 2009 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/test/ui/ui_test.h"
#include "base/file_path.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/pref_value_store.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
class NewTabUITest : public UITest {
public:
NewTabUITest() {
dom_automation_enabled_ = true;
// Set home page to the empty string so that we can set the home page using
// preferences.
homepage_ = L"";
// Setup the DEFAULT_THEME profile (has fake history entries).
set_template_user_data(UITest::ComputeTypicalUserDataSource(
UITest::DEFAULT_THEME));
}
};
TEST_F(NewTabUITest, NTPHasThumbnails) {
// Switch to the "new tab" tab, which should be any new tab after the
// first (the first is about:blank).
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// Bring up a new tab page.
ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
// Blank thumbnails on the NTP have the class 'filler' applied to the div.
// If all the thumbnails load, there should be no div's with 'filler'.
scoped_refptr<TabProxy> tab = window->GetActiveTab();
ASSERT_TRUE(tab.get());
ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"",
L"window.domAutomationController.send("
L"document.getElementsByClassName('filler').length == 0)",
action_max_timeout_ms()));
}
// Fails about 5% of the time on XP. http://crbug.com/45001
#if defined(OS_WIN)
#define ChromeInternalLoadsNTP FLAKY_ChromeInternalLoadsNTP
#endif
TEST_F(NewTabUITest, ChromeInternalLoadsNTP) {
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// Go to the "new tab page" using its old url, rather than chrome://newtab.
scoped_refptr<TabProxy> tab = window->GetTab(0);
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURLAsync(GURL("chrome-internal:")));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
// Ensure there are some thumbnails loaded in the page.
int thumbnails_count = -1;
ASSERT_TRUE(tab->ExecuteAndExtractInt(L"",
L"window.domAutomationController.send("
L"document.getElementsByClassName('thumbnail-container').length)",
&thumbnails_count));
EXPECT_GT(thumbnails_count, 0);
}
TEST_F(NewTabUITest, UpdateUserPrefsVersion) {
// PrefService with JSON user-pref file only, no enforced or advised prefs.
PrefService prefs(new PrefValueStore(
NULL, /* no enforced prefs */
new JsonPrefStore(
FilePath(),
ChromeThread::GetMessageLoopProxyForThread(ChromeThread::FILE)),
/* user prefs */
NULL /* no advised prefs */));
// Does the migration
NewTabUI::RegisterUserPrefs(&prefs);
ASSERT_EQ(NewTabUI::current_pref_version(),
prefs.GetInteger(prefs::kNTPPrefVersion));
// Reset the version
prefs.ClearPref(prefs::kNTPPrefVersion);
ASSERT_EQ(0, prefs.GetInteger(prefs::kNTPPrefVersion));
bool migrated = NewTabUI::UpdateUserPrefsVersion(&prefs);
ASSERT_TRUE(migrated);
ASSERT_EQ(NewTabUI::current_pref_version(),
prefs.GetInteger(prefs::kNTPPrefVersion));
migrated = NewTabUI::UpdateUserPrefsVersion(&prefs);
ASSERT_FALSE(migrated);
}
TEST_F(NewTabUITest, HomePageLink) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
ASSERT_TRUE(
browser->SetBooleanPreference(prefs::kHomePageIsNewTabPage, false));
// Bring up a new tab page.
ASSERT_TRUE(browser->RunCommand(IDC_NEW_TAB));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// TODO(arv): Extract common patterns for doing js testing.
// Fire click. Because tip service is turned off for testing, we first
// force the "make this my home page" tip to appear.
// TODO(arv): Find screen position of element and use a lower level click
// emulation.
bool result;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send("
L"(function() {"
L" tipCache = [{\"set_homepage_tip\":\"Make this the home page\"}];"
L" renderTip();"
L" var e = document.createEvent('Event');"
L" e.initEvent('click', true, true);"
L" var el = document.querySelector('#tip-line > button');"
L" el.dispatchEvent(e);"
L" return true;"
L"})()"
L")",
&result));
ASSERT_TRUE(result);
// Make sure text of "set as home page" tip has been removed.
std::wstring tip_text_content;
ASSERT_TRUE(tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L"(function() {"
L" var el = document.querySelector('#tip-line');"
L" return el.textContent;"
L"})()"
L")",
&tip_text_content));
ASSERT_EQ(L"", tip_text_content);
// Make sure that the notification is visible
bool has_class;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send("
L"(function() {"
L" var el = document.querySelector('#notification');"
L" return el.classList.contains('show');"
L"})()"
L")",
&has_class));
ASSERT_TRUE(has_class);
bool is_home_page;
ASSERT_TRUE(browser->GetBooleanPreference(prefs::kHomePageIsNewTabPage,
&is_home_page));
ASSERT_TRUE(is_home_page);
}
<commit_msg>Mark NewTabUITest.ChromeInternalLoadsNTP flaky on all platforms.<commit_after>// Copyright (c) 2009 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/test/ui/ui_test.h"
#include "base/file_path.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/pref_value_store.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
class NewTabUITest : public UITest {
public:
NewTabUITest() {
dom_automation_enabled_ = true;
// Set home page to the empty string so that we can set the home page using
// preferences.
homepage_ = L"";
// Setup the DEFAULT_THEME profile (has fake history entries).
set_template_user_data(UITest::ComputeTypicalUserDataSource(
UITest::DEFAULT_THEME));
}
};
TEST_F(NewTabUITest, NTPHasThumbnails) {
// Switch to the "new tab" tab, which should be any new tab after the
// first (the first is about:blank).
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// Bring up a new tab page.
ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
// Blank thumbnails on the NTP have the class 'filler' applied to the div.
// If all the thumbnails load, there should be no div's with 'filler'.
scoped_refptr<TabProxy> tab = window->GetActiveTab();
ASSERT_TRUE(tab.get());
ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"",
L"window.domAutomationController.send("
L"document.getElementsByClassName('filler').length == 0)",
action_max_timeout_ms()));
}
// Fails about ~5% of the time on all platforms. http://crbug.com/45001
TEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) {
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// Go to the "new tab page" using its old url, rather than chrome://newtab.
scoped_refptr<TabProxy> tab = window->GetTab(0);
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURLAsync(GURL("chrome-internal:")));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
// Ensure there are some thumbnails loaded in the page.
int thumbnails_count = -1;
ASSERT_TRUE(tab->ExecuteAndExtractInt(L"",
L"window.domAutomationController.send("
L"document.getElementsByClassName('thumbnail-container').length)",
&thumbnails_count));
EXPECT_GT(thumbnails_count, 0);
}
TEST_F(NewTabUITest, UpdateUserPrefsVersion) {
// PrefService with JSON user-pref file only, no enforced or advised prefs.
PrefService prefs(new PrefValueStore(
NULL, /* no enforced prefs */
new JsonPrefStore(
FilePath(),
ChromeThread::GetMessageLoopProxyForThread(ChromeThread::FILE)),
/* user prefs */
NULL /* no advised prefs */));
// Does the migration
NewTabUI::RegisterUserPrefs(&prefs);
ASSERT_EQ(NewTabUI::current_pref_version(),
prefs.GetInteger(prefs::kNTPPrefVersion));
// Reset the version
prefs.ClearPref(prefs::kNTPPrefVersion);
ASSERT_EQ(0, prefs.GetInteger(prefs::kNTPPrefVersion));
bool migrated = NewTabUI::UpdateUserPrefsVersion(&prefs);
ASSERT_TRUE(migrated);
ASSERT_EQ(NewTabUI::current_pref_version(),
prefs.GetInteger(prefs::kNTPPrefVersion));
migrated = NewTabUI::UpdateUserPrefsVersion(&prefs);
ASSERT_FALSE(migrated);
}
TEST_F(NewTabUITest, HomePageLink) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
ASSERT_TRUE(
browser->SetBooleanPreference(prefs::kHomePageIsNewTabPage, false));
// Bring up a new tab page.
ASSERT_TRUE(browser->RunCommand(IDC_NEW_TAB));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// TODO(arv): Extract common patterns for doing js testing.
// Fire click. Because tip service is turned off for testing, we first
// force the "make this my home page" tip to appear.
// TODO(arv): Find screen position of element and use a lower level click
// emulation.
bool result;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send("
L"(function() {"
L" tipCache = [{\"set_homepage_tip\":\"Make this the home page\"}];"
L" renderTip();"
L" var e = document.createEvent('Event');"
L" e.initEvent('click', true, true);"
L" var el = document.querySelector('#tip-line > button');"
L" el.dispatchEvent(e);"
L" return true;"
L"})()"
L")",
&result));
ASSERT_TRUE(result);
// Make sure text of "set as home page" tip has been removed.
std::wstring tip_text_content;
ASSERT_TRUE(tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L"(function() {"
L" var el = document.querySelector('#tip-line');"
L" return el.textContent;"
L"})()"
L")",
&tip_text_content));
ASSERT_EQ(L"", tip_text_content);
// Make sure that the notification is visible
bool has_class;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send("
L"(function() {"
L" var el = document.querySelector('#notification');"
L" return el.classList.contains('show');"
L"})()"
L")",
&has_class));
ASSERT_TRUE(has_class);
bool is_home_page;
ASSERT_TRUE(browser->GetBooleanPreference(prefs::kHomePageIsNewTabPage,
&is_home_page));
ASSERT_TRUE(is_home_page);
}
<|endoftext|> |
<commit_before>#include <iostream>
int main(int argc, char*[] argv)
{
std::cout << "Hello World" << std::enl;
return 0;
}
<commit_msg>Git push<commit_after>#include <iostream>
int main(int argc, char* argv[])
{
std::cout << "Hello World" << std::endl;
return 0;
}
<|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/sessions/session_backend.h"
#include <limits>
#include "base/file_util.h"
#include "base/histogram.h"
#include "base/scoped_vector.h"
using base::TimeTicks;
// File version number.
static const int32 kFileCurrentVersion = 1;
// The signature at the beginning of the file = SSNS (Sessions).
static const int32 kFileSignature = 0x53534E53;
namespace {
// SessionFileReader ----------------------------------------------------------
// SessionFileReader is responsible for reading the set of SessionCommands that
// describe a Session back from a file. SessionFileRead does minimal error
// checking on the file (pretty much only that the header is valid).
class SessionFileReader {
public:
typedef SessionCommand::id_type id_type;
typedef SessionCommand::size_type size_type;
explicit SessionFileReader(const FilePath& path)
: errored_(false),
buffer_(SessionBackend::kFileReadBufferSize, 0),
buffer_position_(0),
available_count_(0) {
file_.reset(new net::FileStream());
file_->Open(path, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ);
}
// Reads the contents of the file specified in the constructor, returning
// true on success. It is up to the caller to free all SessionCommands
// added to commands.
bool Read(BaseSessionService::SessionType type,
std::vector<SessionCommand*>* commands);
private:
// Reads a single command, returning it. A return value of NULL indicates
// either there are no commands, or there was an error. Use errored_ to
// distinguish the two. If NULL is returned, and there is no error, it means
// the end of file was successfully reached.
SessionCommand* ReadCommand();
// Shifts the unused portion of buffer_ to the beginning and fills the
// remaining portion with data from the file. Returns false if the buffer
// couldn't be filled. A return value of false only signals an error if
// errored_ is set to true.
bool FillBuffer();
// Whether an error condition has been detected (
bool errored_;
// As we read from the file, data goes here.
std::string buffer_;
// The file.
scoped_ptr<net::FileStream> file_;
// Position in buffer_ of the data.
size_t buffer_position_;
// Number of available bytes; relative to buffer_position_.
size_t available_count_;
DISALLOW_COPY_AND_ASSIGN(SessionFileReader);
};
bool SessionFileReader::Read(BaseSessionService::SessionType type,
std::vector<SessionCommand*>* commands) {
if (!file_->IsOpen())
return false;
int32 header[2];
int read_count;
TimeTicks start_time = TimeTicks::Now();
read_count = file_->ReadUntilComplete(reinterpret_cast<char*>(&header),
sizeof(header));
if (read_count != sizeof(header) || header[0] != kFileSignature ||
header[1] != kFileCurrentVersion)
return false;
ScopedVector<SessionCommand> read_commands;
SessionCommand* command;
while ((command = ReadCommand()) && !errored_)
read_commands->push_back(command);
if (!errored_)
read_commands->swap(*commands);
if (type == BaseSessionService::TAB_RESTORE) {
UMA_HISTOGRAM_TIMES("TabRestore.read_session_file_time",
TimeTicks::Now() - start_time);
} else {
UMA_HISTOGRAM_TIMES("SessionRestore.read_session_file_time",
TimeTicks::Now() - start_time);
}
return !errored_;
}
SessionCommand* SessionFileReader::ReadCommand() {
// Make sure there is enough in the buffer for the size of the next command.
if (available_count_ < sizeof(size_type)) {
if (!FillBuffer())
return NULL;
if (available_count_ < sizeof(size_type)) {
// Still couldn't read a valid size for the command, assume write was
// incomplete and return NULL.
return NULL;
}
}
// Get the size of the command.
size_type command_size;
memcpy(&command_size, &(buffer_[buffer_position_]), sizeof(command_size));
buffer_position_ += sizeof(command_size);
available_count_ -= sizeof(command_size);
if (command_size == 0) {
// Empty command. Shouldn't happen if write was successful, fail.
return NULL;
}
// Make sure buffer has the complete contents of the command.
if (command_size > available_count_) {
if (command_size > buffer_.size())
buffer_.resize((command_size / 1024 + 1) * 1024, 0);
if (!FillBuffer() || command_size > available_count_) {
// Again, assume the file was ok, and just the last chunk was lost.
return NULL;
}
}
const id_type command_id = buffer_[buffer_position_];
// NOTE: command_size includes the size of the id, which is not part of
// the contents of the SessionCommand.
SessionCommand* command =
new SessionCommand(command_id, command_size - sizeof(id_type));
if (command_size > sizeof(id_type)) {
memcpy(command->contents(),
&(buffer_[buffer_position_ + sizeof(id_type)]),
command_size - sizeof(id_type));
}
buffer_position_ += command_size;
available_count_ -= command_size;
return command;
}
bool SessionFileReader::FillBuffer() {
if (available_count_ > 0 && buffer_position_ > 0) {
// Shift buffer to beginning.
memmove(&(buffer_[0]), &(buffer_[buffer_position_]), available_count_);
}
buffer_position_ = 0;
DCHECK(buffer_position_ + available_count_ < buffer_.size());
int to_read = static_cast<int>(buffer_.size() - available_count_);
int read_count = file_->ReadUntilComplete(&(buffer_[available_count_]),
to_read);
if (read_count < 0) {
errored_ = true;
return false;
}
if (read_count == 0)
return false;
available_count_ += read_count;
return true;
}
} // namespace
// SessionBackend -------------------------------------------------------------
// File names (current and previous) for a type of TAB.
static const char* kCurrentTabSessionFileName = "Current Tabs";
static const char* kLastTabSessionFileName = "Last Tabs";
// File names (current and previous) for a type of SESSION.
static const char* kCurrentSessionFileName = "Current Session";
static const char* kLastSessionFileName = "Last Session";
// static
const int SessionBackend::kFileReadBufferSize = 1024;
SessionBackend::SessionBackend(BaseSessionService::SessionType type,
const FilePath& path_to_dir)
: type_(type),
path_to_dir_(path_to_dir),
last_session_valid_(false),
inited_(false),
empty_file_(true) {
// NOTE: this is invoked on the main thread, don't do file access here.
}
void SessionBackend::Init() {
if (inited_)
return;
inited_ = true;
// Create the directory for session info.
file_util::CreateDirectory(path_to_dir_);
MoveCurrentSessionToLastSession();
}
void SessionBackend::AppendCommands(
std::vector<SessionCommand*>* commands,
bool reset_first) {
Init();
// Make sure and check current_session_file_, if opening the file failed
// current_session_file_ will be NULL.
if ((reset_first && !empty_file_) || !current_session_file_.get() ||
!current_session_file_->IsOpen()) {
ResetFile();
}
// Need to check current_session_file_ again, ResetFile may fail.
if (current_session_file_.get() && current_session_file_->IsOpen() &&
!AppendCommandsToFile(current_session_file_.get(), *commands)) {
current_session_file_.reset(NULL);
}
empty_file_ = false;
STLDeleteElements(commands);
delete commands;
}
void SessionBackend::ReadLastSessionCommands(
scoped_refptr<BaseSessionService::InternalGetCommandsRequest> request) {
if (request->canceled())
return;
Init();
ReadLastSessionCommandsImpl(&(request->commands));
request->ForwardResult(
BaseSessionService::InternalGetCommandsRequest::TupleType(
request->handle(), request));
}
bool SessionBackend::ReadLastSessionCommandsImpl(
std::vector<SessionCommand*>* commands) {
Init();
SessionFileReader file_reader(GetLastSessionPath());
return file_reader.Read(type_, commands);
}
void SessionBackend::DeleteLastSession() {
Init();
file_util::Delete(GetLastSessionPath(), false);
}
void SessionBackend::MoveCurrentSessionToLastSession() {
Init();
current_session_file_.reset(NULL);
const FilePath current_session_path = GetCurrentSessionPath();
const FilePath last_session_path = GetLastSessionPath();
if (file_util::PathExists(last_session_path))
file_util::Delete(last_session_path, false);
if (file_util::PathExists(current_session_path)) {
int64 file_size;
if (file_util::GetFileSize(current_session_path, &file_size)) {
if (type_ == BaseSessionService::TAB_RESTORE) {
UMA_HISTOGRAM_COUNTS("TabRestore.last_session_file_size",
static_cast<int>(file_size / 1024));
} else {
UMA_HISTOGRAM_COUNTS("SessionRestore.last_session_file_size",
static_cast<int>(file_size / 1024));
}
}
last_session_valid_ = file_util::Move(current_session_path,
last_session_path);
}
if (file_util::PathExists(current_session_path))
file_util::Delete(current_session_path, false);
// Create and open the file for the current session.
ResetFile();
}
void SessionBackend::ReadCurrentSessionCommands(
scoped_refptr<BaseSessionService::InternalGetCommandsRequest> request) {
if (request->canceled())
return;
Init();
ReadCurrentSessionCommandsImpl(&(request->commands));
request->ForwardResult(
BaseSessionService::InternalGetCommandsRequest::TupleType(
request->handle(), request));
}
bool SessionBackend::ReadCurrentSessionCommandsImpl(
std::vector<SessionCommand*>* commands) {
Init();
SessionFileReader file_reader(GetCurrentSessionPath());
return file_reader.Read(type_, commands);
}
bool SessionBackend::AppendCommandsToFile(net::FileStream* file,
const std::vector<SessionCommand*>& commands) {
for (std::vector<SessionCommand*>::const_iterator i = commands.begin();
i != commands.end(); ++i) {
int wrote;
const size_type content_size = static_cast<size_type>((*i)->size());
const size_type total_size = content_size + sizeof(id_type);
if (type_ == BaseSessionService::TAB_RESTORE)
UMA_HISTOGRAM_COUNTS("TabRestore.command_size", total_size);
else
UMA_HISTOGRAM_COUNTS("SessionRestore.command_size", total_size);
wrote = file->Write(reinterpret_cast<const char*>(&total_size),
sizeof(total_size), NULL);
if (wrote != sizeof(total_size)) {
NOTREACHED() << "error writing";
return false;
}
id_type command_id = (*i)->id();
wrote = file->Write(reinterpret_cast<char*>(&command_id),
sizeof(command_id), NULL);
if (wrote != sizeof(command_id)) {
NOTREACHED() << "error writing";
return false;
}
if (content_size > 0) {
wrote = file->Write(reinterpret_cast<char*>((*i)->contents()),
content_size, NULL);
if (wrote != content_size) {
NOTREACHED() << "error writing";
return false;
}
}
}
return true;
}
void SessionBackend::ResetFile() {
DCHECK(inited_);
if (current_session_file_.get()) {
// File is already open, truncate it. We truncate instead of closing and
// reopening to avoid the possibility of scanners locking the file out
// from under us once we close it. If truncation fails, we'll try to
// recreate.
if (current_session_file_->Truncate(sizeof_header()) != sizeof_header())
current_session_file_.reset(NULL);
}
if (!current_session_file_.get())
current_session_file_.reset(OpenAndWriteHeader(GetCurrentSessionPath()));
empty_file_ = true;
}
net::FileStream* SessionBackend::OpenAndWriteHeader(const FilePath& path) {
DCHECK(!path.empty());
net::FileStream* file = new net::FileStream();
file->Open(path, base::PLATFORM_FILE_CREATE_ALWAYS |
base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_EXCLUSIVE_WRITE |
base::PLATFORM_FILE_EXCLUSIVE_READ);
if (!file->IsOpen())
return NULL;
int32 header[2];
header[0] = kFileSignature;
header[1] = kFileCurrentVersion;
int wrote = file->Write(reinterpret_cast<char*>(&header),
sizeof(header), NULL);
if (wrote != sizeof_header())
return NULL;
return file;
}
FilePath SessionBackend::GetLastSessionPath() {
FilePath path = path_to_dir_;
if (type_ == BaseSessionService::TAB_RESTORE)
path = path.AppendASCII(kLastTabSessionFileName);
else
path = path.AppendASCII(kLastSessionFileName);
return path;
}
FilePath SessionBackend::GetCurrentSessionPath() {
FilePath path = path_to_dir_;
if (type_ == BaseSessionService::TAB_RESTORE)
path = path.AppendASCII(kCurrentTabSessionFileName);
else
path = path.AppendASCII(kCurrentSessionFileName);
return path;
}
<commit_msg>Coverity: Fix leak in SessionBackend::OpenAndWriteHeader on error conditions.<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/sessions/session_backend.h"
#include <limits>
#include "base/file_util.h"
#include "base/histogram.h"
#include "base/scoped_vector.h"
using base::TimeTicks;
// File version number.
static const int32 kFileCurrentVersion = 1;
// The signature at the beginning of the file = SSNS (Sessions).
static const int32 kFileSignature = 0x53534E53;
namespace {
// SessionFileReader ----------------------------------------------------------
// SessionFileReader is responsible for reading the set of SessionCommands that
// describe a Session back from a file. SessionFileRead does minimal error
// checking on the file (pretty much only that the header is valid).
class SessionFileReader {
public:
typedef SessionCommand::id_type id_type;
typedef SessionCommand::size_type size_type;
explicit SessionFileReader(const FilePath& path)
: errored_(false),
buffer_(SessionBackend::kFileReadBufferSize, 0),
buffer_position_(0),
available_count_(0) {
file_.reset(new net::FileStream());
file_->Open(path, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ);
}
// Reads the contents of the file specified in the constructor, returning
// true on success. It is up to the caller to free all SessionCommands
// added to commands.
bool Read(BaseSessionService::SessionType type,
std::vector<SessionCommand*>* commands);
private:
// Reads a single command, returning it. A return value of NULL indicates
// either there are no commands, or there was an error. Use errored_ to
// distinguish the two. If NULL is returned, and there is no error, it means
// the end of file was successfully reached.
SessionCommand* ReadCommand();
// Shifts the unused portion of buffer_ to the beginning and fills the
// remaining portion with data from the file. Returns false if the buffer
// couldn't be filled. A return value of false only signals an error if
// errored_ is set to true.
bool FillBuffer();
// Whether an error condition has been detected (
bool errored_;
// As we read from the file, data goes here.
std::string buffer_;
// The file.
scoped_ptr<net::FileStream> file_;
// Position in buffer_ of the data.
size_t buffer_position_;
// Number of available bytes; relative to buffer_position_.
size_t available_count_;
DISALLOW_COPY_AND_ASSIGN(SessionFileReader);
};
bool SessionFileReader::Read(BaseSessionService::SessionType type,
std::vector<SessionCommand*>* commands) {
if (!file_->IsOpen())
return false;
int32 header[2];
int read_count;
TimeTicks start_time = TimeTicks::Now();
read_count = file_->ReadUntilComplete(reinterpret_cast<char*>(&header),
sizeof(header));
if (read_count != sizeof(header) || header[0] != kFileSignature ||
header[1] != kFileCurrentVersion)
return false;
ScopedVector<SessionCommand> read_commands;
SessionCommand* command;
while ((command = ReadCommand()) && !errored_)
read_commands->push_back(command);
if (!errored_)
read_commands->swap(*commands);
if (type == BaseSessionService::TAB_RESTORE) {
UMA_HISTOGRAM_TIMES("TabRestore.read_session_file_time",
TimeTicks::Now() - start_time);
} else {
UMA_HISTOGRAM_TIMES("SessionRestore.read_session_file_time",
TimeTicks::Now() - start_time);
}
return !errored_;
}
SessionCommand* SessionFileReader::ReadCommand() {
// Make sure there is enough in the buffer for the size of the next command.
if (available_count_ < sizeof(size_type)) {
if (!FillBuffer())
return NULL;
if (available_count_ < sizeof(size_type)) {
// Still couldn't read a valid size for the command, assume write was
// incomplete and return NULL.
return NULL;
}
}
// Get the size of the command.
size_type command_size;
memcpy(&command_size, &(buffer_[buffer_position_]), sizeof(command_size));
buffer_position_ += sizeof(command_size);
available_count_ -= sizeof(command_size);
if (command_size == 0) {
// Empty command. Shouldn't happen if write was successful, fail.
return NULL;
}
// Make sure buffer has the complete contents of the command.
if (command_size > available_count_) {
if (command_size > buffer_.size())
buffer_.resize((command_size / 1024 + 1) * 1024, 0);
if (!FillBuffer() || command_size > available_count_) {
// Again, assume the file was ok, and just the last chunk was lost.
return NULL;
}
}
const id_type command_id = buffer_[buffer_position_];
// NOTE: command_size includes the size of the id, which is not part of
// the contents of the SessionCommand.
SessionCommand* command =
new SessionCommand(command_id, command_size - sizeof(id_type));
if (command_size > sizeof(id_type)) {
memcpy(command->contents(),
&(buffer_[buffer_position_ + sizeof(id_type)]),
command_size - sizeof(id_type));
}
buffer_position_ += command_size;
available_count_ -= command_size;
return command;
}
bool SessionFileReader::FillBuffer() {
if (available_count_ > 0 && buffer_position_ > 0) {
// Shift buffer to beginning.
memmove(&(buffer_[0]), &(buffer_[buffer_position_]), available_count_);
}
buffer_position_ = 0;
DCHECK(buffer_position_ + available_count_ < buffer_.size());
int to_read = static_cast<int>(buffer_.size() - available_count_);
int read_count = file_->ReadUntilComplete(&(buffer_[available_count_]),
to_read);
if (read_count < 0) {
errored_ = true;
return false;
}
if (read_count == 0)
return false;
available_count_ += read_count;
return true;
}
} // namespace
// SessionBackend -------------------------------------------------------------
// File names (current and previous) for a type of TAB.
static const char* kCurrentTabSessionFileName = "Current Tabs";
static const char* kLastTabSessionFileName = "Last Tabs";
// File names (current and previous) for a type of SESSION.
static const char* kCurrentSessionFileName = "Current Session";
static const char* kLastSessionFileName = "Last Session";
// static
const int SessionBackend::kFileReadBufferSize = 1024;
SessionBackend::SessionBackend(BaseSessionService::SessionType type,
const FilePath& path_to_dir)
: type_(type),
path_to_dir_(path_to_dir),
last_session_valid_(false),
inited_(false),
empty_file_(true) {
// NOTE: this is invoked on the main thread, don't do file access here.
}
void SessionBackend::Init() {
if (inited_)
return;
inited_ = true;
// Create the directory for session info.
file_util::CreateDirectory(path_to_dir_);
MoveCurrentSessionToLastSession();
}
void SessionBackend::AppendCommands(
std::vector<SessionCommand*>* commands,
bool reset_first) {
Init();
// Make sure and check current_session_file_, if opening the file failed
// current_session_file_ will be NULL.
if ((reset_first && !empty_file_) || !current_session_file_.get() ||
!current_session_file_->IsOpen()) {
ResetFile();
}
// Need to check current_session_file_ again, ResetFile may fail.
if (current_session_file_.get() && current_session_file_->IsOpen() &&
!AppendCommandsToFile(current_session_file_.get(), *commands)) {
current_session_file_.reset(NULL);
}
empty_file_ = false;
STLDeleteElements(commands);
delete commands;
}
void SessionBackend::ReadLastSessionCommands(
scoped_refptr<BaseSessionService::InternalGetCommandsRequest> request) {
if (request->canceled())
return;
Init();
ReadLastSessionCommandsImpl(&(request->commands));
request->ForwardResult(
BaseSessionService::InternalGetCommandsRequest::TupleType(
request->handle(), request));
}
bool SessionBackend::ReadLastSessionCommandsImpl(
std::vector<SessionCommand*>* commands) {
Init();
SessionFileReader file_reader(GetLastSessionPath());
return file_reader.Read(type_, commands);
}
void SessionBackend::DeleteLastSession() {
Init();
file_util::Delete(GetLastSessionPath(), false);
}
void SessionBackend::MoveCurrentSessionToLastSession() {
Init();
current_session_file_.reset(NULL);
const FilePath current_session_path = GetCurrentSessionPath();
const FilePath last_session_path = GetLastSessionPath();
if (file_util::PathExists(last_session_path))
file_util::Delete(last_session_path, false);
if (file_util::PathExists(current_session_path)) {
int64 file_size;
if (file_util::GetFileSize(current_session_path, &file_size)) {
if (type_ == BaseSessionService::TAB_RESTORE) {
UMA_HISTOGRAM_COUNTS("TabRestore.last_session_file_size",
static_cast<int>(file_size / 1024));
} else {
UMA_HISTOGRAM_COUNTS("SessionRestore.last_session_file_size",
static_cast<int>(file_size / 1024));
}
}
last_session_valid_ = file_util::Move(current_session_path,
last_session_path);
}
if (file_util::PathExists(current_session_path))
file_util::Delete(current_session_path, false);
// Create and open the file for the current session.
ResetFile();
}
void SessionBackend::ReadCurrentSessionCommands(
scoped_refptr<BaseSessionService::InternalGetCommandsRequest> request) {
if (request->canceled())
return;
Init();
ReadCurrentSessionCommandsImpl(&(request->commands));
request->ForwardResult(
BaseSessionService::InternalGetCommandsRequest::TupleType(
request->handle(), request));
}
bool SessionBackend::ReadCurrentSessionCommandsImpl(
std::vector<SessionCommand*>* commands) {
Init();
SessionFileReader file_reader(GetCurrentSessionPath());
return file_reader.Read(type_, commands);
}
bool SessionBackend::AppendCommandsToFile(net::FileStream* file,
const std::vector<SessionCommand*>& commands) {
for (std::vector<SessionCommand*>::const_iterator i = commands.begin();
i != commands.end(); ++i) {
int wrote;
const size_type content_size = static_cast<size_type>((*i)->size());
const size_type total_size = content_size + sizeof(id_type);
if (type_ == BaseSessionService::TAB_RESTORE)
UMA_HISTOGRAM_COUNTS("TabRestore.command_size", total_size);
else
UMA_HISTOGRAM_COUNTS("SessionRestore.command_size", total_size);
wrote = file->Write(reinterpret_cast<const char*>(&total_size),
sizeof(total_size), NULL);
if (wrote != sizeof(total_size)) {
NOTREACHED() << "error writing";
return false;
}
id_type command_id = (*i)->id();
wrote = file->Write(reinterpret_cast<char*>(&command_id),
sizeof(command_id), NULL);
if (wrote != sizeof(command_id)) {
NOTREACHED() << "error writing";
return false;
}
if (content_size > 0) {
wrote = file->Write(reinterpret_cast<char*>((*i)->contents()),
content_size, NULL);
if (wrote != content_size) {
NOTREACHED() << "error writing";
return false;
}
}
}
return true;
}
void SessionBackend::ResetFile() {
DCHECK(inited_);
if (current_session_file_.get()) {
// File is already open, truncate it. We truncate instead of closing and
// reopening to avoid the possibility of scanners locking the file out
// from under us once we close it. If truncation fails, we'll try to
// recreate.
if (current_session_file_->Truncate(sizeof_header()) != sizeof_header())
current_session_file_.reset(NULL);
}
if (!current_session_file_.get())
current_session_file_.reset(OpenAndWriteHeader(GetCurrentSessionPath()));
empty_file_ = true;
}
net::FileStream* SessionBackend::OpenAndWriteHeader(const FilePath& path) {
DCHECK(!path.empty());
scoped_ptr<net::FileStream> file(new net::FileStream());
file->Open(path, base::PLATFORM_FILE_CREATE_ALWAYS |
base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_EXCLUSIVE_WRITE |
base::PLATFORM_FILE_EXCLUSIVE_READ);
if (!file->IsOpen())
return NULL;
int32 header[2];
header[0] = kFileSignature;
header[1] = kFileCurrentVersion;
int wrote = file->Write(reinterpret_cast<char*>(&header),
sizeof(header), NULL);
if (wrote != sizeof_header())
return NULL;
return file.release();
}
FilePath SessionBackend::GetLastSessionPath() {
FilePath path = path_to_dir_;
if (type_ == BaseSessionService::TAB_RESTORE)
path = path.AppendASCII(kLastTabSessionFileName);
else
path = path.AppendASCII(kLastSessionFileName);
return path;
}
FilePath SessionBackend::GetCurrentSessionPath() {
FilePath path = path_to_dir_;
if (type_ == BaseSessionService::TAB_RESTORE)
path = path.AppendASCII(kCurrentTabSessionFileName);
else
path = path.AppendASCII(kCurrentSessionFileName);
return path;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2008-2017 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Editor.h"
#include "EditorEvents.h"
#include "SceneTab.h"
#include <ImGui/imgui_internal.h>
#include <IconFontCppHeaders/IconsFontAwesome.h>
#include <Toolbox/Toolbox.h>
#include <Toolbox/SystemUI/ImGuiDock.h>
#include <tinyfiledialogs/tinyfiledialogs.h>
#include <Toolbox/SystemUI/ResourceBrowser.h>
#include <Toolbox/IO/ContentUtilities.h>
#include <Toolbox/SystemUI/Widgets.h>
URHO3D_DEFINE_APPLICATION_MAIN(Editor);
namespace Urho3D
{
Editor::Editor(Context* context)
: Application(context)
{
}
void Editor::Setup()
{
#ifdef _WIN32
// Required until SDL supports hdpi on windows
if (HMODULE hLibrary = LoadLibraryA("Shcore.dll"))
{
typedef HRESULT(WINAPI*SetProcessDpiAwarenessType)(size_t value);
if (auto fn = GetProcAddress(hLibrary, "SetProcessDpiAwareness"))
((SetProcessDpiAwarenessType)fn)(2); // PROCESS_PER_MONITOR_DPI_AWARE
FreeLibrary(hLibrary);
}
#endif
engineParameters_[EP_WINDOW_TITLE] = GetTypeName();
engineParameters_[EP_HEADLESS] = false;
engineParameters_[EP_RESOURCE_PREFIX_PATHS] =
context_->GetFileSystem()->GetProgramDir() + ";;..;../share/Urho3D/Resources";
engineParameters_[EP_FULL_SCREEN] = false;
engineParameters_[EP_WINDOW_HEIGHT] = 1080;
engineParameters_[EP_WINDOW_WIDTH] = 1920;
engineParameters_[EP_LOG_LEVEL] = LOG_DEBUG;
engineParameters_[EP_WINDOW_RESIZABLE] = true;
}
void Editor::Start()
{
GetInput()->SetMouseMode(MM_ABSOLUTE);
GetInput()->SetMouseVisible(true);
RegisterToolboxTypes(context_);
context_->RegisterFactory<Editor>();
context_->RegisterSubsystem(this);
GetSystemUI()->ApplyStyleDefault(true, 1.0f);
GetSystemUI()->AddFont("Fonts/fontawesome-webfont.ttf", 0, {ICON_MIN_FA, ICON_MAX_FA, 0}, true);
ui::GetStyle().WindowRounding = 3;
// Disable imgui saving ui settings on it's own. These should be serialized to project file.
ui::GetIO().IniFilename = 0;
GetCache()->SetAutoReloadResources(true);
SubscribeToEvent(E_UPDATE, std::bind(&Editor::OnUpdate, this, _2));
LoadProject("Etc/DefaultEditorProject.xml");
// Prevent overwriting example scene.
sceneTabs_.Front()->ClearCachedPaths();
}
void Editor::Stop()
{
SaveProject(projectFilePath_);
ui::ShutdownDock();
}
void Editor::SaveProject(const String& filePath)
{
if (filePath.Empty())
return;
SharedPtr<XMLFile> xml(new XMLFile(context_));
XMLElement root = xml->CreateRoot("project");
root.SetAttribute("version", "0");
auto window = root.CreateChild("window");
window.SetAttribute("width", ToString("%d", GetGraphics()->GetWidth()));
window.SetAttribute("height", ToString("%d", GetGraphics()->GetHeight()));
window.SetAttribute("x", ToString("%d", GetGraphics()->GetWindowPosition().x_));
window.SetAttribute("y", ToString("%d", GetGraphics()->GetWindowPosition().y_));
auto scenes = root.CreateChild("scenes");
for (auto& sceneTab: sceneTabs_)
sceneTab->SaveProject(scenes.CreateChild("scene"));
ui::SaveDock(root.CreateChild("docks"));
if (!xml->SaveFile(filePath))
URHO3D_LOGERRORF("Saving project to %s failed", filePath.CString());
}
void Editor::LoadProject(const String& filePath)
{
if (filePath.Empty())
return;
SharedPtr<XMLFile> xml;
if (!IsAbsolutePath(filePath))
xml = GetCache()->GetResource<XMLFile>(filePath);
if (xml.Null())
{
xml = new XMLFile(context_);
if (!xml->LoadFile(filePath))
return;
}
auto root = xml->GetRoot();
if (root.NotNull())
{
idPool_.Clear();
auto window = root.GetChild("window");
if (window.NotNull())
{
GetGraphics()->SetMode(ToInt(window.GetAttribute("width")), ToInt(window.GetAttribute("height")));
GetGraphics()->SetWindowPosition(ToInt(window.GetAttribute("x")), ToInt(window.GetAttribute("y")));
}
auto scenes = root.GetChild("scenes");
sceneTabs_.Clear();
if (scenes.NotNull())
{
auto scene = scenes.GetChild("scene");
while (scene.NotNull())
{
CreateNewScene(scene);
scene = scene.GetNext("scene");
}
}
ui::LoadDock(root.GetChild("docks"));
}
}
void Editor::OnUpdate(VariantMap& args)
{
ui::RootDock({0, 20}, ui::GetIO().DisplaySize - ImVec2(0, 20));
RenderMenuBar();
ui::SetNextDockPos(nullptr, ui::Slot_Left, ImGuiCond_FirstUseEver);
if (ui::BeginDock("Hierarchy"))
{
if (!activeTab_.Expired())
activeTab_->RenderSceneNodeTree();
}
ui::EndDock();
bool renderedWasActive = false;
for (auto it = sceneTabs_.Begin(); it != sceneTabs_.End();)
{
auto& tab = *it;
if (tab->RenderWindow())
{
if (tab->IsRendered())
{
// Only active window may override another active window
if (renderedWasActive && tab->IsActive())
activeTab_ = tab;
else if (!renderedWasActive)
{
renderedWasActive = tab->IsActive();
activeTab_ = tab;
}
}
++it;
}
else
it = sceneTabs_.Erase(it);
}
if (!activeTab_.Expired())
{
activeTab_->OnActiveUpdate();
ui::SetNextDockPos(activeTab_->GetUniqueTitle().CString(), ui::Slot_Right, ImGuiCond_FirstUseEver);
}
if (ui::BeginDock("Inspector"))
{
if (!activeTab_.Expired())
activeTab_->RenderInspector();
}
ui::EndDock();
String selected;
if (sceneTabs_.Size())
ui::SetNextDockPos(sceneTabs_.Back()->GetUniqueTitle().CString(), ui::Slot_Bottom, ImGuiCond_FirstUseEver);
if (ResourceBrowserWindow(selected, &resourceBrowserWindowOpen_))
{
auto type = GetContentType(selected);
if (type == CTYPE_SCENE)
{
CreateNewScene()->LoadScene(selected);
}
}
}
void Editor::RenderMenuBar()
{
bool save = false;
if (ui::BeginMainMenuBar())
{
if (ui::BeginMenu("File"))
{
save = ui::MenuItem("Save Project");
if (ui::MenuItem("Save Project As"))
{
save = true;
projectFilePath_.Clear();
}
if (ui::MenuItem("Open Project"))
{
const char* patterns[] = {"*.xml"};
projectFilePath_ = tinyfd_openFileDialog("Open Project", ".", 1, patterns, "XML Files", 0);
LoadProject(projectFilePath_);
}
ui::Separator();
if (ui::MenuItem("New Scene"))
CreateNewScene();
ui::Separator();
if (ui::MenuItem("Exit"))
engine_->Exit();
ui::EndMenu();
}
if (!activeTab_.Expired())
{
save |= ui::ToolbarButton(ICON_FA_FLOPPY_O);
ui::SameLine(0, 2.f);
if (ui::IsItemHovered())
ui::SetTooltip("Save");
ui::TextUnformatted("|");
ui::SameLine(0, 3.f);
activeTab_->RenderGizmoButtons();
SendEvent(E_EDITORTOOLBARBUTTONS);
}
ui::EndMainMenuBar();
}
if (save)
{
if (projectFilePath_.Empty())
{
const char* patterns[] = {"*.xml"};
projectFilePath_ = tinyfd_saveFileDialog("Save Project As", ".", 1, patterns, "XML Files");
}
SaveProject(projectFilePath_);
for (auto& sceneTab: sceneTabs_)
sceneTab->SaveScene();
}
}
SceneTab* Editor::CreateNewScene(XMLElement project)
{
SharedPtr<SceneTab> sceneTab;
StringHash id;
if (project.IsNull())
id = idPool_.NewID(); // Make new ID only if scene is not being loaded from a project.
if (sceneTabs_.Empty())
sceneTab = new SceneTab(context_, id, "Hierarchy", ui::Slot_Right);
else
sceneTab = new SceneTab(context_, id, sceneTabs_.Back()->GetUniqueTitle(), ui::Slot_Tab);
if (project.NotNull())
{
sceneTab->LoadProject(project);
if (!idPool_.TakeID(sceneTab->GetID()))
{
URHO3D_LOGERRORF("Scene loading failed because unique id %s is already taken",
sceneTab->GetID().ToString().CString());
return nullptr;
}
}
// In order to render scene to a texture we must add a dummy node to scene rendered to a screen, which has material
// pointing to scene texture. This object must also be visible to main camera.
sceneTabs_.Push(sceneTab);
return sceneTab;
}
bool Editor::IsActive(Scene* scene)
{
if (scene == nullptr || activeTab_.Null())
return false;
return activeTab_->GetScene() == scene && activeTab_->IsActive();
}
}<commit_msg>Make sure editor loads Autoload data (for PBR scene)<commit_after>//
// Copyright (c) 2008-2017 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Editor.h"
#include "EditorEvents.h"
#include "SceneTab.h"
#include <ImGui/imgui_internal.h>
#include <IconFontCppHeaders/IconsFontAwesome.h>
#include <Toolbox/Toolbox.h>
#include <Toolbox/SystemUI/ImGuiDock.h>
#include <tinyfiledialogs/tinyfiledialogs.h>
#include <Toolbox/SystemUI/ResourceBrowser.h>
#include <Toolbox/IO/ContentUtilities.h>
#include <Toolbox/SystemUI/Widgets.h>
URHO3D_DEFINE_APPLICATION_MAIN(Editor);
namespace Urho3D
{
Editor::Editor(Context* context)
: Application(context)
{
}
void Editor::Setup()
{
#ifdef _WIN32
// Required until SDL supports hdpi on windows
if (HMODULE hLibrary = LoadLibraryA("Shcore.dll"))
{
typedef HRESULT(WINAPI*SetProcessDpiAwarenessType)(size_t value);
if (auto fn = GetProcAddress(hLibrary, "SetProcessDpiAwareness"))
((SetProcessDpiAwarenessType)fn)(2); // PROCESS_PER_MONITOR_DPI_AWARE
FreeLibrary(hLibrary);
}
#endif
engineParameters_[EP_WINDOW_TITLE] = GetTypeName();
engineParameters_[EP_HEADLESS] = false;
engineParameters_[EP_RESOURCE_PREFIX_PATHS] =
context_->GetFileSystem()->GetProgramDir() + ";;..;../share/Urho3D/Resources";
engineParameters_[EP_FULL_SCREEN] = false;
engineParameters_[EP_WINDOW_HEIGHT] = 1080;
engineParameters_[EP_WINDOW_WIDTH] = 1920;
engineParameters_[EP_LOG_LEVEL] = LOG_DEBUG;
engineParameters_[EP_WINDOW_RESIZABLE] = true;
engineParameters_[EP_RESOURCE_PATHS] = "CoreData;Data;Autoload;";
}
void Editor::Start()
{
GetInput()->SetMouseMode(MM_ABSOLUTE);
GetInput()->SetMouseVisible(true);
RegisterToolboxTypes(context_);
context_->RegisterFactory<Editor>();
context_->RegisterSubsystem(this);
GetSystemUI()->ApplyStyleDefault(true, 1.0f);
GetSystemUI()->AddFont("Fonts/fontawesome-webfont.ttf", 0, {ICON_MIN_FA, ICON_MAX_FA, 0}, true);
ui::GetStyle().WindowRounding = 3;
// Disable imgui saving ui settings on it's own. These should be serialized to project file.
ui::GetIO().IniFilename = 0;
GetCache()->SetAutoReloadResources(true);
SubscribeToEvent(E_UPDATE, std::bind(&Editor::OnUpdate, this, _2));
LoadProject("Etc/DefaultEditorProject.xml");
// Prevent overwriting example scene.
sceneTabs_.Front()->ClearCachedPaths();
}
void Editor::Stop()
{
SaveProject(projectFilePath_);
ui::ShutdownDock();
}
void Editor::SaveProject(const String& filePath)
{
if (filePath.Empty())
return;
SharedPtr<XMLFile> xml(new XMLFile(context_));
XMLElement root = xml->CreateRoot("project");
root.SetAttribute("version", "0");
auto window = root.CreateChild("window");
window.SetAttribute("width", ToString("%d", GetGraphics()->GetWidth()));
window.SetAttribute("height", ToString("%d", GetGraphics()->GetHeight()));
window.SetAttribute("x", ToString("%d", GetGraphics()->GetWindowPosition().x_));
window.SetAttribute("y", ToString("%d", GetGraphics()->GetWindowPosition().y_));
auto scenes = root.CreateChild("scenes");
for (auto& sceneTab: sceneTabs_)
sceneTab->SaveProject(scenes.CreateChild("scene"));
ui::SaveDock(root.CreateChild("docks"));
if (!xml->SaveFile(filePath))
URHO3D_LOGERRORF("Saving project to %s failed", filePath.CString());
}
void Editor::LoadProject(const String& filePath)
{
if (filePath.Empty())
return;
SharedPtr<XMLFile> xml;
if (!IsAbsolutePath(filePath))
xml = GetCache()->GetResource<XMLFile>(filePath);
if (xml.Null())
{
xml = new XMLFile(context_);
if (!xml->LoadFile(filePath))
return;
}
auto root = xml->GetRoot();
if (root.NotNull())
{
idPool_.Clear();
auto window = root.GetChild("window");
if (window.NotNull())
{
GetGraphics()->SetMode(ToInt(window.GetAttribute("width")), ToInt(window.GetAttribute("height")));
GetGraphics()->SetWindowPosition(ToInt(window.GetAttribute("x")), ToInt(window.GetAttribute("y")));
}
auto scenes = root.GetChild("scenes");
sceneTabs_.Clear();
if (scenes.NotNull())
{
auto scene = scenes.GetChild("scene");
while (scene.NotNull())
{
CreateNewScene(scene);
scene = scene.GetNext("scene");
}
}
ui::LoadDock(root.GetChild("docks"));
}
}
void Editor::OnUpdate(VariantMap& args)
{
ui::RootDock({0, 20}, ui::GetIO().DisplaySize - ImVec2(0, 20));
RenderMenuBar();
ui::SetNextDockPos(nullptr, ui::Slot_Left, ImGuiCond_FirstUseEver);
if (ui::BeginDock("Hierarchy"))
{
if (!activeTab_.Expired())
activeTab_->RenderSceneNodeTree();
}
ui::EndDock();
bool renderedWasActive = false;
for (auto it = sceneTabs_.Begin(); it != sceneTabs_.End();)
{
auto& tab = *it;
if (tab->RenderWindow())
{
if (tab->IsRendered())
{
// Only active window may override another active window
if (renderedWasActive && tab->IsActive())
activeTab_ = tab;
else if (!renderedWasActive)
{
renderedWasActive = tab->IsActive();
activeTab_ = tab;
}
}
++it;
}
else
it = sceneTabs_.Erase(it);
}
if (!activeTab_.Expired())
{
activeTab_->OnActiveUpdate();
ui::SetNextDockPos(activeTab_->GetUniqueTitle().CString(), ui::Slot_Right, ImGuiCond_FirstUseEver);
}
if (ui::BeginDock("Inspector"))
{
if (!activeTab_.Expired())
activeTab_->RenderInspector();
}
ui::EndDock();
String selected;
if (sceneTabs_.Size())
ui::SetNextDockPos(sceneTabs_.Back()->GetUniqueTitle().CString(), ui::Slot_Bottom, ImGuiCond_FirstUseEver);
if (ResourceBrowserWindow(selected, &resourceBrowserWindowOpen_))
{
auto type = GetContentType(selected);
if (type == CTYPE_SCENE)
{
CreateNewScene()->LoadScene(selected);
}
}
}
void Editor::RenderMenuBar()
{
bool save = false;
if (ui::BeginMainMenuBar())
{
if (ui::BeginMenu("File"))
{
save = ui::MenuItem("Save Project");
if (ui::MenuItem("Save Project As"))
{
save = true;
projectFilePath_.Clear();
}
if (ui::MenuItem("Open Project"))
{
const char* patterns[] = {"*.xml"};
projectFilePath_ = tinyfd_openFileDialog("Open Project", ".", 1, patterns, "XML Files", 0);
LoadProject(projectFilePath_);
}
ui::Separator();
if (ui::MenuItem("New Scene"))
CreateNewScene();
ui::Separator();
if (ui::MenuItem("Exit"))
engine_->Exit();
ui::EndMenu();
}
if (!activeTab_.Expired())
{
save |= ui::ToolbarButton(ICON_FA_FLOPPY_O);
ui::SameLine(0, 2.f);
if (ui::IsItemHovered())
ui::SetTooltip("Save");
ui::TextUnformatted("|");
ui::SameLine(0, 3.f);
activeTab_->RenderGizmoButtons();
SendEvent(E_EDITORTOOLBARBUTTONS);
}
ui::EndMainMenuBar();
}
if (save)
{
if (projectFilePath_.Empty())
{
const char* patterns[] = {"*.xml"};
projectFilePath_ = tinyfd_saveFileDialog("Save Project As", ".", 1, patterns, "XML Files");
}
SaveProject(projectFilePath_);
for (auto& sceneTab: sceneTabs_)
sceneTab->SaveScene();
}
}
SceneTab* Editor::CreateNewScene(XMLElement project)
{
SharedPtr<SceneTab> sceneTab;
StringHash id;
if (project.IsNull())
id = idPool_.NewID(); // Make new ID only if scene is not being loaded from a project.
if (sceneTabs_.Empty())
sceneTab = new SceneTab(context_, id, "Hierarchy", ui::Slot_Right);
else
sceneTab = new SceneTab(context_, id, sceneTabs_.Back()->GetUniqueTitle(), ui::Slot_Tab);
if (project.NotNull())
{
sceneTab->LoadProject(project);
if (!idPool_.TakeID(sceneTab->GetID()))
{
URHO3D_LOGERRORF("Scene loading failed because unique id %s is already taken",
sceneTab->GetID().ToString().CString());
return nullptr;
}
}
// In order to render scene to a texture we must add a dummy node to scene rendered to a screen, which has material
// pointing to scene texture. This object must also be visible to main camera.
sceneTabs_.Push(sceneTab);
return sceneTab;
}
bool Editor::IsActive(Scene* scene)
{
if (scene == nullptr || activeTab_.Null())
return false;
return activeTab_->GetScene() == scene && activeTab_->IsActive();
}
}<|endoftext|> |
<commit_before>//===--- Init.cpp - Runtime initialization ---------------------------------==//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Swift runtime initialization.
//
//===----------------------------------------------------------------------===//
#include <mach/mach.h>
#include <mach/task.h>
#include <cassert>
__attribute__((constructor))
static void init() {
#if defined (__ppc__) || defined(__ppc64__)
thread_state_flavor_t flavor = PPC_THREAD_STATE64;
#elif defined(__i386__) || defined(__x86_64__)
thread_state_flavor_t flavor = x86_THREAD_STATE;
#elif defined(__arm__) || defined(__arm64__)
thread_state_flavor_t flavor = ARM_THREAD_STATE;
#else
#error "unknown architecture"
#endif
kern_return_t KR = task_set_exception_ports(mach_task_self(), EXC_MASK_CRASH,
MACH_PORT_NULL,
EXCEPTION_STATE_IDENTITY
| MACH_EXCEPTION_CODES, flavor);
(void)KR;
assert(KR == 0);
}
<commit_msg>Runtime: automatically enable crash reporting after the announcement<commit_after>//===--- Init.cpp - Runtime initialization ---------------------------------==//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Swift runtime initialization.
//
//===----------------------------------------------------------------------===//
#include <mach/mach.h>
#include <mach/task.h>
#include <time.h>
#include <cassert>
__attribute__((constructor))
static void init() {
if (time(nullptr) > 1401753089) return; // post announcement, do nothing
#if defined (__ppc__) || defined(__ppc64__)
thread_state_flavor_t flavor = PPC_THREAD_STATE64;
#elif defined(__i386__) || defined(__x86_64__)
thread_state_flavor_t flavor = x86_THREAD_STATE;
#elif defined(__arm__) || defined(__arm64__)
thread_state_flavor_t flavor = ARM_THREAD_STATE;
#else
#error "unknown architecture"
#endif
kern_return_t KR = task_set_exception_ports(mach_task_self(), EXC_MASK_CRASH,
MACH_PORT_NULL,
EXCEPTION_STATE_IDENTITY
| MACH_EXCEPTION_CODES, flavor);
(void)KR;
assert(KR == 0);
}
<|endoftext|> |
<commit_before>//===--- Init.cpp - Runtime initialization ---------------------------------==//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Swift runtime initialization.
//
//===----------------------------------------------------------------------===//
#include <mach/mach.h>
#include <mach/task.h>
#include <cassert>
__attribute__((constructor))
static void init() {
#if defined (__ppc__) || defined(__ppc64__)
thread_state_flavor_t flavor = PPC_THREAD_STATE64;
#elif defined(__i386__) || defined(__x86_64__)
thread_state_flavor_t flavor = x86_THREAD_STATE;
#elif defined(__arm__) || defined(__arm64__)
thread_state_flavor_t flavor = ARM_THREAD_STATE;
#else
#error "unknown architecture"
#endif
kern_return_t KR = task_set_exception_ports(mach_task_self(), EXC_MASK_CRASH,
MACH_PORT_NULL,
EXCEPTION_STATE_IDENTITY
| MACH_EXCEPTION_CODES, flavor);
assert(KR == 0);
}
<commit_msg>silence warning<commit_after>//===--- Init.cpp - Runtime initialization ---------------------------------==//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Swift runtime initialization.
//
//===----------------------------------------------------------------------===//
#include <mach/mach.h>
#include <mach/task.h>
#include <cassert>
__attribute__((constructor))
static void init() {
#if defined (__ppc__) || defined(__ppc64__)
thread_state_flavor_t flavor = PPC_THREAD_STATE64;
#elif defined(__i386__) || defined(__x86_64__)
thread_state_flavor_t flavor = x86_THREAD_STATE;
#elif defined(__arm__) || defined(__arm64__)
thread_state_flavor_t flavor = ARM_THREAD_STATE;
#else
#error "unknown architecture"
#endif
kern_return_t KR = task_set_exception_ports(mach_task_self(), EXC_MASK_CRASH,
MACH_PORT_NULL,
EXCEPTION_STATE_IDENTITY
| MACH_EXCEPTION_CODES, flavor);
(void)KR;
assert(KR == 0);
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnordmetric/sql/runtime/orderby.h>
#include <fnordmetric/sql/expressions/boolean.h>
namespace fnordmetric {
namespace query {
OrderBy::OrderBy(
size_t num_columns,
std::vector<SortSpec> sort_specs,
QueryPlanNode* child) :
sort_specs_(sort_specs),
child_(child) {
if (sort_specs_.size() == 0) {
RAISE(kIllegalArgumentError, "empty sort spec");
}
const auto& child_columns = child_->getColumns();
if (child_columns.size() < num_columns) {
RAISE(kRuntimeError, "not enough columns in virtual table");
}
for (int i = 0; i < num_columns; ++i) {
columns_.emplace_back(child_columns[i]);
}
child->setTarget(this);
}
// FIXPAUL this should mergesort while inserting...
void OrderBy::execute() {
child_->execute();
std::sort(rows_.begin(), rows_.end(), [this] (
const std::vector<SValue>& left,
const std::vector<SValue>& right) -> bool {
for (const auto& sort : sort_specs_) {
if (sort.column >= left.size() || sort.column >= right.size()) {
RAISE(kIndexError, "column index out of bounds");
}
SValue args[2];
SValue res(false);
args[0] = left[sort.column];
args[1] = right[sort.column];
expressions::eqExpr(nullptr, 2, args, &res);
if (res.getBool()) {
continue;
}
if (sort.descending) {
expressions::gtExpr(nullptr, 2, args, &res);
} else {
expressions::ltExpr(nullptr, 2, args, &res);
}
return res.getBool();
}
/* all dimensions equal */
return false;
});
for (auto& row : rows_) {
if (row.size() < columns_.size()) {
RAISE(kRuntimeError, "row too small");
}
emitRow(row.data(), columns_.size());
}
}
bool OrderBy::nextRow(SValue* row, int row_len) {
std::vector<SValue> row_vec;
for (int i = 0; i < row_len; i++) {
row_vec.emplace_back(row[i]);
}
rows_.emplace_back(row_vec);
return true;
}
size_t OrderBy::getNumCols() const {
return columns_.size();
}
const std::vector<std::string>& OrderBy::getColumns() const {
return columns_;
}
} // namespace query
} // namespace fnordmetric
<commit_msg>adds missing include for STL's std::sort()<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnordmetric/sql/runtime/orderby.h>
#include <fnordmetric/sql/expressions/boolean.h>
#include <algorithm>
namespace fnordmetric {
namespace query {
OrderBy::OrderBy(
size_t num_columns,
std::vector<SortSpec> sort_specs,
QueryPlanNode* child) :
sort_specs_(sort_specs),
child_(child) {
if (sort_specs_.size() == 0) {
RAISE(kIllegalArgumentError, "empty sort spec");
}
const auto& child_columns = child_->getColumns();
if (child_columns.size() < num_columns) {
RAISE(kRuntimeError, "not enough columns in virtual table");
}
for (int i = 0; i < num_columns; ++i) {
columns_.emplace_back(child_columns[i]);
}
child->setTarget(this);
}
// FIXPAUL this should mergesort while inserting...
void OrderBy::execute() {
child_->execute();
std::sort(rows_.begin(), rows_.end(), [this] (
const std::vector<SValue>& left,
const std::vector<SValue>& right) -> bool {
for (const auto& sort : sort_specs_) {
if (sort.column >= left.size() || sort.column >= right.size()) {
RAISE(kIndexError, "column index out of bounds");
}
SValue args[2];
SValue res(false);
args[0] = left[sort.column];
args[1] = right[sort.column];
expressions::eqExpr(nullptr, 2, args, &res);
if (res.getBool()) {
continue;
}
if (sort.descending) {
expressions::gtExpr(nullptr, 2, args, &res);
} else {
expressions::ltExpr(nullptr, 2, args, &res);
}
return res.getBool();
}
/* all dimensions equal */
return false;
});
for (auto& row : rows_) {
if (row.size() < columns_.size()) {
RAISE(kRuntimeError, "row too small");
}
emitRow(row.data(), columns_.size());
}
}
bool OrderBy::nextRow(SValue* row, int row_len) {
std::vector<SValue> row_vec;
for (int i = 0; i < row_len; i++) {
row_vec.emplace_back(row[i]);
}
rows_.emplace_back(row_vec);
return true;
}
size_t OrderBy::getNumCols() const {
return columns_.size();
}
const std::vector<std::string>& OrderBy::getColumns() const {
return columns_;
}
} // namespace query
} // namespace fnordmetric
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 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 "webkit/tools/test_shell/webwidget_host.h"
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_canvas_linux.h"
#include "skia/ext/platform_device_linux.h"
#include "webkit/glue/webinputevent.h"
#include "webkit/glue/webwidget.h"
namespace {
// In response to an invalidation, we call into WebKit to do layout. On
// Windows, WM_PAINT is a virtual message so any extra invalidates that come up
// while it's doing layout are implicitly swallowed as soon as we actually do
// drawing via BeginPaint.
//
// Though GTK does know how to collapse multiple paint requests, it won't erase
// paint requests from the future when we start drawing. To avoid an infinite
// cycle of repaints, we track whether we're currently handling a redraw, and
// during that if we get told by WebKit that a region has become invalid, we
// still add that region to the local dirty rect but *don't* enqueue yet
// another "do a paint" message.
bool g_handling_expose = false;
// -----------------------------------------------------------------------------
// Callback functions to proxy to host...
// The web contents are completely drawn and handled by WebKit, except that
// windowed plugins are GtkSockets on top of it. We need to place the
// GtkSockets inside a GtkContainer. We use a GtkFixed container, and the
// GtkSocket objects override a little bit to manage their size (see the code
// in webplugin_delegate_impl_gtk.cc). We listen on a the events we're
// interested in and forward them on to the WebWidgetHost. This class is a
// collection of static methods, implementing the widget related code.
class WebWidgetHostGtkWidget {
public:
// This will create a new widget used for hosting the web contents. We use
// our GtkDrawingAreaContainer here, for the reasons mentioned above.
static GtkWidget* CreateNewWidget(GtkWidget* parent_view,
WebWidgetHost* host) {
GtkWidget* widget = gtk_fixed_new();
gtk_fixed_set_has_window(GTK_FIXED(widget), true);
gtk_box_pack_start(GTK_BOX(parent_view), widget, TRUE, TRUE, 0);
gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
g_signal_connect(widget, "size-allocate",
G_CALLBACK(&HandleSizeAllocate), host);
g_signal_connect(widget, "configure-event",
G_CALLBACK(&HandleConfigure), host);
g_signal_connect(widget, "expose-event",
G_CALLBACK(&HandleExpose), host);
g_signal_connect(widget, "destroy",
G_CALLBACK(&HandleDestroy), host);
g_signal_connect(widget, "key-press-event",
G_CALLBACK(&HandleKeyPress), host);
g_signal_connect(widget, "key-release-event",
G_CALLBACK(&HandleKeyRelease), host);
g_signal_connect(widget, "focus",
G_CALLBACK(&HandleFocus), host);
g_signal_connect(widget, "focus-in-event",
G_CALLBACK(&HandleFocusIn), host);
g_signal_connect(widget, "focus-out-event",
G_CALLBACK(&HandleFocusOut), host);
g_signal_connect(widget, "button-press-event",
G_CALLBACK(&HandleButtonPress), host);
g_signal_connect(widget, "button-release-event",
G_CALLBACK(&HandleButtonRelease), host);
g_signal_connect(widget, "motion-notify-event",
G_CALLBACK(&HandleMotionNotify), host);
g_signal_connect(widget, "scroll-event",
G_CALLBACK(&HandleScroll), host);
return widget;
}
private:
// Our size has changed.
static void HandleSizeAllocate(GtkWidget* widget,
GtkAllocation* allocation,
WebWidgetHost* host) {
host->Resize(gfx::Size(allocation->width, allocation->height));
}
// Size, position, or stacking of the GdkWindow changed.
static gboolean HandleConfigure(GtkWidget* widget,
GdkEventConfigure* config,
WebWidgetHost* host) {
host->Resize(gfx::Size(config->width, config->height));
return FALSE;
}
// A portion of the GdkWindow needs to be redraw.
static gboolean HandleExpose(GtkWidget* widget,
GdkEventExpose* expose,
WebWidgetHost* host) {
// See comments above about what g_handling_expose is for.
g_handling_expose = true;
gfx::Rect rect(expose->area);
host->UpdatePaintRect(rect);
host->Paint();
g_handling_expose = false;
return FALSE;
}
// The GdkWindow was destroyed.
static gboolean HandleDestroy(GtkWidget* widget, WebWidgetHost* host) {
host->WindowDestroyed();
return FALSE;
}
// Keyboard key pressed.
static gboolean HandleKeyPress(GtkWidget* widget,
GdkEventKey* event,
WebWidgetHost* host) {
WebKeyboardEvent wke(event);
host->webwidget()->HandleInputEvent(&wke);
// The WebKeyboardEvent model, when holding down a key, is:
// KEY_DOWN, CHAR, (repeated CHAR as key repeats,) KEY_UP
// The GDK model for the same sequence is just:
// KEY_PRESS, (repeated KEY_PRESS as key repeats,) KEY_RELEASE
// So we must simulate a CHAR event for every key press.
if (event->type == GDK_KEY_PRESS) {
wke.type = WebKeyboardEvent::CHAR;
host->webwidget()->HandleInputEvent(&wke);
}
return FALSE;
}
// Keyboard key released.
static gboolean HandleKeyRelease(GtkWidget* widget,
GdkEventKey* event,
WebWidgetHost* host) {
return HandleKeyPress(widget, event, host);
}
// This signal is called when arrow keys or tab is pressed. If we return
// true, we prevent focus from being moved to another widget. If we want to
// allow focus to be moved outside of web contents, we need to implement
// WebViewDelegate::TakeFocus in the test webview delegate.
static gboolean HandleFocus(GtkWidget* widget,
GdkEventFocus* focus,
WebWidgetHost* host) {
return TRUE;
}
// Keyboard focus entered.
static gboolean HandleFocusIn(GtkWidget* widget,
GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(true);
return FALSE;
}
// Keyboard focus left.
static gboolean HandleFocusOut(GtkWidget* widget,
GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(false);
return FALSE;
}
// Mouse button down.
static gboolean HandleButtonPress(GtkWidget* widget,
GdkEventButton* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
// Mouse button up.
static gboolean HandleButtonRelease(GtkWidget* widget,
GdkEventButton* event,
WebWidgetHost* host) {
return HandleButtonPress(widget, event, host);
}
// Mouse pointer movements.
static gboolean HandleMotionNotify(GtkWidget* widget,
GdkEventMotion* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
// Mouse scroll wheel.
static gboolean HandleScroll(GtkWidget* widget,
GdkEventScroll* event,
WebWidgetHost* host) {
WebMouseWheelEvent wmwe(event);
host->webwidget()->HandleInputEvent(&wmwe);
return FALSE;
}
DISALLOW_IMPLICIT_CONSTRUCTORS(WebWidgetHostGtkWidget);
};
} // namespace
// This is provided so that the webview can reuse the custom GTK window code.
// static
gfx::NativeView WebWidgetHost::CreateWidget(
gfx::NativeView parent_view, WebWidgetHost* host) {
return WebWidgetHostGtkWidget::CreateNewWidget(parent_view, host);
}
// static
WebWidgetHost* WebWidgetHost::Create(GtkWidget* parent_view,
WebWidgetDelegate* delegate) {
WebWidgetHost* host = new WebWidgetHost();
host->view_ = CreateWidget(parent_view, host);
host->webwidget_ = WebWidget::Create(delegate);
// We manage our own double buffering because we need to be able to update
// the expose area in an ExposeEvent within the lifetime of the event handler.
gtk_widget_set_double_buffered(GTK_WIDGET(host->view_), false);
return host;
}
void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) {
paint_rect_ = paint_rect_.Union(rect);
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting";
UpdatePaintRect(damaged_rect);
if (!g_handling_expose) {
gtk_widget_queue_draw_area(GTK_WIDGET(view_), damaged_rect.x(),
damaged_rect.y(), damaged_rect.width(), damaged_rect.height());
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// This is used for optimizing painting when the renderer is scrolled. We're
// currently not doing any optimizations so just invalidate the region.
DidInvalidateRect(clip_rect);
}
WebWidgetHost::WebWidgetHost()
: view_(NULL),
webwidget_(NULL),
scroll_dx_(0),
scroll_dy_(0),
track_mouse_leave_(false) {
set_painting(false);
}
WebWidgetHost::~WebWidgetHost() {
webwidget_->Close();
webwidget_->Release();
}
void WebWidgetHost::Resize(const gfx::Size &newsize) {
// The pixel buffer backing us is now the wrong size
canvas_.reset();
webwidget_->Resize(gfx::Size(newsize.width(), newsize.height()));
}
void WebWidgetHost::Paint() {
int width = view_->allocation.width;
int height = view_->allocation.height;
gfx::Rect client_rect(width, height);
// Allocate a canvas if necessary
if (!canvas_.get()) {
ResetScrollRect();
paint_rect_ = client_rect;
canvas_.reset(new skia::PlatformCanvas(width, height, true));
if (!canvas_.get()) {
// memory allocation failed, we can't paint.
LOG(ERROR) << "Failed to allocate memory for " << width << "x" << height;
return;
}
}
// This may result in more invalidation
webwidget_->Layout();
// Paint the canvas if necessary. Allow painting to generate extra rects the
// first time we call it. This is necessary because some WebCore rendering
// objects update their layout only when painted.
// Store the total area painted in total_paint. Then tell the gdk window
// to update that area after we're done painting it.
gfx::Rect total_paint;
for (int i = 0; i < 2; ++i) {
paint_rect_ = client_rect.Intersect(paint_rect_);
if (!paint_rect_.IsEmpty()) {
gfx::Rect rect(paint_rect_);
paint_rect_ = gfx::Rect();
DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations";
PaintRect(rect);
total_paint = total_paint.Union(rect);
}
}
DCHECK(paint_rect_.IsEmpty());
// Invalidate the paint region on the widget's underlying gdk window. Note
// that gdk_window_invalidate_* will generate extra expose events, which
// we wish to avoid. So instead we use calls to begin_paint/end_paint.
GdkRectangle grect = {
total_paint.x(),
total_paint.y(),
total_paint.width(),
total_paint.height(),
};
GdkWindow* window = view_->window;
gdk_window_begin_paint_rect(window, &grect);
// BitBlit to the gdk window.
skia::PlatformDeviceLinux &platdev = canvas_->getTopPlatformDevice();
skia::BitmapPlatformDeviceLinux* const bitdev =
static_cast<skia::BitmapPlatformDeviceLinux* >(&platdev);
cairo_t* cairo_drawable = gdk_cairo_create(window);
cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
cairo_paint(cairo_drawable);
cairo_destroy(cairo_drawable);
gdk_window_end_paint(window);
}
void WebWidgetHost::ResetScrollRect() {
// This method is only needed for optimized scroll painting, which we don't
// care about in the test shell, yet.
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
set_painting(true);
webwidget_->Paint(canvas_.get(), rect);
set_painting(false);
}
void WebWidgetHost::WindowDestroyed() {
delete this;
}
<commit_msg>Some improvements to the browser window resizing.<commit_after>// Copyright (c) 2006-2008 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 "webkit/tools/test_shell/webwidget_host.h"
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_canvas_linux.h"
#include "skia/ext/platform_device_linux.h"
#include "webkit/glue/webinputevent.h"
#include "webkit/glue/webwidget.h"
namespace {
// In response to an invalidation, we call into WebKit to do layout. On
// Windows, WM_PAINT is a virtual message so any extra invalidates that come up
// while it's doing layout are implicitly swallowed as soon as we actually do
// drawing via BeginPaint.
//
// Though GTK does know how to collapse multiple paint requests, it won't erase
// paint requests from the future when we start drawing. To avoid an infinite
// cycle of repaints, we track whether we're currently handling a redraw, and
// during that if we get told by WebKit that a region has become invalid, we
// still add that region to the local dirty rect but *don't* enqueue yet
// another "do a paint" message.
bool g_handling_expose = false;
// -----------------------------------------------------------------------------
// Callback functions to proxy to host...
// The web contents are completely drawn and handled by WebKit, except that
// windowed plugins are GtkSockets on top of it. We need to place the
// GtkSockets inside a GtkContainer. We use a GtkFixed container, and the
// GtkSocket objects override a little bit to manage their size (see the code
// in webplugin_delegate_impl_gtk.cc). We listen on a the events we're
// interested in and forward them on to the WebWidgetHost. This class is a
// collection of static methods, implementing the widget related code.
class WebWidgetHostGtkWidget {
public:
// This will create a new widget used for hosting the web contents. We use
// our GtkDrawingAreaContainer here, for the reasons mentioned above.
static GtkWidget* CreateNewWidget(GtkWidget* parent_view,
WebWidgetHost* host) {
GtkWidget* widget = gtk_fixed_new();
gtk_fixed_set_has_window(GTK_FIXED(widget), true);
gtk_box_pack_start(GTK_BOX(parent_view), widget, TRUE, TRUE, 0);
gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
g_signal_connect(widget, "size-request",
G_CALLBACK(&HandleSizeRequest), host);
g_signal_connect(widget, "size-allocate",
G_CALLBACK(&HandleSizeAllocate), host);
g_signal_connect(widget, "configure-event",
G_CALLBACK(&HandleConfigure), host);
g_signal_connect(widget, "expose-event",
G_CALLBACK(&HandleExpose), host);
g_signal_connect(widget, "destroy",
G_CALLBACK(&HandleDestroy), host);
g_signal_connect(widget, "key-press-event",
G_CALLBACK(&HandleKeyPress), host);
g_signal_connect(widget, "key-release-event",
G_CALLBACK(&HandleKeyRelease), host);
g_signal_connect(widget, "focus",
G_CALLBACK(&HandleFocus), host);
g_signal_connect(widget, "focus-in-event",
G_CALLBACK(&HandleFocusIn), host);
g_signal_connect(widget, "focus-out-event",
G_CALLBACK(&HandleFocusOut), host);
g_signal_connect(widget, "button-press-event",
G_CALLBACK(&HandleButtonPress), host);
g_signal_connect(widget, "button-release-event",
G_CALLBACK(&HandleButtonRelease), host);
g_signal_connect(widget, "motion-notify-event",
G_CALLBACK(&HandleMotionNotify), host);
g_signal_connect(widget, "scroll-event",
G_CALLBACK(&HandleScroll), host);
return widget;
}
private:
// Our size was requested. We let the GtkFixed do its normal calculation,
// after which this callback is called. The GtkFixed will come up with a
// requisition based on its children, which include plugin windows. Since
// we don't want to prevent resizing smaller than a plugin window, we need to
// control the size ourself.
static void HandleSizeRequest(GtkWidget* widget,
GtkRequisition* req,
WebWidgetHost* host) {
// This is arbitrary, but the WebKit scrollbars try to shrink themselves
// if the browser window is too small. Give them some space.
static const int kMinWidthHeight = 64;
req->width = kMinWidthHeight;
req->height = kMinWidthHeight;
}
// Our size has changed.
static void HandleSizeAllocate(GtkWidget* widget,
GtkAllocation* allocation,
WebWidgetHost* host) {
host->Resize(gfx::Size(allocation->width, allocation->height));
}
// Size, position, or stacking of the GdkWindow changed.
static gboolean HandleConfigure(GtkWidget* widget,
GdkEventConfigure* config,
WebWidgetHost* host) {
host->Resize(gfx::Size(config->width, config->height));
return FALSE;
}
// A portion of the GdkWindow needs to be redraw.
static gboolean HandleExpose(GtkWidget* widget,
GdkEventExpose* expose,
WebWidgetHost* host) {
// See comments above about what g_handling_expose is for.
g_handling_expose = true;
gfx::Rect rect(expose->area);
host->UpdatePaintRect(rect);
host->Paint();
g_handling_expose = false;
return FALSE;
}
// The GdkWindow was destroyed.
static gboolean HandleDestroy(GtkWidget* widget, WebWidgetHost* host) {
host->WindowDestroyed();
return FALSE;
}
// Keyboard key pressed.
static gboolean HandleKeyPress(GtkWidget* widget,
GdkEventKey* event,
WebWidgetHost* host) {
WebKeyboardEvent wke(event);
host->webwidget()->HandleInputEvent(&wke);
// The WebKeyboardEvent model, when holding down a key, is:
// KEY_DOWN, CHAR, (repeated CHAR as key repeats,) KEY_UP
// The GDK model for the same sequence is just:
// KEY_PRESS, (repeated KEY_PRESS as key repeats,) KEY_RELEASE
// So we must simulate a CHAR event for every key press.
if (event->type == GDK_KEY_PRESS) {
wke.type = WebKeyboardEvent::CHAR;
host->webwidget()->HandleInputEvent(&wke);
}
return FALSE;
}
// Keyboard key released.
static gboolean HandleKeyRelease(GtkWidget* widget,
GdkEventKey* event,
WebWidgetHost* host) {
return HandleKeyPress(widget, event, host);
}
// This signal is called when arrow keys or tab is pressed. If we return
// true, we prevent focus from being moved to another widget. If we want to
// allow focus to be moved outside of web contents, we need to implement
// WebViewDelegate::TakeFocus in the test webview delegate.
static gboolean HandleFocus(GtkWidget* widget,
GdkEventFocus* focus,
WebWidgetHost* host) {
return TRUE;
}
// Keyboard focus entered.
static gboolean HandleFocusIn(GtkWidget* widget,
GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(true);
return FALSE;
}
// Keyboard focus left.
static gboolean HandleFocusOut(GtkWidget* widget,
GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(false);
return FALSE;
}
// Mouse button down.
static gboolean HandleButtonPress(GtkWidget* widget,
GdkEventButton* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
// Mouse button up.
static gboolean HandleButtonRelease(GtkWidget* widget,
GdkEventButton* event,
WebWidgetHost* host) {
return HandleButtonPress(widget, event, host);
}
// Mouse pointer movements.
static gboolean HandleMotionNotify(GtkWidget* widget,
GdkEventMotion* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
// Mouse scroll wheel.
static gboolean HandleScroll(GtkWidget* widget,
GdkEventScroll* event,
WebWidgetHost* host) {
WebMouseWheelEvent wmwe(event);
host->webwidget()->HandleInputEvent(&wmwe);
return FALSE;
}
DISALLOW_IMPLICIT_CONSTRUCTORS(WebWidgetHostGtkWidget);
};
} // namespace
// This is provided so that the webview can reuse the custom GTK window code.
// static
gfx::NativeView WebWidgetHost::CreateWidget(
gfx::NativeView parent_view, WebWidgetHost* host) {
return WebWidgetHostGtkWidget::CreateNewWidget(parent_view, host);
}
// static
WebWidgetHost* WebWidgetHost::Create(GtkWidget* parent_view,
WebWidgetDelegate* delegate) {
WebWidgetHost* host = new WebWidgetHost();
host->view_ = CreateWidget(parent_view, host);
host->webwidget_ = WebWidget::Create(delegate);
// We manage our own double buffering because we need to be able to update
// the expose area in an ExposeEvent within the lifetime of the event handler.
gtk_widget_set_double_buffered(GTK_WIDGET(host->view_), false);
return host;
}
void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) {
paint_rect_ = paint_rect_.Union(rect);
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting";
UpdatePaintRect(damaged_rect);
if (!g_handling_expose) {
gtk_widget_queue_draw_area(GTK_WIDGET(view_), damaged_rect.x(),
damaged_rect.y(), damaged_rect.width(), damaged_rect.height());
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// This is used for optimizing painting when the renderer is scrolled. We're
// currently not doing any optimizations so just invalidate the region.
DidInvalidateRect(clip_rect);
}
WebWidgetHost::WebWidgetHost()
: view_(NULL),
webwidget_(NULL),
scroll_dx_(0),
scroll_dy_(0),
track_mouse_leave_(false) {
set_painting(false);
}
WebWidgetHost::~WebWidgetHost() {
webwidget_->Close();
webwidget_->Release();
}
void WebWidgetHost::Resize(const gfx::Size &newsize) {
// The pixel buffer backing us is now the wrong size
canvas_.reset();
webwidget_->Resize(gfx::Size(newsize.width(), newsize.height()));
}
void WebWidgetHost::Paint() {
int width = view_->allocation.width;
int height = view_->allocation.height;
gfx::Rect client_rect(width, height);
// Allocate a canvas if necessary
if (!canvas_.get()) {
ResetScrollRect();
paint_rect_ = client_rect;
canvas_.reset(new skia::PlatformCanvas(width, height, true));
if (!canvas_.get()) {
// memory allocation failed, we can't paint.
LOG(ERROR) << "Failed to allocate memory for " << width << "x" << height;
return;
}
}
// This may result in more invalidation
webwidget_->Layout();
// Paint the canvas if necessary. Allow painting to generate extra rects the
// first time we call it. This is necessary because some WebCore rendering
// objects update their layout only when painted.
// Store the total area painted in total_paint. Then tell the gdk window
// to update that area after we're done painting it.
gfx::Rect total_paint;
for (int i = 0; i < 2; ++i) {
paint_rect_ = client_rect.Intersect(paint_rect_);
if (!paint_rect_.IsEmpty()) {
gfx::Rect rect(paint_rect_);
paint_rect_ = gfx::Rect();
DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations";
PaintRect(rect);
total_paint = total_paint.Union(rect);
}
}
DCHECK(paint_rect_.IsEmpty());
// Invalidate the paint region on the widget's underlying gdk window. Note
// that gdk_window_invalidate_* will generate extra expose events, which
// we wish to avoid. So instead we use calls to begin_paint/end_paint.
GdkRectangle grect = {
total_paint.x(),
total_paint.y(),
total_paint.width(),
total_paint.height(),
};
GdkWindow* window = view_->window;
gdk_window_begin_paint_rect(window, &grect);
// BitBlit to the gdk window.
skia::PlatformDeviceLinux &platdev = canvas_->getTopPlatformDevice();
skia::BitmapPlatformDeviceLinux* const bitdev =
static_cast<skia::BitmapPlatformDeviceLinux* >(&platdev);
cairo_t* cairo_drawable = gdk_cairo_create(window);
cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
cairo_paint(cairo_drawable);
cairo_destroy(cairo_drawable);
gdk_window_end_paint(window);
}
void WebWidgetHost::ResetScrollRect() {
// This method is only needed for optimized scroll painting, which we don't
// care about in the test shell, yet.
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
set_painting(true);
webwidget_->Paint(canvas_.get(), rect);
set_painting(false);
}
void WebWidgetHost::WindowDestroyed() {
delete this;
}
<|endoftext|> |
<commit_before>#include <sofa/helper/system/FileSystem.h>
#include <sofa/helper/Utils.h>
#include <fstream>
#include <iostream>
#ifdef WIN32
# include <windows.h>
# include <strsafe.h>
# include "Shlwapi.h" // for PathFileExists()
#elif defined(_XBOX)
# include <xtl.h>
#else
# include <dirent.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <errno.h>
# include <string.h> // for strerror()
#endif
#include <assert.h>
namespace sofa
{
namespace helper
{
namespace system
{
#if defined(WIN32)
// Helper: call FindFirstFile, taking care of wstring to string conversion.
static HANDLE helper_FindFirstFile(std::string path, WIN32_FIND_DATA *ffd)
{
TCHAR szDir[MAX_PATH];
HANDLE hFind = INVALID_HANDLE_VALUE;
// Prepare string for use with FindFile functions. First, copy the
// string to a buffer, then append '\*' to the directory name.
StringCchCopy(szDir, MAX_PATH, Utils::widenString(path).c_str());
StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
// Find the first file in the directory.
hFind = FindFirstFile(szDir, ffd);
return hFind;
}
#elif defined (_XBOX)
static HANDLE helper_FindFirstFile(std::string path, WIN32_FIND_DATA *ffd)
{
char szDir[MAX_PATH];
HANDLE hFind = INVALID_HANDLE_VALUE;
// Prepare string for use with FindFile functions. First, copy the
// string to a buffer, then append '\*' to the directory name.
strcpy_s(szDir, MAX_PATH, path.c_str());
strcat_s(szDir, MAX_PATH, "\\*");
// Find the first file in the directory.
hFind = FindFirstFile(szDir, ffd);
return hFind;
}
#endif
bool FileSystem::listDirectory(const std::string& directoryPath,
std::vector<std::string>& outputFilenames)
{
#if defined(WIN32) || defined (_XBOX)
// Find the first file in the directory.
WIN32_FIND_DATA ffd;
HANDLE hFind = helper_FindFirstFile(directoryPath, &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
std::cerr << "FileSystem::listDirectory(\"" << directoryPath << "\"): "
<< Utils::GetLastError() << std::endl;
return false;
}
// Iterate over files and push them in the output vector
do {
# if defined (_XBOX)
std::string filename = ffd.cFileName;
# else
std::string filename = Utils::narrowString(ffd.cFileName);
# endif
if (filename != "." && filename != "..")
outputFilenames.push_back(filename);
} while (FindNextFile(hFind, &ffd) != 0);
// Check for errors
bool errorOccured = ::GetLastError() != ERROR_NO_MORE_FILES;
if (errorOccured)
std::cerr << "FileSystem::listDirectory(\"" << directoryPath << "\"): "
<< Utils::GetLastError() << std::endl;
FindClose(hFind);
return errorOccured;
#else
DIR *dp = opendir(directoryPath.c_str());
if (dp == NULL) {
std::cerr << "FileSystem::listDirectory(\"" << directoryPath << "\"): "
<< strerror(errno) << std::endl;
return true;
}
struct dirent *ep;
while ( (ep = readdir(dp)) ) {
const std::string filename(ep->d_name);
if (filename != "." && filename != "..")
outputFilenames.push_back(std::string(ep->d_name));
}
closedir(dp);
return false;
#endif
}
bool FileSystem::exists(const std::string& path)
{
#if defined(WIN32)
bool pathExists = PathFileExists(Utils::widenString(path).c_str()) != 0;
DWORD errorCode = ::GetLastError();
if (errorCode != 0) {
std::cerr << "FileSystem::exists(\"" << path << "\"): "
<< Utils::GetLastError() << std::endl;
}
return pathExists;
#elif defined (_XBOX)
DWORD fileAttrib = GetFileAttributes(path.c_str());
return fileAttrib != -1;
#else
struct stat st_buf;
if (stat(path.c_str(), &st_buf) == 0)
return true;
else
if (errno == ENOENT) // No such file or directory
return false;
else {
std::cerr << "FileSystem::exists(\"" << path << "\"): "
<< strerror(errno) << std::endl;
return false;
}
#endif
}
bool FileSystem::isDirectory(const std::string& path)
{
#if defined(WIN32)
DWORD fileAttrib = GetFileAttributes(Utils::widenString(path).c_str());
if (fileAttrib == INVALID_FILE_ATTRIBUTES) {
std::cerr << "FileSystem::isDirectory(\"" << path << "\"): "
<< Utils::GetLastError() << std::endl;
return false;
}
else
return (fileAttrib & FILE_ATTRIBUTE_DIRECTORY) != 0;
#elif defined (_XBOX)
DWORD fileAttrib = GetFileAttributes(path.c_str());
if (fileAttrib == -1) {
std::cerr << "FileSystem::isDirectory(\"" << path << "\"): "
<< Utils::GetLastError() << std::endl;
return false;
}
else
return (fileAttrib & FILE_ATTRIBUTE_DIRECTORY) != 0;
#else
struct stat st_buf;
if (stat(path.c_str(), &st_buf) != 0) {
std::cerr << "FileSystem::isDirectory(\"" << path << "\"): "
<< strerror(errno) << std::endl;
return false;
}
else
return S_ISDIR(st_buf.st_mode);
#endif
}
bool FileSystem::listDirectory(const std::string& directoryPath,
std::vector<std::string>& outputFilenames,
const std::string& extension)
{
// List directory
std::vector<std::string> files;
if (listDirectory(directoryPath, files))
return true;
// Filter files
for (std::size_t i=0 ; i!=files.size() ; i++) {
const std::string& filename = files[i];
if (filename.size() >= extension.size())
if (filename.compare(filename.size()-extension.size(),
std::string::npos, extension) == 0)
outputFilenames.push_back(filename);
}
return false;
}
static bool pathHasDrive(const std::string& path) {
return path.length() >=3
&& ((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z'))
&& path[1] == ':';
}
static std::string pathWithoutDrive(const std::string& path) {
return path.substr(2, std::string::npos);
}
static std::string pathDrive(const std::string& path) {
return path.substr(0, 2);
}
bool FileSystem::isAbsolute(const std::string& path)
{
return !path.empty()
&& (pathHasDrive(path)
|| path[0] == '/');
}
std::string FileSystem::convertBackSlashesToSlashes(const std::string& path)
{
std::string str = path;
size_t backSlashPos = str.find('\\');
while(backSlashPos != std::string::npos)
{
str[backSlashPos] = '/';
backSlashPos = str.find("\\");
}
return str;
}
std::string FileSystem::removeExtraSlashes(const std::string& path)
{
std::string str = path;
size_t pos = str.find("//");
while(pos != std::string::npos) {
str.replace(pos, 2, "/");
pos = str.find("//");
}
return str;
}
std::string FileSystem::cleanPath(const std::string& path)
{
return removeExtraSlashes(convertBackSlashesToSlashes(path));
}
static std::string computeParentDirectory(const std::string& path)
{
if (path == "")
return ".";
else if (path == "/")
return "/";
else if (path[path.length()-1] == '/')
return computeParentDirectory(path.substr(0, path.length() - 1));
else {
size_t last_slash = path.find_last_of('/');
if (last_slash == std::string::npos)
return ".";
else if (last_slash == 0)
return "/";
else if (last_slash == path.length())
return "";
else
return path.substr(0, last_slash);
}
}
std::string FileSystem::getParentDirectory(const std::string& path)
{
if (pathHasDrive(path)) // check for Windows drive
return pathDrive(path) + computeParentDirectory(pathWithoutDrive(path));
else
return computeParentDirectory(path);
}
std::string FileSystem::stripDirectory(const std::string& path)
{
if (pathHasDrive(path)) // check for Windows drive
return stripDirectory(pathWithoutDrive(path));
else
{
size_t last_slash = path.find_last_of("/");
if (last_slash == std::string::npos) // No slash
return path;
else if (last_slash == path.size() - 1) // Trailing slash
if (path.size() == 1)
return "/";
else
return stripDirectory(path.substr(0, path.size() - 1));
else
return path.substr(last_slash + 1, std::string::npos);
return "";
}
}
} // namespace system
} // namespace helper
} // namespace sofa
<commit_msg>FIX: error list when launching sofa with SofaPython on windows<commit_after>#include <sofa/helper/system/FileSystem.h>
#include <sofa/helper/Utils.h>
#include <fstream>
#include <iostream>
#ifdef WIN32
# include <windows.h>
# include <strsafe.h>
# include "Shlwapi.h" // for PathFileExists()
#elif defined(_XBOX)
# include <xtl.h>
#else
# include <dirent.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <errno.h>
# include <string.h> // for strerror()
#endif
#include <assert.h>
namespace sofa
{
namespace helper
{
namespace system
{
#if defined(WIN32)
// Helper: call FindFirstFile, taking care of wstring to string conversion.
static HANDLE helper_FindFirstFile(std::string path, WIN32_FIND_DATA *ffd)
{
TCHAR szDir[MAX_PATH];
HANDLE hFind = INVALID_HANDLE_VALUE;
// Prepare string for use with FindFile functions. First, copy the
// string to a buffer, then append '\*' to the directory name.
StringCchCopy(szDir, MAX_PATH, Utils::widenString(path).c_str());
StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
// Find the first file in the directory.
hFind = FindFirstFile(szDir, ffd);
return hFind;
}
#elif defined (_XBOX)
static HANDLE helper_FindFirstFile(std::string path, WIN32_FIND_DATA *ffd)
{
char szDir[MAX_PATH];
HANDLE hFind = INVALID_HANDLE_VALUE;
// Prepare string for use with FindFile functions. First, copy the
// string to a buffer, then append '\*' to the directory name.
strcpy_s(szDir, MAX_PATH, path.c_str());
strcat_s(szDir, MAX_PATH, "\\*");
// Find the first file in the directory.
hFind = FindFirstFile(szDir, ffd);
return hFind;
}
#endif
bool FileSystem::listDirectory(const std::string& directoryPath,
std::vector<std::string>& outputFilenames)
{
#if defined(WIN32) || defined (_XBOX)
// Find the first file in the directory.
WIN32_FIND_DATA ffd;
HANDLE hFind = helper_FindFirstFile(directoryPath, &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
std::cerr << "FileSystem::listDirectory(\"" << directoryPath << "\"): "
<< Utils::GetLastError() << std::endl;
return false;
}
// Iterate over files and push them in the output vector
do {
# if defined (_XBOX)
std::string filename = ffd.cFileName;
# else
std::string filename = Utils::narrowString(ffd.cFileName);
# endif
if (filename != "." && filename != "..")
outputFilenames.push_back(filename);
} while (FindNextFile(hFind, &ffd) != 0);
// Check for errors
bool errorOccured = ::GetLastError() != ERROR_NO_MORE_FILES;
if (errorOccured)
std::cerr << "FileSystem::listDirectory(\"" << directoryPath << "\"): "
<< Utils::GetLastError() << std::endl;
FindClose(hFind);
return errorOccured;
#else
DIR *dp = opendir(directoryPath.c_str());
if (dp == NULL) {
std::cerr << "FileSystem::listDirectory(\"" << directoryPath << "\"): "
<< strerror(errno) << std::endl;
return true;
}
struct dirent *ep;
while ( (ep = readdir(dp)) ) {
const std::string filename(ep->d_name);
if (filename != "." && filename != "..")
outputFilenames.push_back(std::string(ep->d_name));
}
closedir(dp);
return false;
#endif
}
bool FileSystem::exists(const std::string& path)
{
#if defined(WIN32)
if (PathFileExists(Utils::widenString(path).c_str()) != 0)
return true;
else
{
DWORD errorCode = ::GetLastError();
if (errorCode != 2) // not No such file error
std::cerr << "FileSystem::exists(\"" << path << "\"): "
<< Utils::GetLastError() << std::endl;
return false;
}
#elif defined (_XBOX)
DWORD fileAttrib = GetFileAttributes(path.c_str());
return fileAttrib != -1;
#else
struct stat st_buf;
if (stat(path.c_str(), &st_buf) == 0)
return true;
else
if (errno == ENOENT) // No such file or directory
return false;
else {
std::cerr << "FileSystem::exists(\"" << path << "\"): "
<< strerror(errno) << std::endl;
return false;
}
#endif
}
bool FileSystem::isDirectory(const std::string& path)
{
#if defined(WIN32)
DWORD fileAttrib = GetFileAttributes(Utils::widenString(path).c_str());
if (fileAttrib == INVALID_FILE_ATTRIBUTES) {
std::cerr << "FileSystem::isDirectory(\"" << path << "\"): "
<< Utils::GetLastError() << std::endl;
return false;
}
else
return (fileAttrib & FILE_ATTRIBUTE_DIRECTORY) != 0;
#elif defined (_XBOX)
DWORD fileAttrib = GetFileAttributes(path.c_str());
if (fileAttrib == -1) {
std::cerr << "FileSystem::isDirectory(\"" << path << "\"): "
<< Utils::GetLastError() << std::endl;
return false;
}
else
return (fileAttrib & FILE_ATTRIBUTE_DIRECTORY) != 0;
#else
struct stat st_buf;
if (stat(path.c_str(), &st_buf) != 0) {
std::cerr << "FileSystem::isDirectory(\"" << path << "\"): "
<< strerror(errno) << std::endl;
return false;
}
else
return S_ISDIR(st_buf.st_mode);
#endif
}
bool FileSystem::listDirectory(const std::string& directoryPath,
std::vector<std::string>& outputFilenames,
const std::string& extension)
{
// List directory
std::vector<std::string> files;
if (listDirectory(directoryPath, files))
return true;
// Filter files
for (std::size_t i=0 ; i!=files.size() ; i++) {
const std::string& filename = files[i];
if (filename.size() >= extension.size())
if (filename.compare(filename.size()-extension.size(),
std::string::npos, extension) == 0)
outputFilenames.push_back(filename);
}
return false;
}
static bool pathHasDrive(const std::string& path) {
return path.length() >=3
&& ((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z'))
&& path[1] == ':';
}
static std::string pathWithoutDrive(const std::string& path) {
return path.substr(2, std::string::npos);
}
static std::string pathDrive(const std::string& path) {
return path.substr(0, 2);
}
bool FileSystem::isAbsolute(const std::string& path)
{
return !path.empty()
&& (pathHasDrive(path)
|| path[0] == '/');
}
std::string FileSystem::convertBackSlashesToSlashes(const std::string& path)
{
std::string str = path;
size_t backSlashPos = str.find('\\');
while(backSlashPos != std::string::npos)
{
str[backSlashPos] = '/';
backSlashPos = str.find("\\");
}
return str;
}
std::string FileSystem::removeExtraSlashes(const std::string& path)
{
std::string str = path;
size_t pos = str.find("//");
while(pos != std::string::npos) {
str.replace(pos, 2, "/");
pos = str.find("//");
}
return str;
}
std::string FileSystem::cleanPath(const std::string& path)
{
return removeExtraSlashes(convertBackSlashesToSlashes(path));
}
static std::string computeParentDirectory(const std::string& path)
{
if (path == "")
return ".";
else if (path == "/")
return "/";
else if (path[path.length()-1] == '/')
return computeParentDirectory(path.substr(0, path.length() - 1));
else {
size_t last_slash = path.find_last_of('/');
if (last_slash == std::string::npos)
return ".";
else if (last_slash == 0)
return "/";
else if (last_slash == path.length())
return "";
else
return path.substr(0, last_slash);
}
}
std::string FileSystem::getParentDirectory(const std::string& path)
{
if (pathHasDrive(path)) // check for Windows drive
return pathDrive(path) + computeParentDirectory(pathWithoutDrive(path));
else
return computeParentDirectory(path);
}
std::string FileSystem::stripDirectory(const std::string& path)
{
if (pathHasDrive(path)) // check for Windows drive
return stripDirectory(pathWithoutDrive(path));
else
{
size_t last_slash = path.find_last_of("/");
if (last_slash == std::string::npos) // No slash
return path;
else if (last_slash == path.size() - 1) // Trailing slash
if (path.size() == 1)
return "/";
else
return stripDirectory(path.substr(0, path.size() - 1));
else
return path.substr(last_slash + 1, std::string::npos);
return "";
}
}
} // namespace system
} // namespace helper
} // namespace sofa
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Yahoo! Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This is a stub implementation of the mapkeeper interface that uses
* std::map. Data is not persisted. The server is not thread-safe.
*/
#include <cstdio>
#include "MapKeeper.h"
#include <boost/thread/shared_mutex.hpp>
#include <protocol/TBinaryProtocol.h>
#include <server/TThreadedServer.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::apache::thrift::concurrency;
using boost::shared_ptr;
using namespace mapkeeper;
class StlMapServer: virtual public MapKeeperIf {
public:
StlMapServer() {
}
ResponseCode::type ping() {
return ResponseCode::Success;
}
ResponseCode::type addMap(const std::string& mapName) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
itr_ = maps_.find(mapName);
if (itr_ != maps_.end()) {
return ResponseCode::MapExists;
}
std::map<std::string, std::string> newMap;
std::pair<std::string, std::map<std::string, std::string> > entry(mapName, newMap);
maps_.insert(entry);
return ResponseCode::Success;
}
ResponseCode::type dropMap(const std::string& mapName) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
itr_ = maps_.find(mapName);
if (itr_ == maps_.end()) {
return ResponseCode::MapNotFound;
}
maps_.erase(itr_);
return ResponseCode::Success;
}
void listMaps(StringListResponse& _return) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
for (itr_ = maps_.begin(); itr_ != maps_.end(); itr_++) {
_return.values.push_back(itr_->first);
}
_return.responseCode = ResponseCode::Success;
}
void scan(RecordListResponse& _return, const std::string& mapName, const ScanOrder::type order, const std::string& startKey, const bool startKeyIncluded, const std::string& endKey, const bool endKeyIncluded, const int32_t maxRecords, const int32_t maxBytes) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
}
void get(BinaryResponse& _return, const std::string& mapName, const std::string& key) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
itr_ = maps_.find(mapName);
if (itr_ == maps_.end()) {
_return.responseCode = ResponseCode::MapNotFound;
return;
}
recordIterator_ = itr_->second.find(key);
if (recordIterator_ == itr_->second.end()) {
_return.responseCode = ResponseCode::RecordNotFound;
return;
}
_return.responseCode = ResponseCode::Success;
_return.value = recordIterator_->second;
}
ResponseCode::type put(const std::string& mapName, const std::string& key, const std::string& value) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
itr_ = maps_.find(mapName);
if (itr_ == maps_.end()) {
return ResponseCode::MapNotFound;
}
itr_->second[key] = value;
return ResponseCode::Success;
}
ResponseCode::type insert(const std::string& mapName, const std::string& key, const std::string& value) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
itr_ = maps_.find(mapName);
if (itr_ == maps_.end()) {
return ResponseCode::MapNotFound;
}
if (itr_->second.find(key) != itr_->second.end()) {
return ResponseCode::RecordExists;
}
itr_->second.insert(std::pair<std::string, std::string>(key, value));
return ResponseCode::Success;
}
ResponseCode::type update(const std::string& mapName, const std::string& key, const std::string& value) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
itr_ = maps_.find(mapName);
if (itr_ == maps_.end()) {
return ResponseCode::MapNotFound;
}
if (itr_->second.find(key) == itr_->second.end()) {
return ResponseCode::RecordNotFound;
}
itr_->second[key] = value;
return ResponseCode::Success;
}
ResponseCode::type remove(const std::string& mapName, const std::string& key) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
itr_ = maps_.find(mapName);
if (itr_ == maps_.end()) {
return ResponseCode::MapNotFound;
}
recordIterator_ = itr_->second.find(key);
if (recordIterator_ == itr_->second.end()) {
return ResponseCode::RecordNotFound;
}
itr_->second.erase(recordIterator_);
return ResponseCode::Success;
}
private:
std::map<std::string, std::map<std::string, std::string> > maps_;
boost::shared_mutex mutex_; // protect map_
std::map<std::string, std::map<std::string, std::string> >::iterator itr_;
std::map<std::string, std::string>::iterator recordIterator_;
};
int main(int argc, char **argv) {
int port = 9090;
shared_ptr<StlMapServer> handler(new StlMapServer());
shared_ptr<TProcessor> processor(new MapKeeperProcessor(handler));
shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
shared_ptr<TTransportFactory> transportFactory(new TFramedTransportFactory());
shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TThreadedServer server(processor, serverTransport, transportFactory, protocolFactory);
server.serve();
return 0;
}
<commit_msg>added scan for stl map server.<commit_after>/*
* Copyright 2012 Yahoo! Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This is a stub implementation of the mapkeeper interface that uses
* std::map. Data is not persisted.
*/
#include <map>
#include <string>
#include <arpa/inet.h>
#include "MapKeeper.h"
#include <boost/thread/shared_mutex.hpp>
#include <protocol/TBinaryProtocol.h>
#include <server/TThreadedServer.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>
using namespace std;
using namespace mapkeeper;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using boost::shared_ptr;
class StlMapServer: virtual public MapKeeperIf {
public:
ResponseCode::type ping() {
return ResponseCode::Success;
}
ResponseCode::type addMap(const string& mapName) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
map<string, map<string, string> >::iterator itr = maps_.find(mapName);
if (itr != maps_.end()) {
return ResponseCode::MapExists;
}
map<string, string> newMap;
pair<string, map<string, string> > entry(mapName, newMap);
maps_.insert(entry);
return ResponseCode::Success;
}
ResponseCode::type dropMap(const string& mapName) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
map<string, map<string, string> >::iterator itr = maps_.find(mapName);
if (itr == maps_.end()) {
return ResponseCode::MapNotFound;
}
maps_.erase(itr);
return ResponseCode::Success;
}
void listMaps(StringListResponse& _return) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
map<string, map<string, string> >::iterator itr;
for (itr = maps_.begin(); itr != maps_.end(); itr++) {
_return.values.push_back(itr->first);
}
_return.responseCode = ResponseCode::Success;
}
void scan(RecordListResponse& _return, const string& mapName, const ScanOrder::type order,
const string& startKey, const bool startKeyIncluded,
const string& endKey, const bool endKeyIncluded,
const int32_t maxRecords, const int32_t maxBytes) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
map<string, map<string, string> >::iterator itr = maps_.find(mapName);
if (itr == maps_.end()) {
_return.responseCode = ResponseCode::MapNotFound;
return;
}
if (order == ScanOrder::Ascending) {
scanAscending(_return, itr->second, startKey, startKeyIncluded, endKey, endKeyIncluded, maxRecords, maxBytes);
} else {
scanDescending(_return, itr->second, startKey, startKeyIncluded, endKey, endKeyIncluded, maxRecords, maxBytes);
}
}
void scanAscending(RecordListResponse& _return, const map<string, string>& mymap,
const string& startKey, const bool startKeyIncluded,
const string& endKey, const bool endKeyIncluded,
const int32_t maxRecords, const int32_t maxBytes) {
map<string, string>::const_iterator itr = startKeyIncluded ?
mymap.lower_bound(startKey):
mymap.upper_bound(startKey);
int numBytes = 0;
while (itr != mymap.end()) {
if (!endKey.empty()) {
if (endKeyIncluded && endKey < itr->first) {
break;
}
if (!endKeyIncluded && endKey <= itr->first) {
break;
}
}
Record record;
record.key = itr->first;
record.value = itr->second;
numBytes += record.key.size() + record.value.size();
_return.records.push_back(record);
if (_return.records.size() >= (uint32_t)maxRecords || numBytes >= maxBytes) {
_return.responseCode = ResponseCode::Success;
return;
}
itr++;
}
_return.responseCode = ResponseCode::ScanEnded;
}
void scanDescending(RecordListResponse& _return, const map<string, string>& mymap,
const string& startKey, const bool startKeyIncluded,
const string& endKey, const bool endKeyIncluded,
const int32_t maxRecords, const int32_t maxBytes) {
map<string, string>::const_iterator itr;
if (endKey.empty()) {
itr = mymap.end();
} else {
itr = endKeyIncluded ? mymap.upper_bound(endKey) : mymap.lower_bound(endKey);
}
int numBytes = 0;
while (itr != mymap.begin()) {
itr--;
if (startKeyIncluded && startKey > itr->first) {
break;
}
if (!startKeyIncluded && startKey >= itr->first) {
break;
}
Record record;
record.key = itr->first;
record.value = itr->second;
numBytes += record.key.size() + record.value.size();
_return.records.push_back(record);
if (_return.records.size() >= (uint32_t)maxRecords || numBytes >= maxBytes) {
_return.responseCode = ResponseCode::Success;
return;
}
}
_return.responseCode = ResponseCode::ScanEnded;
}
void get(BinaryResponse& _return, const string& mapName, const string& key) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
map<string, map<string, string> >::iterator itr = maps_.find(mapName);
if (itr == maps_.end()) {
_return.responseCode = ResponseCode::MapNotFound;
return;
}
map<string, string>::iterator recordIterator = itr->second.find(key);
if (recordIterator == itr->second.end()) {
_return.responseCode = ResponseCode::RecordNotFound;
return;
}
_return.responseCode = ResponseCode::Success;
_return.value = recordIterator->second;
}
ResponseCode::type put(const string& mapName, const string& key, const string& value) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
map<string, map<string, string> >::iterator itr = maps_.find(mapName);
if (itr == maps_.end()) {
return ResponseCode::MapNotFound;
}
itr->second[key] = value;
return ResponseCode::Success;
}
ResponseCode::type insert(const string& mapName, const string& key, const string& value) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
map<string, map<string, string> >::iterator itr = maps_.find(mapName);
if (itr == maps_.end()) {
return ResponseCode::MapNotFound;
}
if (itr->second.find(key) != itr->second.end()) {
return ResponseCode::RecordExists;
}
itr->second.insert(pair<string, string>(key, value));
return ResponseCode::Success;
}
ResponseCode::type update(const string& mapName, const string& key, const string& value) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
map<string, map<string, string> >::iterator itr = maps_.find(mapName);
if (itr == maps_.end()) {
return ResponseCode::MapNotFound;
}
if (itr->second.find(key) == itr->second.end()) {
return ResponseCode::RecordNotFound;
}
itr->second[key] = value;
return ResponseCode::Success;
}
ResponseCode::type remove(const string& mapName, const string& key) {
boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
map<string, map<string, string> >::iterator itr = maps_.find(mapName);
if (itr == maps_.end()) {
return ResponseCode::MapNotFound;
}
map<string, string>::iterator recordIterator = itr->second.find(key);
if (recordIterator == itr->second.end()) {
return ResponseCode::RecordNotFound;
}
itr->second.erase(recordIterator);
return ResponseCode::Success;
}
private:
map<string, map<string, string> > maps_;
boost::shared_mutex mutex_; // protect map_
};
int main(int argc, char **argv) {
int port = 9090;
shared_ptr<StlMapServer> handler(new StlMapServer());
shared_ptr<TProcessor> processor(new MapKeeperProcessor(handler));
shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
shared_ptr<TTransportFactory> transportFactory(new TFramedTransportFactory());
shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TThreadedServer server(processor, serverTransport, transportFactory, protocolFactory);
server.serve();
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013-2014 Sam Hardeman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "Modules.h"
#include "OpCodeHandler.h"
#include "NetworkControl.h"
#include "PacketSender.h"
#include "Packet.h"
#include "Client.h"
#include "IceNetServer.h"
#include "IceNetTypedefs.h"
#include <time.h>
namespace IceNet
{
unsigned short RandomID( void )
{
unsigned short id = 0;
while ( 1 )
{
id = rand() & USHRT_MAX;
if ( id <= 256 ) continue;
break;
}
return id;
}
DWORD WINAPI ListenerEntry( void* ptr )
{
srand( (unsigned int) time( 0 ) );
rand();
while ( true )
{
// Poll for stop condition
if ( WaitForSingleObject( NetworkControl::GetSingleton()->m_StopRequestedEvent, 0 ) == WAIT_OBJECT_0 )
{
break;
}
// Accept a new connection (blocking)
SOCKET clientSock = accept( NetworkControl::GetSingleton()->m_SocketTCP, NULL, NULL );
// If something went wrong, simply continue;
if ( clientSock == -1 )
{
continue;
}
unsigned short publicId = RandomID();
unsigned short privateId = RandomID();
while ( NetworkControl::GetSingleton()->m_PublicIdClientMap[ publicId ] != 0 ) publicId = RandomID();
while ( NetworkControl::GetSingleton()->m_PrivateIdClientMap[ privateId ] != 0 ) privateId = RandomID();
// Create a new client
Client* newClientObj = NetworkControl::GetSingleton()->AddClient( publicId, privateId, false, clientSock );
// Call the callback if it exists
VOID_WITH_CLIENT_PARAM fun = ServerSide::GetOnAddClient();
if ( fun != 0 ) fun( newClientObj );
// Ship the new client's IDs back.
Packet* sendidpack = new Packet();
sendidpack->SetOpCodeInternal( OpCodeHandler::GET_ID );
sendidpack->AddDataStreaming<unsigned short>( (unsigned short) newClientObj->m_PublicId );
sendidpack->AddDataStreaming<unsigned short>( (unsigned short) newClientObj->m_PrivateId );
sendidpack->SetUDPEnabled( false );
newClientObj->GetSenderObject()->AddToQueue( sendidpack );
// Broadcast the public ID to all other clients.
Packet* broadcast = new Packet();
broadcast->SetOpCodeInternal( OpCodeHandler::ADD_CLIENT );
broadcast->AddDataStreaming<unsigned short>( (unsigned short) newClientObj->m_PublicId );
broadcast->SetClientPrivateId( newClientObj->m_PrivateId );
broadcast->SetFlag( Packet::PF_EXCLUDEORIGIN );
sendidpack->SetUDPEnabled( false );
NetworkControl::GetSingleton()->BroadcastToAll( broadcast );
if ( NetworkControl::GetSingleton()->m_ClientIds.size() > 0 )
{
for ( unsigned int i = 0; i < NetworkControl::GetSingleton()->m_ClientIds.size(); i++ )
{
if ( NetworkControl::GetSingleton()->m_ClientIds[i].publicId != publicId )
{
Packet* pack = new Packet();
pack->SetOpCodeInternal( OpCodeHandler::ADD_CLIENT );
pack->AddDataStreaming<unsigned short>( (unsigned short) NetworkControl::GetSingleton()->m_ClientIds[i].publicId );
pack->SetClientPrivateId( privateId );
newClientObj->GetSenderObject()->AddToQueue( pack );
}
}
}
}
return 1;
}
};<commit_msg>Small formatting error.<commit_after>/*
Copyright (c) 2013-2014 Sam Hardeman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "Modules.h"
#include "OpCodeHandler.h"
#include "NetworkControl.h"
#include "PacketSender.h"
#include "Packet.h"
#include "Client.h"
#include "IceNetServer.h"
#include "IceNetTypedefs.h"
#include <time.h>
namespace IceNet
{
unsigned short RandomID( void )
{
unsigned short id = 0;
while ( 1 )
{
id = rand() & USHRT_MAX;
if ( id <= 256 ) continue;
break;
}
return id;
}
DWORD WINAPI ListenerEntry( void* ptr )
{
srand( (unsigned int) time( 0 ) );
rand();
while ( true )
{
// Poll for stop condition
if ( WaitForSingleObject( NetworkControl::GetSingleton()->m_StopRequestedEvent, 0 ) == WAIT_OBJECT_0 )
{
break;
}
// Accept a new connection (blocking)
SOCKET clientSock = accept( NetworkControl::GetSingleton()->m_SocketTCP, NULL, NULL );
// If something went wrong, simply continue;
if ( clientSock == -1 )
{
continue;
}
unsigned short publicId = RandomID();
unsigned short privateId = RandomID();
while ( NetworkControl::GetSingleton()->m_PublicIdClientMap[ publicId ] != 0 ) publicId = RandomID();
while ( NetworkControl::GetSingleton()->m_PrivateIdClientMap[ privateId ] != 0 ) privateId = RandomID();
// Create a new client
Client* newClientObj = NetworkControl::GetSingleton()->AddClient( publicId, privateId, false, clientSock );
// Call the callback if it exists
VOID_WITH_CLIENT_PARAM fun = ServerSide::GetOnAddClient();
if ( fun != 0 ) fun( newClientObj );
// Ship the new client's IDs back.
Packet* sendidpack = new Packet();
sendidpack->SetOpCodeInternal( OpCodeHandler::GET_ID );
sendidpack->AddDataStreaming<unsigned short>( (unsigned short) newClientObj->m_PublicId );
sendidpack->AddDataStreaming<unsigned short>( (unsigned short) newClientObj->m_PrivateId );
sendidpack->SetUDPEnabled( false );
newClientObj->GetSenderObject()->AddToQueue( sendidpack );
// Broadcast the public ID to all other clients.
Packet* broadcast = new Packet();
broadcast->SetOpCodeInternal( OpCodeHandler::ADD_CLIENT );
broadcast->AddDataStreaming<unsigned short>( (unsigned short) newClientObj->m_PublicId );
broadcast->SetClientPrivateId( newClientObj->m_PrivateId );
broadcast->SetFlag( Packet::PF_EXCLUDEORIGIN );
sendidpack->SetUDPEnabled( false );
NetworkControl::GetSingleton()->BroadcastToAll( broadcast );
if ( NetworkControl::GetSingleton()->m_ClientIds.size() > 0 )
{
for ( unsigned int i = 0; i < NetworkControl::GetSingleton()->m_ClientIds.size(); i++ )
{
if ( NetworkControl::GetSingleton()->m_ClientIds[i].publicId != publicId )
{
Packet* pack = new Packet();
pack->SetOpCodeInternal( OpCodeHandler::ADD_CLIENT );
pack->AddDataStreaming<unsigned short>( (unsigned short) NetworkControl::GetSingleton()->m_ClientIds[i].publicId );
pack->SetClientPrivateId( privateId );
newClientObj->GetSenderObject()->AddToQueue( pack );
}
}
}
}
return 1;
}
};<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#if !defined(CPPLINQ_LINQ_TAKE_HPP)
#define CPPLINQ_LINQ_TAKE_HPP
#pragma once
namespace cpplinq
{
template <class InnerCursor>
struct linq_take_cursor
{
typedef typename InnerCursor::element_type element_type;
typedef typename InnerCursor::reference_type reference_type;
typedef typename InnerCursor::cursor_category cursor_category;
linq_take_cursor(const InnerCursor& cur, size_t rem) : cur(cur), rem(rem) {}
void forget() { cur.forget(); }
bool empty() const { return cur.empty() || rem == 0; }
void inc() { cur.inc(); --rem; }
reference_type get() const { return cur.get(); }
bool atbegin() const { return cur.atbegin(); }
void dec() { cur.dec(); --rem; }
void skip(size_t n) { cur.skip(n); rem -= n; }
size_t position() const { return cur.position(); }
size_t size() const { return cur.size(); }
private:
InnerCursor cur;
size_t rem;
};
namespace detail {
template <class Collection>
linq_take_cursor<typename Collection::cursor>
take_get_cursor_(
const Collection& c,
size_t n,
onepass_cursor_tag
)
{
return linq_take_cursor<typename Collection::cursor>(c.get_cursor(), n);
}
template <class Collection>
typename Collection::cursor
take_get_cursor_(
const Collection& c,
size_t n,
random_access_cursor_tag
)
{
auto cur = c.get_cursor();
if (cur.size() > n) {
cur.truncate(n);
}
return cur;
}
}
template <class Collection>
struct linq_take
{
typedef typename std::conditional<
util::less_or_equal_cursor_category<
random_access_cursor_tag,
typename Collection::cursor::cursor_category>::value,
typename Collection::cursor,
linq_take_cursor<typename Collection::cursor>>::type
cursor;
linq_take(const Collection& c, size_t n) : c(c), n(n) {}
cursor get_cursor() const {
return detail::take_get_cursor_(c, n, typename Collection::cursor::cursor_category());
}
Collection c;
size_t n;
};
template <class Collection>
auto get_cursor(
const linq_take<Collection>& take
)
-> decltype(get_cursor_(take, typename Collection::cursor::cursor_category()))
{
return get_cursor_(take, typename Collection::cursor::cursor_category());
}
}
#endif // !defined(CPPLINQ_LINQ_TAKE_HPP)
<commit_msg>Update linq_take.hpp<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#if !defined(CPPLINQ_LINQ_TAKE_HPP)
#define CPPLINQ_LINQ_TAKE_HPP
#pragma once
#include <cstddef>
namespace cpplinq
{
template <class InnerCursor>
struct linq_take_cursor
{
typedef typename InnerCursor::element_type element_type;
typedef typename InnerCursor::reference_type reference_type;
typedef typename InnerCursor::cursor_category cursor_category;
linq_take_cursor(const InnerCursor& cur, std::size_t rem) : cur(cur), rem(rem) {}
void forget() { cur.forget(); }
bool empty() const { return cur.empty() || rem == 0; }
void inc() { cur.inc(); --rem; }
reference_type get() const { return cur.get(); }
bool atbegin() const { return cur.atbegin(); }
void dec() { cur.dec(); --rem; }
void skip(std::size_t n) { cur.skip(n); rem -= n; }
std::size_t position() const { return cur.position(); }
std::size_t size() const { return cur.size(); }
private:
InnerCursor cur;
std::size_t rem;
};
namespace detail {
template <class Collection>
linq_take_cursor<typename Collection::cursor>
take_get_cursor_(
const Collection& c,
std::size_t n,
onepass_cursor_tag
)
{
return linq_take_cursor<typename Collection::cursor>(c.get_cursor(), n);
}
template <class Collection>
typename Collection::cursor
take_get_cursor_(
const Collection& c,
std::size_t n,
random_access_cursor_tag
)
{
auto cur = c.get_cursor();
if (cur.size() > n) {
cur.truncate(n);
}
return cur;
}
}
template <class Collection>
struct linq_take
{
typedef typename std::conditional<
util::less_or_equal_cursor_category<
random_access_cursor_tag,
typename Collection::cursor::cursor_category>::value,
typename Collection::cursor,
linq_take_cursor<typename Collection::cursor>>::type
cursor;
linq_take(const Collection& c, std::size_t n) : c(c), n(n) {}
cursor get_cursor() const {
return detail::take_get_cursor_(c, n, typename Collection::cursor::cursor_category());
}
Collection c;
std::size_t n;
};
template <class Collection>
auto get_cursor(
const linq_take<Collection>& take
)
-> decltype(get_cursor_(take, typename Collection::cursor::cursor_category()))
{
return get_cursor_(take, typename Collection::cursor::cursor_category());
}
}
#endif // !defined(CPPLINQ_LINQ_TAKE_HPP)
<|endoftext|> |
<commit_before>#include "common.h"
#include "GL32Renderer.h"
#include "ModelComponent.h"
bool GL32Renderer::IsSupported() {
GL32Renderer renderer(nullptr);
try {
auto e = std::runtime_error(BASEFILE);
renderer.InitGL();
GLint major, minor;
if(!GL(glGetIntegerv(GL_MAJOR_VERSION, &major))) { throw e; }
if(!GL(glGetIntegerv(GL_MINOR_VERSION, &minor))) { throw e; }
/* if OpenGL version is 3.2 or greater */
if(!(major > 3 || (major == 3 && minor >= 2))) {
ENGINE_ERROR("actual OpenGL version is " << major << '.' << minor);
throw e;
}
renderer.Destroy();
} catch(std::exception &) {
renderer.Destroy();
return false;
}
return true;
}
void GL32Renderer::InitGL() {
auto e = std::runtime_error(BASEFILE);
if(!SDL(SDL_Init(SDL_INIT_EVERYTHING))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8))) { throw e; }
if(!SDL(window = SDL_CreateWindow("Polar Engine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN))) { throw e; }
if(!SDL(context = SDL_GL_CreateContext(window))) { throw e; }
if(!SDL(SDL_GL_SetSwapInterval(1))) { throw e; }
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if(err != GLEW_OK) {
ENGINE_ERROR("GLEW: glewInit failed");
throw e;
}
/* GLEW cals glGetString(EXTENSIONS) which
* causes GL_INVALID_ENUM on GL 3.2+ core contexts
*/
IGNORE_GL(false);
}
void GL32Renderer::Init() {
InitGL();
ENGINE_DEBUG(engine->systems.Get<AssetManager>()->Get<TextAsset>("hello").text);
}
GLuint vao;
GLuint vbo;
void GL32Renderer::Update(DeltaTicks &dt, std::vector<Object *> &objects) {
SDL_Event event;
while(SDL_PollEvent(&event)) {
HandleSDL(event);
}
static glm::fvec4 color;
color.x += 0.001f; color.y += 0.0025f; color.z += 0.005f;
SetClearColor(color);
GL(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
static float rot = 0;
static float previousRot = 0;
static DeltaTicks accumulator;
const DeltaTicks timestep = DeltaTicks(ENGINE_TICKS_PER_SECOND / 7);
accumulator += dt;
while(accumulator >= timestep) {
previousRot = rot;
rot += 90.0f * timestep.count() / ENGINE_TICKS_PER_SECOND;
accumulator -= timestep;
}
float alpha = (float)accumulator.count() / (float)timestep.count();
GL(glLoadIdentity());
GL(glRotatef(rot * alpha + previousRot * (1 - alpha), 0, 0, 1));
GL(glBegin(GL_TRIANGLES));
for(auto object : objects) {
auto model = object->Get<ModelComponent>();
if(model != nullptr) {
for(auto point : model->points) {
GL(glVertex4f(point.x, point.y, point.z, point.w));
}
}
}
IGNORE_GL(glEnd());
GL(glDrawArrays(GL_TRIANGLES, 0, 3));
SDL(SDL_GL_SwapWindow(window));
}
void GL32Renderer::Destroy() {
SDL(SDL_GL_DeleteContext(context));
SDL(SDL_DestroyWindow(window));
SDL(SDL_GL_ResetAttributes());
SDL(SDL_Quit());
}
void GL32Renderer::ObjectAdded(Object *object) {
auto model = object->Get<ModelComponent>();
if(model != nullptr) {
auto &points = model->points;
auto v = points.data();
GL(glGenVertexArrays(1, &vao));
GL(glBindVertexArray(vao));
GL(glGenBuffers(1, &vbo));
GL(glBindBuffer(GL_ARRAY_BUFFER, vbo));
GL(glBufferData(GL_ARRAY_BUFFER, sizeof(Point) * points.size(), points.data(), GL_STATIC_DRAW));
}
}
void GL32Renderer::HandleSDL(SDL_Event &event) {
switch(event.type) {
case SDL_QUIT:
engine->systems.Get<EventManager>()->Fire("destroy");
break;
}
}
void GL32Renderer::SetClearColor(const glm::fvec4 &color) {
GL(glClearColor(color.x, color.y, color.z, color.w));
}
<commit_msg>Fixed OpenGL 3.2 renderer issues on OS X.<commit_after>#include "common.h"
#include "GL32Renderer.h"
#include "ModelComponent.h"
bool GL32Renderer::IsSupported() {
GL32Renderer renderer(nullptr);
try {
auto e = std::runtime_error(BASEFILE);
renderer.InitGL();
GLint major, minor;
if(!GL(glGetIntegerv(GL_MAJOR_VERSION, &major))) { throw e; }
if(!GL(glGetIntegerv(GL_MINOR_VERSION, &minor))) { throw e; }
/* if OpenGL version is 3.2 or greater */
if(!(major > 3 || (major == 3 && minor >= 2))) {
ENGINE_ERROR("actual OpenGL version is " << major << '.' << minor);
throw e;
}
renderer.Destroy();
} catch(std::exception &) {
renderer.Destroy();
return false;
}
return true;
}
void GL32Renderer::InitGL() {
auto e = std::runtime_error(BASEFILE);
if(!SDL(SDL_Init(SDL_INIT_EVERYTHING))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1))) { throw e; }
if(!SDL(SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8))) { throw e; }
if(!SDL(window = SDL_CreateWindow("Polar Engine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN))) { throw e; }
if(!SDL(context = SDL_GL_CreateContext(window))) { throw e; }
if(!SDL(SDL_GL_SetSwapInterval(1))) { throw e; }
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if(err != GLEW_OK) {
ENGINE_ERROR("GLEW: glewInit failed");
throw e;
}
/* GLEW cals glGetString(EXTENSIONS) which
* causes GL_INVALID_ENUM on GL 3.2+ core contexts
*/
IGNORE_GL(false);
}
void GL32Renderer::Init() {
InitGL();
//ENGINE_DEBUG(engine->systems.Get<AssetManager>()->Get<TextAsset>("hello").text);
}
GLuint vao;
GLuint vbo;
void GL32Renderer::Update(DeltaTicks &dt, std::vector<Object *> &objects) {
SDL_Event event;
while(SDL_PollEvent(&event)) {
HandleSDL(event);
}
SDL_ClearError();
static glm::fvec4 color;
color.x += 0.001f; color.y += 0.0025f; color.z += 0.005f;
SetClearColor(color);
GL(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
static float rot = 0;
static float previousRot = 0;
static DeltaTicks accumulator;
const DeltaTicks timestep = DeltaTicks(ENGINE_TICKS_PER_SECOND / 7);
accumulator += dt;
while(accumulator >= timestep) {
previousRot = rot;
rot += 90.0f * timestep.count() / ENGINE_TICKS_PER_SECOND;
accumulator -= timestep;
}
float alpha = (float)accumulator.count() / (float)timestep.count();
float interpRot = rot * alpha + previousRot * (1 - alpha);
/*GL(glLoadIdentity());
GL(glRotatef(interpRot, 0, 0, 1));
GL(glBegin(GL_TRIANGLES));
for(auto object : objects) {
auto model = object->Get<ModelComponent>();
if(model != nullptr) {
for(auto point : model->points) {
GL(glVertex4f(point.x, point.y, point.z, point.w));
}
}
}
IGNORE_GL(glEnd());*/
//GL(glDrawArrays(GL_TRIANGLES, 0, 3));
SDL(SDL_GL_SwapWindow(window));
}
void GL32Renderer::Destroy() {
SDL(SDL_GL_DeleteContext(context));
SDL(SDL_DestroyWindow(window));
SDL(SDL_GL_ResetAttributes());
SDL(SDL_Quit());
}
void GL32Renderer::ObjectAdded(Object *object) {
auto model = object->Get<ModelComponent>();
if(model != nullptr) {
auto &points = model->points;
auto v = points.data();
GL(glGenVertexArrays(1, &vao));
GL(glBindVertexArray(vao));
GL(glGenBuffers(1, &vbo));
GL(glBindBuffer(GL_ARRAY_BUFFER, vbo));
GL(glBufferData(GL_ARRAY_BUFFER, sizeof(Point) * points.size(), points.data(), GL_STATIC_DRAW));
}
}
void GL32Renderer::HandleSDL(SDL_Event &event) {
switch(event.type) {
case SDL_QUIT:
engine->systems.Get<EventManager>()->Fire("destroy");
break;
}
}
void GL32Renderer::SetClearColor(const glm::fvec4 &color) {
GL(glClearColor(color.x, color.y, color.z, color.w));
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Kamil Michalak <kmichalak8@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef ACTION_H
#define ACTION_H
#include <string>
#include <assert.h>
#include <jsoncpp/json/json.h>
#include "inc/stringutils.hpp"
#include "inc/config.hpp"
#include "inc/restclient.hpp"
namespace jippi {
/**
* An abstract class representing basic Jira command line client action.
* This class should be used as a base for further actions such as getting,
* creating, deleting issues, etc.
*
* Current implementation allows to specify
*/
class Action
{
public:
Action() {
configuration = new Config(DEFAULT_CONFIG_FILE, DEFAULT_CONFIG_FILE_LOCATION);
restClient = new RestClient();
}
virtual ~Action() {
delete restClient;
delete configuration;
};
inline void withIssue(std::string issue)
{
assertValidStringParam(issue, "Issue ID cannot be an empty string!");
json["issue"] = issue;
}
inline void withProject(std::string project)
{
assertValidStringParam(project, "Project ID cannot be an empty string!");
this->json["jql"] = "project = " + project;
}
inline void withAssignee(std::string assignee)
{
assertValidStringParam(assignee, "Assignee ID cannot be an empty string!");
json["assignee"] = assignee;
}
//-----------------------------------------------------------------------
// new parameters that need to be implemented in argumants handler
//-----------------------------------------------------------------------
inline void withMaxResults(int maxResults)
{
assert(maxResults > 0 && "Max number of results should be greater than 0!");
json["maxResults"] = maxResults;
}
inline void withIssuetypeName(std::string issuetypeName)
{
assertValidStringParam(issuetypeName, "Issue type name cannot be an empty string!");
json["issuetypeName"] = issuetypeName;
}
virtual void perform() {};
protected:
Config *configuration;
RestClient *restClient;
std::string getJSONPayload()
{
std::string payload = jsonWriter.write(json);
return payload;
}
private:
Json::StyledWriter jsonWriter;
Json::Value json;
inline void assertValidStringParam(std::string str, std::string msg)
{
assert(!jippi::StringUtils::isEmpty(str) && msg.c_str());
}
};
}; // end of namespace
#endif // ACTION_H
<commit_msg>Fix typo in withIssueWypeName method name<commit_after>/*
* Copyright 2014 Kamil Michalak <kmichalak8@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef ACTION_H
#define ACTION_H
#include <string>
#include <assert.h>
#include <jsoncpp/json/json.h>
#include "inc/stringutils.hpp"
#include "inc/config.hpp"
#include "inc/restclient.hpp"
namespace jippi {
/**
* An abstract class representing basic Jira command line client action.
* This class should be used as a base for further actions such as getting,
* creating, deleting issues, etc.
*
* Current implementation allows to specify
*/
class Action
{
public:
Action() {
configuration = new Config(DEFAULT_CONFIG_FILE, DEFAULT_CONFIG_FILE_LOCATION);
restClient = new RestClient();
}
virtual ~Action() {
delete restClient;
delete configuration;
};
inline void withIssue(std::string issue)
{
assertValidStringParam(issue, "Issue ID cannot be an empty string!");
json["issue"] = issue;
}
inline void withProject(std::string project)
{
assertValidStringParam(project, "Project ID cannot be an empty string!");
this->json["jql"] = "project = " + project;
}
inline void withAssignee(std::string assignee)
{
assertValidStringParam(assignee, "Assignee ID cannot be an empty string!");
json["assignee"] = assignee;
}
//-----------------------------------------------------------------------
// new parameters that need to be implemented in argumants handler
//-----------------------------------------------------------------------
inline void withMaxResults(int maxResults)
{
assert(maxResults > 0 && "Max number of results should be greater than 0!");
json["maxResults"] = maxResults;
}
inline void withIssueTypeName(std::string issuetypeName)
{
assertValidStringParam(issuetypeName, "Issue type name cannot be an empty string!");
json["issuetypeName"] = issuetypeName;
}
virtual void perform() {};
protected:
Config *configuration;
RestClient *restClient;
std::string getJSONPayload()
{
std::string payload = jsonWriter.write(json);
return payload;
}
private:
Json::StyledWriter jsonWriter;
Json::Value json;
inline void assertValidStringParam(std::string str, std::string msg)
{
assert(!jippi::StringUtils::isEmpty(str) && msg.c_str());
}
};
}; // end of namespace
#endif // ACTION_H
<|endoftext|> |
<commit_before>#include <errno.h>
#include <libintl.h>
#include <node.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace v8;
char * null_helper(char * str)
{
if(!std::strcmp(str, "null")) {
return NULL;
}
return str;
}
char * v8StrToCharStar(v8::Local<v8::Value> value)
{
v8::String::Utf8Value string(value);
char *str = (char *) std::malloc(string.length() + 1);
std::strcpy(str, *string);
return str;
}
int v8StrToInt(v8::Local<v8::Value> value)
{
int integer;
char * str;
str = v8StrToCharStar(value);
integer = std::atoi(str);
free(str);
return integer;
}
void _bindtextdomain(const FunctionCallbackInfo<Value>& args)
{
char * domain_name;
char * dir_name;
char * returned_dir_name;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 2) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate,
"bindtextdomain takes domain_name and dir_name")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
if (!args[1]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Second argument must be a string")));
return;
}
domain_name = v8StrToCharStar(args[0]);
dir_name = v8StrToCharStar(args[1]);
if((returned_dir_name = bindtextdomain(domain_name, dir_name)) == NULL) {
printf("Ran out of memory during call to bindtextdomain()\n");
printf("ERROR: %s\n", strerror(errno));
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_dir_name));
free(domain_name);
free(dir_name);
return;
}
void _gettext(const FunctionCallbackInfo<Value>& args)
{
char * original_text;
char * translated_text;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "gettext takes argument text")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
original_text = v8StrToCharStar(args[0]);
translated_text = gettext(original_text);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, translated_text));
free(original_text);
return;
}
void _setlocale(const FunctionCallbackInfo<Value>& args)
{
int lc_type;
char * lc_code;
char * returned_lc_code;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 2) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate,
"setlocale takes LC_TYPE and LC_CODE")));
return;
}
if (!args[0]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
if (!(args[1]->IsString() || args[1]->IsNull())) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(
isolate, "Second argument must be a string or null")));
return;
}
lc_type = v8StrToInt(args[0]);
lc_code = v8StrToCharStar(args[1]);
lc_code = null_helper(lc_code);
if((returned_lc_code = setlocale(lc_type, lc_code)) == NULL) {
printf("Invalid locale code given: %s\n", lc_code);
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_lc_code));
free(lc_code);
return;
}
void _textdomain(const FunctionCallbackInfo<Value>& args)
{
char * domain_name;
char * returned_domain;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "textdomain takes domain_name")));
return;
}
if (!(args[0]->IsString() || args[0]->IsNull())) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
domain_name = v8StrToCharStar(args[0]);
domain_name = null_helper(domain_name);
if((returned_domain = textdomain(domain_name)) == NULL) {
printf("Ran out of memory during call to textdomain()\n");
printf("ERROR: %s\n", strerror(errno));
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_domain));
free(domain_name);
return;
}
void Init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "bindtextdomain", _bindtextdomain);
NODE_SET_METHOD(exports, "gettext", _gettext);
NODE_SET_METHOD(exports, "setlocale", _setlocale);
NODE_SET_METHOD(exports, "textdomain", _textdomain);
NODE_DEFINE_CONSTANT(exports, LC_ALL);
NODE_DEFINE_CONSTANT(exports, LC_CTYPE);
NODE_DEFINE_CONSTANT(exports, LC_COLLATE);
NODE_DEFINE_CONSTANT(exports, LC_MESSAGES);
NODE_DEFINE_CONSTANT(exports, LC_MONETARY);
NODE_DEFINE_CONSTANT(exports, LC_NUMERIC);
NODE_DEFINE_CONSTANT(exports, LC_TIME);
}
NODE_MODULE(gettextlexer, Init)
<commit_msg>Undo c++ namespacing of std::<commit_after>#include <stdlib.h>
#include <errno.h>
#include <libintl.h>
#include <node.h>
#include <stdio.h>
#include <string.h>
using namespace v8;
char * null_helper(char * str)
{
if(!std::strcmp(str, "null")) {
return NULL;
}
return str;
}
char * v8StrToCharStar(v8::Local<v8::Value> value)
{
v8::String::Utf8Value string(value);
char *str = (char *) malloc(string.length() + 1);
strcpy(str, *string);
return str;
}
int v8StrToInt(v8::Local<v8::Value> value)
{
int integer;
char * str;
str = v8StrToCharStar(value);
integer = atoi(str);
free(str);
return integer;
}
void _bindtextdomain(const FunctionCallbackInfo<Value>& args)
{
char * domain_name;
char * dir_name;
char * returned_dir_name;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 2) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate,
"bindtextdomain takes domain_name and dir_name")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
if (!args[1]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Second argument must be a string")));
return;
}
domain_name = v8StrToCharStar(args[0]);
dir_name = v8StrToCharStar(args[1]);
if((returned_dir_name = bindtextdomain(domain_name, dir_name)) == NULL) {
printf("Ran out of memory during call to bindtextdomain()\n");
printf("ERROR: %s\n", strerror(errno));
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_dir_name));
free(domain_name);
free(dir_name);
return;
}
void _gettext(const FunctionCallbackInfo<Value>& args)
{
char * original_text;
char * translated_text;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "gettext takes argument text")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
original_text = v8StrToCharStar(args[0]);
translated_text = gettext(original_text);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, translated_text));
free(original_text);
return;
}
void _setlocale(const FunctionCallbackInfo<Value>& args)
{
int lc_type;
char * lc_code;
char * returned_lc_code;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 2) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate,
"setlocale takes LC_TYPE and LC_CODE")));
return;
}
if (!args[0]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
if (!(args[1]->IsString() || args[1]->IsNull())) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(
isolate, "Second argument must be a string or null")));
return;
}
lc_type = v8StrToInt(args[0]);
lc_code = v8StrToCharStar(args[1]);
lc_code = null_helper(lc_code);
if((returned_lc_code = setlocale(lc_type, lc_code)) == NULL) {
printf("Invalid locale code given: %s\n", lc_code);
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_lc_code));
free(lc_code);
return;
}
void _textdomain(const FunctionCallbackInfo<Value>& args)
{
char * domain_name;
char * returned_domain;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "textdomain takes domain_name")));
return;
}
if (!(args[0]->IsString() || args[0]->IsNull())) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
domain_name = v8StrToCharStar(args[0]);
domain_name = null_helper(domain_name);
if((returned_domain = textdomain(domain_name)) == NULL) {
printf("Ran out of memory during call to textdomain()\n");
printf("ERROR: %s\n", strerror(errno));
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_domain));
free(domain_name);
return;
}
void Init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "bindtextdomain", _bindtextdomain);
NODE_SET_METHOD(exports, "gettext", _gettext);
NODE_SET_METHOD(exports, "setlocale", _setlocale);
NODE_SET_METHOD(exports, "textdomain", _textdomain);
NODE_DEFINE_CONSTANT(exports, LC_ALL);
NODE_DEFINE_CONSTANT(exports, LC_CTYPE);
NODE_DEFINE_CONSTANT(exports, LC_COLLATE);
NODE_DEFINE_CONSTANT(exports, LC_MESSAGES);
NODE_DEFINE_CONSTANT(exports, LC_MONETARY);
NODE_DEFINE_CONSTANT(exports, LC_NUMERIC);
NODE_DEFINE_CONSTANT(exports, LC_TIME);
}
NODE_MODULE(gettextlexer, Init)
<|endoftext|> |
<commit_before>#include <node.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string.h>
#include <errno.h>
#include <libintl.h>
using namespace v8;
char * v8StrToCharStar(v8::Local<v8::Value> value)
{
v8::String::Utf8Value string(value);
char *str = (char *) malloc(string.length() + 1);
strcpy(str, *string);
return str;
}
int v8StrToInt(v8::Local<v8::Value> value)
{
int integer;
char * str;
str = v8StrToCharStar(value);
integer = atoi(str);
free(str);
return integer;
}
char * null_helper(char * str)
{
if(!strcmp(str, "null")) {
return NULL;
}
return str;
}
void _bindtextdomain(const FunctionCallbackInfo<Value>& args)
{
char * domain_name;
char * dir_name;
char * returned_dir_name;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 2) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate,
"bindtextdomain takes domain_name and dir_name")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
if (!args[1]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Second argument must be a string")));
return;
}
domain_name = v8StrToCharStar(args[0]);
dir_name = v8StrToCharStar(args[1]);
if((returned_dir_name = bindtextdomain(domain_name, dir_name)) == NULL) {
printf("Ran out of memory during call to bindtextdomain()\n");
printf("ERROR: %s\n", strerror(errno));
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_dir_name));
free(domain_name);
free(dir_name);
return;
}
void _gettext(const FunctionCallbackInfo<Value>& args)
{
char * original_text;
char * translated_text;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "gettext takes argument text")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
original_text = v8StrToCharStar(args[0]);
translated_text = gettext(original_text);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, translated_text));
free(original_text);
return;
}
void _setlocale(const FunctionCallbackInfo<Value>& args)
{
int lc_type;
char * lc_code;
char * returned_lc_code;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 2) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate,
"setlocale takes LC_TYPE and LC_CODE")));
return;
}
if (!args[0]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
if (!(args[1]->IsString() || args[1]->IsNull())) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(
isolate, "Second argument must be a string or null")));
return;
}
lc_type = v8StrToInt(args[0]);
lc_code = v8StrToCharStar(args[1]);
lc_code = null_helper(lc_code);
if((returned_lc_code = setlocale(lc_type, lc_code)) == NULL) {
printf("Invalid locale code given: %s\n", lc_code);
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_lc_code));
free(lc_code);
return;
}
void _textdomain(const FunctionCallbackInfo<Value>& args)
{
char * domain_name;
char * returned_domain;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "textdomain takes domain_name")));
return;
}
if (!(args[0]->IsString() || args[0]->IsNull())) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
domain_name = v8StrToCharStar(args[0]);
domain_name = null_helper(domain_name);
if((returned_domain = textdomain(domain_name)) == NULL) {
printf("Ran out of memory during call to textdomain()\n");
printf("ERROR: %s\n", strerror(errno));
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_domain));
free(domain_name);
return;
}
void Init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "bindtextdomain", _bindtextdomain);
NODE_SET_METHOD(exports, "gettext", _gettext);
NODE_SET_METHOD(exports, "setlocale", _setlocale);
NODE_SET_METHOD(exports, "textdomain", _textdomain);
NODE_DEFINE_CONSTANT(exports, LC_ALL);
NODE_DEFINE_CONSTANT(exports, LC_CTYPE);
NODE_DEFINE_CONSTANT(exports, LC_COLLATE);
NODE_DEFINE_CONSTANT(exports, LC_MESSAGES);
NODE_DEFINE_CONSTANT(exports, LC_MONETARY);
NODE_DEFINE_CONSTANT(exports, LC_NUMERIC);
NODE_DEFINE_CONSTANT(exports, LC_TIME);
}
NODE_MODULE(gettextlexer, Init)
<commit_msg>Remove unused includes<commit_after>#include <node.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <libintl.h>
using namespace v8;
char * v8StrToCharStar(v8::Local<v8::Value> value)
{
v8::String::Utf8Value string(value);
char *str = (char *) malloc(string.length() + 1);
strcpy(str, *string);
return str;
}
int v8StrToInt(v8::Local<v8::Value> value)
{
int integer;
char * str;
str = v8StrToCharStar(value);
integer = atoi(str);
free(str);
return integer;
}
char * null_helper(char * str)
{
if(!strcmp(str, "null")) {
return NULL;
}
return str;
}
void _bindtextdomain(const FunctionCallbackInfo<Value>& args)
{
char * domain_name;
char * dir_name;
char * returned_dir_name;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 2) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate,
"bindtextdomain takes domain_name and dir_name")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
if (!args[1]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Second argument must be a string")));
return;
}
domain_name = v8StrToCharStar(args[0]);
dir_name = v8StrToCharStar(args[1]);
if((returned_dir_name = bindtextdomain(domain_name, dir_name)) == NULL) {
printf("Ran out of memory during call to bindtextdomain()\n");
printf("ERROR: %s\n", strerror(errno));
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_dir_name));
free(domain_name);
free(dir_name);
return;
}
void _gettext(const FunctionCallbackInfo<Value>& args)
{
char * original_text;
char * translated_text;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "gettext takes argument text")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
original_text = v8StrToCharStar(args[0]);
translated_text = gettext(original_text);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, translated_text));
free(original_text);
return;
}
void _setlocale(const FunctionCallbackInfo<Value>& args)
{
int lc_type;
char * lc_code;
char * returned_lc_code;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 2) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate,
"setlocale takes LC_TYPE and LC_CODE")));
return;
}
if (!args[0]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
if (!(args[1]->IsString() || args[1]->IsNull())) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(
isolate, "Second argument must be a string or null")));
return;
}
lc_type = v8StrToInt(args[0]);
lc_code = v8StrToCharStar(args[1]);
lc_code = null_helper(lc_code);
if((returned_lc_code = setlocale(lc_type, lc_code)) == NULL) {
printf("Invalid locale code given: %s\n", lc_code);
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_lc_code));
free(lc_code);
return;
}
void _textdomain(const FunctionCallbackInfo<Value>& args)
{
char * domain_name;
char * returned_domain;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "textdomain takes domain_name")));
return;
}
if (!(args[0]->IsString() || args[0]->IsNull())) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
domain_name = v8StrToCharStar(args[0]);
domain_name = null_helper(domain_name);
if((returned_domain = textdomain(domain_name)) == NULL) {
printf("Ran out of memory during call to textdomain()\n");
printf("ERROR: %s\n", strerror(errno));
exit(1);
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returned_domain));
free(domain_name);
return;
}
void Init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "bindtextdomain", _bindtextdomain);
NODE_SET_METHOD(exports, "gettext", _gettext);
NODE_SET_METHOD(exports, "setlocale", _setlocale);
NODE_SET_METHOD(exports, "textdomain", _textdomain);
NODE_DEFINE_CONSTANT(exports, LC_ALL);
NODE_DEFINE_CONSTANT(exports, LC_CTYPE);
NODE_DEFINE_CONSTANT(exports, LC_COLLATE);
NODE_DEFINE_CONSTANT(exports, LC_MESSAGES);
NODE_DEFINE_CONSTANT(exports, LC_MONETARY);
NODE_DEFINE_CONSTANT(exports, LC_NUMERIC);
NODE_DEFINE_CONSTANT(exports, LC_TIME);
}
NODE_MODULE(gettextlexer, Init)
<|endoftext|> |
<commit_before>#include "RayControl.h"
#include "ObjectParticles.h"
#include "Engine.h"
#include "Game.h"
#include "Object.h"
#include "Player.h"
#include "Common.h"
#include "App.h"
CRayControl::CRayControl(void)
{
m_pStarNormal = NULL;
Init();
}
CRayControl::~CRayControl(void)
{
g_Engine.pGame->RemoveNode(m_pStarNormal);
}
int CRayControl::Init()
{
m_pStarNormal = (CObjectParticles*)g_Engine.pGame->LoadNode("data/StarControl/ray_line.node");
if (!m_pStarNormal)
return 0;
m_pStarNormal->GetTracker(TRACKER_CUSTOM)->SetTrackValue(0, 0, vec4(1.0f, 1.0f, 1.0f, 0.5f));
return 1;
}
void CRayControl::Update(const mat4& matTransform, const vec3 & vOffset)
{
m_pStarNormal->SetWorldTransform(matTransform*Translate(vOffset));
}
int CRayControl::isEnable()
{
return m_pStarNormal->IsEnabled();
}
void CRayControl::SetEnable(int nEnable)
{
m_pStarNormal->SetEnabled(nEnable);
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "RayControl.h"
#include "ObjectParticles.h"
#include "Engine.h"
#include "Game.h"
#include "Object.h"
#include "Player.h"
#include "Common.h"
#include "App.h"
CRayControl::CRayControl(void)
{
m_pStarNormal = NULL;
Init();
}
CRayControl::~CRayControl(void)
{
g_Engine.pGame->RemoveNode(m_pStarNormal);
}
int CRayControl::Init()
{
m_pStarNormal = (CObjectParticles*)g_Engine.pGame->LoadNode("data/StarControl/ray_line.node");
if (!m_pStarNormal)
return 0;
m_pStarNormal->GetTracker(TRACKER_CUSTOM)->SetTrackValue(0, 0, vec4(1.0f, 1.0f, 1.0f, 0.5f));
return 1;
}
void CRayControl::Update(const mat4& matTransform, const vec3 & vOffset)
{
m_pStarNormal->SetWorldTransform(matTransform*Translate(vOffset));
}
int CRayControl::isEnable()
{
return m_pStarNormal->IsEnabled();
}
void CRayControl::SetEnable(int nEnable)
{
m_pStarNormal->SetEnabled(nEnable);
}
void CRayControl::SetColor(const vec4& vColor)
{
m_pStarNormal->SetObjectColor(vColor);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "vtkMapper.h"
#include "vtkLookupTable.h"
// Initialize static member that controls global immediate mode rendering
static int vtkMapperGlobalImmediateModeRendering = 0;
// Initialize static member that controls global coincidence resolution
static int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
static double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0;
// Construct with initial range (0,1).
vtkMapper::vtkMapper()
{
this->Colors = NULL;
this->LookupTable = NULL;
this->ScalarVisibility = 1;
this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0;
this->UseLookupTableScalarRange = 0;
this->ImmediateModeRendering = 0;
this->ColorMode = VTK_COLOR_MODE_DEFAULT;
this->ScalarMode = VTK_SCALAR_MODE_DEFAULT;
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;
this->Center[0] = this->Center[1] = this->Center[2] = 0.0;
this->RenderTime = 0.0;
strcpy(this->ArrayName, "");
this->ArrayId = -1;
this->ArrayComponent = -1;
this->ArrayAccessMode = -1;
}
vtkMapper::~vtkMapper()
{
if (this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
if ( this->Colors != NULL )
{
this->Colors->UnRegister(this);
}
}
// Get the bounds for the input of this mapper as
// (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
float *vtkMapper::GetBounds()
{
static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};
if ( ! this->GetInput() )
{
return bounds;
}
else
{
this->Update();
this->GetInput()->GetBounds(this->Bounds);
return this->Bounds;
}
}
vtkDataSet *vtkMapper::GetInput()
{
if (this->NumberOfInputs < 1)
{
return NULL;
}
return (vtkDataSet *)(this->Inputs[0]);
}
void vtkMapper::SetGlobalImmediateModeRendering(int val)
{
if (val == vtkMapperGlobalImmediateModeRendering)
{
return;
}
vtkMapperGlobalImmediateModeRendering = val;
}
int vtkMapper::GetGlobalImmediateModeRendering()
{
return vtkMapperGlobalImmediateModeRendering;
}
void vtkMapper::SetResolveCoincidentTopology(int val)
{
if (val == vtkMapperGlobalResolveCoincidentTopology)
{
return;
}
vtkMapperGlobalResolveCoincidentTopology = val;
}
int vtkMapper::GetResolveCoincidentTopology()
{
return vtkMapperGlobalResolveCoincidentTopology;
}
void vtkMapper::SetResolveCoincidentTopologyToDefault()
{
vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
}
void vtkMapper::SetResolveCoincidentTopologyZShift(double val)
{
if (val == vtkMapperGlobalResolveCoincidentTopologyZShift)
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyZShift = val;
}
double vtkMapper::GetResolveCoincidentTopologyZShift()
{
return vtkMapperGlobalResolveCoincidentTopologyZShift;
}
void vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(
float factor, float units)
{
if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor &&
units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits )
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor;
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = units;
}
void vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(
float& factor, float& units)
{
factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor;
units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits;
}
// Overload standard modified time function. If lookup table is modified,
// then this object is modified as well.
unsigned long vtkMapper::GetMTime()
{
unsigned long mTime=this->MTime.GetMTime();
unsigned long lutMTime;
if ( this->LookupTable != NULL )
{
lutMTime = this->LookupTable->GetMTime();
mTime = ( lutMTime > mTime ? lutMTime : mTime );
}
return mTime;
}
void vtkMapper::ShallowCopy(vtkMapper *m)
{
this->SetLookupTable(m->GetLookupTable());
this->SetClippingPlanes(m->GetClippingPlanes());
this->SetScalarVisibility(m->GetScalarVisibility());
this->SetScalarRange(m->GetScalarRange());
this->SetColorMode(m->GetColorMode());
this->SetScalarMode(m->GetScalarMode());
this->SetImmediateModeRendering(m->GetImmediateModeRendering());
}
// a side effect of this is that this->Colors is also set
// to the return value
vtkScalars *vtkMapper::GetColors()
{
vtkScalars *scalars = NULL;
vtkDataArray *dataArray=0;
vtkPointData *pd;
vtkCellData *cd;
vtkIdType i, numScalars;
// make sure we have an input
if (!this->GetInput())
{
return NULL;
}
// get and scalar data according to scalar mode
if ( this->ScalarMode == VTK_SCALAR_MODE_DEFAULT )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
if (!scalars)
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
pd = this->GetInput()->GetPointData();
if (pd)
{
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = pd->GetArray(this->ArrayId);
}
else
{
dataArray = pd->GetArray(this->ArrayName);
}
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
else
{
vtkWarningMacro(<<"Data array (used for coloring) not found");
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
cd = this->GetInput()->GetCellData();
if (cd)
{
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = cd->GetArray(this->ArrayId);
}
else
{
dataArray = cd->GetArray(this->ArrayName);
}
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
else
{
vtkWarningMacro(<<"Data array (used for coloring) not found");
}
}
// do we have any scalars ?
if (scalars && this->ScalarVisibility)
{
// if the scalars have a lookup table use it instead
if (scalars->GetLookupTable())
{
this->SetLookupTable(scalars->GetLookupTable());
}
else
{
// make sure we have a lookup table
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
this->LookupTable->Build();
}
// Setup mapper/scalar object for color generation
if (!this->UseLookupTableScalarRange)
{
this->LookupTable->SetRange(this->ScalarRange);
}
if (this->Colors)
{
this->Colors->UnRegister(this);
}
this->Colors = scalars;
this->Colors->Register(this);
this->Colors->InitColorTraversal(1.0, this->LookupTable, this->ColorMode);
}
else //scalars not visible
{
if ( this->Colors )
{
this->Colors->UnRegister(this);
}
this->Colors = NULL;
}
if (((this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) ||
(this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)) &&
scalars)
{
scalars->Delete();
}
return this->Colors;
}
void vtkMapper::ColorByArrayComponent(int arrayNum, int component)
{
if (this->ArrayId == arrayNum && component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
this->ArrayId = arrayNum;
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;
}
void vtkMapper::ColorByArrayComponent(char* arrayName, int component)
{
if (strcmp(this->ArrayName, arrayName) == 0 &&
component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
strcpy(this->ArrayName, arrayName);
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME;
}
// Specify a lookup table for the mapper to use.
void vtkMapper::SetLookupTable(vtkScalarsToColors *lut)
{
if ( this->LookupTable != lut )
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = lut;
if (lut)
{
lut->Register(this);
}
this->Modified();
}
}
vtkScalarsToColors *vtkMapper::GetLookupTable()
{
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
return this->LookupTable;
}
void vtkMapper::CreateDefaultLookupTable()
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = vtkLookupTable::New();
}
// Update the network connected to this mapper.
void vtkMapper::Update()
{
if ( this->GetInput() )
{
this->GetInput()->Update();
}
}
// Return the method of coloring scalar data.
const char *vtkMapper::GetColorModeAsString(void)
{
if ( this->ColorMode == VTK_COLOR_MODE_LUMINANCE )
{
return "Luminance";
}
else if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS )
{
return "MapScalars";
}
else
{
return "Default";
}
}
// Return the method for obtaining scalar data.
const char *vtkMapper::GetScalarModeAsString(void)
{
if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
return "UseCellData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
return "UsePointData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
return "UsePointFieldData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
return "UseCellFieldData";
}
else
{
return "Default";
}
}
void vtkMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkAbstractMapper3D::PrintSelf(os,indent);
if ( this->LookupTable )
{
os << indent << "Lookup Table:\n";
this->LookupTable->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Lookup Table: (none)\n";
}
os << indent << "Immediate Mode Rendering: "
<< (this->ImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Global Immediate Mode Rendering: " <<
(vtkMapperGlobalImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Scalar Visibility: "
<< (this->ScalarVisibility ? "On\n" : "Off\n");
float *range = this->GetScalarRange();
os << indent << "Scalar Range: (" << range[0] << ", " << range[1] << ")\n";
os << indent << "UseLookupTableScalarRange: " << this->UseLookupTableScalarRange << "\n";
os << indent << "Color Mode: " << this->GetColorModeAsString() << endl;
os << indent << "Scalar Mode: " << this->GetScalarModeAsString() << endl;
os << indent << "RenderTime: " << this->RenderTime << endl;
os << indent << "Resolve Coincident Topology: ";
if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF )
{
os << "Off" << endl;
}
else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET )
{
os << "Polygon Offset" << endl;
}
else
{
os << "Shift Z-Buffer" << endl;
}
}
<commit_msg>ENH:No need to check if point data and cell data exists; it is guaranteed to always exist<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "vtkMapper.h"
#include "vtkLookupTable.h"
// Initialize static member that controls global immediate mode rendering
static int vtkMapperGlobalImmediateModeRendering = 0;
// Initialize static member that controls global coincidence resolution
static int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
static double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0;
// Construct with initial range (0,1).
vtkMapper::vtkMapper()
{
this->Colors = NULL;
this->LookupTable = NULL;
this->ScalarVisibility = 1;
this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0;
this->UseLookupTableScalarRange = 0;
this->ImmediateModeRendering = 0;
this->ColorMode = VTK_COLOR_MODE_DEFAULT;
this->ScalarMode = VTK_SCALAR_MODE_DEFAULT;
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;
this->Center[0] = this->Center[1] = this->Center[2] = 0.0;
this->RenderTime = 0.0;
strcpy(this->ArrayName, "");
this->ArrayId = -1;
this->ArrayComponent = -1;
this->ArrayAccessMode = -1;
}
vtkMapper::~vtkMapper()
{
if (this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
if ( this->Colors != NULL )
{
this->Colors->UnRegister(this);
}
}
// Get the bounds for the input of this mapper as
// (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
float *vtkMapper::GetBounds()
{
static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};
if ( ! this->GetInput() )
{
return bounds;
}
else
{
this->Update();
this->GetInput()->GetBounds(this->Bounds);
return this->Bounds;
}
}
vtkDataSet *vtkMapper::GetInput()
{
if (this->NumberOfInputs < 1)
{
return NULL;
}
return (vtkDataSet *)(this->Inputs[0]);
}
void vtkMapper::SetGlobalImmediateModeRendering(int val)
{
if (val == vtkMapperGlobalImmediateModeRendering)
{
return;
}
vtkMapperGlobalImmediateModeRendering = val;
}
int vtkMapper::GetGlobalImmediateModeRendering()
{
return vtkMapperGlobalImmediateModeRendering;
}
void vtkMapper::SetResolveCoincidentTopology(int val)
{
if (val == vtkMapperGlobalResolveCoincidentTopology)
{
return;
}
vtkMapperGlobalResolveCoincidentTopology = val;
}
int vtkMapper::GetResolveCoincidentTopology()
{
return vtkMapperGlobalResolveCoincidentTopology;
}
void vtkMapper::SetResolveCoincidentTopologyToDefault()
{
vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
}
void vtkMapper::SetResolveCoincidentTopologyZShift(double val)
{
if (val == vtkMapperGlobalResolveCoincidentTopologyZShift)
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyZShift = val;
}
double vtkMapper::GetResolveCoincidentTopologyZShift()
{
return vtkMapperGlobalResolveCoincidentTopologyZShift;
}
void vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(
float factor, float units)
{
if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor &&
units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits )
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor;
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = units;
}
void vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(
float& factor, float& units)
{
factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor;
units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits;
}
// Overload standard modified time function. If lookup table is modified,
// then this object is modified as well.
unsigned long vtkMapper::GetMTime()
{
unsigned long mTime=this->MTime.GetMTime();
unsigned long lutMTime;
if ( this->LookupTable != NULL )
{
lutMTime = this->LookupTable->GetMTime();
mTime = ( lutMTime > mTime ? lutMTime : mTime );
}
return mTime;
}
void vtkMapper::ShallowCopy(vtkMapper *m)
{
this->SetLookupTable(m->GetLookupTable());
this->SetClippingPlanes(m->GetClippingPlanes());
this->SetScalarVisibility(m->GetScalarVisibility());
this->SetScalarRange(m->GetScalarRange());
this->SetColorMode(m->GetColorMode());
this->SetScalarMode(m->GetScalarMode());
this->SetImmediateModeRendering(m->GetImmediateModeRendering());
}
// a side effect of this is that this->Colors is also set
// to the return value
vtkScalars *vtkMapper::GetColors()
{
vtkScalars *scalars = NULL;
vtkDataArray *dataArray=0;
vtkPointData *pd;
vtkCellData *cd;
vtkIdType i, numScalars;
// make sure we have an input
if (!this->GetInput())
{
return NULL;
}
// get and scalar data according to scalar mode
if ( this->ScalarMode == VTK_SCALAR_MODE_DEFAULT )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
if (!scalars)
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
pd = this->GetInput()->GetPointData();
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = pd->GetArray(this->ArrayId);
}
else
{
dataArray = pd->GetArray(this->ArrayName);
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
else
{
vtkWarningMacro(<<"Data array (used for coloring) not found");
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
cd = this->GetInput()->GetCellData();
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = cd->GetArray(this->ArrayId);
}
else
{
dataArray = cd->GetArray(this->ArrayName);
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
else
{
vtkWarningMacro(<<"Data array (used for coloring) not found");
}
}
// do we have any scalars ?
if (scalars && this->ScalarVisibility)
{
// if the scalars have a lookup table use it instead
if (scalars->GetLookupTable())
{
this->SetLookupTable(scalars->GetLookupTable());
}
else
{
// make sure we have a lookup table
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
this->LookupTable->Build();
}
// Setup mapper/scalar object for color generation
if (!this->UseLookupTableScalarRange)
{
this->LookupTable->SetRange(this->ScalarRange);
}
if (this->Colors)
{
this->Colors->UnRegister(this);
}
this->Colors = scalars;
this->Colors->Register(this);
this->Colors->InitColorTraversal(1.0, this->LookupTable, this->ColorMode);
}
else //scalars not visible
{
if ( this->Colors )
{
this->Colors->UnRegister(this);
}
this->Colors = NULL;
}
if (((this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) ||
(this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)) &&
scalars)
{
scalars->Delete();
}
return this->Colors;
}
void vtkMapper::ColorByArrayComponent(int arrayNum, int component)
{
if (this->ArrayId == arrayNum && component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
this->ArrayId = arrayNum;
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;
}
void vtkMapper::ColorByArrayComponent(char* arrayName, int component)
{
if (strcmp(this->ArrayName, arrayName) == 0 &&
component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
strcpy(this->ArrayName, arrayName);
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME;
}
// Specify a lookup table for the mapper to use.
void vtkMapper::SetLookupTable(vtkScalarsToColors *lut)
{
if ( this->LookupTable != lut )
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = lut;
if (lut)
{
lut->Register(this);
}
this->Modified();
}
}
vtkScalarsToColors *vtkMapper::GetLookupTable()
{
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
return this->LookupTable;
}
void vtkMapper::CreateDefaultLookupTable()
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = vtkLookupTable::New();
}
// Update the network connected to this mapper.
void vtkMapper::Update()
{
if ( this->GetInput() )
{
this->GetInput()->Update();
}
}
// Return the method of coloring scalar data.
const char *vtkMapper::GetColorModeAsString(void)
{
if ( this->ColorMode == VTK_COLOR_MODE_LUMINANCE )
{
return "Luminance";
}
else if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS )
{
return "MapScalars";
}
else
{
return "Default";
}
}
// Return the method for obtaining scalar data.
const char *vtkMapper::GetScalarModeAsString(void)
{
if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
return "UseCellData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
return "UsePointData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
return "UsePointFieldData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
return "UseCellFieldData";
}
else
{
return "Default";
}
}
void vtkMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkAbstractMapper3D::PrintSelf(os,indent);
if ( this->LookupTable )
{
os << indent << "Lookup Table:\n";
this->LookupTable->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Lookup Table: (none)\n";
}
os << indent << "Immediate Mode Rendering: "
<< (this->ImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Global Immediate Mode Rendering: " <<
(vtkMapperGlobalImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Scalar Visibility: "
<< (this->ScalarVisibility ? "On\n" : "Off\n");
float *range = this->GetScalarRange();
os << indent << "Scalar Range: (" << range[0] << ", " << range[1] << ")\n";
os << indent << "UseLookupTableScalarRange: " << this->UseLookupTableScalarRange << "\n";
os << indent << "Color Mode: " << this->GetColorModeAsString() << endl;
os << indent << "Scalar Mode: " << this->GetScalarModeAsString() << endl;
os << indent << "RenderTime: " << this->RenderTime << endl;
os << indent << "Resolve Coincident Topology: ";
if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF )
{
os << "Off" << endl;
}
else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET )
{
os << "Polygon Offset" << endl;
}
else
{
os << "Shift Z-Buffer" << endl;
}
}
<|endoftext|> |
<commit_before>//
// TightDB C++ coding standard - by example
//
// Lines should never exceed 120 characters ---------------------------------------------------------------------------
// Macro names use uppercase and have "TIGHTDB_" as prefix. Non-macro
// names never use all uppercase.
#define TIGHTDB_MY_MACRO 1
// A function name uses lowercase and its parts are separated by
// underscores.
my_type my_func()
{
// Put the opening brace of a function body in the next line below
// the function prototype. This also applies to class member
// functions.
// Put all other opening braces on the same line as the syntax
// element to which the brace is subordinate.
// Use 4 spaces per indentation level (no tabs please).
if (...) {
// ...
}
else {
// ...
}
// Always put subordinate statements on a new line (to ease
// debugging).
if (...)
return ...;
else
return ...;
// No space between type and '*' or '&'
int* foo1 = ...;
int& foo2 = ...;
// 'const' goes before the type
const int foo3 = ...;
// ... but not when 'const' operates on a pointer type
const int* foo3 = ...; // 'const' operates in 'int' not 'int*'
int* const foo4 = ...; // 'const' operates on 'int*'
int* const* const foo5 = ...;
}
void my_func_2()
{
// This indentation and brace placement style agrees with K&R
// style except for the 'extra' indentation of 'cases' in a switch
// statement.
switch (...) {
case type_Foo: {
// ...
break;
}
case type_FooBar: {
// ...
break;
}
}
try {
// ...
}
catch (...) {
// ...
}
}
// A name space name uses lowercase and its parts are separated by
// underscores.
namespace my_namespace {
// No indentation inside name spaces.
// A Class name uses CamelCase with uppercase initial.
template<class T> class MyClass: public Base {
public:
MyClass(...): Base(...), m_bar(7), ... { ... }
MyClass(...):
Base(...), m_bar(7), ...
{
// ...
}
private:
// Static member variables have prefix 's_'.
static int s_foo;
// Regular member variables have prefix 'm_'.
int m_bar;
};
} // namespace my_namespace
// Names of values of an enumeration are composed of two parts
// separated by an underscore. The first part is a common lowercase
// prefix. The second part identifies the value and uses CamelCase
// with uppercase initial.
enum mode {
mode_Foo,
mode_FooBar
};
// Order of class members (roughly):
class MyClass2 {
public:
// Types
// Static variables
// Regular variables
// Static functions
// Regular functions
protected:
// Same as 'public'
private:
// Same as 'public'
// Friends
};
<commit_msg>Added info about FIXMEs to style guide<commit_after>//
// TightDB C++ coding standard - by example
//
// Lines should never exceed 120 characters ---------------------------------------------------------------------------
// Macro names use uppercase and have "TIGHTDB_" as prefix. Non-macro
// names never use all uppercase.
#define TIGHTDB_MY_MACRO 1
// A function name uses lowercase and its parts are separated by
// underscores.
my_type my_func()
{
// Put the opening brace of a function body in the next line below
// the function prototype. This also applies to class member
// functions.
// Put all other opening braces on the same line as the syntax
// element to which the brace is subordinate.
// Use 4 spaces per indentation level (no tabs please).
if (...) {
// ...
}
else {
// ...
}
// Always put subordinate statements on a new line (to ease
// debugging).
if (...)
return ...;
// No space between type and '*' or '&'
int* foo1 = ...;
int& foo2 = ...;
// 'const' goes before the type
const int foo3 = ...;
// ... but not when 'const' operates on a pointer type
const int* foo3 = ...; // 'const' operates on 'int' not 'int*'
int* const foo4 = ...; // 'const' operates on 'int*'
int* const* const foo5 = ...;
}
void my_func_2()
{
// This indentation and brace placement style agrees with K&R
// style except for the 'extra' indentation of 'cases' in a switch
// statement.
switch (...) {
case type_Foo: {
// ...
break;
}
case type_FooBar: {
// ...
break;
}
}
try {
// ...
}
catch (...) {
// ...
}
}
// A name space name uses lowercase and its parts are separated by
// underscores.
namespace my_namespace {
// No indentation inside name spaces.
// A Class name uses CamelCase with uppercase initial.
template<class T> class MyClass: public Base {
public:
MyClass(...):
Base(...),
m_bar(7),
...
{
// ...
}
private:
// Static member variables have prefix 's_'.
static int s_foo;
// Regular member variables have prefix 'm_'.
int m_bar;
};
} // namespace my_namespace
// Names of values of an enumeration are composed of two parts
// separated by an underscore. The first part is a common lowercase
// prefix. The second part identifies the value and uses CamelCase
// with uppercase initial.
enum mode {
mode_Foo,
mode_FooBar
};
// Order of class members (roughly):
class MyClass2 {
public:
// Types
// Static variables
// Regular variables
// Static functions
// Regular functions
protected:
// Same as 'public'
private:
// Same as 'public'
// Friends
};
// About FIXMEs:
//
// A FIXME conveys information about a known issue or shortcoming. It
// may also include information on how to fix the problem, and on
// possible conflicts with anticipated future features.
//
// A FIXME is often added in the following situations:
//
// - While working on, or studying a particular part of the code you
// uncover an issue or a shortcoming. Additionally, you may have
// gained an understanding of how to fix it.
//
// - While implementing a new feature, you are forced to cut a corner,
// but you have some good ideas about how to continue later, and/or
// you may have knowledge about a certain planned feature that would
// require a more complete solution.
//
// A FIXME is generally not about a bug or an error, and is should
// generally not be considered a task either. Is is simply a memo to
// oneself or to some other developer who is going to work on the code
// at some later point in time.
//
// A FIXME should never be deleted unless by somebody who understands
// the mening of it and knows that the problem is fixed, or has
// otherwise diappeard.
<|endoftext|> |
<commit_before>
// todo:
// -Ir
// -Iz
// -zr
// -zt
// -f
#include "i2_options.h"
#include "posix_fe.h"
#include <netdb.h>
class i2_program
{
i2_options opts;
bool _ok;
pxfe_tcp_stream_socket * net_fd;
uint64_t bytes_sent;
uint64_t bytes_received;
pxfe_timeval start_time;
pxfe_string buffer;
pxfe_ticker ticker;
public:
i2_program(int argc, char ** argv)
: opts(argc, argv), _ok(false)
{
_ok = opts.ok;
net_fd = NULL;
bytes_received = 0;
bytes_sent = 0;
}
~i2_program(void)
{
// opts destructor will close the input & output fds.
if (net_fd)
delete net_fd;
}
bool ok(void) const { return _ok; }
int main(void)
{
uint32_t addr;
pxfe_errno e;
if (opts.outbound &&
pxfe_iputils::hostname_to_ipaddr(opts.hostname.c_str(),
&addr) == false)
return 1;
if (opts.outbound)
{
net_fd = new pxfe_tcp_stream_socket;
if (net_fd->init(&e) == false)
{
std::cerr << e.Format() << std::endl;
return 1;
}
if (opts.verbose)
fprintf(stderr, "connecting...");
if (net_fd->connect(addr, opts.port_number, &e) == false)
{
std::cerr << e.Format() << std::endl;
return 1;
}
if (opts.verbose)
fprintf(stderr, "success\n");
}
else
{
pxfe_tcp_stream_socket listen;
if (listen.init(opts.port_number,true,&e) == false)
{
std::cerr << e.Format() << std::endl;
return 1;
}
listen.listen();
if (opts.verbose)
fprintf(stderr, "listening...");
do {
net_fd = listen.accept(&e);
if (e.e != 0)
std::cerr << e.Format() << std::endl;
} while (net_fd == NULL);
if (opts.verbose)
{
uint32_t addr = net_fd->get_peer_addr();
std::cerr << "accepted from "
<< (int) ((addr >> 24) & 0xFF) << "."
<< (int) ((addr >> 16) & 0xFF) << "."
<< (int) ((addr >> 8) & 0xFF) << "."
<< (int) ((addr >> 0) & 0xFF)
<< std::endl;
}
// listen socket closed here, because we
// no longer need it.
}
start_time.getNow();
ticker.start(0, 500000);
pxfe_poll p;
p.set(net_fd->getFd(), POLLIN);
p.set(ticker.fd(), POLLIN);
#define POLLERRS (POLLERR | POLLHUP | POLLNVAL)
while (1)
{
int evt;
if (opts.input_set)
p.set(opts.input_fd, POLLIN);
else
p.set(opts.input_fd, 0);
p.poll(1000);
evt = p.rget(net_fd->getFd());
if (evt & POLLIN)
{
if (!handle_net_fd())
break;
}
else if (evt & POLLERRS)
break;
if (opts.input_set)
{
evt = p.rget(opts.input_fd);
if (evt & POLLIN)
{
if (!handle_input_fd())
break;
}
else if (evt & POLLERRS)
break;
}
if (p.rget(ticker.fd()) & POLLIN)
handle_tick();
}
ticker.pause();
if (opts.verbose || opts.stats_at_end)
print_stats(true);
return 0;
}
private:
bool handle_net_fd(void)
{
pxfe_errno e;
if (net_fd->recv(buffer, &e) == false)
{
std::cerr << e.Format() << std::endl;
return false;
}
if (buffer.length() == 0)
return false;
bytes_received += buffer.length();
if (opts.output_set)
{
int cc = -1;
do {
cc = buffer.write(opts.output_fd);
if (cc == buffer.length())
break;
if (cc < 0)
{
int e = errno;
char * err = strerror(e);
fprintf(stderr, "write failed: %d: %s\n", e, err);
return false;
}
else if (cc == 0)
{
fprintf(stderr, "write returned zero\n");
return false;
}
else
// remove the bytes already written
// and go around again to get the rest.
buffer.erase(0,cc);
} while (true);
}
return true;
}
bool handle_input_fd(void)
{
pxfe_errno e;
int cc = buffer.read(opts.input_fd,
pxfe_tcp_stream_socket::MAX_MSG_LEN, &e);
if (cc < 0)
{
std::cerr << e.Format() << std::endl;
return false;
}
else if (cc == 0)
return false;
else
{
if (net_fd->send(buffer, &e) == false)
{
std::cerr << e.Format() << std::endl;
return false;
}
bytes_sent += buffer.length();
}
return true;
}
void handle_tick(void)
{
ticker.doread();
if (opts.verbose)
print_stats(/*final*/false);
}
void print_stats(bool final)
{
pxfe_timeval now, diff;
uint64_t total = bytes_sent + bytes_received;
now.getNow();
diff = now - start_time;
float t = diff.usecs() / 1000000.0;
if (t == 0.0)
t = 99999.0;
float bytes_per_sec = (float) total / t;
float bits_per_sec = bytes_per_sec * 8.0;
fprintf(stderr, "\r%" PRIu64 " in %u.%06u s "
"(%.0f Bps %.0f bps)",
total,
(unsigned int) diff.tv_sec,
(unsigned int) diff.tv_usec,
bytes_per_sec, bits_per_sec);
if (final)
fprintf(stderr, "\n");
}
};
extern "C" int
i2_main(int argc, char ** argv)
{
i2_program i2(argc, argv);
if (i2.ok() == false)
return 1;
return i2.main();
}
<commit_msg>fix i2 -n<commit_after>
// todo:
// -Ir
// -Iz
// -zr
// -zt
// -f
#include "i2_options.h"
#include "posix_fe.h"
#include <netdb.h>
class i2_program
{
i2_options opts;
bool _ok;
pxfe_tcp_stream_socket * net_fd;
uint64_t bytes_sent;
uint64_t bytes_received;
pxfe_timeval start_time;
pxfe_string buffer;
pxfe_ticker ticker;
public:
i2_program(int argc, char ** argv)
: opts(argc, argv), _ok(false)
{
_ok = opts.ok;
// debug only
// opts.print();
net_fd = NULL;
bytes_received = 0;
bytes_sent = 0;
}
~i2_program(void)
{
// opts destructor will close the input & output fds.
if (net_fd)
delete net_fd;
}
bool ok(void) const { return _ok; }
int main(void)
{
uint32_t addr;
pxfe_errno e;
if (opts.outbound &&
pxfe_iputils::hostname_to_ipaddr(opts.hostname.c_str(),
&addr) == false)
return 1;
if (opts.outbound)
{
net_fd = new pxfe_tcp_stream_socket;
if (net_fd->init(&e) == false)
{
std::cerr << e.Format() << std::endl;
return 1;
}
if (opts.verbose)
fprintf(stderr, "connecting...");
if (net_fd->connect(addr, opts.port_number, &e) == false)
{
std::cerr << e.Format() << std::endl;
return 1;
}
if (opts.verbose)
fprintf(stderr, "success\n");
}
else
{
pxfe_tcp_stream_socket listen;
if (listen.init(opts.port_number,true,&e) == false)
{
std::cerr << e.Format() << std::endl;
return 1;
}
listen.listen();
if (opts.verbose)
fprintf(stderr, "listening...");
do {
net_fd = listen.accept(&e);
if (e.e != 0)
std::cerr << e.Format() << std::endl;
} while (net_fd == NULL);
if (opts.verbose)
{
uint32_t addr = net_fd->get_peer_addr();
std::cerr << "accepted from "
<< (int) ((addr >> 24) & 0xFF) << "."
<< (int) ((addr >> 16) & 0xFF) << "."
<< (int) ((addr >> 8) & 0xFF) << "."
<< (int) ((addr >> 0) & 0xFF)
<< std::endl;
}
// listen socket closed here, because we
// no longer need it.
}
start_time.getNow();
ticker.start(0, 500000);
pxfe_poll p;
p.set(net_fd->getFd(), POLLIN);
p.set(ticker.fd(), POLLIN);
#define POLLERRS (POLLERR | POLLHUP | POLLNVAL)
while (1)
{
int evt;
if (opts.input_set)
p.set(opts.input_fd, POLLIN);
p.poll(1000);
evt = p.rget(net_fd->getFd());
if (evt & POLLIN)
{
if (!handle_net_fd())
break;
}
else if (evt & POLLERRS)
break;
if (opts.input_set)
{
evt = p.rget(opts.input_fd);
if (evt & POLLIN)
{
if (!handle_input_fd())
break;
}
else if (evt & POLLERRS)
break;
}
if (p.rget(ticker.fd()) & POLLIN)
handle_tick();
}
ticker.pause();
if (opts.verbose || opts.stats_at_end)
print_stats(true);
return 0;
}
private:
bool handle_net_fd(void)
{
pxfe_errno e;
if (net_fd->recv(buffer, &e) == false)
{
std::cerr << e.Format() << std::endl;
return false;
}
if (buffer.length() == 0)
return false;
bytes_received += buffer.length();
if (opts.output_set)
{
int cc = -1;
do {
cc = buffer.write(opts.output_fd);
if (cc == buffer.length())
break;
if (cc < 0)
{
int e = errno;
char * err = strerror(e);
fprintf(stderr, "write failed: %d: %s\n", e, err);
return false;
}
else if (cc == 0)
{
fprintf(stderr, "write returned zero\n");
return false;
}
else
// remove the bytes already written
// and go around again to get the rest.
buffer.erase(0,cc);
} while (true);
}
return true;
}
bool handle_input_fd(void)
{
pxfe_errno e;
int cc = buffer.read(opts.input_fd,
pxfe_tcp_stream_socket::MAX_MSG_LEN, &e);
if (cc < 0)
{
std::cerr << e.Format() << std::endl;
return false;
}
else if (cc == 0)
return false;
else
{
if (net_fd->send(buffer, &e) == false)
{
std::cerr << e.Format() << std::endl;
return false;
}
bytes_sent += buffer.length();
}
return true;
}
void handle_tick(void)
{
ticker.doread();
if (opts.verbose)
print_stats(/*final*/false);
}
void print_stats(bool final)
{
pxfe_timeval now, diff;
uint64_t total = bytes_sent + bytes_received;
now.getNow();
diff = now - start_time;
float t = diff.usecs() / 1000000.0;
if (t == 0.0)
t = 99999.0;
float bytes_per_sec = (float) total / t;
float bits_per_sec = bytes_per_sec * 8.0;
fprintf(stderr, "\r%" PRIu64 " in %u.%06u s "
"(%.0f Bps %.0f bps)",
total,
(unsigned int) diff.tv_sec,
(unsigned int) diff.tv_usec,
bytes_per_sec, bits_per_sec);
if (final)
fprintf(stderr, "\n");
}
};
extern "C" int
i2_main(int argc, char ** argv)
{
i2_program i2(argc, argv);
if (i2.ok() == false)
return 1;
return i2.main();
}
<|endoftext|> |
<commit_before>/* SbHalfPong, sort of like Pong but for one
author: Ulrike Hager
*/
#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>
#include <climits>
#include <cmath>
#include <random>
#include <algorithm>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_image.h>
#include "SbTexture.h"
#include "SbTimer.h"
#include "SbWindow.h"
#include "SbObject.h"
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
class Paddle : public SbObject
{
public:
Paddle();
void handle_event(const SDL_Event& event);
int move();
};
class Spark : public SbObject
{
public:
Spark(double x, double y, double width, double height);
~Spark();
void set_texture(SbTexture* tex) {texture_ = tex;}
private:
int lifetime = 15; // milliseconds
};
class Ball : public SbObject
{
public:
Ball();
// void handle_event(const SDL_Event& event);
/*! \retval 1 if ball in goal
\retval 0 else
*/
int move(const SDL_Rect& paddleBox);
void render();
/*! Reset after goal.
*/
void reset();
static Uint32 resetball(Uint32 interval, void *param );
private:
int goal_ = 0;
std::vector<Spark> sparks_;
std::default_random_engine generator_;
std::uniform_int_distribution<int> distr_number { 15, 30 };
std::normal_distribution<double> distr_position { 0.0, 0.01 };
std::normal_distribution<double> distr_size { 0.003, 0.002 };
void create_sparks();
};
TTF_Font *fps_font = nullptr;
/*! Paddle implementation
*/
Paddle::Paddle()
: SbObject(SCREEN_WIDTH - 70, 200, 20, 80)
{
// bounding_rect_ = {};
velocity_y_ = 0;
velocity_ = 1200;
SDL_Color color = {210, 160, 10, 0};
texture_ = new SbTexture();
texture_->from_rectangle( window->renderer(), bounding_rect_.w, bounding_rect_.h, color );
}
void
Paddle::handle_event(const SDL_Event& event)
{
SbObject::handle_event( event );
if( event.type == SDL_KEYDOWN && event.key.repeat == 0 ) {
switch( event.key.keysym.sym ) {
case SDLK_UP: velocity_y_ -= velocity_; break;
case SDLK_DOWN: velocity_y_ += velocity_; break;
}
}
else if( event.type == SDL_KEYUP && event.key.repeat == 0 ) {
switch( event.key.keysym.sym ) {
case SDLK_UP: velocity_y_ += velocity_; break;
case SDLK_DOWN: velocity_y_ -= velocity_; break;
}
}
}
int
Paddle::move()
{
Uint32 deltaT = timer_.getTime();
int velocity = ( window->height() / velocity_y_ )* deltaT;
bounding_rect_.y += velocity;
if( ( bounding_rect_.y < 0 ) || ( bounding_rect_.y + bounding_rect_.h > window->height() ) ) {
bounding_rect_.y -= velocity;
}
move_bounding_box();
timer_.start();
return 0;
}
Spark::Spark(double x, double y, double width, double height)
: SbObject(x,y,width,height)
{
}
Spark::~Spark()
{
texture_ = nullptr;
}
/*! Ball implementation
*/
Ball::Ball()
: SbObject(50, 300, 25, 25)
{
// bounding_box_ = {};
velocity_y_ = 1500;
velocity_x_ = 1500;
velocity_ = 1500;
texture_ = new SbTexture();
texture_->from_file(window->renderer(), "resources/ball.png", bounding_rect_.w, bounding_rect_.h );
}
void
Ball::create_sparks()
{
if (! sparks_.empty() ) sparks_.clear();
int n_sparks = distr_number(generator_);
for ( int i = 0 ; i < n_sparks ; ++i ) {
double x = distr_position(generator_);
double y = distr_position(generator_);
double d = distr_size(generator_);
x += ( bounding_box_[0] + bounding_box_[2]/2);
y += ( bounding_box_[1] + bounding_box_[3]/2);
Spark toAdd(x, y, d, d);
toAdd.set_texture( texture_ );
sparks_.push_back(toAdd);
}
}
int
Ball::move(const SDL_Rect& paddleBox)
{
if ( goal_ ) return 0;
Uint32 deltaT = timer_.getTime();
int x_velocity = ( window->width() / velocity_x_ ) * deltaT;
int y_velocity = ( window->height() / velocity_y_ ) * deltaT;
bounding_rect_.y += y_velocity;
bounding_rect_.x += x_velocity;
if ( bounding_rect_.x + bounding_rect_.w >= window->width() ) {
goal_ = 1;
bounding_rect_.x = 0;
bounding_rect_.y = window->height() / 2 ;
move_bounding_box();
return goal_;
}
bool in_xrange = false, in_yrange = false, x_hit = false, y_hit = false ;
if ( bounding_rect_.x + bounding_rect_.w/2 >= paddleBox.x &&
bounding_rect_.x - bounding_rect_.w/2 <= paddleBox.x + paddleBox.w )
in_xrange = true;
if ( bounding_rect_.y + bounding_rect_.h/2 >= paddleBox.y &&
bounding_rect_.y - bounding_rect_.h/2 <= paddleBox.y + paddleBox.h)
in_yrange = true;
if ( bounding_rect_.x + bounding_rect_.w >= paddleBox.x &&
bounding_rect_.x <= paddleBox.x + paddleBox.w )
x_hit = true;
if ( bounding_rect_.y + bounding_rect_.h >= paddleBox.y &&
bounding_rect_.y <= paddleBox.y + paddleBox.h )
y_hit = true;
if ( ( x_hit && in_yrange ) || bounding_rect_.x <= 0 ) {
velocity_x_ *= -1;
if ( x_hit && in_yrange )
create_sparks();
}
if ( ( y_hit && in_xrange ) || bounding_rect_.y <= 0 || ( bounding_rect_.y + bounding_rect_.h >= window->height() ) )
velocity_y_ *= -1;
move_bounding_box();
timer_.start();
return goal_;
}
void
Ball::render()
{
SbObject::render();
if ( !sparks_.empty() )
std::for_each( sparks_.begin(), sparks_.end(),
[](Spark& spark) -> void { spark.render(); } );
}
void
Ball::reset()
{
goal_ = 0;
timer_.start();
}
Uint32
Ball::resetball(Uint32 interval, void *param )
{
// SDL_Event event;
// SDL_UserEvent userevent;
// userevent.type = SDL_USEREVENT;
// userevent.code = 0;
// userevent.data1 = &reset();
// userevent.data2 = nullptr;
// event.type = SDL_USEREVENT;
// event.user = userevent;
// SDL_PushEvent(&event);
((Ball*)param)->reset();
return(0);
}
SbWindow* SbObject::window;
int main()
{
try {
SbWindow window;
window.initialize("Half-Pong", SCREEN_WIDTH, SCREEN_HEIGHT);
SbObject::window = &window ;
Paddle paddle;
Ball ball;
SbTexture *fps_texture = new SbTexture();
SDL_Color fps_color = {210, 160, 10, 0};
SbTimer fps_timer;
fps_font = TTF_OpenFont( "resources/FreeSans.ttf", 18 );
if ( !fps_font )
throw std::runtime_error( "TTF_OpenFont: " + std::string( TTF_GetError() ) );
SDL_TimerID reset_timer;
SDL_Event event;
bool quit = false;
int fps_counter = 0;
fps_timer.start();
while (!quit) {
while( SDL_PollEvent( &event ) ) {
if (event.type == SDL_QUIT) quit = true;
else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE ) quit = true;
window.handle_event(event);
paddle.handle_event(event);
ball.handle_event( event );
}
if ( fps_counter > 0 && fps_counter < INT_MAX ) {
double average = double(fps_counter)/ ( fps_timer.getTime()/1000.0 ) ;
std::string fps_text = std::to_string(int(average)) + " fps";
fps_texture->from_text( window.renderer(), fps_text, fps_font, fps_color);
}
else {
fps_counter = 0;
fps_timer.start();
}
paddle.move();
int goal = ball.move( paddle.bounding_rect() );
if ( goal ) {
reset_timer = SDL_AddTimer(1000, Ball::resetball, &ball);
}
SDL_RenderClear( window.renderer() );
paddle.render();
ball.render();
fps_texture->render( window.renderer(), 10,10);
SDL_RenderPresent( window.renderer() );
++fps_counter;
}
}
catch (const std::exception& expt) {
std::cerr << expt.what() << std::endl;
}
return 0;
}
<commit_msg>Working on timer to destroy sprites. Stumped.<commit_after>/* SbHalfPong, sort of like Pong but for one
author: Ulrike Hager
*/
#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>
#include <climits>
#include <cmath>
#include <random>
#include <algorithm>
#include <functional>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_image.h>
#include "SbTexture.h"
#include "SbTimer.h"
#include "SbWindow.h"
#include "SbObject.h"
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
class Ball;
class Spark;
class Paddle;
class Paddle : public SbObject
{
public:
Paddle();
void handle_event(const SDL_Event& event);
int move();
};
class Ball : public SbObject
{
public:
Ball();
// void handle_event(const SDL_Event& event);
/*! \retval 1 if ball in goal
\retval 0 else
*/
int move(const SDL_Rect& paddleBox);
void render();
/*! Reset after goal.
*/
void reset();
static Uint32 resetball(Uint32 interval, void *param );
Uint32 remove_spark(Uint32 interval, void *param, int index );
private:
int goal_ = 0;
std::vector<Spark> sparks_;
std::default_random_engine generator_;
std::uniform_int_distribution<int> distr_number { 15, 30 };
std::normal_distribution<double> distr_position { 0.0, 0.01 };
std::normal_distribution<double> distr_size { 0.003, 0.002 };
std::normal_distribution<double> distr_lifetime { 120, 50 };
void create_sparks();
void delete_spark(int index);
};
class Spark : public SbObject
{
friend class Ball;
public:
Spark(double x, double y, double width, double height);
~Spark();
static Uint32 remove_texture(Uint32 interval, void* param);
void set_texture(SbTexture* tex) {texture_ = tex;}
int index() { return index_;}
private:
SDL_TimerID spark_timer_;
int index_;
};
/*! Paddle implementation
*/
Paddle::Paddle()
: SbObject(SCREEN_WIDTH - 70, 200, 20, 80)
{
// bounding_rect_ = {};
velocity_y_ = 0;
velocity_ = 1200;
SDL_Color color = {210, 160, 10, 0};
texture_ = new SbTexture();
texture_->from_rectangle( window->renderer(), bounding_rect_.w, bounding_rect_.h, color );
}
void
Paddle::handle_event(const SDL_Event& event)
{
SbObject::handle_event( event );
if( event.type == SDL_KEYDOWN && event.key.repeat == 0 ) {
switch( event.key.keysym.sym ) {
case SDLK_UP: velocity_y_ -= velocity_; break;
case SDLK_DOWN: velocity_y_ += velocity_; break;
}
}
else if( event.type == SDL_KEYUP && event.key.repeat == 0 ) {
switch( event.key.keysym.sym ) {
case SDLK_UP: velocity_y_ += velocity_; break;
case SDLK_DOWN: velocity_y_ -= velocity_; break;
}
}
}
int
Paddle::move()
{
Uint32 deltaT = timer_.getTime();
int velocity = ( window->height() / velocity_y_ )* deltaT;
bounding_rect_.y += velocity;
if( ( bounding_rect_.y < 0 ) || ( bounding_rect_.y + bounding_rect_.h > window->height() ) ) {
bounding_rect_.y -= velocity;
}
move_bounding_box();
timer_.start();
return 0;
}
Spark::Spark(double x, double y, double width, double height)
: SbObject(x,y,width,height)
{
}
Spark::~Spark()
{
texture_ = nullptr;
}
Uint32
Ball::remove_spark(Uint32 interval, void *param, int index )
{
((Ball*)param)->delete_spark(index);
return(0);
}
void
Ball::delete_spark(int index)
{
std::remove_if( sparks_.begin(), sparks_.end(),
[index](Spark& spark) -> bool { return spark.index() == index;} );
// ((Spark*)param)->set_texture( nullptr );
}
/*! Ball implementation
*/
Ball::Ball()
: SbObject(50, 300, 25, 25)
{
// bounding_box_ = {};
velocity_y_ = 1500;
velocity_x_ = 1500;
velocity_ = 1500;
texture_ = new SbTexture();
texture_->from_file(window->renderer(), "resources/ball.png", bounding_rect_.w, bounding_rect_.h );
}
void
Ball::create_sparks()
{
if (! sparks_.empty() ) sparks_.clear();
int n_sparks = distr_number(generator_);
for ( int i = 0 ; i < n_sparks ; ++i ) {
double x = distr_position(generator_);
double y = distr_position(generator_);
double d = distr_size(generator_);
x += ( bounding_box_[0] + bounding_box_[2]/2);
y += ( bounding_box_[1] + bounding_box_[3]/2);
Spark toAdd(x, y, d, d);
toAdd.set_texture( texture_ );
toAdd.index_ = i;
int lifetime = int(distr_lifetime(generator_));
auto funct = std::bind(&Ball::remove_spark, this, std::placeholders::_1, std::placeholders::_2, index );
toAdd.spark_timer_ = SDL_AddTimer(lifetime, funct, &toAdd);
sparks_.push_back(toAdd);
}
}
int
Ball::move(const SDL_Rect& paddleBox)
{
if ( goal_ ) return 0;
Uint32 deltaT = timer_.getTime();
int x_velocity = ( window->width() / velocity_x_ ) * deltaT;
int y_velocity = ( window->height() / velocity_y_ ) * deltaT;
bounding_rect_.y += y_velocity;
bounding_rect_.x += x_velocity;
if ( bounding_rect_.x + bounding_rect_.w >= window->width() ) {
goal_ = 1;
bounding_rect_.x = 0;
bounding_rect_.y = window->height() / 2 ;
move_bounding_box();
return goal_;
}
bool in_xrange = false, in_yrange = false, x_hit = false, y_hit = false ;
if ( bounding_rect_.x + bounding_rect_.w/2 >= paddleBox.x &&
bounding_rect_.x - bounding_rect_.w/2 <= paddleBox.x + paddleBox.w )
in_xrange = true;
if ( bounding_rect_.y + bounding_rect_.h/2 >= paddleBox.y &&
bounding_rect_.y - bounding_rect_.h/2 <= paddleBox.y + paddleBox.h)
in_yrange = true;
if ( bounding_rect_.x + bounding_rect_.w >= paddleBox.x &&
bounding_rect_.x <= paddleBox.x + paddleBox.w )
x_hit = true;
if ( bounding_rect_.y + bounding_rect_.h >= paddleBox.y &&
bounding_rect_.y <= paddleBox.y + paddleBox.h )
y_hit = true;
if ( ( x_hit && in_yrange ) || bounding_rect_.x <= 0 ) {
velocity_x_ *= -1;
if ( x_hit && in_yrange )
create_sparks();
}
if ( ( y_hit && in_xrange ) || bounding_rect_.y <= 0 || ( bounding_rect_.y + bounding_rect_.h >= window->height() ) )
velocity_y_ *= -1;
move_bounding_box();
timer_.start();
return goal_;
}
void
Ball::render()
{
SbObject::render();
if ( !sparks_.empty() )
std::for_each( sparks_.begin(), sparks_.end(),
[](Spark& spark) -> void { spark.render(); } );
}
void
Ball::reset()
{
goal_ = 0;
timer_.start();
}
Uint32
Ball::resetball(Uint32 interval, void *param )
{
((Ball*)param)->reset();
return(0);
}
SbWindow* SbObject::window;
TTF_Font *fps_font = nullptr;
int main()
{
try {
SbWindow window;
window.initialize("Half-Pong", SCREEN_WIDTH, SCREEN_HEIGHT);
SbObject::window = &window ;
Paddle paddle;
Ball ball;
SbTexture *fps_texture = new SbTexture();
SDL_Color fps_color = {210, 160, 10, 0};
SbTimer fps_timer;
fps_font = TTF_OpenFont( "resources/FreeSans.ttf", 18 );
if ( !fps_font )
throw std::runtime_error( "TTF_OpenFont: " + std::string( TTF_GetError() ) );
SDL_TimerID reset_timer;
SDL_Event event;
bool quit = false;
int fps_counter = 0;
fps_timer.start();
while (!quit) {
while( SDL_PollEvent( &event ) ) {
if (event.type == SDL_QUIT) quit = true;
else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE ) quit = true;
window.handle_event(event);
paddle.handle_event(event);
ball.handle_event( event );
}
if ( fps_counter > 0 && fps_counter < INT_MAX ) {
double average = double(fps_counter)/ ( fps_timer.getTime()/1000.0 ) ;
std::string fps_text = std::to_string(int(average)) + " fps";
fps_texture->from_text( window.renderer(), fps_text, fps_font, fps_color);
}
else {
fps_counter = 0;
fps_timer.start();
}
paddle.move();
int goal = ball.move( paddle.bounding_rect() );
if ( goal ) {
reset_timer = SDL_AddTimer(1000, Ball::resetball, &ball);
}
SDL_RenderClear( window.renderer() );
paddle.render();
ball.render();
fps_texture->render( window.renderer(), 10,10);
SDL_RenderPresent( window.renderer() );
++fps_counter;
}
}
catch (const std::exception& expt) {
std::cerr << expt.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include <tic_tac_toe/tic_tac_toe.hpp>
using namespace eosio;
namespace tic_tac_toe {
struct impl {
/**
* @brief Check if cell is empty
* @param cell - value of the cell (should be either 0, 1, or 2)
* @return true if cell is empty
*/
bool is_empty_cell(const uint8_t& cell) {
return cell == 0;
}
/**
* @brief Check for valid movement
* @detail Movement is considered valid if it is inside the board and done on empty cell
* @param movement - the movement made by the player
* @param game - the game on which the movement is being made
* @return true if movement is valid
*/
bool is_valid_movement(const movement& mvt, const game& game_for_movement) {
uint32_t movement_location = mvt.row * 3 + mvt.column;
bool is_valid = movement_location < board_len && is_empty_cell(game_for_movement.board[movement_location]);
return is_valid;
}
/**
* @brief Get winner of the game
* @detail Winner of the game is the first player who made three consecutive aligned movement
* @param game - the game which we want to determine the winner of
* @return winner of the game (can be either none/ draw/ account name of host/ account name of challenger)
*/
account_name get_winner(const game& current_game) {
if((current_game.board[0] == current_game.board[4] && current_game.board[4] == current_game.board[8]) ||
(current_game.board[1] == current_game.board[4] && current_game.board[4] == current_game.board[7]) ||
(current_game.board[2] == current_game.board[4] && current_game.board[4] == current_game.board[6]) ||
(current_game.board[3] == current_game.board[4] && current_game.board[4] == current_game.board[5])) {
// - | - | x x | - | - - | - | - - | x | -
// - | x | - - | x | - x | x | x - | x | -
// x | - | - - | - | x - | - | - - | x | -
if (current_game.board[4] == 1) {
return current_game.host;
} else if (current_game.board[4] == 2) {
return current_game.challenger;
}
} else if ((current_game.board[0] == current_game.board[1] && current_game.board[1] == current_game.board[2]) ||
(current_game.board[0] == current_game.board[3] && current_game.board[3] == current_game.board[6])) {
// x | x | x x | - | -
// - | - | - x | - | -
// - | - | - x | - | -
if (current_game.board[0] == 1) {
return current_game.host;
} else if (current_game.board[0] == 2) {
return current_game.challenger;
}
} else if ((current_game.board[2] == current_game.board[5] && current_game.board[5] == current_game.board[8]) ||
(current_game.board[6] == current_game.board[7] && current_game.board[7] == current_game.board[8])) {
// - | - | - - | - | x
// - | - | - - | - | x
// x | x | x - | - | x
if (current_game.board[8] == 1) {
return current_game.host;
} else if (current_game.board[8] == 2) {
return current_game.challenger;
}
} else {
bool is_board_full = true;
for (uint8_t i = 0; i < board_len; i++) {
if (is_empty_cell(current_game.board[i])) {
is_board_full = false;
break;
}
}
if (is_board_full) {
return N(draw);
}
}
return N(none);
}
/**
* @brief Apply create action
* @param create - action to be applied
*/
void on(const create& c) {
require_auth(c.host);
eosio_assert(c.challenger != c.host, "challenger shouldn't be the same as host");
// Check if game already exists
games existing_host_games(code_account, c.host);
auto itr = existing_host_games.find( c.challenger );
eosio_assert(itr == existing_host_games.end(), "game already exists");
existing_host_games.emplace(c.host, [&]( auto& g ) {
g.challenger = c.challenger;
g.host = c.host;
g.turn = c.host;
});
}
/**
* @brief Apply restart action
* @param restart - action to be applied
*/
void on(const restart& r) {
require_auth(r.by);
// Check if game exists
games existing_host_games(code_account, r.host);
auto itr = existing_host_games.find( r.challenger );
eosio_assert(itr != existing_host_games.end(), "game doesn't exists");
// Check if this game belongs to the action sender
eosio_assert(r.by == itr->host || r.by == itr->challenger, "this is not your game!");
// Reset game
existing_host_games.modify(itr, itr->host, []( auto& g ) {
g.reset_game();
});
}
/**
* @brief Apply close action
* @param close - action to be applied
*/
void on(const close& c) {
require_auth(c.host);
// Check if game exists
games existing_host_games(code_account, c.host);
auto itr = existing_host_games.find( c.challenger );
eosio_assert(itr != existing_host_games.end(), "game doesn't exists");
// Remove game
existing_host_games.erase(itr);
}
/**
* @brief Apply move action
* @param move - action to be applied
*/
void on(const move& m) {
require_auth(m.by);
// Check if game exists
games existing_host_games(code_account, m.host);
auto itr = existing_host_games.find( m.challenger );
eosio_assert(itr != existing_host_games.end(), "game doesn't exists");
// Check if this game hasn't ended yet
eosio_assert(itr->winner == N(none), "the game has ended!");
// Check if this game belongs to the action sender
eosio_assert(m.by == itr->host || m.by == itr->challenger, "this is not your game!");
// Check if this is the action sender's turn
eosio_assert(m.by == itr->turn, "it's not your turn yet!");
// Check if user makes a valid movement
eosio_assert(is_valid_movement(m.mvt, *itr), "not a valid movement!");
// Fill the cell, 1 for host, 2 for challenger
const auto cell_value = itr->turn == itr->host ? 1 : 2;
const auto turn = itr->turn == itr->host ? itr->challenger : itr->host;
existing_host_games.modify(itr, itr->host, [&]( auto& g ) {
g.board[m.mvt.row * 3 + m.mvt.column] = cell_value;
g.turn = turn;
//check to see if we have a winner
g.winner = get_winner(g);
});
}
/// The apply method implements the dispatch of events to this contract
void apply( uint64_t receiver, uint64_t code, uint64_t action ) {
if (code == code_account) {
if (action == N(create)) {
impl::on(eosio::unpack_action_data<tic_tac_toe::create>());
} else if (action == N(restart)) {
impl::on(eosio::unpack_action_data<tic_tac_toe::restart>());
} else if (action == N(close)) {
impl::on(eosio::unpack_action_data<tic_tac_toe::close>());
} else if (action == N(move)) {
impl::on(eosio::unpack_action_data<tic_tac_toe::move>());
}
}
}
};
}
/**
* The init() and apply() methods must have C calling convention so that the blockchain can lookup and
* call these methods.
*/
extern "C" {
using namespace tic_tac_toe;
/// The apply method implements the dispatch of events to this contract
void apply( uint64_t receiver, uint64_t code, uint64_t action ) {
impl().apply(receiver, code, action);
}
} // extern "C"
<commit_msg>Fixed comment. GH #2214<commit_after>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include <tic_tac_toe/tic_tac_toe.hpp>
using namespace eosio;
namespace tic_tac_toe {
struct impl {
/**
* @brief Check if cell is empty
* @param cell - value of the cell (should be either 0, 1, or 2)
* @return true if cell is empty
*/
bool is_empty_cell(const uint8_t& cell) {
return cell == 0;
}
/**
* @brief Check for valid movement
* @detail Movement is considered valid if it is inside the board and done on empty cell
* @param movement - the movement made by the player
* @param game - the game on which the movement is being made
* @return true if movement is valid
*/
bool is_valid_movement(const movement& mvt, const game& game_for_movement) {
uint32_t movement_location = mvt.row * 3 + mvt.column;
bool is_valid = movement_location < board_len && is_empty_cell(game_for_movement.board[movement_location]);
return is_valid;
}
/**
* @brief Get winner of the game
* @detail Winner of the game is the first player who made three consecutive aligned movement
* @param game - the game which we want to determine the winner of
* @return winner of the game (can be either none/ draw/ account name of host/ account name of challenger)
*/
account_name get_winner(const game& current_game) {
if((current_game.board[0] == current_game.board[4] && current_game.board[4] == current_game.board[8]) ||
(current_game.board[1] == current_game.board[4] && current_game.board[4] == current_game.board[7]) ||
(current_game.board[2] == current_game.board[4] && current_game.board[4] == current_game.board[6]) ||
(current_game.board[3] == current_game.board[4] && current_game.board[4] == current_game.board[5])) {
// - | - | x x | - | - - | - | - - | x | -
// - | x | - - | x | - x | x | x - | x | -
// x | - | - - | - | x - | - | - - | x | -
if (current_game.board[4] == 1) {
return current_game.host;
} else if (current_game.board[4] == 2) {
return current_game.challenger;
}
} else if ((current_game.board[0] == current_game.board[1] && current_game.board[1] == current_game.board[2]) ||
(current_game.board[0] == current_game.board[3] && current_game.board[3] == current_game.board[6])) {
// x | x | x x | - | -
// - | - | - x | - | -
// - | - | - x | - | -
if (current_game.board[0] == 1) {
return current_game.host;
} else if (current_game.board[0] == 2) {
return current_game.challenger;
}
} else if ((current_game.board[2] == current_game.board[5] && current_game.board[5] == current_game.board[8]) ||
(current_game.board[6] == current_game.board[7] && current_game.board[7] == current_game.board[8])) {
// - | - | - - | - | x
// - | - | - - | - | x
// x | x | x - | - | x
if (current_game.board[8] == 1) {
return current_game.host;
} else if (current_game.board[8] == 2) {
return current_game.challenger;
}
} else {
bool is_board_full = true;
for (uint8_t i = 0; i < board_len; i++) {
if (is_empty_cell(current_game.board[i])) {
is_board_full = false;
break;
}
}
if (is_board_full) {
return N(draw);
}
}
return N(none);
}
/**
* @brief Apply create action
* @param create - action to be applied
*/
void on(const create& c) {
require_auth(c.host);
eosio_assert(c.challenger != c.host, "challenger shouldn't be the same as host");
// Check if game already exists
games existing_host_games(code_account, c.host);
auto itr = existing_host_games.find( c.challenger );
eosio_assert(itr == existing_host_games.end(), "game already exists");
existing_host_games.emplace(c.host, [&]( auto& g ) {
g.challenger = c.challenger;
g.host = c.host;
g.turn = c.host;
});
}
/**
* @brief Apply restart action
* @param restart - action to be applied
*/
void on(const restart& r) {
require_auth(r.by);
// Check if game exists
games existing_host_games(code_account, r.host);
auto itr = existing_host_games.find( r.challenger );
eosio_assert(itr != existing_host_games.end(), "game doesn't exists");
// Check if this game belongs to the action sender
eosio_assert(r.by == itr->host || r.by == itr->challenger, "this is not your game!");
// Reset game
existing_host_games.modify(itr, itr->host, []( auto& g ) {
g.reset_game();
});
}
/**
* @brief Apply close action
* @param close - action to be applied
*/
void on(const close& c) {
require_auth(c.host);
// Check if game exists
games existing_host_games(code_account, c.host);
auto itr = existing_host_games.find( c.challenger );
eosio_assert(itr != existing_host_games.end(), "game doesn't exists");
// Remove game
existing_host_games.erase(itr);
}
/**
* @brief Apply move action
* @param move - action to be applied
*/
void on(const move& m) {
require_auth(m.by);
// Check if game exists
games existing_host_games(code_account, m.host);
auto itr = existing_host_games.find( m.challenger );
eosio_assert(itr != existing_host_games.end(), "game doesn't exists");
// Check if this game hasn't ended yet
eosio_assert(itr->winner == N(none), "the game has ended!");
// Check if this game belongs to the action sender
eosio_assert(m.by == itr->host || m.by == itr->challenger, "this is not your game!");
// Check if this is the action sender's turn
eosio_assert(m.by == itr->turn, "it's not your turn yet!");
// Check if user makes a valid movement
eosio_assert(is_valid_movement(m.mvt, *itr), "not a valid movement!");
// Fill the cell, 1 for host, 2 for challenger
const auto cell_value = itr->turn == itr->host ? 1 : 2;
const auto turn = itr->turn == itr->host ? itr->challenger : itr->host;
existing_host_games.modify(itr, itr->host, [&]( auto& g ) {
g.board[m.mvt.row * 3 + m.mvt.column] = cell_value;
g.turn = turn;
//check to see if we have a winner
g.winner = get_winner(g);
});
}
/// The apply method implements the dispatch of events to this contract
void apply( uint64_t receiver, uint64_t code, uint64_t action ) {
if (code == code_account) {
if (action == N(create)) {
impl::on(eosio::unpack_action_data<tic_tac_toe::create>());
} else if (action == N(restart)) {
impl::on(eosio::unpack_action_data<tic_tac_toe::restart>());
} else if (action == N(close)) {
impl::on(eosio::unpack_action_data<tic_tac_toe::close>());
} else if (action == N(move)) {
impl::on(eosio::unpack_action_data<tic_tac_toe::move>());
}
}
}
};
}
/**
* The apply() methods must have C calling convention so that the blockchain can lookup and
* call these methods.
*/
extern "C" {
using namespace tic_tac_toe;
/// The apply method implements the dispatch of events to this contract
void apply( uint64_t receiver, uint64_t code, uint64_t action ) {
impl().apply(receiver, code, action);
}
} // extern "C"
<|endoftext|> |
<commit_before>#include "SvgCreator.h"
#include "SvgItemInfo.h"
#include "SvgTextInfo.h"
#include "SvgLineInfo.h"
#include "SvgCurveInfo.h"
#include "MapData.h"
#include "FilledPolygonItem.h"
#include "LineItem.h"
#include "PointItem.h"
#include "ItemLook.h"
#include "Point.h"
#include "BezierInfo.h"
#include "TextInfo.h"
#include "MessageTypeEnum.h"
#include <sstream>
namespace map_server
{
std::mutex *SvgCreator::_coutMutexPtr = 0;
SvgCreator::~SvgCreator()
{
std::multimap<int, SvgInfo *>::iterator it = _infoMap.begin();
for (; it != _infoMap.end(); ++it) delete (*it).second;
}
void SvgCreator::execute(void)
{
std::stringstream content;
content << "<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>" << "\\n"
<< "<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" version=\\\"1.1\\\" width=\\\"" << _widthInPixels
<< "\\\" height=\\\"" << _heightInPixels << "\\\">" << "\\n";
MapData::lock();
std::multimap<int, SvgInfo *>::iterator it = _infoMap.begin();
for (; it != _infoMap.end(); ++it)
{
SvgItemInfo *svgItemInfo = dynamic_cast<SvgItemInfo *>((*it).second);
if (svgItemInfo != 0)
{
const MapItem *item = svgItemInfo->getItem();
const ItemLook *look = svgItemInfo->getLook();
int resolutionIndex = svgItemInfo->getResolutionIndex();
const FilledPolygonItem *filledPolygonItem = dynamic_cast<const FilledPolygonItem *>(item);
if (filledPolygonItem != 0)
{
std::vector<SvgCurveInfo *> curveInfoVector;
bool lastIn = false;
const double d = 2.0;
int i, n = filledPolygonItem->getPointVector(resolutionIndex).size();
for (i = 0; i < n; ++i)
{
const Point *point = filledPolygonItem->getPointVector(resolutionIndex)[i];
double x = (point->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (point->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
bool in = (x > -d && x < _widthInPixels + d && y > -d && y < _heightInPixels + d);
bool nextIn = false;
if (i < n - 1)
{
const Point *np = filledPolygonItem->getPointVector(resolutionIndex)[i + 1];
double nx = (np->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double ny = (np->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
nextIn = (nx > -d && nx < _widthInPixels + d && ny > -d && ny < _heightInPixels + d);
}
if (!lastIn && !nextIn && x < -d) x = -d;
if (!lastIn && !nextIn && x > _widthInPixels + d) x = _widthInPixels + d;
if (!lastIn && !nextIn && y < -d) y = -d;
if (!lastIn && !nextIn && y > _heightInPixels + d) y = _heightInPixels + d;
if (i == 0)
{
curveInfoVector.push_back(new SvgCurveInfo(0.0, 0.0, 0.0, 0.0, x, y));
}
else
{
double x1 = x, y1 = y, x2 = x, y2 = y;
if (in || lastIn)
{
x1 = (point->getBezierInfo()->getX1() - _xFocus) * _scale + 0.5 * _widthInPixels;
y1 = (point->getBezierInfo()->getY1() - _yFocus) * _scale + 0.5 * _heightInPixels;
x2 = (point->getBezierInfo()->getX2() - _xFocus) * _scale + 0.5 * _widthInPixels;
y2 = (point->getBezierInfo()->getY2() - _yFocus) * _scale + 0.5 * _heightInPixels;
}
curveInfoVector.push_back(new SvgCurveInfo(x1, y1, x2, y2, x, y));
}
lastIn = in;
}
content << "<path style=\\\"fill:" << look->getHexColor()
<< ";fill-opacity:" << static_cast<double>(look->getAlpha()) / 255.0
<< ";fill-rule:evenodd;stroke:none\\\" d=\\\"";
for (i = 0; i < n; ++i)
{
SvgCurveInfo *curveInfo = curveInfoVector[i];
if (i == 0)
{
content << "M " << curveInfo->getX() << "," << curveInfo->getY() << " ";
}
else
{
bool ok = true;
double x = curveInfo->getX();
double y = curveInfo->getY();
if (i != n - 1)
{
SvgCurveInfo *pCurveInfo = curveInfoVector[i - 1];
SvgCurveInfo *nCurveInfo = curveInfoVector[i + 1];
if ((y < -(d - 1.0) || y > _widthInPixels + (d - 1.0)) && pCurveInfo->getY() == y && nCurveInfo->getY() == y) ok = false;
if ((x < -(d - 1.0) || x > _heightInPixels + (d - 1.0)) && pCurveInfo->getX() == x && nCurveInfo->getX() == x) ok = false;
}
if (ok) content << "C " << curveInfo->getX1() << " " << curveInfo->getY1() << ","
<< curveInfo->getX2() << " " << curveInfo->getY2() << "," << x << " " << y << " ";
}
delete curveInfo;
}
content << "\\\"></path>" << "\\n";
}
else
{
const LineItem *lineItem = dynamic_cast<const LineItem *>(item);
if (lineItem != 0)
{
std::string strokeLineCap = "butt";
bool addCircle1 = false, addCircle2 = false;
if (lineItem->cap1Round())
{
if (lineItem->cap2Round()) strokeLineCap = "round";
else addCircle1 = true;
}
else
{
if (lineItem->cap2Round()) addCircle2 = true;
}
content << "<path style=\\\"fill:none;stroke:" << look->getHexColor()
<< ";stroke-opacity:" << static_cast<double>(look->getAlpha()) / 255.0
<< ";stroke-width:" << look->getSize() * _scale * _sizeFactor
<< ";stroke-linecap:" << strokeLineCap << ";stroke-linejoin:round\\\" d=\\\"";
bool lastIn = false;
std::stringstream lastMove;
int i, n = lineItem->getPointVector(resolutionIndex).size();
for (i = 0; i < n; ++i)
{
const Point *point = lineItem->getPointVector(resolutionIndex)[i];
double x = (point->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (point->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
bool in = (x > -10.0 && x < _widthInPixels + 10.0 && y > -10.0 && y < _heightInPixels + 10.0);
if (i == 0 || (!in && !lastIn))
{
lastMove.str("");
lastMove << "M " << x << "," << y << " ";
}
else
{
double x1 = (point->getBezierInfo()->getX1() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y1 = (point->getBezierInfo()->getY1() - _yFocus) * _scale + 0.5 * _heightInPixels;
double x2 = (point->getBezierInfo()->getX2() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y2 = (point->getBezierInfo()->getY2() - _yFocus) * _scale + 0.5 * _heightInPixels;
content << lastMove.str() << "C " << x1 << " " << y1 << "," << x2 << " " << y2 << "," << x << " " << y << " ";
lastMove.str("");
}
lastIn = in;
}
content << "\\\"></path>" << "\\n";
if (addCircle1)
{
const Point *point = lineItem->getPointVector(resolutionIndex)[0];
double x = (point->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (point->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
content << "<circle cx=\\\"" << x << "\\\" cy=\\\"" << y << "\\\" r=\\\"" << 0.5 * look->getSize() * _scale * _sizeFactor
<< "\\\" stroke=\\\"none\\\" fill=\\\"" << look->getHexColor()
<< "\\\" fill-opacity=\\\"" << static_cast<double>(look->getAlpha()) / 255.0 << "\\\"></circle>" << "\\n";
}
if (addCircle2)
{
const Point *point = lineItem->getPointVector(resolutionIndex)[n - 1];
double x = (point->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (point->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
content << "<circle cx=\\\"" << x << "\\\" cy=\\\"" << y << "\\\" r=\\\"" << 0.5 * look->getSize() * _scale * _sizeFactor
<< "\\\" stroke=\\\"none\\\" fill=\\\"" << look->getHexColor()
<< "\\\" fill-opacity=\\\"" << static_cast<double>(look->getAlpha()) / 255.0 << "\\\"></circle>" << "\\n";
}
}
else
{
const PointItem *pointItem = dynamic_cast<const PointItem *>(item);
if (pointItem != 0)
{
double x = (pointItem->getPoint()->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (pointItem->getPoint()->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
if (x > -10.0 && x < _widthInPixels + 10.0 && y > -10.0 && y < _heightInPixels + 10.0)
{
content << "<circle cx=\\\"" << x << "\\\" cy=\\\"" << y << "\\\" r=\\\"" << 0.5 * look->getSize() * _scale * _sizeFactor
<< "\\\" stroke=\\\"black\\\" stroke-width=\\\"" << _scale * _sizeFactor
<< "\\\" fill=\\\"" << look->getHexColor()
<< "\\\" fill-opacity=\\\"" << static_cast<double>(look->getAlpha()) / 255.0 << "\\\"></circle>" << "\\n";
}
}
}
}
}
else
{
SvgTextInfo *svgTextInfo = dynamic_cast<SvgTextInfo *>((*it).second);
if (svgTextInfo != 0)
{
int i, n = svgTextInfo->getLineVector().size();
for (i = 0; i < n; ++i)
{
const SvgLineInfo *lineInfo = svgTextInfo->getLineVector()[i];
double x = (lineInfo->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (lineInfo->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
content << "<text x=\\\"" << x << "\\\" y=\\\"" << y << "\\\" font-size=\\\"" << svgTextInfo->getTextInfo()->getFontSize()
<< "\\\" font-family=\\\"arial\\\" fill=\\\"" << svgTextInfo->getTextInfo()->getHexColor()
<< "\\\" fill-opacity=\\\"" << static_cast<double>(svgTextInfo->getTextInfo()->getAlpha()) / 255.0
<< "\\\">" << lineInfo->getText() << "</text>" << "\\n";
}
}
}
}
MapData::unlock();
content << "<rect x=\\\"0.5\\\" y=\\\"0.5\\\" width=\\\"" << _widthInPixels - 1.0 << "\\\" height=\\\"" << _heightInPixels - 1.0
<< "\\\" style=\\\"fill:none;stroke-width:1;stroke:black\\\"/>" << "\\n" << "</svg>";
_coutMutexPtr->lock();
std::cout << _socketId << " " << _requestId << " " << map_server::SVG
<< " {\"svg\":\"" << content.str() << "\"}" << std::endl;
_coutMutexPtr->unlock();
}
}
<commit_msg>C++ map server: SVG creator: Bug correction<commit_after>#include "SvgCreator.h"
#include "SvgItemInfo.h"
#include "SvgTextInfo.h"
#include "SvgLineInfo.h"
#include "SvgCurveInfo.h"
#include "MapData.h"
#include "FilledPolygonItem.h"
#include "LineItem.h"
#include "PointItem.h"
#include "ItemLook.h"
#include "Point.h"
#include "BezierInfo.h"
#include "TextInfo.h"
#include "MessageTypeEnum.h"
#include <sstream>
namespace map_server
{
std::mutex *SvgCreator::_coutMutexPtr = 0;
SvgCreator::~SvgCreator()
{
std::multimap<int, SvgInfo *>::iterator it = _infoMap.begin();
for (; it != _infoMap.end(); ++it) delete (*it).second;
}
void SvgCreator::execute(void)
{
std::stringstream content;
content << "<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>" << "\\n"
<< "<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" version=\\\"1.1\\\" width=\\\"" << _widthInPixels
<< "\\\" height=\\\"" << _heightInPixels << "\\\">" << "\\n";
MapData::lock();
std::multimap<int, SvgInfo *>::iterator it = _infoMap.begin();
for (; it != _infoMap.end(); ++it)
{
SvgItemInfo *svgItemInfo = dynamic_cast<SvgItemInfo *>((*it).second);
if (svgItemInfo != 0)
{
const MapItem *item = svgItemInfo->getItem();
const ItemLook *look = svgItemInfo->getLook();
int resolutionIndex = svgItemInfo->getResolutionIndex();
const FilledPolygonItem *filledPolygonItem = dynamic_cast<const FilledPolygonItem *>(item);
if (filledPolygonItem != 0)
{
std::vector<SvgCurveInfo *> curveInfoVector;
bool lastIn = false;
const double d = 2.0;
int i, n = filledPolygonItem->getPointVector(resolutionIndex).size();
for (i = 0; i < n; ++i)
{
const Point *point = filledPolygonItem->getPointVector(resolutionIndex)[i];
double x = (point->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (point->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
bool in = (x > -d && x < _widthInPixels + d && y > -d && y < _heightInPixels + d);
bool nextIn = false;
if (i < n - 1)
{
const Point *np = filledPolygonItem->getPointVector(resolutionIndex)[i + 1];
double nx = (np->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double ny = (np->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
nextIn = (nx > -d && nx < _widthInPixels + d && ny > -d && ny < _heightInPixels + d);
}
if (!lastIn && !nextIn && x < -d) x = -d;
if (!lastIn && !nextIn && x > _widthInPixels + d) x = _widthInPixels + d;
if (!lastIn && !nextIn && y < -d) y = -d;
if (!lastIn && !nextIn && y > _heightInPixels + d) y = _heightInPixels + d;
if (i == 0)
{
curveInfoVector.push_back(new SvgCurveInfo(0.0, 0.0, 0.0, 0.0, x, y));
}
else
{
double x1 = x, y1 = y, x2 = x, y2 = y;
if (in || lastIn)
{
x1 = (point->getBezierInfo()->getX1() - _xFocus) * _scale + 0.5 * _widthInPixels;
y1 = (point->getBezierInfo()->getY1() - _yFocus) * _scale + 0.5 * _heightInPixels;
x2 = (point->getBezierInfo()->getX2() - _xFocus) * _scale + 0.5 * _widthInPixels;
y2 = (point->getBezierInfo()->getY2() - _yFocus) * _scale + 0.5 * _heightInPixels;
}
if (curveInfoVector.back()->getX() != x || curveInfoVector.back()->getY() != y)
{
curveInfoVector.push_back(new SvgCurveInfo(x1, y1, x2, y2, x, y));
}
}
lastIn = in;
}
content << "<path style=\\\"fill:" << look->getHexColor()
<< ";fill-opacity:" << static_cast<double>(look->getAlpha()) / 255.0
<< ";fill-rule:evenodd;stroke:none\\\" d=\\\"";
n = curveInfoVector.size();
for (i = 0; i < n; ++i)
{
SvgCurveInfo *curveInfo = curveInfoVector[i];
if (i == 0)
{
content << "M " << curveInfo->getX() << "," << curveInfo->getY() << " ";
}
else
{
bool ok = true;
double x = curveInfo->getX();
double y = curveInfo->getY();
if (i != n - 1)
{
SvgCurveInfo *pCurveInfo = curveInfoVector[i - 1];
SvgCurveInfo *nCurveInfo = curveInfoVector[i + 1];
if ((y < -(d - 1.0) || y > _widthInPixels + (d - 1.0)) && pCurveInfo->getY() == y && nCurveInfo->getY() == y) ok = false;
if ((x < -(d - 1.0) || x > _heightInPixels + (d - 1.0)) && pCurveInfo->getX() == x && nCurveInfo->getX() == x) ok = false;
}
if (ok) content << "C " << curveInfo->getX1() << " " << curveInfo->getY1() << ","
<< curveInfo->getX2() << " " << curveInfo->getY2() << "," << x << " " << y << " ";
}
delete curveInfo;
}
content << "\\\"></path>" << "\\n";
}
else
{
const LineItem *lineItem = dynamic_cast<const LineItem *>(item);
if (lineItem != 0)
{
std::string strokeLineCap = "butt";
bool addCircle1 = false, addCircle2 = false;
if (lineItem->cap1Round())
{
if (lineItem->cap2Round()) strokeLineCap = "round";
else addCircle1 = true;
}
else
{
if (lineItem->cap2Round()) addCircle2 = true;
}
content << "<path style=\\\"fill:none;stroke:" << look->getHexColor()
<< ";stroke-opacity:" << static_cast<double>(look->getAlpha()) / 255.0
<< ";stroke-width:" << look->getSize() * _scale * _sizeFactor
<< ";stroke-linecap:" << strokeLineCap << ";stroke-linejoin:round\\\" d=\\\"";
bool lastIn = false;
std::stringstream lastMove;
int i, n = lineItem->getPointVector(resolutionIndex).size();
for (i = 0; i < n; ++i)
{
const Point *point = lineItem->getPointVector(resolutionIndex)[i];
double x = (point->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (point->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
bool in = (x > -10.0 && x < _widthInPixels + 10.0 && y > -10.0 && y < _heightInPixels + 10.0);
if (i == 0 || (!in && !lastIn))
{
lastMove.str("");
lastMove << "M " << x << "," << y << " ";
}
else
{
double x1 = (point->getBezierInfo()->getX1() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y1 = (point->getBezierInfo()->getY1() - _yFocus) * _scale + 0.5 * _heightInPixels;
double x2 = (point->getBezierInfo()->getX2() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y2 = (point->getBezierInfo()->getY2() - _yFocus) * _scale + 0.5 * _heightInPixels;
content << lastMove.str() << "C " << x1 << " " << y1 << "," << x2 << " " << y2 << "," << x << " " << y << " ";
lastMove.str("");
}
lastIn = in;
}
content << "\\\"></path>" << "\\n";
if (addCircle1)
{
const Point *point = lineItem->getPointVector(resolutionIndex)[0];
double x = (point->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (point->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
content << "<circle cx=\\\"" << x << "\\\" cy=\\\"" << y << "\\\" r=\\\"" << 0.5 * look->getSize() * _scale * _sizeFactor
<< "\\\" stroke=\\\"none\\\" fill=\\\"" << look->getHexColor()
<< "\\\" fill-opacity=\\\"" << static_cast<double>(look->getAlpha()) / 255.0 << "\\\"></circle>" << "\\n";
}
if (addCircle2)
{
const Point *point = lineItem->getPointVector(resolutionIndex)[n - 1];
double x = (point->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (point->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
content << "<circle cx=\\\"" << x << "\\\" cy=\\\"" << y << "\\\" r=\\\"" << 0.5 * look->getSize() * _scale * _sizeFactor
<< "\\\" stroke=\\\"none\\\" fill=\\\"" << look->getHexColor()
<< "\\\" fill-opacity=\\\"" << static_cast<double>(look->getAlpha()) / 255.0 << "\\\"></circle>" << "\\n";
}
}
else
{
const PointItem *pointItem = dynamic_cast<const PointItem *>(item);
if (pointItem != 0)
{
double x = (pointItem->getPoint()->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (pointItem->getPoint()->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
if (x > -10.0 && x < _widthInPixels + 10.0 && y > -10.0 && y < _heightInPixels + 10.0)
{
content << "<circle cx=\\\"" << x << "\\\" cy=\\\"" << y << "\\\" r=\\\"" << 0.5 * look->getSize() * _scale * _sizeFactor
<< "\\\" stroke=\\\"black\\\" stroke-width=\\\"" << _scale * _sizeFactor
<< "\\\" fill=\\\"" << look->getHexColor()
<< "\\\" fill-opacity=\\\"" << static_cast<double>(look->getAlpha()) / 255.0 << "\\\"></circle>" << "\\n";
}
}
}
}
}
else
{
SvgTextInfo *svgTextInfo = dynamic_cast<SvgTextInfo *>((*it).second);
if (svgTextInfo != 0)
{
int i, n = svgTextInfo->getLineVector().size();
for (i = 0; i < n; ++i)
{
const SvgLineInfo *lineInfo = svgTextInfo->getLineVector()[i];
double x = (lineInfo->getX() - _xFocus) * _scale + 0.5 * _widthInPixels;
double y = (lineInfo->getY() - _yFocus) * _scale + 0.5 * _heightInPixels;
content << "<text x=\\\"" << x << "\\\" y=\\\"" << y << "\\\" font-size=\\\"" << svgTextInfo->getTextInfo()->getFontSize()
<< "\\\" font-family=\\\"arial\\\" fill=\\\"" << svgTextInfo->getTextInfo()->getHexColor()
<< "\\\" fill-opacity=\\\"" << static_cast<double>(svgTextInfo->getTextInfo()->getAlpha()) / 255.0
<< "\\\">" << lineInfo->getText() << "</text>" << "\\n";
}
}
}
}
MapData::unlock();
content << "<rect x=\\\"0.5\\\" y=\\\"0.5\\\" width=\\\"" << _widthInPixels - 1.0 << "\\\" height=\\\"" << _heightInPixels - 1.0
<< "\\\" style=\\\"fill:none;stroke-width:1;stroke:black\\\"/>" << "\\n" << "</svg>";
_coutMutexPtr->lock();
std::cout << _socketId << " " << _requestId << " " << map_server::SVG
<< " {\"svg\":\"" << content.str() << "\"}" << std::endl;
_coutMutexPtr->unlock();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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_frame/test/net/fake_external_tab.h"
#include <exdisp.h>
#include "app/app_paths.h"
#include "app/resource_bundle.h"
#include "app/win_util.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/icu_util.h"
#include "base/path_service.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "chrome/browser/browser_prefs.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/process_singleton.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test/net/dialog_watchdog.h"
#include "chrome_frame/test/net/test_automation_resource_message_filter.h"
namespace {
// A special command line switch to allow developers to manually launch the
// browser and debug CF inside the browser.
const wchar_t kManualBrowserLaunch[] = L"manual-browser";
// Pops up a message box after the test environment has been set up
// and before tearing it down. Useful for when debugging tests and not
// the test environment that's been set up.
const wchar_t kPromptAfterSetup[] = L"prompt-after-setup";
const int kTestServerPort = 4666;
// The test HTML we use to initialize Chrome Frame.
// Note that there's a little trick in there to avoid an extra URL request
// that the browser will otherwise make for the site's favicon.
// If we don't do this the browser will create a new URL request after
// the CF page has been initialized and that URL request will confuse the
// global URL instance counter in the unit tests and subsequently trip
// some DCHECKs.
const char kChromeFrameHtml[] = "<html><head>"
"<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\" />"
"<link rel=\"shortcut icon\" href=\"file://c:\\favicon.ico\"/>"
"</head><body>Chrome Frame should now be loaded</body></html>";
bool ShouldLaunchBrowser() {
return !CommandLine::ForCurrentProcess()->HasSwitch(kManualBrowserLaunch);
}
bool PromptAfterSetup() {
return CommandLine::ForCurrentProcess()->HasSwitch(kPromptAfterSetup);
}
} // end namespace
FakeExternalTab::FakeExternalTab() {
PathService::Get(chrome::DIR_USER_DATA, &overridden_user_dir_);
user_data_dir_ = FilePath::FromWStringHack(GetProfilePath());
PathService::Override(chrome::DIR_USER_DATA, user_data_dir_);
process_singleton_.reset(new ProcessSingleton(user_data_dir_));
}
FakeExternalTab::~FakeExternalTab() {
if (!overridden_user_dir_.empty()) {
PathService::Override(chrome::DIR_USER_DATA, overridden_user_dir_);
}
}
std::wstring FakeExternalTab::GetProfileName() {
return L"iexplore";
}
std::wstring FakeExternalTab::GetProfilePath() {
std::wstring path;
GetUserProfileBaseDirectory(&path);
file_util::AppendToPath(&path, GetProfileName());
return path;
}
void FakeExternalTab::Initialize() {
DCHECK(g_browser_process == NULL);
// The gears plugin causes the PluginRequestInterceptor to kick in and it
// will cause problems when it tries to intercept URL requests.
PathService::Override(chrome::FILE_GEARS_PLUGIN, FilePath());
icu_util::Initialize();
chrome::RegisterPathProvider();
app::RegisterPathProvider();
ResourceBundle::InitSharedInstance(L"en-US");
ResourceBundle::GetSharedInstance().LoadThemeResources();
const CommandLine* cmd = CommandLine::ForCurrentProcess();
browser_process_.reset(new BrowserProcessImpl(*cmd));
RenderProcessHost::set_run_renderer_in_process(true);
// BrowserProcessImpl's constructor should set g_browser_process.
DCHECK(g_browser_process);
Profile* profile = g_browser_process->profile_manager()->
GetDefaultProfile(FilePath(user_data()));
PrefService* prefs = profile->GetPrefs();
PrefService* local_state = browser_process_->local_state();
local_state->RegisterStringPref(prefs::kApplicationLocale, L"");
local_state->RegisterBooleanPref(prefs::kMetricsReportingEnabled, false);
browser::RegisterAllPrefs(prefs, local_state);
// Override some settings to avoid hitting some preferences that have not
// been registered.
prefs->SetBoolean(prefs::kPasswordManagerEnabled, false);
prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);
prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);
profile->InitExtensions();
}
void FakeExternalTab::Shutdown() {
browser_process_.reset();
g_browser_process = NULL;
process_singleton_.reset();
ResourceBundle::CleanupSharedInstance();
}
CFUrlRequestUnittestRunner::CFUrlRequestUnittestRunner(int argc, char** argv)
: NetTestSuite(argc, argv),
chrome_frame_html_("/chrome_frame", kChromeFrameHtml) {
fake_chrome_.Initialize();
pss_subclass_.reset(new ProcessSingletonSubclass(this));
EXPECT_TRUE(pss_subclass_->Subclass(fake_chrome_.user_data()));
StartChromeFrameInHostBrowser();
}
CFUrlRequestUnittestRunner::~CFUrlRequestUnittestRunner() {
fake_chrome_.Shutdown();
}
DWORD WINAPI NavigateIE(void* param) {
return 0;
win_util::ScopedCOMInitializer com;
BSTR url = reinterpret_cast<BSTR>(param);
bool found = false;
int retries = 0;
const int kMaxRetries = 20;
while (!found && retries < kMaxRetries) {
ScopedComPtr<IShellWindows> windows;
HRESULT hr = ::CoCreateInstance(__uuidof(ShellWindows), NULL, CLSCTX_ALL,
IID_IShellWindows, reinterpret_cast<void**>(windows.Receive()));
DCHECK(SUCCEEDED(hr)) << "CoCreateInstance";
if (SUCCEEDED(hr)) {
hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
long count = 0; // NOLINT
windows->get_Count(&count);
VARIANT i = { VT_I4 };
for (i.lVal = 0; i.lVal < count; ++i.lVal) {
ScopedComPtr<IDispatch> folder;
windows->Item(i, folder.Receive());
if (folder != NULL) {
ScopedComPtr<IWebBrowser2> browser;
if (SUCCEEDED(browser.QueryFrom(folder))) {
found = true;
browser->Stop();
Sleep(1000);
VARIANT empty = ScopedVariant::kEmptyVariant;
hr = browser->Navigate(url, &empty, &empty, &empty, &empty);
DCHECK(SUCCEEDED(hr)) << "Failed to navigate";
break;
}
}
}
}
if (!found) {
DLOG(INFO) << "Waiting for browser to initialize...";
::Sleep(100);
retries++;
}
}
DCHECK(retries < kMaxRetries);
DCHECK(found);
::SysFreeString(url);
return 0;
}
void CFUrlRequestUnittestRunner::StartChromeFrameInHostBrowser() {
if (!ShouldLaunchBrowser())
return;
win_util::ScopedCOMInitializer com;
chrome_frame_test::CloseAllIEWindows();
test_http_server_.reset(new test_server::SimpleWebServer(kTestServerPort));
test_http_server_->AddResponse(&chrome_frame_html_);
std::wstring url(StringPrintf(L"http://localhost:%i/chrome_frame",
kTestServerPort).c_str());
// Launch IE. This launches IE correctly on Vista too.
ScopedHandle ie_process(chrome_frame_test::LaunchIE(url));
EXPECT_TRUE(ie_process.IsValid());
// NOTE: If you're running IE8 and CF is not being loaded, you need to
// disable IE8's prebinding until CF properly handles that situation.
//
// HKCU\Software\Microsoft\Internet Explorer\Main
// Value name: EnablePreBinding (REG_DWORD)
// Value: 0
}
void CFUrlRequestUnittestRunner::ShutDownHostBrowser() {
if (ShouldLaunchBrowser()) {
win_util::ScopedCOMInitializer com;
chrome_frame_test::CloseAllIEWindows();
}
}
// Override virtual void Initialize to not call icu initialize
void CFUrlRequestUnittestRunner::Initialize() {
DCHECK(::GetCurrentThreadId() == test_thread_id_);
// Start by replicating some of the steps that would otherwise be
// done by TestSuite::Initialize. We can't call the base class
// directly because it will attempt to initialize some things such as
// ICU that have already been initialized for this process.
InitializeLogging();
base::Time::EnableHiResClockForTests();
#if !defined(PURIFY) && defined(OS_WIN)
logging::SetLogAssertHandler(UnitTestAssertHandler);
#endif // !defined(PURIFY)
// Next, do some initialization for NetTestSuite.
NetTestSuite::InitializeTestThread();
}
void CFUrlRequestUnittestRunner::Shutdown() {
DCHECK(::GetCurrentThreadId() == test_thread_id_);
NetTestSuite::Shutdown();
}
void CFUrlRequestUnittestRunner::OnConnectAutomationProviderToChannel(
const std::string& channel_id) {
Profile* profile = g_browser_process->profile_manager()->
GetDefaultProfile(fake_chrome_.user_data());
AutomationProviderList* list =
g_browser_process->InitAutomationProviderList();
DCHECK(list);
list->AddProvider(TestAutomationProvider::NewAutomationProvider(profile,
channel_id, this));
}
void CFUrlRequestUnittestRunner::OnInitialTabLoaded() {
test_http_server_.reset();
StartTests();
}
void CFUrlRequestUnittestRunner::RunMainUIThread() {
DCHECK(MessageLoop::current());
DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI);
// Register the main thread by instantiating it, but don't call any methods.
ChromeThread main_thread;
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
MessageLoop::current()->Run();
}
void CFUrlRequestUnittestRunner::StartTests() {
if (PromptAfterSetup())
MessageBoxA(NULL, "click ok to run", "", MB_OK);
DCHECK_EQ(test_thread_.IsValid(), false);
test_thread_.Set(::CreateThread(NULL, 0, RunAllUnittests, this, 0,
&test_thread_id_));
DCHECK(test_thread_.IsValid());
}
// static
DWORD CFUrlRequestUnittestRunner::RunAllUnittests(void* param) {
PlatformThread::SetName("CFUrlRequestUnittestRunner");
CFUrlRequestUnittestRunner* me =
reinterpret_cast<CFUrlRequestUnittestRunner*>(param);
me->Run();
me->fake_chrome_.ui_loop()->PostTask(FROM_HERE,
NewRunnableFunction(TakeDownBrowser, me));
return 0;
}
// static
void CFUrlRequestUnittestRunner::TakeDownBrowser(
CFUrlRequestUnittestRunner* me) {
if (PromptAfterSetup())
MessageBoxA(NULL, "click ok to exit", "", MB_OK);
me->ShutDownHostBrowser();
}
void CFUrlRequestUnittestRunner::InitializeLogging() {
FilePath exe;
PathService::Get(base::FILE_EXE, &exe);
FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log"));
logging::InitLogging(log_filename.value().c_str(),
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
logging::LOCK_LOG_FILE,
logging::DELETE_OLD_LOG_FILE);
// We want process and thread IDs because we may have multiple processes.
// Note: temporarily enabled timestamps in an effort to catch bug 6361.
logging::SetLogItems(true, true, true, true);
}
void FilterDisabledTests() {
if (::testing::FLAGS_gtest_filter.GetLength() &&
::testing::FLAGS_gtest_filter.Compare("*") != 0) {
// Don't override user specified filters.
return;
}
const char* disabled_tests[] = {
// Tests disabled since they're testing the same functionality used
// by the TestAutomationProvider.
"URLRequestTest.InterceptNetworkError",
"URLRequestTest.InterceptRestartRequired",
"URLRequestTest.InterceptRespectsCancelMain",
"URLRequestTest.InterceptRespectsCancelRedirect",
"URLRequestTest.InterceptRespectsCancelFinal",
"URLRequestTest.InterceptRespectsCancelInRestart",
"URLRequestTest.InterceptRedirect",
"URLRequestTest.InterceptServerError",
"URLRequestTestFTP.*",
// Tests that are currently not working:
// Temporarily disabled because they needs user input (login dialog).
"URLRequestTestHTTP.BasicAuth",
"URLRequestTestHTTP.BasicAuthWithCookies",
// HTTPS tests temporarily disabled due to the certificate error dialog.
// TODO(tommi): The tests currently fail though, so need to fix.
"HTTPSRequestTest.HTTPSMismatchedTest",
"HTTPSRequestTest.HTTPSExpiredTest",
// Tests chrome's network stack's cache (might not apply to CF).
"URLRequestTestHTTP.VaryHeader",
// I suspect we can only get this one to work (if at all) on IE8 and
// later by using the new INTERNET_OPTION_SUPPRESS_BEHAVIOR flags
// See http://msdn.microsoft.com/en-us/library/aa385328(VS.85).aspx
"URLRequestTest.DoNotSaveCookies",
};
std::string filter("-"); // All following filters will be negative.
for (int i = 0; i < arraysize(disabled_tests); ++i) {
if (i > 0)
filter += ":";
filter += disabled_tests[i];
}
::testing::FLAGS_gtest_filter = filter;
}
int main(int argc, char** argv) {
DialogWatchdog watchdog;
// See url_request_unittest.cc for these credentials.
SupplyProxyCredentials credentials("user", "secret");
watchdog.AddObserver(&credentials);
testing::InitGoogleTest(&argc, argv);
FilterDisabledTests();
CFUrlRequestUnittestRunner test_suite(argc, argv);
test_suite.RunMainUIThread();
return 0;
}
<commit_msg>Fixes a compile error due to an call to an incorrect function to get the length.<commit_after>// Copyright (c) 2009 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_frame/test/net/fake_external_tab.h"
#include <exdisp.h>
#include "app/app_paths.h"
#include "app/resource_bundle.h"
#include "app/win_util.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/icu_util.h"
#include "base/path_service.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "chrome/browser/browser_prefs.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/process_singleton.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test/net/dialog_watchdog.h"
#include "chrome_frame/test/net/test_automation_resource_message_filter.h"
namespace {
// A special command line switch to allow developers to manually launch the
// browser and debug CF inside the browser.
const wchar_t kManualBrowserLaunch[] = L"manual-browser";
// Pops up a message box after the test environment has been set up
// and before tearing it down. Useful for when debugging tests and not
// the test environment that's been set up.
const wchar_t kPromptAfterSetup[] = L"prompt-after-setup";
const int kTestServerPort = 4666;
// The test HTML we use to initialize Chrome Frame.
// Note that there's a little trick in there to avoid an extra URL request
// that the browser will otherwise make for the site's favicon.
// If we don't do this the browser will create a new URL request after
// the CF page has been initialized and that URL request will confuse the
// global URL instance counter in the unit tests and subsequently trip
// some DCHECKs.
const char kChromeFrameHtml[] = "<html><head>"
"<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\" />"
"<link rel=\"shortcut icon\" href=\"file://c:\\favicon.ico\"/>"
"</head><body>Chrome Frame should now be loaded</body></html>";
bool ShouldLaunchBrowser() {
return !CommandLine::ForCurrentProcess()->HasSwitch(kManualBrowserLaunch);
}
bool PromptAfterSetup() {
return CommandLine::ForCurrentProcess()->HasSwitch(kPromptAfterSetup);
}
} // end namespace
FakeExternalTab::FakeExternalTab() {
PathService::Get(chrome::DIR_USER_DATA, &overridden_user_dir_);
user_data_dir_ = FilePath::FromWStringHack(GetProfilePath());
PathService::Override(chrome::DIR_USER_DATA, user_data_dir_);
process_singleton_.reset(new ProcessSingleton(user_data_dir_));
}
FakeExternalTab::~FakeExternalTab() {
if (!overridden_user_dir_.empty()) {
PathService::Override(chrome::DIR_USER_DATA, overridden_user_dir_);
}
}
std::wstring FakeExternalTab::GetProfileName() {
return L"iexplore";
}
std::wstring FakeExternalTab::GetProfilePath() {
std::wstring path;
GetUserProfileBaseDirectory(&path);
file_util::AppendToPath(&path, GetProfileName());
return path;
}
void FakeExternalTab::Initialize() {
DCHECK(g_browser_process == NULL);
// The gears plugin causes the PluginRequestInterceptor to kick in and it
// will cause problems when it tries to intercept URL requests.
PathService::Override(chrome::FILE_GEARS_PLUGIN, FilePath());
icu_util::Initialize();
chrome::RegisterPathProvider();
app::RegisterPathProvider();
ResourceBundle::InitSharedInstance(L"en-US");
ResourceBundle::GetSharedInstance().LoadThemeResources();
const CommandLine* cmd = CommandLine::ForCurrentProcess();
browser_process_.reset(new BrowserProcessImpl(*cmd));
RenderProcessHost::set_run_renderer_in_process(true);
// BrowserProcessImpl's constructor should set g_browser_process.
DCHECK(g_browser_process);
Profile* profile = g_browser_process->profile_manager()->
GetDefaultProfile(FilePath(user_data()));
PrefService* prefs = profile->GetPrefs();
PrefService* local_state = browser_process_->local_state();
local_state->RegisterStringPref(prefs::kApplicationLocale, L"");
local_state->RegisterBooleanPref(prefs::kMetricsReportingEnabled, false);
browser::RegisterAllPrefs(prefs, local_state);
// Override some settings to avoid hitting some preferences that have not
// been registered.
prefs->SetBoolean(prefs::kPasswordManagerEnabled, false);
prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);
prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);
profile->InitExtensions();
}
void FakeExternalTab::Shutdown() {
browser_process_.reset();
g_browser_process = NULL;
process_singleton_.reset();
ResourceBundle::CleanupSharedInstance();
}
CFUrlRequestUnittestRunner::CFUrlRequestUnittestRunner(int argc, char** argv)
: NetTestSuite(argc, argv),
chrome_frame_html_("/chrome_frame", kChromeFrameHtml) {
fake_chrome_.Initialize();
pss_subclass_.reset(new ProcessSingletonSubclass(this));
EXPECT_TRUE(pss_subclass_->Subclass(fake_chrome_.user_data()));
StartChromeFrameInHostBrowser();
}
CFUrlRequestUnittestRunner::~CFUrlRequestUnittestRunner() {
fake_chrome_.Shutdown();
}
DWORD WINAPI NavigateIE(void* param) {
return 0;
win_util::ScopedCOMInitializer com;
BSTR url = reinterpret_cast<BSTR>(param);
bool found = false;
int retries = 0;
const int kMaxRetries = 20;
while (!found && retries < kMaxRetries) {
ScopedComPtr<IShellWindows> windows;
HRESULT hr = ::CoCreateInstance(__uuidof(ShellWindows), NULL, CLSCTX_ALL,
IID_IShellWindows, reinterpret_cast<void**>(windows.Receive()));
DCHECK(SUCCEEDED(hr)) << "CoCreateInstance";
if (SUCCEEDED(hr)) {
hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
long count = 0; // NOLINT
windows->get_Count(&count);
VARIANT i = { VT_I4 };
for (i.lVal = 0; i.lVal < count; ++i.lVal) {
ScopedComPtr<IDispatch> folder;
windows->Item(i, folder.Receive());
if (folder != NULL) {
ScopedComPtr<IWebBrowser2> browser;
if (SUCCEEDED(browser.QueryFrom(folder))) {
found = true;
browser->Stop();
Sleep(1000);
VARIANT empty = ScopedVariant::kEmptyVariant;
hr = browser->Navigate(url, &empty, &empty, &empty, &empty);
DCHECK(SUCCEEDED(hr)) << "Failed to navigate";
break;
}
}
}
}
if (!found) {
DLOG(INFO) << "Waiting for browser to initialize...";
::Sleep(100);
retries++;
}
}
DCHECK(retries < kMaxRetries);
DCHECK(found);
::SysFreeString(url);
return 0;
}
void CFUrlRequestUnittestRunner::StartChromeFrameInHostBrowser() {
if (!ShouldLaunchBrowser())
return;
win_util::ScopedCOMInitializer com;
chrome_frame_test::CloseAllIEWindows();
test_http_server_.reset(new test_server::SimpleWebServer(kTestServerPort));
test_http_server_->AddResponse(&chrome_frame_html_);
std::wstring url(StringPrintf(L"http://localhost:%i/chrome_frame",
kTestServerPort).c_str());
// Launch IE. This launches IE correctly on Vista too.
ScopedHandle ie_process(chrome_frame_test::LaunchIE(url));
EXPECT_TRUE(ie_process.IsValid());
// NOTE: If you're running IE8 and CF is not being loaded, you need to
// disable IE8's prebinding until CF properly handles that situation.
//
// HKCU\Software\Microsoft\Internet Explorer\Main
// Value name: EnablePreBinding (REG_DWORD)
// Value: 0
}
void CFUrlRequestUnittestRunner::ShutDownHostBrowser() {
if (ShouldLaunchBrowser()) {
win_util::ScopedCOMInitializer com;
chrome_frame_test::CloseAllIEWindows();
}
}
// Override virtual void Initialize to not call icu initialize
void CFUrlRequestUnittestRunner::Initialize() {
DCHECK(::GetCurrentThreadId() == test_thread_id_);
// Start by replicating some of the steps that would otherwise be
// done by TestSuite::Initialize. We can't call the base class
// directly because it will attempt to initialize some things such as
// ICU that have already been initialized for this process.
InitializeLogging();
base::Time::EnableHiResClockForTests();
#if !defined(PURIFY) && defined(OS_WIN)
logging::SetLogAssertHandler(UnitTestAssertHandler);
#endif // !defined(PURIFY)
// Next, do some initialization for NetTestSuite.
NetTestSuite::InitializeTestThread();
}
void CFUrlRequestUnittestRunner::Shutdown() {
DCHECK(::GetCurrentThreadId() == test_thread_id_);
NetTestSuite::Shutdown();
}
void CFUrlRequestUnittestRunner::OnConnectAutomationProviderToChannel(
const std::string& channel_id) {
Profile* profile = g_browser_process->profile_manager()->
GetDefaultProfile(fake_chrome_.user_data());
AutomationProviderList* list =
g_browser_process->InitAutomationProviderList();
DCHECK(list);
list->AddProvider(TestAutomationProvider::NewAutomationProvider(profile,
channel_id, this));
}
void CFUrlRequestUnittestRunner::OnInitialTabLoaded() {
test_http_server_.reset();
StartTests();
}
void CFUrlRequestUnittestRunner::RunMainUIThread() {
DCHECK(MessageLoop::current());
DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI);
// Register the main thread by instantiating it, but don't call any methods.
ChromeThread main_thread;
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
MessageLoop::current()->Run();
}
void CFUrlRequestUnittestRunner::StartTests() {
if (PromptAfterSetup())
MessageBoxA(NULL, "click ok to run", "", MB_OK);
DCHECK_EQ(test_thread_.IsValid(), false);
test_thread_.Set(::CreateThread(NULL, 0, RunAllUnittests, this, 0,
&test_thread_id_));
DCHECK(test_thread_.IsValid());
}
// static
DWORD CFUrlRequestUnittestRunner::RunAllUnittests(void* param) {
PlatformThread::SetName("CFUrlRequestUnittestRunner");
CFUrlRequestUnittestRunner* me =
reinterpret_cast<CFUrlRequestUnittestRunner*>(param);
me->Run();
me->fake_chrome_.ui_loop()->PostTask(FROM_HERE,
NewRunnableFunction(TakeDownBrowser, me));
return 0;
}
// static
void CFUrlRequestUnittestRunner::TakeDownBrowser(
CFUrlRequestUnittestRunner* me) {
if (PromptAfterSetup())
MessageBoxA(NULL, "click ok to exit", "", MB_OK);
me->ShutDownHostBrowser();
}
void CFUrlRequestUnittestRunner::InitializeLogging() {
FilePath exe;
PathService::Get(base::FILE_EXE, &exe);
FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log"));
logging::InitLogging(log_filename.value().c_str(),
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
logging::LOCK_LOG_FILE,
logging::DELETE_OLD_LOG_FILE);
// We want process and thread IDs because we may have multiple processes.
// Note: temporarily enabled timestamps in an effort to catch bug 6361.
logging::SetLogItems(true, true, true, true);
}
void FilterDisabledTests() {
if (::testing::FLAGS_gtest_filter.length() &&
::testing::FLAGS_gtest_filter.Compare("*") != 0) {
// Don't override user specified filters.
return;
}
const char* disabled_tests[] = {
// Tests disabled since they're testing the same functionality used
// by the TestAutomationProvider.
"URLRequestTest.InterceptNetworkError",
"URLRequestTest.InterceptRestartRequired",
"URLRequestTest.InterceptRespectsCancelMain",
"URLRequestTest.InterceptRespectsCancelRedirect",
"URLRequestTest.InterceptRespectsCancelFinal",
"URLRequestTest.InterceptRespectsCancelInRestart",
"URLRequestTest.InterceptRedirect",
"URLRequestTest.InterceptServerError",
"URLRequestTestFTP.*",
// Tests that are currently not working:
// Temporarily disabled because they needs user input (login dialog).
"URLRequestTestHTTP.BasicAuth",
"URLRequestTestHTTP.BasicAuthWithCookies",
// HTTPS tests temporarily disabled due to the certificate error dialog.
// TODO(tommi): The tests currently fail though, so need to fix.
"HTTPSRequestTest.HTTPSMismatchedTest",
"HTTPSRequestTest.HTTPSExpiredTest",
// Tests chrome's network stack's cache (might not apply to CF).
"URLRequestTestHTTP.VaryHeader",
// I suspect we can only get this one to work (if at all) on IE8 and
// later by using the new INTERNET_OPTION_SUPPRESS_BEHAVIOR flags
// See http://msdn.microsoft.com/en-us/library/aa385328(VS.85).aspx
"URLRequestTest.DoNotSaveCookies",
};
std::string filter("-"); // All following filters will be negative.
for (int i = 0; i < arraysize(disabled_tests); ++i) {
if (i > 0)
filter += ":";
filter += disabled_tests[i];
}
::testing::FLAGS_gtest_filter = filter;
}
int main(int argc, char** argv) {
DialogWatchdog watchdog;
// See url_request_unittest.cc for these credentials.
SupplyProxyCredentials credentials("user", "secret");
watchdog.AddObserver(&credentials);
testing::InitGoogleTest(&argc, argv);
FilterDisabledTests();
CFUrlRequestUnittestRunner test_suite(argc, argv);
test_suite.RunMainUIThread();
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2011 Lasath Fernando <kde@lasath.org>
Copyright (C) 2016 Martin Klapetek <mklapetek@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "conversation.h"
#include "messages-model.h"
#include <TelepathyQt/TextChannel>
#include <TelepathyQt/Account>
#include <TelepathyQt/PendingChannelRequest>
#include <TelepathyQt/PendingChannel>
#include "debug.h"
#include "channel-delegator.h"
class Conversation::ConversationPrivate
{
public:
ConversationPrivate()
{
messages = nullptr;
delegated = false;
valid = false;
isGroupChat = false;
}
MessagesModel *messages;
//stores if the conversation has been delegated to another client and we are only observing the channel
//and not handling it.
bool delegated;
bool valid;
Tp::AccountPtr account;
QTimer *pausedStateTimer;
KPeople::PersonData *personData;
// May be null for group chats.
KTp::ContactPtr targetContact;
bool isGroupChat;
};
Conversation::Conversation(const Tp::TextChannelPtr &channel,
const Tp::AccountPtr &account,
QObject *parent) :
QObject(parent),
d (new ConversationPrivate)
{
qCDebug(KTP_DECLARATIVE);
d->valid = false;
d->isGroupChat = false;
d->account = account;
connect(d->account.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), SLOT(onAccountConnectionChanged(Tp::ConnectionPtr)));
d->messages = new MessagesModel(account, this);
connect(d->messages, &MessagesModel::unreadCountChanged, this, &Conversation::unreadMessagesChanged);
connect(d->messages, &MessagesModel::lastMessageChanged, this, &Conversation::lastMessageChanged);
setTextChannel(channel);
d->delegated = false;
d->pausedStateTimer = new QTimer(this);
d->pausedStateTimer->setSingleShot(true);
connect(d->pausedStateTimer, SIGNAL(timeout()), this, SLOT(onChatPausedTimerExpired()));
}
Conversation::Conversation(const QString &contactId,
const Tp::AccountPtr &account,
QObject *parent)
: QObject(parent),
d(new ConversationPrivate)
{
d->valid = true;
d->isGroupChat = false;
d->account = account;
d->personData = new KPeople::PersonData(QStringLiteral("ktp://") + d->account->objectPath().mid(35) + QStringLiteral("?") + contactId);
d->messages = new MessagesModel(account, this);
connect(d->messages, &MessagesModel::unreadCountChanged, this, &Conversation::unreadMessagesChanged);
connect(d->messages, &MessagesModel::lastMessageChanged, this, &Conversation::lastMessageChanged);
d->messages->setContactData(contactId, d->personData->name());
Q_EMIT avatarChanged();
Q_EMIT titleChanged();
Q_EMIT presenceIconChanged();
Q_EMIT validityChanged(d->valid);
}
void Conversation::setTextChannel(const Tp::TextChannelPtr &channel)
{
if (d->messages->account().isNull()) {
d->messages->setAccount(d->account);
}
if (d->messages->textChannel() != channel) {
d->messages->setTextChannel(channel);
d->valid = channel->isValid();
connect(channel.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));
connect(channel.data(), &Tp::TextChannel::chatStateChanged, this, &Conversation::contactTypingChanged);
if (channel->targetContact().isNull()) {
d->isGroupChat = true;
} else {
d->isGroupChat = false;
d->targetContact = KTp::ContactPtr::qObjectCast(channel->targetContact());
d->personData = new KPeople::PersonData(QStringLiteral("ktp://") + d->account->objectPath().mid(35) + QStringLiteral("?") + d->targetContact->id());
connect(d->targetContact.constData(), SIGNAL(aliasChanged(QString)), SIGNAL(titleChanged()));
connect(d->targetContact.constData(), SIGNAL(presenceChanged(Tp::Presence)), SIGNAL(presenceIconChanged()));
connect(d->targetContact.constData(), SIGNAL(avatarDataChanged(Tp::AvatarData)), SIGNAL(avatarChanged()));
}
Q_EMIT avatarChanged();
Q_EMIT titleChanged();
Q_EMIT presenceIconChanged();
Q_EMIT validityChanged(d->valid);
}
}
Tp::TextChannelPtr Conversation::textChannel() const
{
return d->messages->textChannel();
}
MessagesModel* Conversation::messages() const
{
return d->messages;
}
QString Conversation::title() const
{
if (d->isGroupChat) {
QString roomName = textChannel()->targetId();
return roomName.left(roomName.indexOf(QLatin1Char('@')));
} else {
return d->personData->name();
}
}
QIcon Conversation::presenceIcon() const
{
if (d->isGroupChat) {
return KTp::Presence(Tp::Presence::available()).icon();
} else if (!d->targetContact.isNull()) {
return KTp::Presence(d->targetContact->presence()).icon();
}
return QIcon();
}
QIcon Conversation::avatar() const
{
if (d->isGroupChat) {
return QIcon();
} else {
const QString path = d->targetContact->avatarData().fileName;
QIcon icon;
if (!path.isEmpty()) {
icon = QIcon(path);
}
if (icon.availableSizes().isEmpty()) {
icon = QIcon::fromTheme(QStringLiteral("im-user"));
}
return icon;
}
}
KTp::ContactPtr Conversation::targetContact() const
{
if (d->isGroupChat) {
return KTp::ContactPtr();
} else {
return d->targetContact;
}
}
Tp::AccountPtr Conversation::account() const
{
return d->account;
}
Tp::Account* Conversation::accountObject() const
{
if (!d->account.isNull()) {
return d->account.data();
}
return nullptr;
}
bool Conversation::isValid() const
{
return d->valid;
}
void Conversation::onChannelInvalidated(Tp::DBusProxy *proxy, const QString &errorName, const QString &errorMessage)
{
qCDebug(KTP_DECLARATIVE) << proxy << errorName << ":" << errorMessage;
d->valid = false;
Q_EMIT validityChanged(d->valid);
}
void Conversation::onAccountConnectionChanged(const Tp::ConnectionPtr& connection)
{
//if we have reconnected and we were handling the channel
if (connection && ! d->delegated) {
//general convention is to never use ensureAndHandle when we already have a client registrar
//ensureAndHandle will implicity create a new temporary client registrar which is a waste
//it's also more code to get the new channel
//However, we cannot use use ensureChannel as normal because without being able to pass a preferredHandler
//we need a preferredHandler so that this handler is the one that ends up with the channel if multi handlers are active
//we do not know the name that this handler is currently registered with
Tp::PendingChannel *pendingChannel = d->account->ensureAndHandleTextChat(textChannel()->targetId());
connect(pendingChannel, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onCreateChannelFinished(Tp::PendingOperation*)));
}
}
void Conversation::onCreateChannelFinished(Tp::PendingOperation* op)
{
Tp::PendingChannel *pendingChannelOp = qobject_cast<Tp::PendingChannel*>(op);
Tp::TextChannelPtr textChannel = Tp::TextChannelPtr::dynamicCast(pendingChannelOp->channel());
if (textChannel) {
setTextChannel(textChannel);
}
}
void Conversation::delegateToProperClient()
{
ChannelDelegator::delegateChannel(d->account, d->messages->textChannel());
d->delegated = true;
Q_EMIT conversationCloseRequested();
}
void Conversation::requestClose()
{
qCDebug(KTP_DECLARATIVE);
if (!d->messages->textChannel().isNull()) {
d->messages->textChannel()->requestClose();
}
}
void Conversation::updateTextChanged(const QString &message)
{
if (!message.isEmpty()) {
//if the timer is active, it means the user is continuously typing
if (d->pausedStateTimer->isActive()) {
//just restart the timer and don't spam with chat state changes
d->pausedStateTimer->start(5000);
} else {
//if the user has just typed some text, set state to Composing and start the timer
d->messages->textChannel()->requestChatState(Tp::ChannelChatStateComposing);
d->pausedStateTimer->start(5000);
}
} else {
//if the user typed no text/cleared the input field, set Active and stop the timer
d->messages->textChannel()->requestChatState(Tp::ChannelChatStateActive);
d->pausedStateTimer->stop();
}
}
void Conversation::onChatPausedTimerExpired()
{
d->messages->textChannel()->requestChatState(Tp::ChannelChatStatePaused);
}
Conversation::~Conversation()
{
qCDebug(KTP_DECLARATIVE);
//if we are not handling the channel do nothing.
if (!d->delegated) {
d->messages->textChannel()->requestClose();
}
delete d;
}
bool Conversation::hasUnreadMessages() const
{
if (d->messages) {
return d->messages->unreadCount() > 0;
}
return false;
}
KPeople::PersonData* Conversation::personData() const
{
return d->personData;
}
bool Conversation::isContactTyping() const
{
if (d->messages->textChannel()) {
return d->messages->textChannel()->chatState(d->targetContact) == Tp::ChannelChatStateComposing;
}
return false;
}
bool Conversation::canSendMessages() const
{
if (d->messages && d->messages->textChannel()) {
return true;
}
return false;
}
<commit_msg>Conversation: Fix a crash in destructor<commit_after>/*
Copyright (C) 2011 Lasath Fernando <kde@lasath.org>
Copyright (C) 2016 Martin Klapetek <mklapetek@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "conversation.h"
#include "messages-model.h"
#include <TelepathyQt/TextChannel>
#include <TelepathyQt/Account>
#include <TelepathyQt/PendingChannelRequest>
#include <TelepathyQt/PendingChannel>
#include "debug.h"
#include "channel-delegator.h"
class Conversation::ConversationPrivate
{
public:
ConversationPrivate()
{
messages = nullptr;
delegated = false;
valid = false;
isGroupChat = false;
}
MessagesModel *messages;
//stores if the conversation has been delegated to another client and we are only observing the channel
//and not handling it.
bool delegated;
bool valid;
Tp::AccountPtr account;
QTimer *pausedStateTimer;
KPeople::PersonData *personData;
// May be null for group chats.
KTp::ContactPtr targetContact;
bool isGroupChat;
};
Conversation::Conversation(const Tp::TextChannelPtr &channel,
const Tp::AccountPtr &account,
QObject *parent) :
QObject(parent),
d (new ConversationPrivate)
{
qCDebug(KTP_DECLARATIVE);
d->valid = false;
d->isGroupChat = false;
d->account = account;
connect(d->account.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), SLOT(onAccountConnectionChanged(Tp::ConnectionPtr)));
d->messages = new MessagesModel(account, this);
connect(d->messages, &MessagesModel::unreadCountChanged, this, &Conversation::unreadMessagesChanged);
connect(d->messages, &MessagesModel::lastMessageChanged, this, &Conversation::lastMessageChanged);
setTextChannel(channel);
d->delegated = false;
d->pausedStateTimer = new QTimer(this);
d->pausedStateTimer->setSingleShot(true);
connect(d->pausedStateTimer, SIGNAL(timeout()), this, SLOT(onChatPausedTimerExpired()));
}
Conversation::Conversation(const QString &contactId,
const Tp::AccountPtr &account,
QObject *parent)
: QObject(parent),
d(new ConversationPrivate)
{
d->valid = true;
d->isGroupChat = false;
d->account = account;
d->personData = new KPeople::PersonData(QStringLiteral("ktp://") + d->account->objectPath().mid(35) + QStringLiteral("?") + contactId);
d->messages = new MessagesModel(account, this);
connect(d->messages, &MessagesModel::unreadCountChanged, this, &Conversation::unreadMessagesChanged);
connect(d->messages, &MessagesModel::lastMessageChanged, this, &Conversation::lastMessageChanged);
d->messages->setContactData(contactId, d->personData->name());
Q_EMIT avatarChanged();
Q_EMIT titleChanged();
Q_EMIT presenceIconChanged();
Q_EMIT validityChanged(d->valid);
}
void Conversation::setTextChannel(const Tp::TextChannelPtr &channel)
{
if (d->messages->account().isNull()) {
d->messages->setAccount(d->account);
}
if (d->messages->textChannel() != channel) {
d->messages->setTextChannel(channel);
d->valid = channel->isValid();
connect(channel.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));
connect(channel.data(), &Tp::TextChannel::chatStateChanged, this, &Conversation::contactTypingChanged);
if (channel->targetContact().isNull()) {
d->isGroupChat = true;
} else {
d->isGroupChat = false;
d->targetContact = KTp::ContactPtr::qObjectCast(channel->targetContact());
d->personData = new KPeople::PersonData(QStringLiteral("ktp://") + d->account->objectPath().mid(35) + QStringLiteral("?") + d->targetContact->id());
connect(d->targetContact.constData(), SIGNAL(aliasChanged(QString)), SIGNAL(titleChanged()));
connect(d->targetContact.constData(), SIGNAL(presenceChanged(Tp::Presence)), SIGNAL(presenceIconChanged()));
connect(d->targetContact.constData(), SIGNAL(avatarDataChanged(Tp::AvatarData)), SIGNAL(avatarChanged()));
}
Q_EMIT avatarChanged();
Q_EMIT titleChanged();
Q_EMIT presenceIconChanged();
Q_EMIT validityChanged(d->valid);
}
}
Tp::TextChannelPtr Conversation::textChannel() const
{
return d->messages->textChannel();
}
MessagesModel* Conversation::messages() const
{
return d->messages;
}
QString Conversation::title() const
{
if (d->isGroupChat) {
QString roomName = textChannel()->targetId();
return roomName.left(roomName.indexOf(QLatin1Char('@')));
} else {
return d->personData->name();
}
}
QIcon Conversation::presenceIcon() const
{
if (d->isGroupChat) {
return KTp::Presence(Tp::Presence::available()).icon();
} else if (!d->targetContact.isNull()) {
return KTp::Presence(d->targetContact->presence()).icon();
}
return QIcon();
}
QIcon Conversation::avatar() const
{
if (d->isGroupChat) {
return QIcon();
} else {
const QString path = d->targetContact->avatarData().fileName;
QIcon icon;
if (!path.isEmpty()) {
icon = QIcon(path);
}
if (icon.availableSizes().isEmpty()) {
icon = QIcon::fromTheme(QStringLiteral("im-user"));
}
return icon;
}
}
KTp::ContactPtr Conversation::targetContact() const
{
if (d->isGroupChat) {
return KTp::ContactPtr();
} else {
return d->targetContact;
}
}
Tp::AccountPtr Conversation::account() const
{
return d->account;
}
Tp::Account* Conversation::accountObject() const
{
if (!d->account.isNull()) {
return d->account.data();
}
return nullptr;
}
bool Conversation::isValid() const
{
return d->valid;
}
void Conversation::onChannelInvalidated(Tp::DBusProxy *proxy, const QString &errorName, const QString &errorMessage)
{
qCDebug(KTP_DECLARATIVE) << proxy << errorName << ":" << errorMessage;
d->valid = false;
Q_EMIT validityChanged(d->valid);
}
void Conversation::onAccountConnectionChanged(const Tp::ConnectionPtr& connection)
{
//if we have reconnected and we were handling the channel
if (connection && ! d->delegated) {
//general convention is to never use ensureAndHandle when we already have a client registrar
//ensureAndHandle will implicity create a new temporary client registrar which is a waste
//it's also more code to get the new channel
//However, we cannot use use ensureChannel as normal because without being able to pass a preferredHandler
//we need a preferredHandler so that this handler is the one that ends up with the channel if multi handlers are active
//we do not know the name that this handler is currently registered with
Tp::PendingChannel *pendingChannel = d->account->ensureAndHandleTextChat(textChannel()->targetId());
connect(pendingChannel, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onCreateChannelFinished(Tp::PendingOperation*)));
}
}
void Conversation::onCreateChannelFinished(Tp::PendingOperation* op)
{
Tp::PendingChannel *pendingChannelOp = qobject_cast<Tp::PendingChannel*>(op);
Tp::TextChannelPtr textChannel = Tp::TextChannelPtr::dynamicCast(pendingChannelOp->channel());
if (textChannel) {
setTextChannel(textChannel);
}
}
void Conversation::delegateToProperClient()
{
ChannelDelegator::delegateChannel(d->account, d->messages->textChannel());
d->delegated = true;
Q_EMIT conversationCloseRequested();
}
void Conversation::requestClose()
{
qCDebug(KTP_DECLARATIVE);
if (!d->messages->textChannel().isNull()) {
d->messages->textChannel()->requestClose();
}
}
void Conversation::updateTextChanged(const QString &message)
{
if (!message.isEmpty()) {
//if the timer is active, it means the user is continuously typing
if (d->pausedStateTimer->isActive()) {
//just restart the timer and don't spam with chat state changes
d->pausedStateTimer->start(5000);
} else {
//if the user has just typed some text, set state to Composing and start the timer
d->messages->textChannel()->requestChatState(Tp::ChannelChatStateComposing);
d->pausedStateTimer->start(5000);
}
} else {
//if the user typed no text/cleared the input field, set Active and stop the timer
d->messages->textChannel()->requestChatState(Tp::ChannelChatStateActive);
d->pausedStateTimer->stop();
}
}
void Conversation::onChatPausedTimerExpired()
{
d->messages->textChannel()->requestChatState(Tp::ChannelChatStatePaused);
}
Conversation::~Conversation()
{
qCDebug(KTP_DECLARATIVE);
//if we are not handling the channel do nothing.
// d->messages is valid here (destroyed in a deeper base class destructor)
// but the textChannel actually can be invalid.
if (!d->delegated && !d->messages->textChannel().isNull()) {
d->messages->textChannel()->requestClose();
}
delete d;
}
bool Conversation::hasUnreadMessages() const
{
if (d->messages) {
return d->messages->unreadCount() > 0;
}
return false;
}
KPeople::PersonData* Conversation::personData() const
{
return d->personData;
}
bool Conversation::isContactTyping() const
{
if (d->messages->textChannel()) {
return d->messages->textChannel()->chatState(d->targetContact) == Tp::ChannelChatStateComposing;
}
return false;
}
bool Conversation::canSendMessages() const
{
if (d->messages && d->messages->textChannel()) {
return true;
}
return false;
}
<|endoftext|> |
<commit_before>//
// inpalprime.cpp
// InPal
//
// Created by Bryan Triana on 6/21/16.
// Copyright © 2016 Inverse Palindrome. All rights reserved.
//
#include "inpalprime.hpp"
#include <cmath>
#include <vector>
#include <string>
unsigned long long inpalprime::pn_find(unsigned long long n)
{
//finds the highest possible prime under n
for(std::vector<bool>::size_type it=atkinsieve(n).size()-1; it!=1; it--)
{
if(atkinsieve(n)[it])
{
maxprime=it;
break;
}
}
return maxprime;
}
unsigned long long inpalprime::pn_count(unsigned long long n)
{
//count the number of primes under n
for(std::vector<bool>::size_type it=atkinsieve(n).size()-1; it!=1; it--)
{
if(atkinsieve(n)[it])
{
primecount++;
}
}
return primecount;
}
long double inpalprime::pn_den(long double h)
{
//density of primes from 1 to h
primeden=(pn_count(h)/h);
return primeden;
}
bool inpalprime::pn_test(unsigned long long a)
{
//primality test based on the sieve of atkin
if(a!=pn_find(a))
{
return false;
}
return true;
}
bool inpalprime::pn_twin(unsigned long long a)
{
if(a==2)
{
return false;
}
else if(pn_test(a) && (pn_test(a+2) || pn_test(a-2)))
{
return true;
}
return false;
}
bool inpalprime::pn_cousin(unsigned long long a)
{
if(a==2)
{
return false;
}
else if(pn_test(a) && (pn_test(a+4) || pn_test(a-4)))
{
return true;
}
return false;
}
bool inpalprime::pn_sexy(unsigned long long a)
{
if(a==2 || a==3)
{
return false;
}
else if(pn_test(a) && (pn_test(a+6) || pn_test(a-6)))
{
return true;
}
return false;
}
unsigned long long inpalprime::pn_pal(unsigned long long n)
{
//finds the highest palindromic prime equal or less than n
for(std::vector<bool>::size_type it=atkinsieve(n).size()-1; it!=1; it--)
{
if(atkinsieve(n)[it] && pal_test(it))
{
pal=it;
break;
}
}
return pal;
}
unsigned long long inpalprime::n_maxfac(unsigned long long m)
{
unsigned long long p=3;
//removing factors of 2
while(m%2==0)
{
maxfac=2;
m=m/2;
}
//finding possible prime factors
while(m!=1)
{
while(m%p==0)
{
maxfac=p;
m=m/p;
}
p+=2;
}
return maxfac;
}
std::vector<bool> inpalprime::atkinsieve(unsigned long long m)
{
std::vector<bool> p_test(m+1, false);
//defines square root of n
unsigned long long root=ceil(sqrt(m));
//sieve axioms
for(unsigned long long x=1; x<=root; x++)
{
for(unsigned long long y=1; y<=root; y++)
{
unsigned long long i=(4*x*x)+(y*y);
if (i<=m && (i%12==1 || i%12==5))
{
p_test[i].flip();
}
i=(3*x*x)+(y*y);
if(i<=m && i%12==7)
{
p_test[i].flip();
}
i=(3*x*x)-(y*y);
if(x>y && i<=m && i%12==11)
{
p_test[i].flip();
}
}
}
//marks 2,3,5 and 7 as prime numbers
p_test[2]=p_test[3]=p_test[5]=p_test[7]=true;
//marks all multiples of primes as non primes
for(unsigned long long r=5; r<=root; r++)
{
if((p_test[r]))
{
for(unsigned long long j=r*r; j<=m; j+=r*r)
{
p_test[j]=false;
}
}
}
return p_test;
}
bool inpalprime::pal_test(unsigned long long m)
{
//converting m to a string
ull=std::to_string(m);
//checking if the reverse of ull is equal to ull
if(ull!=std::string(ull.rbegin(), ull.rend()))
{
return false;
}
return true;
}
<commit_msg>Delete inpalprime.cpp<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// Use UNICODE Windows and C API.
#define _UNICODE
#define UNICODE
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#include "uno/environment.hxx"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <tchar.h>
#include "native_share.h"
#include "rtl/bootstrap.hxx"
#include "com/sun/star/uno/XComponentContext.hpp"
#include "cppuhelper/bootstrap.hxx"
#include <delayimp.h>
#include <stdio.h>
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace cli_ure {
WCHAR * resolveLink(WCHAR * path);
}
#define INSTALL_PATH L"Software\\LibreOffice\\UNO\\InstallPath"
#define URE_LINK L"\\ure-link"
#define URE_BIN L"\\bin"
#define UNO_PATH L"UNO_PATH"
namespace
{
/*
* Gets the installation path from the Windows Registry for the specified
* registry key.
*
* @param hroot open handle to predefined root registry key
* @param subKeyName name of the subkey to open
*
* @return the installation path or NULL, if no installation was found or
* if an error occurred
*/
WCHAR* getPathFromRegistryKey( HKEY hroot, LPCWSTR subKeyName )
{
HKEY hkey;
DWORD type;
TCHAR* data = NULL;
DWORD size;
/* open the specified registry key */
if ( RegOpenKeyEx( hroot, subKeyName, 0, KEY_READ, &hkey ) != ERROR_SUCCESS )
{
return NULL;
}
/* find the type and size of the default value */
if ( RegQueryValueEx( hkey, NULL, NULL, &type, NULL, &size) != ERROR_SUCCESS )
{
RegCloseKey( hkey );
return NULL;
}
/* get memory to hold the default value */
data = new WCHAR[size];
/* read the default value */
if ( RegQueryValueEx( hkey, NULL, NULL, &type, (LPBYTE) data, &size ) != ERROR_SUCCESS )
{
RegCloseKey( hkey );
return NULL;
}
/* release registry key handle */
RegCloseKey( hkey );
return data;
}
/* If the path does not end with '\' the las segment will be removed.
path: C:\a\b
-> C:\a
@param io_path
in/out parameter. The string is not reallocated. Simply a '\0'
will be inserted to shorten the string.
*/
void oneDirUp(LPTSTR io_path)
{
WCHAR * pEnd = io_path + lstrlen(io_path) - 1;
while (pEnd > io_path //prevent crashing if provided string does not contain a backslash
&& *pEnd != L'\\')
pEnd --;
*pEnd = L'\0';
}
/* Returns the path to the program folder of the brand layer,
for example c:/openoffice.org 3/program
This path is either obtained from the environment variable UNO_PATH
or the registry item
"Software\\OpenOffice.org\\UNO\\InstallPath"
either in HKEY_CURRENT_USER or HKEY_LOCAL_MACHINE
The return value must be freed with delete[]
*/
WCHAR * getInstallPath()
{
WCHAR * szInstallPath = NULL;
DWORD cChars = GetEnvironmentVariable(UNO_PATH, NULL, 0);
if (cChars > 0)
{
szInstallPath = new WCHAR[cChars];
cChars = GetEnvironmentVariable(UNO_PATH, szInstallPath, cChars);
//If PATH is not set then it is no error
if (cChars == 0)
{
delete[] szInstallPath;
return NULL;
}
}
if (! szInstallPath)
{
szInstallPath = getPathFromRegistryKey( HKEY_CURRENT_USER, INSTALL_PATH );
if ( szInstallPath == NULL )
{
/* read the key's default value from HKEY_LOCAL_MACHINE */
szInstallPath = getPathFromRegistryKey( HKEY_LOCAL_MACHINE, INSTALL_PATH );
}
}
return szInstallPath;
}
/* Returns the path to the URE/bin path, where cppuhelper lib resides.
The returned string must be freed with delete[]
*/
WCHAR* getUnoPath()
{
WCHAR * szLinkPath = NULL;
WCHAR * szUrePath = NULL;
WCHAR * szUreBin = NULL; //the return value
WCHAR * szInstallPath = getInstallPath();
if (szInstallPath)
{
oneDirUp(szInstallPath);
//build the path to the ure-link file
szUrePath = new WCHAR[MAX_PATH];
szUrePath[0] = L'\0';
lstrcat(szUrePath, szInstallPath);
lstrcat(szUrePath, URE_LINK);
//get the path to the actual Ure folder
if (cli_ure::resolveLink(szUrePath))
{
//build the path to the URE/bin directory
szUreBin = new WCHAR[lstrlen(szUrePath) + lstrlen(URE_BIN) + 1];
szUreBin[0] = L'\0';
lstrcat(szUreBin, szUrePath);
lstrcat(szUreBin, URE_BIN);
}
}
#if OSL_DEBUG_LEVEL >=2
if (szUreBin)
{
fwprintf(stdout,L"[cli_cppuhelper]: Path to URE libraries:\n %s \n", szUreBin);
}
else
{
fwprintf(stdout,L"[cli_cppuhelper]: Failed to determine location of URE.\n");
}
#endif
delete[] szInstallPath;
delete[] szLinkPath;
delete[] szUrePath;
return szUreBin;
}
/*We extend the path to contain the Ure/bin folder,
so that components can use osl_loadModule with arguments, such as
"reg3.dll". That is, the arguments are only the library names.
*/
void extendPath(LPCWSTR szUreBinPath)
{
if (!szUreBinPath)
return;
WCHAR * sEnvPath = NULL;
DWORD cChars = GetEnvironmentVariable(L"PATH", sEnvPath, 0);
if (cChars > 0)
{
sEnvPath = new WCHAR[cChars];
cChars = GetEnvironmentVariable(L"PATH", sEnvPath, cChars);
//If PATH is not set then it is no error
if (cChars == 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND)
{
delete[] sEnvPath;
return;
}
}
//prepare the new PATH. Add the Ure/bin directory at the front.
//note also adding ';'
WCHAR * sNewPath = new WCHAR[lstrlen(sEnvPath) + lstrlen(szUreBinPath) + 2];
sNewPath[0] = L'\0';
lstrcat(sNewPath, szUreBinPath);
if (lstrlen(sEnvPath))
{
lstrcat(sNewPath, L";");
lstrcat(sNewPath, sEnvPath);
}
BOOL bSet = SetEnvironmentVariable(L"PATH", sNewPath);
delete[] sEnvPath;
delete[] sNewPath;
}
HMODULE loadFromPath(LPCWSTR sLibName)
{
if (sLibName == NULL)
return NULL;
WCHAR * szUreBinPath = getUnoPath();
if (!szUreBinPath)
return NULL;
extendPath(szUreBinPath);
WCHAR* szFullPath = new WCHAR[lstrlen(sLibName) + lstrlen(szUreBinPath) + 2];
szFullPath[0] = L'\0';
lstrcat(szFullPath, szUreBinPath);
lstrcat(szFullPath, L"\\");
lstrcat(szFullPath, sLibName);
HMODULE handle = LoadLibraryEx(szFullPath, NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
delete[] szFullPath;
delete[] szUreBinPath;
return handle;
}
/*Hook for delayed loading of libraries which this library is linked with.
This is a failure hook. That is, it is only called when the loading of
a library failed. It will be called when loading of cppuhelper failed.
Because we extend the PATH to the URE/bin folder while this function is
executed (see extendPath), all other libraries are found.
*/
extern "C" FARPROC WINAPI delayLoadHook(
unsigned dliNotify,
PDelayLoadInfo pdli
)
{
if (dliNotify == dliFailLoadLib)
{
LPWSTR szLibName = NULL;
//Convert the ansi file name to wchar_t*
int size = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pdli->szDll, -1, NULL, 0);
if (size > 0)
{
szLibName = new WCHAR[size];
if (! MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pdli->szDll, -1, szLibName, size))
{
return 0;
}
}
HANDLE h = loadFromPath(szLibName);
delete[] szLibName;
return (FARPROC) h;
}
return 0;
}
}
ExternC
PfnDliHook __pfnDliFailureHook2 = delayLoadHook;
namespace uno
{
namespace util
{
/** Bootstrapping native UNO.
Bootstrapping requires the existence of many libraries which are contained
in an URE installation. To find and load these libraries the Windows
registry keys HKEY_CURRENT_USER\Software\OpenOffice.org\Layer\URE\1
and HKEY_LOCAL_MACHINE\Software\OpenOffice.org\Layer\URE\1 are examined.
These contain a named value UREINSTALLLOCATION which holds a path to the URE
installation folder.
*/
public __sealed __gc class Bootstrap
{
inline Bootstrap() {}
public:
/** Bootstraps the initial component context from a native UNO installation.
@see cppuhelper/bootstrap.hxx:defaultBootstrap_InitialComponentContext()
*/
static ::unoidl::com::sun::star::uno::XComponentContext *
defaultBootstrap_InitialComponentContext();
/** Bootstraps the initial component context from a native UNO installation.
@param ini_file
a file URL of an ini file, e.g. uno.ini/unorc. (The ini file must
reside next to the cppuhelper library)
@param bootstrap_parameters
bootstrap parameters (maybe null)
@see cppuhelper/bootstrap.hxx:defaultBootstrap_InitialComponentContext()
*/
static ::unoidl::com::sun::star::uno::XComponentContext *
defaultBootstrap_InitialComponentContext(
::System::String * ini_file,
::System::Collections::IDictionaryEnumerator *
bootstrap_parameters );
/** Bootstraps the initial component context from a native UNO installation.
@see cppuhelper/bootstrap.hxx:bootstrap()
*/
static ::unoidl::com::sun::star::uno::XComponentContext *
bootstrap();
};
//______________________________________________________________________________
::unoidl::com::sun::star::uno::XComponentContext *
Bootstrap::defaultBootstrap_InitialComponentContext(
::System::String * ini_file,
::System::Collections::IDictionaryEnumerator * bootstrap_parameters )
{
if (0 != bootstrap_parameters)
{
bootstrap_parameters->Reset();
while (bootstrap_parameters->MoveNext())
{
OUString key(
String_to_ustring( __try_cast< ::System::String * >(
bootstrap_parameters->get_Key() ) ) );
OUString value(
String_to_ustring( __try_cast< ::System::String * >(
bootstrap_parameters->get_Value() ) ) );
::rtl::Bootstrap::set( key, value );
}
}
// bootstrap native uno
Reference< XComponentContext > xContext;
if (0 == ini_file)
{
xContext = ::cppu::defaultBootstrap_InitialComponentContext();
}
else
{
xContext = ::cppu::defaultBootstrap_InitialComponentContext(
String_to_ustring( __try_cast< ::System::String * >( ini_file ) ) );
}
return __try_cast< ::unoidl::com::sun::star::uno::XComponentContext * >(
to_cli( xContext ) );
}
//______________________________________________________________________________
::unoidl::com::sun::star::uno::XComponentContext *
Bootstrap::defaultBootstrap_InitialComponentContext()
{
return defaultBootstrap_InitialComponentContext( 0, 0 );
}
::unoidl::com::sun::star::uno::XComponentContext * Bootstrap::bootstrap()
{
Reference<XComponentContext> xContext = ::cppu::bootstrap();
return __try_cast< ::unoidl::com::sun::star::uno::XComponentContext * >(
to_cli( xContext ) );
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>OpenOffice.org -> LibreOffice in comment<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// Use UNICODE Windows and C API.
#define _UNICODE
#define UNICODE
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#include "uno/environment.hxx"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <tchar.h>
#include "native_share.h"
#include "rtl/bootstrap.hxx"
#include "com/sun/star/uno/XComponentContext.hpp"
#include "cppuhelper/bootstrap.hxx"
#include <delayimp.h>
#include <stdio.h>
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace cli_ure {
WCHAR * resolveLink(WCHAR * path);
}
#define INSTALL_PATH L"Software\\LibreOffice\\UNO\\InstallPath"
#define URE_LINK L"\\ure-link"
#define URE_BIN L"\\bin"
#define UNO_PATH L"UNO_PATH"
namespace
{
/*
* Gets the installation path from the Windows Registry for the specified
* registry key.
*
* @param hroot open handle to predefined root registry key
* @param subKeyName name of the subkey to open
*
* @return the installation path or NULL, if no installation was found or
* if an error occurred
*/
WCHAR* getPathFromRegistryKey( HKEY hroot, LPCWSTR subKeyName )
{
HKEY hkey;
DWORD type;
TCHAR* data = NULL;
DWORD size;
/* open the specified registry key */
if ( RegOpenKeyEx( hroot, subKeyName, 0, KEY_READ, &hkey ) != ERROR_SUCCESS )
{
return NULL;
}
/* find the type and size of the default value */
if ( RegQueryValueEx( hkey, NULL, NULL, &type, NULL, &size) != ERROR_SUCCESS )
{
RegCloseKey( hkey );
return NULL;
}
/* get memory to hold the default value */
data = new WCHAR[size];
/* read the default value */
if ( RegQueryValueEx( hkey, NULL, NULL, &type, (LPBYTE) data, &size ) != ERROR_SUCCESS )
{
RegCloseKey( hkey );
return NULL;
}
/* release registry key handle */
RegCloseKey( hkey );
return data;
}
/* If the path does not end with '\' the las segment will be removed.
path: C:\a\b
-> C:\a
@param io_path
in/out parameter. The string is not reallocated. Simply a '\0'
will be inserted to shorten the string.
*/
void oneDirUp(LPTSTR io_path)
{
WCHAR * pEnd = io_path + lstrlen(io_path) - 1;
while (pEnd > io_path //prevent crashing if provided string does not contain a backslash
&& *pEnd != L'\\')
pEnd --;
*pEnd = L'\0';
}
/* Returns the path to the program folder of the brand layer,
for example c:/LibreOffice 3/program
This path is either obtained from the environment variable UNO_PATH
or the registry item
"Software\\LibreOffice\\UNO\\InstallPath"
either in HKEY_CURRENT_USER or HKEY_LOCAL_MACHINE
The return value must be freed with delete[]
*/
WCHAR * getInstallPath()
{
WCHAR * szInstallPath = NULL;
DWORD cChars = GetEnvironmentVariable(UNO_PATH, NULL, 0);
if (cChars > 0)
{
szInstallPath = new WCHAR[cChars];
cChars = GetEnvironmentVariable(UNO_PATH, szInstallPath, cChars);
//If PATH is not set then it is no error
if (cChars == 0)
{
delete[] szInstallPath;
return NULL;
}
}
if (! szInstallPath)
{
szInstallPath = getPathFromRegistryKey( HKEY_CURRENT_USER, INSTALL_PATH );
if ( szInstallPath == NULL )
{
/* read the key's default value from HKEY_LOCAL_MACHINE */
szInstallPath = getPathFromRegistryKey( HKEY_LOCAL_MACHINE, INSTALL_PATH );
}
}
return szInstallPath;
}
/* Returns the path to the URE/bin path, where cppuhelper lib resides.
The returned string must be freed with delete[]
*/
WCHAR* getUnoPath()
{
WCHAR * szLinkPath = NULL;
WCHAR * szUrePath = NULL;
WCHAR * szUreBin = NULL; //the return value
WCHAR * szInstallPath = getInstallPath();
if (szInstallPath)
{
oneDirUp(szInstallPath);
//build the path to the ure-link file
szUrePath = new WCHAR[MAX_PATH];
szUrePath[0] = L'\0';
lstrcat(szUrePath, szInstallPath);
lstrcat(szUrePath, URE_LINK);
//get the path to the actual Ure folder
if (cli_ure::resolveLink(szUrePath))
{
//build the path to the URE/bin directory
szUreBin = new WCHAR[lstrlen(szUrePath) + lstrlen(URE_BIN) + 1];
szUreBin[0] = L'\0';
lstrcat(szUreBin, szUrePath);
lstrcat(szUreBin, URE_BIN);
}
}
#if OSL_DEBUG_LEVEL >=2
if (szUreBin)
{
fwprintf(stdout,L"[cli_cppuhelper]: Path to URE libraries:\n %s \n", szUreBin);
}
else
{
fwprintf(stdout,L"[cli_cppuhelper]: Failed to determine location of URE.\n");
}
#endif
delete[] szInstallPath;
delete[] szLinkPath;
delete[] szUrePath;
return szUreBin;
}
/*We extend the path to contain the Ure/bin folder,
so that components can use osl_loadModule with arguments, such as
"reg3.dll". That is, the arguments are only the library names.
*/
void extendPath(LPCWSTR szUreBinPath)
{
if (!szUreBinPath)
return;
WCHAR * sEnvPath = NULL;
DWORD cChars = GetEnvironmentVariable(L"PATH", sEnvPath, 0);
if (cChars > 0)
{
sEnvPath = new WCHAR[cChars];
cChars = GetEnvironmentVariable(L"PATH", sEnvPath, cChars);
//If PATH is not set then it is no error
if (cChars == 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND)
{
delete[] sEnvPath;
return;
}
}
//prepare the new PATH. Add the Ure/bin directory at the front.
//note also adding ';'
WCHAR * sNewPath = new WCHAR[lstrlen(sEnvPath) + lstrlen(szUreBinPath) + 2];
sNewPath[0] = L'\0';
lstrcat(sNewPath, szUreBinPath);
if (lstrlen(sEnvPath))
{
lstrcat(sNewPath, L";");
lstrcat(sNewPath, sEnvPath);
}
BOOL bSet = SetEnvironmentVariable(L"PATH", sNewPath);
delete[] sEnvPath;
delete[] sNewPath;
}
HMODULE loadFromPath(LPCWSTR sLibName)
{
if (sLibName == NULL)
return NULL;
WCHAR * szUreBinPath = getUnoPath();
if (!szUreBinPath)
return NULL;
extendPath(szUreBinPath);
WCHAR* szFullPath = new WCHAR[lstrlen(sLibName) + lstrlen(szUreBinPath) + 2];
szFullPath[0] = L'\0';
lstrcat(szFullPath, szUreBinPath);
lstrcat(szFullPath, L"\\");
lstrcat(szFullPath, sLibName);
HMODULE handle = LoadLibraryEx(szFullPath, NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
delete[] szFullPath;
delete[] szUreBinPath;
return handle;
}
/*Hook for delayed loading of libraries which this library is linked with.
This is a failure hook. That is, it is only called when the loading of
a library failed. It will be called when loading of cppuhelper failed.
Because we extend the PATH to the URE/bin folder while this function is
executed (see extendPath), all other libraries are found.
*/
extern "C" FARPROC WINAPI delayLoadHook(
unsigned dliNotify,
PDelayLoadInfo pdli
)
{
if (dliNotify == dliFailLoadLib)
{
LPWSTR szLibName = NULL;
//Convert the ansi file name to wchar_t*
int size = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pdli->szDll, -1, NULL, 0);
if (size > 0)
{
szLibName = new WCHAR[size];
if (! MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pdli->szDll, -1, szLibName, size))
{
return 0;
}
}
HANDLE h = loadFromPath(szLibName);
delete[] szLibName;
return (FARPROC) h;
}
return 0;
}
}
ExternC
PfnDliHook __pfnDliFailureHook2 = delayLoadHook;
namespace uno
{
namespace util
{
/** Bootstrapping native UNO.
Bootstrapping requires the existence of many libraries which are contained
in an URE installation. To find and load these libraries the Windows
registry keys HKEY_CURRENT_USER\Software\LibreOffice\Layer\URE\1
and HKEY_LOCAL_MACHINE\Software\LibreOffice\Layer\URE\1 are examined.
These contain a named value UREINSTALLLOCATION which holds a path to the URE
installation folder.
*/
public __sealed __gc class Bootstrap
{
inline Bootstrap() {}
public:
/** Bootstraps the initial component context from a native UNO installation.
@see cppuhelper/bootstrap.hxx:defaultBootstrap_InitialComponentContext()
*/
static ::unoidl::com::sun::star::uno::XComponentContext *
defaultBootstrap_InitialComponentContext();
/** Bootstraps the initial component context from a native UNO installation.
@param ini_file
a file URL of an ini file, e.g. uno.ini/unorc. (The ini file must
reside next to the cppuhelper library)
@param bootstrap_parameters
bootstrap parameters (maybe null)
@see cppuhelper/bootstrap.hxx:defaultBootstrap_InitialComponentContext()
*/
static ::unoidl::com::sun::star::uno::XComponentContext *
defaultBootstrap_InitialComponentContext(
::System::String * ini_file,
::System::Collections::IDictionaryEnumerator *
bootstrap_parameters );
/** Bootstraps the initial component context from a native UNO installation.
@see cppuhelper/bootstrap.hxx:bootstrap()
*/
static ::unoidl::com::sun::star::uno::XComponentContext *
bootstrap();
};
//______________________________________________________________________________
::unoidl::com::sun::star::uno::XComponentContext *
Bootstrap::defaultBootstrap_InitialComponentContext(
::System::String * ini_file,
::System::Collections::IDictionaryEnumerator * bootstrap_parameters )
{
if (0 != bootstrap_parameters)
{
bootstrap_parameters->Reset();
while (bootstrap_parameters->MoveNext())
{
OUString key(
String_to_ustring( __try_cast< ::System::String * >(
bootstrap_parameters->get_Key() ) ) );
OUString value(
String_to_ustring( __try_cast< ::System::String * >(
bootstrap_parameters->get_Value() ) ) );
::rtl::Bootstrap::set( key, value );
}
}
// bootstrap native uno
Reference< XComponentContext > xContext;
if (0 == ini_file)
{
xContext = ::cppu::defaultBootstrap_InitialComponentContext();
}
else
{
xContext = ::cppu::defaultBootstrap_InitialComponentContext(
String_to_ustring( __try_cast< ::System::String * >( ini_file ) ) );
}
return __try_cast< ::unoidl::com::sun::star::uno::XComponentContext * >(
to_cli( xContext ) );
}
//______________________________________________________________________________
::unoidl::com::sun::star::uno::XComponentContext *
Bootstrap::defaultBootstrap_InitialComponentContext()
{
return defaultBootstrap_InitialComponentContext( 0, 0 );
}
::unoidl::com::sun::star::uno::XComponentContext * Bootstrap::bootstrap()
{
Reference<XComponentContext> xContext = ::cppu::bootstrap();
return __try_cast< ::unoidl::com::sun::star::uno::XComponentContext * >(
to_cli( xContext ) );
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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 "base/i18n/break_iterator.h"
#include "base/logging.h"
#include "unicode/ubrk.h"
#include "unicode/uchar.h"
#include "unicode/ustring.h"
namespace base {
const size_t npos = -1;
BreakIterator::BreakIterator(const string16* str, BreakType break_type)
: iter_(NULL),
string_(str),
break_type_(break_type),
prev_(npos),
pos_(0) {
}
BreakIterator::~BreakIterator() {
if (iter_)
ubrk_close(iter_);
}
bool BreakIterator::Init() {
UErrorCode status = U_ZERO_ERROR;
UBreakIteratorType break_type;
switch (break_type_) {
case BREAK_WORD:
break_type = UBRK_WORD;
break;
case BREAK_SPACE:
break_type = UBRK_LINE;
break;
default:
NOTREACHED();
break_type = UBRK_LINE;
}
iter_ = ubrk_open(break_type, NULL,
string_->data(), static_cast<int32_t>(string_->size()),
&status);
if (U_FAILURE(status)) {
NOTREACHED() << "ubrk_open failed";
return false;
}
ubrk_first(iter_); // Move the iterator to the beginning of the string.
return true;
}
bool BreakIterator::Advance() {
prev_ = pos_;
const int32_t pos = ubrk_next(iter_);
if (pos == UBRK_DONE) {
pos_ = npos;
return false;
} else {
pos_ = static_cast<size_t>(pos);
return true;
}
}
bool BreakIterator::IsWord() const {
return (break_type_ == BREAK_WORD &&
ubrk_getRuleStatus(iter_) != UBRK_WORD_NONE);
}
string16 BreakIterator::GetString() const {
DCHECK(prev_ != npos && pos_ != npos);
return string_->substr(prev_, pos_ - prev_);
}
} // namespace base
<commit_msg>Fix build with -Duse_system_icu=1 and libicu-4.4.*<commit_after>// Copyright (c) 2009 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 "base/i18n/break_iterator.h"
#include "base/logging.h"
#include "unicode/ubrk.h"
#include "unicode/uchar.h"
#include "unicode/ustring.h"
namespace base {
const size_t npos = -1;
BreakIterator::BreakIterator(const string16* str, BreakType break_type)
: iter_(NULL),
string_(str),
break_type_(break_type),
prev_(npos),
pos_(0) {
}
BreakIterator::~BreakIterator() {
if (iter_)
ubrk_close(static_cast<UBreakIterator*>(iter_));
}
bool BreakIterator::Init() {
UErrorCode status = U_ZERO_ERROR;
UBreakIteratorType break_type;
switch (break_type_) {
case BREAK_WORD:
break_type = UBRK_WORD;
break;
case BREAK_SPACE:
break_type = UBRK_LINE;
break;
default:
NOTREACHED();
break_type = UBRK_LINE;
}
iter_ = ubrk_open(break_type, NULL,
string_->data(), static_cast<int32_t>(string_->size()),
&status);
if (U_FAILURE(status)) {
NOTREACHED() << "ubrk_open failed";
return false;
}
// Move the iterator to the beginning of the string.
ubrk_first(static_cast<UBreakIterator*>(iter_));
return true;
}
bool BreakIterator::Advance() {
prev_ = pos_;
const int32_t pos = ubrk_next(static_cast<UBreakIterator*>(iter_));
if (pos == UBRK_DONE) {
pos_ = npos;
return false;
} else {
pos_ = static_cast<size_t>(pos);
return true;
}
}
bool BreakIterator::IsWord() const {
return (break_type_ == BREAK_WORD &&
ubrk_getRuleStatus(static_cast<UBreakIterator*>(iter_)) !=
UBRK_WORD_NONE);
}
string16 BreakIterator::GetString() const {
DCHECK(prev_ != npos && pos_ != npos);
return string_->substr(prev_, pos_ - prev_);
}
} // namespace base
<|endoftext|> |
<commit_before>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/optimization/CRandomSearch.cpp,v $
$Revision: 1.12 $
$Name: $
$Author: anuragr $
$Date: 2005/06/21 20:38:30 $
End CVS Header */
/***************************************************************************
CRandomSearch.cpp - Random Optimizer
-------------------
Programmer : Rohan Luktuke
email : rluktuke@vt.edu
***************************************************************************/
/***************************************************************************
* This is the implementation of the Random Algorithm for Optimization. The
* class is inherited from the COptAlgorithm class
***************************************************************************/
#include "copasi.h"
#include "COptMethod.h"
#include "CRealProblem.h"
#include "randomGenerator/CRandom.h"
//** Taken from COptMethodGA
#include "COptProblem.h"
#include "COptItem.h"
//#include "utilities/CProcessReport.h"
//#include "report/CCopasiObjectReference.h"
//**** include namespace to fix CRandomSearch is not class or namespace error
#include "CRandomSearch.h"
CRandomSearch::CRandomSearch():
COptMethod(CCopasiMethod::RandomSearch)
{
/*addParameter("RandomSearch.Iterations",
CCopasiParameter::UINT,
(unsigned C_INT32) 100000);
addParameter("RandomSearch.RandomGenerator.Type",
CCopasiParameter::INT,
(C_INT32) CRandom::mt19937);
addParameter("RandomSearch.RandomGenerator.Seed",
CCopasiParameter::INT,
(C_INT32) 0); */
//*** Redefined changing the names displayed
addParameter("Number of Iterations",
CCopasiParameter::UINT,
(unsigned C_INT32) 100000);
addParameter("Random Generator Type",
CCopasiParameter::INT,
(C_INT32) CRandom::mt19937);
addParameter("Seed",
CCopasiParameter::INT,
(C_INT32) 0);
//*** added random number generator parameter
addParameter("Random Number Generator", CCopasiParameter::UINT, (unsigned C_INT32) CRandom::mt19937);
}
CRandomSearch::CRandomSearch(const CRandomSearch & src):
COptMethod(src)
{}
/**
* Destructor
*/
CRandomSearch::~CRandomSearch()
{//*** added similar to coptga
cleanup();
}
/**
* Optimizer Function
* Returns: true if properly initialized
//*** should return a boolean
*/
bool CRandomSearch::initialize()
{
//unsigned C_INT32 i;
if (!COptMethod::initialize()) return false;
//C_FLOAT64 la, x, candx = DBL_MAX;
C_FLOAT64 candx = DBL_MAX;
//C_INT32 i, imax = (C_INT32) getValue("Number of Iterations");
mIterations = * getValue("Number of Iterations").pUINT;
//C_INT32 j, jmax = mpOptProblem->getVariableSize();
//C_INT32 jmax = mpOptProblem->getVariableSize();
//mGenerations = * (unsigned C_INT32 *) getValue("Number of Generations");
//mPopulationSize = * (unsigned C_INT32 *) getValue("Population Size");
mpRandom = CRandom::createGenerator(* (CRandom::Type *) getValue("Random Number Generator").pUINT,
* getValue("Seed").pUINT);
//CRandom::Type Type;
Type = * (CRandom::Type *) getValue("Random Generator Type").pUINT;
//unsigned C_INT32 Seed;
Seed = * getValue("Seed").pUINT;
//***mIndividual defined as C_FLOAT64 member variable
mVariableSize = mpOptItem->size();
//*** Single mIndividual defined as a member
mIndividual.resize(mVariableSize);
/*for (i = 0; i < 2*mPopulationSize; i++)
mIndividual[i] = new CVector< C_FLOAT64 >(mVariableSize);
/*mCrossOverFalse.resize(mVariableSize);
mCrossOverFalse = false;
mCrossOver.resize(mVariableSize);
mValue.resize(2*mPopulationSize);
mShuffle.resize(mPopulationSize);
for (i = 0; i < mPopulationSize; i++)
mShuffle[i] = i;
mWins.resize(2*mPopulationSize);
// initialise the variance for mutations
mMutationVarians = 0.1;*/
return true;
}
/**
* Optimizer Function
* Returns: nothing
//*** should return a boolean
*/
//C_INT32 CRandomSearch::optimise()
bool CRandomSearch::optimise()
{
bool linear;
if (!initialize()) return false;
C_FLOAT64 la, candx = DBL_MAX;
//C_INT32 i, imax = (C_INT32) getValue("RandomSearch.Iterations");
mIterations = * getValue("Number of Iterations").pUINT;
//C_INT32 j, jmax = mpOptProblem->getVariableSize();
C_INT32 i, j;
//C_INT32 varSize = mpOptProblem->getVariableSize();
C_FLOAT64 mn;
C_FLOAT64 mx;
/* Create a random number generator * /
CRandom::Type Type;
Type = (CRandom::Type) (C_INT32) getValue("RandomSearch.RandomGenerator.Type");
unsigned C_INT32 Seed;
Seed = (unsigned C_INT32) getValue("RandomSearch.RandomGenerator.Seed");*/
CRandom * pRand = CRandom::createGenerator(Type, Seed);
assert(pRand);
for (i = 0; i < mIterations; i++)
{
for (j = 0; j < mVariableSize; j++)
{
// CALCULATE lower and upper bounds
COptItem & OptItem = *(*mpOptItem)[j];
mn = *OptItem.getLowerBoundValue();
mx = *OptItem.getUpperBoundValue();
C_FLOAT64 mut = mIndividual[j];
try
{
// determine if linear or log scale
linear = false; la = 1.0;
if (mn == 0.0) mn = DBL_EPSILON;
if ((mn < 0.0) || (mx <= 0.0))
linear = true;
else
{
la = log10(mx) - log10(mn);
if (la < 1.8) linear = true;
}
// set it to a random value within the interval
if (linear)
mut = mn + pRand->getRandomCC() * (mx - mn);
else
mut = mn * pow(10, la * pRand->getRandomCC());
}
catch (...)
{
mut = (mx + mn) * 0.5;
}
// force it to be within the bounds
switch (OptItem.checkConstraint(mut))
{
case - 1:
mut = *OptItem.getLowerBoundValue();
if (!OptItem.checkLowerBound(mut)) // Inequality
{
if (mut == 0.0)
mut = DBL_MIN;
else
mut += mut * DBL_EPSILON;
}
break;
case 1:
mut = *OptItem.getUpperBoundValue();
if (!OptItem.checkUpperBound(mut)) // Inequality
{
if (mut == 0.0)
mut = - DBL_MIN;
else
mut -= mut * DBL_EPSILON;
}
break;
}
}
try
{
// calculate its fitness
mValue = evaluate(mIndividual);
}
catch (...)
{
mValue = DBL_MAX;
}
// COMPARE
if (i == 0 && j == 0)
{
//*** initialize mBestValue to start with mValue
mBestValue = mValue;
mpOptProblem->setSolutionValue(mBestValue);
mpOptProblem->setSolutionVariables(mIndividual);
}
if (mValue < mBestValue)
{
mBestValue = mValue;
mpOptProblem->setSolutionValue(mBestValue);
mpOptProblem->setSolutionVariables(mIndividual);
}
/*// get the index of the fittest
mBestIndex = fittest();
// and store that value
mBestValue = mValue[mBestIndex];*/
}
// *** This is not used anymore, use different means
/*const double ** Minimum = mpOptProblem->getParameterMin().array();
//const double ** Maximum = mpOptProblem->getParameterMax().array();
unsigned C_INT32 i;
// initialise the population
// first individual is the initial guess
for (i = 0; i < mVariableSize; i++)
(*mIndividual[0])[i] = *(*mpOptItem)[i]->getObjectValue();
try
{
// calculate the fitness
mValue[0] = evaluate(*mIndividual[0]);
}
catch (...)
{
mValue[0] = DBL_MAX;
}
// the others are random
creation(1, mPopulationSize);
// initialise the update register
// get the index of the fittest
mBestIndex = fittest();
// and store that value
mBestValue = mValue[mBestIndex];
CVector< C_FLOAT64 > & Parameter = mpOptProblem->getCalculateVariables();
for (i = 0; i < imax; i++)
{
//change parameters randomly
for (j = 0; j < jmax; j++)
{
linear = false;
la = 1.0;
if ((*Maximum[j] <= 0.0) || (*Minimum[j] < 0.0)) linear = true;
else
{
la = log10(*Maximum[j]) - log10(std::min(*Minimum[j], DBL_EPSILON));
if (la < 1.8) linear = true;
}
if (linear)
Parameter[j] =
*Minimum[j] + pRand->getRandomCC() * (*Maximum[j] - *Minimum[j]);
else
Parameter[j] = *Minimum[j] * pow(10, la * pRand->getRandomCC());
} // j<..getParameterNum() loop ends
// check parametric constraints
if (!mpOptProblem->checkParametricConstraints()) continue;
// calculate the function in the problem
x = mpOptProblem->calculate();
// check if better than previously stored
if (x < candx)
{
if (!mpOptProblem->checkFunctionalConstraints())
continue;
//set best value
mpOptProblem->setSolutionValue(x);
candx = x;
//store the combination of parameter values
mpOptProblem->getSolutionVariables() = Parameter;
}
}*/
pdelete(pRand);
return 0;
}
// evaluate the fitness of one individual
C_FLOAT64 CRandomSearch::evaluate(const CVector< C_FLOAT64 > & individual)
{
unsigned C_INT32 j;
std::vector< UpdateMethod *>::const_iterator itMethod = mpSetCalculateVariable->begin();
// set the paramter values
for (j = 0; j < mVariableSize; j++, ++itMethod)
(**itMethod)(individual[j]);
// check whether the parametric constraints are fulfilled
if (!mpOptProblem->checkParametricConstraints()) return DBL_MAX;
// evaluate the fitness
try
{
if (!mpOptProblem->calculate()) return DBL_MAX;
}
catch (...)
{
return DBL_MAX;
}
// check wheter the functional constraints are fulfilled
if (!mpOptProblem->checkFunctionalConstraints()) return DBL_MAX;
return mpOptProblem->getCalculateValue();
}
// check the best individual at this generation
/*unsigned C_INT32 CRandomSearch::fittest()
{
unsigned C_INT32 i, BestIndex = 0;
C_FLOAT64 BestValue = mValue[0];
//for (i = 1; i < mPopulationSize; i++)
for (i = 1; i < mIterations; i++)
if (mValue[i] < BestValue)
{
BestIndex = i;
BestValue = mValue[i];
}
return BestIndex;
}*/
<commit_msg>Code cleanup.<commit_after>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/optimization/CRandomSearch.cpp,v $
$Revision: 1.13 $
$Name: $
$Author: shoops $
$Date: 2005/07/01 14:45:38 $
End CVS Header */
/***************************************************************************
CRandomSearch.cpp - Random Optimizer
-------------------
Programmer : Rohan Luktuke
email : rluktuke@vt.edu
***************************************************************************/
/***************************************************************************
* This is the implementation of the Random Algorithm for Optimization. The
* class is inherited from the COptAlgorithm class
***************************************************************************/
#include "copasi.h"
#include "COptMethod.h"
#include "CRealProblem.h"
#include "randomGenerator/CRandom.h"
//** Taken from COptMethodGA
#include "COptProblem.h"
#include "COptItem.h"
//#include "utilities/CProcessReport.h"
//#include "report/CCopasiObjectReference.h"
//**** include namespace to fix CRandomSearch is not class or namespace error
#include "CRandomSearch.h"
CRandomSearch::CRandomSearch():
COptMethod(CCopasiMethod::RandomSearch)
{
addParameter("Number of Iterations", CCopasiParameter::UINT, (unsigned C_INT32) 100000);
addParameter("Random Number Generator", CCopasiParameter::UINT, (unsigned C_INT32) CRandom::mt19937);
addParameter("Seed", CCopasiParameter::UINT, (unsigned C_INT32) 0);
}
CRandomSearch::CRandomSearch(const CRandomSearch & src):
COptMethod(src)
{}
/**
* Destructor
*/
CRandomSearch::~CRandomSearch()
{//*** added similar to coptga
cleanup();
}
#ifdef WIN32
// warning C4056: overflow in floating-point constant arithmetic
// warning C4756: overflow in constant arithmetic
# pragma warning (disable: 4056 4756)
#endif
/**
* Optimizer Function
* Returns: true if properly initialized
//*** should return a boolean
*/
bool CRandomSearch::initialize()
{
if (!COptMethod::initialize()) return false;
mIterations = * getValue("Number of Iterations").pUINT;
mpRandom = CRandom::createGenerator(* (CRandom::Type *) getValue("Random Number Generator").pUINT,
* getValue("Seed").pUINT);
mBestValue = DBL_MAX * 2.0;
mVariableSize = mpOptItem->size();
mIndividual.resize(mVariableSize);
return true;
}
#ifdef WIN32
# pragma warning (default: 4056 4756)
#endif
/**
* Optimizer Function
* Returns: nothing
//*** should return a boolean
*/
//C_INT32 CRandomSearch::optimise()
bool CRandomSearch::optimise()
{
bool linear;
if (!initialize()) return false;
C_FLOAT64 la, candx = DBL_MAX;
mIterations = * getValue("Number of Iterations").pUINT;
unsigned C_INT32 i, j;
C_FLOAT64 mn;
C_FLOAT64 mx;
for (i = 0; i < mIterations; i++)
{
for (j = 0; j < mVariableSize; j++)
{
// CALCULATE lower and upper bounds
COptItem & OptItem = *(*mpOptItem)[j];
mn = *OptItem.getLowerBoundValue();
mx = *OptItem.getUpperBoundValue();
C_FLOAT64 & mut = mIndividual[j];
try
{
// determine if linear or log scale
linear = false; la = 1.0;
if (mn == 0.0) mn = DBL_EPSILON;
if ((mn < 0.0) || (mx <= 0.0))
linear = true;
else
{
la = log10(mx) - log10(mn);
if (la < 1.8) linear = true;
}
// set it to a random value within the interval
if (linear)
mut = mn + mpRandom->getRandomCC() * (mx - mn);
else
mut = mn * pow(10, la * mpRandom->getRandomCC());
}
catch (...)
{
mut = (mx + mn) * 0.5;
}
// force it to be within the bounds
switch (OptItem.checkConstraint(mut))
{
case - 1:
mut = *OptItem.getLowerBoundValue();
if (!OptItem.checkLowerBound(mut)) // Inequality
{
if (mut == 0.0)
mut = DBL_MIN;
else
mut += mut * DBL_EPSILON;
}
break;
case 1:
mut = *OptItem.getUpperBoundValue();
if (!OptItem.checkUpperBound(mut)) // Inequality
{
if (mut == 0.0)
mut = - DBL_MIN;
else
mut -= mut * DBL_EPSILON;
}
break;
}
}
try
{
// calculate its fitness
mValue = evaluate(mIndividual);
}
catch (...)
{
mValue = DBL_MAX;
}
// COMPARE
if (mValue < mBestValue)
{
mBestValue = mValue;
mpOptProblem->setSolutionValue(mBestValue);
mpOptProblem->setSolutionVariables(mIndividual);
}
}
return 0;
}
// evaluate the fitness of one individual
C_FLOAT64 CRandomSearch::evaluate(const CVector< C_FLOAT64 > & individual)
{
unsigned C_INT32 j;
std::vector< UpdateMethod *>::const_iterator itMethod = mpSetCalculateVariable->begin();
// set the paramter values
for (j = 0; j < mVariableSize; j++, ++itMethod)
(**itMethod)(individual[j]);
// check whether the parametric constraints are fulfilled
if (!mpOptProblem->checkParametricConstraints()) return DBL_MAX;
// evaluate the fitness
try
{
if (!mpOptProblem->calculate()) return DBL_MAX;
}
catch (...)
{
return DBL_MAX;
}
// check wheter the functional constraints are fulfilled
if (!mpOptProblem->checkFunctionalConstraints()) return DBL_MAX;
return mpOptProblem->getCalculateValue();
}
<|endoftext|> |
<commit_before>
#ifndef AT_IPC_INTERFACE_H
#define AT_IPC_INTERFACE_H
// INCLUDES
#include <sys/types.h>
#include "atNotifier.h++"
class atIPCInterface : public atNotifier
{
public:
atIPCInterface();
virtual ~atIPCInterface();
virtual int read(u_char * buffer, u_long length) = 0;
virtual int write(u_char * buffer, u_long length) = 0;
};
#endif
<commit_msg>Made the communication classes be atItem's.<commit_after>
#ifndef AT_IPC_INTERFACE_H
#define AT_IPC_INTERFACE_H
// INCLUDES
#include <sys/types.h>
#include "atItem.h++"
class atIPCInterface : public atItem
{
public:
atIPCInterface();
virtual ~atIPCInterface();
virtual int read(u_char * buffer, u_long length) = 0;
virtual int write(u_char * buffer, u_long length) = 0;
};
#endif
<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* Copyright (c) FFLAS-FFPACK
* Written by Philippe LEDENT <philippe.ledent@etu.univ-grenoble-alpes.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>
#include <givaro/givrational.h>
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/paladin/parallel.h"
#include "fflas-ffpack/paladin/fflas_plevel1.h"
#include "fflas-ffpack/utils/args-parser.h"
using namespace std;
using namespace FFLAS;
using namespace FFPACK;
template<class Field>
typename Field::Element run_with_field(int q, size_t iter, size_t N, const size_t BS, const size_t p, const size_t threads){
Field F(q);
typename Field::RandIter G(F, BS);
typename Field::Element_ptr A, B;
typename Field::Element d; F.init(d);
Givaro::OMPTimer chrono, time; time.clear();
for (size_t i=0;i<iter;++i){
A = fflas_new(F, N);
B = fflas_new(F, N);
PAR_BLOCK { pfrand(F, G, N, 1, A); pfrand(F, G, N, 1, B); }
// FFLAS::WriteMatrix(std::cerr, F, 1, N, A, 1);
// FFLAS::WriteMatrix(std::cerr, F, 1, N, B, 1);
F.assign(d, F.zero);
FFLAS::ParSeqHelper::Parallel<
FFLAS::CuttingStrategy::Block,
FFLAS::StrategyParameter::Threads> ParHelper(threads);
chrono.clear();
if (p){
chrono.start();
F.assign(d, fdot(F, N, A, 1U, B, 1U, ParHelper));
chrono.stop();
} else {
chrono.start();
F.assign(d, fdot(F, N, A, 1U, B, 1U, FFLAS::ParSeqHelper::Sequential()));
chrono.stop();
}
std::cerr << chrono
<< " Gfops: " << ((double(2*N)/1000.)/1000.)/(1000.*chrono.realtime())
<< std::endl;
time+=chrono;
FFLAS::fflas_delete(A);
FFLAS::fflas_delete(B);
}
// -----------
// Standard output for benchmark
std::cout << "Time * " << iter << ": " << time
<< " Gfops: " << ((double(2*N)/1000.)/1000.)/(1000.*time.realtime())* double(iter);
// F.write(std::cerr, d) << std::endl;
return d;
}
int main(int argc, char** argv) {
size_t iter = 3;
size_t N = 5000;
size_t BS = 5000;
int q = 131071101;
size_t p =0;
size_t maxallowed_threads; PAR_BLOCK { maxallowed_threads=NUM_THREADS; }
size_t threads=maxallowed_threads;
Argument as[] = {
{ 'n', "-n N", "Set the dimension of the matrix C.",TYPE_INT , &N },
{ 'q', "-q Q", "Set the field characteristic (0 for the integers).", TYPE_INT , &q },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 'b', "-b B", "Set the bitsize of the random elements.", TYPE_INT , &BS},
{ 'p', "-p P", "0 for sequential, 1 for parallel.", TYPE_INT , &p },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &threads },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
if (q > 0){
BS = Givaro::Integer(q).bitsize();
double d = run_with_field<Givaro::ModularBalanced<double> >(q, iter, N, BS, p, threads);
std::cout << ", d: " << d;
} else {
auto d = run_with_field<Givaro::ZRing<Givaro::Integer> > (q, iter, N, BS, p, threads);
std::cout << ", size: " << logtwo(d>0?d:-d);
}
FFLAS::writeCommandString(std::cerr, as) << std::endl;
return 0;
}
<commit_msg>fix bug when GIVARO does not use OMP<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* Copyright (c) FFLAS-FFPACK
* Written by Philippe LEDENT <philippe.ledent@etu.univ-grenoble-alpes.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>
#include <givaro/givrational.h>
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/paladin/parallel.h"
#include "fflas-ffpack/paladin/fflas_plevel1.h"
#include "fflas-ffpack/utils/args-parser.h"
using namespace std;
using namespace FFLAS;
using namespace FFPACK;
template<class Field>
typename Field::Element run_with_field(int q, size_t iter, size_t N, const size_t BS, const size_t p, const size_t threads){
Field F(q);
typename Field::RandIter G(F, BS);
typename Field::Element_ptr A, B;
typename Field::Element d; F.init(d);
#ifdef__GIVARO_USE_OPENMP
Givaro::OMPTimer chrono, time;
#else
Givaro::Timer chrono, time;
#endif
time.clear();
for (size_t i=0;i<iter;++i){
A = fflas_new(F, N);
B = fflas_new(F, N);
PAR_BLOCK { pfrand(F, G, N, 1, A); pfrand(F, G, N, 1, B); }
// FFLAS::WriteMatrix(std::cerr, F, 1, N, A, 1);
// FFLAS::WriteMatrix(std::cerr, F, 1, N, B, 1);
F.assign(d, F.zero);
FFLAS::ParSeqHelper::Parallel<
FFLAS::CuttingStrategy::Block,
FFLAS::StrategyParameter::Threads> ParHelper(threads);
chrono.clear();
if (p){
chrono.start();
F.assign(d, fdot(F, N, A, 1U, B, 1U, ParHelper));
chrono.stop();
} else {
chrono.start();
F.assign(d, fdot(F, N, A, 1U, B, 1U, FFLAS::ParSeqHelper::Sequential()));
chrono.stop();
}
std::cerr << chrono
<< " Gfops: " << ((double(2*N)/1000.)/1000.)/(1000.*chrono.realtime())
<< std::endl;
time+=chrono;
FFLAS::fflas_delete(A);
FFLAS::fflas_delete(B);
}
// -----------
// Standard output for benchmark
std::cout << "Time * " << iter << ": " << time
<< " Gfops: " << ((double(2*N)/1000.)/1000.)/(1000.*time.realtime())* double(iter);
// F.write(std::cerr, d) << std::endl;
return d;
}
int main(int argc, char** argv) {
size_t iter = 3;
size_t N = 5000;
size_t BS = 5000;
int q = 131071101;
size_t p =0;
size_t maxallowed_threads; PAR_BLOCK { maxallowed_threads=NUM_THREADS; }
size_t threads=maxallowed_threads;
Argument as[] = {
{ 'n', "-n N", "Set the dimension of the matrix C.",TYPE_INT , &N },
{ 'q', "-q Q", "Set the field characteristic (0 for the integers).", TYPE_INT , &q },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 'b', "-b B", "Set the bitsize of the random elements.", TYPE_INT , &BS},
{ 'p', "-p P", "0 for sequential, 1 for parallel.", TYPE_INT , &p },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &threads },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
if (q > 0){
BS = Givaro::Integer(q).bitsize();
double d = run_with_field<Givaro::ModularBalanced<double> >(q, iter, N, BS, p, threads);
std::cout << ", d: " << d;
} else {
auto d = run_with_field<Givaro::ZRing<Givaro::Integer> > (q, iter, N, BS, p, threads);
std::cout << ", size: " << logtwo(d>0?d:-d);
}
FFLAS::writeCommandString(std::cerr, as) << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: sectctr.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:58:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SV_SECTCTR_HXX
#define _SV_SECTCTR_HXX
#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
class ImplSplitWindow;
class ScrollBar;
class ScrollBarBox;
class SvSection;
#define SECTION_APPEND ((USHORT)0xFFFF)
#define SECTION_NOTFOUND ((USHORT)0xFFFF)
#define WB_SECTION_STYLE WB_VSCROLL | WB_HSCROLL | WB_TABSTOP
class SvSectionControl : public Control
{
private:
Window aSplitWinContainer;
ImplSplitWindow* pSplitWin;
ScrollBar* pVScrollBar;
ScrollBar* pHScrollBar;
ScrollBarBox* pScrollBarBox;
DockingWindow* pDummy;
long nRealHeight;
long nMaxHeight;
long nMinWidth;
Wallpaper aWallpaper;
DECL_LINK( ScrollHdl, ScrollBar* );
DECL_LINK( EndScrollHdl, ScrollBar* );
protected:
virtual void Resize();
virtual void Paint( const Rectangle& rRect );
virtual void StateChanged( StateChangedType nStateChange );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual void Command( const CommandEvent& rCEvt );
virtual long PreNotify( NotifyEvent& rNEvt );
virtual long Notify( NotifyEvent& rNEvt );
virtual long KeyEventNotify( const KeyEvent& rKEvt );
virtual void SetPosSizePixel( long nX, long nY,long nWidth, long nHeight,USHORT nFlags);
long CalcMaxHeight();
long CalcRealHeight();
long CalcSectionWidth();
void SetScrollBars(BOOL bVert,BOOL bHorz);
void ShowScrollBarBox();
void UpdateScrollBars();
BOOL VScrollResize(Size &aSize);
BOOL HScrollResize(Size &aSize);
void SetChildPos(long nPos, BOOL bScrolling = TRUE);
public:
SvSectionControl( Window* pParent,WinBits nStyle = WB_SECTION_STYLE);
SvSectionControl( Window* pParent, const ResId& rResId );
~SvSectionControl();
void InsertSection( USHORT nSectionId,SvSection* pSection,long nSize,USHORT nPos);
void InsertSection( USHORT nSectionId,SvSection* pSection,USHORT nPos);
void RemoveSection( USHORT nSectionId );
void Clear();
USHORT GetSectionCount() const;
USHORT GetSectionId( USHORT nPos ) const;
USHORT GetSectionPos( USHORT nSectionId ) const;
USHORT GetSectionId( const Point& rPos ) const;
void SetSectionSize( USHORT nId, long nNewSize );
long GetSectionSize( USHORT nId ) const;
/*
void SetCurSectionId( USHORT nSectionId );
USHORT GetCurSectionId() const;
void SetFirstSectionId( USHORT nSectionId );
USHORT GetFirstSectionId() const { return GetSectionId( mnFirstSectionPos ); }
void MakeVisible( USHORT nSectionId );
*/
void SetSectionWidth( USHORT nSectionId, long nWidth);
long GetSectionWidth( USHORT nSectionId ) const;
void SetSection( USHORT nSectionId, SvSection* pPage );
SvSection* GetSection( USHORT nSectionId ) const;
void SetSectionText( USHORT nSectionId, const XubString& rText );
XubString GetSectionText( USHORT nSectionId ) const;
void SetHelpText( USHORT nSectionId, const XubString& rText );
const XubString& GetHelpText( USHORT nSectionId ) const;
void SetHelpId( USHORT nSectionId, ULONG nHelpId );
ULONG GetHelpId( USHORT nSectionId ) const;
void SetHelpText( const XubString& rText )
{ Control::SetHelpText( rText ); }
const XubString& GetHelpText() const
{ return Control::GetHelpText(); }
void SetHelpId( ULONG nId )
{ Control::SetHelpId( nId ); }
ULONG GetHelpId() const
{ return Control::GetHelpId(); }
void SetBackground( const Wallpaper& rBackground ){aWallpaper=rBackground; }
const Wallpaper& GetBackground() const { return aWallpaper; }
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1110); FILE MERGED 2005/09/05 14:51:02 rt 1.1.1.1.1110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sectctr.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 10:17:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SV_SECTCTR_HXX
#define _SV_SECTCTR_HXX
#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
class ImplSplitWindow;
class ScrollBar;
class ScrollBarBox;
class SvSection;
#define SECTION_APPEND ((USHORT)0xFFFF)
#define SECTION_NOTFOUND ((USHORT)0xFFFF)
#define WB_SECTION_STYLE WB_VSCROLL | WB_HSCROLL | WB_TABSTOP
class SvSectionControl : public Control
{
private:
Window aSplitWinContainer;
ImplSplitWindow* pSplitWin;
ScrollBar* pVScrollBar;
ScrollBar* pHScrollBar;
ScrollBarBox* pScrollBarBox;
DockingWindow* pDummy;
long nRealHeight;
long nMaxHeight;
long nMinWidth;
Wallpaper aWallpaper;
DECL_LINK( ScrollHdl, ScrollBar* );
DECL_LINK( EndScrollHdl, ScrollBar* );
protected:
virtual void Resize();
virtual void Paint( const Rectangle& rRect );
virtual void StateChanged( StateChangedType nStateChange );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual void Command( const CommandEvent& rCEvt );
virtual long PreNotify( NotifyEvent& rNEvt );
virtual long Notify( NotifyEvent& rNEvt );
virtual long KeyEventNotify( const KeyEvent& rKEvt );
virtual void SetPosSizePixel( long nX, long nY,long nWidth, long nHeight,USHORT nFlags);
long CalcMaxHeight();
long CalcRealHeight();
long CalcSectionWidth();
void SetScrollBars(BOOL bVert,BOOL bHorz);
void ShowScrollBarBox();
void UpdateScrollBars();
BOOL VScrollResize(Size &aSize);
BOOL HScrollResize(Size &aSize);
void SetChildPos(long nPos, BOOL bScrolling = TRUE);
public:
SvSectionControl( Window* pParent,WinBits nStyle = WB_SECTION_STYLE);
SvSectionControl( Window* pParent, const ResId& rResId );
~SvSectionControl();
void InsertSection( USHORT nSectionId,SvSection* pSection,long nSize,USHORT nPos);
void InsertSection( USHORT nSectionId,SvSection* pSection,USHORT nPos);
void RemoveSection( USHORT nSectionId );
void Clear();
USHORT GetSectionCount() const;
USHORT GetSectionId( USHORT nPos ) const;
USHORT GetSectionPos( USHORT nSectionId ) const;
USHORT GetSectionId( const Point& rPos ) const;
void SetSectionSize( USHORT nId, long nNewSize );
long GetSectionSize( USHORT nId ) const;
/*
void SetCurSectionId( USHORT nSectionId );
USHORT GetCurSectionId() const;
void SetFirstSectionId( USHORT nSectionId );
USHORT GetFirstSectionId() const { return GetSectionId( mnFirstSectionPos ); }
void MakeVisible( USHORT nSectionId );
*/
void SetSectionWidth( USHORT nSectionId, long nWidth);
long GetSectionWidth( USHORT nSectionId ) const;
void SetSection( USHORT nSectionId, SvSection* pPage );
SvSection* GetSection( USHORT nSectionId ) const;
void SetSectionText( USHORT nSectionId, const XubString& rText );
XubString GetSectionText( USHORT nSectionId ) const;
void SetHelpText( USHORT nSectionId, const XubString& rText );
const XubString& GetHelpText( USHORT nSectionId ) const;
void SetHelpId( USHORT nSectionId, ULONG nHelpId );
ULONG GetHelpId( USHORT nSectionId ) const;
void SetHelpText( const XubString& rText )
{ Control::SetHelpText( rText ); }
const XubString& GetHelpText() const
{ return Control::GetHelpText(); }
void SetHelpId( ULONG nId )
{ Control::SetHelpId( nId ); }
ULONG GetHelpId() const
{ return Control::GetHelpId(); }
void SetBackground( const Wallpaper& rBackground ){aWallpaper=rBackground; }
const Wallpaper& GetBackground() const { return aWallpaper; }
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unoimap.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 14:13:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVTOOLS_UNOIMAP_HXX
#define _SVTOOLS_UNOIMAP_HXX
#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
class ImageMap;
struct SvEventDescription;
SVT_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvUnoImageMapRectangleObject_createInstance( const SvEventDescription* pSupportedMacroItems );
SVT_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvUnoImageMapCircleObject_createInstance( const SvEventDescription* pSupportedMacroItems );
SVT_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvUnoImageMapPolygonObject_createInstance( const SvEventDescription* pSupportedMacroItems );
SVT_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvUnoImageMap_createInstance( const SvEventDescription* pSupportedMacroItems );
SVT_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvUnoImageMap_createInstance( const ImageMap& rMap, const SvEventDescription* pSupportedMacroItems );
SVT_DLLPUBLIC sal_Bool SvUnoImageMap_fillImageMap( com::sun::star::uno::Reference< com::sun::star::uno::XInterface > xImageMap, ImageMap& rMap );
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.774); FILE MERGED 2008/04/01 12:43:09 thb 1.3.774.2: #i85898# Stripping all external header guards 2008/03/31 13:00:57 rt 1.3.774.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unoimap.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVTOOLS_UNOIMAP_HXX
#define _SVTOOLS_UNOIMAP_HXX
#include "svtools/svtdllapi.h"
#include <com/sun/star/uno/XInterface.hpp>
class ImageMap;
struct SvEventDescription;
SVT_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvUnoImageMapRectangleObject_createInstance( const SvEventDescription* pSupportedMacroItems );
SVT_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvUnoImageMapCircleObject_createInstance( const SvEventDescription* pSupportedMacroItems );
SVT_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvUnoImageMapPolygonObject_createInstance( const SvEventDescription* pSupportedMacroItems );
SVT_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvUnoImageMap_createInstance( const SvEventDescription* pSupportedMacroItems );
SVT_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SvUnoImageMap_createInstance( const ImageMap& rMap, const SvEventDescription* pSupportedMacroItems );
SVT_DLLPUBLIC sal_Bool SvUnoImageMap_fillImageMap( com::sun::star::uno::Reference< com::sun::star::uno::XInterface > xImageMap, ImageMap& rMap );
#endif
<|endoftext|> |
<commit_before>//===--- LiveRangeEdit.cpp - Basic tools for editing a register live range --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The LiveRangeEdit class represents changes done to a virtual register when it
// is spilled or split.
//===----------------------------------------------------------------------===//
#include "LiveRangeEdit.h"
#include "VirtRegMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
LiveInterval &LiveRangeEdit::create(MachineRegisterInfo &mri,
LiveIntervals &lis,
VirtRegMap &vrm) {
const TargetRegisterClass *RC = mri.getRegClass(getReg());
unsigned VReg = mri.createVirtualRegister(RC);
vrm.grow();
vrm.setIsSplitFromReg(VReg, vrm.getOriginal(getReg()));
LiveInterval &li = lis.getOrCreateInterval(VReg);
newRegs_.push_back(&li);
return li;
}
void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
const TargetInstrInfo &tii,
AliasAnalysis *aa) {
for (LiveInterval::vni_iterator I = parent_.vni_begin(),
E = parent_.vni_end(); I != E; ++I) {
VNInfo *VNI = *I;
if (VNI->isUnused())
continue;
MachineInstr *DefMI = lis.getInstructionFromIndex(VNI->def);
if (!DefMI)
continue;
if (tii.isTriviallyReMaterializable(DefMI, aa))
remattable_.insert(VNI);
}
scannedRemattable_ = true;
}
bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
const TargetInstrInfo &tii,
AliasAnalysis *aa) {
if (!scannedRemattable_)
scanRemattable(lis, tii, aa);
return !remattable_.empty();
}
/// allUsesAvailableAt - Return true if all registers used by OrigMI at
/// OrigIdx are also available with the same value at UseIdx.
bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
SlotIndex OrigIdx,
SlotIndex UseIdx,
LiveIntervals &lis) {
OrigIdx = OrigIdx.getUseIndex();
UseIdx = UseIdx.getUseIndex();
for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = OrigMI->getOperand(i);
if (!MO.isReg() || !MO.getReg() || MO.getReg() == getReg())
continue;
// Reserved registers are OK.
if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
continue;
// We don't want to move any defs.
if (MO.isDef())
return false;
// We cannot depend on virtual registers in uselessRegs_.
if (uselessRegs_)
for (unsigned ui = 0, ue = uselessRegs_->size(); ui != ue; ++ui)
if ((*uselessRegs_)[ui]->reg == MO.getReg())
return false;
LiveInterval &li = lis.getInterval(MO.getReg());
const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
if (!OVNI)
continue;
if (OVNI != li.getVNInfoAt(UseIdx))
return false;
}
return true;
}
bool LiveRangeEdit::canRematerializeAt(Remat &RM,
SlotIndex UseIdx,
bool cheapAsAMove,
LiveIntervals &lis) {
assert(scannedRemattable_ && "Call anyRematerializable first");
// Use scanRemattable info.
if (!remattable_.count(RM.ParentVNI))
return false;
// No defining instruction.
RM.OrigMI = lis.getInstructionFromIndex(RM.ParentVNI->def);
assert(RM.OrigMI && "Defining instruction for remattable value disappeared");
// If only cheap remats were requested, bail out early.
if (cheapAsAMove && !RM.OrigMI->getDesc().isAsCheapAsAMove())
return false;
// Verify that all used registers are available with the same values.
if (!allUsesAvailableAt(RM.OrigMI, RM.ParentVNI->def, UseIdx, lis))
return false;
return true;
}
SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg,
const Remat &RM,
LiveIntervals &lis,
const TargetInstrInfo &tii,
const TargetRegisterInfo &tri) {
assert(RM.OrigMI && "Invalid remat");
tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
rematted_.insert(RM.ParentVNI);
return lis.InsertMachineInstrInMaps(--MI).getDefIndex();
}
void LiveRangeEdit::eraseVirtReg(unsigned Reg, LiveIntervals &LIS) {
if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
LIS.removeInterval(Reg);
}
void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
LiveIntervals &LIS,
const TargetInstrInfo &TII) {
SetVector<LiveInterval*,
SmallVector<LiveInterval*, 8>,
SmallPtrSet<LiveInterval*, 8> > ToShrink;
for (;;) {
// Erase all dead defs.
while (!Dead.empty()) {
MachineInstr *MI = Dead.pop_back_val();
assert(MI->allDefsAreDead() && "Def isn't really dead");
SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
// Never delete inline asm.
if (MI->isInlineAsm()) {
DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
continue;
}
// Use the same criteria as DeadMachineInstructionElim.
bool SawStore = false;
if (!MI->isSafeToMove(&TII, 0, SawStore)) {
DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
continue;
}
DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
// Check for live intervals that may shrink
for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
MOE = MI->operands_end(); MOI != MOE; ++MOI) {
if (!MOI->isReg())
continue;
unsigned Reg = MOI->getReg();
if (!TargetRegisterInfo::isVirtualRegister(Reg))
continue;
LiveInterval &LI = LIS.getInterval(Reg);
// Remove defined value.
if (MOI->isDef())
if (VNInfo *VNI = LI.getVNInfoAt(Idx))
LI.removeValNo(VNI);
// Shrink read registers.
if (MI->readsVirtualRegister(Reg))
ToShrink.insert(&LI);
}
if (delegate_)
delegate_->LRE_WillEraseInstruction(MI);
LIS.RemoveMachineInstrFromMaps(MI);
MI->eraseFromParent();
}
if (ToShrink.empty())
break;
// Shrink just one live interval. Then delete new dead defs.
LIS.shrinkToUses(ToShrink.back(), &Dead);
ToShrink.pop_back();
}
}
<commit_msg>Erase virtual registers that are unused after DCE.<commit_after>//===--- LiveRangeEdit.cpp - Basic tools for editing a register live range --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The LiveRangeEdit class represents changes done to a virtual register when it
// is spilled or split.
//===----------------------------------------------------------------------===//
#include "LiveRangeEdit.h"
#include "VirtRegMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
LiveInterval &LiveRangeEdit::create(MachineRegisterInfo &mri,
LiveIntervals &lis,
VirtRegMap &vrm) {
const TargetRegisterClass *RC = mri.getRegClass(getReg());
unsigned VReg = mri.createVirtualRegister(RC);
vrm.grow();
vrm.setIsSplitFromReg(VReg, vrm.getOriginal(getReg()));
LiveInterval &li = lis.getOrCreateInterval(VReg);
newRegs_.push_back(&li);
return li;
}
void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
const TargetInstrInfo &tii,
AliasAnalysis *aa) {
for (LiveInterval::vni_iterator I = parent_.vni_begin(),
E = parent_.vni_end(); I != E; ++I) {
VNInfo *VNI = *I;
if (VNI->isUnused())
continue;
MachineInstr *DefMI = lis.getInstructionFromIndex(VNI->def);
if (!DefMI)
continue;
if (tii.isTriviallyReMaterializable(DefMI, aa))
remattable_.insert(VNI);
}
scannedRemattable_ = true;
}
bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
const TargetInstrInfo &tii,
AliasAnalysis *aa) {
if (!scannedRemattable_)
scanRemattable(lis, tii, aa);
return !remattable_.empty();
}
/// allUsesAvailableAt - Return true if all registers used by OrigMI at
/// OrigIdx are also available with the same value at UseIdx.
bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
SlotIndex OrigIdx,
SlotIndex UseIdx,
LiveIntervals &lis) {
OrigIdx = OrigIdx.getUseIndex();
UseIdx = UseIdx.getUseIndex();
for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = OrigMI->getOperand(i);
if (!MO.isReg() || !MO.getReg() || MO.getReg() == getReg())
continue;
// Reserved registers are OK.
if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
continue;
// We don't want to move any defs.
if (MO.isDef())
return false;
// We cannot depend on virtual registers in uselessRegs_.
if (uselessRegs_)
for (unsigned ui = 0, ue = uselessRegs_->size(); ui != ue; ++ui)
if ((*uselessRegs_)[ui]->reg == MO.getReg())
return false;
LiveInterval &li = lis.getInterval(MO.getReg());
const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
if (!OVNI)
continue;
if (OVNI != li.getVNInfoAt(UseIdx))
return false;
}
return true;
}
bool LiveRangeEdit::canRematerializeAt(Remat &RM,
SlotIndex UseIdx,
bool cheapAsAMove,
LiveIntervals &lis) {
assert(scannedRemattable_ && "Call anyRematerializable first");
// Use scanRemattable info.
if (!remattable_.count(RM.ParentVNI))
return false;
// No defining instruction.
RM.OrigMI = lis.getInstructionFromIndex(RM.ParentVNI->def);
assert(RM.OrigMI && "Defining instruction for remattable value disappeared");
// If only cheap remats were requested, bail out early.
if (cheapAsAMove && !RM.OrigMI->getDesc().isAsCheapAsAMove())
return false;
// Verify that all used registers are available with the same values.
if (!allUsesAvailableAt(RM.OrigMI, RM.ParentVNI->def, UseIdx, lis))
return false;
return true;
}
SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg,
const Remat &RM,
LiveIntervals &lis,
const TargetInstrInfo &tii,
const TargetRegisterInfo &tri) {
assert(RM.OrigMI && "Invalid remat");
tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
rematted_.insert(RM.ParentVNI);
return lis.InsertMachineInstrInMaps(--MI).getDefIndex();
}
void LiveRangeEdit::eraseVirtReg(unsigned Reg, LiveIntervals &LIS) {
if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
LIS.removeInterval(Reg);
}
void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
LiveIntervals &LIS,
const TargetInstrInfo &TII) {
SetVector<LiveInterval*,
SmallVector<LiveInterval*, 8>,
SmallPtrSet<LiveInterval*, 8> > ToShrink;
for (;;) {
// Erase all dead defs.
while (!Dead.empty()) {
MachineInstr *MI = Dead.pop_back_val();
assert(MI->allDefsAreDead() && "Def isn't really dead");
SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
// Never delete inline asm.
if (MI->isInlineAsm()) {
DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
continue;
}
// Use the same criteria as DeadMachineInstructionElim.
bool SawStore = false;
if (!MI->isSafeToMove(&TII, 0, SawStore)) {
DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
continue;
}
DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
// Check for live intervals that may shrink
for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
MOE = MI->operands_end(); MOI != MOE; ++MOI) {
if (!MOI->isReg())
continue;
unsigned Reg = MOI->getReg();
if (!TargetRegisterInfo::isVirtualRegister(Reg))
continue;
LiveInterval &LI = LIS.getInterval(Reg);
// Shrink read registers.
if (MI->readsVirtualRegister(Reg))
ToShrink.insert(&LI);
// Remove defined value.
if (MOI->isDef()) {
if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
LI.removeValNo(VNI);
if (LI.empty()) {
ToShrink.remove(&LI);
eraseVirtReg(Reg, LIS);
}
}
}
}
if (delegate_)
delegate_->LRE_WillEraseInstruction(MI);
LIS.RemoveMachineInstrFromMaps(MI);
MI->eraseFromParent();
}
if (ToShrink.empty())
break;
// Shrink just one live interval. Then delete new dead defs.
LIS.shrinkToUses(ToShrink.back(), &Dead);
ToShrink.pop_back();
}
}
<|endoftext|> |
<commit_before>//===-- RegAllocBasic.cpp - basic register allocator ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the RABasic function pass, which provides a minimal
// implementation of the basic register allocator.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "regalloc"
#include "LiveIntervalUnion.h"
#include "RegAllocBase.h"
#include "RenderMachineFunction.h"
#include "Spiller.h"
#include "VirtRegRewriter.h"
#include "llvm/Function.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/CodeGen/CalcSpillWeights.h"
#include "llvm/CodeGen/LiveStackAnalysis.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/RegisterCoalescer.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "VirtRegMap.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include <vector>
#include <queue>
using namespace llvm;
static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
createBasicRegisterAllocator);
namespace {
/// RABasic provides a minimal implementation of the basic register allocation
/// algorithm. It prioritizes live virtual registers by spill weight and spills
/// whenever a register is unavailable. This is not practical in production but
/// provides a useful baseline both for measuring other allocators and comparing
/// the speed of the basic algorithm against other styles of allocators.
class RABasic : public MachineFunctionPass, public RegAllocBase
{
// context
MachineFunction *mf_;
const TargetMachine *tm_;
MachineRegisterInfo *mri_;
// analyses
LiveStacks *ls_;
RenderMachineFunction *rmf_;
// state
std::auto_ptr<Spiller> spiller_;
public:
RABasic();
/// Return the pass name.
virtual const char* getPassName() const {
return "Basic Register Allocator";
}
/// RABasic analysis usage.
virtual void getAnalysisUsage(AnalysisUsage &au) const;
virtual void releaseMemory();
virtual unsigned selectOrSplit(LiveInterval &lvr,
SmallVectorImpl<LiveInterval*> &splitLVRs);
/// Perform register allocation.
virtual bool runOnMachineFunction(MachineFunction &mf);
static char ID;
};
char RABasic::ID = 0;
} // end anonymous namespace
// We should not need to publish the initializer as long as no other passes
// require RABasic.
#if 0 // disable INITIALIZE_PASS
INITIALIZE_PASS_BEGIN(RABasic, "basic-regalloc",
"Basic Register Allocator", false, false)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
INITIALIZE_PASS_DEPENDENCY(LiveStacks)
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
#ifndef NDEBUG
INITIALIZE_PASS_DEPENDENCY(RenderMachineFunction)
#endif
INITIALIZE_PASS_END(RABasic, "basic-regalloc",
"Basic Register Allocator", false, false)
#endif // disable INITIALIZE_PASS
RABasic::RABasic(): MachineFunctionPass(ID) {
initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
initializeLiveStacksPass(*PassRegistry::getPassRegistry());
initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
}
void RABasic::getAnalysisUsage(AnalysisUsage &au) const {
au.setPreservesCFG();
au.addRequired<LiveIntervals>();
au.addPreserved<SlotIndexes>();
if (StrongPHIElim)
au.addRequiredID(StrongPHIEliminationID);
au.addRequiredTransitive<RegisterCoalescer>();
au.addRequired<CalculateSpillWeights>();
au.addRequired<LiveStacks>();
au.addPreserved<LiveStacks>();
au.addRequired<MachineLoopInfo>();
au.addPreserved<MachineLoopInfo>();
au.addRequired<VirtRegMap>();
au.addPreserved<VirtRegMap>();
DEBUG(au.addRequired<RenderMachineFunction>());
MachineFunctionPass::getAnalysisUsage(au);
}
void RABasic::releaseMemory() {
spiller_.reset(0);
RegAllocBase::releaseMemory();
}
//===----------------------------------------------------------------------===//
// RegAllocBase Implementation
//===----------------------------------------------------------------------===//
// Instantiate a LiveIntervalUnion for each physical register.
void RegAllocBase::LIUArray::init(unsigned nRegs) {
array_.reset(new LiveIntervalUnion[nRegs]);
nRegs_ = nRegs;
for (unsigned pr = 0; pr < nRegs; ++pr) {
array_[pr].init(pr);
}
}
void RegAllocBase::init(const TargetRegisterInfo &tri, VirtRegMap &vrm,
LiveIntervals &lis) {
tri_ = &tri;
vrm_ = &vrm;
lis_ = &lis;
physReg2liu_.init(tri_->getNumRegs());
}
void RegAllocBase::LIUArray::clear() {
nRegs_ = 0;
array_.reset(0);
}
void RegAllocBase::releaseMemory() {
physReg2liu_.clear();
}
namespace llvm {
/// This class defines a queue of live virtual registers prioritized by spill
/// weight. The heaviest vreg is popped first.
///
/// Currently, this is trivial wrapper that gives us an opaque type in the
/// header, but we may later give it a virtual interface for register allocators
/// to override the priority queue comparator.
class LiveVirtRegQueue {
typedef std::priority_queue
<LiveInterval*, std::vector<LiveInterval*>, LessSpillWeightPriority> PQ;
PQ pq_;
public:
// Is the queue empty?
bool empty() { return pq_.empty(); }
// Get the highest priority lvr (top + pop)
LiveInterval *get() {
LiveInterval *lvr = pq_.top();
pq_.pop();
return lvr;
}
// Add this lvr to the queue
void push(LiveInterval *lvr) {
pq_.push(lvr);
}
};
} // end namespace llvm
// Visit all the live virtual registers. If they are already assigned to a
// physical register, unify them with the corresponding LiveIntervalUnion,
// otherwise push them on the priority queue for later assignment.
void RegAllocBase::seedLiveVirtRegs(LiveVirtRegQueue &lvrQ) {
for (LiveIntervals::iterator liItr = lis_->begin(), liEnd = lis_->end();
liItr != liEnd; ++liItr) {
unsigned reg = liItr->first;
LiveInterval &li = *liItr->second;
if (TargetRegisterInfo::isPhysicalRegister(reg)) {
physReg2liu_[reg].unify(li);
}
else {
lvrQ.push(&li);
}
}
}
// Top-level driver to manage the queue of unassigned LiveVirtRegs and call the
// selectOrSplit implementation.
void RegAllocBase::allocatePhysRegs() {
LiveVirtRegQueue lvrQ;
seedLiveVirtRegs(lvrQ);
while (!lvrQ.empty()) {
LiveInterval *lvr = lvrQ.get();
typedef SmallVector<LiveInterval*, 4> LVRVec;
LVRVec splitLVRs;
unsigned availablePhysReg = selectOrSplit(*lvr, splitLVRs);
if (availablePhysReg) {
assert(splitLVRs.empty() && "inconsistent splitting");
assert(!vrm_->hasPhys(lvr->reg) && "duplicate vreg in interval unions");
vrm_->assignVirt2Phys(lvr->reg, availablePhysReg);
physReg2liu_[availablePhysReg].unify(*lvr);
}
else {
for (LVRVec::iterator lvrI = splitLVRs.begin(), lvrEnd = splitLVRs.end();
lvrI != lvrEnd; ++lvrI) {
assert(TargetRegisterInfo::isVirtualRegister((*lvrI)->reg) &&
"expect split value in virtual register");
lvrQ.push(*lvrI);
}
}
}
}
// Check if this live virtual reg interferes with a physical register. If not,
// then check for interference on each register that aliases with the physical
// register.
bool RegAllocBase::checkPhysRegInterference(LiveIntervalUnion::Query &query,
unsigned preg) {
if (query.checkInterference())
return true;
for (const unsigned *asI = tri_->getAliasSet(preg); *asI; ++asI) {
// We assume it's very unlikely for a register in the alias set to also be
// in the original register class. So we don't bother caching the
// interference.
LiveIntervalUnion::Query subQuery(query.lvr(), physReg2liu_[*asI] );
if (subQuery.checkInterference())
return true;
}
return false;
}
//===----------------------------------------------------------------------===//
// RABasic Implementation
//===----------------------------------------------------------------------===//
// Driver for the register assignment and splitting heuristics.
// Manages iteration over the LiveIntervalUnions.
//
// Minimal implementation of register assignment and splitting--spills whenever
// we run out of registers.
//
// selectOrSplit can only be called once per live virtual register. We then do a
// single interference test for each register the correct class until we find an
// available register. So, the number of interference tests in the worst case is
// |vregs| * |machineregs|. And since the number of interference tests is
// minimal, there is no value in caching them.
unsigned RABasic::selectOrSplit(LiveInterval &lvr,
SmallVectorImpl<LiveInterval*> &splitLVRs) {
// Check for an available reg in this class.
const TargetRegisterClass *trc = mri_->getRegClass(lvr.reg);
for (TargetRegisterClass::iterator trcI = trc->allocation_order_begin(*mf_),
trcEnd = trc->allocation_order_end(*mf_);
trcI != trcEnd; ++trcI) {
unsigned preg = *trcI;
LiveIntervalUnion::Query query(lvr, physReg2liu_[preg]);
if (!checkPhysRegInterference(query, preg)) {
DEBUG(dbgs() << "\tallocating: " << tri_->getName(preg) << lvr << '\n');
return preg;
}
}
DEBUG(dbgs() << "\tspilling: " << lvr << '\n');
SmallVector<LiveInterval*, 1> spillIs; // ignored
spiller_->spill(&lvr, splitLVRs, spillIs);
// FIXME: update LiveStacks
return 0;
}
bool RABasic::runOnMachineFunction(MachineFunction &mf) {
DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
<< "********** Function: "
<< ((Value*)mf.getFunction())->getName() << '\n');
mf_ = &mf;
tm_ = &mf.getTarget();
mri_ = &mf.getRegInfo();
DEBUG(rmf_ = &getAnalysis<RenderMachineFunction>());
RegAllocBase::init(*tm_->getRegisterInfo(), getAnalysis<VirtRegMap>(),
getAnalysis<LiveIntervals>());
spiller_.reset(createSpiller(*this, *mf_, *vrm_));
allocatePhysRegs();
// Diagnostic output before rewriting
DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm_ << "\n");
// optional HTML output
DEBUG(rmf_->renderMachineFunction("After basic register allocation.", vrm_));
// Run rewriter
std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
rewriter->runOnMachineFunction(*mf_, *vrm_, lis_);
// The pass output is in VirtRegMap. Release all the transient data.
releaseMemory();
return true;
}
FunctionPass* llvm::createBasicRegisterAllocator()
{
return new RABasic();
}
<commit_msg>Let RegAllocBasic require MachineDominators - they are already available and splitting needs them.<commit_after>//===-- RegAllocBasic.cpp - basic register allocator ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the RABasic function pass, which provides a minimal
// implementation of the basic register allocator.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "regalloc"
#include "LiveIntervalUnion.h"
#include "RegAllocBase.h"
#include "RenderMachineFunction.h"
#include "Spiller.h"
#include "VirtRegRewriter.h"
#include "llvm/Function.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/CodeGen/CalcSpillWeights.h"
#include "llvm/CodeGen/LiveStackAnalysis.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/RegisterCoalescer.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "VirtRegMap.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include <vector>
#include <queue>
using namespace llvm;
static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
createBasicRegisterAllocator);
namespace {
/// RABasic provides a minimal implementation of the basic register allocation
/// algorithm. It prioritizes live virtual registers by spill weight and spills
/// whenever a register is unavailable. This is not practical in production but
/// provides a useful baseline both for measuring other allocators and comparing
/// the speed of the basic algorithm against other styles of allocators.
class RABasic : public MachineFunctionPass, public RegAllocBase
{
// context
MachineFunction *mf_;
const TargetMachine *tm_;
MachineRegisterInfo *mri_;
// analyses
LiveStacks *ls_;
RenderMachineFunction *rmf_;
// state
std::auto_ptr<Spiller> spiller_;
public:
RABasic();
/// Return the pass name.
virtual const char* getPassName() const {
return "Basic Register Allocator";
}
/// RABasic analysis usage.
virtual void getAnalysisUsage(AnalysisUsage &au) const;
virtual void releaseMemory();
virtual unsigned selectOrSplit(LiveInterval &lvr,
SmallVectorImpl<LiveInterval*> &splitLVRs);
/// Perform register allocation.
virtual bool runOnMachineFunction(MachineFunction &mf);
static char ID;
};
char RABasic::ID = 0;
} // end anonymous namespace
// We should not need to publish the initializer as long as no other passes
// require RABasic.
#if 0 // disable INITIALIZE_PASS
INITIALIZE_PASS_BEGIN(RABasic, "basic-regalloc",
"Basic Register Allocator", false, false)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
INITIALIZE_PASS_DEPENDENCY(LiveStacks)
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
#ifndef NDEBUG
INITIALIZE_PASS_DEPENDENCY(RenderMachineFunction)
#endif
INITIALIZE_PASS_END(RABasic, "basic-regalloc",
"Basic Register Allocator", false, false)
#endif // disable INITIALIZE_PASS
RABasic::RABasic(): MachineFunctionPass(ID) {
initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
initializeLiveStacksPass(*PassRegistry::getPassRegistry());
initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
}
void RABasic::getAnalysisUsage(AnalysisUsage &au) const {
au.setPreservesCFG();
au.addRequired<LiveIntervals>();
au.addPreserved<SlotIndexes>();
if (StrongPHIElim)
au.addRequiredID(StrongPHIEliminationID);
au.addRequiredTransitive<RegisterCoalescer>();
au.addRequired<CalculateSpillWeights>();
au.addRequired<LiveStacks>();
au.addPreserved<LiveStacks>();
au.addRequiredID(MachineDominatorsID);
au.addPreservedID(MachineDominatorsID);
au.addRequired<MachineLoopInfo>();
au.addPreserved<MachineLoopInfo>();
au.addRequired<VirtRegMap>();
au.addPreserved<VirtRegMap>();
DEBUG(au.addRequired<RenderMachineFunction>());
MachineFunctionPass::getAnalysisUsage(au);
}
void RABasic::releaseMemory() {
spiller_.reset(0);
RegAllocBase::releaseMemory();
}
//===----------------------------------------------------------------------===//
// RegAllocBase Implementation
//===----------------------------------------------------------------------===//
// Instantiate a LiveIntervalUnion for each physical register.
void RegAllocBase::LIUArray::init(unsigned nRegs) {
array_.reset(new LiveIntervalUnion[nRegs]);
nRegs_ = nRegs;
for (unsigned pr = 0; pr < nRegs; ++pr) {
array_[pr].init(pr);
}
}
void RegAllocBase::init(const TargetRegisterInfo &tri, VirtRegMap &vrm,
LiveIntervals &lis) {
tri_ = &tri;
vrm_ = &vrm;
lis_ = &lis;
physReg2liu_.init(tri_->getNumRegs());
}
void RegAllocBase::LIUArray::clear() {
nRegs_ = 0;
array_.reset(0);
}
void RegAllocBase::releaseMemory() {
physReg2liu_.clear();
}
namespace llvm {
/// This class defines a queue of live virtual registers prioritized by spill
/// weight. The heaviest vreg is popped first.
///
/// Currently, this is trivial wrapper that gives us an opaque type in the
/// header, but we may later give it a virtual interface for register allocators
/// to override the priority queue comparator.
class LiveVirtRegQueue {
typedef std::priority_queue
<LiveInterval*, std::vector<LiveInterval*>, LessSpillWeightPriority> PQ;
PQ pq_;
public:
// Is the queue empty?
bool empty() { return pq_.empty(); }
// Get the highest priority lvr (top + pop)
LiveInterval *get() {
LiveInterval *lvr = pq_.top();
pq_.pop();
return lvr;
}
// Add this lvr to the queue
void push(LiveInterval *lvr) {
pq_.push(lvr);
}
};
} // end namespace llvm
// Visit all the live virtual registers. If they are already assigned to a
// physical register, unify them with the corresponding LiveIntervalUnion,
// otherwise push them on the priority queue for later assignment.
void RegAllocBase::seedLiveVirtRegs(LiveVirtRegQueue &lvrQ) {
for (LiveIntervals::iterator liItr = lis_->begin(), liEnd = lis_->end();
liItr != liEnd; ++liItr) {
unsigned reg = liItr->first;
LiveInterval &li = *liItr->second;
if (TargetRegisterInfo::isPhysicalRegister(reg)) {
physReg2liu_[reg].unify(li);
}
else {
lvrQ.push(&li);
}
}
}
// Top-level driver to manage the queue of unassigned LiveVirtRegs and call the
// selectOrSplit implementation.
void RegAllocBase::allocatePhysRegs() {
LiveVirtRegQueue lvrQ;
seedLiveVirtRegs(lvrQ);
while (!lvrQ.empty()) {
LiveInterval *lvr = lvrQ.get();
typedef SmallVector<LiveInterval*, 4> LVRVec;
LVRVec splitLVRs;
unsigned availablePhysReg = selectOrSplit(*lvr, splitLVRs);
if (availablePhysReg) {
assert(splitLVRs.empty() && "inconsistent splitting");
assert(!vrm_->hasPhys(lvr->reg) && "duplicate vreg in interval unions");
vrm_->assignVirt2Phys(lvr->reg, availablePhysReg);
physReg2liu_[availablePhysReg].unify(*lvr);
}
else {
for (LVRVec::iterator lvrI = splitLVRs.begin(), lvrEnd = splitLVRs.end();
lvrI != lvrEnd; ++lvrI) {
assert(TargetRegisterInfo::isVirtualRegister((*lvrI)->reg) &&
"expect split value in virtual register");
lvrQ.push(*lvrI);
}
}
}
}
// Check if this live virtual reg interferes with a physical register. If not,
// then check for interference on each register that aliases with the physical
// register.
bool RegAllocBase::checkPhysRegInterference(LiveIntervalUnion::Query &query,
unsigned preg) {
if (query.checkInterference())
return true;
for (const unsigned *asI = tri_->getAliasSet(preg); *asI; ++asI) {
// We assume it's very unlikely for a register in the alias set to also be
// in the original register class. So we don't bother caching the
// interference.
LiveIntervalUnion::Query subQuery(query.lvr(), physReg2liu_[*asI] );
if (subQuery.checkInterference())
return true;
}
return false;
}
//===----------------------------------------------------------------------===//
// RABasic Implementation
//===----------------------------------------------------------------------===//
// Driver for the register assignment and splitting heuristics.
// Manages iteration over the LiveIntervalUnions.
//
// Minimal implementation of register assignment and splitting--spills whenever
// we run out of registers.
//
// selectOrSplit can only be called once per live virtual register. We then do a
// single interference test for each register the correct class until we find an
// available register. So, the number of interference tests in the worst case is
// |vregs| * |machineregs|. And since the number of interference tests is
// minimal, there is no value in caching them.
unsigned RABasic::selectOrSplit(LiveInterval &lvr,
SmallVectorImpl<LiveInterval*> &splitLVRs) {
// Check for an available reg in this class.
const TargetRegisterClass *trc = mri_->getRegClass(lvr.reg);
for (TargetRegisterClass::iterator trcI = trc->allocation_order_begin(*mf_),
trcEnd = trc->allocation_order_end(*mf_);
trcI != trcEnd; ++trcI) {
unsigned preg = *trcI;
LiveIntervalUnion::Query query(lvr, physReg2liu_[preg]);
if (!checkPhysRegInterference(query, preg)) {
DEBUG(dbgs() << "\tallocating: " << tri_->getName(preg) << lvr << '\n');
return preg;
}
}
DEBUG(dbgs() << "\tspilling: " << lvr << '\n');
SmallVector<LiveInterval*, 1> spillIs; // ignored
spiller_->spill(&lvr, splitLVRs, spillIs);
// FIXME: update LiveStacks
return 0;
}
bool RABasic::runOnMachineFunction(MachineFunction &mf) {
DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
<< "********** Function: "
<< ((Value*)mf.getFunction())->getName() << '\n');
mf_ = &mf;
tm_ = &mf.getTarget();
mri_ = &mf.getRegInfo();
DEBUG(rmf_ = &getAnalysis<RenderMachineFunction>());
RegAllocBase::init(*tm_->getRegisterInfo(), getAnalysis<VirtRegMap>(),
getAnalysis<LiveIntervals>());
spiller_.reset(createSpiller(*this, *mf_, *vrm_));
allocatePhysRegs();
// Diagnostic output before rewriting
DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm_ << "\n");
// optional HTML output
DEBUG(rmf_->renderMachineFunction("After basic register allocation.", vrm_));
// Run rewriter
std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
rewriter->runOnMachineFunction(*mf_, *vrm_, lis_);
// The pass output is in VirtRegMap. Release all the transient data.
releaseMemory();
return true;
}
FunctionPass* llvm::createBasicRegisterAllocator()
{
return new RABasic();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdedxv.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 16:19:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVDEDXV_HXX
#define _SVDEDXV_HXX
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
#ifndef _SVDGLEV_HXX
#include <svx/svdglev.hxx>
#endif
//************************************************************
// Vorausdeklarationen
//************************************************************
class SdrOutliner;
class OutlinerView;
class EditStatus;
class EditFieldInfo;
class ImpSdrEditPara;
namespace com { namespace sun { namespace star { namespace uno {
class Any;
} } } }
//************************************************************
// Defines
//************************************************************
enum SdrEndTextEditKind {SDRENDTEXTEDIT_UNCHANGED, // Textobjekt unveraendert
SDRENDTEXTEDIT_CHANGED, // Textobjekt wurde geaendert
SDRENDTEXTEDIT_DELETED, // Textobjekt implizit geloescht
SDRENDTEXTEDIT_SHOULDBEDELETED}; // Fuer Writer: Textobjekt sollte geloescht werden
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@@@ @@@@@ @@@@@@ @@@@@ @@@@@ @@ @@@@@@ @@ @@ @@ @@@@@ @@ @@
// @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@
// @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @ @@
// @@ @@ @@@@@ @@ @@@@ @@ @@ @@ @@ @@@@@ @@ @@@@ @@@@@@@
// @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@@@@@@
// @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@@ @@@
// @@@@ @@@@@ @@@@ @@@@@ @@@@@ @@ @@ @ @@ @@@@@ @@ @@
//
// - Allgemeines Edit fuer objektspeziefische Eigenschaften
// - Textedit fuer alle vom SdrTextObj abgeleiteten Zeichenobjekte
// - Macromodus
//
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
class SVX_DLLPUBLIC SdrObjEditView: public SdrGlueEditView
{
friend class SdrPageView;
friend class ImpSdrEditPara;
protected:
// TextEdit
SdrObjectWeakRef mxTextEditObj; // Aktuell im TextEdit befindliches Obj
SdrPageView* pTextEditPV;
SdrOutliner* pTextEditOutliner; // Na eben der Outliner fuers TextEdit
OutlinerView* pTextEditOutlinerView; // die aktuelle View des Outliners
Window* pTextEditWin; // passendes Win zu pTextEditOutlinerView
Cursor* pTextEditCursorMerker; // Zum Restaurieren des Cursors am jeweiligen Win
ImpSdrEditPara* pEditPara; // Da hau' ich erstmal alles rein um kompatibel zu bleiben...
SdrObject* pMacroObj;
SdrPageView* pMacroPV;
Window* pMacroWin;
Rectangle aTextEditArea;
Rectangle aMinTextEditArea;
Link aOldCalcFieldValueLink; // Zum rufen des alten Handlers
Point aMacroDownPos;
USHORT nMacroTol;
unsigned bTextEditDontDelete : 1; // Outliner und View bei SdrEndTextEdit nicht deleten (f. Rechtschreibpruefung)
unsigned bTextEditOnlyOneView : 1; // Nur eine OutlinerView (f. Rechtschreibpruefung)
unsigned bTextEditNewObj : 1; // Aktuell editiertes Objekt wurde gerade neu erzeugt
unsigned bQuickTextEditMode : 1; // persistent(->CrtV). Default=TRUE
unsigned bMacroMode : 1; // persistent(->CrtV). Default=TRUE
unsigned bMacroDown : 1;
private:
SVX_DLLPRIVATE void ImpClearVars();
protected:
OutlinerView* ImpFindOutlinerView(Window* pWin) const;
// Eine neue OutlinerView auf dem Heap anlegen und alle erforderlichen Parameter setzen.
// pTextEditObj, pTextEditPV und pTextEditOutliner muessen initiallisiert sein.
OutlinerView* ImpMakeOutlinerView(Window* pWin, BOOL bNoPaint, OutlinerView* pGivenView) const;
void ImpPaintOutlinerView(OutlinerView& rOutlView, const Rectangle& rRect) const;
void ImpInvalidateOutlinerView(OutlinerView& rOutlView) const;
// Hintergrundfarbe fuer die Outlinerviews bestimmen
Color ImpGetTextEditBackgroundColor() const;
// Feststellen, ob der gesamte Text markiert ist. Liefert auch TRUE wenn
// kein Text vorhanden ist.
BOOL ImpIsTextEditAllSelected() const;
void ImpMakeTextCursorAreaVisible();
// Handler fuer AutoGrowing Text bei aktivem Outliner
DECL_LINK(ImpOutlinerStatusEventHdl,EditStatus*);
DECL_LINK(ImpOutlinerCalcFieldValueHdl,EditFieldInfo*);
void ImpMacroUp(const Point& rUpPos);
void ImpMacroDown(const Point& rDownPos);
protected:
// #i71538# make constructors of SdrView sub-components protected to avoid incomplete incarnations which may get casted to SdrView
SdrObjEditView(SdrModel* pModel1, OutputDevice* pOut = 0L);
virtual ~SdrObjEditView();
public:
// Actionhandling fuer Macromodus
virtual BOOL IsAction() const;
virtual void MovAction(const Point& rPnt);
virtual void EndAction();
virtual void BrkAction();
virtual void BckAction();
virtual void TakeActionRect(Rectangle& rRect) const;
virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);
virtual void ModelHasChanged();
//************************************************************************
// TextEdit ueber einen Outliner
//************************************************************************
// QuickTextEditMode bedeutet, dass Objekte mit Text sofort beim Anklicken
// editiert werden sollen. Default=TRUE. Persistent.
void SetQuickTextEditMode(BOOL bOn) { bQuickTextEditMode=bOn; }
BOOL IsQuickTextEditMode() const { return bQuickTextEditMode; }
// Starten des TextEditMode. Ist pWin==NULL, wird das erste an der View
// angemeldete Win verwendet.
// Der Cursor des Fensters an dem Editiert wird wird bei
// SdrBeginTextEdit() gemerkt und bei SdrEndTextEdit() wieder restauriert.
// Die App muss sicherstellen, das die zum Zeitpunkt des BegEdit am
// Windows angemeldete Cursorinstanz beim SdrEndTextEdit noch gueltig ist.
// Ueber den Parameter pEditOutliner kann die Applikation einen eigenen
// Outliner vorgeben, der zum Editieren verwendet wird. Dieser gehoert
// nach Aufruf von SdrBeginTextEdit der SdrObjEditView und wird von dieser
// spaeter via delete zerstoert (falls bDontDeleteOutliner=FALSE). Die
// SdrObjEditView setzt dann das Modusflag (EditEngine/Outliner) an
// dieser Instanz und ausserdem auch den StatusEventHdl.
// Ebenso kann eine spezifische OutlinerView vorgegeben werden.
sal_Bool SdrBeginTextEdit(SdrObject* pObj, SdrPageView* pPV = 0L, Window* pWin = 0L,
SdrOutliner* pGivenOutliner = 0L, OutlinerView* pGivenOutlinerView = 0L,
sal_Bool bDontDeleteOutliner = sal_False, sal_Bool bOnlyOneView = sal_False);
sal_Bool SdrBeginTextEdit(SdrObject* pObj, SdrPageView* pPV = 0L, Window* pWin = 0L, sal_Bool bIsNewObj = sal_False,
SdrOutliner* pGivenOutliner = 0L, OutlinerView* pGivenOutlinerView = 0L,
sal_Bool bDontDeleteOutliner = sal_False, sal_Bool bOnlyOneView = sal_False, sal_Bool bGrabFocus = sal_True);
// bDontDeleteReally ist ein Spezialparameter fuer den Writer.
// Ist dieses Flag gesetzt, dann wird ein evtl. leeres Textobjekt
// nicht geloescht. Stattdessen gibt es dann einen Returncode
// SDRENDTEXTEDIT_SHOULDBEDELETED (anstelle von SDRENDTEXTEDIT_BEDELETED)
// der besagt, dass das Objekt geloescht werden sollte.
SdrEndTextEditKind SdrEndTextEdit(sal_Bool bDontDeleteReally = sal_False);
virtual bool IsTextEdit() const;
// TRUE=Es wird ein Textrahmen (OBJ_TEXT,OBJ_OUTLINETEXT,...) editiert
// ansonsten handelt es sich um ein beschriftetes Zeichenobjekt, an dem
// der Text ja bekanntlich hor. und vert. zentriert wird.
BOOL IsTextEditFrame() const;
// Diese Methode liefert TRUE, wenn der Punkt rHit innerhalb der
// des Objektbereichs oder der OutlinerView liegt.
BOOL IsTextEditHit(const Point& rHit, short nTol) const;
// Diese Methode liefert TRUE, wenn der Punkt rHit innerhalb des
// Handle-dicken Rahmens liegt, der die OutlinerView bei TextFrames
// umschliesst.
BOOL IsTextEditFrameHit(const Point& rHit) const;
// Bei aktiver Selektion, also zwischen MouseButtonDown und
// MouseButtonUp liefert diese Methode immer TRUE.
BOOL IsTextEditInSelectionMode() const;
// Folgende Methode addiert einen passenden Offset zum MouseEvent
// um diesen an den Outliner weiterzureichen.
void AddTextEditOfs(MouseEvent& rMEvt) const;
// Wer das z.Zt. im TextEdit befindliche Objekt braucht:
SdrObject* GetTextEditObject() const { return mxTextEditObj.get(); }
// info about TextEditPageView. Default is 0L.
virtual SdrPageView* GetTextEditPageView() const;
// Das aktuelle Win des Outliners
Window* GetTextEditWin() const { return pTextEditWin; }
void SetTextEditWin(Window* pWin);
// An den hier abgeholten Outliner kann man schliesslich
// Events versenden, Attribute setzen, Cut/Copy/Paste rufen,
// Undo/Redo rufen, etc.
const SdrOutliner* GetTextEditOutliner() const { return pTextEditOutliner; }
SdrOutliner* GetTextEditOutliner() { return pTextEditOutliner; }
const OutlinerView* GetTextEditOutlinerView() const { return pTextEditOutlinerView; }
OutlinerView* GetTextEditOutlinerView() { return pTextEditOutlinerView; }
BOOL KeyInput(const KeyEvent& rKEvt, Window* pWin);
virtual BOOL MouseButtonDown(const MouseEvent& rMEvt, Window* pWin);
virtual BOOL MouseButtonUp(const MouseEvent& rMEvt, Window* pWin);
virtual BOOL MouseMove(const MouseEvent& rMEvt, Window* pWin);
virtual BOOL Command(const CommandEvent& rCEvt, Window* pWin);
BOOL Cut(ULONG nFormat=SDR_ANYFORMAT);
BOOL Yank(ULONG nFormat=SDR_ANYFORMAT);
BOOL Paste(Window* pWin=NULL, ULONG nFormat=SDR_ANYFORMAT);
// #97766# make virtual to change implementation e.g. for SdOutlineView
virtual sal_uInt16 GetScriptType() const;
/* new interface src537 */
BOOL GetAttributes(SfxItemSet& rTargetSet, BOOL bOnlyHardAttr=FALSE) const;
BOOL SetAttributes(const SfxItemSet& rSet, BOOL bReplaceAll);
SfxStyleSheet* GetStyleSheet() const; // SfxStyleSheet* GetStyleSheet(BOOL& rOk) const;
BOOL SetStyleSheet(SfxStyleSheet* pStyleSheet, BOOL bDontRemoveHardAttr);
// Intern: Beim Splitteraufziehen neue OutlinerView...
virtual void AddWindowToPaintView(OutputDevice* pNewWin);
virtual void DeleteWindowFromPaintView(OutputDevice* pOldWin);
//************************************************************************
// Object-MacroModus (z.B. Rect als Button oder sowas):
//************************************************************************
// Persistent. Default TRUE. SvDraw wertet das Flag u.a. bei
// SdrView::GetPreferedPointer() aus. Hat nur Wirkung, wenn das Dokument
// Draw-Objekte mit Macrofunktionalitaet hat (SdrObject::HasMacro()==TRUE).
void SetMacroMode(BOOL bOn) { bMacroMode=bOn; }
BOOL IsMacroMode() const { return bMacroMode; }
BOOL BegMacroObj(const Point& rPnt, short nTol, SdrObject* pObj, SdrPageView* pPV, Window* pWin);
BOOL BegMacroObj(const Point& rPnt, SdrObject* pObj, SdrPageView* pPV, Window* pWin) { return BegMacroObj(rPnt,-2,pObj,pPV,pWin); }
void MovMacroObj(const Point& rPnt);
void BrkMacroObj();
BOOL EndMacroObj();
BOOL IsMacroObj() const { return pMacroObj!=NULL; }
BOOL IsMacroObjDown() const { return bMacroDown; }
/** fills the given any with a XTextCursor for the current text selection.
Leaves the any untouched if there currently is no text selected */
void getTextSelection( ::com::sun::star::uno::Any& rSelection );
};
#endif //_SVDEDXV_HXX
<commit_msg>INTEGRATION: CWS impresstables2 (1.2.58); FILE MERGED 2007/05/31 11:11:35 cl 1.2.58.1: #i68103# merging changes to moved header files for tables<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdedxv.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2008-03-12 09:28:16 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVDEDXV_HXX
#define _SVDEDXV_HXX
#include <rtl/ref.hxx>
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
#ifndef _SVDGLEV_HXX
#include <svx/svdglev.hxx>
#endif
#include <svx/selectioncontroller.hxx>
//************************************************************
// Vorausdeklarationen
//************************************************************
class SdrOutliner;
class OutlinerView;
class EditStatus;
class EditFieldInfo;
class ImpSdrEditPara;
namespace com { namespace sun { namespace star { namespace uno {
class Any;
} } } }
namespace sdr {
class SelectionController;
}
//************************************************************
// Defines
//************************************************************
enum SdrEndTextEditKind {SDRENDTEXTEDIT_UNCHANGED, // Textobjekt unveraendert
SDRENDTEXTEDIT_CHANGED, // Textobjekt wurde geaendert
SDRENDTEXTEDIT_DELETED, // Textobjekt implizit geloescht
SDRENDTEXTEDIT_SHOULDBEDELETED}; // Fuer Writer: Textobjekt sollte geloescht werden
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@@@ @@@@@ @@@@@@ @@@@@ @@@@@ @@ @@@@@@ @@ @@ @@ @@@@@ @@ @@
// @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@
// @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @ @@
// @@ @@ @@@@@ @@ @@@@ @@ @@ @@ @@ @@@@@ @@ @@@@ @@@@@@@
// @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@@@@@@
// @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@@ @@@
// @@@@ @@@@@ @@@@ @@@@@ @@@@@ @@ @@ @ @@ @@@@@ @@ @@
//
// - Allgemeines Edit fuer objektspeziefische Eigenschaften
// - Textedit fuer alle vom SdrTextObj abgeleiteten Zeichenobjekte
// - Macromodus
//
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
class SVX_DLLPUBLIC SdrObjEditView: public SdrGlueEditView
{
friend class SdrPageView;
friend class ImpSdrEditPara;
protected:
// TextEdit
SdrObjectWeakRef mxTextEditObj; // Aktuell im TextEdit befindliches Obj
SdrPageView* pTextEditPV;
SdrOutliner* pTextEditOutliner; // Na eben der Outliner fuers TextEdit
OutlinerView* pTextEditOutlinerView; // die aktuelle View des Outliners
Window* pTextEditWin; // passendes Win zu pTextEditOutlinerView
Cursor* pTextEditCursorMerker; // Zum Restaurieren des Cursors am jeweiligen Win
ImpSdrEditPara* pEditPara; // Da hau' ich erstmal alles rein um kompatibel zu bleiben...
SdrObject* pMacroObj;
SdrPageView* pMacroPV;
Window* pMacroWin;
Rectangle aTextEditArea;
Rectangle aMinTextEditArea;
Link aOldCalcFieldValueLink; // Zum rufen des alten Handlers
Point aMacroDownPos;
USHORT nMacroTol;
unsigned bTextEditDontDelete : 1; // Outliner und View bei SdrEndTextEdit nicht deleten (f. Rechtschreibpruefung)
unsigned bTextEditOnlyOneView : 1; // Nur eine OutlinerView (f. Rechtschreibpruefung)
unsigned bTextEditNewObj : 1; // Aktuell editiertes Objekt wurde gerade neu erzeugt
unsigned bQuickTextEditMode : 1; // persistent(->CrtV). Default=TRUE
unsigned bMacroMode : 1; // persistent(->CrtV). Default=TRUE
unsigned bMacroDown : 1;
rtl::Reference< sdr::SelectionController > mxSelectionController;
rtl::Reference< sdr::SelectionController > mxLastSelectionController;
private:
SVX_DLLPRIVATE void ImpClearVars();
protected:
OutlinerView* ImpFindOutlinerView(Window* pWin) const;
// Eine neue OutlinerView auf dem Heap anlegen und alle erforderlichen Parameter setzen.
// pTextEditObj, pTextEditPV und pTextEditOutliner muessen initiallisiert sein.
OutlinerView* ImpMakeOutlinerView(Window* pWin, BOOL bNoPaint, OutlinerView* pGivenView) const;
void ImpPaintOutlinerView(OutlinerView& rOutlView, const Rectangle& rRect) const;
void ImpInvalidateOutlinerView(OutlinerView& rOutlView) const;
// Hintergrundfarbe fuer die Outlinerviews bestimmen
Color ImpGetTextEditBackgroundColor() const;
// Feststellen, ob der gesamte Text markiert ist. Liefert auch TRUE wenn
// kein Text vorhanden ist.
BOOL ImpIsTextEditAllSelected() const;
void ImpMakeTextCursorAreaVisible();
// Handler fuer AutoGrowing Text bei aktivem Outliner
DECL_LINK(ImpOutlinerStatusEventHdl,EditStatus*);
DECL_LINK(ImpOutlinerCalcFieldValueHdl,EditFieldInfo*);
void ImpMacroUp(const Point& rUpPos);
void ImpMacroDown(const Point& rDownPos);
protected:
// #i71538# make constructors of SdrView sub-components protected to avoid incomplete incarnations which may get casted to SdrView
SdrObjEditView(SdrModel* pModel1, OutputDevice* pOut = 0L);
virtual ~SdrObjEditView();
public:
// Actionhandling fuer Macromodus
virtual BOOL IsAction() const;
virtual void MovAction(const Point& rPnt);
virtual void EndAction();
virtual void BrkAction();
virtual void BckAction();
virtual void TakeActionRect(Rectangle& rRect) const;
virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);
virtual void ModelHasChanged();
//************************************************************************
// TextEdit ueber einen Outliner
//************************************************************************
// QuickTextEditMode bedeutet, dass Objekte mit Text sofort beim Anklicken
// editiert werden sollen. Default=TRUE. Persistent.
void SetQuickTextEditMode(BOOL bOn) { bQuickTextEditMode=bOn; }
BOOL IsQuickTextEditMode() const { return bQuickTextEditMode; }
// Starten des TextEditMode. Ist pWin==NULL, wird das erste an der View
// angemeldete Win verwendet.
// Der Cursor des Fensters an dem Editiert wird wird bei
// SdrBeginTextEdit() gemerkt und bei SdrEndTextEdit() wieder restauriert.
// Die App muss sicherstellen, das die zum Zeitpunkt des BegEdit am
// Windows angemeldete Cursorinstanz beim SdrEndTextEdit noch gueltig ist.
// Ueber den Parameter pEditOutliner kann die Applikation einen eigenen
// Outliner vorgeben, der zum Editieren verwendet wird. Dieser gehoert
// nach Aufruf von SdrBeginTextEdit der SdrObjEditView und wird von dieser
// spaeter via delete zerstoert (falls bDontDeleteOutliner=FALSE). Die
// SdrObjEditView setzt dann das Modusflag (EditEngine/Outliner) an
// dieser Instanz und ausserdem auch den StatusEventHdl.
// Ebenso kann eine spezifische OutlinerView vorgegeben werden.
virtual sal_Bool SdrBeginTextEdit(SdrObject* pObj, SdrPageView* pPV = 0L, ::Window* pWin = 0L, sal_Bool bIsNewObj = sal_False,
SdrOutliner* pGivenOutliner = 0L, OutlinerView* pGivenOutlinerView = 0L,
sal_Bool bDontDeleteOutliner = sal_False, sal_Bool bOnlyOneView = sal_False, sal_Bool bGrabFocus = sal_True);
// bDontDeleteReally ist ein Spezialparameter fuer den Writer.
// Ist dieses Flag gesetzt, dann wird ein evtl. leeres Textobjekt
// nicht geloescht. Stattdessen gibt es dann einen Returncode
// SDRENDTEXTEDIT_SHOULDBEDELETED (anstelle von SDRENDTEXTEDIT_BEDELETED)
// der besagt, dass das Objekt geloescht werden sollte.
virtual SdrEndTextEditKind SdrEndTextEdit(sal_Bool bDontDeleteReally = sal_False);
virtual bool IsTextEdit() const;
// TRUE=Es wird ein Textrahmen (OBJ_TEXT,OBJ_OUTLINETEXT,...) editiert
// ansonsten handelt es sich um ein beschriftetes Zeichenobjekt, an dem
// der Text ja bekanntlich hor. und vert. zentriert wird.
BOOL IsTextEditFrame() const;
// Diese Methode liefert TRUE, wenn der Punkt rHit innerhalb der
// des Objektbereichs oder der OutlinerView liegt.
BOOL IsTextEditHit(const Point& rHit, short nTol) const;
// Diese Methode liefert TRUE, wenn der Punkt rHit innerhalb des
// Handle-dicken Rahmens liegt, der die OutlinerView bei TextFrames
// umschliesst.
BOOL IsTextEditFrameHit(const Point& rHit) const;
// Bei aktiver Selektion, also zwischen MouseButtonDown und
// MouseButtonUp liefert diese Methode immer TRUE.
BOOL IsTextEditInSelectionMode() const;
// Folgende Methode addiert einen passenden Offset zum MouseEvent
// um diesen an den Outliner weiterzureichen.
void AddTextEditOfs(MouseEvent& rMEvt) const;
// Wer das z.Zt. im TextEdit befindliche Objekt braucht:
SdrObject* GetTextEditObject() const { return mxTextEditObj.get(); }
// info about TextEditPageView. Default is 0L.
virtual SdrPageView* GetTextEditPageView() const;
// Das aktuelle Win des Outliners
Window* GetTextEditWin() const { return pTextEditWin; }
void SetTextEditWin(Window* pWin);
// An den hier abgeholten Outliner kann man schliesslich
// Events versenden, Attribute setzen, Cut/Copy/Paste rufen,
// Undo/Redo rufen, etc.
const SdrOutliner* GetTextEditOutliner() const { return pTextEditOutliner; }
SdrOutliner* GetTextEditOutliner() { return pTextEditOutliner; }
const OutlinerView* GetTextEditOutlinerView() const { return pTextEditOutlinerView; }
OutlinerView* GetTextEditOutlinerView() { return pTextEditOutlinerView; }
virtual BOOL KeyInput(const KeyEvent& rKEvt, Window* pWin);
virtual BOOL MouseButtonDown(const MouseEvent& rMEvt, Window* pWin);
virtual BOOL MouseButtonUp(const MouseEvent& rMEvt, Window* pWin);
virtual BOOL MouseMove(const MouseEvent& rMEvt, Window* pWin);
virtual BOOL Command(const CommandEvent& rCEvt, Window* pWin);
BOOL Cut(ULONG nFormat=SDR_ANYFORMAT);
BOOL Yank(ULONG nFormat=SDR_ANYFORMAT);
BOOL Paste(Window* pWin=NULL, ULONG nFormat=SDR_ANYFORMAT);
// #97766# make virtual to change implementation e.g. for SdOutlineView
virtual sal_uInt16 GetScriptType() const;
/* new interface src537 */
BOOL GetAttributes(SfxItemSet& rTargetSet, BOOL bOnlyHardAttr=FALSE) const;
BOOL SetAttributes(const SfxItemSet& rSet, BOOL bReplaceAll);
SfxStyleSheet* GetStyleSheet() const; // SfxStyleSheet* GetStyleSheet(BOOL& rOk) const;
BOOL SetStyleSheet(SfxStyleSheet* pStyleSheet, BOOL bDontRemoveHardAttr);
// Intern: Beim Splitteraufziehen neue OutlinerView...
virtual void AddWindowToPaintView(OutputDevice* pNewWin);
virtual void DeleteWindowFromPaintView(OutputDevice* pOldWin);
//************************************************************************
// Object-MacroModus (z.B. Rect als Button oder sowas):
//************************************************************************
// Persistent. Default TRUE. SvDraw wertet das Flag u.a. bei
// SdrView::GetPreferedPointer() aus. Hat nur Wirkung, wenn das Dokument
// Draw-Objekte mit Macrofunktionalitaet hat (SdrObject::HasMacro()==TRUE).
void SetMacroMode(BOOL bOn) { bMacroMode=bOn; }
BOOL IsMacroMode() const { return bMacroMode; }
BOOL BegMacroObj(const Point& rPnt, short nTol, SdrObject* pObj, SdrPageView* pPV, Window* pWin);
BOOL BegMacroObj(const Point& rPnt, SdrObject* pObj, SdrPageView* pPV, Window* pWin) { return BegMacroObj(rPnt,-2,pObj,pPV,pWin); }
void MovMacroObj(const Point& rPnt);
void BrkMacroObj();
BOOL EndMacroObj();
BOOL IsMacroObj() const { return pMacroObj!=NULL; }
BOOL IsMacroObjDown() const { return bMacroDown; }
/** fills the given any with a XTextCursor for the current text selection.
Leaves the any untouched if there currently is no text selected */
void getTextSelection( ::com::sun::star::uno::Any& rSelection );
virtual void MarkListHasChanged();
rtl::Reference< sdr::SelectionController > getSelectionController() const { return mxSelectionController; }
};
#endif //_SVDEDXV_HXX
<|endoftext|> |
<commit_before>///
/// @file test.cpp
/// @brief primecount integration tests (option: --test).
/// These tests are also used by the author for
/// benchmarking code changes.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <int128_t.hpp>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <exception>
#include <random>
#include <sstream>
#include <string>
#ifdef _OPENMP
#include <omp.h>
#endif
/// For types: f1(x) , f2(x, threads)
#define CHECK_12(f1, f2) check_equal(#f1, x, f1 (x), f2 (x, get_num_threads()))
/// For types: f1(x, threads) , f2(x, threads)
#define CHECK_22(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x, get_num_threads()))
#define CHECK_EQUAL(f1, f2, check, iters) \
{ \
cout << "Testing " << #f1 << "(x)" << flush; \
\
/* test for 0 <= x < 10000 */ \
for (int64_t x = 0; x < 10000; x++) \
check(f1, f2); \
\
int64_t x = 0; \
/* test using random increment */ \
for (int64_t i = 0; i < iters; i++, x += dist(gen)) \
{ \
check(f1, f2); \
double percent = 100.0 * (i + 1.0) / iters; \
cout << "\rTesting " << #f1 "(x) " << (int) percent << "%" << flush; \
} \
\
cout << endl; \
}
using namespace std;
using namespace primecount;
namespace {
void check_equal(const string& f1,
int64_t x,
int64_t res1,
int64_t res2)
{
if (res1 != res2)
{
ostringstream oss;
oss << f1 << "(" << x << ") = " << res1
<< " is an error, the correct result is " << res2;
throw primecount_error(oss.str());
}
}
void test_nth_prime(int64_t iters)
{
cout << "Testing nth_prime(x)" << flush;
int64_t n = 0;
int64_t old = 0;
int64_t prime = 0;
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int64_t> dist(1, 10000000);
for (; n < 10000; n++)
check_equal("nth_prime", n, nth_prime(n), primesieve::nth_prime(n));
// test using random increment
for (int64_t i = 0; i < iters; i++, n += dist(gen))
{
prime = primesieve::nth_prime(n - old, prime);
check_equal("nth_prime", n, nth_prime(n), prime);
double percent = 100.0 * (i + 1.0) / iters;
cout << "\rTesting nth_prime(x) " << (int) percent << "%" << flush;
old = n;
}
cout << endl;
}
#ifdef _OPENMP
void test_phi(int64_t iters)
{
cout << "Testing phi(x, a)" << flush;
int64_t sum1 = 0;
int64_t sum2 = 0;
#pragma omp parallel for reduction(+: sum1)
for (int64_t i = 0; i < iters; i++)
sum1 += pi_legendre(10000000 + i, 1);
for (int64_t i = 0; i < iters; i++)
sum2 += pi_legendre(10000000 + i, 1);
if (sum1 != sum2)
throw primecount_error("Error: multi-threaded phi(x, a) is broken.");
cout << "\rTesting phi(x, a) 100%" << endl;
}
#endif
} // namespace
namespace primecount {
void test()
{
set_print_status(false);
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int64_t> dist(1, 10000000);
try
{
#ifdef _OPENMP
test_phi(100);
#endif
CHECK_EQUAL(pi_legendre, pi_primesieve, CHECK_22, 100);
CHECK_EQUAL(pi_meissel, pi_legendre, CHECK_22, 500);
CHECK_EQUAL(pi_lehmer, pi_meissel, CHECK_22, 500);
CHECK_EQUAL(pi_lmo1, pi_meissel, CHECK_12, 50);
CHECK_EQUAL(pi_lmo2, pi_meissel, CHECK_12, 200);
CHECK_EQUAL(pi_lmo3, pi_meissel, CHECK_12, 300);
CHECK_EQUAL(pi_lmo4, pi_meissel, CHECK_12, 300);
CHECK_EQUAL(pi_lmo5, pi_meissel, CHECK_12, 600);
CHECK_EQUAL(pi_lmo_parallel1, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_lmo_parallel2, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_lmo_parallel3, pi_meissel, CHECK_22, 900);
CHECK_EQUAL(pi_deleglise_rivat1, pi_lmo_parallel3, CHECK_12, 600);
CHECK_EQUAL(pi_deleglise_rivat2, pi_lmo_parallel3, CHECK_12, 600);
CHECK_EQUAL(pi_deleglise_rivat_parallel1, pi_lmo_parallel3, CHECK_22, 900);
CHECK_EQUAL(pi_deleglise_rivat_parallel2, pi_lmo_parallel3, CHECK_22, 1500);
#ifdef HAVE_INT128_T
CHECK_EQUAL(pi_deleglise_rivat_parallel3, pi_lmo_parallel3, CHECK_22, 1500);
#endif
test_nth_prime(300);
}
catch (exception& e)
{
cerr << endl << e.what() << endl;
exit(1);
}
cout << "All tests passed successfully!" << endl;
exit(0);
}
} // namespace
<commit_msg>Refactor test.cpp<commit_after>///
/// @file test.cpp
/// @brief primecount integration tests (option: --test).
/// These tests are also used by the author for
/// benchmarking code changes.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <int128_t.hpp>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <exception>
#include <random>
#include <sstream>
#include <string>
#ifdef _OPENMP
#include <omp.h>
#endif
// check: f1(x) == f2(x, threads)
#define CHECK_12(f1, f2) \
check_equal(#f1, x, f1 (x), f2 (x, get_num_threads()))
// check: f1(x, threads) == f2(x, threads)
#define CHECK_22(f1, f2) \
check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x, get_num_threads()))
#define CHECK_EQUAL(f1, f2, check, iters) \
{ \
cout << "Testing " << #f1 << "(x)" << flush; \
\
/* test for 0 <= x < 10000 */ \
for (int64_t x = 0; x < 10000; x++) \
check(f1, f2); \
\
int64_t x = 0; \
/* test random increment */ \
for (int64_t i = 0; i < iters; i++) \
{ \
check(f1, f2); \
double percent = 100.0 * (i + 1.0) / iters; \
cout << "\rTesting " << #f1 "(x) " << (int) percent << "%" << flush; \
x += dist(gen); \
} \
\
cout << endl; \
}
using namespace std;
using namespace primecount;
namespace {
void check_equal(const string& f1,
int64_t x,
int64_t res1,
int64_t res2)
{
if (res1 != res2)
{
ostringstream oss;
oss << f1 << "(" << x << ") = " << res1
<< " is an error, the correct result is " << res2;
throw primecount_error(oss.str());
}
}
void test_nth_prime(int64_t iters)
{
cout << "Testing nth_prime(x)" << flush;
int64_t n = 0;
int64_t old = 0;
int64_t prime = 0;
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int64_t> dist(1, 10000000);
for (; n < 10000; n++)
check_equal("nth_prime", n, nth_prime(n), primesieve::nth_prime(n));
// test random increment
for (int64_t i = 0; i < iters; i++)
{
prime = primesieve::nth_prime(n - old, prime);
check_equal("nth_prime", n, nth_prime(n), prime);
double percent = 100.0 * (i + 1.0) / iters;
cout << "\rTesting nth_prime(x) " << (int) percent << "%" << flush;
old = n;
n += dist(gen);
}
cout << endl;
}
#ifdef _OPENMP
void test_phi(int64_t iters)
{
cout << "Testing phi(x, a)" << flush;
int64_t sum1 = 0;
int64_t sum2 = 0;
#pragma omp parallel for reduction(+: sum1)
for (int64_t i = 0; i < iters; i++)
sum1 += pi_legendre(10000000 + i, 1);
for (int64_t i = 0; i < iters; i++)
sum2 += pi_legendre(10000000 + i, 1);
if (sum1 != sum2)
throw primecount_error("Error: multi-threaded phi(x, a) is broken.");
cout << "\rTesting phi(x, a) 100%" << endl;
}
#endif
} // namespace
namespace primecount {
void test()
{
set_print_status(false);
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int64_t> dist(1, 10000000);
try
{
#ifdef _OPENMP
test_phi(100);
#endif
CHECK_EQUAL(pi_legendre, pi_primesieve, CHECK_22, 100);
CHECK_EQUAL(pi_meissel, pi_legendre, CHECK_22, 500);
CHECK_EQUAL(pi_lehmer, pi_meissel, CHECK_22, 500);
CHECK_EQUAL(pi_lmo1, pi_meissel, CHECK_12, 50);
CHECK_EQUAL(pi_lmo2, pi_meissel, CHECK_12, 200);
CHECK_EQUAL(pi_lmo3, pi_meissel, CHECK_12, 300);
CHECK_EQUAL(pi_lmo4, pi_meissel, CHECK_12, 300);
CHECK_EQUAL(pi_lmo5, pi_meissel, CHECK_12, 600);
CHECK_EQUAL(pi_lmo_parallel1, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_lmo_parallel2, pi_meissel, CHECK_22, 400);
CHECK_EQUAL(pi_lmo_parallel3, pi_meissel, CHECK_22, 900);
CHECK_EQUAL(pi_deleglise_rivat1, pi_lmo_parallel3, CHECK_12, 600);
CHECK_EQUAL(pi_deleglise_rivat2, pi_lmo_parallel3, CHECK_12, 600);
CHECK_EQUAL(pi_deleglise_rivat_parallel1, pi_lmo_parallel3, CHECK_22, 900);
CHECK_EQUAL(pi_deleglise_rivat_parallel2, pi_lmo_parallel3, CHECK_22, 1500);
#ifdef HAVE_INT128_T
CHECK_EQUAL(pi_deleglise_rivat_parallel3, pi_lmo_parallel3, CHECK_22, 1500);
#endif
test_nth_prime(300);
}
catch (exception& e)
{
cerr << endl << e.what() << endl;
exit(1);
}
cout << "All tests passed successfully!" << endl;
exit(0);
}
} // namespace
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cassert>
#include <cmath>
#include "SDL.h"
#include "CursorAlignment.h"
#include "GameWorldPanel.h"
#include "LoadSavePanel.h"
#include "MainMenuPanel.h"
#include "OptionsPanel.h"
#include "PauseMenuPanel.h"
#include "RichTextString.h"
#include "TextAlignment.h"
#include "TextBox.h"
#include "../Entities/CharacterClass.h"
#include "../Entities/Player.h"
#include "../Game/GameData.h"
#include "../Game/Game.h"
#include "../Game/Options.h"
#include "../Math/Constants.h"
#include "../Math/Vector2.h"
#include "../Media/AudioManager.h"
#include "../Media/Color.h"
#include "../Media/FontManager.h"
#include "../Media/FontName.h"
#include "../Media/MusicName.h"
#include "../Media/PaletteFile.h"
#include "../Media/PaletteName.h"
#include "../Media/PortraitFile.h"
#include "../Media/TextureFile.h"
#include "../Media/TextureManager.h"
#include "../Media/TextureName.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Texture.h"
PauseMenuPanel::PauseMenuPanel(Game &game)
: Panel(game)
{
this->playerNameTextBox = [&game]()
{
const int x = 17;
const int y = 154;
const RichTextString richText(
game.getGameData().getPlayer().getFirstName(),
FontName::Char,
Color(215, 121, 8),
TextAlignment::Left,
game.getFontManager());
return std::make_unique<TextBox>(x, y, richText, game.getRenderer());
}();
this->musicTextBox = [&game]()
{
const Int2 center(127, 96);
const std::string text = std::to_string(static_cast<int>(
std::round(game.getOptions().getAudio_MusicVolume() * 100.0)));
const RichTextString richText(
text,
FontName::Arena,
Color(12, 73, 16),
TextAlignment::Center,
game.getFontManager());
return std::make_unique<TextBox>(center, richText, game.getRenderer());
}();
this->soundTextBox = [&game]()
{
const Int2 center(54, 96);
const std::string text = std::to_string(static_cast<int>(
std::round(game.getOptions().getAudio_SoundVolume() * 100.0)));
const RichTextString richText(
text,
FontName::Arena,
Color(12, 73, 16),
TextAlignment::Center,
game.getFontManager());
return std::make_unique<TextBox>(center, richText, game.getRenderer());
}();
this->optionsTextBox = [&game]()
{
const Int2 center(234, 96);
const RichTextString richText(
"OPTIONS",
FontName::Arena,
Color(215, 158, 4),
TextAlignment::Center,
game.getFontManager());
const TextBox::ShadowData shadowData(Color(101, 77, 24), Int2(-1, 1));
return std::make_unique<TextBox>(
center, richText, &shadowData, game.getRenderer());
}();
this->loadButton = []()
{
const int x = 65;
const int y = 118;
auto function = [](Game &game)
{
game.setPanel<LoadSavePanel>(game, LoadSavePanel::Type::Load);
};
return Button<Game&>(x, y, 64, 29, function);
}();
this->exitButton = []()
{
const int x = 193;
const int y = 118;
auto function = []()
{
SDL_Event evt;
evt.quit.type = SDL_QUIT;
evt.quit.timestamp = 0;
SDL_PushEvent(&evt);
};
return Button<>(x, y, 64, 29, function);
}();
this->newButton = []()
{
const int x = 0;
const int y = 118;
auto function = [](Game &game)
{
game.setGameData(nullptr);
game.setPanel<MainMenuPanel>(game);
game.setMusic(MusicName::PercIntro);
};
return Button<Game&>(x, y, 65, 29, function);
}();
this->saveButton = []()
{
const int x = 129;
const int y = 118;
auto function = [](Game &game)
{
// SaveGamePanel...
//auto optionsPanel = std::make_unique<OptionsPanel>(game);
//game.setPanel(std::move(optionsPanel));
};
return Button<Game&>(x, y, 64, 29, function);
}();
this->resumeButton = []()
{
const int x = 257;
const int y = 118;
auto function = [](Game &game)
{
game.setPanel<GameWorldPanel>(game);
};
return Button<Game&>(x, y, 64, 29, function);
}();
this->optionsButton = []()
{
const int x = 162;
const int y = 89;
auto function = [](Game &game)
{
game.setPanel<OptionsPanel>(game);
};
return Button<Game&>(x, y, 145, 14, function);
}();
this->musicUpButton = []()
{
const int x = 119;
const int y = 79;
auto function = [](Options &options, AudioManager &audioManager,
PauseMenuPanel &panel)
{
options.setAudio_MusicVolume(std::min(options.getAudio_MusicVolume() + 0.050, 1.0));
audioManager.setMusicVolume(options.getAudio_MusicVolume());
// Update the music volume text.
panel.updateMusicText(options.getAudio_MusicVolume());
};
return Button<Options&, AudioManager&, PauseMenuPanel&>(x, y, 17, 9, function);
}();
this->musicDownButton = []()
{
const int x = 119;
const int y = 104;
auto function = [](Options &options, AudioManager &audioManager,
PauseMenuPanel &panel)
{
const double newVolume = [&options]()
{
const double volume = std::max(options.getAudio_MusicVolume() - 0.050, 0.0);
// Clamp very small values to zero to avoid precision issues with tiny numbers.
return volume < Constants::Epsilon ? 0.0 : volume;
}();
options.setAudio_MusicVolume(newVolume);
audioManager.setMusicVolume(options.getAudio_MusicVolume());
// Update the music volume text.
panel.updateMusicText(options.getAudio_MusicVolume());
};
return Button<Options&, AudioManager&, PauseMenuPanel&>(x, y, 17, 9, function);
}();
this->soundUpButton = []()
{
const int x = 46;
const int y = 79;
auto function = [](Options &options, AudioManager &audioManager,
PauseMenuPanel &panel)
{
options.setAudio_SoundVolume(std::min(options.getAudio_SoundVolume() + 0.050, 1.0));
audioManager.setSoundVolume(options.getAudio_SoundVolume());
// Update the sound volume text.
panel.updateSoundText(options.getAudio_SoundVolume());
};
return Button<Options&, AudioManager&, PauseMenuPanel&>(x, y, 17, 9, function);
}();
this->soundDownButton = []()
{
const int x = 46;
const int y = 104;
auto function = [](Options &options, AudioManager &audioManager,
PauseMenuPanel &panel)
{
const double newVolume = [&options]()
{
const double volume = std::max(options.getAudio_SoundVolume() - 0.050, 0.0);
// Clamp very small values to zero to avoid precision issues with tiny numbers.
return volume < Constants::Epsilon ? 0.0 : volume;
}();
options.setAudio_SoundVolume(newVolume);
audioManager.setSoundVolume(options.getAudio_SoundVolume());
// Update the sound volume text.
panel.updateSoundText(options.getAudio_SoundVolume());
};
return Button<Options&, AudioManager&, PauseMenuPanel&>(x, y, 17, 9, function);
}();
}
void PauseMenuPanel::updateMusicText(double volume)
{
// Update the displayed music volume.
this->musicTextBox = [this, volume]()
{
const Int2 center(127, 96);
const int displayedVolume = static_cast<int>(std::round(volume * 100.0));
const RichTextString &oldRichText = this->musicTextBox->getRichText();
const RichTextString richText(
std::to_string(displayedVolume),
oldRichText.getFontName(),
oldRichText.getColor(),
oldRichText.getAlignment(),
this->getGame().getFontManager());
return std::make_unique<TextBox>(
center, richText, this->getGame().getRenderer());
}();
}
void PauseMenuPanel::updateSoundText(double volume)
{
// Update the displayed sound volume.
this->soundTextBox = [this, volume]()
{
const Int2 center(54, 96);
const int displayedVolume = static_cast<int>(std::round(volume * 100.0));
const RichTextString &oldRichText = this->soundTextBox->getRichText();
const RichTextString richText(
std::to_string(displayedVolume),
oldRichText.getFontName(),
oldRichText.getColor(),
oldRichText.getAlignment(),
this->getGame().getFontManager());
return std::make_unique<TextBox>(
center, richText, this->getGame().getRenderer());
}();
}
std::pair<SDL_Texture*, CursorAlignment> PauseMenuPanel::getCurrentCursor() const
{
auto &game = this->getGame();
auto &renderer = game.getRenderer();
auto &textureManager = game.getTextureManager();
const auto &texture = textureManager.getTexture(
TextureFile::fromName(TextureName::SwordCursor),
PaletteFile::fromName(PaletteName::Default), renderer);
return std::make_pair(texture.get(), CursorAlignment::TopLeft);
}
void PauseMenuPanel::handleEvent(const SDL_Event &e)
{
const auto &inputManager = this->getGame().getInputManager();
bool escapePressed = inputManager.keyPressed(e, SDLK_ESCAPE);
if (escapePressed)
{
this->resumeButton.click(this->getGame());
}
bool leftClick = inputManager.mouseButtonPressed(e, SDL_BUTTON_LEFT);
if (leftClick)
{
const Int2 mousePosition = inputManager.getMousePosition();
const Int2 mouseOriginalPoint = this->getGame().getRenderer()
.nativeToOriginal(mousePosition);
auto &options = this->getGame().getOptions();
auto &audioManager = this->getGame().getAudioManager();
// See if any of the buttons are clicked.
// (This code is getting kind of bad now. Maybe use a vector?)
if (this->loadButton.contains(mouseOriginalPoint))
{
this->loadButton.click(this->getGame());
}
else if (this->exitButton.contains(mouseOriginalPoint))
{
this->exitButton.click();
}
else if (this->newButton.contains(mouseOriginalPoint))
{
this->newButton.click(this->getGame());
}
else if (this->saveButton.contains(mouseOriginalPoint))
{
this->saveButton.click(this->getGame());
}
else if (this->resumeButton.contains(mouseOriginalPoint))
{
this->resumeButton.click(this->getGame());
}
else if (this->optionsButton.contains(mouseOriginalPoint))
{
this->optionsButton.click(this->getGame());
}
else if (this->musicUpButton.contains(mouseOriginalPoint))
{
this->musicUpButton.click(options, audioManager, *this);
}
else if (this->musicDownButton.contains(mouseOriginalPoint))
{
this->musicDownButton.click(options, audioManager, *this);
}
else if (this->soundUpButton.contains(mouseOriginalPoint))
{
this->soundUpButton.click(options, audioManager, *this);
}
else if (this->soundDownButton.contains(mouseOriginalPoint))
{
this->soundDownButton.click(options, audioManager, *this);
}
}
}
void PauseMenuPanel::render(Renderer &renderer)
{
// Clear full screen.
renderer.clear();
// Set palette.
auto &textureManager = this->getGame().getTextureManager();
textureManager.setPalette(PaletteFile::fromName(PaletteName::Default));
// Draw pause background.
const auto &pauseBackground = textureManager.getTexture(
TextureFile::fromName(TextureName::PauseBackground), renderer);
renderer.drawOriginal(pauseBackground.get());
// Draw game world interface below the pause menu.
const auto &gameInterface = textureManager.getTexture(
TextureFile::fromName(TextureName::GameWorldInterface), renderer);
renderer.drawOriginal(gameInterface.get(), 0,
Renderer::ORIGINAL_HEIGHT - gameInterface.getHeight());
// Draw player portrait.
const auto &player = this->getGame().getGameData().getPlayer();
const auto &headsFilename = PortraitFile::getHeads(
player.getGenderName(), player.getRaceID(), true);
const auto &portrait = textureManager.getTextures(
headsFilename, renderer).at(player.getPortraitID());
const auto &status = textureManager.getTextures(
TextureFile::fromName(TextureName::StatusGradients), renderer).at(0);
renderer.drawOriginal(status.get(), 14, 166);
renderer.drawOriginal(portrait.get(), 14, 166);
// If the player's class can't use magic, show the darkened spell icon.
if (!player.getCharacterClass().canCastMagic())
{
const auto &nonMagicIcon = textureManager.getTexture(
TextureFile::fromName(TextureName::NoSpell), renderer);
renderer.drawOriginal(nonMagicIcon.get(), 91, 177);
}
// Cover up the detail slider with a new options background.
Texture optionsBackground(Texture::generate(Texture::PatternType::Custom1,
this->optionsButton.getWidth(), this->optionsButton.getHeight(),
textureManager, renderer));
renderer.drawOriginal(optionsBackground.get(), this->optionsButton.getX(),
this->optionsButton.getY());
// Draw text: player's name, music volume, sound volume, options.
renderer.drawOriginal(this->playerNameTextBox->getTexture(),
this->playerNameTextBox->getX(), this->playerNameTextBox->getY());
renderer.drawOriginal(this->musicTextBox->getTexture(),
this->musicTextBox->getX(), this->musicTextBox->getY());
renderer.drawOriginal(this->soundTextBox->getTexture(),
this->soundTextBox->getX(), this->soundTextBox->getY());
renderer.drawOriginal(this->optionsTextBox->getTexture(),
this->optionsTextBox->getX() - 1, this->optionsTextBox->getY());
}
<commit_msg>Fixed off-by-one error with pause menu options button.<commit_after>#include <algorithm>
#include <cassert>
#include <cmath>
#include "SDL.h"
#include "CursorAlignment.h"
#include "GameWorldPanel.h"
#include "LoadSavePanel.h"
#include "MainMenuPanel.h"
#include "OptionsPanel.h"
#include "PauseMenuPanel.h"
#include "RichTextString.h"
#include "TextAlignment.h"
#include "TextBox.h"
#include "../Entities/CharacterClass.h"
#include "../Entities/Player.h"
#include "../Game/GameData.h"
#include "../Game/Game.h"
#include "../Game/Options.h"
#include "../Math/Constants.h"
#include "../Math/Vector2.h"
#include "../Media/AudioManager.h"
#include "../Media/Color.h"
#include "../Media/FontManager.h"
#include "../Media/FontName.h"
#include "../Media/MusicName.h"
#include "../Media/PaletteFile.h"
#include "../Media/PaletteName.h"
#include "../Media/PortraitFile.h"
#include "../Media/TextureFile.h"
#include "../Media/TextureManager.h"
#include "../Media/TextureName.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Texture.h"
PauseMenuPanel::PauseMenuPanel(Game &game)
: Panel(game)
{
this->playerNameTextBox = [&game]()
{
const int x = 17;
const int y = 154;
const RichTextString richText(
game.getGameData().getPlayer().getFirstName(),
FontName::Char,
Color(215, 121, 8),
TextAlignment::Left,
game.getFontManager());
return std::make_unique<TextBox>(x, y, richText, game.getRenderer());
}();
this->musicTextBox = [&game]()
{
const Int2 center(127, 96);
const std::string text = std::to_string(static_cast<int>(
std::round(game.getOptions().getAudio_MusicVolume() * 100.0)));
const RichTextString richText(
text,
FontName::Arena,
Color(12, 73, 16),
TextAlignment::Center,
game.getFontManager());
return std::make_unique<TextBox>(center, richText, game.getRenderer());
}();
this->soundTextBox = [&game]()
{
const Int2 center(54, 96);
const std::string text = std::to_string(static_cast<int>(
std::round(game.getOptions().getAudio_SoundVolume() * 100.0)));
const RichTextString richText(
text,
FontName::Arena,
Color(12, 73, 16),
TextAlignment::Center,
game.getFontManager());
return std::make_unique<TextBox>(center, richText, game.getRenderer());
}();
this->optionsTextBox = [&game]()
{
const Int2 center(234, 95);
const RichTextString richText(
"OPTIONS",
FontName::Arena,
Color(215, 158, 4),
TextAlignment::Center,
game.getFontManager());
const TextBox::ShadowData shadowData(Color(101, 77, 24), Int2(-1, 1));
return std::make_unique<TextBox>(
center, richText, &shadowData, game.getRenderer());
}();
this->loadButton = []()
{
const int x = 65;
const int y = 118;
auto function = [](Game &game)
{
game.setPanel<LoadSavePanel>(game, LoadSavePanel::Type::Load);
};
return Button<Game&>(x, y, 64, 29, function);
}();
this->exitButton = []()
{
const int x = 193;
const int y = 118;
auto function = []()
{
SDL_Event evt;
evt.quit.type = SDL_QUIT;
evt.quit.timestamp = 0;
SDL_PushEvent(&evt);
};
return Button<>(x, y, 64, 29, function);
}();
this->newButton = []()
{
const int x = 0;
const int y = 118;
auto function = [](Game &game)
{
game.setGameData(nullptr);
game.setPanel<MainMenuPanel>(game);
game.setMusic(MusicName::PercIntro);
};
return Button<Game&>(x, y, 65, 29, function);
}();
this->saveButton = []()
{
const int x = 129;
const int y = 118;
auto function = [](Game &game)
{
// SaveGamePanel...
//auto optionsPanel = std::make_unique<OptionsPanel>(game);
//game.setPanel(std::move(optionsPanel));
};
return Button<Game&>(x, y, 64, 29, function);
}();
this->resumeButton = []()
{
const int x = 257;
const int y = 118;
auto function = [](Game &game)
{
game.setPanel<GameWorldPanel>(game);
};
return Button<Game&>(x, y, 64, 29, function);
}();
this->optionsButton = []()
{
const int x = 162;
const int y = 88;
auto function = [](Game &game)
{
game.setPanel<OptionsPanel>(game);
};
return Button<Game&>(x, y, 145, 15, function);
}();
this->musicUpButton = []()
{
const int x = 119;
const int y = 79;
auto function = [](Options &options, AudioManager &audioManager,
PauseMenuPanel &panel)
{
options.setAudio_MusicVolume(std::min(options.getAudio_MusicVolume() + 0.050, 1.0));
audioManager.setMusicVolume(options.getAudio_MusicVolume());
// Update the music volume text.
panel.updateMusicText(options.getAudio_MusicVolume());
};
return Button<Options&, AudioManager&, PauseMenuPanel&>(x, y, 17, 9, function);
}();
this->musicDownButton = []()
{
const int x = 119;
const int y = 104;
auto function = [](Options &options, AudioManager &audioManager,
PauseMenuPanel &panel)
{
const double newVolume = [&options]()
{
const double volume = std::max(options.getAudio_MusicVolume() - 0.050, 0.0);
// Clamp very small values to zero to avoid precision issues with tiny numbers.
return volume < Constants::Epsilon ? 0.0 : volume;
}();
options.setAudio_MusicVolume(newVolume);
audioManager.setMusicVolume(options.getAudio_MusicVolume());
// Update the music volume text.
panel.updateMusicText(options.getAudio_MusicVolume());
};
return Button<Options&, AudioManager&, PauseMenuPanel&>(x, y, 17, 9, function);
}();
this->soundUpButton = []()
{
const int x = 46;
const int y = 79;
auto function = [](Options &options, AudioManager &audioManager,
PauseMenuPanel &panel)
{
options.setAudio_SoundVolume(std::min(options.getAudio_SoundVolume() + 0.050, 1.0));
audioManager.setSoundVolume(options.getAudio_SoundVolume());
// Update the sound volume text.
panel.updateSoundText(options.getAudio_SoundVolume());
};
return Button<Options&, AudioManager&, PauseMenuPanel&>(x, y, 17, 9, function);
}();
this->soundDownButton = []()
{
const int x = 46;
const int y = 104;
auto function = [](Options &options, AudioManager &audioManager,
PauseMenuPanel &panel)
{
const double newVolume = [&options]()
{
const double volume = std::max(options.getAudio_SoundVolume() - 0.050, 0.0);
// Clamp very small values to zero to avoid precision issues with tiny numbers.
return volume < Constants::Epsilon ? 0.0 : volume;
}();
options.setAudio_SoundVolume(newVolume);
audioManager.setSoundVolume(options.getAudio_SoundVolume());
// Update the sound volume text.
panel.updateSoundText(options.getAudio_SoundVolume());
};
return Button<Options&, AudioManager&, PauseMenuPanel&>(x, y, 17, 9, function);
}();
}
void PauseMenuPanel::updateMusicText(double volume)
{
// Update the displayed music volume.
this->musicTextBox = [this, volume]()
{
const Int2 center(127, 96);
const int displayedVolume = static_cast<int>(std::round(volume * 100.0));
const RichTextString &oldRichText = this->musicTextBox->getRichText();
const RichTextString richText(
std::to_string(displayedVolume),
oldRichText.getFontName(),
oldRichText.getColor(),
oldRichText.getAlignment(),
this->getGame().getFontManager());
return std::make_unique<TextBox>(
center, richText, this->getGame().getRenderer());
}();
}
void PauseMenuPanel::updateSoundText(double volume)
{
// Update the displayed sound volume.
this->soundTextBox = [this, volume]()
{
const Int2 center(54, 96);
const int displayedVolume = static_cast<int>(std::round(volume * 100.0));
const RichTextString &oldRichText = this->soundTextBox->getRichText();
const RichTextString richText(
std::to_string(displayedVolume),
oldRichText.getFontName(),
oldRichText.getColor(),
oldRichText.getAlignment(),
this->getGame().getFontManager());
return std::make_unique<TextBox>(
center, richText, this->getGame().getRenderer());
}();
}
std::pair<SDL_Texture*, CursorAlignment> PauseMenuPanel::getCurrentCursor() const
{
auto &game = this->getGame();
auto &renderer = game.getRenderer();
auto &textureManager = game.getTextureManager();
const auto &texture = textureManager.getTexture(
TextureFile::fromName(TextureName::SwordCursor),
PaletteFile::fromName(PaletteName::Default), renderer);
return std::make_pair(texture.get(), CursorAlignment::TopLeft);
}
void PauseMenuPanel::handleEvent(const SDL_Event &e)
{
const auto &inputManager = this->getGame().getInputManager();
bool escapePressed = inputManager.keyPressed(e, SDLK_ESCAPE);
if (escapePressed)
{
this->resumeButton.click(this->getGame());
}
bool leftClick = inputManager.mouseButtonPressed(e, SDL_BUTTON_LEFT);
if (leftClick)
{
const Int2 mousePosition = inputManager.getMousePosition();
const Int2 mouseOriginalPoint = this->getGame().getRenderer()
.nativeToOriginal(mousePosition);
auto &options = this->getGame().getOptions();
auto &audioManager = this->getGame().getAudioManager();
// See if any of the buttons are clicked.
// (This code is getting kind of bad now. Maybe use a vector?)
if (this->loadButton.contains(mouseOriginalPoint))
{
this->loadButton.click(this->getGame());
}
else if (this->exitButton.contains(mouseOriginalPoint))
{
this->exitButton.click();
}
else if (this->newButton.contains(mouseOriginalPoint))
{
this->newButton.click(this->getGame());
}
else if (this->saveButton.contains(mouseOriginalPoint))
{
this->saveButton.click(this->getGame());
}
else if (this->resumeButton.contains(mouseOriginalPoint))
{
this->resumeButton.click(this->getGame());
}
else if (this->optionsButton.contains(mouseOriginalPoint))
{
this->optionsButton.click(this->getGame());
}
else if (this->musicUpButton.contains(mouseOriginalPoint))
{
this->musicUpButton.click(options, audioManager, *this);
}
else if (this->musicDownButton.contains(mouseOriginalPoint))
{
this->musicDownButton.click(options, audioManager, *this);
}
else if (this->soundUpButton.contains(mouseOriginalPoint))
{
this->soundUpButton.click(options, audioManager, *this);
}
else if (this->soundDownButton.contains(mouseOriginalPoint))
{
this->soundDownButton.click(options, audioManager, *this);
}
}
}
void PauseMenuPanel::render(Renderer &renderer)
{
// Clear full screen.
renderer.clear();
// Set palette.
auto &textureManager = this->getGame().getTextureManager();
textureManager.setPalette(PaletteFile::fromName(PaletteName::Default));
// Draw pause background.
const auto &pauseBackground = textureManager.getTexture(
TextureFile::fromName(TextureName::PauseBackground), renderer);
renderer.drawOriginal(pauseBackground.get());
// Draw game world interface below the pause menu.
const auto &gameInterface = textureManager.getTexture(
TextureFile::fromName(TextureName::GameWorldInterface), renderer);
renderer.drawOriginal(gameInterface.get(), 0,
Renderer::ORIGINAL_HEIGHT - gameInterface.getHeight());
// Draw player portrait.
const auto &player = this->getGame().getGameData().getPlayer();
const auto &headsFilename = PortraitFile::getHeads(
player.getGenderName(), player.getRaceID(), true);
const auto &portrait = textureManager.getTextures(
headsFilename, renderer).at(player.getPortraitID());
const auto &status = textureManager.getTextures(
TextureFile::fromName(TextureName::StatusGradients), renderer).at(0);
renderer.drawOriginal(status.get(), 14, 166);
renderer.drawOriginal(portrait.get(), 14, 166);
// If the player's class can't use magic, show the darkened spell icon.
if (!player.getCharacterClass().canCastMagic())
{
const auto &nonMagicIcon = textureManager.getTexture(
TextureFile::fromName(TextureName::NoSpell), renderer);
renderer.drawOriginal(nonMagicIcon.get(), 91, 177);
}
// Cover up the detail slider with a new options background.
Texture optionsBackground(Texture::generate(Texture::PatternType::Custom1,
this->optionsButton.getWidth(), this->optionsButton.getHeight(),
textureManager, renderer));
renderer.drawOriginal(optionsBackground.get(), this->optionsButton.getX(),
this->optionsButton.getY());
// Draw text: player's name, music volume, sound volume, options.
renderer.drawOriginal(this->playerNameTextBox->getTexture(),
this->playerNameTextBox->getX(), this->playerNameTextBox->getY());
renderer.drawOriginal(this->musicTextBox->getTexture(),
this->musicTextBox->getX(), this->musicTextBox->getY());
renderer.drawOriginal(this->soundTextBox->getTexture(),
this->soundTextBox->getX(), this->soundTextBox->getY());
renderer.drawOriginal(this->optionsTextBox->getTexture(),
this->optionsTextBox->getX() - 1, this->optionsTextBox->getY());
}
<|endoftext|> |
<commit_before>#include "circuits/circuit.h"
#include "matrix/matrix.h"
#include "gtest/gtest.h"
#include <iostream>
#include <stdio.h>
using namespace std;
TEST(CircuitStampsTest, SimpleResistor) {
// Arrange
int numElements = 1;
int numVariables = 2;
double matrix[MAX_NOS+1][MAX_NOS+2];
init(numVariables, matrix);
Element resistor;
resistor.name = "R1";
resistor.a = 1;
resistor.b = 2;
resistor.valor = 2;
vector<Element> netlist(2);
netlist[1] = resistor;
// Act
applyStamps(numElements, numVariables, netlist, matrix);
// Assert
double expected[MAX_NOS+1][MAX_NOS+2] = {
{0, 0, 0, 0},
{0, 0.5, -0.5, 0},
{0, -0.5, 0.5, 0}
};
for (int i=1; i<=numVariables; i++) {
for (int j=1; j<=numVariables+1; j++) {
EXPECT_EQ(expected[i][j], matrix[i][j]);
}
}
}
<commit_msg>Updates stamps test<commit_after>#include "circuits/circuit.h"
#include "matrix/matrix.h"
#include "gtest/gtest.h"
#include <iostream>
#include <stdio.h>
using namespace std;
TEST(CircuitStampsTest, SimpleResistor) {
// Arrange
int numElements = 1;
int numVariables = 2;
double matrix[MAX_NOS+1][MAX_NOS+2];
init(numVariables, matrix);
Element resistor("R1", 2, 1, 2, 0, 0, 0, 0);
vector<Element> netlist(2);
netlist[1] = resistor;
// Act
applyStamps(numElements, numVariables, netlist, matrix);
// Assert
double expected[MAX_NOS+1][MAX_NOS+2] = {
{0, 0, 0, 0},
{0, 0.5, -0.5, 0},
{0, -0.5, 0.5, 0}
};
for (int i=1; i<=numVariables; i++) {
for (int j=1; j<=numVariables+1; j++) {
EXPECT_EQ(expected[i][j], matrix[i][j]);
}
}
}
<|endoftext|> |
<commit_before>/*
* Rect.cpp
*
* Created on: Feb 2, 2013
* Author: villekankainen
*/
#include <algorithm>
#include "Rect.h"
namespace Gain {
static const char gVertexShader[] =
"attribute vec2 coord2d;\n"
"uniform mat4 anim;"
"void main() {\n"
" gl_Position = anim * vec4(coord2d.x, -coord2d.y, 0.0, 1.0);"
"}\n";
static const char gFragmentShader[] =
"precision mediump float;\n"
"uniform vec4 color;"
"void main(void) {"
" gl_FragColor = color;"
"}"
;
Rect::Rect(int x, int y, int width, int height, const char* vertexShader, const char* fragmentShader)
{
privateConstruct(vertexShader, fragmentShader);
set(x,y,width,height);
setPlacement(TOP_LEFT);
}
Rect::Rect(float x, float y, float width, float height, const char* vertexShader, const char* fragmentShader)
{
privateConstruct(vertexShader, fragmentShader);
setN(x,y,width,height);
}
Rect::Rect(const char* vertexShader, const char* fragmentShader)
{
privateConstruct(vertexShader, fragmentShader);
setN(0,0,0,0);
}
void Rect::privateConstruct(const char* aVertexShader, const char* aFragmentShader)
{
pVertexShader = aVertexShader?aVertexShader:gVertexShader;
pFragmentShader = aFragmentShader?aFragmentShader:gFragmentShader;
program = 0;
// set default to white
setColor(1.0f,1.0f,1.0f,1.f);
pAngle=0.f;
}
Rect::~Rect()
{
/* empty */
}
Rect* Rect::setColor(GLfloat aColor[4])
{
memcpy(color,aColor, sizeof(color));
return this;
}
Rect* Rect::setColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
{
GLfloat color[4] = {red, green, blue, alpha};
setColor(color);
return this;
}
Rect* Rect::setRotation(GLfloat aAngle)
{
pAngle = aAngle;
return this;
}
//void Rect::mapToGraphics() {
// Core* core = CORE;
//
// float half_width = pWidth / core->screen_width;
// float half_height = pHeight / core->screen_width;
//
//
// //center the rectangle within the GL coordinates bound to be [-1,1] in vertical, and [reversed_screen_ratio,-reversed_screen_ratio] in horizontal
//
// square_vertices[0] = -half_width;
// square_vertices[1] = -half_height;
//
// square_vertices[2] = half_width;
// square_vertices[3] = -half_height;
//
// square_vertices[4] = half_width;
// square_vertices[5] = half_height;
//
// square_vertices[6] = -half_width;
// square_vertices[7] = half_height;
//
// translate[0] = 2.f*(pX-core->screen_width/2.f)/core->screen_width + half_width;
//
// translate[1] = -2.f*((pY+pHeight/2.f)-core->screen_height/2.f)/core->screen_height;
//
//}
Rect* Rect::setX(int aX)
{
setXN(-1.f + 2.f*((float)aX)/CORE->screen_width);
return this;
}
Rect* Rect::setY(int aY)
{
setYN(-1.f*CORE->reversed_ratio + 2.f*((float)aY)/CORE->screen_width);
return this;
}
Rect* Rect::setXN(float x)
{
pPositionX = x;
return this;
}
Rect* Rect::setYN(float y)
{
pPositionY = -y*CORE->ratio;
return this;
}
float Rect::getXN()
{
return pPositionX;
}
float Rect::getYN()
{
return -pPositionY*CORE->reversed_ratio;
}
Rect* Rect::setWidth(int aWidth)
{
setWidthN(2.f*((float)aWidth)/CORE->screen_width);
return this;
}
Rect* Rect::setHeight(int aHeight)
{
setHeightN(2.f*((float)aHeight)/CORE->screen_width);
return this;
}
Rect* Rect::set(int aX, int aY, int aWidth, int aHeight)
{
setX(aX);
setY(aY);
setWidth(aWidth);
setHeight(aHeight);
return this;
}
Rect* Rect::setN(float aX, float aY, float aWidth, float aHeight)
{
setXN(aX);
setYN(aY);
setWidthN(aWidth);
setHeightN(aHeight);
return this;
}
Rect* Rect::setWidthN(float width)
{
pHalfWidth=width*0.5f;
square_vertices[0] = -pHalfWidth;
square_vertices[2] = pHalfWidth;
square_vertices[4] = pHalfWidth;
square_vertices[6] = -pHalfWidth;
return this;
}
Rect* Rect::setHeightN(float height)
{
pHalfHeight=height*0.5f;
square_vertices[1] = -pHalfHeight;
square_vertices[3] = -pHalfHeight;
square_vertices[5] = pHalfHeight;
square_vertices[7] = pHalfHeight;
return this;
}
Rect* Rect::setSizeN(float width, float height)
{
setWidthN(width);
setHeightN(height);
return this;
}
Rect* Rect::setPositionN(float x, float y, Placement aPlacement)
{
setXN(x);
setYN(y);
setPlacement(aPlacement);
return this;
}
Rect* Rect::setPlacement(Placement aPlacement)
{
pPlacement = aPlacement;
return this;
}
Rect* Rect::setCenterN(float x, float y)
{
setXN(x);
setYN(y);
setPlacement(MID_CENTER);
return this;
}
Rect* Rect::setCornersN(float tl_x, float tl_y, float tr_x, float tr_y,
float bl_x, float bl_y, float br_x, float br_y)
{
square_vertices[0] = tl_x;
square_vertices[1] = tl_y;
square_vertices[2] = tr_x;
square_vertices[3] = tr_y;
square_vertices[4] = br_x;
square_vertices[5] = br_y;
square_vertices[6] = bl_x;
square_vertices[7] = bl_y;
pPositionX = 0;
pPositionY = 0;
return this;
}
bool Rect::initVariables()
{
const char* attribute_name;
const char* uniform_name;
attribute_name = "coord2d";
attribute_coord2d = GL_EXT_FUNC glGetAttribLocation(program, attribute_name);
if (attribute_coord2d == -1) {
fprintf(stderr, "Could not bind attribute %s\n", attribute_name);
return 0;
}
uniform_name = "anim";
uniform_anim = GL_EXT_FUNC glGetUniformLocation(program, uniform_name);
if (uniform_anim == -1) {
fprintf(stderr, "Could not bind uniform %s\n", uniform_name);
return 0;
}
uniform_name = "color";
uniform_color = GL_EXT_FUNC glGetUniformLocation(program, uniform_name);
if (uniform_color == -1) {
fprintf(stderr, "Could not bind uniform %s\n", uniform_name);
return 0;
}
GL_EXT_FUNC glGenBuffers(1, &vbo_square_vertices);
GL_EXT_FUNC glBindBuffer(GL_ARRAY_BUFFER, vbo_square_vertices);
GL_EXT_FUNC glBufferData(GL_ARRAY_BUFFER, sizeof(square_vertices), square_vertices, GL_STATIC_DRAW);
GLushort square_elements[] = {
// front
0, 1, 2,
2, 3, 0,
};
GL_EXT_FUNC glGenBuffers(1, &ibo_square_elements);
GL_EXT_FUNC glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_square_elements);
GL_EXT_FUNC glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(square_elements), square_elements, GL_STATIC_DRAW);
checkGlError("glBufferData");
return true;
}
bool Rect::setupGraphics() {
if (!program) {
program = createProgram(pVertexShader,pFragmentShader);
if (!program) {
LOGE("Could not create program.");
return false;
}
}
initVariables();
setReady();
return true;
}
void Rect::updateG(float sec, float deltaSec)
{
updateAnimation(sec,deltaSec);
// if(updateTranslationMat)
{
float translateX = pPositionX;
float translateY = pPositionY;
if(pPlacement & (PLACEMENT_LEFT | PLACEMENT_RIGHT))
{
translateX += pPlacement & PLACEMENT_RIGHT ? -pHalfWidth : pHalfWidth;
}
if(pPlacement & (PLACEMENT_TOP | PLACEMENT_BOTTOM))
{
translateY += (pPlacement & PLACEMENT_TOP ? -pHalfHeight : pHalfHeight)*CORE->ratio;
}
translate_mat = glm::translate(glm::mat4(1.0f), glm::vec3(translateX,translateY, 0.0));
}
scale = glm::scale(glm::mat4(1.0f), glm::vec3(1.f,CORE->ratio, 1.0));
rotate = glm::rotate(glm::mat4(1.0f), pAngle, glm::vec3(0.0, 0.0, 1.0)) ;
anim = translate_mat * scale * rotate;
Base::updateG(sec,deltaSec);
}
void Rect::enableAttributes() const
{
GL_EXT_FUNC glEnableVertexAttribArray(attribute_coord2d);
GL_EXT_FUNC glBindBuffer(GL_ARRAY_BUFFER, vbo_square_vertices);
GL_EXT_FUNC glBufferData(GL_ARRAY_BUFFER, sizeof(square_vertices), square_vertices, GL_STATIC_DRAW);
GL_EXT_FUNC glVertexAttribPointer(
attribute_coord2d, // attribute
2, // number of elements per vertex, here (x,y)
GL_FLOAT, // the type of each element
GL_FALSE, // take our values as-is
0, // next coord3d appears every 6 floats
0 // offset of first element
);
GL_EXT_FUNC glUniformMatrix4fv(uniform_anim, 1, GL_FALSE, glm::value_ptr(anim));
GL_EXT_FUNC glUniform4fv(uniform_color, 1, color);
}
void Rect::disableAttributes() const
{
GL_EXT_FUNC glDisableVertexAttribArray(attribute_coord2d);
checkGlError("glDisableVertexAttribArray");
}
void Rect::render() const
{
GL_EXT_FUNC glUseProgram(program);
checkGlError("glUseProgram");
enableAttributes();
GL_EXT_FUNC glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_square_elements);
int size;
GL_EXT_FUNC glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
glDrawElements(GL_TRIANGLES, size/sizeof(GLushort), GL_UNSIGNED_SHORT, 0);
checkGlError("glDrawElements");
disableAttributes();
}
void Rect::moveToN(float aTargetX, float aTargetY, float sec)
{
AnimationContainer* anim = new AnimationContainer();
anim->targetX = aTargetX;
anim->targetY = aTargetY;
anim->startX = getXN();
anim->startY = getYN();
anim->time = sec;
pAnimationList.push(anim);
}
void Rect::updateAnimation(float sec, float deltaSec)
{
if(pAnimationList.size())
{
AnimationContainer* anim = pAnimationList.front();
anim->elapsedTime += deltaSec;
float currentPosition = std::min(1.f, anim->elapsedTime / anim->time);
// currentPosition*=currentPosition;
if(anim->startX != anim->targetX){
setXN(anim->startX + (anim->targetX - anim->startX)*currentPosition);
}
if(anim->startY != anim->targetY){
setYN(anim->startY + (anim->targetY - anim->startY)*currentPosition);
}
if(currentPosition == 1.f)
{
std::map<EventListener*,EventListener*>::iterator it;
for(it = pEventListener.begin();it != pEventListener.end();it++)
{
it->first->onEvent(this, EVENT_ANIMATION_FINISHED);
}
pAnimationList.pop();
delete anim;
anim=0;
}
if(pAnimationList.size())
{
AnimationContainer* anim = pAnimationList.front();
anim->startX = getXN();
anim->startY = getYN();
}
}
}
bool Rect::isWithin(float Xn, float Yn)
{
//TODO: currently works only on centered rects
return Xn < pPositionX+pHalfWidth &&
Xn > pPositionX-pHalfWidth &&
Yn < pPositionX+pHalfHeight &&
Yn > pPositionX-pHalfHeight;
}
} /* namespace Gain */
<commit_msg>isWithin fix<commit_after>/*
* Rect.cpp
*
* Created on: Feb 2, 2013
* Author: villekankainen
*/
#include <algorithm>
#include "Rect.h"
namespace Gain {
static const char gVertexShader[] =
"attribute vec2 coord2d;\n"
"uniform mat4 anim;"
"void main() {\n"
" gl_Position = anim * vec4(coord2d.x, -coord2d.y, 0.0, 1.0);"
"}\n";
static const char gFragmentShader[] =
"precision mediump float;\n"
"uniform vec4 color;"
"void main(void) {"
" gl_FragColor = color;"
"}"
;
Rect::Rect(int x, int y, int width, int height, const char* vertexShader, const char* fragmentShader)
{
privateConstruct(vertexShader, fragmentShader);
set(x,y,width,height);
setPlacement(TOP_LEFT);
}
Rect::Rect(float x, float y, float width, float height, const char* vertexShader, const char* fragmentShader)
{
privateConstruct(vertexShader, fragmentShader);
setN(x,y,width,height);
}
Rect::Rect(const char* vertexShader, const char* fragmentShader)
{
privateConstruct(vertexShader, fragmentShader);
setN(0,0,0,0);
}
void Rect::privateConstruct(const char* aVertexShader, const char* aFragmentShader)
{
pVertexShader = aVertexShader?aVertexShader:gVertexShader;
pFragmentShader = aFragmentShader?aFragmentShader:gFragmentShader;
program = 0;
// set default to white
setColor(1.0f,1.0f,1.0f,1.f);
pAngle=0.f;
setPlacement(MID_CENTER);
}
Rect::~Rect()
{
/* empty */
}
Rect* Rect::setColor(GLfloat aColor[4])
{
memcpy(color,aColor, sizeof(color));
return this;
}
Rect* Rect::setColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
{
GLfloat color[4] = {red, green, blue, alpha};
setColor(color);
return this;
}
Rect* Rect::setRotation(GLfloat aAngle)
{
pAngle = aAngle;
return this;
}
//void Rect::mapToGraphics() {
// Core* core = CORE;
//
// float half_width = pWidth / core->screen_width;
// float half_height = pHeight / core->screen_width;
//
//
// //center the rectangle within the GL coordinates bound to be [-1,1] in vertical, and [reversed_screen_ratio,-reversed_screen_ratio] in horizontal
//
// square_vertices[0] = -half_width;
// square_vertices[1] = -half_height;
//
// square_vertices[2] = half_width;
// square_vertices[3] = -half_height;
//
// square_vertices[4] = half_width;
// square_vertices[5] = half_height;
//
// square_vertices[6] = -half_width;
// square_vertices[7] = half_height;
//
// translate[0] = 2.f*(pX-core->screen_width/2.f)/core->screen_width + half_width;
//
// translate[1] = -2.f*((pY+pHeight/2.f)-core->screen_height/2.f)/core->screen_height;
//
//}
Rect* Rect::setX(int aX)
{
setXN(-1.f + 2.f*((float)aX)/CORE->screen_width);
return this;
}
Rect* Rect::setY(int aY)
{
setYN(-1.f*CORE->reversed_ratio + 2.f*((float)aY)/CORE->screen_width);
return this;
}
Rect* Rect::setXN(float x)
{
pPositionX = x;
return this;
}
Rect* Rect::setYN(float y)
{
pPositionY = -y*CORE->ratio;
return this;
}
float Rect::getXN()
{
return pPositionX;
}
float Rect::getYN()
{
return -pPositionY*CORE->reversed_ratio;
}
Rect* Rect::setWidth(int aWidth)
{
setWidthN(2.f*((float)aWidth)/CORE->screen_width);
return this;
}
Rect* Rect::setHeight(int aHeight)
{
setHeightN(2.f*((float)aHeight)/CORE->screen_width);
return this;
}
Rect* Rect::set(int aX, int aY, int aWidth, int aHeight)
{
setX(aX);
setY(aY);
setWidth(aWidth);
setHeight(aHeight);
return this;
}
Rect* Rect::setN(float aX, float aY, float aWidth, float aHeight)
{
setXN(aX);
setYN(aY);
setWidthN(aWidth);
setHeightN(aHeight);
return this;
}
Rect* Rect::setWidthN(float width)
{
pHalfWidth=width*0.5f;
square_vertices[0] = -pHalfWidth;
square_vertices[2] = pHalfWidth;
square_vertices[4] = pHalfWidth;
square_vertices[6] = -pHalfWidth;
return this;
}
Rect* Rect::setHeightN(float height)
{
pHalfHeight=height*0.5f;
square_vertices[1] = -pHalfHeight;
square_vertices[3] = -pHalfHeight;
square_vertices[5] = pHalfHeight;
square_vertices[7] = pHalfHeight;
return this;
}
Rect* Rect::setSizeN(float width, float height)
{
setWidthN(width);
setHeightN(height);
return this;
}
Rect* Rect::setPositionN(float x, float y, Placement aPlacement)
{
setXN(x);
setYN(y);
setPlacement(aPlacement);
return this;
}
Rect* Rect::setPlacement(Placement aPlacement)
{
pPlacement = aPlacement;
return this;
}
Rect* Rect::setCenterN(float x, float y)
{
setXN(x);
setYN(y);
setPlacement(MID_CENTER);
return this;
}
Rect* Rect::setCornersN(float tl_x, float tl_y, float tr_x, float tr_y,
float bl_x, float bl_y, float br_x, float br_y)
{
square_vertices[0] = tl_x;
square_vertices[1] = tl_y;
square_vertices[2] = tr_x;
square_vertices[3] = tr_y;
square_vertices[4] = br_x;
square_vertices[5] = br_y;
square_vertices[6] = bl_x;
square_vertices[7] = bl_y;
pPositionX = 0;
pPositionY = 0;
return this;
}
bool Rect::initVariables()
{
const char* attribute_name;
const char* uniform_name;
attribute_name = "coord2d";
attribute_coord2d = GL_EXT_FUNC glGetAttribLocation(program, attribute_name);
if (attribute_coord2d == -1) {
fprintf(stderr, "Could not bind attribute %s\n", attribute_name);
return 0;
}
uniform_name = "anim";
uniform_anim = GL_EXT_FUNC glGetUniformLocation(program, uniform_name);
if (uniform_anim == -1) {
fprintf(stderr, "Could not bind uniform %s\n", uniform_name);
return 0;
}
uniform_name = "color";
uniform_color = GL_EXT_FUNC glGetUniformLocation(program, uniform_name);
if (uniform_color == -1) {
fprintf(stderr, "Could not bind uniform %s\n", uniform_name);
return 0;
}
GL_EXT_FUNC glGenBuffers(1, &vbo_square_vertices);
GL_EXT_FUNC glBindBuffer(GL_ARRAY_BUFFER, vbo_square_vertices);
GL_EXT_FUNC glBufferData(GL_ARRAY_BUFFER, sizeof(square_vertices), square_vertices, GL_STATIC_DRAW);
GLushort square_elements[] = {
// front
0, 1, 2,
2, 3, 0,
};
GL_EXT_FUNC glGenBuffers(1, &ibo_square_elements);
GL_EXT_FUNC glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_square_elements);
GL_EXT_FUNC glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(square_elements), square_elements, GL_STATIC_DRAW);
checkGlError("glBufferData");
return true;
}
bool Rect::setupGraphics() {
if (!program) {
program = createProgram(pVertexShader,pFragmentShader);
if (!program) {
LOGE("Could not create program.");
return false;
}
}
initVariables();
setReady();
return true;
}
void Rect::updateG(float sec, float deltaSec)
{
updateAnimation(sec,deltaSec);
// if(updateTranslationMat)
{
float translateX = pPositionX;
float translateY = pPositionY;
if(pPlacement & (PLACEMENT_LEFT | PLACEMENT_RIGHT))
{
translateX += pPlacement & PLACEMENT_RIGHT ? -pHalfWidth : pHalfWidth;
}
if(pPlacement & (PLACEMENT_TOP | PLACEMENT_BOTTOM))
{
translateY += (pPlacement & PLACEMENT_TOP ? -pHalfHeight : pHalfHeight)*CORE->ratio;
}
translate_mat = glm::translate(glm::mat4(1.0f), glm::vec3(translateX,translateY, 0.0));
}
scale = glm::scale(glm::mat4(1.0f), glm::vec3(1.f,CORE->ratio, 1.0));
rotate = glm::rotate(glm::mat4(1.0f), pAngle, glm::vec3(0.0, 0.0, 1.0)) ;
anim = translate_mat * scale * rotate;
Base::updateG(sec,deltaSec);
}
void Rect::enableAttributes() const
{
GL_EXT_FUNC glEnableVertexAttribArray(attribute_coord2d);
GL_EXT_FUNC glBindBuffer(GL_ARRAY_BUFFER, vbo_square_vertices);
GL_EXT_FUNC glBufferData(GL_ARRAY_BUFFER, sizeof(square_vertices), square_vertices, GL_STATIC_DRAW);
GL_EXT_FUNC glVertexAttribPointer(
attribute_coord2d, // attribute
2, // number of elements per vertex, here (x,y)
GL_FLOAT, // the type of each element
GL_FALSE, // take our values as-is
0, // next coord3d appears every 6 floats
0 // offset of first element
);
GL_EXT_FUNC glUniformMatrix4fv(uniform_anim, 1, GL_FALSE, glm::value_ptr(anim));
GL_EXT_FUNC glUniform4fv(uniform_color, 1, color);
}
void Rect::disableAttributes() const
{
GL_EXT_FUNC glDisableVertexAttribArray(attribute_coord2d);
checkGlError("glDisableVertexAttribArray");
}
void Rect::render() const
{
GL_EXT_FUNC glUseProgram(program);
checkGlError("glUseProgram");
enableAttributes();
GL_EXT_FUNC glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_square_elements);
int size;
GL_EXT_FUNC glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
glDrawElements(GL_TRIANGLES, size/sizeof(GLushort), GL_UNSIGNED_SHORT, 0);
checkGlError("glDrawElements");
disableAttributes();
}
void Rect::moveToN(float aTargetX, float aTargetY, float sec)
{
AnimationContainer* anim = new AnimationContainer();
anim->targetX = aTargetX;
anim->targetY = aTargetY;
anim->startX = getXN();
anim->startY = getYN();
anim->time = sec;
pAnimationList.push(anim);
}
void Rect::updateAnimation(float sec, float deltaSec)
{
if(pAnimationList.size())
{
AnimationContainer* anim = pAnimationList.front();
anim->elapsedTime += deltaSec;
float currentPosition = std::min(1.f, anim->elapsedTime / anim->time);
// currentPosition*=currentPosition;
if(anim->startX != anim->targetX){
setXN(anim->startX + (anim->targetX - anim->startX)*currentPosition);
}
if(anim->startY != anim->targetY){
setYN(anim->startY + (anim->targetY - anim->startY)*currentPosition);
}
if(currentPosition == 1.f)
{
std::map<EventListener*,EventListener*>::iterator it;
for(it = pEventListener.begin();it != pEventListener.end();it++)
{
it->first->onEvent(this, EVENT_ANIMATION_FINISHED);
}
pAnimationList.pop();
delete anim;
anim=0;
}
if(pAnimationList.size())
{
AnimationContainer* anim = pAnimationList.front();
anim->startX = getXN();
anim->startY = getYN();
}
}
}
bool Rect::isWithin(float Xn, float Yn)
{
//TODO: currently works only on centered rects
return Xn < pPositionX+pHalfWidth &&
Xn > pPositionX-pHalfWidth &&
Yn < pPositionY+pHalfHeight &&
Yn > pPositionY-pHalfHeight;
}
} /* namespace Gain */
<|endoftext|> |
<commit_before>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE libstorage
#include <boost/test/unit_test.hpp>
#include "storage/Utils/Math.h"
using namespace std;
using namespace storage;
BOOST_AUTO_TEST_CASE(test_is_power_of_two)
{
BOOST_CHECK(!is_power_of_two(0));
BOOST_CHECK(is_power_of_two(1));
BOOST_CHECK(is_power_of_two(2));
BOOST_CHECK(!is_power_of_two(3));
BOOST_CHECK(is_power_of_two(2048));
BOOST_CHECK(!is_power_of_two(2049));
}
BOOST_AUTO_TEST_CASE(test_next_power_of_two)
{
BOOST_CHECK_EQUAL(next_power_of_two(1), 1);
BOOST_CHECK_EQUAL(next_power_of_two(2), 2);
BOOST_CHECK_EQUAL(next_power_of_two(3), 4);
BOOST_CHECK_EQUAL(next_power_of_two(3), 4);
BOOST_CHECK_EQUAL(next_power_of_two(1000), 1024);
BOOST_CHECK_EQUAL(next_power_of_two((1ULL << 50) - 1), (1ULL << 50));
BOOST_CHECK_EQUAL(next_power_of_two((1ULL << 50)), (1ULL << 50));
BOOST_CHECK_EQUAL(next_power_of_two((1ULL << 50) + 1), (1ULL << 51));
}
BOOST_AUTO_TEST_CASE(test_round_down)
{
BOOST_CHECK_EQUAL(round_down(9, 10), 0);
BOOST_CHECK_EQUAL(round_down(10, 10), 10);
BOOST_CHECK_EQUAL(round_down(11, 10), 10);
}
BOOST_AUTO_TEST_CASE(test_round_up)
{
BOOST_CHECK_EQUAL(round_up(9, 10), 10);
BOOST_CHECK_EQUAL(round_up(10, 10), 10);
BOOST_CHECK_EQUAL(round_up(11, 10), 20);
}
<commit_msg>- fixed test<commit_after>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE libstorage
#include <boost/test/unit_test.hpp>
#include "storage/Utils/Math.h"
using namespace std;
using namespace storage;
BOOST_AUTO_TEST_CASE(test_is_power_of_two)
{
BOOST_CHECK(!is_power_of_two(0));
BOOST_CHECK(is_power_of_two(1));
BOOST_CHECK(is_power_of_two(2));
BOOST_CHECK(!is_power_of_two(3));
BOOST_CHECK(is_power_of_two(2048));
BOOST_CHECK(!is_power_of_two(2049));
}
BOOST_AUTO_TEST_CASE(test_next_power_of_two)
{
BOOST_CHECK_EQUAL(next_power_of_two(1), 1);
BOOST_CHECK_EQUAL(next_power_of_two(2), 2);
BOOST_CHECK_EQUAL(next_power_of_two(3), 4);
BOOST_CHECK_EQUAL(next_power_of_two(4), 4);
BOOST_CHECK_EQUAL(next_power_of_two(1000), 1024);
BOOST_CHECK_EQUAL(next_power_of_two((1ULL << 50) - 1), (1ULL << 50));
BOOST_CHECK_EQUAL(next_power_of_two((1ULL << 50)), (1ULL << 50));
BOOST_CHECK_EQUAL(next_power_of_two((1ULL << 50) + 1), (1ULL << 51));
}
BOOST_AUTO_TEST_CASE(test_round_down)
{
BOOST_CHECK_EQUAL(round_down(9, 10), 0);
BOOST_CHECK_EQUAL(round_down(10, 10), 10);
BOOST_CHECK_EQUAL(round_down(11, 10), 10);
}
BOOST_AUTO_TEST_CASE(test_round_up)
{
BOOST_CHECK_EQUAL(round_up(9, 10), 10);
BOOST_CHECK_EQUAL(round_up(10, 10), 10);
BOOST_CHECK_EQUAL(round_up(11, 10), 20);
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
// Macro to setup AliPerformanceTask for
// TPC performance QA to run on PWG1 QA train.
//
// Input: ESDs, ESDfriends (optional), Kinematics (optional), TrackRefs (optional)
// ESD and MC input handlers must be attached to AliAnalysisManager
// to run default configuration.
//
// By default 1 performance components are added to
// the task:
// 1. AliPerformanceTPC (TPC cluster and track and event information)
// 2. AliPerformancedEdx (TPC dEdx information)
//
// Usage on the analysis train (default configuration):
// gSystem->Load("libANALYSIS");
// gSystem->Load("libANALYSISalice");
// gSystem->Load("libTPCcalib.so");
// gSystem->Load("libTENDER.so");
// gSystem->Load("libPWG1.so");
//
// gROOT->LoadMacro("$ALICE_ROOT/PWG1/TPC/macros/AddTaskPerformanceTPCdEdxQA.C");
// AliPerformanceTask *tpcQA = AddTaskPerformanceTPCdEdxQA("kFALSE","kTRUE","kFALSE","triggerClass");
//
// Output:
// TPC.Performance.root file with TPC performance components is created.
//
// Each of the components contains THnSparse generic histograms which
// have to be analysed (post-analysis) by using Analyse() function.
// Each component contains such function.
//
//30.09.2010 - J.Otwinowski@gsi.de
///////////////////////////////////////////////////////////////////////////////
//____________________________________________
AliPerformanceTask* AddTaskPerformanceTPCdEdxQA(Bool_t bUseMCInfo=kFALSE, Bool_t bUseESDfriend=kTRUE, Bool_t highMult = kFALSE, const char *triggerClass=0)
{
//
// Add AliPerformanceTask with TPC performance components
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if(!mgr) {
Error("AddTaskPerformanceTPCdEdxQA","AliAnalysisManager not set!");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType();
if (!type.Contains("ESD")) {
Error("AddTaskPerformanceTPCdEdxQA", "ESD input handler needed!");
return NULL;
}
AliMCEventHandler *mcH = (AliMCEventHandler*)mgr->GetMCtruthEventHandler();
if (!mcH && bUseMCInfo) {
Error("AddTaskPerformanceTPCdEdxQA", "MC input handler needed!");
return NULL;
}
//
// Create task
//
AliPerformanceTask *task = new AliPerformanceTask("PerformanceQA","TPC Performance");
if (!task) {
Error("AddTaskPerformanceTPCdEdxQA", "TPC performance task cannot be created!");
return NULL;
}
task->SetUseMCInfo(bUseMCInfo);
task->SetUseESDfriend(bUseESDfriend);
// task->SetUseTerminate(kFALSE);
//
// Add task to analysis manager
//
mgr->AddTask(task);
//
// Create TPC-ESD track reconstruction cuts
// MB tracks
//
AliRecInfoCuts *pRecInfoCutsTPC = new AliRecInfoCuts();
if(pRecInfoCutsTPC) {
pRecInfoCutsTPC->SetMaxDCAToVertexXY(3.0);
pRecInfoCutsTPC->SetMaxDCAToVertexZ(3.0);
pRecInfoCutsTPC->SetRequireSigmaToVertex(kFALSE);
pRecInfoCutsTPC->SetRequireTPCRefit(kFALSE);
pRecInfoCutsTPC->SetAcceptKinkDaughters(kFALSE);
pRecInfoCutsTPC->SetMinNClustersTPC(70);
pRecInfoCutsTPC->SetMaxChi2PerClusterTPC(4.);
pRecInfoCutsTPC->SetDCAToVertex2D(kTRUE);
pRecInfoCutsTPC->SetHistogramsOn(kFALSE);
}
else {
Error("AddTaskPerformanceTPC", "AliRecInfoCutsTPC cannot be created!");
return NULL;
}
//
// Create TPC-MC track reconstruction cuts
//
AliMCInfoCuts *pMCInfoCuts = new AliMCInfoCuts();
if(pMCInfoCuts) {
pMCInfoCuts->SetMinTrackLength(70);
}
else {
Error("AddTaskPerformanceTPC", "AliMCInfoCuts cannot be created!");
return NULL;
}
//
// Create performance objects for TPC and set cuts
//
enum { kTPC = 0, kTPCITS, kConstrained, kTPCInner, kTPCOuter, kTPCSec };
//
// TPC performance
//
AliPerformanceTPC *pCompTPC0 = new AliPerformanceTPC("AliPerformanceTPC","AliPerformanceTPC",kTPC,kFALSE,-1,highMult);
if(!pCompTPC0) {
Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceTPC");
}
pCompTPC0->SetAliRecInfoCuts(pRecInfoCutsTPC);
pCompTPC0->SetAliMCInfoCuts(pMCInfoCuts);
// pCompTPC0->SetUseTrackVertex(kFALSE);
pCompTPC0->SetUseTrackVertex(kTRUE);
pCompTPC0->SetUseHLT(kFALSE);
pCompTPC0->SetUseTOFBunchCrossing(kTRUE);
//
// TPC ITS match
//
AliPerformanceMatch *pCompMatch1 = new AliPerformanceMatch("AliPerformanceMatchTPCITS","AliPerformanceMatchTPCITS",0,kFALSE);
if(!pCompMatch1) {
Error("AddTaskPerformanceMatch", "Cannot create AliPerformanceMatchTPCITS");
}
pCompMatch1->SetAliRecInfoCuts(pRecInfoCutsTPC);
pCompMatch1->SetAliMCInfoCuts(pMCInfoCuts);
pCompMatch1->SetUseTOFBunchCrossing(kTRUE);
//
// ITS TPC match
//
AliPerformanceMatch *pCompMatch2 = new AliPerformanceMatch("AliPerformanceMatchITSTPC","AliPerformanceMatchITSTPC",1,kFALSE);
if(!pCompMatch2) {
Error("AddTaskPerformanceMatch", "Cannot create AliPerformanceMatchITSTPC"); }
pCompMatch2->SetAliRecInfoCuts(pRecInfoCutsTPC);
pCompMatch2->SetAliMCInfoCuts(pMCInfoCuts);
pCompMatch2->SetUseTOFBunchCrossing(kTRUE);
//
// dEdx
//
AliPerformanceDEdx *pCompDEdx3 = new AliPerformanceDEdx("AliPerformanceDEdxTPCInner","AliPerformanceDEdxTPCInner",kTPCInner,kFALSE);
if(!pCompDEdx3) {
Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceDEdxTPCInner");
}
pCompDEdx3->SetAliRecInfoCuts(pRecInfoCutsTPC);
pCompDEdx3->SetAliMCInfoCuts(pMCInfoCuts);
//pCompDEdx3->SetUseTrackVertex(kFALSE);
pCompDEdx3->SetUseTrackVertex(kTRUE);
//
// Add components to the performance task
//
if(!bUseMCInfo) {
pCompTPC0->SetTriggerClass(triggerClass);
pCompMatch1->SetTriggerClass(triggerClass);
pCompMatch2->SetTriggerClass(triggerClass);
pCompDEdx3->SetTriggerClass(triggerClass);
}
task->AddPerformanceObject( pCompTPC0 );
task->AddPerformanceObject( pCompMatch1 );
task->AddPerformanceObject( pCompMatch2 );
task->AddPerformanceObject( pCompDEdx3 );
//
// Create containers for input
//
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
//
// Create containers for output
//
AliAnalysisDataContainer *coutput_tpc = mgr->CreateContainer("TPCQA", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TPC_%s", mgr->GetCommonFileName(), task->GetName()));
AliAnalysisDataContainer *coutput2_tpc = mgr->CreateContainer("TPCQASummary", TTree::Class(), AliAnalysisManager::kParamContainer, "trending.root:SummaryTPCQA");
mgr->ConnectOutput(task, 1, coutput_tpc);
mgr->ConnectOutput(task, 0, coutput2_tpc);
return task;
}
<commit_msg>update to allow HLT and TPC to run from the same AddTaskMacro<commit_after>///////////////////////////////////////////////////////////////////////////////
// Macro to setup AliPerformanceTask for
// TPC performance QA to run on PWG1 QA train.
//
// Input: ESDs, ESDfriends (optional), Kinematics (optional), TrackRefs (optional)
// ESD and MC input handlers must be attached to AliAnalysisManager
// to run default configuration.
//
// By default 1 performance components are added to
// the task:
// 0. AliPerformanceTPC (TPC cluster and track and event information)
// 1. AliPerformanceMatch (TPC and ITS/TRD matching and TPC eff w.r.t ITS)
// 2. AliPerformanceMatch (TPC and ITS/TRD matching and TPC eff w.r.t TPC)
// 3. AliPerformancedEdx (TPC dEdx information)
// 4. AliPerformanceRes (TPC track resolution w.r.t MC at DCA)
// 5. AliPerformanceEff (TPC track reconstruction efficiency, MC primaries)
//
// Usage on the analysis train (default configuration):
// gSystem->Load("libANALYSIS");
// gSystem->Load("libANALYSISalice");
// gSystem->Load("libTPCcalib.so");
// gSystem->Load("libTENDER.so");
// gSystem->Load("libPWG1.so");
//
// gROOT->LoadMacro("$ALICE_ROOT/PWG1/TPC/macros/AddTaskPerformanceTPCdEdxQA.C");
// AliPerformanceTask *tpcQA = AddTaskPerformanceTPCdEdxQA("kFALSE","kTRUE","kFALSE","triggerClass",kFALSE);
//
// Output:
// TPC.Performance.root file with TPC performance components is created.
//
// Each of the components contains THnSparse generic histograms which
// have to be analysed (post-analysis) by using Analyse() function.
// Each component contains such function.
//
//30.09.2010 - J.Otwinowski@gsi.de
//22.09.2011 - jochen@thaeder.de - Updated
///////////////////////////////////////////////////////////////////////////////
//____________________________________________
AliPerformanceTask* AddTaskPerformanceTPCdEdxQA(Bool_t bUseMCInfo=kFALSE, Bool_t bUseESDfriend=kTRUE,
Bool_t highMult = kFALSE, const char *triggerClass=0,
Bool_t bUseHLT = kFALSE)
{
Char_t *taskName[] = {"TPC", "HLT"};
Int_t idx = 0;
if (bUseHLT) idx = 1;
//
// Add AliPerformanceTask with TPC performance components
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if(!mgr) {
Error("AddTaskPerformanceTPCdEdxQA","AliAnalysisManager not set!");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType();
if (!type.Contains("ESD")) {
Error("AddTaskPerformanceTPCdEdxQA", "ESD input handler needed!");
return NULL;
}
AliMCEventHandler *mcH = (AliMCEventHandler*)mgr->GetMCtruthEventHandler();
if (!mcH && bUseMCInfo) {
Error("AddTaskPerformanceTPCdEdxQA", "MC input handler needed!");
return NULL;
}
//
// Add HLT Event
//
if (bUseHLT) {
AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*>(mgr->GetInputEventHandler());
esdH->SetReadHLT();
}
//
// Create task
//
AliPerformanceTask *task = new AliPerformanceTask("PerformanceQA",Form("%s Performance",taskName[idx]));
if (!task) {
Error("AddTaskPerformanceTPCdEdxQA", Form("%s performance task cannot be created!",taskName[idx]));
return NULL;
}
task->SetUseMCInfo(bUseMCInfo);
task->SetUseESDfriend(bUseESDfriend);
// task->SetUseTerminate(kFALSE);
task->SetUseHLT(bUseHLT);
//
// Add task to analysis manager
//
mgr->AddTask(task);
//
// Create TPC-ESD track reconstruction cuts
// MB tracks
//
AliRecInfoCuts *pRecInfoCutsTPC = new AliRecInfoCuts();
if(pRecInfoCutsTPC) {
pRecInfoCutsTPC->SetMaxDCAToVertexXY(3.0);
pRecInfoCutsTPC->SetMaxDCAToVertexZ(3.0);
pRecInfoCutsTPC->SetRequireSigmaToVertex(kFALSE);
pRecInfoCutsTPC->SetRequireTPCRefit(kFALSE);
pRecInfoCutsTPC->SetAcceptKinkDaughters(kFALSE);
pRecInfoCutsTPC->SetMinNClustersTPC(70);
pRecInfoCutsTPC->SetMaxChi2PerClusterTPC(4.);
pRecInfoCutsTPC->SetDCAToVertex2D(kTRUE);
pRecInfoCutsTPC->SetHistogramsOn(kFALSE);
}
else {
Error("AddTaskPerformanceTPCdEdxQA", "AliRecInfoCutsTPC cannot be created!");
return NULL;
}
//
// Create TPC-MC track reconstruction cuts
//
AliMCInfoCuts *pMCInfoCuts = new AliMCInfoCuts();
if(pMCInfoCuts) {
pMCInfoCuts->SetMinTrackLength(70);
}
else {
Error("AddTaskPerformanceTPCdEdxQA", "AliMCInfoCuts cannot be created!");
return NULL;
}
//
// Create performance objects for TPC and set cuts
//
enum { kTPC = 0, kTPCITS, kConstrained, kTPCInner, kTPCOuter, kTPCSec };
//
// TPC performance
//
AliPerformanceTPC *pCompTPC0 = new AliPerformanceTPC("AliPerformanceTPC","AliPerformanceTPC",kTPC,kFALSE,-1,highMult);
if(!pCompTPC0) {
Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceTPC");
}
pCompTPC0->SetAliRecInfoCuts(pRecInfoCutsTPC);
pCompTPC0->SetAliMCInfoCuts(pMCInfoCuts);
// pCompTPC0->SetUseTrackVertex(kFALSE);
pCompTPC0->SetUseTrackVertex(kTRUE);
pCompTPC0->SetUseHLT(bUseHLT);
pCompTPC0->SetUseTOFBunchCrossing(kTRUE);
//
// TPC ITS match
//
AliPerformanceMatch *pCompMatch1 = new AliPerformanceMatch("AliPerformanceMatchTPCITS","AliPerformanceMatchTPCITS",0,kFALSE);
if(!pCompMatch1) {
Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceMatchTPCITS");
}
pCompMatch1->SetAliRecInfoCuts(pRecInfoCutsTPC);
pCompMatch1->SetAliMCInfoCuts(pMCInfoCuts);
pCompMatch1->SetUseTOFBunchCrossing(kTRUE);
//
// ITS TPC match
//
AliPerformanceMatch *pCompMatch2 = new AliPerformanceMatch("AliPerformanceMatchITSTPC","AliPerformanceMatchITSTPC",1,kFALSE);
if(!pCompMatch2) {
Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceMatchITSTPC"); }
pCompMatch2->SetAliRecInfoCuts(pRecInfoCutsTPC);
pCompMatch2->SetAliMCInfoCuts(pMCInfoCuts);
pCompMatch2->SetUseTOFBunchCrossing(kTRUE);
//
// dEdx
//
AliPerformanceDEdx *pCompDEdx3 = new AliPerformanceDEdx("AliPerformanceDEdxTPCInner","AliPerformanceDEdxTPCInner",kTPCInner,kFALSE);
if(!pCompDEdx3) {
Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceDEdxTPCInner");
}
pCompDEdx3->SetAliRecInfoCuts(pRecInfoCutsTPC);
pCompDEdx3->SetAliMCInfoCuts(pMCInfoCuts);
//pCompDEdx3->SetUseTrackVertex(kFALSE);
pCompDEdx3->SetUseTrackVertex(kTRUE);
//
// Resolution ------------------------------------------------------------------------------------
//
AliPerformanceRes *pCompRes4 = new AliPerformanceRes("AliPerformanceRes",
"AliPerformanceRes",kTPC,kFALSE);
if(!pCompRes4) {
Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceRes");
}
pCompRes4->SetAliRecInfoCuts(pRecInfoCutsTPC);
pCompRes4->SetAliMCInfoCuts(pMCInfoCuts);
pCompRes4->SetUseTrackVertex(kTRUE);
//
// Efficiency ------------------------------------------------------------------------------------
//
AliPerformanceEff *pCompEff5 = new AliPerformanceEff("AliPerformanceEff",
"AliPerformanceEff",kTPC,kFALSE);
if(!pCompEff5) {
Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceEff");
}
pCompEff5->SetAliRecInfoCuts(pRecInfoCutsTPC);
pCompEff5->SetAliMCInfoCuts(pMCInfoCuts);
pCompEff5->SetUseTrackVertex(kTRUE);
//
// Add components to the performance task
//
if(!bUseMCInfo) {
pCompTPC0->SetTriggerClass(triggerClass);
pCompMatch1->SetTriggerClass(triggerClass);
pCompMatch2->SetTriggerClass(triggerClass);
pCompDEdx3->SetTriggerClass(triggerClass);
}
task->AddPerformanceObject( pCompTPC0 );
task->AddPerformanceObject( pCompMatch1 );
task->AddPerformanceObject( pCompMatch2 );
task->AddPerformanceObject( pCompDEdx3 );
if(bUseMCInfo) {
task->AddPerformanceObject( pCompRes4 );
task->AddPerformanceObject( pCompEff5 );
}
//
// Create containers for input
//
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
//
// Create containers for output
//
AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("%sQA", taskName[idx]), TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:%s_%s", mgr->GetCommonFileName(), taskName[idx],task->GetName()));
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(Form("%sQASummary", taskName[idx]), TTree::Class(),
AliAnalysisManager::kParamContainer,
Form("trending.root:Summary%sQA", taskName[idx]));
mgr->ConnectOutput(task, 1, coutput);
mgr->ConnectOutput(task, 0, coutput2);
return task;
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////
// //
// AliFemtoAnalysis - the most basic analysis there is. All other //
// inherit from this one. Provides basic functionality for the analysis. //
// To properly set up the analysis the following steps should be taken: //
// //
// - create particle cuts and add them via SetFirstParticleCut and //
// SetSecondParticleCut. If one analyzes identical particle //
// correlations, the first particle cut must be also the second //
// particle cut. //
// //
// - create pair cuts and add them via SetPairCut //
// //
// - create one or many correlation functions and add them via //
// AddCorrFctn method. //
// //
// - specify how many events are to be strored in the mixing buffer for //
// background construction //
// //
// Then, when the analysis is run, for each event, the EventBegin is //
// called before any processing is done, then the ProcessEvent is called //
// which takes care of creating real and mixed pairs and sending them //
// to all the registered correlation functions. At the end of each event,//
// after all pairs are processed, EventEnd is called. After the whole //
// analysis finishes (there is no more events to process) Finish() is //
// called. //
// //
///////////////////////////////////////////////////////////////////////////
#include "AliFemtoAnalysis.h"
#include "AliFemtoTrackCut.h"
#include "AliFemtoV0Cut.h"
#include "AliFemtoKinkCut.h"
#include <string>
#include <iostream>
#ifdef __ROOT__
ClassImp(AliFemtoAnalysis)
#endif
AliFemtoEventCut* copyTheCut(AliFemtoEventCut*);
AliFemtoParticleCut* copyTheCut(AliFemtoParticleCut*);
AliFemtoPairCut* copyTheCut(AliFemtoPairCut*);
AliFemtoCorrFctn* copyTheCorrFctn(AliFemtoCorrFctn*);
// this little function used to apply ParticleCuts (TrackCuts or V0Cuts) and fill ParticleCollections of picoEvent
// it is called from AliFemtoAnalysis::ProcessEvent()
void FillHbtParticleCollection(AliFemtoParticleCut* partCut,
AliFemtoEvent* hbtEvent,
AliFemtoParticleCollection* partCollection)
{
// Fill particle collections from the event
// by the particles that pass all the cuts
switch (partCut->Type()) {
case hbtTrack: // cut is cutting on Tracks
{
AliFemtoTrackCut* pCut = (AliFemtoTrackCut*) partCut;
AliFemtoTrack* pParticle;
AliFemtoTrackIterator pIter;
AliFemtoTrackIterator startLoop = hbtEvent->TrackCollection()->begin();
AliFemtoTrackIterator endLoop = hbtEvent->TrackCollection()->end();
for (pIter=startLoop;pIter!=endLoop;pIter++){
pParticle = *pIter;
bool tmpPassParticle = pCut->Pass(pParticle);
pCut->FillCutMonitor(pParticle, tmpPassParticle);
if (tmpPassParticle){
AliFemtoParticle* particle = new AliFemtoParticle(pParticle,pCut->Mass());
partCollection->push_back(particle);
}
}
break;
}
case hbtV0: // cut is cutting on V0s
{
AliFemtoV0Cut* pCut = (AliFemtoV0Cut*) partCut;
AliFemtoV0* pParticle;
AliFemtoV0Iterator pIter;
AliFemtoV0Iterator startLoop = hbtEvent->V0Collection()->begin();
AliFemtoV0Iterator endLoop = hbtEvent->V0Collection()->end();
// this following "for" loop is identical to the one above, but because of scoping, I can's see how to avoid repitition...
for (pIter=startLoop;pIter!=endLoop;pIter++){
pParticle = *pIter;
bool tmpPassV0 = pCut->Pass(pParticle);
pCut->FillCutMonitor(pParticle,tmpPassV0);
if (tmpPassV0){
AliFemtoParticle* particle = new AliFemtoParticle(pParticle,partCut->Mass());
partCollection->push_back(particle);
}
}
pCut->FillCutMonitor(hbtEvent,partCollection);// Gael 19/06/02
break;
}
case hbtKink: // cut is cutting on Kinks -- mal 25May2001
{
AliFemtoKinkCut* pCut = (AliFemtoKinkCut*) partCut;
AliFemtoKink* pParticle;
AliFemtoKinkIterator pIter;
AliFemtoKinkIterator startLoop = hbtEvent->KinkCollection()->begin();
AliFemtoKinkIterator endLoop = hbtEvent->KinkCollection()->end();
// this following "for" loop is identical to the one above, but because of scoping, I can's see how to avoid repitition...
for (pIter=startLoop;pIter!=endLoop;pIter++){
pParticle = *pIter;
bool tmpPass = pCut->Pass(pParticle);
pCut->FillCutMonitor(pParticle,tmpPass);
if (tmpPass){
AliFemtoParticle* particle = new AliFemtoParticle(pParticle,partCut->Mass());
partCollection->push_back(particle);
}
}
break;
}
default:
cout << "FillHbtParticleCollection function (in AliFemtoAnalysis.cxx) - undefined Particle Cut type!!! \n";
}
}
//____________________________
AliFemtoAnalysis::AliFemtoAnalysis() :
fPicoEventCollectionVectorHideAway(0),
fPairCut(0),
fCorrFctnCollection(0),
fEventCut(0),
fFirstParticleCut(0),
fSecondParticleCut(0),
fMixingBuffer(0),
fPicoEvent(0),
fNumEventsToMix(0),
fNeventsProcessed(0),
fMinSizePartCollection(0)
{
// Default constructor
// mControlSwitch = 0;
fCorrFctnCollection = new AliFemtoCorrFctnCollection;
fMixingBuffer = new AliFemtoPicoEventCollection;
}
//____________________________
AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) :
AliFemtoBaseAnalysis(),
fPicoEventCollectionVectorHideAway(0),
fPairCut(0),
fCorrFctnCollection(0),
fEventCut(0),
fFirstParticleCut(0),
fSecondParticleCut(0),
fMixingBuffer(0),
fPicoEvent(0),
fNumEventsToMix(0),
fNeventsProcessed(0),
fMinSizePartCollection(0)
{
// Copy constructor
//AliFemtoAnalysis();
fCorrFctnCollection = new AliFemtoCorrFctnCollection;
fMixingBuffer = new AliFemtoPicoEventCollection;
// find the right event cut
fEventCut = a.fEventCut->Clone();
// find the right first particle cut
fFirstParticleCut = a.fFirstParticleCut->Clone();
// find the right second particle cut
if (a.fFirstParticleCut==a.fSecondParticleCut)
SetSecondParticleCut(fFirstParticleCut); // identical particle hbt
else
fSecondParticleCut = a.fSecondParticleCut->Clone();
fPairCut = a.fPairCut->Clone();
if ( fEventCut ) {
SetEventCut(fEventCut); // this will set the myAnalysis pointer inside the cut
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - event cut set " << endl;
}
if ( fFirstParticleCut ) {
SetFirstParticleCut(fFirstParticleCut); // this will set the myAnalysis pointer inside the cut
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - first particle cut set " << endl;
}
if ( fSecondParticleCut ) {
SetSecondParticleCut(fSecondParticleCut); // this will set the myAnalysis pointer inside the cut
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - second particle cut set " << endl;
} if ( fPairCut ) {
SetPairCut(fPairCut); // this will set the myAnalysis pointer inside the cut
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - pair cut set " << endl;
}
AliFemtoCorrFctnIterator iter;
for (iter=a.fCorrFctnCollection->begin(); iter!=a.fCorrFctnCollection->end();iter++){
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - looking for correlation functions " << endl;
AliFemtoCorrFctn* fctn = (*iter)->Clone();
if (fctn) AddCorrFctn(fctn);
else cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - correlation function not found " << endl;
}
fNumEventsToMix = a.fNumEventsToMix;
fMinSizePartCollection = a.fMinSizePartCollection; // minimum # particles in ParticleCollection
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - analysis copied " << endl;
}
//____________________________
AliFemtoAnalysis::~AliFemtoAnalysis(){
// destructor
cout << " AliFemtoAnalysis::~AliFemtoAnalysis()" << endl;
if (fEventCut) delete fEventCut; fEventCut=0;
if (fFirstParticleCut == fSecondParticleCut) fSecondParticleCut=0;
if (fFirstParticleCut) delete fFirstParticleCut; fFirstParticleCut=0;
if (fSecondParticleCut) delete fSecondParticleCut; fSecondParticleCut=0;
if (fPairCut) delete fPairCut; fPairCut=0;
// now delete every CorrFunction in the Collection, and then the Collection itself
AliFemtoCorrFctnIterator iter;
for (iter=fCorrFctnCollection->begin(); iter!=fCorrFctnCollection->end();iter++){
delete *iter;
}
delete fCorrFctnCollection;
// now delete every PicoEvent in the EventMixingBuffer and then the Buffer itself
if (fMixingBuffer) {
AliFemtoPicoEventIterator piter;
for (piter=fMixingBuffer->begin();piter!=fMixingBuffer->end();piter++){
delete *piter;
}
delete fMixingBuffer;
}
}
//______________________
AliFemtoAnalysis& AliFemtoAnalysis::operator=(const AliFemtoAnalysis& aAna)
{
// Assignment operator
if (this == &aAna)
return *this;
fCorrFctnCollection = new AliFemtoCorrFctnCollection;
fMixingBuffer = new AliFemtoPicoEventCollection;
// find the right event cut
fEventCut = aAna.fEventCut->Clone();
// find the right first particle cut
fFirstParticleCut = aAna.fFirstParticleCut->Clone();
// find the right second particle cut
if (aAna.fFirstParticleCut==aAna.fSecondParticleCut)
SetSecondParticleCut(fFirstParticleCut); // identical particle hbt
else
fSecondParticleCut = aAna.fSecondParticleCut->Clone();
fPairCut = aAna.fPairCut->Clone();
if ( fEventCut ) {
SetEventCut(fEventCut); // this will set the myAnalysis pointer inside the cut
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - event cut set " << endl;
}
if ( fFirstParticleCut ) {
SetFirstParticleCut(fFirstParticleCut); // this will set the myAnalysis pointer inside the cut
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - first particle cut set " << endl;
}
if ( fSecondParticleCut ) {
SetSecondParticleCut(fSecondParticleCut); // this will set the myAnalysis pointer inside the cut
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - second particle cut set " << endl;
} if ( fPairCut ) {
SetPairCut(fPairCut); // this will set the myAnalysis pointer inside the cut
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - pair cut set " << endl;
}
AliFemtoCorrFctnIterator iter;
for (iter=aAna.fCorrFctnCollection->begin(); iter!=aAna.fCorrFctnCollection->end();iter++){
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - looking for correlation functions " << endl;
AliFemtoCorrFctn* fctn = (*iter)->Clone();
if (fctn) AddCorrFctn(fctn);
else cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - correlation function not found " << endl;
}
fNumEventsToMix = aAna.fNumEventsToMix;
fMinSizePartCollection = aAna.fMinSizePartCollection; // minimum # particles in ParticleCollection
cout << " AliFemtoAnalysis::AliFemtoAnalysis(const AliFemtoAnalysis& a) - analysis copied " << endl;
return *this;
}
//______________________
AliFemtoCorrFctn* AliFemtoAnalysis::CorrFctn(int n){
// return pointer to n-th correlation function
if ( n<0 || n > (int)fCorrFctnCollection->size() )
return NULL;
AliFemtoCorrFctnIterator iter=fCorrFctnCollection->begin();
for (int i=0; i<n ;i++){
iter++;
}
return *iter;
}
//____________________________
AliFemtoString AliFemtoAnalysis::Report()
{
// Create a simple report from the analysis execution
cout << "AliFemtoAnalysis - constructing Report..."<<endl;
string temp = "-----------\nHbt Analysis Report:\n";
temp += "\nEvent Cuts:\n";
temp += fEventCut->Report();
temp += "\nParticle Cuts - First Particle:\n";
temp += fFirstParticleCut->Report();
temp += "\nParticle Cuts - Second Particle:\n";
temp += fSecondParticleCut->Report();
temp += "\nPair Cuts:\n";
temp += fPairCut->Report();
temp += "\nCorrelation Functions:\n";
AliFemtoCorrFctnIterator iter;
if ( fCorrFctnCollection->size()==0 ) {
cout << "AliFemtoAnalysis-Warning : no correlations functions in this analysis " << endl;
}
for (iter=fCorrFctnCollection->begin(); iter!=fCorrFctnCollection->end();iter++){
temp += (*iter)->Report();
temp += "\n";
}
temp += "-------------\n";
AliFemtoString returnThis=temp;
return returnThis;
}
//_________________________
void AliFemtoAnalysis::ProcessEvent(const AliFemtoEvent* hbtEvent) {
// Add event to processed events
fPicoEvent=0; // we will get a new pico event, if not prevent corr. fctn to access old pico event
AddEventProcessed();
// startup for EbyE
EventBegin(hbtEvent);
// event cut and event cut monitor
bool tmpPassEvent = fEventCut->Pass(hbtEvent);
fEventCut->FillCutMonitor(hbtEvent, tmpPassEvent);
if (tmpPassEvent) {
cout << "AliFemtoAnalysis::ProcessEvent() - Event has passed cut - build picoEvent from " <<
hbtEvent->TrackCollection()->size() << " tracks in TrackCollection" << endl;
// OK, analysis likes the event-- build a pico event from it, using tracks the analysis likes...
fPicoEvent = new AliFemtoPicoEvent; // this is what we will make pairs from and put in Mixing Buffer
// no memory leak. we will delete picoevents when they come out of the mixing buffer
FillHbtParticleCollection(fFirstParticleCut,(AliFemtoEvent*)hbtEvent,fPicoEvent->FirstParticleCollection());
if ( !(AnalyzeIdenticalParticles()) )
FillHbtParticleCollection(fSecondParticleCut,(AliFemtoEvent*)hbtEvent,fPicoEvent->SecondParticleCollection());
cout <<"AliFemtoAnalysis::ProcessEvent - #particles in First, Second Collections: " <<
fPicoEvent->FirstParticleCollection()->size() << " " <<
fPicoEvent->SecondParticleCollection()->size() << endl;
// mal - implement a switch which allows only using events with ParticleCollections containing a minimum
// number of entries (jun2002)
if ((fPicoEvent->FirstParticleCollection()->size() >= fMinSizePartCollection )
&& ( AnalyzeIdenticalParticles() || (fPicoEvent->SecondParticleCollection()->size() >= fMinSizePartCollection ))) {
//------------------------------------------------------------------------------
// Temporary comment:
// This whole section rewritten so that all pairs are built using the
// same code... easier to read and manage, and MakePairs() can be called by
// derived classes. Also, the requirement of a full mixing buffer before
// mixing is removed.
// Dan Magestro, 11/2002
//------ Make real pairs. If identical, make pairs for one collection ------//
if (AnalyzeIdenticalParticles()) {
MakePairs("real", fPicoEvent->FirstParticleCollection() );
}
else {
MakePairs("real", fPicoEvent->FirstParticleCollection(),
fPicoEvent->SecondParticleCollection() );
}
cout << "AliFemtoAnalysis::ProcessEvent() - reals done ";
//---- Make pairs for mixed events, looping over events in mixingBuffer ----//
AliFemtoPicoEvent* storedEvent;
AliFemtoPicoEventIterator fPicoEventIter;
for (fPicoEventIter=MixingBuffer()->begin();fPicoEventIter!=MixingBuffer()->end();fPicoEventIter++){
storedEvent = *fPicoEventIter;
if (AnalyzeIdenticalParticles()) {
MakePairs("mixed",fPicoEvent->FirstParticleCollection(),
storedEvent->FirstParticleCollection() );
}
else {
MakePairs("mixed",fPicoEvent->FirstParticleCollection(),
storedEvent->SecondParticleCollection() );
MakePairs("mixed",storedEvent->FirstParticleCollection(),
fPicoEvent->SecondParticleCollection() );
}
}
cout << " - mixed done " << endl;
//--------- If mixing buffer is full, delete oldest event ---------//
if ( MixingBufferFull() ) {
delete MixingBuffer()->back();
MixingBuffer()->pop_back();
}
//-------- Add current event (fPicoEvent) to mixing buffer --------//
MixingBuffer()->push_front(fPicoEvent);
// Temporary comment: End of rewritten section... Dan Magestro, 11/2002
//------------------------------------------------------------------------------
} // if ParticleCollections are big enough (mal jun2002)
else{
delete fPicoEvent;
}
} // if currentEvent is accepted by currentAnalysis
EventEnd(hbtEvent); // cleanup for EbyE
//cout << "AliFemtoAnalysis::ProcessEvent() - return to caller ... " << endl;
}
//_________________________
void AliFemtoAnalysis::MakePairs(const char* typeIn, AliFemtoParticleCollection *partCollection1,
AliFemtoParticleCollection *partCollection2){
// Build pairs, check pair cuts, and call CFs' AddRealPair() or
// AddMixedPair() methods. If no second particle collection is
// specfied, make pairs within first particle collection.
string type = typeIn;
AliFemtoPair* tPair = new AliFemtoPair;
AliFemtoCorrFctnIterator tCorrFctnIter;
AliFemtoParticleIterator tPartIter1, tPartIter2;
AliFemtoParticleIterator tStartOuterLoop = partCollection1->begin(); // always
AliFemtoParticleIterator tEndOuterLoop = partCollection1->end(); // will be one less if identical
AliFemtoParticleIterator tStartInnerLoop;
AliFemtoParticleIterator tEndInnerLoop;
if (partCollection2) { // Two collections:
tStartInnerLoop = partCollection2->begin(); // Full inner & outer loops
tEndInnerLoop = partCollection2->end(); //
}
else { // One collection:
tEndOuterLoop--; // Outer loop goes to next-to-last particle
tEndInnerLoop = partCollection1->end() ; // Inner loop goes to last particle
}
for (tPartIter1=tStartOuterLoop;tPartIter1!=tEndOuterLoop;tPartIter1++) {
if (!partCollection2){
tStartInnerLoop = tPartIter1;
tStartInnerLoop++;
}
tPair->SetTrack1(*tPartIter1);
for (tPartIter2 = tStartInnerLoop; tPartIter2!=tEndInnerLoop;tPartIter2++) {
tPair->SetTrack2(*tPartIter2);
// The following lines have to be uncommented if you want pairCutMonitors
// they are not in for speed reasons
// bool tmpPassPair = fPairCut->Pass(tPair);
// fPairCut->FillCutMonitor(tPair, tmpPassPair);
// if ( tmpPassPair )
//---- If pair passes cut, loop over CF's and add pair to real/mixed ----//
if (fPairCut->Pass(tPair)){
for (tCorrFctnIter=fCorrFctnCollection->begin();
tCorrFctnIter!=fCorrFctnCollection->end();tCorrFctnIter++){
AliFemtoCorrFctn* tCorrFctn = *tCorrFctnIter;
if(type == "real")
tCorrFctn->AddRealPair(tPair);
else if(type == "mixed")
tCorrFctn->AddMixedPair(tPair);
else
cout << "Problem with pair type, type = " << type.c_str() << endl;
}
}
} // loop over second particle
} // loop over first particle
delete tPair;
}
//_________________________
void AliFemtoAnalysis::EventBegin(const AliFemtoEvent* ev){
// Perform initialization operations at the beginning of the event processing
//cout << " AliFemtoAnalysis::EventBegin(const AliFemtoEvent* ev) " << endl;
fFirstParticleCut->EventBegin(ev);
fSecondParticleCut->EventBegin(ev);
fPairCut->EventBegin(ev);
for (AliFemtoCorrFctnIterator iter=fCorrFctnCollection->begin(); iter!=fCorrFctnCollection->end();iter++){
(*iter)->EventBegin(ev);
}
}
//_________________________
void AliFemtoAnalysis::EventEnd(const AliFemtoEvent* ev){
// Fiinsh operations at the end of event processing
fFirstParticleCut->EventEnd(ev);
fSecondParticleCut->EventEnd(ev);
fPairCut->EventEnd(ev);
for (AliFemtoCorrFctnIterator iter=fCorrFctnCollection->begin(); iter!=fCorrFctnCollection->end();iter++){
(*iter)->EventEnd(ev);
}
}
//_________________________
void AliFemtoAnalysis::Finish(){
// Perform finishing operations after all events are processed
AliFemtoCorrFctnIterator iter;
for (iter=fCorrFctnCollection->begin(); iter!=fCorrFctnCollection->end();iter++){
(*iter)->Finish();
}
}
//_________________________
void AliFemtoAnalysis::AddEventProcessed() {
// Increase count of processed events
fNeventsProcessed++;
}
//_________________________
TList* AliFemtoAnalysis::ListSettings()
{
TList *tListSettings = new TList();
TList *p1Cut = fFirstParticleCut->ListSettings();
TListIter nextp1(p1Cut);
while (TObject *obj = nextp1.Next()) {
TString cuts(obj->GetName());
cuts.Prepend("AliFemtoAnalysis.");
tListSettings->Add(new TObjString(cuts.Data()));
}
if (fSecondParticleCut != fFirstParticleCut) {
TList *p2Cut = fSecondParticleCut->ListSettings();
TIter nextp2(p2Cut);
while (TObject *obj = nextp2()) {
TString cuts(obj->GetName());
cuts.Prepend("AliFemtoAnalysis.");
tListSettings->Add(new TObjString(cuts.Data()));
}
}
TList *pairCut = fPairCut->ListSettings();
TIter nextpair(pairCut);
while (TObject *obj = nextpair()) {
TString cuts(obj->GetName());
cuts.Prepend("AliFemtoAnalysis.");
tListSettings->Add(new TObjString(cuts.Data()));
}
return tListSettings;
}
<commit_msg>just removing dead wood<commit_after><|endoftext|> |
<commit_before>enum anaModes {mLocal,mLocalPAR,mPROOF,mGrid,mGridPAR};
//mLocal: Analyze locally files in your computer using aliroot
//mLocalPAR: Analyze locally files in your computer using root + PAR files
//mPROOF: Analyze CAF files with PROOF
//mGrid: Analyze files on Grid via AliEn plug-in and using precompiled FLOW libraries
// (Remark: When using this mode set also Bool_t bUseParFiles = kFALSE; in CreateAlienHandler.C)
//mGridPAR: Analyze files on Grid via AliEn plug-in and using par files for FLOW package
// (Remark: when using this mode set also Bool_t bUseParFiles = kTRUE; in CreateAlienHandler.C)
// CENTRALITY DEFINITION
//Int_t binfirst = 4; //where do we start numbering bins
//Int_t binlast = 6; //where do we stop numbering bins
//const Int_t numberOfCentralityBins = 9;
Int_t binfirst = 0; //where do we start numbering bins
Int_t binlast = 8; //where do we stop numbering bins
const Int_t numberOfCentralityBins = 9;
Float_t centralityArray[numberOfCentralityBins+1] = {0.,5.,10.,20.,30.,40.,50.,60.,70.,80.}; // in centrality percentile
//Int_t centralityArray[numberOfCentralityBins+1] = {41,80,146,245,384,576,835,1203,1471,10000}; // in terms of TPC only reference multiplicity
TString commonOutputFileName = "outputCentrality"; // e.g.: result for centrality bin 0 will be in the file "outputCentrality0.root", etc
//void runFlowTaskCentralityTrain(Int_t mode=mLocal, Int_t nRuns = 10,
//Bool_t DATA = kFALSE, const Char_t* dataDir="/Users/snelling/alice_data/Therminator_midcentral", Int_t offset = 0)
//void runFlowTaskCentralityTrain(Int_t mode = mGridPAR, Int_t nRuns = 50000000,
// Bool_t DATA = kTRUE, const Char_t* dataDir="/alice/data/LHC10h_000137161_p1_plusplusplus", Int_t offset=0)
void runFlowTaskCentralityTrain(Int_t mode = mLocal, Int_t nRuns = 50000000,
Bool_t DATA = kTRUE, const Char_t* dataDir="./data/", Int_t offset=0)
//void runFlowTaskCentralityTrain(Int_t mode = mGridPAR, Bool_t DATA = kTRUE)
{
// Time:
TStopwatch timer;
timer.Start();
// Cross-check user settings before starting:
// CrossCheckUserSettings(DATA);
// Load needed libraries:
LoadLibraries(mode);
// Create and configure the AliEn plug-in:
if(mode == mGrid || mode == mGridPAR)
{
gROOT->LoadMacro("CreateAlienHandler.C");
AliAnalysisGrid *alienHandler = CreateAlienHandler();
if(!alienHandler) return;
}
// Chains:
if(mode == mLocal || mode == mLocalPAR) {
TChain* chain = CreateESDChain(dataDir, nRuns, offset);
//TChain* chain = CreateAODChain(dataDir, nRuns, offset);
}
// Create analysis manager:
AliAnalysisManager *mgr = new AliAnalysisManager("FlowAnalysisManager");
// Connect plug-in to the analysis manager:
if(mode == mGrid || mode == mGridPAR)
{
mgr->SetGridHandler(alienHandler);
}
// Event handlers:
AliVEventHandler* esdH = new AliESDInputHandler;
mgr->SetInputEventHandler(esdH);
if (!DATA) {
AliMCEventHandler *mc = new AliMCEventHandler();
mgr->SetMCtruthEventHandler(mc);
}
// Task to check the offline trigger:
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
AddTaskPhysicsSelection(!DATA);
//Add the centrality determination task
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
AddTaskCentrality();
//Add the TOF tender
gROOT->LoadMacro("$ALICE_ROOT/PWG2/FLOW/macros/AddTaskTenderTOF.C");
AddTaskTenderTOF();
// Setup analysis per centrality bin:
gROOT->LoadMacro("AddTaskFlowCentrality.C");
for (Int_t i=binfirst; i<binlast+1; i++)
{
Float_t lowCentralityBinEdge = centralityArray[i];
Float_t highCentralityBinEdge = centralityArray[i+1];
Printf("\nWagon for centrality bin %i: %.0f-%.0f",i,lowCentralityBinEdge,highCentralityBinEdge);
AddTaskFlowCentrality( lowCentralityBinEdge,
highCentralityBinEdge,
commonOutputFileName );
} // end of for (Int_t i=0; i<numberOfCentralityBins; i++)
// Enable debug printouts:
mgr->SetDebugLevel(2);
// Run the analysis:
if(!mgr->InitAnalysis()) return;
mgr->PrintStatus();
if(mode == mLocal || mode == mLocalPAR) {
mgr->StartAnalysis("local",chain);
} else if(mode == mPROOF) {
mgr->StartAnalysis("proof",dataDir,nRuns,offset);
} else if(mode == mGrid || mode == mGridPAR) {
mgr->StartAnalysis("grid");
}
// Print real and CPU time used for analysis:
timer.Stop();
timer.Print();
} // end of void runFlowTaskCentralityTrain(...)
//===============================================================================================
/*
void CrossCheckUserSettings(Bool_t bData)
{
// Check in this method if the user settings make sense.
if(LYZ1SUM && LYZ2SUM) {cout<<" WARNING: You cannot run LYZ1 and LYZ2 at the same time! LYZ2 needs the output from LYZ1 !!!!"<<endl; exit(0); }
if(LYZ1PROD && LYZ2PROD) {cout<<" WARNING: You cannot run LYZ1 and LYZ2 at the same time! LYZ2 needs the output from LYZ1 !!!!"<<endl; exit(0); }
if(LYZ2SUM && LYZEP) {cout<<" WARNING: You cannot run LYZ2 and LYZEP at the same time! LYZEP needs the output from LYZ2 !!!!"<<endl; exit(0); }
if(LYZ1SUM && LYZEP) {cout<<" WARNING: You cannot run LYZ1 and LYZEP at the same time! LYZEP needs the output from LYZ2 !!!!"<<endl; exit(0); }
} // end of void CrossCheckUserSettings()
*/
//===============================================================================================
void LoadLibraries(const anaModes mode)
{
//--------------------------------------
// Load the needed libraries most of them already loaded by aliroot
//--------------------------------------
gSystem->Load("libCore");
gSystem->Load("libTree");
gSystem->Load("libGeom");
gSystem->Load("libVMC");
gSystem->Load("libXMLIO");
gSystem->Load("libPhysics");
gSystem->Load("libXMLParser");
gSystem->Load("libProof");
gSystem->Load("libMinuit");
if (mode==mLocal || mode==mGrid || mode == mGridPAR || mode == mLocalPAR )
{
gSystem->Load("libSTEERBase");
gSystem->Load("libCDB");
gSystem->Load("libRAWDatabase");
gSystem->Load("libRAWDatarec");
gSystem->Load("libESD");
gSystem->Load("libAOD");
gSystem->Load("libSTEER");
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libTOFbase");
gSystem->Load("libTOFrec");
gSystem->Load("libTRDbase");
gSystem->Load("libVZERObase");
gSystem->Load("libVZEROrec");
gSystem->Load("libT0base");
gSystem->Load("libT0rec");
gSystem->Load("libTENDER");
gSystem->Load("libTENDERSupplies");
if (mode == mLocal || mode == mGrid)
{
gSystem->Load("libPWG2flowCommon");
gSystem->Load("libPWG2flowTasks");
}
if (mode == mLocalPAR || mode == mGridPAR )
{
AliAnalysisAlien::SetupPar("PWG2flowCommon");
AliAnalysisAlien::SetupPar("PWG2flowTasks");
}
}
//---------------------------------------------------------
// <<<<<<<<<< PROOF mode >>>>>>>>>>>>
//---------------------------------------------------------
else if (mode==mPROOF) {
// set to debug root versus if needed
//TProof::Mgr("alicecaf")->SetROOTVersion("v5-24-00a_dbg");
//TProof::Mgr("alicecaf")->SetROOTVersion("v5-24-00a");
//TProof::Reset("proof://snelling@alicecaf.cern.ch");
// Connect to proof
printf("*** Connect to PROOF ***\n");
gEnv->SetValue("XSec.GSI.DelegProxy","2");
TProof::Open("mkrzewic@alice-caf.cern.ch");
//TProof::Open("mkrzewic@skaf.saske.sk");
// list the data available
//gProof->ShowDataSets("/*/*");
//gProof->ShowDataSets("/alice/sim/"); //for MC Data
//gProof->ShowDataSets("/alice/data/"); //for REAL Data
// Clear the Packages
/*
gProof->ClearPackage("STEERBase.par");
gProof->ClearPackage("ESD.par");
gProof->ClearPackage("AOD.par");
*/
//gProof->ClearPackage("ANALYSIS.par");
//gProof->ClearPackage("ANALYSISalice.par");
//gProof->ClearPackage("CORRFW.par");
gProof->ClearPackage("PWG2flowCommon");
gProof->ClearPackage("PWG2flowTasks");
// Upload the Packages
//gProof->UploadPackage("STEERBase.par");
//gProof->UploadPackage("ESD.par");
//gProof->UploadPackage("AOD.par");
//gProof->UploadPackage("ANALYSIS.par");
//gProof->UploadPackage("ANALYSISalice.par");
gProof->UploadPackage("CORRFW.par");
gProof->UploadPackage("PWG2flowCommon.par");
gProof->UploadPackage("PWG2flowTasks.par");
gProof->UploadPackage("ALIRECO.par");
// Enable the Packages
// The global package
TList* list = new TList();
list->Add(new TNamed("ALIROOT_EXTRA_INCLUDES","RAW:OCDB:STEER:TOF"));
gProof->EnablePackage("VO_ALICE@AliRoot::v4-21-07-AN",list);
gProof->EnablePackage("ALIRECO");
//gProof->EnablePackage("ANALYSIS");
//gProof->EnablePackage("ANALYSISalice");
//gProof->EnablePackage("CORRFW");
gProof->EnablePackage("PWG2flowCommon");
gProof->EnablePackage("PWG2flowTasks");
// Show enables Packages
gProof->ShowEnabledPackages();
}
} // end of void LoadLibraries(const anaModes mode)
// Helper macros for creating chains
// from: CreateESDChain.C,v 1.10 jgrosseo Exp
TChain* CreateESDChain(const char* aDataDir, Int_t aRuns, Int_t offset)
{
// creates chain of files in a given directory or file containing a list.
// In case of directory the structure is expected as:
// <aDataDir>/<dir0>/AliESDs.root
// <aDataDir>/<dir1>/AliESDs.root
// ...
if (!aDataDir)
return 0;
Long_t id, size, flags, modtime;
if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))
{
printf("%s not found.\n", aDataDir);
return 0;
}
TChain* chain = new TChain("esdTree");
TChain* chaingAlice = 0;
if (flags & 2)
{
TString execDir(gSystem->pwd());
TSystemDirectory* baseDir = new TSystemDirectory(".", aDataDir);
TList* dirList = baseDir->GetListOfFiles();
Int_t nDirs = dirList->GetEntries();
gSystem->cd(execDir);
Int_t count = 0;
for (Int_t iDir=0; iDir<nDirs; ++iDir)
{
TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);
if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 || strcmp(presentDir->GetName(), "..") == 0)
continue;
if (offset > 0)
{
--offset;
continue;
}
if (count++ == aRuns)
break;
TString presentDirName(aDataDir);
presentDirName += "/";
presentDirName += presentDir->GetName();
chain->Add(presentDirName + "/AliESDs.root/esdTree");
// cerr<<presentDirName<<endl;
}
}
else
{
// Open the input stream
ifstream in;
in.open(aDataDir);
Int_t count = 0;
// Read the input list of files and add them to the chain
TString esdfile;
while(in.good()) {
in >> esdfile;
if (!esdfile.Contains("root")) continue; // protection
if (offset > 0)
{
--offset;
continue;
}
if (count++ == aRuns)
break;
// add esd file
chain->Add(esdfile);
}
in.close();
}
return chain;
} // end of TChain* CreateESDChain(const char* aDataDir, Int_t aRuns, Int_t offset)
//===============================================================================================
TChain* CreateAODChain(const char* aDataDir, Int_t aRuns, Int_t offset)
{
// creates chain of files in a given directory or file containing a list.
// In case of directory the structure is expected as:
// <aDataDir>/<dir0>/AliAOD.root
// <aDataDir>/<dir1>/AliAOD.root
// ...
if (!aDataDir)
return 0;
Long_t id, size, flags, modtime;
if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))
{
printf("%s not found.\n", aDataDir);
return 0;
}
TChain* chain = new TChain("aodTree");
TChain* chaingAlice = 0;
if (flags & 2)
{
TString execDir(gSystem->pwd());
TSystemDirectory* baseDir = new TSystemDirectory(".", aDataDir);
TList* dirList = baseDir->GetListOfFiles();
Int_t nDirs = dirList->GetEntries();
gSystem->cd(execDir);
Int_t count = 0;
for (Int_t iDir=0; iDir<nDirs; ++iDir)
{
TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);
if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 || strcmp(presentDir->GetName(), "..") == 0)
continue;
if (offset > 0)
{
--offset;
continue;
}
if (count++ == aRuns)
break;
TString presentDirName(aDataDir);
presentDirName += "/";
presentDirName += presentDir->GetName();
chain->Add(presentDirName + "/AliAOD.root/aodTree");
// cerr<<presentDirName<<endl;
}
}
else
{
// Open the input stream
ifstream in;
in.open(aDataDir);
Int_t count = 0;
// Read the input list of files and add them to the chain
TString aodfile;
while(in.good()) {
in >> aodfile;
if (!aodfile.Contains("root")) continue; // protection
if (offset > 0)
{
--offset;
continue;
}
if (count++ == aRuns)
break;
// add aod file
chain->Add(aodfile);
}
in.close();
}
return chain;
} // end of TChain* CreateAODChain(const char* aDataDir, Int_t aRuns, Int_t offset)
<commit_msg>cleanup<commit_after>enum anaModes {mLocal,mPROOF,mGrid};
//mLocal: Analyze locally files in your computer using aliroot
//mLocalPAR: Analyze locally files in your computer using root + PAR files
//mPROOF: Analyze CAF files with PROOF
//mGrid: Analyze files on Grid via AliEn plug-in and using precompiled FLOW libraries
// (Remark: When using this mode set also Bool_t bUseParFiles = kFALSE; in CreateAlienHandler.C)
//mGridPAR: Analyze files on Grid via AliEn plug-in and using par files for FLOW package
// (Remark: when using this mode set also Bool_t bUseParFiles = kTRUE; in CreateAlienHandler.C)
// CENTRALITY DEFINITION
//Int_t binfirst = 4; //where do we start numbering bins
//Int_t binlast = 6; //where do we stop numbering bins
//const Int_t numberOfCentralityBins = 9;
Int_t binfirst = 0; //where do we start numbering bins
Int_t binlast = 8; //where do we stop numbering bins
const Int_t numberOfCentralityBins = 9;
Float_t centralityArray[numberOfCentralityBins+1] = {0.,5.,10.,20.,30.,40.,50.,60.,70.,80.}; // in centrality percentile
//Int_t centralityArray[numberOfCentralityBins+1] = {41,80,146,245,384,576,835,1203,1471,10000}; // in terms of TPC only reference multiplicity
TString commonOutputFileName = "outputCentrality"; // e.g.: result for centrality bin 0 will be in the file "outputCentrality0.root", etc
//void runFlowTaskCentralityTrain(Int_t mode=mLocal, Int_t nEvents = 10,
//Bool_t DATA = kFALSE, const Char_t* dataDir="/Users/snelling/alice_data/Therminator_midcentral", Int_t offset = 0)
//void runFlowTaskCentralityTrain(Int_t mode = mGridPAR, Int_t nEvents = 50000000,
// Bool_t DATA = kTRUE, const Char_t* dataDir="/alice/data/LHC10h_000137161_p1_plusplusplus", Int_t offset=0)
void runFlowTaskCentralityTrain( Int_t mode = mPROOF,
Bool_t useFlowParFiles = kFALSE,
Bool_t DATA = kTRUE,
const Char_t* dataDir="/alice/data/LHC10h_000137162_p1_plusplusplus#esdTree",
Int_t nEvents = 1e4,
Int_t offset=0 )
{
// Time:
TStopwatch timer;
timer.Start();
// Cross-check user settings before starting:
// CrossCheckUserSettings(DATA);
// Load needed libraries:
LoadLibraries(mode,useFlowParFiles);
// Create and configure the AliEn plug-in:
if(mode == mGrid)
{
gROOT->LoadMacro("CreateAlienHandler.C");
AliAnalysisGrid *alienHandler = CreateAlienHandler();
if(!alienHandler) return;
}
// Chains:
if(mode == mLocal)
{
TChain* chain = CreateESDChain(dataDir, nEvents, offset);
//TChain* chain = CreateAODChain(dataDir, nEvents, offset);
}
// Create analysis manager:
AliAnalysisManager *mgr = new AliAnalysisManager("FlowAnalysisManager");
// Connect plug-in to the analysis manager:
if(mode == mGrid)
{
mgr->SetGridHandler(alienHandler);
}
// Event handlers:
AliVEventHandler* esdH = new AliESDInputHandler;
mgr->SetInputEventHandler(esdH);
if (!DATA)
{
AliMCEventHandler *mc = new AliMCEventHandler();
mgr->SetMCtruthEventHandler(mc);
}
// Task to check the offline trigger:
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
AddTaskPhysicsSelection(!DATA);
//Add the centrality determination task
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
AddTaskCentrality();
//Add the TOF tender
gROOT->LoadMacro("$ALICE_ROOT/PWG2/FLOW/macros/AddTaskTenderTOF.C");
AddTaskTenderTOF();
// Setup analysis per centrality bin:
gROOT->LoadMacro("AddTaskFlowCentrality.C");
//for (Int_t i=binfirst; i<binlast+1; i++)
//{
// Float_t lowCentralityBinEdge = centralityArray[i];
// Float_t highCentralityBinEdge = centralityArray[i+1];
// Printf("\nWagon for centrality bin %i: %.0f-%.0f",i,lowCentralityBinEdge,highCentralityBinEdge);
// AddTaskFlowCentrality( lowCentralityBinEdge,
// highCentralityBinEdge,
// commonOutputFileName );
//} // end of for (Int_t i=0; i<numberOfCentralityBins; i++)
AddTaskFlowCentrality();
// Enable debug printouts:
mgr->SetDebugLevel(2);
// Run the analysis:
if(!mgr->InitAnalysis()) return;
mgr->PrintStatus();
if(mode == mLocal)
{
mgr->StartAnalysis("local",chain);
}
else if(mode == mPROOF)
{
mgr->StartAnalysis("proof",dataDir,nEvents,offset);
}
else if(mode == mGrid)
{
mgr->StartAnalysis("grid");
}
// Print real and CPU time used for analysis:
timer.Stop();
timer.Print();
} // end of void runFlowTaskCentralityTrain(...)
//===============================================================================================
/*
void CrossCheckUserSettings(Bool_t bData)
{
// Check in this method if the user settings make sense.
if(LYZ1SUM && LYZ2SUM) {cout<<" WARNING: You cannot run LYZ1 and LYZ2 at the same time! LYZ2 needs the output from LYZ1 !!!!"<<endl; exit(0); }
if(LYZ1PROD && LYZ2PROD) {cout<<" WARNING: You cannot run LYZ1 and LYZ2 at the same time! LYZ2 needs the output from LYZ1 !!!!"<<endl; exit(0); }
if(LYZ2SUM && LYZEP) {cout<<" WARNING: You cannot run LYZ2 and LYZEP at the same time! LYZEP needs the output from LYZ2 !!!!"<<endl; exit(0); }
if(LYZ1SUM && LYZEP) {cout<<" WARNING: You cannot run LYZ1 and LYZEP at the same time! LYZEP needs the output from LYZ2 !!!!"<<endl; exit(0); }
} // end of void CrossCheckUserSettings()
*/
//===============================================================================================
void LoadLibraries(const anaModes mode, Bool_t useFlowParFiles )
{
//--------------------------------------
// Load the needed libraries most of them already loaded by aliroot
//--------------------------------------
gSystem->Load("libCore");
gSystem->Load("libTree");
gSystem->Load("libGeom");
gSystem->Load("libVMC");
gSystem->Load("libXMLIO");
gSystem->Load("libPhysics");
gSystem->Load("libXMLParser");
gSystem->Load("libProof");
gSystem->Load("libMinuit");
if (mode==mLocal || mode==mGrid)
{
gSystem->Load("libSTEERBase");
gSystem->Load("libCDB");
gSystem->Load("libRAWDatabase");
gSystem->Load("libRAWDatarec");
gSystem->Load("libESD");
gSystem->Load("libAOD");
gSystem->Load("libSTEER");
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libTOFbase");
gSystem->Load("libTOFrec");
gSystem->Load("libTRDbase");
gSystem->Load("libVZERObase");
gSystem->Load("libVZEROrec");
gSystem->Load("libT0base");
gSystem->Load("libT0rec");
gSystem->Load("libTENDER");
gSystem->Load("libTENDERSupplies");
if (useFlowParFiles)
{
AliAnalysisAlien::SetupPar("PWG2flowCommon");
AliAnalysisAlien::SetupPar("PWG2flowTasks");
}
else
{
gSystem->Load("libPWG2flowCommon");
gSystem->Load("libPWG2flowTasks");
}
}
else if (mode==mPROOF)
{
TList* list = new TList();
list->Add(new TNamed("ALIROOT_MODE", "ALIROOT"));
if (useFlowParFiles)
list->Add(new TNamed("ALIROOT_EXTRA_LIBS", "ANALYSIS:ANALYSISalice:TENDER:TENDERSupplies"));
else
list->Add(new TNamed("ALIROOT_EXTRA_LIBS", "ANALYSIS:ANALYSISalice:TENDER:TENDERSupplies:PWG2flowCommon:PWG2flowTasks"));
//list->Add(new TNamed("ALIROOT_EXTRA_INCLUDES","PWG2/FLOW/AliFlowCommon:PWG2/FLOW/AliFlowTasks"));
// Connect to proof
printf("*** Connect to PROOF ***\n");
gEnv->SetValue("XSec.GSI.DelegProxy","2");
//TProof* proof = TProof::Open("alice-caf.cern.ch");
TProof* proof = TProof::Open("skaf.saske.sk");
// list the data available
//gProof->ShowDataSets("/*/*");
//gProof->ShowDataSets("/alice/sim/"); //for MC Data
//gProof->ShowDataSets("/alice/data/"); //for REAL Data
proof->ClearPackages();
proof->EnablePackage("VO_ALICE@AliRoot::v4-21-14-AN",list);
if (useFlowParFiles)
{
gProof->UploadPackage("PWG2flowCommon.par");
gProof->UploadPackage("PWG2flowTasks.par");
}
// Show enables Packages
gProof->ShowEnabledPackages();
}
} // end of void LoadLibraries(const anaModes mode)
// Helper macros for creating chains
// from: CreateESDChain.C,v 1.10 jgrosseo Exp
TChain* CreateESDChain(const char* aDataDir, Int_t aRuns, Int_t offset)
{
// creates chain of files in a given directory or file containing a list.
// In case of directory the structure is expected as:
// <aDataDir>/<dir0>/AliESDs.root
// <aDataDir>/<dir1>/AliESDs.root
// ...
if (!aDataDir)
return 0;
Long_t id, size, flags, modtime;
if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))
{
printf("%s not found.\n", aDataDir);
return 0;
}
TChain* chain = new TChain("esdTree");
TChain* chaingAlice = 0;
if (flags & 2)
{
TString execDir(gSystem->pwd());
TSystemDirectory* baseDir = new TSystemDirectory(".", aDataDir);
TList* dirList = baseDir->GetListOfFiles();
Int_t nDirs = dirList->GetEntries();
gSystem->cd(execDir);
Int_t count = 0;
for (Int_t iDir=0; iDir<nDirs; ++iDir)
{
TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);
if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 || strcmp(presentDir->GetName(), "..") == 0)
continue;
if (offset > 0)
{
--offset;
continue;
}
if (count++ == aRuns)
break;
TString presentDirName(aDataDir);
presentDirName += "/";
presentDirName += presentDir->GetName();
chain->Add(presentDirName + "/AliESDs.root/esdTree");
// cerr<<presentDirName<<endl;
}
}
else
{
// Open the input stream
ifstream in;
in.open(aDataDir);
Int_t count = 0;
// Read the input list of files and add them to the chain
TString esdfile;
while(in.good())
{
in >> esdfile;
if (!esdfile.Contains("root")) continue; // protection
if (offset > 0)
{
--offset;
continue;
}
if (count++ == aRuns)
break;
// add esd file
chain->Add(esdfile);
}
in.close();
}
return chain;
} // end of TChain* CreateESDChain(const char* aDataDir, Int_t aRuns, Int_t offset)
//===============================================================================================
TChain* CreateAODChain(const char* aDataDir, Int_t aRuns, Int_t offset)
{
// creates chain of files in a given directory or file containing a list.
// In case of directory the structure is expected as:
// <aDataDir>/<dir0>/AliAOD.root
// <aDataDir>/<dir1>/AliAOD.root
// ...
if (!aDataDir)
return 0;
Long_t id, size, flags, modtime;
if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))
{
printf("%s not found.\n", aDataDir);
return 0;
}
TChain* chain = new TChain("aodTree");
TChain* chaingAlice = 0;
if (flags & 2)
{
TString execDir(gSystem->pwd());
TSystemDirectory* baseDir = new TSystemDirectory(".", aDataDir);
TList* dirList = baseDir->GetListOfFiles();
Int_t nDirs = dirList->GetEntries();
gSystem->cd(execDir);
Int_t count = 0;
for (Int_t iDir=0; iDir<nDirs; ++iDir)
{
TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);
if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 || strcmp(presentDir->GetName(), "..") == 0)
continue;
if (offset > 0)
{
--offset;
continue;
}
if (count++ == aRuns)
break;
TString presentDirName(aDataDir);
presentDirName += "/";
presentDirName += presentDir->GetName();
chain->Add(presentDirName + "/AliAOD.root/aodTree");
// cerr<<presentDirName<<endl;
}
}
else
{
// Open the input stream
ifstream in;
in.open(aDataDir);
Int_t count = 0;
// Read the input list of files and add them to the chain
TString aodfile;
while(in.good())
{
in >> aodfile;
if (!aodfile.Contains("root")) continue; // protection
if (offset > 0)
{
--offset;
continue;
}
if (count++ == aRuns)
break;
// add aod file
chain->Add(aodfile);
}
in.close();
}
return chain;
} // end of TChain* CreateAODChain(const char* aDataDir, Int_t aRuns, Int_t offset)
<|endoftext|> |
<commit_before>/*!
* \file SU2_DEF.cpp
* \brief Main file of Mesh Deformation Code (SU2_DEF).
* \author F. Palacios, T. Economon
* \version 4.0.0 "Cardinal"
*
* SU2 Lead Developers: Dr. Francisco Palacios (Francisco.D.Palacios@boeing.com).
* Dr. Thomas D. Economon (economon@stanford.edu).
*
* SU2 Developers: Prof. Juan J. Alonso's group at Stanford University.
* Prof. Piero Colonna's group at Delft University of Technology.
* Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology.
* Prof. Alberto Guardone's group at Polytechnic University of Milan.
* Prof. Rafael Palacios' group at Imperial College London.
*
* Copyright (C) 2012-2015 SU2, the open-source CFD code.
*
* SU2 is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* SU2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../include/SU2_DEF.hpp"
using namespace std;
int main(int argc, char *argv[]) {
unsigned short iZone, nZone = SINGLE_ZONE, iMarker;
double StartTime = 0.0, StopTime = 0.0, UsedTime = 0.0;
char config_file_name[MAX_STRING_SIZE];
int rank = MASTER_NODE, size = SINGLE_NODE;
string str;
bool allmoving=true;
/*--- MPI initialization ---*/
#ifdef HAVE_MPI
SU2_MPI::Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
#endif
/*--- Pointer to different structures that will be used throughout
the entire code ---*/
CConfig **config_container = NULL;
CGeometry **geometry_container = NULL;
CSurfaceMovement *surface_movement = NULL;
CVolumetricMovement *grid_movement = NULL;
COutput *output = NULL;
/*--- Load in the number of zones and spatial dimensions in the mesh file
(if no config file is specified, default.cfg is used) ---*/
if (argc == 2){ strcpy(config_file_name,argv[1]); }
else{ strcpy(config_file_name, "default.cfg"); }
/*--- Definition of the containers per zones ---*/
config_container = new CConfig*[nZone];
geometry_container = new CGeometry*[nZone];
output = new COutput();
for (iZone = 0; iZone < nZone; iZone++) {
config_container[iZone] = NULL;
geometry_container[iZone] = NULL;
}
/*--- Loop over all zones to initialize the various classes. In most
cases, nZone is equal to one. This represents the solution of a partial
differential equation on a single block, unstructured mesh. ---*/
for (iZone = 0; iZone < nZone; iZone++) {
/*--- Definition of the configuration option class for all zones. In this
constructor, the input configuration file is parsed and all options are
read and stored. ---*/
config_container[iZone] = new CConfig(config_file_name, SU2_DEF, iZone, nZone, 0, VERB_HIGH);
/*--- Definition of the geometry class to store the primal grid in the partitioning process. ---*/
CGeometry *geometry_aux = NULL;
/*--- All ranks process the grid and call ParMETIS for partitioning ---*/
geometry_aux = new CPhysicalGeometry(config_container[iZone], iZone, nZone);
/*--- Color the initial grid and set the send-receive domains (ParMETIS) ---*/
geometry_aux->SetColorGrid_Parallel(config_container[iZone]);
/*--- Allocate the memory of the current domain, and
divide the grid between the nodes ---*/
geometry_container[iZone] = new CPhysicalGeometry(geometry_aux, config_container[iZone], 1);
/*--- Deallocate the memory of geometry_aux ---*/
delete geometry_aux;
/*--- Add the Send/Receive boundaries ---*/
geometry_container[iZone]->SetSendReceive(config_container[iZone]);
/*--- Add the Send/Receive boundaries ---*/
geometry_container[iZone]->SetBoundaries(config_container[iZone]);
}
/*--- Set up a timer for performance benchmarking (preprocessing time is included) ---*/
#ifdef HAVE_MPI
StartTime = MPI_Wtime();
#else
StartTime = su2double(clock())/su2double(CLOCKS_PER_SEC);
#endif
/*--- Computational grid preprocesing ---*/
if (rank == MASTER_NODE) cout << endl << "----------------------- Preprocessing computations ----------------------" << endl;
/*--- Compute elements surrounding points, points surrounding points ---*/
if (rank == MASTER_NODE) cout << "Setting local point connectivity." <<endl;
geometry_container[ZONE_0]->SetPoint_Connectivity();
/*--- Check the orientation before computing geometrical quantities ---*/
if (rank == MASTER_NODE) cout << "Checking the numerical grid orientation of the interior elements." <<endl;
geometry_container[ZONE_0]->Check_IntElem_Orientation(config_container[ZONE_0]);
/*--- Create the edge structure ---*/
if (rank == MASTER_NODE) cout << "Identify edges and vertices." <<endl;
geometry_container[ZONE_0]->SetEdges(); geometry_container[ZONE_0]->SetVertex(config_container[ZONE_0]);
/*--- Compute center of gravity ---*/
if (rank == MASTER_NODE) cout << "Computing centers of gravity." << endl;
geometry_container[ZONE_0]->SetCG();
/*--- Create the dual control volume structures ---*/
if (rank == MASTER_NODE) cout << "Setting the bound control volume structure." << endl;
geometry_container[ZONE_0]->SetBoundControlVolume(config_container[ZONE_0], ALLOCATE);
/*--- Output original grid for visualization, if requested (surface and volumetric) ---*/
if (config_container[ZONE_0]->GetVisualize_Deformation()) {
output->SetMesh_Files(geometry_container, config_container, SINGLE_ZONE, true, false);
// if (rank == MASTER_NODE) cout << "Writing an STL file of the surface mesh." << endl;
// if (size > 1) SPRINTF (buffer_char, "_%d.stl", rank+1); else SPRINTF (buffer_char, ".stl");
// strcpy (out_file, "Surface_Grid"); strcat(out_file, buffer_char); geometry[ZONE_0]->SetBoundSTL(out_file, true, config[ZONE_0]);
}
/*--- Surface grid deformation using design variables ---*/
if (rank == MASTER_NODE) cout << endl << "------------------------- Surface grid deformation ----------------------" << endl;
/*--- Definition and initialization of the surface deformation class ---*/
surface_movement = new CSurfaceMovement();
/*--- Copy coordinates to the surface structure ---*/
surface_movement->CopyBoundary(geometry_container[ZONE_0], config_container[ZONE_0]);
/*--- Surface grid deformation ---*/
if (rank == MASTER_NODE) cout << "Performing the deformation of the surface grid." << endl;
surface_movement->SetSurface_Deformation(geometry_container[ZONE_0], config_container[ZONE_0]);
if (config_container[ZONE_0]->GetDesign_Variable(0) != FFD_SETTING) {
if (rank == MASTER_NODE)
cout << endl << "----------------------- Volumetric grid deformation ---------------------" << endl;
/*--- Definition of the Class for grid movement ---*/
grid_movement = new CVolumetricMovement(geometry_container[ZONE_0]);
}
/*--- For scale, translation and rotation if all boundaries are moving they are set via volume method
* Otherwise, the surface deformation has been set already in SetSurface_Deformation. --- */
allmoving = true;
/*--- Loop over markers, set flag to false if any are not moving ---*/
for (iMarker = 0; iMarker < config_container[ZONE_0]->GetnMarker_All(); iMarker++){
if (config_container[ZONE_0]->GetMarker_All_DV(iMarker) == NO)
allmoving = false;
}
/*--- Volumetric grid deformation/transformations ---*/
if (config_container[ZONE_0]->GetDesign_Variable(0) == SCALE and allmoving) {
if (rank == MASTER_NODE)
cout << "Performing a scaling of the volumetric grid." << endl;
grid_movement->SetVolume_Scaling(geometry_container[ZONE_0], config_container[ZONE_0], false);
} else if (config_container[ZONE_0]->GetDesign_Variable(0) == TRANSLATION and allmoving) {
if (rank == MASTER_NODE)
cout << "Performing a translation of the volumetric grid." << endl;
grid_movement->SetVolume_Translation(geometry_container[ZONE_0], config_container[ZONE_0], false);
} else if (config_container[ZONE_0]->GetDesign_Variable(0) == ROTATION and allmoving) {
if (rank == MASTER_NODE)
cout << "Performing a rotation of the volumetric grid." << endl;
grid_movement->SetVolume_Rotation(geometry_container[ZONE_0], config_container[ZONE_0], false);
} else if (config_container[ZONE_0]->GetDesign_Variable(0) != FFD_SETTING) {
if (rank == MASTER_NODE)
cout << "Performing the deformation of the volumetric grid." << endl;
grid_movement->SetVolume_Deformation(geometry_container[ZONE_0], config_container[ZONE_0], false);
}
/*--- Computational grid preprocesing ---*/
if (rank == MASTER_NODE) cout << endl << "----------------------- Write deformed grid files -----------------------" << endl;
/*--- Output deformed grid for visualization, if requested (surface and volumetric), in parallel
requires to move all the data to the master node---*/
output = new COutput();
output->SetMesh_Files(geometry_container, config_container, SINGLE_ZONE, false, true);
/*--- Write the the free-form deformation boxes after deformation. ---*/
if (rank == MASTER_NODE) cout << "Adding any FFD information to the SU2 file." << endl;
surface_movement->WriteFFDInfo(geometry_container[ZONE_0], config_container[ZONE_0]);
/*--- Synchronization point after a single solver iteration. Compute the
wall clock time required. ---*/
#ifdef HAVE_MPI
StopTime = MPI_Wtime();
#else
StopTime = su2double(clock())/su2double(CLOCKS_PER_SEC);
#endif
/*--- Compute/print the total time for performance benchmarking. ---*/
UsedTime = StopTime-StartTime;
if (rank == MASTER_NODE) {
cout << "\nCompleted in " << fixed << UsedTime << " seconds on "<< size;
if (size == 1) cout << " core." << endl; else cout << " cores." << endl;
}
/*--- Exit the solver cleanly ---*/
if (rank == MASTER_NODE)
cout << endl << "------------------------- Exit Success (SU2_DEF) ------------------------" << endl << endl;
/*--- Finalize MPI parallelization ---*/
#ifdef HAVE_MPI
MPI_Finalize();
#endif
return EXIT_SUCCESS;
}
<commit_msg> su2double fix<commit_after>/*!
* \file SU2_DEF.cpp
* \brief Main file of Mesh Deformation Code (SU2_DEF).
* \author F. Palacios, T. Economon
* \version 4.0.0 "Cardinal"
*
* SU2 Lead Developers: Dr. Francisco Palacios (Francisco.D.Palacios@boeing.com).
* Dr. Thomas D. Economon (economon@stanford.edu).
*
* SU2 Developers: Prof. Juan J. Alonso's group at Stanford University.
* Prof. Piero Colonna's group at Delft University of Technology.
* Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology.
* Prof. Alberto Guardone's group at Polytechnic University of Milan.
* Prof. Rafael Palacios' group at Imperial College London.
*
* Copyright (C) 2012-2015 SU2, the open-source CFD code.
*
* SU2 is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* SU2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../include/SU2_DEF.hpp"
using namespace std;
int main(int argc, char *argv[]) {
unsigned short iZone, nZone = SINGLE_ZONE, iMarker;
su2double StartTime = 0.0, StopTime = 0.0, UsedTime = 0.0;
char config_file_name[MAX_STRING_SIZE];
int rank = MASTER_NODE, size = SINGLE_NODE;
string str;
bool allmoving=true;
/*--- MPI initialization ---*/
#ifdef HAVE_MPI
SU2_MPI::Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
#endif
/*--- Pointer to different structures that will be used throughout
the entire code ---*/
CConfig **config_container = NULL;
CGeometry **geometry_container = NULL;
CSurfaceMovement *surface_movement = NULL;
CVolumetricMovement *grid_movement = NULL;
COutput *output = NULL;
/*--- Load in the number of zones and spatial dimensions in the mesh file
(if no config file is specified, default.cfg is used) ---*/
if (argc == 2){ strcpy(config_file_name,argv[1]); }
else{ strcpy(config_file_name, "default.cfg"); }
/*--- Definition of the containers per zones ---*/
config_container = new CConfig*[nZone];
geometry_container = new CGeometry*[nZone];
output = new COutput();
for (iZone = 0; iZone < nZone; iZone++) {
config_container[iZone] = NULL;
geometry_container[iZone] = NULL;
}
/*--- Loop over all zones to initialize the various classes. In most
cases, nZone is equal to one. This represents the solution of a partial
differential equation on a single block, unstructured mesh. ---*/
for (iZone = 0; iZone < nZone; iZone++) {
/*--- Definition of the configuration option class for all zones. In this
constructor, the input configuration file is parsed and all options are
read and stored. ---*/
config_container[iZone] = new CConfig(config_file_name, SU2_DEF, iZone, nZone, 0, VERB_HIGH);
/*--- Definition of the geometry class to store the primal grid in the partitioning process. ---*/
CGeometry *geometry_aux = NULL;
/*--- All ranks process the grid and call ParMETIS for partitioning ---*/
geometry_aux = new CPhysicalGeometry(config_container[iZone], iZone, nZone);
/*--- Color the initial grid and set the send-receive domains (ParMETIS) ---*/
geometry_aux->SetColorGrid_Parallel(config_container[iZone]);
/*--- Allocate the memory of the current domain, and
divide the grid between the nodes ---*/
geometry_container[iZone] = new CPhysicalGeometry(geometry_aux, config_container[iZone], 1);
/*--- Deallocate the memory of geometry_aux ---*/
delete geometry_aux;
/*--- Add the Send/Receive boundaries ---*/
geometry_container[iZone]->SetSendReceive(config_container[iZone]);
/*--- Add the Send/Receive boundaries ---*/
geometry_container[iZone]->SetBoundaries(config_container[iZone]);
}
/*--- Set up a timer for performance benchmarking (preprocessing time is included) ---*/
#ifdef HAVE_MPI
StartTime = MPI_Wtime();
#else
StartTime = su2double(clock())/su2double(CLOCKS_PER_SEC);
#endif
/*--- Computational grid preprocesing ---*/
if (rank == MASTER_NODE) cout << endl << "----------------------- Preprocessing computations ----------------------" << endl;
/*--- Compute elements surrounding points, points surrounding points ---*/
if (rank == MASTER_NODE) cout << "Setting local point connectivity." <<endl;
geometry_container[ZONE_0]->SetPoint_Connectivity();
/*--- Check the orientation before computing geometrical quantities ---*/
if (rank == MASTER_NODE) cout << "Checking the numerical grid orientation of the interior elements." <<endl;
geometry_container[ZONE_0]->Check_IntElem_Orientation(config_container[ZONE_0]);
/*--- Create the edge structure ---*/
if (rank == MASTER_NODE) cout << "Identify edges and vertices." <<endl;
geometry_container[ZONE_0]->SetEdges(); geometry_container[ZONE_0]->SetVertex(config_container[ZONE_0]);
/*--- Compute center of gravity ---*/
if (rank == MASTER_NODE) cout << "Computing centers of gravity." << endl;
geometry_container[ZONE_0]->SetCG();
/*--- Create the dual control volume structures ---*/
if (rank == MASTER_NODE) cout << "Setting the bound control volume structure." << endl;
geometry_container[ZONE_0]->SetBoundControlVolume(config_container[ZONE_0], ALLOCATE);
/*--- Output original grid for visualization, if requested (surface and volumetric) ---*/
if (config_container[ZONE_0]->GetVisualize_Deformation()) {
output->SetMesh_Files(geometry_container, config_container, SINGLE_ZONE, true, false);
// if (rank == MASTER_NODE) cout << "Writing an STL file of the surface mesh." << endl;
// if (size > 1) SPRINTF (buffer_char, "_%d.stl", rank+1); else SPRINTF (buffer_char, ".stl");
// strcpy (out_file, "Surface_Grid"); strcat(out_file, buffer_char); geometry[ZONE_0]->SetBoundSTL(out_file, true, config[ZONE_0]);
}
/*--- Surface grid deformation using design variables ---*/
if (rank == MASTER_NODE) cout << endl << "------------------------- Surface grid deformation ----------------------" << endl;
/*--- Definition and initialization of the surface deformation class ---*/
surface_movement = new CSurfaceMovement();
/*--- Copy coordinates to the surface structure ---*/
surface_movement->CopyBoundary(geometry_container[ZONE_0], config_container[ZONE_0]);
/*--- Surface grid deformation ---*/
if (rank == MASTER_NODE) cout << "Performing the deformation of the surface grid." << endl;
surface_movement->SetSurface_Deformation(geometry_container[ZONE_0], config_container[ZONE_0]);
if (config_container[ZONE_0]->GetDesign_Variable(0) != FFD_SETTING) {
if (rank == MASTER_NODE)
cout << endl << "----------------------- Volumetric grid deformation ---------------------" << endl;
/*--- Definition of the Class for grid movement ---*/
grid_movement = new CVolumetricMovement(geometry_container[ZONE_0]);
}
/*--- For scale, translation and rotation if all boundaries are moving they are set via volume method
* Otherwise, the surface deformation has been set already in SetSurface_Deformation. --- */
allmoving = true;
/*--- Loop over markers, set flag to false if any are not moving ---*/
for (iMarker = 0; iMarker < config_container[ZONE_0]->GetnMarker_All(); iMarker++){
if (config_container[ZONE_0]->GetMarker_All_DV(iMarker) == NO)
allmoving = false;
}
/*--- Volumetric grid deformation/transformations ---*/
if (config_container[ZONE_0]->GetDesign_Variable(0) == SCALE and allmoving) {
if (rank == MASTER_NODE)
cout << "Performing a scaling of the volumetric grid." << endl;
grid_movement->SetVolume_Scaling(geometry_container[ZONE_0], config_container[ZONE_0], false);
} else if (config_container[ZONE_0]->GetDesign_Variable(0) == TRANSLATION and allmoving) {
if (rank == MASTER_NODE)
cout << "Performing a translation of the volumetric grid." << endl;
grid_movement->SetVolume_Translation(geometry_container[ZONE_0], config_container[ZONE_0], false);
} else if (config_container[ZONE_0]->GetDesign_Variable(0) == ROTATION and allmoving) {
if (rank == MASTER_NODE)
cout << "Performing a rotation of the volumetric grid." << endl;
grid_movement->SetVolume_Rotation(geometry_container[ZONE_0], config_container[ZONE_0], false);
} else if (config_container[ZONE_0]->GetDesign_Variable(0) != FFD_SETTING) {
if (rank == MASTER_NODE)
cout << "Performing the deformation of the volumetric grid." << endl;
grid_movement->SetVolume_Deformation(geometry_container[ZONE_0], config_container[ZONE_0], false);
}
/*--- Computational grid preprocesing ---*/
if (rank == MASTER_NODE) cout << endl << "----------------------- Write deformed grid files -----------------------" << endl;
/*--- Output deformed grid for visualization, if requested (surface and volumetric), in parallel
requires to move all the data to the master node---*/
output = new COutput();
output->SetMesh_Files(geometry_container, config_container, SINGLE_ZONE, false, true);
/*--- Write the the free-form deformation boxes after deformation. ---*/
if (rank == MASTER_NODE) cout << "Adding any FFD information to the SU2 file." << endl;
surface_movement->WriteFFDInfo(geometry_container[ZONE_0], config_container[ZONE_0]);
/*--- Synchronization point after a single solver iteration. Compute the
wall clock time required. ---*/
#ifdef HAVE_MPI
StopTime = MPI_Wtime();
#else
StopTime = su2double(clock())/su2double(CLOCKS_PER_SEC);
#endif
/*--- Compute/print the total time for performance benchmarking. ---*/
UsedTime = StopTime-StartTime;
if (rank == MASTER_NODE) {
cout << "\nCompleted in " << fixed << UsedTime << " seconds on "<< size;
if (size == 1) cout << " core." << endl; else cout << " cores." << endl;
}
/*--- Exit the solver cleanly ---*/
if (rank == MASTER_NODE)
cout << endl << "------------------------- Exit Success (SU2_DEF) ------------------------" << endl << endl;
/*--- Finalize MPI parallelization ---*/
#ifdef HAVE_MPI
MPI_Finalize();
#endif
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* Copyright 2017 The primitiv Authors. All Rights Reserved. */
#include <primitiv/config.h>
#include <string>
#include <vector>
#include <primitiv/shape.h>
#include <primitiv/c/internal.h>
#include <primitiv/c/shape.h>
using primitiv::Shape;
using primitiv::c::internal::to_c_ptr;
using primitiv::c::internal::to_cpp_ptr;
using primitiv::c::internal::to_c_ptr_from_value;
extern "C" {
primitiv_Status primitiv_Shape_new(primitiv_Shape **shape) try {
*shape = to_c_ptr(new Shape());
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_new_with_dims(
const uint32_t *dims, size_t n, uint32_t batch,
primitiv_Shape **shape) try {
PRIMITIV_C_CHECK_PTR_ARG(dims);
*shape = to_c_ptr(new Shape(std::vector<uint32_t>(dims, dims + n), batch));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_delete(primitiv_Shape *shape) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
delete to_cpp_ptr(shape);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_op_getitem(
const primitiv_Shape *shape, uint32_t i, uint32_t *dim_size) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*dim_size = to_cpp_ptr(shape)->operator[](i);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_dims(
const primitiv_Shape *shape, uint32_t *dims, size_t *array_size) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
const std::vector<uint32_t> v = to_cpp_ptr(shape)->dims();
if (array_size) {
*array_size = v.size();
}
if (dims) {
std::copy(v.begin(), v.end(), dims);
}
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_depth(
const primitiv_Shape *shape, uint32_t *depth) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*depth = to_cpp_ptr(shape)->depth();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_batch(
const primitiv_Shape *shape, uint32_t *batch) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*batch = to_cpp_ptr(shape)->batch();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_volume(
const primitiv_Shape *shape, uint32_t *volume) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*volume = to_cpp_ptr(shape)->volume();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_lower_volume(
const primitiv_Shape *shape, uint32_t dim, uint32_t *lower_volume) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*lower_volume = to_cpp_ptr(shape)->lower_volume(dim);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_size(
const primitiv_Shape *shape, uint32_t *size) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*size = to_cpp_ptr(shape)->size();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_to_string(
const primitiv_Shape *shape, char *buffer, size_t *buffer_size) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
const std::string str = to_cpp_ptr(shape)->to_string();
if (buffer_size) {
*buffer_size = str.length();
}
if (buffer) {
std::strcpy(buffer, str.c_str());
}
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_op_eq(
const primitiv_Shape *shape, const primitiv_Shape *rhs,
unsigned char *eq) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
PRIMITIV_C_CHECK_PTR_ARG(rhs);
*eq = to_cpp_ptr(shape)->operator==(*to_cpp_ptr(rhs));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_op_ne(
const primitiv_Shape *shape, const primitiv_Shape *rhs,
unsigned char *ne) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
PRIMITIV_C_CHECK_PTR_ARG(rhs);
*ne = to_cpp_ptr(shape)->operator!=(*to_cpp_ptr(rhs));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_has_batch(
const primitiv_Shape *shape, unsigned char *has_batch) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*has_batch = to_cpp_ptr(shape)->has_batch();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_has_compatible_batch(
const primitiv_Shape *shape, const primitiv_Shape *rhs,
unsigned char *has_compatible_batch) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
PRIMITIV_C_CHECK_PTR_ARG(rhs);
*has_compatible_batch =
to_cpp_ptr(shape)->has_compatible_batch(*to_cpp_ptr(rhs));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_is_scalar(
const primitiv_Shape *shape, unsigned char *is_scalar) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*is_scalar = to_cpp_ptr(shape)->is_scalar();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_is_row_vector(
const primitiv_Shape *shape, unsigned char *is_row_vector) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*is_row_vector = to_cpp_ptr(shape)->is_row_vector();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_is_matrix(
const primitiv_Shape *shape, unsigned char *is_matrix) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*is_matrix = to_cpp_ptr(shape)->is_matrix();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_has_same_dims(
const primitiv_Shape *shape, const primitiv_Shape *rhs,
unsigned char *has_same_dims) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
PRIMITIV_C_CHECK_PTR_ARG(rhs);
*has_same_dims = to_cpp_ptr(shape)->has_same_dims(*to_cpp_ptr(rhs));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_has_same_loo_dims(
const primitiv_Shape *shape, const primitiv_Shape *rhs, uint32_t dim,
unsigned char *has_same_loo_dims) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
PRIMITIV_C_CHECK_PTR_ARG(rhs);
*has_same_loo_dims =
to_cpp_ptr(shape)->has_same_loo_dims(*to_cpp_ptr(rhs), dim);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_resize_dim(
const primitiv_Shape *shape, uint32_t dim, uint32_t m,
primitiv_Shape **new_shape) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*new_shape = to_c_ptr_from_value(to_cpp_ptr(shape)->resize_dim(dim, m));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_resize_batch(
const primitiv_Shape *shape, uint32_t batch,
primitiv_Shape **new_shape) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*new_shape = to_c_ptr_from_value(to_cpp_ptr(shape)->resize_batch(batch));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_update_dim(
primitiv_Shape *shape, uint32_t dim, uint32_t m) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
to_cpp_ptr(shape)->update_dim(dim, m);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_update_batch(
primitiv_Shape *shape, uint32_t batch) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
to_cpp_ptr(shape)->update_batch(batch);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
} // end extern "C"
<commit_msg>Include header.<commit_after>/* Copyright 2017 The primitiv Authors. All Rights Reserved. */
#include <primitiv/config.h>
#include <algorithm>
#include <string>
#include <vector>
#include <primitiv/shape.h>
#include <primitiv/c/internal.h>
#include <primitiv/c/shape.h>
using primitiv::Shape;
using primitiv::c::internal::to_c_ptr;
using primitiv::c::internal::to_cpp_ptr;
using primitiv::c::internal::to_c_ptr_from_value;
extern "C" {
primitiv_Status primitiv_Shape_new(primitiv_Shape **shape) try {
*shape = to_c_ptr(new Shape());
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_new_with_dims(
const uint32_t *dims, size_t n, uint32_t batch,
primitiv_Shape **shape) try {
PRIMITIV_C_CHECK_PTR_ARG(dims);
*shape = to_c_ptr(new Shape(std::vector<uint32_t>(dims, dims + n), batch));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_delete(primitiv_Shape *shape) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
delete to_cpp_ptr(shape);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_op_getitem(
const primitiv_Shape *shape, uint32_t i, uint32_t *dim_size) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*dim_size = to_cpp_ptr(shape)->operator[](i);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_dims(
const primitiv_Shape *shape, uint32_t *dims, size_t *array_size) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
const std::vector<uint32_t> v = to_cpp_ptr(shape)->dims();
if (array_size) {
*array_size = v.size();
}
if (dims) {
std::copy(v.begin(), v.end(), dims);
}
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_depth(
const primitiv_Shape *shape, uint32_t *depth) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*depth = to_cpp_ptr(shape)->depth();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_batch(
const primitiv_Shape *shape, uint32_t *batch) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*batch = to_cpp_ptr(shape)->batch();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_volume(
const primitiv_Shape *shape, uint32_t *volume) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*volume = to_cpp_ptr(shape)->volume();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_lower_volume(
const primitiv_Shape *shape, uint32_t dim, uint32_t *lower_volume) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*lower_volume = to_cpp_ptr(shape)->lower_volume(dim);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_size(
const primitiv_Shape *shape, uint32_t *size) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*size = to_cpp_ptr(shape)->size();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_to_string(
const primitiv_Shape *shape, char *buffer, size_t *buffer_size) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
const std::string str = to_cpp_ptr(shape)->to_string();
if (buffer_size) {
*buffer_size = str.length();
}
if (buffer) {
std::strcpy(buffer, str.c_str());
}
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_op_eq(
const primitiv_Shape *shape, const primitiv_Shape *rhs,
unsigned char *eq) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
PRIMITIV_C_CHECK_PTR_ARG(rhs);
*eq = to_cpp_ptr(shape)->operator==(*to_cpp_ptr(rhs));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_op_ne(
const primitiv_Shape *shape, const primitiv_Shape *rhs,
unsigned char *ne) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
PRIMITIV_C_CHECK_PTR_ARG(rhs);
*ne = to_cpp_ptr(shape)->operator!=(*to_cpp_ptr(rhs));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_has_batch(
const primitiv_Shape *shape, unsigned char *has_batch) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*has_batch = to_cpp_ptr(shape)->has_batch();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_has_compatible_batch(
const primitiv_Shape *shape, const primitiv_Shape *rhs,
unsigned char *has_compatible_batch) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
PRIMITIV_C_CHECK_PTR_ARG(rhs);
*has_compatible_batch =
to_cpp_ptr(shape)->has_compatible_batch(*to_cpp_ptr(rhs));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_is_scalar(
const primitiv_Shape *shape, unsigned char *is_scalar) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*is_scalar = to_cpp_ptr(shape)->is_scalar();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_is_row_vector(
const primitiv_Shape *shape, unsigned char *is_row_vector) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*is_row_vector = to_cpp_ptr(shape)->is_row_vector();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_is_matrix(
const primitiv_Shape *shape, unsigned char *is_matrix) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*is_matrix = to_cpp_ptr(shape)->is_matrix();
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_has_same_dims(
const primitiv_Shape *shape, const primitiv_Shape *rhs,
unsigned char *has_same_dims) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
PRIMITIV_C_CHECK_PTR_ARG(rhs);
*has_same_dims = to_cpp_ptr(shape)->has_same_dims(*to_cpp_ptr(rhs));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_has_same_loo_dims(
const primitiv_Shape *shape, const primitiv_Shape *rhs, uint32_t dim,
unsigned char *has_same_loo_dims) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
PRIMITIV_C_CHECK_PTR_ARG(rhs);
*has_same_loo_dims =
to_cpp_ptr(shape)->has_same_loo_dims(*to_cpp_ptr(rhs), dim);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_resize_dim(
const primitiv_Shape *shape, uint32_t dim, uint32_t m,
primitiv_Shape **new_shape) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*new_shape = to_c_ptr_from_value(to_cpp_ptr(shape)->resize_dim(dim, m));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_resize_batch(
const primitiv_Shape *shape, uint32_t batch,
primitiv_Shape **new_shape) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
*new_shape = to_c_ptr_from_value(to_cpp_ptr(shape)->resize_batch(batch));
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_update_dim(
primitiv_Shape *shape, uint32_t dim, uint32_t m) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
to_cpp_ptr(shape)->update_dim(dim, m);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
primitiv_Status primitiv_Shape_update_batch(
primitiv_Shape *shape, uint32_t batch) try {
PRIMITIV_C_CHECK_PTR_ARG(shape);
to_cpp_ptr(shape)->update_batch(batch);
return ::primitiv_Status::PRIMITIV_OK;
} PRIMITIV_C_HANDLE_EXCEPTIONS
} // end extern "C"
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "base/threading/sequenced_worker_pool_task_runner.h"
#include "base/callback.h"
#include "base/location.h"
#include "base/logging.h"
namespace base {
SequencedWorkerPoolTaskRunner::SequencedWorkerPoolTaskRunner(
const scoped_refptr<SequencedWorkerPool>& pool,
SequencedWorkerPool::SequenceToken token)
: pool_(pool),
token_(token) {
}
SequencedWorkerPoolTaskRunner::~SequencedWorkerPoolTaskRunner() {
}
bool SequencedWorkerPoolTaskRunner::PostDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
int64 delay_ms) {
return PostDelayedTaskAssertZeroDelay(from_here, task, delay_ms);
}
bool SequencedWorkerPoolTaskRunner::PostDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
return PostDelayedTaskAssertZeroDelay(from_here, task, delay);
}
bool SequencedWorkerPoolTaskRunner::RunsTasksOnCurrentThread() const {
return pool_->RunsTasksOnCurrentThread();
}
bool SequencedWorkerPoolTaskRunner::PostNonNestableDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
int64 delay_ms) {
return PostDelayedTaskAssertZeroDelay(from_here, task, delay_ms);
}
bool SequencedWorkerPoolTaskRunner::PostNonNestableDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
return PostDelayedTaskAssertZeroDelay(from_here, task, delay);
}
bool SequencedWorkerPoolTaskRunner::PostDelayedTaskAssertZeroDelay(
const tracked_objects::Location& from_here,
const Closure& task,
int64 delay_ms) {
// TODO(francoisk777@gmail.com): Change the following two statements once
// SequencedWorkerPool supports non-zero delays.
DCHECK_EQ(delay_ms, 0)
<< "SequencedWorkerPoolTaskRunner does not yet support non-zero delays";
return pool_->PostSequencedWorkerTask(token_, from_here, task);
}
bool SequencedWorkerPoolTaskRunner::PostDelayedTaskAssertZeroDelay(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
return PostDelayedTaskAssertZeroDelay(from_here,
task,
delay.InMillisecondsRoundedUp());
}
} // namespace base
<commit_msg>Modify SequencedWorkerPoolTaskRunner's RunsTasksOnCurrentThread method to more specifically test if the underlying SWP is currently running a task that matches the runner's sequence token.<commit_after>// Copyright (c) 2012 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 "base/threading/sequenced_worker_pool_task_runner.h"
#include "base/callback.h"
#include "base/location.h"
#include "base/logging.h"
namespace base {
SequencedWorkerPoolTaskRunner::SequencedWorkerPoolTaskRunner(
const scoped_refptr<SequencedWorkerPool>& pool,
SequencedWorkerPool::SequenceToken token)
: pool_(pool),
token_(token) {
}
SequencedWorkerPoolTaskRunner::~SequencedWorkerPoolTaskRunner() {
}
bool SequencedWorkerPoolTaskRunner::PostDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
int64 delay_ms) {
return PostDelayedTaskAssertZeroDelay(from_here, task, delay_ms);
}
bool SequencedWorkerPoolTaskRunner::PostDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
return PostDelayedTaskAssertZeroDelay(from_here, task, delay);
}
bool SequencedWorkerPoolTaskRunner::RunsTasksOnCurrentThread() const {
return pool_->IsRunningSequenceOnCurrentThread(token_);
}
bool SequencedWorkerPoolTaskRunner::PostNonNestableDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
int64 delay_ms) {
return PostDelayedTaskAssertZeroDelay(from_here, task, delay_ms);
}
bool SequencedWorkerPoolTaskRunner::PostNonNestableDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
return PostDelayedTaskAssertZeroDelay(from_here, task, delay);
}
bool SequencedWorkerPoolTaskRunner::PostDelayedTaskAssertZeroDelay(
const tracked_objects::Location& from_here,
const Closure& task,
int64 delay_ms) {
// TODO(francoisk777@gmail.com): Change the following two statements once
// SequencedWorkerPool supports non-zero delays.
DCHECK_EQ(delay_ms, 0)
<< "SequencedWorkerPoolTaskRunner does not yet support non-zero delays";
return pool_->PostSequencedWorkerTask(token_, from_here, task);
}
bool SequencedWorkerPoolTaskRunner::PostDelayedTaskAssertZeroDelay(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
return PostDelayedTaskAssertZeroDelay(from_here,
task,
delay.InMillisecondsRoundedUp());
}
} // namespace base
<|endoftext|> |
<commit_before>/*
* THE UNICODE TEST SUITE FOR CINDER: https://github.com/arielm/Unicode
* COPYRIGHT (C) 2013, ARIEL MALKA ALL RIGHTS RESERVED.
*
* THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:
* https://github.com/arielm/Unicode/blob/master/LICENSE.md
*/
/*
* TESTING LANGUAGE-SPECIFIC FEATURES, AS DESCRIBE IN:
* http://www.mail-archive.com/harfbuzz@lists.freedesktop.org/msg03194.html
*
*
* RESULTS:
*
* - WEBKIT EXAMPLE: IT WORKS ONLY FOR THE FIRST LETTER
* - PANGO EXAMPLE: IT WORKS AS INTENDED
* - SCHEHERAZADE EXAMPLE: IT DOES NOT WORK AS INTENDED:
* - TRYING "snd" INSTEAD OF "sd" FOR LANGUAGE IS NOT HELPING...
*/
#include "cinder/app/AppNative.h"
#include "YFont.h"
using namespace std;
using namespace ci;
using namespace app;
const float FONT_SIZE = 56;
const fs::path EXTERNAL_FONTS_DIRECTORY = "/Users/arielm/Downloads/fonts";
class Application : public AppNative
{
shared_ptr<FreetypeHelper> ftHelper; // THE UNDERLYING FT_Library WILL BE DESTROYED AFTER ALL THE YFont INSTANCES
shared_ptr<YFont> font1;
shared_ptr<YFont> font2;
shared_ptr<YFont> font3;
public:
void prepareSettings(Settings *settings);
void setup();
void draw();
void drawSpan(const YFont &font, const TextSpan &span1, const TextSpan &span2, float y);
void drawHLine(float y);
};
void Application::prepareSettings(Settings *settings)
{
settings->setWindowSize(1024, 512);
}
void Application::setup()
{
ftHelper = make_shared<FreetypeHelper>();
font1 = make_shared<YFont>(ftHelper, FontDescriptor(loadFile(EXTERNAL_FONTS_DIRECTORY / "dejavu-fonts-ttf-2.34/ttf/DejaVuSerif.ttf")), FONT_SIZE);
font2 = make_shared<YFont>(ftHelper, FontDescriptor(loadFile("/Library/Fonts/Verdana.ttf")), FONT_SIZE);
font3 = make_shared<YFont>(ftHelper, FontDescriptor(loadFile(EXTERNAL_FONTS_DIRECTORY / "Scheherazade-2.010/Scheherazade-R.ttf")), FONT_SIZE);
// ---
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
}
void Application::draw()
{
gl::clear(Color::gray(0.5f), false);
gl::setMatricesWindow(toPixels(getWindowSize()), true);
drawSpan(*font1, TextSpan("бгдпт", HB_SCRIPT_CYRILLIC, HB_DIRECTION_LTR, "ru"), TextSpan("бгдпт", HB_SCRIPT_CYRILLIC, HB_DIRECTION_LTR, "sr"), 128);
drawSpan(*font2, TextSpan("şţ", HB_SCRIPT_LATIN, HB_DIRECTION_LTR, "en"), TextSpan("şţ", HB_SCRIPT_LATIN, HB_DIRECTION_LTR, "ro"), 256);
drawSpan(*font3, TextSpan("ههه ۴۵۶۷", HB_SCRIPT_ARABIC, HB_DIRECTION_RTL, "ar"), TextSpan("ههه ۴۵۶۷", HB_SCRIPT_ARABIC, HB_DIRECTION_RTL, "sd"), 384);
}
void Application::drawSpan(const YFont &font, const TextSpan &span1, const TextSpan &span2, float y)
{
glColor4f(1, 1, 1, 1);
font.drawSpan(span1, 24, y);
font.drawSpan(span2, 512 + 24, y);
glColor4f(1, 0.75f, 0, 0.5f);
drawHLine(y);
glColor4f(1, 1, 0, 0.33f);
drawHLine(y - font.ascent);
drawHLine(y + font.descent);
}
void Application::drawHLine(float y)
{
gl::drawLine(Vec2f(-9999, y), Vec2f(+9999, y));
}
CINDER_APP_NATIVE(Application, RendererGl(RendererGl::AA_NONE))
<commit_msg>Update Application.cpp<commit_after>/*
* THE UNICODE TEST SUITE FOR CINDER: https://github.com/arielm/Unicode
* COPYRIGHT (C) 2013, ARIEL MALKA ALL RIGHTS RESERVED.
*
* THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:
* https://github.com/arielm/Unicode/blob/master/LICENSE.md
*/
/*
* TESTING LANGUAGE-SPECIFIC FEATURES, AS DESCRIBED IN:
* http://www.mail-archive.com/harfbuzz@lists.freedesktop.org/msg03194.html
*
*
* RESULTS:
*
* - WEBKIT EXAMPLE: IT WORKS ONLY FOR THE FIRST LETTER
* - PANGO EXAMPLE: IT WORKS AS INTENDED
* - SCHEHERAZADE EXAMPLE: IT DOES NOT WORK AS INTENDED:
* - TRYING "snd" INSTEAD OF "sd" FOR LANGUAGE IS NOT HELPING...
*/
#include "cinder/app/AppNative.h"
#include "YFont.h"
using namespace std;
using namespace ci;
using namespace app;
const float FONT_SIZE = 56;
const fs::path EXTERNAL_FONTS_DIRECTORY = "/Users/arielm/Downloads/fonts";
class Application : public AppNative
{
shared_ptr<FreetypeHelper> ftHelper; // THE UNDERLYING FT_Library WILL BE DESTROYED AFTER ALL THE YFont INSTANCES
shared_ptr<YFont> font1;
shared_ptr<YFont> font2;
shared_ptr<YFont> font3;
public:
void prepareSettings(Settings *settings);
void setup();
void draw();
void drawSpan(const YFont &font, const TextSpan &span1, const TextSpan &span2, float y);
void drawHLine(float y);
};
void Application::prepareSettings(Settings *settings)
{
settings->setWindowSize(1024, 512);
}
void Application::setup()
{
ftHelper = make_shared<FreetypeHelper>();
font1 = make_shared<YFont>(ftHelper, FontDescriptor(loadFile(EXTERNAL_FONTS_DIRECTORY / "dejavu-fonts-ttf-2.34/ttf/DejaVuSerif.ttf")), FONT_SIZE);
font2 = make_shared<YFont>(ftHelper, FontDescriptor(loadFile("/Library/Fonts/Verdana.ttf")), FONT_SIZE);
font3 = make_shared<YFont>(ftHelper, FontDescriptor(loadFile(EXTERNAL_FONTS_DIRECTORY / "Scheherazade-2.010/Scheherazade-R.ttf")), FONT_SIZE);
// ---
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
}
void Application::draw()
{
gl::clear(Color::gray(0.5f), false);
gl::setMatricesWindow(toPixels(getWindowSize()), true);
drawSpan(*font1, TextSpan("бгдпт", HB_SCRIPT_CYRILLIC, HB_DIRECTION_LTR, "ru"), TextSpan("бгдпт", HB_SCRIPT_CYRILLIC, HB_DIRECTION_LTR, "sr"), 128);
drawSpan(*font2, TextSpan("şţ", HB_SCRIPT_LATIN, HB_DIRECTION_LTR, "en"), TextSpan("şţ", HB_SCRIPT_LATIN, HB_DIRECTION_LTR, "ro"), 256);
drawSpan(*font3, TextSpan("ههه ۴۵۶۷", HB_SCRIPT_ARABIC, HB_DIRECTION_RTL, "ar"), TextSpan("ههه ۴۵۶۷", HB_SCRIPT_ARABIC, HB_DIRECTION_RTL, "sd"), 384);
}
void Application::drawSpan(const YFont &font, const TextSpan &span1, const TextSpan &span2, float y)
{
glColor4f(1, 1, 1, 1);
font.drawSpan(span1, 24, y);
font.drawSpan(span2, 512 + 24, y);
glColor4f(1, 0.75f, 0, 0.5f);
drawHLine(y);
glColor4f(1, 1, 0, 0.33f);
drawHLine(y - font.ascent);
drawHLine(y + font.descent);
}
void Application::drawHLine(float y)
{
gl::drawLine(Vec2f(-9999, y), Vec2f(+9999, y));
}
CINDER_APP_NATIVE(Application, RendererGl(RendererGl::AA_NONE))
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "fnord-base/util/binarymessagewriter.h"
#include "fnord-tsdb/TSDBServlet.h"
#include "fnord-json/json.h"
#include <fnord-base/wallclock.h>
#include "fnord-msg/MessageEncoder.h"
#include "fnord-msg/MessagePrinter.h"
#include <fnord-base/util/Base64.h>
#include <fnord-sstable/sstablereader.h>
namespace fnord {
namespace tsdb {
TSDBServlet::TSDBServlet(TSDBNode* node) : node_(node) {}
void TSDBServlet::handleHTTPRequest(
RefPtr<http::HTTPRequestStream> req_stream,
RefPtr<http::HTTPResponseStream> res_stream) {
req_stream->readBody();
const auto& req = req_stream->request();
URI uri(req.uri());
http::HTTPResponse res;
res.populateFromRequest(req);
res.addHeader("Access-Control-Allow-Origin", "*");
try {
if (StringUtil::endsWith(uri.path(), "/insert")) {
insertRecord(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
if (StringUtil::endsWith(uri.path(), "/insert_batch")) {
insertRecordsBatch(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
if (StringUtil::endsWith(uri.path(), "/replicate")) {
insertRecordsReplication(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
if (StringUtil::endsWith(uri.path(), "/list_chunks")) {
listChunks(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
if (StringUtil::endsWith(uri.path(), "/list_files")) {
listFiles(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
if (StringUtil::endsWith(uri.path(), "/fetch_chunk")) {
fetchChunk(&req, &res, res_stream, &uri);
return;
}
if (StringUtil::endsWith(uri.path(), "/fetch_derived_dataset")) {
fetchDerivedDataset(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
res.setStatus(fnord::http::kStatusNotFound);
res.addBody("not found");
res_stream->writeResponse(res);
} catch (const Exception& e) {
res.setStatus(http::kStatusInternalServerError);
res.addBody(StringUtil::format("error: $0: $1", e.getTypeName(), e.getMessage()));
res_stream->writeResponse(res);
}
}
void TSDBServlet::insertRecord(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String stream;
if (!URI::getParam(params, "stream", &stream)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?stream=... parameter");
return;
}
uint64_t record_id = rnd_.random64();
auto time = WallClock::now();
if (req->body().size() == 0) {
RAISEF(kRuntimeError, "empty record: $0", record_id);
}
node_->insertRecord(stream, record_id, req->body(), time);
res->setStatus(http::kStatusCreated);
}
void TSDBServlet::insertRecordsBatch(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String stream;
if (!URI::getParam(params, "stream", &stream)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?stream=... parameter");
return;
}
auto& buf = req->body();
util::BinaryMessageReader reader(buf.data(), buf.size());
Vector<RecordRef> recs;
while (reader.remaining() > 0) {
auto time = *reader.readUInt64();
auto record_id = *reader.readUInt64();
auto len = reader.readVarUInt();
auto data = reader.read(len);
if (len == 0) {
RAISEF(kRuntimeError, "empty record: $0", record_id);
}
recs.emplace_back(RecordRef(record_id, time, Buffer(data, len)));
}
node_->insertRecords(stream, recs);
res->setStatus(http::kStatusCreated);
}
void TSDBServlet::insertRecordsReplication(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String stream;
if (!URI::getParam(params, "stream", &stream)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?stream=... parameter");
return;
}
String chunk_base64;
if (!URI::getParam(params, "chunk", &chunk_base64)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?chunk=... parameter");
return;
}
String chunk;
util::Base64::decode(chunk_base64, &chunk);
auto& buf = req->body();
util::BinaryMessageReader reader(buf.data(), buf.size());
Vector<RecordRef> recs;
while (reader.remaining() > 0) {
auto record_id = *reader.readUInt64();
auto len = reader.readVarUInt();
auto data = reader.read(len);
if (len == 0) {
RAISEF(kRuntimeError, "empty record: $0", record_id);
}
recs.emplace_back(RecordRef(record_id, 0, Buffer(data, len)));
}
node_->insertRecords(stream, chunk, recs);
res->setStatus(http::kStatusCreated);
}
void TSDBServlet::listChunks(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String stream;
if (!URI::getParam(params, "stream", &stream)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?stream=... parameter");
return;
}
DateTime from;
String from_str;
if (URI::getParam(params, "from", &from_str)) {
from = DateTime(std::stoul(from_str));
} else {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?from=... parameter");
return;
}
DateTime until;
String until_str;
if (URI::getParam(params, "until", &until_str)) {
until = DateTime(std::stoul(until_str));
} else {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?until=... parameter");
return;
}
auto cfg = node_->configFor(stream);
auto chunks = StreamChunk::streamChunkKeysFor(stream, from, until, *cfg);
Vector<String> chunks_encoded;
for (const auto& c : chunks) {
String encoded;
util::Base64::encode(c, &encoded);
chunks_encoded.emplace_back(encoded);
}
util::BinaryMessageWriter buf;
for (const auto& c : chunks_encoded) {
buf.appendLenencString(c);
}
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res->addBody(buf.data(), buf.size());
/*
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream j(res->getBodyOutputStream());
j.beginObject();
j.addObjectEntry("stream");
j.addString(stream);
j.addComma();
j.addObjectEntry("from");
j.addInteger(from.unixMicros());
j.addComma();
j.addObjectEntry("until");
j.addInteger(until.unixMicros());
j.addComma();
j.addObjectEntry("chunk_keys");
json::toJSON(chunks_encoded, &j);
j.endObject();
*/
}
void TSDBServlet::listFiles(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String chunk;
if (!URI::getParam(params, "chunk", &chunk)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?chunk=... parameter");
return;
}
String chunk_key;
util::Base64::decode(chunk, &chunk_key);
auto files = node_->listFiles(chunk_key);
util::BinaryMessageWriter buf;
for (const auto& f : files) {
buf.appendLenencString(f);
}
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res->addBody(buf.data(), buf.size());
/*
Vector<String> chunks_encoded;
for (const auto& c : chunks) {
String encoded;
util::Base64::encode(c, &encoded);
chunks_encoded.emplace_back(encoded);
}
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream j(res->getBodyOutputStream());
j.beginObject();
j.addObjectEntry("stream");
j.addString(stream);
j.addComma();
j.addObjectEntry("from");
j.addInteger(from.unixMicros());
j.addComma();
j.addObjectEntry("until");
j.addInteger(until.unixMicros());
j.addComma();
j.addObjectEntry("chunk_keys");
json::toJSON(chunks_encoded, &j);
j.endObject();
*/
}
void TSDBServlet::fetchChunk(
const http::HTTPRequest* req,
http::HTTPResponse* res,
RefPtr<http::HTTPResponseStream> res_stream,
URI* uri) {
const auto& params = uri->queryParams();
String chunk;
if (!URI::getParam(params, "chunk", &chunk)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?chunk=... parameter");
res_stream->writeResponse(*res);
return;
}
String chunk_key;
util::Base64::decode(chunk, &chunk_key);
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res_stream->startResponse(*res);
auto files = node_->listFiles(chunk_key);
for (const auto& f : files) {
sstable::SSTableReader reader(f);
auto cursor = reader.getCursor();
while (cursor->valid()) {
void* key;
size_t key_size;
cursor->getKey(&key, &key_size);
if (key_size != sizeof(uint64_t)) {
continue;
}
void* data;
size_t data_size;
cursor->getData(&data, &data_size);
util::BinaryMessageWriter buf;
buf.appendVarUInt(*((uint64_t*) key));
buf.appendVarUInt(data_size);
buf.append(data, data_size);
res_stream->writeBodyChunk(Buffer(buf.data(), buf.size()));
if (!cursor->next()) {
break;
}
}
}
res_stream->finishResponse();
}
void TSDBServlet::fetchDerivedDataset(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String chunk;
if (!URI::getParam(params, "chunk", &chunk)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?chunk=... parameter");
return;
}
String derived;
if (!URI::getParam(params, "derived_dataset", &derived)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?derived_dataset=... parameter");
return;
}
String chunk_key;
util::Base64::decode(chunk, &chunk_key);
auto buf = node_->fetchDerivedDataset(chunk_key, derived);
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res->addBody(buf.data(), buf.size());
}
}
}
<commit_msg>set Connection: close header<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "fnord-base/util/binarymessagewriter.h"
#include "fnord-tsdb/TSDBServlet.h"
#include "fnord-json/json.h"
#include <fnord-base/wallclock.h>
#include "fnord-msg/MessageEncoder.h"
#include "fnord-msg/MessagePrinter.h"
#include <fnord-base/util/Base64.h>
#include <fnord-sstable/sstablereader.h>
namespace fnord {
namespace tsdb {
TSDBServlet::TSDBServlet(TSDBNode* node) : node_(node) {}
void TSDBServlet::handleHTTPRequest(
RefPtr<http::HTTPRequestStream> req_stream,
RefPtr<http::HTTPResponseStream> res_stream) {
req_stream->readBody();
const auto& req = req_stream->request();
URI uri(req.uri());
http::HTTPResponse res;
res.populateFromRequest(req);
res.addHeader("Access-Control-Allow-Origin", "*");
try {
if (StringUtil::endsWith(uri.path(), "/insert")) {
insertRecord(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
if (StringUtil::endsWith(uri.path(), "/insert_batch")) {
insertRecordsBatch(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
if (StringUtil::endsWith(uri.path(), "/replicate")) {
insertRecordsReplication(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
if (StringUtil::endsWith(uri.path(), "/list_chunks")) {
listChunks(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
if (StringUtil::endsWith(uri.path(), "/list_files")) {
listFiles(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
if (StringUtil::endsWith(uri.path(), "/fetch_chunk")) {
fetchChunk(&req, &res, res_stream, &uri);
return;
}
if (StringUtil::endsWith(uri.path(), "/fetch_derived_dataset")) {
fetchDerivedDataset(&req, &res, &uri);
res_stream->writeResponse(res);
return;
}
res.setStatus(fnord::http::kStatusNotFound);
res.addBody("not found");
res_stream->writeResponse(res);
} catch (const Exception& e) {
res.setStatus(http::kStatusInternalServerError);
res.addBody(StringUtil::format("error: $0: $1", e.getTypeName(), e.getMessage()));
res_stream->writeResponse(res);
}
}
void TSDBServlet::insertRecord(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String stream;
if (!URI::getParam(params, "stream", &stream)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?stream=... parameter");
return;
}
uint64_t record_id = rnd_.random64();
auto time = WallClock::now();
if (req->body().size() == 0) {
RAISEF(kRuntimeError, "empty record: $0", record_id);
}
node_->insertRecord(stream, record_id, req->body(), time);
res->setStatus(http::kStatusCreated);
}
void TSDBServlet::insertRecordsBatch(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String stream;
if (!URI::getParam(params, "stream", &stream)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?stream=... parameter");
return;
}
auto& buf = req->body();
util::BinaryMessageReader reader(buf.data(), buf.size());
Vector<RecordRef> recs;
while (reader.remaining() > 0) {
auto time = *reader.readUInt64();
auto record_id = *reader.readUInt64();
auto len = reader.readVarUInt();
auto data = reader.read(len);
if (len == 0) {
RAISEF(kRuntimeError, "empty record: $0", record_id);
}
recs.emplace_back(RecordRef(record_id, time, Buffer(data, len)));
}
node_->insertRecords(stream, recs);
res->setStatus(http::kStatusCreated);
}
void TSDBServlet::insertRecordsReplication(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String stream;
if (!URI::getParam(params, "stream", &stream)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?stream=... parameter");
return;
}
String chunk_base64;
if (!URI::getParam(params, "chunk", &chunk_base64)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?chunk=... parameter");
return;
}
String chunk;
util::Base64::decode(chunk_base64, &chunk);
auto& buf = req->body();
util::BinaryMessageReader reader(buf.data(), buf.size());
Vector<RecordRef> recs;
while (reader.remaining() > 0) {
auto record_id = *reader.readUInt64();
auto len = reader.readVarUInt();
auto data = reader.read(len);
if (len == 0) {
RAISEF(kRuntimeError, "empty record: $0", record_id);
}
recs.emplace_back(RecordRef(record_id, 0, Buffer(data, len)));
}
node_->insertRecords(stream, chunk, recs);
res->setStatus(http::kStatusCreated);
}
void TSDBServlet::listChunks(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String stream;
if (!URI::getParam(params, "stream", &stream)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?stream=... parameter");
return;
}
DateTime from;
String from_str;
if (URI::getParam(params, "from", &from_str)) {
from = DateTime(std::stoul(from_str));
} else {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?from=... parameter");
return;
}
DateTime until;
String until_str;
if (URI::getParam(params, "until", &until_str)) {
until = DateTime(std::stoul(until_str));
} else {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?until=... parameter");
return;
}
auto cfg = node_->configFor(stream);
auto chunks = StreamChunk::streamChunkKeysFor(stream, from, until, *cfg);
Vector<String> chunks_encoded;
for (const auto& c : chunks) {
String encoded;
util::Base64::encode(c, &encoded);
chunks_encoded.emplace_back(encoded);
}
util::BinaryMessageWriter buf;
for (const auto& c : chunks_encoded) {
buf.appendLenencString(c);
}
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res->addBody(buf.data(), buf.size());
/*
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream j(res->getBodyOutputStream());
j.beginObject();
j.addObjectEntry("stream");
j.addString(stream);
j.addComma();
j.addObjectEntry("from");
j.addInteger(from.unixMicros());
j.addComma();
j.addObjectEntry("until");
j.addInteger(until.unixMicros());
j.addComma();
j.addObjectEntry("chunk_keys");
json::toJSON(chunks_encoded, &j);
j.endObject();
*/
}
void TSDBServlet::listFiles(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String chunk;
if (!URI::getParam(params, "chunk", &chunk)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?chunk=... parameter");
return;
}
String chunk_key;
util::Base64::decode(chunk, &chunk_key);
auto files = node_->listFiles(chunk_key);
util::BinaryMessageWriter buf;
for (const auto& f : files) {
buf.appendLenencString(f);
}
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res->addBody(buf.data(), buf.size());
/*
Vector<String> chunks_encoded;
for (const auto& c : chunks) {
String encoded;
util::Base64::encode(c, &encoded);
chunks_encoded.emplace_back(encoded);
}
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream j(res->getBodyOutputStream());
j.beginObject();
j.addObjectEntry("stream");
j.addString(stream);
j.addComma();
j.addObjectEntry("from");
j.addInteger(from.unixMicros());
j.addComma();
j.addObjectEntry("until");
j.addInteger(until.unixMicros());
j.addComma();
j.addObjectEntry("chunk_keys");
json::toJSON(chunks_encoded, &j);
j.endObject();
*/
}
void TSDBServlet::fetchChunk(
const http::HTTPRequest* req,
http::HTTPResponse* res,
RefPtr<http::HTTPResponseStream> res_stream,
URI* uri) {
const auto& params = uri->queryParams();
String chunk;
if (!URI::getParam(params, "chunk", &chunk)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?chunk=... parameter");
res_stream->writeResponse(*res);
return;
}
String chunk_key;
util::Base64::decode(chunk, &chunk_key);
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res->addHeader("Connection", "close");
res_stream->startResponse(*res);
auto files = node_->listFiles(chunk_key);
for (const auto& f : files) {
sstable::SSTableReader reader(f);
auto cursor = reader.getCursor();
while (cursor->valid()) {
void* key;
size_t key_size;
cursor->getKey(&key, &key_size);
if (key_size != sizeof(uint64_t)) {
continue;
}
void* data;
size_t data_size;
cursor->getData(&data, &data_size);
util::BinaryMessageWriter buf;
buf.appendVarUInt(*((uint64_t*) key));
buf.appendVarUInt(data_size);
buf.append(data, data_size);
res_stream->writeBodyChunk(Buffer(buf.data(), buf.size()));
if (!cursor->next()) {
break;
}
}
}
res_stream->finishResponse();
}
void TSDBServlet::fetchDerivedDataset(
const http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String chunk;
if (!URI::getParam(params, "chunk", &chunk)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?chunk=... parameter");
return;
}
String derived;
if (!URI::getParam(params, "derived_dataset", &derived)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?derived_dataset=... parameter");
return;
}
String chunk_key;
util::Base64::decode(chunk, &chunk_key);
auto buf = node_->fetchDerivedDataset(chunk_key, derived);
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res->addBody(buf.data(), buf.size());
}
}
}
<|endoftext|> |
<commit_before>//===------ UnixToolChains.cpp - Job invocations (non-Darwin Unix) --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "ToolChains.h"
#include "swift/Basic/Dwarf.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/Platform.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/TaskQueue.h"
#include "swift/Config.h"
#include "swift/Driver/Compilation.h"
#include "swift/Driver/Driver.h"
#include "swift/Driver/Job.h"
#include "swift/Option/Options.h"
#include "swift/Option/SanitizerOptions.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/Util.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/ProfileData/InstrProf.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Program.h"
using namespace swift;
using namespace swift::driver;
using namespace llvm::opt;
std::string
toolchains::GenericUnix::sanitizerRuntimeLibName(StringRef Sanitizer,
bool shared) const {
return (Twine("libclang_rt.") + Sanitizer + "-" +
this->getTriple().getArchName() + ".a")
.str();
}
ToolChain::InvocationInfo
toolchains::GenericUnix::constructInvocation(const InterpretJobAction &job,
const JobContext &context) const {
InvocationInfo II = ToolChain::constructInvocation(job, context);
SmallVector<std::string, 4> runtimeLibraryPaths;
getRuntimeLibraryPaths(runtimeLibraryPaths, context.Args, context.OI.SDKPath,
/*Shared=*/true);
addPathEnvironmentVariableIfNeeded(II.ExtraEnvironment, "LD_LIBRARY_PATH",
":", options::OPT_L, context.Args,
runtimeLibraryPaths);
return II;
}
ToolChain::InvocationInfo toolchains::GenericUnix::constructInvocation(
const AutolinkExtractJobAction &job, const JobContext &context) const {
assert(context.Output.getPrimaryOutputType() == file_types::TY_AutolinkFile);
InvocationInfo II{"swift-autolink-extract"};
ArgStringList &Arguments = II.Arguments;
II.allowsResponseFiles = true;
addPrimaryInputsOfType(Arguments, context.Inputs, context.Args,
file_types::TY_Object);
addInputsOfType(Arguments, context.InputActions, file_types::TY_Object);
Arguments.push_back("-o");
Arguments.push_back(
context.Args.MakeArgString(context.Output.getPrimaryOutputFilename()));
return II;
}
std::string toolchains::GenericUnix::getDefaultLinker() const {
switch (getTriple().getArch()) {
case llvm::Triple::arm:
case llvm::Triple::aarch64:
case llvm::Triple::armeb:
case llvm::Triple::thumb:
case llvm::Triple::thumbeb:
// BFD linker has issues wrt relocation of the protocol conformance
// section on these targets, it also generates COPY relocations for
// final executables, as such, unless specified, we default to gold
// linker.
return "gold";
case llvm::Triple::x86:
case llvm::Triple::x86_64:
case llvm::Triple::ppc64:
case llvm::Triple::ppc64le:
case llvm::Triple::systemz:
// BFD linker has issues wrt relocations against protected symbols.
return "gold";
default:
// Otherwise, use the default BFD linker.
return "";
}
}
std::string toolchains::GenericUnix::getTargetForLinker() const {
return getTriple().str();
}
bool toolchains::GenericUnix::shouldProvideRPathToLinker() const {
return true;
}
ToolChain::InvocationInfo
toolchains::GenericUnix::constructInvocation(const DynamicLinkJobAction &job,
const JobContext &context) const {
assert(context.Output.getPrimaryOutputType() == file_types::TY_Image &&
"Invalid linker output type.");
ArgStringList Arguments;
switch (job.getKind()) {
case LinkKind::None:
llvm_unreachable("invalid link kind");
case LinkKind::Executable:
// Default case, nothing extra needed.
break;
case LinkKind::DynamicLibrary:
Arguments.push_back("-shared");
break;
case LinkKind::StaticLibrary:
llvm_unreachable("the dynamic linker cannot build static libraries");
}
// Select the linker to use.
std::string Linker;
if (const Arg *A = context.Args.getLastArg(options::OPT_use_ld)) {
Linker = A->getValue();
} else {
Linker = getDefaultLinker();
}
if (!Linker.empty()) {
#if defined(__HAIKU__)
// For now, passing -fuse-ld on Haiku doesn't work as swiftc doesn't
// recognise it. Passing -use-ld= as the argument works fine.
Arguments.push_back(context.Args.MakeArgString("-use-ld=" + Linker));
#else
Arguments.push_back(context.Args.MakeArgString("-fuse-ld=" + Linker));
#endif
}
// Configure the toolchain.
// By default, use the system clang++ to link.
const char *Clang = "clang++";
if (const Arg *A = context.Args.getLastArg(options::OPT_tools_directory)) {
StringRef toolchainPath(A->getValue());
// If there is a clang in the toolchain folder, use that instead.
if (auto toolchainClang =
llvm::sys::findProgramByName("clang++", {toolchainPath})) {
Clang = context.Args.MakeArgString(toolchainClang.get());
}
// Look for binutils in the toolchain folder.
Arguments.push_back("-B");
Arguments.push_back(context.Args.MakeArgString(A->getValue()));
}
if (getTriple().getOS() == llvm::Triple::Linux &&
job.getKind() == LinkKind::Executable) {
Arguments.push_back("-pie");
}
std::string Target = getTargetForLinker();
if (!Target.empty()) {
Arguments.push_back("-target");
Arguments.push_back(context.Args.MakeArgString(Target));
}
bool staticExecutable = false;
bool staticStdlib = false;
if (context.Args.hasFlag(options::OPT_static_executable,
options::OPT_no_static_executable, false)) {
staticExecutable = true;
} else if (context.Args.hasFlag(options::OPT_static_stdlib,
options::OPT_no_static_stdlib, false)) {
staticStdlib = true;
}
SmallVector<std::string, 4> RuntimeLibPaths;
getRuntimeLibraryPaths(RuntimeLibPaths, context.Args, context.OI.SDKPath,
/*Shared=*/!(staticExecutable || staticStdlib));
if (!(staticExecutable || staticStdlib) && shouldProvideRPathToLinker()) {
// FIXME: We probably shouldn't be adding an rpath here unless we know
// ahead of time the standard library won't be copied.
for (auto path : RuntimeLibPaths) {
Arguments.push_back("-Xlinker");
Arguments.push_back("-rpath");
Arguments.push_back("-Xlinker");
Arguments.push_back(context.Args.MakeArgString(path));
}
}
SmallString<128> SharedResourceDirPath;
getResourceDirPath(SharedResourceDirPath, context.Args, /*Shared=*/true);
SmallString<128> swiftrtPath = SharedResourceDirPath;
llvm::sys::path::append(swiftrtPath,
swift::getMajorArchitectureName(getTriple()));
llvm::sys::path::append(swiftrtPath, "swiftrt.o");
Arguments.push_back(context.Args.MakeArgString(swiftrtPath));
addPrimaryInputsOfType(Arguments, context.Inputs, context.Args,
file_types::TY_Object);
addInputsOfType(Arguments, context.InputActions, file_types::TY_Object);
for (const Arg *arg :
context.Args.filtered(options::OPT_F, options::OPT_Fsystem)) {
if (arg->getOption().matches(options::OPT_Fsystem))
Arguments.push_back("-iframework");
else
Arguments.push_back(context.Args.MakeArgString(arg->getSpelling()));
Arguments.push_back(arg->getValue());
}
if (!context.OI.SDKPath.empty()) {
Arguments.push_back("--sysroot");
Arguments.push_back(context.Args.MakeArgString(context.OI.SDKPath));
}
// Add any autolinking scripts to the arguments
for (const Job *Cmd : context.Inputs) {
auto &OutputInfo = Cmd->getOutput();
if (OutputInfo.getPrimaryOutputType() == file_types::TY_AutolinkFile)
Arguments.push_back(context.Args.MakeArgString(
Twine("@") + OutputInfo.getPrimaryOutputFilename()));
}
// Add the runtime library link paths.
for (auto path : RuntimeLibPaths) {
Arguments.push_back("-L");
Arguments.push_back(context.Args.MakeArgString(path));
}
// Link the standard library. In two paths, we do this using a .lnk file;
// if we're going that route, we'll set `linkFilePath` to the path to that
// file.
SmallString<128> linkFilePath;
getResourceDirPath(linkFilePath, context.Args, /*Shared=*/false);
if (staticExecutable) {
llvm::sys::path::append(linkFilePath, "static-executable-args.lnk");
} else if (staticStdlib) {
llvm::sys::path::append(linkFilePath, "static-stdlib-args.lnk");
} else {
linkFilePath.clear();
Arguments.push_back("-lswiftCore");
}
if (!linkFilePath.empty()) {
auto linkFile = linkFilePath.str();
if (llvm::sys::fs::is_regular_file(linkFile)) {
Arguments.push_back(context.Args.MakeArgString(Twine("@") + linkFile));
} else {
llvm::report_fatal_error(linkFile + " not found");
}
}
// Explicitly pass the target to the linker
Arguments.push_back(
context.Args.MakeArgString("--target=" + getTriple().str()));
// Delegate to Clang for sanitizers. It will figure out the correct linker
// options.
if (job.getKind() == LinkKind::Executable && context.OI.SelectedSanitizers) {
Arguments.push_back(context.Args.MakeArgString(
"-fsanitize=" + getSanitizerList(context.OI.SelectedSanitizers)));
// The TSan runtime depends on the blocks runtime and libdispatch.
if (context.OI.SelectedSanitizers & SanitizerKind::Thread) {
Arguments.push_back("-lBlocksRuntime");
Arguments.push_back("-ldispatch");
}
}
if (context.Args.hasArg(options::OPT_profile_generate)) {
SmallString<128> LibProfile(SharedResourceDirPath);
llvm::sys::path::remove_filename(LibProfile); // remove platform name
llvm::sys::path::append(LibProfile, "clang", "lib");
llvm::sys::path::append(LibProfile, getTriple().getOSName(),
Twine("libclang_rt.profile-") +
getTriple().getArchName() + ".a");
Arguments.push_back(context.Args.MakeArgString(LibProfile));
Arguments.push_back(context.Args.MakeArgString(
Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
}
// Run clang++ in verbose mode if "-v" is set
if (context.Args.hasArg(options::OPT_v)) {
Arguments.push_back("-v");
}
// These custom arguments should be right before the object file at the end.
context.Args.AddAllArgs(Arguments, options::OPT_linker_option_Group);
context.Args.AddAllArgs(Arguments, options::OPT_Xlinker);
context.Args.AddAllArgValues(Arguments, options::OPT_Xclang_linker);
// This should be the last option, for convenience in checking output.
Arguments.push_back("-o");
Arguments.push_back(
context.Args.MakeArgString(context.Output.getPrimaryOutputFilename()));
InvocationInfo II{Clang, Arguments};
II.allowsResponseFiles = true;
return II;
}
ToolChain::InvocationInfo
toolchains::GenericUnix::constructInvocation(const StaticLinkJobAction &job,
const JobContext &context) const {
assert(context.Output.getPrimaryOutputType() == file_types::TY_Image &&
"Invalid linker output type.");
ArgStringList Arguments;
// Configure the toolchain.
const char *AR = "ar";
Arguments.push_back("crs");
Arguments.push_back(
context.Args.MakeArgString(context.Output.getPrimaryOutputFilename()));
addPrimaryInputsOfType(Arguments, context.Inputs, context.Args,
file_types::TY_Object);
addInputsOfType(Arguments, context.InputActions, file_types::TY_Object);
InvocationInfo II{AR, Arguments};
return II;
}
std::string toolchains::Android::getTargetForLinker() const {
const llvm::Triple &T = getTriple();
if (T.getArch() == llvm::Triple::arm &&
T.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v7)
// Explicitly set the linker target to "androideabi", as opposed to the
// llvm::Triple representation of "armv7-none-linux-android".
return "armv7-none-linux-androideabi";
return T.str();
}
bool toolchains::Android::shouldProvideRPathToLinker() const { return false; }
std::string toolchains::Cygwin::getDefaultLinker() const {
// Cygwin uses the default BFD linker, even on ARM.
return "";
}
std::string toolchains::Cygwin::getTargetForLinker() const { return ""; }
<commit_msg>Driver: pass `-target` immediately after clang++ (NFC)<commit_after>//===------ UnixToolChains.cpp - Job invocations (non-Darwin Unix) --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "ToolChains.h"
#include "swift/Basic/Dwarf.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/Platform.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/TaskQueue.h"
#include "swift/Config.h"
#include "swift/Driver/Compilation.h"
#include "swift/Driver/Driver.h"
#include "swift/Driver/Job.h"
#include "swift/Option/Options.h"
#include "swift/Option/SanitizerOptions.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/Util.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/ProfileData/InstrProf.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Program.h"
using namespace swift;
using namespace swift::driver;
using namespace llvm::opt;
std::string
toolchains::GenericUnix::sanitizerRuntimeLibName(StringRef Sanitizer,
bool shared) const {
return (Twine("libclang_rt.") + Sanitizer + "-" +
this->getTriple().getArchName() + ".a")
.str();
}
ToolChain::InvocationInfo
toolchains::GenericUnix::constructInvocation(const InterpretJobAction &job,
const JobContext &context) const {
InvocationInfo II = ToolChain::constructInvocation(job, context);
SmallVector<std::string, 4> runtimeLibraryPaths;
getRuntimeLibraryPaths(runtimeLibraryPaths, context.Args, context.OI.SDKPath,
/*Shared=*/true);
addPathEnvironmentVariableIfNeeded(II.ExtraEnvironment, "LD_LIBRARY_PATH",
":", options::OPT_L, context.Args,
runtimeLibraryPaths);
return II;
}
ToolChain::InvocationInfo toolchains::GenericUnix::constructInvocation(
const AutolinkExtractJobAction &job, const JobContext &context) const {
assert(context.Output.getPrimaryOutputType() == file_types::TY_AutolinkFile);
InvocationInfo II{"swift-autolink-extract"};
ArgStringList &Arguments = II.Arguments;
II.allowsResponseFiles = true;
addPrimaryInputsOfType(Arguments, context.Inputs, context.Args,
file_types::TY_Object);
addInputsOfType(Arguments, context.InputActions, file_types::TY_Object);
Arguments.push_back("-o");
Arguments.push_back(
context.Args.MakeArgString(context.Output.getPrimaryOutputFilename()));
return II;
}
std::string toolchains::GenericUnix::getDefaultLinker() const {
switch (getTriple().getArch()) {
case llvm::Triple::arm:
case llvm::Triple::aarch64:
case llvm::Triple::armeb:
case llvm::Triple::thumb:
case llvm::Triple::thumbeb:
// BFD linker has issues wrt relocation of the protocol conformance
// section on these targets, it also generates COPY relocations for
// final executables, as such, unless specified, we default to gold
// linker.
return "gold";
case llvm::Triple::x86:
case llvm::Triple::x86_64:
case llvm::Triple::ppc64:
case llvm::Triple::ppc64le:
case llvm::Triple::systemz:
// BFD linker has issues wrt relocations against protected symbols.
return "gold";
default:
// Otherwise, use the default BFD linker.
return "";
}
}
std::string toolchains::GenericUnix::getTargetForLinker() const {
return getTriple().str();
}
bool toolchains::GenericUnix::shouldProvideRPathToLinker() const {
return true;
}
ToolChain::InvocationInfo
toolchains::GenericUnix::constructInvocation(const DynamicLinkJobAction &job,
const JobContext &context) const {
assert(context.Output.getPrimaryOutputType() == file_types::TY_Image &&
"Invalid linker output type.");
ArgStringList Arguments;
std::string Target = getTargetForLinker();
if (!Target.empty()) {
Arguments.push_back("-target");
Arguments.push_back(context.Args.MakeArgString(Target));
}
switch (job.getKind()) {
case LinkKind::None:
llvm_unreachable("invalid link kind");
case LinkKind::Executable:
// Default case, nothing extra needed.
break;
case LinkKind::DynamicLibrary:
Arguments.push_back("-shared");
break;
case LinkKind::StaticLibrary:
llvm_unreachable("the dynamic linker cannot build static libraries");
}
// Select the linker to use.
std::string Linker;
if (const Arg *A = context.Args.getLastArg(options::OPT_use_ld)) {
Linker = A->getValue();
} else {
Linker = getDefaultLinker();
}
if (!Linker.empty()) {
#if defined(__HAIKU__)
// For now, passing -fuse-ld on Haiku doesn't work as swiftc doesn't
// recognise it. Passing -use-ld= as the argument works fine.
Arguments.push_back(context.Args.MakeArgString("-use-ld=" + Linker));
#else
Arguments.push_back(context.Args.MakeArgString("-fuse-ld=" + Linker));
#endif
}
// Configure the toolchain.
// By default, use the system clang++ to link.
const char *Clang = "clang++";
if (const Arg *A = context.Args.getLastArg(options::OPT_tools_directory)) {
StringRef toolchainPath(A->getValue());
// If there is a clang in the toolchain folder, use that instead.
if (auto toolchainClang =
llvm::sys::findProgramByName("clang++", {toolchainPath})) {
Clang = context.Args.MakeArgString(toolchainClang.get());
}
// Look for binutils in the toolchain folder.
Arguments.push_back("-B");
Arguments.push_back(context.Args.MakeArgString(A->getValue()));
}
if (getTriple().getOS() == llvm::Triple::Linux &&
job.getKind() == LinkKind::Executable) {
Arguments.push_back("-pie");
}
bool staticExecutable = false;
bool staticStdlib = false;
if (context.Args.hasFlag(options::OPT_static_executable,
options::OPT_no_static_executable, false)) {
staticExecutable = true;
} else if (context.Args.hasFlag(options::OPT_static_stdlib,
options::OPT_no_static_stdlib, false)) {
staticStdlib = true;
}
SmallVector<std::string, 4> RuntimeLibPaths;
getRuntimeLibraryPaths(RuntimeLibPaths, context.Args, context.OI.SDKPath,
/*Shared=*/!(staticExecutable || staticStdlib));
if (!(staticExecutable || staticStdlib) && shouldProvideRPathToLinker()) {
// FIXME: We probably shouldn't be adding an rpath here unless we know
// ahead of time the standard library won't be copied.
for (auto path : RuntimeLibPaths) {
Arguments.push_back("-Xlinker");
Arguments.push_back("-rpath");
Arguments.push_back("-Xlinker");
Arguments.push_back(context.Args.MakeArgString(path));
}
}
SmallString<128> SharedResourceDirPath;
getResourceDirPath(SharedResourceDirPath, context.Args, /*Shared=*/true);
SmallString<128> swiftrtPath = SharedResourceDirPath;
llvm::sys::path::append(swiftrtPath,
swift::getMajorArchitectureName(getTriple()));
llvm::sys::path::append(swiftrtPath, "swiftrt.o");
Arguments.push_back(context.Args.MakeArgString(swiftrtPath));
addPrimaryInputsOfType(Arguments, context.Inputs, context.Args,
file_types::TY_Object);
addInputsOfType(Arguments, context.InputActions, file_types::TY_Object);
for (const Arg *arg :
context.Args.filtered(options::OPT_F, options::OPT_Fsystem)) {
if (arg->getOption().matches(options::OPT_Fsystem))
Arguments.push_back("-iframework");
else
Arguments.push_back(context.Args.MakeArgString(arg->getSpelling()));
Arguments.push_back(arg->getValue());
}
if (!context.OI.SDKPath.empty()) {
Arguments.push_back("--sysroot");
Arguments.push_back(context.Args.MakeArgString(context.OI.SDKPath));
}
// Add any autolinking scripts to the arguments
for (const Job *Cmd : context.Inputs) {
auto &OutputInfo = Cmd->getOutput();
if (OutputInfo.getPrimaryOutputType() == file_types::TY_AutolinkFile)
Arguments.push_back(context.Args.MakeArgString(
Twine("@") + OutputInfo.getPrimaryOutputFilename()));
}
// Add the runtime library link paths.
for (auto path : RuntimeLibPaths) {
Arguments.push_back("-L");
Arguments.push_back(context.Args.MakeArgString(path));
}
// Link the standard library. In two paths, we do this using a .lnk file;
// if we're going that route, we'll set `linkFilePath` to the path to that
// file.
SmallString<128> linkFilePath;
getResourceDirPath(linkFilePath, context.Args, /*Shared=*/false);
if (staticExecutable) {
llvm::sys::path::append(linkFilePath, "static-executable-args.lnk");
} else if (staticStdlib) {
llvm::sys::path::append(linkFilePath, "static-stdlib-args.lnk");
} else {
linkFilePath.clear();
Arguments.push_back("-lswiftCore");
}
if (!linkFilePath.empty()) {
auto linkFile = linkFilePath.str();
if (llvm::sys::fs::is_regular_file(linkFile)) {
Arguments.push_back(context.Args.MakeArgString(Twine("@") + linkFile));
} else {
llvm::report_fatal_error(linkFile + " not found");
}
}
// Explicitly pass the target to the linker
Arguments.push_back(
context.Args.MakeArgString("--target=" + getTriple().str()));
// Delegate to Clang for sanitizers. It will figure out the correct linker
// options.
if (job.getKind() == LinkKind::Executable && context.OI.SelectedSanitizers) {
Arguments.push_back(context.Args.MakeArgString(
"-fsanitize=" + getSanitizerList(context.OI.SelectedSanitizers)));
// The TSan runtime depends on the blocks runtime and libdispatch.
if (context.OI.SelectedSanitizers & SanitizerKind::Thread) {
Arguments.push_back("-lBlocksRuntime");
Arguments.push_back("-ldispatch");
}
}
if (context.Args.hasArg(options::OPT_profile_generate)) {
SmallString<128> LibProfile(SharedResourceDirPath);
llvm::sys::path::remove_filename(LibProfile); // remove platform name
llvm::sys::path::append(LibProfile, "clang", "lib");
llvm::sys::path::append(LibProfile, getTriple().getOSName(),
Twine("libclang_rt.profile-") +
getTriple().getArchName() + ".a");
Arguments.push_back(context.Args.MakeArgString(LibProfile));
Arguments.push_back(context.Args.MakeArgString(
Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
}
// Run clang++ in verbose mode if "-v" is set
if (context.Args.hasArg(options::OPT_v)) {
Arguments.push_back("-v");
}
// These custom arguments should be right before the object file at the end.
context.Args.AddAllArgs(Arguments, options::OPT_linker_option_Group);
context.Args.AddAllArgs(Arguments, options::OPT_Xlinker);
context.Args.AddAllArgValues(Arguments, options::OPT_Xclang_linker);
// This should be the last option, for convenience in checking output.
Arguments.push_back("-o");
Arguments.push_back(
context.Args.MakeArgString(context.Output.getPrimaryOutputFilename()));
InvocationInfo II{Clang, Arguments};
II.allowsResponseFiles = true;
return II;
}
ToolChain::InvocationInfo
toolchains::GenericUnix::constructInvocation(const StaticLinkJobAction &job,
const JobContext &context) const {
assert(context.Output.getPrimaryOutputType() == file_types::TY_Image &&
"Invalid linker output type.");
ArgStringList Arguments;
// Configure the toolchain.
const char *AR = "ar";
Arguments.push_back("crs");
Arguments.push_back(
context.Args.MakeArgString(context.Output.getPrimaryOutputFilename()));
addPrimaryInputsOfType(Arguments, context.Inputs, context.Args,
file_types::TY_Object);
addInputsOfType(Arguments, context.InputActions, file_types::TY_Object);
InvocationInfo II{AR, Arguments};
return II;
}
std::string toolchains::Android::getTargetForLinker() const {
const llvm::Triple &T = getTriple();
if (T.getArch() == llvm::Triple::arm &&
T.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v7)
// Explicitly set the linker target to "androideabi", as opposed to the
// llvm::Triple representation of "armv7-none-linux-android".
return "armv7-none-linux-androideabi";
return T.str();
}
bool toolchains::Android::shouldProvideRPathToLinker() const { return false; }
std::string toolchains::Cygwin::getDefaultLinker() const {
// Cygwin uses the default BFD linker, even on ARM.
return "";
}
std::string toolchains::Cygwin::getTargetForLinker() const { return ""; }
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkUnstructuredGridVolumeMapper.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkUnstructuredGridVolumeMapper.h"
#include "vtkUnstructuredGrid.h"
#include "vtkDataSet.h"
vtkCxxRevisionMacro(vtkUnstructuredGridVolumeMapper, "1.3");
// Construct a vtkUnstructuredGridVolumeMapper with empty scalar input and clipping off.
vtkUnstructuredGridVolumeMapper::vtkUnstructuredGridVolumeMapper()
{
this->BlendMode = vtkUnstructuredGridVolumeMapper::COMPOSITE_BLEND;
}
vtkUnstructuredGridVolumeMapper::~vtkUnstructuredGridVolumeMapper()
{
}
void vtkUnstructuredGridVolumeMapper::SetInput( vtkDataSet *genericInput )
{
vtkUnstructuredGrid *input =
vtkUnstructuredGrid::SafeDownCast( genericInput );
if ( input )
{
this->SetInput( input );
}
else
{
vtkErrorMacro("The SetInput method of this mapper requires vtkImageData as input");
}
}
void vtkUnstructuredGridVolumeMapper::SetInput( vtkUnstructuredGrid *input )
{
this->vtkProcessObject::SetNthInput(0, input);
}
vtkUnstructuredGrid *vtkUnstructuredGridVolumeMapper::GetInput()
{
if (this->NumberOfInputs < 1)
{
return NULL;
}
return (vtkUnstructuredGrid *)this->Inputs[0];
}
// Print the vtkUnstructuredGridVolumeMapper
void vtkUnstructuredGridVolumeMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Blend Mode: " << this->BlendMode << endl;
}
<commit_msg>fixed typo in error macro<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkUnstructuredGridVolumeMapper.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkUnstructuredGridVolumeMapper.h"
#include "vtkUnstructuredGrid.h"
#include "vtkDataSet.h"
vtkCxxRevisionMacro(vtkUnstructuredGridVolumeMapper, "1.4");
// Construct a vtkUnstructuredGridVolumeMapper with empty scalar input and clipping off.
vtkUnstructuredGridVolumeMapper::vtkUnstructuredGridVolumeMapper()
{
this->BlendMode = vtkUnstructuredGridVolumeMapper::COMPOSITE_BLEND;
}
vtkUnstructuredGridVolumeMapper::~vtkUnstructuredGridVolumeMapper()
{
}
void vtkUnstructuredGridVolumeMapper::SetInput( vtkDataSet *genericInput )
{
vtkUnstructuredGrid *input =
vtkUnstructuredGrid::SafeDownCast( genericInput );
if ( input )
{
this->SetInput( input );
}
else
{
vtkErrorMacro("The SetInput method of this mapper requires vtkUnstructuredGrid as input");
}
}
void vtkUnstructuredGridVolumeMapper::SetInput( vtkUnstructuredGrid *input )
{
this->vtkProcessObject::SetNthInput(0, input);
}
vtkUnstructuredGrid *vtkUnstructuredGridVolumeMapper::GetInput()
{
if (this->NumberOfInputs < 1)
{
return NULL;
}
return (vtkUnstructuredGrid *)this->Inputs[0];
}
// Print the vtkUnstructuredGridVolumeMapper
void vtkUnstructuredGridVolumeMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Blend Mode: " << this->BlendMode << endl;
}
<|endoftext|> |
<commit_before>#include <stddef.h>
#include <stdint.h>
#include <chrono>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <Windows.h>
#include <Console\Console.hpp>
#include "Thoth.hpp"
int32_t __stdcall TopLevelExceptionHandler(uint32_t ErrorCode, const EXCEPTION_POINTERS* const ExceptionInfo);
uint32_t __stdcall ThothThread(void*)
{
__try
{
std::chrono::high_resolution_clock::time_point PrevTime, CurTime;
CurTime = std::chrono::high_resolution_clock::now();
while( true )
{
PrevTime = CurTime;
CurTime = std::chrono::high_resolution_clock::now();
Thoth::Instance().Tick(
(CurTime - PrevTime)
);
}
}
__except( TopLevelExceptionHandler(GetExceptionCode(), GetExceptionInformation()) )
{
}
return 0;
}
int32_t __stdcall DllMain(HINSTANCE hDLL, uint32_t Reason, void* Reserved)
{
switch( Reason )
{
case DLL_PROCESS_ATTACH:
{
if( !DisableThreadLibraryCalls(hDLL) )
{
MessageBox(nullptr, "Unable to disable thread library calls", "Thoth", MB_OK);
return false;
}
Console::AllocateConsole("Thoth");
CreateThread(nullptr,
0,
reinterpret_cast<DWORD(__stdcall*)(void*)>(&ThothThread),
nullptr,
0,
nullptr);
}
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
default:
{
return true;
}
}
return false;
}
int32_t __stdcall TopLevelExceptionHandler(uint32_t ErrorCode, const EXCEPTION_POINTERS* const ExceptionInfo)
{
std::cout << std::endl << "Exception: [0x" << std::uppercase << std::hex << ExceptionInfo->ExceptionRecord->ExceptionCode << ']';
std::stringstream ErrorMessage;
ErrorMessage << std::hex << std::setfill('0');
switch( ErrorCode )
{
default:
{
ErrorMessage << "Unknown";
break;
}
case EXCEPTION_ACCESS_VIOLATION:
{
ErrorMessage << "EXCEPTION_ACCESS_VIOLATION [";
const char* const MemOperation[2] = { "Reading","Writing" };
ErrorMessage << MemOperation[ExceptionInfo->ExceptionRecord->ExceptionInformation[0] & 1];
ErrorMessage << " to 0x"
<< std::uppercase << std::setw(sizeof(uintptr_t) << 1)
<< ExceptionInfo->ExceptionRecord->ExceptionInformation[1] << ']';
break;
}
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
{
ErrorMessage << "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
break;
}
case EXCEPTION_BREAKPOINT:
{
ErrorMessage << "EXCEPTION_BREAKPOINT";
break;
}
case EXCEPTION_DATATYPE_MISALIGNMENT:
{
ErrorMessage << "EXCEPTION_DATATYPE_MISALIGNMENT";
break;
}
case EXCEPTION_FLT_DENORMAL_OPERAND:
{
ErrorMessage << "EXCEPTION_FLT_DENORMAL_OPERAND";
break;
}
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
{
ErrorMessage << "EXCEPTION_FLT_DIVIDE_BY_ZERO";
break;
}
case EXCEPTION_FLT_INEXACT_RESULT:
{
ErrorMessage << "EXCEPTION_FLT_INEXACT_RESULT";
break;
}
case EXCEPTION_FLT_INVALID_OPERATION:
{
ErrorMessage << "EXCEPTION_FLT_INVALID_OPERATION";
break;
}
case EXCEPTION_FLT_OVERFLOW:
{
ErrorMessage << "EXCEPTION_FLT_OVERFLOW";
break;
}
case EXCEPTION_FLT_STACK_CHECK:
{
ErrorMessage << "EXCEPTION_FLT_STACK_CHECK";
break;
}
case EXCEPTION_FLT_UNDERFLOW:
{
ErrorMessage << "EXCEPTION_FLT_UNDERFLOW";
break;
}
case EXCEPTION_ILLEGAL_INSTRUCTION:
{
ErrorMessage << "EXCEPTION_ILLEGAL_INSTRUCTION";
break;
}
case EXCEPTION_IN_PAGE_ERROR:
{
ErrorMessage << "EXCEPTION_IN_PAGE_ERROR";
break;
}
case EXCEPTION_INT_DIVIDE_BY_ZERO:
{
ErrorMessage << "EXCEPTION_INT_DIVIDE_BY_ZERO";
break;
}
case EXCEPTION_INT_OVERFLOW:
{
ErrorMessage << "EXCEPTION_INT_OVERFLOW";
break;
}
case EXCEPTION_INVALID_DISPOSITION:
{
ErrorMessage << "EXCEPTION_INVALID_DISPOSITION";
break;
}
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
{
ErrorMessage << "EXCEPTION_NONCONTINUABLE_EXCEPTION";
break;
}
case EXCEPTION_PRIV_INSTRUCTION:
{
ErrorMessage << "EXCEPTION_PRIV_INSTRUCTION";
break;
}
case EXCEPTION_SINGLE_STEP:
{
ErrorMessage << "EXCEPTION_SINGLE_STEP";
break;
}
case EXCEPTION_STACK_OVERFLOW:
{
ErrorMessage << "EXCEPTION_STACK_OVERFLOW";
break;
}
}
// Format exception string
std::cout << std::nouppercase << " - " << ErrorMessage.str() << std::endl;
return EXCEPTION_CONTINUE_SEARCH;
}<commit_msg>Changed Main thread to use top-level exception handling<commit_after>#include <stddef.h>
#include <stdint.h>
#include <chrono>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <functional>
#include <Windows.h>
#include <Console\Console.hpp>
#include "Thoth.hpp"
int32_t __stdcall StructuredExceptionPrinter(
uint32_t ErrorCode,
const EXCEPTION_POINTERS* const ExceptionInfo
);
uint32_t __stdcall ThothThread(void*)
{
__try
{
[]()
{
Console::AllocateConsole("Thoth");
std::chrono::high_resolution_clock::time_point PrevTime, CurTime;
CurTime = std::chrono::high_resolution_clock::now();
while( true )
{
PrevTime = CurTime;
CurTime = std::chrono::high_resolution_clock::now();
Thoth::Instance()->Tick(
(CurTime - PrevTime)
);
}
}();
}
__except( StructuredExceptionPrinter(GetExceptionCode(), GetExceptionInformation()) )
{
}
return 0;
}
int32_t __stdcall DllMain(HINSTANCE hDLL, uint32_t Reason, void *Reserved)
{
switch( Reason )
{
case DLL_PROCESS_ATTACH:
{
if( !DisableThreadLibraryCalls(hDLL) )
{
MessageBox(nullptr, "Unable to disable thread library calls", "Thoth", MB_OK);
return false;
}
CreateThread(
nullptr,
0,
reinterpret_cast<unsigned long(__stdcall*)(void*)>(&ThothThread),
nullptr,
0,
nullptr);
}
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
default:
{
return true;
}
}
return false;
}
int32_t __stdcall StructuredExceptionPrinter(uint32_t ErrorCode, const EXCEPTION_POINTERS* const ExceptionInfo)
{
std::cout << std::endl << "Exception: [0x" << std::uppercase << std::hex << ExceptionInfo->ExceptionRecord->ExceptionCode << ']';
std::stringstream ErrorMessage;
ErrorMessage << std::hex << std::setfill('0');
switch( ErrorCode )
{
default:
{
ErrorMessage << "Unknown";
break;
}
case EXCEPTION_ACCESS_VIOLATION:
{
ErrorMessage << "EXCEPTION_ACCESS_VIOLATION [";
const char* const MemOperation[2] = { "Reading","Writing" };
ErrorMessage << MemOperation[ExceptionInfo->ExceptionRecord->ExceptionInformation[0] & 1];
ErrorMessage << " to 0x"
<< std::uppercase << std::setw(sizeof(uintptr_t) << 1)
<< ExceptionInfo->ExceptionRecord->ExceptionInformation[1] << ']';
break;
}
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
{
ErrorMessage << "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
break;
}
case EXCEPTION_BREAKPOINT:
{
ErrorMessage << "EXCEPTION_BREAKPOINT";
break;
}
case EXCEPTION_DATATYPE_MISALIGNMENT:
{
ErrorMessage << "EXCEPTION_DATATYPE_MISALIGNMENT";
break;
}
case EXCEPTION_FLT_DENORMAL_OPERAND:
{
ErrorMessage << "EXCEPTION_FLT_DENORMAL_OPERAND";
break;
}
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
{
ErrorMessage << "EXCEPTION_FLT_DIVIDE_BY_ZERO";
break;
}
case EXCEPTION_FLT_INEXACT_RESULT:
{
ErrorMessage << "EXCEPTION_FLT_INEXACT_RESULT";
break;
}
case EXCEPTION_FLT_INVALID_OPERATION:
{
ErrorMessage << "EXCEPTION_FLT_INVALID_OPERATION";
break;
}
case EXCEPTION_FLT_OVERFLOW:
{
ErrorMessage << "EXCEPTION_FLT_OVERFLOW";
break;
}
case EXCEPTION_FLT_STACK_CHECK:
{
ErrorMessage << "EXCEPTION_FLT_STACK_CHECK";
break;
}
case EXCEPTION_FLT_UNDERFLOW:
{
ErrorMessage << "EXCEPTION_FLT_UNDERFLOW";
break;
}
case EXCEPTION_ILLEGAL_INSTRUCTION:
{
ErrorMessage << "EXCEPTION_ILLEGAL_INSTRUCTION";
break;
}
case EXCEPTION_IN_PAGE_ERROR:
{
ErrorMessage << "EXCEPTION_IN_PAGE_ERROR";
break;
}
case EXCEPTION_INT_DIVIDE_BY_ZERO:
{
ErrorMessage << "EXCEPTION_INT_DIVIDE_BY_ZERO";
break;
}
case EXCEPTION_INT_OVERFLOW:
{
ErrorMessage << "EXCEPTION_INT_OVERFLOW";
break;
}
case EXCEPTION_INVALID_DISPOSITION:
{
ErrorMessage << "EXCEPTION_INVALID_DISPOSITION";
break;
}
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
{
ErrorMessage << "EXCEPTION_NONCONTINUABLE_EXCEPTION";
break;
}
case EXCEPTION_PRIV_INSTRUCTION:
{
ErrorMessage << "EXCEPTION_PRIV_INSTRUCTION";
break;
}
case EXCEPTION_SINGLE_STEP:
{
ErrorMessage << "EXCEPTION_SINGLE_STEP";
break;
}
case EXCEPTION_STACK_OVERFLOW:
{
ErrorMessage << "EXCEPTION_STACK_OVERFLOW";
break;
}
}
// Format exception string
std::cout << std::nouppercase << " - " << ErrorMessage.str() << std::endl;
return EXCEPTION_CONTINUE_SEARCH;
}<|endoftext|> |
<commit_before>#include "BoundaryConditions.h"
// to avoid compiler confusion, python.hpp must be include before Halide headers
#include <boost/python.hpp>
#include "../../src/Lambda.h" // needed by BoundaryConditions.h
#include "../../src/ImageParam.h"
#include "../../src/BoundaryConditions.h"
#include "../../src/Func.h"
#include <string>
namespace h = Halide;
namespace hb = Halide::BoundaryConditions;
namespace p = boost::python;
namespace {
template<typename T>
h::Func constant_exterior0(T func_like, h::Expr value)
{
return hb::constant_exterior(func_like, value);
}
// C++ fun, variadic template recursive function !
template<typename T=void, typename ...Types>
void def_constant_exterior_for_image()
{
p::def("constant_exterior", &constant_exterior0<h::Image<T>>, p::args("source", "value"));
def_constant_exterior_for_image<Types...>(); // recursive call
return;
}
template<>
void def_constant_exterior_for_image<void>()
{ // end of recursion
return;
}
} // end of anonymous namespace
namespace {
template<typename T>
h::Func repeat_edge0(T func_like)
{
return hb::repeat_edge(func_like);
}
// C++ fun, variadic template recursive function !
template<typename T=void, typename ...Types>
void def_repeat_edge_for_image()
{
p::def("repeat_edge", &repeat_edge0<h::Image<T>>, p::args("source"));
def_repeat_edge_for_image<Types...>(); // recursive call
return;
}
template<>
void def_repeat_edge_for_image<void>()
{ // end of recursion
return;
}
} // end of anonymous namespace
namespace {
template<typename T>
h::Func repeat_image0(T func_like)
{
return hb::repeat_image(func_like);
}
// C++ fun, variadic template recursive function !
template<typename T=void, typename ...Types>
void def_repeat_image_for_image()
{
p::def("repeat_image", &repeat_image0<h::Image<T>>, p::args("source"));
def_repeat_image_for_image<Types...>(); // recursive call
return;
}
template<>
void def_repeat_image_for_image<void>()
{ // end of recursion
return;
}
} // end of anonymous namespace
namespace {
template<typename T>
h::Func mirror_image0(T func_like)
{
return hb::mirror_image(func_like);
}
// C++ fun, variadic template recursive function !
template<typename T=void, typename ...Types>
void def_mirror_image_for_image()
{
p::def("mirror_image", &mirror_image0<h::Image<T>>, p::args("source"));
def_mirror_image_for_image<Types...>(); // recursive call
return;
}
template<>
void def_mirror_image_for_image<void>()
{ // end of recursion
return;
}
} // end of anonymous namespace
namespace {
template<typename T>
h::Func mirror_interior0(T func_like)
{
return hb::mirror_interior(func_like);
}
// C++ fun, variadic template recursive function !
template<typename T=void, typename ...Types>
void def_mirror_interior_for_image()
{
p::def("mirror_interior", &mirror_interior0<h::Image<T>>, p::args("source"));
def_mirror_interior_for_image<Types...>(); // recursive call
return;
}
template<>
void def_mirror_interior_for_image<void>()
{ // end of recursion
return;
}
} // end of anonymous namespace
void defineBoundaryConditions()
{
// Other variants of constant_exterior exist, but not yet implemented
p::def("constant_exterior", &constant_exterior0<h::ImageParam>, p::args("source", "value"),
"Impose a boundary condition such that a given expression is returned "
"everywhere outside the boundary. Generally the expression will be a "
"constant, though the code currently allows accessing the arguments "
"of source.\n\n"
"An ImageParam, Image<T>, or similar can be passed instead of a Func. If this "
"is done and no bounds are given, the boundaries will be taken from the "
"min and extent methods of the passed object.\n\n"
"(This is similar to setting GL_TEXTURE_WRAP_* to GL_CLAMP_TO_BORDER "
" and putting value in the border of the texture.) ");
def_constant_exterior_for_image<
boost::uint8_t, boost::uint16_t, boost::uint32_t,
boost::int8_t, boost::int16_t, boost::int32_t,
float, double >();
// The following variant is not yet implemented
// EXPORT Func constant_exterior(const Func &source, Expr value,
// const std::vector<std::pair<Expr, Expr>> &bounds);
p::def("repeat_edge", &repeat_edge0<h::ImageParam>, p::args("source"),
"Impose a boundary condition such that the nearest edge sample is returned "
"everywhere outside the given region.\n\n"
"An ImageParam, Image<T>, or similar can be passed instead of a Func. If this "
"is done and no bounds are given, the boundaries will be taken from the "
"min and extent methods of the passed object.\n\n"
"(This is similar to setting GL_TEXTURE_WRAP_* to GL_CLAMP_TO_EDGE.)");
def_repeat_edge_for_image<
boost::uint8_t, boost::uint16_t, boost::uint32_t,
boost::int8_t, boost::int16_t, boost::int32_t,
float, double >();
// The following variant is not yet implemented
// EXPORT Func repeat_edge(const Func &source,
// const std::vector<std::pair<Expr, Expr>> &bounds);
p::def("repeat_image", &repeat_image0<h::ImageParam>, p::args("source"),
"Impose a boundary condition such that the entire coordinate space is "
"tiled with copies of the image abutted against each other.\n\n"
"An ImageParam, Image<T>, or similar can be passed instead of a Func. If this "
"is done and no bounds are given, the boundaries will be taken from the "
"min and extent methods of the passed object.\n\n"
"(This is similar to setting GL_TEXTURE_WRAP_* to GL_REPEAT.)");
def_repeat_image_for_image<
boost::uint8_t, boost::uint16_t, boost::uint32_t,
boost::int8_t, boost::int16_t, boost::int32_t,
float, double >();
//The following variant is not yet implemented
// EXPORT Func repeat_image(const Func &source,
// const std::vector<std::pair<Expr, Expr>> &bounds);
p::def("mirror_image", &mirror_image0<h::ImageParam>, p::args("source"),
"Impose a boundary condition such that the entire coordinate space is "
"tiled with copies of the image abutted against each other, but mirror "
"them such that adjacent edges are the same.\n\n"
"An ImageParam, Image<T>, or similar can be passed instead of a Func. If this "
"is done and no bounds are given, the boundaries will be taken from the "
"min and extent methods of the passed object.\n\n"
"(This is similar to setting GL_TEXTURE_WRAP_* to GL_MIRRORED_REPEAT.)");
def_mirror_image_for_image<
boost::uint8_t, boost::uint16_t, boost::uint32_t,
boost::int8_t, boost::int16_t, boost::int32_t,
float, double >();
// The following variant is not yet implemented
// EXPORT Func mirror_image(const Func &source,
// const std::vector<std::pair<Expr, Expr>> &bounds);
p::def("mirror_interior", &mirror_interior0<h::ImageParam>, p::args("source"),
"Impose a boundary condition such that the entire coordinate space is "
"tiled with copies of the image abutted against each other, but mirror "
"them such that adjacent edges are the same and then overlap the edges.\n\n"
"This produces an error if any extent is 1 or less. (TODO: check this.)\n\n"
"An ImageParam, Image<T>, or similar can be passed instead of a Func. If this "
"is done and no bounds are given, the boundaries will be taken from the "
"min and extent methods of the passed object. "
"(I do not believe there is a direct GL_TEXTURE_WRAP_* equivalent for this.)");
def_mirror_interior_for_image<
boost::uint8_t, boost::uint16_t, boost::uint32_t,
boost::int8_t, boost::int16_t, boost::int32_t,
float, double >();
// The following variant is not yet implemented
// EXPORT Func mirror_interior(const Func &source,
// const std::vector<std::pair<Expr, Expr>> &bounds);
return;
}
<commit_msg>Python: Added more boundary condition functions<commit_after>#include "BoundaryConditions.h"
// to avoid compiler confusion, python.hpp must be include before Halide headers
#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>
#include "../../src/Lambda.h" // needed by BoundaryConditions.h
#include "../../src/ImageParam.h"
#include "../../src/BoundaryConditions.h"
#include "../../src/Func.h"
#include <string>
#include <vector>
#include <algorithm>
namespace h = Halide;
namespace hb = Halide::BoundaryConditions;
namespace p = boost::python;
template<typename T, typename S> inline std::pair<T, S> to_pair(const p::object& iterable)
{
return std::pair<T, S>(p::extract<T>(iterable[0]), p::extract<T>(iterable[1]));
}
template<typename T> inline std::vector<T> to_vector(const p::object& iterable)
{
return std::vector<T>(p::stl_input_iterator<T>(iterable), p::stl_input_iterator<T>());
}
std::vector<std::pair<h::Expr, h::Expr>> inline pyobject_to_bounds(const p::object& pybounds)
{
std::vector<p::object> intermediate = to_vector<p::object>(pybounds);
std::vector<std::pair<h::Expr, h::Expr>> result(intermediate.size());
std::transform(intermediate.begin(), intermediate.end(), result.begin(), to_pair<h::Expr, h::Expr>);
return result;
}
namespace {
template<typename T>
h::Func constant_exterior0(T func_like, h::Expr value)
{
return hb::constant_exterior(func_like, value);
}
h::Func constant_exterior_bounds(h::Func func, h::Expr value, p::object bounds_)
{
return hb::constant_exterior(func, value, pyobject_to_bounds(bounds_));
}
// C++ fun, variadic template recursive function !
template<typename T=void, typename ...Types>
void def_constant_exterior_for_image()
{
p::def("constant_exterior", &constant_exterior0<h::Image<T>>, p::args("source", "value"));
def_constant_exterior_for_image<Types...>(); // recursive call
return;
}
template<>
void def_constant_exterior_for_image<void>()
{ // end of recursion
return;
}
} // end of anonymous namespace
namespace {
template<typename T>
h::Func repeat_edge0(T func_like)
{
return hb::repeat_edge(func_like);
}
h::Func repeat_edge_bounds(h::Func func, p::object bounds_)
{
return hb::repeat_edge(func, pyobject_to_bounds(bounds_));
}
// C++ fun, variadic template recursive function !
template<typename T=void, typename ...Types>
void def_repeat_edge_for_image()
{
p::def("repeat_edge", &repeat_edge0<h::Image<T>>, p::args("source"));
def_repeat_edge_for_image<Types...>(); // recursive call
return;
}
template<>
void def_repeat_edge_for_image<void>()
{ // end of recursion
return;
}
} // end of anonymous namespace
namespace {
template<typename T>
h::Func repeat_image0(T func_like)
{
return hb::repeat_image(func_like);
}
h::Func repeat_image_bounds(h::Func func, p::object bounds_)
{
return hb::repeat_image(func, pyobject_to_bounds(bounds_));
}
// C++ fun, variadic template recursive function !
template<typename T=void, typename ...Types>
void def_repeat_image_for_image()
{
p::def("repeat_image", &repeat_image0<h::Image<T>>, p::args("source"));
def_repeat_image_for_image<Types...>(); // recursive call
return;
}
template<>
void def_repeat_image_for_image<void>()
{ // end of recursion
return;
}
} // end of anonymous namespace
namespace {
template<typename T>
h::Func mirror_image0(T func_like)
{
return hb::mirror_image(func_like);
}
h::Func mirror_image_bounds(h::Func func, p::object bounds_)
{
return hb::mirror_image(func, pyobject_to_bounds(bounds_));
}
// C++ fun, variadic template recursive function !
template<typename T=void, typename ...Types>
void def_mirror_image_for_image()
{
p::def("mirror_image", &mirror_image0<h::Image<T>>, p::args("source"));
def_mirror_image_for_image<Types...>(); // recursive call
return;
}
template<>
void def_mirror_image_for_image<void>()
{ // end of recursion
return;
}
} // end of anonymous namespace
namespace {
template<typename T>
h::Func mirror_interior0(T func_like)
{
return hb::mirror_interior(func_like);
}
h::Func mirror_interior_bounds(h::Func func, p::object bounds_)
{
return hb::mirror_interior(func, pyobject_to_bounds(bounds_));
}
// C++ fun, variadic template recursive function !
template<typename T=void, typename ...Types>
void def_mirror_interior_for_image()
{
p::def("mirror_interior", &mirror_interior0<h::Image<T>>, p::args("source"));
def_mirror_interior_for_image<Types...>(); // recursive call
return;
}
template<>
void def_mirror_interior_for_image<void>()
{ // end of recursion
return;
}
} // end of anonymous namespace
void defineBoundaryConditions()
{
// constant_exterior
p::def("constant_exterior", &constant_exterior0<h::ImageParam>, p::args("source", "value"),
"Impose a boundary condition such that a given expression is returned "
"everywhere outside the boundary. Generally the expression will be a "
"constant, though the code currently allows accessing the arguments "
"of source.\n\n"
"An ImageParam, Image<T>, or similar can be passed instead of a Func. If this "
"is done and no bounds are given, the boundaries will be taken from the "
"min and extent methods of the passed object.\n\n"
"(This is similar to setting GL_TEXTURE_WRAP_* to GL_CLAMP_TO_BORDER "
" and putting value in the border of the texture.) ");
def_constant_exterior_for_image<
boost::uint8_t, boost::uint16_t, boost::uint32_t,
boost::int8_t, boost::int16_t, boost::int32_t,
float, double >();
p::def("constant_exterior", &constant_exterior_bounds, p::args("source", "value", "bounds"));
// repeat_edge
p::def("repeat_edge", &repeat_edge0<h::ImageParam>, p::args("source"),
"Impose a boundary condition such that the nearest edge sample is returned "
"everywhere outside the given region.\n\n"
"An ImageParam, Image<T>, or similar can be passed instead of a Func. If this "
"is done and no bounds are given, the boundaries will be taken from the "
"min and extent methods of the passed object.\n\n"
"(This is similar to setting GL_TEXTURE_WRAP_* to GL_CLAMP_TO_EDGE.)");
def_repeat_edge_for_image<
boost::uint8_t, boost::uint16_t, boost::uint32_t,
boost::int8_t, boost::int16_t, boost::int32_t,
float, double >();
p::def("repeat_edge", &repeat_edge_bounds, p::args("source", "bounds"));
// repeat_image
p::def("repeat_image", &repeat_image0<h::ImageParam>, p::args("source"),
"Impose a boundary condition such that the entire coordinate space is "
"tiled with copies of the image abutted against each other.\n\n"
"An ImageParam, Image<T>, or similar can be passed instead of a Func. If this "
"is done and no bounds are given, the boundaries will be taken from the "
"min and extent methods of the passed object.\n\n"
"(This is similar to setting GL_TEXTURE_WRAP_* to GL_REPEAT.)");
def_repeat_image_for_image<
boost::uint8_t, boost::uint16_t, boost::uint32_t,
boost::int8_t, boost::int16_t, boost::int32_t,
float, double >();
p::def("repeat_image", &repeat_image_bounds, p::args("source", "bounds"));
// mirror_image
p::def("mirror_image", &mirror_image0<h::ImageParam>, p::args("source"),
"Impose a boundary condition such that the entire coordinate space is "
"tiled with copies of the image abutted against each other, but mirror "
"them such that adjacent edges are the same.\n\n"
"An ImageParam, Image<T>, or similar can be passed instead of a Func. If this "
"is done and no bounds are given, the boundaries will be taken from the "
"min and extent methods of the passed object.\n\n"
"(This is similar to setting GL_TEXTURE_WRAP_* to GL_MIRRORED_REPEAT.)");
def_mirror_image_for_image<
boost::uint8_t, boost::uint16_t, boost::uint32_t,
boost::int8_t, boost::int16_t, boost::int32_t,
float, double >();
p::def("mirror_image", &mirror_image_bounds, p::args("source", "bounds"));
// mirror_interior
p::def("mirror_interior", &mirror_interior0<h::ImageParam>, p::args("source"),
"Impose a boundary condition such that the entire coordinate space is "
"tiled with copies of the image abutted against each other, but mirror "
"them such that adjacent edges are the same and then overlap the edges.\n\n"
"This produces an error if any extent is 1 or less. (TODO: check this.)\n\n"
"An ImageParam, Image<T>, or similar can be passed instead of a Func. If this "
"is done and no bounds are given, the boundaries will be taken from the "
"min and extent methods of the passed object. "
"(I do not believe there is a direct GL_TEXTURE_WRAP_* equivalent for this.)");
def_mirror_interior_for_image<
boost::uint8_t, boost::uint16_t, boost::uint32_t,
boost::int8_t, boost::int16_t, boost::int32_t,
float, double >();
p::def("mirror_interior", &mirror_interior_bounds, p::args("source", "bounds"));
return;
}
<|endoftext|> |
<commit_before><commit_msg>Mark nacl_ui_tests as flaky on Mac TEST=none BUG=none<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: utility.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2003-03-19 16:19:10 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_UTILITY_HXX_
#define CONFIGMGR_UTILITY_HXX_
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#include <salhelper/simplereferenceobject.hxx>
#endif
#define CFG_NOTHROW() SAL_THROW( () )
#define CFG_THROW1( Ex1 ) SAL_THROW( (Ex1) )
#define CFG_THROW2( Ex1,Ex2 ) SAL_THROW( (Ex1,Ex2) )
#define CFG_THROW3( Ex1,Ex2,Ex3 ) SAL_THROW( (Ex1,Ex2,Ex3) )
#define CFG_THROW4( Ex1,Ex2,Ex3,Ex4 ) SAL_THROW( (Ex1,Ex2,Ex3,Ex4) )
#define CFG_THROW5( Ex1,Ex2,Ex3,Ex4,Ex5 ) SAL_THROW( (Ex1,Ex2,Ex3,Ex4,Ex5) )
#define CFG_THROW6( Ex1,Ex2,Ex3,Ex4,Ex5,Ex6 ) SAL_THROW( (Ex1,Ex2,Ex3,Ex4,Ex5,Ex6) )
#define CFG_UNO_THROW1( Ex1 ) \
SAL_THROW( (::com::sun::star::Ex1, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW2( Ex1,Ex2 ) \
SAL_THROW( (::com::sun::star::Ex1, ::com::sun::star::Ex2, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW3( Ex1,Ex2,Ex3 ) \
SAL_THROW( (::com::sun::star::Ex1, ::com::sun::star::Ex2, ::com::sun::star::Ex3, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW4( Ex1,Ex2,Ex3,Ex4 ) \
SAL_THROW( (::com::sun::star::Ex1, ::com::sun::star::Ex2, ::com::sun::star::Ex3, \
::com::sun::star::Ex4, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW5( Ex1,Ex2,Ex3,Ex4,Ex5 ) \
SAL_THROW( (::com::sun::star::Ex1, ::com::sun::star::Ex2, ::com::sun::star::Ex3, \
::com::sun::star::Ex4, ::com::sun::star::Ex5, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW6( Ex1,Ex2,Ex3,Ex4,Ex5,Ex6 ) \
SAL_THROW( (::com::sun::star::Ex1, ::com::sun::star::Ex2, ::com::sun::star::Ex3, \
::com::sun::star::Ex4, ::com::sun::star::Ex5, ::com::sun::star::Ex6, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW_ALL( ) CFG_UNO_THROW1(uno::Exception)
#define CFG_UNO_THROW_RTE( ) CFG_UNO_THROW1(uno::RuntimeException)
namespace configmgr
{
class Noncopyable
{
protected:
Noncopyable() {}
~Noncopyable() {}
private:
Noncopyable (Noncopyable& notImplemented);
void operator= (Noncopyable& notImplemented);
};
struct Refcounted
: virtual salhelper::SimpleReferenceObject
{
};
}
#endif // CONFIGMGR_UTILITY_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.194); FILE MERGED 2005/09/05 17:04:42 rt 1.5.194.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: utility.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 04:01:52 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONFIGMGR_UTILITY_HXX_
#define CONFIGMGR_UTILITY_HXX_
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#include <salhelper/simplereferenceobject.hxx>
#endif
#define CFG_NOTHROW() SAL_THROW( () )
#define CFG_THROW1( Ex1 ) SAL_THROW( (Ex1) )
#define CFG_THROW2( Ex1,Ex2 ) SAL_THROW( (Ex1,Ex2) )
#define CFG_THROW3( Ex1,Ex2,Ex3 ) SAL_THROW( (Ex1,Ex2,Ex3) )
#define CFG_THROW4( Ex1,Ex2,Ex3,Ex4 ) SAL_THROW( (Ex1,Ex2,Ex3,Ex4) )
#define CFG_THROW5( Ex1,Ex2,Ex3,Ex4,Ex5 ) SAL_THROW( (Ex1,Ex2,Ex3,Ex4,Ex5) )
#define CFG_THROW6( Ex1,Ex2,Ex3,Ex4,Ex5,Ex6 ) SAL_THROW( (Ex1,Ex2,Ex3,Ex4,Ex5,Ex6) )
#define CFG_UNO_THROW1( Ex1 ) \
SAL_THROW( (::com::sun::star::Ex1, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW2( Ex1,Ex2 ) \
SAL_THROW( (::com::sun::star::Ex1, ::com::sun::star::Ex2, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW3( Ex1,Ex2,Ex3 ) \
SAL_THROW( (::com::sun::star::Ex1, ::com::sun::star::Ex2, ::com::sun::star::Ex3, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW4( Ex1,Ex2,Ex3,Ex4 ) \
SAL_THROW( (::com::sun::star::Ex1, ::com::sun::star::Ex2, ::com::sun::star::Ex3, \
::com::sun::star::Ex4, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW5( Ex1,Ex2,Ex3,Ex4,Ex5 ) \
SAL_THROW( (::com::sun::star::Ex1, ::com::sun::star::Ex2, ::com::sun::star::Ex3, \
::com::sun::star::Ex4, ::com::sun::star::Ex5, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW6( Ex1,Ex2,Ex3,Ex4,Ex5,Ex6 ) \
SAL_THROW( (::com::sun::star::Ex1, ::com::sun::star::Ex2, ::com::sun::star::Ex3, \
::com::sun::star::Ex4, ::com::sun::star::Ex5, ::com::sun::star::Ex6, \
::com::sun::star::uno::RuntimeException) )
#define CFG_UNO_THROW_ALL( ) CFG_UNO_THROW1(uno::Exception)
#define CFG_UNO_THROW_RTE( ) CFG_UNO_THROW1(uno::RuntimeException)
namespace configmgr
{
class Noncopyable
{
protected:
Noncopyable() {}
~Noncopyable() {}
private:
Noncopyable (Noncopyable& notImplemented);
void operator= (Noncopyable& notImplemented);
};
struct Refcounted
: virtual salhelper::SimpleReferenceObject
{
};
}
#endif // CONFIGMGR_UTILITY_HXX_
<|endoftext|> |
<commit_before>#ifndef BULL_RENDER_TARGET_RENDERTARGET_HPP
#define BULL_RENDER_TARGET_RENDERTARGET_HPP
#include <memory>
#include <Bull/Core/Configuration/Integer.hpp>
#include <Bull/Core/Pattern/NonCopyable.hpp>
#include <Bull/Math/Vector/Vector2.hpp>
#include <Bull/Render/Context/ContextResource.hpp>
#include <Bull/Render/Context/ContextSettings.hpp>
#include <Bull/Render/Target/Viewport.hpp>
#include <Bull/Core/Utility/Color.hpp>
#include <Bull/Core/Window/VideoMode.hpp>
namespace Bull
{
namespace prv
{
class GlContext;
}
class BULL_RENDER_API RenderTarget : public ContextResource, public NonCopyable
{
public:
/*! \brief Destructor
*
*/
virtual ~RenderTarget();
/*! \brief Clear the RenderTarget with the specified color
*
* \param red The red component of the color
* \param green The green component of the color
* \param blue The blue component of the color
* \param alpha The alpha component of the color
*
*/
void clear(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha = 255);
/*! \brief Clear the RenderTarget with the specified color
*
* \param color The color to use
*
*/
void clear(const Color& color = Color::Black);
/*! \brief Activate or deactivate the context
*
* \param active True to activate, false to deactivate the context
*
* \return Return true if the context's status changed successfully, false otherwise
*
*/
bool setActive(bool active = true);
/*! \brief Change the viewport of the RenderTarget
*
* \param viewport The viewport
*
*/
void setViewport(const Viewport& viewport);
/*! \brief Get the current viewport of the RenderTarget
*
* \return Return the viewport
*
*/
const Viewport& getViewport() const;
/*! \brief Get the default viewport of the RenderTarget
*
* \return Return the viewport
*
*/
virtual Viewport getDefaultViewport() const = 0;
/*! \brief Reset the viewport by the default one
*
*/
void resetViewport();
/*! \brief Display what have been rendered so far
*
*/
virtual void display() = 0;
/*! \brief Get the ContextSettings of the context
*
* \return Return the ContextSettings
*
*/
const ContextSettings& getSettings() const;
protected:
/*! \brief Default constructor
*
*/
RenderTarget() = default;
std::unique_ptr<prv::GlContext> m_context;
private:
Viewport m_currentViewport;
};
}
#endif // BULL_RENDER_TARGET_RENDERTARGET_HPP
<commit_msg>[Render/RenderTarget]Move headers<commit_after>#ifndef BULL_RENDER_TARGET_RENDERTARGET_HPP
#define BULL_RENDER_TARGET_RENDERTARGET_HPP
#include <memory>
#include <Bull/Core/Configuration/Integer.hpp>
#include <Bull/Core/Pattern/NonCopyable.hpp>
#include <Bull/Core/Utility/Color.hpp>
#include <Bull/Core/Window/VideoMode.hpp>
#include <Bull/Math/Vector/Vector2.hpp>
#include <Bull/Render/Context/ContextResource.hpp>
#include <Bull/Render/Context/ContextSettings.hpp>
#include <Bull/Render/Target/Viewport.hpp>
namespace Bull
{
namespace prv
{
class GlContext;
}
class BULL_RENDER_API RenderTarget : public ContextResource, public NonCopyable
{
public:
/*! \brief Destructor
*
*/
virtual ~RenderTarget();
/*! \brief Clear the RenderTarget with the specified color
*
* \param red The red component of the color
* \param green The green component of the color
* \param blue The blue component of the color
* \param alpha The alpha component of the color
*
*/
void clear(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha = 255);
/*! \brief Clear the RenderTarget with the specified color
*
* \param color The color to use
*
*/
void clear(const Color& color = Color::Black);
/*! \brief Activate or deactivate the context
*
* \param active True to activate, false to deactivate the context
*
* \return Return true if the context's status changed successfully, false otherwise
*
*/
bool setActive(bool active = true);
/*! \brief Change the viewport of the RenderTarget
*
* \param viewport The viewport
*
*/
void setViewport(const Viewport& viewport);
/*! \brief Get the current viewport of the RenderTarget
*
* \return Return the viewport
*
*/
const Viewport& getViewport() const;
/*! \brief Get the default viewport of the RenderTarget
*
* \return Return the viewport
*
*/
virtual Viewport getDefaultViewport() const = 0;
/*! \brief Reset the viewport by the default one
*
*/
void resetViewport();
/*! \brief Display what have been rendered so far
*
*/
virtual void display() = 0;
/*! \brief Get the ContextSettings of the context
*
* \return Return the ContextSettings
*
*/
const ContextSettings& getSettings() const;
protected:
/*! \brief Default constructor
*
*/
RenderTarget() = default;
std::unique_ptr<prv::GlContext> m_context;
private:
Viewport m_currentViewport;
};
}
#endif // BULL_RENDER_TARGET_RENDERTARGET_HPP
<|endoftext|> |
<commit_before>#ifndef WINDTUNNEL_ENGINE_ENTITY_ENTITY_HPP
#define WINDTUNNEL_ENGINE_ENTITY_ENTITY_HPP
#include <Windtunnel/Maths/Vector2/Vector2.hpp>
namespace wind
{
class Entity
{
private:
friend class Engine;
unsigned int m_id;
public:
Vector2f position{0.f, 0.f};
Vector2f velocity{0.f, 0.f};
Vector2f force{0.f, 0.f};
unsigned int get_id();
};
}
#endif<commit_msg>Added entity mass component<commit_after>#ifndef WINDTUNNEL_ENGINE_ENTITY_ENTITY_HPP
#define WINDTUNNEL_ENGINE_ENTITY_ENTITY_HPP
#include <Windtunnel/Maths/Vector2/Vector2.hpp>
namespace wind
{
class Entity
{
private:
friend class Engine;
unsigned int m_id;
public:
Vector2f position{0.f, 0.f};
Vector2f velocity{0.f, 0.f};
Vector2f force{0.f, 0.f};
float mass{1.f};
unsigned int get_id();
};
}
#endif<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2005-2008.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : privide core implementation for Unit Test Framework.
// Extensions could be provided in separate files
// ***************************************************************************
#ifndef BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER
#define BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER
// Boost.Test
#include <boost/detail/workaround.hpp>
#include <boost/test/unit_test_suite_impl.hpp>
#include <boost/test/framework.hpp>
#include <boost/test/utils/foreach.hpp>
#include <boost/test/results_collector.hpp>
#include <boost/test/detail/unit_test_parameters.hpp>
// Boost
#include <boost/timer.hpp>
// STL
#include <algorithm>
#include <vector>
#include <boost/test/detail/suppress_warnings.hpp>
#if BOOST_WORKAROUND(__BORLANDC__, < 0x600) && \
BOOST_WORKAROUND(_STLPORT_VERSION, <= 0x450) \
/**/
using std::rand; // rand is in std and random_shuffle is in _STL
#endif
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
// ************************************************************************** //
// ************** test_unit ************** //
// ************************************************************************** //
test_unit::test_unit( const_string name, test_unit_type t )
: p_type( t )
, p_type_name( t == tut_case ? "case" : "suite" )
, p_id( INV_TEST_UNIT_ID )
, p_name( std::string( name.begin(), name.size() ) )
, p_enabled( true )
{
}
//____________________________________________________________________________//
test_unit::~test_unit()
{
framework::deregister_test_unit( this );
}
//____________________________________________________________________________//
void
test_unit::depends_on( test_unit* tu )
{
m_dependencies.push_back( tu->p_id );
}
//____________________________________________________________________________//
bool
test_unit::check_dependencies() const
{
BOOST_TEST_FOREACH( test_unit_id, tu_id, m_dependencies ) {
if( !unit_test::results_collector.results( tu_id ).passed() )
return false;
}
return true;
}
//____________________________________________________________________________//
void
test_unit::increase_exp_fail( unsigned num )
{
p_expected_failures.value += num;
if( p_parent_id != 0 )
framework::get<test_suite>( p_parent_id ).increase_exp_fail( num );
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** test_case ************** //
// ************************************************************************** //
test_case::test_case( const_string name, callback0<> const& test_func )
: test_unit( name, (test_unit_type)type )
, m_test_func( test_func )
{
// !! weirdest MSVC BUG; try to remove this statement; looks like it eats first token of next statement
#if BOOST_WORKAROUND(BOOST_MSVC,<1300)
0;
#endif
framework::register_test_unit( this );
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** test_suite ************** //
// ************************************************************************** //
//____________________________________________________________________________//
test_suite::test_suite( const_string name )
: test_unit( name, (test_unit_type)type )
{
framework::register_test_unit( this );
}
//____________________________________________________________________________//
void
test_suite::add( test_unit* tu, counter_t expected_failures, unsigned timeout )
{
if( timeout != 0 )
tu->p_timeout.value = timeout;
m_members.push_back( tu->p_id );
tu->p_parent_id.value = p_id;
if( tu->p_expected_failures )
increase_exp_fail( tu->p_expected_failures );
if( expected_failures )
tu->increase_exp_fail( expected_failures );
}
//____________________________________________________________________________//
void
test_suite::add( test_unit_generator const& gen, unsigned timeout )
{
test_unit* tu;
while((tu = gen.next(), tu))
add( tu, 0, timeout );
}
//____________________________________________________________________________//
void
test_suite::remove( test_unit_id id )
{
std::vector<test_unit_id>::iterator it = std::find( m_members.begin(), m_members.begin(), id );
if( it != m_members.end() )
m_members.erase( it );
}
//____________________________________________________________________________//
test_unit_id
test_suite::get( const_string tu_name ) const
{
BOOST_TEST_FOREACH( test_unit_id, id, m_members ) {
if( tu_name == framework::get( id, ut_detail::test_id_2_unit_type( id ) ).p_name.get() )
return id;
}
return INV_TEST_UNIT_ID;
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** traverse_test_tree ************** //
// ************************************************************************** //
void
traverse_test_tree( test_case const& tc, test_tree_visitor& V )
{
if( tc.p_enabled )
V.visit( tc );
}
//____________________________________________________________________________//
void
traverse_test_tree( test_suite const& suite, test_tree_visitor& V )
{
if( !suite.p_enabled || !V.test_suite_start( suite ) )
return;
try {
if( runtime_config::random_seed() == 0 ) {
BOOST_TEST_FOREACH( test_unit_id, id, suite.m_members )
traverse_test_tree( id, V );
}
else {
std::vector<test_unit_id> members( suite.m_members );
std::random_shuffle( members.begin(), members.end() );
BOOST_TEST_FOREACH( test_unit_id, id, members )
traverse_test_tree( id, V );
}
} catch( test_being_aborted const& ) {
V.test_suite_finish( suite );
framework::test_unit_aborted( suite );
throw;
}
V.test_suite_finish( suite );
}
//____________________________________________________________________________//
void
traverse_test_tree( test_unit_id id, test_tree_visitor& V )
{
if( ut_detail::test_id_2_unit_type( id ) == tut_case )
traverse_test_tree( framework::get<test_case>( id ), V );
else
traverse_test_tree( framework::get<test_suite>( id ), V );
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** test_case_counter ************** //
// ************************************************************************** //
void
test_case_counter::visit( test_case const& tc )
{
if( tc.p_enabled )
++p_count.value;
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** object generators ************** //
// ************************************************************************** //
namespace ut_detail {
std::string
normalize_test_case_name( const_string name )
{
return ( name[0] == '&'
? std::string( name.begin()+1, name.size()-1 )
: std::string( name.begin(), name.size() ) );
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** auto_test_unit_registrar ************** //
// ************************************************************************** //
auto_test_unit_registrar::auto_test_unit_registrar( test_case* tc, counter_t exp_fail )
{
curr_ts_store().back()->add( tc, exp_fail );
}
//____________________________________________________________________________//
auto_test_unit_registrar::auto_test_unit_registrar( const_string ts_name )
{
test_unit_id id = curr_ts_store().back()->get( ts_name );
test_suite* ts;
if( id != INV_TEST_UNIT_ID ) {
ts = &framework::get<test_suite>( id ); // !! test for invalid tu type
BOOST_ASSERT( ts->p_parent_id == curr_ts_store().back()->p_id );
}
else {
ts = new test_suite( ts_name );
curr_ts_store().back()->add( ts );
}
curr_ts_store().push_back( ts );
}
//____________________________________________________________________________//
auto_test_unit_registrar::auto_test_unit_registrar( test_unit_generator const& tc_gen )
{
curr_ts_store().back()->add( tc_gen );
}
//____________________________________________________________________________//
auto_test_unit_registrar::auto_test_unit_registrar( int )
{
if( curr_ts_store().size() == 0 )
return; // report error?
curr_ts_store().pop_back();
}
//____________________________________________________________________________//
std::list<test_suite*>&
auto_test_unit_registrar::curr_ts_store()
{
static std::list<test_suite*> inst( 1, &framework::master_test_suite() );
return inst;
}
//____________________________________________________________________________//
} // namespace ut_detail
// ************************************************************************** //
// ************** global_fixture ************** //
// ************************************************************************** //
global_fixture::global_fixture()
{
framework::register_observer( *this );
}
//____________________________________________________________________________//
} // namespace unit_test
} // namespace boost
//____________________________________________________________________________//
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER
<commit_msg>bug in test_suite::remove Fixed. Fix #2587<commit_after>// (C) Copyright Gennadiy Rozental 2005-2008.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : privide core implementation for Unit Test Framework.
// Extensions could be provided in separate files
// ***************************************************************************
#ifndef BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER
#define BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER
// Boost.Test
#include <boost/detail/workaround.hpp>
#include <boost/test/unit_test_suite_impl.hpp>
#include <boost/test/framework.hpp>
#include <boost/test/utils/foreach.hpp>
#include <boost/test/results_collector.hpp>
#include <boost/test/detail/unit_test_parameters.hpp>
// Boost
#include <boost/timer.hpp>
// STL
#include <algorithm>
#include <vector>
#include <boost/test/detail/suppress_warnings.hpp>
#if BOOST_WORKAROUND(__BORLANDC__, < 0x600) && \
BOOST_WORKAROUND(_STLPORT_VERSION, <= 0x450) \
/**/
using std::rand; // rand is in std and random_shuffle is in _STL
#endif
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
// ************************************************************************** //
// ************** test_unit ************** //
// ************************************************************************** //
test_unit::test_unit( const_string name, test_unit_type t )
: p_type( t )
, p_type_name( t == tut_case ? "case" : "suite" )
, p_id( INV_TEST_UNIT_ID )
, p_name( std::string( name.begin(), name.size() ) )
, p_enabled( true )
{
}
//____________________________________________________________________________//
test_unit::~test_unit()
{
framework::deregister_test_unit( this );
}
//____________________________________________________________________________//
void
test_unit::depends_on( test_unit* tu )
{
m_dependencies.push_back( tu->p_id );
}
//____________________________________________________________________________//
bool
test_unit::check_dependencies() const
{
BOOST_TEST_FOREACH( test_unit_id, tu_id, m_dependencies ) {
if( !unit_test::results_collector.results( tu_id ).passed() )
return false;
}
return true;
}
//____________________________________________________________________________//
void
test_unit::increase_exp_fail( unsigned num )
{
p_expected_failures.value += num;
if( p_parent_id != 0 )
framework::get<test_suite>( p_parent_id ).increase_exp_fail( num );
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** test_case ************** //
// ************************************************************************** //
test_case::test_case( const_string name, callback0<> const& test_func )
: test_unit( name, (test_unit_type)type )
, m_test_func( test_func )
{
// !! weirdest MSVC BUG; try to remove this statement; looks like it eats first token of next statement
#if BOOST_WORKAROUND(BOOST_MSVC,<1300)
0;
#endif
framework::register_test_unit( this );
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** test_suite ************** //
// ************************************************************************** //
//____________________________________________________________________________//
test_suite::test_suite( const_string name )
: test_unit( name, (test_unit_type)type )
{
framework::register_test_unit( this );
}
//____________________________________________________________________________//
void
test_suite::add( test_unit* tu, counter_t expected_failures, unsigned timeout )
{
if( timeout != 0 )
tu->p_timeout.value = timeout;
m_members.push_back( tu->p_id );
tu->p_parent_id.value = p_id;
if( tu->p_expected_failures )
increase_exp_fail( tu->p_expected_failures );
if( expected_failures )
tu->increase_exp_fail( expected_failures );
}
//____________________________________________________________________________//
void
test_suite::add( test_unit_generator const& gen, unsigned timeout )
{
test_unit* tu;
while((tu = gen.next(), tu))
add( tu, 0, timeout );
}
//____________________________________________________________________________//
void
test_suite::remove( test_unit_id id )
{
std::vector<test_unit_id>::iterator it = std::find( m_members.begin(), m_members.end(), id );
if( it != m_members.end() )
m_members.erase( it );
}
//____________________________________________________________________________//
test_unit_id
test_suite::get( const_string tu_name ) const
{
BOOST_TEST_FOREACH( test_unit_id, id, m_members ) {
if( tu_name == framework::get( id, ut_detail::test_id_2_unit_type( id ) ).p_name.get() )
return id;
}
return INV_TEST_UNIT_ID;
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** traverse_test_tree ************** //
// ************************************************************************** //
void
traverse_test_tree( test_case const& tc, test_tree_visitor& V )
{
if( tc.p_enabled )
V.visit( tc );
}
//____________________________________________________________________________//
void
traverse_test_tree( test_suite const& suite, test_tree_visitor& V )
{
if( !suite.p_enabled || !V.test_suite_start( suite ) )
return;
try {
if( runtime_config::random_seed() == 0 ) {
BOOST_TEST_FOREACH( test_unit_id, id, suite.m_members )
traverse_test_tree( id, V );
}
else {
std::vector<test_unit_id> members( suite.m_members );
std::random_shuffle( members.begin(), members.end() );
BOOST_TEST_FOREACH( test_unit_id, id, members )
traverse_test_tree( id, V );
}
} catch( test_being_aborted const& ) {
V.test_suite_finish( suite );
framework::test_unit_aborted( suite );
throw;
}
V.test_suite_finish( suite );
}
//____________________________________________________________________________//
void
traverse_test_tree( test_unit_id id, test_tree_visitor& V )
{
if( ut_detail::test_id_2_unit_type( id ) == tut_case )
traverse_test_tree( framework::get<test_case>( id ), V );
else
traverse_test_tree( framework::get<test_suite>( id ), V );
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** test_case_counter ************** //
// ************************************************************************** //
void
test_case_counter::visit( test_case const& tc )
{
if( tc.p_enabled )
++p_count.value;
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** object generators ************** //
// ************************************************************************** //
namespace ut_detail {
std::string
normalize_test_case_name( const_string name )
{
return ( name[0] == '&'
? std::string( name.begin()+1, name.size()-1 )
: std::string( name.begin(), name.size() ) );
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** auto_test_unit_registrar ************** //
// ************************************************************************** //
auto_test_unit_registrar::auto_test_unit_registrar( test_case* tc, counter_t exp_fail )
{
curr_ts_store().back()->add( tc, exp_fail );
}
//____________________________________________________________________________//
auto_test_unit_registrar::auto_test_unit_registrar( const_string ts_name )
{
test_unit_id id = curr_ts_store().back()->get( ts_name );
test_suite* ts;
if( id != INV_TEST_UNIT_ID ) {
ts = &framework::get<test_suite>( id ); // !! test for invalid tu type
BOOST_ASSERT( ts->p_parent_id == curr_ts_store().back()->p_id );
}
else {
ts = new test_suite( ts_name );
curr_ts_store().back()->add( ts );
}
curr_ts_store().push_back( ts );
}
//____________________________________________________________________________//
auto_test_unit_registrar::auto_test_unit_registrar( test_unit_generator const& tc_gen )
{
curr_ts_store().back()->add( tc_gen );
}
//____________________________________________________________________________//
auto_test_unit_registrar::auto_test_unit_registrar( int )
{
if( curr_ts_store().size() == 0 )
return; // report error?
curr_ts_store().pop_back();
}
//____________________________________________________________________________//
std::list<test_suite*>&
auto_test_unit_registrar::curr_ts_store()
{
static std::list<test_suite*> inst( 1, &framework::master_test_suite() );
return inst;
}
//____________________________________________________________________________//
} // namespace ut_detail
// ************************************************************************** //
// ************** global_fixture ************** //
// ************************************************************************** //
global_fixture::global_fixture()
{
framework::register_observer( *this );
}
//____________________________________________________________________________//
} // namespace unit_test
} // namespace boost
//____________________________________________________________________________//
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_UNIT_TEST_SUITE_IPP_012205GER
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2013 CoDyCo Project
* Author: Silvio Traversaro
* website: http://www.codyco.eu
*/
#ifndef UNDIRECTED_TREE_SOLVER_H
#define UNDIRECTED_TREE_SOLVER_H
#include <kdl/tree.hpp>
#include <kdl_codyco/undirectedtree.hpp>
#include "kdl_codyco/treeserialization.hpp"
namespace KDL
{
namespace CoDyCo
{
/**
* \brief This is the base class for all the Tree solvers (kinematics,
* dynamics, COM, ... ) that use the UndirectedTree object
*
*
*/
class UndirectedTreeSolver
{
protected:
const UndirectedTree undirected_tree;
Traversal traversal;
public:
UndirectedTreeSolver(const Tree & tree_arg, const TreeSerialization & serialization_arg):
undirected_tree(tree_arg,serialization_arg)
{ undirected_tree.compute_traversal(traversal); assert(undirected_tree.check_consistency(traversal) == 0);};
~UndirectedTreeSolver() {};
bool changeBase(std::string new_base_name)
{
int ret = undirected_tree.compute_traversal(traversal,new_base_name);
if( ret != 0 ) { return false; }
return true; }
bool changeBase(int new_base_id)
{
if( new_base_id < 0 || new_base_id >= (int)undirected_tree.getNrOfLinks() ) {
return false;
}
int ret = undirected_tree.compute_traversal(traversal,new_base_id);
if( ret != 0 ) { return false; }
return true;
}
const TreeSerialization getSerialization() const
{
return undirected_tree.getSerialization();
}
};
}
}
#endif
<commit_msg>Added documentation<commit_after>/**
* Copyright (C) 2013 CoDyCo Project
* Author: Silvio Traversaro
* website: http://www.codyco.eu
*/
#ifndef UNDIRECTED_TREE_SOLVER_H
#define UNDIRECTED_TREE_SOLVER_H
#include <kdl/tree.hpp>
#include <kdl_codyco/undirectedtree.hpp>
#include "kdl_codyco/treeserialization.hpp"
namespace KDL
{
namespace CoDyCo
{
/**
* \brief This is the base class for all the Tree solvers (kinematics,
* dynamics, COM, ... ) that use the UndirectedTree object.
* If a solver uses this base class, then for that solver
* it will be possible to define a custom serialization for joints
* and links using a KDL::CoDyCo::TreeSerialization object.
* It will also be possible to change online the base of the
* tree using the changeBase method.
*/
class UndirectedTreeSolver
{
protected:
const UndirectedTree undirected_tree;
Traversal traversal;
public:
UndirectedTreeSolver(const Tree & tree_arg, const TreeSerialization & serialization_arg):
undirected_tree(tree_arg,serialization_arg)
{ undirected_tree.compute_traversal(traversal); assert(undirected_tree.check_consistency(traversal) == 0);};
~UndirectedTreeSolver() {};
/**
* Change the link used as the base one in the solver
*
* @param[in] new_base_name the name of the new base
* @return true if all went well, false otherwise
*/
bool changeBase(const std::string new_base_name)
{
int ret = undirected_tree.compute_traversal(traversal,new_base_name);
if( ret != 0 ) { return false; }
return true;
}
/**
* Change the link used as the base one in the solver
*
* @param[in] new_base_id the ID of the new base (as specified in getSerialization()
* @return true if all went well, false otherwise
*/
bool changeBase(const int new_base_id)
{
if( new_base_id < 0 || new_base_id >= (int)undirected_tree.getNrOfLinks() ) {
return false;
}
int ret = undirected_tree.compute_traversal(traversal,new_base_id);
if( ret != 0 ) { return false; }
return true;
}
/**
* Return the KDL::CoDyCo::TreeSerialization object used for the solver.
* If it was not specified in the constructor, it is the default one of
* input KDL::Tree (i.e. if tree is the input tree: TreeSerialization(tree))
*
* @return the TreeSerialization object
*/
const TreeSerialization getSerialization() const
{
return undirected_tree.getSerialization();
}
};
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <type_traits>
#include <utility>
#include <hadesmem/config.hpp>
// TODO: Implement same interface as std::optional<T> to make switching later
// easier.
// TODO: Add tests.
namespace hadesmem
{
namespace detail
{
// WARNING: T must have no-throw move, no-throw move assignment and no-throw
// destruction.
template <typename T>
class Optional
{
private:
typedef void (Optional::* Boolean)() const;
public:
HADESMEM_DETAIL_CONSTEXPR Optional() HADESMEM_DETAIL_NOEXCEPT
: t_(),
valid_(false)
{ }
explicit Optional(T const& t)
: t_(),
valid_(false)
{
Construct(t);
}
// TODO: Conditional noexcept.
explicit Optional(T&& t)
: t_(),
valid_(false)
{
Construct(std::move(t));
}
Optional(Optional const& other)
: t_(),
valid_(false)
{
Construct(other.Get());
}
Optional& operator=(Optional const& other)
{
Optional tmp(other);
*this = std::move(tmp);
return *this;
}
Optional(Optional&& other) HADESMEM_DETAIL_NOEXCEPT
: t_(),
valid_(false)
{
Construct(std::move(other.Get()));
other.valid_ = false;
}
Optional& operator=(Optional&& other) HADESMEM_DETAIL_NOEXCEPT
{
Destroy();
Construct(std::move(other.Get()));
other.valid_ = false;
return *this;
}
Optional& operator=(T const& t)
{
Destroy();
Construct(t);
return *this;
}
Optional& operator=(T&& t) HADESMEM_DETAIL_NOEXCEPT
{
Destroy();
Construct(std::move(t));
return *this;
}
~Optional() HADESMEM_DETAIL_NOEXCEPT
{
Destroy();
}
// TODO: Emplacement support. (Including default construction of T.)
#if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)
operator Boolean() const HADESMEM_DETAIL_NOEXCEPT
{
return valid_ ? &Optional::NotComparable : nullptr;
}
#else // #if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)
HADESMEM_DETAIL_EXPLICIT_CONVERSION_OPERATOR operator bool() const
HADESMEM_DETAIL_NOEXCEPT
{
return valid_;
}
#endif // #if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)
T& Get() HADESMEM_DETAIL_NOEXCEPT
{
return *GetPtr();
}
T const& Get() const HADESMEM_DETAIL_NOEXCEPT
{
return *GetPtr();
}
T& operator*() HADESMEM_DETAIL_NOEXCEPT
{
return Get();
}
T const& operator*() const HADESMEM_DETAIL_NOEXCEPT
{
return Get();
}
T* GetPtr() HADESMEM_DETAIL_NOEXCEPT
{
return static_cast<T*>(static_cast<void*>(&t_));
}
T const* GetPtr() const HADESMEM_DETAIL_NOEXCEPT
{
return static_cast<T const*>(static_cast<void const*>(&t_));
}
T* operator->() HADESMEM_DETAIL_NOEXCEPT
{
return GetPtr();
}
T const* operator->() const HADESMEM_DETAIL_NOEXCEPT
{
return GetPtr();
}
private:
void NotComparable() const HADESMEM_DETAIL_NOEXCEPT
{ }
template <typename U>
void Construct(U&& u)
{
if (valid_)
{
Destroy();
}
new (&t_) T(std::forward<U>(u));
valid_ = true;
}
void Destroy() HADESMEM_DETAIL_NOEXCEPT
{
if (valid_)
{
GetPtr()->~T();
valid_ = false;
}
}
typename std::aligned_storage<sizeof(T),
std::alignment_of<T>::value>::type t_;
bool valid_;
};
// TODO: Add conditional noexcept to operator overloads.
template <typename T>
inline bool operator==(Optional<T> const& lhs, Optional<T> const& rhs)
{
return (!lhs && !rhs) || ((rhs && lhs) && *rhs == *lhs);
}
template <typename T>
inline bool operator!=(Optional<T> const& lhs, Optional<T> const& rhs)
{
return !(lhs == rhs);
}
template <typename T>
inline bool operator<(Optional<T> const& lhs, Optional<T> const& rhs)
{
return (!lhs && !rhs) || ((rhs && lhs) && *rhs < *lhs);
}
}
}
<commit_msg>* Note to self.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <type_traits>
#include <utility>
#include <hadesmem/config.hpp>
// TODO: Implement same interface as std::optional<T> to make switching later
// easier.
// TODO: Add tests.
// TODO: Add constexpr support. (http://bit.ly/U7lSYy)
namespace hadesmem
{
namespace detail
{
// WARNING: T must have no-throw move, no-throw move assignment and no-throw
// destruction.
template <typename T>
class Optional
{
private:
typedef void (Optional::* Boolean)() const;
public:
HADESMEM_DETAIL_CONSTEXPR Optional() HADESMEM_DETAIL_NOEXCEPT
: t_(),
valid_(false)
{ }
explicit Optional(T const& t)
: t_(),
valid_(false)
{
Construct(t);
}
// TODO: Conditional noexcept.
explicit Optional(T&& t)
: t_(),
valid_(false)
{
Construct(std::move(t));
}
Optional(Optional const& other)
: t_(),
valid_(false)
{
Construct(other.Get());
}
Optional& operator=(Optional const& other)
{
Optional tmp(other);
*this = std::move(tmp);
return *this;
}
Optional(Optional&& other) HADESMEM_DETAIL_NOEXCEPT
: t_(),
valid_(false)
{
Construct(std::move(other.Get()));
other.valid_ = false;
}
Optional& operator=(Optional&& other) HADESMEM_DETAIL_NOEXCEPT
{
Destroy();
Construct(std::move(other.Get()));
other.valid_ = false;
return *this;
}
Optional& operator=(T const& t)
{
Destroy();
Construct(t);
return *this;
}
Optional& operator=(T&& t) HADESMEM_DETAIL_NOEXCEPT
{
Destroy();
Construct(std::move(t));
return *this;
}
~Optional() HADESMEM_DETAIL_NOEXCEPT
{
Destroy();
}
// TODO: Emplacement support. (Including default construction of T.)
#if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)
operator Boolean() const HADESMEM_DETAIL_NOEXCEPT
{
return valid_ ? &Optional::NotComparable : nullptr;
}
#else // #if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)
HADESMEM_DETAIL_EXPLICIT_CONVERSION_OPERATOR operator bool() const
HADESMEM_DETAIL_NOEXCEPT
{
return valid_;
}
#endif // #if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)
T& Get() HADESMEM_DETAIL_NOEXCEPT
{
return *GetPtr();
}
T const& Get() const HADESMEM_DETAIL_NOEXCEPT
{
return *GetPtr();
}
T& operator*() HADESMEM_DETAIL_NOEXCEPT
{
return Get();
}
T const& operator*() const HADESMEM_DETAIL_NOEXCEPT
{
return Get();
}
T* GetPtr() HADESMEM_DETAIL_NOEXCEPT
{
return static_cast<T*>(static_cast<void*>(&t_));
}
T const* GetPtr() const HADESMEM_DETAIL_NOEXCEPT
{
return static_cast<T const*>(static_cast<void const*>(&t_));
}
T* operator->() HADESMEM_DETAIL_NOEXCEPT
{
return GetPtr();
}
T const* operator->() const HADESMEM_DETAIL_NOEXCEPT
{
return GetPtr();
}
private:
void NotComparable() const HADESMEM_DETAIL_NOEXCEPT
{ }
template <typename U>
void Construct(U&& u)
{
if (valid_)
{
Destroy();
}
new (&t_) T(std::forward<U>(u));
valid_ = true;
}
void Destroy() HADESMEM_DETAIL_NOEXCEPT
{
if (valid_)
{
GetPtr()->~T();
valid_ = false;
}
}
typename std::aligned_storage<sizeof(T),
std::alignment_of<T>::value>::type t_;
bool valid_;
};
// TODO: Add conditional noexcept to operator overloads.
template <typename T>
inline bool operator==(Optional<T> const& lhs, Optional<T> const& rhs)
{
return (!lhs && !rhs) || ((rhs && lhs) && *rhs == *lhs);
}
template <typename T>
inline bool operator!=(Optional<T> const& lhs, Optional<T> const& rhs)
{
return !(lhs == rhs);
}
template <typename T>
inline bool operator<(Optional<T> const& lhs, Optional<T> const& rhs)
{
return (!lhs && !rhs) || ((rhs && lhs) && *rhs < *lhs);
}
}
}
<|endoftext|> |
<commit_before>#include "protocolsupport.h"
#include "protocolparser.h"
ProtocolSupport::ProtocolSupport() :
maxdatasize(0),
int64(true),
float64(true),
specialFloat(true),
bitfield(true),
longbitfield(false),
bitfieldtest(false),
disableunrecognized(false),
bigendian(true),
packetStructureSuffix("PacketStructure"),
packetParameterSuffix("Packet")
{
}
//! Return the list of attributes understood by ProtocolSupport
QStringList ProtocolSupport::getAttriblist(void) const
{
QStringList attribs;
attribs << "maxSize"
<< "supportInt64"
<< "supportFloat64"
<< "supportSpecialFloat"
<< "supportBitfield"
<< "supportLongBitfield"
<< "bitfieldTest"
<< "file"
<< "prefix"
<< "packetStructureSuffix"
<< "packetParameterSuffix"
<< "endian"
<< "pointer";
return attribs;
}
void ProtocolSupport::parse(const QDomNamedNodeMap& map)
{
// Maximum bytes of data in a packet.
maxdatasize = ProtocolParser::getAttribute("maxSize", map, "0").toInt();
// 64-bit support can be turned off
if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportInt64", map)))
int64 = false;
// double support can be turned off
if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportFloat64", map)))
float64 = false;
// special float support can be turned off
if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportSpecialFloat", map)))
specialFloat = false;
// bitfield support can be turned off
if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportBitfield", map)))
bitfield = false;
// long bitfield support can be turned on
if(int64 && ProtocolParser::isFieldSet(ProtocolParser::getAttribute("supportLongBitfield", map)))
longbitfield = true;
// bitfield test support can be turned on
if(ProtocolParser::isFieldSet(ProtocolParser::getAttribute("bitfieldTest", map)))
bitfieldtest = true;
// Global file names can be specified, but cannot have a "." in it
globalFileName = ProtocolParser::getAttribute("file", map);
globalFileName = globalFileName.left(globalFileName.indexOf("."));
// Prefix is not required
prefix = ProtocolParser::getAttribute("prefix", map);
// Packet pointer type (default is 'void')
pointerType = ProtocolParser::getAttribute("pointer", map, "void");
if(!pointerType.endsWith("*"))
{
pointerType += "*";
}
// Packet name post fixes
packetStructureSuffix = ProtocolParser::getAttribute("packetStructureSuffix", map, packetStructureSuffix);
packetParameterSuffix = ProtocolParser::getAttribute("packetParameterSuffix", map, packetParameterSuffix);
if(ProtocolParser::getAttribute("endian", map).contains("little", Qt::CaseInsensitive))
bigendian = false;
}// ProtocolSupport::parse
<commit_msg>Do not require the pointer to end with an asterisk - User could use a typedef to mask the pointer<commit_after>#include "protocolsupport.h"
#include "protocolparser.h"
ProtocolSupport::ProtocolSupport() :
maxdatasize(0),
int64(true),
float64(true),
specialFloat(true),
bitfield(true),
longbitfield(false),
bitfieldtest(false),
disableunrecognized(false),
bigendian(true),
packetStructureSuffix("PacketStructure"),
packetParameterSuffix("Packet")
{
}
//! Return the list of attributes understood by ProtocolSupport
QStringList ProtocolSupport::getAttriblist(void) const
{
QStringList attribs;
attribs << "maxSize"
<< "supportInt64"
<< "supportFloat64"
<< "supportSpecialFloat"
<< "supportBitfield"
<< "supportLongBitfield"
<< "bitfieldTest"
<< "file"
<< "prefix"
<< "packetStructureSuffix"
<< "packetParameterSuffix"
<< "endian"
<< "pointer";
return attribs;
}
void ProtocolSupport::parse(const QDomNamedNodeMap& map)
{
// Maximum bytes of data in a packet.
maxdatasize = ProtocolParser::getAttribute("maxSize", map, "0").toInt();
// 64-bit support can be turned off
if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportInt64", map)))
int64 = false;
// double support can be turned off
if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportFloat64", map)))
float64 = false;
// special float support can be turned off
if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportSpecialFloat", map)))
specialFloat = false;
// bitfield support can be turned off
if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportBitfield", map)))
bitfield = false;
// long bitfield support can be turned on
if(int64 && ProtocolParser::isFieldSet(ProtocolParser::getAttribute("supportLongBitfield", map)))
longbitfield = true;
// bitfield test support can be turned on
if(ProtocolParser::isFieldSet(ProtocolParser::getAttribute("bitfieldTest", map)))
bitfieldtest = true;
// Global file names can be specified, but cannot have a "." in it
globalFileName = ProtocolParser::getAttribute("file", map);
globalFileName = globalFileName.left(globalFileName.indexOf("."));
// Prefix is not required
prefix = ProtocolParser::getAttribute("prefix", map);
// Packet pointer type (default is 'void')
pointerType = ProtocolParser::getAttribute("pointer", map, "void");
// Packet name post fixes
packetStructureSuffix = ProtocolParser::getAttribute("packetStructureSuffix", map, packetStructureSuffix);
packetParameterSuffix = ProtocolParser::getAttribute("packetParameterSuffix", map, packetParameterSuffix);
if(ProtocolParser::getAttribute("endian", map).contains("little", Qt::CaseInsensitive))
bigendian = false;
}// ProtocolSupport::parse
<|endoftext|> |
<commit_before>/*
Q Light Controller Plus
e131controller.cpp
Copyright (c) Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "e131controller.h"
#include <QMutexLocker>
#include <QDebug>
#define TRANSMIT_FULL "Full"
#define TRANSMIT_PARTIAL "Partial"
E131Controller::E131Controller(QNetworkInterface const& interface, QString const& ipaddr,
Type type, quint32 line, QObject *parent)
: QObject(parent)
, m_interface(interface)
, m_ipAddr(ipaddr)
, m_packetSent(0)
, m_packetReceived(0)
, m_line(line)
, m_UdpSocket(new QUdpSocket(this))
, m_packetizer(new E131Packetizer())
{
qDebug() << "[E131Controller] type: " << type;
m_UdpSocket->bind(m_ipAddr, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
// Output multicast on the correct interface
m_UdpSocket->setMulticastInterface(m_interface);
// Don't send multicast to self
m_UdpSocket->setSocketOption(QAbstractSocket::MulticastLoopbackOption, false);
}
E131Controller::~E131Controller()
{
qDebug() << Q_FUNC_INFO;
qDeleteAll(m_dmxValuesMap);
}
QString E131Controller::getNetworkIP()
{
return m_ipAddr.toString();
}
void E131Controller::addUniverse(quint32 universe, E131Controller::Type type)
{
qDebug() << "[E1.31] addUniverse - universe" << universe << ", type" << type;
if (m_universeMap.contains(universe))
{
m_universeMap[universe].type |= (int)type;
}
else
{
UniverseInfo info;
info.inputMulticast = true;
info.inputMcastAddress = QHostAddress(QString("239.255.0.%1").arg(universe + 1));
info.inputUcastPort = E131_DEFAULT_PORT;
info.inputUniverse = universe + 1;
info.inputSocket.clear();
info.outputMulticast = true;
info.outputMcastAddress = QHostAddress(QString("239.255.0.%1").arg(universe + 1));
if (m_ipAddr != QHostAddress::LocalHost)
info.outputUcastAddress = QHostAddress(quint32((m_ipAddr.toIPv4Address() & 0xFFFFFF00) + (universe + 1)));
else
info.outputUcastAddress = m_ipAddr;
info.outputUcastPort = E131_DEFAULT_PORT;
info.outputUniverse = universe + 1;
info.outputTransmissionMode = Full;
info.outputPriority = E131_PRIORITY_DEFAULT;
info.type = type;
m_universeMap[universe] = info;
}
if (type == Input)
{
UniverseInfo& info = m_universeMap[universe];
info.inputSocket.clear();
info.inputSocket = getInputSocket(true, info.inputMcastAddress, E131_DEFAULT_PORT);
}
}
void E131Controller::removeUniverse(quint32 universe, E131Controller::Type type)
{
if (m_universeMap.contains(universe))
{
UniverseInfo& info = m_universeMap[universe];
if (type == Input)
info.inputSocket.clear();
if (info.type == type)
m_universeMap.take(universe);
else
info.type &= ~type;
}
}
void E131Controller::setInputMulticast(quint32 universe, bool multicast)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
UniverseInfo& info = m_universeMap[universe];
if (info.inputMulticast == multicast)
return;
info.inputMulticast = multicast;
info.inputSocket.clear();
if (multicast)
info.inputSocket = getInputSocket(true, info.inputMcastAddress, E131_DEFAULT_PORT);
else
info.inputSocket = getInputSocket(false, m_ipAddr, info.inputUcastPort);
}
QSharedPointer<QUdpSocket> E131Controller::getInputSocket(bool multicast, QHostAddress const& address, quint16 port)
{
if (!multicast && port == E131_DEFAULT_PORT)
return m_UdpSocket;
foreach(UniverseInfo const& info, m_universeMap)
{
if (info.inputSocket && info.inputMulticast == multicast)
{
if (info.inputMulticast && info.inputMcastAddress == address)
return info.inputSocket;
if (!info.inputMulticast && info.inputUcastPort == port)
return info.inputSocket;
}
}
QSharedPointer<QUdpSocket> inputSocket(new QUdpSocket(this));
if (multicast)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
inputSocket->bind(QHostAddress::AnyIPv4, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
#else
inputSocket->bind(QHostAddress::Any, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
#endif
inputSocket->joinMulticastGroup(address, m_interface);
}
else
{
inputSocket->bind(m_ipAddr, port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
}
connect(inputSocket.data(), SIGNAL(readyRead()),
this, SLOT(processPendingPackets()));
return inputSocket;
}
void E131Controller::setInputMCastAddress(quint32 universe, QString address)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
UniverseInfo& info = m_universeMap[universe];
QHostAddress newAddress(QString("239.255.0.%1").arg(address));
if (info.inputMcastAddress == newAddress)
return;
info.inputMcastAddress = newAddress;
if (!info.inputMulticast)
{
info.inputSocket.clear();
info.inputSocket = getInputSocket(true, info.inputMcastAddress, E131_DEFAULT_PORT);
}
}
void E131Controller::setInputUCastPort(quint32 universe, quint16 port)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
UniverseInfo& info = m_universeMap[universe];
if (info.inputUcastPort == port)
return;
info.inputUcastPort = port;
if (!info.inputMulticast)
{
info.inputSocket.clear();
info.inputSocket = getInputSocket(false, m_ipAddr, info.inputUcastPort);
}
}
void E131Controller::setInputUniverse(quint32 universe, quint32 e131Uni)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
UniverseInfo& info = m_universeMap[universe];
if (info.inputUniverse == e131Uni)
return;
info.inputUniverse = e131Uni;
}
void E131Controller::setOutputMulticast(quint32 universe, bool multicast)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputMulticast = multicast;
}
void E131Controller::setOutputMCastAddress(quint32 universe, QString address)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputMcastAddress = QHostAddress(QString("239.255.0.%1").arg(address));
}
void E131Controller::setOutputUCastAddress(quint32 universe, QString address)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputUcastAddress = QHostAddress(address);
}
void E131Controller::setOutputUCastPort(quint32 universe, quint16 port)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputUcastPort = port;
}
void E131Controller::setOutputUniverse(quint32 universe, quint32 e131Uni)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputUniverse = e131Uni;
}
void E131Controller::setOutputPriority(quint32 universe, quint32 e131Priority)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputPriority = e131Priority;
}
void E131Controller::setOutputTransmissionMode(quint32 universe, E131Controller::TransmissionMode mode)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputTransmissionMode = int(mode);
}
QString E131Controller::transmissionModeToString(E131Controller::TransmissionMode mode)
{
switch (mode)
{
default:
case Full:
return QString(TRANSMIT_FULL);
break;
case Partial:
return QString(TRANSMIT_PARTIAL);
break;
}
}
E131Controller::TransmissionMode E131Controller::stringToTransmissionMode(const QString &mode)
{
if (mode == QString(TRANSMIT_PARTIAL))
return Partial;
else
return Full;
}
QList<quint32> E131Controller::universesList()
{
return m_universeMap.keys();
}
UniverseInfo *E131Controller::getUniverseInfo(quint32 universe)
{
if (m_universeMap.contains(universe))
return &m_universeMap[universe];
return NULL;
}
E131Controller::Type E131Controller::type()
{
int type = Unknown;
foreach(UniverseInfo info, m_universeMap.values())
{
type |= info.type;
}
return Type(type);
}
quint32 E131Controller::line()
{
return m_line;
}
quint64 E131Controller::getPacketSentNumber()
{
return m_packetSent;
}
quint64 E131Controller::getPacketReceivedNumber()
{
return m_packetReceived;
}
void E131Controller::sendDmx(const quint32 universe, const QByteArray &data)
{
QMutexLocker locker(&m_dataMutex);
QByteArray dmxPacket;
QHostAddress outAddress = QHostAddress(QString("239.255.0.%1").arg(universe + 1));
quint16 outPort = E131_DEFAULT_PORT;
quint32 outUniverse = universe;
quint32 outPriority = E131_PRIORITY_DEFAULT;
TransmissionMode transmitMode = Full;
if (m_universeMap.contains(universe))
{
UniverseInfo const& info = m_universeMap[universe];
if (info.outputMulticast)
{
outAddress = info.outputMcastAddress;
}
else
{
outAddress = info.outputUcastAddress;
outPort = info.outputUcastPort;
}
outUniverse = info.outputUniverse;
outPriority = info.outputPriority;
transmitMode = TransmissionMode(info.outputTransmissionMode);
}
else
qWarning() << Q_FUNC_INFO << "universe" << universe << "unknown";
if (transmitMode == Full)
{
QByteArray wholeuniverse(512, 0);
wholeuniverse.replace(0, data.length(), data);
m_packetizer->setupE131Dmx(dmxPacket, outUniverse, outPriority, wholeuniverse);
}
else
m_packetizer->setupE131Dmx(dmxPacket, outUniverse, outPriority, data);
qint64 sent = m_UdpSocket->writeDatagram(dmxPacket.data(), dmxPacket.size(),
outAddress, outPort);
if (sent < 0)
{
qDebug() << "sendDmx failed";
qDebug() << "Errno: " << m_UdpSocket->error();
qDebug() << "Errmsg: " << m_UdpSocket->errorString();
}
else
m_packetSent++;
}
void E131Controller::processPendingPackets()
{
QUdpSocket* socket = qobject_cast<QUdpSocket*>(sender());
Q_ASSERT(socket != NULL);
while (socket->hasPendingDatagrams())
{
QByteArray datagram;
QHostAddress senderAddress;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(), datagram.size(), &senderAddress);
QByteArray dmxData;
quint32 e131universe;
if (m_packetizer->checkPacket(datagram)
&& m_packetizer->fillDMXdata(datagram, dmxData, e131universe))
{
qDebug() << "Received packet with size: " << datagram.size() << ", from: " << senderAddress.toString()
<< ", for E1.31 universe: " << e131universe;
++m_packetReceived;
for (QMap<quint32, UniverseInfo>::iterator it = m_universeMap.begin(); it != m_universeMap.end(); ++it)
{
quint32 universe = it.key();
UniverseInfo& info = it.value();
if (info.inputSocket == socket && info.inputUniverse == e131universe)
{
QByteArray *dmxValues;
if (m_dmxValuesMap.contains(universe) == false)
m_dmxValuesMap[universe] = new QByteArray(512, 0);
dmxValues = m_dmxValuesMap[universe];
for (int i = 0; i < dmxData.length(); i++)
{
if (dmxValues->at(i) != dmxData.at(i))
{
dmxValues->replace(i, 1, (const char *)(dmxData.data() + i), 1);
emit valueChanged(universe, m_line, i, (uchar)dmxData.at(i));
}
}
}
}
}
else
{
qDebug() << "Received packet with size: " << datagram.size() << ", from: " << senderAddress.toString()
<< ", that does not look like E1.31";
}
}
// TODO? use this test? if (senderAddress != m_ipAddr || info.inputMulticast == false)
}
<commit_msg>E1.31: bind outputsocket on a random port<commit_after>/*
Q Light Controller Plus
e131controller.cpp
Copyright (c) Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "e131controller.h"
#include <QMutexLocker>
#include <QDebug>
#define TRANSMIT_FULL "Full"
#define TRANSMIT_PARTIAL "Partial"
E131Controller::E131Controller(QNetworkInterface const& interface, QString const& ipaddr,
Type type, quint32 line, QObject *parent)
: QObject(parent)
, m_interface(interface)
, m_ipAddr(ipaddr)
, m_packetSent(0)
, m_packetReceived(0)
, m_line(line)
, m_UdpSocket(new QUdpSocket(this))
, m_packetizer(new E131Packetizer())
{
qDebug() << "[E131Controller] type: " << type;
m_UdpSocket->bind(m_ipAddr, 0);
// Output multicast on the correct interface
m_UdpSocket->setMulticastInterface(m_interface);
// Don't send multicast to self
m_UdpSocket->setSocketOption(QAbstractSocket::MulticastLoopbackOption, false);
}
E131Controller::~E131Controller()
{
qDebug() << Q_FUNC_INFO;
qDeleteAll(m_dmxValuesMap);
}
QString E131Controller::getNetworkIP()
{
return m_ipAddr.toString();
}
void E131Controller::addUniverse(quint32 universe, E131Controller::Type type)
{
qDebug() << "[E1.31] addUniverse - universe" << universe << ", type" << type;
if (m_universeMap.contains(universe))
{
m_universeMap[universe].type |= (int)type;
}
else
{
UniverseInfo info;
info.inputMulticast = true;
info.inputMcastAddress = QHostAddress(QString("239.255.0.%1").arg(universe + 1));
info.inputUcastPort = E131_DEFAULT_PORT;
info.inputUniverse = universe + 1;
info.inputSocket.clear();
info.outputMulticast = true;
info.outputMcastAddress = QHostAddress(QString("239.255.0.%1").arg(universe + 1));
if (m_ipAddr != QHostAddress::LocalHost)
info.outputUcastAddress = QHostAddress(quint32((m_ipAddr.toIPv4Address() & 0xFFFFFF00) + (universe + 1)));
else
info.outputUcastAddress = m_ipAddr;
info.outputUcastPort = E131_DEFAULT_PORT;
info.outputUniverse = universe + 1;
info.outputTransmissionMode = Full;
info.outputPriority = E131_PRIORITY_DEFAULT;
info.type = type;
m_universeMap[universe] = info;
}
if (type == Input)
{
UniverseInfo& info = m_universeMap[universe];
info.inputSocket.clear();
info.inputSocket = getInputSocket(true, info.inputMcastAddress, E131_DEFAULT_PORT);
}
}
void E131Controller::removeUniverse(quint32 universe, E131Controller::Type type)
{
if (m_universeMap.contains(universe))
{
UniverseInfo& info = m_universeMap[universe];
if (type == Input)
info.inputSocket.clear();
if (info.type == type)
m_universeMap.take(universe);
else
info.type &= ~type;
}
}
void E131Controller::setInputMulticast(quint32 universe, bool multicast)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
UniverseInfo& info = m_universeMap[universe];
if (info.inputMulticast == multicast)
return;
info.inputMulticast = multicast;
info.inputSocket.clear();
if (multicast)
info.inputSocket = getInputSocket(true, info.inputMcastAddress, E131_DEFAULT_PORT);
else
info.inputSocket = getInputSocket(false, m_ipAddr, info.inputUcastPort);
}
QSharedPointer<QUdpSocket> E131Controller::getInputSocket(bool multicast, QHostAddress const& address, quint16 port)
{
foreach(UniverseInfo const& info, m_universeMap)
{
if (info.inputSocket && info.inputMulticast == multicast)
{
if (info.inputMulticast && info.inputMcastAddress == address)
return info.inputSocket;
if (!info.inputMulticast && info.inputUcastPort == port)
return info.inputSocket;
}
}
QSharedPointer<QUdpSocket> inputSocket(new QUdpSocket(this));
if (multicast)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
inputSocket->bind(QHostAddress::AnyIPv4, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
#else
inputSocket->bind(QHostAddress::Any, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
#endif
inputSocket->joinMulticastGroup(address, m_interface);
}
else
{
inputSocket->bind(m_ipAddr, port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
}
connect(inputSocket.data(), SIGNAL(readyRead()),
this, SLOT(processPendingPackets()));
return inputSocket;
}
void E131Controller::setInputMCastAddress(quint32 universe, QString address)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
UniverseInfo& info = m_universeMap[universe];
QHostAddress newAddress(QString("239.255.0.%1").arg(address));
if (info.inputMcastAddress == newAddress)
return;
info.inputMcastAddress = newAddress;
if (!info.inputMulticast)
{
info.inputSocket.clear();
info.inputSocket = getInputSocket(true, info.inputMcastAddress, E131_DEFAULT_PORT);
}
}
void E131Controller::setInputUCastPort(quint32 universe, quint16 port)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
UniverseInfo& info = m_universeMap[universe];
if (info.inputUcastPort == port)
return;
info.inputUcastPort = port;
if (!info.inputMulticast)
{
info.inputSocket.clear();
info.inputSocket = getInputSocket(false, m_ipAddr, info.inputUcastPort);
}
}
void E131Controller::setInputUniverse(quint32 universe, quint32 e131Uni)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
UniverseInfo& info = m_universeMap[universe];
if (info.inputUniverse == e131Uni)
return;
info.inputUniverse = e131Uni;
}
void E131Controller::setOutputMulticast(quint32 universe, bool multicast)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputMulticast = multicast;
}
void E131Controller::setOutputMCastAddress(quint32 universe, QString address)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputMcastAddress = QHostAddress(QString("239.255.0.%1").arg(address));
}
void E131Controller::setOutputUCastAddress(quint32 universe, QString address)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputUcastAddress = QHostAddress(address);
}
void E131Controller::setOutputUCastPort(quint32 universe, quint16 port)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputUcastPort = port;
}
void E131Controller::setOutputUniverse(quint32 universe, quint32 e131Uni)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputUniverse = e131Uni;
}
void E131Controller::setOutputPriority(quint32 universe, quint32 e131Priority)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputPriority = e131Priority;
}
void E131Controller::setOutputTransmissionMode(quint32 universe, E131Controller::TransmissionMode mode)
{
if (m_universeMap.contains(universe) == false)
return;
QMutexLocker locker(&m_dataMutex);
m_universeMap[universe].outputTransmissionMode = int(mode);
}
QString E131Controller::transmissionModeToString(E131Controller::TransmissionMode mode)
{
switch (mode)
{
default:
case Full:
return QString(TRANSMIT_FULL);
break;
case Partial:
return QString(TRANSMIT_PARTIAL);
break;
}
}
E131Controller::TransmissionMode E131Controller::stringToTransmissionMode(const QString &mode)
{
if (mode == QString(TRANSMIT_PARTIAL))
return Partial;
else
return Full;
}
QList<quint32> E131Controller::universesList()
{
return m_universeMap.keys();
}
UniverseInfo *E131Controller::getUniverseInfo(quint32 universe)
{
if (m_universeMap.contains(universe))
return &m_universeMap[universe];
return NULL;
}
E131Controller::Type E131Controller::type()
{
int type = Unknown;
foreach(UniverseInfo info, m_universeMap.values())
{
type |= info.type;
}
return Type(type);
}
quint32 E131Controller::line()
{
return m_line;
}
quint64 E131Controller::getPacketSentNumber()
{
return m_packetSent;
}
quint64 E131Controller::getPacketReceivedNumber()
{
return m_packetReceived;
}
void E131Controller::sendDmx(const quint32 universe, const QByteArray &data)
{
QMutexLocker locker(&m_dataMutex);
QByteArray dmxPacket;
QHostAddress outAddress = QHostAddress(QString("239.255.0.%1").arg(universe + 1));
quint16 outPort = E131_DEFAULT_PORT;
quint32 outUniverse = universe;
quint32 outPriority = E131_PRIORITY_DEFAULT;
TransmissionMode transmitMode = Full;
if (m_universeMap.contains(universe))
{
UniverseInfo const& info = m_universeMap[universe];
if (info.outputMulticast)
{
outAddress = info.outputMcastAddress;
}
else
{
outAddress = info.outputUcastAddress;
outPort = info.outputUcastPort;
}
outUniverse = info.outputUniverse;
outPriority = info.outputPriority;
transmitMode = TransmissionMode(info.outputTransmissionMode);
}
else
qWarning() << Q_FUNC_INFO << "universe" << universe << "unknown";
if (transmitMode == Full)
{
QByteArray wholeuniverse(512, 0);
wholeuniverse.replace(0, data.length(), data);
m_packetizer->setupE131Dmx(dmxPacket, outUniverse, outPriority, wholeuniverse);
}
else
m_packetizer->setupE131Dmx(dmxPacket, outUniverse, outPriority, data);
qint64 sent = m_UdpSocket->writeDatagram(dmxPacket.data(), dmxPacket.size(),
outAddress, outPort);
if (sent < 0)
{
qDebug() << "sendDmx failed";
qDebug() << "Errno: " << m_UdpSocket->error();
qDebug() << "Errmsg: " << m_UdpSocket->errorString();
}
else
m_packetSent++;
}
void E131Controller::processPendingPackets()
{
QUdpSocket* socket = qobject_cast<QUdpSocket*>(sender());
Q_ASSERT(socket != NULL);
while (socket->hasPendingDatagrams())
{
QByteArray datagram;
QHostAddress senderAddress;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(), datagram.size(), &senderAddress);
QByteArray dmxData;
quint32 e131universe;
if (m_packetizer->checkPacket(datagram)
&& m_packetizer->fillDMXdata(datagram, dmxData, e131universe))
{
qDebug() << "Received packet with size: " << datagram.size() << ", from: " << senderAddress.toString()
<< ", for E1.31 universe: " << e131universe;
++m_packetReceived;
for (QMap<quint32, UniverseInfo>::iterator it = m_universeMap.begin(); it != m_universeMap.end(); ++it)
{
quint32 universe = it.key();
UniverseInfo& info = it.value();
if (info.inputSocket == socket && info.inputUniverse == e131universe)
{
QByteArray *dmxValues;
if (m_dmxValuesMap.contains(universe) == false)
m_dmxValuesMap[universe] = new QByteArray(512, 0);
dmxValues = m_dmxValuesMap[universe];
for (int i = 0; i < dmxData.length(); i++)
{
if (dmxValues->at(i) != dmxData.at(i))
{
dmxValues->replace(i, 1, (const char *)(dmxData.data() + i), 1);
emit valueChanged(universe, m_line, i, (uchar)dmxData.at(i));
}
}
}
}
}
else
{
qDebug() << "Received packet with size: " << datagram.size() << ", from: " << senderAddress.toString()
<< ", that does not look like E1.31";
}
}
// TODO? use this test? if (senderAddress != m_ipAddr || info.inputMulticast == false)
}
<|endoftext|> |
<commit_before>#include <ctime>
#include <iostream>
#include <cassert>
#include "policy/kasp.pb.h"
// Interface of this cpp file is used by C code, we need to declare
// extern "C" to prevent linking errors.
extern "C" {
#include "enforcer/setup_cmd.h"
#include "policy/update_kasp_task.h"
#include "keystate/update_keyzones_task.h"
#include "hsmkey/update_hsmkeys_task.h"
#include "policy/policy_resalt_task.h"
#include "shared/duration.h"
#include "shared/file.h"
#include "daemon/engine.h"
}
static const char *module_str = "setup_cmd";
/**
* Print help for the 'setup' command
*
*/
void help_setup_cmd(int sockfd)
{
char buf[ODS_SE_MAXLINE];
(void) snprintf(buf, ODS_SE_MAXLINE,
"setup delete existing database files and then perform:\n"
" update kasp\n"
" policy resalt\n"
" update zonelist\n"
" update hsmkeys\n"
);
ods_writen(sockfd, buf, strlen(buf));
}
/**
* Handle the 'setup' command.
*
*/
int handled_setup_cmd(int sockfd, engine_type* engine,
const char *cmd, ssize_t n)
{
char buf[ODS_SE_MAXLINE];
const char *scmd = "setup";
ssize_t ncmd = strlen(scmd);
if (n < ncmd || strncmp(cmd, scmd, ncmd) != 0) return 0;
ods_log_debug("[%s] %s command", module_str, scmd);
if (cmd[ncmd] == '\0') {
cmd = "";
} else if (cmd[ncmd] != ' ') {
return 0;
} else {
cmd = &cmd[ncmd+1];
}
time_t tstart = time(NULL);
const char *datastore = engine->config->datastore;
std::string policy_pb = std::string(datastore) + ".policy.pb";
std::string keystate_pb = std::string(datastore) + ".keystate.pb";
std::string hsmkey_pb = std::string(datastore) + ".hsmkey.pb";
if (unlink(policy_pb.c_str())==-1) {
ods_log_error("[%s] unlink of \"%s\" failed: %s",
module_str,policy_pb.c_str(),strerror(errno));
(void)snprintf(buf, ODS_SE_MAXLINE, "unlink of \"%s\" failed: %s\n",
policy_pb.c_str(),strerror(errno));
ods_writen(sockfd, buf, strlen(buf));
}
if (unlink(keystate_pb.c_str())==-1) {
ods_log_error("[%s] unlink of \"%s\" failed: %s",
module_str,keystate_pb.c_str(),strerror(errno));
(void)snprintf(buf, ODS_SE_MAXLINE, "unlink of \"%s\" failed: %s\n",
keystate_pb.c_str(),strerror(errno));
ods_writen(sockfd, buf, strlen(buf));
}
if (unlink(hsmkey_pb.c_str())==-1) {
ods_log_error("[%s] unlink of \"%s\" failed: %s",
module_str,hsmkey_pb.c_str(),strerror(errno));
(void)snprintf(buf, ODS_SE_MAXLINE, "unlink of \"%s\" failed: %s\n",
hsmkey_pb.c_str(),strerror(errno));
ods_writen(sockfd, buf, strlen(buf));
}
perform_update_kasp(sockfd, engine->config);
perform_policy_resalt(sockfd, engine->config);
perform_update_keyzones(sockfd, engine->config);
perform_update_hsmkeys(sockfd, engine->config);
(void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
scmd,time(NULL)-tstart);
ods_writen(sockfd, buf, strlen(buf));
return 1;
}
<commit_msg>No longer automatically import all hsm keys into the enforcer on setup.<commit_after>#include <ctime>
#include <iostream>
#include <cassert>
#include "policy/kasp.pb.h"
// Interface of this cpp file is used by C code, we need to declare
// extern "C" to prevent linking errors.
extern "C" {
#include "enforcer/setup_cmd.h"
#include "policy/update_kasp_task.h"
#include "policy/policy_resalt_task.h"
#include "keystate/update_keyzones_task.h"
#include "shared/duration.h"
#include "shared/file.h"
#include "daemon/engine.h"
}
static const char *module_str = "setup_cmd";
/**
* Print help for the 'setup' command
*
*/
void help_setup_cmd(int sockfd)
{
char buf[ODS_SE_MAXLINE];
(void) snprintf(buf, ODS_SE_MAXLINE,
"setup delete existing database files and then perform:\n"
" update kasp\n"
" policy resalt\n"
" update zonelist\n"
);
ods_writen(sockfd, buf, strlen(buf));
}
/**
* Handle the 'setup' command.
*
*/
int handled_setup_cmd(int sockfd, engine_type* engine,
const char *cmd, ssize_t n)
{
char buf[ODS_SE_MAXLINE];
const char *scmd = "setup";
ssize_t ncmd = strlen(scmd);
if (n < ncmd || strncmp(cmd, scmd, ncmd) != 0) return 0;
ods_log_debug("[%s] %s command", module_str, scmd);
if (cmd[ncmd] == '\0') {
cmd = "";
} else if (cmd[ncmd] != ' ') {
return 0;
} else {
cmd = &cmd[ncmd+1];
}
time_t tstart = time(NULL);
const char *datastore = engine->config->datastore;
std::string policy_pb = std::string(datastore) + ".policy.pb";
std::string keystate_pb = std::string(datastore) + ".keystate.pb";
std::string hsmkey_pb = std::string(datastore) + ".hsmkey.pb";
if (unlink(policy_pb.c_str())==-1) {
ods_log_error("[%s] unlink of \"%s\" failed: %s",
module_str,policy_pb.c_str(),strerror(errno));
(void)snprintf(buf, ODS_SE_MAXLINE, "unlink of \"%s\" failed: %s\n",
policy_pb.c_str(),strerror(errno));
ods_writen(sockfd, buf, strlen(buf));
}
if (unlink(keystate_pb.c_str())==-1) {
ods_log_error("[%s] unlink of \"%s\" failed: %s",
module_str,keystate_pb.c_str(),strerror(errno));
(void)snprintf(buf, ODS_SE_MAXLINE, "unlink of \"%s\" failed: %s\n",
keystate_pb.c_str(),strerror(errno));
ods_writen(sockfd, buf, strlen(buf));
}
if (unlink(hsmkey_pb.c_str())==-1) {
ods_log_error("[%s] unlink of \"%s\" failed: %s",
module_str,hsmkey_pb.c_str(),strerror(errno));
(void)snprintf(buf, ODS_SE_MAXLINE, "unlink of \"%s\" failed: %s\n",
hsmkey_pb.c_str(),strerror(errno));
ods_writen(sockfd, buf, strlen(buf));
}
perform_update_kasp(sockfd, engine->config);
perform_policy_resalt(sockfd, engine->config);
perform_update_keyzones(sockfd, engine->config);
(void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
scmd,time(NULL)-tstart);
ods_writen(sockfd, buf, strlen(buf));
return 1;
}
<|endoftext|> |
<commit_before>#include <string>
#include <stdio.h>
#include <tag.h>
#include <tstringlist.h>
#include <tbytevectorlist.h>
#include <tpropertymap.h>
#include <apetag.h>
#include <tdebug.h>
#include <cppunit/extensions/HelperMacros.h>
#include "utils.h"
using namespace std;
using namespace TagLib;
class TestAPETag : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(TestAPETag);
CPPUNIT_TEST(testIsEmpty);
CPPUNIT_TEST(testIsEmpty2);
CPPUNIT_TEST(testPropertyInterface1);
CPPUNIT_TEST(testPropertyInterface2);
CPPUNIT_TEST(testInvalidKeys);
CPPUNIT_TEST_SUITE_END();
public:
void testIsEmpty()
{
APE::Tag tag;
CPPUNIT_ASSERT(tag.isEmpty());
tag.addValue("COMPOSER", "Mike Oldfield");
CPPUNIT_ASSERT(!tag.isEmpty());
}
void testIsEmpty2()
{
APE::Tag tag;
CPPUNIT_ASSERT(tag.isEmpty());
tag.setArtist("Mike Oldfield");
CPPUNIT_ASSERT(!tag.isEmpty());
}
void testPropertyInterface1()
{
APE::Tag tag;
PropertyMap dict = tag.properties();
CPPUNIT_ASSERT(dict.isEmpty());
dict["ARTIST"] = String("artist 1");
dict["ARTIST"].append("artist 2");
dict["TRACKNUMBER"].append("17");
tag.setProperties(dict);
CPPUNIT_ASSERT_EQUAL(String("17"), tag.itemListMap()["TRACK"].values()[0]);
CPPUNIT_ASSERT_EQUAL(2u, tag.itemListMap()["ARTIST"].values().size());
CPPUNIT_ASSERT_EQUAL(String("artist 1"), tag.artist());
CPPUNIT_ASSERT_EQUAL(17u, tag.track());
}
void testPropertyInterface2()
{
APE::Tag tag;
APE::Item item1 = APE::Item("TRACK", "17");
tag.setItem("TRACK", item1);
APE::Item item2 = APE::Item();
item2.setType(APE::Item::Binary);
tag.setItem("TESTBINARY", item2);
PropertyMap properties = tag.properties();
CPPUNIT_ASSERT_EQUAL(1u, properties.unsupportedData().size());
CPPUNIT_ASSERT(properties.contains("TRACKNUMBER"));
CPPUNIT_ASSERT(!properties.contains("TRACK"));
CPPUNIT_ASSERT(tag.itemListMap().contains("TESTBINARY"));
tag.removeUnsupportedProperties(properties.unsupportedData());
CPPUNIT_ASSERT(!tag.itemListMap().contains("TESTBINARY"));
APE::Item item3 = APE::Item("TRACKNUMBER", "29");
tag.setItem("TRACKNUMBER", item3);
properties = tag.properties();
CPPUNIT_ASSERT_EQUAL(TagLib::uint(2), properties["TRACKNUMBER"].size());
CPPUNIT_ASSERT_EQUAL(String("17"), properties["TRACKNUMBER"][0]);
CPPUNIT_ASSERT_EQUAL(String("29"), properties["TRACKNUMBER"][1]);
}
void testInvalidKeys()
{
PropertyMap properties;
properties["A"] = String("invalid key: one character");
properties["MP+"] = String("invalid key: forbidden string");
properties["A B~C"] = String("valid key: space and tilde");
properties["ARTIST"] = String("valid key: normal one");
APE::Tag tag;
PropertyMap unsuccessful = tag.setProperties(properties);
CPPUNIT_ASSERT_EQUAL(TagLib::uint(2), unsuccessful.size());
CPPUNIT_ASSERT(unsuccessful.contains("A"));
CPPUNIT_ASSERT(unsuccessful.contains("MP+"));
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestAPETag);
<commit_msg>Added a test for APE::Item<commit_after>#include <string>
#include <stdio.h>
#include <tag.h>
#include <tstringlist.h>
#include <tbytevectorlist.h>
#include <tpropertymap.h>
#include <apetag.h>
#include <tdebug.h>
#include <cppunit/extensions/HelperMacros.h>
#include "utils.h"
using namespace std;
using namespace TagLib;
class TestAPETag : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(TestAPETag);
CPPUNIT_TEST(testIsEmpty);
CPPUNIT_TEST(testIsEmpty2);
CPPUNIT_TEST(testPropertyInterface1);
CPPUNIT_TEST(testPropertyInterface2);
CPPUNIT_TEST(testInvalidKeys);
CPPUNIT_TEST(testTextBinary);
CPPUNIT_TEST_SUITE_END();
public:
void testIsEmpty()
{
APE::Tag tag;
CPPUNIT_ASSERT(tag.isEmpty());
tag.addValue("COMPOSER", "Mike Oldfield");
CPPUNIT_ASSERT(!tag.isEmpty());
}
void testIsEmpty2()
{
APE::Tag tag;
CPPUNIT_ASSERT(tag.isEmpty());
tag.setArtist("Mike Oldfield");
CPPUNIT_ASSERT(!tag.isEmpty());
}
void testPropertyInterface1()
{
APE::Tag tag;
PropertyMap dict = tag.properties();
CPPUNIT_ASSERT(dict.isEmpty());
dict["ARTIST"] = String("artist 1");
dict["ARTIST"].append("artist 2");
dict["TRACKNUMBER"].append("17");
tag.setProperties(dict);
CPPUNIT_ASSERT_EQUAL(String("17"), tag.itemListMap()["TRACK"].values()[0]);
CPPUNIT_ASSERT_EQUAL(2u, tag.itemListMap()["ARTIST"].values().size());
CPPUNIT_ASSERT_EQUAL(String("artist 1"), tag.artist());
CPPUNIT_ASSERT_EQUAL(17u, tag.track());
}
void testPropertyInterface2()
{
APE::Tag tag;
APE::Item item1 = APE::Item("TRACK", "17");
tag.setItem("TRACK", item1);
APE::Item item2 = APE::Item();
item2.setType(APE::Item::Binary);
tag.setItem("TESTBINARY", item2);
PropertyMap properties = tag.properties();
CPPUNIT_ASSERT_EQUAL(1u, properties.unsupportedData().size());
CPPUNIT_ASSERT(properties.contains("TRACKNUMBER"));
CPPUNIT_ASSERT(!properties.contains("TRACK"));
CPPUNIT_ASSERT(tag.itemListMap().contains("TESTBINARY"));
tag.removeUnsupportedProperties(properties.unsupportedData());
CPPUNIT_ASSERT(!tag.itemListMap().contains("TESTBINARY"));
APE::Item item3 = APE::Item("TRACKNUMBER", "29");
tag.setItem("TRACKNUMBER", item3);
properties = tag.properties();
CPPUNIT_ASSERT_EQUAL(TagLib::uint(2), properties["TRACKNUMBER"].size());
CPPUNIT_ASSERT_EQUAL(String("17"), properties["TRACKNUMBER"][0]);
CPPUNIT_ASSERT_EQUAL(String("29"), properties["TRACKNUMBER"][1]);
}
void testInvalidKeys()
{
PropertyMap properties;
properties["A"] = String("invalid key: one character");
properties["MP+"] = String("invalid key: forbidden string");
properties["A B~C"] = String("valid key: space and tilde");
properties["ARTIST"] = String("valid key: normal one");
APE::Tag tag;
PropertyMap unsuccessful = tag.setProperties(properties);
CPPUNIT_ASSERT_EQUAL(TagLib::uint(2), unsuccessful.size());
CPPUNIT_ASSERT(unsuccessful.contains("A"));
CPPUNIT_ASSERT(unsuccessful.contains("MP+"));
}
void testTextBinary()
{
APE::Item item = APE::Item("DUMMY", "Test Text");
CPPUNIT_ASSERT_EQUAL(String("Test Text"), item.toString());
CPPUNIT_ASSERT_EQUAL(ByteVector::null, item.binaryData());
ByteVector data("Test Data");
item.setBinaryData(data);
CPPUNIT_ASSERT(item.values().isEmpty());
CPPUNIT_ASSERT_EQUAL(String::null, item.toString());
CPPUNIT_ASSERT_EQUAL(data, item.binaryData());
item.setValue("Test Text 2");
CPPUNIT_ASSERT_EQUAL(String("Test Text 2"), item.toString());
CPPUNIT_ASSERT_EQUAL(ByteVector::null, item.binaryData());
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestAPETag);
<|endoftext|> |
<commit_before>#include <bitbots_ros_control/core_hardware_interface.h>
namespace bitbots_ros_control {
CoreHardwareInterface::CoreHardwareInterface(std::shared_ptr<DynamixelDriver> &driver,
int id, int read_rate) {
driver_ = driver;
id_ = id;
read_rate_ = read_rate;
read_counter_ = 0;
requested_power_switch_status_ = true;
power_switch_status_.data = false;
power_switch_status_ = std_msgs::Bool();
VCC_ = std_msgs::Float64();
VBAT_ = std_msgs::Float64();
VEXT_ = std_msgs::Float64();
VDXL_ = std_msgs::Float64();
current_ = std_msgs::Float64();
}
bool CoreHardwareInterface::switch_power(std_srvs::SetBoolRequest &req, std_srvs::SetBoolResponse &resp) {
requested_power_switch_status_ = req.data;
// wait for main loop to set value
resp.success = true;
return true;
}
bool CoreHardwareInterface::init(ros::NodeHandle &nh, ros::NodeHandle &hw_nh) {
nh_ = nh;
data_ = (uint8_t *) malloc(16 * sizeof(uint8_t));
power_pub_ = nh.advertise<std_msgs::Bool>("/core/power_switch_status", 1);
vcc_pub_ = nh.advertise<std_msgs::Float64>("/core/vcc", 1);
vbat_pub_ = nh.advertise<std_msgs::Float64>("/core/vbat", 1);
vext_pub_ = nh.advertise<std_msgs::Float64>("/core/vext", 1);
vdxl_pub_ = nh.advertise<std_msgs::Float64>("/core/vdxl", 1);
current_pub_ = nh.advertise<std_msgs::Float64>("/core/current", 1);
diagnostic_pub_ = nh.advertise<diagnostic_msgs::DiagnosticArray>("/diagnostics", 10, true);
// service to switch power
power_switch_service_ = nh_.advertiseService("/core/switch_power", &CoreHardwareInterface::switch_power, this);
return true;
}
void CoreHardwareInterface::read(const ros::Time &t, const ros::Duration &dt) {
/**
* Reads the CORE board
*/
if (read_counter_ % read_rate_ == 0) {
read_counter_ = 0;
// read core
bool read_successful = true;
if (driver_->readMultipleRegisters(id_, 28, 22, data_)) {
// we read one string of bytes. see CORE firmware for definition of registers
// convert to volt
VEXT_.data = (((float) dxlMakeword(data_[0], data_[1])) * (3.3 / 1024)) * 6;
VCC_.data = (((float) dxlMakeword(data_[2], data_[3])) * (3.3 / 1024)) * 6;
VDXL_.data = (((float) dxlMakeword(data_[4], data_[5])) * (3.3 / 1024)) * 6;
// convert to ampere. first go to voltage by 1024*3.3. shift by 2.5 and mulitply by volt/ampere
current_.data = ((((float) dxlMakeword(data_[6], data_[7])) * (3.3 / 1024)) - 2.5) / -0.066;
// we need to apply a threshold on this to see if power is on or off
power_switch_status_.data = dxlMakeword(data_[8], data_[9];
//TODO cell voltages
power_pub_.publish(power_switch_status_);
vcc_pub_.publish(VCC_);
vbat_pub_.publish(VBAT_);
vext_pub_.publish(VEXT_);
vdxl_pub_.publish(VDXL_);
current_pub_.publish(current_);
} else {
ROS_ERROR_THROTTLE(3.0, "Could not read CORE sensor");
read_successful = false;
}
// diagnostics. check if values are changing, otherwise there is a connection error on the board
diagnostic_msgs::DiagnosticArray array_msg = diagnostic_msgs::DiagnosticArray();
std::vector<diagnostic_msgs::DiagnosticStatus> array = std::vector<diagnostic_msgs::DiagnosticStatus>();
array_msg.header.stamp = ros::Time::now();
diagnostic_msgs::DiagnosticStatus status = diagnostic_msgs::DiagnosticStatus();
// add prefix CORE to sort in diagnostic analyser
status.name = "CORECORE";
status.hardware_id = std::to_string(id_);
std::map<std::string, std::string> map;
if (power_switch_status_.data) {
map.insert(std::make_pair("power_switch_status", "ON"));
} else {
map.insert(std::make_pair("power_switch_status", "OFF"));
}
map.insert(std::make_pair("VCC", std::to_string(VCC_.data)));
map.insert(std::make_pair("VBAT", std::to_string(VBAT_.data)));
map.insert(std::make_pair("VEXT", std::to_string(VEXT_.data)));
map.insert(std::make_pair("VDXL", std::to_string(VDXL_.data)));
map.insert(std::make_pair("Current", std::to_string(current_.data)));
if (read_successful) {
status.level = diagnostic_msgs::DiagnosticStatus::OK;
status.message = "OK";
} else {
status.level = diagnostic_msgs::DiagnosticStatus::STALE;
status.message = "No response";
}
std::vector<diagnostic_msgs::KeyValue> keyValues = std::vector<diagnostic_msgs::KeyValue>();
// iterate through map and save it into values
for (auto const &ent1 : map) {
diagnostic_msgs::KeyValue key_value = diagnostic_msgs::KeyValue();
key_value.key = ent1.first;
key_value.value = ent1.second;
keyValues.push_back(key_value);
}
status.values = keyValues;
array.push_back(status);
array_msg.status = array;
diagnostic_pub_.publish(array_msg);
}
read_counter_++;
}
void CoreHardwareInterface::write(const ros::Time &t, const ros::Duration &dt) {
// we only need to write something if requested power status and current power status do not match
if (requested_power_switch_status_ != power_switch_status_.data) {
driver_->writeRegister(id_, "Power", requested_power_switch_status_);
power_switch_status_.data = requested_power_switch_status_;
}
}
}
<commit_msg>ros_control: syntax error :(<commit_after>#include <bitbots_ros_control/core_hardware_interface.h>
namespace bitbots_ros_control {
CoreHardwareInterface::CoreHardwareInterface(std::shared_ptr<DynamixelDriver> &driver,
int id, int read_rate) {
driver_ = driver;
id_ = id;
read_rate_ = read_rate;
read_counter_ = 0;
requested_power_switch_status_ = true;
power_switch_status_.data = false;
power_switch_status_ = std_msgs::Bool();
VCC_ = std_msgs::Float64();
VBAT_ = std_msgs::Float64();
VEXT_ = std_msgs::Float64();
VDXL_ = std_msgs::Float64();
current_ = std_msgs::Float64();
}
bool CoreHardwareInterface::switch_power(std_srvs::SetBoolRequest &req, std_srvs::SetBoolResponse &resp) {
requested_power_switch_status_ = req.data;
// wait for main loop to set value
resp.success = true;
return true;
}
bool CoreHardwareInterface::init(ros::NodeHandle &nh, ros::NodeHandle &hw_nh) {
nh_ = nh;
data_ = (uint8_t *) malloc(16 * sizeof(uint8_t));
power_pub_ = nh.advertise<std_msgs::Bool>("/core/power_switch_status", 1);
vcc_pub_ = nh.advertise<std_msgs::Float64>("/core/vcc", 1);
vbat_pub_ = nh.advertise<std_msgs::Float64>("/core/vbat", 1);
vext_pub_ = nh.advertise<std_msgs::Float64>("/core/vext", 1);
vdxl_pub_ = nh.advertise<std_msgs::Float64>("/core/vdxl", 1);
current_pub_ = nh.advertise<std_msgs::Float64>("/core/current", 1);
diagnostic_pub_ = nh.advertise<diagnostic_msgs::DiagnosticArray>("/diagnostics", 10, true);
// service to switch power
power_switch_service_ = nh_.advertiseService("/core/switch_power", &CoreHardwareInterface::switch_power, this);
return true;
}
void CoreHardwareInterface::read(const ros::Time &t, const ros::Duration &dt) {
/**
* Reads the CORE board
*/
if (read_counter_ % read_rate_ == 0) {
read_counter_ = 0;
// read core
bool read_successful = true;
if (driver_->readMultipleRegisters(id_, 28, 22, data_)) {
// we read one string of bytes. see CORE firmware for definition of registers
// convert to volt
VEXT_.data = (((float) dxlMakeword(data_[0], data_[1])) * (3.3 / 1024)) * 6;
VCC_.data = (((float) dxlMakeword(data_[2], data_[3])) * (3.3 / 1024)) * 6;
VDXL_.data = (((float) dxlMakeword(data_[4], data_[5])) * (3.3 / 1024)) * 6;
// convert to ampere. first go to voltage by 1024*3.3. shift by 2.5 and mulitply by volt/ampere
current_.data = ((((float) dxlMakeword(data_[6], data_[7])) * (3.3 / 1024)) - 2.5) / -0.066;
// we need to apply a threshold on this to see if power is on or off
power_switch_status_.data = dxlMakeword(data_[8], data_[9]);
//TODO cell voltages
power_pub_.publish(power_switch_status_);
vcc_pub_.publish(VCC_);
vbat_pub_.publish(VBAT_);
vext_pub_.publish(VEXT_);
vdxl_pub_.publish(VDXL_);
current_pub_.publish(current_);
} else {
ROS_ERROR_THROTTLE(3.0, "Could not read CORE sensor");
read_successful = false;
}
// diagnostics. check if values are changing, otherwise there is a connection error on the board
diagnostic_msgs::DiagnosticArray array_msg = diagnostic_msgs::DiagnosticArray();
std::vector<diagnostic_msgs::DiagnosticStatus> array = std::vector<diagnostic_msgs::DiagnosticStatus>();
array_msg.header.stamp = ros::Time::now();
diagnostic_msgs::DiagnosticStatus status = diagnostic_msgs::DiagnosticStatus();
// add prefix CORE to sort in diagnostic analyser
status.name = "CORECORE";
status.hardware_id = std::to_string(id_);
std::map<std::string, std::string> map;
if (power_switch_status_.data) {
map.insert(std::make_pair("power_switch_status", "ON"));
} else {
map.insert(std::make_pair("power_switch_status", "OFF"));
}
map.insert(std::make_pair("VCC", std::to_string(VCC_.data)));
map.insert(std::make_pair("VBAT", std::to_string(VBAT_.data)));
map.insert(std::make_pair("VEXT", std::to_string(VEXT_.data)));
map.insert(std::make_pair("VDXL", std::to_string(VDXL_.data)));
map.insert(std::make_pair("Current", std::to_string(current_.data)));
if (read_successful) {
status.level = diagnostic_msgs::DiagnosticStatus::OK;
status.message = "OK";
} else {
status.level = diagnostic_msgs::DiagnosticStatus::STALE;
status.message = "No response";
}
std::vector<diagnostic_msgs::KeyValue> keyValues = std::vector<diagnostic_msgs::KeyValue>();
// iterate through map and save it into values
for (auto const &ent1 : map) {
diagnostic_msgs::KeyValue key_value = diagnostic_msgs::KeyValue();
key_value.key = ent1.first;
key_value.value = ent1.second;
keyValues.push_back(key_value);
}
status.values = keyValues;
array.push_back(status);
array_msg.status = array;
diagnostic_pub_.publish(array_msg);
}
read_counter_++;
}
void CoreHardwareInterface::write(const ros::Time &t, const ros::Duration &dt) {
// we only need to write something if requested power status and current power status do not match
if (requested_power_switch_status_ != power_switch_status_.data) {
driver_->writeRegister(id_, "Power", requested_power_switch_status_);
power_switch_status_.data = requested_power_switch_status_;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(RXCPP_RX_SCHEDULER_VIRTUAL_TIME_HPP)
#define RXCPP_RX_SCHEDULER_VIRTUAL_TIME_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace schedulers {
namespace detail {
template<class Absolute, class Relative>
struct virtual_time_base : std::enable_shared_from_this<virtual_time_base<Absolute, Relative>>
{
private:
typedef virtual_time_base<Absolute, Relative> this_type;
virtual_time_base(const virtual_time_base&);
mutable bool isenabled;
public:
typedef Absolute absolute;
typedef Relative relative;
virtual ~virtual_time_base()
{
}
protected:
virtual_time_base()
: isenabled(false)
, clock_now(0)
{
}
explicit virtual_time_base(absolute initialClock)
: isenabled(false)
, clock_now(initialClock)
{
}
mutable absolute clock_now;
typedef time_schedulable<long> item_type;
virtual absolute add(absolute, relative) const =0;
virtual typename scheduler_base::clock_type::time_point to_time_point(absolute) const =0;
virtual relative to_relative(typename scheduler_base::clock_type::duration) const =0;
virtual item_type top() const =0;
virtual void pop() const =0;
virtual bool empty() const =0;
public:
virtual void schedule_absolute(absolute, const schedulable&) const =0;
virtual void schedule_relative(relative when, const schedulable& a) const {
auto at = add(clock_now, when);
return schedule_absolute(at, a);
}
bool is_enabled() const {return isenabled;}
absolute clock() const {return clock_now;}
void start() const
{
if (!isenabled) {
isenabled = true;
rxsc::recursion r;
r.reset(false);
while (!empty() && isenabled) {
auto next = top();
pop();
if (next.what.is_subscribed()) {
if (next.when > clock_now) {
clock_now = next.when;
}
next.what(r.get_recurse());
}
else {
isenabled = false;
}
}
}
}
void stop() const
{
isenabled = false;
}
void advance_to(absolute time) const
{
if (time < clock_now) {
abort();
}
if (time == clock_now) {
return;
}
if (!isenabled) {
isenabled = true;
rxsc::recursion r;
while (!empty() && isenabled) {
auto next = top();
pop();
if (next.what.is_subscribed() && next.when <= time) {
if (next.when > clock_now) {
clock_now = next.when;
}
next.what(r.get_recurse());
}
else {
isenabled = false;
}
}
clock_now = time;
}
else {
abort();
}
}
void advance_by(relative time) const
{
auto dt = add(clock_now, time);
if (dt < clock_now) {
abort();
}
if (dt == clock_now) {
return;
}
if (!isenabled) {
advance_to(dt);
}
else {
abort();
}
}
void sleep(relative time) const
{
auto dt = add(clock_now, time);
if (dt < clock_now) {
abort();
}
clock_now = dt;
}
};
}
template<class Absolute, class Relative>
struct virtual_time : public detail::virtual_time_base<Absolute, Relative>
{
typedef detail::virtual_time_base<Absolute, Relative> base;
typedef typename base::item_type item_type;
typedef detail::schedulable_queue<
typename item_type::time_point_type> queue_item_time;
mutable queue_item_time queue;
public:
virtual ~virtual_time()
{
}
protected:
virtual_time()
{
}
explicit virtual_time(typename base::absolute initialClock)
: base(initialClock)
{
}
virtual item_type top() const {
return queue.top();
}
virtual void pop() const {
queue.pop();
}
virtual bool empty() const {
return queue.empty();
}
using base::schedule_absolute;
using base::schedule_relative;
virtual void schedule_absolute(typename base::absolute when, const schedulable& a) const
{
// use a separate subscription here so that a's subscription is not affected
auto run = make_schedulable(
a.get_worker(),
composite_subscription(),
[a](const schedulable& scbl) {
rxsc::recursion r;
r.reset(false);
if (scbl.is_subscribed()) {
scbl.unsubscribe(); // unsubscribe() run, not a;
a(r.get_recurse());
}
});
queue.push(item_type(when, run));
}
};
}
}
#endif
<commit_msg>fix bug reported in test scheduler<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(RXCPP_RX_SCHEDULER_VIRTUAL_TIME_HPP)
#define RXCPP_RX_SCHEDULER_VIRTUAL_TIME_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace schedulers {
namespace detail {
template<class Absolute, class Relative>
struct virtual_time_base : std::enable_shared_from_this<virtual_time_base<Absolute, Relative>>
{
private:
typedef virtual_time_base<Absolute, Relative> this_type;
virtual_time_base(const virtual_time_base&);
mutable bool isenabled;
public:
typedef Absolute absolute;
typedef Relative relative;
virtual ~virtual_time_base()
{
}
protected:
virtual_time_base()
: isenabled(false)
, clock_now(0)
{
}
explicit virtual_time_base(absolute initialClock)
: isenabled(false)
, clock_now(initialClock)
{
}
mutable absolute clock_now;
typedef time_schedulable<long> item_type;
virtual absolute add(absolute, relative) const =0;
virtual typename scheduler_base::clock_type::time_point to_time_point(absolute) const =0;
virtual relative to_relative(typename scheduler_base::clock_type::duration) const =0;
virtual item_type top() const =0;
virtual void pop() const =0;
virtual bool empty() const =0;
public:
virtual void schedule_absolute(absolute, const schedulable&) const =0;
virtual void schedule_relative(relative when, const schedulable& a) const {
auto at = add(clock_now, when);
return schedule_absolute(at, a);
}
bool is_enabled() const {return isenabled;}
absolute clock() const {return clock_now;}
void start() const
{
if (!isenabled) {
isenabled = true;
rxsc::recursion r;
r.reset(false);
while (!empty() && isenabled) {
auto next = top();
pop();
if (next.what.is_subscribed()) {
if (next.when > clock_now) {
clock_now = next.when;
}
next.what(r.get_recurse());
}
}
isenabled = false;
}
}
void stop() const
{
isenabled = false;
}
void advance_to(absolute time) const
{
if (time < clock_now) {
abort();
}
if (time == clock_now) {
return;
}
if (!isenabled) {
isenabled = true;
rxsc::recursion r;
while (!empty() && isenabled) {
auto next = top();
if (next.when <= time) {
pop();
if (!next.what.is_subscribed()) {
continue;
}
if (next.when > clock_now) {
clock_now = next.when;
}
next.what(r.get_recurse());
}
else {
break;
}
}
isenabled = false;
clock_now = time;
}
else {
abort();
}
}
void advance_by(relative time) const
{
auto dt = add(clock_now, time);
if (dt < clock_now) {
abort();
}
if (dt == clock_now) {
return;
}
if (!isenabled) {
advance_to(dt);
}
else {
abort();
}
}
void sleep(relative time) const
{
auto dt = add(clock_now, time);
if (dt < clock_now) {
abort();
}
clock_now = dt;
}
};
}
template<class Absolute, class Relative>
struct virtual_time : public detail::virtual_time_base<Absolute, Relative>
{
typedef detail::virtual_time_base<Absolute, Relative> base;
typedef typename base::item_type item_type;
typedef detail::schedulable_queue<
typename item_type::time_point_type> queue_item_time;
mutable queue_item_time queue;
public:
virtual ~virtual_time()
{
}
protected:
virtual_time()
{
}
explicit virtual_time(typename base::absolute initialClock)
: base(initialClock)
{
}
virtual item_type top() const {
return queue.top();
}
virtual void pop() const {
queue.pop();
}
virtual bool empty() const {
return queue.empty();
}
using base::schedule_absolute;
using base::schedule_relative;
virtual void schedule_absolute(typename base::absolute when, const schedulable& a) const
{
// use a separate subscription here so that a's subscription is not affected
auto run = make_schedulable(
a.get_worker(),
composite_subscription(),
[a](const schedulable& scbl) {
rxsc::recursion r;
r.reset(false);
if (scbl.is_subscribed()) {
scbl.unsubscribe(); // unsubscribe() run, not a;
a(r.get_recurse());
}
});
queue.push(item_type(when, run));
}
};
}
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: implrenderer.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2005-03-10 13:23:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CPPCANVAS_IMPLRENDERER_HXX
#define _CPPCANVAS_IMPLRENDERER_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#ifndef _CPPCANVAS_RENDERER_HXX
#include <cppcanvas/renderer.hxx>
#endif
#ifndef _CPPCANVAS_CANVAS_HXX
#include <cppcanvas/canvas.hxx>
#endif
#include <canvasgraphichelper.hxx>
#include <action.hxx>
#include <vector>
class GDIMetaFile;
class BitmapEx;
class VirtualDevice;
class Gradient;
namespace cppcanvas
{
namespace internal
{
struct OutDevState;
// state stack of OutputDevice, to correctly handle
// push/pop actions
typedef ::std::vector< OutDevState > VectorOfOutDevStates;
class ImplRenderer : public virtual Renderer, protected CanvasGraphicHelper
{
public:
ImplRenderer( const CanvasSharedPtr& rCanvas,
const GDIMetaFile& rMtf,
const Parameters& rParms );
ImplRenderer( const CanvasSharedPtr& rCanvas,
const BitmapEx& rBmpEx,
const Parameters& rParms );
virtual ~ImplRenderer();
virtual bool draw() const;
virtual bool drawSubset( int nStartIndex,
int nEndIndex ) const;
// element of the Renderer's action vector. Need to be
// public, since some functors need it, too.
struct MtfAction
{
MtfAction( const ActionSharedPtr& rAction,
int nOrigIndex ) :
mpAction( rAction ),
mnOrigIndex( nOrigIndex )
{
}
ActionSharedPtr mpAction;
int mnOrigIndex;
};
private:
// default: disabled copy/assignment
ImplRenderer(const ImplRenderer&);
ImplRenderer& operator=( const ImplRenderer& );
void updateClipping( VectorOfOutDevStates& rStates,
const ::basegfx::B2DPolyPolygon& rClipPoly,
const CanvasSharedPtr& rCanvas,
bool bIntersect );
void updateClipping( VectorOfOutDevStates& rStates,
const ::Rectangle& rClipRect,
const CanvasSharedPtr& rCanvas,
bool bIntersect );
::com::sun::star::uno::Reference<
::com::sun::star::rendering::XCanvasFont > createFont( ::basegfx::B2DHomMatrix& o_rFontMatrix,
const ::Font& rFont,
const CanvasSharedPtr& rCanvas,
const ::VirtualDevice& rVDev,
const Parameters& rParms ) const;
bool createActions( const CanvasSharedPtr& rCanvas,
VirtualDevice& rVDev,
GDIMetaFile& rMtf,
VectorOfOutDevStates& rStates,
const Parameters& rParms,
int& io_rCurrActionIndex );
bool createFillAndStroke( const ::PolyPolygon& rPolyPoly,
const CanvasSharedPtr& rCanvas,
int rActionIndex,
VectorOfOutDevStates& rStates );
void skipContent( GDIMetaFile& rMtf,
const char& rCommentString ) const;
void createGradientAction( const ::PolyPolygon& rPoly,
const ::Gradient& rGradient,
::VirtualDevice& rVDev,
const CanvasSharedPtr& rCanvas,
VectorOfOutDevStates& rStates,
const Parameters& rParms,
int& io_rCurrActionIndex,
bool bIsPolygonRectangle );
// create text effects such as shadow/relief/embossed
void createTextWithEffectsAction(
const Point& rStartPoint,
const String rString,
int nIndex,
int nLength,
const long* pCharWidths,
VirtualDevice& rVDev,
const CanvasSharedPtr& rCanvas,
VectorOfOutDevStates& rStates,
const Parameters& rParms,
int nCurrActionIndex );
// create text draw actions and add text lines
void createTextWithLinesAction(
const Point& rStartPoint,
const String rString,
int nIndex,
int nLength,
const long* pCharWidths,
VirtualDevice& rVDev,
const CanvasSharedPtr& rCanvas,
VectorOfOutDevStates& rStates,
const Parameters& rParms,
int nCurrActionIndex );
// create text lines such as underline and strikeout
void createJustTextLinesAction(
const Point& rStartPoint,
long nLineWidth,
VirtualDevice& rVDev,
const CanvasSharedPtr& rCanvas,
VectorOfOutDevStates& rStates,
const Parameters& rParms,
int nCurrActionIndex );
// prefetched and prepared canvas actions
// (externally not visible)
typedef ::std::vector< MtfAction > ActionVector;
ActionVector maActions;
};
}
}
#endif /* _CPPCANVAS_IMPLRENDERER_HXX */
<commit_msg>INTEGRATION: CWS presfixes02 (1.6.2); FILE MERGED 2005/03/18 18:56:38 thb 1.6.2.3: #i44515# Finished subsetting rework (now drawSubset() does the right thing for various border cases) 2005/03/16 17:40:28 thb 1.6.2.2: #i35136# For bitmap textures with a transparent gradient, falling back to TransparencyGroupAction (XCanvas currently cannot handle both alpha gradient and texture) 2005/03/14 16:04:51 thb 1.6.2.1: #i35136# #i36914# #i41113# #i44100# #i40115# #i41839# #i44404# Merge from presfixes01 patches<commit_after>/*************************************************************************
*
* $RCSfile: implrenderer.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-03-30 08:24:58 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CPPCANVAS_IMPLRENDERER_HXX
#define _CPPCANVAS_IMPLRENDERER_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#ifndef _CPPCANVAS_RENDERER_HXX
#include <cppcanvas/renderer.hxx>
#endif
#ifndef _CPPCANVAS_CANVAS_HXX
#include <cppcanvas/canvas.hxx>
#endif
#include <canvasgraphichelper.hxx>
#include <action.hxx>
#include <vector>
class GDIMetaFile;
class BitmapEx;
class VirtualDevice;
class Gradient;
namespace cppcanvas
{
namespace internal
{
struct OutDevState;
// state stack of OutputDevice, to correctly handle
// push/pop actions
typedef ::std::vector< OutDevState > VectorOfOutDevStates;
class ImplRenderer : public virtual Renderer, protected CanvasGraphicHelper
{
public:
ImplRenderer( const CanvasSharedPtr& rCanvas,
const GDIMetaFile& rMtf,
const Parameters& rParms );
ImplRenderer( const CanvasSharedPtr& rCanvas,
const BitmapEx& rBmpEx,
const Parameters& rParms );
virtual ~ImplRenderer();
virtual bool draw() const;
virtual bool drawSubset( sal_Int32 nStartIndex,
sal_Int32 nEndIndex ) const;
// element of the Renderer's action vector. Need to be
// public, since some functors need it, too.
struct MtfAction
{
MtfAction( const ActionSharedPtr& rAction,
sal_Int32 nOrigIndex ) :
mpAction( rAction ),
mnOrigIndex( nOrigIndex )
{
}
ActionSharedPtr mpAction;
sal_Int32 mnOrigIndex;
};
private:
// default: disabled copy/assignment
ImplRenderer(const ImplRenderer&);
ImplRenderer& operator=( const ImplRenderer& );
void updateClipping( VectorOfOutDevStates& rStates,
const ::basegfx::B2DPolyPolygon& rClipPoly,
const CanvasSharedPtr& rCanvas,
bool bIntersect );
void updateClipping( VectorOfOutDevStates& rStates,
const ::Rectangle& rClipRect,
const CanvasSharedPtr& rCanvas,
bool bIntersect );
::com::sun::star::uno::Reference<
::com::sun::star::rendering::XCanvasFont > createFont( double& o_rFontRotation,
const ::Font& rFont,
const CanvasSharedPtr& rCanvas,
const ::VirtualDevice& rVDev,
const Parameters& rParms ) const;
bool createActions( const CanvasSharedPtr& rCanvas,
VirtualDevice& rVDev,
GDIMetaFile& rMtf,
VectorOfOutDevStates& rStates,
const Parameters& rParms,
bool bSubsettableActions,
sal_Int32& io_rCurrActionIndex );
bool createFillAndStroke( const ::PolyPolygon& rPolyPoly,
const CanvasSharedPtr& rCanvas,
sal_Int32& rActionIndex,
const VectorOfOutDevStates& rStates );
void skipContent( GDIMetaFile& rMtf,
const char* pCommentString,
sal_Int32& io_rCurrActionIndex ) const;
bool isActionContained( GDIMetaFile& rMtf,
const char* pCommentString,
USHORT nType ) const;
void createGradientAction( const ::PolyPolygon& rPoly,
const ::Gradient& rGradient,
::VirtualDevice& rVDev,
const CanvasSharedPtr& rCanvas,
VectorOfOutDevStates& rStates,
const Parameters& rParms,
sal_Int32& io_rCurrActionIndex,
bool bIsPolygonRectangle,
bool bSubsettableActions );
void createTextAction( const ::Point& rStartPoint,
const String rString,
int nIndex,
int nLength,
const sal_Int32* pCharWidths,
::VirtualDevice& rVDev,
const CanvasSharedPtr& rCanvas,
const VectorOfOutDevStates& rStates,
const Parameters& rParms,
bool bSubsettable,
sal_Int32& io_rCurrActionIndex );
// prefetched and prepared canvas actions
// (externally not visible)
typedef ::std::vector< MtfAction > ActionVector;
ActionVector maActions;
};
}
}
#endif /* _CPPCANVAS_IMPLRENDERER_HXX */
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017 Darren Smith
*
* wampcc is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "wampcc/wampcc.h"
#include <memory>
#include <iostream>
using namespace wampcc;
using namespace std;
int main(int argc, char** argv)
{
try {
/* Create the wampcc kernel. */
kernel the_kernel;
/* Create the embedded wamp router. */
wamp_router router(&the_kernel, nullptr);
/* Listen for clients on IPv4 port, no authentication. */
auto fut = router.listen(auth_provider::no_auth_required(), 55555);
if (auto ec = fut.get())
throw runtime_error(ec.message());
/* Provide an RPC */
router.provide(
"default_realm", "greeting", {},
[](wamp_invocation& invocation) {
invocation.yield({"hello"});
});
/* Suspend main thread */
promise<void> unset;
unset.get_future().wait();
return 0;
}
catch (const exception& e) {
cout << e.what() << endl;
return 1;
}
}
<commit_msg>tidy up<commit_after>/*
* Copyright (c) 2017 Darren Smith
*
* wampcc is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "wampcc/wampcc.h"
#include <memory>
#include <iostream>
using namespace wampcc;
using namespace std;
int main(int argc, char** argv)
{
try {
/* Create the wampcc kernel. */
kernel the_kernel;
/* Create the embedded wamp router. */
wamp_router router(&the_kernel, nullptr);
/* Accept clients on IPv4 port, without authentication. */
auto fut = router.listen(auth_provider::no_auth_required(), 55555);
if (auto ec = fut.get())
throw runtime_error(ec.message());
/* Provide an RPC. */
router.provide("default_realm", "greeting", {},
[](wamp_invocation& invocation) {
invocation.yield({"hello"});
});
/* Suspend main thread */
promise<void> unset;
unset.get_future().wait();
return 0;
}
catch (const exception& e) {
cout << e.what() << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 Felix Rieseberg <feriese@microsoft.com> and Jason Poon <jason.poon@microsoft.com>. All rights reserved.
// Copyright (c) 2015 Ryan McShane <rmcshane@bandwidth.com> and Brandon Smith <bsmith@bandwidth.com>
// Thanks to both of those folks mentioned above who first thought up a bunch of this code
// and released it as MIT to the world.
#include "browser/win/windows_toast_notification.h"
#include <shlobj.h>
#include "base/strings/utf_string_conversions.h"
#include "browser/notification_delegate.h"
#include "browser/win/scoped_hstring.h"
#include "browser/win/notification_presenter_win.h"
#include "common/application_info.h"
using namespace ABI::Windows::Data::Xml::Dom;
namespace brightray {
namespace {
bool GetAppUserModelId(ScopedHString* app_id) {
PWSTR current_app_id;
if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(¤t_app_id))) {
app_id->Reset(current_app_id);
CoTaskMemFree(current_app_id);
} else {
app_id->Reset(base::UTF8ToUTF16(GetApplicationName()));
}
return app_id->success();
}
} // namespace
// static
Notification* Notification::Create(NotificationDelegate* delegate,
NotificationPresenter* presenter) {
return new WindowsToastNotification(delegate, presenter);
}
// static
ComPtr<ABI::Windows::UI::Notifications::IToastNotificationManagerStatics>
WindowsToastNotification::toast_manager_;
// static
ComPtr<ABI::Windows::UI::Notifications::IToastNotifier>
WindowsToastNotification::toast_notifier_;
// static
bool WindowsToastNotification::Initialize() {
// Just initialize, don't care if it fails or already initialized.
Windows::Foundation::Initialize(RO_INIT_MULTITHREADED);
ScopedHString toast_manager_str(
RuntimeClass_Windows_UI_Notifications_ToastNotificationManager);
if (!toast_manager_str.success())
return false;
if (FAILED(Windows::Foundation::GetActivationFactory(toast_manager_str,
&toast_manager_)))
return false;
ScopedHString app_id;
if (!GetAppUserModelId(&app_id))
return false;
return SUCCEEDED(
toast_manager_->CreateToastNotifierWithId(app_id, &toast_notifier_));
}
WindowsToastNotification::WindowsToastNotification(
NotificationDelegate* delegate,
NotificationPresenter* presenter)
: Notification(delegate, presenter) {
}
WindowsToastNotification::~WindowsToastNotification() {
// Remove the notification on exit.
if (toast_notification_) {
RemoveCallbacks(toast_notification_.Get());
Dismiss();
}
}
void WindowsToastNotification::Show(
const base::string16& title,
const base::string16& msg,
const std::string& tag,
const GURL& icon_url,
const SkBitmap& icon,
const bool silent) {
auto presenter_win = static_cast<NotificationPresenterWin*>(presenter());
std::wstring icon_path = presenter_win->SaveIconToFilesystem(icon, icon_url);
// Ask Windows for the current notification settings
// If not allowed, we return here (0 = enabled)
ABI::Windows::UI::Notifications::NotificationSetting setting;
toast_notifier_->get_Setting(&setting);
if (setting != 0) {
NotificationFailed();
return;
}
ComPtr<IXmlDocument> toast_xml;
if(FAILED(GetToastXml(toast_manager_.Get(), title, msg, icon_path, silent, &toast_xml))) {
NotificationFailed();
return;
}
ScopedHString toast_str(
RuntimeClass_Windows_UI_Notifications_ToastNotification);
if (!toast_str.success()) {
NotificationFailed();
return;
}
ComPtr<ABI::Windows::UI::Notifications::IToastNotificationFactory> toast_factory;
if (FAILED(Windows::Foundation::GetActivationFactory(toast_str,
&toast_factory))) {
NotificationFailed();
return;
}
if (FAILED(toast_factory->CreateToastNotification(toast_xml.Get(),
&toast_notification_))) {
NotificationFailed();
return;
}
if (FAILED(SetupCallbacks(toast_notification_.Get()))) {
NotificationFailed();
return;
}
if (FAILED(toast_notifier_->Show(toast_notification_.Get()))) {
NotificationFailed();
return;
}
delegate()->NotificationDisplayed();
}
void WindowsToastNotification::Dismiss() {
toast_notifier_->Hide(toast_notification_.Get());
}
void WindowsToastNotification::NotificationClicked() {
delegate()->NotificationClick();
Destroy();
}
void WindowsToastNotification::NotificationDismissed() {
delegate()->NotificationClosed();
Destroy();
}
void WindowsToastNotification::NotificationFailed() {
delegate()->NotificationFailed();
Destroy();
}
bool WindowsToastNotification::GetToastXml(
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics* toastManager,
const std::wstring& title,
const std::wstring& msg,
const std::wstring& icon_path,
const bool silent,
IXmlDocument** toast_xml) {
ABI::Windows::UI::Notifications::ToastTemplateType template_type;
if (title.empty() || msg.empty()) {
// Single line toast.
template_type = icon_path.empty() ? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText01 :
ABI::Windows::UI::Notifications::ToastTemplateType_ToastImageAndText01;
if (FAILED(toast_manager_->GetTemplateContent(template_type, toast_xml)))
return false;
if (!SetXmlText(*toast_xml, title.empty() ? msg : title))
return false;
} else {
// Title and body toast.
template_type = icon_path.empty() ? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText02 :
ABI::Windows::UI::Notifications::ToastTemplateType_ToastImageAndText02;
if (FAILED(toastManager->GetTemplateContent(template_type, toast_xml)))
return false;
if (!SetXmlText(*toast_xml, title, msg))
return false;
}
// Configure the toast's notification sound
if (silent) {
if (FAILED(SetXmlAudioSilent(*toast_xml)))
return false;
}
// Configure the toast's image
if (!icon_path.empty())
return SetXmlImage(*toast_xml, icon_path);
return true;
}
bool WindowsToastNotification::SetXmlAudioSilent(
IXmlDocument* doc) {
ScopedHString tag(L"toast");
if (!tag.success())
return false;
ComPtr<IXmlNodeList> node_list;
if (FAILED(doc->GetElementsByTagName(tag, &node_list)))
return false;
ComPtr<IXmlNode> root;
if (FAILED(node_list->Item(0, &root)))
return false;
ComPtr<IXmlElement> audio_element;
ScopedHString audio_str(L"audio");
if (FAILED(doc->CreateElement(audio_str, &audio_element)))
return false;
ComPtr<IXmlNode> audio_node_tmp;
if (FAILED(audio_element.As(&audio_node_tmp)))
return false;
// Append audio node to toast xml
ComPtr<IXmlNode> audio_node;
if (FAILED(root->AppendChild(audio_node_tmp.Get(), &audio_node)))
return false;
// Create silent attribute
ComPtr<IXmlNamedNodeMap> attributes;
if (FAILED(audio_node->get_Attributes(&attributes)))
return false;
ComPtr<IXmlAttribute> silent_attribute;
ScopedHString silent_str(L"silent");
if (FAILED(doc->CreateAttribute(silent_str, &silent_attribute)))
return false;
ComPtr<IXmlNode> silent_attribute_node;
if (FAILED(silent_attribute.As(&silent_attribute_node)))
return false;
// Set silent attribute to true
ScopedHString silent_value(L"true");
if (!silent_value.success())
return false;
ComPtr<IXmlText> silent_text;
if (FAILED(doc->CreateTextNode(silent_value, &silent_text)))
return false;
ComPtr<IXmlNode> silent_node;
if (FAILED(silent_text.As(&silent_node)))
return false;
ComPtr<IXmlNode> child_node;
if (FAILED(silent_attribute_node->AppendChild(silent_node.Get(), &child_node)))
return false;
ComPtr<IXmlNode> silent_attribute_pnode;
return SUCCEEDED(attributes.Get()->SetNamedItem(silent_attribute_node.Get(), &silent_attribute_pnode));
}
bool WindowsToastNotification::SetXmlText(
IXmlDocument* doc, const std::wstring& text) {
ScopedHString tag;
ComPtr<IXmlNodeList> node_list;
if (!GetTextNodeList(&tag, doc, &node_list, 1))
return false;
ComPtr<IXmlNode> node;
if (FAILED(node_list->Item(0, &node)))
return false;
return AppendTextToXml(doc, node.Get(), text);
}
bool WindowsToastNotification::SetXmlText(
IXmlDocument* doc, const std::wstring& title, const std::wstring& body) {
ScopedHString tag;
ComPtr<IXmlNodeList> node_list;
if (!GetTextNodeList(&tag, doc, &node_list, 2))
return false;
ComPtr<IXmlNode> node;
if (FAILED(node_list->Item(0, &node)))
return false;
if (!AppendTextToXml(doc, node.Get(), title))
return false;
if (FAILED(node_list->Item(1, &node)))
return false;
return AppendTextToXml(doc, node.Get(), body);
}
bool WindowsToastNotification::SetXmlImage(
IXmlDocument* doc, const std::wstring& icon_path) {
ScopedHString tag(L"image");
if (!tag.success())
return false;
ComPtr<IXmlNodeList> node_list;
if (FAILED(doc->GetElementsByTagName(tag, &node_list)))
return false;
ComPtr<IXmlNode> image_node;
if (FAILED(node_list->Item(0, &image_node)))
return false;
ComPtr<IXmlNamedNodeMap> attrs;
if (FAILED(image_node->get_Attributes(&attrs)))
return false;
ScopedHString src(L"src");
if (!src.success())
return false;
ComPtr<IXmlNode> src_attr;
if (FAILED(attrs->GetNamedItem(src, &src_attr)))
return false;
ScopedHString img_path(icon_path.c_str());
if (!img_path.success())
return false;
ComPtr<IXmlText> src_text;
if (FAILED(doc->CreateTextNode(img_path, &src_text)))
return false;
ComPtr<IXmlNode> src_node;
if (FAILED(src_text.As(&src_node)))
return false;
ComPtr<IXmlNode> child_node;
return SUCCEEDED(src_attr->AppendChild(src_node.Get(), &child_node));
}
bool WindowsToastNotification::GetTextNodeList(
ScopedHString* tag,
IXmlDocument* doc,
IXmlNodeList** node_list,
uint32_t req_length) {
tag->Reset(L"text");
if (!tag->success())
return false;
if (FAILED(doc->GetElementsByTagName(*tag, node_list)))
return false;
uint32_t node_length;
if (FAILED((*node_list)->get_Length(&node_length)))
return false;
return node_length >= req_length;
}
bool WindowsToastNotification::AppendTextToXml(
IXmlDocument* doc, IXmlNode* node, const std::wstring& text) {
ScopedHString str(text);
if (!str.success())
return false;
ComPtr<IXmlText> xml_text;
if (FAILED(doc->CreateTextNode(str, &xml_text)))
return false;
ComPtr<IXmlNode> text_node;
if (FAILED(xml_text.As(&text_node)))
return false;
ComPtr<IXmlNode> append_node;
return SUCCEEDED(node->AppendChild(text_node.Get(), &append_node));
}
bool WindowsToastNotification::SetupCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast) {
event_handler_ = Make<ToastEventHandler>(this);
if (FAILED(toast->add_Activated(event_handler_.Get(), &activated_token_)))
return false;
if (FAILED(toast->add_Dismissed(event_handler_.Get(), &dismissed_token_)))
return false;
return SUCCEEDED(toast->add_Failed(event_handler_.Get(), &failed_token_));
}
bool WindowsToastNotification::RemoveCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast) {
if (FAILED(toast->remove_Activated(activated_token_)))
return false;
if (FAILED(toast->remove_Dismissed(dismissed_token_)))
return false;
return SUCCEEDED(toast->remove_Failed(failed_token_));
}
/*
/ Toast Event Handler
*/
ToastEventHandler::ToastEventHandler(WindowsToastNotification* notification)
: notification_(notification) {
}
ToastEventHandler::~ToastEventHandler() {
}
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender, IInspectable* args) {
notification_->NotificationClicked();
return S_OK;
}
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastDismissedEventArgs* e) {
notification_->NotificationDismissed();
return S_OK;
}
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastFailedEventArgs* e) {
notification_->NotificationFailed();
return S_OK;
}
} // namespace brightray
<commit_msg>Do not use get_Setting to determine whether notification is enabled<commit_after>// Copyright (c) 2015 Felix Rieseberg <feriese@microsoft.com> and Jason Poon <jason.poon@microsoft.com>. All rights reserved.
// Copyright (c) 2015 Ryan McShane <rmcshane@bandwidth.com> and Brandon Smith <bsmith@bandwidth.com>
// Thanks to both of those folks mentioned above who first thought up a bunch of this code
// and released it as MIT to the world.
#include "browser/win/windows_toast_notification.h"
#include <shlobj.h>
#include "base/strings/utf_string_conversions.h"
#include "browser/notification_delegate.h"
#include "browser/win/scoped_hstring.h"
#include "browser/win/notification_presenter_win.h"
#include "common/application_info.h"
using namespace ABI::Windows::Data::Xml::Dom;
namespace brightray {
namespace {
bool GetAppUserModelId(ScopedHString* app_id) {
PWSTR current_app_id;
if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(¤t_app_id))) {
app_id->Reset(current_app_id);
CoTaskMemFree(current_app_id);
} else {
app_id->Reset(base::UTF8ToUTF16(GetApplicationName()));
}
return app_id->success();
}
} // namespace
// static
Notification* Notification::Create(NotificationDelegate* delegate,
NotificationPresenter* presenter) {
return new WindowsToastNotification(delegate, presenter);
}
// static
ComPtr<ABI::Windows::UI::Notifications::IToastNotificationManagerStatics>
WindowsToastNotification::toast_manager_;
// static
ComPtr<ABI::Windows::UI::Notifications::IToastNotifier>
WindowsToastNotification::toast_notifier_;
// static
bool WindowsToastNotification::Initialize() {
// Just initialize, don't care if it fails or already initialized.
Windows::Foundation::Initialize(RO_INIT_MULTITHREADED);
ScopedHString toast_manager_str(
RuntimeClass_Windows_UI_Notifications_ToastNotificationManager);
if (!toast_manager_str.success())
return false;
if (FAILED(Windows::Foundation::GetActivationFactory(toast_manager_str,
&toast_manager_)))
return false;
ScopedHString app_id;
if (!GetAppUserModelId(&app_id))
return false;
return SUCCEEDED(
toast_manager_->CreateToastNotifierWithId(app_id, &toast_notifier_));
}
WindowsToastNotification::WindowsToastNotification(
NotificationDelegate* delegate,
NotificationPresenter* presenter)
: Notification(delegate, presenter) {
}
WindowsToastNotification::~WindowsToastNotification() {
// Remove the notification on exit.
if (toast_notification_) {
RemoveCallbacks(toast_notification_.Get());
Dismiss();
}
}
void WindowsToastNotification::Show(
const base::string16& title,
const base::string16& msg,
const std::string& tag,
const GURL& icon_url,
const SkBitmap& icon,
const bool silent) {
auto presenter_win = static_cast<NotificationPresenterWin*>(presenter());
std::wstring icon_path = presenter_win->SaveIconToFilesystem(icon, icon_url);
ComPtr<IXmlDocument> toast_xml;
if(FAILED(GetToastXml(toast_manager_.Get(), title, msg, icon_path, silent, &toast_xml))) {
NotificationFailed();
return;
}
ScopedHString toast_str(
RuntimeClass_Windows_UI_Notifications_ToastNotification);
if (!toast_str.success()) {
NotificationFailed();
return;
}
ComPtr<ABI::Windows::UI::Notifications::IToastNotificationFactory> toast_factory;
if (FAILED(Windows::Foundation::GetActivationFactory(toast_str,
&toast_factory))) {
NotificationFailed();
return;
}
if (FAILED(toast_factory->CreateToastNotification(toast_xml.Get(),
&toast_notification_))) {
NotificationFailed();
return;
}
if (FAILED(SetupCallbacks(toast_notification_.Get()))) {
NotificationFailed();
return;
}
if (FAILED(toast_notifier_->Show(toast_notification_.Get()))) {
NotificationFailed();
return;
}
delegate()->NotificationDisplayed();
}
void WindowsToastNotification::Dismiss() {
toast_notifier_->Hide(toast_notification_.Get());
}
void WindowsToastNotification::NotificationClicked() {
delegate()->NotificationClick();
Destroy();
}
void WindowsToastNotification::NotificationDismissed() {
delegate()->NotificationClosed();
Destroy();
}
void WindowsToastNotification::NotificationFailed() {
delegate()->NotificationFailed();
Destroy();
}
bool WindowsToastNotification::GetToastXml(
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics* toastManager,
const std::wstring& title,
const std::wstring& msg,
const std::wstring& icon_path,
const bool silent,
IXmlDocument** toast_xml) {
ABI::Windows::UI::Notifications::ToastTemplateType template_type;
if (title.empty() || msg.empty()) {
// Single line toast.
template_type = icon_path.empty() ? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText01 :
ABI::Windows::UI::Notifications::ToastTemplateType_ToastImageAndText01;
if (FAILED(toast_manager_->GetTemplateContent(template_type, toast_xml)))
return false;
if (!SetXmlText(*toast_xml, title.empty() ? msg : title))
return false;
} else {
// Title and body toast.
template_type = icon_path.empty() ? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText02 :
ABI::Windows::UI::Notifications::ToastTemplateType_ToastImageAndText02;
if (FAILED(toastManager->GetTemplateContent(template_type, toast_xml)))
return false;
if (!SetXmlText(*toast_xml, title, msg))
return false;
}
// Configure the toast's notification sound
if (silent) {
if (FAILED(SetXmlAudioSilent(*toast_xml)))
return false;
}
// Configure the toast's image
if (!icon_path.empty())
return SetXmlImage(*toast_xml, icon_path);
return true;
}
bool WindowsToastNotification::SetXmlAudioSilent(
IXmlDocument* doc) {
ScopedHString tag(L"toast");
if (!tag.success())
return false;
ComPtr<IXmlNodeList> node_list;
if (FAILED(doc->GetElementsByTagName(tag, &node_list)))
return false;
ComPtr<IXmlNode> root;
if (FAILED(node_list->Item(0, &root)))
return false;
ComPtr<IXmlElement> audio_element;
ScopedHString audio_str(L"audio");
if (FAILED(doc->CreateElement(audio_str, &audio_element)))
return false;
ComPtr<IXmlNode> audio_node_tmp;
if (FAILED(audio_element.As(&audio_node_tmp)))
return false;
// Append audio node to toast xml
ComPtr<IXmlNode> audio_node;
if (FAILED(root->AppendChild(audio_node_tmp.Get(), &audio_node)))
return false;
// Create silent attribute
ComPtr<IXmlNamedNodeMap> attributes;
if (FAILED(audio_node->get_Attributes(&attributes)))
return false;
ComPtr<IXmlAttribute> silent_attribute;
ScopedHString silent_str(L"silent");
if (FAILED(doc->CreateAttribute(silent_str, &silent_attribute)))
return false;
ComPtr<IXmlNode> silent_attribute_node;
if (FAILED(silent_attribute.As(&silent_attribute_node)))
return false;
// Set silent attribute to true
ScopedHString silent_value(L"true");
if (!silent_value.success())
return false;
ComPtr<IXmlText> silent_text;
if (FAILED(doc->CreateTextNode(silent_value, &silent_text)))
return false;
ComPtr<IXmlNode> silent_node;
if (FAILED(silent_text.As(&silent_node)))
return false;
ComPtr<IXmlNode> child_node;
if (FAILED(silent_attribute_node->AppendChild(silent_node.Get(), &child_node)))
return false;
ComPtr<IXmlNode> silent_attribute_pnode;
return SUCCEEDED(attributes.Get()->SetNamedItem(silent_attribute_node.Get(), &silent_attribute_pnode));
}
bool WindowsToastNotification::SetXmlText(
IXmlDocument* doc, const std::wstring& text) {
ScopedHString tag;
ComPtr<IXmlNodeList> node_list;
if (!GetTextNodeList(&tag, doc, &node_list, 1))
return false;
ComPtr<IXmlNode> node;
if (FAILED(node_list->Item(0, &node)))
return false;
return AppendTextToXml(doc, node.Get(), text);
}
bool WindowsToastNotification::SetXmlText(
IXmlDocument* doc, const std::wstring& title, const std::wstring& body) {
ScopedHString tag;
ComPtr<IXmlNodeList> node_list;
if (!GetTextNodeList(&tag, doc, &node_list, 2))
return false;
ComPtr<IXmlNode> node;
if (FAILED(node_list->Item(0, &node)))
return false;
if (!AppendTextToXml(doc, node.Get(), title))
return false;
if (FAILED(node_list->Item(1, &node)))
return false;
return AppendTextToXml(doc, node.Get(), body);
}
bool WindowsToastNotification::SetXmlImage(
IXmlDocument* doc, const std::wstring& icon_path) {
ScopedHString tag(L"image");
if (!tag.success())
return false;
ComPtr<IXmlNodeList> node_list;
if (FAILED(doc->GetElementsByTagName(tag, &node_list)))
return false;
ComPtr<IXmlNode> image_node;
if (FAILED(node_list->Item(0, &image_node)))
return false;
ComPtr<IXmlNamedNodeMap> attrs;
if (FAILED(image_node->get_Attributes(&attrs)))
return false;
ScopedHString src(L"src");
if (!src.success())
return false;
ComPtr<IXmlNode> src_attr;
if (FAILED(attrs->GetNamedItem(src, &src_attr)))
return false;
ScopedHString img_path(icon_path.c_str());
if (!img_path.success())
return false;
ComPtr<IXmlText> src_text;
if (FAILED(doc->CreateTextNode(img_path, &src_text)))
return false;
ComPtr<IXmlNode> src_node;
if (FAILED(src_text.As(&src_node)))
return false;
ComPtr<IXmlNode> child_node;
return SUCCEEDED(src_attr->AppendChild(src_node.Get(), &child_node));
}
bool WindowsToastNotification::GetTextNodeList(
ScopedHString* tag,
IXmlDocument* doc,
IXmlNodeList** node_list,
uint32_t req_length) {
tag->Reset(L"text");
if (!tag->success())
return false;
if (FAILED(doc->GetElementsByTagName(*tag, node_list)))
return false;
uint32_t node_length;
if (FAILED((*node_list)->get_Length(&node_length)))
return false;
return node_length >= req_length;
}
bool WindowsToastNotification::AppendTextToXml(
IXmlDocument* doc, IXmlNode* node, const std::wstring& text) {
ScopedHString str(text);
if (!str.success())
return false;
ComPtr<IXmlText> xml_text;
if (FAILED(doc->CreateTextNode(str, &xml_text)))
return false;
ComPtr<IXmlNode> text_node;
if (FAILED(xml_text.As(&text_node)))
return false;
ComPtr<IXmlNode> append_node;
return SUCCEEDED(node->AppendChild(text_node.Get(), &append_node));
}
bool WindowsToastNotification::SetupCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast) {
event_handler_ = Make<ToastEventHandler>(this);
if (FAILED(toast->add_Activated(event_handler_.Get(), &activated_token_)))
return false;
if (FAILED(toast->add_Dismissed(event_handler_.Get(), &dismissed_token_)))
return false;
return SUCCEEDED(toast->add_Failed(event_handler_.Get(), &failed_token_));
}
bool WindowsToastNotification::RemoveCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast) {
if (FAILED(toast->remove_Activated(activated_token_)))
return false;
if (FAILED(toast->remove_Dismissed(dismissed_token_)))
return false;
return SUCCEEDED(toast->remove_Failed(failed_token_));
}
/*
/ Toast Event Handler
*/
ToastEventHandler::ToastEventHandler(WindowsToastNotification* notification)
: notification_(notification) {
}
ToastEventHandler::~ToastEventHandler() {
}
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender, IInspectable* args) {
notification_->NotificationClicked();
return S_OK;
}
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastDismissedEventArgs* e) {
notification_->NotificationDismissed();
return S_OK;
}
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastFailedEventArgs* e) {
notification_->NotificationFailed();
return S_OK;
}
} // namespace brightray
<|endoftext|> |
<commit_before>
#include "../../Flare.h"
#include "FlareCargoInfo.h"
#include "../../Spacecrafts/FlareSimulatedSpacecraft.h"
#include "../../Player/FlareMenuManager.h"
#define LOCTEXT_NAMESPACE "FlareCargoInfo"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareCargoInfo::Construct(const FArguments& InArgs)
{
// Params
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
TargetSpacecraft = InArgs._Spacecraft;
CargoIndex = InArgs._CargoIndex;
OnClicked = InArgs._OnClicked;
TSharedPtr<SButton> Button;
// Layout
ChildSlot
.HAlign(HAlign_Left)
.VAlign(VAlign_Center)
.Padding(FMargin(1))
[
// Button (behaviour only, no display)
SAssignNew(Button, SButton)
.OnClicked(this, &SFlareCargoInfo::OnButtonClicked)
.ContentPadding(FMargin(0))
.ButtonStyle(FCoreStyle::Get(), "NoBorder")
[
SNew(SBorder)
.Padding(FMargin(0))
.BorderImage(this, &SFlareCargoInfo::GetResourceIcon)
[
SNew(SBox)
.WidthOverride(Theme.ResourceWidth)
.HeightOverride(Theme.ResourceHeight)
.Padding(FMargin(0))
[
SNew(SVerticalBox)
// Resource name
+ SVerticalBox::Slot()
.Padding(Theme.SmallContentPadding)
[
SNew(STextBlock)
.TextStyle(&Theme.TextFont)
.Text(this, &SFlareCargoInfo::GetResourceAcronym)
]
// Resource quantity
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.SmallContentPadding)
.VAlign(VAlign_Bottom)
.HAlign(HAlign_Center)
[
SNew(STextBlock)
.TextStyle(&Theme.SmallFont)
.Text(this, &SFlareCargoInfo::GetResourceQuantity)
]
]
]
]
];
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
void SFlareCargoInfo::OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent)
{
SWidget::OnMouseEnter(MyGeometry, MouseEvent);
AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton();
FFlareCargo* Cargo = &TargetSpacecraft->GetCargoBay()[CargoIndex];
check(Cargo);
if (MenuManager)
{
FText InfoText = Cargo->Resource ? Cargo->Resource->Description : LOCTEXT("EmptyInfo", "Empty bay");
MenuManager->ShowTooltip(this, InfoText);
}
}
void SFlareCargoInfo::OnMouseLeave(const FPointerEvent& MouseEvent)
{
SWidget::OnMouseLeave(MouseEvent);
AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton();
if (MenuManager)
{
MenuManager->HideTooltip(this);
}
}
const FSlateBrush* SFlareCargoInfo::GetResourceIcon() const
{
FFlareCargo* Cargo = &TargetSpacecraft->GetCargoBay()[CargoIndex];
check(Cargo);
if (Cargo->Resource)
{
return &Cargo->Resource->Icon;
}
else
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
return &Theme.ResourceBackground;
}
}
FText SFlareCargoInfo::GetResourceAcronym() const
{
FFlareCargo* Cargo = &TargetSpacecraft->GetCargoBay()[CargoIndex];
check(Cargo);
if (Cargo->Resource)
{
return Cargo->Resource->Acronym;
}
else
{
return LOCTEXT("Empty", " ");
}
}
FText SFlareCargoInfo::GetResourceQuantity() const
{
FFlareCargo* Cargo = &TargetSpacecraft->GetCargoBay()[CargoIndex];
check(Cargo);
return FText::FromString(FString::Printf(TEXT("%u/%u"), Cargo->Quantity, Cargo->Capacity)); //FString needed here
}
FReply SFlareCargoInfo::OnButtonClicked()
{
FFlareCargo* Cargo = &TargetSpacecraft->GetCargoBay()[CargoIndex];
if (Cargo && Cargo->Resource)
{
OnClicked.ExecuteIfBound();
}
return FReply::Handled();
}
#undef LOCTEXT_NAMESPACE
<commit_msg>Don't let cargo bays intercept clicks<commit_after>
#include "../../Flare.h"
#include "FlareCargoInfo.h"
#include "../../Spacecrafts/FlareSimulatedSpacecraft.h"
#include "../../Player/FlareMenuManager.h"
#define LOCTEXT_NAMESPACE "FlareCargoInfo"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareCargoInfo::Construct(const FArguments& InArgs)
{
// Params
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
TargetSpacecraft = InArgs._Spacecraft;
CargoIndex = InArgs._CargoIndex;
OnClicked = InArgs._OnClicked;
TSharedPtr<SButton> Button;
// Layout
ChildSlot
.HAlign(HAlign_Left)
.VAlign(VAlign_Center)
.Padding(FMargin(1))
[
// Button (behaviour only, no display)
SAssignNew(Button, SButton)
.OnClicked(this, &SFlareCargoInfo::OnButtonClicked)
.ContentPadding(FMargin(0))
.ButtonStyle(FCoreStyle::Get(), "NoBorder")
[
SNew(SBorder)
.Padding(FMargin(0))
.BorderImage(this, &SFlareCargoInfo::GetResourceIcon)
[
SNew(SBox)
.WidthOverride(Theme.ResourceWidth)
.HeightOverride(Theme.ResourceHeight)
.Padding(FMargin(0))
[
SNew(SVerticalBox)
// Resource name
+ SVerticalBox::Slot()
.Padding(Theme.SmallContentPadding)
[
SNew(STextBlock)
.TextStyle(&Theme.TextFont)
.Text(this, &SFlareCargoInfo::GetResourceAcronym)
]
// Resource quantity
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.SmallContentPadding)
.VAlign(VAlign_Bottom)
.HAlign(HAlign_Center)
[
SNew(STextBlock)
.TextStyle(&Theme.SmallFont)
.Text(this, &SFlareCargoInfo::GetResourceQuantity)
]
]
]
]
];
// Don't intercept clicks if it's not interactive
if (!OnClicked.IsBound())
{
Button->SetVisibility(EVisibility::HitTestInvisible);
}
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
void SFlareCargoInfo::OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent)
{
SWidget::OnMouseEnter(MyGeometry, MouseEvent);
AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton();
FFlareCargo* Cargo = &TargetSpacecraft->GetCargoBay()[CargoIndex];
check(Cargo);
if (MenuManager)
{
FText InfoText = Cargo->Resource ? Cargo->Resource->Description : LOCTEXT("EmptyInfo", "Empty bay");
MenuManager->ShowTooltip(this, InfoText);
}
}
void SFlareCargoInfo::OnMouseLeave(const FPointerEvent& MouseEvent)
{
SWidget::OnMouseLeave(MouseEvent);
AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton();
if (MenuManager)
{
MenuManager->HideTooltip(this);
}
}
const FSlateBrush* SFlareCargoInfo::GetResourceIcon() const
{
FFlareCargo* Cargo = &TargetSpacecraft->GetCargoBay()[CargoIndex];
check(Cargo);
if (Cargo->Resource)
{
return &Cargo->Resource->Icon;
}
else
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
return &Theme.ResourceBackground;
}
}
FText SFlareCargoInfo::GetResourceAcronym() const
{
FFlareCargo* Cargo = &TargetSpacecraft->GetCargoBay()[CargoIndex];
check(Cargo);
if (Cargo->Resource)
{
return Cargo->Resource->Acronym;
}
else
{
return LOCTEXT("Empty", " ");
}
}
FText SFlareCargoInfo::GetResourceQuantity() const
{
FFlareCargo* Cargo = &TargetSpacecraft->GetCargoBay()[CargoIndex];
check(Cargo);
return FText::FromString(FString::Printf(TEXT("%u/%u"), Cargo->Quantity, Cargo->Capacity)); //FString needed here
}
FReply SFlareCargoInfo::OnButtonClicked()
{
FFlareCargo* Cargo = &TargetSpacecraft->GetCargoBay()[CargoIndex];
if (Cargo && Cargo->Resource)
{
OnClicked.ExecuteIfBound();
}
return FReply::Handled();
}
#undef LOCTEXT_NAMESPACE
<|endoftext|> |
<commit_before>/*!
* \file SickLMSBufferMonitor.cc
* \brief Implements a class for monitoring the receive
* buffer when interfacing w/ a Sick LMS LIDAR.
*
* Code by Jason C. Derenick and Thomas H. Miller.
* Contact derenick(at)lehigh(dot)edu
*
* The Sick LIDAR Matlab/C++ Toolbox
* Copyright (c) 2008, Jason C. Derenick and Thomas H. Miller
* All rights reserved.
*
* This software is released under a BSD Open-Source License.
* See http://sicktoolbox.sourceforge.net
*/
/* Auto-generated header */
#include "SickConfig.hh"
/* Implementation dependencies */
#include <iostream>
#include <termios.h>
#include "SickLMS.hh"
#include "SickLMSBufferMonitor.hh"
#include "SickLMSMessage.hh"
#include "SickException.hh"
#include "SickLMSUtility.hh"
/* Associate the namespace */
namespace SickToolbox {
/**
* \brief A standard constructor
*/
SickLMSBufferMonitor::SickLMSBufferMonitor( ) : SickBufferMonitor<SickLMSBufferMonitor,SickLMSMessage>(this) { }
/**
* \brief Acquires the next message from the SickLMS byte stream
* \param &sick_message The returned message object
*/
void SickLMSBufferMonitor::GetNextMessageFromDataStream( SickLMSMessage &sick_message ) throw( SickIOException ) {
uint8_t search_buffer[2] = {0};
uint8_t payload_length_buffer[2] = {0};
uint8_t payload_buffer[SickLMSMessage::MESSAGE_PAYLOAD_MAX_LENGTH] = {0};
uint8_t checksum_buffer[2] = {0};
uint16_t payload_length, checksum;
try {
/* Drain the I/O buffers! */
if (tcdrain(_sick_fd) != 0) {
throw SickIOException("SickLMS::_getNextMessageFromDataStream: tcdrain failed!");
}
/* Read until we get a valid message header */
unsigned int bytes_searched = 0;
while(search_buffer[0] != 0x02 || search_buffer[1] != DEFAULT_SICK_LMS_HOST_ADDRESS) {
/* Slide the search window */
search_buffer[0] = search_buffer[1];
/* Attempt to read in another byte */
_readBytes(&search_buffer[1],1,DEFAULT_SICK_LMS_SICK_BYTE_TIMEOUT);
/* Header should be no more than max message length + header length bytes away */
if (bytes_searched > SickLMSMessage::MESSAGE_MAX_LENGTH + SickLMSMessage::MESSAGE_HEADER_LENGTH) {
throw SickTimeoutException("SickLMSBufferMonitor::GetNextMessageFromDataStream: header timeout!");
}
/* Increment the number of bytes searched */
bytes_searched++;
}
/* Read until we receive the payload length or we timeout */
_readBytes(payload_length_buffer,2,DEFAULT_SICK_LMS_SICK_BYTE_TIMEOUT);
/* Extract the payload length */
memcpy(&payload_length,payload_length_buffer,2);
payload_length = sick_lms_to_host_byte_order(payload_length);
/* Make sure the payload length is legitimate, otherwise disregard */
if (payload_length <= SickLMSMessage::MESSAGE_MAX_LENGTH) {
/* Read until we receive the payload or we timeout */
_readBytes(payload_buffer,payload_length,DEFAULT_SICK_LMS_SICK_BYTE_TIMEOUT);
/* Read until we receive the checksum or we timeout */
_readBytes(checksum_buffer,2,DEFAULT_SICK_LMS_SICK_BYTE_TIMEOUT);
/* Copy into uint16_t so it can be used */
memcpy(&checksum,checksum_buffer,2);
checksum = sick_lms_to_host_byte_order(checksum);
/* Build a frame and compute the crc */
sick_message.BuildMessage(DEFAULT_SICK_LMS_HOST_ADDRESS,payload_buffer,payload_length);
/* See if the checksums match */
if(sick_message.GetChecksum() != checksum) {
throw SickBadChecksumException("SickLMS::_getNextMessageFromDataStream: CRC16 failed!");
}
}
}
catch(SickTimeoutException &sick_timeout_exception) { /* This is ok! */ }
/* Catch a bad checksum! */
catch(SickBadChecksumException &sick_checksum_exception) {
sick_message.Clear(); // Clear the message container
std::cerr << sick_checksum_exception.what() << std::endl;
}
/* Catch any serious IO exceptions */
catch(SickIOException &sick_io_exception) {
std::cerr << sick_io_exception.what() << std::endl;
throw;
}
/* A sanity check */
catch (...) {
std::cerr << "SickLMSBufferMonitor::_getNextMessageFromByteStream: Unknown exception!" << std::endl;
throw;
}
}
/**
* \brief A standard destructor
*/
SickLMSBufferMonitor::~SickLMSBufferMonitor( ) { }
} /* namespace SickToolbox */
<commit_msg>Took out std::cerr in bad checksum exception handler.<commit_after>/*!
* \file SickLMSBufferMonitor.cc
* \brief Implements a class for monitoring the receive
* buffer when interfacing w/ a Sick LMS LIDAR.
*
* Code by Jason C. Derenick and Thomas H. Miller.
* Contact derenick(at)lehigh(dot)edu
*
* The Sick LIDAR Matlab/C++ Toolbox
* Copyright (c) 2008, Jason C. Derenick and Thomas H. Miller
* All rights reserved.
*
* This software is released under a BSD Open-Source License.
* See http://sicktoolbox.sourceforge.net
*/
/* Auto-generated header */
#include "SickConfig.hh"
/* Implementation dependencies */
#include <iostream>
#include <termios.h>
#include "SickLMS.hh"
#include "SickLMSBufferMonitor.hh"
#include "SickLMSMessage.hh"
#include "SickException.hh"
#include "SickLMSUtility.hh"
/* Associate the namespace */
namespace SickToolbox {
/**
* \brief A standard constructor
*/
SickLMSBufferMonitor::SickLMSBufferMonitor( ) : SickBufferMonitor<SickLMSBufferMonitor,SickLMSMessage>(this) { }
/**
* \brief Acquires the next message from the SickLMS byte stream
* \param &sick_message The returned message object
*/
void SickLMSBufferMonitor::GetNextMessageFromDataStream( SickLMSMessage &sick_message ) throw( SickIOException ) {
uint8_t search_buffer[2] = {0};
uint8_t payload_length_buffer[2] = {0};
uint8_t payload_buffer[SickLMSMessage::MESSAGE_PAYLOAD_MAX_LENGTH] = {0};
uint8_t checksum_buffer[2] = {0};
uint16_t payload_length, checksum;
try {
/* Drain the I/O buffers! */
if (tcdrain(_sick_fd) != 0) {
throw SickIOException("SickLMSBufferMonitor::GetNextMessageFromDataStream: tcdrain failed!");
}
/* Read until we get a valid message header */
unsigned int bytes_searched = 0;
while(search_buffer[0] != 0x02 || search_buffer[1] != DEFAULT_SICK_LMS_HOST_ADDRESS) {
/* Slide the search window */
search_buffer[0] = search_buffer[1];
/* Attempt to read in another byte */
_readBytes(&search_buffer[1],1,DEFAULT_SICK_LMS_SICK_BYTE_TIMEOUT);
/* Header should be no more than max message length + header length bytes away */
if (bytes_searched > SickLMSMessage::MESSAGE_MAX_LENGTH + SickLMSMessage::MESSAGE_HEADER_LENGTH) {
throw SickTimeoutException("SickLMSBufferMonitor::GetNextMessageFromDataStream: header timeout!");
}
/* Increment the number of bytes searched */
bytes_searched++;
}
/* Read until we receive the payload length or we timeout */
_readBytes(payload_length_buffer,2,DEFAULT_SICK_LMS_SICK_BYTE_TIMEOUT);
/* Extract the payload length */
memcpy(&payload_length,payload_length_buffer,2);
payload_length = sick_lms_to_host_byte_order(payload_length);
/* Make sure the payload length is legitimate, otherwise disregard */
if (payload_length <= SickLMSMessage::MESSAGE_MAX_LENGTH) {
/* Read until we receive the payload or we timeout */
_readBytes(payload_buffer,payload_length,DEFAULT_SICK_LMS_SICK_BYTE_TIMEOUT);
/* Read until we receive the checksum or we timeout */
_readBytes(checksum_buffer,2,DEFAULT_SICK_LMS_SICK_BYTE_TIMEOUT);
/* Copy into uint16_t so it can be used */
memcpy(&checksum,checksum_buffer,2);
checksum = sick_lms_to_host_byte_order(checksum);
/* Build a frame and compute the crc */
sick_message.BuildMessage(DEFAULT_SICK_LMS_HOST_ADDRESS,payload_buffer,payload_length);
/* See if the checksums match */
if(sick_message.GetChecksum() != checksum) {
throw SickBadChecksumException("SickLMS::GetNextMessageFromDataStream: CRC16 failed!");
}
}
}
catch(SickTimeoutException &sick_timeout_exception) { /* This is ok! */ }
/* Handle a bad checksum! */
catch(SickBadChecksumException &sick_checksum_exception) {
sick_message.Clear(); // Clear the message container
}
/* Handle any serious IO exceptions */
catch(SickIOException &sick_io_exception) {
throw;
}
/* A sanity check */
catch (...) {
throw;
}
}
/**
* \brief A standard destructor
*/
SickLMSBufferMonitor::~SickLMSBufferMonitor( ) { }
} /* namespace SickToolbox */
<|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 "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kCompletionOnPause[] =
"files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Fails after WebKit roll 59365:59477, http://crbug.com/44202.
#if defined(OS_LINUX)
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif // defined(OS_LINUX)
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
RunTest("testHeapProfiler", kHeapProfilerPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
// Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
DISABLED_TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
// The test fails on linux and should be related to Webkit patch
// http://trac.webkit.org/changeset/64124/trunk.
// Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
DISABLED_TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Fails after WebKit roll 66724:66804, http://crbug.com/54592
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestCompletionOnPause FAILS_TestCompletionOnPause
#else
#define MAYBE_TestCompletionOnPause TestCompletionOnPause
#endif // defined(OS_LINUX) || defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
} // namespace
<commit_msg>DevTools: enable two sanity tests (fixed upstream)<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 "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kCompletionOnPause[] =
"files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Fails after WebKit roll 59365:59477, http://crbug.com/44202.
#if defined(OS_LINUX)
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif // defined(OS_LINUX)
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
RunTest("testHeapProfiler", kHeapProfilerPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Fails after WebKit roll 66724:66804, http://crbug.com/54592
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestCompletionOnPause FAILS_TestCompletionOnPause
#else
#define MAYBE_TestCompletionOnPause TestCompletionOnPause
#endif // defined(OS_LINUX) || defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
} // namespace
<|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 "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
RunTest("testHeapProfiler", kHeapProfilerPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
} // namespace
<commit_msg>DevToolsSanityTest.TestHeapProfiler fails.<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 "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FAILS_TestHeapProfiler) {
RunTest("testHeapProfiler", kHeapProfilerPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
} // namespace
<|endoftext|> |
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/CIFactory.h"
#include "DeclCollector.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
//
// Dummy function so we can use dladdr to find the executable path.
//
void locate_cling_executable()
{
}
/// \brief Retrieves the clang CC1 specific flags out of the compilation's
/// jobs. Returns NULL on error.
static const clang::driver::ArgStringList
*GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,
clang::driver::Compilation *Compilation) {
// We expect to get back exactly one Command job, if we didn't something
// failed. Extract that job from the Compilation.
const clang::driver::JobList &Jobs = Compilation->getJobs();
if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {
// diagnose this...
return NULL;
}
// The one job we find should be to invoke clang again.
const clang::driver::Command *Cmd
= cast<clang::driver::Command>(*Jobs.begin());
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
// diagnose this...
return NULL;
}
return &Cmd->getArguments();
}
CompilerInstance* CIFactory::createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir) {
return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,
llvmdir);
}
CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
int argc,
const char* const *argv,
const char* llvmdir) {
// Create an instance builder, passing the llvmdir and arguments.
//
// Initialize the llvm library.
llvm::InitializeNativeTarget();
llvm::InitializeAllAsmPrinters();
llvm::sys::Path resource_path;
if (llvmdir) {
resource_path = llvmdir;
resource_path.appendComponent("lib");
resource_path.appendComponent("clang");
resource_path.appendComponent(CLANG_VERSION_STRING);
} else {
// FIXME: The first arg really does need to be argv[0] on FreeBSD.
//
// Note: The second arg is not used for Apple, FreeBSD, Linux,
// or cygwin, and can only be used on systems which support
// the use of dladdr().
//
// Note: On linux and cygwin this uses /proc/self/exe to find the path.
//
// Note: On Apple it uses _NSGetExecutablePath().
//
// Note: On FreeBSD it uses getprogpath().
//
// Note: Otherwise it uses dladdr().
//
resource_path
= CompilerInvocation::GetResourcesPath("cling",
(void*)(intptr_t) locate_cling_executable
);
}
if (!resource_path.canRead()) {
llvm::errs()
<< "ERROR in cling::CIFactory::createCI():\n resource directory "
<< resource_path.str() << " not found!\n";
resource_path = "";
}
//______________________________________
DiagnosticOptions DefaultDiagnosticOptions;
DefaultDiagnosticOptions.ShowColors = 1;
TextDiagnosticPrinter* DiagnosticPrinter
= new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());
DiagnosticsEngine* Diagnostics
= new DiagnosticsEngine(DiagIDs, DiagnosticPrinter,
/*Owns it*/ true); // LEAKS!
std::vector<const char*> argvCompile(argv, argv + argc);
// We do C++ by default; append right after argv[0] name
// Only insert it if there is no other "-x":
bool haveMinusX = false;
for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;
++iarg) {
haveMinusX = !strcmp(*iarg, "-x");
}
if (!haveMinusX) {
argvCompile.insert(argvCompile.begin() + 1,"-x");
argvCompile.insert(argvCompile.begin() + 2, "c++");
}
argvCompile.push_back("-c");
argvCompile.push_back("-");
bool IsProduction = false;
assert(IsProduction = true && "set IsProduction if asserts are on.");
clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),
"cling.out",
IsProduction,
*Diagnostics);
//Driver.setWarnMissingInput(false);
Driver.setCheckInputsExist(false); // think foo.C(12)
llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());
llvm::OwningPtr<clang::driver::Compilation>
Compilation(Driver.BuildCompilation(RF));
const clang::driver::ArgStringList* CC1Args
= GetCC1Arguments(Diagnostics, Compilation.get());
if (CC1Args == NULL) {
return 0;
}
clang::CompilerInvocation*
Invocation = new clang::CompilerInvocation;
clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,
CC1Args->data() + CC1Args->size(),
*Diagnostics);
Invocation->getFrontendOpts().DisableFree = true;
if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&
!resource_path.empty()) {
// Update ResourceDir
// header search opts' entry for resource_path/include isn't
// updated by providing a new resource path; update it manually.
clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();
llvm::sys::Path oldResInc(Opts.ResourceDir);
oldResInc.appendComponent("include");
llvm::sys::Path newResInc(resource_path);
newResInc.appendComponent("include");
bool foundOldResInc = false;
for (unsigned i = 0, e = Opts.UserEntries.size();
!foundOldResInc && i != e; ++i) {
HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
if (!E.IsUserSupplied && !E.IsFramework
&& E.Group == clang::frontend::System && E.IgnoreSysRoot
&& E.IsInternal && !E.ImplicitExternC
&& oldResInc.str() == E.Path) {
E.Path = newResInc.str();
foundOldResInc = true;
}
}
Opts.ResourceDir = resource_path.str();
}
// Create and setup a compiler instance.
CompilerInstance* CI = new CompilerInstance();
CI->setInvocation(Invocation);
CI->createDiagnostics(CC1Args->size(), CC1Args->data() + 1);
{
//
// Buffer the error messages while we process
// the compiler options.
//
// Set the language options, which cling needs
SetClingCustomLangOpts(CI->getLangOpts());
CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
if (CI->getDiagnostics().hasErrorOccurred()) {
delete CI;
CI = 0;
return 0;
}
}
CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
Invocation->getTargetOpts()));
if (!CI->hasTarget()) {
delete CI;
CI = 0;
return 0;
}
CI->getTarget().setForcedLangOptions(CI->getLangOpts());
SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());
// Set up source and file managers
CI->createFileManager();
CI->createSourceManager(CI->getFileManager());
// Set up the memory buffer
if (buffer)
CI->getSourceManager().createMainFileIDForMemBuffer(buffer);
// Set up the preprocessor
CI->createPreprocessor();
Preprocessor& PP = CI->getPreprocessor();
PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
PP.getLangOpts());
// Set up the ASTContext
ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
PP.getSourceManager(), &CI->getTarget(),
PP.getIdentifierTable(),
PP.getSelectorTable(), PP.getBuiltinInfo(),
/*size_reserve*/0, /*DelayInit*/false);
CI->setASTContext(Ctx);
// Set up the ASTConsumers
CI->setASTConsumer(new DeclCollector());
// Set up Sema
CodeCompleteConsumer* CCC = 0;
CI->createSema(TU_Complete, CCC);
// Set CodeGen options
// CI->getCodeGenOpts().DebugInfo = 1; // want debug info
// CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
// When asserts are on, TURN ON not compare the VerifyModule
assert(CI->getCodeGenOpts().VerifyModule = 1);
return CI;
}
void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
Opts.EmitAllDecls = 1;
Opts.Exceptions = 1;
Opts.CXXExceptions = 1;
Opts.Deprecated = 1;
Opts.Modules = 1;
}
void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
const TargetInfo& Target) {
if (Target.getTriple().getOS() == llvm::Triple::Win32) {
Opts.MicrosoftExt = 1;
Opts.MSCVersion = 1300;
// Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
Opts.DelayedTemplateParsing = 1;
} else {
Opts.MicrosoftExt = 0;
}
}
} // end namespace
<commit_msg>Turn off the codegen option CXXCtorDtorAliases for the jit. This prevents codegen from implementing a complete constructor by using a linker alias to the base constructor, instead it emits the function itself. This prevents the jit from crashing on simple code.<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/CIFactory.h"
#include "DeclCollector.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
//
// Dummy function so we can use dladdr to find the executable path.
//
void locate_cling_executable()
{
}
/// \brief Retrieves the clang CC1 specific flags out of the compilation's
/// jobs. Returns NULL on error.
static const clang::driver::ArgStringList
*GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,
clang::driver::Compilation *Compilation) {
// We expect to get back exactly one Command job, if we didn't something
// failed. Extract that job from the Compilation.
const clang::driver::JobList &Jobs = Compilation->getJobs();
if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {
// diagnose this...
return NULL;
}
// The one job we find should be to invoke clang again.
const clang::driver::Command *Cmd
= cast<clang::driver::Command>(*Jobs.begin());
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
// diagnose this...
return NULL;
}
return &Cmd->getArguments();
}
CompilerInstance* CIFactory::createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir) {
return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,
llvmdir);
}
CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
int argc,
const char* const *argv,
const char* llvmdir) {
// Create an instance builder, passing the llvmdir and arguments.
//
// Initialize the llvm library.
llvm::InitializeNativeTarget();
llvm::InitializeAllAsmPrinters();
llvm::sys::Path resource_path;
if (llvmdir) {
resource_path = llvmdir;
resource_path.appendComponent("lib");
resource_path.appendComponent("clang");
resource_path.appendComponent(CLANG_VERSION_STRING);
} else {
// FIXME: The first arg really does need to be argv[0] on FreeBSD.
//
// Note: The second arg is not used for Apple, FreeBSD, Linux,
// or cygwin, and can only be used on systems which support
// the use of dladdr().
//
// Note: On linux and cygwin this uses /proc/self/exe to find the path.
//
// Note: On Apple it uses _NSGetExecutablePath().
//
// Note: On FreeBSD it uses getprogpath().
//
// Note: Otherwise it uses dladdr().
//
resource_path
= CompilerInvocation::GetResourcesPath("cling",
(void*)(intptr_t) locate_cling_executable
);
}
if (!resource_path.canRead()) {
llvm::errs()
<< "ERROR in cling::CIFactory::createCI():\n resource directory "
<< resource_path.str() << " not found!\n";
resource_path = "";
}
//______________________________________
DiagnosticOptions DefaultDiagnosticOptions;
DefaultDiagnosticOptions.ShowColors = 1;
TextDiagnosticPrinter* DiagnosticPrinter
= new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());
DiagnosticsEngine* Diagnostics
= new DiagnosticsEngine(DiagIDs, DiagnosticPrinter,
/*Owns it*/ true); // LEAKS!
std::vector<const char*> argvCompile(argv, argv + argc);
// We do C++ by default; append right after argv[0] name
// Only insert it if there is no other "-x":
bool haveMinusX = false;
for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;
++iarg) {
haveMinusX = !strcmp(*iarg, "-x");
}
if (!haveMinusX) {
argvCompile.insert(argvCompile.begin() + 1,"-x");
argvCompile.insert(argvCompile.begin() + 2, "c++");
}
argvCompile.push_back("-c");
argvCompile.push_back("-");
bool IsProduction = false;
assert(IsProduction = true && "set IsProduction if asserts are on.");
clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),
"cling.out",
IsProduction,
*Diagnostics);
//Driver.setWarnMissingInput(false);
Driver.setCheckInputsExist(false); // think foo.C(12)
llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());
llvm::OwningPtr<clang::driver::Compilation>
Compilation(Driver.BuildCompilation(RF));
const clang::driver::ArgStringList* CC1Args
= GetCC1Arguments(Diagnostics, Compilation.get());
if (CC1Args == NULL) {
return 0;
}
clang::CompilerInvocation*
Invocation = new clang::CompilerInvocation;
clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,
CC1Args->data() + CC1Args->size(),
*Diagnostics);
Invocation->getFrontendOpts().DisableFree = true;
if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&
!resource_path.empty()) {
// Update ResourceDir
// header search opts' entry for resource_path/include isn't
// updated by providing a new resource path; update it manually.
clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();
llvm::sys::Path oldResInc(Opts.ResourceDir);
oldResInc.appendComponent("include");
llvm::sys::Path newResInc(resource_path);
newResInc.appendComponent("include");
bool foundOldResInc = false;
for (unsigned i = 0, e = Opts.UserEntries.size();
!foundOldResInc && i != e; ++i) {
HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
if (!E.IsUserSupplied && !E.IsFramework
&& E.Group == clang::frontend::System && E.IgnoreSysRoot
&& E.IsInternal && !E.ImplicitExternC
&& oldResInc.str() == E.Path) {
E.Path = newResInc.str();
foundOldResInc = true;
}
}
Opts.ResourceDir = resource_path.str();
}
// Create and setup a compiler instance.
CompilerInstance* CI = new CompilerInstance();
CI->setInvocation(Invocation);
CI->createDiagnostics(CC1Args->size(), CC1Args->data() + 1);
{
//
// Buffer the error messages while we process
// the compiler options.
//
// Set the language options, which cling needs
SetClingCustomLangOpts(CI->getLangOpts());
CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
if (CI->getDiagnostics().hasErrorOccurred()) {
delete CI;
CI = 0;
return 0;
}
}
CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
Invocation->getTargetOpts()));
if (!CI->hasTarget()) {
delete CI;
CI = 0;
return 0;
}
CI->getTarget().setForcedLangOptions(CI->getLangOpts());
SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());
// Set up source and file managers
CI->createFileManager();
CI->createSourceManager(CI->getFileManager());
// Set up the memory buffer
if (buffer)
CI->getSourceManager().createMainFileIDForMemBuffer(buffer);
// Set up the preprocessor
CI->createPreprocessor();
Preprocessor& PP = CI->getPreprocessor();
PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
PP.getLangOpts());
// Set up the ASTContext
ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
PP.getSourceManager(), &CI->getTarget(),
PP.getIdentifierTable(),
PP.getSelectorTable(), PP.getBuiltinInfo(),
/*size_reserve*/0, /*DelayInit*/false);
CI->setASTContext(Ctx);
// Set up the ASTConsumers
CI->setASTConsumer(new DeclCollector());
// Set up Sema
CodeCompleteConsumer* CCC = 0;
CI->createSema(TU_Complete, CCC);
// Set CodeGen options
// CI->getCodeGenOpts().DebugInfo = 1; // want debug info
// CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
CI->getCodeGenOpts().CXXCtorDtorAliases = 0; // aliasing the complete
// ctor to the base ctor causes
// the JIT to crash
// When asserts are on, TURN ON not compare the VerifyModule
assert(CI->getCodeGenOpts().VerifyModule = 1);
return CI;
}
void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
Opts.EmitAllDecls = 1;
Opts.Exceptions = 1;
Opts.CXXExceptions = 1;
Opts.Deprecated = 1;
Opts.Modules = 1;
}
void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
const TargetInfo& Target) {
if (Target.getTriple().getOS() == llvm::Triple::Win32) {
Opts.MicrosoftExt = 1;
Opts.MSCVersion = 1300;
// Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
Opts.DelayedTemplateParsing = 1;
} else {
Opts.MicrosoftExt = 0;
}
}
} // end namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2011 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/history/in_memory_url_index_types.h"
#include <algorithm>
#include <functional>
#include <iterator>
#include "base/i18n/break_iterator.h"
#include "base/i18n/case_conversion.h"
#include "base/string_util.h"
namespace history {
// Matches within URL and Title Strings ----------------------------------------
TermMatches MatchTermInString(const string16& term,
const string16& string,
int term_num) {
const size_t kMaxCompareLength = 2048;
const string16& short_string = (string.length() > kMaxCompareLength) ?
string.substr(0, kMaxCompareLength) : string;
TermMatches matches;
for (size_t location = short_string.find(term); location != string16::npos;
location = short_string.find(term, location + 1))
matches.push_back(TermMatch(term_num, location, term.length()));
return matches;
}
// Comparison function for sorting TermMatches by their offsets.
bool MatchOffsetLess(const TermMatch& m1, const TermMatch& m2) {
return m1.offset < m2.offset;
}
TermMatches SortAndDeoverlapMatches(const TermMatches& matches) {
if (matches.empty())
return matches;
TermMatches sorted_matches = matches;
std::sort(sorted_matches.begin(), sorted_matches.end(), MatchOffsetLess);
TermMatches clean_matches;
TermMatch last_match;
for (TermMatches::const_iterator iter = sorted_matches.begin();
iter != sorted_matches.end(); ++iter) {
if (iter->offset >= last_match.offset + last_match.length) {
last_match = *iter;
clean_matches.push_back(last_match);
}
}
return clean_matches;
}
std::vector<size_t> OffsetsFromTermMatches(const TermMatches& matches) {
std::vector<size_t> offsets;
for (TermMatches::const_iterator i = matches.begin(); i != matches.end(); ++i)
offsets.push_back(i->offset);
return offsets;
}
TermMatches ReplaceOffsetsInTermMatches(const TermMatches& matches,
const std::vector<size_t>& offsets) {
DCHECK_EQ(matches.size(), offsets.size());
TermMatches new_matches;
std::vector<size_t>::const_iterator offset_iter = offsets.begin();
for (TermMatches::const_iterator term_iter = matches.begin();
term_iter != matches.end(); ++term_iter, ++offset_iter) {
if (*offset_iter != string16::npos) {
TermMatch new_match(*term_iter);
new_match.offset = *offset_iter;
new_matches.push_back(new_match);
}
}
return new_matches;
}
// ScoredHistoryMatch ----------------------------------------------------------
ScoredHistoryMatch::ScoredHistoryMatch()
: raw_score(0),
can_inline(false) {}
ScoredHistoryMatch::ScoredHistoryMatch(const URLRow& url_info)
: HistoryMatch(url_info, 0, false, false),
raw_score(0),
can_inline(false) {}
ScoredHistoryMatch::~ScoredHistoryMatch() {}
// Comparison function for sorting ScoredMatches by their scores.
bool ScoredHistoryMatch::MatchScoreGreater(const ScoredHistoryMatch& m1,
const ScoredHistoryMatch& m2) {
return m1.raw_score >= m2.raw_score;
}
// InMemoryURLIndex's Private Data ---------------------------------------------
URLIndexPrivateData::URLIndexPrivateData() {}
URLIndexPrivateData::~URLIndexPrivateData() {}
void URLIndexPrivateData::Clear() {
word_list_.clear();
available_words_.clear();
word_map_.clear();
char_word_map_.clear();
word_id_history_map_.clear();
history_id_word_map_.clear();
history_info_map_.clear();
}
void URLIndexPrivateData::AddToHistoryIDWordMap(HistoryID history_id,
WordID word_id) {
HistoryIDWordMap::iterator iter = history_id_word_map_.find(history_id);
if (iter != history_id_word_map_.end()) {
WordIDSet& word_id_set(iter->second);
word_id_set.insert(word_id);
} else {
WordIDSet word_id_set;
word_id_set.insert(word_id);
history_id_word_map_[history_id] = word_id_set;
}
}
WordIDSet URLIndexPrivateData::WordIDSetForTermChars(
const Char16Set& term_chars) {
WordIDSet word_id_set;
for (Char16Set::const_iterator c_iter = term_chars.begin();
c_iter != term_chars.end(); ++c_iter) {
CharWordIDMap::iterator char_iter = char_word_map_.find(*c_iter);
if (char_iter == char_word_map_.end()) {
// A character was not found so there are no matching results: bail.
word_id_set.clear();
break;
}
WordIDSet& char_word_id_set(char_iter->second);
// It is possible for there to no longer be any words associated with
// a particular character. Give up in that case.
if (char_word_id_set.empty()) {
word_id_set.clear();
break;
}
if (c_iter == term_chars.begin()) {
// First character results becomes base set of results.
word_id_set = char_word_id_set;
} else {
// Subsequent character results get intersected in.
WordIDSet new_word_id_set;
std::set_intersection(word_id_set.begin(), word_id_set.end(),
char_word_id_set.begin(), char_word_id_set.end(),
std::inserter(new_word_id_set,
new_word_id_set.begin()));
word_id_set.swap(new_word_id_set);
}
}
return word_id_set;
}
// Utility Functions -----------------------------------------------------------
String16Set String16SetFromString16(const string16& uni_string) {
const size_t kMaxWordLength = 64;
String16Vector words = String16VectorFromString16(uni_string, false);
String16Set word_set;
for (String16Vector::const_iterator iter = words.begin(); iter != words.end();
++iter)
word_set.insert(base::i18n::ToLower(*iter).substr(0, kMaxWordLength));
return word_set;
}
String16Vector String16VectorFromString16(const string16& uni_string,
bool break_on_space) {
base::i18n::BreakIterator iter(uni_string,
break_on_space ? base::i18n::BreakIterator::BREAK_SPACE :
base::i18n::BreakIterator::BREAK_WORD);
String16Vector words;
if (!iter.Init())
return words;
while (iter.Advance()) {
if (break_on_space || iter.IsWord()) {
string16 word = iter.GetString();
if (break_on_space)
TrimWhitespace(word, TRIM_ALL, &word);
if (!word.empty())
words.push_back(word);
}
}
return words;
}
Char16Set Char16SetFromString16(const string16& term) {
Char16Set characters;
for (string16::const_iterator iter = term.begin(); iter != term.end(); ++iter)
characters.insert(*iter);
return characters;
}
} // namespace history
<commit_msg>Remove extraneous file left over from earlier revert of 8120004.<commit_after><|endoftext|> |
<commit_before>//===-- jello.cpp - LLVM Just in Time Compiler ----------------------------===//
//
// This tool implements a just-in-time compiler for LLVM, allowing direct
// execution of LLVM bytecode in an efficient manner.
//
// FIXME: This code will get more object oriented as we get the call back
// intercept stuff implemented.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "Support/CommandLine.h"
#include "Support/Statistic.h"
namespace {
cl::opt<std::string>
InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-"));
cl::opt<std::string>
MainFunction("f", cl::desc("Function to execute"), cl::init("main"),
cl::value_desc("function name"));
}
//===----------------------------------------------------------------------===//
// main Driver function
//
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm just in time compiler\n");
// Allocate a target... in the future this will be controllable on the
// command line.
std::auto_ptr<TargetMachine> target(allocateX86TargetMachine());
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Parse the input bytecode file...
std::string ErrorMsg;
std::auto_ptr<Module> M(ParseBytecodeFile(InputFile, &ErrorMsg));
if (M.get() == 0) {
std::cerr << argv[0] << ": bytecode '" << InputFile
<< "' didn't read correctly: << " << ErrorMsg << "\n";
return 1;
}
PassManager Passes;
if (Target.addPassesToJITCompile(Passes)) {
std::cerr << argv[0] << ": target '" << Target.getName()
<< "' doesn't support JIT compilation!\n";
return 1;
}
// JIT all of the methods in the module. Eventually this will JIT functions
// on demand.
Passes.run(*M.get());
return 0;
}
<commit_msg>Add initial support for machine code emission<commit_after>//===-- jello.cpp - LLVM Just in Time Compiler ----------------------------===//
//
// This tool implements a just-in-time compiler for LLVM, allowing direct
// execution of LLVM bytecode in an efficient manner.
//
// FIXME: This code will get more object oriented as we get the call back
// intercept stuff implemented.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "Support/CommandLine.h"
#include "Support/Statistic.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
struct JelloMachineCodeEmitter : public MachineCodeEmitter {
};
namespace {
cl::opt<std::string>
InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-"));
cl::opt<std::string>
MainFunction("f", cl::desc("Function to execute"), cl::init("main"),
cl::value_desc("function name"));
}
//===----------------------------------------------------------------------===//
// main Driver function
//
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm just in time compiler\n");
// Allocate a target... in the future this will be controllable on the
// command line.
std::auto_ptr<TargetMachine> target(allocateX86TargetMachine());
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Parse the input bytecode file...
std::string ErrorMsg;
std::auto_ptr<Module> M(ParseBytecodeFile(InputFile, &ErrorMsg));
if (M.get() == 0) {
std::cerr << argv[0] << ": bytecode '" << InputFile
<< "' didn't read correctly: << " << ErrorMsg << "\n";
return 1;
}
PassManager Passes;
// Compile LLVM Code down to machine code in the intermediate representation
if (Target.addPassesToJITCompile(Passes)) {
std::cerr << argv[0] << ": target '" << Target.getName()
<< "' doesn't support JIT compilation!\n";
return 1;
}
// Turn the machine code intermediate representation into bytes in memory that
// may be executed.
//
JelloMachineCodeEmitter MCE;
if (Target.addPassesToEmitMachineCode(Passes, MCE)) {
std::cerr << argv[0] << ": target '" << Target.getName()
<< "' doesn't support machine code emission!\n";
return 1;
}
// JIT all of the methods in the module. Eventually this will JIT functions
// on demand.
Passes.run(*M.get());
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 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/ui/webui/bidi_checker_web_ui_test.h"
#include "base/base_paths.h"
#include "base/i18n/rtl.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#endif
// These tests are failing on linux views build. crbug.com/96891
#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
#define MAYBE_TestCrashesPageRTL DISABLED_TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL DISABLED_TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL DISABLED_TestMainHistoryPageRTL
#define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL DISABLED_TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL DISABLED_TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL DISABLED_TestSettingsPageRTL
#else
#define MAYBE_TestCrashesPageRTL TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL TestMainHistoryPageRTL
#define MAYBE_TestNewTabPageRTL TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL TestSettingsPageRTL
#endif
static const FilePath::CharType* kWebUIBidiCheckerLibraryJS =
FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js");
namespace {
FilePath WebUIBidiCheckerLibraryJSPath() {
FilePath src_root;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root))
LOG(ERROR) << "Couldn't find source root";
return src_root.Append(kWebUIBidiCheckerLibraryJS);
}
}
static const FilePath::CharType* kBidiCheckerTestsJS =
FILE_PATH_LITERAL("bidichecker_tests.js");
WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {}
WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {}
void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() {
WebUIBrowserTest::SetUpInProcessBrowserTestFixture();
WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath());
WebUIBrowserTest::AddLibrary(FilePath(kBidiCheckerTestsJS));
}
void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(const char pageURL[],
bool isRTL) {
ui_test_utils::NavigateToURL(browser(), GURL(pageURL));
ASSERT_TRUE(RunJavascriptTest("runBidiChecker",
Value::CreateStringValue(pageURL),
Value::CreateBooleanValue(isRTL)));
}
// WebUIBidiCheckerBrowserTestFakeBidi
WebUIBidiCheckerBrowserTestFakeBidi::~WebUIBidiCheckerBrowserTestFakeBidi() {}
WebUIBidiCheckerBrowserTestFakeBidi::WebUIBidiCheckerBrowserTestFakeBidi() {}
void WebUIBidiCheckerBrowserTestFakeBidi::SetUpOnMainThread() {
WebUIBidiCheckerBrowserTest::SetUpOnMainThread();
FilePath pak_path;
app_locale_ = base::i18n::GetConfiguredLocale();
ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path));
pak_path = pak_path.DirName();
pak_path = pak_path.AppendASCII("pseudo_locales");
pak_path = pak_path.AppendASCII("fake-bidi");
pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak"));
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path);
ResourceBundle::ReloadSharedInstance("he");
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
#endif
}
void WebUIBidiCheckerBrowserTestFakeBidi::CleanUpOnMainThread() {
WebUIBidiCheckerBrowserTest::CleanUpOnMainThread();
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR);
#endif
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(FilePath());
ResourceBundle::ReloadSharedInstance(app_locale_);
}
// Tests
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestMainHistoryPageLTR) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.ynet.co.il");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title;
ASSERT_TRUE(UTF8ToUTF16("\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21",
12,
&title));
history_service->SetPageTitle(history_url, title);
RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestMainHistoryPageRTL) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.google.com");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title = UTF8ToUTF16("Google");
history_service->SetPageTitle(history_url, title);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestAboutPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIAboutURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestBugReportPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIBugReportURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestCrashesPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestCrashesPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUICrashesURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestDownloadsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestDownloadsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUIDownloadsURL, true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestNewTabPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestNewTabPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUINewTabURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestPluginsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestPluginsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestSettingsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUISettingsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestSettingsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUISettingsURL, true);
}
#if defined(OS_MACOSX)
// http://crbug.com/94642
#define MAYBE_TestSettingsAutofillPageLTR FLAKY_TestSettingsAutofillPageLTR
#elif defined(OS_WIN)
// http://crbug.com/95425
#define MAYBE_TestSettingsAutofillPageLTR FAILS_TestSettingsAutofillPageLTR
#else
#define MAYBE_TestSettingsAutofillPageLTR TestSettingsAutofillPageLTR
#endif // defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest,
MAYBE_TestSettingsAutofillPageLTR) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"\xD7\x9E\xD7\xA9\xD7\x94",
"\xD7\x91",
"\xD7\x9B\xD7\x94\xD7\x9F",
"moshe.b.cohen@biditest.com",
"\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20\xD7\x91\xD7\xA2\xD7\x9E",
"\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7\x99\xD7\x9F\x20\x32\x33",
"\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36",
"\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99\xD7\x91",
"",
"66183",
"\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C",
"0000");
PersonalDataManager* personal_data_manager =
browser()->profile()->GetPersonalDataManager();
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
RunBidiCheckerOnPage(url.c_str(), false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestSettingsAutofillPageRTL) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"Milton",
"C.",
"Waddams",
"red.swingline@initech.com",
"Initech",
"4120 Freidrich Lane",
"Basement",
"Austin",
"Texas",
"78744",
"United States",
"5125551234");
PersonalDataManager* personal_data_manager =
browser()->profile()->GetPersonalDataManager();
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(url.c_str(), true);
}
<commit_msg>Disable crashing WebUIBidiCheckerBrowserTestFakeBidi.TestNewTabPageRTL<commit_after>// Copyright (c) 2011 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/ui/webui/bidi_checker_web_ui_test.h"
#include "base/base_paths.h"
#include "base/i18n/rtl.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#endif
// These tests are failing on linux views build. crbug.com/96891
#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
#define MAYBE_TestCrashesPageRTL DISABLED_TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL DISABLED_TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL DISABLED_TestMainHistoryPageRTL
#define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL DISABLED_TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL DISABLED_TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL DISABLED_TestSettingsPageRTL
#else
#define MAYBE_TestCrashesPageRTL TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL TestMainHistoryPageRTL
#define MAYBE_TestNewTabPageRTL TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL TestSettingsPageRTL
#endif
// Disabled, http://crbug.com/97453
#define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL
static const FilePath::CharType* kWebUIBidiCheckerLibraryJS =
FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js");
namespace {
FilePath WebUIBidiCheckerLibraryJSPath() {
FilePath src_root;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root))
LOG(ERROR) << "Couldn't find source root";
return src_root.Append(kWebUIBidiCheckerLibraryJS);
}
}
static const FilePath::CharType* kBidiCheckerTestsJS =
FILE_PATH_LITERAL("bidichecker_tests.js");
WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {}
WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {}
void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() {
WebUIBrowserTest::SetUpInProcessBrowserTestFixture();
WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath());
WebUIBrowserTest::AddLibrary(FilePath(kBidiCheckerTestsJS));
}
void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(const char pageURL[],
bool isRTL) {
ui_test_utils::NavigateToURL(browser(), GURL(pageURL));
ASSERT_TRUE(RunJavascriptTest("runBidiChecker",
Value::CreateStringValue(pageURL),
Value::CreateBooleanValue(isRTL)));
}
// WebUIBidiCheckerBrowserTestFakeBidi
WebUIBidiCheckerBrowserTestFakeBidi::~WebUIBidiCheckerBrowserTestFakeBidi() {}
WebUIBidiCheckerBrowserTestFakeBidi::WebUIBidiCheckerBrowserTestFakeBidi() {}
void WebUIBidiCheckerBrowserTestFakeBidi::SetUpOnMainThread() {
WebUIBidiCheckerBrowserTest::SetUpOnMainThread();
FilePath pak_path;
app_locale_ = base::i18n::GetConfiguredLocale();
ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path));
pak_path = pak_path.DirName();
pak_path = pak_path.AppendASCII("pseudo_locales");
pak_path = pak_path.AppendASCII("fake-bidi");
pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak"));
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path);
ResourceBundle::ReloadSharedInstance("he");
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
#endif
}
void WebUIBidiCheckerBrowserTestFakeBidi::CleanUpOnMainThread() {
WebUIBidiCheckerBrowserTest::CleanUpOnMainThread();
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR);
#endif
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(FilePath());
ResourceBundle::ReloadSharedInstance(app_locale_);
}
// Tests
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestMainHistoryPageLTR) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.ynet.co.il");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title;
ASSERT_TRUE(UTF8ToUTF16("\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21",
12,
&title));
history_service->SetPageTitle(history_url, title);
RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestMainHistoryPageRTL) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.google.com");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title = UTF8ToUTF16("Google");
history_service->SetPageTitle(history_url, title);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestAboutPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIAboutURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestBugReportPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIBugReportURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestCrashesPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestCrashesPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUICrashesURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestDownloadsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestDownloadsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUIDownloadsURL, true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestNewTabPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestNewTabPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUINewTabURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestPluginsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestPluginsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestSettingsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUISettingsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestSettingsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUISettingsURL, true);
}
#if defined(OS_MACOSX)
// http://crbug.com/94642
#define MAYBE_TestSettingsAutofillPageLTR FLAKY_TestSettingsAutofillPageLTR
#elif defined(OS_WIN)
// http://crbug.com/95425
#define MAYBE_TestSettingsAutofillPageLTR FAILS_TestSettingsAutofillPageLTR
#else
#define MAYBE_TestSettingsAutofillPageLTR TestSettingsAutofillPageLTR
#endif // defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest,
MAYBE_TestSettingsAutofillPageLTR) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"\xD7\x9E\xD7\xA9\xD7\x94",
"\xD7\x91",
"\xD7\x9B\xD7\x94\xD7\x9F",
"moshe.b.cohen@biditest.com",
"\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20\xD7\x91\xD7\xA2\xD7\x9E",
"\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7\x99\xD7\x9F\x20\x32\x33",
"\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36",
"\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99\xD7\x91",
"",
"66183",
"\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C",
"0000");
PersonalDataManager* personal_data_manager =
browser()->profile()->GetPersonalDataManager();
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
RunBidiCheckerOnPage(url.c_str(), false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestSettingsAutofillPageRTL) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"Milton",
"C.",
"Waddams",
"red.swingline@initech.com",
"Initech",
"4120 Freidrich Lane",
"Basement",
"Austin",
"Texas",
"78744",
"United States",
"5125551234");
PersonalDataManager* personal_data_manager =
browser()->profile()->GetPersonalDataManager();
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(url.c_str(), true);
}
<|endoftext|> |
<commit_before>// selfdestructing.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "crash_on_copy.hpp"
#include <iostream>
#include <vector>
#include <functional>
#include <cassert>
struct TestNumberCrash : public crashes::on<2>::copies {};
struct TestCopyNrCrash : public crashes::after<2>::copies {};
struct TestTotalNrCrash : public crashes::on_total<2,TestTotalNrCrash>::instances {};
struct TestAfterTotalNrCrash : public crashes::after_total<2,TestAfterTotalNrCrash>::instances {};
int main(int argc, char* argv[])
{
std::vector<std::pair<std::function<void()>,bool>> tests;
tests.push_back(std::make_pair([]{
TestNumberCrash C;
C.set_feedback([](int num) { std::cout<<num<<std::endl; });
TestNumberCrash C2=C;
TestNumberCrash C3=C;
},true));
tests.push_back(std::make_pair([]{
TestCopyNrCrash C;
C.set_feedback([](int num) { std::cout<<num<<std::endl; });
TestCopyNrCrash C2=C;
TestCopyNrCrash C3=C;
},false));
tests.push_back(std::make_pair([]{
TestCopyNrCrash C;
C.set_feedback([](int num) { std::cout<<num<<std::endl; });
TestCopyNrCrash C2=C;
TestCopyNrCrash C3=C2;
},true));
tests.push_back(std::make_pair([]{
TestTotalNrCrash C;
TestTotalNrCrash C2;
},true));
tests.push_back(std::make_pair([]{
{ TestTotalNrCrash C; }
TestTotalNrCrash C;
},false));
tests.push_back(std::make_pair([]{
TestTotalNrCrash C;
TestTotalNrCrash C2=C;
},true));
tests.push_back(std::make_pair([]{
{ TestAfterTotalNrCrash C; }
TestAfterTotalNrCrash C;
},true));
tests.push_back(std::make_pair([]{
TestAfterTotalNrCrash C;
TestAfterTotalNrCrash C2=C;
},true));
for (auto test : tests) {
bool crashed=false;
try {
test.first();
} catch (std::exception& e) {
crashed=true;
std::cout<<e.what()<<std::endl;
}
assert(crashed==test.second);
}
return 0;
}
<commit_msg>locality of test classes<commit_after>// selfdestructing.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "crash_on_copy.hpp"
#include <iostream>
#include <vector>
#include <functional>
#include <cassert>
int main(int argc, char* argv[])
{
std::vector<std::pair<std::function<void()>,bool>> tests;
// testing use by inheritance
struct TestNumberCrash : public crashes::on<2>::copies {};
tests.push_back(std::make_pair([]{
TestNumberCrash C;
C.set_feedback([](int num) { std::cout<<num<<std::endl; });
TestNumberCrash C2=C;
TestNumberCrash C3=C;
},true));
struct TestCopyNrCrash : public crashes::after<2>::copies {};
tests.push_back(std::make_pair([]{
TestCopyNrCrash C;
C.set_feedback([](int num) { std::cout<<num<<std::endl; });
TestCopyNrCrash C2=C;
TestCopyNrCrash C3=C;
},false));
tests.push_back(std::make_pair([]{
TestCopyNrCrash C;
C.set_feedback([](int num) { std::cout<<num<<std::endl; });
TestCopyNrCrash C2=C;
TestCopyNrCrash C3=C2;
},true));
struct TestTotalNrCrash : public crashes::on_total<2,TestTotalNrCrash>::instances {};
tests.push_back(std::make_pair([]{
TestTotalNrCrash C;
TestTotalNrCrash C2;
},true));
tests.push_back(std::make_pair([]{
{ TestTotalNrCrash C; }
TestTotalNrCrash C;
},false));
tests.push_back(std::make_pair([]{
TestTotalNrCrash C;
TestTotalNrCrash C2=C;
},true));
struct TestAfterTotalNrCrash : public crashes::after_total<2,TestAfterTotalNrCrash>::instances {};
tests.push_back(std::make_pair([]{
{ TestAfterTotalNrCrash C; }
TestAfterTotalNrCrash C;
},true));
tests.push_back(std::make_pair([]{
TestAfterTotalNrCrash C;
TestAfterTotalNrCrash C2=C;
},true));
// testing use by aggregation
struct TestNumberCrashMember { crashes::on<2>::copies _; };
tests.push_back(std::make_pair([]{
TestNumberCrashMember C;
C._.set_feedback([](int num) { std::cout<<num<<std::endl; });
TestNumberCrashMember C2=C;
TestNumberCrashMember C3=C;
},true));
struct TestCopyNrCrashMember { crashes::after<2>::copies _; };
tests.push_back(std::make_pair([]{
TestCopyNrCrashMember C;
C._.set_feedback([](int num) { std::cout<<num<<std::endl; });
TestCopyNrCrashMember C2=C;
TestCopyNrCrashMember C3=C;
},false));
tests.push_back(std::make_pair([]{
TestCopyNrCrashMember C;
C._.set_feedback([](int num) { std::cout<<num<<std::endl; });
TestCopyNrCrashMember C2=C;
TestCopyNrCrashMember C3=C2;
},true));
struct TestTotalNrCrashMember { crashes::on_total<2,TestTotalNrCrashMember>::instances _; };
tests.push_back(std::make_pair([]{
TestTotalNrCrashMember C;
TestTotalNrCrashMember C2;
},true));
tests.push_back(std::make_pair([]{
{ TestTotalNrCrashMember C; }
TestTotalNrCrashMember C;
},false));
tests.push_back(std::make_pair([]{
TestTotalNrCrashMember C;
TestTotalNrCrashMember C2=C;
},true));
struct TestAfterTotalNrCrashMember { crashes::after_total<2,TestAfterTotalNrCrashMember>::instances _; };
tests.push_back(std::make_pair([]{
{ TestAfterTotalNrCrashMember C; }
TestAfterTotalNrCrashMember C;
},true));
tests.push_back(std::make_pair([]{
TestAfterTotalNrCrashMember C;
TestAfterTotalNrCrashMember C2=C;
},true));
for (auto test : tests) {
bool crashed=false;
try {
test.first();
} catch (std::exception& e) {
crashed=true;
std::cout<<e.what()<<std::endl;
}
assert(crashed==test.second);
}
return 0;
}
<|endoftext|> |
<commit_before>//===-- DataExtractor.cpp -------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/DataExtractor.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/SwapByteOrder.h"
using namespace llvm;
template <typename T>
static T getU(uint32_t *offset_ptr, const DataExtractor *de,
bool isLittleEndian, const char *Data) {
T val = 0;
uint32_t offset = *offset_ptr;
if (de->isValidOffsetForDataOfSize(offset, sizeof(val))) {
std::memcpy(&val, &Data[offset], sizeof(val));
if (sys::IsLittleEndianHost != isLittleEndian)
sys::swapByteOrder(val);
// Advance the offset
*offset_ptr += sizeof(val);
}
return val;
}
template <typename T>
static T *getUs(uint32_t *offset_ptr, T *dst, uint32_t count,
const DataExtractor *de, bool isLittleEndian, const char *Data){
uint32_t offset = *offset_ptr;
if (count > 0 && de->isValidOffsetForDataOfSize(offset, sizeof(*dst)*count)) {
for (T *value_ptr = dst, *end = dst + count; value_ptr != end;
++value_ptr, offset += sizeof(*dst))
*value_ptr = getU<T>(offset_ptr, de, isLittleEndian, Data);
// Advance the offset
*offset_ptr = offset;
// Return a non-NULL pointer to the converted data as an indicator of
// success
return dst;
}
return nullptr;
}
uint8_t DataExtractor::getU8(uint32_t *offset_ptr) const {
return getU<uint8_t>(offset_ptr, this, IsLittleEndian, Data.data());
}
uint8_t *
DataExtractor::getU8(uint32_t *offset_ptr, uint8_t *dst, uint32_t count) const {
return getUs<uint8_t>(offset_ptr, dst, count, this, IsLittleEndian,
Data.data());
}
uint16_t DataExtractor::getU16(uint32_t *offset_ptr) const {
return getU<uint16_t>(offset_ptr, this, IsLittleEndian, Data.data());
}
uint16_t *DataExtractor::getU16(uint32_t *offset_ptr, uint16_t *dst,
uint32_t count) const {
return getUs<uint16_t>(offset_ptr, dst, count, this, IsLittleEndian,
Data.data());
}
uint32_t DataExtractor::getU24(uint32_t *offset_ptr) const {
uint24_t ExtractedVal =
getU<uint24_t>(offset_ptr, this, IsLittleEndian, Data.data());
// The 3 bytes are in the correct byte order for the host.
return ExtractedVal.getAsUint32(sys::IsLittleEndianHost);
}
uint32_t DataExtractor::getU32(uint32_t *offset_ptr) const {
return getU<uint32_t>(offset_ptr, this, IsLittleEndian, Data.data());
}
uint32_t *DataExtractor::getU32(uint32_t *offset_ptr, uint32_t *dst,
uint32_t count) const {
return getUs<uint32_t>(offset_ptr, dst, count, this, IsLittleEndian,
Data.data());
}
uint64_t DataExtractor::getU64(uint32_t *offset_ptr) const {
return getU<uint64_t>(offset_ptr, this, IsLittleEndian, Data.data());
}
uint64_t *DataExtractor::getU64(uint32_t *offset_ptr, uint64_t *dst,
uint32_t count) const {
return getUs<uint64_t>(offset_ptr, dst, count, this, IsLittleEndian,
Data.data());
}
uint64_t
DataExtractor::getUnsigned(uint32_t *offset_ptr, uint32_t byte_size) const {
switch (byte_size) {
case 1:
return getU8(offset_ptr);
case 2:
return getU16(offset_ptr);
case 4:
return getU32(offset_ptr);
case 8:
return getU64(offset_ptr);
}
llvm_unreachable("getUnsigned unhandled case!");
}
int64_t
DataExtractor::getSigned(uint32_t *offset_ptr, uint32_t byte_size) const {
switch (byte_size) {
case 1:
return (int8_t)getU8(offset_ptr);
case 2:
return (int16_t)getU16(offset_ptr);
case 4:
return (int32_t)getU32(offset_ptr);
case 8:
return (int64_t)getU64(offset_ptr);
}
llvm_unreachable("getSigned unhandled case!");
}
const char *DataExtractor::getCStr(uint32_t *offset_ptr) const {
uint32_t offset = *offset_ptr;
StringRef::size_type pos = Data.find('\0', offset);
if (pos != StringRef::npos) {
*offset_ptr = pos + 1;
return Data.data() + offset;
}
return nullptr;
}
StringRef DataExtractor::getCStrRef(uint32_t *OffsetPtr) const {
uint32_t Start = *OffsetPtr;
StringRef::size_type Pos = Data.find('\0', Start);
if (Pos != StringRef::npos) {
*OffsetPtr = Pos + 1;
return StringRef(Data.data() + Start, Pos - Start);
}
return StringRef();
}
uint64_t DataExtractor::getULEB128(uint32_t *offset_ptr) const {
uint64_t result = 0;
if (Data.empty())
return 0;
unsigned shift = 0;
uint32_t offset = *offset_ptr;
uint8_t byte = 0;
while (isValidOffset(offset)) {
byte = Data[offset++];
result |= uint64_t(byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
*offset_ptr = offset;
return result;
}
}
return 0;
}
int64_t DataExtractor::getSLEB128(uint32_t *offset_ptr) const {
int64_t result = 0;
if (Data.empty())
return 0;
unsigned shift = 0;
uint32_t offset = *offset_ptr;
uint8_t byte = 0;
while (isValidOffset(offset)) {
byte = Data[offset++];
result |= uint64_t(byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
// Sign bit of byte is 2nd high order bit (0x40)
if (shift < 64 && (byte & 0x40))
result |= -(1ULL << shift);
*offset_ptr = offset;
return result;
}
}
return 0;
}
<commit_msg>NFC: DataExtractor: use decodeULEB128 to implement getULEB128<commit_after>//===-- DataExtractor.cpp -------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/DataExtractor.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/SwapByteOrder.h"
#include "llvm/Support/LEB128.h"
using namespace llvm;
template <typename T>
static T getU(uint32_t *offset_ptr, const DataExtractor *de,
bool isLittleEndian, const char *Data) {
T val = 0;
uint32_t offset = *offset_ptr;
if (de->isValidOffsetForDataOfSize(offset, sizeof(val))) {
std::memcpy(&val, &Data[offset], sizeof(val));
if (sys::IsLittleEndianHost != isLittleEndian)
sys::swapByteOrder(val);
// Advance the offset
*offset_ptr += sizeof(val);
}
return val;
}
template <typename T>
static T *getUs(uint32_t *offset_ptr, T *dst, uint32_t count,
const DataExtractor *de, bool isLittleEndian, const char *Data){
uint32_t offset = *offset_ptr;
if (count > 0 && de->isValidOffsetForDataOfSize(offset, sizeof(*dst)*count)) {
for (T *value_ptr = dst, *end = dst + count; value_ptr != end;
++value_ptr, offset += sizeof(*dst))
*value_ptr = getU<T>(offset_ptr, de, isLittleEndian, Data);
// Advance the offset
*offset_ptr = offset;
// Return a non-NULL pointer to the converted data as an indicator of
// success
return dst;
}
return nullptr;
}
uint8_t DataExtractor::getU8(uint32_t *offset_ptr) const {
return getU<uint8_t>(offset_ptr, this, IsLittleEndian, Data.data());
}
uint8_t *
DataExtractor::getU8(uint32_t *offset_ptr, uint8_t *dst, uint32_t count) const {
return getUs<uint8_t>(offset_ptr, dst, count, this, IsLittleEndian,
Data.data());
}
uint16_t DataExtractor::getU16(uint32_t *offset_ptr) const {
return getU<uint16_t>(offset_ptr, this, IsLittleEndian, Data.data());
}
uint16_t *DataExtractor::getU16(uint32_t *offset_ptr, uint16_t *dst,
uint32_t count) const {
return getUs<uint16_t>(offset_ptr, dst, count, this, IsLittleEndian,
Data.data());
}
uint32_t DataExtractor::getU24(uint32_t *offset_ptr) const {
uint24_t ExtractedVal =
getU<uint24_t>(offset_ptr, this, IsLittleEndian, Data.data());
// The 3 bytes are in the correct byte order for the host.
return ExtractedVal.getAsUint32(sys::IsLittleEndianHost);
}
uint32_t DataExtractor::getU32(uint32_t *offset_ptr) const {
return getU<uint32_t>(offset_ptr, this, IsLittleEndian, Data.data());
}
uint32_t *DataExtractor::getU32(uint32_t *offset_ptr, uint32_t *dst,
uint32_t count) const {
return getUs<uint32_t>(offset_ptr, dst, count, this, IsLittleEndian,
Data.data());
}
uint64_t DataExtractor::getU64(uint32_t *offset_ptr) const {
return getU<uint64_t>(offset_ptr, this, IsLittleEndian, Data.data());
}
uint64_t *DataExtractor::getU64(uint32_t *offset_ptr, uint64_t *dst,
uint32_t count) const {
return getUs<uint64_t>(offset_ptr, dst, count, this, IsLittleEndian,
Data.data());
}
uint64_t
DataExtractor::getUnsigned(uint32_t *offset_ptr, uint32_t byte_size) const {
switch (byte_size) {
case 1:
return getU8(offset_ptr);
case 2:
return getU16(offset_ptr);
case 4:
return getU32(offset_ptr);
case 8:
return getU64(offset_ptr);
}
llvm_unreachable("getUnsigned unhandled case!");
}
int64_t
DataExtractor::getSigned(uint32_t *offset_ptr, uint32_t byte_size) const {
switch (byte_size) {
case 1:
return (int8_t)getU8(offset_ptr);
case 2:
return (int16_t)getU16(offset_ptr);
case 4:
return (int32_t)getU32(offset_ptr);
case 8:
return (int64_t)getU64(offset_ptr);
}
llvm_unreachable("getSigned unhandled case!");
}
const char *DataExtractor::getCStr(uint32_t *offset_ptr) const {
uint32_t offset = *offset_ptr;
StringRef::size_type pos = Data.find('\0', offset);
if (pos != StringRef::npos) {
*offset_ptr = pos + 1;
return Data.data() + offset;
}
return nullptr;
}
StringRef DataExtractor::getCStrRef(uint32_t *OffsetPtr) const {
uint32_t Start = *OffsetPtr;
StringRef::size_type Pos = Data.find('\0', Start);
if (Pos != StringRef::npos) {
*OffsetPtr = Pos + 1;
return StringRef(Data.data() + Start, Pos - Start);
}
return StringRef();
}
uint64_t DataExtractor::getULEB128(uint32_t *offset_ptr) const {
assert(*offset_ptr <= Data.size());
const char *error;
unsigned bytes_read;
uint64_t result = decodeULEB128(
reinterpret_cast<const uint8_t *>(Data.data() + *offset_ptr), &bytes_read,
reinterpret_cast<const uint8_t *>(Data.data() + Data.size()), &error);
if (error)
return 0;
*offset_ptr += bytes_read;
return result;
}
int64_t DataExtractor::getSLEB128(uint32_t *offset_ptr) const {
int64_t result = 0;
if (Data.empty())
return 0;
unsigned shift = 0;
uint32_t offset = *offset_ptr;
uint8_t byte = 0;
while (isValidOffset(offset)) {
byte = Data[offset++];
result |= uint64_t(byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
// Sign bit of byte is 2nd high order bit (0x40)
if (shift < 64 && (byte & 0x40))
result |= -(1ULL << shift);
*offset_ptr = offset;
return result;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: resultset.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 12:20:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _DATASUPPLIER_HXX
#include <provider/datasupplier.hxx>
#endif
#ifndef _RESULTSET_HXX
#include <provider/resultset.hxx>
#endif
#ifndef _RESULTSETFACTORY_HXX
#include <provider/resultsetfactory.hxx>
#endif
using namespace com::sun::star::lang;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
using namespace chelp;
//=========================================================================
//=========================================================================
//
// DynamicResultSet Implementation.
//
//=========================================================================
//=========================================================================
DynamicResultSet::DynamicResultSet(
const Reference< XMultiServiceFactory >& rxSMgr,
const vos::ORef< Content >& rxContent,
const OpenCommandArgument2& rCommand,
const Reference< XCommandEnvironment >& rxEnv,
ResultSetFactory* pFactory )
: ResultSetImplHelper( rxSMgr, rCommand ),
m_xContent( rxContent ),
m_xEnv( rxEnv ),
m_pFactory( pFactory )
{
}
DynamicResultSet::~DynamicResultSet()
{
delete m_pFactory;
}
//=========================================================================
//
// Non-interface methods.
//
//=========================================================================
void DynamicResultSet::initStatic()
{
m_xResultSet1 = Reference< XResultSet >( m_pFactory->createResultSet() );
}
//=========================================================================
void DynamicResultSet::initDynamic()
{
m_xResultSet1 = Reference< XResultSet >( m_pFactory->createResultSet() );
m_xResultSet2 = m_xResultSet1;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.2.18); FILE MERGED 2006/04/19 16:00:11 sb 1.2.18.1: #i53898# Removed dead code.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: resultset.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-20 00:39:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _RESULTSET_HXX
#include <provider/resultset.hxx>
#endif
#ifndef _RESULTSETFACTORY_HXX
#include <provider/resultsetfactory.hxx>
#endif
using namespace com::sun::star::lang;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
using namespace chelp;
//=========================================================================
//=========================================================================
//
// DynamicResultSet Implementation.
//
//=========================================================================
//=========================================================================
DynamicResultSet::DynamicResultSet(
const Reference< XMultiServiceFactory >& rxSMgr,
const vos::ORef< Content >& rxContent,
const OpenCommandArgument2& rCommand,
const Reference< XCommandEnvironment >& rxEnv,
ResultSetFactory* pFactory )
: ResultSetImplHelper( rxSMgr, rCommand ),
m_xContent( rxContent ),
m_xEnv( rxEnv ),
m_pFactory( pFactory )
{
}
DynamicResultSet::~DynamicResultSet()
{
delete m_pFactory;
}
//=========================================================================
//
// Non-interface methods.
//
//=========================================================================
void DynamicResultSet::initStatic()
{
m_xResultSet1 = Reference< XResultSet >( m_pFactory->createResultSet() );
}
//=========================================================================
void DynamicResultSet::initDynamic()
{
m_xResultSet1 = Reference< XResultSet >( m_pFactory->createResultSet() );
m_xResultSet2 = m_xResultSet1;
}
<|endoftext|> |
<commit_before>//===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCLabel.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/Signals.h"
using namespace llvm;
typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
MCContext::MCContext(const MCAsmInfo &mai, const MCRegisterInfo &mri,
const MCObjectFileInfo *mofi, const SourceMgr *mgr) :
SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
Allocator(), Symbols(Allocator), UsedNames(Allocator),
NextUniqueID(0),
CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
AllowTemporaryLabels(true) {
MachOUniquingMap = 0;
ELFUniquingMap = 0;
COFFUniquingMap = 0;
SecureLogFile = getenv("AS_SECURE_LOG_FILE");
SecureLog = 0;
SecureLogUsed = false;
DwarfLocSeen = false;
GenDwarfForAssembly = false;
GenDwarfFileNumber = 0;
}
MCContext::~MCContext() {
// NOTE: The symbols are all allocated out of a bump pointer allocator,
// we don't need to free them here.
// If we have the MachO uniquing map, free it.
delete (MachOUniqueMapTy*)MachOUniquingMap;
delete (ELFUniqueMapTy*)ELFUniquingMap;
delete (COFFUniqueMapTy*)COFFUniquingMap;
// If the stream for the .secure_log_unique directive was created free it.
delete (raw_ostream*)SecureLog;
}
//===----------------------------------------------------------------------===//
// Symbol Manipulation
//===----------------------------------------------------------------------===//
MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
assert(!Name.empty() && "Normal symbols cannot be unnamed!");
// Do the lookup and get the entire StringMapEntry. We want access to the
// key if we are creating the entry.
StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
MCSymbol *Sym = Entry.getValue();
if (Sym)
return Sym;
Sym = CreateSymbol(Name);
Entry.setValue(Sym);
return Sym;
}
MCSymbol *MCContext::CreateSymbol(StringRef Name) {
// Determine whether this is an assembler temporary or normal label, if used.
bool isTemporary = false;
if (AllowTemporaryLabels)
isTemporary = Name.startswith(MAI.getPrivateGlobalPrefix());
StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
if (NameEntry->getValue()) {
assert(isTemporary && "Cannot rename non temporary symbols");
SmallString<128> NewName = Name;
do {
NewName.resize(Name.size());
raw_svector_ostream(NewName) << NextUniqueID++;
NameEntry = &UsedNames.GetOrCreateValue(NewName);
} while (NameEntry->getValue());
}
NameEntry->setValue(true);
// Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
// to the copy of the string that is embedded in the UsedNames entry.
MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
return Result;
}
MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
SmallString<128> NameSV;
Name.toVector(NameSV);
return GetOrCreateSymbol(NameSV.str());
}
MCSymbol *MCContext::CreateTempSymbol() {
SmallString<128> NameSV;
raw_svector_ostream(NameSV)
<< MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
return CreateSymbol(NameSV);
}
unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
MCLabel *&Label = Instances[LocalLabelVal];
if (!Label)
Label = new (*this) MCLabel(0);
return Label->incInstance();
}
unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
MCLabel *&Label = Instances[LocalLabelVal];
if (!Label)
Label = new (*this) MCLabel(0);
return Label->getInstance();
}
MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
Twine(LocalLabelVal) +
"\2" +
Twine(NextInstance(LocalLabelVal)));
}
MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
int bORf) {
return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
Twine(LocalLabelVal) +
"\2" +
Twine(GetInstance(LocalLabelVal) + bORf));
}
MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
return Symbols.lookup(Name);
}
//===----------------------------------------------------------------------===//
// Section Management
//===----------------------------------------------------------------------===//
const MCSectionMachO *MCContext::
getMachOSection(StringRef Segment, StringRef Section,
unsigned TypeAndAttributes,
unsigned Reserved2, SectionKind Kind) {
// We unique sections by their segment/section pair. The returned section
// may not have the same flags as the requested section, if so this should be
// diagnosed by the client as an error.
// Create the map if it doesn't already exist.
if (MachOUniquingMap == 0)
MachOUniquingMap = new MachOUniqueMapTy();
MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
// Form the name to look up.
SmallString<64> Name;
Name += Segment;
Name.push_back(',');
Name += Section;
// Do the lookup, if we have a hit, return it.
const MCSectionMachO *&Entry = Map[Name.str()];
if (Entry) return Entry;
// Otherwise, return a new section.
return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
Reserved2, Kind);
}
const MCSectionELF *MCContext::
getELFSection(StringRef Section, unsigned Type, unsigned Flags,
SectionKind Kind) {
return getELFSection(Section, Type, Flags, Kind, 0, "");
}
const MCSectionELF *MCContext::
getELFSection(StringRef Section, unsigned Type, unsigned Flags,
SectionKind Kind, unsigned EntrySize, StringRef Group) {
if (ELFUniquingMap == 0)
ELFUniquingMap = new ELFUniqueMapTy();
ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
// Do the lookup, if we have a hit, return it.
StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
if (Entry.getValue()) return Entry.getValue();
// Possibly refine the entry size first.
if (!EntrySize) {
EntrySize = MCSectionELF::DetermineEntrySize(Kind);
}
MCSymbol *GroupSym = NULL;
if (!Group.empty())
GroupSym = GetOrCreateSymbol(Group);
MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
Kind, EntrySize, GroupSym);
Entry.setValue(Result);
return Result;
}
const MCSectionELF *MCContext::CreateELFGroupSection() {
MCSectionELF *Result =
new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
SectionKind::getReadOnly(), 4, NULL);
return Result;
}
const MCSection *MCContext::getCOFFSection(StringRef Section,
unsigned Characteristics,
int Selection,
SectionKind Kind) {
if (COFFUniquingMap == 0)
COFFUniquingMap = new COFFUniqueMapTy();
COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
// Do the lookup, if we have a hit, return it.
StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
if (Entry.getValue()) return Entry.getValue();
MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
Characteristics,
Selection, Kind);
Entry.setValue(Result);
return Result;
}
//===----------------------------------------------------------------------===//
// Dwarf Management
//===----------------------------------------------------------------------===//
/// GetDwarfFile - takes a file name an number to place in the dwarf file and
/// directory tables. If the file number has already been allocated it is an
/// error and zero is returned and the client reports the error, else the
/// allocated file number is returned. The file numbers may be in any order.
unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
unsigned FileNumber) {
// TODO: a FileNumber of zero says to use the next available file number.
// Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
// to not be less than one. This needs to be change to be not less than zero.
// Make space for this FileNumber in the MCDwarfFiles vector if needed.
if (FileNumber >= MCDwarfFiles.size()) {
MCDwarfFiles.resize(FileNumber + 1);
} else {
MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
if (ExistingFile)
// It is an error to use see the same number more than once.
return 0;
}
// Get the new MCDwarfFile slot for this FileNumber.
MCDwarfFile *&File = MCDwarfFiles[FileNumber];
if (Directory.empty()) {
// Separate the directory part from the basename of the FileName.
StringRef tFileName = sys::path::filename(FileName);
if (!tFileName.empty()) {
Directory = sys::path::parent_path(FileName);
if (!Directory.empty())
FileName = sys::path::filename(FileName);
}
}
// Find or make a entry in the MCDwarfDirs vector for this Directory.
// Capture directory name.
unsigned DirIndex;
if (Directory.empty()) {
// For FileNames with no directories a DirIndex of 0 is used.
DirIndex = 0;
} else {
DirIndex = 0;
for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
if (Directory == MCDwarfDirs[DirIndex])
break;
}
if (DirIndex >= MCDwarfDirs.size()) {
char *Buf = static_cast<char *>(Allocate(Directory.size()));
memcpy(Buf, Directory.data(), Directory.size());
MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
}
// The DirIndex is one based, as DirIndex of 0 is used for FileNames with
// no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
// directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
// are stored at MCDwarfFiles[FileNumber].Name .
DirIndex++;
}
// Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
// vector.
char *Buf = static_cast<char *>(Allocate(FileName.size()));
memcpy(Buf, FileName.data(), FileName.size());
File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
// return the allocated FileNumber.
return FileNumber;
}
/// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
/// currently is assigned and false otherwise.
bool MCContext::isValidDwarfFileNumber(unsigned FileNumber) {
if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
return false;
return MCDwarfFiles[FileNumber] != 0;
}
void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
// If we have a source manager and a location, use it. Otherwise just
// use the generic report_fatal_error().
if (!SrcMgr || Loc == SMLoc())
report_fatal_error(Msg);
// Use the source manager to print the message.
SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
// If we reached here, we are failing ungracefully. Run the interrupt handlers
// to make sure any special cleanups get done, in particular that we remove
// files registered with RemoveFileOnSignal.
sys::RunInterruptHandlers();
exit(1);
}
<commit_msg>MCContext.cpp: Fixup for my odd previous commit. No functional changes.<commit_after>//===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCLabel.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/Signals.h"
using namespace llvm;
typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
MCContext::MCContext(const MCAsmInfo &mai, const MCRegisterInfo &mri,
const MCObjectFileInfo *mofi, const SourceMgr *mgr) :
SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
Allocator(), Symbols(Allocator), UsedNames(Allocator),
NextUniqueID(0),
CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
AllowTemporaryLabels(true) {
MachOUniquingMap = 0;
ELFUniquingMap = 0;
COFFUniquingMap = 0;
SecureLogFile = getenv("AS_SECURE_LOG_FILE");
SecureLog = 0;
SecureLogUsed = false;
DwarfLocSeen = false;
GenDwarfForAssembly = false;
GenDwarfFileNumber = 0;
}
MCContext::~MCContext() {
// NOTE: The symbols are all allocated out of a bump pointer allocator,
// we don't need to free them here.
// If we have the MachO uniquing map, free it.
delete (MachOUniqueMapTy*)MachOUniquingMap;
delete (ELFUniqueMapTy*)ELFUniquingMap;
delete (COFFUniqueMapTy*)COFFUniquingMap;
// If the stream for the .secure_log_unique directive was created free it.
delete (raw_ostream*)SecureLog;
}
//===----------------------------------------------------------------------===//
// Symbol Manipulation
//===----------------------------------------------------------------------===//
MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
assert(!Name.empty() && "Normal symbols cannot be unnamed!");
// Do the lookup and get the entire StringMapEntry. We want access to the
// key if we are creating the entry.
StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
MCSymbol *Sym = Entry.getValue();
if (Sym)
return Sym;
Sym = CreateSymbol(Name);
Entry.setValue(Sym);
return Sym;
}
MCSymbol *MCContext::CreateSymbol(StringRef Name) {
// Determine whether this is an assembler temporary or normal label, if used.
bool isTemporary = false;
if (AllowTemporaryLabels)
isTemporary = Name.startswith(MAI.getPrivateGlobalPrefix());
StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
if (NameEntry->getValue()) {
assert(isTemporary && "Cannot rename non temporary symbols");
SmallString<128> NewName = Name;
do {
NewName.resize(Name.size());
raw_svector_ostream(NewName) << NextUniqueID++;
NameEntry = &UsedNames.GetOrCreateValue(NewName);
} while (NameEntry->getValue());
}
NameEntry->setValue(true);
// Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
// to the copy of the string that is embedded in the UsedNames entry.
MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
return Result;
}
MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
SmallString<128> NameSV;
Name.toVector(NameSV);
return GetOrCreateSymbol(NameSV.str());
}
MCSymbol *MCContext::CreateTempSymbol() {
SmallString<128> NameSV;
raw_svector_ostream(NameSV)
<< MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
return CreateSymbol(NameSV);
}
unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
MCLabel *&Label = Instances[LocalLabelVal];
if (!Label)
Label = new (*this) MCLabel(0);
return Label->incInstance();
}
unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
MCLabel *&Label = Instances[LocalLabelVal];
if (!Label)
Label = new (*this) MCLabel(0);
return Label->getInstance();
}
MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
Twine(LocalLabelVal) +
"\2" +
Twine(NextInstance(LocalLabelVal)));
}
MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
int bORf) {
return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
Twine(LocalLabelVal) +
"\2" +
Twine(GetInstance(LocalLabelVal) + bORf));
}
MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
return Symbols.lookup(Name);
}
//===----------------------------------------------------------------------===//
// Section Management
//===----------------------------------------------------------------------===//
const MCSectionMachO *MCContext::
getMachOSection(StringRef Segment, StringRef Section,
unsigned TypeAndAttributes,
unsigned Reserved2, SectionKind Kind) {
// We unique sections by their segment/section pair. The returned section
// may not have the same flags as the requested section, if so this should be
// diagnosed by the client as an error.
// Create the map if it doesn't already exist.
if (MachOUniquingMap == 0)
MachOUniquingMap = new MachOUniqueMapTy();
MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
// Form the name to look up.
SmallString<64> Name;
Name += Segment;
Name.push_back(',');
Name += Section;
// Do the lookup, if we have a hit, return it.
const MCSectionMachO *&Entry = Map[Name.str()];
if (Entry) return Entry;
// Otherwise, return a new section.
return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
Reserved2, Kind);
}
const MCSectionELF *MCContext::
getELFSection(StringRef Section, unsigned Type, unsigned Flags,
SectionKind Kind) {
return getELFSection(Section, Type, Flags, Kind, 0, "");
}
const MCSectionELF *MCContext::
getELFSection(StringRef Section, unsigned Type, unsigned Flags,
SectionKind Kind, unsigned EntrySize, StringRef Group) {
if (ELFUniquingMap == 0)
ELFUniquingMap = new ELFUniqueMapTy();
ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
// Do the lookup, if we have a hit, return it.
StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
if (Entry.getValue()) return Entry.getValue();
// Possibly refine the entry size first.
if (!EntrySize) {
EntrySize = MCSectionELF::DetermineEntrySize(Kind);
}
MCSymbol *GroupSym = NULL;
if (!Group.empty())
GroupSym = GetOrCreateSymbol(Group);
MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
Kind, EntrySize, GroupSym);
Entry.setValue(Result);
return Result;
}
const MCSectionELF *MCContext::CreateELFGroupSection() {
MCSectionELF *Result =
new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
SectionKind::getReadOnly(), 4, NULL);
return Result;
}
const MCSection *MCContext::getCOFFSection(StringRef Section,
unsigned Characteristics,
int Selection,
SectionKind Kind) {
if (COFFUniquingMap == 0)
COFFUniquingMap = new COFFUniqueMapTy();
COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
// Do the lookup, if we have a hit, return it.
StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
if (Entry.getValue()) return Entry.getValue();
MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
Characteristics,
Selection, Kind);
Entry.setValue(Result);
return Result;
}
//===----------------------------------------------------------------------===//
// Dwarf Management
//===----------------------------------------------------------------------===//
/// GetDwarfFile - takes a file name an number to place in the dwarf file and
/// directory tables. If the file number has already been allocated it is an
/// error and zero is returned and the client reports the error, else the
/// allocated file number is returned. The file numbers may be in any order.
unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
unsigned FileNumber) {
// TODO: a FileNumber of zero says to use the next available file number.
// Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
// to not be less than one. This needs to be change to be not less than zero.
// Make space for this FileNumber in the MCDwarfFiles vector if needed.
if (FileNumber >= MCDwarfFiles.size()) {
MCDwarfFiles.resize(FileNumber + 1);
} else {
MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
if (ExistingFile)
// It is an error to use see the same number more than once.
return 0;
}
// Get the new MCDwarfFile slot for this FileNumber.
MCDwarfFile *&File = MCDwarfFiles[FileNumber];
if (Directory.empty()) {
// Separate the directory part from the basename of the FileName.
StringRef tFileName = sys::path::filename(FileName);
if (!tFileName.empty()) {
Directory = sys::path::parent_path(FileName);
if (!Directory.empty())
FileName = tFileName;
}
}
// Find or make a entry in the MCDwarfDirs vector for this Directory.
// Capture directory name.
unsigned DirIndex;
if (Directory.empty()) {
// For FileNames with no directories a DirIndex of 0 is used.
DirIndex = 0;
} else {
DirIndex = 0;
for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
if (Directory == MCDwarfDirs[DirIndex])
break;
}
if (DirIndex >= MCDwarfDirs.size()) {
char *Buf = static_cast<char *>(Allocate(Directory.size()));
memcpy(Buf, Directory.data(), Directory.size());
MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
}
// The DirIndex is one based, as DirIndex of 0 is used for FileNames with
// no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
// directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
// are stored at MCDwarfFiles[FileNumber].Name .
DirIndex++;
}
// Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
// vector.
char *Buf = static_cast<char *>(Allocate(FileName.size()));
memcpy(Buf, FileName.data(), FileName.size());
File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
// return the allocated FileNumber.
return FileNumber;
}
/// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
/// currently is assigned and false otherwise.
bool MCContext::isValidDwarfFileNumber(unsigned FileNumber) {
if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
return false;
return MCDwarfFiles[FileNumber] != 0;
}
void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
// If we have a source manager and a location, use it. Otherwise just
// use the generic report_fatal_error().
if (!SrcMgr || Loc == SMLoc())
report_fatal_error(Msg);
// Use the source manager to print the message.
SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
// If we reached here, we are failing ungracefully. Run the interrupt handlers
// to make sure any special cleanups get done, in particular that we remove
// files registered with RemoveFileOnSignal.
sys::RunInterruptHandlers();
exit(1);
}
<|endoftext|> |
<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <hspp/Tasks/PlayerTasks/CombatTask.hpp>
#include <hspp/Tasks/SimpleTasks/DestroyTask.hpp>
#include <hspp/Tasks/SimpleTasks/FreezeTask.hpp>
#include <hspp/Tasks/SimpleTasks/PoisonousTask.hpp>
using namespace Hearthstonepp::SimpleTasks;
namespace Hearthstonepp::PlayerTasks
{
CombatTask::CombatTask(TaskAgent& agent, Entity* source, Entity* target)
: ITask(source, target), m_requirement(TaskID::SELECT_TARGET, agent)
{
// Do nothing
}
TaskID CombatTask::GetTaskID() const
{
return TaskID::COMBAT;
}
MetaData CombatTask::Impl(Player& player)
{
auto [sourceIndex, targetIndex] = CalculateIndex(player);
// Verify index of the source
// NOTE: 0 means hero, 1 ~ field.size() means minion
if (sourceIndex > player.GetField().GetNumOfMinions())
{
return MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE;
}
// Verify index of the target
// NOTE: 0 means hero, 1 ~ field.size() means minion
if (targetIndex > player.GetOpponent().GetField().GetNumOfMinions())
{
return MetaData::COMBAT_DST_IDX_OUT_OF_RANGE;
}
auto source = (sourceIndex > 0)
? dynamic_cast<Character*>(
player.GetField().GetMinion(sourceIndex - 1))
: dynamic_cast<Character*>(player.GetHero());
auto target =
(targetIndex > 0)
? dynamic_cast<Character*>(
player.GetOpponent().GetField().GetMinion(targetIndex - 1))
: dynamic_cast<Character*>(player.GetOpponent().GetHero());
if (!source->CanAttack() ||
!source->IsValidCombatTarget(player.GetOpponent(), target))
{
return MetaData::COMBAT_SOURCE_CANT_ATTACK;
}
const size_t targetAttack = target->GetAttack();
const size_t sourceAttack = source->GetAttack();
const size_t targetDamage = target->TakeDamage(*source, sourceAttack);
const bool isTargetDamaged = targetDamage > 0;
// Destroy target if attacker is poisonous
if (isTargetDamaged && source->GetGameTag(GameTag::POISONOUS) == 1)
{
PoisonousTask(target).Run(player);
}
// Freeze target if attacker is freezer
if (isTargetDamaged && source->GetGameTag(GameTag::FREEZE) == 1)
{
FreezeTask(EntityType::TARGET, target).Run(player);
}
// Ignore damage from defenders with 0 attack
if (targetAttack > 0)
{
const size_t sourceDamage = source->TakeDamage(*target, targetAttack);
const bool isSourceDamaged = sourceDamage > 0;
// Destroy source if defender is poisonous
if (isSourceDamaged && target->GetGameTag(GameTag::POISONOUS) == 1)
{
PoisonousTask(source).Run(player);
}
// Freeze source if defender is freezer
if (isSourceDamaged && target->GetGameTag(GameTag::FREEZE) == 1)
{
FreezeTask(EntityType::SOURCE, source).Run(player);
}
}
// Remove stealth ability if attacker has it
if (source->GetGameTag(GameTag::STEALTH) == 1)
{
source->SetGameTag(GameTag::STEALTH, 0);
}
// Remove durability from weapon if hero attack
const Hero* hero = dynamic_cast<Hero*>(source);
if (hero != nullptr && hero->weapon != nullptr &&
hero->weapon->GetGameTag(GameTag::IMMUNE) == 0)
{
hero->weapon->SetDurability(hero->weapon->GetDurability() - 1);
// Destroy weapon if durability is 0
if (hero->weapon->GetDurability() <= 0)
{
DestroyTask(EntityType::WEAPON).Run(player);
}
}
source->attackableCount--;
if (source->isDestroyed)
{
source->Destroy();
}
if (target->isDestroyed)
{
target->Destroy();
}
return MetaData::COMBAT_SUCCESS;
}
std::tuple<BYTE, BYTE> CombatTask::CalculateIndex(Player& player) const
{
if (m_source != nullptr && m_target != nullptr)
{
Minion* minionSource = dynamic_cast<Minion*>(m_source);
Minion* minionTarget = dynamic_cast<Minion*>(m_target);
int sourceIndex = -1, targetIndex = -1;
if (m_source == player.GetHero())
{
sourceIndex = 0;
}
else
{
if (minionSource != nullptr)
{
sourceIndex = static_cast<BYTE>(
player.GetField().FindMinionPos(*minionSource).value());
sourceIndex += 1;
}
}
Player& opponent = player.GetOpponent();
if (m_target == opponent.GetHero())
{
targetIndex = 0;
}
else
{
if (minionTarget != nullptr)
{
targetIndex = static_cast<BYTE>(
opponent.GetField().FindMinionPos(*minionTarget).value());
targetIndex += 1;
}
}
if (sourceIndex == -1 || targetIndex == -1)
{
throw std::logic_error(
"CombatTask::CalculateIndex() - Invalid index!");
}
return std::make_tuple(static_cast<BYTE>(sourceIndex),
static_cast<BYTE>(targetIndex));
}
TaskMeta serialized;
// Get targeting response from game interface
m_requirement.Interact(player.GetID(), serialized);
// Get the source and the target
const auto req = TaskMeta::ConvertTo<FlatData::ResponseTarget>(serialized);
return std::make_tuple(req->src(), req->dst());
}
} // namespace Hearthstonepp::PlayerTasks
<commit_msg>fix: Compile error on macOS (<optional> is experimental)<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <hspp/Tasks/PlayerTasks/CombatTask.hpp>
#include <hspp/Tasks/SimpleTasks/DestroyTask.hpp>
#include <hspp/Tasks/SimpleTasks/FreezeTask.hpp>
#include <hspp/Tasks/SimpleTasks/PoisonousTask.hpp>
using namespace Hearthstonepp::SimpleTasks;
namespace Hearthstonepp::PlayerTasks
{
CombatTask::CombatTask(TaskAgent& agent, Entity* source, Entity* target)
: ITask(source, target), m_requirement(TaskID::SELECT_TARGET, agent)
{
// Do nothing
}
TaskID CombatTask::GetTaskID() const
{
return TaskID::COMBAT;
}
MetaData CombatTask::Impl(Player& player)
{
auto [sourceIndex, targetIndex] = CalculateIndex(player);
// Verify index of the source
// NOTE: 0 means hero, 1 ~ field.size() means minion
if (sourceIndex > player.GetField().GetNumOfMinions())
{
return MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE;
}
// Verify index of the target
// NOTE: 0 means hero, 1 ~ field.size() means minion
if (targetIndex > player.GetOpponent().GetField().GetNumOfMinions())
{
return MetaData::COMBAT_DST_IDX_OUT_OF_RANGE;
}
auto source = (sourceIndex > 0)
? dynamic_cast<Character*>(
player.GetField().GetMinion(sourceIndex - 1))
: dynamic_cast<Character*>(player.GetHero());
auto target =
(targetIndex > 0)
? dynamic_cast<Character*>(
player.GetOpponent().GetField().GetMinion(targetIndex - 1))
: dynamic_cast<Character*>(player.GetOpponent().GetHero());
if (!source->CanAttack() ||
!source->IsValidCombatTarget(player.GetOpponent(), target))
{
return MetaData::COMBAT_SOURCE_CANT_ATTACK;
}
const size_t targetAttack = target->GetAttack();
const size_t sourceAttack = source->GetAttack();
const size_t targetDamage = target->TakeDamage(*source, sourceAttack);
const bool isTargetDamaged = targetDamage > 0;
// Destroy target if attacker is poisonous
if (isTargetDamaged && source->GetGameTag(GameTag::POISONOUS) == 1)
{
PoisonousTask(target).Run(player);
}
// Freeze target if attacker is freezer
if (isTargetDamaged && source->GetGameTag(GameTag::FREEZE) == 1)
{
FreezeTask(EntityType::TARGET, target).Run(player);
}
// Ignore damage from defenders with 0 attack
if (targetAttack > 0)
{
const size_t sourceDamage = source->TakeDamage(*target, targetAttack);
const bool isSourceDamaged = sourceDamage > 0;
// Destroy source if defender is poisonous
if (isSourceDamaged && target->GetGameTag(GameTag::POISONOUS) == 1)
{
PoisonousTask(source).Run(player);
}
// Freeze source if defender is freezer
if (isSourceDamaged && target->GetGameTag(GameTag::FREEZE) == 1)
{
FreezeTask(EntityType::SOURCE, source).Run(player);
}
}
// Remove stealth ability if attacker has it
if (source->GetGameTag(GameTag::STEALTH) == 1)
{
source->SetGameTag(GameTag::STEALTH, 0);
}
// Remove durability from weapon if hero attack
const Hero* hero = dynamic_cast<Hero*>(source);
if (hero != nullptr && hero->weapon != nullptr &&
hero->weapon->GetGameTag(GameTag::IMMUNE) == 0)
{
hero->weapon->SetDurability(hero->weapon->GetDurability() - 1);
// Destroy weapon if durability is 0
if (hero->weapon->GetDurability() <= 0)
{
DestroyTask(EntityType::WEAPON).Run(player);
}
}
source->attackableCount--;
if (source->isDestroyed)
{
source->Destroy();
}
if (target->isDestroyed)
{
target->Destroy();
}
return MetaData::COMBAT_SUCCESS;
}
std::tuple<BYTE, BYTE> CombatTask::CalculateIndex(Player& player) const
{
if (m_source != nullptr && m_target != nullptr)
{
Minion* minionSource = dynamic_cast<Minion*>(m_source);
Minion* minionTarget = dynamic_cast<Minion*>(m_target);
int sourceIndex = -1, targetIndex = -1;
if (m_source == player.GetHero())
{
sourceIndex = 0;
}
else
{
if (minionSource != nullptr)
{
sourceIndex =
static_cast<BYTE>(player.GetField()
.FindMinionPos(*minionSource)
.value_or(-1));
sourceIndex += 1;
}
}
Player& opponent = player.GetOpponent();
if (m_target == opponent.GetHero())
{
targetIndex = 0;
}
else
{
if (minionTarget != nullptr)
{
targetIndex =
static_cast<BYTE>(opponent.GetField()
.FindMinionPos(*minionTarget)
.value_or(-1));
targetIndex += 1;
}
}
if (sourceIndex == -1 || targetIndex == -1)
{
throw std::logic_error(
"CombatTask::CalculateIndex() - Invalid index!");
}
return std::make_tuple(static_cast<BYTE>(sourceIndex),
static_cast<BYTE>(targetIndex));
}
TaskMeta serialized;
// Get targeting response from game interface
m_requirement.Interact(player.GetID(), serialized);
// Get the source and the target
const auto req = TaskMeta::ConvertTo<FlatData::ResponseTarget>(serialized);
return std::make_tuple(req->src(), req->dst());
}
} // namespace Hearthstonepp::PlayerTasks
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: XMLPropertyBackpatcher.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: dvo $ $Date: 2001-05-17 14:27:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_XMLPROPERTYBACKPATCHER_HXX
#define _XMLOFF_XMLPROPERTYBACKPATCHER_HXX
#ifndef __SGI_STL_MAP
#include <map>
#endif
#ifndef __SGI_STL_VECTOR
#include <vector>
#endif
#if SUPD > 632 || DVO_TEST
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#else
#ifndef _XMLOFF_FUNCTIONAL_HXX
#include "functional.hxx"
#endif
#endif
namespace rtl { class OUString; }
namespace com { namespace sun { namespace star {
namespace beans { class XPropertySet; }
namespace uno { template<class A> class Reference; }
} } }
/** This class maintains an OUString->sal_Int16 mapping for cases in
* which an XPropertySet needs to be filled with values that are not
* yet known.
*
* A good example for appropriate use are footnotes and references to
* footnoes. Internally, the StarOffice API numbers footnotes, and
* references to footnotes refer to that internal numbering. In the
* XML file format, these numbers are replaced with name strings. Now
* if during import of a document a reference to a footnote is
* encountered, two things can happen: 1) The footnote already
* appeared in the document. In this case the name is already known
* and the proper ID can be requested from the footnote. 2) The
* footnote will appear later in the document. In this case the ID is
* not yet known, and the reference-ID property of the reference
* cannot be determined. Hence, the reference has to be stored and the
* ID needs to bet set later, when the footnote is eventually found in
* the document.
*
* This class simplifies this process: If the footnote is found,
* ResolveId with the XML name and the ID is called. When a reference
* is encountered, SetProperty gets called with the reference's
* XPropertySet and the XML name. All remaining tasks are handled by
* the class.
*/
template <class A>
class XMLPropertyBackpatcher
{
/// name of property that gets set or backpatched
::rtl::OUString sPropertyName;
/// should a default value be set for unresolved properties
sal_Bool bDefaultHandling;
/// should the sPreservePropertyName be preserved
sal_Bool bPreserveProperty;
/// name of the property to preserve
::rtl::OUString sPreservePropertyName;
/// default value for unresolved properties (if bDefaultHandling)
A aDefault;
/// backpatch list type
typedef ::std::vector<
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> > BackpatchListType;
/* use void* instead of BackpatchListType to avoid linker problems
with long typenames. The real typename (commented out) contains
>1200 chars. */
/// backpatch list for unresolved IDs
//::std::map<const ::rtl::OUString, BackpatchListType*> aBackpatchListMap;
#if SUPD > 632 || DVO_TEST
::std::map<const ::rtl::OUString, void*, ::comphelper::UStringLess> aBackpatchListMap;
#else
::std::map<const ::rtl::OUString, void*, less_functor> aBackpatchListMap;
#endif
/// mapping of names -> IDs
#if SUPD > 632 || DVO_TEST
::std::map<const ::rtl::OUString, A, ::comphelper::UStringLess> aIDMap;
#else
::std::map<const ::rtl::OUString, A, less_functor> aIDMap;
#endif
public:
XMLPropertyBackpatcher(
const ::rtl::OUString& sPropertyName);
XMLPropertyBackpatcher(
const ::rtl::OUString& sPropertyName,
const ::rtl::OUString& sPreservePropertyName,
sal_Bool bDefault,
A aDef);
XMLPropertyBackpatcher(
const sal_Char* pPropertyName);
XMLPropertyBackpatcher(
const sal_Char* pPropertyName,
const sal_Char* pPreservePropertyName,
sal_Bool bDefault,
A aDef);
~XMLPropertyBackpatcher();
/// resolve a known ID.
/// Call this as soon as the value for a particular name is known.
void ResolveId(
const ::rtl::OUString& sName,
A aValue);
/// Set property with the proper value for this name. If the value
/// is not yet known, store the XPropertySet in the backpatch list.
/// Use this whenever the value should be set, even if it is not yet known.
/// const version
void SetProperty(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & xPropSet,
const ::rtl::OUString& sName);
/// non-const version of SetProperty
void SetProperty(
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & xPropSet,
const ::rtl::OUString& sName);
/// set default (if bDefaultHandling) for unresolved names
/// called by destructor
void SetDefault();
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.640); FILE MERGED 2005/09/05 14:39:57 rt 1.4.640.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLPropertyBackpatcher.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:15:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_XMLPROPERTYBACKPATCHER_HXX
#define _XMLOFF_XMLPROPERTYBACKPATCHER_HXX
#ifndef __SGI_STL_MAP
#include <map>
#endif
#ifndef __SGI_STL_VECTOR
#include <vector>
#endif
#if SUPD > 632 || DVO_TEST
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#else
#ifndef _XMLOFF_FUNCTIONAL_HXX
#include "functional.hxx"
#endif
#endif
namespace rtl { class OUString; }
namespace com { namespace sun { namespace star {
namespace beans { class XPropertySet; }
namespace uno { template<class A> class Reference; }
} } }
/** This class maintains an OUString->sal_Int16 mapping for cases in
* which an XPropertySet needs to be filled with values that are not
* yet known.
*
* A good example for appropriate use are footnotes and references to
* footnoes. Internally, the StarOffice API numbers footnotes, and
* references to footnotes refer to that internal numbering. In the
* XML file format, these numbers are replaced with name strings. Now
* if during import of a document a reference to a footnote is
* encountered, two things can happen: 1) The footnote already
* appeared in the document. In this case the name is already known
* and the proper ID can be requested from the footnote. 2) The
* footnote will appear later in the document. In this case the ID is
* not yet known, and the reference-ID property of the reference
* cannot be determined. Hence, the reference has to be stored and the
* ID needs to bet set later, when the footnote is eventually found in
* the document.
*
* This class simplifies this process: If the footnote is found,
* ResolveId with the XML name and the ID is called. When a reference
* is encountered, SetProperty gets called with the reference's
* XPropertySet and the XML name. All remaining tasks are handled by
* the class.
*/
template <class A>
class XMLPropertyBackpatcher
{
/// name of property that gets set or backpatched
::rtl::OUString sPropertyName;
/// should a default value be set for unresolved properties
sal_Bool bDefaultHandling;
/// should the sPreservePropertyName be preserved
sal_Bool bPreserveProperty;
/// name of the property to preserve
::rtl::OUString sPreservePropertyName;
/// default value for unresolved properties (if bDefaultHandling)
A aDefault;
/// backpatch list type
typedef ::std::vector<
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> > BackpatchListType;
/* use void* instead of BackpatchListType to avoid linker problems
with long typenames. The real typename (commented out) contains
>1200 chars. */
/// backpatch list for unresolved IDs
//::std::map<const ::rtl::OUString, BackpatchListType*> aBackpatchListMap;
#if SUPD > 632 || DVO_TEST
::std::map<const ::rtl::OUString, void*, ::comphelper::UStringLess> aBackpatchListMap;
#else
::std::map<const ::rtl::OUString, void*, less_functor> aBackpatchListMap;
#endif
/// mapping of names -> IDs
#if SUPD > 632 || DVO_TEST
::std::map<const ::rtl::OUString, A, ::comphelper::UStringLess> aIDMap;
#else
::std::map<const ::rtl::OUString, A, less_functor> aIDMap;
#endif
public:
XMLPropertyBackpatcher(
const ::rtl::OUString& sPropertyName);
XMLPropertyBackpatcher(
const ::rtl::OUString& sPropertyName,
const ::rtl::OUString& sPreservePropertyName,
sal_Bool bDefault,
A aDef);
XMLPropertyBackpatcher(
const sal_Char* pPropertyName);
XMLPropertyBackpatcher(
const sal_Char* pPropertyName,
const sal_Char* pPreservePropertyName,
sal_Bool bDefault,
A aDef);
~XMLPropertyBackpatcher();
/// resolve a known ID.
/// Call this as soon as the value for a particular name is known.
void ResolveId(
const ::rtl::OUString& sName,
A aValue);
/// Set property with the proper value for this name. If the value
/// is not yet known, store the XPropertySet in the backpatch list.
/// Use this whenever the value should be set, even if it is not yet known.
/// const version
void SetProperty(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & xPropSet,
const ::rtl::OUString& sName);
/// non-const version of SetProperty
void SetProperty(
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & xPropSet,
const ::rtl::OUString& sName);
/// set default (if bDefaultHandling) for unresolved names
/// called by destructor
void SetDefault();
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: docu_pe2.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-07-12 15:43:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef ADC_DSAPI_DOCU_PE2_HXX
#define ADC_DSAPI_DOCU_PE2_HXX
// USED SERVICES
// BASE CLASSES
#include <s2_dsapi/tokintpr.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace info
{
class CodeInformation;
class DocuToken;
} // namespace info
} // namespace ary
namespace csi
{
namespace dsapi
{
class Token;
class DT_AtTag;
class SapiDocu_PE : public TokenInterpreter
{
public:
SapiDocu_PE();
~SapiDocu_PE();
void ProcessToken(
DYN csi::dsapi::Token &
let_drToken );
virtual void Process_AtTag(
const Tok_AtTag & i_rToken );
virtual void Process_HtmlTag(
const Tok_HtmlTag & i_rToken );
virtual void Process_XmlConst(
const Tok_XmlConst &
i_rToken );
virtual void Process_XmlLink_BeginTag(
const Tok_XmlLink_BeginTag &
i_rToken );
virtual void Process_XmlLink_EndTag(
const Tok_XmlLink_EndTag &
i_rToken );
virtual void Process_XmlFormat_BeginTag(
const Tok_XmlFormat_BeginTag &
i_rToken );
virtual void Process_XmlFormat_EndTag(
const Tok_XmlFormat_EndTag &
i_rToken );
virtual void Process_Word(
const Tok_Word & i_rToken );
virtual void Process_Comma();
virtual void Process_DocuEnd();
virtual void Process_EOL();
DYN ary::info::CodeInformation *
ReleaseJustParsedDocu();
bool IsComplete() const;
private:
enum E_State
{
e_none = 0,
st_short,
st_description,
st_attags,
st_complete
};
typedef void ( SapiDocu_PE::*F_TokenAdder )( DYN ary::info::DocuToken & let_drNewToken );
void AddDocuToken2Void(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Short(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Description(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Deprecated(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2CurAtTag(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurParameterAtTagName(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurSeeAlsoAtTagLinkText(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurSinceAtTagVersion(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2SinceAtTag(
DYN ary::info::DocuToken &
let_drNewToken );
// DATA
Dyn<ary::info::CodeInformation>
pDocu;
E_State eState;
F_TokenAdder fCurTokenAddFunction;
Dyn<DT_AtTag> pCurAtTag;
udmstri sCurDimAttribute;
};
} // namespace dsapi
} // namespace csi
// IMPLEMENTATION
#endif
<commit_msg>INTEGRATION: CWS adc10 (1.3.8); FILE MERGED 2005/01/12 13:14:31 np 1.3.8.1: #i31025# Convenient error log file.<commit_after>/*************************************************************************
*
* $RCSfile: docu_pe2.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2005-01-27 11:29:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef ADC_DSAPI_DOCU_PE2_HXX
#define ADC_DSAPI_DOCU_PE2_HXX
// USED SERVICES
// BASE CLASSES
#include <s2_dsapi/tokintpr.hxx>
// COMPONENTS
// PARAMETERS
class ParserInfo;
namespace ary
{
namespace info
{
class CodeInformation;
class DocuToken;
} // namespace info
} // namespace ary
namespace csi
{
namespace dsapi
{
class Token;
class DT_AtTag;
class SapiDocu_PE : public TokenInterpreter
{
public:
SapiDocu_PE(
ParserInfo & io_rPositionInfo );
~SapiDocu_PE();
void ProcessToken(
DYN csi::dsapi::Token &
let_drToken );
virtual void Process_AtTag(
const Tok_AtTag & i_rToken );
virtual void Process_HtmlTag(
const Tok_HtmlTag & i_rToken );
virtual void Process_XmlConst(
const Tok_XmlConst &
i_rToken );
virtual void Process_XmlLink_BeginTag(
const Tok_XmlLink_BeginTag &
i_rToken );
virtual void Process_XmlLink_EndTag(
const Tok_XmlLink_EndTag &
i_rToken );
virtual void Process_XmlFormat_BeginTag(
const Tok_XmlFormat_BeginTag &
i_rToken );
virtual void Process_XmlFormat_EndTag(
const Tok_XmlFormat_EndTag &
i_rToken );
virtual void Process_Word(
const Tok_Word & i_rToken );
virtual void Process_Comma();
virtual void Process_DocuEnd();
virtual void Process_EOL();
DYN ary::info::CodeInformation *
ReleaseJustParsedDocu();
bool IsComplete() const;
private:
enum E_State
{
e_none = 0,
st_short,
st_description,
st_attags,
st_complete
};
typedef void ( SapiDocu_PE::*F_TokenAdder )( DYN ary::info::DocuToken & let_drNewToken );
void AddDocuToken2Void(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Short(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Description(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2Deprecated(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2CurAtTag(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurParameterAtTagName(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurSeeAlsoAtTagLinkText(
DYN ary::info::DocuToken &
let_drNewToken );
void SetCurSinceAtTagVersion(
DYN ary::info::DocuToken &
let_drNewToken );
void AddDocuToken2SinceAtTag(
DYN ary::info::DocuToken &
let_drNewToken );
// DATA
Dyn<ary::info::CodeInformation>
pDocu;
E_State eState;
ParserInfo * pPositionInfo;
F_TokenAdder fCurTokenAddFunction;
Dyn<DT_AtTag> pCurAtTag;
String sCurDimAttribute;
};
} // namespace dsapi
} // namespace csi
// IMPLEMENTATION
#endif
<|endoftext|> |
<commit_before>/*!
\file binlog.cpp
\brief Binary logs reader definition
\author Ivan Shynkarenka
\date 16.09.2015
\copyright MIT License
*/
#include "logging/record.h"
#include "logging/layouts/text_layout.h"
#include "logging/version.h"
#include "filesystem/file.h"
#include "system/stream.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include <vector>
#include <OptionParser.h>
using namespace CppCommon;
using namespace CppLogging;
bool InputRecord(Reader& input, Record& record)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
uint8_t logger_size;
std::memcpy(&logger_size, buffer, sizeof(uint8_t));
buffer += sizeof(uint8_t);
record.logger.insert(record.logger.begin(), buffer, buffer + logger_size);
buffer += logger_size;
uint16_t message_size;
std::memcpy(&message_size, buffer, sizeof(uint16_t));
buffer += sizeof(uint16_t);
record.message.insert(record.message.begin(), buffer, buffer + message_size);
buffer += message_size;
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool OutputRecord(Writer& output, Record& record)
{
TextLayout layout;
layout.LayoutRecord(record);
size_t size = record.raw.size() - 1;
if (output.Write(record.raw.data(), size) != size)
{
std::cerr << "Failed to write into the output source!" << std::endl;
return false;
}
return true;
}
int main(int argc, char** argv)
{
auto parser = optparse::OptionParser().version(version);
parser.add_option("-h", "--help").help("Show help");
parser.add_option("-i", "--input").help("Input file name");
parser.add_option("-o", "--output").help("Output file name");
optparse::Values options = parser.parse_args(argc, argv);
// Print help
if (options.get("help"))
{
parser.print_help();
return 0;
}
// Open the input file or stdin
std::unique_ptr<Reader> input(new StdInput());
if (options.is_set("input"))
{
File* file = new File(Path(options.get("input")));
file->Open(true, false);
input.reset(file);
}
// Open the output file or stdout
std::unique_ptr<Writer> output(new StdOutput());
if (options.is_set("output"))
{
File* file = new File(Path(options.get("output")));
file->Open(false, true);
output.reset(file);
}
// Process all logging record
Record record;
while (InputRecord(*input, record))
if (!OutputRecord(*output, record))
break;
return 0;
}
<commit_msg>update<commit_after>/*!
\file binlog.cpp
\brief Binary logs reader definition
\author Ivan Shynkarenka
\date 16.09.2015
\copyright MIT License
*/
#include "logging/record.h"
#include "logging/layouts/text_layout.h"
#include "logging/version.h"
#include "filesystem/file.h"
#include "system/stream.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include <vector>
#include <OptionParser.h>
using namespace CppCommon;
using namespace CppLogging;
bool InputRecord(Reader& input, Record& record)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
uint8_t logger_size;
std::memcpy(&logger_size, buffer, sizeof(uint8_t));
buffer += sizeof(uint8_t);
record.logger.insert(record.logger.begin(), buffer, buffer + logger_size);
buffer += logger_size;
uint16_t message_size;
std::memcpy(&message_size, buffer, sizeof(uint16_t));
buffer += sizeof(uint16_t);
record.message.insert(record.message.begin(), buffer, buffer + message_size);
buffer += message_size;
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool OutputRecord(Writer& output, Record& record)
{
TextLayout layout;
layout.LayoutRecord(record);
size_t size = record.raw.size() - 1;
if (output.Write(record.raw.data(), size) != size)
{
std::cerr << "Failed to write into the output source!" << std::endl;
return false;
}
return true;
}
int main(int argc, char** argv)
{
auto parser = optparse::OptionParser().version(version);
parser.add_option("-i", "--input").help("Input file name");
parser.add_option("-o", "--output").help("Output file name");
optparse::Values options = parser.parse_args(argc, argv);
// Print help
if (options.get("help"))
{
parser.print_help();
return 0;
}
// Open the input file or stdin
std::unique_ptr<Reader> input(new StdInput());
if (options.is_set("input"))
{
File* file = new File(Path(options.get("input")));
file->Open(true, false);
input.reset(file);
}
// Open the output file or stdout
std::unique_ptr<Writer> output(new StdOutput());
if (options.is_set("output"))
{
File* file = new File(Path(options.get("output")));
file->Open(false, true);
output.reset(file);
}
// Process all logging record
Record record;
while (InputRecord(*input, record))
if (!OutputRecord(*output, record))
break;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ActionMapTypesOOo.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2004-11-27 12:08:55 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_ACTIONMAPTYPESOOO_HXX
#define _XMLOFF_ACTIONMAPTYPESOOO_HXX
enum ActionMapTypesOOo
{
PROP_OOO_GRAPHIC_ATTR_ACTIONS,
PROP_OOO_GRAPHIC_ELEM_ACTIONS,
PROP_OOO_DRAWING_PAGE_ATTR_ACTIONS,
PROP_OOO_PAGE_LAYOUT_ATTR_ACTIONS,
PROP_OOO_HEADER_FOOTER_ATTR_ACTIONS,
PROP_OOO_TEXT_ATTR_ACTIONS,
PROP_OOO_TEXT_ELEM_ACTIONS,
PROP_OOO_PARAGRAPH_ATTR_ACTIONS,
PROP_OOO_PARAGRAPH_ELEM_ACTIONS,
PROP_OOO_SECTION_ATTR_ACTIONS,
PROP_OOO_TABLE_ATTR_ACTIONS,
PROP_OOO_TABLE_COLUMN_ATTR_ACTIONS,
PROP_OOO_TABLE_ROW_ATTR_ACTIONS,
PROP_OOO_TABLE_CELL_ATTR_ACTIONS,
PROP_OOO_TABLE_CELL_ELEM_ACTIONS,
PROP_OOO_LIST_LEVEL_ATTR_ACTIONS,
PROP_OOO_CHART_ATTR_ACTIONS,
PROP_OOO_CHART_ELEM_ACTIONS,
MAX_OOO_PROP_ACTIONS,
OOO_STYLE_ACTIONS = MAX_OOO_PROP_ACTIONS,
OOO_FONT_DECL_ACTIONS,
OOO_SHAPE_ACTIONS,
OOO_CONNECTOR_ACTIONS,
OOO_INDEX_ENTRY_TAB_STOP_ACTIONS,
OOO_TAB_STOP_ACTIONS,
OOO_LINENUMBERING_ACTIONS,
OOO_FOOTNOTE_SEP_ACTIONS,
OOO_DROP_CAP_ACTIONS,
OOO_COLUMNS_ACTIONS,
OOO_TEXT_VALUE_TYPE_ACTIONS,
OOO_TABLE_VALUE_TYPE_ACTIONS,
OOO_PARA_ACTIONS,
OOO_STYLE_REF_ACTIONS,
OOO_MASTER_PAGE_ACTIONS,
OOO_ANNOTATION_ACTIONS,
OOO_CHANGE_INFO_ACTIONS,
OOO_FRAME_ELEM_ACTIONS,
OOO_FRAME_ATTR_ACTIONS,
OOO_BACKGROUND_IMAGE_ACTIONS,
OOO_DDE_CONNECTION_DECL_ACTIONS,
OOO_EVENT_ACTIONS,
OOO_FORM_CONTROL_ACTIONS,
OOO_FORM_COLUMN_ACTIONS,
OOO_FORM_PROP_ACTIONS,
OOO_XLINK_ACTIONS,
OOO_CONFIG_ITEM_SET_ACTIONS,
OOO_FORMULA_ACTIONS,
OOO_CHART_ACTIONS,
OOO_ERROR_MACRO_ACTIONS,
OOO_DDE_CONV_MODE_ACTIONS,
OOO_ALPHABETICAL_INDEX_MARK_ACTIONS,
OOO_DATAPILOT_MEMBER_ACTIONS,
OOO_DATAPILOT_LEVEL_ACTIONS,
OOO_SOURCE_SERVICE_ACTIONS,
OOO_DRAW_AREA_POLYGON_ACTIONS,
OOO_SCRIPT_ACTIONS,
MAX_OOO_ACTIONS
};
#endif // _XMLOFF_ACTIONMAPTYPESOOO_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.202); FILE MERGED 2005/09/05 14:40:16 rt 1.6.202.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ActionMapTypesOOo.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:35:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_ACTIONMAPTYPESOOO_HXX
#define _XMLOFF_ACTIONMAPTYPESOOO_HXX
enum ActionMapTypesOOo
{
PROP_OOO_GRAPHIC_ATTR_ACTIONS,
PROP_OOO_GRAPHIC_ELEM_ACTIONS,
PROP_OOO_DRAWING_PAGE_ATTR_ACTIONS,
PROP_OOO_PAGE_LAYOUT_ATTR_ACTIONS,
PROP_OOO_HEADER_FOOTER_ATTR_ACTIONS,
PROP_OOO_TEXT_ATTR_ACTIONS,
PROP_OOO_TEXT_ELEM_ACTIONS,
PROP_OOO_PARAGRAPH_ATTR_ACTIONS,
PROP_OOO_PARAGRAPH_ELEM_ACTIONS,
PROP_OOO_SECTION_ATTR_ACTIONS,
PROP_OOO_TABLE_ATTR_ACTIONS,
PROP_OOO_TABLE_COLUMN_ATTR_ACTIONS,
PROP_OOO_TABLE_ROW_ATTR_ACTIONS,
PROP_OOO_TABLE_CELL_ATTR_ACTIONS,
PROP_OOO_TABLE_CELL_ELEM_ACTIONS,
PROP_OOO_LIST_LEVEL_ATTR_ACTIONS,
PROP_OOO_CHART_ATTR_ACTIONS,
PROP_OOO_CHART_ELEM_ACTIONS,
MAX_OOO_PROP_ACTIONS,
OOO_STYLE_ACTIONS = MAX_OOO_PROP_ACTIONS,
OOO_FONT_DECL_ACTIONS,
OOO_SHAPE_ACTIONS,
OOO_CONNECTOR_ACTIONS,
OOO_INDEX_ENTRY_TAB_STOP_ACTIONS,
OOO_TAB_STOP_ACTIONS,
OOO_LINENUMBERING_ACTIONS,
OOO_FOOTNOTE_SEP_ACTIONS,
OOO_DROP_CAP_ACTIONS,
OOO_COLUMNS_ACTIONS,
OOO_TEXT_VALUE_TYPE_ACTIONS,
OOO_TABLE_VALUE_TYPE_ACTIONS,
OOO_PARA_ACTIONS,
OOO_STYLE_REF_ACTIONS,
OOO_MASTER_PAGE_ACTIONS,
OOO_ANNOTATION_ACTIONS,
OOO_CHANGE_INFO_ACTIONS,
OOO_FRAME_ELEM_ACTIONS,
OOO_FRAME_ATTR_ACTIONS,
OOO_BACKGROUND_IMAGE_ACTIONS,
OOO_DDE_CONNECTION_DECL_ACTIONS,
OOO_EVENT_ACTIONS,
OOO_FORM_CONTROL_ACTIONS,
OOO_FORM_COLUMN_ACTIONS,
OOO_FORM_PROP_ACTIONS,
OOO_XLINK_ACTIONS,
OOO_CONFIG_ITEM_SET_ACTIONS,
OOO_FORMULA_ACTIONS,
OOO_CHART_ACTIONS,
OOO_ERROR_MACRO_ACTIONS,
OOO_DDE_CONV_MODE_ACTIONS,
OOO_ALPHABETICAL_INDEX_MARK_ACTIONS,
OOO_DATAPILOT_MEMBER_ACTIONS,
OOO_DATAPILOT_LEVEL_ACTIONS,
OOO_SOURCE_SERVICE_ACTIONS,
OOO_DRAW_AREA_POLYGON_ACTIONS,
OOO_SCRIPT_ACTIONS,
MAX_OOO_ACTIONS
};
#endif // _XMLOFF_ACTIONMAPTYPESOOO_HXX
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "chain.h"
#include "chainparams.h"
#include "hash.h"
#include "main.h"
#include "pow.h"
#include "uint256.h"
#include <stdint.h>
using namespace std;
static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f';
static const char DB_TXINDEX = 't';
static const char DB_BLOCK_INDEX = 'b';
static const char DB_BEST_BLOCK = 'B';
static const char DB_FLAG = 'F';
static const char DB_REINDEX_FLAG = 'R';
static const char DB_LAST_BLOCK = 'l';
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true)
{
}
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
LOCK(cs_utxo);
return db.Read(make_pair(DB_COINS, txid), coins);
}
bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
LOCK(cs_utxo);
return db.Exists(make_pair(DB_COINS, txid));
}
uint256 CCoinsViewDB::GetBestBlock() const {
LOCK(cs_utxo);
uint256 hashBestChain;
if (!db.Read(DB_BEST_BLOCK, hashBestChain))
return uint256();
return hashBestChain;
}
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
LOCK(cs_utxo);
CDBBatch batch(&db.GetObfuscateKey());
size_t count = 0;
size_t changed = 0;
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
if (it->second.coins.IsPruned())
batch.Erase(make_pair(DB_COINS, it->first));
else
batch.Write(make_pair(DB_COINS, it->first), it->second.coins);
changed++;
}
count++;
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
if (!hashBlock.IsNull())
batch.Write(DB_BEST_BLOCK, hashBlock);
LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
return db.WriteBatch(batch);
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair(DB_BLOCK_FILES, nFile), info);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write(DB_REINDEX_FLAG, '1');
else
return Erase(DB_REINDEX_FLAG);
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists(DB_REINDEX_FLAG);
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read(DB_LAST_BLOCK, nFile);
}
bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
CAmount nTotalAmount = 0;
{
LOCK(cs_utxo);
/* It seems that there are no "const iterators" for LevelDB. Since we
only need read operations on it, use a const-cast to get around
that restriction. */
boost::scoped_ptr<CDBIterator> pcursor(const_cast<CDBWrapper*>(&db)->NewIterator());
pcursor->Seek(DB_COINS);
{
LOCK(cs_main);
stats.hashBlock = GetBestBlock();
stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
}
ss << stats.hashBlock;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
std::pair<char, uint256> key;
CCoins coins;
if (pcursor->GetKey(key) && key.first == DB_COINS) {
if (pcursor->GetValue(coins)) {
stats.nTransactions++;
for (unsigned int i=0; i<coins.vout.size(); i++) {
const CTxOut &out = coins.vout[i];
if (!out.IsNull()) {
stats.nTransactionOutputs++;
ss << VARINT(i+1);
ss << out;
nTotalAmount += out.nValue;
}
}
stats.nSerializedSize += 32 + pcursor->GetValueSize();
ss << VARINT(0);
} else {
return error("CCoinsViewDB::GetStats() : unable to read value");
}
} else {
break;
}
pcursor->Next();
}
}
stats.hashSerialized = ss.GetHash();
stats.nTotalAmount = nTotalAmount;
return true;
}
bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
CDBBatch batch(&GetObfuscateKey());
for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
}
batch.Write(DB_LAST_BLOCK, nLastFile);
for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
}
return WriteBatch(batch, true);
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair(DB_TXINDEX, txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CDBBatch batch(&GetObfuscateKey());
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair(DB_FLAG, name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts()
{
boost::scoped_ptr<CDBIterator> pcursor(NewIterator());
pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256()));
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
std::pair<char, uint256> key;
if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
CDiskBlockIndex diskindex;
if (pcursor->GetValue(diskindex)) {
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
return error("LoadBlockIndex() : failed to read value");
}
} else {
break;
}
}
return true;
}
<commit_msg>resolve potential deadlock issue<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "chain.h"
#include "chainparams.h"
#include "hash.h"
#include "main.h"
#include "pow.h"
#include "uint256.h"
#include <stdint.h>
using namespace std;
static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f';
static const char DB_TXINDEX = 't';
static const char DB_BLOCK_INDEX = 'b';
static const char DB_BEST_BLOCK = 'B';
static const char DB_FLAG = 'F';
static const char DB_REINDEX_FLAG = 'R';
static const char DB_LAST_BLOCK = 'l';
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true)
{
}
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
LOCK(cs_utxo);
return db.Read(make_pair(DB_COINS, txid), coins);
}
bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
LOCK(cs_utxo);
return db.Exists(make_pair(DB_COINS, txid));
}
uint256 CCoinsViewDB::GetBestBlock() const {
LOCK(cs_utxo);
uint256 hashBestChain;
if (!db.Read(DB_BEST_BLOCK, hashBestChain))
return uint256();
return hashBestChain;
}
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
LOCK(cs_utxo);
CDBBatch batch(&db.GetObfuscateKey());
size_t count = 0;
size_t changed = 0;
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
if (it->second.coins.IsPruned())
batch.Erase(make_pair(DB_COINS, it->first));
else
batch.Write(make_pair(DB_COINS, it->first), it->second.coins);
changed++;
}
count++;
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
if (!hashBlock.IsNull())
batch.Write(DB_BEST_BLOCK, hashBlock);
LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
return db.WriteBatch(batch);
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair(DB_BLOCK_FILES, nFile), info);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write(DB_REINDEX_FLAG, '1');
else
return Erase(DB_REINDEX_FLAG);
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists(DB_REINDEX_FLAG);
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read(DB_LAST_BLOCK, nFile);
}
bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
CAmount nTotalAmount = 0;
// I want to lock cs_utxo before unlocking cd_main so that a new block arrival
// does not have a moment to update the utxo set between our grabbing the
// hash and the height, and our utxo tally.
// But there is not reason to keep cs_main locked while we look at the utxo
try
{
cs_main.lock();
stats.hashBlock = GetBestBlock();
stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
}
catch (...)
{
cs_main.unlock();
throw;
}
{
LOCK(cs_utxo);
cs_main.unlock();
/* It seems that there are no "const iterators" for LevelDB. Since we
only need read operations on it, use a const-cast to get around
that restriction. */
boost::scoped_ptr<CDBIterator> pcursor(const_cast<CDBWrapper*>(&db)->NewIterator());
pcursor->Seek(DB_COINS);
ss << stats.hashBlock;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
std::pair<char, uint256> key;
CCoins coins;
if (pcursor->GetKey(key) && key.first == DB_COINS) {
if (pcursor->GetValue(coins)) {
stats.nTransactions++;
for (unsigned int i=0; i<coins.vout.size(); i++) {
const CTxOut &out = coins.vout[i];
if (!out.IsNull()) {
stats.nTransactionOutputs++;
ss << VARINT(i+1);
ss << out;
nTotalAmount += out.nValue;
}
}
stats.nSerializedSize += 32 + pcursor->GetValueSize();
ss << VARINT(0);
} else {
return error("CCoinsViewDB::GetStats() : unable to read value");
}
} else {
break;
}
pcursor->Next();
}
}
stats.hashSerialized = ss.GetHash();
stats.nTotalAmount = nTotalAmount;
return true;
}
bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
CDBBatch batch(&GetObfuscateKey());
for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
}
batch.Write(DB_LAST_BLOCK, nLastFile);
for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
}
return WriteBatch(batch, true);
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair(DB_TXINDEX, txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CDBBatch batch(&GetObfuscateKey());
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair(DB_FLAG, name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts()
{
boost::scoped_ptr<CDBIterator> pcursor(NewIterator());
pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256()));
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
std::pair<char, uint256> key;
if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
CDiskBlockIndex diskindex;
if (pcursor->GetValue(diskindex)) {
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
return error("LoadBlockIndex() : failed to read value");
}
} else {
break;
}
}
return true;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "config.h"
#ifndef HAVE_EIGEN
int main() { std::cerr << "Please rebuild with --with-eigen PATH\n"; return 1; }
#else
#include <cmath>
#include <set>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include <Eigen/Dense>
#include "m.h"
#include "lattice.h"
#include "stringlib.h"
#include "filelib.h"
#include "tdict.h"
namespace po = boost::program_options;
using namespace std;
#define kDIMENSIONS 10
typedef Eigen::Matrix<float, kDIMENSIONS, 1> RVector;
typedef Eigen::Matrix<float, 1, kDIMENSIONS> RTVector;
typedef Eigen::Matrix<float, kDIMENSIONS, kDIMENSIONS> TMatrix;
vector<RVector> r_src, r_trg;
bool InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("input,i",po::value<string>(),"Input file")
("iterations,I",po::value<unsigned>()->default_value(1000),"Number of iterations of training")
("diagonal_tension,T", po::value<double>()->default_value(4.0), "How sharp or flat around the diagonal is the alignment distribution (0 = uniform, >0 sharpens)")
("testset,x", po::value<string>(), "After training completes, compute the log likelihood of this set of sentence pairs under the learned model");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help,h", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (argc < 2 || conf->count("help")) {
cerr << "Usage " << argv[0] << " [OPTIONS] -i corpus.fr-en\n";
cerr << dcmdline_options << endl;
return false;
}
return true;
}
int main(int argc, char** argv) {
po::variables_map conf;
if (!InitCommandLine(argc, argv, &conf)) return 1;
const string fname = conf["input"].as<string>();
const int ITERATIONS = conf["iterations"].as<unsigned>();
const double diagonal_tension = conf["diagonal_tension"].as<double>();
if (diagonal_tension < 0.0) {
cerr << "Invalid value for diagonal_tension: must be >= 0\n";
return 1;
}
string testset;
if (conf.count("testset")) testset = conf["testset"].as<string>();
int lc = 0;
vector<double> unnormed_a_i;
string line;
string ssrc, strg;
bool flag = false;
Lattice src, trg;
set<WordID> vocab_e;
{ // read through corpus, initialize int map, check lines are good
cerr << "INITIAL READ OF " << fname << endl;
ReadFile rf(fname);
istream& in = *rf.stream();
while(getline(in, line)) {
++lc;
if (lc % 1000 == 0) { cerr << '.'; flag = true; }
if (lc %50000 == 0) { cerr << " [" << lc << "]\n" << flush; flag = false; }
ParseTranslatorInput(line, &ssrc, &strg);
LatticeTools::ConvertTextToLattice(ssrc, &src);
LatticeTools::ConvertTextToLattice(strg, &trg);
if (src.size() == 0 || trg.size() == 0) {
cerr << "Error: " << lc << "\n" << line << endl;
assert(src.size() > 0);
assert(trg.size() > 0);
}
if (src.size() > unnormed_a_i.size())
unnormed_a_i.resize(src.size());
for (unsigned i = 0; i < trg.size(); ++i) {
assert(trg[i].size() == 1);
vocab_e.insert(trg[i][0].label);
}
}
}
if (flag) cerr << endl;
// do optimization
for (int iter = 0; iter < ITERATIONS; ++iter) {
cerr << "ITERATION " << (iter + 1) << endl;
ReadFile rf(fname);
istream& in = *rf.stream();
double likelihood = 0;
double denom = 0.0;
lc = 0;
flag = false;
while(true) {
getline(in, line);
if (!in) break;
++lc;
if (lc % 1000 == 0) { cerr << '.'; flag = true; }
if (lc %50000 == 0) { cerr << " [" << lc << "]\n" << flush; flag = false; }
ParseTranslatorInput(line, &ssrc, &strg);
LatticeTools::ConvertTextToLattice(ssrc, &src);
LatticeTools::ConvertTextToLattice(strg, &trg);
denom += trg.size();
vector<double> probs(src.size() + 1);
for (int j = 0; j < trg.size(); ++j) {
const WordID& f_j = trg[j][0].label;
double sum = 0;
const double j_over_ts = double(j) / trg.size();
double az = 0;
for (int ta = 0; ta < src.size(); ++ta) {
unnormed_a_i[ta] = exp(-fabs(double(ta) / src.size() - j_over_ts) * diagonal_tension);
az += unnormed_a_i[ta];
}
for (int i = 1; i <= src.size(); ++i) {
const double prob_a_i = unnormed_a_i[i-1] / az;
// TODO
probs[i] = 1; // tt.prob(src[i-1][0].label, f_j) * prob_a_i;
sum += probs[i];
}
}
}
if (flag) { cerr << endl; }
const double base2_likelihood = likelihood / log(2);
cerr << " log_e likelihood: " << likelihood << endl;
cerr << " log_2 likelihood: " << base2_likelihood << endl;
cerr << " cross entropy: " << (-base2_likelihood / denom) << endl;
cerr << " perplexity: " << pow(2.0, -base2_likelihood / denom) << endl;
}
return 0;
}
#endif
<commit_msg>basic lbl model, nothing to see here<commit_after>#include <iostream>
#include "config.h"
#ifndef HAVE_EIGEN
int main() { std::cerr << "Please rebuild with --with-eigen PATH\n"; return 1; }
#else
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
#include <cstring> // memset
#include <ctime>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include <Eigen/Dense>
#include "array2d.h"
#include "m.h"
#include "lattice.h"
#include "stringlib.h"
#include "filelib.h"
#include "tdict.h"
namespace po = boost::program_options;
using namespace std;
#define kDIMENSIONS 25
typedef Eigen::Matrix<float, kDIMENSIONS, 1> RVector;
typedef Eigen::Matrix<float, 1, kDIMENSIONS> RTVector;
typedef Eigen::Matrix<float, kDIMENSIONS, kDIMENSIONS> TMatrix;
vector<RVector> r_src, r_trg;
bool InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("input,i",po::value<string>(),"Input file")
("iterations,I",po::value<unsigned>()->default_value(1000),"Number of iterations of training")
("eta,e", po::value<float>()->default_value(0.1f), "Eta for SGD")
("random_seed", po::value<unsigned>(), "Random seed")
("diagonal_tension,T", po::value<double>()->default_value(4.0), "How sharp or flat around the diagonal is the alignment distribution (0 = uniform, >0 sharpens)")
("testset,x", po::value<string>(), "After training completes, compute the log likelihood of this set of sentence pairs under the learned model");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help,h", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (argc < 2 || conf->count("help")) {
cerr << "Usage " << argv[0] << " [OPTIONS] -i corpus.fr-en\n";
cerr << dcmdline_options << endl;
return false;
}
return true;
}
void Normalize(RVector* v) {
float norm = v->norm();
*v /= norm;
}
int main(int argc, char** argv) {
po::variables_map conf;
if (!InitCommandLine(argc, argv, &conf)) return 1;
const string fname = conf["input"].as<string>();
const int ITERATIONS = conf["iterations"].as<unsigned>();
const float eta = conf["eta"].as<float>();
const double diagonal_tension = conf["diagonal_tension"].as<double>();
bool SGD = true;
if (diagonal_tension < 0.0) {
cerr << "Invalid value for diagonal_tension: must be >= 0\n";
return 1;
}
string testset;
if (conf.count("testset")) testset = conf["testset"].as<string>();
unsigned lc = 0;
vector<double> unnormed_a_i;
string line;
string ssrc, strg;
bool flag = false;
Lattice src, trg;
vector<WordID> vocab_e;
{ // read through corpus, initialize int map, check lines are good
set<WordID> svocab_e;
cerr << "INITIAL READ OF " << fname << endl;
ReadFile rf(fname);
istream& in = *rf.stream();
while(getline(in, line)) {
++lc;
if (lc % 1000 == 0) { cerr << '.'; flag = true; }
if (lc %50000 == 0) { cerr << " [" << lc << "]\n" << flush; flag = false; }
ParseTranslatorInput(line, &ssrc, &strg);
LatticeTools::ConvertTextToLattice(ssrc, &src);
LatticeTools::ConvertTextToLattice(strg, &trg);
if (src.size() == 0 || trg.size() == 0) {
cerr << "Error: " << lc << "\n" << line << endl;
assert(src.size() > 0);
assert(trg.size() > 0);
}
if (src.size() > unnormed_a_i.size())
unnormed_a_i.resize(src.size());
for (unsigned i = 0; i < trg.size(); ++i) {
assert(trg[i].size() == 1);
svocab_e.insert(trg[i][0].label);
}
}
copy(svocab_e.begin(), svocab_e.end(), back_inserter(vocab_e));
}
if (flag) cerr << endl;
cerr << "Number of target word types: " << vocab_e.size() << endl;
const float num_examples = lc;
r_trg.resize(TD::NumWords() + 1);
r_src.resize(TD::NumWords() + 1);
if (conf.count("random_seed")) {
srand(conf["random_seed"].as<unsigned>());
} else {
unsigned seed = time(NULL);
cerr << "Random seed: " << seed << endl;
srand(seed);
}
TMatrix t = TMatrix::Random() / 100.0;
for (unsigned i = 1; i < r_trg.size(); ++i) {
r_trg[i] = RVector::Random();
r_src[i] = RVector::Random();
r_trg[i][i % kDIMENSIONS] = 0.5;
r_src[i][(i-1) % kDIMENSIONS] = 0.5;
Normalize(&r_trg[i]);
Normalize(&r_src[i]);
}
vector<set<unsigned> > trg_pos(TD::NumWords() + 1);
// do optimization
TMatrix g;
vector<TMatrix> exp_src;
vector<double> z_src;
for (int iter = 0; iter < ITERATIONS; ++iter) {
cerr << "ITERATION " << (iter + 1) << endl;
ReadFile rf(fname);
istream& in = *rf.stream();
double likelihood = 0;
double denom = 0.0;
lc = 0;
flag = false;
g *= 0;
while(getline(in, line)) {
++lc;
if (lc % 1000 == 0) { cerr << '.'; flag = true; }
if (lc %50000 == 0) { cerr << " [" << lc << "]\n" << flush; flag = false; }
ParseTranslatorInput(line, &ssrc, &strg);
LatticeTools::ConvertTextToLattice(ssrc, &src);
LatticeTools::ConvertTextToLattice(strg, &trg);
denom += trg.size();
exp_src.clear(); exp_src.resize(src.size(), TMatrix::Zero());
z_src.clear(); z_src.resize(src.size(), 0.0);
Array2D<TMatrix> exp_refs(src.size(), trg.size(), TMatrix::Zero());
Array2D<double> z_refs(src.size(), trg.size(), 0.0);
for (unsigned j = 0; j < trg.size(); ++j)
trg_pos[trg[j][0].label].insert(j);
for (unsigned i = 0; i < src.size(); ++i) {
const RVector& r_s = r_src[src[i][0].label];
const RTVector pred = r_s.transpose() * t;
TMatrix& exp_m = exp_src[i];
double& z = z_src[i];
for (unsigned k = 0; k < vocab_e.size(); ++k) {
const WordID v_k = vocab_e[k];
const RVector& r_t = r_trg[v_k];
const double dot_prod = pred * r_t;
const double u = exp(dot_prod);
z += u;
const TMatrix v = r_s * r_t.transpose() * u;
exp_m += v;
set<unsigned>& ref_locs = trg_pos[v_k];
if (!ref_locs.empty()) {
for (set<unsigned>::iterator it = ref_locs.begin(); it != ref_locs.end(); ++it) {
TMatrix& exp_ref_ij = exp_refs(i, *it);
double& z_ref_ij = z_refs(i, *it);
z_ref_ij += u;
exp_ref_ij += v;
}
}
}
}
for (unsigned j = 0; j < trg.size(); ++j)
trg_pos[trg[j][0].label].clear();
// model expectations for a single target generation with
// uniform alignment prior
double m_z = 0;
TMatrix m_exp = TMatrix::Zero();
for (unsigned i = 0; i < src.size(); ++i) {
m_exp += exp_src[i];
m_z += z_src[i];
}
m_exp /= m_z;
Array2D<bool> al(src.size(), trg.size(), false);
for (unsigned j = 0; j < trg.size(); ++j) {
double ref_z = 0;
TMatrix ref_exp = TMatrix::Zero();
int max_i = 0;
double max_s = -9999999;
for (unsigned i = 0; i < src.size(); ++i) {
ref_exp += exp_refs(i, j);
ref_z += z_refs(i, j);
if (log(z_refs(i, j)) > max_s) {
max_s = log(z_refs(i, j));
max_i = i;
}
// TODO handle alignment prob
}
if (ref_z <= 0) {
cerr << "TRG=" << TD::Convert(trg[j][0].label) << endl;
cerr << " LINE=" << line << endl;
cerr << " REF_EXP=\n" << ref_exp << endl;
cerr << " M_EXP=\n" << m_exp << endl;
abort();
}
al(max_i, j) = true;
ref_exp /= ref_z;
g += m_exp - ref_exp;
likelihood += log(ref_z) - log(m_z);
if (SGD) {
t -= g * eta / num_examples;
g *= 0;
} else {
assert(!"not implemented");
}
}
if (iter == (ITERATIONS - 1) || lc == 28) { cerr << al << endl; }
}
if (flag) { cerr << endl; }
const double base2_likelihood = likelihood / log(2);
cerr << " log_e likelihood: " << likelihood << endl;
cerr << " log_2 likelihood: " << base2_likelihood << endl;
cerr << " cross entropy: " << (-base2_likelihood / denom) << endl;
cerr << " perplexity: " << pow(2.0, -base2_likelihood / denom) << endl;
cerr << t << endl;
}
cerr << "TRANSLATION MATRIX:" << endl << t << endl;
return 0;
}
#endif
<|endoftext|> |
<commit_before>#include "qmultimodeltree.h"
#include <QtCore/QDebug>
#include <QtCore/QDataStream>
#include <QtCore/QMimeData>
#include <QtCore/QMimeType>
#if QT_VERSION < 0x050700
//Q_FOREACH is deprecated and Qt CoW containers are detached on C++11 for loops
template<typename T>
const T& qAsConst(const T& v)
{
return const_cast<const T&>(v);
}
#endif
struct InternalItem
{
enum class Mode {
ROOT,
PROXY
};
int m_Index;
Mode m_Mode;
QAbstractItemModel* m_pModel;
InternalItem* m_pParent;
QVector<InternalItem*> m_lChildren;
QString m_Title;
QVariant m_UId;
};
class QMultiModelTreePrivate : public QObject
{
public:
explicit QMultiModelTreePrivate(QObject* p) : QObject(p) {}
QVector<InternalItem*> m_lRows;
QHash<const QAbstractItemModel*, InternalItem*> m_hModels;
bool m_HasIdRole {false};
int m_IdRole {Qt::DisplayRole};
QMultiModelTree* q_ptr;
public Q_SLOTS:
void slotRowsInserted(const QModelIndex& parent, int first, int last);
void slotAddRows(const QModelIndex& parent, int first, int last, QAbstractItemModel* src);
};
QMultiModelTree::QMultiModelTree(QObject* parent) : QAbstractItemModel(parent),
d_ptr(new QMultiModelTreePrivate(this))
{
d_ptr->q_ptr = this;
}
QMultiModelTree::~QMultiModelTree()
{
d_ptr->m_hModels.clear();
while(!d_ptr->m_lRows.isEmpty()) {
while(!d_ptr->m_lRows.first()->m_lChildren.isEmpty())
delete d_ptr->m_lRows.first()->m_lChildren.first();
delete d_ptr->m_lRows.first();
}
delete d_ptr;
}
QVariant QMultiModelTree::data(const QModelIndex& idx, int role) const
{
if (!idx.isValid())
return {};
const auto i = static_cast<InternalItem*>(idx.internalPointer());
if (i->m_Mode == InternalItem::Mode::PROXY)
return i->m_pModel->data(mapToSource(idx), role);
if (d_ptr->m_HasIdRole && d_ptr->m_IdRole == role)
return i->m_UId;
switch (role) {
case Qt::DisplayRole:
return (!i->m_Title.isEmpty()) ?
i->m_Title : i->m_pModel->objectName();
};
return {};
}
bool QMultiModelTree::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
return {};
auto i = static_cast<InternalItem*>(index.internalPointer());
switch(i->m_Mode) {
case InternalItem::Mode::PROXY:
return i->m_pModel->setData(mapToSource(index), value, role);
case InternalItem::Mode::ROOT:
if (d_ptr->m_HasIdRole && d_ptr->m_IdRole == role) {
i->m_UId = value;
return true;
}
switch(role) {
case Qt::DisplayRole:
case Qt::EditRole:
i->m_Title = value.toString();
return true;
}
break;
};
return false;
}
int QMultiModelTree::rowCount(const QModelIndex& parent) const
{
if (!parent.isValid())
return d_ptr->m_lRows.size();
const auto i = static_cast<InternalItem*>(parent.internalPointer());
if (i->m_Mode == InternalItem::Mode::PROXY)
return 0;
return i->m_pModel->rowCount();
}
int QMultiModelTree::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent)
return 1;
}
QModelIndex QMultiModelTree::index(int row, int column, const QModelIndex& parent) const
{
if (
(!parent.isValid())
&& row >= 0
&& row < d_ptr->m_lRows.size()
&& column == 0
)
return createIndex(row, column, d_ptr->m_lRows[row]);
if ((!parent.isValid()) || parent.model() != this)
return {};
const auto i = static_cast<InternalItem*>(parent.internalPointer());
return mapFromSource(i->m_pModel->index(row, column));
}
Qt::ItemFlags QMultiModelTree::flags(const QModelIndex &idx) const
{
const auto pidx = mapToSource(idx);
return pidx.isValid() ?
pidx.flags() : Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
QModelIndex QMultiModelTree::parent(const QModelIndex& idx) const
{
if (!idx.isValid())
return {};
const auto i = static_cast<InternalItem*>(idx.internalPointer());
if (i->m_Mode == InternalItem::Mode::ROOT)
return {};
return createIndex(i->m_pParent->m_Index, 0, i->m_pParent);
}
QModelIndex QMultiModelTree::mapFromSource(const QModelIndex& sourceIndex) const
{
if ((!sourceIndex.isValid()) || sourceIndex.parent().isValid() || sourceIndex.column())
return {};
const auto i = d_ptr->m_hModels[sourceIndex.model()];
if ((!i) || sourceIndex.row() >= i->m_lChildren.size())
return {};
return createIndex(sourceIndex.row(), 0, i->m_lChildren[sourceIndex.row()]);
}
QModelIndex QMultiModelTree::mapToSource(const QModelIndex& proxyIndex) const
{
if ((!proxyIndex.isValid()) || proxyIndex.model() != this)
return {};
if (!proxyIndex.parent().isValid())
return {};
const auto i = static_cast<InternalItem*>(proxyIndex.internalPointer());
return i->m_pModel->index(proxyIndex.row(), proxyIndex.column());
}
bool QMultiModelTree::removeRows(int row, int count, const QModelIndex &parent)
{
if (row < 0 || count < 1)
return false;
auto idx = parent;
while (idx.parent().isValid())
idx = idx.parent();
if (idx.isValid() && !idx.parent().isValid()) {
const auto i = static_cast<InternalItem*>(idx.internalPointer());
if (i->m_pModel->removeRows(row, count, mapToSource(parent))) {
beginRemoveRows(parent, row, row + count - 1);
endRemoveRows();
return true;
}
//FIXME update the m_Index
}
else if (!parent.isValid() && row + count <= d_ptr->m_lRows.size()) {
beginRemoveRows(parent, row, row + count - 1);
for(int i = row; i < row+count; i++) {
auto item = d_ptr->m_lRows[i];
d_ptr->m_hModels.remove(item->m_pModel);
delete item;
}
d_ptr->m_lRows.remove(row, count);
for (int i = row+count-1; i < rowCount(); i++)
d_ptr->m_lRows[i]->m_Index = i;
endRemoveRows();
//Q_EMIT dataChanged(index(0, 0), index(rowCount()-1, columnCount() -1));
return true;
}
return false;
}
void QMultiModelTreePrivate::slotAddRows(const QModelIndex& parent, int first, int last, QAbstractItemModel* src)
{
if (parent.isValid()) return;
auto p = m_hModels[src];
Q_ASSERT(p);
const auto localParent = q_ptr->index(p->m_Index, 0);
q_ptr->beginInsertRows(localParent, first, last);
for (int i = first; i <= last; i++) {
p->m_lChildren << new InternalItem {
p->m_lChildren.size(),
InternalItem::Mode::PROXY,
src,
p,
{},
QStringLiteral("N/A"),
{}
};
}
q_ptr->endInsertRows();
}
void QMultiModelTreePrivate::slotRowsInserted(const QModelIndex& parent, int first, int last)
{
const auto model = qobject_cast<QAbstractItemModel*>(QObject::sender());
Q_ASSERT(model);
slotAddRows(parent, first, last, model);
}
QModelIndex QMultiModelTree::appendModel(QAbstractItemModel* model, const QVariant& id)
{
if ((!model) || d_ptr->m_hModels[model]) return {};
beginInsertRows({}, d_ptr->m_lRows.size(), d_ptr->m_lRows.size());
d_ptr->m_hModels[model] = new InternalItem {
d_ptr->m_lRows.size(),
InternalItem::Mode::ROOT,
model,
Q_NULLPTR,
{},
id.canConvert<QString>() ? id.toString() : model->objectName(),
id
};
d_ptr->m_lRows << d_ptr->m_hModels[model];
endInsertRows();
d_ptr->slotAddRows({}, 0, model->rowCount(), model);
//TODO connect to the model row moved/removed/reset
connect(model, &QAbstractItemModel::rowsInserted,
d_ptr, &QMultiModelTreePrivate::slotRowsInserted);
return index(rowCount()-1, 0);
}
bool QMultiModelTree::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const
{
auto idx = index(row, column, parent);
if (!idx.isValid())
return false;
const auto i = static_cast<InternalItem*>(idx.internalPointer());
auto srcIdx = mapToSource(idx);
return i->m_pModel->canDropMimeData(data, action, srcIdx.row(), srcIdx.column(), srcIdx.parent());
}
bool QMultiModelTree::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
auto idx = index(row, column, parent);
if (!idx.isValid())
return false;
const auto i = static_cast<InternalItem*>(idx.internalPointer());
auto srcIdx = mapToSource(idx);
return i->m_pModel->dropMimeData(data, action, srcIdx.row(), srcIdx.column(), srcIdx.parent());
}
QMimeData* QMultiModelTree::mimeData(const QModelIndexList &indexes) const
{
QModelIndexList newList;
bool singleModel = true;
QAbstractItemModel* srcModel = Q_NULLPTR;
for (auto i : qAsConst(indexes)) {
const auto srcIdx = mapToSource(i);
Q_ASSERT(srcIdx.model() != this);
if (!srcModel)
srcModel = const_cast<QAbstractItemModel*>(srcIdx.model());
else if (srcIdx.model() && srcIdx.model() != srcModel) {
singleModel = false;
break;
}
if (i.isValid()) {
Q_ASSERT(i.model() == this);
newList << srcIdx;
}
}
if (singleModel && (!newList.isEmpty()) && srcModel)
return srcModel->mimeData(newList);
return QAbstractItemModel::mimeData(indexes);
}
int QMultiModelTree::topLevelIdentifierRole() const
{
return d_ptr->m_IdRole;
}
void QMultiModelTree::setTopLevelIdentifierRole(int role)
{
d_ptr->m_HasIdRole = true;
d_ptr->m_IdRole = role;
}
<commit_msg>multimodel: Forward dataChanged<commit_after>#include "qmultimodeltree.h"
#include <QtCore/QDebug>
#include <QtCore/QDataStream>
#include <QtCore/QMimeData>
#include <QtCore/QMimeType>
#if QT_VERSION < 0x050700
//Q_FOREACH is deprecated and Qt CoW containers are detached on C++11 for loops
template<typename T>
const T& qAsConst(const T& v)
{
return const_cast<const T&>(v);
}
#endif
struct InternalItem
{
enum class Mode {
ROOT,
PROXY
};
int m_Index;
Mode m_Mode;
QAbstractItemModel* m_pModel;
InternalItem* m_pParent;
QVector<InternalItem*> m_lChildren;
QString m_Title;
QVariant m_UId;
};
class QMultiModelTreePrivate : public QObject
{
public:
explicit QMultiModelTreePrivate(QObject* p) : QObject(p) {}
QVector<InternalItem*> m_lRows;
QHash<const QAbstractItemModel*, InternalItem*> m_hModels;
bool m_HasIdRole {false};
int m_IdRole {Qt::DisplayRole};
QMultiModelTree* q_ptr;
public Q_SLOTS:
void slotRowsInserted(const QModelIndex& parent, int first, int last);
void slotDataChanged(const QModelIndex& tl, const QModelIndex& br);
void slotAddRows(const QModelIndex& parent, int first, int last, QAbstractItemModel* src);
};
QMultiModelTree::QMultiModelTree(QObject* parent) : QAbstractItemModel(parent),
d_ptr(new QMultiModelTreePrivate(this))
{
d_ptr->q_ptr = this;
}
QMultiModelTree::~QMultiModelTree()
{
d_ptr->m_hModels.clear();
while(!d_ptr->m_lRows.isEmpty()) {
while(!d_ptr->m_lRows.first()->m_lChildren.isEmpty())
delete d_ptr->m_lRows.first()->m_lChildren.first();
delete d_ptr->m_lRows.first();
}
delete d_ptr;
}
QVariant QMultiModelTree::data(const QModelIndex& idx, int role) const
{
if (!idx.isValid())
return {};
const auto i = static_cast<InternalItem*>(idx.internalPointer());
if (i->m_Mode == InternalItem::Mode::PROXY)
return i->m_pModel->data(mapToSource(idx), role);
if (d_ptr->m_HasIdRole && d_ptr->m_IdRole == role)
return i->m_UId;
switch (role) {
case Qt::DisplayRole:
return (!i->m_Title.isEmpty()) ?
i->m_Title : i->m_pModel->objectName();
};
return {};
}
bool QMultiModelTree::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
return {};
auto i = static_cast<InternalItem*>(index.internalPointer());
switch(i->m_Mode) {
case InternalItem::Mode::PROXY:
return i->m_pModel->setData(mapToSource(index), value, role);
case InternalItem::Mode::ROOT:
if (d_ptr->m_HasIdRole && d_ptr->m_IdRole == role) {
i->m_UId = value;
return true;
}
switch(role) {
case Qt::DisplayRole:
case Qt::EditRole:
i->m_Title = value.toString();
return true;
}
break;
};
return false;
}
int QMultiModelTree::rowCount(const QModelIndex& parent) const
{
if (!parent.isValid())
return d_ptr->m_lRows.size();
const auto i = static_cast<InternalItem*>(parent.internalPointer());
if (i->m_Mode == InternalItem::Mode::PROXY)
return 0;
return i->m_pModel->rowCount();
}
int QMultiModelTree::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent)
return 1;
}
QModelIndex QMultiModelTree::index(int row, int column, const QModelIndex& parent) const
{
if (
(!parent.isValid())
&& row >= 0
&& row < d_ptr->m_lRows.size()
&& column == 0
)
return createIndex(row, column, d_ptr->m_lRows[row]);
if ((!parent.isValid()) || parent.model() != this)
return {};
const auto i = static_cast<InternalItem*>(parent.internalPointer());
return mapFromSource(i->m_pModel->index(row, column));
}
Qt::ItemFlags QMultiModelTree::flags(const QModelIndex &idx) const
{
const auto pidx = mapToSource(idx);
return pidx.isValid() ?
pidx.flags() : Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
QModelIndex QMultiModelTree::parent(const QModelIndex& idx) const
{
if (!idx.isValid())
return {};
const auto i = static_cast<InternalItem*>(idx.internalPointer());
if (i->m_Mode == InternalItem::Mode::ROOT)
return {};
return createIndex(i->m_pParent->m_Index, 0, i->m_pParent);
}
QModelIndex QMultiModelTree::mapFromSource(const QModelIndex& sourceIndex) const
{
if ((!sourceIndex.isValid()) || sourceIndex.parent().isValid() || sourceIndex.column())
return {};
const auto i = d_ptr->m_hModels[sourceIndex.model()];
if ((!i) || sourceIndex.row() >= i->m_lChildren.size())
return {};
return createIndex(sourceIndex.row(), 0, i->m_lChildren[sourceIndex.row()]);
}
QModelIndex QMultiModelTree::mapToSource(const QModelIndex& proxyIndex) const
{
if ((!proxyIndex.isValid()) || proxyIndex.model() != this)
return {};
if (!proxyIndex.parent().isValid())
return {};
const auto i = static_cast<InternalItem*>(proxyIndex.internalPointer());
return i->m_pModel->index(proxyIndex.row(), proxyIndex.column());
}
bool QMultiModelTree::removeRows(int row, int count, const QModelIndex &parent)
{
if (row < 0 || count < 1)
return false;
auto idx = parent;
while (idx.parent().isValid())
idx = idx.parent();
if (idx.isValid() && !idx.parent().isValid()) {
const auto i = static_cast<InternalItem*>(idx.internalPointer());
if (i->m_pModel->removeRows(row, count, mapToSource(parent))) {
beginRemoveRows(parent, row, row + count - 1);
endRemoveRows();
return true;
}
//FIXME update the m_Index
}
else if (!parent.isValid() && row + count <= d_ptr->m_lRows.size()) {
beginRemoveRows(parent, row, row + count - 1);
for(int i = row; i < row+count; i++) {
auto item = d_ptr->m_lRows[i];
d_ptr->m_hModels.remove(item->m_pModel);
delete item;
}
d_ptr->m_lRows.remove(row, count);
for (int i = row+count-1; i < rowCount(); i++)
d_ptr->m_lRows[i]->m_Index = i;
endRemoveRows();
return true;
}
return false;
}
void QMultiModelTreePrivate::slotAddRows(const QModelIndex& parent, int first, int last, QAbstractItemModel* src)
{
if (parent.isValid()) return;
auto p = m_hModels[src];
Q_ASSERT(p);
const auto localParent = q_ptr->index(p->m_Index, 0);
q_ptr->beginInsertRows(localParent, first, last);
for (int i = first; i <= last; i++) {
p->m_lChildren << new InternalItem {
p->m_lChildren.size(),
InternalItem::Mode::PROXY,
src,
p,
{},
QStringLiteral("N/A"),
{}
};
}
q_ptr->endInsertRows();
}
void QMultiModelTreePrivate::slotRowsInserted(const QModelIndex& parent, int first, int last)
{
const auto model = qobject_cast<QAbstractItemModel*>(QObject::sender());
Q_ASSERT(model);
slotAddRows(parent, first, last, model);
}
void QMultiModelTreePrivate::slotDataChanged(const QModelIndex& tl, const QModelIndex& br)
{
if (tl == br && !tl.parent().isValid()) {
const auto i = q_ptr->mapFromSource(tl);
Q_ASSERT((!tl.isValid()) || i.isValid());
Q_EMIT q_ptr->dataChanged(i, i);
}
else {
Q_EMIT q_ptr->dataChanged(q_ptr->mapFromSource(tl), q_ptr->mapFromSource(br));
}
}
QModelIndex QMultiModelTree::appendModel(QAbstractItemModel* model, const QVariant& id)
{
if ((!model) || d_ptr->m_hModels[model]) return {};
beginInsertRows({}, d_ptr->m_lRows.size(), d_ptr->m_lRows.size());
d_ptr->m_hModels[model] = new InternalItem {
d_ptr->m_lRows.size(),
InternalItem::Mode::ROOT,
model,
Q_NULLPTR,
{},
id.canConvert<QString>() ? id.toString() : model->objectName(),
id
};
d_ptr->m_lRows << d_ptr->m_hModels[model];
endInsertRows();
d_ptr->slotAddRows({}, 0, model->rowCount(), model);
//TODO connect to the model row moved/removed/reset
connect(model, &QAbstractItemModel::rowsInserted,
d_ptr, &QMultiModelTreePrivate::slotRowsInserted);
connect(model, &QAbstractItemModel::dataChanged,
d_ptr, &QMultiModelTreePrivate::slotDataChanged);
return index(rowCount()-1, 0);
}
bool QMultiModelTree::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const
{
auto idx = index(row, column, parent);
if (!idx.isValid())
return false;
const auto i = static_cast<InternalItem*>(idx.internalPointer());
auto srcIdx = mapToSource(idx);
return i->m_pModel->canDropMimeData(data, action, srcIdx.row(), srcIdx.column(), srcIdx.parent());
}
bool QMultiModelTree::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
auto idx = index(row, column, parent);
if (!idx.isValid())
return false;
const auto i = static_cast<InternalItem*>(idx.internalPointer());
auto srcIdx = mapToSource(idx);
return i->m_pModel->dropMimeData(data, action, srcIdx.row(), srcIdx.column(), srcIdx.parent());
}
QMimeData* QMultiModelTree::mimeData(const QModelIndexList &indexes) const
{
QModelIndexList newList;
bool singleModel = true;
QAbstractItemModel* srcModel = Q_NULLPTR;
for (auto i : qAsConst(indexes)) {
const auto srcIdx = mapToSource(i);
Q_ASSERT(srcIdx.model() != this);
if (!srcModel)
srcModel = const_cast<QAbstractItemModel*>(srcIdx.model());
else if (srcIdx.model() && srcIdx.model() != srcModel) {
singleModel = false;
break;
}
if (i.isValid()) {
Q_ASSERT(i.model() == this);
newList << srcIdx;
}
}
if (singleModel && (!newList.isEmpty()) && srcModel)
return srcModel->mimeData(newList);
return QAbstractItemModel::mimeData(indexes);
}
int QMultiModelTree::topLevelIdentifierRole() const
{
return d_ptr->m_IdRole;
}
void QMultiModelTree::setTopLevelIdentifierRole(int role)
{
d_ptr->m_HasIdRole = true;
d_ptr->m_IdRole = role;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBrains2MaskImageIOTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <string>
#include "itkImage.h"
#include "itkExceptionObject.h"
#include "itkNumericTraits.h"
#include "itkImageRegionIterator.h"
#include "itkImageIOFactory.h"
#include "itkBrains2MaskImageIO.h"
#include "itkBrains2MaskImageIOFactory.h"
#include "stdlib.h"
#include <itksys/SystemTools.hxx>
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkFlipImageFilter.h"
#include "vnl/vnl_sample.h"
int itkBrains2MaskTest(int ac, char *av[])
{
typedef itk::Image<unsigned int,3> ImageType;
typedef itk::ImageFileReader<ImageType> ImageReaderType;
typedef itk::ImageFileWriter<ImageType> ImageWriterType;
//
// create a random image to write out.
const ImageType::SizeType imageSize = {{4,4,4}};
const ImageType::IndexType imageIndex = {{0,0,0}};
ImageType::RegionType region;
region.SetSize(imageSize);
region.SetIndex(imageIndex);
ImageType::Pointer img = ImageType::New();
ImageType::Pointer flipped;
img->SetLargestPossibleRegion(region);
img->SetBufferedRegion(region);
img->SetRequestedRegion(region);
img->Allocate();
vnl_sample_reseed(8775070);
itk::ImageRegionIterator<ImageType> ri(img,region);
try
{
unsigned int counter = 0;
while(!ri.IsAtEnd())
{
unsigned int val
= static_cast<unsigned int>(vnl_sample_uniform(0.0, 16384.0));
val = val > 8192 ? 255 : 0;
if(counter && counter % 8 == 0)
std::cerr << val << std::endl;
else
std::cerr << val << " ";
counter++;
ri.Set(val);
++ri;
}
std::cerr << std::endl << std::endl;
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return -1;
}
//
// images in brains2 format are flipped in the y axis
itk::FlipImageFilter<ImageType>::Pointer flipper =
itk::FlipImageFilter<ImageType>::New();
itk::FlipImageFilter<ImageType>::FlipAxesArrayType axesFlip;
axesFlip[0] = false;
axesFlip[1] = true;
axesFlip[2] = false;
flipper->SetFlipAxes(axesFlip);
flipper->SetInput(img);
flipper->Update();
flipped = flipper->GetOutput();
itk::ImageIOBase::Pointer io;
io = itk::Brains2MaskImageIO::New();
if(ac < 2)
{
std::cout << "Must specify directory containing Brains2Test.mask"
<< std::endl;
return -1;
}
std::string fileName(av[1]);
fileName = fileName + "/Brains2Test.mask";
ImageWriterType::Pointer imageWriter = ImageWriterType::New();
imageWriter->SetImageIO(io);
imageWriter->SetFileName(fileName.c_str());
imageWriter->SetInput(flipped);
try
{
imageWriter->Write();
}
catch (itk::ExceptionObject &ex)
{
std::string message;
message = "Problem found while writing image ";
message += fileName;
message += "\n";
message += ex.GetLocation();
message += "\n";
message += ex.GetDescription();
std::cerr << message << std::endl;
itksys::SystemTools::RemoveFile(fileName.c_str());
return -1;
}
ImageType::Pointer readImage;
try
{
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetImageIO(io);
imageReader->SetFileName(fileName.c_str());
imageReader->Update();
readImage = imageReader->GetOutput();
}
catch (itk::ExceptionObject &)
{
return -1;
}
ri.GoToBegin();
itk::ImageRegionIterator<ImageType> ri2(readImage,region);
try
{
unsigned int counter = 0;
while(!ri.IsAtEnd() && !ri2.IsAtEnd())
{
unsigned int x = ri.Get();
unsigned int y = ri2.Get();
if(counter && counter % 8 == 0)
std::cerr << y << std::endl;
else
std::cerr << y << " ";
if(x != y)
{
std::cerr <<
"Error comparing Input Image and File Image of Brains2 Mask" <<
std::endl;
return -1;
}
counter++;
++ri;
++ri2;
}
if(!ri.IsAtEnd() || !ri2.IsAtEnd())
{
std::cerr << "Error, inconsistent image sizes " << std::endl;
return -1;
}
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return -1;
}
//
// test the factory interface. This ImageIO class doesn't get
// added to the list of Builtin factories, so add it explicitly, and
// then try and open the mask file.
itk::ObjectFactoryBase::RegisterFactory(itk::Brains2MaskImageIOFactory::New() );
try
{
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetFileName(fileName.c_str());
imageReader->Update();
readImage = imageReader->GetOutput();
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return -1;
}
return 0;
}
<commit_msg>ENH: Added error message when file read fails.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBrains2MaskImageIOTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <string>
#include "itkImage.h"
#include "itkExceptionObject.h"
#include "itkNumericTraits.h"
#include "itkImageRegionIterator.h"
#include "itkImageIOFactory.h"
#include "itkBrains2MaskImageIO.h"
#include "itkBrains2MaskImageIOFactory.h"
#include "stdlib.h"
#include <itksys/SystemTools.hxx>
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkFlipImageFilter.h"
#include "vnl/vnl_sample.h"
int itkBrains2MaskTest(int ac, char *av[])
{
typedef itk::Image<unsigned int,3> ImageType;
typedef itk::ImageFileReader<ImageType> ImageReaderType;
typedef itk::ImageFileWriter<ImageType> ImageWriterType;
//
// create a random image to write out.
const ImageType::SizeType imageSize = {{4,4,4}};
const ImageType::IndexType imageIndex = {{0,0,0}};
ImageType::RegionType region;
region.SetSize(imageSize);
region.SetIndex(imageIndex);
ImageType::Pointer img = ImageType::New();
ImageType::Pointer flipped;
img->SetLargestPossibleRegion(region);
img->SetBufferedRegion(region);
img->SetRequestedRegion(region);
img->Allocate();
vnl_sample_reseed(8775070);
itk::ImageRegionIterator<ImageType> ri(img,region);
try
{
unsigned int counter = 0;
while(!ri.IsAtEnd())
{
unsigned int val
= static_cast<unsigned int>(vnl_sample_uniform(0.0, 16384.0));
val = val > 8192 ? 255 : 0;
if(counter && counter % 8 == 0)
std::cerr << val << std::endl;
else
std::cerr << val << " ";
counter++;
ri.Set(val);
++ri;
}
std::cerr << std::endl << std::endl;
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return -1;
}
//
// images in brains2 format are flipped in the y axis
itk::FlipImageFilter<ImageType>::Pointer flipper =
itk::FlipImageFilter<ImageType>::New();
itk::FlipImageFilter<ImageType>::FlipAxesArrayType axesFlip;
axesFlip[0] = false;
axesFlip[1] = true;
axesFlip[2] = false;
flipper->SetFlipAxes(axesFlip);
flipper->SetInput(img);
flipper->Update();
flipped = flipper->GetOutput();
itk::ImageIOBase::Pointer io;
io = itk::Brains2MaskImageIO::New();
if(ac < 2)
{
std::cout << "Must specify directory containing Brains2Test.mask"
<< std::endl;
return -1;
}
std::string fileName(av[1]);
fileName = fileName + "/Brains2Test.mask";
ImageWriterType::Pointer imageWriter = ImageWriterType::New();
imageWriter->SetImageIO(io);
imageWriter->SetFileName(fileName.c_str());
imageWriter->SetInput(flipped);
try
{
imageWriter->Write();
}
catch (itk::ExceptionObject &ex)
{
std::string message;
message = "Problem found while writing image ";
message += fileName;
message += "\n";
message += ex.GetLocation();
message += "\n";
message += ex.GetDescription();
std::cerr << message << std::endl;
itksys::SystemTools::RemoveFile(fileName.c_str());
return -1;
}
ImageType::Pointer readImage;
try
{
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetImageIO(io);
imageReader->SetFileName(fileName.c_str());
imageReader->Update();
readImage = imageReader->GetOutput();
}
catch (itk::ExceptionObject& ex)
{
std::string message;
message = "Problem found while reading image ";
message += fileName;
message += "\n";
message += ex.GetLocation();
message += "\n";
message += ex.GetDescription();
std::cerr << message << std::endl;
itksys::SystemTools::RemoveFile(fileName.c_str());
return -1;
}
ri.GoToBegin();
itk::ImageRegionIterator<ImageType> ri2(readImage,region);
try
{
unsigned int counter = 0;
while(!ri.IsAtEnd() && !ri2.IsAtEnd())
{
unsigned int x = ri.Get();
unsigned int y = ri2.Get();
if(counter && counter % 8 == 0)
std::cerr << y << std::endl;
else
std::cerr << y << " ";
if(x != y)
{
std::cerr <<
"Error comparing Input Image and File Image of Brains2 Mask" <<
std::endl;
return -1;
}
counter++;
++ri;
++ri2;
}
if(!ri.IsAtEnd() || !ri2.IsAtEnd())
{
std::cerr << "Error, inconsistent image sizes " << std::endl;
return -1;
}
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return -1;
}
//
// test the factory interface. This ImageIO class doesn't get
// added to the list of Builtin factories, so add it explicitly, and
// then try and open the mask file.
itk::ObjectFactoryBase::RegisterFactory(itk::Brains2MaskImageIOFactory::New() );
try
{
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetFileName(fileName.c_str());
imageReader->Update();
readImage = imageReader->GetOutput();
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "splashscreen.h"
#include "clientversion.h"
#include "init.h"
#include "networkstyle.h"
#include "ui_interface.h"
#include "util.h"
#include "version.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#endif
#include <QApplication>
#include <QCloseEvent>
#include <QDesktopWidget>
#include <QPainter>
SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle* networkStyle) : QWidget(0, f), curAlignment(0)
{
// set reference point, paddings
int paddingLeft = 14;
int paddingTop = 470;
int titleVersionVSpace = 17;
int titleCopyrightVSpace = 32;
float fontFactor = 1.0;
// define text to place
QString titleText = tr("PIVX Core");
QString versionText = QString(tr("Version %1")).arg(QString::fromStdString(FormatFullVersion()));
QString copyrightTextBtc = QChar(0xA9) + QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers"));
QString copyrightTextDash = QChar(0xA9) + QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Dash Core developers"));
QString copyrightTextPIVX = QChar(0xA9) + QString(" 2015-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The PIVX Core developers"));
QString titleAddText = networkStyle->getTitleAddText();
QString font = QApplication::font().toString();
// load the bitmap for writing some text over it
pixmap = networkStyle->getSplashImage();
QPainter pixPaint(&pixmap);
pixPaint.setPen(QColor(100, 100, 100));
// check font size and drawing with
pixPaint.setFont(QFont(font, 28 * fontFactor));
QFontMetrics fm = pixPaint.fontMetrics();
int titleTextWidth = fm.width(titleText);
if (titleTextWidth > 160) {
// strange font rendering, Arial probably not found
fontFactor = 0.75;
}
pixPaint.setFont(QFont(font, 28 * fontFactor));
fm = pixPaint.fontMetrics();
//titleTextWidth = fm.width(titleText);
pixPaint.drawText(paddingLeft, paddingTop, titleText);
pixPaint.setFont(QFont(font, 15 * fontFactor));
pixPaint.drawText(paddingLeft, paddingTop + titleVersionVSpace, versionText);
// draw copyright stuff
pixPaint.setFont(QFont(font, 10 * fontFactor));
pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace, copyrightTextBtc);
pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 12, copyrightTextDash);
pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 24, copyrightTextPIVX);
// draw additional text if special network
if (!titleAddText.isEmpty()) {
QFont boldFont = QFont(font, 10 * fontFactor);
boldFont.setWeight(QFont::Bold);
pixPaint.setFont(boldFont);
fm = pixPaint.fontMetrics();
int titleAddTextWidth = fm.width(titleAddText);
pixPaint.drawText(pixmap.width() - titleAddTextWidth - 10, pixmap.height() - 25, titleAddText);
}
pixPaint.end();
// Set window title
setWindowTitle(titleText + " " + titleAddText);
// Resize window and move to center of desktop, disallow resizing
QRect r(QPoint(), pixmap.size());
resize(r.size());
setFixedSize(r.size());
move(QApplication::desktop()->screenGeometry().center() - r.center());
subscribeToCoreSignals();
}
SplashScreen::~SplashScreen()
{
unsubscribeFromCoreSignals();
}
void SplashScreen::slotFinish(QWidget* mainWin)
{
Q_UNUSED(mainWin);
hide();
}
static void InitMessage(SplashScreen* splash, const std::string& message)
{
QMetaObject::invokeMethod(splash, "showMessage",
Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(int, Qt::AlignBottom | Qt::AlignHCenter),
Q_ARG(QColor, QColor(100, 100, 100)));
}
static void ShowProgress(SplashScreen* splash, const std::string& title, int nProgress)
{
InitMessage(splash, title + strprintf("%d", nProgress) + "%");
}
#ifdef ENABLE_WALLET
static void ConnectWallet(SplashScreen* splash, CWallet* wallet)
{
wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2));
}
#endif
void SplashScreen::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));
uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
#ifdef ENABLE_WALLET
uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1));
#endif
}
void SplashScreen::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));
uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#ifdef ENABLE_WALLET
if (pwalletMain)
pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#endif
}
void SplashScreen::showMessage(const QString& message, int alignment, const QColor& color)
{
curMessage = message;
curAlignment = alignment;
curColor = color;
update();
}
void SplashScreen::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
painter.drawPixmap(0, 0, pixmap);
QRect r = rect().adjusted(5, 5, -5, -5);
painter.setPen(curColor);
painter.drawText(r, curAlignment, curMessage);
}
void SplashScreen::closeEvent(QCloseEvent* event)
{
StartShutdown(); // allows an "emergency" shutdown during startup
event->ignore();
}
<commit_msg>Update splashscreen.cpp<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017 The Phore developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "splashscreen.h"
#include "clientversion.h"
#include "init.h"
#include "networkstyle.h"
#include "ui_interface.h"
#include "util.h"
#include "version.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#endif
#include <QApplication>
#include <QCloseEvent>
#include <QDesktopWidget>
#include <QPainter>
SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle* networkStyle) : QWidget(0, f), curAlignment(0)
{
// set reference point, paddings
int paddingLeft = 14;
int paddingTop = 470;
int titleVersionVSpace = 17;
int titleCopyrightVSpace = 32;
float fontFactor = 1.0;
// define text to place
QString titleText = tr("Phore Core");
QString versionText = QString(tr("Version %1")).arg(QString::fromStdString(FormatFullVersion()));
QString copyrightTextBtc = QChar(0xA9) + QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers"));
QString copyrightTextDash = QChar(0xA9) + QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Dash Core developers"));
QString copyrightTextPIVX = QChar(0xA9) + QString(" 2015-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The PIVX Core developers"));
QString copyrightTextPhore = QChar(0xA9) + QString(" 2017-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Phore Core developers"));
QString titleAddText = networkStyle->getTitleAddText();
QString font = QApplication::font().toString();
// load the bitmap for writing some text over it
pixmap = networkStyle->getSplashImage();
QPainter pixPaint(&pixmap);
pixPaint.setPen(QColor(100, 100, 100));
// check font size and drawing with
pixPaint.setFont(QFont(font, 28 * fontFactor));
QFontMetrics fm = pixPaint.fontMetrics();
int titleTextWidth = fm.width(titleText);
if (titleTextWidth > 160) {
// strange font rendering, Arial probably not found
fontFactor = 0.75;
}
pixPaint.setFont(QFont(font, 28 * fontFactor));
fm = pixPaint.fontMetrics();
//titleTextWidth = fm.width(titleText);
pixPaint.drawText(paddingLeft, paddingTop, titleText);
pixPaint.setFont(QFont(font, 15 * fontFactor));
pixPaint.drawText(paddingLeft, paddingTop + titleVersionVSpace, versionText);
// draw copyright stuff
pixPaint.setFont(QFont(font, 10 * fontFactor));
pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace, copyrightTextBtc);
pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 12, copyrightTextDash);
pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 24, copyrightTextPIVX);
pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 36, copyrightTextPhore);
// draw additional text if special network
if (!titleAddText.isEmpty()) {
QFont boldFont = QFont(font, 10 * fontFactor);
boldFont.setWeight(QFont::Bold);
pixPaint.setFont(boldFont);
fm = pixPaint.fontMetrics();
int titleAddTextWidth = fm.width(titleAddText);
pixPaint.drawText(pixmap.width() - titleAddTextWidth - 10, pixmap.height() - 25, titleAddText);
}
pixPaint.end();
// Set window title
setWindowTitle(titleText + " " + titleAddText);
// Resize window and move to center of desktop, disallow resizing
QRect r(QPoint(), pixmap.size());
resize(r.size());
setFixedSize(r.size());
move(QApplication::desktop()->screenGeometry().center() - r.center());
subscribeToCoreSignals();
}
SplashScreen::~SplashScreen()
{
unsubscribeFromCoreSignals();
}
void SplashScreen::slotFinish(QWidget* mainWin)
{
Q_UNUSED(mainWin);
hide();
}
static void InitMessage(SplashScreen* splash, const std::string& message)
{
QMetaObject::invokeMethod(splash, "showMessage",
Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(int, Qt::AlignBottom | Qt::AlignHCenter),
Q_ARG(QColor, QColor(100, 100, 100)));
}
static void ShowProgress(SplashScreen* splash, const std::string& title, int nProgress)
{
InitMessage(splash, title + strprintf("%d", nProgress) + "%");
}
#ifdef ENABLE_WALLET
static void ConnectWallet(SplashScreen* splash, CWallet* wallet)
{
wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2));
}
#endif
void SplashScreen::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));
uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
#ifdef ENABLE_WALLET
uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1));
#endif
}
void SplashScreen::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));
uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#ifdef ENABLE_WALLET
if (pwalletMain)
pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#endif
}
void SplashScreen::showMessage(const QString& message, int alignment, const QColor& color)
{
curMessage = message;
curAlignment = alignment;
curColor = color;
update();
}
void SplashScreen::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
painter.drawPixmap(0, 0, pixmap);
QRect r = rect().adjusted(5, 5, -5, -5);
painter.setPen(curColor);
painter.drawText(r, curAlignment, curMessage);
}
void SplashScreen::closeEvent(QCloseEvent* event)
{
StartShutdown(); // allows an "emergency" shutdown during startup
event->ignore();
}
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: A. Huaman */
#include "urdf_world_parser.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <tinyxml.h>
#include <urdf_parser/urdf_parser.h>
#include <urdf_model/model.h>
#include <urdf_world/world.h>
#include <urdf_model/pose.h>
#include "dart/common/Console.h"
const bool debug = false;
namespace dart {
namespace utils {
namespace urdf_parsing {
Entity::Entity(const urdf::Entity& urdfEntity)
: model(urdfEntity.model),
origin(urdfEntity.origin),
twist(urdfEntity.twist)
{
// Do nothing
}
/**
* @function parseWorldURDF
*/
std::shared_ptr<World> parseWorldURDF(
const std::string& _xml_string,
const dart::common::Uri& _baseUri)
{
TiXmlDocument xml_doc;
xml_doc.Parse( _xml_string.c_str() );
TiXmlElement *world_xml = xml_doc.FirstChildElement("world");
if( !world_xml )
{
dtwarn << "[parseWorldURDF] ERROR: Could not find a <world> element in XML, exiting and not loading! \n";
return nullptr;
}
// Get world name
const char *name = world_xml->Attribute("name");
if(!name)
{
dtwarn << "[parseWorldURDF] ERROR: World does not have a name tag specified. Exiting and not loading! \n";
return nullptr;
}
std::shared_ptr<World> world(new World);
world->name = std::string(name);
if(debug) std::cout<< "World name: "<< world->name << std::endl;
// Get all include filenames
int count = 0;
std::map<std::string, std::string> includedFiles;
for( TiXmlElement* include_xml = world_xml->FirstChildElement("include");
include_xml != nullptr;
include_xml = include_xml->NextSiblingElement("include") )
{
++count;
const char *filename = include_xml->Attribute("filename");
const char *model_name = include_xml->Attribute("model_name");
std::string string_filename( filename );
std::string string_model_name( model_name );
includedFiles[string_model_name] = string_filename;
if(debug) std::cout<< "Include: Model name: " << model_name << " filename: " << filename <<std::endl;
}
if(debug) std::cout<<"Found "<< count <<" include filenames "<<std::endl;
// Get all entities
count = 0;
for( TiXmlElement* entity_xml = world_xml->FirstChildElement("entity");
entity_xml != nullptr;
entity_xml = entity_xml->NextSiblingElement("entity") )
{
count++;
dart::utils::urdf_parsing::Entity entity;
try
{
const char* entity_model = entity_xml->Attribute("model");
std::string string_entity_model( entity_model );
// Find the model
if( includedFiles.find( string_entity_model ) == includedFiles.end() )
{
dtwarn << "[parseWorldURDF] Cannot find the model ["
<< string_entity_model << "], did you provide the correct name? "
<< "We will return a nullptr.\n"<<std::endl;
return nullptr;
}
else
{
std::string fileName = includedFiles.find( string_entity_model )->second;
dart::common::Uri absoluteUri;
if(!absoluteUri.fromRelativeUri(_baseUri, fileName))
{
dtwarn << "[parseWorldURDF] Failed resolving mesh URI '"
<< fileName << "' relative to '" << _baseUri.toString()
<< "'. We will return a nullptr.\n";
return nullptr;
}
const std::string fileFullName = absoluteUri.getFilesystemPath();
entity.uri = absoluteUri;
// Parse model
std::string xml_model_string;
std::fstream xml_file( fileFullName.c_str(), std::fstream::in );
if(!xml_file.is_open())
{
dtwarn << "[parseWorldURDF] Could not open the file [" << fileFullName
<< "]. Returning a nullptr.\n";
return nullptr;
}
while( xml_file.good() )
{
std::string line;
std::getline( xml_file, line );
xml_model_string += (line + "\n");
}
xml_file.close();
entity.model = urdf::parseURDF( xml_model_string );
if( !entity.model )
{
dtwarn << "[parseWorldURDF] Could not find a model named ["
<< xml_model_string << "] in file [" << fileFullName
<< "]. We will return a nullptr.\n";
return nullptr;
}
else
{
// Parse location
TiXmlElement* origin = entity_xml->FirstChildElement("origin");
if( origin )
{
if( !urdf::parsePose( entity.origin, origin ) )
{
dtwarn << "[ERROR] Missing origin tag for '" << entity.model->getName() << "'\n";
return world;
}
}
// If name is defined
const char* entity_name = entity_xml->Attribute("name");
if( entity_name )
{
std::string string_entity_name( entity_name );
entity.model->name_ = string_entity_name;
}
// Store in world
world->models.push_back( entity );
}
} // end of include read
}
catch( urdf::ParseError& e )
{
if(debug) std::cout << "Entity xml not initialized correctly \n";
//entity->reset();
//world->reset();
return world;
}
} // end for
if(debug) std::cout << "Found " << count << " entities \n";
return world;
}
} // namesapce urdf_parsing
} // namespace utils
} // namespace dart
<commit_msg>Include <iostream> to define std::cout.<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: A. Huaman */
#include "urdf_world_parser.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iostream>
#include <tinyxml.h>
#include <urdf_parser/urdf_parser.h>
#include <urdf_model/model.h>
#include <urdf_world/world.h>
#include <urdf_model/pose.h>
#include "dart/common/Console.h"
const bool debug = false;
namespace dart {
namespace utils {
namespace urdf_parsing {
Entity::Entity(const urdf::Entity& urdfEntity)
: model(urdfEntity.model),
origin(urdfEntity.origin),
twist(urdfEntity.twist)
{
// Do nothing
}
/**
* @function parseWorldURDF
*/
std::shared_ptr<World> parseWorldURDF(
const std::string& _xml_string,
const dart::common::Uri& _baseUri)
{
TiXmlDocument xml_doc;
xml_doc.Parse( _xml_string.c_str() );
TiXmlElement *world_xml = xml_doc.FirstChildElement("world");
if( !world_xml )
{
dtwarn << "[parseWorldURDF] ERROR: Could not find a <world> element in XML, exiting and not loading! \n";
return nullptr;
}
// Get world name
const char *name = world_xml->Attribute("name");
if(!name)
{
dtwarn << "[parseWorldURDF] ERROR: World does not have a name tag specified. Exiting and not loading! \n";
return nullptr;
}
std::shared_ptr<World> world(new World);
world->name = std::string(name);
if(debug) std::cout<< "World name: "<< world->name << std::endl;
// Get all include filenames
int count = 0;
std::map<std::string, std::string> includedFiles;
for( TiXmlElement* include_xml = world_xml->FirstChildElement("include");
include_xml != nullptr;
include_xml = include_xml->NextSiblingElement("include") )
{
++count;
const char *filename = include_xml->Attribute("filename");
const char *model_name = include_xml->Attribute("model_name");
std::string string_filename( filename );
std::string string_model_name( model_name );
includedFiles[string_model_name] = string_filename;
if(debug) std::cout<< "Include: Model name: " << model_name << " filename: " << filename <<std::endl;
}
if(debug) std::cout<<"Found "<< count <<" include filenames "<<std::endl;
// Get all entities
count = 0;
for( TiXmlElement* entity_xml = world_xml->FirstChildElement("entity");
entity_xml != nullptr;
entity_xml = entity_xml->NextSiblingElement("entity") )
{
count++;
dart::utils::urdf_parsing::Entity entity;
try
{
const char* entity_model = entity_xml->Attribute("model");
std::string string_entity_model( entity_model );
// Find the model
if( includedFiles.find( string_entity_model ) == includedFiles.end() )
{
dtwarn << "[parseWorldURDF] Cannot find the model ["
<< string_entity_model << "], did you provide the correct name? "
<< "We will return a nullptr.\n"<<std::endl;
return nullptr;
}
else
{
std::string fileName = includedFiles.find( string_entity_model )->second;
dart::common::Uri absoluteUri;
if(!absoluteUri.fromRelativeUri(_baseUri, fileName))
{
dtwarn << "[parseWorldURDF] Failed resolving mesh URI '"
<< fileName << "' relative to '" << _baseUri.toString()
<< "'. We will return a nullptr.\n";
return nullptr;
}
const std::string fileFullName = absoluteUri.getFilesystemPath();
entity.uri = absoluteUri;
// Parse model
std::string xml_model_string;
std::fstream xml_file( fileFullName.c_str(), std::fstream::in );
if(!xml_file.is_open())
{
dtwarn << "[parseWorldURDF] Could not open the file [" << fileFullName
<< "]. Returning a nullptr.\n";
return nullptr;
}
while( xml_file.good() )
{
std::string line;
std::getline( xml_file, line );
xml_model_string += (line + "\n");
}
xml_file.close();
entity.model = urdf::parseURDF( xml_model_string );
if( !entity.model )
{
dtwarn << "[parseWorldURDF] Could not find a model named ["
<< xml_model_string << "] in file [" << fileFullName
<< "]. We will return a nullptr.\n";
return nullptr;
}
else
{
// Parse location
TiXmlElement* origin = entity_xml->FirstChildElement("origin");
if( origin )
{
if( !urdf::parsePose( entity.origin, origin ) )
{
dtwarn << "[ERROR] Missing origin tag for '" << entity.model->getName() << "'\n";
return world;
}
}
// If name is defined
const char* entity_name = entity_xml->Attribute("name");
if( entity_name )
{
std::string string_entity_name( entity_name );
entity.model->name_ = string_entity_name;
}
// Store in world
world->models.push_back( entity );
}
} // end of include read
}
catch( urdf::ParseError& e )
{
if(debug) std::cout << "Entity xml not initialized correctly \n";
//entity->reset();
//world->reset();
return world;
}
} // end for
if(debug) std::cout << "Found " << count << " entities \n";
return world;
}
} // namesapce urdf_parsing
} // namespace utils
} // namespace dart
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the Delaunay project.
Copyright T.J. Corona
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "Polygon.hh"
#include "Shape/LineSegment.hh"
namespace
{
typedef Delaunay::Shape::PointVector PointVector;
template <class Container>
PointVector Sort(const Container& points)
{
PointVector sortedPoints;
unsigned positionOfSmallest =
std::distance(points.begin(), std::min_element(points.begin(),
points.end()));
unsigned size = points.size();
for (unsigned i=0;i<size;i++)
{
sortedPoints.push_back(std::cref(points[(i+positionOfSmallest)%size]));
}
return sortedPoints;
}
}
namespace Delaunay
{
namespace Shape
{
Polygon::Polygon(const std::vector<Point>& points) :
Points(Sort(points))
{
}
Polygon::Polygon(const PointVector& points) :
Points(Sort(points))
{
}
bool Polygon::Contains(const Point& p) const
{
(void)p;
return false;
}
double Polygon::Distance(const Point& p) const
{
(void)p;
return 0.;
}
}
}
<commit_msg>Add missing include for min_element.<commit_after>/******************************************************************************
This source file is part of the Delaunay project.
Copyright T.J. Corona
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "Polygon.hh"
#include "Shape/LineSegment.hh"
#include <algorithm>
namespace
{
typedef Delaunay::Shape::PointVector PointVector;
template <class Container>
PointVector Sort(const Container& points)
{
PointVector sortedPoints;
unsigned positionOfSmallest =
std::distance(points.begin(), std::min_element(points.begin(),
points.end()));
unsigned size = points.size();
for (unsigned i=0;i<size;i++)
{
sortedPoints.push_back(std::cref(points[(i+positionOfSmallest)%size]));
}
return sortedPoints;
}
}
namespace Delaunay
{
namespace Shape
{
Polygon::Polygon(const std::vector<Point>& points) :
Points(Sort(points))
{
}
Polygon::Polygon(const PointVector& points) :
Points(Sort(points))
{
}
bool Polygon::Contains(const Point& p) const
{
(void)p;
return false;
}
double Polygon::Distance(const Point& p) const
{
(void)p;
return 0.;
}
}
}
<|endoftext|> |
<commit_before>#ifndef ___INANITY_INPUT_KEY_HPP___
#define ___INANITY_INPUT_KEY_HPP___
BEGIN_INANITY_INPUT
/// Номера клавиш.
/** Кроссплатформенные. */
struct Keys
{
enum _
{
a = 'A',
b = 'B',
c = 'C',
d = 'D',
e = 'E',
f = 'F',
g = 'G',
h = 'H',
i = 'I',
j = 'J',
k = 'K',
l = 'L',
m = 'M',
n = 'N',
o = 'O',
p = 'P',
q = 'Q',
r = 'R',
s = 'S',
t = 'T',
u = 'U',
v = 'V',
w = 'W',
x = 'X',
y = 'Y',
z = 'Z',
leftCtrl = 123,
rightCtrl = 456
};
};
typedef Keys::_ Key;
END_INANITY_INPUT
#endif
<commit_msg>key codes for input<commit_after>#ifndef ___INANITY_INPUT_KEY_HPP___
#define ___INANITY_INPUT_KEY_HPP___
BEGIN_INANITY_INPUT
/// Key numbers.
/** Cross-platform, but are get mostly from X11 key numbers. */
struct Keys
{
enum _
{
_Unknown = 0,
BackSpace = 0x08,
Tab = 0x09,
LineFeed = 0x0a,
Clear = 0x0b,
Return = 0x0d,
Pause = 0x13,
ScrollLock = 0x14,
SysReq = 0x15,
Escape = 0x1b,
Delete = 0xff,
Home = 0x50,
Left = 0x51,
Up = 0x52,
Right = 0x53,
Down = 0x54,
PageUp = 0x55,
PageDown = 0x56,
End = 0x57,
Begin = 0x58,
// keypad
NumLock = 0x7f,
KeyPadSpace = 0x80,
KeyPadTab = 0x89,
KeyPadEnter = 0x8d,
KeyPadF1 = 0x91,
KeyPadF2 = 0x92,
KeyPadF3 = 0x93,
KeyPadF4 = 0x94,
KeyPadHome = 0x95,
KeyPadLeft = 0x96,
KeyPadUp = 0x97,
KeyPadRight = 0x98,
KeyPadDown = 0x99,
KeyPadPageUp = 0x9a,
KeyPadPageDown = 0x9b,
KeyPadEnd = 0x9c,
KeyPadBegin = 0x9d,
KeyPadInsert = 0x9e,
KeyPadDelete = 0x9f,
KeyPadEqual = 0xbd,
KeyPadMultiply = 0xaa,
KeyPadAdd = 0xab,
KeyPadSeparator = 0xac, // comma
KeyPadSubtract = 0xad,
KeyPadDecimal = 0xae,
KeyPadDivide = 0xaf,
KeyPad0 = 0xb0,
KeyPad1 = 0xb1,
KeyPad2 = 0xb2,
KeyPad3 = 0xb3,
KeyPad4 = 0xb4,
KeyPad5 = 0xb5,
KeyPad6 = 0xb6,
KeyPad7 = 0xb7,
KeyPad8 = 0xb8,
KeyPad9 = 0xb9,
F1 = 0xbe,
F2 = 0xbf,
F3 = 0xc0,
F4 = 0xc1,
F5 = 0xc2,
F6 = 0xc3,
F7 = 0xc4,
F8 = 0xc5,
F9 = 0xc6,
F10 = 0xc7,
F11 = 0xc8,
F12 = 0xc9,
ShiftL = 0xe1,
ShiftR = 0xe2,
ControlL = 0xe3,
ControlR = 0xe4,
CapsLock = 0xe5,
ShiftLock = 0xe6,
MetaL = 0xe7,
MetaR = 0xe8,
AltL = 0xe9,
AltR = 0xea,
SuperL = 0xeb,
SuperR = 0xec,
HyperL = 0xed,
HyperR = 0xee,
Space = ' ',
_0 = 0x30,
_1 = 0x31,
_2 = 0x32,
_3 = 0x33,
_4 = 0x34,
_5 = 0x35,
_6 = 0x36,
_7 = 0x37,
_8 = 0x38,
_9 = 0x39,
A = 'A',
B = 'B',
C = 'C',
D = 'D',
E = 'E',
F = 'F',
G = 'G',
H = 'H',
I = 'I',
J = 'J',
K = 'K',
L = 'L',
M = 'M',
N = 'N',
O = 'O',
P = 'P',
Q = 'Q',
R = 'R',
S = 'S',
T = 'T',
U = 'U',
V = 'V',
W = 'W',
X = 'X',
Y = 'Y',
Z = 'Z',
};
};
typedef Keys::_ Key;
END_INANITY_INPUT
#endif
<|endoftext|> |
<commit_before>#include "main.h"
#include "User.h"
#include "Nick.h"
#include "Modules.h"
#include "Chan.h"
#include "Utils.h"
#include <pwd.h>
#ifndef HAVE_LIBSSL
#error This plugin only works with OpenSSL
#endif /* HAVE_LIBSSL */
#define CRYPT_VERIFICATION_TOKEN "::__:SAVEBUFF:__::"
/*
* Buffer Saving thing, incase your shit goes out while your out
* Author: imaginos <imaginos@imaginos.net>
*
* Its only as secure as your shell, the encryption only offers a slightly
* better solution then plain text.
*
* $Log$
* Revision 1.2 2004/11/07 02:53:32 imaginos
* added replay to savebuff so one can 'replay' a channel
*
* Revision 1.1.1.1 2004/08/24 00:08:52 prozacx
*
*
*
*/
class CSaveBuff;
class CSaveBuffJob : public CTimer
{
public:
CSaveBuffJob( CModule* pModule, unsigned int uInterval, unsigned int uCycles, const string& sLabel, const string& sDescription )
: CTimer( pModule, uInterval, uCycles, sLabel, sDescription) {}
virtual ~CSaveBuffJob() {}
protected:
virtual void RunJob();
};
class CSaveBuff : public CModule
{
public:
MODCONSTRUCTOR(CSaveBuff)
{
// m_sPassword = CBlowfish::MD5( "" );
AddTimer( new CSaveBuffJob( this, 60, 0, "SaveBuff", "Saves the current buffer to disk every 1 minute" ) );
}
virtual ~CSaveBuff()
{
SaveBufferToDisk();
}
virtual bool OnBoot()
{
if ( m_sPassword.empty() )
{
char *pTmp = getpass( "Enter Encryption Key for savebuff.so: " );
if ( pTmp )
m_sPassword = CBlowfish::MD5( pTmp );
*pTmp = 0;
}
const vector<CChan *>& vChans = m_pUser->GetChans();
for( u_int a = 0; a < vChans.size(); a++ )
{
string sFile;
if ( DecryptChannel( vChans[a]->GetName(), sFile ) )
{
string sLine;
u_int iPos = 0;
while( ReadLine( sFile, sLine, iPos ) )
{
CUtils::Trim( sLine );
vChans[a]->AddBuffer( sLine );
}
} else
{
cerr << "Failed to Decrypt [" << vChans[a]->GetName() << "]" << endl;
return( false );
}
}
return true;
}
void SaveBufferToDisk()
{
if ( !m_sPassword.empty() )
{
const vector<CChan *>& vChans = m_pUser->GetChans();
for( u_int a = 0; a < vChans.size(); a++ )
{
const vector<string> & vBuffer = vChans[a]->GetBuffer();
if ( vBuffer.empty() )
continue;
string sFile = CRYPT_VERIFICATION_TOKEN;
for( u_int b = 0; b < vBuffer.size(); b++ )
sFile += vBuffer[b] + "\n";
CBlowfish c( m_sPassword, BF_ENCRYPT );
sFile = c.Crypt( sFile );
string sPath = GetPath( vChans[a]->GetName() );
if ( !sPath.empty() )
{
WriteFile( sPath, sFile );
chmod( sPath.c_str(), 0600 );
}
}
}
}
virtual string GetDescription()
{
return ( "Stores channel buffers to disk, encrypted." );
}
virtual void OnModCommand( const string& sCommand )
{
u_int iPos = sCommand.find( " " );
string sCom, sArgs;
if ( iPos == string::npos )
sCom = sCommand;
else
{
sCom = sCommand.substr( 0, iPos );
sArgs = sCommand.substr( iPos + 1, string::npos );
}
if ( strcasecmp( sCom.c_str(), "setpass" ) == 0 )
{
PutModule( "Password set to [" + sArgs + "]" );
m_sPassword = CBlowfish::MD5( sArgs );
} else if ( strcasecmp( sCom.c_str(), "dumpbuff" ) == 0 )
{
string sFile;
if ( DecryptChannel( sArgs, sFile ) )
{
string sLine;
u_int iPos = 0;
while( ReadLine( sFile, sLine, iPos ) )
{
CUtils::Trim( sLine );
PutModule( "[" + sLine + "]" );
}
}
PutModule( "//!-- EOF " + sArgs );
} else if ( strcasecmp( sCom.c_str(), "replay" ) == 0 )
{
string sFile;
PutUser( ":***!znc@znc.com PRIVMSG " + sArgs + " :Replaying ..." );
if ( DecryptChannel( sArgs, sFile ) )
{
string sLine;
u_int iPos = 0;
while( ReadLine( sFile, sLine, iPos ) )
{
CUtils::Trim( sLine );
PutUser( sLine );
}
}
PutModule( "Replayed " + sArgs );
PutUser( ":***!znc@znc.com PRIVMSG " + sArgs + " :Done!" );
} else if ( strcasecmp( sCom.c_str(), "save" ) == 0 )
{
SaveBufferToDisk();
PutModule( "Done." );
} else
PutModule( "Unknown command [" + sCommand + "]" );
}
string GetPath( const string & sChannel )
{
string sBuffer = m_pUser->GetUserName() + Lower( sChannel );
string sRet = m_pUser->GetHomePath();
sRet += "/.znc-savebuff-" + CBlowfish::MD5( sBuffer, true );
return( sRet );
}
private:
string m_sPassword;
bool DecryptChannel( const string & sChan, string & sBuffer )
{
string sChannel = GetPath( sChan );
string sFile;
sBuffer = "";
if ( ( sChannel.empty() ) || ( !ReadFile( sChannel, sFile ) ) )
{
PutModule( "Unable to find buffer for that channel" );
return( true ); // gonna be successful here
}
if ( !sFile.empty() )
{
CBlowfish c( m_sPassword, BF_DECRYPT );
sBuffer = c.Crypt( sFile );
if ( sBuffer.substr( 0, strlen( CRYPT_VERIFICATION_TOKEN ) ) != CRYPT_VERIFICATION_TOKEN )
{
// failed to decode :(
PutModule( "Unable to decode Encrypted file [" + sChannel + "]" );
return( false );
}
sBuffer.erase( 0, strlen( CRYPT_VERIFICATION_TOKEN ) );
}
return( true );
}
};
void CSaveBuffJob::RunJob()
{
CSaveBuff *p = (CSaveBuff *)m_pModule;
p->SaveBufferToDisk();
}
MODULEDEFS(CSaveBuff)
<commit_msg>force requirements on main class to so savebuff can be sure to save all data needed. added todo list<commit_after>#include "main.h"
#include "User.h"
#include "Nick.h"
#include "Modules.h"
#include "Chan.h"
#include "Utils.h"
#include <pwd.h>
/* TODO list
* store timestamp to be displayed
* store OnJoin, OnQuit, OnPart, etc send down as messages
*/
#ifndef HAVE_LIBSSL
#error This plugin only works with OpenSSL
#endif /* HAVE_LIBSSL */
#define CRYPT_VERIFICATION_TOKEN "::__:SAVEBUFF:__::"
/*
* Buffer Saving thing, incase your shit goes out while your out
* Author: imaginos <imaginos@imaginos.net>
*
* Its only as secure as your shell, the encryption only offers a slightly
* better solution then plain text.
*
* $Log$
* Revision 1.3 2005/01/28 04:37:47 imaginos
* force requirements on main class to so savebuff can be sure to save all data needed. added todo list
*
* Revision 1.2 2004/11/07 02:53:32 imaginos
* added replay to savebuff so one can 'replay' a channel
*
* Revision 1.1.1.1 2004/08/24 00:08:52 prozacx
*
*
*
*/
class CSaveBuff;
class CSaveBuffJob : public CTimer
{
public:
CSaveBuffJob( CModule* pModule, unsigned int uInterval, unsigned int uCycles, const string& sLabel, const string& sDescription )
: CTimer( pModule, uInterval, uCycles, sLabel, sDescription) {}
virtual ~CSaveBuffJob() {}
protected:
virtual void RunJob();
};
class CSaveBuff : public CModule
{
public:
MODCONSTRUCTOR(CSaveBuff)
{
// m_sPassword = CBlowfish::MD5( "" );
AddTimer( new CSaveBuffJob( this, 60, 0, "SaveBuff", "Saves the current buffer to disk every 1 minute" ) );
}
virtual ~CSaveBuff()
{
SaveBufferToDisk();
}
virtual bool OnBoot()
{
if ( m_sPassword.empty() )
{
char *pTmp = getpass( "Enter Encryption Key for savebuff.so: " );
if ( pTmp )
m_sPassword = CBlowfish::MD5( pTmp );
*pTmp = 0;
}
const vector<CChan *>& vChans = m_pUser->GetChans();
for( u_int a = 0; a < vChans.size(); a++ )
{
if ( !BootStrap( vChans[a] ) )
return( false );
}
return true;
}
bool BootStrap( CChan *pChan )
{
string sFile;
if ( DecryptChannel( pChan->GetName(), sFile ) )
{
string sLine;
u_int iPos = 0;
while( ReadLine( sFile, sLine, iPos ) )
{
CUtils::Trim( sLine );
pChan->AddBuffer( sLine );
}
} else
{
cerr << "Failed to Decrypt [" << pChan->GetName() << "]" << endl;
return( false );
}
return( true );
}
void SaveBufferToDisk()
{
if ( !m_sPassword.empty() )
{
const vector<CChan *>& vChans = m_pUser->GetChans();
for( u_int a = 0; a < vChans.size(); a++ )
{
const vector<string> & vBuffer = vChans[a]->GetBuffer();
vChans[a]->SetKeepBuffer( true );
vChans[a]->SetBufferCount( 500 );
if ( vBuffer.empty() )
{
if ( !m_sPassword.empty() )
BootStrap( vChans[a] );
continue;
}
string sFile = CRYPT_VERIFICATION_TOKEN;
for( u_int b = 0; b < vBuffer.size(); b++ )
sFile += vBuffer[b] + "\n";
CBlowfish c( m_sPassword, BF_ENCRYPT );
sFile = c.Crypt( sFile );
string sPath = GetPath( vChans[a]->GetName() );
if ( !sPath.empty() )
{
WriteFile( sPath, sFile );
chmod( sPath.c_str(), 0600 );
}
}
}
}
virtual string GetDescription()
{
return ( "Stores channel buffers to disk, encrypted." );
}
virtual void OnModCommand( const string& sCommand )
{
u_int iPos = sCommand.find( " " );
string sCom, sArgs;
if ( iPos == string::npos )
sCom = sCommand;
else
{
sCom = sCommand.substr( 0, iPos );
sArgs = sCommand.substr( iPos + 1, string::npos );
}
if ( strcasecmp( sCom.c_str(), "setpass" ) == 0 )
{
PutModule( "Password set to [" + sArgs + "]" );
m_sPassword = CBlowfish::MD5( sArgs );
} else if ( strcasecmp( sCom.c_str(), "dumpbuff" ) == 0 )
{
string sFile;
if ( DecryptChannel( sArgs, sFile ) )
{
string sLine;
u_int iPos = 0;
while( ReadLine( sFile, sLine, iPos ) )
{
CUtils::Trim( sLine );
PutModule( "[" + sLine + "]" );
}
}
PutModule( "//!-- EOF " + sArgs );
} else if ( strcasecmp( sCom.c_str(), "replay" ) == 0 )
{
string sFile;
PutUser( ":***!znc@znc.com PRIVMSG " + sArgs + " :Replaying ..." );
if ( DecryptChannel( sArgs, sFile ) )
{
string sLine;
u_int iPos = 0;
while( ReadLine( sFile, sLine, iPos ) )
{
CUtils::Trim( sLine );
PutUser( sLine );
}
}
PutModule( "Replayed " + sArgs );
PutUser( ":***!znc@znc.com PRIVMSG " + sArgs + " :Done!" );
} else if ( strcasecmp( sCom.c_str(), "save" ) == 0 )
{
SaveBufferToDisk();
PutModule( "Done." );
} else
PutModule( "Unknown command [" + sCommand + "]" );
}
string GetPath( const string & sChannel )
{
string sBuffer = m_pUser->GetUserName() + Lower( sChannel );
string sRet = m_pUser->GetHomePath();
sRet += "/.znc-savebuff-" + CBlowfish::MD5( sBuffer, true );
return( sRet );
}
private:
string m_sPassword;
bool DecryptChannel( const string & sChan, string & sBuffer )
{
string sChannel = GetPath( sChan );
string sFile;
sBuffer = "";
if ( ( sChannel.empty() ) || ( !ReadFile( sChannel, sFile ) ) )
{
PutModule( "Unable to find buffer for that channel" );
return( true ); // gonna be successful here
}
if ( !sFile.empty() )
{
CBlowfish c( m_sPassword, BF_DECRYPT );
sBuffer = c.Crypt( sFile );
if ( sBuffer.substr( 0, strlen( CRYPT_VERIFICATION_TOKEN ) ) != CRYPT_VERIFICATION_TOKEN )
{
// failed to decode :(
PutModule( "Unable to decode Encrypted file [" + sChannel + "]" );
return( false );
}
sBuffer.erase( 0, strlen( CRYPT_VERIFICATION_TOKEN ) );
}
return( true );
}
};
void CSaveBuffJob::RunJob()
{
CSaveBuff *p = (CSaveBuff *)m_pModule;
p->SaveBufferToDisk();
}
MODULEDEFS(CSaveBuff)
<|endoftext|> |
<commit_before>#include "Halide.h"
using namespace Halide;
// Define a 1D Gaussian blur (a [1 4 6 4 1] filter) of 5 elements.
Expr blur5(Expr x0, Expr x1, Expr x2, Expr x3, Expr x4) {
// Widen to 16 bits, so we don't overflow while computing the stencil.
x0 = cast<uint16_t>(x0);
x1 = cast<uint16_t>(x1);
x2 = cast<uint16_t>(x2);
x3 = cast<uint16_t>(x3);
x4 = cast<uint16_t>(x4);
return cast<uint8_t>((x0 + 4*x1 + 6*x2 + 4*x3 + x4 + 8)/16);
}
int main(int argc, char **argv) {
Target target = get_target_from_environment();
std::cout << "Target: " << target.to_string() << "\n";
Var x("x"), y("y"), c("c");
// Takes an 8-bit input image.
ImageParam input(UInt(8), 3);
// Apply a boundary condition to the input.
Func input_bounded = BoundaryConditions::repeat_edge(input);
// Implement this as a separable blur in y followed by x.
Func blur_y("blur_y");
blur_y(x, y, c) = blur5(input_bounded(x, y - 2, c),
input_bounded(x, y - 1, c),
input_bounded(x, y, c),
input_bounded(x, y + 1, c),
input_bounded(x, y + 2, c));
RDom r(0, 1000);
blur_y(x, y, c) += cast<uint8_t>(r);
Func blur("blur");
blur(x, y, c) = blur5(blur_y(x - 2, y, c),
blur_y(x - 1, y, c),
blur_y(x, y, c),
blur_y(x + 1, y, c),
blur_y(x + 2, y, c));
// Schedule.
// Require the input and output to have 3 channels.
blur.bound(c, 0, 3);
input.set_min(2, 0).set_extent(2, 3);
if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
const int vector_size = target.has_feature(Target::HVX_128) ? 128 : 64;
// The strategy here is to split each scanline of the result
// into chunks of multiples of the vector size, computing the
// blur in y at each chunk. We use the RoundUp tail strategy to
// keep the last chunk's memory accesses aligned.
Var xo("xo"), xi("xi");
blur.compute_root()
.hexagon()
.split(x, xo, xi, vector_size*2, TailStrategy::RoundUp)
.vectorize(xi, vector_size)
.parallel(y, 64);
blur_y.compute_at(blur, y)
.vectorize(x, vector_size, TailStrategy::RoundUp);
// Require scanlines of the input and output to be aligned.
auto blur_buffer = blur.output_buffer();
input.set_host_alignment(vector_size);
blur_buffer.set_host_alignment(vector_size);
input.set_min(0, 0).set_extent(0, (input.extent(0)/vector_size)*vector_size);
blur_buffer.set_min(0, 0).set_extent(0, (blur_buffer.extent(0)/vector_size)*vector_size);
for (int i = 1; i < 3; i++) {
input.set_stride(i, (input.stride(i)/vector_size)*vector_size);
blur_buffer.set_stride(i, (blur_buffer.stride(i)/vector_size)*vector_size);
}
} else {
const int vector_size = target.natural_vector_size<uint8_t>();
blur.compute_root()
.parallel(y, 16)
.vectorize(x, vector_size);
blur_y.compute_at(blur, y)
.vectorize(x, vector_size);
}
std::stringstream hdr;
hdr << argv[2] << ".h";
blur.compile_to_header(hdr.str(), {input}, argv[2], target);
std::stringstream obj;
obj << argv[1] << ".o";
blur.compile_to_object(obj.str(), {input}, argv[2], target);
return 0;
}
<commit_msg>Revert testing code<commit_after>#include "Halide.h"
using namespace Halide;
// Define a 1D Gaussian blur (a [1 4 6 4 1] filter) of 5 elements.
Expr blur5(Expr x0, Expr x1, Expr x2, Expr x3, Expr x4) {
// Widen to 16 bits, so we don't overflow while computing the stencil.
x0 = cast<uint16_t>(x0);
x1 = cast<uint16_t>(x1);
x2 = cast<uint16_t>(x2);
x3 = cast<uint16_t>(x3);
x4 = cast<uint16_t>(x4);
return cast<uint8_t>((x0 + 4*x1 + 6*x2 + 4*x3 + x4 + 8)/16);
}
int main(int argc, char **argv) {
Target target = get_target_from_environment();
std::cout << "Target: " << target.to_string() << "\n";
Var x("x"), y("y"), c("c");
// Takes an 8-bit input image.
ImageParam input(UInt(8), 3);
// Apply a boundary condition to the input.
Func input_bounded = BoundaryConditions::repeat_edge(input);
// Implement this as a separable blur in y followed by x.
Func blur_y("blur_y");
blur_y(x, y, c) = blur5(input_bounded(x, y - 2, c),
input_bounded(x, y - 1, c),
input_bounded(x, y, c),
input_bounded(x, y + 1, c),
input_bounded(x, y + 2, c));
Func blur("blur");
blur(x, y, c) = blur5(blur_y(x - 2, y, c),
blur_y(x - 1, y, c),
blur_y(x, y, c),
blur_y(x + 1, y, c),
blur_y(x + 2, y, c));
// Schedule.
// Require the input and output to have 3 channels.
blur.bound(c, 0, 3);
input.set_min(2, 0).set_extent(2, 3);
if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
const int vector_size = target.has_feature(Target::HVX_128) ? 128 : 64;
// The strategy here is to split each scanline of the result
// into chunks of multiples of the vector size, computing the
// blur in y at each chunk. We use the RoundUp tail strategy to
// keep the last chunk's memory accesses aligned.
Var xo("xo"), xi("xi");
blur.compute_root()
.hexagon()
.split(x, xo, xi, vector_size*2, TailStrategy::RoundUp)
.vectorize(xi, vector_size)
.parallel(y, 16);
blur_y.compute_at(blur, y)
.vectorize(x, vector_size, TailStrategy::RoundUp);
// Require scanlines of the input and output to be aligned.
auto blur_buffer = blur.output_buffer();
input.set_host_alignment(vector_size);
blur_buffer.set_host_alignment(vector_size);
input.set_min(0, 0).set_extent(0, (input.extent(0)/vector_size)*vector_size);
blur_buffer.set_min(0, 0).set_extent(0, (blur_buffer.extent(0)/vector_size)*vector_size);
for (int i = 1; i < 3; i++) {
input.set_stride(i, (input.stride(i)/vector_size)*vector_size);
blur_buffer.set_stride(i, (blur_buffer.stride(i)/vector_size)*vector_size);
}
} else {
const int vector_size = target.natural_vector_size<uint8_t>();
blur.compute_root()
.parallel(y, 16)
.vectorize(x, vector_size);
blur_y.compute_at(blur, y)
.vectorize(x, vector_size);
}
std::stringstream hdr;
hdr << argv[2] << ".h";
blur.compile_to_header(hdr.str(), {input}, argv[2], target);
std::stringstream obj;
obj << argv[1] << ".o";
blur.compile_to_object(obj.str(), {input}, argv[2], target);
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gcach_ftyp.hxx,v $
*
* $Revision: 1.32 $
*
* last change: $Author: kz $ $Date: 2005-11-02 13:30:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SV_GCACHFTYP_HXX
#define _SV_GCACHFTYP_HXX
#include <glyphcache.hxx>
#include <rtl/textcvt.h>
#include <ft2build.h>
#include FT_FREETYPE_H
class FreetypeServerFont;
struct FT_GlyphRec_;
// -----------------------------------------------------------------------
// FtFontFile has the responsibility that a font file is only mapped once.
// (#86621#) the old directly ft-managed solution caused it to be mapped
// in up to nTTC*nSizes*nOrientation*nSynthetic times
class FtFontFile
{
public:
static FtFontFile* FindFontFile( const ::rtl::OString& rNativeFileName );
bool Map();
void Unmap();
const unsigned char* GetBuffer() const { return mpFileMap; }
int GetFileSize() const { return mnFileSize; }
const ::rtl::OString* GetFileName() const { return &maNativeFileName; }
int GetLangBoost() const { return mnLangBoost; }
private:
FtFontFile( const ::rtl::OString& rNativeFileName );
const ::rtl::OString maNativeFileName;
const unsigned char* mpFileMap;
int mnFileSize;
int mnRefCount;
int mnLangBoost;
};
// -----------------------------------------------------------------------
// FtFontInfo corresponds to an unscaled font face
class FtFontInfo
{
public:
FtFontInfo( const ImplDevFontAttributes&,
const ::rtl::OString& rNativeFileName,
int nFaceNum, int nFontId, int nSynthetic,
const ExtraKernInfo* );
~FtFontInfo();
const unsigned char* GetTable( const char*, ULONG* pLength=0 ) const;
FT_FaceRec_* GetFaceFT();
void ReleaseFaceFT( FT_FaceRec_* );
const ::rtl::OString* GetFontFileName() const { return mpFontFile->GetFileName(); }
int GetFaceNum() const { return mnFaceNum; }
int GetSynthetic() const { return mnSynthetic; }
int GetFontId() const { return mnFontId; }
bool IsSymbolFont() const { return maDevFontAttributes.IsSymbolFont(); }
const ImplFontAttributes& GetFontAttributes() const { return maDevFontAttributes; }
void AnnounceFont( ImplDevFontList* );
int GetGlyphIndex( sal_UCS4 cChar ) const;
void CacheGlyphIndex( sal_UCS4 cChar, int nGI ) const;
bool HasExtraKerning() const;
int GetExtraKernPairs( ImplKernPairData** ) const;
int GetExtraGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;
private:
FT_FaceRec_* maFaceFT;
FtFontFile* mpFontFile;
const int mnFaceNum;
int mnRefCount;
const int mnSynthetic;
int mnFontId;
ImplDevFontAttributes maDevFontAttributes;
// cache unicode->glyphid mapping because looking it up is expensive
// TODO: change to hash_multimap when a use case requires a m:n mapping
typedef ::std::hash_map<int,int> Int2IntMap;
mutable Int2IntMap maChar2Glyph;
mutable Int2IntMap maGlyph2Char;
const ExtraKernInfo* mpExtraKernInfo;
};
// these two inlines are very important for performance
inline int FtFontInfo::GetGlyphIndex( sal_UCS4 cChar ) const
{
Int2IntMap::const_iterator it = maChar2Glyph.find( cChar );
if( it == maChar2Glyph.end() )
return -1;
return it->second;
}
inline void FtFontInfo::CacheGlyphIndex( sal_UCS4 cChar, int nIndex ) const
{
maChar2Glyph[ cChar ] = nIndex;
maGlyph2Char[ nIndex ] = cChar;
}
// -----------------------------------------------------------------------
class FreetypeManager
{
public:
FreetypeManager();
~FreetypeManager();
long AddFontDir( const String& rUrlName );
void AddFontFile( const rtl::OString& rNormalizedName,
int nFaceNum, int nFontId, const ImplDevFontAttributes&,
const ExtraKernInfo* );
void AnnounceFonts( ImplDevFontList* ) const;
void ClearFontList();
FreetypeServerFont* CreateFont( const ImplFontSelectData& );
private:
typedef ::std::hash_map<int,FtFontInfo*> FontList;
FontList maFontList;
int mnMaxFontId;
int mnNextFontId;
};
// -----------------------------------------------------------------------
class FreetypeServerFont : public ServerFont
{
public:
FreetypeServerFont( const ImplFontSelectData&, FtFontInfo* );
virtual ~FreetypeServerFont();
virtual const ::rtl::OString* GetFontFileName() const { return mpFontInfo->GetFontFileName(); }
virtual int GetFontFaceNum() const { return mpFontInfo->GetFaceNum(); }
virtual bool TestFont() const;
virtual void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;
virtual int GetGlyphIndex( sal_UCS4 ) const;
int GetRawGlyphIndex( sal_UCS4 ) const;
int FixupGlyphIndex( int nGlyphIndex, sal_UCS4 ) const;
virtual bool GetAntialiasAdvice( void ) const;
virtual bool GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;
virtual bool GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;
virtual bool GetGlyphOutline( int nGlyphIndex, ::basegfx::B2DPolyPolygon& ) const;
virtual int GetGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;
virtual ULONG GetKernPairs( ImplKernPairData** ) const;
const unsigned char* GetTable( const char* pName, ULONG* pLength )
{ return mpFontInfo->GetTable( pName, pLength ); }
int GetEmUnits() const;
const FT_Size_Metrics& GetMetricsFT() const { return maSizeFT->metrics; }
protected:
friend class GlyphCache;
int ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_*, bool ) const;
virtual void InitGlyphData( int nGlyphIndex, GlyphData& ) const;
virtual ULONG GetFontCodeRanges( sal_uInt32* pCodes ) const;
bool ApplyGSUB( const ImplFontSelectData& );
virtual ServerFontLayoutEngine* GetLayoutEngine();
private:
int mnWidth;
FtFontInfo* mpFontInfo;
FT_Int mnLoadFlags;
double mfStretch;
FT_FaceRec_* maFaceFT;
FT_SizeRec_* maSizeFT;
typedef ::std::hash_map<int,int> GlyphSubstitution;
GlyphSubstitution maGlyphSubstitution;
rtl_UnicodeToTextConverter maRecodeConverter;
ServerFontLayoutEngine* mpLayoutEngine;
};
// -----------------------------------------------------------------------
class ImplFTSFontData : public ImplFontData
{
private:
FtFontInfo* mpFtFontInfo;
enum { IFTSFONT_MAGIC = 0x1F150A1C };
public:
ImplFTSFontData( FtFontInfo*, const ImplDevFontAttributes& );
virtual ~ImplFTSFontData();
FtFontInfo* GetFtFontInfo() const { return mpFtFontInfo; }
virtual ImplFontEntry* CreateFontInstance( ImplFontSelectData& ) const;
virtual ImplFontData* Clone() const { return new ImplFTSFontData( *this ); }
virtual int GetFontId() const { return mpFtFontInfo->GetFontId(); }
static bool CheckFontData( const ImplFontData& r ) { return r.CheckMagic( IFTSFONT_MAGIC ); }
};
// -----------------------------------------------------------------------
#endif // _SV_GCACHFTYP_HXX
<commit_msg>INTEGRATION: CWS fakebold (1.31.48); FILE MERGED 2005/12/06 12:30:39 hdu 1.31.48.2: RESYNC: (1.31-1.32); FILE MERGED 2005/10/11 14:22:27 hdu 1.31.48.1: #i18285# apply the patch for synthetic font attributes<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gcach_ftyp.hxx,v $
*
* $Revision: 1.33 $
*
* last change: $Author: rt $ $Date: 2005-12-14 09:12:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SV_GCACHFTYP_HXX
#define _SV_GCACHFTYP_HXX
#include <glyphcache.hxx>
#include <rtl/textcvt.h>
#include <ft2build.h>
#include FT_FREETYPE_H
class FreetypeServerFont;
struct FT_GlyphRec_;
// -----------------------------------------------------------------------
// FtFontFile has the responsibility that a font file is only mapped once.
// (#86621#) the old directly ft-managed solution caused it to be mapped
// in up to nTTC*nSizes*nOrientation*nSynthetic times
class FtFontFile
{
public:
static FtFontFile* FindFontFile( const ::rtl::OString& rNativeFileName );
bool Map();
void Unmap();
const unsigned char* GetBuffer() const { return mpFileMap; }
int GetFileSize() const { return mnFileSize; }
const ::rtl::OString* GetFileName() const { return &maNativeFileName; }
int GetLangBoost() const { return mnLangBoost; }
private:
FtFontFile( const ::rtl::OString& rNativeFileName );
const ::rtl::OString maNativeFileName;
const unsigned char* mpFileMap;
int mnFileSize;
int mnRefCount;
int mnLangBoost;
};
// -----------------------------------------------------------------------
// FtFontInfo corresponds to an unscaled font face
class FtFontInfo
{
public:
FtFontInfo( const ImplDevFontAttributes&,
const ::rtl::OString& rNativeFileName,
int nFaceNum, int nFontId, int nSynthetic,
const ExtraKernInfo* );
~FtFontInfo();
const unsigned char* GetTable( const char*, ULONG* pLength=0 ) const;
FT_FaceRec_* GetFaceFT();
void ReleaseFaceFT( FT_FaceRec_* );
const ::rtl::OString* GetFontFileName() const { return mpFontFile->GetFileName(); }
int GetFaceNum() const { return mnFaceNum; }
int GetSynthetic() const { return mnSynthetic; }
int GetFontId() const { return mnFontId; }
bool IsSymbolFont() const { return maDevFontAttributes.IsSymbolFont(); }
const ImplFontAttributes& GetFontAttributes() const { return maDevFontAttributes; }
void AnnounceFont( ImplDevFontList* );
int GetGlyphIndex( sal_UCS4 cChar ) const;
void CacheGlyphIndex( sal_UCS4 cChar, int nGI ) const;
bool HasExtraKerning() const;
int GetExtraKernPairs( ImplKernPairData** ) const;
int GetExtraGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;
private:
FT_FaceRec_* maFaceFT;
FtFontFile* mpFontFile;
const int mnFaceNum;
int mnRefCount;
const int mnSynthetic;
int mnFontId;
ImplDevFontAttributes maDevFontAttributes;
// cache unicode->glyphid mapping because looking it up is expensive
// TODO: change to hash_multimap when a use case requires a m:n mapping
typedef ::std::hash_map<int,int> Int2IntMap;
mutable Int2IntMap maChar2Glyph;
mutable Int2IntMap maGlyph2Char;
const ExtraKernInfo* mpExtraKernInfo;
};
// these two inlines are very important for performance
inline int FtFontInfo::GetGlyphIndex( sal_UCS4 cChar ) const
{
Int2IntMap::const_iterator it = maChar2Glyph.find( cChar );
if( it == maChar2Glyph.end() )
return -1;
return it->second;
}
inline void FtFontInfo::CacheGlyphIndex( sal_UCS4 cChar, int nIndex ) const
{
maChar2Glyph[ cChar ] = nIndex;
maGlyph2Char[ nIndex ] = cChar;
}
// -----------------------------------------------------------------------
class FreetypeManager
{
public:
FreetypeManager();
~FreetypeManager();
long AddFontDir( const String& rUrlName );
void AddFontFile( const rtl::OString& rNormalizedName,
int nFaceNum, int nFontId, const ImplDevFontAttributes&,
const ExtraKernInfo* );
void AnnounceFonts( ImplDevFontList* ) const;
void ClearFontList();
FreetypeServerFont* CreateFont( const ImplFontSelectData& );
private:
typedef ::std::hash_map<int,FtFontInfo*> FontList;
FontList maFontList;
int mnMaxFontId;
int mnNextFontId;
};
// -----------------------------------------------------------------------
class FreetypeServerFont : public ServerFont
{
public:
FreetypeServerFont( const ImplFontSelectData&, FtFontInfo* );
virtual ~FreetypeServerFont();
virtual const ::rtl::OString* GetFontFileName() const { return mpFontInfo->GetFontFileName(); }
virtual int GetFontFaceNum() const { return mpFontInfo->GetFaceNum(); }
virtual bool TestFont() const;
virtual void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;
virtual int GetGlyphIndex( sal_UCS4 ) const;
int GetRawGlyphIndex( sal_UCS4 ) const;
int FixupGlyphIndex( int nGlyphIndex, sal_UCS4 ) const;
virtual bool GetAntialiasAdvice( void ) const;
virtual bool GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;
virtual bool GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;
virtual bool GetGlyphOutline( int nGlyphIndex, ::basegfx::B2DPolyPolygon& ) const;
virtual int GetGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const;
virtual ULONG GetKernPairs( ImplKernPairData** ) const;
const unsigned char* GetTable( const char* pName, ULONG* pLength )
{ return mpFontInfo->GetTable( pName, pLength ); }
int GetEmUnits() const;
const FT_Size_Metrics& GetMetricsFT() const { return maSizeFT->metrics; }
protected:
friend class GlyphCache;
int ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_*, bool ) const;
virtual void InitGlyphData( int nGlyphIndex, GlyphData& ) const;
virtual ULONG GetFontCodeRanges( sal_uInt32* pCodes ) const;
bool ApplyGSUB( const ImplFontSelectData& );
virtual ServerFontLayoutEngine* GetLayoutEngine();
private:
int mnWidth;
FtFontInfo* mpFontInfo;
FT_Int mnLoadFlags;
double mfStretch;
FT_FaceRec_* maFaceFT;
FT_SizeRec_* maSizeFT;
bool mbArtItalic;
bool mbArtBold;
bool mbUseGamma;
typedef ::std::hash_map<int,int> GlyphSubstitution;
GlyphSubstitution maGlyphSubstitution;
rtl_UnicodeToTextConverter maRecodeConverter;
ServerFontLayoutEngine* mpLayoutEngine;
};
// -----------------------------------------------------------------------
class ImplFTSFontData : public ImplFontData
{
private:
FtFontInfo* mpFtFontInfo;
enum { IFTSFONT_MAGIC = 0x1F150A1C };
public:
ImplFTSFontData( FtFontInfo*, const ImplDevFontAttributes& );
virtual ~ImplFTSFontData();
FtFontInfo* GetFtFontInfo() const { return mpFtFontInfo; }
virtual ImplFontEntry* CreateFontInstance( ImplFontSelectData& ) const;
virtual ImplFontData* Clone() const { return new ImplFTSFontData( *this ); }
virtual int GetFontId() const { return mpFtFontInfo->GetFontId(); }
static bool CheckFontData( const ImplFontData& r ) { return r.CheckMagic( IFTSFONT_MAGIC ); }
};
// -----------------------------------------------------------------------
#endif // _SV_GCACHFTYP_HXX
<|endoftext|> |
<commit_before>
/*
/~` _ _ _|_. _ _ |_ | _
\_,(_)| | | || ||_|(_||_)|(/_
https://github.com/Naios/continuable
v3.0.0
Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**/
#ifndef CONTINUABLE_DETAIL_COMPOSITION_ALL_HPP_INCLUDED
#define CONTINUABLE_DETAIL_COMPOSITION_ALL_HPP_INCLUDED
#include <atomic>
#include <memory>
#include <mutex>
#include <tuple>
#include <type_traits>
#include <utility>
#include <continuable/detail/base.hpp>
#include <continuable/detail/composition-remapping.hpp>
#include <continuable/detail/composition.hpp>
#include <continuable/detail/hints.hpp>
#include <continuable/detail/traits.hpp>
#include <continuable/detail/types.hpp>
namespace cti {
namespace detail {
namespace composition {
namespace all {
struct all_hint_deducer {
static constexpr auto deduce(hints::signature_hint_tag<>) noexcept
-> decltype(spread_this());
template <typename First>
static constexpr auto deduce(hints::signature_hint_tag<First>) -> First;
template <typename First, typename Second, typename... Args>
static constexpr auto
deduce(hints::signature_hint_tag<First, Second, Args...>)
-> decltype(spread_this(std::declval<First>(), std::declval<Second>(),
std::declval<Args>()...));
template <
typename T,
std::enable_if_t<base::is_continuable<std::decay_t<T>>::value>* = nullptr>
auto operator()(T&& /*continuable*/) const
-> decltype(deduce(hints::hint_of(traits::identify<T>{})));
};
constexpr auto deduce_from_pack(traits::identity<void>)
-> hints::signature_hint_tag<>;
template <typename... T>
constexpr auto deduce_from_pack(traits::identity<std::tuple<T...>>)
-> hints::signature_hint_tag<T...>;
template <typename T>
constexpr auto deduce_from_pack(traits::identity<T>)
-> hints::signature_hint_tag<T>;
// We must guard the mapped type against to be void since this represents an
// empty signature hint.
template <typename Composition>
constexpr auto deduce_hint(Composition && /*composition*/)
-> decltype(deduce_from_pack(
traits::identity<decltype(map_pack(all_hint_deducer{},
std::declval<Composition>()))>{})){};
/// Caches the partial results and invokes the callback when all results
/// are arrived. This class is thread safe.
template <typename Callback, typename Result>
class result_submitter
: public std::enable_shared_from_this<result_submitter<Callback, Result>>,
public util::non_movable {
Callback callback_;
Result result_;
std::atomic<std::size_t> left_;
std::once_flag flag_;
// Invokes the callback with the cached result
void invoke() {
assert((left_ == 0U) && "Expected that the submitter is finished!");
std::atomic_thread_fence(std::memory_order_acquire);
auto cleaned =
map_pack(remapping::unpack_result_guards{}, std::move(result_));
// Call the final callback with the cleaned result
traits::unpack(std::move(cleaned), [&](auto&&... args) {
std::call_once(flag_, std::move(callback_),
std::forward<decltype(args)>(args)...);
});
}
// Completes one result
void complete_one() {
assert((left_ > 0U) && "Expected that the submitter isn't finished!");
auto const current = --left_;
if (!current) {
invoke();
}
}
template <typename Target>
struct partial_all_callback {
Target* target;
std::shared_ptr<result_submitter> me;
template <typename... Args>
void operator()(Args&&... args) && {
// Assign the result to the target
*target = remapping::wrap(std::forward<decltype(args)>(args)...);
// Complete one result
me->complete_one();
}
template <typename... PartialArgs>
void operator()(types::dispatch_error_tag tag, types::error_type error) && {
// We never complete the composition, but we forward the first error
// which was raised.
std::call_once(me->flag_, std::move(me->callback_), tag,
std::move(error));
}
};
public:
explicit result_submitter(Callback callback, Result&& result)
: callback_(std::move(callback)), result_(std::move(result)), left_(1) {
}
/// Creates a submitter which submits it's result into the storage
template <typename Target>
auto create_callback(Target* target) {
left_.fetch_add(1, std::memory_order_seq_cst);
return partial_all_callback<std::decay_t<Target>>{target,
this->shared_from_this()};
}
/// Initially the counter is created with an initial count of 1 in order
/// to prevent that the composition is finished before all callbacks
/// were registered.
void accept() {
complete_one();
}
constexpr Result* result_ptr() noexcept {
return &result_;
}
};
template <typename Submitter>
struct continuable_dispatcher {
std::shared_ptr<Submitter>& submitter;
template <typename Index, typename Target,
std::enable_if_t<
base::is_continuable<std::decay_t<Index>>::value>* = nullptr>
void operator()(Index* index, Target* target) const {
// Retrieve a callback from the submitter and attach it to the continuable
std::move(*index).next(submitter->create_callback(target)).done();
}
};
} // namespace all
/// Finalizes the all logic of a given composition
template <>
struct composition_finalizer<composition_strategy_all_tag> {
template <typename Composition>
static constexpr auto hint() {
return decltype(all::deduce_hint(std::declval<Composition>())){};
}
/// Finalizes the all logic of a given composition
template <typename Composition>
static auto finalize(Composition&& composition) {
return [composition = std::forward<Composition>(composition)] // ...
(auto&& callback) mutable {
// Create the target result from the composition
auto result = remapping::create_result_pack(std::move(composition));
using submitter_t =
all::result_submitter<std::decay_t<decltype(callback)>,
std::decay_t<decltype(result)>>;
// Create the shared state which holds the result and the final callback
auto state = std::make_shared<submitter_t>(
std::forward<decltype(callback)>(callback), std::move(result));
// Dispatch the continuables and store its partial result
// in the whole result
// TODO Fix use after move here
remapping::relocate_index_pack(
all::continuable_dispatcher<submitter_t>{state}, &composition,
state->result_ptr());
// Finalize the composition if all results arrived in-place
state->accept();
};
}
};
} // namespace composition
} // namespace detail
} // namespace cti
#endif // CONTINUABLE_DETAIL_COMPOSITION_ALL_HPP_INCLUDED
<commit_msg>Attempt to fix the clang build<commit_after>
/*
/~` _ _ _|_. _ _ |_ | _
\_,(_)| | | || ||_|(_||_)|(/_
https://github.com/Naios/continuable
v3.0.0
Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**/
#ifndef CONTINUABLE_DETAIL_COMPOSITION_ALL_HPP_INCLUDED
#define CONTINUABLE_DETAIL_COMPOSITION_ALL_HPP_INCLUDED
#include <atomic>
#include <memory>
#include <mutex>
#include <tuple>
#include <type_traits>
#include <utility>
#include <continuable/detail/base.hpp>
#include <continuable/detail/composition-remapping.hpp>
#include <continuable/detail/composition.hpp>
#include <continuable/detail/hints.hpp>
#include <continuable/detail/traits.hpp>
#include <continuable/detail/types.hpp>
namespace cti {
namespace detail {
namespace composition {
namespace all {
struct all_hint_deducer {
static constexpr auto deduce(hints::signature_hint_tag<>) noexcept {
return spread_this();
}
template <typename First>
static constexpr auto deduce(hints::signature_hint_tag<First>) {
return First{};
}
template <typename First, typename Second, typename... Args>
static constexpr auto
deduce(hints::signature_hint_tag<First, Second, Args...>) {
return spread_this(First{}, Second{}, Args{}...);
}
template <
typename T,
std::enable_if_t<base::is_continuable<std::decay_t<T>>::value>* = nullptr>
auto operator()(T&& /*continuable*/) const {
return deduce(hints::hint_of(traits::identify<T>{}));
}
};
constexpr auto deduce_from_pack(traits::identity<void>)
-> hints::signature_hint_tag<>;
template <typename... T>
constexpr auto deduce_from_pack(traits::identity<std::tuple<T...>>)
-> hints::signature_hint_tag<T...>;
template <typename T>
constexpr auto deduce_from_pack(traits::identity<T>)
-> hints::signature_hint_tag<T>;
// We must guard the mapped type against to be void since this represents an
// empty signature hint.
template <typename Composition>
constexpr auto deduce_hint(Composition && /*composition*/)
-> decltype(deduce_from_pack(
traits::identity<decltype(map_pack(all_hint_deducer{},
std::declval<Composition>()))>{})){};
/// Caches the partial results and invokes the callback when all results
/// are arrived. This class is thread safe.
template <typename Callback, typename Result>
class result_submitter
: public std::enable_shared_from_this<result_submitter<Callback, Result>>,
public util::non_movable {
Callback callback_;
Result result_;
std::atomic<std::size_t> left_;
std::once_flag flag_;
// Invokes the callback with the cached result
void invoke() {
assert((left_ == 0U) && "Expected that the submitter is finished!");
std::atomic_thread_fence(std::memory_order_acquire);
auto cleaned =
map_pack(remapping::unpack_result_guards{}, std::move(result_));
// Call the final callback with the cleaned result
traits::unpack(std::move(cleaned), [&](auto&&... args) {
std::call_once(flag_, std::move(callback_),
std::forward<decltype(args)>(args)...);
});
}
// Completes one result
void complete_one() {
assert((left_ > 0U) && "Expected that the submitter isn't finished!");
auto const current = --left_;
if (!current) {
invoke();
}
}
template <typename Target>
struct partial_all_callback {
Target* target;
std::shared_ptr<result_submitter> me;
template <typename... Args>
void operator()(Args&&... args) && {
// Assign the result to the target
*target = remapping::wrap(std::forward<decltype(args)>(args)...);
// Complete one result
me->complete_one();
}
template <typename... PartialArgs>
void operator()(types::dispatch_error_tag tag, types::error_type error) && {
// We never complete the composition, but we forward the first error
// which was raised.
std::call_once(me->flag_, std::move(me->callback_), tag,
std::move(error));
}
};
public:
explicit result_submitter(Callback callback, Result&& result)
: callback_(std::move(callback)), result_(std::move(result)), left_(1) {
}
/// Creates a submitter which submits it's result into the storage
template <typename Target>
auto create_callback(Target* target) {
left_.fetch_add(1, std::memory_order_seq_cst);
return partial_all_callback<std::decay_t<Target>>{target,
this->shared_from_this()};
}
/// Initially the counter is created with an initial count of 1 in order
/// to prevent that the composition is finished before all callbacks
/// were registered.
void accept() {
complete_one();
}
constexpr Result* result_ptr() noexcept {
return &result_;
}
};
template <typename Submitter>
struct continuable_dispatcher {
std::shared_ptr<Submitter>& submitter;
template <typename Index, typename Target,
std::enable_if_t<
base::is_continuable<std::decay_t<Index>>::value>* = nullptr>
void operator()(Index* index, Target* target) const {
// Retrieve a callback from the submitter and attach it to the continuable
std::move(*index).next(submitter->create_callback(target)).done();
}
};
} // namespace all
/// Finalizes the all logic of a given composition
template <>
struct composition_finalizer<composition_strategy_all_tag> {
template <typename Composition>
static constexpr auto hint() {
return decltype(all::deduce_hint(std::declval<Composition>())){};
}
/// Finalizes the all logic of a given composition
template <typename Composition>
static auto finalize(Composition&& composition) {
return [composition = std::forward<Composition>(composition)] // ...
(auto&& callback) mutable {
// Create the target result from the composition
auto result = remapping::create_result_pack(std::move(composition));
using submitter_t =
all::result_submitter<std::decay_t<decltype(callback)>,
std::decay_t<decltype(result)>>;
// Create the shared state which holds the result and the final callback
auto state = std::make_shared<submitter_t>(
std::forward<decltype(callback)>(callback), std::move(result));
// Dispatch the continuables and store its partial result
// in the whole result
// TODO Fix use after move here
remapping::relocate_index_pack(
all::continuable_dispatcher<submitter_t>{state}, &composition,
state->result_ptr());
// Finalize the composition if all results arrived in-place
state->accept();
};
}
};
} // namespace composition
} // namespace detail
} // namespace cti
#endif // CONTINUABLE_DETAIL_COMPOSITION_ALL_HPP_INCLUDED
<|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_OS_POSIX_STAT_HPP__
#define __STOUT_OS_POSIX_STAT_HPP__
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <string>
#include <stout/bytes.hpp>
#include <stout/try.hpp>
#include <stout/unreachable.hpp>
namespace os {
namespace stat {
inline bool isdir(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return false;
}
return S_ISDIR(s.st_mode);
}
inline bool isfile(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return false;
}
return S_ISREG(s.st_mode);
}
inline bool islink(const std::string& path)
{
struct stat s;
if (::lstat(path.c_str(), &s) < 0) {
return false;
}
return S_ISLNK(s.st_mode);
}
// Describes the different semantics supported for the implementation
// of `size` defined below.
enum FollowSymlink
{
DO_NOT_FOLLOW_SYMLINK,
FOLLOW_SYMLINK
};
// Returns the size in Bytes of a given file system entry. When
// applied to a symbolic link with `follow` set to
// `DO_NOT_FOLLOW_SYMLINK`, this will return the length of the entry
// name (strlen).
inline Try<Bytes> size(
const std::string& path,
const FollowSymlink follow = FOLLOW_SYMLINK)
{
struct stat s;
switch (follow) {
case DO_NOT_FOLLOW_SYMLINK: {
if (::lstat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking lstat for '" + path + "'");
} else {
return Bytes(s.st_size);
}
break;
}
case FOLLOW_SYMLINK: {
if (::stat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
} else {
return Bytes(s.st_size);
}
break;
}
}
UNREACHABLE();
}
inline Try<long> mtime(const std::string& path)
{
struct stat s;
if (::lstat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
}
return s.st_mtime;
}
inline Try<mode_t> mode(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
}
return s.st_mode;
}
inline Try<dev_t> dev(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
}
return s.st_dev;
}
inline Try<dev_t> rdev(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
}
if (!S_ISCHR(s.st_mode) && !S_ISBLK(s.st_mode)) {
return Error("Not a special file: " + path);
}
return s.st_rdev;
}
inline Try<ino_t> inode(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
}
return s.st_ino;
}
} // namespace stat {
} // namespace os {
#endif // __STOUT_OS_STAT_HPP__
<commit_msg>Fixed a comment in `stat.hpp`.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_OS_POSIX_STAT_HPP__
#define __STOUT_OS_POSIX_STAT_HPP__
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <string>
#include <stout/bytes.hpp>
#include <stout/try.hpp>
#include <stout/unreachable.hpp>
namespace os {
namespace stat {
inline bool isdir(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return false;
}
return S_ISDIR(s.st_mode);
}
inline bool isfile(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return false;
}
return S_ISREG(s.st_mode);
}
inline bool islink(const std::string& path)
{
struct stat s;
if (::lstat(path.c_str(), &s) < 0) {
return false;
}
return S_ISLNK(s.st_mode);
}
// Describes the different semantics supported for the implementation
// of `size` defined below.
enum FollowSymlink
{
DO_NOT_FOLLOW_SYMLINK,
FOLLOW_SYMLINK
};
// Returns the size in Bytes of a given file system entry. When
// applied to a symbolic link with `follow` set to
// `DO_NOT_FOLLOW_SYMLINK`, this will return the length of the entry
// name (strlen).
inline Try<Bytes> size(
const std::string& path,
const FollowSymlink follow = FOLLOW_SYMLINK)
{
struct stat s;
switch (follow) {
case DO_NOT_FOLLOW_SYMLINK: {
if (::lstat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking lstat for '" + path + "'");
} else {
return Bytes(s.st_size);
}
break;
}
case FOLLOW_SYMLINK: {
if (::stat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
} else {
return Bytes(s.st_size);
}
break;
}
}
UNREACHABLE();
}
inline Try<long> mtime(const std::string& path)
{
struct stat s;
if (::lstat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
}
return s.st_mtime;
}
inline Try<mode_t> mode(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
}
return s.st_mode;
}
inline Try<dev_t> dev(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
}
return s.st_dev;
}
inline Try<dev_t> rdev(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
}
if (!S_ISCHR(s.st_mode) && !S_ISBLK(s.st_mode)) {
return Error("Not a special file: " + path);
}
return s.st_rdev;
}
inline Try<ino_t> inode(const std::string& path)
{
struct stat s;
if (::stat(path.c_str(), &s) < 0) {
return ErrnoError("Error invoking stat for '" + path + "'");
}
return s.st_ino;
}
} // namespace stat {
} // namespace os {
#endif // __STOUT_OS_POSIX_STAT_HPP__
<|endoftext|> |
<commit_before><commit_msg>windows opengl: Use the updated DrawMask to get nice text with OpenGL.<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.