text
stringlengths 54
60.6k
|
|---|
<commit_before>1a958d92-2e4d-11e5-9284-b827eb9e62be<commit_msg>1a9ac492-2e4d-11e5-9284-b827eb9e62be<commit_after>1a9ac492-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>bde62e66-2e4d-11e5-9284-b827eb9e62be<commit_msg>bdeb21b4-2e4d-11e5-9284-b827eb9e62be<commit_after>bdeb21b4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c3a2e38e-2e4e-11e5-9284-b827eb9e62be<commit_msg>c3a7d98e-2e4e-11e5-9284-b827eb9e62be<commit_after>c3a7d98e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1fe2d8b6-2e4f-11e5-9284-b827eb9e62be<commit_msg>1fe7d05a-2e4f-11e5-9284-b827eb9e62be<commit_after>1fe7d05a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>32560220-2e4f-11e5-9284-b827eb9e62be<commit_msg>325b00b8-2e4f-11e5-9284-b827eb9e62be<commit_after>325b00b8-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d23bb544-2e4c-11e5-9284-b827eb9e62be<commit_msg>d240d236-2e4c-11e5-9284-b827eb9e62be<commit_after>d240d236-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>17b0fe9e-2e4e-11e5-9284-b827eb9e62be<commit_msg>17b6496c-2e4e-11e5-9284-b827eb9e62be<commit_after>17b6496c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>2c2d641a-2e4f-11e5-9284-b827eb9e62be<commit_msg>2c325786-2e4f-11e5-9284-b827eb9e62be<commit_after>2c325786-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d8f99324-2e4c-11e5-9284-b827eb9e62be<commit_msg>d8fea71a-2e4c-11e5-9284-b827eb9e62be<commit_after>d8fea71a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>6f72c456-2e4d-11e5-9284-b827eb9e62be<commit_msg>6f77d13a-2e4d-11e5-9284-b827eb9e62be<commit_after>6f77d13a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3e88e0ae-2e4e-11e5-9284-b827eb9e62be<commit_msg>3e8ded6a-2e4e-11e5-9284-b827eb9e62be<commit_after>3e8ded6a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e07aa844-2e4d-11e5-9284-b827eb9e62be<commit_msg>e07fac9a-2e4d-11e5-9284-b827eb9e62be<commit_after>e07fac9a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>54e92710-2e4d-11e5-9284-b827eb9e62be<commit_msg>54ee350c-2e4d-11e5-9284-b827eb9e62be<commit_after>54ee350c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>#include <algorithm>
#include <map>
#include <memory>
#include "common.h"
// Size of the buffer to store result of ReadDirectoryChangesW.
static const unsigned int kDirectoryWatcherBufferSize = 4096;
// Object template to create representation of WatcherHandle.
static Nan::Persistent<ObjectTemplate> g_object_template;
// Mutex for the HandleWrapper map.
static uv_mutex_t g_handle_wrap_map_mutex;
// The events to be waited on.
static std::vector<HANDLE> g_events;
// The dummy event to wakeup the thread.
static HANDLE g_wake_up_event;
// The dummy event to ensure we are not waiting on a file handle when destroying it.
static HANDLE g_file_handles_free_event;
struct ScopedLocker {
explicit ScopedLocker(uv_mutex_t& mutex) : mutex_(&mutex) { uv_mutex_lock(mutex_); }
~ScopedLocker() { Unlock(); }
void Unlock() { uv_mutex_unlock(mutex_); }
uv_mutex_t* mutex_;
};
struct HandleWrapper {
HandleWrapper(WatcherHandle handle, const char* path_str)
: dir_handle(handle),
path(strlen(path_str)),
canceled(false) {
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
g_events.push_back(overlapped.hEvent);
std::copy(path_str, path_str + path.size(), path.data());
map_[overlapped.hEvent] = this;
}
~HandleWrapper() {
if (!canceled) {
Cancel();
}
CloseHandle(dir_handle);
CloseHandle(overlapped.hEvent);
}
void Cancel() {
canceled = true;
CancelIoEx(dir_handle, &overlapped);
g_events.erase(std::remove(g_events.begin(), g_events.end(), overlapped.hEvent), g_events.end());
map_.erase(overlapped.hEvent);
}
WatcherHandle dir_handle;
std::vector<char> path;
bool canceled;
OVERLAPPED overlapped;
char buffer[kDirectoryWatcherBufferSize];
static HandleWrapper* Get(HANDLE key) { return map_[key]; }
static std::map<WatcherHandle, HandleWrapper*> map_;
};
std::map<WatcherHandle, HandleWrapper*> HandleWrapper::map_;
struct WatcherEvent {
EVENT_TYPE type;
WatcherHandle handle;
std::vector<char> new_path;
std::vector<char> old_path;
};
static bool QueueReaddirchanges(HandleWrapper* handle) {
return ReadDirectoryChangesW(handle->dir_handle,
handle->buffer,
kDirectoryWatcherBufferSize,
FALSE,
FILE_NOTIFY_CHANGE_FILE_NAME |
FILE_NOTIFY_CHANGE_DIR_NAME |
FILE_NOTIFY_CHANGE_ATTRIBUTES |
FILE_NOTIFY_CHANGE_SIZE |
FILE_NOTIFY_CHANGE_LAST_WRITE |
FILE_NOTIFY_CHANGE_LAST_ACCESS |
FILE_NOTIFY_CHANGE_CREATION |
FILE_NOTIFY_CHANGE_SECURITY,
NULL,
&handle->overlapped,
NULL) == TRUE;
}
Local<Value> WatcherHandleToV8Value(WatcherHandle handle) {
Local<Value> value = Nan::New(g_object_template)->NewInstance();
Nan::SetInternalFieldPointer(value->ToObject(), 0, handle);
return value;
}
WatcherHandle V8ValueToWatcherHandle(Local<Value> value) {
return reinterpret_cast<WatcherHandle>(Nan::GetInternalFieldPointer(
value->ToObject(), 0));
}
bool IsV8ValueWatcherHandle(Local<Value> value) {
return value->IsObject() && value->ToObject()->InternalFieldCount() == 1;
}
void PlatformInit() {
uv_mutex_init(&g_handle_wrap_map_mutex);
g_file_handles_free_event = CreateEvent(NULL, TRUE, TRUE, NULL);
g_wake_up_event = CreateEvent(NULL, FALSE, FALSE, NULL);
g_events.push_back(g_wake_up_event);
g_object_template.Reset(Nan::New<ObjectTemplate>());
Nan::New(g_object_template)->SetInternalFieldCount(1);
WakeupNewThread();
}
void PlatformThread() {
while (true) {
// Do not use g_events directly, since reallocation could happen when there
// are new watchers adding to g_events when WaitForMultipleObjects is still
// polling.
ScopedLocker locker(g_handle_wrap_map_mutex);
std::vector<HANDLE> copied_events(g_events);
locker.Unlock();
ResetEvent(g_file_handles_free_event);
DWORD r = WaitForMultipleObjects(copied_events.size(),
copied_events.data(),
FALSE,
INFINITE);
SetEvent(g_file_handles_free_event);
int i = r - WAIT_OBJECT_0;
if (i >= 0 && i < copied_events.size()) {
// It's a wake up event, there is no fs events.
if (copied_events[i] == g_wake_up_event)
continue;
ScopedLocker locker(g_handle_wrap_map_mutex);
HandleWrapper* handle = HandleWrapper::Get(copied_events[i]);
if (!handle || handle->canceled)
continue;
DWORD bytes_transferred;
if (!GetOverlappedResult(handle->dir_handle, &handle->overlapped, &bytes_transferred, FALSE))
continue;
if (bytes_transferred == 0)
continue;
std::vector<char> old_path;
std::vector<WatcherEvent> events;
DWORD offset = 0;
while (true) {
FILE_NOTIFY_INFORMATION* file_info =
reinterpret_cast<FILE_NOTIFY_INFORMATION*>(handle->buffer + offset);
// Emit events for children.
EVENT_TYPE event = EVENT_NONE;
switch (file_info->Action) {
case FILE_ACTION_ADDED:
event = EVENT_CHILD_CREATE;
break;
case FILE_ACTION_REMOVED:
event = EVENT_CHILD_DELETE;
break;
case FILE_ACTION_RENAMED_OLD_NAME:
event = EVENT_CHILD_RENAME;
break;
case FILE_ACTION_RENAMED_NEW_NAME:
event = EVENT_CHILD_RENAME;
break;
case FILE_ACTION_MODIFIED:
event = EVENT_CHILD_CHANGE;
break;
}
if (event != EVENT_NONE) {
// The FileNameLength is in "bytes", but the WideCharToMultiByte
// requires the length to be in "characters"!
int file_name_length_in_characters =
file_info->FileNameLength / sizeof(wchar_t);
char filename[MAX_PATH] = { 0 };
int size = WideCharToMultiByte(CP_UTF8,
0,
file_info->FileName,
file_name_length_in_characters,
filename,
MAX_PATH,
NULL,
NULL);
// Convert file name to file path, same with:
// path = handle->path + '\\' + filename
std::vector<char> path(handle->path.size() + 1 + size);
std::vector<char>::iterator iter = path.begin();
iter = std::copy(handle->path.begin(), handle->path.end(), iter);
*(iter++) = '\\';
std::copy(filename, filename + size, iter);
if (file_info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
// Do not send rename event until the NEW_NAME event, but still keep
// a record of old name.
old_path.swap(path);
} else if (file_info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
WatcherEvent e = { event, handle->overlapped.hEvent };
e.new_path.swap(path);
e.old_path.swap(old_path);
events.push_back(e);
} else {
WatcherEvent e = { event, handle->overlapped.hEvent };
e.new_path.swap(path);
events.push_back(e);
}
}
if (file_info->NextEntryOffset == 0) break;
offset += file_info->NextEntryOffset;
}
// Restart the monitor, it was reset after each call.
QueueReaddirchanges(handle);
locker.Unlock();
for (size_t i = 0; i < events.size(); ++i)
PostEventAndWait(events[i].type,
events[i].handle,
events[i].new_path,
events[i].old_path);
}
}
}
WatcherHandle PlatformWatch(const char* path) {
wchar_t wpath[MAX_PATH] = { 0 };
MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, MAX_PATH);
// Requires a directory, file watching is emulated in js.
DWORD attr = GetFileAttributesW(wpath);
if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY)) {
return INVALID_HANDLE_VALUE;
}
WatcherHandle dir_handle = CreateFileW(wpath,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_DELETE |
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS |
FILE_FLAG_OVERLAPPED,
NULL);
if (!PlatformIsHandleValid(dir_handle)) {
return INVALID_HANDLE_VALUE;
}
std::unique_ptr<HandleWrapper> handle;
{
ScopedLocker locker(g_handle_wrap_map_mutex);
handle.reset(new HandleWrapper(dir_handle, path));
}
if (!QueueReaddirchanges(handle.get())) {
return INVALID_HANDLE_VALUE;
}
// Wake up the thread to add the new event.
SetEvent(g_wake_up_event);
// The pointer is leaked if no error happened.
return handle.release()->overlapped.hEvent;
}
void PlatformUnwatch(WatcherHandle key) {
if (PlatformIsHandleValid(key)) {
HandleWrapper* handle;
{
ScopedLocker locker(g_handle_wrap_map_mutex);
handle = HandleWrapper::Get(key);
handle->Cancel();
}
do {
SetEvent(g_wake_up_event);
} while (WaitForSingleObject(g_file_handles_free_event, 50) == WAIT_TIMEOUT);
delete handle;
}
}
bool PlatformIsHandleValid(WatcherHandle handle) {
return handle != INVALID_HANDLE_VALUE;
}
// We have no errno on Windows.
int PlatformInvalidHandleToErrorNumber(WatcherHandle handle) {
return 0;
}
<commit_msg>Fix Windows build errors for Node.js 12, too.<commit_after>#include <algorithm>
#include <map>
#include <memory>
#include "common.h"
// Size of the buffer to store result of ReadDirectoryChangesW.
static const unsigned int kDirectoryWatcherBufferSize = 4096;
// Object template to create representation of WatcherHandle.
static Nan::Persistent<ObjectTemplate> g_object_template;
// Mutex for the HandleWrapper map.
static uv_mutex_t g_handle_wrap_map_mutex;
// The events to be waited on.
static std::vector<HANDLE> g_events;
// The dummy event to wakeup the thread.
static HANDLE g_wake_up_event;
// The dummy event to ensure we are not waiting on a file handle when destroying it.
static HANDLE g_file_handles_free_event;
struct ScopedLocker {
explicit ScopedLocker(uv_mutex_t& mutex) : mutex_(&mutex) { uv_mutex_lock(mutex_); }
~ScopedLocker() { Unlock(); }
void Unlock() { uv_mutex_unlock(mutex_); }
uv_mutex_t* mutex_;
};
struct HandleWrapper {
HandleWrapper(WatcherHandle handle, const char* path_str)
: dir_handle(handle),
path(strlen(path_str)),
canceled(false) {
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
g_events.push_back(overlapped.hEvent);
std::copy(path_str, path_str + path.size(), path.data());
map_[overlapped.hEvent] = this;
}
~HandleWrapper() {
if (!canceled) {
Cancel();
}
CloseHandle(dir_handle);
CloseHandle(overlapped.hEvent);
}
void Cancel() {
canceled = true;
CancelIoEx(dir_handle, &overlapped);
g_events.erase(std::remove(g_events.begin(), g_events.end(), overlapped.hEvent), g_events.end());
map_.erase(overlapped.hEvent);
}
WatcherHandle dir_handle;
std::vector<char> path;
bool canceled;
OVERLAPPED overlapped;
char buffer[kDirectoryWatcherBufferSize];
static HandleWrapper* Get(HANDLE key) { return map_[key]; }
static std::map<WatcherHandle, HandleWrapper*> map_;
};
std::map<WatcherHandle, HandleWrapper*> HandleWrapper::map_;
struct WatcherEvent {
EVENT_TYPE type;
WatcherHandle handle;
std::vector<char> new_path;
std::vector<char> old_path;
};
static bool QueueReaddirchanges(HandleWrapper* handle) {
return ReadDirectoryChangesW(handle->dir_handle,
handle->buffer,
kDirectoryWatcherBufferSize,
FALSE,
FILE_NOTIFY_CHANGE_FILE_NAME |
FILE_NOTIFY_CHANGE_DIR_NAME |
FILE_NOTIFY_CHANGE_ATTRIBUTES |
FILE_NOTIFY_CHANGE_SIZE |
FILE_NOTIFY_CHANGE_LAST_WRITE |
FILE_NOTIFY_CHANGE_LAST_ACCESS |
FILE_NOTIFY_CHANGE_CREATION |
FILE_NOTIFY_CHANGE_SECURITY,
NULL,
&handle->overlapped,
NULL) == TRUE;
}
Local<Value> WatcherHandleToV8Value(WatcherHandle handle) {
Local<v8::Context> context = Nan::GetCurrentContext();
Local<Value> value = Nan::New(g_object_template)->NewInstance(context).ToLocalChecked();
Nan::SetInternalFieldPointer(value->ToObject(context).ToLocalChecked(), 0, handle);
return value;
}
WatcherHandle V8ValueToWatcherHandle(Local<Value> value) {
return reinterpret_cast<WatcherHandle>(Nan::GetInternalFieldPointer(
value->ToObject(Nan::GetCurrentContext()).ToLocalChecked(), 0));
}
bool IsV8ValueWatcherHandle(Local<Value> value) {
return value->IsObject() &&
value->ToObject(Nan::GetCurrentContext()).ToLocalChecked()->InternalFieldCount() == 1;
}
void PlatformInit() {
uv_mutex_init(&g_handle_wrap_map_mutex);
g_file_handles_free_event = CreateEvent(NULL, TRUE, TRUE, NULL);
g_wake_up_event = CreateEvent(NULL, FALSE, FALSE, NULL);
g_events.push_back(g_wake_up_event);
g_object_template.Reset(Nan::New<ObjectTemplate>());
Nan::New(g_object_template)->SetInternalFieldCount(1);
WakeupNewThread();
}
void PlatformThread() {
while (true) {
// Do not use g_events directly, since reallocation could happen when there
// are new watchers adding to g_events when WaitForMultipleObjects is still
// polling.
ScopedLocker locker(g_handle_wrap_map_mutex);
std::vector<HANDLE> copied_events(g_events);
locker.Unlock();
ResetEvent(g_file_handles_free_event);
DWORD r = WaitForMultipleObjects(copied_events.size(),
copied_events.data(),
FALSE,
INFINITE);
SetEvent(g_file_handles_free_event);
int i = r - WAIT_OBJECT_0;
if (i >= 0 && i < copied_events.size()) {
// It's a wake up event, there is no fs events.
if (copied_events[i] == g_wake_up_event)
continue;
ScopedLocker locker(g_handle_wrap_map_mutex);
HandleWrapper* handle = HandleWrapper::Get(copied_events[i]);
if (!handle || handle->canceled)
continue;
DWORD bytes_transferred;
if (!GetOverlappedResult(handle->dir_handle, &handle->overlapped, &bytes_transferred, FALSE))
continue;
if (bytes_transferred == 0)
continue;
std::vector<char> old_path;
std::vector<WatcherEvent> events;
DWORD offset = 0;
while (true) {
FILE_NOTIFY_INFORMATION* file_info =
reinterpret_cast<FILE_NOTIFY_INFORMATION*>(handle->buffer + offset);
// Emit events for children.
EVENT_TYPE event = EVENT_NONE;
switch (file_info->Action) {
case FILE_ACTION_ADDED:
event = EVENT_CHILD_CREATE;
break;
case FILE_ACTION_REMOVED:
event = EVENT_CHILD_DELETE;
break;
case FILE_ACTION_RENAMED_OLD_NAME:
event = EVENT_CHILD_RENAME;
break;
case FILE_ACTION_RENAMED_NEW_NAME:
event = EVENT_CHILD_RENAME;
break;
case FILE_ACTION_MODIFIED:
event = EVENT_CHILD_CHANGE;
break;
}
if (event != EVENT_NONE) {
// The FileNameLength is in "bytes", but the WideCharToMultiByte
// requires the length to be in "characters"!
int file_name_length_in_characters =
file_info->FileNameLength / sizeof(wchar_t);
char filename[MAX_PATH] = { 0 };
int size = WideCharToMultiByte(CP_UTF8,
0,
file_info->FileName,
file_name_length_in_characters,
filename,
MAX_PATH,
NULL,
NULL);
// Convert file name to file path, same with:
// path = handle->path + '\\' + filename
std::vector<char> path(handle->path.size() + 1 + size);
std::vector<char>::iterator iter = path.begin();
iter = std::copy(handle->path.begin(), handle->path.end(), iter);
*(iter++) = '\\';
std::copy(filename, filename + size, iter);
if (file_info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
// Do not send rename event until the NEW_NAME event, but still keep
// a record of old name.
old_path.swap(path);
} else if (file_info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
WatcherEvent e = { event, handle->overlapped.hEvent };
e.new_path.swap(path);
e.old_path.swap(old_path);
events.push_back(e);
} else {
WatcherEvent e = { event, handle->overlapped.hEvent };
e.new_path.swap(path);
events.push_back(e);
}
}
if (file_info->NextEntryOffset == 0) break;
offset += file_info->NextEntryOffset;
}
// Restart the monitor, it was reset after each call.
QueueReaddirchanges(handle);
locker.Unlock();
for (size_t i = 0; i < events.size(); ++i)
PostEventAndWait(events[i].type,
events[i].handle,
events[i].new_path,
events[i].old_path);
}
}
}
WatcherHandle PlatformWatch(const char* path) {
wchar_t wpath[MAX_PATH] = { 0 };
MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, MAX_PATH);
// Requires a directory, file watching is emulated in js.
DWORD attr = GetFileAttributesW(wpath);
if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY)) {
return INVALID_HANDLE_VALUE;
}
WatcherHandle dir_handle = CreateFileW(wpath,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_DELETE |
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS |
FILE_FLAG_OVERLAPPED,
NULL);
if (!PlatformIsHandleValid(dir_handle)) {
return INVALID_HANDLE_VALUE;
}
std::unique_ptr<HandleWrapper> handle;
{
ScopedLocker locker(g_handle_wrap_map_mutex);
handle.reset(new HandleWrapper(dir_handle, path));
}
if (!QueueReaddirchanges(handle.get())) {
return INVALID_HANDLE_VALUE;
}
// Wake up the thread to add the new event.
SetEvent(g_wake_up_event);
// The pointer is leaked if no error happened.
return handle.release()->overlapped.hEvent;
}
void PlatformUnwatch(WatcherHandle key) {
if (PlatformIsHandleValid(key)) {
HandleWrapper* handle;
{
ScopedLocker locker(g_handle_wrap_map_mutex);
handle = HandleWrapper::Get(key);
handle->Cancel();
}
do {
SetEvent(g_wake_up_event);
} while (WaitForSingleObject(g_file_handles_free_event, 50) == WAIT_TIMEOUT);
delete handle;
}
}
bool PlatformIsHandleValid(WatcherHandle handle) {
return handle != INVALID_HANDLE_VALUE;
}
// We have no errno on Windows.
int PlatformInvalidHandleToErrorNumber(WatcherHandle handle) {
return 0;
}
<|endoftext|>
|
<commit_before>0495d664-2e4d-11e5-9284-b827eb9e62be<commit_msg>049acaf2-2e4d-11e5-9284-b827eb9e62be<commit_after>049acaf2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>#include <algorithm>
#include <map>
#include <memory>
#include "common.h"
// Size of the buffer to store result of ReadDirectoryChangesW.
static const unsigned int kDirectoryWatcherBufferSize = 4096;
// Object template to create representation of WatcherHandle.
static Nan::Persistent<ObjectTemplate> g_object_template;
// Mutex for the HandleWrapper map.
static uv_mutex_t g_handle_wrap_map_mutex;
// The events to be waited on.
static std::vector<HANDLE> g_events;
// The dummy event to wakeup the thread.
static HANDLE g_wake_up_event;
struct ScopedLocker {
explicit ScopedLocker(uv_mutex_t& mutex) : mutex_(&mutex) { uv_mutex_lock(mutex_); }
~ScopedLocker() { Unlock(); }
void Unlock() { uv_mutex_unlock(mutex_); }
uv_mutex_t* mutex_;
};
struct HandleWrapper {
HandleWrapper(WatcherHandle handle, const char* path_str)
: dir_handle(handle),
path(strlen(path_str)),
canceled(false) {
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
g_events.push_back(overlapped.hEvent);
std::copy(path_str, path_str + path.size(), path.data());
map_[overlapped.hEvent] = this;
}
~HandleWrapper() {
CloseFile();
map_.erase(overlapped.hEvent);
CloseHandle(overlapped.hEvent);
g_events.erase(
std::remove(g_events.begin(), g_events.end(), overlapped.hEvent),
g_events.end());
}
void CloseFile() {
if (dir_handle != INVALID_HANDLE_VALUE) {
CloseHandle(dir_handle);
dir_handle = INVALID_HANDLE_VALUE;
}
}
WatcherHandle dir_handle;
std::vector<char> path;
bool canceled;
OVERLAPPED overlapped;
char buffer[kDirectoryWatcherBufferSize];
static HandleWrapper* Get(HANDLE key) { return map_[key]; }
static std::map<WatcherHandle, HandleWrapper*> map_;
};
std::map<WatcherHandle, HandleWrapper*> HandleWrapper::map_;
struct WatcherEvent {
EVENT_TYPE type;
WatcherHandle handle;
std::vector<char> new_path;
std::vector<char> old_path;
};
static bool QueueReaddirchanges(HandleWrapper* handle) {
return ReadDirectoryChangesW(handle->dir_handle,
handle->buffer,
kDirectoryWatcherBufferSize,
FALSE,
FILE_NOTIFY_CHANGE_FILE_NAME |
FILE_NOTIFY_CHANGE_DIR_NAME |
FILE_NOTIFY_CHANGE_ATTRIBUTES |
FILE_NOTIFY_CHANGE_SIZE |
FILE_NOTIFY_CHANGE_LAST_WRITE |
FILE_NOTIFY_CHANGE_LAST_ACCESS |
FILE_NOTIFY_CHANGE_CREATION |
FILE_NOTIFY_CHANGE_SECURITY,
NULL,
&handle->overlapped,
NULL) == TRUE;
}
Local<Value> WatcherHandleToV8Value(WatcherHandle handle) {
Local<Value> value = Nan::New(g_object_template)->NewInstance();
Nan::SetInternalFieldPointer(value->ToObject(), 0, handle);
return value;
}
WatcherHandle V8ValueToWatcherHandle(Local<Value> value) {
return reinterpret_cast<WatcherHandle>(Nan::GetInternalFieldPointer(
value->ToObject(), 0));
}
bool IsV8ValueWatcherHandle(Local<Value> value) {
return value->IsObject() && value->ToObject()->InternalFieldCount() == 1;
}
void PlatformInit() {
uv_mutex_init(&g_handle_wrap_map_mutex);
g_wake_up_event = CreateEvent(NULL, FALSE, FALSE, NULL);
g_events.push_back(g_wake_up_event);
g_object_template.Reset(ObjectTemplate::New());
Nan::New(g_object_template)->SetInternalFieldCount(1);
WakeupNewThread();
}
void PlatformThread() {
while (true) {
// Do not use g_events directly, since reallocation could happen when there
// are new watchers adding to g_events when WaitForMultipleObjects is still
// polling.
ScopedLocker locker(g_handle_wrap_map_mutex);
std::vector<HANDLE> copied_events(g_events);
locker.Unlock();
DWORD r = WaitForMultipleObjects(copied_events.size(),
copied_events.data(),
FALSE,
INFINITE);
int i = r - WAIT_OBJECT_0;
if (i >= 0 && i < copied_events.size()) {
// It's a wake up event, there is no fs events.
if (copied_events[i] == g_wake_up_event)
continue;
ScopedLocker locker(g_handle_wrap_map_mutex);
HandleWrapper* handle = HandleWrapper::Get(copied_events[i]);
if (!handle)
continue;
if (handle->canceled) {
delete handle;
continue;
}
DWORD bytes;
if (GetOverlappedResult(handle->dir_handle,
&handle->overlapped,
&bytes,
FALSE) == FALSE)
continue;
std::vector<char> old_path;
std::vector<WatcherEvent> events;
DWORD offset = 0;
while (true) {
FILE_NOTIFY_INFORMATION* file_info =
reinterpret_cast<FILE_NOTIFY_INFORMATION*>(handle->buffer + offset);
// Emit events for children.
EVENT_TYPE event = EVENT_NONE;
switch (file_info->Action) {
case FILE_ACTION_ADDED:
event = EVENT_CHILD_CREATE;
break;
case FILE_ACTION_REMOVED:
event = EVENT_CHILD_DELETE;
break;
case FILE_ACTION_RENAMED_OLD_NAME:
event = EVENT_CHILD_RENAME;
break;
case FILE_ACTION_RENAMED_NEW_NAME:
event = EVENT_CHILD_RENAME;
break;
case FILE_ACTION_MODIFIED:
event = EVENT_CHILD_CHANGE;
break;
}
if (event != EVENT_NONE) {
// The FileNameLength is in "bytes", but the WideCharToMultiByte
// requires the length to be in "characters"!
int file_name_length_in_characters =
file_info->FileNameLength / sizeof(wchar_t);
char filename[MAX_PATH] = { 0 };
int size = WideCharToMultiByte(CP_UTF8,
0,
file_info->FileName,
file_name_length_in_characters,
filename,
MAX_PATH,
NULL,
NULL);
// Convert file name to file path, same with:
// path = handle->path + '\\' + filename
std::vector<char> path(handle->path.size() + 1 + size);
std::vector<char>::iterator iter = path.begin();
iter = std::copy(handle->path.begin(), handle->path.end(), iter);
*(iter++) = '\\';
std::copy(filename, filename + size, iter);
if (file_info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
// Do not send rename event until the NEW_NAME event, but still keep
// a record of old name.
old_path.swap(path);
} else if (file_info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
WatcherEvent e = { event, handle->overlapped.hEvent };
e.new_path.swap(path);
e.old_path.swap(old_path);
events.push_back(e);
} else {
WatcherEvent e = { event, handle->overlapped.hEvent };
e.new_path.swap(path);
events.push_back(e);
}
}
if (file_info->NextEntryOffset == 0) break;
offset += file_info->NextEntryOffset;
}
// Restart the monitor, it was reset after each call.
QueueReaddirchanges(handle);
locker.Unlock();
for (size_t i = 0; i < events.size(); ++i)
PostEventAndWait(events[i].type,
events[i].handle,
events[i].new_path,
events[i].old_path);
}
}
}
WatcherHandle PlatformWatch(const char* path) {
wchar_t wpath[MAX_PATH] = { 0 };
MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, MAX_PATH);
// Requires a directory, file watching is emulated in js.
DWORD attr = GetFileAttributesW(wpath);
if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY)) {
return INVALID_HANDLE_VALUE;
}
WatcherHandle dir_handle = CreateFileW(wpath,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_DELETE |
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS |
FILE_FLAG_OVERLAPPED,
NULL);
if (!PlatformIsHandleValid(dir_handle)) {
return INVALID_HANDLE_VALUE;
}
std::unique_ptr<HandleWrapper> handle;
{
ScopedLocker locker(g_handle_wrap_map_mutex);
handle.reset(new HandleWrapper(dir_handle, path));
}
if (!QueueReaddirchanges(handle.get())) {
return INVALID_HANDLE_VALUE;
}
// Wake up the thread to add the new event.
SetEvent(g_wake_up_event);
// The pointer is leaked if no error happened.
return handle.release()->overlapped.hEvent;
}
void PlatformUnwatch(WatcherHandle key) {
if (PlatformIsHandleValid(key)) {
ScopedLocker locker(g_handle_wrap_map_mutex);
HandleWrapper* handle = HandleWrapper::Get(key);
handle->canceled = true;
CancelIoEx(handle->dir_handle, &handle->overlapped);
handle->CloseFile();
}
}
bool PlatformIsHandleValid(WatcherHandle handle) {
return handle != INVALID_HANDLE_VALUE;
}
// We have no errno on Windows.
int PlatformInvalidHandleToErrorNumber(WatcherHandle handle) {
return 0;
}
<commit_msg>Fix race condition on Windows<commit_after>#include <algorithm>
#include <map>
#include <memory>
#include "common.h"
// Size of the buffer to store result of ReadDirectoryChangesW.
static const unsigned int kDirectoryWatcherBufferSize = 4096;
// Object template to create representation of WatcherHandle.
static Nan::Persistent<ObjectTemplate> g_object_template;
// Mutex for the HandleWrapper map.
static uv_mutex_t g_handle_wrap_map_mutex;
// The events to be waited on.
static std::vector<HANDLE> g_events;
// The dummy event to wakeup the thread.
static HANDLE g_wake_up_event;
// The dummy event to ensure we are not waiting on a file handle when destroying it.
static HANDLE g_file_handles_free_event;
struct ScopedLocker {
explicit ScopedLocker(uv_mutex_t& mutex) : mutex_(&mutex) { uv_mutex_lock(mutex_); }
~ScopedLocker() { Unlock(); }
void Unlock() { uv_mutex_unlock(mutex_); }
uv_mutex_t* mutex_;
};
struct HandleWrapper {
HandleWrapper(WatcherHandle handle, const char* path_str)
: dir_handle(handle),
path(strlen(path_str)),
canceled(false) {
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
g_events.push_back(overlapped.hEvent);
std::copy(path_str, path_str + path.size(), path.data());
map_[overlapped.hEvent] = this;
}
~HandleWrapper() {
if (!canceled) {
Cancel();
}
CloseHandle(dir_handle);
CloseHandle(overlapped.hEvent);
}
void Cancel() {
canceled = true;
CancelIoEx(dir_handle, &overlapped);
g_events.erase(std::remove(g_events.begin(), g_events.end(), overlapped.hEvent), g_events.end());
map_.erase(overlapped.hEvent);
}
WatcherHandle dir_handle;
std::vector<char> path;
bool canceled;
OVERLAPPED overlapped;
char buffer[kDirectoryWatcherBufferSize];
static HandleWrapper* Get(HANDLE key) { return map_[key]; }
static std::map<WatcherHandle, HandleWrapper*> map_;
};
std::map<WatcherHandle, HandleWrapper*> HandleWrapper::map_;
struct WatcherEvent {
EVENT_TYPE type;
WatcherHandle handle;
std::vector<char> new_path;
std::vector<char> old_path;
};
static bool QueueReaddirchanges(HandleWrapper* handle) {
return ReadDirectoryChangesW(handle->dir_handle,
handle->buffer,
kDirectoryWatcherBufferSize,
FALSE,
FILE_NOTIFY_CHANGE_FILE_NAME |
FILE_NOTIFY_CHANGE_DIR_NAME |
FILE_NOTIFY_CHANGE_ATTRIBUTES |
FILE_NOTIFY_CHANGE_SIZE |
FILE_NOTIFY_CHANGE_LAST_WRITE |
FILE_NOTIFY_CHANGE_LAST_ACCESS |
FILE_NOTIFY_CHANGE_CREATION |
FILE_NOTIFY_CHANGE_SECURITY,
NULL,
&handle->overlapped,
NULL) == TRUE;
}
Local<Value> WatcherHandleToV8Value(WatcherHandle handle) {
Local<Value> value = Nan::New(g_object_template)->NewInstance();
Nan::SetInternalFieldPointer(value->ToObject(), 0, handle);
return value;
}
WatcherHandle V8ValueToWatcherHandle(Local<Value> value) {
return reinterpret_cast<WatcherHandle>(Nan::GetInternalFieldPointer(
value->ToObject(), 0));
}
bool IsV8ValueWatcherHandle(Local<Value> value) {
return value->IsObject() && value->ToObject()->InternalFieldCount() == 1;
}
void PlatformInit() {
uv_mutex_init(&g_handle_wrap_map_mutex);
g_file_handles_free_event = CreateEvent(NULL, TRUE, TRUE, NULL);
g_wake_up_event = CreateEvent(NULL, FALSE, FALSE, NULL);
g_events.push_back(g_wake_up_event);
g_object_template.Reset(ObjectTemplate::New());
Nan::New(g_object_template)->SetInternalFieldCount(1);
WakeupNewThread();
}
void PlatformThread() {
while (true) {
// Do not use g_events directly, since reallocation could happen when there
// are new watchers adding to g_events when WaitForMultipleObjects is still
// polling.
ScopedLocker locker(g_handle_wrap_map_mutex);
std::vector<HANDLE> copied_events(g_events);
locker.Unlock();
ResetEvent(g_file_handles_free_event);
DWORD r = WaitForMultipleObjects(copied_events.size(),
copied_events.data(),
FALSE,
INFINITE);
SetEvent(g_file_handles_free_event);
int i = r - WAIT_OBJECT_0;
if (i >= 0 && i < copied_events.size()) {
// It's a wake up event, there is no fs events.
if (copied_events[i] == g_wake_up_event)
continue;
ScopedLocker locker(g_handle_wrap_map_mutex);
HandleWrapper* handle = HandleWrapper::Get(copied_events[i]);
if (!handle || handle->canceled)
continue;
DWORD bytes;
if (GetOverlappedResult(handle->dir_handle,
&handle->overlapped,
&bytes,
FALSE) == FALSE)
continue;
std::vector<char> old_path;
std::vector<WatcherEvent> events;
DWORD offset = 0;
while (true) {
FILE_NOTIFY_INFORMATION* file_info =
reinterpret_cast<FILE_NOTIFY_INFORMATION*>(handle->buffer + offset);
// Emit events for children.
EVENT_TYPE event = EVENT_NONE;
switch (file_info->Action) {
case FILE_ACTION_ADDED:
event = EVENT_CHILD_CREATE;
break;
case FILE_ACTION_REMOVED:
event = EVENT_CHILD_DELETE;
break;
case FILE_ACTION_RENAMED_OLD_NAME:
event = EVENT_CHILD_RENAME;
break;
case FILE_ACTION_RENAMED_NEW_NAME:
event = EVENT_CHILD_RENAME;
break;
case FILE_ACTION_MODIFIED:
event = EVENT_CHILD_CHANGE;
break;
}
if (event != EVENT_NONE) {
// The FileNameLength is in "bytes", but the WideCharToMultiByte
// requires the length to be in "characters"!
int file_name_length_in_characters =
file_info->FileNameLength / sizeof(wchar_t);
char filename[MAX_PATH] = { 0 };
int size = WideCharToMultiByte(CP_UTF8,
0,
file_info->FileName,
file_name_length_in_characters,
filename,
MAX_PATH,
NULL,
NULL);
// Convert file name to file path, same with:
// path = handle->path + '\\' + filename
std::vector<char> path(handle->path.size() + 1 + size);
std::vector<char>::iterator iter = path.begin();
iter = std::copy(handle->path.begin(), handle->path.end(), iter);
*(iter++) = '\\';
std::copy(filename, filename + size, iter);
if (file_info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
// Do not send rename event until the NEW_NAME event, but still keep
// a record of old name.
old_path.swap(path);
} else if (file_info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
WatcherEvent e = { event, handle->overlapped.hEvent };
e.new_path.swap(path);
e.old_path.swap(old_path);
events.push_back(e);
} else {
WatcherEvent e = { event, handle->overlapped.hEvent };
e.new_path.swap(path);
events.push_back(e);
}
}
if (file_info->NextEntryOffset == 0) break;
offset += file_info->NextEntryOffset;
}
// Restart the monitor, it was reset after each call.
QueueReaddirchanges(handle);
locker.Unlock();
for (size_t i = 0; i < events.size(); ++i)
PostEventAndWait(events[i].type,
events[i].handle,
events[i].new_path,
events[i].old_path);
}
}
}
WatcherHandle PlatformWatch(const char* path) {
wchar_t wpath[MAX_PATH] = { 0 };
MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, MAX_PATH);
// Requires a directory, file watching is emulated in js.
DWORD attr = GetFileAttributesW(wpath);
if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY)) {
return INVALID_HANDLE_VALUE;
}
WatcherHandle dir_handle = CreateFileW(wpath,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_DELETE |
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS |
FILE_FLAG_OVERLAPPED,
NULL);
if (!PlatformIsHandleValid(dir_handle)) {
return INVALID_HANDLE_VALUE;
}
std::unique_ptr<HandleWrapper> handle;
{
ScopedLocker locker(g_handle_wrap_map_mutex);
handle.reset(new HandleWrapper(dir_handle, path));
}
if (!QueueReaddirchanges(handle.get())) {
return INVALID_HANDLE_VALUE;
}
// Wake up the thread to add the new event.
SetEvent(g_wake_up_event);
// The pointer is leaked if no error happened.
return handle.release()->overlapped.hEvent;
}
void PlatformUnwatch(WatcherHandle key) {
if (PlatformIsHandleValid(key)) {
HandleWrapper* handle;
{
ScopedLocker locker(g_handle_wrap_map_mutex);
handle = HandleWrapper::Get(key);
handle->Cancel();
}
do {
SetEvent(g_wake_up_event);
} while (WaitForSingleObject(g_file_handles_free_event, 50) == WAIT_TIMEOUT);
delete handle;
}
}
bool PlatformIsHandleValid(WatcherHandle handle) {
return handle != INVALID_HANDLE_VALUE;
}
// We have no errno on Windows.
int PlatformInvalidHandleToErrorNumber(WatcherHandle handle) {
return 0;
}
<|endoftext|>
|
<commit_before>32e69c9a-2e4f-11e5-9284-b827eb9e62be<commit_msg>32eb9984-2e4f-11e5-9284-b827eb9e62be<commit_after>32eb9984-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>#include "../src/smiles.h"
#include "../src/fileio/molecules.h"
#include "test.h"
using namespace Helium;
void test_parse_smiles()
{
HeMol mol;
hemol_from_smiles("C", mol);
COMPARE(1, num_atoms(mol));
COMPARE(0, num_bonds(mol));
COMPARE(6, get_element(mol, get_atom(mol, 0)));
COMPARE(12, get_mass(mol, get_atom(mol, 0)));
COMPARE(0, get_charge(mol, get_atom(mol, 0)));
COMPARE(4, num_hydrogens(mol, get_atom(mol, 0)));
hemol_from_smiles("N", mol);
COMPARE(1, num_atoms(mol));
COMPARE(0, num_bonds(mol));
COMPARE(7, get_element(mol, get_atom(mol, 0)));
COMPARE(14, get_mass(mol, get_atom(mol, 0)));
COMPARE(0, get_charge(mol, get_atom(mol, 0)));
COMPARE(3, num_hydrogens(mol, get_atom(mol, 0)));
hemol_from_smiles("[13CH4]", mol);
COMPARE(1, num_atoms(mol));
COMPARE(0, num_bonds(mol));
COMPARE(6, get_element(mol, get_atom(mol, 0)));
COMPARE(13, get_mass(mol, get_atom(mol, 0)));
COMPARE(0, get_charge(mol, get_atom(mol, 0)));
COMPARE(4, num_hydrogens(mol, get_atom(mol, 0)));
hemol_from_smiles("[NH4+]", mol);
COMPARE(1, num_atoms(mol));
COMPARE(0, num_bonds(mol));
COMPARE(7, get_element(mol, get_atom(mol, 0)));
COMPARE(14, get_mass(mol, get_atom(mol, 0)));
COMPARE(1, get_charge(mol, get_atom(mol, 0)));
COMPARE(4, num_hydrogens(mol, get_atom(mol, 0)));
hemol_from_smiles("CC", mol);
COMPARE(2, num_atoms(mol));
COMPARE(1, num_bonds(mol));
COMPARE(6, get_element(mol, get_atom(mol, 0)));
COMPARE(6, get_element(mol, get_atom(mol, 1)));
COMPARE(1, get_order(mol, get_bond(mol, 0)));
hemol_from_smiles("C=C", mol);
COMPARE(2, num_atoms(mol));
COMPARE(1, num_bonds(mol));
COMPARE(6, get_element(mol, get_atom(mol, 0)));
COMPARE(6, get_element(mol, get_atom(mol, 1)));
COMPARE(2, get_order(mol, get_bond(mol, 0)));
COMPARE(2, get_bond(mol, 0).order());
hemol_from_smiles("c1ccccc1", mol);
COMPARE(6, mol.numAtoms());
COMPARE(6, mol.numBonds());
}
void test_write_smiles(const std::string &smiles)
{
HeMol mol = hemol_from_smiles(smiles);
COMPARE(smiles, write_smiles(mol));
}
int main()
{
test_parse_smiles();
// simple chain
test_write_smiles("CCCCC");
// branches
test_write_smiles("CCC(CC)CC");
test_write_smiles("CCC(CC)(CC)CC");
test_write_smiles("CCC(CC(CC)CC)CC");
// rings
test_write_smiles("C1CCCC1");
test_write_smiles("C1CCCC1C2CCCC2");
// aromatic
test_write_smiles("n1ccccc1");
test_write_smiles("[13C]");
test_write_smiles("[C+]");
}
<commit_msg>Test reading multi-component smiles (SMILES.SMILES)<commit_after>#include "../src/smiles.h"
#include "../src/fileio/molecules.h"
#include "../src/algorithms/components.h"
#include "test.h"
using namespace Helium;
void test_parse_smiles()
{
HeMol mol;
hemol_from_smiles("C", mol);
COMPARE(1, num_atoms(mol));
COMPARE(0, num_bonds(mol));
COMPARE(6, get_element(mol, get_atom(mol, 0)));
COMPARE(12, get_mass(mol, get_atom(mol, 0)));
COMPARE(0, get_charge(mol, get_atom(mol, 0)));
COMPARE(4, num_hydrogens(mol, get_atom(mol, 0)));
hemol_from_smiles("N", mol);
COMPARE(1, num_atoms(mol));
COMPARE(0, num_bonds(mol));
COMPARE(7, get_element(mol, get_atom(mol, 0)));
COMPARE(14, get_mass(mol, get_atom(mol, 0)));
COMPARE(0, get_charge(mol, get_atom(mol, 0)));
COMPARE(3, num_hydrogens(mol, get_atom(mol, 0)));
hemol_from_smiles("[13CH4]", mol);
COMPARE(1, num_atoms(mol));
COMPARE(0, num_bonds(mol));
COMPARE(6, get_element(mol, get_atom(mol, 0)));
COMPARE(13, get_mass(mol, get_atom(mol, 0)));
COMPARE(0, get_charge(mol, get_atom(mol, 0)));
COMPARE(4, num_hydrogens(mol, get_atom(mol, 0)));
hemol_from_smiles("[NH4+]", mol);
COMPARE(1, num_atoms(mol));
COMPARE(0, num_bonds(mol));
COMPARE(7, get_element(mol, get_atom(mol, 0)));
COMPARE(14, get_mass(mol, get_atom(mol, 0)));
COMPARE(1, get_charge(mol, get_atom(mol, 0)));
COMPARE(4, num_hydrogens(mol, get_atom(mol, 0)));
hemol_from_smiles("CC", mol);
COMPARE(2, num_atoms(mol));
COMPARE(1, num_bonds(mol));
COMPARE(6, get_element(mol, get_atom(mol, 0)));
COMPARE(6, get_element(mol, get_atom(mol, 1)));
COMPARE(1, get_order(mol, get_bond(mol, 0)));
hemol_from_smiles("C=C", mol);
COMPARE(2, num_atoms(mol));
COMPARE(1, num_bonds(mol));
COMPARE(6, get_element(mol, get_atom(mol, 0)));
COMPARE(6, get_element(mol, get_atom(mol, 1)));
COMPARE(2, get_order(mol, get_bond(mol, 0)));
COMPARE(2, get_bond(mol, 0).order());
hemol_from_smiles("c1ccccc1", mol);
COMPARE(6, mol.numAtoms());
COMPARE(6, mol.numBonds());
hemol_from_smiles("CC.CC", mol);
COMPARE(4, mol.numAtoms());
COMPARE(2, mol.numBonds());
COMPARE(2, num_connected_components(mol));
}
void test_write_smiles(const std::string &smiles)
{
HeMol mol = hemol_from_smiles(smiles);
COMPARE(smiles, write_smiles(mol));
}
int main()
{
test_parse_smiles();
// simple chain
test_write_smiles("CCCCC");
// branches
test_write_smiles("CCC(CC)CC");
test_write_smiles("CCC(CC)(CC)CC");
test_write_smiles("CCC(CC(CC)CC)CC");
// rings
test_write_smiles("C1CCCC1");
test_write_smiles("C1CCCC1C2CCCC2");
// aromatic
test_write_smiles("n1ccccc1");
test_write_smiles("[13C]");
test_write_smiles("[C+]");
}
<|endoftext|>
|
<commit_before>38eff640-2e4f-11e5-9284-b827eb9e62be<commit_msg>38f4eace-2e4f-11e5-9284-b827eb9e62be<commit_after>38f4eace-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>4a109648-2e4d-11e5-9284-b827eb9e62be<commit_msg>4a15a66a-2e4d-11e5-9284-b827eb9e62be<commit_after>4a15a66a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>18acd04c-2e4f-11e5-9284-b827eb9e62be<commit_msg>18b1e44c-2e4f-11e5-9284-b827eb9e62be<commit_after>18b1e44c-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c347dbfc-2e4d-11e5-9284-b827eb9e62be<commit_msg>c34ce980-2e4d-11e5-9284-b827eb9e62be<commit_after>c34ce980-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>fce2573e-2e4d-11e5-9284-b827eb9e62be<commit_msg>fce74b36-2e4d-11e5-9284-b827eb9e62be<commit_after>fce74b36-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>9a4ed236-2e4e-11e5-9284-b827eb9e62be<commit_msg>9a53f91e-2e4e-11e5-9284-b827eb9e62be<commit_after>9a53f91e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f18e68ba-2e4c-11e5-9284-b827eb9e62be<commit_msg>f193754e-2e4c-11e5-9284-b827eb9e62be<commit_after>f193754e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>32e1a528-2e4f-11e5-9284-b827eb9e62be<commit_msg>32e69c9a-2e4f-11e5-9284-b827eb9e62be<commit_after>32e69c9a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f8ab93ce-2e4d-11e5-9284-b827eb9e62be<commit_msg>f8b09cac-2e4d-11e5-9284-b827eb9e62be<commit_after>f8b09cac-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>fefbfa7e-2e4e-11e5-9284-b827eb9e62be<commit_msg>ff00f862-2e4e-11e5-9284-b827eb9e62be<commit_after>ff00f862-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>df5e82ae-2e4e-11e5-9284-b827eb9e62be<commit_msg>df6377d2-2e4e-11e5-9284-b827eb9e62be<commit_after>df6377d2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c2593e56-2e4e-11e5-9284-b827eb9e62be<commit_msg>c25e34ce-2e4e-11e5-9284-b827eb9e62be<commit_after>c25e34ce-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1ec7524a-2e4f-11e5-9284-b827eb9e62be<commit_msg>1ecc4b6a-2e4f-11e5-9284-b827eb9e62be<commit_after>1ecc4b6a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3ecfecce-2e4e-11e5-9284-b827eb9e62be<commit_msg>3ed4f4d0-2e4e-11e5-9284-b827eb9e62be<commit_after>3ed4f4d0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>4d651f5c-2e4e-11e5-9284-b827eb9e62be<commit_msg>4d6a2a7e-2e4e-11e5-9284-b827eb9e62be<commit_after>4d6a2a7e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f1bf3ebc-2e4d-11e5-9284-b827eb9e62be<commit_msg>f1c44f92-2e4d-11e5-9284-b827eb9e62be<commit_after>f1c44f92-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>aec729fc-2e4e-11e5-9284-b827eb9e62be<commit_msg>aecc1e1c-2e4e-11e5-9284-b827eb9e62be<commit_after>aecc1e1c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>2ae00ab8-2e4f-11e5-9284-b827eb9e62be<commit_msg>2ae50388-2e4f-11e5-9284-b827eb9e62be<commit_after>2ae50388-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>6176153c-2e4e-11e5-9284-b827eb9e62be<commit_msg>617b2554-2e4e-11e5-9284-b827eb9e62be<commit_after>617b2554-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c0571632-2e4e-11e5-9284-b827eb9e62be<commit_msg>c05c0d2c-2e4e-11e5-9284-b827eb9e62be<commit_after>c05c0d2c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>6db85e0e-2e4e-11e5-9284-b827eb9e62be<commit_msg>6dbd5b8e-2e4e-11e5-9284-b827eb9e62be<commit_after>6dbd5b8e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>2ba6d7c4-2e4f-11e5-9284-b827eb9e62be<commit_msg>2babd15c-2e4f-11e5-9284-b827eb9e62be<commit_after>2babd15c-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>cbce227c-2e4d-11e5-9284-b827eb9e62be<commit_msg>cbd3161a-2e4d-11e5-9284-b827eb9e62be<commit_after>cbd3161a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d666d8f4-2e4e-11e5-9284-b827eb9e62be<commit_msg>d66bcfda-2e4e-11e5-9284-b827eb9e62be<commit_after>d66bcfda-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>64a68b10-2e4e-11e5-9284-b827eb9e62be<commit_msg>64ab9704-2e4e-11e5-9284-b827eb9e62be<commit_after>64ab9704-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>33bc1150-2e4e-11e5-9284-b827eb9e62be<commit_msg>33c10a0c-2e4e-11e5-9284-b827eb9e62be<commit_after>33c10a0c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>9443862a-2e4e-11e5-9284-b827eb9e62be<commit_msg>94488378-2e4e-11e5-9284-b827eb9e62be<commit_after>94488378-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c1cd9dba-2e4e-11e5-9284-b827eb9e62be<commit_msg>c1d29996-2e4e-11e5-9284-b827eb9e62be<commit_after>c1d29996-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>790fa4d8-2e4e-11e5-9284-b827eb9e62be<commit_msg>7914b2a2-2e4e-11e5-9284-b827eb9e62be<commit_after>7914b2a2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>216f64d0-2e4d-11e5-9284-b827eb9e62be<commit_msg>21746552-2e4d-11e5-9284-b827eb9e62be<commit_after>21746552-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>8ea297fc-2e4d-11e5-9284-b827eb9e62be<commit_msg>8ea796e4-2e4d-11e5-9284-b827eb9e62be<commit_after>8ea796e4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0ae9d6fe-2e4e-11e5-9284-b827eb9e62be<commit_msg>0aeecdc6-2e4e-11e5-9284-b827eb9e62be<commit_after>0aeecdc6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>33074280-2e4d-11e5-9284-b827eb9e62be<commit_msg>330c5dd8-2e4d-11e5-9284-b827eb9e62be<commit_after>330c5dd8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b09e3cfe-2e4c-11e5-9284-b827eb9e62be<commit_msg>b0a33010-2e4c-11e5-9284-b827eb9e62be<commit_after>b0a33010-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>9083732a-2e4d-11e5-9284-b827eb9e62be<commit_msg>908865f6-2e4d-11e5-9284-b827eb9e62be<commit_after>908865f6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c8763a88-2e4d-11e5-9284-b827eb9e62be<commit_msg>c87b3506-2e4d-11e5-9284-b827eb9e62be<commit_after>c87b3506-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>86f20988-2e4e-11e5-9284-b827eb9e62be<commit_msg>86f71536-2e4e-11e5-9284-b827eb9e62be<commit_after>86f71536-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>28900b6e-2e4f-11e5-9284-b827eb9e62be<commit_msg>289500ec-2e4f-11e5-9284-b827eb9e62be<commit_after>289500ec-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>316b0d6c-2e4d-11e5-9284-b827eb9e62be<commit_msg>316fffca-2e4d-11e5-9284-b827eb9e62be<commit_after>316fffca-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d1bc3d0a-2e4c-11e5-9284-b827eb9e62be<commit_msg>d1c14516-2e4c-11e5-9284-b827eb9e62be<commit_after>d1c14516-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>a35157ba-2e4d-11e5-9284-b827eb9e62be<commit_msg>a3564f2c-2e4d-11e5-9284-b827eb9e62be<commit_after>a3564f2c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>9b7a88fe-2e4d-11e5-9284-b827eb9e62be<commit_msg>9b7f7eae-2e4d-11e5-9284-b827eb9e62be<commit_after>9b7f7eae-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include <shadow.hpp>
#include <algorithm>
#include <vector>
void
fun1(void)
{
}
// value parameter
void
fun2(int i)
{
}
int
fun3(const int& i)
{
return i * 2;
}
void
fun4(int& i)
{
i *= 2;
}
int
fun5(const int* i)
{
return *i * 2;
}
void
fun6(int* i)
{
*i *= 2;
}
void
fun7(int& i)
{
i *= 2;
}
void
fun7(double& d)
{
d *= 2.0;
}
namespace test_space
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE_END()
REGISTER_FREE_FUNCTION(fun1)
REGISTER_FREE_FUNCTION(fun2)
REGISTER_FREE_FUNCTION(fun3)
REGISTER_FREE_FUNCTION(fun4)
REGISTER_FREE_FUNCTION(fun5)
REGISTER_FREE_FUNCTION(fun6)
REGISTER_FREE_FUNCTION_EXPLICIT(fun7, void, int&)
REGISTER_FREE_FUNCTION_EXPLICIT(fun7, void, double&)
SHADOW_INIT()
}
TEST_CASE("get iterator pair to all available functions",
"[reflection_manager]")
{
auto ff_pair = test_space::manager.free_functions();
SECTION("find fun1")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun1");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun1 through reflection system")
{
auto fun1_refl = *found;
// call with no param overload
auto res = fun1_refl();
// call with regular overload
std::vector<shadow::variable> noargs;
auto res2 = fun1_refl(noargs.begin(), noargs.end());
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(res2.type().name() == std::string("void"));
}
}
SECTION("find fun2")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun2");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun2 through reflection system")
{
auto fun2_refl = *found;
std::vector<shadow::variable> args{
test_space::static_create<int>(23)};
auto res = fun2_refl(args.begin(), args.end());
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<int>(args[0]) == 23);
}
}
SECTION("find fun3")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
using namespace std::string_literals;
return ff.name() == "fun3"s;
});
REQUIRE(found != ff_pair.second);
SECTION("call fun3 through reflection system")
{
auto fun3_refl = *found;
std::vector<shadow::variable> args{
test_space::static_create<int>(10)};
auto res = fun3_refl(args.begin(), args.end());
REQUIRE(res.type().name() == std::string("int"));
REQUIRE(test_space::static_value_cast<int>(res) == 20);
REQUIRE(test_space::static_value_cast<int>(args[0]) == 10);
}
}
SECTION("find fun4")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
using namespace std::string_literals;
return ff.name() == "fun4"s;
});
REQUIRE(found != ff_pair.second);
SECTION("call fun4 through reflection system")
{
auto fun4_refl = *found;
std::vector<shadow::variable> args{
test_space::static_create<int>(10)};
auto res = fun4_refl(args.begin(), args.end());
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<int>(args[0]) == 20);
}
}
SECTION("find fun5")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
using namespace std::string_literals;
return ff.name() == "fun5"s;
});
REQUIRE(found != ff_pair.second);
SECTION("call fun5 through reflection system")
{
auto fun5_refl = *found;
std::vector<shadow::variable> args{
test_space::static_create<int>(10)};
auto res = fun5_refl(args.begin(), args.end());
REQUIRE(res.type().name() == std::string("int"));
REQUIRE(test_space::static_value_cast<int>(res) == 20);
REQUIRE(test_space::static_value_cast<int>(args[0]) == 10);
}
}
SECTION("find fun6")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun6");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun6 through reflection system")
{
auto fun6_refl = *found;
std::vector<shadow::variable> args{
test_space::static_create<int>(10)};
auto res = fun6_refl(args.begin(), args.end());
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<int>(args[0]) == 20);
}
}
SECTION("find fun7 with int& param")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun7") &&
ff.parameter_types().first->name() == std::string("int");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun7(int&) through reflection system")
{
auto fun7_refl = *found;
auto anint = test_space::static_create<int>(200);
auto res = fun7_refl(&anint, &anint + 1);
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<int>(anint) == 400);
}
}
SECTION("find fun7 with double& param")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun7") &&
ff.parameter_types().first->name() ==
std::string("double");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun7(double&) through reflection system")
{
auto fun7_refl = *found;
auto adouble = test_space::static_create<double>(1.5);
auto res = fun7_refl(&adouble, &adouble + 1);
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<double>(adouble) == Approx(3.0));
}
}
}
<commit_msg>Add unit test for overloaded free function taking pointer param. modified: tests/test_free_function_api.cpp<commit_after>#include "catch.hpp"
#include <shadow.hpp>
#include <algorithm>
#include <vector>
void
fun1(void)
{
}
// value parameter
void
fun2(int i)
{
}
int
fun3(const int& i)
{
return i * 2;
}
void
fun4(int& i)
{
i *= 2;
}
int
fun5(const int* i)
{
return *i * 2;
}
void
fun6(int* i)
{
*i *= 2;
}
void
fun7(int& i)
{
i *= 2;
}
void
fun7(double& d)
{
d *= 2.0;
}
void
fun7(char* c)
{
*c += 2;
}
namespace test_space
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE_END()
REGISTER_FREE_FUNCTION(fun1)
REGISTER_FREE_FUNCTION(fun2)
REGISTER_FREE_FUNCTION(fun3)
REGISTER_FREE_FUNCTION(fun4)
REGISTER_FREE_FUNCTION(fun5)
REGISTER_FREE_FUNCTION(fun6)
REGISTER_FREE_FUNCTION_EXPLICIT(fun7, void, int&)
REGISTER_FREE_FUNCTION_EXPLICIT(fun7, void, double&)
REGISTER_FREE_FUNCTION_EXPLICIT(fun7, void, char*)
SHADOW_INIT()
}
TEST_CASE("get iterator pair to all available functions",
"[reflection_manager]")
{
auto ff_pair = test_space::manager.free_functions();
SECTION("find fun1")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun1");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun1 through reflection system")
{
auto fun1_refl = *found;
// call with no param overload
auto res = fun1_refl();
// call with regular overload
std::vector<shadow::variable> noargs;
auto res2 = fun1_refl(noargs.begin(), noargs.end());
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(res2.type().name() == std::string("void"));
}
}
SECTION("find fun2")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun2");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun2 through reflection system")
{
auto fun2_refl = *found;
std::vector<shadow::variable> args{
test_space::static_create<int>(23)};
auto res = fun2_refl(args.begin(), args.end());
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<int>(args[0]) == 23);
}
}
SECTION("find fun3")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
using namespace std::string_literals;
return ff.name() == "fun3"s;
});
REQUIRE(found != ff_pair.second);
SECTION("call fun3 through reflection system")
{
auto fun3_refl = *found;
std::vector<shadow::variable> args{
test_space::static_create<int>(10)};
auto res = fun3_refl(args.begin(), args.end());
REQUIRE(res.type().name() == std::string("int"));
REQUIRE(test_space::static_value_cast<int>(res) == 20);
REQUIRE(test_space::static_value_cast<int>(args[0]) == 10);
}
}
SECTION("find fun4")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
using namespace std::string_literals;
return ff.name() == "fun4"s;
});
REQUIRE(found != ff_pair.second);
SECTION("call fun4 through reflection system")
{
auto fun4_refl = *found;
std::vector<shadow::variable> args{
test_space::static_create<int>(10)};
auto res = fun4_refl(args.begin(), args.end());
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<int>(args[0]) == 20);
}
}
SECTION("find fun5")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
using namespace std::string_literals;
return ff.name() == "fun5"s;
});
REQUIRE(found != ff_pair.second);
SECTION("call fun5 through reflection system")
{
auto fun5_refl = *found;
std::vector<shadow::variable> args{
test_space::static_create<int>(10)};
auto res = fun5_refl(args.begin(), args.end());
REQUIRE(res.type().name() == std::string("int"));
REQUIRE(test_space::static_value_cast<int>(res) == 20);
REQUIRE(test_space::static_value_cast<int>(args[0]) == 10);
}
}
SECTION("find fun6")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun6");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun6 through reflection system")
{
auto fun6_refl = *found;
std::vector<shadow::variable> args{
test_space::static_create<int>(10)};
auto res = fun6_refl(args.begin(), args.end());
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<int>(args[0]) == 20);
}
}
SECTION("find fun7 with int& param")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun7") &&
ff.parameter_types().first->name() == std::string("int");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun7(int&) through reflection system")
{
auto fun7_refl = *found;
auto anint = test_space::static_create<int>(200);
auto res = fun7_refl(&anint, &anint + 1);
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<int>(anint) == 400);
}
}
SECTION("find fun7 with double& param")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun7") &&
ff.parameter_types().first->name() ==
std::string("double");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun7(double&) through reflection system")
{
auto fun7_refl = *found;
auto adouble = test_space::static_create<double>(1.5);
auto res = fun7_refl(&adouble, &adouble + 1);
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<double>(adouble) ==
Approx(3.0));
}
}
SECTION("find fun7 with char* param")
{
auto found =
std::find_if(ff_pair.first, ff_pair.second, [](const auto& ff) {
return ff.name() == std::string("fun7") &&
ff.parameter_types().first->name() ==
std::string("char");
});
REQUIRE(found != ff_pair.second);
SECTION("call fun7(char*) through reflection system")
{
auto fun7_refl = *found;
auto achar = test_space::static_create<char>('a');
auto res = fun7_refl(&achar, &achar + 1);
REQUIRE(res.type().name() == std::string("void"));
REQUIRE(test_space::static_value_cast<char>(achar) == 'c');
}
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, 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.
*/
#if defined(__APPLE__)
#include <pthread.h>
#elif defined(__linux__)
#include <linux/unistd.h>
#include <sys/syscall.h>
#include <unistd.h>
#elif defined(_WIN32)
#include <windows.h>
#endif
#include "phosphor/platform/thread.h"
namespace phosphor {
namespace platform {
THREAD_LOCAL uint64_t thread_id = 0;
uint64_t getCurrentThreadID() {
#if defined(__APPLE__)
return pthread_mach_thread_np(pthread_self());
#elif defined(__linux__)
return syscall(__NR_gettid);
#elif defined(_WIN32)
return GetCurrentThreadId(void);
#else
#error Unsupported platform, no way to get threadid
#endif
}
}
}
<commit_msg>Fix Windows GetCurrentThreadID call<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, 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.
*/
#if defined(__APPLE__)
#include <pthread.h>
#elif defined(__linux__)
#include <linux/unistd.h>
#include <sys/syscall.h>
#include <unistd.h>
#elif defined(_WIN32)
#include <windows.h>
#endif
#include "phosphor/platform/thread.h"
namespace phosphor {
namespace platform {
THREAD_LOCAL uint64_t thread_id = 0;
uint64_t getCurrentThreadID() {
#if defined(__APPLE__)
return pthread_mach_thread_np(pthread_self());
#elif defined(__linux__)
return syscall(__NR_gettid);
#elif defined(_WIN32)
return GetCurrentThreadId();
#else
#error Unsupported platform, no way to get threadid
#endif
}
}
}
<|endoftext|>
|
<commit_before>int total=0; int rejected=0;
Float_t fromPt=1.; Float_t toPt=5.;
namespace RawProduction {
class Output;
}
void CountReject(RawProduction::Output& output, const char* trigger, int cent, const char* pid, const char* methode)
{
TH1* hist = output.GetHistogram(Form("%s/c%03i/%s/%s", trigger, cent, pid, methode));
int fromBin = hist->FindBin(fromPt);
int toBin = hist->FindBin( toPt);
for(int bin = fromBin; bin<=toBin; ++bin) {
++total;
if( 0. == hist->GetBinContent(bin))
++rejected;
}
}
void CountRejected()
{
gROOT->LoadMacro("MakeRawProduction.C+g");
RawProduction::Output output("RawProduction21.root");
gStyle->SetOptStat(0);
TStringToken pids("All Allcore Allwou Disp Disp2 Dispcore Dispwou CPV CPVcore CPV2 Both Bothcore", " ");
while( pids.NextToken() ) {
TStringToken fits("mr1r mr1 mr2r mr2", " ");
while( fits.NextToken() ) {
CountReject(output, "kMB", -1, pids.Data(), fits.Data());
//CountReject(output, "kMB", -11, pids.Data(), fits.Data());
CountReject(output, "kMB", -10, pids.Data(), fits.Data());
//CountReject(output, "kMB", -6, pids.Data(), fits.Data());
CountReject(output, "kCentral", -1, pids.Data(), fits.Data());
//CountReject(output, "kSemiCentral", -11, pids.Data(), fits.Data());
}
}
Printf("fits:%i, rejected:%i", total, rejected);
}
<commit_msg>Minor cleanup of CountRejected.C<commit_after>int total=0; int rejected=0;
Float_t fromPt=1.; Float_t toPt=5.;
namespace RawProduction {
class Output;
}
void CountReject(RawProduction::Output& output, const char* trigger, int cent, const char* pid, const char* methode)
{
TH1* hist = output.GetHistogram(Form("%s/c%03i/%s/%s", trigger, cent, pid, methode));
int fromBin = hist->FindBin(fromPt);
int toBin = hist->FindBin( toPt);
for(int bin = fromBin; bin<=toBin; ++bin) {
++total;
if( 0. == hist->GetBinContent(bin))
++rejected;
}
}
void CountRejected()
{
gROOT->LoadMacro("MakeRawProduction.C+g");
RawProduction::Output output("RawProduction.root");
gStyle->SetOptStat(0);
TStringToken pids("All Allcore Allwou Disp Disp2 Dispcore Dispwou CPV CPVcore CPV2 Both Bothcore", " ");
while( pids.NextToken() ) {
TStringToken fits("mr1r mr1 mr2r mr2", " ");
while( fits.NextToken() ) {
CountReject(output, "kMB", -1, pids.Data(), fits.Data());
//CountReject(output, "kMB", -11, pids.Data(), fits.Data());
CountReject(output, "kMB", -10, pids.Data(), fits.Data());
//CountReject(output, "kMB", -6, pids.Data(), fits.Data());
CountReject(output, "kCentral", -1, pids.Data(), fits.Data());
//CountReject(output, "kSemiCentral", -11, pids.Data(), fits.Data());
}
}
Printf("fits:%i, rejected:%i", total, rejected);
}
<|endoftext|>
|
<commit_before>// BenchmarkRegex.cpp : Defines the entry point for the console application.
//
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <cmath>
#include <cassert>
#include <sstream>
#include <cstdlib>
#include <chrono>
#include <regex>
#include <unordered_map>
#include <map>
#include <thread>
#include <mutex>
#include <memory>
using namespace std;
const int LOOP = 1000000;
const int THREADS = 4;
class timer
{
public:
timer() = default;
void start_timing(const string& text_)
{
text = text_;
begin = chrono::high_resolution_clock::now();
}
void stop_timing()
{
auto end = chrono::high_resolution_clock::now();
auto dur = end - begin;
auto ms = chrono::duration_cast<chrono::milliseconds>(dur).count();
cout << setw(35) << text << ":" << setw(5) << ms << "ms" << endl;
}
private:
string text;
chrono::steady_clock::time_point begin;
};
#ifdef WIN32
#pragma optimize("", off)
template <class T>
void do_not_optimize_away(T* datum) {
datum = datum;
}
#pragma optimize("", on)
#else
static void do_not_optimize_away(void* p) {
asm volatile("" : : "g"(p) : "memory");
}
#endif
struct singleton
{
public:
typedef unordered_map<thread::id, unique_ptr<regex> > MapType;
static void init(const string& reg_exp) { s_reg_exp = reg_exp; }
static const regex& get()
{
lock_guard<mutex> lock(s_mutex);
thread::id thread_id = this_thread::get_id();
MapType::iterator it = s_map.find(thread_id);
if (it == s_map.end())
{
prevent_false_sharing(1000);
s_map[thread_id] = unique_ptr<regex>(new regex(s_reg_exp));
return *s_map[thread_id];
}
return *(it->second);
}
private:
static void prevent_false_sharing(size_t size)
{
unique_ptr<char[]> p = unique_ptr<char[]>(new char[size]);
s_vec_temp_alloc.push_back(move(p));
}
static MapType s_map;
static string s_reg_exp;
static mutex s_mutex;
static vector< unique_ptr<char[]> > s_vec_temp_alloc;
};
singleton::MapType singleton::s_map;
string singleton::s_reg_exp;
mutex singleton::s_mutex;
vector< unique_ptr<char[]> > singleton::s_vec_temp_alloc;
struct factory
{
public:
static unique_ptr<regex> get(const string& reg_exp)
{
lock_guard<mutex> lock(s_mutex);
prevent_false_sharing(1000);
return unique_ptr<regex>(new regex(reg_exp));
}
private:
static void prevent_false_sharing(size_t size)
{
unique_ptr<char[]> p = unique_ptr<char[]>(new char[size]);
s_vec_temp_alloc.push_back(move(p));
}
static mutex s_mutex;
static vector< unique_ptr<char[]> > s_vec_temp_alloc;
};
mutex factory::s_mutex;
vector< unique_ptr<char[]> > factory::s_vec_temp_alloc;
const string local_match(const string& text);
const string static_match(const string& text); // not reentrant-safe
const string singleton_match(const string& text);
const string factory_match(const string& text, const regex& regex);
void parallel_invoke(const int size, const int threads, function<void(int, int)> func)
{
typedef unique_ptr<thread> PtrType;
vector< PtrType > vec;
int each = size / threads;
for (int i = 0; i < threads; ++i)
{
if (i == threads - 1) // last thread
{
vec.emplace_back(PtrType(new thread(func, each*i, each*(i + 1) + (size % threads) - 1)));
}
else
{
vec.emplace_back(PtrType(new thread(func, each*i, each*(i + 1) - 1 )));
}
}
for (size_t i = 0; i < vec.size(); ++i)
{
vec[i]->join();
}
}
const string REG_EXP = ".*PRICE:.*US\\$(\\d+\\.\\d+|[-+]*\\d+).*PER SHARE";
int main(int argc, char* argv[])
{
string str1 = "Zoomer PRICE: US$1.23 PER SHARE";
string str2 = "Boomer PRICE: US$4.56 PER SHARE";
vector<string> vec;
vec.push_back(str1);
vec.push_back(str2);
timer stopwatch;
stopwatch.start_timing("local regex object");
for(int j = 0; j < LOOP; ++j)
{
for(size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(local_match(vec[i]).c_str());
}
}
stopwatch.stop_timing();
stopwatch.start_timing("static regex object");
for(int j = 0; j < LOOP; ++j)
{
for(size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(static_match(vec[i]).c_str());
}
}
stopwatch.stop_timing();
singleton::init(REG_EXP);
stopwatch.start_timing("singleton regex object");
for (int j = 0; j < LOOP; ++j)
{
for (size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(singleton_match(vec[i]).c_str());
}
}
stopwatch.stop_timing();
ostringstream os;
os << "local regex object(" << THREADS << " threads)";
stopwatch.start_timing(os.str());
parallel_invoke(LOOP, THREADS, [&vec](int start, int end) {
for (int j = start; j < end; ++j)
{
for (size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(local_match(vec[i]).c_str());
}
}
});
stopwatch.stop_timing();
os.clear();
os.str("");
os << "singleton regex object(" << THREADS << " threads)";
stopwatch.start_timing(os.str());
parallel_invoke(LOOP, THREADS, [&vec] (int start, int end) {
for (int j = start; j < end; ++j)
{
for (size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(singleton_match(vec[i]).c_str());
}
}
});
stopwatch.stop_timing();
os.clear();
os.str("");
os << "factory regex object(" << THREADS << " threads)";
stopwatch.start_timing(os.str());
parallel_invoke(LOOP, THREADS, [&vec](int start, int end) {
unique_ptr<regex> ptr = factory::get(REG_EXP);
const regex& regex = *ptr;
for (int j = start; j < end; ++j)
{
for (size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(factory_match(vec[i], regex).c_str());
}
}
});
stopwatch.stop_timing();
/*
cout << local_match(str1) << endl;
cout << local_match(str2) << endl;
cout << static_match(str1) << endl;
cout << static_match(str2) << endl;
singleton::init(REG_EXP);
cout << singleton_match(str1) << endl;
cout << singleton_match(str2) << endl;
const regex regex(REG_EXP);
cout << factory_match(str1, regex) << endl;
cout << factory_match(str2, regex) << endl;
*/
return 0;
}
const string local_match(const string& text)
{
string price = "";
smatch what;
const regex regex(REG_EXP);
if (regex_match(text, what, regex))
{
price = what[1];
}
return price;
}
const string static_match(const string& text) // not reentrant-safe
{
string price = "";
smatch what;
static const regex regex(REG_EXP);
if (regex_match(text, what, regex))
{
price = what[1];
}
return price;
}
const string singleton_match(const string& text)
{
string price = "";
smatch what;
const regex& regex = singleton::get();
if (regex_match(text, what, regex))
{
price = what[1];
}
return price;
}
const string factory_match(const string& text, const regex& regex)
{
string price = "";
smatch what;
if (regex_match(text, what, regex))
{
price = what[1];
}
return price;
}
<commit_msg>Add thread_local benchmark<commit_after>// BenchmarkRegex.cpp : Defines the entry point for the console application.
//
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <cmath>
#include <cassert>
#include <sstream>
#include <cstdlib>
#include <chrono>
#include <regex>
#include <unordered_map>
#include <map>
#include <thread>
#include <mutex>
#include <memory>
using namespace std;
const int LOOP = 1000000;
const int THREADS = 4;
class timer
{
public:
timer() = default;
void start_timing(const string& text_)
{
text = text_;
begin = chrono::high_resolution_clock::now();
}
void stop_timing()
{
auto end = chrono::high_resolution_clock::now();
auto dur = end - begin;
auto ms = chrono::duration_cast<chrono::milliseconds>(dur).count();
cout << setw(38) << text << ":" << setw(5) << ms << "ms" << endl;
}
private:
string text;
chrono::steady_clock::time_point begin;
};
#ifdef WIN32
#pragma optimize("", off)
template <class T>
void do_not_optimize_away(T* datum) {
datum = datum;
}
#pragma optimize("", on)
#else
static void do_not_optimize_away(void* p) {
asm volatile("" : : "g"(p) : "memory");
}
#endif
struct singleton
{
public:
typedef unordered_map<thread::id, unique_ptr<regex> > MapType;
static void init(const string& reg_exp) { s_reg_exp = reg_exp; }
static const regex& get()
{
lock_guard<mutex> lock(s_mutex);
thread::id thread_id = this_thread::get_id();
MapType::iterator it = s_map.find(thread_id);
if (it == s_map.end())
{
prevent_false_sharing(1000);
s_map[thread_id] = unique_ptr<regex>(new regex(s_reg_exp));
return *s_map[thread_id];
}
return *(it->second);
}
private:
static void prevent_false_sharing(size_t size)
{
unique_ptr<char[]> p = unique_ptr<char[]>(new char[size]);
s_vec_temp_alloc.push_back(move(p));
}
static MapType s_map;
static string s_reg_exp;
static mutex s_mutex;
static vector< unique_ptr<char[]> > s_vec_temp_alloc;
};
singleton::MapType singleton::s_map;
string singleton::s_reg_exp;
mutex singleton::s_mutex;
vector< unique_ptr<char[]> > singleton::s_vec_temp_alloc;
struct factory
{
public:
static unique_ptr<regex> get(const string& reg_exp)
{
lock_guard<mutex> lock(s_mutex);
prevent_false_sharing(1000);
return unique_ptr<regex>(new regex(reg_exp));
}
private:
static void prevent_false_sharing(size_t size)
{
unique_ptr<char[]> p = unique_ptr<char[]>(new char[size]);
s_vec_temp_alloc.push_back(move(p));
}
static mutex s_mutex;
static vector< unique_ptr<char[]> > s_vec_temp_alloc;
};
mutex factory::s_mutex;
vector< unique_ptr<char[]> > factory::s_vec_temp_alloc;
const string local_match(const string& text);
const string static_match(const string& text); // not reentrant-safe
const string thread_local_match(const string& text); // not reentrant-safe
const string singleton_match(const string& text);
const string factory_match(const string& text, const regex& regex);
void parallel_invoke(const int size, const int threads, function<void(int, int)> func)
{
typedef unique_ptr<thread> PtrType;
vector< PtrType > vec;
int each = size / threads;
for (int i = 0; i < threads; ++i)
{
if (i == threads - 1) // last thread
{
vec.emplace_back(PtrType(new thread(func, each*i, each*(i + 1) + (size % threads) - 1)));
}
else
{
vec.emplace_back(PtrType(new thread(func, each*i, each*(i + 1) - 1 )));
}
}
for (size_t i = 0; i < vec.size(); ++i)
{
vec[i]->join();
}
}
const string REG_EXP = ".*PRICE:.*US\\$(\\d+\\.\\d+|[-+]*\\d+).*PER SHARE";
#include <utility>
int main(int argc, char* argv[])
{
int a = 1, b = 2;
std::swap(a, b);
string str1 = "Zoomer PRICE: US$1.23 PER SHARE";
string str2 = "Boomer PRICE: US$4.56 PER SHARE";
vector<string> vec;
vec.push_back(str1);
vec.push_back(str2);
timer stopwatch;
stopwatch.start_timing("local regex object");
for(int j = 0; j < LOOP; ++j)
{
for(size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(local_match(vec[i]).c_str());
}
}
stopwatch.stop_timing();
stopwatch.start_timing("static regex object");
for(int j = 0; j < LOOP; ++j)
{
for(size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(static_match(vec[i]).c_str());
}
}
stopwatch.stop_timing();
singleton::init(REG_EXP);
stopwatch.start_timing("singleton regex object");
for (int j = 0; j < LOOP; ++j)
{
for (size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(singleton_match(vec[i]).c_str());
}
}
stopwatch.stop_timing();
singleton::init(REG_EXP);
stopwatch.start_timing("thread_local regex object");
for (int j = 0; j < LOOP; ++j)
{
for (size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(thread_local_match(vec[i]).c_str());
}
}
stopwatch.stop_timing();
ostringstream os;
os << "local regex object(" << THREADS << " threads)";
stopwatch.start_timing(os.str());
parallel_invoke(LOOP, THREADS, [&vec](int start, int end) {
for (int j = start; j < end; ++j)
{
for (size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(local_match(vec[i]).c_str());
}
}
});
stopwatch.stop_timing();
os.clear();
os.str("");
os << "singleton regex object(" << THREADS << " threads)";
stopwatch.start_timing(os.str());
parallel_invoke(LOOP, THREADS, [&vec] (int start, int end) {
for (int j = start; j < end; ++j)
{
for (size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(singleton_match(vec[i]).c_str());
}
}
});
stopwatch.stop_timing();
os.clear();
os.str("");
os << "factory regex object(" << THREADS << " threads)";
stopwatch.start_timing(os.str());
parallel_invoke(LOOP, THREADS, [&vec](int start, int end) {
unique_ptr<regex> ptr = factory::get(REG_EXP);
const regex& regex = *ptr;
for (int j = start; j < end; ++j)
{
for (size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(factory_match(vec[i], regex).c_str());
}
}
});
stopwatch.stop_timing();
os.clear();
os.str("");
os << "thread_local regex object(" << THREADS << " threads)";
stopwatch.start_timing(os.str());
parallel_invoke(LOOP, THREADS, [&vec](int start, int end) {
unique_ptr<regex> ptr = factory::get(REG_EXP);
const regex& regex = *ptr;
for (int j = start; j < end; ++j)
{
for (size_t i = 0; i < vec.size(); ++i)
{
do_not_optimize_away(thread_local_match(vec[i]).c_str());
}
}
});
stopwatch.stop_timing();
/*
cout << local_match(str1) << endl;
cout << local_match(str2) << endl;
cout << static_match(str1) << endl;
cout << static_match(str2) << endl;
singleton::init(REG_EXP);
cout << singleton_match(str1) << endl;
cout << singleton_match(str2) << endl;
const regex regex(REG_EXP);
cout << factory_match(str1, regex) << endl;
cout << factory_match(str2, regex) << endl;
cout << thread_local_match(str1) << endl;
cout << thread_local_match(str2) << endl;
*/
return 0;
}
const string local_match(const string& text)
{
string price = "";
smatch what;
const regex regex(REG_EXP);
if (regex_match(text, what, regex))
{
price = what[1];
}
return price;
}
const string static_match(const string& text) // not reentrant-safe
{
string price = "";
smatch what;
static const regex regex(REG_EXP);
if (regex_match(text, what, regex))
{
price = what[1];
}
return price;
}
const string thread_local_match(const string& text) // not reentrant-safe
{
string price = "";
smatch what;
static thread_local const regex regex(REG_EXP);
if (regex_match(text, what, regex))
{
price = what[1];
}
return price;
}
const string singleton_match(const string& text)
{
string price = "";
smatch what;
const regex& regex = singleton::get();
if (regex_match(text, what, regex))
{
price = what[1];
}
return price;
}
const string factory_match(const string& text, const regex& regex)
{
string price = "";
smatch what;
if (regex_match(text, what, regex))
{
price = what[1];
}
return price;
}
<|endoftext|>
|
<commit_before>#include <ma.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <apfMDS.h>
#include <PCU.h>
int main(int argc, char** argv)
{
assert(argc==4);
MPI_Init(&argc,&argv);
PCU_Comm_Init();
gmi_register_mesh();
ma::Mesh* m = apf::loadMdsMesh(argv[1],argv[2]);
ma::runUniformRefinement(m);
m->writeNative(argv[3]);
m->destroyNative();
apf::destroyMesh(m);
PCU_Comm_Free();
MPI_Finalize();
}
<commit_msg>uniform exe doesn't snap or fix shape now<commit_after>#include <ma.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <apfMDS.h>
#include <PCU.h>
int main(int argc, char** argv)
{
assert(argc==4);
MPI_Init(&argc,&argv);
PCU_Comm_Init();
gmi_register_mesh();
ma::Mesh* m = apf::loadMdsMesh(argv[1],argv[2]);
ma::Input* in = ma::configureUniformRefine(m, 1);
if (in->shouldSnap) {
in->shouldSnap = false;
assert(in->shouldTransferParametric);
}
in->shouldFixShape = false;
ma::adapt(in);
m->writeNative(argv[3]);
m->destroyNative();
apf::destroyMesh(m);
PCU_Comm_Free();
MPI_Finalize();
}
<|endoftext|>
|
<commit_before>#ifndef COMMANDITERATIONUPDATE_CPP_
#define COMMANDITERATIONUPDATE_CPP_
#include "itkCommand.h"
// Class to handle blah blah blah
using namespace std;
template<typename OptimizerType>
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {}
public:
typedef const OptimizerType* OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject & event)
{
// in this case, just calls the const version of Execute
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object );
if( ! itk::IterationEvent().CheckEvent( &event ) )
{
return;
}
cout << optimizer->GetCurrentIteration() << " = ";
cout << optimizer->GetValue() << " : ";
cout << optimizer->GetCurrentPosition() << endl;
}
};
#endif<commit_msg>Changed tab spacing in CommandIterationUpdate.hpp<commit_after>#ifndef COMMANDITERATIONUPDATE_CPP_
#define COMMANDITERATIONUPDATE_CPP_
#include "itkCommand.h"
// Class to handle blah blah blah
using namespace std;
template<typename OptimizerType>
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {}
public:
typedef const OptimizerType* OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject & event)
{
// in this case, just calls the const version of Execute
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object );
if( ! itk::IterationEvent().CheckEvent( &event ) )
{
return;
}
cout << optimizer->GetCurrentIteration() << " = ";
cout << optimizer->GetValue() << " : ";
cout << optimizer->GetCurrentPosition() << endl;
}
};
#endif<|endoftext|>
|
<commit_before>// Register two LoRes slices to each other
#include "boost/filesystem.hpp"
// my files
#include "Stack.hpp"
#include "StackInitializers.hpp"
#include "RegistrationBuilder.hpp"
#include "StackAligner.hpp"
#include "StackIOHelpers.hpp"
#include "IOHelpers.hpp"
#include "StackTransforms.hpp"
#include "Dirs.hpp"
#include "Parameters.hpp"
#include "Profiling.hpp"
void checkUsage(int argc, char const *argv[]) {
if( argc < 4 )
{
cerr << "\nUsage: " << endl;
cerr << argv[0] << " dataSet slice1 slice2 (writeVolumes=false)\n\n";
cerr << "e.g. " << argv[0] << " Rat28 0053 0054 true\n\n";
exit(EXIT_FAILURE);
}
}
int main(int argc, char const *argv[]) {
using namespace boost::filesystem;
// Verify the number of parameters in the command line
checkUsage(argc, argv);
// Process command line arguments
Dirs::SetDataSet(argv[1]);
string slice1BaseName(argv[2]);
string slice2BaseName(argv[3]);
Dirs::SetOutputDirName("LoResCorrectionTransforms");
vector< string > slice1FileName, slice2FileName;
string blockDir(Dirs::ImagesDir() + "LoRes_rgb/downsamples_1/");
slice1FileName.push_back(Dirs::BlockDir() + slice1BaseName + ".bmp");
slice2FileName.push_back(Dirs::BlockDir() + slice2BaseName + ".bmp");
// initialise stack objects with correct spacings, sizes etc
typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;
StackType::SliceVectorType slice1Image = readImages< StackType >(slice1FileName);
StackType::SliceVectorType slice2Image = readImages< StackType >(slice2FileName);
boost::shared_ptr< StackType > slice1Stack = InitializeLoResStack<StackType>(slice1Image);
boost::shared_ptr< StackType > slice2Stack = InitializeLoResStack<StackType>(slice2Image);
// initialize stacks' transforms
StackTransforms::InitializeWithTranslation( *slice1Stack, StackTransforms::GetLoResTranslation("whole_heart") );
StackTransforms::InitializeWithTranslation( *slice2Stack, StackTransforms::GetLoResTranslation("whole_heart") );
// create output dir before write operations
create_directory( Dirs::ResultsDir() );
// Build LoRes slices
slice1Stack->updateVolumes();
slice2Stack->updateVolumes();
if(argc >= 5)
{
writeImage< StackType::SliceType >( slice1Stack->GetResampledSlice(0), Dirs::ResultsDir() + slice1BaseName + ".mha" );
writeImage< StackType::SliceType >( slice2Stack->GetResampledSlice(0), Dirs::ResultsDir() + slice2BaseName + "_before_registration.mha" );
writeImage< StackType::SliceType >( slice1Stack->GetOriginalImage(0), Dirs::ResultsDir() + slice1BaseName + "_original.mha" );
writeImage< StackType::SliceType >( slice2Stack->GetOriginalImage(0), Dirs::ResultsDir() + slice2BaseName + "_original.mha" );
}
// initialise registration framework
boost::shared_ptr<YAML::Node> pParameters = config("2_slice_parameters.yml");
typedef RegistrationBuilder< StackType > RegistrationBuilderType;
RegistrationBuilderType registrationBuilder(*pParameters);
RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();
// Could change this to register against original fixed image and fixed image masks,
// by applying the inverse fixed transform to the moving one, registering, then
// applying the fixed transform back again afterwards.
registration->SetFixedImage( slice1Stack->GetResampledSlice(0) );
registration->SetMovingImage( slice2Stack->GetOriginalImage(0) );
registration->GetMetric()->SetFixedImageMask( slice1Stack->GetResampled2DMask(0) );
registration->GetMetric()->SetMovingImageMask( slice2Stack->GetOriginal2DMask(0) );
registration->SetTransform( slice2Stack->GetTransform(0) );
registration->SetInitialTransformParameters( slice2Stack->GetTransform(0)->GetParameters() );
try { registration->Update(); }
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
cout << "Optimizer stop condition: "
<< registration->GetOptimizer()->GetStopConditionDescription() << endl << endl;
// write registered image
slice2Stack->updateVolumes();
if(argc >= 5)
{
writeImage< StackType::SliceType >( slice2Stack->GetResampledSlice(0), Dirs::ResultsDir() + slice2BaseName + "_after_registration.mha" );
}
// Write resultant transform
// subtract initial translation, so that
// transform represents the relative translation from one slice to another
StackTransforms::Translate(*slice2Stack, -StackTransforms::GetLoResTranslation("whole_heart"));
vector< string > transformFileName(1, slice1BaseName + "_" + slice2BaseName);
Save(*slice2Stack, transformFileName, Dirs::ResultsDir());
return EXIT_SUCCESS;
}
<commit_msg>Removed debugging output from Register2Slices.<commit_after>// Register two LoRes slices to each other
#include "boost/filesystem.hpp"
// my files
#include "Stack.hpp"
#include "StackInitializers.hpp"
#include "RegistrationBuilder.hpp"
#include "StackAligner.hpp"
#include "StackIOHelpers.hpp"
#include "IOHelpers.hpp"
#include "StackTransforms.hpp"
#include "Dirs.hpp"
#include "Parameters.hpp"
#include "Profiling.hpp"
void checkUsage(int argc, char const *argv[]) {
if( argc < 4 )
{
cerr << "\nUsage: " << endl;
cerr << argv[0] << " dataSet slice1 slice2 (writeVolumes=false)\n\n";
cerr << "e.g. " << argv[0] << " Rat28 0053 0054 true\n\n";
exit(EXIT_FAILURE);
}
}
int main(int argc, char const *argv[]) {
using namespace boost::filesystem;
// Verify the number of parameters in the command line
checkUsage(argc, argv);
// Process command line arguments
Dirs::SetDataSet(argv[1]);
string slice1BaseName(argv[2]);
string slice2BaseName(argv[3]);
Dirs::SetOutputDirName("LoResCorrectionTransforms");
vector< string > slice1FileName, slice2FileName;
string blockDir(Dirs::ImagesDir() + "LoRes_rgb/downsamples_1/");
slice1FileName.push_back(Dirs::BlockDir() + slice1BaseName + ".bmp");
slice2FileName.push_back(Dirs::BlockDir() + slice2BaseName + ".bmp");
// initialise stack objects with correct spacings, sizes etc
typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;
StackType::SliceVectorType slice1Image = readImages< StackType >(slice1FileName);
StackType::SliceVectorType slice2Image = readImages< StackType >(slice2FileName);
boost::shared_ptr< StackType > slice1Stack = InitializeLoResStack<StackType>(slice1Image);
boost::shared_ptr< StackType > slice2Stack = InitializeLoResStack<StackType>(slice2Image);
// initialize stacks' transforms
StackTransforms::InitializeWithTranslation( *slice1Stack, StackTransforms::GetLoResTranslation("whole_heart") );
StackTransforms::InitializeWithTranslation( *slice2Stack, StackTransforms::GetLoResTranslation("whole_heart") );
// create output dir before write operations
create_directory( Dirs::ResultsDir() );
// Build LoRes slices
slice1Stack->updateVolumes();
slice2Stack->updateVolumes();
if(argc >= 5)
{
writeImage< StackType::SliceType >( slice1Stack->GetResampledSlice(0), Dirs::ResultsDir() + slice1BaseName + ".mha" );
writeImage< StackType::SliceType >( slice2Stack->GetResampledSlice(0), Dirs::ResultsDir() + slice2BaseName + "_before_registration.mha" );
}
// initialise registration framework
boost::shared_ptr<YAML::Node> pParameters = config("2_slice_parameters.yml");
typedef RegistrationBuilder< StackType > RegistrationBuilderType;
RegistrationBuilderType registrationBuilder(*pParameters);
RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();
// Could change this to register against original fixed image and fixed image masks,
// by applying the inverse fixed transform to the moving one, registering, then
// applying the fixed transform back again afterwards.
registration->SetFixedImage( slice1Stack->GetResampledSlice(0) );
registration->SetMovingImage( slice2Stack->GetOriginalImage(0) );
registration->GetMetric()->SetFixedImageMask( slice1Stack->GetResampled2DMask(0) );
registration->GetMetric()->SetMovingImageMask( slice2Stack->GetOriginal2DMask(0) );
registration->SetTransform( slice2Stack->GetTransform(0) );
registration->SetInitialTransformParameters( slice2Stack->GetTransform(0)->GetParameters() );
try { registration->Update(); }
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
cout << "Optimizer stop condition: "
<< registration->GetOptimizer()->GetStopConditionDescription() << endl << endl;
// write registered image
slice2Stack->updateVolumes();
if(argc >= 5)
{
writeImage< StackType::SliceType >( slice2Stack->GetResampledSlice(0), Dirs::ResultsDir() + slice2BaseName + "_after_registration.mha" );
}
// Write resultant transform
// subtract initial translation, so that
// transform represents the relative translation from one slice to another
StackTransforms::Translate(*slice2Stack, -StackTransforms::GetLoResTranslation("whole_heart"));
vector< string > transformFileName(1, slice1BaseName + "_" + slice2BaseName);
Save(*slice2Stack, transformFileName, Dirs::ResultsDir());
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Flutter 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 "flutter/flow/layers/transform_layer.h"
namespace flutter {
TransformLayer::TransformLayer(const SkMatrix& transform)
: transform_(transform) {
// Checks (in some degree) that SkMatrix transform_ is valid and initialized.
//
// If transform_ is uninitialized, this assert may look flaky as it doesn't
// fail all the time, and some rerun may make it pass. But don't ignore it and
// just rerun the test if this is triggered, since even a flaky failure here
// may signify a potentially big problem in the code.
//
// We have to write this flaky test because there is no reliable way to test
// whether a variable is initialized or not in C++.
FML_CHECK(transform_.isFinite());
}
TransformLayer::~TransformLayer() = default;
void TransformLayer::Preroll(PrerollContext* context, const SkMatrix& matrix) {
SkMatrix child_matrix;
child_matrix.setConcat(matrix, transform_);
SkRect previous_cull_rect = context->cull_rect;
SkMatrix inverse_transform_;
// Perspective projections don't produce rectangles that are useful for
// culling for some reason.
if (!transform_.hasPerspective() && transform_.invert(&inverse_transform_)) {
inverse_transform_.mapRect(&context->cull_rect);
} else {
context->cull_rect = kGiantRect;
}
SkRect child_paint_bounds = SkRect::MakeEmpty();
PrerollChildren(context, child_matrix, &child_paint_bounds);
transform_.mapRect(&child_paint_bounds);
set_paint_bounds(child_paint_bounds);
context->cull_rect = previous_cull_rect;
}
#if defined(OS_FUCHSIA)
void TransformLayer::UpdateScene(SceneUpdateContext& context) {
FML_DCHECK(needs_system_composite());
SceneUpdateContext::Transform transform(context, transform_);
UpdateSceneChildren(context);
}
#endif // defined(OS_FUCHSIA)
void TransformLayer::Paint(PaintContext& context) const {
TRACE_EVENT0("flutter", "TransformLayer::Paint");
FML_DCHECK(needs_painting());
SkAutoCanvasRestore save(context.internal_nodes_canvas, true);
context.internal_nodes_canvas->concat(transform_);
PaintChildren(context);
}
} // namespace flutter
<commit_msg>Set identity instead of crash in opt build (#9262)<commit_after>// Copyright 2013 The Flutter 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 "flutter/flow/layers/transform_layer.h"
namespace flutter {
TransformLayer::TransformLayer(const SkMatrix& transform)
: transform_(transform) {
// Checks (in some degree) that SkMatrix transform_ is valid and initialized.
//
// If transform_ is uninitialized, this assert may look flaky as it doesn't
// fail all the time, and some rerun may make it pass. But don't ignore it and
// just rerun the test if this is triggered, since even a flaky failure here
// may signify a potentially big problem in the code.
//
// We have to write this flaky test because there is no reliable way to test
// whether a variable is initialized or not in C++.
FML_DCHECK(transform_.isFinite());
if (!transform_.isFinite()) {
FML_LOG(ERROR) << "TransformLayer is constructed with an invalid matrix.";
transform_.setIdentity();
}
}
TransformLayer::~TransformLayer() = default;
void TransformLayer::Preroll(PrerollContext* context, const SkMatrix& matrix) {
SkMatrix child_matrix;
child_matrix.setConcat(matrix, transform_);
SkRect previous_cull_rect = context->cull_rect;
SkMatrix inverse_transform_;
// Perspective projections don't produce rectangles that are useful for
// culling for some reason.
if (!transform_.hasPerspective() && transform_.invert(&inverse_transform_)) {
inverse_transform_.mapRect(&context->cull_rect);
} else {
context->cull_rect = kGiantRect;
}
SkRect child_paint_bounds = SkRect::MakeEmpty();
PrerollChildren(context, child_matrix, &child_paint_bounds);
transform_.mapRect(&child_paint_bounds);
set_paint_bounds(child_paint_bounds);
context->cull_rect = previous_cull_rect;
}
#if defined(OS_FUCHSIA)
void TransformLayer::UpdateScene(SceneUpdateContext& context) {
FML_DCHECK(needs_system_composite());
SceneUpdateContext::Transform transform(context, transform_);
UpdateSceneChildren(context);
}
#endif // defined(OS_FUCHSIA)
void TransformLayer::Paint(PaintContext& context) const {
TRACE_EVENT0("flutter", "TransformLayer::Paint");
FML_DCHECK(needs_painting());
SkAutoCanvasRestore save(context.internal_nodes_canvas, true);
context.internal_nodes_canvas->concat(transform_);
PaintChildren(context);
}
} // namespace flutter
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/detail/CacheLocality.h>
#ifndef _MSC_VER
#define _GNU_SOURCE 1 // for RTLD_NOLOAD
#include <dlfcn.h>
#endif
#include <fstream>
#include <folly/Conv.h>
#include <folly/Exception.h>
#include <folly/FileUtil.h>
#include <folly/Format.h>
#include <folly/ScopeGuard.h>
namespace folly { namespace detail {
///////////// CacheLocality
/// Returns the best real CacheLocality information available
static CacheLocality getSystemLocalityInfo() {
#ifdef __linux__
try {
return CacheLocality::readFromSysfs();
} catch (...) {
// keep trying
}
#endif
long numCpus = sysconf(_SC_NPROCESSORS_CONF);
if (numCpus <= 0) {
// This shouldn't happen, but if it does we should try to keep
// going. We are probably not going to be able to parse /sys on
// this box either (although we will try), which means we are going
// to fall back to the SequentialThreadId splitter. On my 16 core
// (x hyperthreading) dev box 16 stripes is enough to get pretty good
// contention avoidance with SequentialThreadId, and there is little
// improvement from going from 32 to 64. This default gives us some
// wiggle room
numCpus = 32;
}
return CacheLocality::uniform(numCpus);
}
template <>
const CacheLocality& CacheLocality::system<std::atomic>() {
static CacheLocality cache(getSystemLocalityInfo());
return cache;
}
// Each level of cache has sharing sets, which are the set of cpus
// that share a common cache at that level. These are available in a
// hex bitset form (/sys/devices/system/cpu/cpu0/index0/shared_cpu_map,
// for example). They are also available in a human-readable list form,
// as in /sys/devices/system/cpu/cpu0/index0/shared_cpu_list. The list
// is a comma-separated list of numbers and ranges, where the ranges are
// a pair of decimal numbers separated by a '-'.
//
// To sort the cpus for optimum locality we don't really need to parse
// the sharing sets, we just need a unique representative from the
// equivalence class. The smallest value works fine, and happens to be
// the first decimal number in the file. We load all of the equivalence
// class information from all of the cpu*/index* directories, order the
// cpus first by increasing last-level cache equivalence class, then by
// the smaller caches. Finally, we break ties with the cpu number itself.
/// Returns the first decimal number in the string, or throws an exception
/// if the string does not start with a number terminated by ',', '-',
/// '\n', or eos.
static size_t parseLeadingNumber(const std::string& line) {
auto raw = line.c_str();
char *end;
unsigned long val = strtoul(raw, &end, 10);
if (end == raw || (*end != ',' && *end != '-' && *end != '\n' && *end != 0)) {
throw std::runtime_error(to<std::string>(
"error parsing list '", line, "'").c_str());
}
return val;
}
CacheLocality CacheLocality::readFromSysfsTree(
const std::function<std::string(std::string)>& mapping) {
// number of equivalence classes per level
std::vector<size_t> numCachesByLevel;
// the list of cache equivalence classes, where equivalance classes
// are named by the smallest cpu in the class
std::vector<std::vector<size_t>> equivClassesByCpu;
std::vector<size_t> cpus;
while (true) {
auto cpu = cpus.size();
std::vector<size_t> levels;
for (size_t index = 0; ; ++index) {
auto dir = format("/sys/devices/system/cpu/cpu{}/cache/index{}/",
cpu, index).str();
auto cacheType = mapping(dir + "type");
auto equivStr = mapping(dir + "shared_cpu_list");
if (cacheType.size() == 0 || equivStr.size() == 0) {
// no more caches
break;
}
if (cacheType[0] == 'I') {
// cacheType in { "Data", "Instruction", "Unified" }. skip icache
continue;
}
auto equiv = parseLeadingNumber(equivStr);
auto level = levels.size();
levels.push_back(equiv);
if (equiv == cpu) {
// we only want to count the equiv classes once, so we do it when
// we first encounter them
while (numCachesByLevel.size() <= level) {
numCachesByLevel.push_back(0);
}
numCachesByLevel[level]++;
}
}
if (levels.size() == 0) {
// no levels at all for this cpu, we must be done
break;
}
equivClassesByCpu.emplace_back(std::move(levels));
cpus.push_back(cpu);
}
if (cpus.size() == 0) {
throw std::runtime_error("unable to load cache sharing info");
}
std::sort(cpus.begin(), cpus.end(), [&](size_t lhs, size_t rhs) -> bool {
// sort first by equiv class of cache with highest index, direction
// doesn't matter. If different cpus have different numbers of
// caches then this code might produce a sub-optimal ordering, but
// it won't crash
auto& lhsEquiv = equivClassesByCpu[lhs];
auto& rhsEquiv = equivClassesByCpu[rhs];
for (int i = std::min(lhsEquiv.size(), rhsEquiv.size()) - 1; i >= 0; --i) {
if (lhsEquiv[i] != rhsEquiv[i]) {
return lhsEquiv[i] < rhsEquiv[i];
}
}
// break ties deterministically by cpu
return lhs < rhs;
});
// the cpus are now sorted by locality, with neighboring entries closer
// to each other than entries that are far away. For striping we want
// the inverse map, since we are starting with the cpu
std::vector<size_t> indexes(cpus.size());
for (size_t i = 0; i < cpus.size(); ++i) {
indexes[cpus[i]] = i;
}
return CacheLocality{
cpus.size(), std::move(numCachesByLevel), std::move(indexes) };
}
CacheLocality CacheLocality::readFromSysfs() {
return readFromSysfsTree([](std::string name) {
std::ifstream xi(name.c_str());
std::string rv;
std::getline(xi, rv);
return rv;
});
}
CacheLocality CacheLocality::uniform(size_t numCpus) {
CacheLocality rv;
rv.numCpus = numCpus;
// one cache shared by all cpus
rv.numCachesByLevel.push_back(numCpus);
// no permutations in locality index mapping
for (size_t cpu = 0; cpu < numCpus; ++cpu) {
rv.localityIndexByCpu.push_back(cpu);
}
return rv;
}
////////////// Getcpu
/// Resolves the dynamically loaded symbol __vdso_getcpu, returning null
/// on failure
static Getcpu::Func loadVdsoGetcpu() {
#ifdef _MSC_VER
return nullptr;
#else
void* h = dlopen("linux-vdso.so.1", RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
if (h == nullptr) {
return nullptr;
}
auto func = Getcpu::Func(dlsym(h, "__vdso_getcpu"));
if (func == nullptr) {
// technically a null result could either be a failure or a successful
// lookup of a symbol with the null value, but the second can't actually
// happen for this symbol. No point holding the handle forever if
// we don't need the code
dlclose(h);
}
return func;
#endif
}
Getcpu::Func Getcpu::vdsoFunc() {
static Func func = loadVdsoGetcpu();
return func;
}
#ifdef FOLLY_TLS
/////////////// SequentialThreadId
template<>
std::atomic<size_t> SequentialThreadId<std::atomic>::prevId(0);
template<>
FOLLY_TLS size_t SequentialThreadId<std::atomic>::currentId(0);
#endif
/////////////// AccessSpreader
template<>
const AccessSpreader<std::atomic>
AccessSpreader<std::atomic>::stripeByCore(
CacheLocality::system<>().numCachesByLevel.front());
template<>
const AccessSpreader<std::atomic>
AccessSpreader<std::atomic>::stripeByChip(
CacheLocality::system<>().numCachesByLevel.back());
template<>
AccessSpreaderArray<std::atomic,128>
AccessSpreaderArray<std::atomic,128>::sharedInstance = {};
/// Always claims to be on CPU zero, node zero
static int degenerateGetcpu(unsigned* cpu, unsigned* node, void* /* unused */) {
if (cpu != nullptr) {
*cpu = 0;
}
if (node != nullptr) {
*node = 0;
}
return 0;
}
template<>
Getcpu::Func AccessSpreader<std::atomic>::pickGetcpuFunc(size_t numStripes) {
if (numStripes == 1) {
// there's no need to call getcpu if there is only one stripe.
// This should not be common, so we don't want to waste a test and
// branch in the main code path, but we might as well use a faster
// function pointer
return °enerateGetcpu;
} else {
auto best = Getcpu::vdsoFunc();
return best ? best : &FallbackGetcpuType::getcpu;
}
}
} } // namespace folly::detail
<commit_msg>Make folly/future portable on android<commit_after>/*
* Copyright 2015 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/detail/CacheLocality.h>
#ifndef _MSC_VER
#define _GNU_SOURCE 1 // for RTLD_NOLOAD
#include <dlfcn.h>
#endif
#include <fstream>
#include <folly/Conv.h>
#include <folly/Exception.h>
#include <folly/FileUtil.h>
#include <folly/Format.h>
#include <folly/ScopeGuard.h>
namespace folly { namespace detail {
///////////// CacheLocality
/// Returns the best real CacheLocality information available
static CacheLocality getSystemLocalityInfo() {
#ifdef __linux__
try {
return CacheLocality::readFromSysfs();
} catch (...) {
// keep trying
}
#endif
long numCpus = sysconf(_SC_NPROCESSORS_CONF);
if (numCpus <= 0) {
// This shouldn't happen, but if it does we should try to keep
// going. We are probably not going to be able to parse /sys on
// this box either (although we will try), which means we are going
// to fall back to the SequentialThreadId splitter. On my 16 core
// (x hyperthreading) dev box 16 stripes is enough to get pretty good
// contention avoidance with SequentialThreadId, and there is little
// improvement from going from 32 to 64. This default gives us some
// wiggle room
numCpus = 32;
}
return CacheLocality::uniform(numCpus);
}
template <>
const CacheLocality& CacheLocality::system<std::atomic>() {
static CacheLocality cache(getSystemLocalityInfo());
return cache;
}
// Each level of cache has sharing sets, which are the set of cpus
// that share a common cache at that level. These are available in a
// hex bitset form (/sys/devices/system/cpu/cpu0/index0/shared_cpu_map,
// for example). They are also available in a human-readable list form,
// as in /sys/devices/system/cpu/cpu0/index0/shared_cpu_list. The list
// is a comma-separated list of numbers and ranges, where the ranges are
// a pair of decimal numbers separated by a '-'.
//
// To sort the cpus for optimum locality we don't really need to parse
// the sharing sets, we just need a unique representative from the
// equivalence class. The smallest value works fine, and happens to be
// the first decimal number in the file. We load all of the equivalence
// class information from all of the cpu*/index* directories, order the
// cpus first by increasing last-level cache equivalence class, then by
// the smaller caches. Finally, we break ties with the cpu number itself.
/// Returns the first decimal number in the string, or throws an exception
/// if the string does not start with a number terminated by ',', '-',
/// '\n', or eos.
static size_t parseLeadingNumber(const std::string& line) {
auto raw = line.c_str();
char *end;
unsigned long val = strtoul(raw, &end, 10);
if (end == raw || (*end != ',' && *end != '-' && *end != '\n' && *end != 0)) {
throw std::runtime_error(to<std::string>(
"error parsing list '", line, "'").c_str());
}
return val;
}
CacheLocality CacheLocality::readFromSysfsTree(
const std::function<std::string(std::string)>& mapping) {
// number of equivalence classes per level
std::vector<size_t> numCachesByLevel;
// the list of cache equivalence classes, where equivalance classes
// are named by the smallest cpu in the class
std::vector<std::vector<size_t>> equivClassesByCpu;
std::vector<size_t> cpus;
while (true) {
auto cpu = cpus.size();
std::vector<size_t> levels;
for (size_t index = 0; ; ++index) {
auto dir = format("/sys/devices/system/cpu/cpu{}/cache/index{}/",
cpu, index).str();
auto cacheType = mapping(dir + "type");
auto equivStr = mapping(dir + "shared_cpu_list");
if (cacheType.size() == 0 || equivStr.size() == 0) {
// no more caches
break;
}
if (cacheType[0] == 'I') {
// cacheType in { "Data", "Instruction", "Unified" }. skip icache
continue;
}
auto equiv = parseLeadingNumber(equivStr);
auto level = levels.size();
levels.push_back(equiv);
if (equiv == cpu) {
// we only want to count the equiv classes once, so we do it when
// we first encounter them
while (numCachesByLevel.size() <= level) {
numCachesByLevel.push_back(0);
}
numCachesByLevel[level]++;
}
}
if (levels.size() == 0) {
// no levels at all for this cpu, we must be done
break;
}
equivClassesByCpu.emplace_back(std::move(levels));
cpus.push_back(cpu);
}
if (cpus.size() == 0) {
throw std::runtime_error("unable to load cache sharing info");
}
std::sort(cpus.begin(), cpus.end(), [&](size_t lhs, size_t rhs) -> bool {
// sort first by equiv class of cache with highest index, direction
// doesn't matter. If different cpus have different numbers of
// caches then this code might produce a sub-optimal ordering, but
// it won't crash
auto& lhsEquiv = equivClassesByCpu[lhs];
auto& rhsEquiv = equivClassesByCpu[rhs];
for (int i = std::min(lhsEquiv.size(), rhsEquiv.size()) - 1; i >= 0; --i) {
if (lhsEquiv[i] != rhsEquiv[i]) {
return lhsEquiv[i] < rhsEquiv[i];
}
}
// break ties deterministically by cpu
return lhs < rhs;
});
// the cpus are now sorted by locality, with neighboring entries closer
// to each other than entries that are far away. For striping we want
// the inverse map, since we are starting with the cpu
std::vector<size_t> indexes(cpus.size());
for (size_t i = 0; i < cpus.size(); ++i) {
indexes[cpus[i]] = i;
}
return CacheLocality{
cpus.size(), std::move(numCachesByLevel), std::move(indexes) };
}
CacheLocality CacheLocality::readFromSysfs() {
return readFromSysfsTree([](std::string name) {
std::ifstream xi(name.c_str());
std::string rv;
std::getline(xi, rv);
return rv;
});
}
CacheLocality CacheLocality::uniform(size_t numCpus) {
CacheLocality rv;
rv.numCpus = numCpus;
// one cache shared by all cpus
rv.numCachesByLevel.push_back(numCpus);
// no permutations in locality index mapping
for (size_t cpu = 0; cpu < numCpus; ++cpu) {
rv.localityIndexByCpu.push_back(cpu);
}
return rv;
}
////////////// Getcpu
/// Resolves the dynamically loaded symbol __vdso_getcpu, returning null
/// on failure
static Getcpu::Func loadVdsoGetcpu() {
#if defined(_MSC_VER) || defined(__BIONIC__)
return nullptr;
#else
void* h = dlopen("linux-vdso.so.1", RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
if (h == nullptr) {
return nullptr;
}
auto func = Getcpu::Func(dlsym(h, "__vdso_getcpu"));
if (func == nullptr) {
// technically a null result could either be a failure or a successful
// lookup of a symbol with the null value, but the second can't actually
// happen for this symbol. No point holding the handle forever if
// we don't need the code
dlclose(h);
}
return func;
#endif
}
Getcpu::Func Getcpu::vdsoFunc() {
static Func func = loadVdsoGetcpu();
return func;
}
#ifdef FOLLY_TLS
/////////////// SequentialThreadId
template<>
std::atomic<size_t> SequentialThreadId<std::atomic>::prevId(0);
template<>
FOLLY_TLS size_t SequentialThreadId<std::atomic>::currentId(0);
#endif
/////////////// AccessSpreader
template<>
const AccessSpreader<std::atomic>
AccessSpreader<std::atomic>::stripeByCore(
CacheLocality::system<>().numCachesByLevel.front());
template<>
const AccessSpreader<std::atomic>
AccessSpreader<std::atomic>::stripeByChip(
CacheLocality::system<>().numCachesByLevel.back());
template<>
AccessSpreaderArray<std::atomic,128>
AccessSpreaderArray<std::atomic,128>::sharedInstance = {};
/// Always claims to be on CPU zero, node zero
static int degenerateGetcpu(unsigned* cpu, unsigned* node, void* /* unused */) {
if (cpu != nullptr) {
*cpu = 0;
}
if (node != nullptr) {
*node = 0;
}
return 0;
}
template<>
Getcpu::Func AccessSpreader<std::atomic>::pickGetcpuFunc(size_t numStripes) {
if (numStripes == 1) {
// there's no need to call getcpu if there is only one stripe.
// This should not be common, so we don't want to waste a test and
// branch in the main code path, but we might as well use a faster
// function pointer
return °enerateGetcpu;
} else {
auto best = Getcpu::vdsoFunc();
return best ? best : &FallbackGetcpuType::getcpu;
}
}
} } // namespace folly::detail
<|endoftext|>
|
<commit_before>
#include <iostream>
#include <allegro/system.h>
#include <allegro/color.h>
#include <allegro/target.h>
#include <allegro/display.h>
#include <allegro/keyboard.h>
#include <allegro/timer.h>
#include <allegro/event.h>
#include <allegro/event_queue.h>
#include <gui/container.h>
#include <gui/form_layout.h>
#include <gui/box_layout.h>
#include <gui/grid_layout.h>
#include <gui/tree_layout.h>
namespace {
////////////////////////////////////////
std::shared_ptr<layout> test_box( std::shared_ptr<container> c )
{
auto l = std::make_shared<box_layout>( c, direction::DOWN );
for ( size_t i = 0; i < 5; ++i )
{
auto a = l->new_area( i == 2 ? 1.0 : 0.0 );
a->set_minimum( 100, 24 );
}
return l;
}
////////////////////////////////////////
std::shared_ptr<layout> test_tree( std::shared_ptr<container> c )
{
auto l = std::make_shared<tree_layout>( c, 24.0 );
for ( size_t i = 0; i < 2; ++i )
{
auto a = l->new_area( 0.0 );
a->set_minimum( 100, 24 );
}
auto b1 = l->new_branch();
for ( size_t i = 0; i < 2; ++i )
{
auto a = b1->new_area();
a->set_minimum( 100, 24 );
}
for ( size_t i = 0; i < 2; ++i )
{
auto a = l->new_area( 0.0 );
a->set_minimum( 100, 24 );
}
l->new_area( 1.0 );
return l;
}
////////////////////////////////////////
std::shared_ptr<layout> test_form( std::shared_ptr<container> c )
{
std::shared_ptr<area> a, b;
auto l = std::make_shared<form_layout>( c );
for ( size_t i = 0; i < 5; ++i )
{
std::tie( a, b ) = l->new_row();
a->set_minimum( 100, 24 );
b->set_minimum( 100, 24 );
}
return l;
}
////////////////////////////////////////
std::shared_ptr<layout> test_grid( std::shared_ptr<container> c )
{
auto l = std::make_shared<grid_layout>( c );
for ( size_t i = 0; i < 5; ++i )
auto tmp = l->new_column( i == 2 ? 1.0 : 0.0 );
for ( size_t i = 0; i < 5; ++i )
{
auto tmp = l->new_row( i == 2 ? 1.0 : 0.0 );
for ( auto a: tmp )
a->set_minimum( 50, 24 );
}
return l;
}
////////////////////////////////////////
int safemain( int argc, char **argv )
{
allegro::system sys;
al_set_new_display_flags( ALLEGRO_WINDOWED | ALLEGRO_RESIZABLE );
allegro::event_queue queue;
allegro::display win( 640, 480 );
win.set_title( "Hello World" );
queue.add_source( win );
allegro::keyboard keyb;
queue.add_source( keyb );
allegro::timer timer( 0.1 );
queue.add_source( timer );
allegro::color black( 0, 0, 0 );
allegro::color white( 255, 255, 255 );
std::shared_ptr<container> c = std::make_shared<container>();
auto layout = test_grid( c );
auto recompute_layout = [&] ( double w, double h ) {
c->bounds()->set_horizontal( 0, w );
c->bounds()->set_vertical( 0, h );
layout->recompute_minimum();
layout->recompute_layout();
};
recompute_layout( 640, 480 );
timer.start();
bool done = false;
do
{
allegro::event ev;
queue.wait( ev );
switch ( ev.type() )
{
case allegro::EVENT_KEY_DOWN:
case allegro::EVENT_DISPLAY_CLOSE:
done = true;
break;
case allegro::EVENT_DISPLAY_RESIZE:
recompute_layout( ev.width(), ev.height() );
ev.acknowledge_resize();
break;
case allegro::EVENT_TIMER:
{
allegro::target t( win );
t.clear( white );
for ( auto a: *c )
t.draw_rect( a->x1() + 0.5, a->y1() + 0.5, a->x2() - 0.5, a->y2() - 0.5, black, 1.F );
t.flip();
break;
}
default:
break;
}
} while ( !done );
return 0;
}
}
////////////////////////////////////////
int main( int argc, char *argv[] )
{
int ret = -1;
try
{
ret = safemain( argc, argv );
}
catch ( std::exception &e )
{
print_exception( std::cerr, e );
}
return ret;
}
////////////////////////////////////////
<commit_msg>Added multiple test without recompiling.<commit_after>
#include <iostream>
#include <map>
#include <functional>
#include <allegro/system.h>
#include <allegro/color.h>
#include <allegro/target.h>
#include <allegro/display.h>
#include <allegro/keyboard.h>
#include <allegro/timer.h>
#include <allegro/event.h>
#include <allegro/event_queue.h>
#include <gui/container.h>
#include <gui/form_layout.h>
#include <gui/box_layout.h>
#include <gui/grid_layout.h>
#include <gui/tree_layout.h>
namespace {
////////////////////////////////////////
std::shared_ptr<layout> test_box( std::shared_ptr<container> c )
{
auto l = std::make_shared<box_layout>( c, direction::DOWN );
for ( size_t i = 0; i < 5; ++i )
{
auto a = l->new_area( i == 2 ? 1.0 : 0.0 );
a->set_minimum( 100, 24 );
}
return l;
}
////////////////////////////////////////
std::shared_ptr<layout> test_tree( std::shared_ptr<container> c )
{
auto l = std::make_shared<tree_layout>( c, 24.0 );
for ( size_t i = 0; i < 2; ++i )
{
auto a = l->new_area( 0.0 );
a->set_minimum( 100, 24 );
}
auto b1 = l->new_branch();
for ( size_t i = 0; i < 2; ++i )
{
auto a = b1->new_area();
a->set_minimum( 100, 24 );
}
for ( size_t i = 0; i < 2; ++i )
{
auto a = l->new_area( 0.0 );
a->set_minimum( 100, 24 );
}
l->new_area( 1.0 );
return l;
}
////////////////////////////////////////
std::shared_ptr<layout> test_form( std::shared_ptr<container> c )
{
std::shared_ptr<area> a, b;
auto l = std::make_shared<form_layout>( c );
for ( size_t i = 0; i < 5; ++i )
{
std::tie( a, b ) = l->new_row();
a->set_minimum( 100, 24 );
b->set_minimum( 100, 24 );
}
return l;
}
////////////////////////////////////////
std::shared_ptr<layout> test_grid( std::shared_ptr<container> c )
{
auto l = std::make_shared<grid_layout>( c );
for ( size_t i = 0; i < 5; ++i )
auto tmp = l->new_column( i == 2 ? 1.0 : 0.0 );
for ( size_t i = 0; i < 5; ++i )
{
auto tmp = l->new_row( i == 2 ? 1.0 : 0.0 );
for ( auto a: tmp )
a->set_minimum( 50, 24 );
}
return l;
}
////////////////////////////////////////
std::map<std::string,std::function<std::shared_ptr<layout>(std::shared_ptr<container>)>> tests =
{
{ "grid", test_grid },
{ "box", test_box },
{ "form", test_form },
{ "tree", test_tree },
};
////////////////////////////////////////
int safemain( int argc, char **argv )
{
precondition( argc > 1, "expected argument" );
allegro::system sys;
al_set_new_display_flags( ALLEGRO_WINDOWED | ALLEGRO_RESIZABLE );
allegro::event_queue queue;
allegro::display win( 640, 480 );
win.set_title( "Hello World" );
queue.add_source( win );
allegro::keyboard keyb;
queue.add_source( keyb );
allegro::timer timer( 0.1 );
queue.add_source( timer );
allegro::color black( 0, 0, 0 );
allegro::color white( 255, 255, 255 );
std::shared_ptr<container> c = std::make_shared<container>();
auto layout = tests[argv[1]]( c );
auto recompute_layout = [&] ( double w, double h ) {
c->bounds()->set_horizontal( 0, w );
c->bounds()->set_vertical( 0, h );
layout->recompute_minimum();
layout->recompute_layout();
};
recompute_layout( 640, 480 );
timer.start();
bool done = false;
do
{
allegro::event ev;
queue.wait( ev );
switch ( ev.type() )
{
case allegro::EVENT_KEY_DOWN:
case allegro::EVENT_DISPLAY_CLOSE:
done = true;
break;
case allegro::EVENT_DISPLAY_RESIZE:
recompute_layout( ev.width(), ev.height() );
ev.acknowledge_resize();
break;
case allegro::EVENT_TIMER:
{
allegro::target t( win );
t.clear( white );
for ( auto a: *c )
t.draw_rect( a->x1() + 0.5, a->y1() + 0.5, a->x2() - 0.5, a->y2() - 0.5, black, 1.F );
t.flip();
break;
}
default:
break;
}
} while ( !done );
return 0;
}
}
////////////////////////////////////////
int main( int argc, char *argv[] )
{
int ret = -1;
try
{
ret = safemain( argc, argv );
}
catch ( std::exception &e )
{
print_exception( std::cerr, e );
}
return ret;
}
////////////////////////////////////////
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "MooseMesh.h"
#include "Factory.h"
#include "MeshModifier.h"
#include "GatherNearbyElements.h"
// libMesh
#include "boundary_info.h"
#include "mesh_tools.h"
#include "mesh_refinement.h"
#include "parallel.h"
#include "mesh_communication.h"
#include "parallel_mesh.h"
static const int GRAIN_SIZE = 1; // the grain_size does not have much influence on our execution speed
MooseMesh::MooseMesh(int mesh_dim) :
_mesh(mesh_dim),
_is_changed(false),
//_is_parallel(false),
_active_local_elem_range(NULL),
_active_semilocal_node_range(NULL),
_active_node_range(NULL),
_local_node_range(NULL),
_bnd_node_range(NULL),
_patch_size(40)
{
}
MooseMesh::MooseMesh(const MooseMesh & other_mesh) :
_mesh(other_mesh._mesh),
_is_changed(false),
//_is_parallel(false),
_active_local_elem_range(NULL),
_active_semilocal_node_range(NULL),
_active_node_range(NULL),
_local_node_range(NULL),
_bnd_node_range(NULL),
_patch_size(40)
{
(*_mesh.boundary_info) = (*other_mesh._mesh.boundary_info);
}
MooseMesh::~MooseMesh()
{
freeBndNodes();
delete _active_local_elem_range;
delete _active_node_range;
delete _active_semilocal_node_range;
delete _local_node_range;
delete _bnd_node_range;
}
void
MooseMesh::freeBndNodes()
{
// free memory
for (std::vector<BndNode *>::iterator it = _bnd_nodes.begin(); it != _bnd_nodes.end(); ++it)
delete (*it);
for (std::map<short int, std::vector<unsigned int> >::iterator it = _node_set_nodes.begin(); it != _node_set_nodes.end(); ++it)
it->second.clear();
_node_set_nodes.clear();
}
void
MooseMesh::read(const std::string file_name)
{
_mesh.read(file_name);
}
void
MooseMesh::prepare()
{
// This is now done in Nemesis_IO::read()
// If we are using a truly Parallel mesh (like Nemesis) then we might not even have neighbors!
// if(parallel())
// MeshCommunication().gather_neighboring_elements(libmesh_cast_ref<ParallelMesh&>(getMesh()));
//
_mesh.prepare_for_use(false);
// If using ParallelMesh this will delete non-local elements from the current processor
// If using SerialMesh, this function is a no-op.
_mesh.delete_remote_elements();
if(!_mesh.is_serial())
Moose::gatherNearbyElements(*this, _ghosted_boundaries, _ghosted_boundaries_inflation);
// Collect (local) subdomain IDs
const MeshBase::element_iterator el_end = _mesh.elements_end();
/*
unsigned int num_elems = 0;
for (MeshBase::element_iterator el = _mesh.elements_begin(); el != el_end; ++el)
num_elems++;
// std::cerr<<libMesh::processor_id()<<": num_elems: "<<num_elems<<std::endl;
Parallel::sum(num_elems);
std::cout<<"Total elems: "<<num_elems<<std::endl;
*/
for (MeshBase::element_iterator el = _mesh.elements_begin(); el != el_end; ++el)
_mesh_subdomains.insert((*el)->subdomain_id());
// Collect (local) boundary IDs
const std::set<short>& local_bids = _mesh.boundary_info->get_boundary_ids();
_mesh_boundary_ids.insert(local_bids.begin(), local_bids.end());
// Communicate subdomain and boundary IDs if this is a parallel mesh
if (!_mesh.is_serial())
{
// Subdomain size before
// std::cout << "(before) _mesh_subdomains.size()=" << _mesh_subdomains.size() << std::endl;
// Pack our subdomain IDs into a vector
std::vector<subdomain_id_type> mesh_subdomains_vector(_mesh_subdomains.begin(),
_mesh_subdomains.end());
// Gather them all into an enlarged vector
Parallel::allgather(mesh_subdomains_vector);
// Attempt to insert any new IDs into the set (any existing ones will be skipped)
_mesh_subdomains.insert(mesh_subdomains_vector.begin(),
mesh_subdomains_vector.end());
// Subdomain size after
// std::cout << "(after) _mesh_subdomains.size()=" << _mesh_subdomains.size() << std::endl;
// Boundary ID size before
// std::cout << "(before) _mesh_boundary_ids.size()=" << _mesh_boundary_ids.size() << std::endl;
// Pack our boundary IDs into a vector for communication
std::vector<short> mesh_boundary_ids_vector(_mesh_boundary_ids.begin(),
_mesh_boundary_ids.end());
// Gather them all into an enlarged vector
Parallel::allgather(mesh_boundary_ids_vector);
// Attempt to insert any new IDs into the set (any existing ones will be skipped)
_mesh_boundary_ids.insert(mesh_boundary_ids_vector.begin(),
mesh_boundary_ids_vector.end());
// Boundary ID size after
// std::cout << "(after) _mesh_boundary_ids.size()=" << _mesh_boundary_ids.size() << std::endl;
}
update();
}
void
MooseMesh::update()
{
// Rebuild the boundary conditions
build_node_list_from_side_list();
//Update the node to elem map
_node_to_elem_map.clear();
MeshTools::build_nodes_to_elem_map(_mesh, _node_to_elem_map);
buildNodeList();
cacheInfo();
}
#ifdef LIBMESH_ENABLE_AMR
void
MooseMesh::uniformlyRefine(int level)
{
MeshRefinement mesh_refinement(_mesh);
mesh_refinement.uniformly_refine(level);
}
#endif //LIBMESH_ENABLE_AMR
void
MooseMesh::meshChanged()
{
update();
// Rebuild the active local element range
delete _active_local_elem_range;
_active_local_elem_range = NULL;
// Rebuild the node range
delete _active_node_range;
_active_node_range = NULL;
// Rebuild the semilocal range
delete _active_semilocal_node_range;
_active_semilocal_node_range = NULL;
// Rebuild the local node range
delete _local_node_range;
_local_node_range = NULL;
// Rebuild the boundary node range
delete _bnd_node_range;
_bnd_node_range = NULL;
// Rebuild the ranges
getActiveLocalElementRange();
getActiveNodeRange();
getLocalNodeRange();
getBoundaryNodeRange();
// Print out information about the adapted mesh if requested
// if (_print_mesh_changed)
// {
// std::cout << "\nMesh Changed:\n";
// _mesh->print_info();
// }
// Lets the output system know that the mesh has changed recently.
_is_changed = true;
}
void
MooseMesh::updateActiveSemiLocalNodeRange(std::set<unsigned int> & ghosted_elems)
{
_semilocal_node_list.clear();
// First add the nodes connected to local elems
ConstElemRange * active_local_elems = getActiveLocalElementRange();
for(ConstElemRange::const_iterator it=active_local_elems->begin();
it!=active_local_elems->end();
++it)
{
const Elem * elem = *it;
for(unsigned int n=0; n<elem->n_nodes(); n++)
{
Node * node = elem->get_node(n);
_semilocal_node_list.insert(node);
}
}
// Now add the nodes connected to ghosted_elems
for(std::set<unsigned int>::iterator it=ghosted_elems.begin();
it!=ghosted_elems.end();
++it)
{
Elem * elem = _mesh.elem(*it);
for(unsigned int n=0; n<elem->n_nodes(); n++)
{
Node * node = elem->get_node(n);
_semilocal_node_list.insert(node);
}
}
delete _active_semilocal_node_range;
// Now create the actual range
_active_semilocal_node_range = new SemiLocalNodeRange(_semilocal_node_list.begin(), _semilocal_node_list.end());
}
void
MooseMesh::buildNodeList()
{
freeBndNodes();
/// Boundary node list (node ids and corresponding side-set ids, arrays always have the same length)
std::vector<unsigned int> nodes;
std::vector<short int> ids;
_mesh.boundary_info->build_node_list(nodes, ids);
int n = nodes.size();
_bnd_nodes.resize(n);
for (int i = 0; i < n; i++)
{
_bnd_nodes[i] = new BndNode(&_mesh.node(nodes[i]), ids[i]);
_node_set_nodes[ids[i]].push_back(nodes[i]);
}
}
ConstElemRange *
MooseMesh::getActiveLocalElementRange()
{
if (!_active_local_elem_range)
{
_active_local_elem_range = new ConstElemRange(_mesh.active_local_elements_begin(),
_mesh.active_local_elements_end(), GRAIN_SIZE);
}
return _active_local_elem_range;
}
NodeRange *
MooseMesh::getActiveNodeRange()
{
if (!_active_node_range)
{
_active_node_range = new NodeRange(_mesh.active_nodes_begin(),
_mesh.active_nodes_end(), GRAIN_SIZE);
}
return _active_node_range;
}
SemiLocalNodeRange *
MooseMesh::getActiveSemiLocalNodeRange()
{
mooseAssert(_active_semilocal_node_range, "_active_semilocal_node_range has not been created yet!");
/*
if (!_active_node_range)
{
_active_semilocal_node_range = new NodeRange(_mesh.local_nodes_begin(),
_mesh.local_nodes_end(), GRAIN_SIZE);
}
*/
return _active_semilocal_node_range;
}
ConstNodeRange *
MooseMesh::getLocalNodeRange()
{
if (!_local_node_range)
{
_local_node_range = new ConstNodeRange(_mesh.local_nodes_begin(),
_mesh.local_nodes_end(), GRAIN_SIZE);
}
return _local_node_range;
}
ConstBndNodeRange *
MooseMesh::getBoundaryNodeRange()
{
if (!_bnd_node_range)
{
_bnd_node_range = new ConstBndNodeRange(bnd_nodes_begin(),
bnd_nodes_end(), GRAIN_SIZE);
}
return _bnd_node_range;
}
// MooseMesh Modifiers /////
void
MooseMesh::addMeshModifer(const std::string & mod_name, const std::string & name, InputParameters parameters)
{
_mesh_modifiers.push_back(static_cast<MeshModifier *>(Factory::instance()->create(mod_name, name, parameters)));
}
void
MooseMesh::applyMeshModifications()
{
for (std::vector<MeshModifier *>::iterator i = _mesh_modifiers.begin(); i != _mesh_modifiers.end(); ++i)
(*i)->modifyMesh(_mesh);
}
void
MooseMesh::cacheInfo()
{
for (MeshBase::element_iterator el = _mesh.local_elements_begin(); el != _mesh.local_elements_end(); ++el)
{
Elem * elem = *el;
for(unsigned int nd = 0; nd < elem->n_nodes(); ++nd)
{
Node & node = *elem->get_node(nd);
_block_node_list[node.id()].insert(elem->subdomain_id());
}
}
}
std::set<subdomain_id_type> &
MooseMesh::getNodeBlockIds(const Node & node)
{
return _block_node_list[node.id()];
}
// default begin() accessor
bnd_node_iterator
MooseMesh::bnd_nodes_begin ()
{
Predicates::NotNull<bnd_node_iterator_imp> p;
return bnd_node_iterator(_bnd_nodes.begin(), _bnd_nodes.end(), p);
}
// default end() accessor
bnd_node_iterator
MooseMesh::bnd_nodes_end ()
{
Predicates::NotNull<bnd_node_iterator_imp> p;
return bnd_node_iterator(_bnd_nodes.end(), _bnd_nodes.end(), p);
}
<commit_msg>Clean-up (this is done in Adaptivity class) (#000)<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "MooseMesh.h"
#include "Factory.h"
#include "MeshModifier.h"
#include "GatherNearbyElements.h"
// libMesh
#include "boundary_info.h"
#include "mesh_tools.h"
#include "mesh_refinement.h"
#include "parallel.h"
#include "mesh_communication.h"
#include "parallel_mesh.h"
static const int GRAIN_SIZE = 1; // the grain_size does not have much influence on our execution speed
MooseMesh::MooseMesh(int mesh_dim) :
_mesh(mesh_dim),
_is_changed(false),
//_is_parallel(false),
_active_local_elem_range(NULL),
_active_semilocal_node_range(NULL),
_active_node_range(NULL),
_local_node_range(NULL),
_bnd_node_range(NULL),
_patch_size(40)
{
}
MooseMesh::MooseMesh(const MooseMesh & other_mesh) :
_mesh(other_mesh._mesh),
_is_changed(false),
//_is_parallel(false),
_active_local_elem_range(NULL),
_active_semilocal_node_range(NULL),
_active_node_range(NULL),
_local_node_range(NULL),
_bnd_node_range(NULL),
_patch_size(40)
{
(*_mesh.boundary_info) = (*other_mesh._mesh.boundary_info);
}
MooseMesh::~MooseMesh()
{
freeBndNodes();
delete _active_local_elem_range;
delete _active_node_range;
delete _active_semilocal_node_range;
delete _local_node_range;
delete _bnd_node_range;
}
void
MooseMesh::freeBndNodes()
{
// free memory
for (std::vector<BndNode *>::iterator it = _bnd_nodes.begin(); it != _bnd_nodes.end(); ++it)
delete (*it);
for (std::map<short int, std::vector<unsigned int> >::iterator it = _node_set_nodes.begin(); it != _node_set_nodes.end(); ++it)
it->second.clear();
_node_set_nodes.clear();
}
void
MooseMesh::read(const std::string file_name)
{
_mesh.read(file_name);
}
void
MooseMesh::prepare()
{
// This is now done in Nemesis_IO::read()
// If we are using a truly Parallel mesh (like Nemesis) then we might not even have neighbors!
// if(parallel())
// MeshCommunication().gather_neighboring_elements(libmesh_cast_ref<ParallelMesh&>(getMesh()));
//
_mesh.prepare_for_use(false);
// If using ParallelMesh this will delete non-local elements from the current processor
// If using SerialMesh, this function is a no-op.
_mesh.delete_remote_elements();
if(!_mesh.is_serial())
Moose::gatherNearbyElements(*this, _ghosted_boundaries, _ghosted_boundaries_inflation);
// Collect (local) subdomain IDs
const MeshBase::element_iterator el_end = _mesh.elements_end();
/*
unsigned int num_elems = 0;
for (MeshBase::element_iterator el = _mesh.elements_begin(); el != el_end; ++el)
num_elems++;
// std::cerr<<libMesh::processor_id()<<": num_elems: "<<num_elems<<std::endl;
Parallel::sum(num_elems);
std::cout<<"Total elems: "<<num_elems<<std::endl;
*/
for (MeshBase::element_iterator el = _mesh.elements_begin(); el != el_end; ++el)
_mesh_subdomains.insert((*el)->subdomain_id());
// Collect (local) boundary IDs
const std::set<short>& local_bids = _mesh.boundary_info->get_boundary_ids();
_mesh_boundary_ids.insert(local_bids.begin(), local_bids.end());
// Communicate subdomain and boundary IDs if this is a parallel mesh
if (!_mesh.is_serial())
{
// Subdomain size before
// std::cout << "(before) _mesh_subdomains.size()=" << _mesh_subdomains.size() << std::endl;
// Pack our subdomain IDs into a vector
std::vector<subdomain_id_type> mesh_subdomains_vector(_mesh_subdomains.begin(),
_mesh_subdomains.end());
// Gather them all into an enlarged vector
Parallel::allgather(mesh_subdomains_vector);
// Attempt to insert any new IDs into the set (any existing ones will be skipped)
_mesh_subdomains.insert(mesh_subdomains_vector.begin(),
mesh_subdomains_vector.end());
// Subdomain size after
// std::cout << "(after) _mesh_subdomains.size()=" << _mesh_subdomains.size() << std::endl;
// Boundary ID size before
// std::cout << "(before) _mesh_boundary_ids.size()=" << _mesh_boundary_ids.size() << std::endl;
// Pack our boundary IDs into a vector for communication
std::vector<short> mesh_boundary_ids_vector(_mesh_boundary_ids.begin(),
_mesh_boundary_ids.end());
// Gather them all into an enlarged vector
Parallel::allgather(mesh_boundary_ids_vector);
// Attempt to insert any new IDs into the set (any existing ones will be skipped)
_mesh_boundary_ids.insert(mesh_boundary_ids_vector.begin(),
mesh_boundary_ids_vector.end());
// Boundary ID size after
// std::cout << "(after) _mesh_boundary_ids.size()=" << _mesh_boundary_ids.size() << std::endl;
}
update();
}
void
MooseMesh::update()
{
// Rebuild the boundary conditions
build_node_list_from_side_list();
//Update the node to elem map
_node_to_elem_map.clear();
MeshTools::build_nodes_to_elem_map(_mesh, _node_to_elem_map);
buildNodeList();
cacheInfo();
}
#ifdef LIBMESH_ENABLE_AMR
void
MooseMesh::uniformlyRefine(int level)
{
MeshRefinement mesh_refinement(_mesh);
mesh_refinement.uniformly_refine(level);
}
#endif //LIBMESH_ENABLE_AMR
void
MooseMesh::meshChanged()
{
update();
// Rebuild the active local element range
delete _active_local_elem_range;
_active_local_elem_range = NULL;
// Rebuild the node range
delete _active_node_range;
_active_node_range = NULL;
// Rebuild the semilocal range
delete _active_semilocal_node_range;
_active_semilocal_node_range = NULL;
// Rebuild the local node range
delete _local_node_range;
_local_node_range = NULL;
// Rebuild the boundary node range
delete _bnd_node_range;
_bnd_node_range = NULL;
// Rebuild the ranges
getActiveLocalElementRange();
getActiveNodeRange();
getLocalNodeRange();
getBoundaryNodeRange();
// Lets the output system know that the mesh has changed recently.
_is_changed = true;
}
void
MooseMesh::updateActiveSemiLocalNodeRange(std::set<unsigned int> & ghosted_elems)
{
_semilocal_node_list.clear();
// First add the nodes connected to local elems
ConstElemRange * active_local_elems = getActiveLocalElementRange();
for(ConstElemRange::const_iterator it=active_local_elems->begin();
it!=active_local_elems->end();
++it)
{
const Elem * elem = *it;
for(unsigned int n=0; n<elem->n_nodes(); n++)
{
Node * node = elem->get_node(n);
_semilocal_node_list.insert(node);
}
}
// Now add the nodes connected to ghosted_elems
for(std::set<unsigned int>::iterator it=ghosted_elems.begin();
it!=ghosted_elems.end();
++it)
{
Elem * elem = _mesh.elem(*it);
for(unsigned int n=0; n<elem->n_nodes(); n++)
{
Node * node = elem->get_node(n);
_semilocal_node_list.insert(node);
}
}
delete _active_semilocal_node_range;
// Now create the actual range
_active_semilocal_node_range = new SemiLocalNodeRange(_semilocal_node_list.begin(), _semilocal_node_list.end());
}
void
MooseMesh::buildNodeList()
{
freeBndNodes();
/// Boundary node list (node ids and corresponding side-set ids, arrays always have the same length)
std::vector<unsigned int> nodes;
std::vector<short int> ids;
_mesh.boundary_info->build_node_list(nodes, ids);
int n = nodes.size();
_bnd_nodes.resize(n);
for (int i = 0; i < n; i++)
{
_bnd_nodes[i] = new BndNode(&_mesh.node(nodes[i]), ids[i]);
_node_set_nodes[ids[i]].push_back(nodes[i]);
}
}
ConstElemRange *
MooseMesh::getActiveLocalElementRange()
{
if (!_active_local_elem_range)
{
_active_local_elem_range = new ConstElemRange(_mesh.active_local_elements_begin(),
_mesh.active_local_elements_end(), GRAIN_SIZE);
}
return _active_local_elem_range;
}
NodeRange *
MooseMesh::getActiveNodeRange()
{
if (!_active_node_range)
{
_active_node_range = new NodeRange(_mesh.active_nodes_begin(),
_mesh.active_nodes_end(), GRAIN_SIZE);
}
return _active_node_range;
}
SemiLocalNodeRange *
MooseMesh::getActiveSemiLocalNodeRange()
{
mooseAssert(_active_semilocal_node_range, "_active_semilocal_node_range has not been created yet!");
/*
if (!_active_node_range)
{
_active_semilocal_node_range = new NodeRange(_mesh.local_nodes_begin(),
_mesh.local_nodes_end(), GRAIN_SIZE);
}
*/
return _active_semilocal_node_range;
}
ConstNodeRange *
MooseMesh::getLocalNodeRange()
{
if (!_local_node_range)
{
_local_node_range = new ConstNodeRange(_mesh.local_nodes_begin(),
_mesh.local_nodes_end(), GRAIN_SIZE);
}
return _local_node_range;
}
ConstBndNodeRange *
MooseMesh::getBoundaryNodeRange()
{
if (!_bnd_node_range)
{
_bnd_node_range = new ConstBndNodeRange(bnd_nodes_begin(),
bnd_nodes_end(), GRAIN_SIZE);
}
return _bnd_node_range;
}
// MooseMesh Modifiers /////
void
MooseMesh::addMeshModifer(const std::string & mod_name, const std::string & name, InputParameters parameters)
{
_mesh_modifiers.push_back(static_cast<MeshModifier *>(Factory::instance()->create(mod_name, name, parameters)));
}
void
MooseMesh::applyMeshModifications()
{
for (std::vector<MeshModifier *>::iterator i = _mesh_modifiers.begin(); i != _mesh_modifiers.end(); ++i)
(*i)->modifyMesh(_mesh);
}
void
MooseMesh::cacheInfo()
{
for (MeshBase::element_iterator el = _mesh.local_elements_begin(); el != _mesh.local_elements_end(); ++el)
{
Elem * elem = *el;
for(unsigned int nd = 0; nd < elem->n_nodes(); ++nd)
{
Node & node = *elem->get_node(nd);
_block_node_list[node.id()].insert(elem->subdomain_id());
}
}
}
std::set<subdomain_id_type> &
MooseMesh::getNodeBlockIds(const Node & node)
{
return _block_node_list[node.id()];
}
// default begin() accessor
bnd_node_iterator
MooseMesh::bnd_nodes_begin ()
{
Predicates::NotNull<bnd_node_iterator_imp> p;
return bnd_node_iterator(_bnd_nodes.begin(), _bnd_nodes.end(), p);
}
// default end() accessor
bnd_node_iterator
MooseMesh::bnd_nodes_end ()
{
Predicates::NotNull<bnd_node_iterator_imp> p;
return bnd_node_iterator(_bnd_nodes.end(), _bnd_nodes.end(), p);
}
<|endoftext|>
|
<commit_before>#include "cacheline.h"
#include "get.h"
#include "put.h"
#include "ring.h"
#include "sequence.h"
#include <thread>
#include <iostream>
//using namespace L3;
#ifndef L3_ITERATIONS
// 100 Million.
#define L3_ITERATIONS (100000000)
#endif
constexpr size_t iterations {L3_ITERATIONS};
#ifndef L3_QSIZE
#define L3_QSIZE 19 /* 1/2 MB */
#endif
constexpr size_t qSize {L3_QSIZE};
using Msg = size_t;
using Ring = L3::Ring<Msg, qSize>;
L3_CACHE_LINE Ring ring;
using Iterator = Ring::Iterator<ring>;
L3_CACHE_LINE L3::Sequence commitCursor{Ring::size - 1};
L3_CACHE_LINE L3::Sequence writeCursor{Ring::size};
L3_CACHE_LINE L3::Sequence readCursor{Ring::size};
using Get = L3::Get<readCursor, Iterator, L3::SequenceList<commitCursor>>;
using Put = L3::Put<
writeCursor, commitCursor,
Iterator,
L3::SequenceList<readCursor>,
L3::CommitPolicy::Unique>;
void
dbg()
{
// std::cout << "Ring::size: " << Ring::size << std::endl;
// std::cout << "qSize: " << qSize << std::endl;
std::cout << "commitCursor: " << commitCursor
<< ", writeCursor: " << writeCursor
<< ", readCursor: " << readCursor
<< ", value: " << ring[readCursor]
<< std::endl;
}
bool test1Thread()
{
// Put()(ring) = 42;
Put() = 42;
for(auto& m: Get())
{
std::cout << "m: " << m << std::endl;
if(m != 42)
{
return false;
}
}
Put() = 101;
Put() = 202;
for(auto& m: Get())
{
std::cout << "m: " << m << std::endl;
}
return true;
}
bool
test2Threads()
{
std::thread prod1(
[](){ for(Msg i = 1; i < iterations; ++i) Put() = i; });
Msg previous = 0;
for(Msg i = 1; i < iterations;)
{
for(auto& msg: Get())
{
i++;
if(msg != previous + 1)
{
std::cout << "previous: " << previous
<< ", msg: " << msg
<< std::endl;
return false;
}
previous = msg;
}
}
prod1.join();
return true;
}
int
main()
{
bool status = true;
status &= test1Thread();
status &= test2Threads();
return status ? 0 : 1;
}
<commit_msg>Small clean up.<commit_after>#include "cacheline.h"
#include "get.h"
#include "put.h"
#include "ring.h"
#include "sequence.h"
#include <thread>
#include <iostream>
#ifndef L3_ITERATIONS
// 100 Million.
# define L3_ITERATIONS (100000000)
#endif
constexpr size_t iterations {L3_ITERATIONS};
#ifndef L3_QSIZE
# define L3_QSIZE 19 /* 1/2 MB */
#endif
using Msg = size_t;
constexpr size_t qSize {L3_QSIZE};
using Ring = L3::Ring<Msg, qSize>;
L3_CACHE_LINE Ring ring;
using Iterator = Ring::Iterator<ring>;
L3_CACHE_LINE L3::Sequence commitCursor{Ring::size - 1};
L3_CACHE_LINE L3::Sequence writeCursor{Ring::size};
L3_CACHE_LINE L3::Sequence readCursor{Ring::size};
using Get = L3::Get<readCursor, Iterator, L3::SequenceList<commitCursor>>;
using Put = L3::Put<
writeCursor, commitCursor,
Iterator,
L3::SequenceList<readCursor>,
L3::CommitPolicy::Unique>;
void
dbg()
{
std::cout << "commitCursor: " << commitCursor
<< ", writeCursor: " << writeCursor
<< ", readCursor: " << readCursor
<< ", value: " << ring[readCursor]
<< std::endl;
}
bool test1Thread()
{
Put() = 42;
for(auto& m: Get())
{
std::cout << "m: " << m << std::endl;
if(m != 42)
{
return false;
}
}
Put() = 101;
Put() = 202;
for(auto& m: Get())
{
std::cout << "m: " << m << std::endl;
}
return true;
}
bool
test2Threads()
{
std::thread prod1(
[](){ for(Msg i = 1; i < iterations; ++i) Put() = i; });
Msg previous = 0;
for(Msg i = 1; i < iterations;)
{
for(auto& msg: Get())
{
i++;
if(msg != previous + 1)
{
std::cout << "previous: " << previous
<< ", msg: " << msg
<< std::endl;
return false;
}
previous = msg;
}
}
prod1.join();
return true;
}
int
main()
{
bool status = true;
status &= test1Thread();
status &= test2Threads();
return status ? 0 : 1;
}
<|endoftext|>
|
<commit_before>#ifndef GENERIC_SWALLOW_HPP
# define GENERIC_SWALLOW_HPP
# pragma once
namespace generic
{
struct swallow
{
template <typename ...T>
swallow(T&&) noexcept
{
}
};
}
#endif // GENERIC_SWALLOW_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_SWALLOW_HPP
# define GENERIC_SWALLOW_HPP
# pragma once
namespace generic
{
struct swallow
{
template <typename ...T>
swallow(T&& ...) noexcept
{
}
};
}
#endif // GENERIC_SWALLOW_HPP
<|endoftext|>
|
<commit_before>#include "common.hpp"
#include "internal/cache.hpp"
TEST_CASE("Cache Check", "[cache]")
{
using namespace libkeen::internal;
Cache cache_ref;
REQUIRE(cache_ref.connected());
cache_ref.clear();
std::string event_name = "name1";
std::string event_data = "data1";
std::string event_name_2 = "name2";
std::string event_data_2 = "data2";
cache_ref.push(event_name, event_data);
REQUIRE(cache_ref.exists(event_name, event_data));
std::vector<std::pair<std::string, std::string>> holder;
cache_ref.pop(holder, 1);
REQUIRE(holder.size() == 1);
REQUIRE(holder.back().first == event_name);
REQUIRE(holder.back().second == event_data);
cache_ref.pop(holder, 10);
REQUIRE(holder.size() == 1);
REQUIRE(holder.back().first == event_name);
REQUIRE(holder.back().second == event_data);
cache_ref.push(event_name_2, event_data_2);
REQUIRE(cache_ref.exists(event_name_2, event_data_2));
cache_ref.pop(holder, 10);
REQUIRE(holder.size() == 2);
REQUIRE(holder.front().first == event_name);
REQUIRE(holder.front().second == event_data);
REQUIRE(holder.back().first == event_name_2);
REQUIRE(holder.back().second == event_data_2);
cache_ref.remove(event_name, event_data);
REQUIRE(!cache_ref.exists(event_name, event_data));
}
<commit_msg>reworked cache unit tests, added a multi threaded access test + BDD style checks<commit_after>#include "common.hpp"
#include "asio.hpp"
#include "internal/cache.hpp"
SCENARIO("Cache functionality", "[cache]")
{
std::vector<std::pair<std::string, std::string>> records;
std::string key = "key";
std::string val = "val";
GIVEN("An instance of Cache class")
{
using namespace libkeen::internal;
Cache cache;
REQUIRE(cache.connected());
cache.clear();
REQUIRE(cache.count() == 0);
THEN("A record is pushed")
{
cache.push(key, val);
REQUIRE(cache.count() == 1);
REQUIRE(cache.exists(key, val));
}
THEN("A record is popped")
{
cache.push(key, val);
cache.pop(records, 10);
REQUIRE(records.size() == 1);
REQUIRE(records.back().first == key);
REQUIRE(records.back().second == val);
REQUIRE(cache.exists(key, val));
}
THEN("A record is removed")
{
cache.push(key, val);
REQUIRE(cache.exists(key, val));
cache.remove(key, val);
REQUIRE(cache.count() == 0);
REQUIRE(!cache.exists(key, val));
}
THEN("50 records are pushed single threaded")
{
REQUIRE(cache.count() == 0);
int count = 50;
for (int index = 0; index < count; ++index)
cache.push(key + std::to_string(index), val + std::to_string(index));
REQUIRE(cache.count() == count);
cache.clear();
REQUIRE(cache.count() == 0);
}
THEN("50 records are pushed multi threaded")
{
REQUIRE(cache.count() == 0);
asio::io_service service;
int count = 50;
for (int index = 0; index < count; ++index)
service.post([=, &cache] { cache.push(key + std::to_string(index), val + std::to_string(index)); });
std::vector<std::thread> pool;
for (unsigned t = 0; t < std::thread::hardware_concurrency(); ++t)
pool.push_back(std::thread([&service] { service.run(); }));
service.run();
for (auto& worker : pool)
if (worker.joinable())
worker.join();
REQUIRE(cache.count() == count);
}
}
}
<|endoftext|>
|
<commit_before>//===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the bugpoint internals that narrow down compilation crashes
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "ListReducer.h"
#include "llvm/Constant.h"
#include "llvm/iTerminators.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/PassManager.h"
#include "llvm/SymbolTable.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bytecode/Writer.h"
#include "llvm/Support/CFG.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "Support/FileUtilities.h"
#include <fstream>
#include <set>
class DebugCrashes : public ListReducer<const PassInfo*> {
BugDriver &BD;
public:
DebugCrashes(BugDriver &bd) : BD(bd) {}
// doTest - Return true iff running the "removed" passes succeeds, and running
// the "Kept" passes fail when run on the output of the "removed" passes. If
// we return true, we update the current module of bugpoint.
//
virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
std::vector<const PassInfo*> &Kept);
};
DebugCrashes::TestResult
DebugCrashes::doTest(std::vector<const PassInfo*> &Prefix,
std::vector<const PassInfo*> &Suffix) {
std::string PrefixOutput;
Module *OrigProgram = 0;
if (!Prefix.empty()) {
std::cout << "Checking to see if these passes crash: "
<< getPassesString(Prefix) << ": ";
if (BD.runPasses(Prefix, PrefixOutput))
return KeepPrefix;
OrigProgram = BD.Program;
BD.Program = BD.ParseInputFile(PrefixOutput);
if (BD.Program == 0) {
std::cerr << BD.getToolName() << ": Error reading bytecode file '"
<< PrefixOutput << "'!\n";
exit(1);
}
removeFile(PrefixOutput);
}
std::cout << "Checking to see if these passes crash: "
<< getPassesString(Suffix) << ": ";
if (BD.runPasses(Suffix)) {
delete OrigProgram; // The suffix crashes alone...
return KeepSuffix;
}
// Nothing failed, restore state...
if (OrigProgram) {
delete BD.Program;
BD.Program = OrigProgram;
}
return NoFailure;
}
class ReduceCrashingFunctions : public ListReducer<Function*> {
BugDriver &BD;
public:
ReduceCrashingFunctions(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Kept) {
if (!Kept.empty() && TestFuncs(Kept))
return KeepSuffix;
if (!Prefix.empty() && TestFuncs(Prefix))
return KeepPrefix;
return NoFailure;
}
bool TestFuncs(std::vector<Function*> &Prefix);
};
bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
// Clone the program to try hacking it apart...
Module *M = CloneModule(BD.Program);
// Convert list to set for fast lookup...
std::set<Function*> Functions;
for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Function *CMF = M->getFunction(Funcs[i]->getName(),
Funcs[i]->getFunctionType());
assert(CMF && "Function not in module?!");
Functions.insert(CMF);
}
std::cout << "Checking for crash with only these functions:";
for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
std::cout << " " << Funcs[i]->getName();
std::cout << ": ";
// Loop over and delete any functions which we aren't supposed to be playing
// with...
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->isExternal() && !Functions.count(I))
DeleteFunctionBody(I);
// Try running the hacked up program...
std::swap(BD.Program, M);
if (BD.runPasses(BD.PassesToRun)) {
delete M; // It crashed, keep the trimmed version...
// Make sure to use function pointers that point into the now-current
// module.
Funcs.assign(Functions.begin(), Functions.end());
return true;
}
delete BD.Program; // It didn't crash, revert...
BD.Program = M;
return false;
}
/// ReduceCrashingBlocks reducer - This works by setting the terminators of all
/// terminators except the specified basic blocks to a 'ret' instruction, then
/// running the simplify-cfg pass. This has the effect of chopping up the CFG
/// really fast which can reduce large functions quickly.
///
class ReduceCrashingBlocks : public ListReducer<BasicBlock*> {
BugDriver &BD;
public:
ReduceCrashingBlocks(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
std::vector<BasicBlock*> &Kept) {
if (!Kept.empty() && TestBlocks(Kept))
return KeepSuffix;
if (!Prefix.empty() && TestBlocks(Prefix))
return KeepPrefix;
return NoFailure;
}
bool TestBlocks(std::vector<BasicBlock*> &Prefix);
};
bool ReduceCrashingBlocks::TestBlocks(std::vector<BasicBlock*> &BBs) {
// Clone the program to try hacking it apart...
Module *M = CloneModule(BD.Program);
// Convert list to set for fast lookup...
std::set<BasicBlock*> Blocks;
for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
// Convert the basic block from the original module to the new module...
Function *F = BBs[i]->getParent();
Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
assert(CMF && "Function not in module?!");
// Get the mapped basic block...
Function::iterator CBI = CMF->begin();
std::advance(CBI, std::distance(F->begin(), Function::iterator(BBs[i])));
Blocks.insert(CBI);
}
std::cout << "Checking for crash with only these blocks:";
for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
std::cout << " " << BBs[i]->getName();
std::cout << ": ";
// Loop over and delete any hack up any blocks that are not listed...
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
if (!Blocks.count(BB) && !isa<ReturnInst>(BB->getTerminator())) {
// Loop over all of the successors of this block, deleting any PHI nodes
// that might include it.
for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
(*SI)->removePredecessor(BB);
// Delete the old terminator instruction...
BB->getInstList().pop_back();
// Add a new return instruction of the appropriate type...
const Type *RetTy = BB->getParent()->getReturnType();
ReturnInst *RI = new ReturnInst(RetTy == Type::VoidTy ? 0 :
Constant::getNullValue(RetTy));
BB->getInstList().push_back(RI);
}
// The CFG Simplifier pass may delete one of the basic blocks we are
// interested in. If it does we need to take the block out of the list. Make
// a "persistent mapping" by turning basic blocks into <function, name> pairs.
// This won't work well if blocks are unnamed, but that is just the risk we
// have to take.
std::vector<std::pair<Function*, std::string> > BlockInfo;
for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
I != E; ++I)
BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
// Now run the CFG simplify pass on the function...
PassManager Passes;
Passes.add(createCFGSimplificationPass());
Passes.add(createVerifierPass());
Passes.run(*M);
// Try running on the hacked up program...
std::swap(BD.Program, M);
if (BD.runPasses(BD.PassesToRun)) {
delete M; // It crashed, keep the trimmed version...
// Make sure to use basic block pointers that point into the now-current
// module, and that they don't include any deleted blocks.
BBs.clear();
for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
SymbolTable::iterator I = ST.find(Type::LabelTy);
if (I != ST.end() && I->second.count(BlockInfo[i].second))
BBs.push_back(cast<BasicBlock>(I->second[BlockInfo[i].second]));
}
return true;
}
delete BD.Program; // It didn't crash, revert...
BD.Program = M;
return false;
}
/// debugCrash - This method is called when some pass crashes on input. It
/// attempts to prune down the testcase to something reasonable, and figure
/// out exactly which pass is crashing.
///
bool BugDriver::debugCrash() {
bool AnyReduction = false;
std::cout << "\n*** Debugging optimizer crash!\n";
// Reduce the list of passes which causes the optimizer to crash...
unsigned OldSize = PassesToRun.size();
DebugCrashes(*this).reduceList(PassesToRun);
std::cout << "\n*** Found crashing pass"
<< (PassesToRun.size() == 1 ? ": " : "es: ")
<< getPassesString(PassesToRun) << "\n";
EmitProgressBytecode("passinput");
// See if we can get away with nuking all of the global variable initializers
// in the program...
if (Program->gbegin() != Program->gend()) {
Module *M = CloneModule(Program);
bool DeletedInit = false;
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
if (I->hasInitializer()) {
I->setInitializer(0);
I->setLinkage(GlobalValue::ExternalLinkage);
DeletedInit = true;
}
if (!DeletedInit) {
delete M; // No change made...
} else {
// See if the program still causes a crash...
std::cout << "\nChecking to see if we can delete global inits: ";
std::swap(Program, M);
if (runPasses(PassesToRun)) { // Still crashes?
AnyReduction = true;
delete M;
std::cout << "\n*** Able to remove all global initializers!\n";
} else { // No longer crashes?
delete Program; // Restore program.
Program = M;
std::cout << " - Removing all global inits hides problem!\n";
}
}
}
// Now try to reduce the number of functions in the module to something small.
std::vector<Function*> Functions;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
if (!I->isExternal())
Functions.push_back(I);
if (Functions.size() > 1) {
std::cout << "\n*** Attempting to reduce the number of functions "
"in the testcase\n";
OldSize = Functions.size();
ReduceCrashingFunctions(*this).reduceList(Functions);
if (Functions.size() < OldSize) {
EmitProgressBytecode("reduced-function");
AnyReduction = true;
}
}
// Attempt to delete entire basic blocks at a time to speed up
// convergence... this actually works by setting the terminator of the blocks
// to a return instruction then running simplifycfg, which can potentially
// shrinks the code dramatically quickly
//
if (!DisableSimplifyCFG) {
std::vector<BasicBlock*> Blocks;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
for (Function::iterator FI = I->begin(), E = I->end(); FI != E; ++FI)
Blocks.push_back(FI);
ReduceCrashingBlocks(*this).reduceList(Blocks);
}
// FIXME: This should use the list reducer to converge faster by deleting
// larger chunks of instructions at a time!
unsigned Simplification = 4;
do {
--Simplification;
std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
<< "tions: Simplification Level #" << Simplification << "\n";
// Now that we have deleted the functions that are unnecessary for the
// program, try to remove instructions that are not necessary to cause the
// crash. To do this, we loop through all of the instructions in the
// remaining functions, deleting them (replacing any values produced with
// nulls), and then running ADCE and SimplifyCFG. If the transformed input
// still triggers failure, keep deleting until we cannot trigger failure
// anymore.
//
TryAgain:
// Loop over all of the (non-terminator) instructions remaining in the
// function, attempting to delete them.
for (Module::iterator FI = Program->begin(), E = Program->end();
FI != E; ++FI)
if (!FI->isExternal()) {
for (Function::iterator BI = FI->begin(), E = FI->end(); BI != E; ++BI)
for (BasicBlock::iterator I = BI->begin(), E = --BI->end();
I != E; ++I) {
Module *M = deleteInstructionFromProgram(I, Simplification);
// Make the function the current program...
std::swap(Program, M);
// Find out if the pass still crashes on this pass...
std::cout << "Checking instruction '" << I->getName() << "': ";
if (runPasses(PassesToRun)) {
// Yup, it does, we delete the old module, and continue trying to
// reduce the testcase...
delete M;
AnyReduction = true;
goto TryAgain; // I wish I had a multi-level break here!
}
// This pass didn't crash without this instruction, try the next
// one.
delete Program;
Program = M;
}
}
} while (Simplification);
// Try to clean up the testcase by running funcresolve and globaldce...
std::cout << "\n*** Attempting to perform final cleanups: ";
Module *M = performFinalCleanups();
std::swap(Program, M);
// Find out if the pass still crashes on the cleaned up program...
if (runPasses(PassesToRun)) {
// Yup, it does, keep the reduced version...
delete M;
AnyReduction = true;
} else {
delete Program; // Otherwise, restore the original module...
Program = M;
}
if (AnyReduction)
EmitProgressBytecode("reduced-simplified");
return false;
}
<commit_msg>Do not print out lists with thousands of elements in them, that's kinda silly<commit_after>//===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the bugpoint internals that narrow down compilation crashes
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "ListReducer.h"
#include "llvm/Constant.h"
#include "llvm/iTerminators.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/PassManager.h"
#include "llvm/SymbolTable.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bytecode/Writer.h"
#include "llvm/Support/CFG.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "Support/FileUtilities.h"
#include <fstream>
#include <set>
class DebugCrashes : public ListReducer<const PassInfo*> {
BugDriver &BD;
public:
DebugCrashes(BugDriver &bd) : BD(bd) {}
// doTest - Return true iff running the "removed" passes succeeds, and running
// the "Kept" passes fail when run on the output of the "removed" passes. If
// we return true, we update the current module of bugpoint.
//
virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
std::vector<const PassInfo*> &Kept);
};
DebugCrashes::TestResult
DebugCrashes::doTest(std::vector<const PassInfo*> &Prefix,
std::vector<const PassInfo*> &Suffix) {
std::string PrefixOutput;
Module *OrigProgram = 0;
if (!Prefix.empty()) {
std::cout << "Checking to see if these passes crash: "
<< getPassesString(Prefix) << ": ";
if (BD.runPasses(Prefix, PrefixOutput))
return KeepPrefix;
OrigProgram = BD.Program;
BD.Program = BD.ParseInputFile(PrefixOutput);
if (BD.Program == 0) {
std::cerr << BD.getToolName() << ": Error reading bytecode file '"
<< PrefixOutput << "'!\n";
exit(1);
}
removeFile(PrefixOutput);
}
std::cout << "Checking to see if these passes crash: "
<< getPassesString(Suffix) << ": ";
if (BD.runPasses(Suffix)) {
delete OrigProgram; // The suffix crashes alone...
return KeepSuffix;
}
// Nothing failed, restore state...
if (OrigProgram) {
delete BD.Program;
BD.Program = OrigProgram;
}
return NoFailure;
}
class ReduceCrashingFunctions : public ListReducer<Function*> {
BugDriver &BD;
public:
ReduceCrashingFunctions(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Kept) {
if (!Kept.empty() && TestFuncs(Kept))
return KeepSuffix;
if (!Prefix.empty() && TestFuncs(Prefix))
return KeepPrefix;
return NoFailure;
}
bool TestFuncs(std::vector<Function*> &Prefix);
};
bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
// Clone the program to try hacking it apart...
Module *M = CloneModule(BD.Program);
// Convert list to set for fast lookup...
std::set<Function*> Functions;
for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Function *CMF = M->getFunction(Funcs[i]->getName(),
Funcs[i]->getFunctionType());
assert(CMF && "Function not in module?!");
Functions.insert(CMF);
}
std::cout << "Checking for crash with only these functions:";
unsigned NumPrint = Funcs.size();
if (NumPrint > 10) NumPrint = 10;
for (unsigned i = 0; i != NumPrint; ++i)
std::cout << " " << Funcs[i]->getName();
if (NumPrint < Funcs.size())
std::cout << "... <" << Funcs.size() << " total>";
std::cout << ": ";
// Loop over and delete any functions which we aren't supposed to be playing
// with...
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->isExternal() && !Functions.count(I))
DeleteFunctionBody(I);
// Try running the hacked up program...
std::swap(BD.Program, M);
if (BD.runPasses(BD.PassesToRun)) {
delete M; // It crashed, keep the trimmed version...
// Make sure to use function pointers that point into the now-current
// module.
Funcs.assign(Functions.begin(), Functions.end());
return true;
}
delete BD.Program; // It didn't crash, revert...
BD.Program = M;
return false;
}
/// ReduceCrashingBlocks reducer - This works by setting the terminators of all
/// terminators except the specified basic blocks to a 'ret' instruction, then
/// running the simplify-cfg pass. This has the effect of chopping up the CFG
/// really fast which can reduce large functions quickly.
///
class ReduceCrashingBlocks : public ListReducer<BasicBlock*> {
BugDriver &BD;
public:
ReduceCrashingBlocks(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
std::vector<BasicBlock*> &Kept) {
if (!Kept.empty() && TestBlocks(Kept))
return KeepSuffix;
if (!Prefix.empty() && TestBlocks(Prefix))
return KeepPrefix;
return NoFailure;
}
bool TestBlocks(std::vector<BasicBlock*> &Prefix);
};
bool ReduceCrashingBlocks::TestBlocks(std::vector<BasicBlock*> &BBs) {
// Clone the program to try hacking it apart...
Module *M = CloneModule(BD.Program);
// Convert list to set for fast lookup...
std::set<BasicBlock*> Blocks;
for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
// Convert the basic block from the original module to the new module...
Function *F = BBs[i]->getParent();
Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
assert(CMF && "Function not in module?!");
// Get the mapped basic block...
Function::iterator CBI = CMF->begin();
std::advance(CBI, std::distance(F->begin(), Function::iterator(BBs[i])));
Blocks.insert(CBI);
}
std::cout << "Checking for crash with only these blocks:";
unsigned NumPrint = Blocks.size();
if (NumPrint > 10) NumPrint = 10;
for (unsigned i = 0, e = NumPrint; i != e; ++i)
std::cout << " " << BBs[i]->getName();
if (NumPrint < Blocks.size())
std::cout << "... <" << Blocks.size() << " total>";
std::cout << ": ";
// Loop over and delete any hack up any blocks that are not listed...
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
if (!Blocks.count(BB) && !isa<ReturnInst>(BB->getTerminator())) {
// Loop over all of the successors of this block, deleting any PHI nodes
// that might include it.
for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
(*SI)->removePredecessor(BB);
// Delete the old terminator instruction...
BB->getInstList().pop_back();
// Add a new return instruction of the appropriate type...
const Type *RetTy = BB->getParent()->getReturnType();
ReturnInst *RI = new ReturnInst(RetTy == Type::VoidTy ? 0 :
Constant::getNullValue(RetTy));
BB->getInstList().push_back(RI);
}
// The CFG Simplifier pass may delete one of the basic blocks we are
// interested in. If it does we need to take the block out of the list. Make
// a "persistent mapping" by turning basic blocks into <function, name> pairs.
// This won't work well if blocks are unnamed, but that is just the risk we
// have to take.
std::vector<std::pair<Function*, std::string> > BlockInfo;
for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
I != E; ++I)
BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
// Now run the CFG simplify pass on the function...
PassManager Passes;
Passes.add(createCFGSimplificationPass());
Passes.add(createVerifierPass());
Passes.run(*M);
// Try running on the hacked up program...
std::swap(BD.Program, M);
if (BD.runPasses(BD.PassesToRun)) {
delete M; // It crashed, keep the trimmed version...
// Make sure to use basic block pointers that point into the now-current
// module, and that they don't include any deleted blocks.
BBs.clear();
for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
SymbolTable::iterator I = ST.find(Type::LabelTy);
if (I != ST.end() && I->second.count(BlockInfo[i].second))
BBs.push_back(cast<BasicBlock>(I->second[BlockInfo[i].second]));
}
return true;
}
delete BD.Program; // It didn't crash, revert...
BD.Program = M;
return false;
}
/// debugCrash - This method is called when some pass crashes on input. It
/// attempts to prune down the testcase to something reasonable, and figure
/// out exactly which pass is crashing.
///
bool BugDriver::debugCrash() {
bool AnyReduction = false;
std::cout << "\n*** Debugging optimizer crash!\n";
// Reduce the list of passes which causes the optimizer to crash...
unsigned OldSize = PassesToRun.size();
DebugCrashes(*this).reduceList(PassesToRun);
std::cout << "\n*** Found crashing pass"
<< (PassesToRun.size() == 1 ? ": " : "es: ")
<< getPassesString(PassesToRun) << "\n";
EmitProgressBytecode("passinput");
// See if we can get away with nuking all of the global variable initializers
// in the program...
if (Program->gbegin() != Program->gend()) {
Module *M = CloneModule(Program);
bool DeletedInit = false;
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
if (I->hasInitializer()) {
I->setInitializer(0);
I->setLinkage(GlobalValue::ExternalLinkage);
DeletedInit = true;
}
if (!DeletedInit) {
delete M; // No change made...
} else {
// See if the program still causes a crash...
std::cout << "\nChecking to see if we can delete global inits: ";
std::swap(Program, M);
if (runPasses(PassesToRun)) { // Still crashes?
AnyReduction = true;
delete M;
std::cout << "\n*** Able to remove all global initializers!\n";
} else { // No longer crashes?
delete Program; // Restore program.
Program = M;
std::cout << " - Removing all global inits hides problem!\n";
}
}
}
// Now try to reduce the number of functions in the module to something small.
std::vector<Function*> Functions;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
if (!I->isExternal())
Functions.push_back(I);
if (Functions.size() > 1) {
std::cout << "\n*** Attempting to reduce the number of functions "
"in the testcase\n";
OldSize = Functions.size();
ReduceCrashingFunctions(*this).reduceList(Functions);
if (Functions.size() < OldSize) {
EmitProgressBytecode("reduced-function");
AnyReduction = true;
}
}
// Attempt to delete entire basic blocks at a time to speed up
// convergence... this actually works by setting the terminator of the blocks
// to a return instruction then running simplifycfg, which can potentially
// shrinks the code dramatically quickly
//
if (!DisableSimplifyCFG) {
std::vector<BasicBlock*> Blocks;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
for (Function::iterator FI = I->begin(), E = I->end(); FI != E; ++FI)
Blocks.push_back(FI);
ReduceCrashingBlocks(*this).reduceList(Blocks);
}
// FIXME: This should use the list reducer to converge faster by deleting
// larger chunks of instructions at a time!
unsigned Simplification = 4;
do {
--Simplification;
std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
<< "tions: Simplification Level #" << Simplification << "\n";
// Now that we have deleted the functions that are unnecessary for the
// program, try to remove instructions that are not necessary to cause the
// crash. To do this, we loop through all of the instructions in the
// remaining functions, deleting them (replacing any values produced with
// nulls), and then running ADCE and SimplifyCFG. If the transformed input
// still triggers failure, keep deleting until we cannot trigger failure
// anymore.
//
TryAgain:
// Loop over all of the (non-terminator) instructions remaining in the
// function, attempting to delete them.
for (Module::iterator FI = Program->begin(), E = Program->end();
FI != E; ++FI)
if (!FI->isExternal()) {
for (Function::iterator BI = FI->begin(), E = FI->end(); BI != E; ++BI)
for (BasicBlock::iterator I = BI->begin(), E = --BI->end();
I != E; ++I) {
Module *M = deleteInstructionFromProgram(I, Simplification);
// Make the function the current program...
std::swap(Program, M);
// Find out if the pass still crashes on this pass...
std::cout << "Checking instruction '" << I->getName() << "': ";
if (runPasses(PassesToRun)) {
// Yup, it does, we delete the old module, and continue trying to
// reduce the testcase...
delete M;
AnyReduction = true;
goto TryAgain; // I wish I had a multi-level break here!
}
// This pass didn't crash without this instruction, try the next
// one.
delete Program;
Program = M;
}
}
} while (Simplification);
// Try to clean up the testcase by running funcresolve and globaldce...
std::cout << "\n*** Attempting to perform final cleanups: ";
Module *M = performFinalCleanups();
std::swap(Program, M);
// Find out if the pass still crashes on the cleaned up program...
if (runPasses(PassesToRun)) {
// Yup, it does, keep the reduced version...
delete M;
AnyReduction = true;
} else {
delete Program; // Otherwise, restore the original module...
Program = M;
}
if (AnyReduction)
EmitProgressBytecode("reduced-simplified");
return false;
}
<|endoftext|>
|
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include <librealsense2/rs.hpp>
#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <thread>
#include <mutex>
#include <chrono>
#include <condition_variable>
#include "tclap/CmdLine.h"
#include "tclap/ValueArg.h"
using namespace TCLAP;
#define WAIT_FOR_DEVICE_TIMEOUT 10
#if _WIN32
#include <io.h>
#define ISATTY _isatty
#define FILENO _fileno
#else
#include <unistd.h>
#define ISATTY isatty
#define FILENO fileno
#endif
std::vector<uint8_t> read_fw_file(std::string file_path)
{
std::vector<uint8_t> rv;
std::ifstream file(file_path, std::ios::in | std::ios::binary | std::ios::ate);
if (file.is_open())
{
rv.resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read((char*)rv.data(), rv.size());
file.close();
}
return rv;
}
void print_device_info(rs2::device d)
{
std::map<rs2_camera_info, std::string> camera_info;
for (int i = 0; i < RS2_CAMERA_INFO_COUNT; i++)
{
auto info = (rs2_camera_info)i;
camera_info[info] = d.supports(info) ? d.get_info(info) : "unknown";
}
std::cout << "Name: " << camera_info[RS2_CAMERA_INFO_NAME] <<
", serial number: " << camera_info[RS2_CAMERA_INFO_SERIAL_NUMBER] <<
", update serial number: " << camera_info[RS2_CAMERA_INFO_FIRMWARE_UPDATE_ID] <<
", firmware version: " << camera_info[RS2_CAMERA_INFO_FIRMWARE_VERSION] <<
", USB type: " << camera_info[RS2_CAMERA_INFO_USB_TYPE_DESCRIPTOR] << std::endl;
}
std::vector<uint8_t> read_firmware_data(bool is_set, const std::string& file_path)
{
if (!is_set)
{
throw rs2::error("firmware file must be selected");
}
std::vector<uint8_t> fw_image = read_fw_file(file_path);
if (fw_image.size() == 0)
{
throw rs2::error("failed to read firmware file");
}
return fw_image;
}
void update(rs2::update_device fwu_dev, std::vector<uint8_t> fw_image)
{
std::cout << std::endl << "firmware update started"<< std::endl << std::endl;
if (ISATTY(FILENO(stdout)))
{
fwu_dev.update(fw_image, [&](const float progress)
{
printf("\rfirmware update progress: %d[%%]", (int)(progress * 100));
});
}
else
fwu_dev.update(fw_image, [&](const float progress){});
std::cout << std::endl << std::endl << "firmware update done" << std::endl;
}
void list_devices(rs2::context ctx)
{
auto devs = ctx.query_devices();
if (devs.size() == 0)
{
std::cout << std::endl << "there are no connected devices" << std::endl;
return;
}
std::cout << std::endl << "connected devices:" << std::endl;
int counter = 0;
for (auto&& d : devs)
{
std::cout << ++counter << ") ";
print_device_info(d);
}
}
int main(int argc, char** argv) try
{
#ifdef BUILD_EASYLOGGINGPP
rs2::log_to_console(RS2_LOG_SEVERITY_ERROR);
#endif
rs2::context ctx;
std::condition_variable cv;
std::mutex mutex;
std::string selected_serial_number;
rs2::device new_device;
rs2::update_device new_fw_update_device;
bool done = false;
CmdLine cmd("librealsense rs-fw-update tool", ' ', RS2_API_VERSION_STR);
SwitchArg list_devices_arg("l", "list_devices", "List all available devices");
SwitchArg recover_arg("r", "recover", "Recover all connected devices which are in recovery mode");
SwitchArg unsigned_arg("u", "unsigned", "Update unsigned firmware, available only for unlocked cameras");
ValueArg<std::string> backup_arg("b", "backup", "Create a backup to the camera flash and saved it to the given path", false, "", "string");
ValueArg<std::string> file_arg("f", "file", "Path of the firmware image file", false, "", "string");
ValueArg<std::string> serial_number_arg("s", "serial_number", "The serial number of the device to be update, this is mandetory if more than one device is connected", false, "", "string");
cmd.add(list_devices_arg);
cmd.add(recover_arg);
cmd.add(unsigned_arg);
cmd.add(file_arg);
cmd.add(serial_number_arg);
cmd.add(backup_arg);
cmd.parse(argc, argv);
bool recovery_request = recover_arg.getValue();
if (list_devices_arg.isSet())
{
list_devices(ctx);
return EXIT_SUCCESS;
}
if (!file_arg.isSet() && !backup_arg.isSet())
{
std::cout << std::endl << "nothing to do, run again with -h for help" << std::endl;
return EXIT_FAILURE;
}
if (serial_number_arg.isSet())
{
selected_serial_number = serial_number_arg.getValue();
std::cout << std::endl << "search for device with serial number: " << selected_serial_number << std::endl;
}
std::string update_serial_number;
// Recovery
bool recovery_executed = false;
if (recover_arg.isSet() )
{
std::vector<uint8_t> fw_image = read_firmware_data(file_arg.isSet(), file_arg.getValue());
std::cout << std::endl << "update to FW: " << file_arg.getValue() << std::endl;
auto devs = ctx.query_devices(RS2_PRODUCT_LINE_DEPTH);
for (auto&& d : devs)
{
if (!d.is<rs2::update_device>())
continue;
try
{
std::cout << std::endl << "recovering device: " << std::endl;
print_device_info(d);
update(d, fw_image);
recovery_executed = true;
}
catch (...)
{
std::cout << std::endl << "failed to recover device" << std::endl;
}
}
if (recovery_executed)
{
std::cout << std::endl << "recovery done" << std::endl;
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
// Update device
ctx.set_devices_changed_callback([&](rs2::event_information& info)
{
if (info.get_new_devices().size() == 0)
{
return;
}
for (auto&& d : info.get_new_devices())
{
std::lock_guard<std::mutex> lk(mutex);
if (d.is<rs2::update_device>() && (d.get_info(RS2_CAMERA_INFO_FIRMWARE_UPDATE_ID) == update_serial_number))
new_fw_update_device = d;
else
new_device = d;
}
if(new_fw_update_device || new_device)
cv.notify_one();
});
auto devs = ctx.query_devices(RS2_PRODUCT_LINE_DEPTH);
if (!serial_number_arg.isSet() && devs.size() > 1)
{
std::cout << std::endl << "more than one device is connected, serial number must be selected" << std::endl << std::endl;
return EXIT_FAILURE;
}
bool device_found = false;
for (auto&& d : devs)
{
if (!d.is<rs2::updatable>() || !(d.supports(RS2_CAMERA_INFO_SERIAL_NUMBER) && d.supports(RS2_CAMERA_INFO_FIRMWARE_UPDATE_ID)))
continue;
if (d.supports(RS2_CAMERA_INFO_USB_TYPE_DESCRIPTOR))
{
std::string usb_type = d.get_info(RS2_CAMERA_INFO_USB_TYPE_DESCRIPTOR);
if (usb_type.find("2.") != std::string::npos) {
std::cout << std::endl << "Warning! the camera is connected via USB 2 port, in case the process fails, connect the camera to a USB 3 port and try again" << std::endl;
}
}
update_serial_number = d.get_info(RS2_CAMERA_INFO_FIRMWARE_UPDATE_ID);
auto sn = d.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);
if (sn != selected_serial_number && devs.size() != 1)
continue;
device_found = true;
auto fw = d.get_info(RS2_CAMERA_INFO_FIRMWARE_VERSION);
if (backup_arg.isSet())
{
std::cout << std::endl << "backing-up device flash: " << std::endl;
if (ISATTY(FILENO(stdout)))
{
auto flash = d.as<rs2::updatable>().create_flash_backup([&](const float progress)
{
printf("\rflash backup progress: %d[%%]", (int)(progress * 100));
});
}
else
auto flash = d.as<rs2::updatable>().create_flash_backup([&](const float progress){});
auto temp = backup_arg.getValue();
std::ofstream file(temp.c_str(), std::ios::binary);
file.write((const char*)flash.data(), flash.size());
}
if (!file_arg.isSet())
continue;
std::vector<uint8_t> fw_image = read_firmware_data(file_arg.isSet(), file_arg.getValue());
std::cout << std::endl << "updating device: " << std::endl;
print_device_info(d);
if (unsigned_arg.isSet())
{
std::cout << std::endl << "firmware update started" << std::endl << std::endl;
if (ISATTY(FILENO(stdout)))
{
d.as<rs2::updatable>().update_unsigned(fw_image, [&](const float progress)
{
printf("\rfirmware update progress: %d[%%]", (int)(progress * 100));
});
}
else
d.as<rs2::updatable>().update_unsigned(fw_image, [&](const float progress){});
std::cout << std::endl << std::endl << "firmware update done" << std::endl;
}
else
{
d.as<rs2::updatable>().enter_update_state();
std::unique_lock<std::mutex> lk(mutex);
if (!cv.wait_for(lk, std::chrono::seconds(WAIT_FOR_DEVICE_TIMEOUT), [&] { return new_fw_update_device; }))
{
std::cout << std::endl << "failed to locate a device in FW update mode" << std::endl;
return EXIT_FAILURE;
}
update(new_fw_update_device, fw_image);
done = true;
break;
}
}
if (!device_found)
{
if(serial_number_arg.isSet())
std::cout << std::endl << "couldn't find the requested serial number" << std::endl;
else if (devs.size() == 1)
{
std::cout << std::endl << "nothing to do, run again with -h for help" << std::endl;
}
return EXIT_FAILURE;
}
std::unique_lock<std::mutex> lk(mutex);
cv.wait_for(lk, std::chrono::seconds(WAIT_FOR_DEVICE_TIMEOUT), [&] { return !done || new_device; });
if (done)
{
auto devs = ctx.query_devices();
for (auto&& d : devs)
{
auto sn = d.supports(RS2_CAMERA_INFO_SERIAL_NUMBER) ? d.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER) : "unknown";
if (serial_number_arg.isSet() && sn != selected_serial_number)
continue;
auto fw = d.supports(RS2_CAMERA_INFO_FIRMWARE_VERSION) ? d.get_info(RS2_CAMERA_INFO_FIRMWARE_VERSION) : "unknown";
std::cout << std::endl << "device " << sn << " successfully updated to FW: " << fw << std::endl;
}
}
return EXIT_SUCCESS;
}
catch (const rs2::error & e)
{
std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl;
return EXIT_FAILURE;
}
<commit_msg>fix for bug<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include <librealsense2/rs.hpp>
#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <thread>
#include <mutex>
#include <chrono>
#include <condition_variable>
#include "tclap/CmdLine.h"
#include "tclap/ValueArg.h"
using namespace TCLAP;
#define WAIT_FOR_DEVICE_TIMEOUT 10
#if _WIN32
#include <io.h>
#define ISATTY _isatty
#define FILENO _fileno
#else
#include <unistd.h>
#define ISATTY isatty
#define FILENO fileno
#endif
std::vector<uint8_t> read_fw_file(std::string file_path)
{
std::vector<uint8_t> rv;
std::ifstream file(file_path, std::ios::in | std::ios::binary | std::ios::ate);
if (file.is_open())
{
rv.resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read((char*)rv.data(), rv.size());
file.close();
}
return rv;
}
void print_device_info(rs2::device d)
{
std::map<rs2_camera_info, std::string> camera_info;
for (int i = 0; i < RS2_CAMERA_INFO_COUNT; i++)
{
auto info = (rs2_camera_info)i;
camera_info[info] = d.supports(info) ? d.get_info(info) : "unknown";
}
std::cout << "Name: " << camera_info[RS2_CAMERA_INFO_NAME] <<
", serial number: " << camera_info[RS2_CAMERA_INFO_SERIAL_NUMBER] <<
", update serial number: " << camera_info[RS2_CAMERA_INFO_FIRMWARE_UPDATE_ID] <<
", firmware version: " << camera_info[RS2_CAMERA_INFO_FIRMWARE_VERSION] <<
", USB type: " << camera_info[RS2_CAMERA_INFO_USB_TYPE_DESCRIPTOR] << std::endl;
}
std::vector<uint8_t> read_firmware_data(bool is_set, const std::string& file_path)
{
if (!is_set)
{
throw rs2::error("firmware file must be selected");
}
std::vector<uint8_t> fw_image = read_fw_file(file_path);
if (fw_image.size() == 0)
{
throw rs2::error("failed to read firmware file");
}
return fw_image;
}
void update(rs2::update_device fwu_dev, std::vector<uint8_t> fw_image)
{
std::cout << std::endl << "firmware update started"<< std::endl << std::endl;
if (ISATTY(FILENO(stdout)))
{
fwu_dev.update(fw_image, [&](const float progress)
{
printf("\rfirmware update progress: %d[%%]", (int)(progress * 100));
});
}
else
fwu_dev.update(fw_image, [&](const float progress){});
std::cout << std::endl << std::endl << "firmware update done" << std::endl;
}
void list_devices(rs2::context ctx)
{
auto devs = ctx.query_devices();
if (devs.size() == 0)
{
std::cout << std::endl << "there are no connected devices" << std::endl;
return;
}
std::cout << std::endl << "connected devices:" << std::endl;
int counter = 0;
for (auto&& d : devs)
{
std::cout << ++counter << ") ";
print_device_info(d);
}
}
int main(int argc, char** argv) try
{
#ifdef BUILD_EASYLOGGINGPP
rs2::log_to_console(RS2_LOG_SEVERITY_ERROR);
#endif
rs2::context ctx;
std::condition_variable cv;
std::mutex mutex;
std::string selected_serial_number;
rs2::device new_device;
rs2::update_device new_fw_update_device;
bool done = false;
CmdLine cmd("librealsense rs-fw-update tool", ' ', RS2_API_VERSION_STR);
SwitchArg list_devices_arg("l", "list_devices", "List all available devices");
SwitchArg recover_arg("r", "recover", "Recover all connected devices which are in recovery mode");
SwitchArg unsigned_arg("u", "unsigned", "Update unsigned firmware, available only for unlocked cameras");
ValueArg<std::string> backup_arg("b", "backup", "Create a backup to the camera flash and saved it to the given path", false, "", "string");
ValueArg<std::string> file_arg("f", "file", "Path of the firmware image file", false, "", "string");
ValueArg<std::string> serial_number_arg("s", "serial_number", "The serial number of the device to be update, this is mandetory if more than one device is connected", false, "", "string");
cmd.add(list_devices_arg);
cmd.add(recover_arg);
cmd.add(unsigned_arg);
cmd.add(file_arg);
cmd.add(serial_number_arg);
cmd.add(backup_arg);
cmd.parse(argc, argv);
bool recovery_request = recover_arg.getValue();
if (list_devices_arg.isSet())
{
list_devices(ctx);
return EXIT_SUCCESS;
}
if (!file_arg.isSet() && !backup_arg.isSet())
{
std::cout << std::endl << "nothing to do, run again with -h for help" << std::endl;
return EXIT_FAILURE;
}
if (serial_number_arg.isSet())
{
selected_serial_number = serial_number_arg.getValue();
std::cout << std::endl << "search for device with serial number: " << selected_serial_number << std::endl;
}
std::string update_serial_number;
// Recovery
bool recovery_executed = false;
if (recover_arg.isSet() )
{
std::vector<uint8_t> fw_image = read_firmware_data(file_arg.isSet(), file_arg.getValue());
std::cout << std::endl << "update to FW: " << file_arg.getValue() << std::endl;
auto devs = ctx.query_devices(RS2_PRODUCT_LINE_DEPTH);
for (auto&& d : devs)
{
if (!d.is<rs2::update_device>())
continue;
try
{
std::cout << std::endl << "recovering device: " << std::endl;
print_device_info(d);
update(d, fw_image);
recovery_executed = true;
}
catch (...)
{
std::cout << std::endl << "failed to recover device" << std::endl;
}
}
if (recovery_executed)
{
std::cout << std::endl << "recovery done" << std::endl;
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
// Update device
ctx.set_devices_changed_callback([&](rs2::event_information& info)
{
if (info.get_new_devices().size() == 0)
{
return;
}
for (auto&& d : info.get_new_devices())
{
std::lock_guard<std::mutex> lk(mutex);
if (d.is<rs2::update_device>() && (d.get_info(RS2_CAMERA_INFO_FIRMWARE_UPDATE_ID) == update_serial_number))
new_fw_update_device = d;
else
new_device = d;
}
if(new_fw_update_device || new_device)
cv.notify_one();
});
auto devs = ctx.query_devices(RS2_PRODUCT_LINE_DEPTH);
if (!serial_number_arg.isSet() && devs.size() > 1)
{
std::cout << std::endl << "more than one device is connected, serial number must be selected" << std::endl << std::endl;
return EXIT_FAILURE;
}
bool device_found = false;
for (auto&& d : devs)
{
if (!d.is<rs2::updatable>() || !(d.supports(RS2_CAMERA_INFO_SERIAL_NUMBER) && d.supports(RS2_CAMERA_INFO_FIRMWARE_UPDATE_ID)))
continue;
if (d.supports(RS2_CAMERA_INFO_USB_TYPE_DESCRIPTOR))
{
std::string usb_type = d.get_info(RS2_CAMERA_INFO_USB_TYPE_DESCRIPTOR);
if (usb_type.find("2.") != std::string::npos) {
std::cout << std::endl << "Warning! the camera is connected via USB 2 port, in case the process fails, connect the camera to a USB 3 port and try again" << std::endl;
}
}
update_serial_number = d.get_info(RS2_CAMERA_INFO_FIRMWARE_UPDATE_ID);
auto sn = d.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);
if (sn != selected_serial_number && devs.size() != 1)
continue;
device_found = true;
auto fw = d.get_info(RS2_CAMERA_INFO_FIRMWARE_VERSION);
if (backup_arg.isSet())
{
std::cout << std::endl << "backing-up device flash: " << std::endl;
std::vector< uint8_t > flash;
if( ISATTY( FILENO( stdout )))
{
flash = d.as< rs2::updatable >().create_flash_backup( [&]( const float progress ) {
printf( "\rflash backup progress: %d[%%]", (int)( progress * 100 ) );
} );
}
else
flash = d.as<rs2::updatable>().create_flash_backup([&](const float progress){});
auto temp = backup_arg.getValue();
std::ofstream file(temp.c_str(), std::ios::binary);
file.write((const char*)flash.data(), flash.size());
}
if (!file_arg.isSet())
continue;
std::vector<uint8_t> fw_image = read_firmware_data(file_arg.isSet(), file_arg.getValue());
std::cout << std::endl << "updating device: " << std::endl;
print_device_info(d);
if (unsigned_arg.isSet())
{
std::cout << std::endl << "firmware update started" << std::endl << std::endl;
if (ISATTY(FILENO(stdout)))
{
d.as<rs2::updatable>().update_unsigned(fw_image, [&](const float progress)
{
printf("\rfirmware update progress: %d[%%]", (int)(progress * 100));
});
}
else
d.as<rs2::updatable>().update_unsigned(fw_image, [&](const float progress){});
std::cout << std::endl << std::endl << "firmware update done" << std::endl;
}
else
{
d.as<rs2::updatable>().enter_update_state();
std::unique_lock<std::mutex> lk(mutex);
if (!cv.wait_for(lk, std::chrono::seconds(WAIT_FOR_DEVICE_TIMEOUT), [&] { return new_fw_update_device; }))
{
std::cout << std::endl << "failed to locate a device in FW update mode" << std::endl;
return EXIT_FAILURE;
}
update(new_fw_update_device, fw_image);
done = true;
break;
}
}
if (!device_found)
{
if(serial_number_arg.isSet())
std::cout << std::endl << "couldn't find the requested serial number" << std::endl;
else if (devs.size() == 1)
{
std::cout << std::endl << "nothing to do, run again with -h for help" << std::endl;
}
return EXIT_FAILURE;
}
std::unique_lock<std::mutex> lk(mutex);
cv.wait_for(lk, std::chrono::seconds(WAIT_FOR_DEVICE_TIMEOUT), [&] { return !done || new_device; });
if (done)
{
auto devs = ctx.query_devices();
for (auto&& d : devs)
{
auto sn = d.supports(RS2_CAMERA_INFO_SERIAL_NUMBER) ? d.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER) : "unknown";
if (serial_number_arg.isSet() && sn != selected_serial_number)
continue;
auto fw = d.supports(RS2_CAMERA_INFO_FIRMWARE_VERSION) ? d.get_info(RS2_CAMERA_INFO_FIRMWARE_VERSION) : "unknown";
std::cout << std::endl << "device " << sn << " successfully updated to FW: " << fw << std::endl;
}
}
return EXIT_SUCCESS;
}
catch (const rs2::error & e)
{
std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl;
return EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before>#include "rsys/common.h"
#include "rsys/host.h"
#include "rsys/vdriver.h"
#include "rsys/cquick.h" /* for ROMlib_log2 */
#include "rsys/adb.h"
#include "rsys/osevent.h"
#include "rsys/scrap.h"
#include "rsys/keyboard.h"
#include "OSEvent.h"
#include "ToolboxEvent.h"
#include "SegmentLdr.h"
#include "ScrapMgr.h"
#include "keycode_map.h"
#include <SDL.h>
namespace Executor
{
/* These variables are required by the vdriver interface. */
uint8_t *vdriver_fbuf;
int vdriver_row_bytes;
int vdriver_width = 1024;
int vdriver_height = 768;
int vdriver_bpp = 8, vdriver_log2_bpp;
int vdriver_max_bpp, vdriver_log2_max_bpp;
vdriver_modes_t *vdriver_mode_list;
int host_cursor_depth = 1;
}
using namespace Executor;
namespace
{
vdriver_modes_t sdl_impotent_modes = { 0, 0 };
SDL_Window *sdlWindow;
SDL_Renderer *sdlRenderer;
SDL_Texture *sdlTexture;
SDL_Surface *sdlSurface;
}
void Executor::vdriver_opt_register(void)
{
}
bool Executor::vdriver_init(int _max_width, int _max_height, int _max_bpp,
bool fixed_p, int *argc, char *argv[])
{
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0)
{
SDL_Log("Failed to initialize SDL: %s", SDL_GetError());
return false;
}
return true;
}
bool Executor::vdriver_acceptable_mode_p(int width, int height, int bpp,
bool grayscale_p, bool exact_match_p)
{
if(bpp == 1 || bpp == 4 || bpp == 8 || bpp == 16 || bpp == 32)
return true;
else
return false;
}
bool Executor::vdriver_set_mode(int width, int height, int bpp, bool grayscale_p)
{
printf("set_mode: %d %d %d", width, height, bpp);
if(vdriver_fbuf)
delete[] vdriver_fbuf;
if(width)
vdriver_width = width;
if(height)
vdriver_height = height;
if(bpp)
vdriver_bpp = bpp;
vdriver_row_bytes = vdriver_width * vdriver_bpp / 8;
vdriver_log2_bpp = ROMlib_log2[vdriver_bpp];
vdriver_mode_list = &sdl_impotent_modes;
vdriver_max_bpp = 8; //32;
vdriver_log2_max_bpp = 3; //5;
sdlWindow = SDL_CreateWindow("Window",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
vdriver_width, vdriver_height,
0);
//SDL_WINDOW_FULLSCREEN_DESKTOP);
/*sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, 0);
SDL_RenderSetLogicalSize(sdlRenderer, vdriver_width, vdriver_height);
SDL_SetRenderDrawColor(sdlRenderer, 128, 128, 128, 255);
SDL_RenderClear(sdlRenderer);
SDL_RenderPresent(sdlRenderer);*/
uint32_t pixelFormat;
switch(vdriver_bpp)
{
case 1:
pixelFormat = SDL_PIXELFORMAT_INDEX1LSB;
break;
case 4:
pixelFormat = SDL_PIXELFORMAT_INDEX4LSB;
break;
case 8:
pixelFormat = SDL_PIXELFORMAT_INDEX8;
break;
case 16:
pixelFormat = SDL_PIXELFORMAT_RGB555;
break;
case 32:
pixelFormat = SDL_PIXELFORMAT_BGRX8888;
break;
default:
std::abort();
}
vdriver_fbuf = new uint8_t[vdriver_width * vdriver_height * 4];
sdlSurface = SDL_CreateRGBSurfaceWithFormatFrom(
vdriver_fbuf,
vdriver_width, vdriver_height,
vdriver_bpp,
vdriver_row_bytes,
pixelFormat);
return true;
}
void Executor::vdriver_set_colors(int first_color, int num_colors, const ColorSpec *colors)
{
SDL_Color *sdlColors = (SDL_Color *)alloca(sizeof(SDL_Color) * num_colors);
for(int i = 0; i < num_colors; i++)
{
sdlColors[i].a = 255;
sdlColors[i].r = CW(colors[i].rgb.red) >> 8;
sdlColors[i].g = CW(colors[i].rgb.green) >> 8;
sdlColors[i].b = CW(colors[i].rgb.blue) >> 8;
}
SDL_SetPaletteColors(sdlSurface->format->palette, sdlColors, first_color, num_colors);
}
void Executor::vdriver_get_colors(int first_color, int num_colors, ColorSpec *colors)
{
SDL_Color *sdlColors = sdlSurface->format->palette->colors;
for(int i = 0; i < num_colors; i++)
{
SDL_Color &c = sdlColors[first_color + i];
colors[i].value = CW(first_color + i);
colors[i].rgb.red = CW(c.r << 8 | c.r);
colors[i].rgb.green = CW(c.g << 8 | c.g);
colors[i].rgb.blue = CW(c.b << 8 | c.b);
}
}
int Executor::vdriver_update_screen_rects(int num_rects, const vdriver_rect_t *r,
bool cursor_p)
{
/*SDL_UpdateTexture(sdlTexture, NULL, vdriver_fbuf, vdriver_row_bytes);
SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);
SDL_RenderPresent(sdlRenderer);*/
SDL_BlitSurface(sdlSurface, NULL, SDL_GetWindowSurface(sdlWindow), NULL);
SDL_UpdateWindowSurface(sdlWindow);
}
int Executor::vdriver_update_screen(int top, int left, int bottom, int right,
bool cursor_p)
{
/*SDL_UpdateTexture(sdlTexture, NULL, vdriver_fbuf, vdriver_row_bytes);
SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);
SDL_RenderPresent(sdlRenderer);*/
SDL_BlitSurface(sdlSurface, NULL, SDL_GetWindowSurface(sdlWindow), NULL);
SDL_UpdateWindowSurface(sdlWindow);
}
void Executor::vdriver_flush_display(void)
{
}
void Executor::vdriver_shutdown(void)
{
}
void Executor::host_flush_shadow_screen(void)
{
}
static bool ConfirmQuit()
{
const SDL_MessageBoxButtonData buttons[] = {
{ SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, 2, "Cancel" },
{ SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, 1, "Force Quit" },
};
const SDL_MessageBoxData messageboxdata = {
SDL_MESSAGEBOX_INFORMATION, /* .flags */
sdlWindow, /* .window */
"Quit", /* .title */
"Do you want to quit Executor?", /* .message */
SDL_arraysize(buttons), /* .numbuttons */
buttons, /* .buttons */
NULL /* .colorScheme */
};
int buttonid;
SDL_ShowMessageBox(&messageboxdata, &buttonid);
return buttonid == 1;
}
static bool isModifier(unsigned char virt, uint16 *modstore)
{
/* Note: shift and control can be cleared if right* and left* are pressed */
switch(virt)
{
case MKV_LEFTSHIFT:
case MKV_RIGHTSHIFT:
*modstore = shiftKey;
break;
case MKV_CAPS:
*modstore = alphaLock;
break;
case MKV_LEFTCNTL:
case MKV_RIGHTCNTL:
*modstore = ControlKey;
break;
case MKV_CLOVER:
*modstore = cmdKey;
break;
case MKV_LEFTOPTION:
case MKV_RIGHTOPTION:
*modstore = optionKey;
break;
default:
*modstore = 0;
return false;
}
return true;
}
void Executor::vdriver_pump_events()
{
SDL_Event event;
static uint16_t keymod = 0;
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_MOUSEMOTION:
MouseLocation.h = CW(event.motion.x);
MouseLocation.v = CW(event.motion.y);
adb_apeiron_hack(false);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
{
bool down_p;
int32 when;
Point where;
down_p = (event.button.state == SDL_PRESSED);
if(down_p)
keymod &= ~btnState;
else
keymod |= btnState;
when = TickCount();
where.h = event.button.x;
where.v = event.button.y;
ROMlib_PPostEvent(down_p ? mouseDown : mouseUp,
0, (GUEST<EvQElPtr> *)0, when, where,
keymod);
adb_apeiron_hack(false);
}
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
{
bool down_p;
unsigned char mkvkey;
uint16 mod;
LONGINT keywhat;
int32 when;
Point where;
init_sdlk_to_mkv();
down_p = (event.key.state == SDL_PRESSED);
/*if(use_scan_codes)
mkvkey = ibm_virt_to_mac_virt[event.key.keysym.scancode];
else*/
{
auto p = sdlk_to_mkv.find(event.key.keysym.sym);
if(p == sdlk_to_mkv.end())
mkvkey = NOTAKEY;
else
mkvkey = p->second;
}
mkvkey = ROMlib_right_to_left_key_map(mkvkey);
if(isModifier(mkvkey, &mod))
{
if(down_p)
keymod |= mod;
else
keymod &= ~mod;
}
when = TickCount();
where.h = CW(MouseLocation.h);
where.v = CW(MouseLocation.v);
keywhat = ROMlib_xlate(mkvkey, keymod, down_p);
post_keytrans_key_events(down_p ? keyDown : keyUp,
keywhat, when, where,
keymod, mkvkey);
}
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
//if(!we_lost_clipboard())
sendresumeevent(false);
//else
//{
// ZeroScrap();
// sendresumeevent(true);
//}
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
sendsuspendevent();
break;
case SDL_QUIT:
if(ConfirmQuit())
ExitToShell();
break;
}
}
}
extern "C" void
ROMlib_SetTitle(char *title)
{
}
extern "C" char *
ROMlib_GetTitle(void)
{
static char str[] = "Foo";
return str;
}
extern "C" void
ROMlib_FreeTitle(char *title)
{
}
/* This is really inefficient. We should hash the cursors */
void Executor::host_set_cursor(char *cursor_data,
unsigned short cursor_mask[16],
int hotspot_x, int hotspot_y)
{
SDL_Cursor *old_cursor, *new_cursor;
old_cursor = SDL_GetCursor();
new_cursor = SDL_CreateCursor((unsigned char *)cursor_data,
(unsigned char *)cursor_mask,
16, 16, hotspot_x, hotspot_y);
if(new_cursor != NULL)
{
SDL_SetCursor(new_cursor);
SDL_FreeCursor(old_cursor);
}
}
int Executor::host_set_cursor_visible(int show_p)
{
return (SDL_ShowCursor(show_p));
}
<commit_msg>sdl2: SDL_CreateRGBSurfaceWithFormatFrom is only available starting in sdl 2.0.5, be conservative and use PixelFormatEnumToMasks and CreateRGBSurfaceFrom instead<commit_after>#include "rsys/common.h"
#include "rsys/host.h"
#include "rsys/vdriver.h"
#include "rsys/cquick.h" /* for ROMlib_log2 */
#include "rsys/adb.h"
#include "rsys/osevent.h"
#include "rsys/scrap.h"
#include "rsys/keyboard.h"
#include "OSEvent.h"
#include "ToolboxEvent.h"
#include "SegmentLdr.h"
#include "ScrapMgr.h"
#include "keycode_map.h"
#include <SDL.h>
namespace Executor
{
/* These variables are required by the vdriver interface. */
uint8_t *vdriver_fbuf;
int vdriver_row_bytes;
int vdriver_width = 1024;
int vdriver_height = 768;
int vdriver_bpp = 8, vdriver_log2_bpp;
int vdriver_max_bpp, vdriver_log2_max_bpp;
vdriver_modes_t *vdriver_mode_list;
int host_cursor_depth = 1;
}
using namespace Executor;
namespace
{
vdriver_modes_t sdl_impotent_modes = { 0, 0 };
SDL_Window *sdlWindow;
SDL_Renderer *sdlRenderer;
SDL_Texture *sdlTexture;
SDL_Surface *sdlSurface;
}
void Executor::vdriver_opt_register(void)
{
}
bool Executor::vdriver_init(int _max_width, int _max_height, int _max_bpp,
bool fixed_p, int *argc, char *argv[])
{
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0)
{
SDL_Log("Failed to initialize SDL: %s", SDL_GetError());
return false;
}
return true;
}
bool Executor::vdriver_acceptable_mode_p(int width, int height, int bpp,
bool grayscale_p, bool exact_match_p)
{
if(bpp == 1 || bpp == 4 || bpp == 8 || bpp == 16 || bpp == 32)
return true;
else
return false;
}
bool Executor::vdriver_set_mode(int width, int height, int bpp, bool grayscale_p)
{
printf("set_mode: %d %d %d", width, height, bpp);
if(vdriver_fbuf)
delete[] vdriver_fbuf;
if(width)
vdriver_width = width;
if(height)
vdriver_height = height;
if(bpp)
vdriver_bpp = bpp;
vdriver_row_bytes = vdriver_width * vdriver_bpp / 8;
vdriver_log2_bpp = ROMlib_log2[vdriver_bpp];
vdriver_mode_list = &sdl_impotent_modes;
vdriver_max_bpp = 8; //32;
vdriver_log2_max_bpp = 3; //5;
sdlWindow = SDL_CreateWindow("Window",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
vdriver_width, vdriver_height,
0);
//SDL_WINDOW_FULLSCREEN_DESKTOP);
/*sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, 0);
SDL_RenderSetLogicalSize(sdlRenderer, vdriver_width, vdriver_height);
SDL_SetRenderDrawColor(sdlRenderer, 128, 128, 128, 255);
SDL_RenderClear(sdlRenderer);
SDL_RenderPresent(sdlRenderer);*/
uint32_t pixelFormat;
switch(vdriver_bpp)
{
case 1:
pixelFormat = SDL_PIXELFORMAT_INDEX1LSB;
break;
case 4:
pixelFormat = SDL_PIXELFORMAT_INDEX4LSB;
break;
case 8:
pixelFormat = SDL_PIXELFORMAT_INDEX8;
break;
case 16:
pixelFormat = SDL_PIXELFORMAT_RGB555;
break;
case 32:
pixelFormat = SDL_PIXELFORMAT_BGRX8888;
break;
default:
std::abort();
}
vdriver_fbuf = new uint8_t[vdriver_width * vdriver_height * 4];
#if 1
uint32_t rmask, gmask, bmask, amask;
int sdlBpp;
SDL_PixelFormatEnumToMasks(pixelFormat, &sdlBpp, &rmask, &gmask, &bmask, &amask);
sdlSurface = SDL_CreateRGBSurfaceFrom(
vdriver_fbuf,
vdriver_width, vdriver_height,
sdlBpp,
vdriver_row_bytes,
rmask, gmask, bmask, amask);
#else
sdlSurface = SDL_CreateRGBSurfaceWithFormatFrom(
vdriver_fbuf,
vdriver_width, vdriver_height,
vdriver_bpp,
vdriver_row_bytes,
pixelFormat);
#endif
return true;
}
void Executor::vdriver_set_colors(int first_color, int num_colors, const ColorSpec *colors)
{
SDL_Color *sdlColors = (SDL_Color *)alloca(sizeof(SDL_Color) * num_colors);
for(int i = 0; i < num_colors; i++)
{
sdlColors[i].a = 255;
sdlColors[i].r = CW(colors[i].rgb.red) >> 8;
sdlColors[i].g = CW(colors[i].rgb.green) >> 8;
sdlColors[i].b = CW(colors[i].rgb.blue) >> 8;
}
SDL_SetPaletteColors(sdlSurface->format->palette, sdlColors, first_color, num_colors);
}
void Executor::vdriver_get_colors(int first_color, int num_colors, ColorSpec *colors)
{
SDL_Color *sdlColors = sdlSurface->format->palette->colors;
for(int i = 0; i < num_colors; i++)
{
SDL_Color &c = sdlColors[first_color + i];
colors[i].value = CW(first_color + i);
colors[i].rgb.red = CW(c.r << 8 | c.r);
colors[i].rgb.green = CW(c.g << 8 | c.g);
colors[i].rgb.blue = CW(c.b << 8 | c.b);
}
}
int Executor::vdriver_update_screen_rects(int num_rects, const vdriver_rect_t *r,
bool cursor_p)
{
/*SDL_UpdateTexture(sdlTexture, NULL, vdriver_fbuf, vdriver_row_bytes);
SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);
SDL_RenderPresent(sdlRenderer);*/
SDL_BlitSurface(sdlSurface, NULL, SDL_GetWindowSurface(sdlWindow), NULL);
SDL_UpdateWindowSurface(sdlWindow);
}
int Executor::vdriver_update_screen(int top, int left, int bottom, int right,
bool cursor_p)
{
/*SDL_UpdateTexture(sdlTexture, NULL, vdriver_fbuf, vdriver_row_bytes);
SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);
SDL_RenderPresent(sdlRenderer);*/
SDL_BlitSurface(sdlSurface, NULL, SDL_GetWindowSurface(sdlWindow), NULL);
SDL_UpdateWindowSurface(sdlWindow);
}
void Executor::vdriver_flush_display(void)
{
}
void Executor::vdriver_shutdown(void)
{
}
void Executor::host_flush_shadow_screen(void)
{
}
static bool ConfirmQuit()
{
const SDL_MessageBoxButtonData buttons[] = {
{ SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, 2, "Cancel" },
{ SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, 1, "Force Quit" },
};
const SDL_MessageBoxData messageboxdata = {
SDL_MESSAGEBOX_INFORMATION, /* .flags */
sdlWindow, /* .window */
"Quit", /* .title */
"Do you want to quit Executor?", /* .message */
SDL_arraysize(buttons), /* .numbuttons */
buttons, /* .buttons */
NULL /* .colorScheme */
};
int buttonid;
SDL_ShowMessageBox(&messageboxdata, &buttonid);
return buttonid == 1;
}
static bool isModifier(unsigned char virt, uint16 *modstore)
{
/* Note: shift and control can be cleared if right* and left* are pressed */
switch(virt)
{
case MKV_LEFTSHIFT:
case MKV_RIGHTSHIFT:
*modstore = shiftKey;
break;
case MKV_CAPS:
*modstore = alphaLock;
break;
case MKV_LEFTCNTL:
case MKV_RIGHTCNTL:
*modstore = ControlKey;
break;
case MKV_CLOVER:
*modstore = cmdKey;
break;
case MKV_LEFTOPTION:
case MKV_RIGHTOPTION:
*modstore = optionKey;
break;
default:
*modstore = 0;
return false;
}
return true;
}
void Executor::vdriver_pump_events()
{
SDL_Event event;
static uint16_t keymod = 0;
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_MOUSEMOTION:
MouseLocation.h = CW(event.motion.x);
MouseLocation.v = CW(event.motion.y);
adb_apeiron_hack(false);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
{
bool down_p;
int32 when;
Point where;
down_p = (event.button.state == SDL_PRESSED);
if(down_p)
keymod &= ~btnState;
else
keymod |= btnState;
when = TickCount();
where.h = event.button.x;
where.v = event.button.y;
ROMlib_PPostEvent(down_p ? mouseDown : mouseUp,
0, (GUEST<EvQElPtr> *)0, when, where,
keymod);
adb_apeiron_hack(false);
}
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
{
bool down_p;
unsigned char mkvkey;
uint16 mod;
LONGINT keywhat;
int32 when;
Point where;
init_sdlk_to_mkv();
down_p = (event.key.state == SDL_PRESSED);
/*if(use_scan_codes)
mkvkey = ibm_virt_to_mac_virt[event.key.keysym.scancode];
else*/
{
auto p = sdlk_to_mkv.find(event.key.keysym.sym);
if(p == sdlk_to_mkv.end())
mkvkey = NOTAKEY;
else
mkvkey = p->second;
}
mkvkey = ROMlib_right_to_left_key_map(mkvkey);
if(isModifier(mkvkey, &mod))
{
if(down_p)
keymod |= mod;
else
keymod &= ~mod;
}
when = TickCount();
where.h = CW(MouseLocation.h);
where.v = CW(MouseLocation.v);
keywhat = ROMlib_xlate(mkvkey, keymod, down_p);
post_keytrans_key_events(down_p ? keyDown : keyUp,
keywhat, when, where,
keymod, mkvkey);
}
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
//if(!we_lost_clipboard())
sendresumeevent(false);
//else
//{
// ZeroScrap();
// sendresumeevent(true);
//}
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
sendsuspendevent();
break;
case SDL_QUIT:
if(ConfirmQuit())
ExitToShell();
break;
}
}
}
extern "C" void
ROMlib_SetTitle(char *title)
{
}
extern "C" char *
ROMlib_GetTitle(void)
{
static char str[] = "Foo";
return str;
}
extern "C" void
ROMlib_FreeTitle(char *title)
{
}
/* This is really inefficient. We should hash the cursors */
void Executor::host_set_cursor(char *cursor_data,
unsigned short cursor_mask[16],
int hotspot_x, int hotspot_y)
{
SDL_Cursor *old_cursor, *new_cursor;
old_cursor = SDL_GetCursor();
new_cursor = SDL_CreateCursor((unsigned char *)cursor_data,
(unsigned char *)cursor_mask,
16, 16, hotspot_x, hotspot_y);
if(new_cursor != NULL)
{
SDL_SetCursor(new_cursor);
SDL_FreeCursor(old_cursor);
}
}
int Executor::host_set_cursor_visible(int show_p)
{
return (SDL_ShowCursor(show_p));
}
<|endoftext|>
|
<commit_before>#include "types/root_typemanager.h"
#include "context/root_static_context.h"
#include "system/globalenv.h"
namespace zorba {
static const char *default_ns_initializers [] = {
"fn", XQUERY_FN_NS,
"xml", "http://www.w3.org/XML/1998/namespace",
"xs", "http://www.w3.org/2001/XMLSchema",
"xsi", "http://www.w3.org/2001/XMLSchema-instance",
"local", "http://www.w3.org/2005/xquery-local-functions",
NULL, NULL
};
root_static_context::root_static_context()
: static_context()
{
typemgr.reset(new RootTypeManager());
}
void root_static_context::init() {
set_xpath1_0compatib_mode(StaticContextConsts::xpath2_0);
const char **p = default_ns_initializers;
for (; *p != NULL; p += 2)
bind_ns (p [0], p [1]);
set_default_elem_type_ns ("");
set_default_function_namespace (lookup_ns ("fn"));
set_context_item_static_type(GENV_TYPESYSTEM.ITEM_TYPE_ONE);
set_default_collation_uri ("http://www.flworfound.org/collations/IDENTICAL/en/US");
set_construction_mode(StaticContextConsts::cons_strip);
set_ordering_mode(StaticContextConsts::ordered);
set_order_empty_mode(StaticContextConsts::empty_greatest);
set_boundary_space_mode(StaticContextConsts::strip_space);
set_inherit_mode(StaticContextConsts::no_inherit_ns);
set_preserve_mode(StaticContextConsts::no_preserve_ns);
set_default_collection_type(GENV_TYPESYSTEM.ITEM_TYPE_STAR);
set_current_absolute_baseuri("");
}
root_static_context::~root_static_context()
{
}
}
/* vim:set ts=2 sw=2: */
<commit_msg>Added ns binding for err<commit_after>#include "types/root_typemanager.h"
#include "context/root_static_context.h"
#include "system/globalenv.h"
namespace zorba {
static const char *default_ns_initializers [] = {
"fn", XQUERY_FN_NS,
"xml", "http://www.w3.org/XML/1998/namespace",
"xs", "http://www.w3.org/2001/XMLSchema",
"xsi", "http://www.w3.org/2001/XMLSchema-instance",
"local", "http://www.w3.org/2005/xquery-local-functions",
"err", "http://www.w3.org/2005/xqt-errors",
NULL, NULL
};
root_static_context::root_static_context()
: static_context()
{
typemgr.reset(new RootTypeManager());
}
void root_static_context::init() {
set_xpath1_0compatib_mode(StaticContextConsts::xpath2_0);
const char **p = default_ns_initializers;
for (; *p != NULL; p += 2)
bind_ns (p [0], p [1]);
set_default_elem_type_ns ("");
set_default_function_namespace (lookup_ns ("fn"));
set_context_item_static_type(GENV_TYPESYSTEM.ITEM_TYPE_ONE);
set_default_collation_uri ("http://www.flworfound.org/collations/IDENTICAL/en/US");
set_construction_mode(StaticContextConsts::cons_strip);
set_ordering_mode(StaticContextConsts::ordered);
set_order_empty_mode(StaticContextConsts::empty_greatest);
set_boundary_space_mode(StaticContextConsts::strip_space);
set_inherit_mode(StaticContextConsts::no_inherit_ns);
set_preserve_mode(StaticContextConsts::no_preserve_ns);
set_default_collection_type(GENV_TYPESYSTEM.ITEM_TYPE_STAR);
set_current_absolute_baseuri("");
}
root_static_context::~root_static_context()
{
}
}
/* vim:set ts=2 sw=2: */
<|endoftext|>
|
<commit_before>/*
*
* Copyright (c) 2021 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <controller/AutoCommissioner.h>
#include <controller/CHIPDeviceController.h>
namespace chip {
namespace Controller {
CHIP_ERROR AutoCommissioner::SetCommissioningParameters(const CommissioningParameters & params)
{
mParams = params;
if (params.HasThreadOperationalDataset())
{
ByteSpan dataset = params.GetThreadOperationalDataset().Value();
if (dataset.size() > CommissioningParameters::kMaxCredentialsLen)
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
memcpy(mThreadOperationalDataset, dataset.data(), dataset.size());
mParams.SetThreadOperationalDataset(ByteSpan(mThreadOperationalDataset, dataset.size()));
}
if (params.HasWiFiCredentials())
{
WiFiCredentials creds = params.GetWiFiCredentials().Value();
if (creds.ssid.size() > CommissioningParameters::kMaxSsidLen ||
creds.credentials.size() > CommissioningParameters::kMaxCredentialsLen)
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
memcpy(mSsid, creds.ssid.data(), creds.ssid.size());
memcpy(mCredentials, creds.credentials.data(), creds.credentials.size());
mParams.SetWiFiCredentials(
WiFiCredentials(ByteSpan(mSsid, creds.ssid.size()), ByteSpan(mCredentials, creds.credentials.size())));
}
return CHIP_NO_ERROR;
}
CommissioningStage AutoCommissioner::GetNextCommissioningStage(CommissioningStage currentStage, CHIP_ERROR lastErr)
{
if (lastErr != CHIP_NO_ERROR)
{
return CommissioningStage::kCleanup;
}
switch (currentStage)
{
case CommissioningStage::kSecurePairing:
return CommissioningStage::kArmFailsafe;
case CommissioningStage::kArmFailsafe:
return CommissioningStage::kConfigRegulatory;
case CommissioningStage::kConfigRegulatory:
return CommissioningStage::kDeviceAttestation;
case CommissioningStage::kDeviceAttestation:
// TODO(cecille): device attestation casues operational cert provisioinging to happen, This should be a separate stage.
// For thread and wifi, this should go to network setup then enable. For on-network we can skip right to finding the
// operational network because the provisioning of certificates will trigger the device to start operational advertising.
if (mParams.HasWiFiCredentials())
{
return CommissioningStage::kWiFiNetworkSetup;
}
else if (mParams.HasThreadOperationalDataset())
{
return CommissioningStage::kThreadNetworkSetup;
}
else
{
#if CHIP_DEVICE_CONFIG_ENABLE_DNSSD
return CommissioningStage::kFindOperational;
#else
return CommissioningStage::kSendComplete;
#endif
}
case CommissioningStage::kWiFiNetworkSetup:
if (mParams.HasThreadOperationalDataset())
{
return CommissioningStage::kThreadNetworkSetup;
}
else
{
return CommissioningStage::kWiFiNetworkEnable;
}
case CommissioningStage::kThreadNetworkSetup:
if (mParams.HasWiFiCredentials())
{
return CommissioningStage::kWiFiNetworkEnable;
}
else
{
return CommissioningStage::kThreadNetworkEnable;
}
case CommissioningStage::kWiFiNetworkEnable:
if (mParams.HasThreadOperationalDataset())
{
return CommissioningStage::kThreadNetworkEnable;
}
else
{
return CommissioningStage::kFindOperational;
}
case CommissioningStage::kThreadNetworkEnable:
return CommissioningStage::kFindOperational;
case CommissioningStage::kFindOperational:
return CommissioningStage::kSendComplete;
case CommissioningStage::kSendComplete:
return CommissioningStage::kCleanup;
// Currently unimplemented.
case CommissioningStage::kConfigACL:
case CommissioningStage::kCheckCertificates:
return CommissioningStage::kError;
// Neither of these have a next stage so return kError;
case CommissioningStage::kCleanup:
case CommissioningStage::kError:
return CommissioningStage::kError;
}
return CommissioningStage::kError;
}
void AutoCommissioner::StartCommissioning(CommissioneeDeviceProxy * proxy)
{
// TODO: check that there is no commissioning in progress currently.
mCommissioneeDeviceProxy = proxy;
mCommissioner->PerformCommissioningStep(mCommissioneeDeviceProxy, CommissioningStage::kArmFailsafe, mParams, this);
}
void AutoCommissioner::CommissioningStepFinished(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report)
{
if (report.stageCompleted == CommissioningStage::kFindOperational)
{
mOperationalDeviceProxy = report.OperationalNodeFoundData.operationalProxy;
}
CommissioningStage nextStage = GetNextCommissioningStage(report.stageCompleted, err);
DeviceProxy * proxy = mCommissioneeDeviceProxy;
if (nextStage == CommissioningStage::kSendComplete ||
(nextStage == CommissioningStage::kCleanup && mOperationalDeviceProxy != nullptr))
{
proxy = mOperationalDeviceProxy;
}
if (proxy == nullptr)
{
ChipLogError(Controller, "Invalid device for commissioning");
return;
}
mParams.SetCompletionStatus(err);
mCommissioner->PerformCommissioningStep(proxy, nextStage, mParams, this);
}
} // namespace Controller
} // namespace chip
<commit_msg>Fix sizing on thread data set (#13662)<commit_after>/*
*
* Copyright (c) 2021 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <controller/AutoCommissioner.h>
#include <controller/CHIPDeviceController.h>
namespace chip {
namespace Controller {
CHIP_ERROR AutoCommissioner::SetCommissioningParameters(const CommissioningParameters & params)
{
mParams = params;
if (params.HasThreadOperationalDataset())
{
ByteSpan dataset = params.GetThreadOperationalDataset().Value();
if (dataset.size() > CommissioningParameters::kMaxThreadDatasetLen)
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
memcpy(mThreadOperationalDataset, dataset.data(), dataset.size());
mParams.SetThreadOperationalDataset(ByteSpan(mThreadOperationalDataset, dataset.size()));
}
if (params.HasWiFiCredentials())
{
WiFiCredentials creds = params.GetWiFiCredentials().Value();
if (creds.ssid.size() > CommissioningParameters::kMaxSsidLen ||
creds.credentials.size() > CommissioningParameters::kMaxCredentialsLen)
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
memcpy(mSsid, creds.ssid.data(), creds.ssid.size());
memcpy(mCredentials, creds.credentials.data(), creds.credentials.size());
mParams.SetWiFiCredentials(
WiFiCredentials(ByteSpan(mSsid, creds.ssid.size()), ByteSpan(mCredentials, creds.credentials.size())));
}
return CHIP_NO_ERROR;
}
CommissioningStage AutoCommissioner::GetNextCommissioningStage(CommissioningStage currentStage, CHIP_ERROR lastErr)
{
if (lastErr != CHIP_NO_ERROR)
{
return CommissioningStage::kCleanup;
}
switch (currentStage)
{
case CommissioningStage::kSecurePairing:
return CommissioningStage::kArmFailsafe;
case CommissioningStage::kArmFailsafe:
return CommissioningStage::kConfigRegulatory;
case CommissioningStage::kConfigRegulatory:
return CommissioningStage::kDeviceAttestation;
case CommissioningStage::kDeviceAttestation:
// TODO(cecille): device attestation casues operational cert provisioinging to happen, This should be a separate stage.
// For thread and wifi, this should go to network setup then enable. For on-network we can skip right to finding the
// operational network because the provisioning of certificates will trigger the device to start operational advertising.
if (mParams.HasWiFiCredentials())
{
return CommissioningStage::kWiFiNetworkSetup;
}
else if (mParams.HasThreadOperationalDataset())
{
return CommissioningStage::kThreadNetworkSetup;
}
else
{
#if CHIP_DEVICE_CONFIG_ENABLE_DNSSD
return CommissioningStage::kFindOperational;
#else
return CommissioningStage::kSendComplete;
#endif
}
case CommissioningStage::kWiFiNetworkSetup:
if (mParams.HasThreadOperationalDataset())
{
return CommissioningStage::kThreadNetworkSetup;
}
else
{
return CommissioningStage::kWiFiNetworkEnable;
}
case CommissioningStage::kThreadNetworkSetup:
if (mParams.HasWiFiCredentials())
{
return CommissioningStage::kWiFiNetworkEnable;
}
else
{
return CommissioningStage::kThreadNetworkEnable;
}
case CommissioningStage::kWiFiNetworkEnable:
if (mParams.HasThreadOperationalDataset())
{
return CommissioningStage::kThreadNetworkEnable;
}
else
{
return CommissioningStage::kFindOperational;
}
case CommissioningStage::kThreadNetworkEnable:
return CommissioningStage::kFindOperational;
case CommissioningStage::kFindOperational:
return CommissioningStage::kSendComplete;
case CommissioningStage::kSendComplete:
return CommissioningStage::kCleanup;
// Currently unimplemented.
case CommissioningStage::kConfigACL:
case CommissioningStage::kCheckCertificates:
return CommissioningStage::kError;
// Neither of these have a next stage so return kError;
case CommissioningStage::kCleanup:
case CommissioningStage::kError:
return CommissioningStage::kError;
}
return CommissioningStage::kError;
}
void AutoCommissioner::StartCommissioning(CommissioneeDeviceProxy * proxy)
{
// TODO: check that there is no commissioning in progress currently.
mCommissioneeDeviceProxy = proxy;
mCommissioner->PerformCommissioningStep(mCommissioneeDeviceProxy, CommissioningStage::kArmFailsafe, mParams, this);
}
void AutoCommissioner::CommissioningStepFinished(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report)
{
if (report.stageCompleted == CommissioningStage::kFindOperational)
{
mOperationalDeviceProxy = report.OperationalNodeFoundData.operationalProxy;
}
CommissioningStage nextStage = GetNextCommissioningStage(report.stageCompleted, err);
DeviceProxy * proxy = mCommissioneeDeviceProxy;
if (nextStage == CommissioningStage::kSendComplete ||
(nextStage == CommissioningStage::kCleanup && mOperationalDeviceProxy != nullptr))
{
proxy = mOperationalDeviceProxy;
}
if (proxy == nullptr)
{
ChipLogError(Controller, "Invalid device for commissioning");
return;
}
mParams.SetCompletionStatus(err);
mCommissioner->PerformCommissioningStep(proxy, nextStage, mParams, this);
}
} // namespace Controller
} // namespace chip
<|endoftext|>
|
<commit_before>// -----------------------------------------------------------------------------
//
// Copyright (C) 2021 CERN & University of Surrey for the benefit of the
// BioDynaMo collaboration. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#include "core/util/plot_memory_layout.h"
#include <algorithm>
#include <limits>
#include <string>
// ROOT
#include <TAxis.h>
#include <TCanvas.h>
#include <TFrame.h>
#include <TGraph.h>
#include <TGraphAsymmErrors.h>
#include <TGraphErrors.h>
#include <TH1F.h>
#include <TLegend.h>
#include <TMath.h>
#include <TMultiGraph.h>
#include <TPad.h>
#include <TStyle.h>
// BioDynaMo
#include "core/agent/agent.h"
#include "core/environment/environment.h"
#include "core/scheduler.h"
#include "core/simulation.h"
namespace bdm {
// -----------------------------------------------------------------------------
void PlotMemoryLayout(const std::vector<Agent*>& agents, int numa_node) {
TCanvas c;
c.SetCanvasSize(1920, 1200);
std::vector<double> x(agents.size());
std::vector<double> y(agents.size());
uint64_t min = std::numeric_limits<uint64_t>::max();
for (uint64_t i = 0; i < agents.size(); ++i) {
auto val = reinterpret_cast<uint64_t>(agents[i]);
if (val < min) {
min = val;
}
}
for (uint64_t i = 1; i < agents.size(); ++i) {
x[i] = i;
y[i] = reinterpret_cast<uint64_t>(agents[i]) - min;
}
TGraph graph(agents.size(), x.data(), y.data());
graph.SetTitle(";Agent element index; Virtual memory address");
graph.Draw("ap");
c.Update();
gPad->Modified();
gPad->Update();
c.Modified();
c.cd(0);
auto steps = Simulation::GetActive()->GetScheduler()->GetSimulatedSteps();
auto dir = Simulation::GetActive()->GetOutputDir();
c.SaveAs(Concat(dir, "/mem-layout-", steps, "-", numa_node, ".png").c_str());
}
// -----------------------------------------------------------------------------
void PlotMemoryHistogram(const std::vector<Agent*>& agents, int numa_node) {
TCanvas c;
c.SetCanvasSize(1920, 1200);
TH1F hist("", "", 100, 1, 10000);
hist.SetTitle(";#Delta bytes; Count");
for (uint64_t i = 1; i < agents.size(); ++i) {
float val = 0;
auto t = reinterpret_cast<uint64_t>(agents[i]);
auto l = reinterpret_cast<uint64_t>(agents[i - 1]);
if (t > l) {
val = t - l;
} else {
val = l - t;
}
val = std::min(val, 10000.f - 1);
hist.Fill(val);
}
hist.Draw();
c.Update();
gPad->SetLogy();
gPad->Modified();
gPad->Update();
c.Modified();
c.cd(0);
auto steps = Simulation::GetActive()->GetScheduler()->GetSimulatedSteps();
auto dir = Simulation::GetActive()->GetOutputDir();
c.SaveAs(
Concat(dir, "/mem-layout-hist-", steps, "-", numa_node, ".png").c_str());
}
// -----------------------------------------------------------------------------
struct Fen : public Functor<void, Agent*, double> {
std::vector<int64_t>& diffs;
Agent* query;
Fen(std::vector<int64_t>& diffs, Agent* query) : diffs(diffs), query(query) {}
void operator()(Agent* neighbor, double) {
if (neighbor == query) {
return;
}
auto t = reinterpret_cast<int64_t>(query);
auto l = reinterpret_cast<int64_t>(neighbor);
diffs.push_back(t - l);
}
};
// -----------------------------------------------------------------------------
struct Fea : public Functor<void, Agent*, AgentHandle> {
std::vector<int64_t>& diffs;
explicit Fea(std::vector<int64_t>& diffs) : diffs(diffs) {}
void operator()(Agent* agent, AgentHandle) {
Fen fen(diffs, agent);
auto* sim = Simulation::GetActive();
auto* env = sim->GetEnvironment();
auto squared_radius = env->GetLargestAgentSizeSquared();
sim->GetExecutionContext()->ForEachNeighbor(fen, *agent, squared_radius);
}
};
// -----------------------------------------------------------------------------
void PlotNeighborMemoryHistogram(bool before) {
TCanvas c;
c.SetCanvasSize(1920, 1200);
auto* rm = Simulation::GetActive()->GetResourceManager();
std::vector<int64_t> diffs;
diffs.reserve(rm->GetNumAgents() * 3);
if (!before) {
Simulation::GetActive()->GetEnvironment()->Update();
}
Fea fea(diffs);
rm->ForEachAgent(fea);
auto min = std::numeric_limits<float>::max();
auto max = std::numeric_limits<float>::min();
for (uint64_t i = 0; i < diffs.size(); ++i) {
if (diffs[i] < min) {
min = diffs[i];
}
if (diffs[i] > max) {
max = diffs[i];
}
}
min--;
max++;
uint64_t nbins = std::max(static_cast<uint64_t>(100u),
static_cast<uint64_t>((max - min) / 20000));
TH1F hist("", "", nbins, min, max);
hist.SetTitle(";#Delta bytes; Count");
for (uint64_t i = 0; i < diffs.size(); ++i) {
hist.Fill(diffs[i]);
}
hist.Draw();
c.Update();
gPad->SetLogy();
gPad->Modified();
gPad->Update();
c.Modified();
c.cd(0);
auto steps = Simulation::GetActive()->GetScheduler()->GetSimulatedSteps();
auto dir = Simulation::GetActive()->GetOutputDir();
std::string suffix = "-end";
if (before) {
suffix = "-begin";
}
c.SaveAs(
Concat(dir, "/mem-layout-neighbor-hist-", steps, suffix, ".png").c_str());
c.SaveAs(
Concat(dir, "/mem-layout-neighbor-hist-", steps, suffix, ".C").c_str());
}
} // namespace bdm
<commit_msg>Add safety check in function PlotNeighborMemoryHistogram<commit_after>// -----------------------------------------------------------------------------
//
// Copyright (C) 2021 CERN & University of Surrey for the benefit of the
// BioDynaMo collaboration. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#include "core/util/plot_memory_layout.h"
#include <algorithm>
#include <limits>
#include <string>
// ROOT
#include <TAxis.h>
#include <TCanvas.h>
#include <TFrame.h>
#include <TGraph.h>
#include <TGraphAsymmErrors.h>
#include <TGraphErrors.h>
#include <TH1F.h>
#include <TLegend.h>
#include <TMath.h>
#include <TMultiGraph.h>
#include <TPad.h>
#include <TStyle.h>
// BioDynaMo
#include "core/agent/agent.h"
#include "core/environment/environment.h"
#include "core/scheduler.h"
#include "core/simulation.h"
namespace bdm {
// -----------------------------------------------------------------------------
void PlotMemoryLayout(const std::vector<Agent*>& agents, int numa_node) {
TCanvas c;
c.SetCanvasSize(1920, 1200);
std::vector<double> x(agents.size());
std::vector<double> y(agents.size());
uint64_t min = std::numeric_limits<uint64_t>::max();
for (uint64_t i = 0; i < agents.size(); ++i) {
auto val = reinterpret_cast<uint64_t>(agents[i]);
if (val < min) {
min = val;
}
}
for (uint64_t i = 1; i < agents.size(); ++i) {
x[i] = i;
y[i] = reinterpret_cast<uint64_t>(agents[i]) - min;
}
TGraph graph(agents.size(), x.data(), y.data());
graph.SetTitle(";Agent element index; Virtual memory address");
graph.Draw("ap");
c.Update();
gPad->Modified();
gPad->Update();
c.Modified();
c.cd(0);
auto steps = Simulation::GetActive()->GetScheduler()->GetSimulatedSteps();
auto dir = Simulation::GetActive()->GetOutputDir();
c.SaveAs(Concat(dir, "/mem-layout-", steps, "-", numa_node, ".png").c_str());
}
// -----------------------------------------------------------------------------
void PlotMemoryHistogram(const std::vector<Agent*>& agents, int numa_node) {
TCanvas c;
c.SetCanvasSize(1920, 1200);
TH1F hist("", "", 100, 1, 10000);
hist.SetTitle(";#Delta bytes; Count");
for (uint64_t i = 1; i < agents.size(); ++i) {
float val = 0;
auto t = reinterpret_cast<uint64_t>(agents[i]);
auto l = reinterpret_cast<uint64_t>(agents[i - 1]);
if (t > l) {
val = t - l;
} else {
val = l - t;
}
val = std::min(val, 10000.f - 1);
hist.Fill(val);
}
hist.Draw();
c.Update();
gPad->SetLogy();
gPad->Modified();
gPad->Update();
c.Modified();
c.cd(0);
auto steps = Simulation::GetActive()->GetScheduler()->GetSimulatedSteps();
auto dir = Simulation::GetActive()->GetOutputDir();
c.SaveAs(
Concat(dir, "/mem-layout-hist-", steps, "-", numa_node, ".png").c_str());
}
// -----------------------------------------------------------------------------
struct Fen : public Functor<void, Agent*, double> {
std::vector<int64_t>& diffs;
Agent* query;
Fen(std::vector<int64_t>& diffs, Agent* query) : diffs(diffs), query(query) {}
void operator()(Agent* neighbor, double) {
if (neighbor == query) {
return;
}
auto t = reinterpret_cast<int64_t>(query);
auto l = reinterpret_cast<int64_t>(neighbor);
diffs.push_back(t - l);
}
};
// -----------------------------------------------------------------------------
struct Fea : public Functor<void, Agent*, AgentHandle> {
std::vector<int64_t>& diffs;
explicit Fea(std::vector<int64_t>& diffs) : diffs(diffs) {}
void operator()(Agent* agent, AgentHandle) {
Fen fen(diffs, agent);
auto* sim = Simulation::GetActive();
auto* env = sim->GetEnvironment();
auto squared_radius = env->GetLargestAgentSizeSquared();
sim->GetExecutionContext()->ForEachNeighbor(fen, *agent, squared_radius);
}
};
// -----------------------------------------------------------------------------
void PlotNeighborMemoryHistogram(bool before) {
TCanvas c;
c.SetCanvasSize(1920, 1200);
auto* rm = Simulation::GetActive()->GetResourceManager();
if (rm->GetNumAgents() == 0) {
return;
}
std::vector<int64_t> diffs;
diffs.reserve(rm->GetNumAgents() * 3);
if (!before) {
Simulation::GetActive()->GetEnvironment()->Update();
}
Fea fea(diffs);
rm->ForEachAgent(fea);
auto min = std::numeric_limits<float>::max();
auto max = std::numeric_limits<float>::min();
for (uint64_t i = 0; i < diffs.size(); ++i) {
if (diffs[i] < min) {
min = diffs[i];
}
if (diffs[i] > max) {
max = diffs[i];
}
}
min--;
max++;
uint64_t nbins = std::max(static_cast<uint64_t>(100u),
static_cast<uint64_t>((max - min) / 20000));
TH1F hist("", "", nbins, min, max);
hist.SetTitle(";#Delta bytes; Count");
for (uint64_t i = 0; i < diffs.size(); ++i) {
hist.Fill(diffs[i]);
}
hist.Draw();
c.Update();
gPad->SetLogy();
gPad->Modified();
gPad->Update();
c.Modified();
c.cd(0);
auto steps = Simulation::GetActive()->GetScheduler()->GetSimulatedSteps();
auto dir = Simulation::GetActive()->GetOutputDir();
std::string suffix = "-end";
if (before) {
suffix = "-begin";
}
c.SaveAs(
Concat(dir, "/mem-layout-neighbor-hist-", steps, suffix, ".png").c_str());
c.SaveAs(
Concat(dir, "/mem-layout-neighbor-hist-", steps, suffix, ".C").c_str());
}
} // namespace bdm
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: tustring.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: th $ $Date: 2001-03-16 15:25:57 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <string.h>
#ifndef _OSL_INTERLCK_H
#include <osl/interlck.h>
#endif
#ifndef _RTL_ALLOC_H
#include <rtl/alloc.h>
#endif
#ifndef _RTL_MEMORY_H
#include <rtl/memory.h>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#define private public
#include <string.hxx>
#undef private
#include <impstrg.hxx>
#include <debug.hxx>
// =======================================================================
DBG_NAME( UniString );
DBG_NAMEEX( ByteString );
// -----------------------------------------------------------------------
#define STRCODE sal_Unicode
#define STRING UniString
#define STRINGDATA UniStringData
#define DBGCHECKSTRING DbgCheckUniString
// -----------------------------------------------------------------------
#include <strimp.cxx>
#include <strucvt.cxx>
#include <strascii.cxx>
// -----------------------------------------------------------------------
UniString UniString::CreateFromInt32( sal_Int32 n, sal_Int16 nRadix )
{
sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFINT32];
return UniString( aBuf, rtl_ustr_valueOfInt32( aBuf, n, nRadix ) );
}
// -----------------------------------------------------------------------
UniString UniString::CreateFromInt64( sal_Int64 n, sal_Int16 nRadix )
{
sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFINT64];
return UniString( aBuf, rtl_ustr_valueOfInt64( aBuf, n, nRadix ) );
}
// -----------------------------------------------------------------------
UniString UniString::CreateFromFloat( float f )
{
sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFFLOAT];
return UniString( aBuf, rtl_ustr_valueOfFloat( aBuf, f ) );
}
// -----------------------------------------------------------------------
UniString UniString::CreateFromDouble( double d )
{
sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFDOUBLE];
return UniString( aBuf, rtl_ustr_valueOfDouble( aBuf, d ) );
}
// -----------------------------------------------------------------------
sal_Int32 UniString::ToInt32() const
{
DBG_CHKTHIS( UniString, DbgCheckUniString );
return rtl_ustr_toInt32( mpData->maStr, 10 );
}
// -----------------------------------------------------------------------
sal_Int64 UniString::ToInt64() const
{
DBG_CHKTHIS( UniString, DbgCheckUniString );
return rtl_ustr_toInt64( mpData->maStr, 10 );
}
// -----------------------------------------------------------------------
float UniString::ToFloat() const
{
DBG_CHKTHIS( UniString, DbgCheckUniString );
return rtl_ustr_toFloat( mpData->maStr );
}
// -----------------------------------------------------------------------
double UniString::ToDouble() const
{
DBG_CHKTHIS( UniString, DbgCheckUniString );
return rtl_ustr_toDouble( mpData->maStr );
}
<commit_msg>INTEGRATION: CWS sb13 (1.2.210); FILE MERGED 2004/02/06 08:57:17 sb 1.2.210.1: #i19699# Tightened tools/string.hxx so that arithmetic/enumeration type arguments are not silently converted to char/sal_Unicode.<commit_after>/*************************************************************************
*
* $RCSfile: tustring.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2004-02-26 13:21:30 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <string.h>
#ifndef _OSL_INTERLCK_H
#include <osl/interlck.h>
#endif
#ifndef _RTL_ALLOC_H
#include <rtl/alloc.h>
#endif
#ifndef _RTL_MEMORY_H
#include <rtl/memory.h>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#define private public
#include <string.hxx>
#undef private
#include <impstrg.hxx>
#include <debug.hxx>
// =======================================================================
DBG_NAME( UniString );
DBG_NAMEEX( ByteString );
// -----------------------------------------------------------------------
#define STRCODE sal_Unicode
#define STRING UniString
#define STRINGDATA UniStringData
#define DBGCHECKSTRING DbgCheckUniString
// -----------------------------------------------------------------------
#include <strimp.cxx>
#include <strucvt.cxx>
#include <strascii.cxx>
UniString::UniString(char c): mpData(ImplAllocData(1)) { mpData->maStr[0] = c; }
// -----------------------------------------------------------------------
UniString UniString::CreateFromInt32( sal_Int32 n, sal_Int16 nRadix )
{
sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFINT32];
return UniString( aBuf, rtl_ustr_valueOfInt32( aBuf, n, nRadix ) );
}
// -----------------------------------------------------------------------
UniString UniString::CreateFromInt64( sal_Int64 n, sal_Int16 nRadix )
{
sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFINT64];
return UniString( aBuf, rtl_ustr_valueOfInt64( aBuf, n, nRadix ) );
}
// -----------------------------------------------------------------------
UniString UniString::CreateFromFloat( float f )
{
sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFFLOAT];
return UniString( aBuf, rtl_ustr_valueOfFloat( aBuf, f ) );
}
// -----------------------------------------------------------------------
UniString UniString::CreateFromDouble( double d )
{
sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFDOUBLE];
return UniString( aBuf, rtl_ustr_valueOfDouble( aBuf, d ) );
}
// -----------------------------------------------------------------------
sal_Int32 UniString::ToInt32() const
{
DBG_CHKTHIS( UniString, DbgCheckUniString );
return rtl_ustr_toInt32( mpData->maStr, 10 );
}
// -----------------------------------------------------------------------
sal_Int64 UniString::ToInt64() const
{
DBG_CHKTHIS( UniString, DbgCheckUniString );
return rtl_ustr_toInt64( mpData->maStr, 10 );
}
// -----------------------------------------------------------------------
float UniString::ToFloat() const
{
DBG_CHKTHIS( UniString, DbgCheckUniString );
return rtl_ustr_toFloat( mpData->maStr );
}
// -----------------------------------------------------------------------
double UniString::ToDouble() const
{
DBG_CHKTHIS( UniString, DbgCheckUniString );
return rtl_ustr_toDouble( mpData->maStr );
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkContourModelSetGLMapper2D.h"
#include "mitkPlaneGeometry.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkContourModelSet.h"
#include <vtkLinearTransform.h>
#include "mitkContourModel.h"
#include "mitkBaseRenderer.h"
#include "mitkOverlayManager.h"
#include "mitkTextOverlay2D.h"
#include "mitkGL.h"
mitk::ContourModelGLMapper2DBase::ContourModelGLMapper2DBase()
{
m_PointNumbersOverlay = mitk::TextOverlay2D::New();
m_ControlPointNumbersOverlay = mitk::TextOverlay2D::New();
}
mitk::ContourModelGLMapper2DBase::~ContourModelGLMapper2DBase()
{
RendererListType::const_iterator iter;
for ( iter=m_RendererList.begin(); iter != m_RendererList.end(); ++iter)
{
(*iter)->GetOverlayManager()->RemoveOverlay( m_PointNumbersOverlay.GetPointer() );
(*iter)->GetOverlayManager()->RemoveOverlay( m_ControlPointNumbersOverlay.GetPointer() );
}
m_RendererList.clear();
}
void mitk::ContourModelGLMapper2DBase::DrawContour(mitk::ContourModel* renderingContour, mitk::BaseRenderer* renderer)
{
if ( std::find( m_RendererList.begin(), m_RendererList.end(), renderer ) == m_RendererList.end() )
{
m_RendererList.push_back( renderer );
}
renderer->GetOverlayManager()->AddOverlay( m_PointNumbersOverlay.GetPointer(), renderer );
m_PointNumbersOverlay->SetVisibility( false, renderer );
renderer->GetOverlayManager()->AddOverlay( m_ControlPointNumbersOverlay.GetPointer(), renderer );
m_ControlPointNumbersOverlay->SetVisibility( false, renderer );
InternalDrawContour( renderingContour, renderer );
}
void mitk::ContourModelGLMapper2DBase::InternalDrawContour(mitk::ContourModel* renderingContour, mitk::BaseRenderer* renderer)
{
if(!renderingContour) return;
mitk::DataNode* dataNode = this->GetDataNode();
renderingContour->UpdateOutputInformation();
unsigned int timestep = renderer->GetTimeStep();
if ( !renderingContour->IsEmptyTimeStep(timestep) )
{
mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
assert(displayGeometry.IsNotNull());
//apply color and opacity read from the PropertyList
ApplyColorAndOpacityProperties(renderer);
mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(dataNode->GetProperty("contour.color", renderer));
float opacity = 0.5;
dataNode->GetFloatProperty("opacity", opacity, renderer);
if(colorprop)
{
//set the color of the contour
double red = colorprop->GetColor().GetRed();
double green = colorprop->GetColor().GetGreen();
double blue = colorprop->GetColor().GetBlue();
glColor4f(red, green, blue, opacity);
}
mitk::ColorProperty::Pointer selectedcolor = dynamic_cast<mitk::ColorProperty*>(dataNode->GetProperty("contour.points.color", renderer));
if(!selectedcolor)
{
selectedcolor = mitk::ColorProperty::New(1.0,0.0,0.1);
}
vtkLinearTransform* transform = dataNode->GetVtkTransform();
// ContourModel::OutputType point;
mitk::Point3D point;
mitk::Point3D p, projected_p;
float vtkp[3];
float lineWidth = 3.0;
bool drawit=false;
bool isHovering = false;
dataNode->GetBoolProperty("contour.hovering", isHovering);
if (isHovering)
dataNode->GetFloatProperty("contour.hovering.width", lineWidth);
else
dataNode->GetFloatProperty("contour.width", lineWidth);
bool showSegments = false;
dataNode->GetBoolProperty("contour.segments.show", showSegments);
bool showControlPoints = false;
dataNode->GetBoolProperty("contour.controlpoints.show", showControlPoints);
bool showPoints = false;
dataNode->GetBoolProperty("contour.points.show", showPoints);
bool showPointsNumbers = false;
dataNode->GetBoolProperty("contour.points.text", showPointsNumbers);
bool showControlPointsNumbers = false;
dataNode->GetBoolProperty("contour.controlpoints.text", showControlPointsNumbers);
bool projectmode=false;
dataNode->GetVisibility(projectmode, renderer, "contour.project-onto-plane");
mitk::ContourModel::VertexIterator pointsIt = renderingContour->IteratorBegin(timestep);
Point2D pt2d; // projected_p in display coordinates
Point2D lastPt2d;
int index = 0;
mitk::ScalarType maxDiff = 0.25;
while ( pointsIt != renderingContour->IteratorEnd(timestep) )
{
lastPt2d = pt2d;
point = (*pointsIt)->Coordinates;
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
displayGeometry->Project(p, projected_p);
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
Vector3D diff=p-projected_p;
ScalarType scalardiff = diff.GetNorm();
//project to plane
if(projectmode)
{
drawit=true;
}
else if(scalardiff<maxDiff)//point is close enough to be drawn
{
drawit=true;
}
else
{
drawit = false;
}
//draw line
if(drawit)
{
if (showSegments)
{
//lastPt2d is not valid in first step
if( !(pointsIt == renderingContour->IteratorBegin(timestep)) )
{
glLineWidth(lineWidth);
glBegin (GL_LINES);
glVertex2f(pt2d[0], pt2d[1]);
glVertex2f(lastPt2d[0], lastPt2d[1]);
glEnd();
glLineWidth(1);
}
}
if (showControlPoints)
{
//draw ontrol points
if ((*pointsIt)->IsControlPoint)
{
float pointsize = 4;
Point2D tmp;
Vector2D horz,vert;
horz[1]=0;
vert[0]=0;
horz[0]=pointsize;
vert[1]=pointsize;
glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen());
glLineWidth(1);
//a rectangle around the point with the selected color
glBegin (GL_LINE_LOOP);
tmp=pt2d-horz; glVertex2dv(&tmp[0]);
tmp=pt2d+vert; glVertex2dv(&tmp[0]);
tmp=pt2d+horz; glVertex2dv(&tmp[0]);
tmp=pt2d-vert; glVertex2dv(&tmp[0]);
glEnd();
glLineWidth(1);
//the actual point in the specified color to see the usual color of the point
glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue());
glPointSize(1);
glBegin (GL_POINTS);
tmp=pt2d; glVertex2dv(&tmp[0]);
glEnd ();
}
}
if (showPoints)
{
float pointsize = 3;
Point2D tmp;
Vector2D horz,vert;
horz[1]=0;
vert[0]=0;
horz[0]=pointsize;
vert[1]=pointsize;
glColor3f(0.0, 0.0, 0.0);
glLineWidth(1);
//a rectangle around the point with the selected color
glBegin (GL_LINE_LOOP);
tmp=pt2d-horz; glVertex2dv(&tmp[0]);
tmp=pt2d+vert; glVertex2dv(&tmp[0]);
tmp=pt2d+horz; glVertex2dv(&tmp[0]);
tmp=pt2d-vert; glVertex2dv(&tmp[0]);
glEnd();
glLineWidth(1);
//the actual point in the specified color to see the usual color of the point
glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue());
glPointSize(1);
glBegin (GL_POINTS);
tmp=pt2d; glVertex2dv(&tmp[0]);
glEnd ();
}
if (showPointsNumbers)
{
std::string l;
std::stringstream ss;
ss << index;
l.append(ss.str());
float rgb[3];
rgb[0] = 0.0; rgb[1] = 0.0; rgb[2] = 0.0;
WriteTextWithOverlay( m_PointNumbersOverlay, l.c_str(), rgb, pt2d, renderer );
}
if (showControlPointsNumbers && (*pointsIt)->IsControlPoint)
{
std::string l;
std::stringstream ss;
ss << index;
l.append(ss.str());
float rgb[3];
rgb[0] = 1.0; rgb[1] = 1.0; rgb[2] = 0.0;
WriteTextWithOverlay( m_ControlPointNumbersOverlay, l.c_str(), rgb, pt2d, renderer );
}
index++;
}
pointsIt++;
}//end while iterate over controlpoints
//close contour if necessary
if(renderingContour->IsClosed(timestep) && drawit && showSegments)
{
lastPt2d = pt2d;
point = renderingContour->GetVertexAt(0,timestep)->Coordinates;
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
displayGeometry->Project(p, projected_p);
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
glLineWidth(lineWidth);
glBegin (GL_LINES);
glVertex2f(lastPt2d[0], lastPt2d[1]);
glVertex2f( pt2d[0], pt2d[1] );
glEnd();
glLineWidth(1);
}
//draw selected vertex if exists
if(renderingContour->GetSelectedVertex())
{
//transform selected vertex
point = renderingContour->GetSelectedVertex()->Coordinates;
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
displayGeometry->Project(p, projected_p);
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
Vector3D diff=p-projected_p;
ScalarType scalardiff = diff.GetNorm();
//----------------------------------
//draw point if close to plane
if(scalardiff<maxDiff)
{
float pointsize = 5;
Point2D tmp;
glColor3f(0.0, 1.0, 0.0);
glLineWidth(1);
//a diamond around the point
glBegin (GL_LINE_LOOP);
//begin from upper left corner and paint clockwise
tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2dv(&tmp[0]);
tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2dv(&tmp[0]);
tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2dv(&tmp[0]);
tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2dv(&tmp[0]);
glEnd ();
}
//------------------------------------
}
}
}
void mitk::ContourModelGLMapper2DBase::WriteTextWithOverlay( TextOverlayPointerType textOverlay,
const char* text,
float rgb[3],
Point2D pt2d,
mitk::BaseRenderer* renderer )
{
textOverlay->SetText( text );
textOverlay->SetColor( rgb );
textOverlay->SetOpacity( 1 );
textOverlay->SetFontSize( 16 );
textOverlay->SetBoolProperty( "drawShadow", false );
textOverlay->SetVisibility( true, renderer );
}
<commit_msg>commented code that causes crashes when closing the application<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkContourModelSetGLMapper2D.h"
#include "mitkPlaneGeometry.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkContourModelSet.h"
#include <vtkLinearTransform.h>
#include "mitkContourModel.h"
#include "mitkBaseRenderer.h"
#include "mitkOverlayManager.h"
#include "mitkTextOverlay2D.h"
#include "mitkGL.h"
mitk::ContourModelGLMapper2DBase::ContourModelGLMapper2DBase()
{
m_PointNumbersOverlay = mitk::TextOverlay2D::New();
m_ControlPointNumbersOverlay = mitk::TextOverlay2D::New();
}
mitk::ContourModelGLMapper2DBase::~ContourModelGLMapper2DBase()
{
// RendererListType::const_iterator iter;
// for ( iter=m_RendererList.begin(); iter != m_RendererList.end(); ++iter)
// {
// (*iter)->GetOverlayManager()->RemoveOverlay( m_PointNumbersOverlay.GetPointer() );
// (*iter)->GetOverlayManager()->RemoveOverlay( m_ControlPointNumbersOverlay.GetPointer() );
// }
// m_RendererList.clear();
}
void mitk::ContourModelGLMapper2DBase::DrawContour(mitk::ContourModel* renderingContour, mitk::BaseRenderer* renderer)
{
if ( std::find( m_RendererList.begin(), m_RendererList.end(), renderer ) == m_RendererList.end() )
{
m_RendererList.push_back( renderer );
}
renderer->GetOverlayManager()->AddOverlay( m_PointNumbersOverlay.GetPointer(), renderer );
m_PointNumbersOverlay->SetVisibility( false, renderer );
renderer->GetOverlayManager()->AddOverlay( m_ControlPointNumbersOverlay.GetPointer(), renderer );
m_ControlPointNumbersOverlay->SetVisibility( false, renderer );
InternalDrawContour( renderingContour, renderer );
}
void mitk::ContourModelGLMapper2DBase::InternalDrawContour(mitk::ContourModel* renderingContour, mitk::BaseRenderer* renderer)
{
if(!renderingContour) return;
mitk::DataNode* dataNode = this->GetDataNode();
renderingContour->UpdateOutputInformation();
unsigned int timestep = renderer->GetTimeStep();
if ( !renderingContour->IsEmptyTimeStep(timestep) )
{
mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
assert(displayGeometry.IsNotNull());
//apply color and opacity read from the PropertyList
ApplyColorAndOpacityProperties(renderer);
mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(dataNode->GetProperty("contour.color", renderer));
float opacity = 0.5;
dataNode->GetFloatProperty("opacity", opacity, renderer);
if(colorprop)
{
//set the color of the contour
double red = colorprop->GetColor().GetRed();
double green = colorprop->GetColor().GetGreen();
double blue = colorprop->GetColor().GetBlue();
glColor4f(red, green, blue, opacity);
}
mitk::ColorProperty::Pointer selectedcolor = dynamic_cast<mitk::ColorProperty*>(dataNode->GetProperty("contour.points.color", renderer));
if(!selectedcolor)
{
selectedcolor = mitk::ColorProperty::New(1.0,0.0,0.1);
}
vtkLinearTransform* transform = dataNode->GetVtkTransform();
// ContourModel::OutputType point;
mitk::Point3D point;
mitk::Point3D p, projected_p;
float vtkp[3];
float lineWidth = 3.0;
bool drawit=false;
bool isHovering = false;
dataNode->GetBoolProperty("contour.hovering", isHovering);
if (isHovering)
dataNode->GetFloatProperty("contour.hovering.width", lineWidth);
else
dataNode->GetFloatProperty("contour.width", lineWidth);
bool showSegments = false;
dataNode->GetBoolProperty("contour.segments.show", showSegments);
bool showControlPoints = false;
dataNode->GetBoolProperty("contour.controlpoints.show", showControlPoints);
bool showPoints = false;
dataNode->GetBoolProperty("contour.points.show", showPoints);
bool showPointsNumbers = false;
dataNode->GetBoolProperty("contour.points.text", showPointsNumbers);
bool showControlPointsNumbers = false;
dataNode->GetBoolProperty("contour.controlpoints.text", showControlPointsNumbers);
bool projectmode=false;
dataNode->GetVisibility(projectmode, renderer, "contour.project-onto-plane");
mitk::ContourModel::VertexIterator pointsIt = renderingContour->IteratorBegin(timestep);
Point2D pt2d; // projected_p in display coordinates
Point2D lastPt2d;
int index = 0;
mitk::ScalarType maxDiff = 0.25;
while ( pointsIt != renderingContour->IteratorEnd(timestep) )
{
lastPt2d = pt2d;
point = (*pointsIt)->Coordinates;
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
displayGeometry->Project(p, projected_p);
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
Vector3D diff=p-projected_p;
ScalarType scalardiff = diff.GetNorm();
//project to plane
if(projectmode)
{
drawit=true;
}
else if(scalardiff<maxDiff)//point is close enough to be drawn
{
drawit=true;
}
else
{
drawit = false;
}
//draw line
if(drawit)
{
if (showSegments)
{
//lastPt2d is not valid in first step
if( !(pointsIt == renderingContour->IteratorBegin(timestep)) )
{
glLineWidth(lineWidth);
glBegin (GL_LINES);
glVertex2f(pt2d[0], pt2d[1]);
glVertex2f(lastPt2d[0], lastPt2d[1]);
glEnd();
glLineWidth(1);
}
}
if (showControlPoints)
{
//draw ontrol points
if ((*pointsIt)->IsControlPoint)
{
float pointsize = 4;
Point2D tmp;
Vector2D horz,vert;
horz[1]=0;
vert[0]=0;
horz[0]=pointsize;
vert[1]=pointsize;
glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen());
glLineWidth(1);
//a rectangle around the point with the selected color
glBegin (GL_LINE_LOOP);
tmp=pt2d-horz; glVertex2dv(&tmp[0]);
tmp=pt2d+vert; glVertex2dv(&tmp[0]);
tmp=pt2d+horz; glVertex2dv(&tmp[0]);
tmp=pt2d-vert; glVertex2dv(&tmp[0]);
glEnd();
glLineWidth(1);
//the actual point in the specified color to see the usual color of the point
glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue());
glPointSize(1);
glBegin (GL_POINTS);
tmp=pt2d; glVertex2dv(&tmp[0]);
glEnd ();
}
}
if (showPoints)
{
float pointsize = 3;
Point2D tmp;
Vector2D horz,vert;
horz[1]=0;
vert[0]=0;
horz[0]=pointsize;
vert[1]=pointsize;
glColor3f(0.0, 0.0, 0.0);
glLineWidth(1);
//a rectangle around the point with the selected color
glBegin (GL_LINE_LOOP);
tmp=pt2d-horz; glVertex2dv(&tmp[0]);
tmp=pt2d+vert; glVertex2dv(&tmp[0]);
tmp=pt2d+horz; glVertex2dv(&tmp[0]);
tmp=pt2d-vert; glVertex2dv(&tmp[0]);
glEnd();
glLineWidth(1);
//the actual point in the specified color to see the usual color of the point
glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue());
glPointSize(1);
glBegin (GL_POINTS);
tmp=pt2d; glVertex2dv(&tmp[0]);
glEnd ();
}
if (showPointsNumbers)
{
std::string l;
std::stringstream ss;
ss << index;
l.append(ss.str());
float rgb[3];
rgb[0] = 0.0; rgb[1] = 0.0; rgb[2] = 0.0;
WriteTextWithOverlay( m_PointNumbersOverlay, l.c_str(), rgb, pt2d, renderer );
}
if (showControlPointsNumbers && (*pointsIt)->IsControlPoint)
{
std::string l;
std::stringstream ss;
ss << index;
l.append(ss.str());
float rgb[3];
rgb[0] = 1.0; rgb[1] = 1.0; rgb[2] = 0.0;
WriteTextWithOverlay( m_ControlPointNumbersOverlay, l.c_str(), rgb, pt2d, renderer );
}
index++;
}
pointsIt++;
}//end while iterate over controlpoints
//close contour if necessary
if(renderingContour->IsClosed(timestep) && drawit && showSegments)
{
lastPt2d = pt2d;
point = renderingContour->GetVertexAt(0,timestep)->Coordinates;
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
displayGeometry->Project(p, projected_p);
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
glLineWidth(lineWidth);
glBegin (GL_LINES);
glVertex2f(lastPt2d[0], lastPt2d[1]);
glVertex2f( pt2d[0], pt2d[1] );
glEnd();
glLineWidth(1);
}
//draw selected vertex if exists
if(renderingContour->GetSelectedVertex())
{
//transform selected vertex
point = renderingContour->GetSelectedVertex()->Coordinates;
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
displayGeometry->Project(p, projected_p);
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
Vector3D diff=p-projected_p;
ScalarType scalardiff = diff.GetNorm();
//----------------------------------
//draw point if close to plane
if(scalardiff<maxDiff)
{
float pointsize = 5;
Point2D tmp;
glColor3f(0.0, 1.0, 0.0);
glLineWidth(1);
//a diamond around the point
glBegin (GL_LINE_LOOP);
//begin from upper left corner and paint clockwise
tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2dv(&tmp[0]);
tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2dv(&tmp[0]);
tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2dv(&tmp[0]);
tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2dv(&tmp[0]);
glEnd ();
}
//------------------------------------
}
}
}
void mitk::ContourModelGLMapper2DBase::WriteTextWithOverlay( TextOverlayPointerType textOverlay,
const char* text,
float rgb[3],
Point2D pt2d,
mitk::BaseRenderer* renderer )
{
textOverlay->SetText( text );
textOverlay->SetColor( rgb );
textOverlay->SetOpacity( 1 );
textOverlay->SetFontSize( 16 );
textOverlay->SetBoolProperty( "drawShadow", false );
textOverlay->SetVisibility( true, renderer );
}
<|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/browser/net/websocket_experiment/websocket_experiment_runner.h"
#include "base/compiler_specific.h"
#include "base/histogram.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "chrome/browser/chrome_thread.h"
#include "net/base/net_errors.h"
namespace chrome_browser_net_websocket_experiment {
static const char *kExperimentHost = "websocket-experiment.chromium.org";
static const int kAlternativePort = 61985;
static const int kUrlFetchDeadlineSec = 10;
static const int kWebSocketConnectDeadlineSec = 10;
static const int kWebSocketEchoDeadlineSec = 5;
static const int kWebSocketIdleSec = 1;
static const int kWebSocketPushDeadlineSec = 1;
static const int kWebSocketByeDeadlineSec = 10;
static const int kWebSocketCloseDeadlineSec = 5;
static const int kWebSocketTimeSec = 10;
static const int kTimeBucketCount = 50;
// TODO(ukai): Use new thread-safe-reference-counted Histograms.
#define UPDATE_HISTOGRAM(name, sample, min, max, bucket_count) do { \
switch (task_state_) { \
case STATE_RUN_WS: \
{ \
static LinearHistogram counter( \
"WebSocketExperiment.Basic." name, min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.Add(sample); \
} \
break; \
case STATE_RUN_WSS: \
{ \
static LinearHistogram counter( \
"WebSocketExperiment.Secure." name, min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.Add(sample); \
} \
break; \
case STATE_RUN_WS_NODEFAULT_PORT: \
{ \
static LinearHistogram counter( \
"WebSocketExperiment.NoDefaultPort." name, \
min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.Add(sample); \
} \
break; \
default: \
NOTREACHED(); \
break; \
} \
} while (0)
#define UPDATE_HISTOGRAM_TIMES(name, sample, min, max, bucket_count) do { \
switch (task_state_) { \
case STATE_RUN_WS: \
{ \
static Histogram counter( \
"WebSocketExperiment.Basic." name, min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.AddTime(sample); \
} \
break; \
case STATE_RUN_WSS: \
{ \
static Histogram counter( \
"WebSocketExperiment.Secure." name, min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.AddTime(sample); \
} \
break; \
case STATE_RUN_WS_NODEFAULT_PORT: \
{ \
static Histogram counter( \
"WebSocketExperiment.NoDefaultPort." name, \
min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.AddTime(sample); \
} \
break; \
default: \
NOTREACHED(); \
break; \
} \
} while (0);
// Hold reference while experiment is running.
static scoped_refptr<WebSocketExperimentRunner> runner;
/* static */
void WebSocketExperimentRunner::Start() {
DCHECK(!runner.get());
runner = new WebSocketExperimentRunner;
runner->Run();
}
/* static */
void WebSocketExperimentRunner::Stop() {
if (runner.get())
runner->Cancel();
runner = NULL;
}
WebSocketExperimentRunner::WebSocketExperimentRunner()
: next_state_(STATE_NONE),
task_state_(STATE_NONE),
ALLOW_THIS_IN_INITIALIZER_LIST(
task_callback_(this, &WebSocketExperimentRunner::OnTaskCompleted)) {
InitConfig();
}
WebSocketExperimentRunner::~WebSocketExperimentRunner() {
DCHECK(!task_.get());
}
void WebSocketExperimentRunner::Run() {
DCHECK_EQ(next_state_, STATE_NONE);
next_state_ = STATE_RUN_WS;
ChromeThread::PostDelayedTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(this, &WebSocketExperimentRunner::DoLoop),
config_.initial_delay_ms);
}
void WebSocketExperimentRunner::Cancel() {
next_state_ = STATE_NONE;
ChromeThread::PostTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(this, &WebSocketExperimentRunner::DoLoop));
}
void WebSocketExperimentRunner::InitConfig() {
config_.initial_delay_ms = 5 * 60 * 1000; // 5 mins
config_.next_delay_ms = 12 * 60 * 60 * 1000; // 12 hours
WebSocketExperimentTask::Config task_config;
task_config.ws_protocol = "google-websocket-liveexperiment";
task_config.ws_origin = "http://dev.chromium.org/";
task_config.url_fetch_deadline_ms = kUrlFetchDeadlineSec * 1000;
task_config.websocket_onopen_deadline_ms =
kWebSocketConnectDeadlineSec * 1000;
task_config.websocket_hello_message = "Hello";
task_config.websocket_hello_echoback_deadline_ms =
kWebSocketEchoDeadlineSec * 1000;
// Note: wait 1.5 sec in websocket_experiment_def.txt
task_config.websocket_idle_ms = kWebSocketIdleSec * 1000;
task_config.websocket_receive_push_message_deadline_ms =
kWebSocketPushDeadlineSec * 1000;
task_config.websocket_bye_message = "Bye";
task_config.websocket_bye_deadline_ms =
kWebSocketByeDeadlineSec * 1000;
task_config.websocket_close_deadline_ms =
kWebSocketCloseDeadlineSec * 1000;
config_.ws_config = task_config;
config_.ws_config.url =
GURL(StringPrintf("ws://%s/live_exp", kExperimentHost));
config_.ws_config.ws_location =
StringPrintf("ws://%s/live_exp", kExperimentHost);
config_.ws_config.http_url =
GURL(StringPrintf("http://%s/", kExperimentHost));
config_.wss_config = task_config;
config_.wss_config.url =
GURL(StringPrintf("wss://%s/live_exp", kExperimentHost));
config_.wss_config.ws_location =
StringPrintf("wss://%s/live_exp", kExperimentHost);
config_.wss_config.http_url =
GURL(StringPrintf("https://%s/", kExperimentHost));
config_.ws_nondefault_config = task_config;
config_.ws_nondefault_config.url =
GURL(StringPrintf("ws://%s:%d/live_exp",
kExperimentHost, kAlternativePort));
config_.ws_nondefault_config.ws_location =
StringPrintf("ws://%s:%d/live_exp",
kExperimentHost, kAlternativePort);
config_.ws_nondefault_config.http_url =
GURL(StringPrintf("http://%s:%d/",
kExperimentHost, kAlternativePort));
}
void WebSocketExperimentRunner::DoLoop() {
if (next_state_ == STATE_NONE) {
if (task_.get()) {
AddRef(); // Release in OnTaskCompleted.
task_->Cancel();
}
return;
}
State state = next_state_;
task_state_ = STATE_NONE;
next_state_ = STATE_NONE;
switch (state) {
case STATE_IDLE:
task_.reset();
next_state_ = STATE_RUN_WS;
ChromeThread::PostDelayedTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(this, &WebSocketExperimentRunner::DoLoop),
config_.next_delay_ms);
break;
case STATE_RUN_WS:
task_.reset(new WebSocketExperimentTask(config_.ws_config,
&task_callback_));
task_state_ = STATE_RUN_WS;
next_state_ = STATE_RUN_WSS;
break;
case STATE_RUN_WSS:
task_.reset(new WebSocketExperimentTask(config_.wss_config,
&task_callback_));
task_state_ = STATE_RUN_WSS;
next_state_ = STATE_RUN_WS_NODEFAULT_PORT;
break;
case STATE_RUN_WS_NODEFAULT_PORT:
task_.reset(new WebSocketExperimentTask(config_.ws_nondefault_config,
&task_callback_));
task_state_ = STATE_RUN_WS_NODEFAULT_PORT;
next_state_ = STATE_IDLE;
break;
default:
NOTREACHED();
break;
}
if (task_.get())
task_->Run();
}
void WebSocketExperimentRunner::OnTaskCompleted(int result) {
if (result == net::ERR_ABORTED) {
task_.reset();
// Task is Canceled.
DLOG(INFO) << "WebSocketExperiment Task is canceled.";
Release();
return;
}
UpdateTaskResultHistogram(task_.get());
task_.reset();
DoLoop();
}
void WebSocketExperimentRunner::UpdateTaskResultHistogram(
const WebSocketExperimentTask* task) {
DCHECK(task);
const WebSocketExperimentTask::Result& task_result = task->result();
UPDATE_HISTOGRAM("LastState", task_result.last_state,
1, WebSocketExperimentTask::NUM_STATES,
WebSocketExperimentTask::NUM_STATES + 1);
UPDATE_HISTOGRAM_TIMES("UrlFetch", task_result.url_fetch,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(kUrlFetchDeadlineSec),
kTimeBucketCount);
if (task_result.last_state <
WebSocketExperimentTask::STATE_WEBSOCKET_CONNECT_COMPLETE)
return;
UPDATE_HISTOGRAM_TIMES("WebSocketConnect", task_result.websocket_connect,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(
kWebSocketConnectDeadlineSec),
kTimeBucketCount);
if (task_result.last_state <
WebSocketExperimentTask::STATE_WEBSOCKET_RECV_HELLO)
return;
UPDATE_HISTOGRAM_TIMES("WebSocketEcho", task_result.websocket_echo,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(
kWebSocketEchoDeadlineSec),
kTimeBucketCount);
if (task_result.last_state <
WebSocketExperimentTask::STATE_WEBSOCKET_KEEP_IDLE)
return;
UPDATE_HISTOGRAM_TIMES("WebSocketIdle", task_result.websocket_idle,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(
kWebSocketIdleSec + kWebSocketPushDeadlineSec),
kTimeBucketCount);
if (task_result.last_state <
WebSocketExperimentTask::STATE_WEBSOCKET_CLOSE_COMPLETE)
return;
UPDATE_HISTOGRAM_TIMES("WebSocketTotal", task_result.websocket_total,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(kWebSocketTimeSec),
kTimeBucketCount);
}
} // namespace chrome_browser_net_websocket_experiment
<commit_msg>Throttle websocket live experiment<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/browser/net/websocket_experiment/websocket_experiment_runner.h"
#include "base/compiler_specific.h"
#include "base/field_trial.h"
#include "base/histogram.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "chrome/browser/chrome_thread.h"
#include "net/base/net_errors.h"
namespace chrome_browser_net_websocket_experiment {
static const char *kExperimentHost = "websocket-experiment.chromium.org";
static const int kAlternativePort = 61985;
static const int kUrlFetchDeadlineSec = 10;
static const int kWebSocketConnectDeadlineSec = 10;
static const int kWebSocketEchoDeadlineSec = 5;
static const int kWebSocketIdleSec = 1;
static const int kWebSocketPushDeadlineSec = 1;
static const int kWebSocketByeDeadlineSec = 10;
static const int kWebSocketCloseDeadlineSec = 5;
static const int kWebSocketTimeSec = 10;
static const int kTimeBucketCount = 50;
// TODO(ukai): Use new thread-safe-reference-counted Histograms.
#define UPDATE_HISTOGRAM(name, sample, min, max, bucket_count) do { \
switch (task_state_) { \
case STATE_RUN_WS: \
{ \
static LinearHistogram counter( \
"WebSocketExperiment.Basic." name, min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.Add(sample); \
} \
break; \
case STATE_RUN_WSS: \
{ \
static LinearHistogram counter( \
"WebSocketExperiment.Secure." name, min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.Add(sample); \
} \
break; \
case STATE_RUN_WS_NODEFAULT_PORT: \
{ \
static LinearHistogram counter( \
"WebSocketExperiment.NoDefaultPort." name, \
min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.Add(sample); \
} \
break; \
default: \
NOTREACHED(); \
break; \
} \
} while (0)
#define UPDATE_HISTOGRAM_TIMES(name, sample, min, max, bucket_count) do { \
switch (task_state_) { \
case STATE_RUN_WS: \
{ \
static Histogram counter( \
"WebSocketExperiment.Basic." name, min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.AddTime(sample); \
} \
break; \
case STATE_RUN_WSS: \
{ \
static Histogram counter( \
"WebSocketExperiment.Secure." name, min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.AddTime(sample); \
} \
break; \
case STATE_RUN_WS_NODEFAULT_PORT: \
{ \
static Histogram counter( \
"WebSocketExperiment.NoDefaultPort." name, \
min, max, bucket_count); \
counter.SetFlags(kUmaTargetedHistogramFlag); \
counter.AddTime(sample); \
} \
break; \
default: \
NOTREACHED(); \
break; \
} \
} while (0);
// Hold reference while experiment is running.
static scoped_refptr<WebSocketExperimentRunner> runner;
/* static */
void WebSocketExperimentRunner::Start() {
DCHECK(!runner.get());
scoped_refptr<FieldTrial> trial = new FieldTrial("WebSocketExperiment", 1000);
trial->AppendGroup("_active", 5); // 0.5% in _active group.
if (trial->group() == FieldTrial::kNotParticipating)
return;
runner = new WebSocketExperimentRunner;
runner->Run();
}
/* static */
void WebSocketExperimentRunner::Stop() {
if (runner.get())
runner->Cancel();
runner = NULL;
}
WebSocketExperimentRunner::WebSocketExperimentRunner()
: next_state_(STATE_NONE),
task_state_(STATE_NONE),
ALLOW_THIS_IN_INITIALIZER_LIST(
task_callback_(this, &WebSocketExperimentRunner::OnTaskCompleted)) {
InitConfig();
}
WebSocketExperimentRunner::~WebSocketExperimentRunner() {
DCHECK(!task_.get());
}
void WebSocketExperimentRunner::Run() {
DCHECK_EQ(next_state_, STATE_NONE);
next_state_ = STATE_RUN_WS;
ChromeThread::PostDelayedTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(this, &WebSocketExperimentRunner::DoLoop),
config_.initial_delay_ms);
}
void WebSocketExperimentRunner::Cancel() {
next_state_ = STATE_NONE;
ChromeThread::PostTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(this, &WebSocketExperimentRunner::DoLoop));
}
void WebSocketExperimentRunner::InitConfig() {
config_.initial_delay_ms = 5 * 60 * 1000; // 5 mins
config_.next_delay_ms = 12 * 60 * 60 * 1000; // 12 hours
WebSocketExperimentTask::Config task_config;
task_config.ws_protocol = "google-websocket-liveexperiment";
task_config.ws_origin = "http://dev.chromium.org/";
task_config.url_fetch_deadline_ms = kUrlFetchDeadlineSec * 1000;
task_config.websocket_onopen_deadline_ms =
kWebSocketConnectDeadlineSec * 1000;
task_config.websocket_hello_message = "Hello";
task_config.websocket_hello_echoback_deadline_ms =
kWebSocketEchoDeadlineSec * 1000;
// Note: wait 1.5 sec in websocket_experiment_def.txt
task_config.websocket_idle_ms = kWebSocketIdleSec * 1000;
task_config.websocket_receive_push_message_deadline_ms =
kWebSocketPushDeadlineSec * 1000;
task_config.websocket_bye_message = "Bye";
task_config.websocket_bye_deadline_ms =
kWebSocketByeDeadlineSec * 1000;
task_config.websocket_close_deadline_ms =
kWebSocketCloseDeadlineSec * 1000;
config_.ws_config = task_config;
config_.ws_config.url =
GURL(StringPrintf("ws://%s/live_exp", kExperimentHost));
config_.ws_config.ws_location =
StringPrintf("ws://%s/live_exp", kExperimentHost);
config_.ws_config.http_url =
GURL(StringPrintf("http://%s/", kExperimentHost));
config_.wss_config = task_config;
config_.wss_config.url =
GURL(StringPrintf("wss://%s/live_exp", kExperimentHost));
config_.wss_config.ws_location =
StringPrintf("wss://%s/live_exp", kExperimentHost);
config_.wss_config.http_url =
GURL(StringPrintf("https://%s/", kExperimentHost));
config_.ws_nondefault_config = task_config;
config_.ws_nondefault_config.url =
GURL(StringPrintf("ws://%s:%d/live_exp",
kExperimentHost, kAlternativePort));
config_.ws_nondefault_config.ws_location =
StringPrintf("ws://%s:%d/live_exp",
kExperimentHost, kAlternativePort);
config_.ws_nondefault_config.http_url =
GURL(StringPrintf("http://%s:%d/",
kExperimentHost, kAlternativePort));
}
void WebSocketExperimentRunner::DoLoop() {
if (next_state_ == STATE_NONE) {
if (task_.get()) {
AddRef(); // Release in OnTaskCompleted.
task_->Cancel();
}
return;
}
State state = next_state_;
task_state_ = STATE_NONE;
next_state_ = STATE_NONE;
switch (state) {
case STATE_IDLE:
task_.reset();
next_state_ = STATE_RUN_WS;
ChromeThread::PostDelayedTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(this, &WebSocketExperimentRunner::DoLoop),
config_.next_delay_ms);
break;
case STATE_RUN_WS:
task_.reset(new WebSocketExperimentTask(config_.ws_config,
&task_callback_));
task_state_ = STATE_RUN_WS;
next_state_ = STATE_RUN_WSS;
break;
case STATE_RUN_WSS:
task_.reset(new WebSocketExperimentTask(config_.wss_config,
&task_callback_));
task_state_ = STATE_RUN_WSS;
next_state_ = STATE_RUN_WS_NODEFAULT_PORT;
break;
case STATE_RUN_WS_NODEFAULT_PORT:
task_.reset(new WebSocketExperimentTask(config_.ws_nondefault_config,
&task_callback_));
task_state_ = STATE_RUN_WS_NODEFAULT_PORT;
next_state_ = STATE_IDLE;
break;
default:
NOTREACHED();
break;
}
if (task_.get())
task_->Run();
}
void WebSocketExperimentRunner::OnTaskCompleted(int result) {
if (result == net::ERR_ABORTED) {
task_.reset();
// Task is Canceled.
DLOG(INFO) << "WebSocketExperiment Task is canceled.";
Release();
return;
}
UpdateTaskResultHistogram(task_.get());
task_.reset();
DoLoop();
}
void WebSocketExperimentRunner::UpdateTaskResultHistogram(
const WebSocketExperimentTask* task) {
DCHECK(task);
const WebSocketExperimentTask::Result& task_result = task->result();
UPDATE_HISTOGRAM("LastState", task_result.last_state,
1, WebSocketExperimentTask::NUM_STATES,
WebSocketExperimentTask::NUM_STATES + 1);
UPDATE_HISTOGRAM_TIMES("UrlFetch", task_result.url_fetch,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(kUrlFetchDeadlineSec),
kTimeBucketCount);
if (task_result.last_state <
WebSocketExperimentTask::STATE_WEBSOCKET_CONNECT_COMPLETE)
return;
UPDATE_HISTOGRAM_TIMES("WebSocketConnect", task_result.websocket_connect,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(
kWebSocketConnectDeadlineSec),
kTimeBucketCount);
if (task_result.last_state <
WebSocketExperimentTask::STATE_WEBSOCKET_RECV_HELLO)
return;
UPDATE_HISTOGRAM_TIMES("WebSocketEcho", task_result.websocket_echo,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(
kWebSocketEchoDeadlineSec),
kTimeBucketCount);
if (task_result.last_state <
WebSocketExperimentTask::STATE_WEBSOCKET_KEEP_IDLE)
return;
UPDATE_HISTOGRAM_TIMES("WebSocketIdle", task_result.websocket_idle,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(
kWebSocketIdleSec + kWebSocketPushDeadlineSec),
kTimeBucketCount);
if (task_result.last_state <
WebSocketExperimentTask::STATE_WEBSOCKET_CLOSE_COMPLETE)
return;
UPDATE_HISTOGRAM_TIMES("WebSocketTotal", task_result.websocket_total,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(kWebSocketTimeSec),
kTimeBucketCount);
}
} // namespace chrome_browser_net_websocket_experiment
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/QR>
template<typename MatrixType> void qr(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
Index rows = m.rows();
Index cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> MatrixQType;
MatrixType a = MatrixType::Random(rows,cols);
HouseholderQR<MatrixType> qrOfA(a);
MatrixQType q = qrOfA.householderQ();
VERIFY_IS_UNITARY(q);
MatrixType r = qrOfA.matrixQR().template triangularView<Upper>();
VERIFY_IS_APPROX(a, qrOfA.householderQ() * r);
}
template<typename MatrixType, int Cols2> void qr_fixedsize()
{
enum { Rows = MatrixType::RowsAtCompileTime, Cols = MatrixType::ColsAtCompileTime };
typedef typename MatrixType::Scalar Scalar;
Matrix<Scalar,Rows,Cols> m1 = Matrix<Scalar,Rows,Cols>::Random();
HouseholderQR<Matrix<Scalar,Rows,Cols> > qr(m1);
Matrix<Scalar,Rows,Cols> r = qr.matrixQR();
// FIXME need better way to construct trapezoid
for(int i = 0; i < Rows; i++) for(int j = 0; j < Cols; j++) if(i>j) r(i,j) = Scalar(0);
VERIFY_IS_APPROX(m1, qr.householderQ() * r);
Matrix<Scalar,Cols,Cols2> m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2);
Matrix<Scalar,Rows,Cols2> m3 = m1*m2;
m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2);
m2 = qr.solve(m3);
VERIFY_IS_APPROX(m3, m1*m2);
}
template<typename MatrixType> void qr_invertible()
{
using std::log;
using std::abs;
typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
typedef typename MatrixType::Scalar Scalar;
int size = internal::random<int>(10,50);
MatrixType m1(size, size), m2(size, size), m3(size, size);
m1 = MatrixType::Random(size,size);
if (internal::is_same<RealScalar,float>::value)
{
// let's build a matrix more stable to inverse
MatrixType a = MatrixType::Random(size,size*2);
m1 += a * a.adjoint();
}
HouseholderQR<MatrixType> qr(m1);
m3 = MatrixType::Random(size,size);
m2 = qr.solve(m3);
VERIFY_IS_APPROX(m3, m1*m2);
// now construct a matrix with prescribed determinant
m1.setZero();
for(int i = 0; i < size; i++) m1(i,i) = internal::random<Scalar>();
RealScalar absdet = abs(m1.diagonal().prod());
m3 = qr.householderQ(); // get a unitary
m1 = m3 * m1 * m3;
qr.compute(m1);
VERIFY_IS_APPROX(absdet, qr.absDeterminant());
VERIFY_IS_APPROX(log(absdet), qr.logAbsDeterminant());
}
template<typename MatrixType> void qr_verify_assert()
{
MatrixType tmp;
HouseholderQR<MatrixType> qr;
VERIFY_RAISES_ASSERT(qr.matrixQR())
VERIFY_RAISES_ASSERT(qr.solve(tmp))
VERIFY_RAISES_ASSERT(qr.householderQ())
VERIFY_RAISES_ASSERT(qr.absDeterminant())
VERIFY_RAISES_ASSERT(qr.logAbsDeterminant())
}
void test_qr()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( qr(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_2( qr(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2),internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2))) );
CALL_SUBTEST_3(( qr_fixedsize<Matrix<float,3,4>, 2 >() ));
CALL_SUBTEST_4(( qr_fixedsize<Matrix<double,6,2>, 4 >() ));
CALL_SUBTEST_5(( qr_fixedsize<Matrix<double,2,5>, 7 >() ));
CALL_SUBTEST_11( qr(Matrix<float,1,1>()) );
}
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( qr_invertible<MatrixXf>() );
CALL_SUBTEST_6( qr_invertible<MatrixXd>() );
CALL_SUBTEST_7( qr_invertible<MatrixXcf>() );
CALL_SUBTEST_8( qr_invertible<MatrixXcd>() );
}
CALL_SUBTEST_9(qr_verify_assert<Matrix3f>());
CALL_SUBTEST_10(qr_verify_assert<Matrix3d>());
CALL_SUBTEST_1(qr_verify_assert<MatrixXf>());
CALL_SUBTEST_6(qr_verify_assert<MatrixXd>());
CALL_SUBTEST_7(qr_verify_assert<MatrixXcf>());
CALL_SUBTEST_8(qr_verify_assert<MatrixXcd>());
// Test problem size constructors
CALL_SUBTEST_12(HouseholderQR<MatrixXf>(10, 20));
}
<commit_msg>reduce false negative in the qr unit test<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/QR>
template<typename MatrixType> void qr(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
Index rows = m.rows();
Index cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> MatrixQType;
MatrixType a = MatrixType::Random(rows,cols);
HouseholderQR<MatrixType> qrOfA(a);
MatrixQType q = qrOfA.householderQ();
VERIFY_IS_UNITARY(q);
MatrixType r = qrOfA.matrixQR().template triangularView<Upper>();
VERIFY_IS_APPROX(a, qrOfA.householderQ() * r);
}
template<typename MatrixType, int Cols2> void qr_fixedsize()
{
enum { Rows = MatrixType::RowsAtCompileTime, Cols = MatrixType::ColsAtCompileTime };
typedef typename MatrixType::Scalar Scalar;
Matrix<Scalar,Rows,Cols> m1 = Matrix<Scalar,Rows,Cols>::Random();
HouseholderQR<Matrix<Scalar,Rows,Cols> > qr(m1);
Matrix<Scalar,Rows,Cols> r = qr.matrixQR();
// FIXME need better way to construct trapezoid
for(int i = 0; i < Rows; i++) for(int j = 0; j < Cols; j++) if(i>j) r(i,j) = Scalar(0);
VERIFY_IS_APPROX(m1, qr.householderQ() * r);
Matrix<Scalar,Cols,Cols2> m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2);
Matrix<Scalar,Rows,Cols2> m3 = m1*m2;
m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2);
m2 = qr.solve(m3);
VERIFY_IS_APPROX(m3, m1*m2);
}
template<typename MatrixType> void qr_invertible()
{
using std::log;
using std::abs;
using std::pow;
using std::max;
typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
typedef typename MatrixType::Scalar Scalar;
int size = internal::random<int>(10,50);
MatrixType m1(size, size), m2(size, size), m3(size, size);
m1 = MatrixType::Random(size,size);
if (internal::is_same<RealScalar,float>::value)
{
// let's build a matrix more stable to inverse
MatrixType a = MatrixType::Random(size,size*4);
m1 += a * a.adjoint();
}
HouseholderQR<MatrixType> qr(m1);
m3 = MatrixType::Random(size,size);
m2 = qr.solve(m3);
VERIFY_IS_APPROX(m3, m1*m2);
// now construct a matrix with prescribed determinant
m1.setZero();
for(int i = 0; i < size; i++) m1(i,i) = internal::random<Scalar>();
RealScalar absdet = abs(m1.diagonal().prod());
m3 = qr.householderQ(); // get a unitary
m1 = m3 * m1 * m3;
qr.compute(m1);
VERIFY_IS_APPROX(log(absdet), qr.logAbsDeterminant());
// This test is tricky if the determinant becomes too small.
// Since we generate random numbers with magnitude rrange [0,1], the average determinant is 0.5^size
VERIFY_IS_MUCH_SMALLER_THAN( abs(absdet-qr.absDeterminant()), (max)(RealScalar(pow(0.5,size)),(max)(abs(absdet),abs(qr.absDeterminant()))) );
}
template<typename MatrixType> void qr_verify_assert()
{
MatrixType tmp;
HouseholderQR<MatrixType> qr;
VERIFY_RAISES_ASSERT(qr.matrixQR())
VERIFY_RAISES_ASSERT(qr.solve(tmp))
VERIFY_RAISES_ASSERT(qr.householderQ())
VERIFY_RAISES_ASSERT(qr.absDeterminant())
VERIFY_RAISES_ASSERT(qr.logAbsDeterminant())
}
void test_qr()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( qr(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_2( qr(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2),internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2))) );
CALL_SUBTEST_3(( qr_fixedsize<Matrix<float,3,4>, 2 >() ));
CALL_SUBTEST_4(( qr_fixedsize<Matrix<double,6,2>, 4 >() ));
CALL_SUBTEST_5(( qr_fixedsize<Matrix<double,2,5>, 7 >() ));
CALL_SUBTEST_11( qr(Matrix<float,1,1>()) );
}
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( qr_invertible<MatrixXf>() );
CALL_SUBTEST_6( qr_invertible<MatrixXd>() );
CALL_SUBTEST_7( qr_invertible<MatrixXcf>() );
CALL_SUBTEST_8( qr_invertible<MatrixXcd>() );
}
CALL_SUBTEST_9(qr_verify_assert<Matrix3f>());
CALL_SUBTEST_10(qr_verify_assert<Matrix3d>());
CALL_SUBTEST_1(qr_verify_assert<MatrixXf>());
CALL_SUBTEST_6(qr_verify_assert<MatrixXd>());
CALL_SUBTEST_7(qr_verify_assert<MatrixXcf>());
CALL_SUBTEST_8(qr_verify_assert<MatrixXcd>());
// Test problem size constructors
CALL_SUBTEST_12(HouseholderQR<MatrixXf>(10, 20));
}
<|endoftext|>
|
<commit_before>#include "testApp.h"
//--------------------------------------------------------------
void testApp::setup()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
ofBackground(10, 10, 10);
camera.setDistance(10);
light.setPosition(10,30,-25);
objectLoader = new waveFrontLoader();
objectLoader->loadFile("test.obj");
mesh = objectLoader->generateMesh();
delete objectLoader;
}
//--------------------------------------------------------------
void testApp::update()
{
}
//--------------------------------------------------------------
void testApp::draw()
{
camera.begin();
light.enable();
mesh.draw();
light.disable();
camera.end();
}
<commit_msg>Update testApp.cpp<commit_after>#include "testApp.h"
//--------------------------------------------------------------
void testApp::setup()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
ofBackground(10, 10, 10);
camera.setDistance(10);
light.setPosition(10,30,-25);
objectLoader = new waveFrontLoader();
objectLoader->loadMaterial(true); //true or false depending on if a .mtl file exists
objectLoader->loadFile("test.obj");
mesh = objectLoader->generateMesh();
delete objectLoader;
}
//--------------------------------------------------------------
void testApp::update()
{
}
//--------------------------------------------------------------
void testApp::draw()
{
camera.begin();
light.enable();
mesh.draw();
light.disable();
camera.end();
}
<|endoftext|>
|
<commit_before>// Copyright 2014 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 "config.h"
#include "modules/screen_orientation/ScreenOrientationController.h"
#include "core/events/Event.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalFrame.h"
#include "core/page/Page.h"
#include "modules/screen_orientation/ScreenOrientation.h"
#include "platform/LayoutTestSupport.h"
#include "platform/PlatformScreen.h"
#include "public/platform/WebScreenOrientationClient.h"
namespace blink {
ScreenOrientationController::~ScreenOrientationController()
{
}
void ScreenOrientationController::persistentHostHasBeenDestroyed()
{
// Unregister lifecycle observation once page is being torn down.
observeContext(0);
}
void ScreenOrientationController::provideTo(LocalFrame& frame, blink::WebScreenOrientationClient* client)
{
ASSERT(RuntimeEnabledFeatures::screenOrientationEnabled());
ScreenOrientationController* controller = new ScreenOrientationController(frame, client);
WillBeHeapSupplement<LocalFrame>::provideTo(frame, supplementName(), adoptPtrWillBeNoop(controller));
}
ScreenOrientationController* ScreenOrientationController::from(LocalFrame& frame)
{
return static_cast<ScreenOrientationController*>(WillBeHeapSupplement<LocalFrame>::from(frame, supplementName()));
}
ScreenOrientationController::ScreenOrientationController(LocalFrame& frame, blink::WebScreenOrientationClient* client)
: PageLifecycleObserver(frame.page())
, m_client(client)
, m_frame(frame)
, m_dispatchEventTimer(this, &ScreenOrientationController::dispatchEventTimerFired)
{
}
const char* ScreenOrientationController::supplementName()
{
return "ScreenOrientationController";
}
// Compute the screen orientation using the orientation angle and the screen width / height.
blink::WebScreenOrientationType ScreenOrientationController::computeOrientation(FrameView* view)
{
// Bypass orientation detection in layout tests to get consistent results.
// FIXME: The screen dimension should be fixed when running the layout tests to avoid such
// issues.
if (LayoutTestSupport::isRunningLayoutTest())
return blink::WebScreenOrientationPortraitPrimary;
FloatRect rect = screenRect(view);
uint16_t rotation = screenOrientationAngle(view);
bool isTallDisplay = rotation % 180 ? rect.height() < rect.width() : rect.height() > rect.width();
switch (rotation) {
case 0:
return isTallDisplay ? blink::WebScreenOrientationPortraitPrimary : blink::WebScreenOrientationLandscapePrimary;
case 90:
return isTallDisplay ? blink::WebScreenOrientationLandscapePrimary : blink::WebScreenOrientationPortraitSecondary;
case 180:
return isTallDisplay ? blink::WebScreenOrientationPortraitSecondary : blink::WebScreenOrientationLandscapeSecondary;
case 270:
return isTallDisplay ? blink::WebScreenOrientationLandscapeSecondary : blink::WebScreenOrientationPortraitPrimary;
default:
ASSERT_NOT_REACHED();
return blink::WebScreenOrientationPortraitPrimary;
}
}
void ScreenOrientationController::updateOrientation()
{
ASSERT(m_orientation);
blink::WebScreenOrientationType orientationType = screenOrientationType(m_frame.view());
if (orientationType == blink::WebScreenOrientationUndefined) {
// The embedder could not provide us with an orientation, deduce it ourselves.
orientationType = computeOrientation(m_frame.view());
}
ASSERT(orientationType != blink::WebScreenOrientationUndefined);
m_orientation->setType(orientationType);
m_orientation->setAngle(screenOrientationAngle(m_frame.view()));
}
void ScreenOrientationController::pageVisibilityChanged()
{
if (!m_orientation || !page() || page()->visibilityState() != PageVisibilityStateVisible)
return;
// The orientation type and angle are tied in a way that if the angle has
// changed, the type must have changed.
unsigned short currentAngle = screenOrientationAngle(m_frame.view());
// FIXME: sendOrientationChangeEvent() currently send an event all the
// children of the frame, so it should only be called on the frame on
// top of the tree. We would need the embedder to call
// sendOrientationChangeEvent on every WebFrame part of a WebView to be
// able to remove this.
if (m_frame == m_frame.localFrameRoot() && m_orientation->angle() != currentAngle)
notifyOrientationChanged();
}
void ScreenOrientationController::notifyOrientationChanged()
{
ASSERT(RuntimeEnabledFeatures::screenOrientationEnabled());
if (!m_orientation || !page() || page()->visibilityState() != PageVisibilityStateVisible)
return;
updateOrientation();
// Keep track of the frames that need to be notified before notifying the
// current frame as it will prevent side effects from the change event
// handlers.
Vector<RefPtr<LocalFrame> > childFrames;
for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling()) {
if (child->isLocalFrame())
childFrames.append(toLocalFrame(child));
}
// Notify current orientation object.
if (!m_dispatchEventTimer.isActive())
m_dispatchEventTimer.startOneShot(0, FROM_HERE);
// ... and child frames, if they have a ScreenOrientationController.
for (size_t i = 0; i < childFrames.size(); ++i) {
ScreenOrientationController* controller = ScreenOrientationController::from(*childFrames[i]);
if (controller)
controller->notifyOrientationChanged();
}
}
void ScreenOrientationController::setOrientation(ScreenOrientation* orientation)
{
m_orientation = orientation;
if (m_orientation)
updateOrientation();
}
void ScreenOrientationController::lock(blink::WebScreenOrientationLockType orientation, blink::WebLockOrientationCallback* callback)
{
if (!m_client) {
return;
}
m_client->lockOrientation(orientation, callback);
}
void ScreenOrientationController::unlock()
{
if (!m_client) {
return;
}
m_client->unlockOrientation();
}
const LocalFrame& ScreenOrientationController::frame() const
{
return m_frame;
}
void ScreenOrientationController::dispatchEventTimerFired(Timer<ScreenOrientationController>*)
{
if (!m_orientation)
return;
m_orientation->dispatchEvent(Event::create(EventTypeNames::change));
}
void ScreenOrientationController::trace(Visitor* visitor)
{
visitor->trace(m_orientation);
WillBeHeapSupplement<LocalFrame>::trace(visitor);
}
} // namespace blink
<commit_msg>ASSERT in ScreenOrientationController::{un,}lock() if no m_client.<commit_after>// Copyright 2014 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 "config.h"
#include "modules/screen_orientation/ScreenOrientationController.h"
#include "core/events/Event.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalFrame.h"
#include "core/page/Page.h"
#include "modules/screen_orientation/ScreenOrientation.h"
#include "platform/LayoutTestSupport.h"
#include "platform/PlatformScreen.h"
#include "public/platform/WebScreenOrientationClient.h"
namespace blink {
ScreenOrientationController::~ScreenOrientationController()
{
}
void ScreenOrientationController::persistentHostHasBeenDestroyed()
{
// Unregister lifecycle observation once page is being torn down.
observeContext(0);
}
void ScreenOrientationController::provideTo(LocalFrame& frame, blink::WebScreenOrientationClient* client)
{
ASSERT(RuntimeEnabledFeatures::screenOrientationEnabled());
ScreenOrientationController* controller = new ScreenOrientationController(frame, client);
WillBeHeapSupplement<LocalFrame>::provideTo(frame, supplementName(), adoptPtrWillBeNoop(controller));
}
ScreenOrientationController* ScreenOrientationController::from(LocalFrame& frame)
{
return static_cast<ScreenOrientationController*>(WillBeHeapSupplement<LocalFrame>::from(frame, supplementName()));
}
ScreenOrientationController::ScreenOrientationController(LocalFrame& frame, blink::WebScreenOrientationClient* client)
: PageLifecycleObserver(frame.page())
, m_client(client)
, m_frame(frame)
, m_dispatchEventTimer(this, &ScreenOrientationController::dispatchEventTimerFired)
{
}
const char* ScreenOrientationController::supplementName()
{
return "ScreenOrientationController";
}
// Compute the screen orientation using the orientation angle and the screen width / height.
blink::WebScreenOrientationType ScreenOrientationController::computeOrientation(FrameView* view)
{
// Bypass orientation detection in layout tests to get consistent results.
// FIXME: The screen dimension should be fixed when running the layout tests to avoid such
// issues.
if (LayoutTestSupport::isRunningLayoutTest())
return blink::WebScreenOrientationPortraitPrimary;
FloatRect rect = screenRect(view);
uint16_t rotation = screenOrientationAngle(view);
bool isTallDisplay = rotation % 180 ? rect.height() < rect.width() : rect.height() > rect.width();
switch (rotation) {
case 0:
return isTallDisplay ? blink::WebScreenOrientationPortraitPrimary : blink::WebScreenOrientationLandscapePrimary;
case 90:
return isTallDisplay ? blink::WebScreenOrientationLandscapePrimary : blink::WebScreenOrientationPortraitSecondary;
case 180:
return isTallDisplay ? blink::WebScreenOrientationPortraitSecondary : blink::WebScreenOrientationLandscapeSecondary;
case 270:
return isTallDisplay ? blink::WebScreenOrientationLandscapeSecondary : blink::WebScreenOrientationPortraitPrimary;
default:
ASSERT_NOT_REACHED();
return blink::WebScreenOrientationPortraitPrimary;
}
}
void ScreenOrientationController::updateOrientation()
{
ASSERT(m_orientation);
blink::WebScreenOrientationType orientationType = screenOrientationType(m_frame.view());
if (orientationType == blink::WebScreenOrientationUndefined) {
// The embedder could not provide us with an orientation, deduce it ourselves.
orientationType = computeOrientation(m_frame.view());
}
ASSERT(orientationType != blink::WebScreenOrientationUndefined);
m_orientation->setType(orientationType);
m_orientation->setAngle(screenOrientationAngle(m_frame.view()));
}
void ScreenOrientationController::pageVisibilityChanged()
{
if (!m_orientation || !page() || page()->visibilityState() != PageVisibilityStateVisible)
return;
// The orientation type and angle are tied in a way that if the angle has
// changed, the type must have changed.
unsigned short currentAngle = screenOrientationAngle(m_frame.view());
// FIXME: sendOrientationChangeEvent() currently send an event all the
// children of the frame, so it should only be called on the frame on
// top of the tree. We would need the embedder to call
// sendOrientationChangeEvent on every WebFrame part of a WebView to be
// able to remove this.
if (m_frame == m_frame.localFrameRoot() && m_orientation->angle() != currentAngle)
notifyOrientationChanged();
}
void ScreenOrientationController::notifyOrientationChanged()
{
ASSERT(RuntimeEnabledFeatures::screenOrientationEnabled());
if (!m_orientation || !page() || page()->visibilityState() != PageVisibilityStateVisible)
return;
updateOrientation();
// Keep track of the frames that need to be notified before notifying the
// current frame as it will prevent side effects from the change event
// handlers.
Vector<RefPtr<LocalFrame> > childFrames;
for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling()) {
if (child->isLocalFrame())
childFrames.append(toLocalFrame(child));
}
// Notify current orientation object.
if (!m_dispatchEventTimer.isActive())
m_dispatchEventTimer.startOneShot(0, FROM_HERE);
// ... and child frames, if they have a ScreenOrientationController.
for (size_t i = 0; i < childFrames.size(); ++i) {
ScreenOrientationController* controller = ScreenOrientationController::from(*childFrames[i]);
if (controller)
controller->notifyOrientationChanged();
}
}
void ScreenOrientationController::setOrientation(ScreenOrientation* orientation)
{
m_orientation = orientation;
if (m_orientation)
updateOrientation();
}
void ScreenOrientationController::lock(blink::WebScreenOrientationLockType orientation, blink::WebLockOrientationCallback* callback)
{
ASSERT(m_client);
m_client->lockOrientation(orientation, callback);
}
void ScreenOrientationController::unlock()
{
ASSERT(m_client);
m_client->unlockOrientation();
}
const LocalFrame& ScreenOrientationController::frame() const
{
return m_frame;
}
void ScreenOrientationController::dispatchEventTimerFired(Timer<ScreenOrientationController>*)
{
if (!m_orientation)
return;
m_orientation->dispatchEvent(Event::create(EventTypeNames::change));
}
void ScreenOrientationController::trace(Visitor* visitor)
{
visitor->trace(m_orientation);
WillBeHeapSupplement<LocalFrame>::trace(visitor);
}
} // namespace blink
<|endoftext|>
|
<commit_before>//==============================================================================
// Single cell simulation graph panels widget
//==============================================================================
#include "singlecellsimulationgraphpanel.h"
#include "singlecellsimulationgraphpanels.h"
//==============================================================================
#include <QSettings>
#include <QWheelEvent>
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulation {
//==============================================================================
SingleCellSimulationGraphPanels::SingleCellSimulationGraphPanels(const QString &pName,
QWidget *pParent) :
QSplitter(Qt::Vertical, pParent),
CommonWidget(pName, this, pParent),
mGraphPanelsCount(0)
{
}
//==============================================================================
static const QString SettingsGraphPanelsCount = "GraphPanelsCount";
//==============================================================================
void SingleCellSimulationGraphPanels::loadSettings(QSettings *pSettings)
{
// Retrieve the number of graph panels (default: 1) and create the
// corresponding number of graphs
int graphPanelsCount = pSettings->value(SettingsGraphPanelsCount, 1).toInt();
for (int i = 0; i < graphPanelsCount; ++i)
addGraphPanel();
// Select the first graph panel
qobject_cast<SingleCellSimulationGraphPanel *>(widget(0))->setActive(true);
}
//==============================================================================
void SingleCellSimulationGraphPanels::saveSettings(QSettings *pSettings) const
{
// Keep track of the number of graph panels
pSettings->setValue(SettingsGraphPanelsCount, mGraphPanelsCount);
}
//==============================================================================
void SingleCellSimulationGraphPanels::wheelEvent(QWheelEvent *pEvent)
{
// Default handling of the event
QSplitter::wheelEvent(pEvent);
// Select the previous/next graph panel, if any
if (pEvent->delta())
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive()) {
// We are dealing with the currently active graph panel, so
// inactivate it and activate either its predecessor or successor
graphPanel->setActive(false);
i += (pEvent->delta() < 0)?1:-1;
if (i < 0)
i = 0;
else if (i == iMax)
i = iMax-1;
qobject_cast<SingleCellSimulationGraphPanel *>(widget(i))->setActive(true);
break;
}
}
}
//==============================================================================
SingleCellSimulationGraphPanel * SingleCellSimulationGraphPanels::addGraphPanel()
{
// Check whether there is already a graph panel and if not, then delete our
// dummy widget which ensures that we don't shrink
if (!mGraphPanelsCount && count()) {
// No previous graph panel, so...
// Note: the test for count() above is for the very first time we want
// to add a graph panel and therefore where no dummy widget will
// be present...
QWidget *dummyWidget = qobject_cast<QWidget*>(widget(0));
dummyWidget->hide();
delete dummyWidget;
}
// Create a new graph panel
SingleCellSimulationGraphPanel *res = new SingleCellSimulationGraphPanel(this);
// Add the graph panel to ourselves
addWidget(res);
// Keep track of the fact that we are holding one more graph panel
++mGraphPanelsCount;
// Create a connection to keep track of whenever the graph panel gets
// activated
connect(res, SIGNAL(activated(SingleCellSimulationGraphPanel *)),
this, SLOT(graphPanelActivated(SingleCellSimulationGraphPanel *)));
// Activate it
res->setActive(true);
// Let people know that we have added a graph panel
emit grapPanelAdded(res);
// Return our newly created graph panel
return res;
}
//==============================================================================
void SingleCellSimulationGraphPanels::removeGraphPanel()
{
if (!mGraphPanelsCount)
// We don't have any graph panel to remove, so...
return;
// Remove the current graph panel
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive()) {
// We are dealing with the currently active graph panel, so remove
// it
graphPanel->hide();
delete graphPanel;
// Keep track of the fact that we are holding one less graph panel
--mGraphPanelsCount;
// Activate the next graph panel or the last one available, if any
iMax = count();
if (!iMax)
// No more graph panel, so...
break;
else if (i < iMax)
// There is a next graph panel, so activate it
qobject_cast<SingleCellSimulationGraphPanel *>(widget(i))->setActive(true);
else
// We were dealing with the last graph panel, but there is still
// at least one left, so activate the new last graph panel
qobject_cast<SingleCellSimulationGraphPanel *>(widget(count()-1))->setActive(true);
// We are all done, so...
break;
}
}
// Check whether we have any graph panel left and if so add a dummy widget
// which will ensure that we don't shrink
if (!mGraphPanelsCount)
addWidget(new QWidget(this));
// Let people know that we have removed a graph panel
emit grapPanelRemoved();
}
//==============================================================================
int SingleCellSimulationGraphPanels::graphPanelsCount() const
{
// Return the number of graph panels we currently hold
return mGraphPanelsCount;
}
//==============================================================================
SingleCellSimulationGraphPanel * SingleCellSimulationGraphPanels::activeGraphPanel()
{
// Return the active graph panel
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive())
// We found the active graph panel, so...
return graphPanel;
}
// There are no graph panels, so...
// Note: indeed, since if there is at least one graph panel, then we have an
// active graph panel...
return 0;
}
//==============================================================================
void SingleCellSimulationGraphPanels::graphPanelActivated(SingleCellSimulationGraphPanel *pGraphPanel)
{
// A graph panel has been activated, so inactivate all the others
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel != pGraphPanel)
// We are not dealing with the graph panel that just got activated,
// so inactivate it
graphPanel->setActive(false);
}
}
//==============================================================================
} // namespace SingleCellSimulation
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Closes #54 (again!).<commit_after>//==============================================================================
// Single cell simulation graph panels widget
//==============================================================================
#include "singlecellsimulationgraphpanel.h"
#include "singlecellsimulationgraphpanels.h"
//==============================================================================
#include <QSettings>
#include <QWheelEvent>
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulation {
//==============================================================================
SingleCellSimulationGraphPanels::SingleCellSimulationGraphPanels(const QString &pName,
QWidget *pParent) :
QSplitter(Qt::Vertical, pParent),
CommonWidget(pName, this, pParent),
mGraphPanelsCount(0)
{
}
//==============================================================================
static const QString SettingsGraphPanelsCount = "GraphPanelsCount";
//==============================================================================
void SingleCellSimulationGraphPanels::loadSettings(QSettings *pSettings)
{
// Retrieve the number of graph panels (default: 1) and create the
// corresponding number of graphs
int graphPanelsCount = pSettings->value(SettingsGraphPanelsCount, 1).toInt();
for (int i = 0; i < graphPanelsCount; ++i)
addGraphPanel();
// Select the first graph panel
qobject_cast<SingleCellSimulationGraphPanel *>(widget(0))->setActive(true);
}
//==============================================================================
void SingleCellSimulationGraphPanels::saveSettings(QSettings *pSettings) const
{
// Keep track of the number of graph panels
pSettings->setValue(SettingsGraphPanelsCount, mGraphPanelsCount);
}
//==============================================================================
void SingleCellSimulationGraphPanels::wheelEvent(QWheelEvent *pEvent)
{
// Default handling of the event
QSplitter::wheelEvent(pEvent);
// Select the previous/next graph panel, if any
if (pEvent->delta())
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive()) {
// We are dealing with the currently active graph panel, so
// inactivate it and activate either its predecessor or successor
graphPanel->setActive(false);
#ifdef Q_WS_MAC
i -= (pEvent->delta() < 0)?1:-1;
#else
i += (pEvent->delta() < 0)?1:-1;
#endif
if (i < 0)
i = 0;
else if (i == iMax)
i = iMax-1;
qobject_cast<SingleCellSimulationGraphPanel *>(widget(i))->setActive(true);
break;
}
}
}
//==============================================================================
SingleCellSimulationGraphPanel * SingleCellSimulationGraphPanels::addGraphPanel()
{
// Check whether there is already a graph panel and if not, then delete our
// dummy widget which ensures that we don't shrink
if (!mGraphPanelsCount && count()) {
// No previous graph panel, so...
// Note: the test for count() above is for the very first time we want
// to add a graph panel and therefore where no dummy widget will
// be present...
QWidget *dummyWidget = qobject_cast<QWidget*>(widget(0));
dummyWidget->hide();
delete dummyWidget;
}
// Create a new graph panel
SingleCellSimulationGraphPanel *res = new SingleCellSimulationGraphPanel(this);
// Add the graph panel to ourselves
addWidget(res);
// Keep track of the fact that we are holding one more graph panel
++mGraphPanelsCount;
// Create a connection to keep track of whenever the graph panel gets
// activated
connect(res, SIGNAL(activated(SingleCellSimulationGraphPanel *)),
this, SLOT(graphPanelActivated(SingleCellSimulationGraphPanel *)));
// Activate it
res->setActive(true);
// Let people know that we have added a graph panel
emit grapPanelAdded(res);
// Return our newly created graph panel
return res;
}
//==============================================================================
void SingleCellSimulationGraphPanels::removeGraphPanel()
{
if (!mGraphPanelsCount)
// We don't have any graph panel to remove, so...
return;
// Remove the current graph panel
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive()) {
// We are dealing with the currently active graph panel, so remove
// it
graphPanel->hide();
delete graphPanel;
// Keep track of the fact that we are holding one less graph panel
--mGraphPanelsCount;
// Activate the next graph panel or the last one available, if any
iMax = count();
if (!iMax)
// No more graph panel, so...
break;
else if (i < iMax)
// There is a next graph panel, so activate it
qobject_cast<SingleCellSimulationGraphPanel *>(widget(i))->setActive(true);
else
// We were dealing with the last graph panel, but there is still
// at least one left, so activate the new last graph panel
qobject_cast<SingleCellSimulationGraphPanel *>(widget(count()-1))->setActive(true);
// We are all done, so...
break;
}
}
// Check whether we have any graph panel left and if so add a dummy widget
// which will ensure that we don't shrink
if (!mGraphPanelsCount)
addWidget(new QWidget(this));
// Let people know that we have removed a graph panel
emit grapPanelRemoved();
}
//==============================================================================
int SingleCellSimulationGraphPanels::graphPanelsCount() const
{
// Return the number of graph panels we currently hold
return mGraphPanelsCount;
}
//==============================================================================
SingleCellSimulationGraphPanel * SingleCellSimulationGraphPanels::activeGraphPanel()
{
// Return the active graph panel
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive())
// We found the active graph panel, so...
return graphPanel;
}
// There are no graph panels, so...
// Note: indeed, since if there is at least one graph panel, then we have an
// active graph panel...
return 0;
}
//==============================================================================
void SingleCellSimulationGraphPanels::graphPanelActivated(SingleCellSimulationGraphPanel *pGraphPanel)
{
// A graph panel has been activated, so inactivate all the others
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel != pGraphPanel)
// We are not dealing with the graph panel that just got activated,
// so inactivate it
graphPanel->setActive(false);
}
}
//==============================================================================
} // namespace SingleCellSimulation
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012-2013 Razor team
* Authors:
* Petr Vanek <petr@scribus.info>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include <QDir>
#include "lxqtapplication.h"
#include "lxqtsettings.h"
#include <XdgDirs>
using namespace LXQt;
#define COLOR_DEBUG "\033[32;2m"
#define COLOR_WARN "\033[33;2m"
#define COLOR_CRITICAL "\033[31;1m"
#define COLOR_FATAL "\033[33;1m"
#define COLOR_RESET "\033[0m"
#define QAPP_NAME qApp ? qApp->objectName().toUtf8().constData() : ""
#include <cstdio>
#include <unistd.h>
#include <cstring>
#include <csignal>
#include <sys/socket.h>
#include <QDateTime>
#include <QDebug>
#include <QSocketNotifier>
/*! \brief Log qDebug input to file
Used only in pure Debug builds or when is the system environment
variable LXQT_DEBUG set
*/
void dbgMessageOutput(QtMsgType type, const QMessageLogContext &ctx, const QString & msgStr)
{
QByteArray msgBuf = msgStr.toUtf8();
const char* msg = msgBuf.constData();
QDir dir(XdgDirs::configHome().toUtf8() + QLatin1String("/lxqt"));
dir.mkpath(".");
const char* typestr;
const char* color;
switch (type) {
case QtDebugMsg:
typestr = "Debug";
color = COLOR_DEBUG;
break;
case QtWarningMsg:
typestr = "Warning";
color = COLOR_WARN;
break;
case QtFatalMsg:
typestr = "Fatal";
color = COLOR_FATAL;
break;
default: // QtCriticalMsg
typestr = "Critical";
color = COLOR_CRITICAL;
}
QByteArray dt = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz").toUtf8();
if (isatty(STDERR_FILENO))
fprintf(stderr, "%s %s(%p) %s: %s%s\n", color, QAPP_NAME, qApp, typestr, msg, COLOR_RESET);
else
fprintf(stderr, "%s(%p) %s: %s\n", QAPP_NAME, qApp, typestr, msg);
FILE *f = fopen(dir.absoluteFilePath("debug.log").toUtf8().constData(), "a+");
fprintf(f, "%s %s(%p) %s: %s\n", dt.constData(), QAPP_NAME, qApp, typestr, msg);
fclose(f);
if (type == QtFatalMsg)
abort();
}
Application::Application(int &argc, char** argv)
: QApplication(argc, argv)
{
#ifdef DEBUG
qInstallMessageHandler(dbgMessageOutput);
#else
if (!qgetenv("LXQT_DEBUG").isNull())
qInstallMessageHandler(dbgMessageOutput);
#endif
setWindowIcon(QIcon(QString(LXQT_GRAPHICS_DIR) + "/lxqt_logo.png"));
connect(Settings::globalSettings(), SIGNAL(lxqtThemeChanged()), this, SLOT(updateTheme()));
updateTheme();
}
Application::Application(int &argc, char** argv, bool handleQuitSignals)
: Application(argc, argv)
{
if (handleQuitSignals)
{
QList<int> signo_list = {SIGINT, SIGTERM, SIGHUP};
connect(this, &Application::unixSignal, [this, signo_list] (int signo)
{
if (signo_list.contains(signo))
quit();
});
listenToUnixSignals(signo_list);
}
}
void Application::updateTheme()
{
QString styleSheetKey = QFileInfo(applicationFilePath()).fileName();
setStyleSheet(lxqtTheme.qss(styleSheetKey));
emit themeChanged();
}
namespace
{
int signal_sock[2];
void signalHandler(int signo)
{
int ret = write(signal_sock[0], &signo, sizeof (int));
if (sizeof (int) != ret)
qCritical() << QStringLiteral("unable to write into socketpair, %1").arg(strerror(errno));
}
}
void Application::listenToUnixSignals(QList<int> const & signoList)
{
static QSocketNotifier * signal_notifier = nullptr;
if (nullptr == signal_notifier)
{
if (0 != socketpair(AF_UNIX, SOCK_STREAM, 0, signal_sock))
{
qCritical() << QStringLiteral("unable to create socketpair for correct signal handling: %1)").arg(strerror(errno));
return;
}
signal_notifier = new QSocketNotifier(signal_sock[1], QSocketNotifier::Read, this);
connect(signal_notifier, &QSocketNotifier::activated, [this] {
int signo = 0;
int ret = read(signal_sock[1], &signo, sizeof (int));
if (sizeof (int) != ret)
qCritical() << QStringLiteral("unable to read signal from socketpair, %1").arg(strerror(errno));
emit unixSignal(signo);
});
}
struct sigaction sa;
sa.sa_handler = signalHandler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
for (auto const & signo : signoList)
sigaction(signo, &sa, nullptr);
}
<commit_msg>application: Correct signal handling & clean-up (#72)<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012-2013 Razor team
* Authors:
* Petr Vanek <petr@scribus.info>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include <QDir>
#include "lxqtapplication.h"
#include "lxqtsettings.h"
#include <XdgDirs>
using namespace LXQt;
#define COLOR_DEBUG "\033[32;2m"
#define COLOR_WARN "\033[33;2m"
#define COLOR_CRITICAL "\033[31;1m"
#define COLOR_FATAL "\033[33;1m"
#define COLOR_RESET "\033[0m"
#define QAPP_NAME qApp ? qApp->objectName().toUtf8().constData() : ""
#include <cstdio>
#include <unistd.h>
#include <cstring>
#include <csignal>
#include <sys/socket.h>
#include <QDateTime>
#include <QDebug>
#include <QSocketNotifier>
/*! \brief Log qDebug input to file
Used only in pure Debug builds or when is the system environment
variable LXQT_DEBUG set
*/
void dbgMessageOutput(QtMsgType type, const QMessageLogContext &ctx, const QString & msgStr)
{
QByteArray msgBuf = msgStr.toUtf8();
const char* msg = msgBuf.constData();
QDir dir(XdgDirs::configHome().toUtf8() + QLatin1String("/lxqt"));
dir.mkpath(".");
const char* typestr;
const char* color;
switch (type) {
case QtDebugMsg:
typestr = "Debug";
color = COLOR_DEBUG;
break;
case QtWarningMsg:
typestr = "Warning";
color = COLOR_WARN;
break;
case QtFatalMsg:
typestr = "Fatal";
color = COLOR_FATAL;
break;
default: // QtCriticalMsg
typestr = "Critical";
color = COLOR_CRITICAL;
}
QByteArray dt = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz").toUtf8();
if (isatty(STDERR_FILENO))
fprintf(stderr, "%s %s(%p) %s: %s%s\n", color, QAPP_NAME, qApp, typestr, msg, COLOR_RESET);
else
fprintf(stderr, "%s(%p) %s: %s\n", QAPP_NAME, qApp, typestr, msg);
FILE *f = fopen(dir.absoluteFilePath("debug.log").toUtf8().constData(), "a+");
fprintf(f, "%s %s(%p) %s: %s\n", dt.constData(), QAPP_NAME, qApp, typestr, msg);
fclose(f);
if (type == QtFatalMsg)
abort();
}
Application::Application(int &argc, char** argv)
: QApplication(argc, argv)
{
#ifdef DEBUG
qInstallMessageHandler(dbgMessageOutput);
#else
if (!qgetenv("LXQT_DEBUG").isNull())
qInstallMessageHandler(dbgMessageOutput);
#endif
setWindowIcon(QIcon(QString(LXQT_GRAPHICS_DIR) + "/lxqt_logo.png"));
connect(Settings::globalSettings(), SIGNAL(lxqtThemeChanged()), this, SLOT(updateTheme()));
updateTheme();
}
Application::Application(int &argc, char** argv, bool handleQuitSignals)
: Application(argc, argv)
{
if (handleQuitSignals)
{
QList<int> signo_list = {SIGINT, SIGTERM, SIGHUP};
connect(this, &Application::unixSignal, [this, signo_list] (int signo)
{
if (signo_list.contains(signo))
quit();
});
listenToUnixSignals(signo_list);
}
}
void Application::updateTheme()
{
QString styleSheetKey = QFileInfo(applicationFilePath()).fileName();
setStyleSheet(lxqtTheme.qss(styleSheetKey));
emit themeChanged();
}
namespace
{
class SignalHandler
{
public:
static void signalHandler(int signo)
{
int ret = write(instance->mSignalSock[0], &signo, sizeof (int));
if (sizeof (int) != ret)
qCritical() << QStringLiteral("unable to write into socketpair, %1").arg(strerror(errno));
}
public:
template <class Lambda>
SignalHandler(Lambda signalEmitter)
: mSignalSock{-1, -1}
{
if (0 != socketpair(AF_UNIX, SOCK_STREAM, 0, mSignalSock))
{
qCritical() << QStringLiteral("unable to create socketpair for correct signal handling: %1)").arg(strerror(errno));
return;
}
mNotifier.reset(new QSocketNotifier(mSignalSock[1], QSocketNotifier::Read));
QObject::connect(mNotifier.data(), &QSocketNotifier::activated, [this, signalEmitter] {
int signo = 0;
int ret = read(mSignalSock[1], &signo, sizeof (int));
if (sizeof (int) != ret)
qCritical() << QStringLiteral("unable to read signal from socketpair, %1").arg(strerror(errno));
signalEmitter(signo);
});
}
~SignalHandler()
{
close(mSignalSock[0]);
close(mSignalSock[1]);
}
void listenToSignals(QList<int> const & signoList)
{
struct sigaction sa;
sa.sa_handler = signalHandler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
for (auto const & signo : signoList)
sigaction(signo, &sa, nullptr);
}
public:
static QScopedPointer<SignalHandler> instance;
private:
int mSignalSock[2];
QScopedPointer<QSocketNotifier> mNotifier;
};
QScopedPointer<SignalHandler> SignalHandler::instance;
}
void Application::listenToUnixSignals(QList<int> const & signoList)
{
static QScopedPointer<QSocketNotifier> signal_notifier;
if (SignalHandler::instance.isNull())
SignalHandler::instance.reset(new SignalHandler{[this] (int signo) { emit unixSignal(signo); }});
SignalHandler::instance->listenToSignals(signoList);
}
<|endoftext|>
|
<commit_before>#include <QImage>
#include "raster.h"
#include "pixeliterator.h"
#include "rootdrawer.h"
#include "factory.h"
#include "abstractfactory.h"
#include "drawers/rasterimagefactory.h"
#include "drawers/attributevisualproperties.h"
#include "rastervalueimage.h"
using namespace Ilwis;
using namespace Geodrawer;
REGISTER_RASTERIMAGETYPE(RasterValueImage,itNUMERICDOMAIN);
RasterValueImage::RasterValueImage(DrawerInterface *rootDrawer, const IRasterCoverage& raster, const VisualAttribute &vattribute,const IOOptions &options) :
RasterImage(rootDrawer,raster,vattribute, options)
{
}
RasterValueImage::~RasterValueImage()
{
}
RasterImage *RasterValueImage::create(DrawerInterface *rootDrawer, const IRasterCoverage& raster, const VisualAttribute &vattribute,const IOOptions &options)
{
return new RasterValueImage(rootDrawer, raster, vattribute, options) ;
}
bool RasterValueImage::prepare(int prepareType)
{
bool resetImage = false;
BoundingBox bb(_raster->size());
int xl = (quint32)bb.xlength() % 4 == 0 ? bb.xlength() : (((quint32)bb.xlength() / 4) + 1) * 4;
int rest = xl - bb.xlength();
if ( hasType(prepareType, DrawerInterface::ptRENDER)){
std::vector<QColor> colors = _visualAttribute.colors();
_colorTable = QVector<QRgb>(colors.size()) ;
for(int i = 0; i < _colorTable.size(); ++i)
_colorTable[i] = colors[i].rgba();
resetImage = true;
}
if ( hasType(prepareType, DrawerInterface::ptGEOMETRY)){
quint32 size = xl * bb.ylength();
_pixels.resize(size);
PixelIterator pixIter(_raster);
SPNumericRange numrange = _raster->datadef().range<NumericRange>();
auto end = pixIter.end();
quint32 position = 0;
while(pixIter != end){
double value = *pixIter;
int index = value == rUNDEF ? 0 : 1 + (_colorTable.size() - 1) * (value - numrange->min()) / numrange->distance();
_pixels[position] = index;
++pixIter;
if ( pixIter.ychanged()){
position += rest;
}
++position;
}
resetImage = true;
}
if ( resetImage) {
const uchar *datablock = (const uchar *)_pixels.data();
_image.reset(new QImage(datablock,xl, bb.ylength(),QImage::Format_Indexed8));
_image->setColorTable(_colorTable);
}
return resetImage;
}
<commit_msg>comments<commit_after>#include <QImage>
#include "raster.h"
#include "pixeliterator.h"
#include "rootdrawer.h"
#include "factory.h"
#include "abstractfactory.h"
#include "drawers/rasterimagefactory.h"
#include "drawers/attributevisualproperties.h"
#include "rastervalueimage.h"
using namespace Ilwis;
using namespace Geodrawer;
REGISTER_RASTERIMAGETYPE(RasterValueImage,itNUMERICDOMAIN);
RasterValueImage::RasterValueImage(DrawerInterface *rootDrawer, const IRasterCoverage& raster, const VisualAttribute &vattribute,const IOOptions &options) :
RasterImage(rootDrawer,raster,vattribute, options)
{
}
RasterValueImage::~RasterValueImage()
{
}
RasterImage *RasterValueImage::create(DrawerInterface *rootDrawer, const IRasterCoverage& raster, const VisualAttribute &vattribute,const IOOptions &options)
{
return new RasterValueImage(rootDrawer, raster, vattribute, options) ;
}
bool RasterValueImage::prepare(int prepareType)
{
bool resetImage = false;
BoundingBox bb(_raster->size());
// lines must be 32 bit alligned. an entry pixel is a byte, so everything must be 4 alligned (32 bit is 4 bytes)
int xl = (quint32)bb.xlength() % 4 == 0 ? bb.xlength() : (((quint32)bb.xlength() / 4) + 1) * 4;
int rest = xl - bb.xlength();
if ( hasType(prepareType, DrawerInterface::ptRENDER)){
std::vector<QColor> colors = _visualAttribute.colors();
_colorTable = QVector<QRgb>(colors.size()) ;
for(int i = 0; i < _colorTable.size(); ++i)
_colorTable[i] = colors[i].rgba();
resetImage = true;
}
if ( hasType(prepareType, DrawerInterface::ptGEOMETRY)){
quint32 size = xl * bb.ylength();
_pixels.resize(size);
PixelIterator pixIter(_raster);
SPNumericRange numrange = _raster->datadef().range<NumericRange>();
auto end = pixIter.end();
quint32 position = 0;
while(pixIter != end){
double value = *pixIter;
int index = value == rUNDEF ? 0 : 1 + (_colorTable.size() - 1) * (value - numrange->min()) / numrange->distance();
_pixels[position] = index;
++pixIter;
if ( pixIter.ychanged()){
position += rest;
}
++position;
}
resetImage = true;
}
if ( resetImage) {
const uchar *datablock = (const uchar *)_pixels.data();
_image.reset(new QImage(datablock,xl, bb.ylength(),QImage::Format_Indexed8));
_image->setColorTable(_colorTable);
}
return resetImage;
}
<|endoftext|>
|
<commit_before>//===--- DiagnosticConsumer.cpp - Diagnostic Consumer Impl ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the DiagnosticConsumer class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "swift-ast"
#include "swift/AST/DiagnosticConsumer.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/SourceManager.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
DiagnosticConsumer::~DiagnosticConsumer() = default;
llvm::SMLoc DiagnosticConsumer::getRawLoc(SourceLoc loc) {
return loc.Value;
}
LLVM_ATTRIBUTE_UNUSED
static bool hasDuplicateFileNames(
ArrayRef<FileSpecificDiagnosticConsumer::ConsumerPair> consumers) {
llvm::StringSet<> seenFiles;
for (const auto &consumerPair : consumers) {
if (consumerPair.first.empty()) {
// We can handle multiple consumers that aren't associated with any file,
// because they only collect diagnostics that aren't in any of the special
// files. This isn't an important use case to support, but also SmallSet
// doesn't handle empty strings anyway!
continue;
}
bool isUnique = seenFiles.insert(consumerPair.first).second;
if (!isUnique)
return true;
}
return false;
}
FileSpecificDiagnosticConsumer::FileSpecificDiagnosticConsumer(
SmallVectorImpl<ConsumerPair> &consumers)
: SubConsumers(std::move(consumers)) {
assert(!SubConsumers.empty() &&
"don't waste time handling diagnostics that will never get emitted");
assert(!hasDuplicateFileNames(SubConsumers) &&
"having multiple consumers for the same file is not implemented");
}
void FileSpecificDiagnosticConsumer::computeConsumersOrderedByRange(
SourceManager &SM) {
// Look up each file's source range and add it to the "map" (to be sorted).
for (const ConsumerPair &pair : SubConsumers) {
if (pair.first.empty())
continue;
Optional<unsigned> bufferID = SM.getIDForBufferIdentifier(pair.first);
assert(bufferID.hasValue() && "consumer registered for unknown file");
CharSourceRange range = SM.getRangeForBuffer(bufferID.getValue());
ConsumersOrderedByRange.emplace_back(
ConsumerSpecificInformation(range, pair.second.get()));
}
// Sort the "map" by buffer /end/ location, for use with std::lower_bound
// later. (Sorting by start location would produce the same sort, since the
// ranges must not be overlapping, but since we need to check end locations
// later it's consistent to sort by that here.)
std::sort(ConsumersOrderedByRange.begin(), ConsumersOrderedByRange.end(),
[](const ConsumerSpecificInformation &left,
const ConsumerSpecificInformation &right) -> bool {
auto compare = std::less<const char *>();
return compare(getRawLoc(left.range.getEnd()).getPointer(),
getRawLoc(right.range.getEnd()).getPointer());
});
// Check that the ranges are non-overlapping. If the files really are all
// distinct, this should be trivially true, but if it's ever not we might end
// up mis-filing diagnostics.
assert(ConsumersOrderedByRange.end() ==
std::adjacent_find(ConsumersOrderedByRange.begin(),
ConsumersOrderedByRange.end(),
[](const ConsumerSpecificInformation &left,
const ConsumerSpecificInformation &right) {
return left.range.overlaps(right.range);
}) &&
"overlapping ranges despite having distinct files");
}
Optional<FileSpecificDiagnosticConsumer::ConsumerSpecificInformation *>
FileSpecificDiagnosticConsumer::consumerSpecificInformationForLocation(
SourceManager &SM, SourceLoc loc) const {
// Diagnostics with invalid locations always go to every consumer.
if (loc.isInvalid())
return None;
// This map is generated on first use and cached, to allow the
// FileSpecificDiagnosticConsumer to be set up before the source files are
// actually loaded.
if (ConsumersOrderedByRange.empty()) {
// It's possible to get here while a bridging header PCH is being
// attached-to, if there's some sort of AST-reader warning or error, which
// happens before CompilerInstance::setUpInputs(), at which point _no_
// source buffers are loaded in yet. In that case we return None, rather
// than trying to build a nonsensical map (and actually crashing since we
// can't find buffers for the inputs).
assert(!SubConsumers.empty());
if (!SM.getIDForBufferIdentifier(SubConsumers.begin()->first).hasValue()) {
assert(llvm::none_of(SubConsumers, [&](const ConsumerPair &pair) {
return SM.getIDForBufferIdentifier(pair.first).hasValue();
}));
return None;
}
auto *mutableThis = const_cast<FileSpecificDiagnosticConsumer*>(this);
mutableThis->computeConsumersOrderedByRange(SM);
}
// This std::lower_bound call is doing a binary search for the first range
// that /might/ contain 'loc'. Specifically, since the ranges are sorted
// by end location, it's looking for the first range where the end location
// is greater than or equal to 'loc'.
const ConsumerSpecificInformation *possiblyContainingRangeIter =
std::lower_bound(
ConsumersOrderedByRange.begin(), ConsumersOrderedByRange.end(), loc,
[](const ConsumerSpecificInformation &entry, SourceLoc loc) -> bool {
auto compare = std::less<const char *>();
return compare(getRawLoc(entry.range.getEnd()).getPointer(),
getRawLoc(loc).getPointer());
});
if (possiblyContainingRangeIter != ConsumersOrderedByRange.end() &&
possiblyContainingRangeIter->range.contains(loc)) {
return const_cast<ConsumerSpecificInformation *>(
possiblyContainingRangeIter);
}
return None;
}
void FileSpecificDiagnosticConsumer::handleDiagnostic(
SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind,
StringRef FormatString, ArrayRef<DiagnosticArgument> FormatArgs,
const DiagnosticInfo &Info) {
HasAnErrorBeenConsumed |= Kind == DiagnosticKind::Error;
Optional<ConsumerSpecificInformation *> consumerSpecificInfo;
switch (Kind) {
case DiagnosticKind::Error:
case DiagnosticKind::Warning:
case DiagnosticKind::Remark:
consumerSpecificInfo = consumerSpecificInformationForLocation(SM, Loc);
ConsumerSpecificInfoForSubsequentNotes = consumerSpecificInfo;
break;
case DiagnosticKind::Note:
consumerSpecificInfo = ConsumerSpecificInfoForSubsequentNotes;
break;
}
if (!consumerSpecificInfo.hasValue()) {
for (auto &subConsumer : SubConsumers) {
if (subConsumer.second) {
subConsumer.second->handleDiagnostic(SM, Loc, Kind, FormatString,
FormatArgs, Info);
}
}
return;
}
if (!consumerSpecificInfo.getValue()->consumer)
return; // Suppress non-primary diagnostic in batch mode.
consumerSpecificInfo.getValue()->consumer->handleDiagnostic(
SM, Loc, Kind, FormatString, FormatArgs, Info);
consumerSpecificInfo.getValue()->hasAnErrorBeenEmitted |=
Kind == DiagnosticKind::Error;
}
bool FileSpecificDiagnosticConsumer::finishProcessing(SourceManager &SM) {
addNonSpecificErrors(SM);
// Deliberately don't use std::any_of here because we don't want early-exit
// behavior.
bool hadError = false;
for (auto &subConsumer : SubConsumers)
hadError |= subConsumer.second && subConsumer.second->finishProcessing(SM);
return hadError;
}
static void produceNonSpecificError(
FileSpecificDiagnosticConsumer::ConsumerSpecificInformation &info,
SourceManager &SM) {
Diagnostic diagnostic(
diag::error_compilation_stopped_by_errors_in_other_files);
// Stolen from DiagnosticEngine::emitDiagnostic
DiagnosticInfo Info;
Info.ID = diagnostic.getID();
info.consumer->handleDiagnostic(
SM, info.range.getStart(), DiagnosticKind::Error,
DiagnosticEngine::diagnosticStringFor(diagnostic.getID()), {}, Info);
}
void FileSpecificDiagnosticConsumer::addNonSpecificErrors(SourceManager &SM) {
if (!HasAnErrorBeenConsumed)
return;
for (auto &info : ConsumersOrderedByRange) {
if (!info.hasAnErrorBeenEmitted && info.consumer) {
produceNonSpecificError(info, SM);
info.hasAnErrorBeenEmitted = true;
}
}
}
void NullDiagnosticConsumer::handleDiagnostic(
SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind,
StringRef FormatString, ArrayRef<DiagnosticArgument> FormatArgs,
const DiagnosticInfo &Info) {
DEBUG({
llvm::dbgs() << "NullDiagnosticConsumer received diagnostic: ";
DiagnosticEngine::formatDiagnosticText(llvm::dbgs(), FormatString,
FormatArgs);
llvm::dbgs() << "\n";
});
}
<commit_msg>Rename info to consumerInfo to be less confusable with Info in procedNonSpecificError.<commit_after>//===--- DiagnosticConsumer.cpp - Diagnostic Consumer Impl ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the DiagnosticConsumer class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "swift-ast"
#include "swift/AST/DiagnosticConsumer.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/SourceManager.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
DiagnosticConsumer::~DiagnosticConsumer() = default;
llvm::SMLoc DiagnosticConsumer::getRawLoc(SourceLoc loc) {
return loc.Value;
}
LLVM_ATTRIBUTE_UNUSED
static bool hasDuplicateFileNames(
ArrayRef<FileSpecificDiagnosticConsumer::ConsumerPair> consumers) {
llvm::StringSet<> seenFiles;
for (const auto &consumerPair : consumers) {
if (consumerPair.first.empty()) {
// We can handle multiple consumers that aren't associated with any file,
// because they only collect diagnostics that aren't in any of the special
// files. This isn't an important use case to support, but also SmallSet
// doesn't handle empty strings anyway!
continue;
}
bool isUnique = seenFiles.insert(consumerPair.first).second;
if (!isUnique)
return true;
}
return false;
}
FileSpecificDiagnosticConsumer::FileSpecificDiagnosticConsumer(
SmallVectorImpl<ConsumerPair> &consumers)
: SubConsumers(std::move(consumers)) {
assert(!SubConsumers.empty() &&
"don't waste time handling diagnostics that will never get emitted");
assert(!hasDuplicateFileNames(SubConsumers) &&
"having multiple consumers for the same file is not implemented");
}
void FileSpecificDiagnosticConsumer::computeConsumersOrderedByRange(
SourceManager &SM) {
// Look up each file's source range and add it to the "map" (to be sorted).
for (const ConsumerPair &pair : SubConsumers) {
if (pair.first.empty())
continue;
Optional<unsigned> bufferID = SM.getIDForBufferIdentifier(pair.first);
assert(bufferID.hasValue() && "consumer registered for unknown file");
CharSourceRange range = SM.getRangeForBuffer(bufferID.getValue());
ConsumersOrderedByRange.emplace_back(
ConsumerSpecificInformation(range, pair.second.get()));
}
// Sort the "map" by buffer /end/ location, for use with std::lower_bound
// later. (Sorting by start location would produce the same sort, since the
// ranges must not be overlapping, but since we need to check end locations
// later it's consistent to sort by that here.)
std::sort(ConsumersOrderedByRange.begin(), ConsumersOrderedByRange.end(),
[](const ConsumerSpecificInformation &left,
const ConsumerSpecificInformation &right) -> bool {
auto compare = std::less<const char *>();
return compare(getRawLoc(left.range.getEnd()).getPointer(),
getRawLoc(right.range.getEnd()).getPointer());
});
// Check that the ranges are non-overlapping. If the files really are all
// distinct, this should be trivially true, but if it's ever not we might end
// up mis-filing diagnostics.
assert(ConsumersOrderedByRange.end() ==
std::adjacent_find(ConsumersOrderedByRange.begin(),
ConsumersOrderedByRange.end(),
[](const ConsumerSpecificInformation &left,
const ConsumerSpecificInformation &right) {
return left.range.overlaps(right.range);
}) &&
"overlapping ranges despite having distinct files");
}
Optional<FileSpecificDiagnosticConsumer::ConsumerSpecificInformation *>
FileSpecificDiagnosticConsumer::consumerSpecificInformationForLocation(
SourceManager &SM, SourceLoc loc) const {
// Diagnostics with invalid locations always go to every consumer.
if (loc.isInvalid())
return None;
// This map is generated on first use and cached, to allow the
// FileSpecificDiagnosticConsumer to be set up before the source files are
// actually loaded.
if (ConsumersOrderedByRange.empty()) {
// It's possible to get here while a bridging header PCH is being
// attached-to, if there's some sort of AST-reader warning or error, which
// happens before CompilerInstance::setUpInputs(), at which point _no_
// source buffers are loaded in yet. In that case we return None, rather
// than trying to build a nonsensical map (and actually crashing since we
// can't find buffers for the inputs).
assert(!SubConsumers.empty());
if (!SM.getIDForBufferIdentifier(SubConsumers.begin()->first).hasValue()) {
assert(llvm::none_of(SubConsumers, [&](const ConsumerPair &pair) {
return SM.getIDForBufferIdentifier(pair.first).hasValue();
}));
return None;
}
auto *mutableThis = const_cast<FileSpecificDiagnosticConsumer*>(this);
mutableThis->computeConsumersOrderedByRange(SM);
}
// This std::lower_bound call is doing a binary search for the first range
// that /might/ contain 'loc'. Specifically, since the ranges are sorted
// by end location, it's looking for the first range where the end location
// is greater than or equal to 'loc'.
const ConsumerSpecificInformation *possiblyContainingRangeIter =
std::lower_bound(
ConsumersOrderedByRange.begin(), ConsumersOrderedByRange.end(), loc,
[](const ConsumerSpecificInformation &entry, SourceLoc loc) -> bool {
auto compare = std::less<const char *>();
return compare(getRawLoc(entry.range.getEnd()).getPointer(),
getRawLoc(loc).getPointer());
});
if (possiblyContainingRangeIter != ConsumersOrderedByRange.end() &&
possiblyContainingRangeIter->range.contains(loc)) {
return const_cast<ConsumerSpecificInformation *>(
possiblyContainingRangeIter);
}
return None;
}
void FileSpecificDiagnosticConsumer::handleDiagnostic(
SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind,
StringRef FormatString, ArrayRef<DiagnosticArgument> FormatArgs,
const DiagnosticInfo &Info) {
HasAnErrorBeenConsumed |= Kind == DiagnosticKind::Error;
Optional<ConsumerSpecificInformation *> consumerSpecificInfo;
switch (Kind) {
case DiagnosticKind::Error:
case DiagnosticKind::Warning:
case DiagnosticKind::Remark:
consumerSpecificInfo = consumerSpecificInformationForLocation(SM, Loc);
ConsumerSpecificInfoForSubsequentNotes = consumerSpecificInfo;
break;
case DiagnosticKind::Note:
consumerSpecificInfo = ConsumerSpecificInfoForSubsequentNotes;
break;
}
if (!consumerSpecificInfo.hasValue()) {
for (auto &subConsumer : SubConsumers) {
if (subConsumer.second) {
subConsumer.second->handleDiagnostic(SM, Loc, Kind, FormatString,
FormatArgs, Info);
}
}
return;
}
if (!consumerSpecificInfo.getValue()->consumer)
return; // Suppress non-primary diagnostic in batch mode.
consumerSpecificInfo.getValue()->consumer->handleDiagnostic(
SM, Loc, Kind, FormatString, FormatArgs, Info);
consumerSpecificInfo.getValue()->hasAnErrorBeenEmitted |=
Kind == DiagnosticKind::Error;
}
bool FileSpecificDiagnosticConsumer::finishProcessing(SourceManager &SM) {
addNonSpecificErrors(SM);
// Deliberately don't use std::any_of here because we don't want early-exit
// behavior.
bool hadError = false;
for (auto &subConsumer : SubConsumers)
hadError |= subConsumer.second && subConsumer.second->finishProcessing(SM);
return hadError;
}
static void produceNonSpecificError(
FileSpecificDiagnosticConsumer::ConsumerSpecificInformation &consumerInfo,
SourceManager &SM) {
Diagnostic diagnostic(
diag::error_compilation_stopped_by_errors_in_other_files);
// Stolen from DiagnosticEngine::emitDiagnostic
DiagnosticInfo Info;
Info.ID = diagnostic.getID();
consumerInfo.consumer->handleDiagnostic(
SM, consumerInfo.range.getStart(), DiagnosticKind::Error,
DiagnosticEngine::diagnosticStringFor(diagnostic.getID()), {}, Info);
}
void FileSpecificDiagnosticConsumer::addNonSpecificErrors(SourceManager &SM) {
if (!HasAnErrorBeenConsumed)
return;
for (auto &info : ConsumersOrderedByRange) {
if (!info.hasAnErrorBeenEmitted && info.consumer) {
produceNonSpecificError(info, SM);
info.hasAnErrorBeenEmitted = true;
}
}
}
void NullDiagnosticConsumer::handleDiagnostic(
SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind,
StringRef FormatString, ArrayRef<DiagnosticArgument> FormatArgs,
const DiagnosticInfo &Info) {
DEBUG({
llvm::dbgs() << "NullDiagnosticConsumer received diagnostic: ";
DiagnosticEngine::formatDiagnosticText(llvm::dbgs(), FormatString,
FormatArgs);
llvm::dbgs() << "\n";
});
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: vcsentry.cpp
// Purpose: Implementation of wxExVCSEntry class
// Author: Anton van Wezenbeek
// Created: 2010-08-27
// RCS-ID: $Id$
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/vcsentry.h>
#include <wx/extension/defs.h>
#include <wx/extension/util.h>
#include <wx/extension/vcs.h>
int wxExVCSCommand::m_Instances = 0;
wxExVCSCommand::wxExVCSCommand()
: m_Command()
, m_SubMenu()
, m_SubMenuIsCommand(false)
, m_No(0)
, m_Type(VCS_COMMAND_IS_UNKNOWN)
{
}
wxExVCSCommand::wxExVCSCommand(
const wxString& command,
const wxString& type,
const wxString& submenu,
const wxString& subcommand)
: m_Command(command)
, m_SubMenu(!submenu.empty() ? submenu: subcommand)
, m_SubMenuIsCommand(!subcommand.empty())
, m_No(m_Instances++)
, m_Type(From(type))
{
}
int wxExVCSCommand::From(const wxString& type) const
{
if (type.IsEmpty())
{
return VCS_COMMAND_IS_BOTH;
}
else if (type == "popup")
{
return VCS_COMMAND_IS_POPUP;
}
else if (type == "main")
{
return VCS_COMMAND_IS_MAIN;
}
else
{
return VCS_COMMAND_IS_UNKNOWN;
}
}
const wxString wxExVCSCommand::GetCommand(
bool include_subcommand,
bool include_accelerators) const
{
wxString command = m_Command;
if (m_SubMenuIsCommand && include_subcommand)
{
command += " " + m_SubMenu;
}
if (command.Contains("&") && !include_accelerators)
{
command.Replace("&", wxEmptyString);
}
return command;
}
bool wxExVCSCommand::IsAdd() const
{
return
GetCommand(false) == "add";
}
bool wxExVCSCommand::IsCheckout() const
{
return
GetCommand(false) == "checkout" ||
GetCommand(false) == "co";
}
bool wxExVCSCommand::IsCommit() const
{
return
GetCommand(false) == "commit" ||
GetCommand(false) == "ci";
}
bool wxExVCSCommand::IsDiff() const
{
return
GetCommand(false) == "diff";
}
bool wxExVCSCommand::IsHelp() const
{
return
GetCommand(false) == "help";
}
bool wxExVCSCommand::IsOpen() const
{
return
GetCommand(false) == "blame" ||
GetCommand(false) == "cat" ||
GetCommand(false) == "diff";
}
bool wxExVCSCommand::IsUpdate() const
{
return
GetCommand(false) == "update" ||
GetCommand(false) == "up";
}
int wxExVCSEntry::m_Instances = wxExVCS::VCS_AUTO + 1;
wxExVCSEntry::wxExVCSEntry()
: m_No(-1)
, m_Name()
, m_SupportKeywordExpansion(false)
{
}
wxExVCSEntry::wxExVCSEntry(const wxXmlNode* node)
: m_No(m_Instances++)
, m_Name(node->GetAttribute("name"))
, m_SupportKeywordExpansion(
node->GetAttribute("keyword-expansion") == "true")
{
if (m_Name.empty())
{
wxLogError(_("Missing vcs on line: %d"), node->GetLineNumber());
}
else
{
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "commands")
{
m_Commands = ParseNodeCommands(child);
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined tag: %s on line: %d"),
child->GetName().c_str(),
child->GetLineNumber());
}
child = child->GetNext();
}
}
}
#if wxUSE_GUI
void wxExVCSEntry::BuildMenu(int base_id, wxMenu* menu, bool is_popup) const
{
wxMenu* submenu = NULL;
wxString prev_menu = "XXXXX";
for (
auto it = m_Commands.begin();
it != m_Commands.end();
++it)
{
bool add = false;
if (!it->SubMenu().empty() && prev_menu != it->SubMenu())
{
if (submenu == NULL)
{
submenu = new wxMenu();
prev_menu = it->SubMenu();
menu->AppendSubMenu(submenu, it->SubMenu());
}
}
else if (submenu != NULL)
{
submenu = NULL;
}
switch (it->GetType())
{
case wxExVCSCommand::VCS_COMMAND_IS_BOTH: add = true; break;
case wxExVCSCommand::VCS_COMMAND_IS_POPUP: add = is_popup; break;
case wxExVCSCommand::VCS_COMMAND_IS_MAIN: add = !is_popup; break;
case wxExVCSCommand::VCS_COMMAND_IS_UNKNOWN: add = false; break;
default: wxFAIL;
}
if (add)
{
wxMenu* usemenu = (submenu == NULL ? menu: submenu);
usemenu->Append(base_id + it->GetNo(), wxExEllipsed(it->GetCommand()));
}
}
}
#endif
const wxExVCSCommand wxExVCSEntry::GetCommand(int command_id) const
{
if (command_id >= m_Commands.size() || command_id < 0)
{
return wxExVCSCommand();
}
else
{
return m_Commands.at(command_id);
}
}
const std::vector<wxExVCSCommand> wxExVCSEntry::ParseNodeCommands(
const wxXmlNode* node) const
{
std::vector<wxExVCSCommand> v;
wxExVCSCommand::ResetInstances();
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "command")
{
if (v.size() == VCS_MAX_COMMANDS)
{
wxLogError(_("Reached commands limit: %d"), VCS_MAX_COMMANDS);
}
else
{
const wxString content = child->GetNodeContent().Strip(wxString::both);
const wxString attrib = child->GetAttribute("type");
const wxString submenu = child->GetAttribute("submenu");
const wxString subcommand = child->GetAttribute("subcommand");
v.push_back(wxExVCSCommand(content, attrib, submenu, subcommand));
}
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined tag: %s on line: %d"),
child->GetName().c_str(),
child->GetLineNumber());
}
child = child->GetNext();
}
return v;
}
<commit_msg>fixed accel in menu<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: vcsentry.cpp
// Purpose: Implementation of wxExVCSEntry class
// Author: Anton van Wezenbeek
// Created: 2010-08-27
// RCS-ID: $Id$
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/vcsentry.h>
#include <wx/extension/defs.h>
#include <wx/extension/util.h>
#include <wx/extension/vcs.h>
int wxExVCSCommand::m_Instances = 0;
wxExVCSCommand::wxExVCSCommand()
: m_Command()
, m_SubMenu()
, m_SubMenuIsCommand(false)
, m_No(0)
, m_Type(VCS_COMMAND_IS_UNKNOWN)
{
}
wxExVCSCommand::wxExVCSCommand(
const wxString& command,
const wxString& type,
const wxString& submenu,
const wxString& subcommand)
: m_Command(command)
, m_SubMenu(!submenu.empty() ? submenu: subcommand)
, m_SubMenuIsCommand(!subcommand.empty())
, m_No(m_Instances++)
, m_Type(From(type))
{
}
int wxExVCSCommand::From(const wxString& type) const
{
if (type.IsEmpty())
{
return VCS_COMMAND_IS_BOTH;
}
else if (type == "popup")
{
return VCS_COMMAND_IS_POPUP;
}
else if (type == "main")
{
return VCS_COMMAND_IS_MAIN;
}
else
{
return VCS_COMMAND_IS_UNKNOWN;
}
}
const wxString wxExVCSCommand::GetCommand(
bool include_subcommand,
bool include_accelerators) const
{
wxString command = m_Command;
if (m_SubMenuIsCommand && include_subcommand)
{
command += " " + m_SubMenu;
}
if (command.Contains("&") && !include_accelerators)
{
command.Replace("&", wxEmptyString);
}
return command;
}
bool wxExVCSCommand::IsAdd() const
{
return
GetCommand(false) == "add";
}
bool wxExVCSCommand::IsCheckout() const
{
return
GetCommand(false) == "checkout" ||
GetCommand(false) == "co";
}
bool wxExVCSCommand::IsCommit() const
{
return
GetCommand(false) == "commit" ||
GetCommand(false) == "ci";
}
bool wxExVCSCommand::IsDiff() const
{
return
GetCommand(false) == "diff";
}
bool wxExVCSCommand::IsHelp() const
{
return
GetCommand(false) == "help";
}
bool wxExVCSCommand::IsOpen() const
{
return
GetCommand(false) == "blame" ||
GetCommand(false) == "cat" ||
GetCommand(false) == "diff";
}
bool wxExVCSCommand::IsUpdate() const
{
return
GetCommand(false) == "update" ||
GetCommand(false) == "up";
}
int wxExVCSEntry::m_Instances = wxExVCS::VCS_AUTO + 1;
wxExVCSEntry::wxExVCSEntry()
: m_No(-1)
, m_Name()
, m_SupportKeywordExpansion(false)
{
}
wxExVCSEntry::wxExVCSEntry(const wxXmlNode* node)
: m_No(m_Instances++)
, m_Name(node->GetAttribute("name"))
, m_SupportKeywordExpansion(
node->GetAttribute("keyword-expansion") == "true")
{
if (m_Name.empty())
{
wxLogError(_("Missing vcs on line: %d"), node->GetLineNumber());
}
else
{
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "commands")
{
m_Commands = ParseNodeCommands(child);
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined tag: %s on line: %d"),
child->GetName().c_str(),
child->GetLineNumber());
}
child = child->GetNext();
}
}
}
#if wxUSE_GUI
void wxExVCSEntry::BuildMenu(int base_id, wxMenu* menu, bool is_popup) const
{
wxMenu* submenu = NULL;
wxString prev_menu = "XXXXX";
for (
auto it = m_Commands.begin();
it != m_Commands.end();
++it)
{
bool add = false;
if (!it->SubMenu().empty() && prev_menu != it->SubMenu())
{
if (submenu == NULL)
{
submenu = new wxMenu();
prev_menu = it->SubMenu();
menu->AppendSubMenu(submenu, it->SubMenu());
}
}
else if (submenu != NULL)
{
submenu = NULL;
}
switch (it->GetType())
{
case wxExVCSCommand::VCS_COMMAND_IS_BOTH: add = true; break;
case wxExVCSCommand::VCS_COMMAND_IS_POPUP: add = is_popup; break;
case wxExVCSCommand::VCS_COMMAND_IS_MAIN: add = !is_popup; break;
case wxExVCSCommand::VCS_COMMAND_IS_UNKNOWN: add = false; break;
default: wxFAIL;
}
if (add)
{
wxMenu* usemenu = (submenu == NULL ? menu: submenu);
usemenu->Append(
base_id + it->GetNo(),
wxExEllipsed(it->GetCommand(false, true))); // use no sub and do accel
}
}
}
#endif
const wxExVCSCommand wxExVCSEntry::GetCommand(int command_id) const
{
if (command_id >= m_Commands.size() || command_id < 0)
{
return wxExVCSCommand();
}
else
{
return m_Commands.at(command_id);
}
}
const std::vector<wxExVCSCommand> wxExVCSEntry::ParseNodeCommands(
const wxXmlNode* node) const
{
std::vector<wxExVCSCommand> v;
wxExVCSCommand::ResetInstances();
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "command")
{
if (v.size() == VCS_MAX_COMMANDS)
{
wxLogError(_("Reached commands limit: %d"), VCS_MAX_COMMANDS);
}
else
{
const wxString content = child->GetNodeContent().Strip(wxString::both);
const wxString attrib = child->GetAttribute("type");
const wxString submenu = child->GetAttribute("submenu");
const wxString subcommand = child->GetAttribute("subcommand");
v.push_back(wxExVCSCommand(content, attrib, submenu, subcommand));
}
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError(_("Undefined tag: %s on line: %d"),
child->GetName().c_str(),
child->GetLineNumber());
}
child = child->GetNext();
}
return v;
}
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
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 <srs_app_server.hpp>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <algorithm>
#include <srs_kernel_log.hpp>
#include <srs_kernel_error.hpp>
#include <srs_app_rtmp_conn.hpp>
#include <srs_app_config.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_app_http_api.hpp>
#include <srs_app_http_conn.hpp>
#define SERVER_LISTEN_BACKLOG 512
#define SRS_TIME_RESOLUTION_MS 500
SrsListener::SrsListener(SrsServer* _server, SrsListenerType _type)
{
fd = -1;
stfd = NULL;
port = 0;
server = _server;
type = _type;
pthread = new SrsThread(this, 0);
}
SrsListener::~SrsListener()
{
srs_close_stfd(stfd);
pthread->stop();
srs_freep(pthread);
// st does not close it sometimes,
// close it manually.
close(fd);
}
int SrsListener::listen(int _port)
{
int ret = ERROR_SUCCESS;
port = _port;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
ret = ERROR_SOCKET_CREATE;
srs_error("create linux socket error. ret=%d", ret);
return ret;
}
srs_verbose("create linux socket success. fd=%d", fd);
int reuse_socket = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_socket, sizeof(int)) == -1) {
ret = ERROR_SOCKET_SETREUSE;
srs_error("setsockopt reuse-addr error. ret=%d", ret);
return ret;
}
srs_verbose("setsockopt reuse-addr success. fd=%d", fd);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(fd, (const sockaddr*)&addr, sizeof(sockaddr_in)) == -1) {
ret = ERROR_SOCKET_BIND;
srs_error("bind socket error. ret=%d", ret);
return ret;
}
srs_verbose("bind socket success. fd=%d", fd);
if (::listen(fd, SERVER_LISTEN_BACKLOG) == -1) {
ret = ERROR_SOCKET_LISTEN;
srs_error("listen socket error. ret=%d", ret);
return ret;
}
srs_verbose("listen socket success. fd=%d", fd);
if ((stfd = st_netfd_open_socket(fd)) == NULL){
ret = ERROR_ST_OPEN_SOCKET;
srs_error("st_netfd_open_socket open socket failed. ret=%d", ret);
return ret;
}
srs_verbose("st open socket success. fd=%d", fd);
if ((ret = pthread->start()) != ERROR_SUCCESS) {
srs_error("st_thread_create listen thread error. ret=%d", ret);
return ret;
}
srs_verbose("create st listen thread success.");
srs_trace("server started, listen at port=%d, type=%d, fd=%d", port, type, fd);
return ret;
}
void SrsListener::on_enter_loop()
{
srs_trace("listen cycle start, port=%d, type=%d, fd=%d", port, type, fd);
}
int SrsListener::cycle()
{
int ret = ERROR_SUCCESS;
st_netfd_t client_stfd = st_accept(stfd, NULL, NULL, ST_UTIME_NO_TIMEOUT);
if(client_stfd == NULL){
// ignore error.
srs_warn("ignore accept thread stoppped for accept client error");
return ret;
}
srs_verbose("get a client. fd=%d", st_netfd_fileno(client_stfd));
if ((ret = server->accept_client(type, client_stfd)) != ERROR_SUCCESS) {
srs_warn("accept client error. ret=%d", ret);
return ret;
}
srs_verbose("accept client finished. conns=%d, ret=%d", (int)conns.size(), ret);
return ret;
}
SrsServer::SrsServer()
{
signal_reload = false;
signal_gmc_stop = false;
srs_assert(_srs_config);
_srs_config->subscribe(this);
}
SrsServer::~SrsServer()
{
_srs_config->unsubscribe(this);
if (true) {
std::vector<SrsConnection*>::iterator it;
for (it = conns.begin(); it != conns.end(); ++it) {
SrsConnection* conn = *it;
srs_freep(conn);
}
conns.clear();
}
close_listeners();
}
int SrsServer::initialize()
{
int ret = ERROR_SUCCESS;
return ret;
}
int SrsServer::acquire_pid_file()
{
int ret = ERROR_SUCCESS;
std::string pid_file = _srs_config->get_pid_file();
// -rw-r--r--
// 644
int mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
int fd;
// open pid file
if ((fd = ::open(pid_file.c_str(), O_WRONLY | O_CREAT, mode)) < 0) {
ret = ERROR_SYSTEM_PID_ACQUIRE;
srs_error("open pid file %s error, ret=%#x", pid_file.c_str(), ret);
return ret;
}
// require write lock
flock lock;
lock.l_type = F_WRLCK; // F_RDLCK, F_WRLCK, F_UNLCK
lock.l_start = 0; // type offset, relative to l_whence
lock.l_whence = SEEK_SET; // SEEK_SET, SEEK_CUR, SEEK_END
lock.l_len = 0;
if (fcntl(fd, F_SETLK, &lock) < 0) {
if(errno == EACCES || errno == EAGAIN) {
ret = ERROR_SYSTEM_PID_ALREADY_RUNNING;
srs_error("srs is already running! ret=%#x", ret);
return ret;
}
ret = ERROR_SYSTEM_PID_LOCK;
srs_error("require lock for file %s error! ret=%#x", pid_file.c_str(), ret);
return ret;
}
// truncate file
if (ftruncate(fd, 0) < 0) {
ret = ERROR_SYSTEM_PID_TRUNCATE_FILE;
srs_error("truncate pid file %s error! ret=%#x", pid_file.c_str(), ret);
return ret;
}
int pid = (int)getpid();
// write the pid
char buf[512];
snprintf(buf, sizeof(buf), "%d", pid);
if (write(fd, buf, strlen(buf)) != (int)strlen(buf)) {
ret = ERROR_SYSTEM_PID_WRITE_FILE;
srs_error("write our pid error! pid=%d file=%s ret=%#x", pid, pid_file.c_str(), ret);
return ret;
}
// auto close when fork child process.
int val;
if ((val = fcntl(fd, F_GETFD, 0)) < 0) {
ret = ERROR_SYSTEM_PID_GET_FILE_INFO;
srs_error("fnctl F_GETFD error! file=%s ret=%#x", pid_file.c_str(), ret);
return ret;
}
val |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, val) < 0) {
ret = ERROR_SYSTEM_PID_SET_FILE_INFO;
srs_error("fcntl F_SETFD error! file=%s ret=%#x", pid_file.c_str(), ret);
return ret;
}
srs_trace("write pid=%d to %s success!", pid, pid_file.c_str());
return ret;
}
int SrsServer::initialize_st()
{
int ret = ERROR_SUCCESS;
// use linux epoll.
if (st_set_eventsys(ST_EVENTSYS_ALT) == -1) {
ret = ERROR_ST_SET_EPOLL;
srs_error("st_set_eventsys use linux epoll failed. ret=%d", ret);
return ret;
}
srs_verbose("st_set_eventsys use linux epoll success");
if(st_init() != 0){
ret = ERROR_ST_INITIALIZE;
srs_error("st_init failed. ret=%d", ret);
return ret;
}
srs_verbose("st_init success");
// set current log id.
_srs_context->generate_id();
srs_info("log set id success");
return ret;
}
int SrsServer::listen()
{
int ret = ERROR_SUCCESS;
SrsConfDirective* conf = NULL;
// stream service port.
conf = _srs_config->get_listen();
srs_assert(conf);
close_listeners();
for (int i = 0; i < (int)conf->args.size(); i++) {
SrsListener* listener = new SrsListener(this, SrsListenerRtmpStream);
listeners.push_back(listener);
int port = ::atoi(conf->args.at(i).c_str());
if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
srs_error("RTMP stream listen at port %d failed. ret=%d", port, ret);
return ret;
}
}
if (_srs_config->get_http_api_enabled()) {
SrsListener* listener = new SrsListener(this, SrsListenerHttpApi);
listeners.push_back(listener);
int port = _srs_config->get_http_api_listen();
if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
srs_error("HTTP api listen at port %d failed. ret=%d", port, ret);
return ret;
}
}
if (_srs_config->get_http_stream_enabled()) {
SrsListener* listener = new SrsListener(this, SrsListenerHttpStream);
listeners.push_back(listener);
int port = _srs_config->get_http_stream_listen();
if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
srs_error("HTTP stream listen at port %d failed. ret=%d", port, ret);
return ret;
}
}
return ret;
}
int SrsServer::cycle()
{
int ret = ERROR_SUCCESS;
// the deamon thread, update the time cache
while (true) {
st_usleep(SRS_TIME_RESOLUTION_MS * 1000);
srs_update_system_time_ms();
// for gperf heap checker,
// @see: research/gperftools/heap-checker/heap_checker.cc
// if user interrupt the program, exit to check mem leak.
// but, if gperf, use reload to ensure main return normally,
// because directly exit will cause core-dump.
#ifdef SRS_GPERF_MC
if (signal_gmc_stop) {
break;
}
#endif
if (signal_reload) {
signal_reload = false;
srs_info("get signal reload, to reload the config.");
if ((ret = _srs_config->reload()) != ERROR_SUCCESS) {
srs_error("reload config failed. ret=%d", ret);
return ret;
}
srs_trace("reload config success.");
}
}
return ret;
}
void SrsServer::remove(SrsConnection* conn)
{
std::vector<SrsConnection*>::iterator it = std::find(conns.begin(), conns.end(), conn);
if (it != conns.end()) {
conns.erase(it);
}
srs_info("conn removed. conns=%d", (int)conns.size());
// all connections are created by server,
// so we free it here.
srs_freep(conn);
}
void SrsServer::on_signal(int signo)
{
if (signo == SIGNAL_RELOAD) {
signal_reload = true;
return;
}
if (signo == SIGINT) {
#ifdef SRS_GPERF_MC
srs_trace("gmc is on, main cycle will terminate normally.");
signal_gmc_stop = true;
#else
srs_trace("user terminate program");
exit(0);
#endif
return;
}
if (signo == SIGTERM) {
srs_trace("user terminate program");
exit(0);
return;
}
}
void SrsServer::close_listeners()
{
std::vector<SrsListener*>::iterator it;
for (it = listeners.begin(); it != listeners.end(); ++it) {
SrsListener* listener = *it;
srs_freep(listener);
}
listeners.clear();
}
int SrsServer::accept_client(SrsListenerType type, st_netfd_t client_stfd)
{
int ret = ERROR_SUCCESS;
int max_connections = _srs_config->get_max_connections();
if ((int)conns.size() >= max_connections) {
int fd = st_netfd_fileno(client_stfd);
srs_error("exceed the max connections, drop client: "
"clients=%d, max=%d, fd=%d", (int)conns.size(), max_connections, fd);
srs_close_stfd(client_stfd);
return ret;
}
SrsConnection* conn = NULL;
if (type == SrsListenerRtmpStream) {
conn = new SrsRtmpConn(this, client_stfd);
} else if (type == SrsListenerHttpApi) {
#ifdef SRS_HTTP_API
conn = new SrsHttpApi(this, client_stfd);
#else
srs_warn("close http client for server not support http-api");
srs_close_stfd(client_stfd);
return ret;
#endif
} else if (type == SrsListenerHttpStream) {
#ifdef SRS_HTTP_SERVER
conn = new SrsHttpConn(this, client_stfd);
#else
srs_warn("close http client for server not support http-server");
srs_close_stfd(client_stfd);
return ret;
#endif
} else {
// TODO: FIXME: handler others
}
srs_assert(conn);
// directly enqueue, the cycle thread will remove the client.
conns.push_back(conn);
srs_verbose("add conn from port %d to vector. conns=%d", port, (int)conns.size());
// cycle will start process thread and when finished remove the client.
if ((ret = conn->start()) != ERROR_SUCCESS) {
return ret;
}
srs_verbose("conn start finished. ret=%d", ret);
return ret;
}
int SrsServer::on_reload_listen()
{
return listen();
}
<commit_msg>refine code, donot listen if not enabled http<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
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 <srs_app_server.hpp>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <algorithm>
#include <srs_kernel_log.hpp>
#include <srs_kernel_error.hpp>
#include <srs_app_rtmp_conn.hpp>
#include <srs_app_config.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_app_http_api.hpp>
#include <srs_app_http_conn.hpp>
#define SERVER_LISTEN_BACKLOG 512
#define SRS_TIME_RESOLUTION_MS 500
SrsListener::SrsListener(SrsServer* _server, SrsListenerType _type)
{
fd = -1;
stfd = NULL;
port = 0;
server = _server;
type = _type;
pthread = new SrsThread(this, 0);
}
SrsListener::~SrsListener()
{
srs_close_stfd(stfd);
pthread->stop();
srs_freep(pthread);
// st does not close it sometimes,
// close it manually.
close(fd);
}
int SrsListener::listen(int _port)
{
int ret = ERROR_SUCCESS;
port = _port;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
ret = ERROR_SOCKET_CREATE;
srs_error("create linux socket error. ret=%d", ret);
return ret;
}
srs_verbose("create linux socket success. fd=%d", fd);
int reuse_socket = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_socket, sizeof(int)) == -1) {
ret = ERROR_SOCKET_SETREUSE;
srs_error("setsockopt reuse-addr error. ret=%d", ret);
return ret;
}
srs_verbose("setsockopt reuse-addr success. fd=%d", fd);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(fd, (const sockaddr*)&addr, sizeof(sockaddr_in)) == -1) {
ret = ERROR_SOCKET_BIND;
srs_error("bind socket error. ret=%d", ret);
return ret;
}
srs_verbose("bind socket success. fd=%d", fd);
if (::listen(fd, SERVER_LISTEN_BACKLOG) == -1) {
ret = ERROR_SOCKET_LISTEN;
srs_error("listen socket error. ret=%d", ret);
return ret;
}
srs_verbose("listen socket success. fd=%d", fd);
if ((stfd = st_netfd_open_socket(fd)) == NULL){
ret = ERROR_ST_OPEN_SOCKET;
srs_error("st_netfd_open_socket open socket failed. ret=%d", ret);
return ret;
}
srs_verbose("st open socket success. fd=%d", fd);
if ((ret = pthread->start()) != ERROR_SUCCESS) {
srs_error("st_thread_create listen thread error. ret=%d", ret);
return ret;
}
srs_verbose("create st listen thread success.");
srs_trace("server started, listen at port=%d, type=%d, fd=%d", port, type, fd);
return ret;
}
void SrsListener::on_enter_loop()
{
srs_trace("listen cycle start, port=%d, type=%d, fd=%d", port, type, fd);
}
int SrsListener::cycle()
{
int ret = ERROR_SUCCESS;
st_netfd_t client_stfd = st_accept(stfd, NULL, NULL, ST_UTIME_NO_TIMEOUT);
if(client_stfd == NULL){
// ignore error.
srs_warn("ignore accept thread stoppped for accept client error");
return ret;
}
srs_verbose("get a client. fd=%d", st_netfd_fileno(client_stfd));
if ((ret = server->accept_client(type, client_stfd)) != ERROR_SUCCESS) {
srs_warn("accept client error. ret=%d", ret);
return ret;
}
srs_verbose("accept client finished. conns=%d, ret=%d", (int)conns.size(), ret);
return ret;
}
SrsServer::SrsServer()
{
signal_reload = false;
signal_gmc_stop = false;
srs_assert(_srs_config);
_srs_config->subscribe(this);
}
SrsServer::~SrsServer()
{
_srs_config->unsubscribe(this);
if (true) {
std::vector<SrsConnection*>::iterator it;
for (it = conns.begin(); it != conns.end(); ++it) {
SrsConnection* conn = *it;
srs_freep(conn);
}
conns.clear();
}
close_listeners();
}
int SrsServer::initialize()
{
int ret = ERROR_SUCCESS;
return ret;
}
int SrsServer::acquire_pid_file()
{
int ret = ERROR_SUCCESS;
std::string pid_file = _srs_config->get_pid_file();
// -rw-r--r--
// 644
int mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
int fd;
// open pid file
if ((fd = ::open(pid_file.c_str(), O_WRONLY | O_CREAT, mode)) < 0) {
ret = ERROR_SYSTEM_PID_ACQUIRE;
srs_error("open pid file %s error, ret=%#x", pid_file.c_str(), ret);
return ret;
}
// require write lock
flock lock;
lock.l_type = F_WRLCK; // F_RDLCK, F_WRLCK, F_UNLCK
lock.l_start = 0; // type offset, relative to l_whence
lock.l_whence = SEEK_SET; // SEEK_SET, SEEK_CUR, SEEK_END
lock.l_len = 0;
if (fcntl(fd, F_SETLK, &lock) < 0) {
if(errno == EACCES || errno == EAGAIN) {
ret = ERROR_SYSTEM_PID_ALREADY_RUNNING;
srs_error("srs is already running! ret=%#x", ret);
return ret;
}
ret = ERROR_SYSTEM_PID_LOCK;
srs_error("require lock for file %s error! ret=%#x", pid_file.c_str(), ret);
return ret;
}
// truncate file
if (ftruncate(fd, 0) < 0) {
ret = ERROR_SYSTEM_PID_TRUNCATE_FILE;
srs_error("truncate pid file %s error! ret=%#x", pid_file.c_str(), ret);
return ret;
}
int pid = (int)getpid();
// write the pid
char buf[512];
snprintf(buf, sizeof(buf), "%d", pid);
if (write(fd, buf, strlen(buf)) != (int)strlen(buf)) {
ret = ERROR_SYSTEM_PID_WRITE_FILE;
srs_error("write our pid error! pid=%d file=%s ret=%#x", pid, pid_file.c_str(), ret);
return ret;
}
// auto close when fork child process.
int val;
if ((val = fcntl(fd, F_GETFD, 0)) < 0) {
ret = ERROR_SYSTEM_PID_GET_FILE_INFO;
srs_error("fnctl F_GETFD error! file=%s ret=%#x", pid_file.c_str(), ret);
return ret;
}
val |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, val) < 0) {
ret = ERROR_SYSTEM_PID_SET_FILE_INFO;
srs_error("fcntl F_SETFD error! file=%s ret=%#x", pid_file.c_str(), ret);
return ret;
}
srs_trace("write pid=%d to %s success!", pid, pid_file.c_str());
return ret;
}
int SrsServer::initialize_st()
{
int ret = ERROR_SUCCESS;
// use linux epoll.
if (st_set_eventsys(ST_EVENTSYS_ALT) == -1) {
ret = ERROR_ST_SET_EPOLL;
srs_error("st_set_eventsys use linux epoll failed. ret=%d", ret);
return ret;
}
srs_verbose("st_set_eventsys use linux epoll success");
if(st_init() != 0){
ret = ERROR_ST_INITIALIZE;
srs_error("st_init failed. ret=%d", ret);
return ret;
}
srs_verbose("st_init success");
// set current log id.
_srs_context->generate_id();
srs_info("log set id success");
return ret;
}
int SrsServer::listen()
{
int ret = ERROR_SUCCESS;
SrsConfDirective* conf = NULL;
// stream service port.
conf = _srs_config->get_listen();
srs_assert(conf);
close_listeners();
for (int i = 0; i < (int)conf->args.size(); i++) {
SrsListener* listener = new SrsListener(this, SrsListenerRtmpStream);
listeners.push_back(listener);
int port = ::atoi(conf->args.at(i).c_str());
if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
srs_error("RTMP stream listen at port %d failed. ret=%d", port, ret);
return ret;
}
}
#ifdef SRS_HTTP_API
if (_srs_config->get_http_api_enabled()) {
SrsListener* listener = new SrsListener(this, SrsListenerHttpApi);
listeners.push_back(listener);
int port = _srs_config->get_http_api_listen();
if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
srs_error("HTTP api listen at port %d failed. ret=%d", port, ret);
return ret;
}
}
#endif
#ifdef SRS_HTTP_SERVER
if (_srs_config->get_http_stream_enabled()) {
SrsListener* listener = new SrsListener(this, SrsListenerHttpStream);
listeners.push_back(listener);
int port = _srs_config->get_http_stream_listen();
if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
srs_error("HTTP stream listen at port %d failed. ret=%d", port, ret);
return ret;
}
}
#endif
return ret;
}
int SrsServer::cycle()
{
int ret = ERROR_SUCCESS;
// the deamon thread, update the time cache
while (true) {
st_usleep(SRS_TIME_RESOLUTION_MS * 1000);
srs_update_system_time_ms();
// for gperf heap checker,
// @see: research/gperftools/heap-checker/heap_checker.cc
// if user interrupt the program, exit to check mem leak.
// but, if gperf, use reload to ensure main return normally,
// because directly exit will cause core-dump.
#ifdef SRS_GPERF_MC
if (signal_gmc_stop) {
break;
}
#endif
if (signal_reload) {
signal_reload = false;
srs_info("get signal reload, to reload the config.");
if ((ret = _srs_config->reload()) != ERROR_SUCCESS) {
srs_error("reload config failed. ret=%d", ret);
return ret;
}
srs_trace("reload config success.");
}
}
return ret;
}
void SrsServer::remove(SrsConnection* conn)
{
std::vector<SrsConnection*>::iterator it = std::find(conns.begin(), conns.end(), conn);
if (it != conns.end()) {
conns.erase(it);
}
srs_info("conn removed. conns=%d", (int)conns.size());
// all connections are created by server,
// so we free it here.
srs_freep(conn);
}
void SrsServer::on_signal(int signo)
{
if (signo == SIGNAL_RELOAD) {
signal_reload = true;
return;
}
if (signo == SIGINT) {
#ifdef SRS_GPERF_MC
srs_trace("gmc is on, main cycle will terminate normally.");
signal_gmc_stop = true;
#else
srs_trace("user terminate program");
exit(0);
#endif
return;
}
if (signo == SIGTERM) {
srs_trace("user terminate program");
exit(0);
return;
}
}
void SrsServer::close_listeners()
{
std::vector<SrsListener*>::iterator it;
for (it = listeners.begin(); it != listeners.end(); ++it) {
SrsListener* listener = *it;
srs_freep(listener);
}
listeners.clear();
}
int SrsServer::accept_client(SrsListenerType type, st_netfd_t client_stfd)
{
int ret = ERROR_SUCCESS;
int max_connections = _srs_config->get_max_connections();
if ((int)conns.size() >= max_connections) {
int fd = st_netfd_fileno(client_stfd);
srs_error("exceed the max connections, drop client: "
"clients=%d, max=%d, fd=%d", (int)conns.size(), max_connections, fd);
srs_close_stfd(client_stfd);
return ret;
}
SrsConnection* conn = NULL;
if (type == SrsListenerRtmpStream) {
conn = new SrsRtmpConn(this, client_stfd);
} else if (type == SrsListenerHttpApi) {
#ifdef SRS_HTTP_API
conn = new SrsHttpApi(this, client_stfd);
#else
srs_warn("close http client for server not support http-api");
srs_close_stfd(client_stfd);
return ret;
#endif
} else if (type == SrsListenerHttpStream) {
#ifdef SRS_HTTP_SERVER
conn = new SrsHttpConn(this, client_stfd);
#else
srs_warn("close http client for server not support http-server");
srs_close_stfd(client_stfd);
return ret;
#endif
} else {
// TODO: FIXME: handler others
}
srs_assert(conn);
// directly enqueue, the cycle thread will remove the client.
conns.push_back(conn);
srs_verbose("add conn from port %d to vector. conns=%d", port, (int)conns.size());
// cycle will start process thread and when finished remove the client.
if ((ret = conn->start()) != ERROR_SUCCESS) {
return ret;
}
srs_verbose("conn start finished. ret=%d", ret);
return ret;
}
int SrsServer::on_reload_listen()
{
return listen();
}
<|endoftext|>
|
<commit_before>//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
//
// This pass eliminates machine instruction PHI nodes by inserting copy
// instructions. This destroys SSA information, but is the desired input for
// some register allocators.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/CodeGen/LiveVariables.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
namespace {
struct PNE : public MachineFunctionPass {
bool runOnMachineFunction(MachineFunction &Fn) {
bool Changed = false;
// Eliminate PHI instructions by inserting copies into predecessor blocks.
//
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Changed |= EliminatePHINodes(Fn, *I);
//std::cerr << "AFTER PHI NODE ELIM:\n";
//Fn.dump();
return Changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<LiveVariables>();
MachineFunctionPass::getAnalysisUsage(AU);
}
private:
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
/// in predecessor basic blocks.
///
bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
};
RegisterPass<PNE> X("phi-node-elimination",
"Eliminate PHI nodes for register allocation");
}
const PassInfo *PHIEliminationID = X.getPassInfo();
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
/// predecessor basic blocks.
///
bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
if (MBB.empty() || MBB.front()->getOpcode() != TargetInstrInfo::PHI)
return false; // Quick exit for normal case...
LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
const TargetInstrInfo &MII = MF.getTarget().getInstrInfo();
const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
while (MBB.front()->getOpcode() == TargetInstrInfo::PHI) {
MachineInstr *MI = MBB.front();
// Unlink the PHI node from the basic block... but don't delete the PHI yet
MBB.erase(MBB.begin());
assert(MI->getOperand(0).isVirtualRegister() &&
"PHI node doesn't write virt reg?");
unsigned DestReg = MI->getOperand(0).getAllocatedRegNum();
// Create a new register for the incoming PHI arguments
const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
// Insert a register to register copy in the top of the current block (but
// after any remaining phi nodes) which copies the new incoming register
// into the phi node destination.
//
MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
if (AfterPHIsIt != MBB.end())
while ((*AfterPHIsIt)->getOpcode() == TargetInstrInfo::PHI) ++AfterPHIsIt;
RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
// Update live variable information if there is any...
if (LV) {
MachineInstr *PHICopy = *(AfterPHIsIt-1);
// Add information to LiveVariables to know that the incoming value is
// dead. This says that the register is dead, not killed, because we
// cannot use the live variable information to indicate that the variable
// is defined in multiple entry blocks. Instead, we pretend that this
// instruction defined it and killed it at the same time.
//
LV->addVirtualRegisterDead(IncomingReg, PHICopy);
// Since we are going to be deleting the PHI node, if it is the last use
// of any registers, or if the value itself is dead, we need to move this
// information over to the new copy we just inserted...
//
std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator>
RKs = LV->killed_range(MI);
if (RKs.first != RKs.second) {
for (LiveVariables::killed_iterator I = RKs.first; I != RKs.second; ++I)
LV->addVirtualRegisterKilled(I->second, PHICopy);
LV->removeVirtualRegistersKilled(RKs.first, RKs.second);
}
RKs = LV->dead_range(MI);
if (RKs.first != RKs.second) {
for (LiveVariables::killed_iterator I = RKs.first; I != RKs.second; ++I)
LV->addVirtualRegisterDead(I->second, PHICopy);
LV->removeVirtualRegistersDead(RKs.first, RKs.second);
}
}
// Now loop over all of the incoming arguments, changing them to copy into
// the IncomingReg register in the corresponding predecessor basic block.
//
for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
MachineOperand &opVal = MI->getOperand(i-1);
// Get the MachineBasicBlock equivalent of the BasicBlock that is the
// source path the PHI.
MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
// Figure out where to insert the copy, which is at the end of the
// predecessor basic block, but before any terminator/branch
// instructions...
MachineBasicBlock::iterator I = opBlock.end();
if (I != opBlock.begin()) { // Handle empty blocks
--I;
// must backtrack over ALL the branches in the previous block
while (MII.isTerminatorInstr((*I)->getOpcode()) &&
I != opBlock.begin())
--I;
// move back to the first branch instruction so new instructions
// are inserted right in front of it and not in front of a non-branch
if (!MII.isTerminatorInstr((*I)->getOpcode()))
++I;
}
// Check to make sure we haven't already emitted the copy for this block.
// This can happen because PHI nodes may have multiple entries for the
// same basic block. It doesn't matter which entry we use though, because
// all incoming values are guaranteed to be the same for a particular bb.
//
// If we emitted a copy for this basic block already, it will be right
// where we want to insert one now. Just check for a definition of the
// register we are interested in!
//
bool HaveNotEmitted = true;
if (I != opBlock.begin()) {
MachineInstr *PrevInst = *(I-1);
for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) {
MachineOperand &MO = PrevInst->getOperand(i);
if (MO.isVirtualRegister() && MO.getReg() == IncomingReg)
if (MO.opIsDef() || MO.opIsDefAndUse()) {
HaveNotEmitted = false;
break;
}
}
}
if (HaveNotEmitted) {
assert(opVal.isVirtualRegister() &&
"Machine PHI Operands must all be virtual registers!");
RegInfo->copyRegToReg(opBlock, I, IncomingReg, opVal.getReg(), RC);
}
}
// really delete the PHI instruction now!
delete MI;
}
return true;
}
<commit_msg>Fix bug where we could iterate off the end of a basic block<commit_after>//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
//
// This pass eliminates machine instruction PHI nodes by inserting copy
// instructions. This destroys SSA information, but is the desired input for
// some register allocators.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/CodeGen/LiveVariables.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
namespace {
struct PNE : public MachineFunctionPass {
bool runOnMachineFunction(MachineFunction &Fn) {
bool Changed = false;
// Eliminate PHI instructions by inserting copies into predecessor blocks.
//
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Changed |= EliminatePHINodes(Fn, *I);
//std::cerr << "AFTER PHI NODE ELIM:\n";
//Fn.dump();
return Changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<LiveVariables>();
MachineFunctionPass::getAnalysisUsage(AU);
}
private:
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
/// in predecessor basic blocks.
///
bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
};
RegisterPass<PNE> X("phi-node-elimination",
"Eliminate PHI nodes for register allocation");
}
const PassInfo *PHIEliminationID = X.getPassInfo();
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
/// predecessor basic blocks.
///
bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
if (MBB.empty() || MBB.front()->getOpcode() != TargetInstrInfo::PHI)
return false; // Quick exit for normal case...
LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
const TargetInstrInfo &MII = MF.getTarget().getInstrInfo();
const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
while (MBB.front()->getOpcode() == TargetInstrInfo::PHI) {
MachineInstr *MI = MBB.front();
// Unlink the PHI node from the basic block... but don't delete the PHI yet
MBB.erase(MBB.begin());
assert(MI->getOperand(0).isVirtualRegister() &&
"PHI node doesn't write virt reg?");
unsigned DestReg = MI->getOperand(0).getAllocatedRegNum();
// Create a new register for the incoming PHI arguments
const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
// Insert a register to register copy in the top of the current block (but
// after any remaining phi nodes) which copies the new incoming register
// into the phi node destination.
//
MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
while (AfterPHIsIt != MBB.end() &&
(*AfterPHIsIt)->getOpcode() == TargetInstrInfo::PHI)
++AfterPHIsIt; // Skip over all of the PHI nodes...
RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
// Update live variable information if there is any...
if (LV) {
MachineInstr *PHICopy = *(AfterPHIsIt-1);
// Add information to LiveVariables to know that the incoming value is
// dead. This says that the register is dead, not killed, because we
// cannot use the live variable information to indicate that the variable
// is defined in multiple entry blocks. Instead, we pretend that this
// instruction defined it and killed it at the same time.
//
LV->addVirtualRegisterDead(IncomingReg, PHICopy);
// Since we are going to be deleting the PHI node, if it is the last use
// of any registers, or if the value itself is dead, we need to move this
// information over to the new copy we just inserted...
//
std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator>
RKs = LV->killed_range(MI);
if (RKs.first != RKs.second) {
for (LiveVariables::killed_iterator I = RKs.first; I != RKs.second; ++I)
LV->addVirtualRegisterKilled(I->second, PHICopy);
LV->removeVirtualRegistersKilled(RKs.first, RKs.second);
}
RKs = LV->dead_range(MI);
if (RKs.first != RKs.second) {
for (LiveVariables::killed_iterator I = RKs.first; I != RKs.second; ++I)
LV->addVirtualRegisterDead(I->second, PHICopy);
LV->removeVirtualRegistersDead(RKs.first, RKs.second);
}
}
// Now loop over all of the incoming arguments, changing them to copy into
// the IncomingReg register in the corresponding predecessor basic block.
//
for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
MachineOperand &opVal = MI->getOperand(i-1);
// Get the MachineBasicBlock equivalent of the BasicBlock that is the
// source path the PHI.
MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
// Figure out where to insert the copy, which is at the end of the
// predecessor basic block, but before any terminator/branch
// instructions...
MachineBasicBlock::iterator I = opBlock.end();
if (I != opBlock.begin()) { // Handle empty blocks
--I;
// must backtrack over ALL the branches in the previous block
while (MII.isTerminatorInstr((*I)->getOpcode()) &&
I != opBlock.begin())
--I;
// move back to the first branch instruction so new instructions
// are inserted right in front of it and not in front of a non-branch
if (!MII.isTerminatorInstr((*I)->getOpcode()))
++I;
}
// Check to make sure we haven't already emitted the copy for this block.
// This can happen because PHI nodes may have multiple entries for the
// same basic block. It doesn't matter which entry we use though, because
// all incoming values are guaranteed to be the same for a particular bb.
//
// If we emitted a copy for this basic block already, it will be right
// where we want to insert one now. Just check for a definition of the
// register we are interested in!
//
bool HaveNotEmitted = true;
if (I != opBlock.begin()) {
MachineInstr *PrevInst = *(I-1);
for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) {
MachineOperand &MO = PrevInst->getOperand(i);
if (MO.isVirtualRegister() && MO.getReg() == IncomingReg)
if (MO.opIsDef() || MO.opIsDefAndUse()) {
HaveNotEmitted = false;
break;
}
}
}
if (HaveNotEmitted) {
assert(opVal.isVirtualRegister() &&
"Machine PHI Operands must all be virtual registers!");
RegInfo->copyRegToReg(opBlock, I, IncomingReg, opVal.getReg(), RC);
}
}
// really delete the PHI instruction now!
delete MI;
}
return true;
}
<|endoftext|>
|
<commit_before>/*
* DeliverMissionObjectiveImplementation.cpp
*
* Created on: 20/08/2010
* Author: dannuic
*/
#include "server/zone/objects/mission/DeliverMissionObjective.h"
#include "server/zone/objects/area/MissionSpawnActiveArea.h"
#include "server/ServerCore.h"
#include "server/zone/objects/waypoint/WaypointObject.h"
#include "server/zone/objects/creature/AiAgent.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/region/Region.h"
#include "server/zone/Zone.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/object/ObjectManager.h"
#include "server/zone/managers/creature/CreatureManager.h"
#include "server/zone/managers/mission/MissionManager.h"
#include "server/zone/managers/terrain/TerrainManager.h"
#include "server/zone/managers/planet/PlanetManager.h"
#include "server/zone/packets/object/NpcConversationMessage.h"
#include "server/zone/packets/object/StartNpcConversation.h"
#include "server/zone/packets/object/StopNpcConversation.h"
#include "server/zone/objects/mission/MissionObject.h"
#include "server/zone/objects/mission/MissionObserver.h"
void DeliverMissionObjectiveImplementation::activate() {
if (activated) {
return;
}
MissionObjectiveImplementation::activate();
if (!activateWithResult()) {
//Send error message to player.
ManagedReference<CreatureObject*> owner = getPlayerOwner();
if (owner == NULL) {
return;
}
int randomNumber = System::random(4) + 1;
StringIdChatParameter message("@mission/mission_generic:mission_incomplete_0" + String::valueOf(randomNumber));
owner->sendSystemMessage(message);
removeMissionFromPlayer();
}
}
void DeliverMissionObjectiveImplementation::deactivate() {
if (activated) {
MissionObjectiveImplementation::deactivate();
despawnNpcs();
}
}
bool DeliverMissionObjectiveImplementation::activateWithResult() {
ManagedReference<CreatureObject*> owner = getPlayerOwner();
ManagedReference<MissionObject* > mission = this->mission.get();
if (owner == NULL) {
return false;
}
Zone* zone = owner->getZone();
if (zone == NULL) {
return false;
}
CreatureManager* creatureManager = zone->getCreatureManager();
PlanetManager* planetManager = zone->getPlanetManager();
if (planetManager == NULL) {
return false;
}
TerrainManager* terrainManager = planetManager->getTerrainManager();
if (terrainManager == NULL) {
return false;
}
ZoneServer* zoneServer = owner->getZoneServer();
if (zoneServer == NULL) {
return false;
}
MissionManager* missionManager = zoneServer->getMissionManager();
if (missionManager == NULL) {
return false;
}
//Select spawn type.
int spawnType = NpcSpawnPoint::NEUTRALSPAWN;
switch (mission->getFaction()) {
case MissionObject::FACTIONIMPERIAL:
spawnType = NpcSpawnPoint::IMPERIALSPAWN;
break;
case MissionObject::FACTIONREBEL:
spawnType = NpcSpawnPoint::REBELSPAWN;
break;
default:
spawnType = NpcSpawnPoint::NEUTRALSPAWN;
break;
}
//Spawn target and destination NPC's.
//Target NPC
//Find a free spawn point.
targetSpawnPoint = missionManager->getRandomFreeNpcSpawnPoint(mission->getStartPlanetCRC(), mission->getStartPositionX(), mission->getStartPositionY(), spawnType);
if (targetSpawnPoint == NULL) {
return false;
}
Vector3* targetPosition = targetSpawnPoint->getPosition();
if (targetPosition == NULL) {
return false;
}
//Destination NPC.
//Find a free spawn point.
int retries = 10;
destinationSpawnPoint = NULL;
while (retries > 0 && (destinationSpawnPoint == NULL || destinationSpawnPoint == targetSpawnPoint)) {
destinationSpawnPoint = missionManager->getRandomFreeNpcSpawnPoint(mission->getEndPlanet().hashCode(), mission->getEndPositionX(), mission->getEndPositionY(), spawnType);
retries--;
}
if (destinationSpawnPoint == NULL || destinationSpawnPoint == targetSpawnPoint) {
return false;
}
missionManager->allocateMissionNpcs(targetSpawnPoint, destinationSpawnPoint, terrainManager, creatureManager);
//Create waypoint and activate it.
if (objectiveStatus == 0) {
WaypointObject* waypoint = mission->getWaypointToMission();
if (waypoint == NULL) {
waypoint = mission->createWaypoint();
}
waypoint->setPlanetCRC(mission->getStartPlanetCRC());
waypoint->setPosition(targetPosition->getX(), 0, targetPosition->getY());
waypoint->setActive(true);
mission->updateMissionLocation();
} else {
updateMissionTarget(getPlayerOwner().get());
}
return true;
}
void DeliverMissionObjectiveImplementation::abort() {
MissionObjectiveImplementation::abort();
despawnNpcs();
}
void DeliverMissionObjectiveImplementation::complete() {
despawnNpcs();
MissionObjectiveImplementation::complete();
}
void DeliverMissionObjectiveImplementation::despawnNpcs() {
ZoneServer* zoneServer = ServerCore::getZoneServer();
MissionManager* missionManager = zoneServer->getMissionManager();
if (targetSpawnPoint != NULL)
missionManager->freeMissionNpc(targetSpawnPoint);
if (destinationSpawnPoint != NULL)
missionManager->freeMissionNpc(destinationSpawnPoint);
}
void DeliverMissionObjectiveImplementation::updateMissionStatus(CreatureObject* player) {
ManagedReference<MissionObject* > mission = this->mission.get();
StringBuffer itemEntry;
itemEntry << "m" << mission->getMissionNumber();
ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");
StringId itemName;
Locker lock(player);
switch (objectiveStatus) {
case 0:
itemEntry << "l";
item = NULL;
//TODO: create correct item.
item = (player->getZoneServer()->createObject(String("object/tangible/mission/mission_datadisk.iff").hashCode(), 2)).castTo<TangibleObject*>();
if (item == NULL) {
abort();
return;
}
itemName.setStringId("mission/mission_deliver_neutral_easy", itemEntry.toString());
item->setObjectName(itemName);
//Give player the item to deliver
if (inventory->transferObject(item, -1, true)) {
item->sendTo(player, true);
} else {
abort();
item->destroyObjectFromDatabase(true);
return;
}
updateMissionTarget(player);
objectiveStatus = PICKEDUPSTATUS;
break;
case 1:
// check for item, then remove item
if (item == NULL || !inventory->hasObjectInContainer(item->getObjectID())) {
return;
}
item->destroyObjectFromWorld(true);
item->destroyObjectFromDatabase(true);
complete();
objectiveStatus = DELIVEREDSTATUS;
break;
default:
break;
}
}
bool DeliverMissionObjectiveImplementation::updateMissionTarget(CreatureObject* player) {
//Now update the waypoint to the new target
ManagedReference<MissionObject* > mission = this->mission.get();
WaypointObject* waypoint = mission->getWaypointToMission();
if (waypoint == NULL) {
waypoint = mission->createWaypoint();
}
waypoint->setPlanetCRC(mission->getEndPlanet().hashCode());
waypoint->setPosition(destinationSpawnPoint->getPosition()->getX(), 0, destinationSpawnPoint->getPosition()->getY());
waypoint->setActive(true);
mission->updateMissionLocation();
return true;
}
<commit_msg>[Fixed] stability issue<commit_after>/*
* DeliverMissionObjectiveImplementation.cpp
*
* Created on: 20/08/2010
* Author: dannuic
*/
#include "server/zone/objects/mission/DeliverMissionObjective.h"
#include "server/zone/objects/area/MissionSpawnActiveArea.h"
#include "server/ServerCore.h"
#include "server/zone/objects/waypoint/WaypointObject.h"
#include "server/zone/objects/creature/AiAgent.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/region/Region.h"
#include "server/zone/Zone.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/object/ObjectManager.h"
#include "server/zone/managers/creature/CreatureManager.h"
#include "server/zone/managers/mission/MissionManager.h"
#include "server/zone/managers/terrain/TerrainManager.h"
#include "server/zone/managers/planet/PlanetManager.h"
#include "server/zone/packets/object/NpcConversationMessage.h"
#include "server/zone/packets/object/StartNpcConversation.h"
#include "server/zone/packets/object/StopNpcConversation.h"
#include "server/zone/objects/mission/MissionObject.h"
#include "server/zone/objects/mission/MissionObserver.h"
void DeliverMissionObjectiveImplementation::activate() {
if (activated) {
return;
}
MissionObjectiveImplementation::activate();
if (!activateWithResult()) {
//Send error message to player.
ManagedReference<CreatureObject*> owner = getPlayerOwner();
if (owner == NULL) {
return;
}
int randomNumber = System::random(4) + 1;
StringIdChatParameter message("@mission/mission_generic:mission_incomplete_0" + String::valueOf(randomNumber));
owner->sendSystemMessage(message);
removeMissionFromPlayer();
}
}
void DeliverMissionObjectiveImplementation::deactivate() {
if (activated) {
MissionObjectiveImplementation::deactivate();
despawnNpcs();
}
}
bool DeliverMissionObjectiveImplementation::activateWithResult() {
ManagedReference<CreatureObject*> owner = getPlayerOwner();
ManagedReference<MissionObject* > mission = this->mission.get();
if (owner == NULL) {
return false;
}
Zone* zone = owner->getZone();
if (zone == NULL) {
return false;
}
CreatureManager* creatureManager = zone->getCreatureManager();
PlanetManager* planetManager = zone->getPlanetManager();
if (planetManager == NULL) {
return false;
}
TerrainManager* terrainManager = planetManager->getTerrainManager();
if (terrainManager == NULL) {
return false;
}
ZoneServer* zoneServer = owner->getZoneServer();
if (zoneServer == NULL) {
return false;
}
MissionManager* missionManager = zoneServer->getMissionManager();
if (missionManager == NULL) {
return false;
}
//Select spawn type.
int spawnType = NpcSpawnPoint::NEUTRALSPAWN;
switch (mission->getFaction()) {
case MissionObject::FACTIONIMPERIAL:
spawnType = NpcSpawnPoint::IMPERIALSPAWN;
break;
case MissionObject::FACTIONREBEL:
spawnType = NpcSpawnPoint::REBELSPAWN;
break;
default:
spawnType = NpcSpawnPoint::NEUTRALSPAWN;
break;
}
//Spawn target and destination NPC's.
//Target NPC
//Find a free spawn point.
targetSpawnPoint = missionManager->getRandomFreeNpcSpawnPoint(mission->getStartPlanetCRC(), mission->getStartPositionX(), mission->getStartPositionY(), spawnType);
if (targetSpawnPoint == NULL) {
return false;
}
Vector3* targetPosition = targetSpawnPoint->getPosition();
if (targetPosition == NULL) {
return false;
}
//Destination NPC.
//Find a free spawn point.
int retries = 10;
destinationSpawnPoint = NULL;
while (retries > 0 && (destinationSpawnPoint == NULL || destinationSpawnPoint == targetSpawnPoint)) {
destinationSpawnPoint = missionManager->getRandomFreeNpcSpawnPoint(mission->getEndPlanet().hashCode(), mission->getEndPositionX(), mission->getEndPositionY(), spawnType);
retries--;
}
if (destinationSpawnPoint == NULL || destinationSpawnPoint == targetSpawnPoint) {
return false;
}
missionManager->allocateMissionNpcs(targetSpawnPoint, destinationSpawnPoint, terrainManager, creatureManager);
//Create waypoint and activate it.
if (objectiveStatus == 0) {
WaypointObject* waypoint = mission->getWaypointToMission();
if (waypoint == NULL) {
waypoint = mission->createWaypoint();
}
waypoint->setPlanetCRC(mission->getStartPlanetCRC());
waypoint->setPosition(targetPosition->getX(), 0, targetPosition->getY());
waypoint->setActive(true);
mission->updateMissionLocation();
} else {
updateMissionTarget(getPlayerOwner().get());
}
return true;
}
void DeliverMissionObjectiveImplementation::abort() {
MissionObjectiveImplementation::abort();
despawnNpcs();
}
void DeliverMissionObjectiveImplementation::complete() {
despawnNpcs();
MissionObjectiveImplementation::complete();
}
void DeliverMissionObjectiveImplementation::despawnNpcs() {
ZoneServer* zoneServer = ServerCore::getZoneServer();
MissionManager* missionManager = zoneServer->getMissionManager();
if (targetSpawnPoint != NULL)
missionManager->freeMissionNpc(targetSpawnPoint);
if (destinationSpawnPoint != NULL)
missionManager->freeMissionNpc(destinationSpawnPoint);
}
void DeliverMissionObjectiveImplementation::updateMissionStatus(CreatureObject* player) {
ManagedReference<MissionObject* > mission = this->mission.get();
StringBuffer itemEntry;
itemEntry << "m" << mission->getMissionNumber();
ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");
StringId itemName;
Locker lock(player);
if (objectiveStatus == 0) {
itemEntry << "l";
item = NULL;
//TODO: create correct item.
item = (player->getZoneServer()->createObject(String("object/tangible/mission/mission_datadisk.iff").hashCode(), 2)).castTo<TangibleObject*>();
if (item == NULL) {
abort();
return;
}
Locker clocker(item, player);
itemName.setStringId("mission/mission_deliver_neutral_easy", itemEntry.toString());
item->setObjectName(itemName);
//Give player the item to deliver
if (inventory->transferObject(item, -1, true)) {
item->sendTo(player, true);
} else {
abort();
item->destroyObjectFromDatabase(true);
return;
}
updateMissionTarget(player);
objectiveStatus = PICKEDUPSTATUS;
} else if (objectiveStatus == 1) {
// check for item, then remove item
if (item == NULL || !inventory->hasObjectInContainer(item->getObjectID())) {
return;
}
Locker clocker2(item, player);
item->destroyObjectFromWorld(true);
item->destroyObjectFromDatabase(true);
complete();
objectiveStatus = DELIVEREDSTATUS;
}
}
bool DeliverMissionObjectiveImplementation::updateMissionTarget(CreatureObject* player) {
//Now update the waypoint to the new target
ManagedReference<MissionObject* > mission = this->mission.get();
WaypointObject* waypoint = mission->getWaypointToMission();
if (waypoint == NULL) {
waypoint = mission->createWaypoint();
}
waypoint->setPlanetCRC(mission->getEndPlanet().hashCode());
waypoint->setPosition(destinationSpawnPoint->getPosition()->getX(), 0, destinationSpawnPoint->getPosition()->getY());
waypoint->setActive(true);
mission->updateMissionLocation();
return true;
}
<|endoftext|>
|
<commit_before>// ------------------------------------------------------------------------
// Pion is a development platform for building Reactors that process Events
// ------------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Pion is free software: you can redistribute it and/or modify it under the
// terms of the GNU Affero General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// Pion 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 Affero General Public License for
// more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Pion. If not, see <http://www.gnu.org/licenses/>.
//
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>
#include <pion/PionScheduler.hpp>
#include <pion/platform/ConfigManager.hpp>
#include <pion/platform/CodecFactory.hpp>
#include <pion/platform/ReactionEngine.hpp>
#include "LogInputReactor.hpp"
using namespace pion::platform;
namespace bfs = boost::filesystem;
namespace pion { // begin namespace pion
namespace plugins { // begin namespace plugins
// static members of LogInputReactor
const boost::uint32_t LogInputReactor::DEFAULT_FREQUENCY = 1;
const std::string LogInputReactor::CODEC_ELEMENT_NAME = "Codec";
const std::string LogInputReactor::DIRECTORY_ELEMENT_NAME = "Directory";
const std::string LogInputReactor::FILENAME_ELEMENT_NAME = "Filename";
const std::string LogInputReactor::JUST_ONE_ELEMENT_NAME = "JustOne";
const std::string LogInputReactor::FREQUENCY_ELEMENT_NAME = "Frequency";
// LogInputReactor member functions
void LogInputReactor::setConfig(const Vocabulary& v, const xmlNodePtr config_ptr)
{
// first set config options for the Reactor base class
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
Reactor::setConfig(v, config_ptr);
// get the Codec that the Reactor should use
if (! ConfigManager::getConfigOption(CODEC_ELEMENT_NAME, m_codec_id, config_ptr))
throw EmptyCodecException(getId());
m_codec_ptr = getCodecFactory().getCodec(m_codec_id);
PION_ASSERT(m_codec_ptr);
// get the directory where the Reactor will look for new log files
if (! ConfigManager::getConfigOption(DIRECTORY_ELEMENT_NAME, m_log_directory, config_ptr))
throw EmptyDirectoryException(getId());
// resolve paths relative to the ReactionEngine's config file location
m_log_directory = getReactionEngine().resolveRelativePath(m_log_directory);
// make sure that the directory exists
if (! boost::filesystem::exists(m_log_directory) )
throw DirectoryNotFoundException(m_log_directory);
if (! boost::filesystem::is_directory(m_log_directory) )
throw NotADirectoryException(m_log_directory);
// get the filename regex to use for finding log files
std::string filename_str;
if (! ConfigManager::getConfigOption(FILENAME_ELEMENT_NAME, filename_str, config_ptr))
throw EmptyFilenameException(getId());
m_log_regex = filename_str;
// check if the the Reactor should only read the first Event & duplicate it (for testing)
m_just_one = false;
std::string just_one_option;
if (ConfigManager::getConfigOption(JUST_ONE_ELEMENT_NAME, just_one_option,
config_ptr))
{
if (just_one_option == "true")
m_just_one = true;
}
// get the frequency to check for new logs (if defined)
std::string frequency_str;
if (ConfigManager::getConfigOption(FREQUENCY_ELEMENT_NAME, frequency_str, config_ptr)) {
const boost::uint32_t frequency_value = boost::lexical_cast<boost::uint32_t>(frequency_str);
if (frequency_value <= 0)
throw BadFrequencyException(getId());
m_frequency = frequency_value;
} else {
m_frequency = DEFAULT_FREQUENCY;
}
}
void LogInputReactor::updateVocabulary(const Vocabulary& v)
{
// first update anything in the Reactor base class that might be needed
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
Reactor::updateVocabulary(v);
if (m_codec_ptr)
m_codec_ptr->updateVocabulary(v);
}
void LogInputReactor::updateCodecs(void)
{
// check if the codec was deleted (if so, stop now!)
if (! getCodecFactory().hasPlugin(m_codec_id)) {
stop();
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
m_codec_ptr.reset();
} else {
// update the codec pointer
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
m_codec_ptr = getCodecFactory().getCodec(m_codec_id);
}
}
void LogInputReactor::operator()(const EventPtr& e)
{
if (isRunning()) {
boost::mutex::scoped_lock reactor_lock(m_mutex);
incrementEventsIn();
deliverEvent(e);
}
}
void LogInputReactor::start(void)
{
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
if (! m_is_running) {
// schedule a check for new log files
scheduleLogFileCheck(0);
m_is_running = true;
}
}
void LogInputReactor::stop(void)
{
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
if (m_is_running) {
// set flag to notify reader thread to shutdown
PION_LOG_DEBUG(m_logger, "Stopping input log thread: " << getId());
m_is_running = false;
m_timer_ptr.reset();
}
}
void LogInputReactor::scheduleLogFileCheck(boost::uint32_t seconds)
{
if (seconds == 0) {
getScheduler().post(boost::bind(&LogInputReactor::checkForLogFiles, this));
} else {
if (! m_timer_ptr)
m_timer_ptr.reset(new boost::asio::deadline_timer(getScheduler().getIOService()));
m_timer_ptr->expires_from_now(boost::posix_time::seconds(seconds));
m_timer_ptr->async_wait(boost::bind(&LogInputReactor::checkForLogFiles, this));
}
}
void LogInputReactor::checkForLogFiles(void)
{
// make sure that the reactor is still running
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
if (! isRunning())
return;
PION_LOG_DEBUG(m_logger, "Checking for new log files in " << m_log_directory);
// get the current logs located in the log directory
LogFileCollection current_logs;
getLogFilesInLogDirectory(current_logs);
// remove logs from the consumed collection that are no longer there
LogFileCollection::iterator temp_itr;
LogFileCollection::iterator log_itr = m_logs_consumed.begin();
while (log_itr != m_logs_consumed.end()) {
temp_itr = log_itr++;
if (current_logs.find(*temp_itr) == current_logs.end())
m_logs_consumed.erase(temp_itr);
}
// check for an existing log that has not yet been consumed
for (log_itr = current_logs.begin(); log_itr != current_logs.end(); ++log_itr) {
if (m_logs_consumed.find(*log_itr) == m_logs_consumed.end())
break;
}
if (log_itr == current_logs.end()) {
// no new logs to consume
// sleep until it is time to check again
PION_LOG_DEBUG(m_logger, "No new logs (sleeping for " << m_frequency
<< " seconds): " << m_log_directory);
scheduleLogFileCheck(m_frequency);
} else {
// found a new log to consume
m_logs_consumed.insert(*log_itr);
// re-calculate the full path to the file
bfs::path full_path(m_log_directory);
full_path /= *log_itr;
m_log_file = full_path.file_string();
PION_LOG_DEBUG(m_logger, "Found a new log file to consume: " << m_log_file);
scheduleReadFromLog(true);
}
}
void LogInputReactor::readFromLog(bool use_one_thread)
{
// make sure that the reactor is still running
if (! isRunning())
return;
try {
// open up the log file for reading (if not open already)
if (! m_log_stream.is_open()) {
m_log_stream.open(m_log_file.c_str(), std::ios::in | std::ios::binary);
if (! m_log_stream.is_open())
throw OpenLogException(m_log_file);
else if (m_log_stream.eof())
throw EmptyLogException(m_log_file);
}
const Event::EventType event_type(m_codec_ptr->getEventType());
EventFactory event_factory;
EventPtr event_ptr;
do {
// get a new event from the EventFactory
event_factory.create(event_ptr, event_type);
// read an Event from the log file (convert into an Event using the Codec)
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
if (! m_codec_ptr->read(m_log_stream, *event_ptr))
throw ReadEventException(m_log_file);
// check if only Event should be read
if (m_just_one) {
PION_LOG_DEBUG(m_logger, "JustOne: generating lots of event copies for testing");
m_log_stream.close();
m_log_stream.clear();
// just duplicate the event repeatedly until the Reactor is stopped
EventPtr original_event_ptr(event_ptr);
while (isRunning()) {
// duplicate the original event
event_factory.create(event_ptr, event_type);
*event_ptr += *original_event_ptr;
// deliver the Event to connected Reactors
incrementEventsIn();
deliverEvent(event_ptr);
}
break;
}
// check for end of file
if (m_log_stream.eof()) {
// all done with this log file
PION_LOG_DEBUG(m_logger, "Finished consuming log file: " << m_log_file);
m_log_stream.close();
m_log_stream.clear();
// check for more logs
scheduleLogFileCheck(0);
// deliver the Event to connected Reactors
incrementEventsIn();
deliverEvent(event_ptr);
break;
} else {
// more available: schedule another read operation?
if (! use_one_thread) {
scheduleReadFromLog(false);
// deliver the Event to connected Reactors
incrementEventsIn();
deliverEvent(event_ptr);
break;
}
// deliver the Event to connected Reactors
incrementEventsIn();
deliverEvent(event_ptr);
}
} while (isRunning());
} catch (std::exception& e) {
PION_LOG_ERROR(m_logger, e.what());
m_log_stream.close();
m_log_stream.clear();
scheduleLogFileCheck(0);
}
}
void LogInputReactor::getLogFilesInLogDirectory(LogFileCollection& files)
{
bfs::path dir_path(m_log_directory);
for (bfs::directory_iterator itr(dir_path); itr!=bfs::directory_iterator(); ++itr) {
if (bfs::is_regular(itr->status())) {
const std::string filename(itr->path().leaf());
if (boost::regex_search(filename, m_log_regex))
files.insert(filename);
}
}
}
} // end namespace plugins
} // end namespace pion
/// creates new LogInputReactor objects
extern "C" PION_PLUGIN_API pion::platform::Reactor *pion_create_LogInputReactor(void) {
return new pion::plugins::LogInputReactor();
}
/// destroys LogInputReactor objects
extern "C" PION_PLUGIN_API void pion_destroy_LogInputReactor(pion::plugins::LogInputReactor *reactor_ptr) {
delete reactor_ptr;
}
<commit_msg>Fixed deadlock involving the JustOne LogInputReactor parameter<commit_after>// ------------------------------------------------------------------------
// Pion is a development platform for building Reactors that process Events
// ------------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Pion is free software: you can redistribute it and/or modify it under the
// terms of the GNU Affero General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// Pion 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 Affero General Public License for
// more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Pion. If not, see <http://www.gnu.org/licenses/>.
//
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>
#include <pion/PionScheduler.hpp>
#include <pion/platform/ConfigManager.hpp>
#include <pion/platform/CodecFactory.hpp>
#include <pion/platform/ReactionEngine.hpp>
#include "LogInputReactor.hpp"
using namespace pion::platform;
namespace bfs = boost::filesystem;
namespace pion { // begin namespace pion
namespace plugins { // begin namespace plugins
// static members of LogInputReactor
const boost::uint32_t LogInputReactor::DEFAULT_FREQUENCY = 1;
const std::string LogInputReactor::CODEC_ELEMENT_NAME = "Codec";
const std::string LogInputReactor::DIRECTORY_ELEMENT_NAME = "Directory";
const std::string LogInputReactor::FILENAME_ELEMENT_NAME = "Filename";
const std::string LogInputReactor::JUST_ONE_ELEMENT_NAME = "JustOne";
const std::string LogInputReactor::FREQUENCY_ELEMENT_NAME = "Frequency";
// LogInputReactor member functions
void LogInputReactor::setConfig(const Vocabulary& v, const xmlNodePtr config_ptr)
{
// first set config options for the Reactor base class
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
Reactor::setConfig(v, config_ptr);
// get the Codec that the Reactor should use
if (! ConfigManager::getConfigOption(CODEC_ELEMENT_NAME, m_codec_id, config_ptr))
throw EmptyCodecException(getId());
m_codec_ptr = getCodecFactory().getCodec(m_codec_id);
PION_ASSERT(m_codec_ptr);
// get the directory where the Reactor will look for new log files
if (! ConfigManager::getConfigOption(DIRECTORY_ELEMENT_NAME, m_log_directory, config_ptr))
throw EmptyDirectoryException(getId());
// resolve paths relative to the ReactionEngine's config file location
m_log_directory = getReactionEngine().resolveRelativePath(m_log_directory);
// make sure that the directory exists
if (! boost::filesystem::exists(m_log_directory) )
throw DirectoryNotFoundException(m_log_directory);
if (! boost::filesystem::is_directory(m_log_directory) )
throw NotADirectoryException(m_log_directory);
// get the filename regex to use for finding log files
std::string filename_str;
if (! ConfigManager::getConfigOption(FILENAME_ELEMENT_NAME, filename_str, config_ptr))
throw EmptyFilenameException(getId());
m_log_regex = filename_str;
// check if the the Reactor should only read the first Event & duplicate it (for testing)
m_just_one = false;
std::string just_one_option;
if (ConfigManager::getConfigOption(JUST_ONE_ELEMENT_NAME, just_one_option,
config_ptr))
{
if (just_one_option == "true")
m_just_one = true;
}
// get the frequency to check for new logs (if defined)
std::string frequency_str;
if (ConfigManager::getConfigOption(FREQUENCY_ELEMENT_NAME, frequency_str, config_ptr)) {
const boost::uint32_t frequency_value = boost::lexical_cast<boost::uint32_t>(frequency_str);
if (frequency_value <= 0)
throw BadFrequencyException(getId());
m_frequency = frequency_value;
} else {
m_frequency = DEFAULT_FREQUENCY;
}
}
void LogInputReactor::updateVocabulary(const Vocabulary& v)
{
// first update anything in the Reactor base class that might be needed
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
Reactor::updateVocabulary(v);
if (m_codec_ptr)
m_codec_ptr->updateVocabulary(v);
}
void LogInputReactor::updateCodecs(void)
{
// check if the codec was deleted (if so, stop now!)
if (! getCodecFactory().hasPlugin(m_codec_id)) {
stop();
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
m_codec_ptr.reset();
} else {
// update the codec pointer
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
m_codec_ptr = getCodecFactory().getCodec(m_codec_id);
}
}
void LogInputReactor::operator()(const EventPtr& e)
{
if (isRunning()) {
boost::mutex::scoped_lock reactor_lock(m_mutex);
incrementEventsIn();
deliverEvent(e);
}
}
void LogInputReactor::start(void)
{
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
if (! m_is_running) {
// schedule a check for new log files
scheduleLogFileCheck(0);
m_is_running = true;
}
}
void LogInputReactor::stop(void)
{
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
if (m_is_running) {
// set flag to notify reader thread to shutdown
PION_LOG_DEBUG(m_logger, "Stopping input log thread: " << getId());
m_is_running = false;
m_timer_ptr.reset();
}
}
void LogInputReactor::scheduleLogFileCheck(boost::uint32_t seconds)
{
if (seconds == 0) {
getScheduler().post(boost::bind(&LogInputReactor::checkForLogFiles, this));
} else {
if (! m_timer_ptr)
m_timer_ptr.reset(new boost::asio::deadline_timer(getScheduler().getIOService()));
m_timer_ptr->expires_from_now(boost::posix_time::seconds(seconds));
m_timer_ptr->async_wait(boost::bind(&LogInputReactor::checkForLogFiles, this));
}
}
void LogInputReactor::checkForLogFiles(void)
{
// make sure that the reactor is still running
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
if (! isRunning())
return;
PION_LOG_DEBUG(m_logger, "Checking for new log files in " << m_log_directory);
// get the current logs located in the log directory
LogFileCollection current_logs;
getLogFilesInLogDirectory(current_logs);
// remove logs from the consumed collection that are no longer there
LogFileCollection::iterator temp_itr;
LogFileCollection::iterator log_itr = m_logs_consumed.begin();
while (log_itr != m_logs_consumed.end()) {
temp_itr = log_itr++;
if (current_logs.find(*temp_itr) == current_logs.end())
m_logs_consumed.erase(temp_itr);
}
// check for an existing log that has not yet been consumed
for (log_itr = current_logs.begin(); log_itr != current_logs.end(); ++log_itr) {
if (m_logs_consumed.find(*log_itr) == m_logs_consumed.end())
break;
}
if (log_itr == current_logs.end()) {
// no new logs to consume
// sleep until it is time to check again
PION_LOG_DEBUG(m_logger, "No new logs (sleeping for " << m_frequency
<< " seconds): " << m_log_directory);
scheduleLogFileCheck(m_frequency);
} else {
// found a new log to consume
m_logs_consumed.insert(*log_itr);
// re-calculate the full path to the file
bfs::path full_path(m_log_directory);
full_path /= *log_itr;
m_log_file = full_path.file_string();
PION_LOG_DEBUG(m_logger, "Found a new log file to consume: " << m_log_file);
scheduleReadFromLog(true);
}
}
void LogInputReactor::readFromLog(bool use_one_thread)
{
// make sure that the reactor is still running
if (! isRunning())
return;
try {
// open up the log file for reading (if not open already)
if (! m_log_stream.is_open()) {
m_log_stream.open(m_log_file.c_str(), std::ios::in | std::ios::binary);
if (! m_log_stream.is_open())
throw OpenLogException(m_log_file);
else if (m_log_stream.eof())
throw EmptyLogException(m_log_file);
}
const Event::EventType event_type(m_codec_ptr->getEventType());
EventFactory event_factory;
EventPtr event_ptr;
do {
// get a new event from the EventFactory
event_factory.create(event_ptr, event_type);
// read an Event from the log file (convert into an Event using the Codec)
boost::unique_lock<boost::mutex> reactor_lock(m_mutex);
if (! m_codec_ptr->read(m_log_stream, *event_ptr))
throw ReadEventException(m_log_file);
// check if only Event should be read
if (m_just_one) {
PION_LOG_DEBUG(m_logger, "JustOne: generating lots of event copies for testing");
m_log_stream.close();
m_log_stream.clear();
reactor_lock.unlock();
// just duplicate the event repeatedly until the Reactor is stopped
EventPtr original_event_ptr(event_ptr);
while (isRunning()) {
// duplicate the original event
event_factory.create(event_ptr, event_type);
*event_ptr += *original_event_ptr;
// deliver the Event to connected Reactors
boost::unique_lock<boost::mutex> delivery_lock(m_mutex);
incrementEventsIn();
deliverEvent(event_ptr);
}
break;
}
// check for end of file
if (m_log_stream.eof()) {
// all done with this log file
PION_LOG_DEBUG(m_logger, "Finished consuming log file: " << m_log_file);
m_log_stream.close();
m_log_stream.clear();
// check for more logs
scheduleLogFileCheck(0);
// deliver the Event to connected Reactors
incrementEventsIn();
deliverEvent(event_ptr);
break;
} else {
// more available: schedule another read operation?
if (! use_one_thread) {
scheduleReadFromLog(false);
// deliver the Event to connected Reactors
incrementEventsIn();
deliverEvent(event_ptr);
break;
}
// deliver the Event to connected Reactors
incrementEventsIn();
deliverEvent(event_ptr);
}
} while (isRunning());
} catch (std::exception& e) {
PION_LOG_ERROR(m_logger, e.what());
m_log_stream.close();
m_log_stream.clear();
scheduleLogFileCheck(0);
}
}
void LogInputReactor::getLogFilesInLogDirectory(LogFileCollection& files)
{
bfs::path dir_path(m_log_directory);
for (bfs::directory_iterator itr(dir_path); itr!=bfs::directory_iterator(); ++itr) {
if (bfs::is_regular(itr->status())) {
const std::string filename(itr->path().leaf());
if (boost::regex_search(filename, m_log_regex))
files.insert(filename);
}
}
}
} // end namespace plugins
} // end namespace pion
/// creates new LogInputReactor objects
extern "C" PION_PLUGIN_API pion::platform::Reactor *pion_create_LogInputReactor(void) {
return new pion::plugins::LogInputReactor();
}
/// destroys LogInputReactor objects
extern "C" PION_PLUGIN_API void pion_destroy_LogInputReactor(pion::plugins::LogInputReactor *reactor_ptr) {
delete reactor_ptr;
}
<|endoftext|>
|
<commit_before>/* $Id$ */
/*
* Copyright (c) 2010 SURFnet bv
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "log.h"
#include "ObjectStore.h"
#include "Token.h"
#include "OSAttribute.h"
#include "ByteString.h"
#include "SecureDataManager.h"
#include <sys/time.h>
// Constructor
Token::Token()
{
tokenMutex = MutexFactory::i()->getMutex();
token = NULL;
sdm = NULL;
valid = false;
}
// Constructor
Token::Token(OSToken* token)
{
tokenMutex = MutexFactory::i()->getMutex();
this->token = token;
ByteString soPINBlob, userPINBlob;
valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob);
sdm = new SecureDataManager(soPINBlob, userPINBlob);
}
// Destructor
Token::~Token()
{
if (sdm != NULL) delete sdm;
MutexFactory::i()->recycleMutex(tokenMutex);
}
// Check if the token is still valid
bool Token::isValid()
{
// Lock access to the token
MutexLocker lock(tokenMutex);
return (valid && token->isValid());
}
// Check if the token is initialized
bool Token::isInitialized()
{
if (token == NULL) return false;
return true;
}
// Check if SO is logged in
bool Token::isSOLoggedIn()
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return false;
return sdm->isSOLoggedIn();
}
// Check if user is logged in
bool Token::isUserLoggedIn()
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return false;
return sdm->isUserLoggedIn();
}
// Login SO
CK_RV Token::loginSO(ByteString& pin)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return CKR_GENERAL_ERROR;
// User cannot be logged in
if (sdm->isUserLoggedIn()) return CKR_USER_ANOTHER_ALREADY_LOGGED_IN;
// SO cannot be logged in
if (sdm->isSOLoggedIn()) return CKR_USER_ALREADY_LOGGED_IN;
return sdm->loginSO(pin) ? CKR_OK : CKR_PIN_INCORRECT;
}
// Login user
CK_RV Token::loginUser(ByteString& pin)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return CKR_GENERAL_ERROR;
// SO cannot be logged in
if (sdm->isSOLoggedIn()) return CKR_USER_ANOTHER_ALREADY_LOGGED_IN;
// User cannot be logged in
if (sdm->isUserLoggedIn()) return CKR_USER_ALREADY_LOGGED_IN;
// The user PIN has to be initialized;
if (sdm->getUserPINBlob().size() == 0) return CKR_USER_PIN_NOT_INITIALIZED;
return sdm->loginUser(pin) ? CKR_OK : CKR_PIN_INCORRECT;
}
// Logout any user on this token;
void Token::logout()
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return;
sdm->logout();
}
// Change SO PIN
CK_RV Token::setSOPIN(ByteString& oldPIN, ByteString& newPIN)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return CKR_GENERAL_ERROR;
// Verify oldPIN
SecureDataManager *verifier = new SecureDataManager(sdm->getSOPINBlob(), sdm->getUserPINBlob());
bool result = verifier->loginSO(oldPIN);
delete verifier;
if (result == false) return CKR_PIN_INCORRECT;
if (sdm->setSOPIN(newPIN) == false) return CKR_GENERAL_ERROR;
// Save PIN to token file
if (token->setSOPIN(sdm->getSOPINBlob()) == false) return CKR_GENERAL_ERROR;
ByteString soPINBlob, userPINBlob;
valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob);
return CKR_OK;
}
// Change the user PIN
CK_RV Token::setUserPIN(ByteString& oldPIN, ByteString& newPIN)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return CKR_GENERAL_ERROR;
// Check if user should stay logged in
bool stayLoggedIn = sdm->isUserLoggedIn();
// Verify oldPIN
SecureDataManager *newSdm = new SecureDataManager(sdm->getSOPINBlob(), sdm->getUserPINBlob());
if (newSdm->loginUser(oldPIN) == false)
{
delete newSdm;
return CKR_PIN_INCORRECT;
}
// Set the new user PIN
if (newSdm->setUserPIN(newPIN) == false)
{
delete newSdm;
return CKR_GENERAL_ERROR;
}
// Save PIN to token file
if (token->setUserPIN(sdm->getUserPINBlob()) == false)
{
delete newSdm;
return CKR_GENERAL_ERROR;
}
// Restore previous login state
if (!stayLoggedIn) newSdm->logout();
// Switch sdm
delete sdm;
sdm = newSdm;
ByteString soPINBlob, userPINBlob;
valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob);
return CKR_OK;
}
// Init the user PIN
CK_RV Token::initUserPIN(ByteString& pin)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return CKR_GENERAL_ERROR;
if (sdm->setUserPIN(pin) == false) return CKR_GENERAL_ERROR;
// Save PIN to token file
if (token->setUserPIN(sdm->getUserPINBlob()) == false) return CKR_GENERAL_ERROR;
ByteString soPINBlob, userPINBlob;
valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob);
return CKR_OK;
}
// Create a new token
CK_RV Token::createToken(ObjectStore* objectStore, ByteString& soPIN, CK_UTF8CHAR_PTR label)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (objectStore == NULL) return CKR_GENERAL_ERROR;
if (label == NULL_PTR) return CKR_ARGUMENTS_BAD;
if (token != NULL)
{
if (sdm->getSOPINBlob().size() > 0 && !sdm->loginSO(soPIN))
{
ERROR_MSG("Incorrect SO PIN");
return CKR_PIN_INCORRECT;
}
// The token is already initialised. Destroy it first.
if (!objectStore->destroyToken(token))
{
ERROR_MSG("Failed to destroy existing token");
return CKR_DEVICE_ERROR;
}
token = NULL;
}
// Generate the SO PIN blob
SecureDataManager soPINBlobGen;
if (!soPINBlobGen.setSOPIN(soPIN))
{
return CKR_GENERAL_ERROR;
}
// Convert the label
ByteString labelByteStr((const unsigned char*) label, 32);
// Create the token
OSToken* newToken = objectStore->newToken(labelByteStr);
if (newToken == NULL)
{
return CKR_DEVICE_ERROR;
}
// Set the SO PIN on the token
if (!newToken->setSOPIN(soPINBlobGen.getSOPINBlob()))
{
ERROR_MSG("Failed to set SO PIN on new token");
if (!objectStore->destroyToken(newToken))
{
ERROR_MSG("Failed to destroy incomplete token");
}
return CKR_DEVICE_ERROR;
}
token = newToken;
ByteString soPINBlob, userPINBlob;
valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob);
if (sdm != NULL) delete sdm;
sdm = new SecureDataManager(soPINBlob, userPINBlob);
return CKR_OK;
}
// Retrieve token information for the token
CK_RV Token::getTokenInfo(CK_TOKEN_INFO_PTR info)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
ByteString label, serial;
if (info == NULL)
{
return CKR_ARGUMENTS_BAD;
}
memset(info->label, ' ', 32);
memset(info->serialNumber, ' ', 16);
// Token specific information
if (token)
{
if (!token->getTokenFlags(info->flags))
{
ERROR_MSG("Could not get the token flags");
return CKR_GENERAL_ERROR;
}
if (token->getTokenLabel(label))
{
strncpy((char*) info->label, (char*) label.byte_str(), label.size());
}
if (token->getTokenSerial(serial))
{
strncpy((char*) info->serialNumber, (char*) serial.byte_str(), serial.size());
}
}
else
{
info->flags = CKF_RNG |
CKF_LOGIN_REQUIRED |
CKF_RESTORE_KEY_NOT_NEEDED |
CKF_SO_PIN_LOCKED |
CKF_SO_PIN_TO_BE_CHANGED;
}
// Information shared by all tokens
char mfgID[33];
char model[17];
snprintf(mfgID, 33, "SoftHSM project");
snprintf(model, 17, "SoftHSM v2");
memset(info->manufacturerID, ' ', 32);
memset(info->model, ' ', 16);
strncpy((char*) info->manufacturerID, mfgID, strlen(mfgID));
strncpy((char*) info->model, model, strlen(model));
// TODO: Can we set these?
info->ulSessionCount = CK_UNAVAILABLE_INFORMATION;
info->ulRwSessionCount = CK_UNAVAILABLE_INFORMATION;
info->ulMaxRwSessionCount = CK_EFFECTIVELY_INFINITE;
info->ulMaxSessionCount = CK_EFFECTIVELY_INFINITE;
info->ulMaxPinLen = MAX_PIN_LEN;
info->ulMinPinLen = MIN_PIN_LEN;
info->ulTotalPublicMemory = CK_UNAVAILABLE_INFORMATION;
info->ulFreePublicMemory = CK_UNAVAILABLE_INFORMATION;
info->ulTotalPrivateMemory = CK_UNAVAILABLE_INFORMATION;
info->ulFreePrivateMemory = CK_UNAVAILABLE_INFORMATION;
info->hardwareVersion.major = VERSION_MAJOR;
info->hardwareVersion.minor = VERSION_MINOR;
info->firmwareVersion.major = VERSION_MAJOR;
info->firmwareVersion.minor = VERSION_MINOR;
// Current time
time_t rawtime;
time(&rawtime);
char dateTime[17];
strftime(dateTime, 17, "%Y%m%d%H%M%S00", gmtime(&rawtime));
memcpy(info->utcTime, dateTime, 16);
return CKR_OK;
}
<commit_msg>Use the correct SDM<commit_after>/* $Id$ */
/*
* Copyright (c) 2010 SURFnet bv
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "log.h"
#include "ObjectStore.h"
#include "Token.h"
#include "OSAttribute.h"
#include "ByteString.h"
#include "SecureDataManager.h"
#include <sys/time.h>
// Constructor
Token::Token()
{
tokenMutex = MutexFactory::i()->getMutex();
token = NULL;
sdm = NULL;
valid = false;
}
// Constructor
Token::Token(OSToken* token)
{
tokenMutex = MutexFactory::i()->getMutex();
this->token = token;
ByteString soPINBlob, userPINBlob;
valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob);
sdm = new SecureDataManager(soPINBlob, userPINBlob);
}
// Destructor
Token::~Token()
{
if (sdm != NULL) delete sdm;
MutexFactory::i()->recycleMutex(tokenMutex);
}
// Check if the token is still valid
bool Token::isValid()
{
// Lock access to the token
MutexLocker lock(tokenMutex);
return (valid && token->isValid());
}
// Check if the token is initialized
bool Token::isInitialized()
{
if (token == NULL) return false;
return true;
}
// Check if SO is logged in
bool Token::isSOLoggedIn()
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return false;
return sdm->isSOLoggedIn();
}
// Check if user is logged in
bool Token::isUserLoggedIn()
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return false;
return sdm->isUserLoggedIn();
}
// Login SO
CK_RV Token::loginSO(ByteString& pin)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return CKR_GENERAL_ERROR;
// User cannot be logged in
if (sdm->isUserLoggedIn()) return CKR_USER_ANOTHER_ALREADY_LOGGED_IN;
// SO cannot be logged in
if (sdm->isSOLoggedIn()) return CKR_USER_ALREADY_LOGGED_IN;
return sdm->loginSO(pin) ? CKR_OK : CKR_PIN_INCORRECT;
}
// Login user
CK_RV Token::loginUser(ByteString& pin)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return CKR_GENERAL_ERROR;
// SO cannot be logged in
if (sdm->isSOLoggedIn()) return CKR_USER_ANOTHER_ALREADY_LOGGED_IN;
// User cannot be logged in
if (sdm->isUserLoggedIn()) return CKR_USER_ALREADY_LOGGED_IN;
// The user PIN has to be initialized;
if (sdm->getUserPINBlob().size() == 0) return CKR_USER_PIN_NOT_INITIALIZED;
return sdm->loginUser(pin) ? CKR_OK : CKR_PIN_INCORRECT;
}
// Logout any user on this token;
void Token::logout()
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return;
sdm->logout();
}
// Change SO PIN
CK_RV Token::setSOPIN(ByteString& oldPIN, ByteString& newPIN)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return CKR_GENERAL_ERROR;
// Verify oldPIN
SecureDataManager *verifier = new SecureDataManager(sdm->getSOPINBlob(), sdm->getUserPINBlob());
bool result = verifier->loginSO(oldPIN);
delete verifier;
if (result == false) return CKR_PIN_INCORRECT;
if (sdm->setSOPIN(newPIN) == false) return CKR_GENERAL_ERROR;
// Save PIN to token file
if (token->setSOPIN(sdm->getSOPINBlob()) == false) return CKR_GENERAL_ERROR;
ByteString soPINBlob, userPINBlob;
valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob);
return CKR_OK;
}
// Change the user PIN
CK_RV Token::setUserPIN(ByteString& oldPIN, ByteString& newPIN)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return CKR_GENERAL_ERROR;
// Check if user should stay logged in
bool stayLoggedIn = sdm->isUserLoggedIn();
// Verify oldPIN
SecureDataManager *newSdm = new SecureDataManager(sdm->getSOPINBlob(), sdm->getUserPINBlob());
if (newSdm->loginUser(oldPIN) == false)
{
delete newSdm;
return CKR_PIN_INCORRECT;
}
// Set the new user PIN
if (newSdm->setUserPIN(newPIN) == false)
{
delete newSdm;
return CKR_GENERAL_ERROR;
}
// Save PIN to token file
if (token->setUserPIN(newSdm->getUserPINBlob()) == false)
{
delete newSdm;
return CKR_GENERAL_ERROR;
}
// Restore previous login state
if (!stayLoggedIn) newSdm->logout();
// Switch sdm
delete sdm;
sdm = newSdm;
ByteString soPINBlob, userPINBlob;
valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob);
return CKR_OK;
}
// Init the user PIN
CK_RV Token::initUserPIN(ByteString& pin)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (sdm == NULL) return CKR_GENERAL_ERROR;
if (sdm->setUserPIN(pin) == false) return CKR_GENERAL_ERROR;
// Save PIN to token file
if (token->setUserPIN(sdm->getUserPINBlob()) == false) return CKR_GENERAL_ERROR;
ByteString soPINBlob, userPINBlob;
valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob);
return CKR_OK;
}
// Create a new token
CK_RV Token::createToken(ObjectStore* objectStore, ByteString& soPIN, CK_UTF8CHAR_PTR label)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
if (objectStore == NULL) return CKR_GENERAL_ERROR;
if (label == NULL_PTR) return CKR_ARGUMENTS_BAD;
if (token != NULL)
{
if (sdm->getSOPINBlob().size() > 0 && !sdm->loginSO(soPIN))
{
ERROR_MSG("Incorrect SO PIN");
return CKR_PIN_INCORRECT;
}
// The token is already initialised. Destroy it first.
if (!objectStore->destroyToken(token))
{
ERROR_MSG("Failed to destroy existing token");
return CKR_DEVICE_ERROR;
}
token = NULL;
}
// Generate the SO PIN blob
SecureDataManager soPINBlobGen;
if (!soPINBlobGen.setSOPIN(soPIN))
{
return CKR_GENERAL_ERROR;
}
// Convert the label
ByteString labelByteStr((const unsigned char*) label, 32);
// Create the token
OSToken* newToken = objectStore->newToken(labelByteStr);
if (newToken == NULL)
{
return CKR_DEVICE_ERROR;
}
// Set the SO PIN on the token
if (!newToken->setSOPIN(soPINBlobGen.getSOPINBlob()))
{
ERROR_MSG("Failed to set SO PIN on new token");
if (!objectStore->destroyToken(newToken))
{
ERROR_MSG("Failed to destroy incomplete token");
}
return CKR_DEVICE_ERROR;
}
token = newToken;
ByteString soPINBlob, userPINBlob;
valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob);
if (sdm != NULL) delete sdm;
sdm = new SecureDataManager(soPINBlob, userPINBlob);
return CKR_OK;
}
// Retrieve token information for the token
CK_RV Token::getTokenInfo(CK_TOKEN_INFO_PTR info)
{
// Lock access to the token
MutexLocker lock(tokenMutex);
ByteString label, serial;
if (info == NULL)
{
return CKR_ARGUMENTS_BAD;
}
memset(info->label, ' ', 32);
memset(info->serialNumber, ' ', 16);
// Token specific information
if (token)
{
if (!token->getTokenFlags(info->flags))
{
ERROR_MSG("Could not get the token flags");
return CKR_GENERAL_ERROR;
}
if (token->getTokenLabel(label))
{
strncpy((char*) info->label, (char*) label.byte_str(), label.size());
}
if (token->getTokenSerial(serial))
{
strncpy((char*) info->serialNumber, (char*) serial.byte_str(), serial.size());
}
}
else
{
info->flags = CKF_RNG |
CKF_LOGIN_REQUIRED |
CKF_RESTORE_KEY_NOT_NEEDED |
CKF_SO_PIN_LOCKED |
CKF_SO_PIN_TO_BE_CHANGED;
}
// Information shared by all tokens
char mfgID[33];
char model[17];
snprintf(mfgID, 33, "SoftHSM project");
snprintf(model, 17, "SoftHSM v2");
memset(info->manufacturerID, ' ', 32);
memset(info->model, ' ', 16);
strncpy((char*) info->manufacturerID, mfgID, strlen(mfgID));
strncpy((char*) info->model, model, strlen(model));
// TODO: Can we set these?
info->ulSessionCount = CK_UNAVAILABLE_INFORMATION;
info->ulRwSessionCount = CK_UNAVAILABLE_INFORMATION;
info->ulMaxRwSessionCount = CK_EFFECTIVELY_INFINITE;
info->ulMaxSessionCount = CK_EFFECTIVELY_INFINITE;
info->ulMaxPinLen = MAX_PIN_LEN;
info->ulMinPinLen = MIN_PIN_LEN;
info->ulTotalPublicMemory = CK_UNAVAILABLE_INFORMATION;
info->ulFreePublicMemory = CK_UNAVAILABLE_INFORMATION;
info->ulTotalPrivateMemory = CK_UNAVAILABLE_INFORMATION;
info->ulFreePrivateMemory = CK_UNAVAILABLE_INFORMATION;
info->hardwareVersion.major = VERSION_MAJOR;
info->hardwareVersion.minor = VERSION_MINOR;
info->firmwareVersion.major = VERSION_MAJOR;
info->firmwareVersion.minor = VERSION_MINOR;
// Current time
time_t rawtime;
time(&rawtime);
char dateTime[17];
strftime(dateTime, 17, "%Y%m%d%H%M%S00", gmtime(&rawtime));
memcpy(info->utcTime, dateTime, 16);
return CKR_OK;
}
<|endoftext|>
|
<commit_before>//===--- ArgumentCompletion.cpp ---------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 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 "swift/IDE/ArgumentCompletion.h"
#include "swift/IDE/CodeCompletion.h"
#include "swift/IDE/CompletionLookup.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"
using namespace swift;
using namespace swift::ide;
using namespace swift::constraints;
bool ArgumentTypeCheckCompletionCallback::addPossibleParams(
const ArgumentTypeCheckCompletionCallback::Result &Res,
SmallVectorImpl<PossibleParamInfo> &Params, SmallVectorImpl<Type> &Types) {
if (!Res.ParamIdx) {
// We don't really know much here. Suggest global results without a specific
// expected type.
return true;
}
if (Res.HasLabel) {
// We already have a parameter label, suggest types
Types.push_back(Res.ExpectedType);
return true;
}
ArrayRef<AnyFunctionType::Param> ParamsToPass =
Res.FuncTy->getAs<AnyFunctionType>()->getParams();
ParameterList *PL = nullptr;
if (Res.FuncD) {
PL = swift::getParameterList(Res.FuncD);
}
assert(!PL || PL->size() == ParamsToPass.size());
bool ShowGlobalCompletions = false;
for (auto Idx : range(*Res.ParamIdx, ParamsToPass.size())) {
bool IsCompletion = (Idx == Res.ParamIdx);
// Stop at the first param claimed by other arguments.
if (!IsCompletion && Res.ClaimedParamIndices.count(Idx) > 0) {
break;
}
const AnyFunctionType::Param *P = &ParamsToPass[Idx];
bool Required =
!(PL && PL->get(Idx)->isDefaultArgument()) && !P->isVariadic();
if (P->hasLabel() && !(IsCompletion && Res.IsNoninitialVariadic)) {
// Suggest parameter label if parameter has label, we are completing in it
// and it is not a variadic parameter that already has arguments
PossibleParamInfo PP(P, Required);
if (!llvm::is_contained(Params, PP)) {
Params.push_back(std::move(PP));
}
} else {
// We have a parameter that doesn't require a label. Suggest global
// results for that type.
ShowGlobalCompletions = true;
Types.push_back(P->getPlainType());
}
if (Required) {
// The user should only be suggested the first required param. Stop.
break;
}
}
return ShowGlobalCompletions;
}
void ArgumentTypeCheckCompletionCallback::sawSolutionImpl(const Solution &S) {
Type ExpectedTy = getTypeForCompletion(S, CompletionExpr);
auto &CS = S.getConstraintSystem();
Expr *ParentCall = CompletionExpr;
while (ParentCall && ParentCall->getArgs() == nullptr) {
ParentCall = CS.getParentExpr(ParentCall);
}
if (!ParentCall || ParentCall == CompletionExpr) {
// We might not have a call that contains the code completion expression if
// we type-checked the fallback code completion expression that only
// contains the code completion token, but not the surrounding call.
return;
}
auto ArgInfo = getCompletionArgInfo(ParentCall, CS);
if (!ArgInfo) {
assert(false && "bad parent call match?");
return;
}
auto ArgIdx = ArgInfo->completionIdx;
auto *CallLocator = CS.getConstraintLocator(ParentCall);
auto *CalleeLocator = S.getCalleeLocator(CallLocator);
auto SelectedOverload = S.getOverloadChoiceIfAvailable(CalleeLocator);
if (!SelectedOverload) {
return;
}
Type CallBaseTy = SelectedOverload->choice.getBaseType();
if (CallBaseTy) {
CallBaseTy = S.simplifyType(CallBaseTy)->getRValueType();
}
ValueDecl *FuncD = SelectedOverload->choice.getDeclOrNull();
Type FuncTy = S.simplifyTypeForCodeCompletion(SelectedOverload->openedType);
// For completion as the arg in a call to the implicit [keypath: _] subscript
// the solver can't know what kind of keypath is expected without an actual
// argument (e.g. a KeyPath vs WritableKeyPath) so it ends up as a hole.
// Just assume KeyPath so we show the expected keypath's root type to users
// rather than '_'.
if (SelectedOverload->choice.getKind() ==
OverloadChoiceKind::KeyPathApplication) {
auto Params = FuncTy->getAs<AnyFunctionType>()->getParams();
if (Params.size() == 1 && Params[0].getPlainType()->is<UnresolvedType>()) {
auto *KPDecl = CS.getASTContext().getKeyPathDecl();
Type KPTy =
KPDecl->mapTypeIntoContext(KPDecl->getDeclaredInterfaceType());
Type KPValueTy = KPTy->castTo<BoundGenericType>()->getGenericArgs()[1];
KPTy = BoundGenericType::get(KPDecl, Type(), {CallBaseTy, KPValueTy});
FuncTy = FunctionType::get({Params[0].withType(KPTy)}, KPValueTy);
}
}
// Find the parameter the completion was bound to (if any), as well as which
// parameters are already bound (so we don't suggest them even when the args
// are out of order).
Optional<unsigned> ParamIdx;
std::set<unsigned> ClaimedParams;
bool IsNoninitialVariadic = false;
ConstraintLocator *ArgumentLocator;
ArgumentLocator =
CS.getConstraintLocator(CallLocator, ConstraintLocator::ApplyArgument);
auto ArgMatchChoices = S.argumentMatchingChoices.find(ArgumentLocator);
if (ArgMatchChoices != S.argumentMatchingChoices.end()) {
// We might not have argument matching choices when applying a subscript
// found via @dynamicMemberLookup.
auto Bindings = ArgMatchChoices->second.parameterBindings;
for (auto i : indices(Bindings)) {
bool Claimed = false;
for (auto j : Bindings[i]) {
if (j == ArgIdx) {
assert(!ParamIdx);
ParamIdx = i;
IsNoninitialVariadic = llvm::any_of(
Bindings[i], [j](unsigned other) { return other < j; });
}
// Synthesized args don't count.
if (j < ArgInfo->argCount) {
Claimed = true;
}
}
if (Claimed) {
ClaimedParams.insert(i);
}
}
} else {
// FIXME: We currently don't look through @dynamicMemberLookup applications
// for subscripts (rdar://90363138)
}
bool HasLabel = false;
if (auto PE = CS.getParentExpr(CompletionExpr)) {
if (auto Args = PE->getArgs()) {
HasLabel = !Args->getLabel(ArgIdx).empty();
}
}
bool IsAsync = isContextAsync(S, DC);
// If this is a duplicate of any other result, ignore this solution.
if (llvm::any_of(Results, [&](const Result &R) {
return R.FuncD == FuncD && nullableTypesEqual(R.FuncTy, FuncTy) &&
nullableTypesEqual(R.BaseType, CallBaseTy) &&
R.ParamIdx == ParamIdx &&
R.IsNoninitialVariadic == IsNoninitialVariadic;
})) {
return;
}
Results.push_back({ExpectedTy, isa<SubscriptExpr>(ParentCall), FuncD, FuncTy,
ArgIdx, ParamIdx, std::move(ClaimedParams),
IsNoninitialVariadic, CallBaseTy, HasLabel, IsAsync});
}
void ArgumentTypeCheckCompletionCallback::deliverResults(
bool IncludeSignature, SourceLoc Loc, DeclContext *DC,
ide::CodeCompletionContext &CompletionCtx,
CodeCompletionConsumer &Consumer) {
ASTContext &Ctx = DC->getASTContext();
CompletionLookup Lookup(CompletionCtx.getResultSink(), Ctx, DC,
&CompletionCtx);
// Perform global completion as a fallback if we don't have any results.
bool shouldPerformGlobalCompletion = Results.empty();
SmallVector<Type, 8> ExpectedTypes;
if (IncludeSignature && !Results.empty()) {
Lookup.setHaveLParen(true);
for (auto &Result : Results) {
auto SemanticContext = SemanticContextKind::None;
NominalTypeDecl *BaseNominal = nullptr;
if (Result.BaseType) {
Type BaseTy = Result.BaseType;
if (auto InstanceTy = BaseTy->getMetatypeInstanceType()) {
BaseTy = InstanceTy;
}
if ((BaseNominal = BaseTy->getAnyNominal())) {
SemanticContext = SemanticContextKind::CurrentNominal;
if (Result.FuncD &&
Result.FuncD->getDeclContext()->getSelfNominalTypeDecl() !=
BaseNominal) {
SemanticContext = SemanticContextKind::Super;
}
} else if (BaseTy->is<TupleType>() || BaseTy->is<SubstitutableType>()) {
SemanticContext = SemanticContextKind::CurrentNominal;
}
}
if (Result.IsSubscript) {
assert(SemanticContext != SemanticContextKind::None);
auto *SD = dyn_cast_or_null<SubscriptDecl>(Result.FuncD);
Lookup.addSubscriptCallPattern(Result.FuncTy->getAs<AnyFunctionType>(),
SD, SemanticContext);
} else {
auto *FD = dyn_cast_or_null<AbstractFunctionDecl>(Result.FuncD);
Lookup.addFunctionCallPattern(Result.FuncTy->getAs<AnyFunctionType>(),
FD, SemanticContext);
}
}
Lookup.setHaveLParen(false);
shouldPerformGlobalCompletion |=
!Lookup.FoundFunctionCalls || Lookup.FoundFunctionsWithoutFirstKeyword;
} else if (!Results.empty()) {
SmallVector<PossibleParamInfo, 8> Params;
for (auto &Ret : Results) {
shouldPerformGlobalCompletion |=
addPossibleParams(Ret, Params, ExpectedTypes);
}
Lookup.addCallArgumentCompletionResults(Params);
}
if (shouldPerformGlobalCompletion) {
for (auto &Result : Results) {
ExpectedTypes.push_back(Result.ExpectedType);
}
Lookup.setExpectedTypes(ExpectedTypes, false);
bool IsInAsyncContext = llvm::any_of(
Results, [](const Result &Res) { return Res.IsInAsyncContext; });
Lookup.setCanCurrDeclContextHandleAsync(IsInAsyncContext);
Lookup.getValueCompletionsInDeclContext(Loc);
Lookup.getSelfTypeCompletionInDeclContext(Loc, /*isForDeclResult=*/false);
// Add any keywords that can be used in an argument expr position.
addSuperKeyword(CompletionCtx.getResultSink(), DC);
addExprKeywords(CompletionCtx.getResultSink(), DC);
}
deliverCompletionResults(CompletionCtx, Lookup, DC, Consumer);
}
<commit_msg>[CodeCompletion] Compute semantic context based on where the called fucntion is defined<commit_after>//===--- ArgumentCompletion.cpp ---------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 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 "swift/IDE/ArgumentCompletion.h"
#include "swift/IDE/CodeCompletion.h"
#include "swift/IDE/CompletionLookup.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"
using namespace swift;
using namespace swift::ide;
using namespace swift::constraints;
bool ArgumentTypeCheckCompletionCallback::addPossibleParams(
const ArgumentTypeCheckCompletionCallback::Result &Res,
SmallVectorImpl<PossibleParamInfo> &Params, SmallVectorImpl<Type> &Types) {
if (!Res.ParamIdx) {
// We don't really know much here. Suggest global results without a specific
// expected type.
return true;
}
if (Res.HasLabel) {
// We already have a parameter label, suggest types
Types.push_back(Res.ExpectedType);
return true;
}
ArrayRef<AnyFunctionType::Param> ParamsToPass =
Res.FuncTy->getAs<AnyFunctionType>()->getParams();
ParameterList *PL = nullptr;
if (Res.FuncD) {
PL = swift::getParameterList(Res.FuncD);
}
assert(!PL || PL->size() == ParamsToPass.size());
bool ShowGlobalCompletions = false;
for (auto Idx : range(*Res.ParamIdx, ParamsToPass.size())) {
bool IsCompletion = (Idx == Res.ParamIdx);
// Stop at the first param claimed by other arguments.
if (!IsCompletion && Res.ClaimedParamIndices.count(Idx) > 0) {
break;
}
const AnyFunctionType::Param *P = &ParamsToPass[Idx];
bool Required =
!(PL && PL->get(Idx)->isDefaultArgument()) && !P->isVariadic();
if (P->hasLabel() && !(IsCompletion && Res.IsNoninitialVariadic)) {
// Suggest parameter label if parameter has label, we are completing in it
// and it is not a variadic parameter that already has arguments
PossibleParamInfo PP(P, Required);
if (!llvm::is_contained(Params, PP)) {
Params.push_back(std::move(PP));
}
} else {
// We have a parameter that doesn't require a label. Suggest global
// results for that type.
ShowGlobalCompletions = true;
Types.push_back(P->getPlainType());
}
if (Required) {
// The user should only be suggested the first required param. Stop.
break;
}
}
return ShowGlobalCompletions;
}
void ArgumentTypeCheckCompletionCallback::sawSolutionImpl(const Solution &S) {
Type ExpectedTy = getTypeForCompletion(S, CompletionExpr);
auto &CS = S.getConstraintSystem();
Expr *ParentCall = CompletionExpr;
while (ParentCall && ParentCall->getArgs() == nullptr) {
ParentCall = CS.getParentExpr(ParentCall);
}
if (!ParentCall || ParentCall == CompletionExpr) {
// We might not have a call that contains the code completion expression if
// we type-checked the fallback code completion expression that only
// contains the code completion token, but not the surrounding call.
return;
}
auto ArgInfo = getCompletionArgInfo(ParentCall, CS);
if (!ArgInfo) {
assert(false && "bad parent call match?");
return;
}
auto ArgIdx = ArgInfo->completionIdx;
auto *CallLocator = CS.getConstraintLocator(ParentCall);
auto *CalleeLocator = S.getCalleeLocator(CallLocator);
auto SelectedOverload = S.getOverloadChoiceIfAvailable(CalleeLocator);
if (!SelectedOverload) {
return;
}
Type CallBaseTy = SelectedOverload->choice.getBaseType();
if (CallBaseTy) {
CallBaseTy = S.simplifyType(CallBaseTy)->getRValueType();
}
ValueDecl *FuncD = SelectedOverload->choice.getDeclOrNull();
Type FuncTy = S.simplifyTypeForCodeCompletion(SelectedOverload->openedType);
// For completion as the arg in a call to the implicit [keypath: _] subscript
// the solver can't know what kind of keypath is expected without an actual
// argument (e.g. a KeyPath vs WritableKeyPath) so it ends up as a hole.
// Just assume KeyPath so we show the expected keypath's root type to users
// rather than '_'.
if (SelectedOverload->choice.getKind() ==
OverloadChoiceKind::KeyPathApplication) {
auto Params = FuncTy->getAs<AnyFunctionType>()->getParams();
if (Params.size() == 1 && Params[0].getPlainType()->is<UnresolvedType>()) {
auto *KPDecl = CS.getASTContext().getKeyPathDecl();
Type KPTy =
KPDecl->mapTypeIntoContext(KPDecl->getDeclaredInterfaceType());
Type KPValueTy = KPTy->castTo<BoundGenericType>()->getGenericArgs()[1];
KPTy = BoundGenericType::get(KPDecl, Type(), {CallBaseTy, KPValueTy});
FuncTy = FunctionType::get({Params[0].withType(KPTy)}, KPValueTy);
}
}
// Find the parameter the completion was bound to (if any), as well as which
// parameters are already bound (so we don't suggest them even when the args
// are out of order).
Optional<unsigned> ParamIdx;
std::set<unsigned> ClaimedParams;
bool IsNoninitialVariadic = false;
ConstraintLocator *ArgumentLocator;
ArgumentLocator =
CS.getConstraintLocator(CallLocator, ConstraintLocator::ApplyArgument);
auto ArgMatchChoices = S.argumentMatchingChoices.find(ArgumentLocator);
if (ArgMatchChoices != S.argumentMatchingChoices.end()) {
// We might not have argument matching choices when applying a subscript
// found via @dynamicMemberLookup.
auto Bindings = ArgMatchChoices->second.parameterBindings;
for (auto i : indices(Bindings)) {
bool Claimed = false;
for (auto j : Bindings[i]) {
if (j == ArgIdx) {
assert(!ParamIdx);
ParamIdx = i;
IsNoninitialVariadic = llvm::any_of(
Bindings[i], [j](unsigned other) { return other < j; });
}
// Synthesized args don't count.
if (j < ArgInfo->argCount) {
Claimed = true;
}
}
if (Claimed) {
ClaimedParams.insert(i);
}
}
} else {
// FIXME: We currently don't look through @dynamicMemberLookup applications
// for subscripts (rdar://90363138)
}
bool HasLabel = false;
if (auto PE = CS.getParentExpr(CompletionExpr)) {
if (auto Args = PE->getArgs()) {
HasLabel = !Args->getLabel(ArgIdx).empty();
}
}
bool IsAsync = isContextAsync(S, DC);
// If this is a duplicate of any other result, ignore this solution.
if (llvm::any_of(Results, [&](const Result &R) {
return R.FuncD == FuncD && nullableTypesEqual(R.FuncTy, FuncTy) &&
nullableTypesEqual(R.BaseType, CallBaseTy) &&
R.ParamIdx == ParamIdx &&
R.IsNoninitialVariadic == IsNoninitialVariadic;
})) {
return;
}
Results.push_back({ExpectedTy, isa<SubscriptExpr>(ParentCall), FuncD, FuncTy,
ArgIdx, ParamIdx, std::move(ClaimedParams),
IsNoninitialVariadic, CallBaseTy, HasLabel, IsAsync});
}
void ArgumentTypeCheckCompletionCallback::deliverResults(
bool IncludeSignature, SourceLoc Loc, DeclContext *DC,
ide::CodeCompletionContext &CompletionCtx,
CodeCompletionConsumer &Consumer) {
ASTContext &Ctx = DC->getASTContext();
CompletionLookup Lookup(CompletionCtx.getResultSink(), Ctx, DC,
&CompletionCtx);
// Perform global completion as a fallback if we don't have any results.
bool shouldPerformGlobalCompletion = Results.empty();
SmallVector<Type, 8> ExpectedTypes;
if (IncludeSignature && !Results.empty()) {
Lookup.setHaveLParen(true);
for (auto &Result : Results) {
auto SemanticContext = SemanticContextKind::None;
NominalTypeDecl *BaseNominal = nullptr;
if (Result.BaseType) {
Type BaseTy = Result.BaseType;
if (auto InstanceTy = BaseTy->getMetatypeInstanceType()) {
BaseTy = InstanceTy;
}
if ((BaseNominal = BaseTy->getAnyNominal())) {
SemanticContext = SemanticContextKind::CurrentNominal;
if (Result.FuncD &&
Result.FuncD->getDeclContext()->getSelfNominalTypeDecl() !=
BaseNominal) {
SemanticContext = SemanticContextKind::Super;
}
} else if (BaseTy->is<TupleType>() || BaseTy->is<SubstitutableType>()) {
SemanticContext = SemanticContextKind::CurrentNominal;
}
}
if (SemanticContext == SemanticContextKind::None && Result.FuncD) {
if (Result.FuncD->getDeclContext()->isTypeContext()) {
SemanticContext = SemanticContextKind::CurrentNominal;
} else if (Result.FuncD->getDeclContext()->isLocalContext()) {
SemanticContext = SemanticContextKind::Local;
} else if (Result.FuncD->getModuleContext() == DC->getParentModule()) {
SemanticContext = SemanticContextKind::CurrentModule;
}
}
if (Result.IsSubscript) {
assert(SemanticContext != SemanticContextKind::None);
auto *SD = dyn_cast_or_null<SubscriptDecl>(Result.FuncD);
Lookup.addSubscriptCallPattern(Result.FuncTy->getAs<AnyFunctionType>(),
SD, SemanticContext);
} else {
auto *FD = dyn_cast_or_null<AbstractFunctionDecl>(Result.FuncD);
Lookup.addFunctionCallPattern(Result.FuncTy->getAs<AnyFunctionType>(),
FD, SemanticContext);
}
}
Lookup.setHaveLParen(false);
shouldPerformGlobalCompletion |=
!Lookup.FoundFunctionCalls || Lookup.FoundFunctionsWithoutFirstKeyword;
} else if (!Results.empty()) {
SmallVector<PossibleParamInfo, 8> Params;
for (auto &Ret : Results) {
shouldPerformGlobalCompletion |=
addPossibleParams(Ret, Params, ExpectedTypes);
}
Lookup.addCallArgumentCompletionResults(Params);
}
if (shouldPerformGlobalCompletion) {
for (auto &Result : Results) {
ExpectedTypes.push_back(Result.ExpectedType);
}
Lookup.setExpectedTypes(ExpectedTypes, false);
bool IsInAsyncContext = llvm::any_of(
Results, [](const Result &Res) { return Res.IsInAsyncContext; });
Lookup.setCanCurrDeclContextHandleAsync(IsInAsyncContext);
Lookup.getValueCompletionsInDeclContext(Loc);
Lookup.getSelfTypeCompletionInDeclContext(Loc, /*isForDeclResult=*/false);
// Add any keywords that can be used in an argument expr position.
addSuperKeyword(CompletionCtx.getResultSink(), DC);
addExprKeywords(CompletionCtx.getResultSink(), DC);
}
deliverCompletionResults(CompletionCtx, Lookup, DC, Consumer);
}
<|endoftext|>
|
<commit_before>// Example of analysis class for the H1 data using code generated by MakeProxy.
// ===========================================================================
//
// This file uses 4 large data sets from the H1 collaboration at DESY Hamburg.
// One can access these data sets (277 MBytes) from the standard Root web site
// at: ftp://root.cern.ch/root/h1analysis/
// The Physics plots below generated by this example cannot be produced when
// using smaller data sets.
//
// There are several ways to analyze data stored in a Root Tree
// -Using TTree::Draw: This is very convenient and efficient for small tasks.
// A TTree::Draw call produces one histogram at the time. The histogram
// is automatically generated. The selection expression may be specified
// in the command line.
//
// -Using the TTreeViewer: This is a graphical interface to TTree::Draw
// with the same functionality.
//
// -Using the code generated by TTree::MakeClass: In this case, the user
// creates an instance of the analysis class. He has the control over
// the event loop and he can generate an unlimited number of histograms.
//
// -Using the code generated by TTree::MakeSelector. Like for the code
// generated by TTree::MakeClass, the user can do complex analysis.
// However, he cannot control the event loop. The event loop is controlled
// by TTree::Process called by the user. This solution is illustrated
// by the current code. The advantage of this method is that it can be run
// in a parallel environment using PROOF (the Parallel Root Facility).
//
// A chain of 4 files (originally converted from PAW ntuples) is used
// to illustrate the various ways to loop on Root data sets.
// Each data set contains a Root Tree named "h42"
// The class definition in h1analysis.h has been generated automatically
// by the Root utility TTree::MakeSelector using one of the files with the
// following statement:
// h42->MakeSelector("h1analysis");
// This produces two files: h1analysis.h and h1analysis.C (skeleton of this file)
// The h1analysis class is derived from the Root class TSelector.
//
// The following members functions are called by the TTree::Process functions.
// Begin(): called everytime a loop on the tree starts.
// a convenient place to create your histograms.
// SlaveBegin():
//
// Notify(): This function is called at the first entry of a new Tree
// in a chain.
// Process(): called to analyze each entry.
//
// SlaveTerminate():
//
// Terminate(): called at the end of a loop on a TTree.
// a convenient place to draw/fit your histograms.
//
// To use this file, try the following session
//
// Root > gROOT->Time(); //will show RT & CPU time per command
//
//==> A- create a TChain with the 4 H1 data files
// The chain can be created by executed the short macro h1chain.C below:
// {
// TChain chain("h42");
// chain.Add("$H1/dstarmb.root"); // 21330730 bytes 21920 events
// chain.Add("$H1/dstarp1a.root"); // 71464503 bytes 73243 events
// chain.Add("$H1/dstarp1b.root"); // 83827959 bytes 85597 events
// chain.Add("$H1/dstarp2.root"); // 100675234 bytes 103053 events
// //where $H1 is a system symbol pointing to the H1 data directory.
// }
//
// Root > .x h1chain.C
//
//==> B- loop on all events
// Root > chain.Process("h1analysis.C")
//
//==> C- same as B, but in addition fill the event list with selected entries.
// The event list is saved to a file "elist.root" by the Terminate function.
// To see the list of selected events, you can do elist->Print("all").
// The selection function has selected 7525 events out of the 283813 events
// in the chain of files. (2.65 per cent)
// Root > chain.Process("h1analysis.C","fillList")
//
//==> D- Process only entries in the event list
// The event list is read from the file in elist.root generated by step C
// Root > chain.Process("h1analysis.C","useList")
//
//==> E- the above steps have been executed via the interpreter.
// You can repeat the steps B, C and D using the script compiler
// by replacing "h1analysis.C" by "h1analysis.C+" or "h1analysis.C++"
//
// in a new session with ,eg:
//
//==> F- Create the chain as in A, then execute
// Root > chain.Process("h1analysis.C+","useList")
//
// The commands executed with the 4 different methods B,C,D and E
// produce two canvases shown below:
// begin_html <a href="gif/h1analysis_dstar.gif" >the Dstar plot</a> end_html
// begin_html <a href="gif/h1analysis_tau.gif" >the Tau D0 plot</a> end_html
//
//Author; Philippe Canal from original h1analysis.C by Rene Brun
TEventList *elist;
Bool_t useList, fillList;
TH1F *hdmd;
TH2F *h2;
//_____________________________________________________________________
void h1analysisProxy_Begin(TTree * /* tree */ )
{
// function called before starting the event loop
// -it performs some cleanup
// -it creates histograms
// -it sets some initialisation for the event list
//print the option specified in the Process function.
TString option = GetOption();
printf("Starting (begin) h1analysis with process option: %s\n",option.Data());
//some cleanup in case this function had already been executed
//delete any previously generated histograms or functions
gDirectory->Delete("hdmd");
gDirectory->Delete("h2*");
delete gROOT->GetFunction("f5");
delete gROOT->GetFunction("f2");
}
//_____________________________________________________________________
void h1analysisProxy_SlaveBegin(TTree *tree)
{
// function called before starting the event loop
// -it performs some cleanup
// -it creates histograms
// -it sets some initialisation for the event list
//initialize the Tree branch addresses
Init(tree);
//print the option specified in the Process function.
TString option = GetOption();
printf("Starting (slave) h1analysis with process option: %s\n",option.Data());
//some cleanup in case this function had already been executed
//delete any previously generated histograms or functions
gDirectory->Delete("hdmd");
gDirectory->Delete("h2*");
delete gROOT->GetFunction("f5");
delete gROOT->GetFunction("f2");
//create histograms
hdmd = new TH1F("hdmd","dm_d",40,0.13,0.17);
h2 = new TH2F("h2","ptD0 vs dm_d",30,0.135,0.165,30,-3,6);
fOutput->Add(hdmd);
fOutput->Add(h2);
//process cases with event list
fillList = kFALSE;
useList = kFALSE;
tree->SetEventList(0);
delete gDirectory->GetList()->FindObject("elist");
// case when one creates/fills the event list
if (option.Contains("fillList")) {
fillList = kTRUE;
elist = new TEventList("elist","selection from Cut",5000);
} else elist = 0;
// case when one uses the event list generated in a previous call
if (option.Contains("useList")) {
useList = kTRUE;
TFile f("elist.root");
elist = (TEventList*)f.Get("elist");
if (elist) elist->SetDirectory(0); //otherwise the file destructor will delete elist
tree->SetEventList(elist);
}
}
Double_t h1analysisProxy() {
return 0;
}
//_____________________________________________________________________
Bool_t h1analysisProxy_Process(Long64_t entry)
{
// entry is the entry number in the current Tree
// Selection function to select D* and D0.
//in case one event list is given in input, the selection has already been done.
if (!useList) {
float f1 = md0_d;
float f2 = md0_d-1.8646;
bool test = TMath::Abs(md0_d-1.8646) >= 0.04;
if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
fChain->GetReadEntry(),f1,f2,test);
if (TMath::Abs(md0_d-1.8646) >= 0.04) return kFALSE;
if (ptds_d <= 2.5) return kFALSE;
if (TMath::Abs(etads_d) >= 1.5) return kFALSE;
int cik = ik-1; //original ik used f77 convention starting at 1
int cipi = ipi-1; //original ipi used f77 convention starting at 1
f1 = nhitrp[cik];
f2 = nhitrp[cipi];
test = nhitrp[cik]*nhitrp[cipi] <= 1;
if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
fChain->GetReadEntry(),f1,f2,test);
if (nhitrp[cik]*nhitrp[cipi] <= 1) return kFALSE;
if (rend[cik] -rstart[cik] <= 22) return kFALSE;
if (rend[cipi]-rstart[cipi] <= 22) return kFALSE;
if (nlhk[cik] <= 0.1) return kFALSE;
if (nlhpi[cipi] <= 0.1) return kFALSE;
// fix because read-only
if (nlhpi[ipis-1] <= 0.1) return kFALSE;
if (njets < 1) return kFALSE;
}
// if option fillList, fill the event list
if (fillList) elist->Enter(fChain->GetChainEntryNumber(entry));
//fill some histograms
hdmd->Fill(dm_d);
h2->Fill(dm_d,rpd0_t/0.029979*1.8646/ptd0_d);
return kTRUE;
}
//_____________________________________________________________________
void h1analysisProxy_SlaveTerminate()
{
// nothing to be done
printf("Terminate (slave) h1analysis\n");
}
//_____________________________________________________________________
void h1analysisProxy_Terminate()
{
printf("Terminate (final) h1analysis\n");
// function called at the end of the event loop
hdmd = dynamic_cast<TH1F*>(fOutput->FindObject("hdmd"));
h2 = dynamic_cast<TH2F*>(fOutput->FindObject("h2"));
if (hdmd == 0 || h2 == 0) {
Error("Terminate", "hdmd = %p , h2 = %p", hdmd, h2);
return;
}
//create the canvas for the h1analysis fit
gStyle->SetOptFit();
TCanvas *c1 = new TCanvas("c1","h1analysis analysis",10,10,800,600);
c1->SetBottomMargin(0.15);
hdmd->GetXaxis()->SetTitle("m_{K#pi#pi} - m_{K#pi}[GeV/c^{2}]");
hdmd->GetXaxis()->SetTitleOffset(1.4);
//fit histogram hdmd with function f5 using the loglikelihood option
TF1 *f5 = new TF1("f5",fdm5,0.139,0.17,5);
f5->SetParameters(1000000, .25, 2000, .1454, .001);
hdmd->Fit("f5","lr");
//create the canvas for tau d0
gStyle->SetOptFit(0);
gStyle->SetOptStat(1100);
TCanvas *c2 = new TCanvas("c2","tauD0",100,100,800,600);
c2->SetGrid();
c2->SetBottomMargin(0.15);
// Project slices of 2-d histogram h2 along X , then fit each slice
// with function f2 and make a histogram for each fit parameter
// Note that the generated histograms are added to the list of objects
// in the current directory.
TF1 *f2 = new TF1("f2",fdm2,0.139,0.17,2);
f2->SetParameters(10000, 10);
h2->FitSlicesX(f2,0,0,1,"qln");
TH1D *h2_1 = (TH1D*)gDirectory->Get("h2_1");
h2_1->GetXaxis()->SetTitle("#tau[ps]");
h2_1->SetMarkerStyle(21);
h2_1->Draw();
c2->Update();
TLine *line = new TLine(0,0,0,c2->GetUymax());
line->Draw();
//save the event list to a Root file if one was produced
if (fillList) {
TFile efile("elist.root","recreate");
elist->Write();
}
}
<commit_msg>Correctly indicate usage of the 'MakeProxy' selector'<commit_after>// Example of analysis class for the H1 data using code generated by MakeProxy.
// ===========================================================================
//
// This file uses 4 large data sets from the H1 collaboration at DESY Hamburg.
// One can access these data sets (277 MBytes) from the standard Root web site
// at: ftp://root.cern.ch/root/h1analysis/
// The Physics plots below generated by this example cannot be produced when
// using smaller data sets.
//
// There are several ways to analyze data stored in a Root Tree
// -Using TTree::Draw: This is very convenient and efficient for small tasks.
// A TTree::Draw call produces one histogram at the time. The histogram
// is automatically generated. The selection expression may be specified
// in the command line.
//
// -Using the TTreeViewer: This is a graphical interface to TTree::Draw
// with the same functionality.
//
// -Using the code generated by TTree::MakeClass: In this case, the user
// creates an instance of the analysis class. He has the control over
// the event loop and he can generate an unlimited number of histograms.
//
// -Using the code generated by TTree::MakeSelector. Like for the code
// generated by TTree::MakeClass, the user can do complex analysis.
// However, he cannot control the event loop. The event loop is controlled
// by TTree::Process called by the user. This solution is illustrated
// by the current code. The advantage of this method is that it can be run
// in a parallel environment using PROOF (the Parallel Root Facility).
//
// A chain of 4 files (originally converted from PAW ntuples) is used
// to illustrate the various ways to loop on Root data sets.
// Each data set contains a Root Tree named "h42"
//
// h1analysProxy.C can use either via TTree::Draw:
// h42->Draw("h1analysisProxy.C");
// or it can be used directly with TTree::MakeProxy, for example to generate a
// shared library. TTree::MakeProxy will generate a TSelector skeleton that
// include h1analysProxy.C:
// h42->MakeProxy("h1sel","h1analysisProxy.C");
// This produces one file: h1sel.h which does a #include "h1analysProxy.C"
// The h1sel class is derived from the Root class TSelector and can then
// be used as:
// h42->Process("h1sel.h+");
//
// The following members functions are called by the TTree::Process functions.
// h1analysProxy_Begin(): called everytime a loop on the tree starts.
// a convenient place to create your histograms.
// h1analysProxy_SlaveBegin():
//
// h1analysProxy_Notify(): This function is called at the first entry of a new Tree
// in a chain.
// h1analysProxy_Process(): called to analyze each entry.
//
// h1analysProxy_SlaveTerminate():
//
// h1analysProxy_Terminate(): called at the end of a loop on a TTree.
// a convenient place to draw/fit your histograms.
//
// To use this file, try the following session
//
// Root > gROOT->Time(); //will show RT & CPU time per command
//
//==> A- create a TChain with the 4 H1 data files
// The chain can be created by executed the short macro h1chain.C below:
// {
// TChain chain("h42");
// chain.Add("$H1/dstarmb.root"); // 21330730 bytes 21920 events
// chain.Add("$H1/dstarp1a.root"); // 71464503 bytes 73243 events
// chain.Add("$H1/dstarp1b.root"); // 83827959 bytes 85597 events
// chain.Add("$H1/dstarp2.root"); // 100675234 bytes 103053 events
// //where $H1 is a system symbol pointing to the H1 data directory.
// }
//
// Root > .x h1chain.C
//
//==> B- loop on all events
// Root > chain.Draw("h1analysisProxy.C")
//
//==> C- same as B, but in addition fill the event list with selected entries.
// The event list is saved to a file "elist.root" by the Terminate function.
// To see the list of selected events, you can do elist->Print("all").
// The selection function has selected 7525 events out of the 283813 events
// in the chain of files. (2.65 per cent)
// Root > chain.Draw("h1analysisProxy.C","","fillList")
//
//==> D- Process only entries in the event list
// The event list is read from the file in elist.root generated by step C
// Root > chain.Draw("h1analysisProxy.C","","useList")
////
// The commands executed with the 3 different methods B,C and D
// produce two canvases shown below:
// begin_html <a href="gif/h1analysis_dstar.gif" >the Dstar plot</a> end_html
// begin_html <a href="gif/h1analysis_tau.gif" >the Tau D0 plot</a> end_html
//
//Author; Philippe Canal from original h1analysis.C by Rene Brun
TEventList *elist;
Bool_t useList, fillList;
TH1F *hdmd;
TH2F *h2;
//_____________________________________________________________________
void h1analysisProxy_Begin(TTree * /* tree */ )
{
// function called before starting the event loop
// -it performs some cleanup
// -it creates histograms
// -it sets some initialisation for the event list
//print the option specified in the Process function.
TString option = GetOption();
printf("Starting (begin) h1analysis with process option: %s\n",option.Data());
//some cleanup in case this function had already been executed
//delete any previously generated histograms or functions
gDirectory->Delete("hdmd");
gDirectory->Delete("h2*");
delete gROOT->GetFunction("f5");
delete gROOT->GetFunction("f2");
}
//_____________________________________________________________________
void h1analysisProxy_SlaveBegin(TTree *tree)
{
// function called before starting the event loop
// -it performs some cleanup
// -it creates histograms
// -it sets some initialisation for the event list
//initialize the Tree branch addresses
Init(tree);
//print the option specified in the Process function.
TString option = GetOption();
printf("Starting (slave) h1analysis with process option: %s\n",option.Data());
//some cleanup in case this function had already been executed
//delete any previously generated histograms or functions
gDirectory->Delete("hdmd");
gDirectory->Delete("h2*");
delete gROOT->GetFunction("f5");
delete gROOT->GetFunction("f2");
//create histograms
hdmd = new TH1F("hdmd","dm_d",40,0.13,0.17);
h2 = new TH2F("h2","ptD0 vs dm_d",30,0.135,0.165,30,-3,6);
fOutput->Add(hdmd);
fOutput->Add(h2);
//process cases with event list
fillList = kFALSE;
useList = kFALSE;
tree->SetEventList(0);
delete gDirectory->GetList()->FindObject("elist");
// case when one creates/fills the event list
if (option.Contains("fillList")) {
fillList = kTRUE;
elist = new TEventList("elist","selection from Cut",5000);
} else elist = 0;
// case when one uses the event list generated in a previous call
if (option.Contains("useList")) {
useList = kTRUE;
TFile f("elist.root");
elist = (TEventList*)f.Get("elist");
if (elist) elist->SetDirectory(0); //otherwise the file destructor will delete elist
tree->SetEventList(elist);
}
}
Double_t h1analysisProxy() {
return 0;
}
//_____________________________________________________________________
Bool_t h1analysisProxy_Process(Long64_t entry)
{
// entry is the entry number in the current Tree
// Selection function to select D* and D0.
//in case one event list is given in input, the selection has already been done.
if (!useList) {
float f1 = md0_d;
float f2 = md0_d-1.8646;
bool test = TMath::Abs(md0_d-1.8646) >= 0.04;
if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
fChain->GetReadEntry(),f1,f2,test);
if (TMath::Abs(md0_d-1.8646) >= 0.04) return kFALSE;
if (ptds_d <= 2.5) return kFALSE;
if (TMath::Abs(etads_d) >= 1.5) return kFALSE;
int cik = ik-1; //original ik used f77 convention starting at 1
int cipi = ipi-1; //original ipi used f77 convention starting at 1
f1 = nhitrp[cik];
f2 = nhitrp[cipi];
test = nhitrp[cik]*nhitrp[cipi] <= 1;
if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
fChain->GetReadEntry(),f1,f2,test);
if (nhitrp[cik]*nhitrp[cipi] <= 1) return kFALSE;
if (rend[cik] -rstart[cik] <= 22) return kFALSE;
if (rend[cipi]-rstart[cipi] <= 22) return kFALSE;
if (nlhk[cik] <= 0.1) return kFALSE;
if (nlhpi[cipi] <= 0.1) return kFALSE;
// fix because read-only
if (nlhpi[ipis-1] <= 0.1) return kFALSE;
if (njets < 1) return kFALSE;
}
// if option fillList, fill the event list
if (fillList) elist->Enter(fChain->GetChainEntryNumber(entry));
//fill some histograms
hdmd->Fill(dm_d);
h2->Fill(dm_d,rpd0_t/0.029979*1.8646/ptd0_d);
return kTRUE;
}
//_____________________________________________________________________
void h1analysisProxy_SlaveTerminate()
{
// nothing to be done
printf("Terminate (slave) h1analysis\n");
}
//_____________________________________________________________________
void h1analysisProxy_Terminate()
{
printf("Terminate (final) h1analysis\n");
// function called at the end of the event loop
hdmd = dynamic_cast<TH1F*>(fOutput->FindObject("hdmd"));
h2 = dynamic_cast<TH2F*>(fOutput->FindObject("h2"));
if (hdmd == 0 || h2 == 0) {
Error("Terminate", "hdmd = %p , h2 = %p", hdmd, h2);
return;
}
//create the canvas for the h1analysis fit
gStyle->SetOptFit();
TCanvas *c1 = new TCanvas("c1","h1analysis analysis",10,10,800,600);
c1->SetBottomMargin(0.15);
hdmd->GetXaxis()->SetTitle("m_{K#pi#pi} - m_{K#pi}[GeV/c^{2}]");
hdmd->GetXaxis()->SetTitleOffset(1.4);
//fit histogram hdmd with function f5 using the loglikelihood option
TF1 *f5 = new TF1("f5",fdm5,0.139,0.17,5);
f5->SetParameters(1000000, .25, 2000, .1454, .001);
hdmd->Fit("f5","lr");
//create the canvas for tau d0
gStyle->SetOptFit(0);
gStyle->SetOptStat(1100);
TCanvas *c2 = new TCanvas("c2","tauD0",100,100,800,600);
c2->SetGrid();
c2->SetBottomMargin(0.15);
// Project slices of 2-d histogram h2 along X , then fit each slice
// with function f2 and make a histogram for each fit parameter
// Note that the generated histograms are added to the list of objects
// in the current directory.
TF1 *f2 = new TF1("f2",fdm2,0.139,0.17,2);
f2->SetParameters(10000, 10);
h2->FitSlicesX(f2,0,0,1,"qln");
TH1D *h2_1 = (TH1D*)gDirectory->Get("h2_1");
h2_1->GetXaxis()->SetTitle("#tau[ps]");
h2_1->SetMarkerStyle(21);
h2_1->Draw();
c2->Update();
TLine *line = new TLine(0,0,0,c2->GetUymax());
line->Draw();
//save the event list to a Root file if one was produced
if (fillList) {
TFile efile("elist.root","recreate");
elist->Write();
}
}
<|endoftext|>
|
<commit_before>//
// (C) CharLS Team 2014, all rights reserved. See the accompanying "License.txt" for licensed use.
//
#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\src\encoderstrategy.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
class EncoderStrategyTester : EncoderStrategy
{
public:
EncoderStrategyTester(const JlsParameters& info) : EncoderStrategy(info)
{
}
virtual void SetPresets(const JlsCustomParameters&)
{
}
virtual size_t EncodeScan(std::unique_ptr<ProcessLine>, ByteStreamInfo*, void*)
{
return 0;
}
virtual ProcessLine* CreateProcess(ByteStreamInfo)
{
return nullptr;
}
void AppendToBitStreamTest(int32_t value, int32_t length)
{
AppendToBitStream(value, length);
}
};
namespace CharLSUnitTest
{
TEST_CLASS(EncoderStrategyTest)
{
public:
TEST_METHOD(AppendToBitStream)
{
JlsParameters info;
EncoderStrategyTester es(info);
es.AppendToBitStreamTest(0, 0);
}
};
}
<commit_msg>Method argument updated to match base class.<commit_after>//
// (C) CharLS Team 2014, all rights reserved. See the accompanying "License.txt" for licensed use.
//
#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\src\encoderstrategy.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
class EncoderStrategyTester : EncoderStrategy
{
public:
EncoderStrategyTester(const JlsParameters& info) : EncoderStrategy(info)
{
}
virtual void SetPresets(const JlsCustomParameters&)
{
}
virtual size_t EncodeScan(std::unique_ptr<ProcessLine>, ByteStreamInfo&, void*)
{
return 0;
}
virtual ProcessLine* CreateProcess(ByteStreamInfo)
{
return nullptr;
}
void AppendToBitStreamTest(int32_t value, int32_t length)
{
AppendToBitStream(value, length);
}
};
namespace CharLSUnitTest
{
TEST_CLASS(EncoderStrategyTest)
{
public:
TEST_METHOD(AppendToBitStream)
{
JlsParameters info;
EncoderStrategyTester es(info);
es.AppendToBitStreamTest(0, 0);
}
};
}
<|endoftext|>
|
<commit_before>
#include <iostream>
#include <gtest/gtest.h>
#include "TestHelpers.h"
#include "dart/dynamics/SoftBodyNode.h"
using namespace dart;
using namespace math;
using namespace dynamics;
//==============================================================================
TEST(NameManagement, Basic)
{
//--------------------------------------------------------------------------
//
//--------------------------------------------------------------------------
// Bodies
BodyNode* body1 = new BodyNode;
BodyNode* body2 = new BodyNode;
BodyNode* body3 = new BodyNode;
// TODO: Add some SoftBodyNodes into this test.
// Grey is not familiar with construction of SoftBodyNodes,
// so he is leaving that for someone else for the time being.
// Joints
Joint* joint1 = new RevoluteJoint(Eigen::Vector3d::UnitX(), "joint");
Joint* joint2 = new TranslationalJoint("joint");
Joint* joint3 = new FreeJoint("joint");
// Testing whether DegreesOfFreedom get named correctly
EXPECT_TRUE(joint1->getDof(0)->getName() == "joint");
EXPECT_TRUE(joint2->getDof(0)->getName() == "joint_x");
EXPECT_TRUE(joint2->getDof(1)->getName() == "joint_y");
EXPECT_TRUE(joint2->getDof(2)->getName() == "joint_z");
EXPECT_TRUE(joint3->getDof(0)->getName() == "joint_rot_x");
EXPECT_TRUE(joint3->getDof(1)->getName() == "joint_rot_y");
EXPECT_TRUE(joint3->getDof(2)->getName() == "joint_rot_z");
EXPECT_TRUE(joint3->getDof(3)->getName() == "joint_pos_x");
EXPECT_TRUE(joint3->getDof(4)->getName() == "joint_pos_y");
EXPECT_TRUE(joint3->getDof(5)->getName() == "joint_pos_z");
// Skeleton
Skeleton* skel = new Skeleton;
body1->setParentJoint(joint1);
body2->setParentJoint(joint2);
body3->setParentJoint(joint3);
body1->addChildBodyNode(body2);
body2->addChildBodyNode(body3);
skel->addBodyNode(body1);
skel->addBodyNode(body2);
skel->addBodyNode(body3);
skel->init();
// Testing whether the repeated names of BodyNodes and Joints get resolved
// correctly as BodyNodes get added to the Skeleton
EXPECT_FALSE(body1->getName() == body2->getName());
EXPECT_FALSE(body2->getName() == body3->getName());
EXPECT_FALSE(body3->getName() == body1->getName());
EXPECT_FALSE(joint1->getName() == joint2->getName());
EXPECT_FALSE(joint2->getName() == joint3->getName());
EXPECT_FALSE(joint3->getName() == joint1->getName());
EXPECT_TRUE(joint1->getDof(0)->getName() == "joint");
EXPECT_TRUE(joint2->getDof(0)->getName() == "joint(1)_x");
EXPECT_TRUE(joint2->getDof(1)->getName() == "joint(1)_y");
EXPECT_TRUE(joint2->getDof(2)->getName() == "joint(1)_z");
EXPECT_TRUE(joint3->getDof(0)->getName() == "joint(2)_rot_x");
EXPECT_TRUE(joint3->getDof(1)->getName() == "joint(2)_rot_y");
EXPECT_TRUE(joint3->getDof(2)->getName() == "joint(2)_rot_z");
EXPECT_TRUE(joint3->getDof(3)->getName() == "joint(2)_pos_x");
EXPECT_TRUE(joint3->getDof(4)->getName() == "joint(2)_pos_y");
EXPECT_TRUE(joint3->getDof(5)->getName() == "joint(2)_pos_z");
// Testing whether the repeated names of BodyNodes get resolved correctly
// as they are changed with BodyNode::setName(~)
std::string newname1 = body1->setName("same_name");
std::string newname2 = body2->setName("same_name");
std::string newname3 = body3->setName("same_name");
EXPECT_FALSE(body1->getName() == body2->getName());
EXPECT_FALSE(body2->getName() == body3->getName());
EXPECT_FALSE(body3->getName() == body1->getName());
EXPECT_TRUE(body1->getName() == newname1);
EXPECT_TRUE(body2->getName() == newname2);
EXPECT_TRUE(body3->getName() == newname3);
EXPECT_TRUE(skel->getBodyNode(newname1) == body1);
EXPECT_TRUE(skel->getBodyNode(newname2) == body2);
EXPECT_TRUE(skel->getBodyNode(newname3) == body3);
// Testing whether the repeated names of Joints get resolved correctly
// as they are changed with Joint::setName(~)
newname1 = joint1->setName("another_name");
newname2 = joint2->setName("another_name");
newname3 = joint3->setName("another_name");
EXPECT_FALSE(joint1->getName() == joint2->getName());
EXPECT_FALSE(joint2->getName() == joint3->getName());
EXPECT_FALSE(joint3->getName() == joint1->getName());
EXPECT_TRUE(joint1->getName() == newname1);
EXPECT_TRUE(joint2->getName() == newname2);
EXPECT_TRUE(joint3->getName() == newname3);
EXPECT_TRUE(skel->getJoint(newname1) == joint1);
EXPECT_TRUE(skel->getJoint(newname2) == joint2);
EXPECT_TRUE(skel->getJoint(newname3) == joint3);
// Testing whether unique names get accidentally changed by the NameManager
std::string unique_name = body2->setName("a_unique_name");
EXPECT_TRUE(body2->getName() == "a_unique_name");
EXPECT_TRUE(skel->getBodyNode("a_unique_name") == body2);
EXPECT_FALSE(body1->getName() == body2->getName());
EXPECT_FALSE(body2->getName() == body3->getName());
EXPECT_FALSE(body3->getName() == body1->getName());
unique_name = joint3->setName("a_unique_name");
EXPECT_TRUE(joint3->getName() == "a_unique_name");
EXPECT_TRUE(skel->getJoint("a_unique_name") == joint3);
// Testing whether the DegreeOfFreedom names get updated correctly upon their
// joint's name change
EXPECT_TRUE(joint3->getDof(0)->getName() == "a_unique_name_rot_x");
EXPECT_TRUE(joint3->getDof(1)->getName() == "a_unique_name_rot_y");
EXPECT_TRUE(joint3->getDof(2)->getName() == "a_unique_name_rot_z");
EXPECT_TRUE(joint3->getDof(3)->getName() == "a_unique_name_pos_x");
EXPECT_TRUE(joint3->getDof(4)->getName() == "a_unique_name_pos_y");
EXPECT_TRUE(joint3->getDof(5)->getName() == "a_unique_name_pos_z");
EXPECT_TRUE(joint3->getDof(0) == skel->getDof("a_unique_name_rot_x"));
EXPECT_TRUE(joint3->getDof(3) == skel->getDof("a_unique_name_pos_x"));
// Note: The following assumes the joint order in the Skeleton is:
// RevoluteJoint -> TranslationalJoint -> FreeJoint
EXPECT_TRUE(joint1->getDof(0) == skel->getDof(0));
EXPECT_TRUE(joint2->getDof(0) == skel->getDof(1));
EXPECT_TRUE(joint2->getDof(1) == skel->getDof(2));
EXPECT_TRUE(joint2->getDof(2) == skel->getDof(3));
EXPECT_TRUE(joint3->getDof(0) == skel->getDof(4));
EXPECT_TRUE(joint3->getDof(1) == skel->getDof(5));
EXPECT_TRUE(joint3->getDof(2) == skel->getDof(6));
EXPECT_TRUE(joint3->getDof(3) == skel->getDof(7));
EXPECT_TRUE(joint3->getDof(4) == skel->getDof(8));
EXPECT_TRUE(joint3->getDof(5) == skel->getDof(9));
// Test whether the return of getIndexInSkeleton() and the index of the
// corresponding DegreeOfFreedom in the Skeleton are same
for (size_t i = 0; i < skel->getNumDofs(); ++i)
EXPECT_TRUE(skel->getDof(i)->getIndexInSkeleton() == i);
// Test whether all the joint names are still unique
EXPECT_FALSE(joint1->getName() == joint2->getName());
EXPECT_FALSE(joint2->getName() == joint3->getName());
EXPECT_FALSE(joint3->getName() == joint1->getName());
// Make sure that the Skeleton gives back NULL for non existent names
EXPECT_TRUE(skel->getBodyNode("nonexistent_name") == NULL);
EXPECT_TRUE(skel->getJoint("nonexistent_name") == NULL);
EXPECT_TRUE(skel->getSoftBodyNode("nonexistent_name") == NULL);
Joint* oldJoint = body3->getParentJoint();
std::string oldJointName = oldJoint->getName();
Joint* newJoint = new RevoluteJoint(Eigen::Vector3d(1,0,0), "a_new_joint");
body3->setParentJoint(newJoint);
EXPECT_TRUE(skel->getJoint("a_new_joint") == newJoint);
// Make sure that the Skeleton returns NULL on any Joint names that have been
// taken away from it
EXPECT_FALSE(skel->getJoint(oldJointName) == oldJoint);
EXPECT_TRUE(skel->getJoint(oldJointName) == NULL);
}
//==============================================================================
TEST(NameManagement, SetPattern)
{
dart::common::NameManager<BodyNode> test_mgr;
BodyNode* bn0 = new BodyNode("name");
BodyNode* bn1 = new BodyNode("name");
BodyNode* bn2 = new BodyNode("name");
test_mgr.setPattern("%s(%d)");
test_mgr.issueNewNameAndAdd(bn0->getName(), bn0);
test_mgr.issueNewNameAndAdd(bn1->getName(), bn1);
test_mgr.issueNewNameAndAdd(bn2->getName(), bn2);
EXPECT_TRUE( test_mgr.getObject("name") == bn0);
EXPECT_TRUE( test_mgr.getObject("name(1)") == bn1);
EXPECT_TRUE( test_mgr.getObject("name(2)") == bn2);
test_mgr.clear();
bn0->setName("bodynode");
bn1->setName("bodynode");
bn2->setName("bodynode");
test_mgr.setPattern("(%d)-%s");
test_mgr.issueNewNameAndAdd(bn0->getName(), bn0);
test_mgr.issueNewNameAndAdd(bn1->getName(), bn1);
test_mgr.issueNewNameAndAdd(bn2->getName(), bn2);
EXPECT_TRUE( test_mgr.getObject("bodynode") == bn0);
EXPECT_TRUE( test_mgr.getObject("(1)-bodynode") == bn1 );
EXPECT_TRUE( test_mgr.getObject("(2)-bodynode") == bn2 );
delete bn0;
delete bn1;
delete bn2;
}
//==============================================================================
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>added copyright to unit test<commit_after>/*
* Copyright (c) 2014, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Michael X. Grey <mxgrey@gatech.edu>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* 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.
* 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 HOLDER 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 <iostream>
#include <gtest/gtest.h>
#include "TestHelpers.h"
#include "dart/dynamics/SoftBodyNode.h"
using namespace dart;
using namespace math;
using namespace dynamics;
//==============================================================================
TEST(NameManagement, Basic)
{
//--------------------------------------------------------------------------
//
//--------------------------------------------------------------------------
// Bodies
BodyNode* body1 = new BodyNode;
BodyNode* body2 = new BodyNode;
BodyNode* body3 = new BodyNode;
// TODO: Add some SoftBodyNodes into this test.
// Grey is not familiar with construction of SoftBodyNodes,
// so he is leaving that for someone else for the time being.
// Joints
Joint* joint1 = new RevoluteJoint(Eigen::Vector3d::UnitX(), "joint");
Joint* joint2 = new TranslationalJoint("joint");
Joint* joint3 = new FreeJoint("joint");
// Testing whether DegreesOfFreedom get named correctly
EXPECT_TRUE(joint1->getDof(0)->getName() == "joint");
EXPECT_TRUE(joint2->getDof(0)->getName() == "joint_x");
EXPECT_TRUE(joint2->getDof(1)->getName() == "joint_y");
EXPECT_TRUE(joint2->getDof(2)->getName() == "joint_z");
EXPECT_TRUE(joint3->getDof(0)->getName() == "joint_rot_x");
EXPECT_TRUE(joint3->getDof(1)->getName() == "joint_rot_y");
EXPECT_TRUE(joint3->getDof(2)->getName() == "joint_rot_z");
EXPECT_TRUE(joint3->getDof(3)->getName() == "joint_pos_x");
EXPECT_TRUE(joint3->getDof(4)->getName() == "joint_pos_y");
EXPECT_TRUE(joint3->getDof(5)->getName() == "joint_pos_z");
// Skeleton
Skeleton* skel = new Skeleton;
body1->setParentJoint(joint1);
body2->setParentJoint(joint2);
body3->setParentJoint(joint3);
body1->addChildBodyNode(body2);
body2->addChildBodyNode(body3);
skel->addBodyNode(body1);
skel->addBodyNode(body2);
skel->addBodyNode(body3);
skel->init();
// Testing whether the repeated names of BodyNodes and Joints get resolved
// correctly as BodyNodes get added to the Skeleton
EXPECT_FALSE(body1->getName() == body2->getName());
EXPECT_FALSE(body2->getName() == body3->getName());
EXPECT_FALSE(body3->getName() == body1->getName());
EXPECT_FALSE(joint1->getName() == joint2->getName());
EXPECT_FALSE(joint2->getName() == joint3->getName());
EXPECT_FALSE(joint3->getName() == joint1->getName());
EXPECT_TRUE(joint1->getDof(0)->getName() == "joint");
EXPECT_TRUE(joint2->getDof(0)->getName() == "joint(1)_x");
EXPECT_TRUE(joint2->getDof(1)->getName() == "joint(1)_y");
EXPECT_TRUE(joint2->getDof(2)->getName() == "joint(1)_z");
EXPECT_TRUE(joint3->getDof(0)->getName() == "joint(2)_rot_x");
EXPECT_TRUE(joint3->getDof(1)->getName() == "joint(2)_rot_y");
EXPECT_TRUE(joint3->getDof(2)->getName() == "joint(2)_rot_z");
EXPECT_TRUE(joint3->getDof(3)->getName() == "joint(2)_pos_x");
EXPECT_TRUE(joint3->getDof(4)->getName() == "joint(2)_pos_y");
EXPECT_TRUE(joint3->getDof(5)->getName() == "joint(2)_pos_z");
// Testing whether the repeated names of BodyNodes get resolved correctly
// as they are changed with BodyNode::setName(~)
std::string newname1 = body1->setName("same_name");
std::string newname2 = body2->setName("same_name");
std::string newname3 = body3->setName("same_name");
EXPECT_FALSE(body1->getName() == body2->getName());
EXPECT_FALSE(body2->getName() == body3->getName());
EXPECT_FALSE(body3->getName() == body1->getName());
EXPECT_TRUE(body1->getName() == newname1);
EXPECT_TRUE(body2->getName() == newname2);
EXPECT_TRUE(body3->getName() == newname3);
EXPECT_TRUE(skel->getBodyNode(newname1) == body1);
EXPECT_TRUE(skel->getBodyNode(newname2) == body2);
EXPECT_TRUE(skel->getBodyNode(newname3) == body3);
// Testing whether the repeated names of Joints get resolved correctly
// as they are changed with Joint::setName(~)
newname1 = joint1->setName("another_name");
newname2 = joint2->setName("another_name");
newname3 = joint3->setName("another_name");
EXPECT_FALSE(joint1->getName() == joint2->getName());
EXPECT_FALSE(joint2->getName() == joint3->getName());
EXPECT_FALSE(joint3->getName() == joint1->getName());
EXPECT_TRUE(joint1->getName() == newname1);
EXPECT_TRUE(joint2->getName() == newname2);
EXPECT_TRUE(joint3->getName() == newname3);
EXPECT_TRUE(skel->getJoint(newname1) == joint1);
EXPECT_TRUE(skel->getJoint(newname2) == joint2);
EXPECT_TRUE(skel->getJoint(newname3) == joint3);
// Testing whether unique names get accidentally changed by the NameManager
std::string unique_name = body2->setName("a_unique_name");
EXPECT_TRUE(body2->getName() == "a_unique_name");
EXPECT_TRUE(skel->getBodyNode("a_unique_name") == body2);
EXPECT_FALSE(body1->getName() == body2->getName());
EXPECT_FALSE(body2->getName() == body3->getName());
EXPECT_FALSE(body3->getName() == body1->getName());
unique_name = joint3->setName("a_unique_name");
EXPECT_TRUE(joint3->getName() == "a_unique_name");
EXPECT_TRUE(skel->getJoint("a_unique_name") == joint3);
// Testing whether the DegreeOfFreedom names get updated correctly upon their
// joint's name change
EXPECT_TRUE(joint3->getDof(0)->getName() == "a_unique_name_rot_x");
EXPECT_TRUE(joint3->getDof(1)->getName() == "a_unique_name_rot_y");
EXPECT_TRUE(joint3->getDof(2)->getName() == "a_unique_name_rot_z");
EXPECT_TRUE(joint3->getDof(3)->getName() == "a_unique_name_pos_x");
EXPECT_TRUE(joint3->getDof(4)->getName() == "a_unique_name_pos_y");
EXPECT_TRUE(joint3->getDof(5)->getName() == "a_unique_name_pos_z");
EXPECT_TRUE(joint3->getDof(0) == skel->getDof("a_unique_name_rot_x"));
EXPECT_TRUE(joint3->getDof(3) == skel->getDof("a_unique_name_pos_x"));
// Note: The following assumes the joint order in the Skeleton is:
// RevoluteJoint -> TranslationalJoint -> FreeJoint
EXPECT_TRUE(joint1->getDof(0) == skel->getDof(0));
EXPECT_TRUE(joint2->getDof(0) == skel->getDof(1));
EXPECT_TRUE(joint2->getDof(1) == skel->getDof(2));
EXPECT_TRUE(joint2->getDof(2) == skel->getDof(3));
EXPECT_TRUE(joint3->getDof(0) == skel->getDof(4));
EXPECT_TRUE(joint3->getDof(1) == skel->getDof(5));
EXPECT_TRUE(joint3->getDof(2) == skel->getDof(6));
EXPECT_TRUE(joint3->getDof(3) == skel->getDof(7));
EXPECT_TRUE(joint3->getDof(4) == skel->getDof(8));
EXPECT_TRUE(joint3->getDof(5) == skel->getDof(9));
// Test whether the return of getIndexInSkeleton() and the index of the
// corresponding DegreeOfFreedom in the Skeleton are same
for (size_t i = 0; i < skel->getNumDofs(); ++i)
EXPECT_TRUE(skel->getDof(i)->getIndexInSkeleton() == i);
// Test whether all the joint names are still unique
EXPECT_FALSE(joint1->getName() == joint2->getName());
EXPECT_FALSE(joint2->getName() == joint3->getName());
EXPECT_FALSE(joint3->getName() == joint1->getName());
// Make sure that the Skeleton gives back NULL for non existent names
EXPECT_TRUE(skel->getBodyNode("nonexistent_name") == NULL);
EXPECT_TRUE(skel->getJoint("nonexistent_name") == NULL);
EXPECT_TRUE(skel->getSoftBodyNode("nonexistent_name") == NULL);
Joint* oldJoint = body3->getParentJoint();
std::string oldJointName = oldJoint->getName();
Joint* newJoint = new RevoluteJoint(Eigen::Vector3d(1,0,0), "a_new_joint");
body3->setParentJoint(newJoint);
EXPECT_TRUE(skel->getJoint("a_new_joint") == newJoint);
// Make sure that the Skeleton returns NULL on any Joint names that have been
// taken away from it
EXPECT_FALSE(skel->getJoint(oldJointName) == oldJoint);
EXPECT_TRUE(skel->getJoint(oldJointName) == NULL);
}
//==============================================================================
TEST(NameManagement, SetPattern)
{
dart::common::NameManager<BodyNode> test_mgr;
BodyNode* bn0 = new BodyNode("name");
BodyNode* bn1 = new BodyNode("name");
BodyNode* bn2 = new BodyNode("name");
test_mgr.setPattern("%s(%d)");
test_mgr.issueNewNameAndAdd(bn0->getName(), bn0);
test_mgr.issueNewNameAndAdd(bn1->getName(), bn1);
test_mgr.issueNewNameAndAdd(bn2->getName(), bn2);
EXPECT_TRUE( test_mgr.getObject("name") == bn0);
EXPECT_TRUE( test_mgr.getObject("name(1)") == bn1);
EXPECT_TRUE( test_mgr.getObject("name(2)") == bn2);
test_mgr.clear();
bn0->setName("bodynode");
bn1->setName("bodynode");
bn2->setName("bodynode");
test_mgr.setPattern("(%d)-%s");
test_mgr.issueNewNameAndAdd(bn0->getName(), bn0);
test_mgr.issueNewNameAndAdd(bn1->getName(), bn1);
test_mgr.issueNewNameAndAdd(bn2->getName(), bn2);
EXPECT_TRUE( test_mgr.getObject("bodynode") == bn0);
EXPECT_TRUE( test_mgr.getObject("(1)-bodynode") == bn1 );
EXPECT_TRUE( test_mgr.getObject("(2)-bodynode") == bn2 );
delete bn0;
delete bn1;
delete bn2;
}
//==============================================================================
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.