text
stringlengths
54
60.6k
<commit_before>#include <stdlib.h> #include <windows.h> #include "refalrts-platform-specific.h" bool refalrts::api::get_main_module_name( char (&module_name)[refalrts::api::cModuleNameBufferLen] ) { DWORD length = GetModuleFileName(NULL, module_name, cModuleNameBufferLen); return (length != 0) && ( length < cModuleNameBufferLen || ( // На ОС > Windows XP функция при недостаточном размере буфера // возвращает этот код ошибки. GetLastError() != ERROR_INSUFFICIENT_BUFFER // Windows XP не устанавливает кода ошибки, но при этом заполняет // буфер без добавления концевого нуля && module_name[cModuleNameBufferLen - 1] == '\0' ) ); } int refalrts::api::system(const char *command) { return ::system(command); } bool refalrts::api::get_current_directory(char buffer[], size_t size) { DWORD result = GetCurrentDirectory(size, buffer); return (0 != result && result < size); } refalrts::RefalNumber refalrts::api::get_pid() { return static_cast<refalrts::RefalNumber>(GetCurrentProcessId()); } refalrts::RefalNumber refalrts::api::get_ppid() { return static_cast<refalrts::RefalNumber>(GetCurrentProcessId()); } <commit_msg>Предупреждение компилятора Microsoft Visual C++<commit_after>#include <stdlib.h> #include <windows.h> #include "refalrts-platform-specific.h" bool refalrts::api::get_main_module_name( char (&module_name)[refalrts::api::cModuleNameBufferLen] ) { DWORD length = GetModuleFileName(NULL, module_name, cModuleNameBufferLen); return (length != 0) && ( length < cModuleNameBufferLen || ( // На ОС > Windows XP функция при недостаточном размере буфера // возвращает этот код ошибки. GetLastError() != ERROR_INSUFFICIENT_BUFFER // Windows XP не устанавливает кода ошибки, но при этом заполняет // буфер без добавления концевого нуля && module_name[cModuleNameBufferLen - 1] == '\0' ) ); } int refalrts::api::system(const char *command) { return ::system(command); } bool refalrts::api::get_current_directory(char buffer[], size_t size) { DWORD result = GetCurrentDirectory(static_cast<DWORD>(size), buffer); return (0 != result && result < size); } refalrts::RefalNumber refalrts::api::get_pid() { return static_cast<refalrts::RefalNumber>(GetCurrentProcessId()); } refalrts::RefalNumber refalrts::api::get_ppid() { return static_cast<refalrts::RefalNumber>(GetCurrentProcessId()); } <|endoftext|>
<commit_before>#include "TrayIcon.h" #include <QApplication> #include <QLibraryInfo> #include <QMessageBox> #include <QShowEvent> #include <QTranslator> #include <QtQml> #include "ViewModels/SettingsViewModel.h" #include "ViewModels/SourceViewModel.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); a.installTranslator(&qtTranslator); QTranslator myappTranslator; myappTranslator.load("translations/Tapeciarnia_" + QLocale::system().name()); a.installTranslator(&myappTranslator); if (!QSystemTrayIcon::isSystemTrayAvailable()) { QMessageBox::critical(0, QObject::tr("Tapeciarnia"), QObject::tr("I couldn't detect any system tray " "on this system.")); return 1; } QApplication::setQuitOnLastWindowClosed(false); TrayIcon trayIcon; trayIcon.show(); // register QML types qmlRegisterType<SourceViewModel>("SourceViewModel", 1, 0, "SourceViewModel"); qmlRegisterType<SettingsViewModel>("SettingsViewModel", 1, 0, "SettingsViewModel"); return a.exec(); } <commit_msg>Fixed bug with too late QML objects registration (config view could be empty if opened too fast).<commit_after>#include "TrayIcon.h" #include <QApplication> #include <QLibraryInfo> #include <QMessageBox> #include <QShowEvent> #include <QTranslator> #include <QtQml> #include "ViewModels/SettingsViewModel.h" #include "ViewModels/SourceViewModel.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); a.installTranslator(&qtTranslator); QTranslator myappTranslator; myappTranslator.load("translations/Tapeciarnia_" + QLocale::system().name()); a.installTranslator(&myappTranslator); if (!QSystemTrayIcon::isSystemTrayAvailable()) { QMessageBox::critical(0, QObject::tr("Tapeciarnia"), QObject::tr("I couldn't detect any system tray " "on this system.")); return 1; } QApplication::setQuitOnLastWindowClosed(false); // register QML types qmlRegisterType<SourceViewModel>("SourceViewModel", 1, 0, "SourceViewModel"); qmlRegisterType<SettingsViewModel>("SettingsViewModel", 1, 0, "SettingsViewModel"); TrayIcon trayIcon; trayIcon.show(); return a.exec(); } <|endoftext|>
<commit_before>#include "platform_gl.h" ELEMENTARY_GLVIEW_GLOBAL_DEFINE() namespace Tangram { GLenum GL::getError() { return __evas_gl_glapi->glGetError(); } const GLubyte* GL::getString(GLenum name) { return __evas_gl_glapi->glGetString(name); } void GL::clear(GLbitfield mask) { __evas_gl_glapi->glClear(mask); } void GL::lineWidth(GLfloat width) { __evas_gl_glapi->glLineWidth(width); } void GL::viewport(GLint x, GLint y, GLsizei width, GLsizei height) { __evas_gl_glapi->glViewport(x, y, width, height); } void GL::enable(GLenum id) { __evas_gl_glapi->glEnable(id); } void GL::disable(GLenum id) { __evas_gl_glapi->glDisable(id); } void GL::depthFunc(GLenum func) { __evas_gl_glapi->glDepthFunc(func); } void GL::depthMask(GLboolean flag) { __evas_gl_glapi->glDepthMask(flag); } void GL::depthRange(GLfloat n, GLfloat f) { __evas_gl_glapi->glDepthRangef(n, f); } void GL::clearDepth(GLfloat d) { __evas_gl_glapi->glClearDepthf(d); } void GL::blendFunc(GLenum sfactor, GLenum dfactor) { __evas_gl_glapi->glBlendFunc(sfactor, dfactor); } void GL::stencilFunc(GLenum func, GLint ref, GLuint mask) { __evas_gl_glapi->glStencilFunc(func, ref, mask); } void GL::stencilMask(GLuint mask) { __evas_gl_glapi->glStencilMask(mask); } void GL::stencilOp(GLenum fail, GLenum zfail, GLenum zpass) { __evas_gl_glapi->glStencilOp(fail, zfail, zpass); } void GL::clearStencil(GLint s) { __evas_gl_glapi->glClearStencil(s); } void GL::colorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) { __evas_gl_glapi->glColorMask(red, green, blue, alpha); } void GL::cullFace(GLenum mode) { __evas_gl_glapi->glCullFace(mode); } void GL::frontFace(GLenum mode) { __evas_gl_glapi->glFrontFace(mode); } void GL::clearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) { __evas_gl_glapi->glClearColor(red, green, blue, alpha); } void GL::getIntegerv(GLenum pname, GLint *params ) { __evas_gl_glapi->glGetIntegerv(pname, params ); } // Program void GL::useProgram(GLuint program) { __evas_gl_glapi->glUseProgram(program); } void GL::deleteProgram(GLuint program) { __evas_gl_glapi->glDeleteProgram(program); } void GL::deleteShader(GLuint shader) { __evas_gl_glapi->glDeleteShader(shader); } GLuint GL::createShader(GLenum type) { return __evas_gl_glapi->glCreateShader(type); } GLuint GL::createProgram() { return __evas_gl_glapi->glCreateProgram(); } void GL::compileShader(GLuint shader) { __evas_gl_glapi->glCompileShader(shader); } void GL::attachShader(GLuint program, GLuint shader) { __evas_gl_glapi->glAttachShader(program,shader); } void GL::linkProgram(GLuint program) { __evas_gl_glapi->glLinkProgram(program); } void GL::shaderSource(GLuint shader, GLsizei count, const GLchar **string, const GLint *length) { auto source = const_cast<const GLchar**>(string); __evas_gl_glapi->glShaderSource(shader, count, source, length); } void GL::getShaderInfoLog(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog) { __evas_gl_glapi->glGetShaderInfoLog(shader, bufSize, length, infoLog); } void GL::getProgramInfoLog(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog) { __evas_gl_glapi->glGetProgramInfoLog(program, bufSize, length, infoLog); } GLint GL::getUniformLocation(GLuint program, const GLchar *name) { return __evas_gl_glapi->glGetUniformLocation(program, name); } GLint GL::getAttribLocation(GLuint program, const GLchar *name) { return __evas_gl_glapi->glGetAttribLocation(program, name); } void GL::getProgramiv(GLuint program, GLenum pname, GLint *params) { __evas_gl_glapi->glGetProgramiv(program,pname,params); } void GL::getShaderiv(GLuint shader, GLenum pname, GLint *params) { __evas_gl_glapi->glGetShaderiv(shader,pname, params); } // Buffers void GL::bindBuffer(GLenum target, GLuint buffer) { __evas_gl_glapi->glBindBuffer(target, buffer); } void GL::deleteBuffers(GLsizei n, const GLuint *buffers) { __evas_gl_glapi->glDeleteBuffers(n, buffers); } void GL::genBuffers(GLsizei n, GLuint *buffers) { __evas_gl_glapi->glGenBuffers(n, buffers); } void GL::bufferData(GLenum target, GLsizeiptr size, const void *data, GLenum usage) { __evas_gl_glapi->glBufferData(target, size, data, usage); } void GL::bufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void *data) { __evas_gl_glapi->glBufferSubData(target, offset, size, data); } void GL::readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels) { __evas_gl_glapi->glReadPixels(x, y, width, height, format, type, pixels); } // Texture void GL::bindTexture(GLenum target, GLuint texture ) { __evas_gl_glapi->glBindTexture(target, texture ); } void GL::activeTexture(GLenum texture) { __evas_gl_glapi->glActiveTexture(texture); } void GL::genTextures(GLsizei n, GLuint *textures ) { __evas_gl_glapi->glGenTextures(n, textures ); } void GL::deleteTextures(GLsizei n, const GLuint *textures) { __evas_gl_glapi->glDeleteTextures(n, textures); } void GL::texParameteri(GLenum target, GLenum pname, GLint param ) { __evas_gl_glapi->glTexParameteri(target, pname, param ); } void GL::texImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels) { __evas_gl_glapi->glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels); } void GL::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels) { __evas_gl_glapi->glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } void GL::generateMipmap(GLenum target) { __evas_gl_glapi->glGenerateMipmap(target); } void GL::enableVertexAttribArray(GLuint index) { __evas_gl_glapi->glEnableVertexAttribArray(index); } void GL::disableVertexAttribArray(GLuint index) { __evas_gl_glapi->glDisableVertexAttribArray(index); } void GL::vertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer) { __evas_gl_glapi->glVertexAttribPointer(index, size, type, normalized, stride, pointer); } void GL::drawArrays(GLenum mode, GLint first, GLsizei count ) { __evas_gl_glapi->glDrawArrays(mode, first, count ); } void GL::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices ) { __evas_gl_glapi->glDrawElements(mode, count, type, indices ); } void GL::uniform1f(GLint location, GLfloat v0) { __evas_gl_glapi->glUniform1f(location, v0); } void GL::uniform2f(GLint location, GLfloat v0, GLfloat v1) { __evas_gl_glapi->glUniform2f(location, v0, v1); } void GL::uniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) { __evas_gl_glapi->glUniform3f(location, v0, v1, v2); } void GL::uniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { __evas_gl_glapi->glUniform4f(location, v0, v1, v2, v3); } void GL::uniform1i(GLint location, GLint v0) { __evas_gl_glapi->glUniform1i(location, v0); } void GL::uniform2i(GLint location, GLint v0, GLint v1) { __evas_gl_glapi->glUniform2i(location, v0, v1); } void GL::uniform3i(GLint location, GLint v0, GLint v1, GLint v2) { __evas_gl_glapi->glUniform3i(location, v0, v1, v2); } void GL::uniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) { __evas_gl_glapi->glUniform4i(location, v0, v1, v2, v3); } void GL::uniform1fv(GLint location, GLsizei count, const GLfloat *value) { __evas_gl_glapi->glUniform1fv(location, count, value); } void GL::uniform2fv(GLint location, GLsizei count, const GLfloat *value) { __evas_gl_glapi->glUniform2fv(location, count, value); } void GL::uniform3fv(GLint location, GLsizei count, const GLfloat *value) { __evas_gl_glapi->glUniform3fv(location, count, value); } void GL::uniform4fv(GLint location, GLsizei count, const GLfloat *value) { __evas_gl_glapi->glUniform4fv(location, count, value); } void GL::uniform1iv(GLint location, GLsizei count, const GLint *value) { __evas_gl_glapi->glUniform1iv(location, count, value); } void GL::uniform2iv(GLint location, GLsizei count, const GLint *value) { __evas_gl_glapi->glUniform2iv(location, count, value); } void GL::uniform3iv(GLint location, GLsizei count, const GLint *value) { __evas_gl_glapi->glUniform3iv(location, count, value); } void GL::uniform4iv(GLint location, GLsizei count, const GLint *value) { __evas_gl_glapi->glUniform4iv(location, count, value); } void GL::uniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { __evas_gl_glapi->glUniformMatrix2fv(location, count, transpose, value); } void GL::uniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { __evas_gl_glapi->glUniformMatrix3fv(location, count, transpose, value); } void GL::uniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { __evas_gl_glapi->glUniformMatrix4fv(location, count, transpose, value); } // mapbuffer void* GL::mapBuffer(GLenum target, GLenum access) { return __evas_gl_glapi->glMapBufferOES(target, access); } GLboolean GL::unmapBuffer(GLenum target) { return __evas_gl_glapi->glUnmapBufferOES(target); } void GL::finish(void) { __evas_gl_glapi->glFinish(); } // VAO void GL::bindVertexArray(GLuint array) { __evas_gl_glapi->glBindVertexArrayOES(array); } void GL::deleteVertexArrays(GLsizei n, const GLuint *arrays) { __evas_gl_glapi->glDeleteVertexArraysOES(n, arrays); } void GL::genVertexArrays(GLsizei n, GLuint *arrays) { __evas_gl_glapi->glGenVertexArraysOES(n, arrays); } } <commit_msg>tizen: update platform_gl<commit_after>#include "platform_gl.h" ELEMENTARY_GLVIEW_GLOBAL_DEFINE() namespace Tangram { GLenum GL::getError() { return __evas_gl_glapi->glGetError(); } const GLubyte* GL::getString(GLenum name) { return __evas_gl_glapi->glGetString(name); } void GL::clear(GLbitfield mask) { __evas_gl_glapi->glClear(mask); } void GL::lineWidth(GLfloat width) { __evas_gl_glapi->glLineWidth(width); } void GL::viewport(GLint x, GLint y, GLsizei width, GLsizei height) { __evas_gl_glapi->glViewport(x, y, width, height); } void GL::enable(GLenum id) { __evas_gl_glapi->glEnable(id); } void GL::disable(GLenum id) { __evas_gl_glapi->glDisable(id); } void GL::depthFunc(GLenum func) { __evas_gl_glapi->glDepthFunc(func); } void GL::depthMask(GLboolean flag) { __evas_gl_glapi->glDepthMask(flag); } void GL::depthRange(GLfloat n, GLfloat f) { __evas_gl_glapi->glDepthRangef(n, f); } void GL::clearDepth(GLfloat d) { __evas_gl_glapi->glClearDepthf(d); } void GL::blendFunc(GLenum sfactor, GLenum dfactor) { __evas_gl_glapi->glBlendFunc(sfactor, dfactor); } void GL::stencilFunc(GLenum func, GLint ref, GLuint mask) { __evas_gl_glapi->glStencilFunc(func, ref, mask); } void GL::stencilMask(GLuint mask) { __evas_gl_glapi->glStencilMask(mask); } void GL::stencilOp(GLenum fail, GLenum zfail, GLenum zpass) { __evas_gl_glapi->glStencilOp(fail, zfail, zpass); } void GL::clearStencil(GLint s) { __evas_gl_glapi->glClearStencil(s); } void GL::colorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) { __evas_gl_glapi->glColorMask(red, green, blue, alpha); } void GL::cullFace(GLenum mode) { __evas_gl_glapi->glCullFace(mode); } void GL::frontFace(GLenum mode) { __evas_gl_glapi->glFrontFace(mode); } void GL::clearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) { __evas_gl_glapi->glClearColor(red, green, blue, alpha); } void GL::getIntegerv(GLenum pname, GLint *params ) { __evas_gl_glapi->glGetIntegerv(pname, params ); } // Program void GL::useProgram(GLuint program) { __evas_gl_glapi->glUseProgram(program); } void GL::deleteProgram(GLuint program) { __evas_gl_glapi->glDeleteProgram(program); } void GL::deleteShader(GLuint shader) { __evas_gl_glapi->glDeleteShader(shader); } GLuint GL::createShader(GLenum type) { return __evas_gl_glapi->glCreateShader(type); } GLuint GL::createProgram() { return __evas_gl_glapi->glCreateProgram(); } void GL::compileShader(GLuint shader) { __evas_gl_glapi->glCompileShader(shader); } void GL::attachShader(GLuint program, GLuint shader) { __evas_gl_glapi->glAttachShader(program,shader); } void GL::linkProgram(GLuint program) { __evas_gl_glapi->glLinkProgram(program); } void GL::shaderSource(GLuint shader, GLsizei count, const GLchar **string, const GLint *length) { auto source = const_cast<const GLchar**>(string); __evas_gl_glapi->glShaderSource(shader, count, source, length); } void GL::getShaderInfoLog(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog) { __evas_gl_glapi->glGetShaderInfoLog(shader, bufSize, length, infoLog); } void GL::getProgramInfoLog(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog) { __evas_gl_glapi->glGetProgramInfoLog(program, bufSize, length, infoLog); } GLint GL::getUniformLocation(GLuint program, const GLchar *name) { return __evas_gl_glapi->glGetUniformLocation(program, name); } GLint GL::getAttribLocation(GLuint program, const GLchar *name) { return __evas_gl_glapi->glGetAttribLocation(program, name); } void GL::getProgramiv(GLuint program, GLenum pname, GLint *params) { __evas_gl_glapi->glGetProgramiv(program,pname,params); } void GL::getShaderiv(GLuint shader, GLenum pname, GLint *params) { __evas_gl_glapi->glGetShaderiv(shader,pname, params); } // Buffers void GL::bindBuffer(GLenum target, GLuint buffer) { __evas_gl_glapi->glBindBuffer(target, buffer); } void GL::deleteBuffers(GLsizei n, const GLuint *buffers) { __evas_gl_glapi->glDeleteBuffers(n, buffers); } void GL::genBuffers(GLsizei n, GLuint *buffers) { __evas_gl_glapi->glGenBuffers(n, buffers); } void GL::bufferData(GLenum target, GLsizeiptr size, const void *data, GLenum usage) { __evas_gl_glapi->glBufferData(target, size, data, usage); } void GL::bufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void *data) { __evas_gl_glapi->glBufferSubData(target, offset, size, data); } void GL::readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels) { __evas_gl_glapi->glReadPixels(x, y, width, height, format, type, pixels); } // Texture void GL::bindTexture(GLenum target, GLuint texture ) { __evas_gl_glapi->glBindTexture(target, texture ); } void GL::activeTexture(GLenum texture) { __evas_gl_glapi->glActiveTexture(texture); } void GL::genTextures(GLsizei n, GLuint *textures ) { __evas_gl_glapi->glGenTextures(n, textures ); } void GL::deleteTextures(GLsizei n, const GLuint *textures) { __evas_gl_glapi->glDeleteTextures(n, textures); } void GL::texParameteri(GLenum target, GLenum pname, GLint param ) { __evas_gl_glapi->glTexParameteri(target, pname, param ); } void GL::texImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels) { __evas_gl_glapi->glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels); } void GL::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels) { __evas_gl_glapi->glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } void GL::generateMipmap(GLenum target) { __evas_gl_glapi->glGenerateMipmap(target); } void GL::enableVertexAttribArray(GLuint index) { __evas_gl_glapi->glEnableVertexAttribArray(index); } void GL::disableVertexAttribArray(GLuint index) { __evas_gl_glapi->glDisableVertexAttribArray(index); } void GL::vertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer) { __evas_gl_glapi->glVertexAttribPointer(index, size, type, normalized, stride, pointer); } void GL::drawArrays(GLenum mode, GLint first, GLsizei count ) { __evas_gl_glapi->glDrawArrays(mode, first, count ); } void GL::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices ) { __evas_gl_glapi->glDrawElements(mode, count, type, indices ); } void GL::uniform1f(GLint location, GLfloat v0) { __evas_gl_glapi->glUniform1f(location, v0); } void GL::uniform2f(GLint location, GLfloat v0, GLfloat v1) { __evas_gl_glapi->glUniform2f(location, v0, v1); } void GL::uniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) { __evas_gl_glapi->glUniform3f(location, v0, v1, v2); } void GL::uniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { __evas_gl_glapi->glUniform4f(location, v0, v1, v2, v3); } void GL::uniform1i(GLint location, GLint v0) { __evas_gl_glapi->glUniform1i(location, v0); } void GL::uniform2i(GLint location, GLint v0, GLint v1) { __evas_gl_glapi->glUniform2i(location, v0, v1); } void GL::uniform3i(GLint location, GLint v0, GLint v1, GLint v2) { __evas_gl_glapi->glUniform3i(location, v0, v1, v2); } void GL::uniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) { __evas_gl_glapi->glUniform4i(location, v0, v1, v2, v3); } void GL::uniform1fv(GLint location, GLsizei count, const GLfloat *value) { __evas_gl_glapi->glUniform1fv(location, count, value); } void GL::uniform2fv(GLint location, GLsizei count, const GLfloat *value) { __evas_gl_glapi->glUniform2fv(location, count, value); } void GL::uniform3fv(GLint location, GLsizei count, const GLfloat *value) { __evas_gl_glapi->glUniform3fv(location, count, value); } void GL::uniform4fv(GLint location, GLsizei count, const GLfloat *value) { __evas_gl_glapi->glUniform4fv(location, count, value); } void GL::uniform1iv(GLint location, GLsizei count, const GLint *value) { __evas_gl_glapi->glUniform1iv(location, count, value); } void GL::uniform2iv(GLint location, GLsizei count, const GLint *value) { __evas_gl_glapi->glUniform2iv(location, count, value); } void GL::uniform3iv(GLint location, GLsizei count, const GLint *value) { __evas_gl_glapi->glUniform3iv(location, count, value); } void GL::uniform4iv(GLint location, GLsizei count, const GLint *value) { __evas_gl_glapi->glUniform4iv(location, count, value); } void GL::uniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { __evas_gl_glapi->glUniformMatrix2fv(location, count, transpose, value); } void GL::uniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { __evas_gl_glapi->glUniformMatrix3fv(location, count, transpose, value); } void GL::uniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) { __evas_gl_glapi->glUniformMatrix4fv(location, count, transpose, value); } // mapbuffer void* GL::mapBuffer(GLenum target, GLenum access) { return __evas_gl_glapi->glMapBufferOES(target, access); } GLboolean GL::unmapBuffer(GLenum target) { return __evas_gl_glapi->glUnmapBufferOES(target); } void GL::finish(void) { __evas_gl_glapi->glFinish(); } // VAO void GL::bindVertexArray(GLuint array) { __evas_gl_glapi->glBindVertexArrayOES(array); } void GL::deleteVertexArrays(GLsizei n, const GLuint *arrays) { __evas_gl_glapi->glDeleteVertexArraysOES(n, arrays); } void GL::genVertexArrays(GLsizei n, GLuint *arrays) { __evas_gl_glapi->glGenVertexArraysOES(n, arrays); } // Framebuffer void GL::bindFramebuffer(GLenum target, GLuint framebuffer) { __evas_gl_glapi->glBindFramebuffer(target, framebuffer); } void GL::genFramebuffers(GLsizei n, GLuint *framebuffers) { __evas_gl_glapi->glGenFramebuffers(n, framebuffers); } void GL::framebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) { __evas_gl_glapi->glFramebufferTexture2D(target, attachment, textarget, texture, level); } void GL::renderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height) { __evas_gl_glapi->glRenderbufferStorage(target, internalformat, width, height); } void GL::framebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) { __evas_gl_glapi->glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); } void GL::genRenderbuffers(GLsizei n, GLuint *renderbuffers) { __evas_gl_glapi->glGenRenderbuffers(n, renderbuffers); } void GL::bindRenderbuffer(GLenum target, GLuint renderbuffer) { __evas_gl_glapi->glBindRenderbuffer(target, renderbuffer); } void GL::deleteFramebuffers(GLsizei n, const GLuint *framebuffers) { __evas_gl_glapi->glDeleteFramebuffers(n, framebuffers); } void GL::deleteRenderbuffers(GLsizei n, const GLuint *renderbuffers) { __evas_gl_glapi->glDeleteRenderbuffers(n, renderbuffers); } GLenum GL::checkFramebufferStatus(GLenum target) { return __evas_gl_glapi->glCheckFramebufferStatus(target); } } <|endoftext|>
<commit_before>/* Generated from orogen/lib/orogen/templates/typekit/corba/Convertions.hpp */ #ifndef __OROGEN_GENERATED_<%= typekit.name.upcase %>_CORBA_CONVERTIONS_HPP #define __OROGEN_GENERATED_<%= typekit.name.upcase %>_CORBA_CONVERTIONS_HPP #include "../../Types.hpp" #include "<%= typekit.name %>/transports/corba/<%= typekit.name %>TypesC.h" #include <boost/cstdint.hpp> #include <string> namespace orogen_typekits { /** Converted types: */ <% typesets.converted_types.each do |type| target_type = typekit.intermediate_type_for(type) %> bool toCORBA( <%= target_type.corba_ref_type %> corba, <%= type.arg_type %> value ); bool fromCORBA( <%= type.ref_type %> value, <%= target_type.corba_arg_type %> corba ); <% end %> /** Array types: */ <% typesets.array_types.each do |type| target_type = typekit.intermediate_type_for(type) %> bool toCORBA( <%= target_type.corba_ref_type %> corba, <%= type.arg_type %> value, int length ); bool fromCORBA( <%= type.ref_type %> value, int length, <%= target_type.corba_arg_type %> corba ); <% end %> } #endif <commit_msg>templates: dont' use relative paths in public headers<commit_after>/* Generated from orogen/lib/orogen/templates/typekit/corba/Convertions.hpp */ #ifndef __OROGEN_GENERATED_<%= typekit.name.upcase %>_CORBA_CONVERTIONS_HPP #define __OROGEN_GENERATED_<%= typekit.name.upcase %>_CORBA_CONVERTIONS_HPP #include "<%= typekit.name %>/Types.hpp" #include "<%= typekit.name %>/transports/corba/<%= typekit.name %>TypesC.h" #include <boost/cstdint.hpp> #include <string> namespace orogen_typekits { /** Converted types: */ <% typesets.converted_types.each do |type| target_type = typekit.intermediate_type_for(type) %> bool toCORBA( <%= target_type.corba_ref_type %> corba, <%= type.arg_type %> value ); bool fromCORBA( <%= type.ref_type %> value, <%= target_type.corba_arg_type %> corba ); <% end %> /** Array types: */ <% typesets.array_types.each do |type| target_type = typekit.intermediate_type_for(type) %> bool toCORBA( <%= target_type.corba_ref_type %> corba, <%= type.arg_type %> value, int length ); bool fromCORBA( <%= type.ref_type %> value, int length, <%= target_type.corba_arg_type %> corba ); <% end %> } #endif <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH #define DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH #include <type_traits> #include <memory> #include <dune/common/exceptions.hh> #include <dune/localfunctions/raviartthomas.hh> #include <dune/fem/space/common/allgeomtypes.hh> #include <dune/fem_localfunctions/localfunctions/transformations.hh> #include <dune/fem_localfunctions/basefunctions/genericbasefunctionsetstorage.hh> #include <dune/fem_localfunctions/basefunctionsetmap/basefunctionsetmap.hh> #include <dune/fem_localfunctions/space/genericdiscretefunctionspace.hh> #include <dune/stuff/common/color.hh> #include "../../mapper/fem.hh" #include "../../basefunctionset/fem-localfunctions.hh" #include "../constraints.hh" #include "../interface.hh" namespace Dune { namespace GDT { namespace RaviartThomasSpace { // forward, to be used in the traits and to allow for specialization template <class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class FemLocalfunctionsWrapper; // forward, to allow for specialization template <class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class FemLocalfunctionsWrapperTraits; template <class GridPartImp, int polynomialOrder, class RangeFieldImp> class FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 2> { static_assert(GridPartImp::dimension == 2, "Only implemented for dimDomain 2!"); static_assert(polynomialOrder >= 0, "Wrong polOrder given!"); public: typedef GridPartImp GridPartType; static const int polOrder = polynomialOrder; private: typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; public: typedef RangeFieldImp RangeFieldType; static const unsigned int dimRange = 2; static const unsigned int dimRangeCols = 1; typedef FemLocalfunctionsWrapper<GridPartType, polOrder, RangeFieldType, dimRange, dimRangeCols> derived_type; private: typedef Dune::RaviartThomasSimplexLocalFiniteElement<dimDomain, DomainFieldType, RangeFieldType> FiniteElementType; typedef Dune::FemLocalFunctions::BaseFunctionSetMap<GridPartType, FiniteElementType, Dune::FemLocalFunctions::PiolaTransformation, Dune::FemLocalFunctions::SimpleStorage, polOrder, polOrder, true> BaseFunctionSetMapType; public: typedef Dune::FemLocalFunctions::DiscreteFunctionSpace<BaseFunctionSetMapType> BackendType; typedef Mapper::FemDofWrapper<typename BackendType::MapperType> MapperType; typedef BaseFunctionSet::FemLocalfunctionsWrapper<BaseFunctionSetMapType, DomainFieldType, dimDomain, RangeFieldType, dimRange, dimRangeCols> BaseFunctionSetType; typedef typename BaseFunctionSetType::EntityType EntityType; private: template <class G, int p, class R, int r, int rC> friend class FemLocalfunctionsWrapper; }; // class FemLocalfunctionsWrapperTraits< ..., 2, 1 > template <class GridPartImp, int polynomialOrder, class RangeFieldImp> class FemLocalfunctionsWrapper<GridPartImp, polynomialOrder, RangeFieldImp, 2> : public SpaceInterface<FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 2>> { typedef FemLocalfunctionsWrapper<GridPartImp, polynomialOrder, RangeFieldImp, 2> ThisType; typedef SpaceInterface<FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 2>> BaseType; public: typedef FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 2> Traits; typedef typename Traits::GridPartType GridPartType; typedef typename GridPartType::ctype DomainFieldType; static const int polOrder = Traits::polOrder; static const unsigned int dimDomain = GridPartType::dimension; typedef typename Traits::RangeFieldType RangeFieldType; static const unsigned int dimRange = Traits::dimRange; static const unsigned int dimRangeCols = Traits::dimRangeCols; typedef typename Traits::BackendType BackendType; typedef typename Traits::MapperType MapperType; typedef typename Traits::BaseFunctionSetType BaseFunctionSetType; typedef typename Traits::EntityType EntityType; typedef Dune::Stuff::LA::SparsityPatternDefault PatternType; private: typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType; public: FemLocalfunctionsWrapper(const std::shared_ptr<const GridPartType>& gridP) : gridPart_(assertGridPart(gridP)) , baseFunctionSetMap_(new BaseFunctionSetMapType(*gridPart_)) , backend_(new BackendType(const_cast<GridPartType&>(*gridPart_), *baseFunctionSetMap_)) , mapper_(new MapperType(backend_->mapper())) { } FemLocalfunctionsWrapper(const ThisType& other) : gridPart_(other.gridPart_) , baseFunctionSetMap_(other.baseFunctionSetMap_) , backend_(other.backend_) , mapper_(other.mapper_) { } ThisType& operator=(const ThisType& other) { if (this != &other) { gridPart_ = other.gridPart_; baseFunctionSetMap_ = other.baseFunctionSetMap_; backend_ = other.backend_; mapper_ = other.mapper_; } return *this; } std::shared_ptr<const GridPartType> gridPart() const { return gridPart_; } const BackendType& backend() const { return *backend_; } bool continuous() const { return false; } const MapperType& mapper() const { return *mapper_; } BaseFunctionSetType baseFunctionSet(const EntityType& entity) const { return BaseFunctionSetType(*baseFunctionSetMap_, entity); } template <class R> void localConstraints(const EntityType& /*entity*/, Constraints::LocalDefault<R>& /*ret*/) const { static_assert(Dune::AlwaysFalse<R>::value, "ERROR: not implemented for arbitrary constraints!"); } using BaseType::computePattern; template <class LocalGridPartType, class OtherSpaceType> PatternType* computePattern(const LocalGridPartType& /*localGridPart*/, const OtherSpaceType& /*otherSpace*/) const { static_assert(Dune::AlwaysFalse<LocalGridPartType>::value, "Not implemented!"); return nullptr; } private: static std::shared_ptr<const GridPartType> assertGridPart(const std::shared_ptr<const GridPartType> gP) { // check typedef typename Dune::Fem::AllGeomTypes<typename GridPartType::IndexSetType, typename GridPartType::GridType> AllGeometryTypes; const AllGeometryTypes allGeometryTypes(gP->indexSet()); const std::vector<Dune::GeometryType>& geometryTypes = allGeometryTypes.geomTypes(0); if (!(geometryTypes.size() == 1 && geometryTypes[0].isSimplex())) DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " this space is only implemented for simplicial grids!"); return gP; } // ... assertGridPart(...) std::shared_ptr<const GridPartType> gridPart_; std::shared_ptr<BaseFunctionSetMapType> baseFunctionSetMap_; std::shared_ptr<const BackendType> backend_; std::shared_ptr<const MapperType> mapper_; }; // class FemLocalfunctionsWrapper< ..., 1, 1 > } // namespace RaviartThomasSpace } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH <commit_msg>[playground.space.raviartthomas...] update * add static checks * update to fulfill interface<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH #define DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH #include <type_traits> #include <memory> #include <dune/common/exceptions.hh> #include <dune/grid/common/capabilities.hh> #if HAVE_DUNE_FEM_LOCALFUNCTIONS #include <dune/localfunctions/raviartthomas.hh> #include <dune/fem_localfunctions/localfunctions/transformations.hh> #include <dune/fem_localfunctions/basefunctions/genericbasefunctionsetstorage.hh> #include <dune/fem_localfunctions/basefunctionsetmap/basefunctionsetmap.hh> #include <dune/fem_localfunctions/space/genericdiscretefunctionspace.hh> #endif // HAVE_DUNE_FEM_LOCALFUNCTIONS #include <dune/stuff/common/color.hh> #include "../../../mapper/fem.hh" #include "../../../basefunctionset/fem-localfunctions.hh" #include "../../../space/constraints.hh" #include "../../../space/interface.hh" namespace Dune { namespace GDT { namespace RaviartThomasSpace { #if HAVE_DUNE_FEM_LOCALFUNCTIONS // forward, to be used in the traits and to allow for specialization template <class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class FemLocalfunctionsWrapper { static_assert(Dune::AlwaysFalse<GridPartImp>::value, "Untested for these dimensions!"); }; // forward, to allow for specialization template <class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols> class FemLocalfunctionsWrapperTraits { static_assert(Dune::AlwaysFalse<GridPartImp>::value, "Untested for these dimensions!"); }; template <class GridPartImp, int polynomialOrder, class RangeFieldImp> class FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 2, 1> { static_assert(GridPartImp::dimension == 2, "Only implemented for dimDomain 2!"); static_assert(polynomialOrder == 0, "Wrong polOrder given!"); public: typedef GridPartImp GridPartType; typedef typename GridPartType::GridViewType GridViewType; static const int polOrder = polynomialOrder; private: typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; public: typedef RangeFieldImp RangeFieldType; static const unsigned int dimRange = 2; static const unsigned int dimRangeCols = 1; typedef FemLocalfunctionsWrapper<GridPartType, polOrder, RangeFieldType, dimRange, dimRangeCols> derived_type; private: typedef typename GridPartType::GridType GridType; static_assert(Capabilities::hasSingleGeometryType<GridType>::v, "This space is only implemented for fully simplicial grids!"); static_assert(Capabilities::hasSingleGeometryType<GridType>::topologyId == GenericGeometry::SimplexTopology<dimDomain>::type::id, "This space is only implemented for fully simplicial grids!"); typedef Dune::RaviartThomasSimplexLocalFiniteElement<dimDomain, DomainFieldType, RangeFieldType> FiniteElementType; typedef Dune::FemLocalFunctions::BaseFunctionSetMap<GridPartType, FiniteElementType, Dune::FemLocalFunctions::PiolaTransformation, Dune::FemLocalFunctions::SimpleStorage, polOrder, polOrder, true> BaseFunctionSetMapType; public: typedef Dune::FemLocalFunctions::DiscreteFunctionSpace<BaseFunctionSetMapType> BackendType; typedef Mapper::FemDofWrapper<typename BackendType::MapperType> MapperType; typedef BaseFunctionSet::FemLocalfunctionsWrapper<BaseFunctionSetMapType, DomainFieldType, dimDomain, RangeFieldType, dimRange, dimRangeCols> BaseFunctionSetType; typedef typename BaseFunctionSetType::EntityType EntityType; static const bool needs_grid_view = false; private: template <class G, int p, class R, int r, int rC> friend class FemLocalfunctionsWrapper; }; // class FemLocalfunctionsWrapperTraits< ..., 2, 1 > template <class GridPartImp, int polynomialOrder, class RangeFieldImp> class FemLocalfunctionsWrapper<GridPartImp, polynomialOrder, RangeFieldImp, 2, 1> : public SpaceInterface<FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 2, 1>> { typedef FemLocalfunctionsWrapper<GridPartImp, polynomialOrder, RangeFieldImp, 2, 1> ThisType; typedef SpaceInterface<FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 2, 1>> BaseType; public: typedef FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 2, 1> Traits; typedef typename Traits::GridPartType GridPartType; typedef typename Traits::GridViewType GridViewType; typedef typename GridPartType::ctype DomainFieldType; static const int polOrder = Traits::polOrder; static const unsigned int dimDomain = GridPartType::dimension; typedef typename Traits::RangeFieldType RangeFieldType; static const unsigned int dimRange = Traits::dimRange; static const unsigned int dimRangeCols = Traits::dimRangeCols; typedef typename Traits::BackendType BackendType; typedef typename Traits::MapperType MapperType; typedef typename Traits::BaseFunctionSetType BaseFunctionSetType; typedef typename Traits::EntityType EntityType; typedef Dune::Stuff::LA::SparsityPatternDefault PatternType; private: typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType; public: FemLocalfunctionsWrapper(const std::shared_ptr<const GridPartType>& gridP) : gridPart_(gridP) , grid_view_(new GridViewType(gridPart_->gridView())) , baseFunctionSetMap_(new BaseFunctionSetMapType(*gridPart_)) , backend_(new BackendType(const_cast<GridPartType&>(*gridPart_), *baseFunctionSetMap_)) , mapper_(new MapperType(backend_->mapper())) { } FemLocalfunctionsWrapper(const ThisType& other) : gridPart_(other.gridPart_) , grid_view_(other.grid_view_) , baseFunctionSetMap_(other.baseFunctionSetMap_) , backend_(other.backend_) , mapper_(other.mapper_) { } ThisType& operator=(const ThisType& other) { if (this != &other) { gridPart_ = other.gridPart_; grid_view_ = other.grid_view_; baseFunctionSetMap_ = other.baseFunctionSetMap_; backend_ = other.backend_; mapper_ = other.mapper_; } return *this; } const std::shared_ptr<const GridPartType>& grid_part() const { return gridPart_; } const std::shared_ptr<const GridViewType>& grid_view() const { return grid_view_; } const BackendType& backend() const { return *backend_; } bool continuous() const { return false; } const MapperType& mapper() const { return *mapper_; } BaseFunctionSetType base_function_set(const EntityType& entity) const { return BaseFunctionSetType(*baseFunctionSetMap_, entity); } template <class R> void local_constraints(const EntityType& /*entity*/, Constraints::LocalDefault<R>& /*ret*/) const { static_assert(Dune::AlwaysFalse<R>::value, "Not implemented for arbitrary constraints!"); } using BaseType::compute_pattern; template <class LocalGridViewType, class O> PatternType compute_pattern(const LocalGridViewType& local_grid_view, const SpaceInterface<O>& other) const { return BaseType::compute_face_and_volume_pattern(local_grid_view, other); } private: std::shared_ptr<const GridPartType> gridPart_; std::shared_ptr<const GridViewType> grid_view_; std::shared_ptr<BaseFunctionSetMapType> baseFunctionSetMap_; std::shared_ptr<const BackendType> backend_; std::shared_ptr<const MapperType> mapper_; }; // class FemLocalfunctionsWrapper< ..., 2, 1 > #else // HAVE_DUNE_FEM_LOCALFUNCTIONS template <class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class FemLocalfunctionsWrapper { static_assert(Dune::AlwaysFalse<GridPartImp>::value, "You are missing dune-fem-localfunctions!"); }; #endif // HAVE_DUNE_FEM_LOCALFUNCTIONS } // namespace RaviartThomasSpace } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACE_RAVIARTTHOMAS_FEM_LOCALFUNCTIONS_HH <|endoftext|>
<commit_before>/// /// @file pi_deleglise_rivat_parallel2.cpp /// @brief Parallel implementation of the Lagarias-Miller-Odlyzko prime /// counting algorithm with the improvements of Deleglise and /// Rivat. In this implementation the easy leaves have been /// split up into clustered easy leaves and sparse easy leaves. /// This implementation is based on the paper: /// Tomás Oliveira e Silva, Computing pi(x): the combinatorial /// method, Revista do DETUA, vol. 4, no. 6, March 2006, /// pp. 759-768. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <primesieve.hpp> #include <aligned_vector.hpp> #include <balance_S2_load.hpp> #include <bit_sieve.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <tos_counters.hpp> #include <utils.hpp> #include <stdint.h> #include <algorithm> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { /// For each prime calculate its first multiple >= low. template <typename T1, typename T2> void init_next_multiples(T1& next, T2& primes, int64_t size, int64_t low) { next.reserve(size); next.push_back(0); for (int64_t b = 1; b < size; b++) { int64_t prime = primes[b]; int64_t next_multiple = ((low + prime - 1) / prime) * prime; next_multiple += prime * (~next_multiple & 1); next.push_back(next_multiple); } } template <typename T1, typename T2> void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters) { int64_t segment_size = sieve.size(); int64_t k = next_multiple; for (; k < high; k += prime * 2) { if (sieve[k - low]) { sieve.unset(k - low); cnt_update(counters, k - low, segment_size); } } next_multiple = k; } /// Compute the S2 contribution for the interval /// [low_process, low_process + segments * segment_size[. /// The missing special leaf contributions for the interval /// [1, low_process[ are later reconstructed and added in /// the calling (parent) S2 function. /// int64_t S2_thread(int64_t x, int64_t y, int64_t z, int64_t c, int64_t pi_sqrty, int64_t pi_y, int64_t segment_size, int64_t segments_per_thread, int64_t thread_num, int64_t low, int64_t limit, vector<int32_t>& pi, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu, vector<int64_t>& mu_sum, vector<int64_t>& phi) { low += segment_size * segments_per_thread * thread_num; limit = min(low + segment_size * segments_per_thread, limit); int64_t size = pi[min(isqrt(x / low), y)] + 1; int64_t S2_thread = 0; if (c >= size - 1) return 0; bit_sieve sieve(segment_size); vector<int32_t> counters(segment_size); vector<int64_t> next; init_next_multiples(next, primes, size, low); phi.resize(size, 0); mu_sum.resize(size, 0); // Process the segments corresponding to the current thread for (; low < limit; low += segment_size) { // Current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = 2; sieve.memset(low); // phi(y, b) nodes with b <= c do not contribute to S2, so we // simply sieve out the multiples of the first c primes for (; b <= c; b++) { int64_t k = next[b]; for (int64_t prime = primes[b]; k < high; k += prime * 2) sieve.unset(k - low); next[b] = k; } // Initialize special tree data structure from sieve cnt_finit(sieve, counters, segment_size); // For c + 1 <= b < pi_sqrty // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m] // which satisfy: low <= (x / n) < high for (; b < min(pi_sqrty, size); b++) { int64_t prime = primes[b]; int64_t min_m = max(x / (prime * high), y / prime); int64_t max_m = min(x / (prime * low), y); if (prime >= max_m) goto next_segment; for (int64_t m = max_m; m > min_m; m--) { if (mu[m] != 0 && prime < lpf[m]) { int64_t n = prime * m; int64_t count = cnt_query(counters, (x / n) - low); int64_t phi_xn = phi[b] + count; S2_thread -= mu[m] * phi_xn; mu_sum[b] -= mu[m]; } } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } // For pi_sqrty <= b < pi_y // Find all special leaves: n = primes[b] * primes[l] // which satisfy: low <= (x / n) < high for (; b < pi_y; b++) { int64_t prime = primes[b]; int64_t l = pi[min(x / (prime * low), y)]; if (prime >= primes[l]) goto next_segment; int64_t min_m = max(x / (prime * high), y / prime); min_m = in_between(prime, min_m, y); int64_t min_trivial_leaf = pi[min(x / (prime * prime), y)]; int64_t min_clustered_easy_leaf = pi[min(isqrt(x / prime), y)]; int64_t min_sparse_easy_leaf = pi[min(z / prime, y)]; int64_t min_hard_leaf = pi[min_m]; min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf); min_clustered_easy_leaf = max(min_hard_leaf, min_clustered_easy_leaf); min_sparse_easy_leaf = max(min_hard_leaf, min_sparse_easy_leaf); // For max(x / primes[b]^2, primes[b]) < primes[l] <= y // Find all trivial leaves which satisfy: // phi(x / (primes[b] * primes[l]), b - 1) = 1 if (l > min_trivial_leaf) { S2_thread += l - min_trivial_leaf; l = min_trivial_leaf; } // For max(sqrt(x / primes[b]), primes[b]) < primes[l] <= x / primes[b]^2 // Find all clustered easy leaves which satisfy: // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2 // And phi(x / n, b - 1) == phi(x / m, b - 1) while (l > min_clustered_easy_leaf) { int64_t n = prime * primes[l]; int64_t phi_xn = pi[x / n] - b + 2; int64_t m = prime * primes[b + phi_xn - 1]; int64_t l2 = pi[x / m]; l2 = max(l2, min_clustered_easy_leaf); S2_thread += phi_xn * (l - l2); l = l2; } // For max(z / primes[b], primes[b]) < primes[l] <= sqrt(x / primes[b]) // Find all sparse easy leaves which satisfy: // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2 for (; l > min_sparse_easy_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; S2_thread += pi[xn] - b + 2; } // For max(x / (primes[b] * high), primes[b]) < primes[l] <= z / primes[b] // Find all hard leaves which satisfy: // low <= (x / n) < high for (; l > min_hard_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; int64_t count = cnt_query(counters, xn - low); int64_t phi_xn = phi[b] + count; S2_thread += phi_xn; mu_sum[b]++; } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } next_segment:; } return S2_thread; } /// Calculate the contribution of the special leaves. /// This is a parallel implementation with advanced load balancing. /// As most special leaves tend to be in the first segments we /// start off with a small segment size and few segments /// per thread, after each iteration we dynamically increase /// the segment size and the segments per thread. /// @pre y > 0 && c > 1 /// int64_t S2(int64_t x, int64_t y, int64_t z, int64_t pi_y, int64_t c, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu, int threads) { threads = validate_threads(threads); int64_t S2_total = 0; int64_t low = 1; int64_t limit = x / y + 1; int64_t sqrt_limit = isqrt(limit); int64_t logx = max(1, ilog(x)); int64_t min_segment_size = 1 << 6; int64_t segment_size = next_power_of_2(sqrt_limit / (logx * threads)); int64_t segments_per_thread = 1; int64_t pi_sqrty = pi_bsearch(primes, isqrt(y)); double relative_standard_deviation = 30; segment_size = max(segment_size, min_segment_size); vector<int32_t> pi = make_pi(y); vector<int64_t> phi_total(primes.size(), 0); while (low < limit) { int64_t segments = (limit - low + segment_size - 1) / segment_size; threads = in_between(1, threads, segments); segments_per_thread = in_between(1, segments_per_thread, (segments + threads - 1) / threads); aligned_vector<vector<int64_t> > phi(threads); aligned_vector<vector<int64_t> > mu_sum(threads); aligned_vector<double> timings(threads); #pragma omp parallel for num_threads(threads) reduction(+: S2_total) for (int i = 0; i < threads; i++) { timings[i] = get_wtime(); S2_total += S2_thread(x, y, z, c, pi_sqrty, pi_y, segment_size, segments_per_thread, i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i]); timings[i] = get_wtime() - timings[i]; } // Once all threads have finished reconstruct and add the // missing contribution of all special leaves. This must // be done in order as each thread (i) requires the sum of // the phi values from the previous threads. // for (int i = 0; i < threads; i++) { for (size_t j = 1; j < phi[i].size(); j++) { S2_total += phi_total[j] * mu_sum[i][j]; phi_total[j] += phi[i][j]; } } low += segments_per_thread * threads * segment_size; balance_S2_load(&segment_size, &segments_per_thread, min_segment_size, sqrt_limit, &relative_standard_deviation, timings); } return S2_total; } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log log x) space. /// int64_t pi_deleglise_rivat_parallel2(int64_t x, int threads) { if (x < 2) return 0; // alpha is a tuning factor double d = (double) x; double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x)); int64_t x13 = iroot<3>(x); int64_t y = (int64_t)(x13 * alpha); int64_t z = x / (int64_t) (x13 * sqrt(alpha)); vector<int32_t> mu = make_moebius(y); vector<int32_t> lpf = make_least_prime_factor(y); vector<int32_t> primes; primes.push_back(0); primesieve::generate_primes(y, &primes); int64_t pi_y = primes.size() - 1; int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y); int64_t s1 = S1(x, y, c, primes, lpf , mu); int64_t s2 = S2(x, y, z, pi_y, c, primes, lpf , mu, threads); int64_t p2 = P2(x, y, threads); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount <commit_msg>Refactoring<commit_after>/// /// @file pi_deleglise_rivat_parallel2.cpp /// @brief Parallel implementation of the Lagarias-Miller-Odlyzko prime /// counting algorithm with the improvements of Deleglise and /// Rivat. In this implementation the easy leaves have been /// split up into clustered easy leaves and sparse easy leaves. /// This implementation is based on the paper: /// Tomás Oliveira e Silva, Computing pi(x): the combinatorial /// method, Revista do DETUA, vol. 4, no. 6, March 2006, /// pp. 759-768. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <primesieve.hpp> #include <aligned_vector.hpp> #include <balance_S2_load.hpp> #include <bit_sieve.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <tos_counters.hpp> #include <utils.hpp> #include <stdint.h> #include <algorithm> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { /// For each prime calculate its first multiple >= low. template <typename T1, typename T2> void init_next_multiples(T1& next, T2& primes, int64_t size, int64_t low) { next.reserve(size); next.push_back(0); for (int64_t b = 1; b < size; b++) { int64_t prime = primes[b]; int64_t next_multiple = ((low + prime - 1) / prime) * prime; next_multiple += prime * (~next_multiple & 1); next.push_back(next_multiple); } } template <typename T1, typename T2> void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters) { int64_t segment_size = sieve.size(); int64_t k = next_multiple; for (; k < high; k += prime * 2) { if (sieve[k - low]) { sieve.unset(k - low); cnt_update(counters, k - low, segment_size); } } next_multiple = k; } /// Compute the S2 contribution for the interval /// [low_process, low_process + segments * segment_size[. /// The missing special leaf contributions for the interval /// [1, low_process[ are later reconstructed and added in /// the calling (parent) S2 function. /// int64_t S2_thread(int64_t x, int64_t y, int64_t z, int64_t c, int64_t pi_sqrty, int64_t pi_y, int64_t segment_size, int64_t segments_per_thread, int64_t thread_num, int64_t low, int64_t limit, vector<int32_t>& pi, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu, vector<int64_t>& mu_sum, vector<int64_t>& phi) { low += segment_size * segments_per_thread * thread_num; limit = min(low + segment_size * segments_per_thread, limit); int64_t size = pi[min(isqrt(x / low), y)] + 1; int64_t S2_thread = 0; if (c >= size - 1) return 0; bit_sieve sieve(segment_size); vector<int32_t> counters(segment_size); vector<int64_t> next; init_next_multiples(next, primes, size, low); phi.resize(size, 0); mu_sum.resize(size, 0); // Process the segments corresponding to the current thread for (; low < limit; low += segment_size) { // Current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = 2; sieve.memset(low); // phi(y, b) nodes with b <= c do not contribute to S2, so we // simply sieve out the multiples of the first c primes for (; b <= c; b++) { int64_t k = next[b]; for (int64_t prime = primes[b]; k < high; k += prime * 2) sieve.unset(k - low); next[b] = k; } // Initialize special tree data structure from sieve cnt_finit(sieve, counters, segment_size); // For c + 1 <= b < pi_sqrty // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m] // which satisfy: low <= (x / n) < high for (; b < min(pi_sqrty, size); b++) { int64_t prime = primes[b]; int64_t min_m = max(x / (prime * high), y / prime); int64_t max_m = min(x / (prime * low), y); if (prime >= max_m) goto next_segment; for (int64_t m = max_m; m > min_m; m--) { if (mu[m] != 0 && prime < lpf[m]) { int64_t n = prime * m; int64_t count = cnt_query(counters, (x / n) - low); int64_t phi_xn = phi[b] + count; S2_thread -= mu[m] * phi_xn; mu_sum[b] -= mu[m]; } } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } // For pi_sqrty <= b < pi_y // Find all special leaves: n = primes[b] * primes[l] // which satisfy: low <= (x / n) < high for (; b < pi_y; b++) { int64_t prime = primes[b]; int64_t l = pi[min(x / (prime * low), y)]; if (prime >= primes[l]) goto next_segment; int64_t min_m = max(x / (prime * high), y / prime); min_m = in_between(prime, min_m, y); int64_t min_trivial_leaf = pi[min(x / (prime * prime), y)]; int64_t min_clustered_easy_leaf = pi[min(isqrt(x / prime), y)]; int64_t min_sparse_easy_leaf = pi[min(z / prime, y)]; int64_t min_hard_leaf = pi[min_m]; min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf); min_clustered_easy_leaf = max(min_hard_leaf, min_clustered_easy_leaf); min_sparse_easy_leaf = max(min_hard_leaf, min_sparse_easy_leaf); // For max(x / primes[b]^2, primes[b]) < primes[l] <= y // Find all trivial leaves which satisfy: // phi(x / (primes[b] * primes[l]), b - 1) = 1 if (l > min_trivial_leaf) { S2_thread += l - min_trivial_leaf; l = min_trivial_leaf; } // For max(sqrt(x / primes[b]), primes[b]) < primes[l] <= x / primes[b]^2 // Find all clustered easy leaves which satisfy: // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2 // And phi(x / n, b - 1) == phi(x / m, b - 1) while (l > min_clustered_easy_leaf) { int64_t n = prime * primes[l]; int64_t phi_xn = pi[x / n] - b + 2; int64_t m = prime * primes[b + phi_xn - 1]; int64_t l2 = pi[x / m]; l2 = max(l2, min_clustered_easy_leaf); S2_thread += phi_xn * (l - l2); l = l2; } // For max(z / primes[b], primes[b]) < primes[l] <= sqrt(x / primes[b]) // Find all sparse easy leaves which satisfy: // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2 for (; l > min_sparse_easy_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; S2_thread += pi[xn] - b + 2; } // For max(x / (primes[b] * high), primes[b]) < primes[l] <= z / primes[b] // Find all hard leaves which satisfy: // low <= (x / n) < high for (; l > min_hard_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; int64_t count = cnt_query(counters, xn - low); int64_t phi_xn = phi[b] + count; S2_thread += phi_xn; mu_sum[b]++; } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } next_segment:; } return S2_thread; } /// Calculate the contribution of the special leaves. /// This is a parallel implementation with advanced load balancing. /// As most special leaves tend to be in the first segments we /// start off with a small segment size and few segments /// per thread, after each iteration we dynamically increase /// the segment size and the segments per thread. /// @pre y > 0 && c > 1 /// int64_t S2(int64_t x, int64_t y, int64_t z, int64_t pi_y, int64_t c, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu, int threads) { threads = validate_threads(threads); int64_t S2_total = 0; int64_t low = 1; int64_t limit = x / y + 1; int64_t sqrt_limit = isqrt(limit); int64_t logx = max(1, ilog(x)); int64_t min_segment_size = 1 << 6; int64_t segment_size = next_power_of_2(sqrt_limit / (logx * threads)); int64_t segments_per_thread = 1; int64_t pi_sqrty = pi_bsearch(primes, isqrt(y)); double relative_standard_deviation = 30; segment_size = max(segment_size, min_segment_size); vector<int32_t> pi = make_pi(y); vector<int64_t> phi_total(primes.size(), 0); while (low < limit) { int64_t segments = (limit - low + segment_size - 1) / segment_size; threads = in_between(1, threads, segments); segments_per_thread = in_between(1, segments_per_thread, (segments + threads - 1) / threads); aligned_vector<vector<int64_t> > phi(threads); aligned_vector<vector<int64_t> > mu_sum(threads); aligned_vector<double> timings(threads); #pragma omp parallel for num_threads(threads) reduction(+: S2_total) for (int i = 0; i < threads; i++) { timings[i] = get_wtime(); S2_total += S2_thread(x, y, z, c, pi_sqrty, pi_y, segment_size, segments_per_thread, i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i]); timings[i] = get_wtime() - timings[i]; } // Once all threads have finished reconstruct and add the // missing contribution of all special leaves. This must // be done in order as each thread (i) requires the sum of // the phi values from the previous threads. // for (int i = 0; i < threads; i++) { for (size_t j = 1; j < phi[i].size(); j++) { S2_total += phi_total[j] * mu_sum[i][j]; phi_total[j] += phi[i][j]; } } low += segments_per_thread * threads * segment_size; balance_S2_load(&segment_size, &segments_per_thread, min_segment_size, sqrt_limit, &relative_standard_deviation, timings); } return S2_total; } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log log x) space. /// int64_t pi_deleglise_rivat_parallel2(int64_t x, int threads) { if (x < 2) return 0; // alpha is a tuning factor double d = (double) x; double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x)); int64_t x13 = iroot<3>(x); int64_t y = (int64_t)(x13 * alpha); int64_t z = x / (int64_t) (x13 * sqrt(alpha)); vector<int32_t> mu = make_moebius(y); vector<int32_t> lpf = make_least_prime_factor(y); vector<int32_t> primes; primes.push_back(0); primesieve::generate_primes(y, &primes); int64_t pi_y = primes.size() - 1; int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y); int64_t s1 = S1(x, y, c, primes, lpf , mu); int64_t s2 = S2(x, y, z, pi_y, c, primes, lpf , mu, threads); int64_t p2 = P2(x, y, threads); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount <|endoftext|>
<commit_before>//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===// // // 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. // //===----------------------------------------------------------------------===// // // Collect the sequence of machine instructions for a basic block. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/BasicBlock.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/LeakDetector.h" #include <iostream> #include <algorithm> using namespace llvm; MachineBasicBlock::~MachineBasicBlock() { LeakDetector::removeGarbageObject(this); } // MBBs start out as #-1. When a MBB is added to a MachineFunction, it // gets the next available unique MBB number. If it is removed from a // MachineFunction, it goes back to being #-1. void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock* N) { assert(N->Parent == 0 && "machine instruction already in a basic block"); N->Parent = Parent; N->Number = Parent->addToMBBNumbering(N); LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock* N) { assert(N->Parent != 0 && "machine instruction not in a basic block"); N->Parent->removeFromMBBNumbering(N->Number); N->Number = -1; N->Parent = 0; LeakDetector::addGarbageObject(N); } MachineInstr* ilist_traits<MachineInstr>::createSentinel() { MachineInstr* dummy = new MachineInstr(0, 0); LeakDetector::removeGarbageObject(dummy); return dummy; } void ilist_traits<MachineInstr>::addNodeToList(MachineInstr* N) { assert(N->parent == 0 && "machine instruction already in a basic block"); N->parent = parent; LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr* N) { assert(N->parent != 0 && "machine instruction not in a basic block"); N->parent = 0; LeakDetector::addGarbageObject(N); } void ilist_traits<MachineInstr>::transferNodesFromList( iplist<MachineInstr, ilist_traits<MachineInstr> >& fromList, ilist_iterator<MachineInstr> first, ilist_iterator<MachineInstr> last) { if (parent != fromList.parent) for (; first != last; ++first) first->parent = parent; } MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() { const TargetInstrInfo& TII = *getParent()->getTarget().getInstrInfo(); iterator I = end(); while (I != begin() && TII.isTerminatorInstr((--I)->getOpcode())); if (I != end() && !TII.isTerminatorInstr(I->getOpcode())) ++I; return I; } void MachineBasicBlock::dump() const { print(std::cerr); } void MachineBasicBlock::print(std::ostream &OS) const { if(!getParent()) { OS << "Can't print out MachineBasicBlock because parent MachineFunction" << " is null\n"; return; } const BasicBlock *LBB = getBasicBlock(); OS << "\n"; if (LBB) OS << LBB->getName(); OS << " (" << (const void*)this << ", LLVM BB @" << (const void*) LBB << ", ID#" << getNumber()<< "):\n"; // Print the preds of this block according to the CFG. if (!pred_empty()) { OS << " Predecessors according to CFG:"; for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI) OS << " " << *PI; OS << "\n"; } for (const_iterator I = begin(); I != end(); ++I) { OS << "\t"; I->print(OS, &getParent()->getTarget()); } // Print the successors of this block according to the CFG. if (!succ_empty()) { OS << " Successors according to CFG:"; for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) OS << " " << *SI; OS << "\n"; } } void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) { Successors.push_back(succ); succ->addPredecessor(this); } void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) { succ->removePredecessor(this); succ_iterator I = std::find(Successors.begin(), Successors.end(), succ); assert(I != Successors.end() && "Not a current successor!"); Successors.erase(I); } void MachineBasicBlock::removeSuccessor(succ_iterator I) { assert(I != Successors.end() && "Not a current successor!"); (*I)->removePredecessor(this); Successors.erase(I); } void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) { Predecessors.push_back(pred); } void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) { std::vector<MachineBasicBlock *>::iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred); assert(I != Predecessors.end() && "Pred is not a predecessor of this block!"); Predecessors.erase(I); } <commit_msg>add moveBefore/moveAfter helper methods<commit_after>//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===// // // 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. // //===----------------------------------------------------------------------===// // // Collect the sequence of machine instructions for a basic block. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/BasicBlock.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/LeakDetector.h" #include <iostream> #include <algorithm> using namespace llvm; MachineBasicBlock::~MachineBasicBlock() { LeakDetector::removeGarbageObject(this); } // MBBs start out as #-1. When a MBB is added to a MachineFunction, it // gets the next available unique MBB number. If it is removed from a // MachineFunction, it goes back to being #-1. void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock* N) { assert(N->Parent == 0 && "machine instruction already in a basic block"); N->Parent = Parent; N->Number = Parent->addToMBBNumbering(N); LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock* N) { assert(N->Parent != 0 && "machine instruction not in a basic block"); N->Parent->removeFromMBBNumbering(N->Number); N->Number = -1; N->Parent = 0; LeakDetector::addGarbageObject(N); } MachineInstr* ilist_traits<MachineInstr>::createSentinel() { MachineInstr* dummy = new MachineInstr(0, 0); LeakDetector::removeGarbageObject(dummy); return dummy; } void ilist_traits<MachineInstr>::addNodeToList(MachineInstr* N) { assert(N->parent == 0 && "machine instruction already in a basic block"); N->parent = parent; LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr* N) { assert(N->parent != 0 && "machine instruction not in a basic block"); N->parent = 0; LeakDetector::addGarbageObject(N); } void ilist_traits<MachineInstr>::transferNodesFromList( iplist<MachineInstr, ilist_traits<MachineInstr> >& fromList, ilist_iterator<MachineInstr> first, ilist_iterator<MachineInstr> last) { if (parent != fromList.parent) for (; first != last; ++first) first->parent = parent; } MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() { const TargetInstrInfo& TII = *getParent()->getTarget().getInstrInfo(); iterator I = end(); while (I != begin() && TII.isTerminatorInstr((--I)->getOpcode())); if (I != end() && !TII.isTerminatorInstr(I->getOpcode())) ++I; return I; } void MachineBasicBlock::dump() const { print(std::cerr); } void MachineBasicBlock::print(std::ostream &OS) const { if(!getParent()) { OS << "Can't print out MachineBasicBlock because parent MachineFunction" << " is null\n"; return; } const BasicBlock *LBB = getBasicBlock(); OS << "\n"; if (LBB) OS << LBB->getName(); OS << " (" << (const void*)this << ", LLVM BB @" << (const void*) LBB << ", ID#" << getNumber()<< "):\n"; // Print the preds of this block according to the CFG. if (!pred_empty()) { OS << " Predecessors according to CFG:"; for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI) OS << " " << *PI; OS << "\n"; } for (const_iterator I = begin(); I != end(); ++I) { OS << "\t"; I->print(OS, &getParent()->getTarget()); } // Print the successors of this block according to the CFG. if (!succ_empty()) { OS << " Successors according to CFG:"; for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) OS << " " << *SI; OS << "\n"; } } void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) { MachineFunction::BasicBlockListType &BBList =getParent()->getBasicBlockList(); getParent()->getBasicBlockList().splice(NewAfter, BBList, this); } void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) { MachineFunction::BasicBlockListType &BBList =getParent()->getBasicBlockList(); MachineFunction::iterator BBI = NewBefore; getParent()->getBasicBlockList().splice(++BBI, BBList, this); } void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) { Successors.push_back(succ); succ->addPredecessor(this); } void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) { succ->removePredecessor(this); succ_iterator I = std::find(Successors.begin(), Successors.end(), succ); assert(I != Successors.end() && "Not a current successor!"); Successors.erase(I); } void MachineBasicBlock::removeSuccessor(succ_iterator I) { assert(I != Successors.end() && "Not a current successor!"); (*I)->removePredecessor(this); Successors.erase(I); } void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) { Predecessors.push_back(pred); } void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) { std::vector<MachineBasicBlock *>::iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred); assert(I != Predecessors.end() && "Pred is not a predecessor of this block!"); Predecessors.erase(I); } <|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. */ #include "phosphor/sentinel.h" namespace phosphor { Sentinel::Sentinel() : state(State::open) { } bool Sentinel::acquire() { auto expected = State::open; while (!state.compare_exchange_weak(expected, State::busy)) { if (expected == State::closed) { return false; } expected = State::open; } return true; } void Sentinel::release() { state.store(State::open, std::memory_order_release); } void Sentinel::close() { auto expected = State::open; while (!state.compare_exchange_weak(expected, State::closed)) { expected = State::open; } } bool Sentinel::reopen() { auto expected = State::closed; return state.compare_exchange_strong(expected, State::busy); } }<commit_msg>Assert Sentinel::release() invariant in debug builds<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. */ #include <cassert> #include "phosphor/sentinel.h" namespace phosphor { Sentinel::Sentinel() : state(State::open) { } bool Sentinel::acquire() { auto expected = State::open; while (!state.compare_exchange_weak(expected, State::busy)) { if (expected == State::closed) { return false; } expected = State::open; } return true; } void Sentinel::release() { #ifdef NDEBUG state.store(State::open, std::memory_order_release); #else auto expected = State::busy; // Sentinel::release() should only be called while State::busy assert(state.compare_exchange_strong(expected, State::open)); (void) expected; #endif } void Sentinel::close() { auto expected = State::open; while (!state.compare_exchange_weak(expected, State::closed)) { expected = State::open; } } bool Sentinel::reopen() { auto expected = State::closed; return state.compare_exchange_strong(expected, State::busy); } }<|endoftext|>
<commit_before><commit_msg>Added a comment.<commit_after><|endoftext|>
<commit_before>/* * ChaCha20Poly1305 AEAD * (C) 2014,2016,2018 Jack Lloyd * (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/chacha20poly1305.h> #include <botan/loadstor.h> namespace Botan { ChaCha20Poly1305_Mode::ChaCha20Poly1305_Mode() : m_chacha(StreamCipher::create("ChaCha")), m_poly1305(MessageAuthenticationCode::create("Poly1305")) { if(!m_chacha || !m_poly1305) throw Algorithm_Not_Found("ChaCha20Poly1305"); } bool ChaCha20Poly1305_Mode::valid_nonce_length(size_t n) const { return (n == 8 || n == 12 || n == 24); } void ChaCha20Poly1305_Mode::clear() { m_chacha->clear(); m_poly1305->clear(); reset(); } void ChaCha20Poly1305_Mode::reset() { m_ad.clear(); m_ctext_len = 0; m_nonce_len = 0; } void ChaCha20Poly1305_Mode::key_schedule(const uint8_t key[], size_t length) { m_chacha->set_key(key, length); } void ChaCha20Poly1305_Mode::set_associated_data(const uint8_t ad[], size_t length) { if(m_ctext_len > 0 || m_nonce_len > 0) throw Invalid_State("Cannot set AD for ChaCha20Poly1305 while processing a message"); m_ad.assign(ad, ad + length); } void ChaCha20Poly1305_Mode::update_len(size_t len) { uint8_t len8[8] = { 0 }; store_le(static_cast<uint64_t>(len), len8); m_poly1305->update(len8, 8); } void ChaCha20Poly1305_Mode::start_msg(const uint8_t nonce[], size_t nonce_len) { if(!valid_nonce_length(nonce_len)) throw Invalid_IV_Length(name(), nonce_len); m_ctext_len = 0; m_nonce_len = nonce_len; m_chacha->set_iv(nonce, nonce_len); secure_vector<uint8_t> first_block(64); m_chacha->write_keystream(first_block.data(), first_block.size()); m_poly1305->set_key(first_block.data(), 32); // Remainder of first block is discarded m_poly1305->update(m_ad); if(cfrg_version()) { if(m_ad.size() % 16) { const uint8_t zeros[16] = { 0 }; m_poly1305->update(zeros, 16 - m_ad.size() % 16); } } else { update_len(m_ad.size()); } } size_t ChaCha20Poly1305_Encryption::process(uint8_t buf[], size_t sz) { m_chacha->cipher1(buf, sz); m_poly1305->update(buf, sz); // poly1305 of ciphertext m_ctext_len += sz; return sz; } void ChaCha20Poly1305_Encryption::finish(secure_vector<uint8_t>& buffer, size_t offset) { update(buffer, offset); if(cfrg_version()) { if(m_ctext_len % 16) { const uint8_t zeros[16] = { 0 }; m_poly1305->update(zeros, 16 - m_ctext_len % 16); } update_len(m_ad.size()); } update_len(m_ctext_len); const secure_vector<uint8_t> mac = m_poly1305->final(); buffer += std::make_pair(mac.data(), tag_size()); m_ctext_len = 0; m_nonce_len = 0; } size_t ChaCha20Poly1305_Decryption::process(uint8_t buf[], size_t sz) { m_poly1305->update(buf, sz); // poly1305 of ciphertext m_chacha->cipher1(buf, sz); m_ctext_len += sz; return sz; } void ChaCha20Poly1305_Decryption::finish(secure_vector<uint8_t>& buffer, size_t offset) { BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane"); const size_t sz = buffer.size() - offset; uint8_t* buf = buffer.data() + offset; BOTAN_ASSERT(sz >= tag_size(), "Have the tag as part of final input"); const size_t remaining = sz - tag_size(); if(remaining) { m_poly1305->update(buf, remaining); // poly1305 of ciphertext m_chacha->cipher1(buf, remaining); m_ctext_len += remaining; } if(cfrg_version()) { if(m_ctext_len % 16) { const uint8_t zeros[16] = { 0 }; m_poly1305->update(zeros, 16 - m_ctext_len % 16); } update_len(m_ad.size()); } update_len(m_ctext_len); const secure_vector<uint8_t> mac = m_poly1305->final(); const uint8_t* included_tag = &buf[remaining]; m_ctext_len = 0; m_nonce_len = 0; if(!constant_time_compare(mac.data(), included_tag, tag_size())) throw Invalid_Authentication_Tag("ChaCha20Poly1305 tag check failed"); buffer.resize(offset + remaining); } } <commit_msg>Avoid memory allocations during ChaCha20Poly1305 start and finish<commit_after>/* * ChaCha20Poly1305 AEAD * (C) 2014,2016,2018 Jack Lloyd * (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/chacha20poly1305.h> #include <botan/loadstor.h> namespace Botan { ChaCha20Poly1305_Mode::ChaCha20Poly1305_Mode() : m_chacha(StreamCipher::create("ChaCha")), m_poly1305(MessageAuthenticationCode::create("Poly1305")) { if(!m_chacha || !m_poly1305) throw Algorithm_Not_Found("ChaCha20Poly1305"); } bool ChaCha20Poly1305_Mode::valid_nonce_length(size_t n) const { return (n == 8 || n == 12 || n == 24); } void ChaCha20Poly1305_Mode::clear() { m_chacha->clear(); m_poly1305->clear(); reset(); } void ChaCha20Poly1305_Mode::reset() { m_ad.clear(); m_ctext_len = 0; m_nonce_len = 0; } void ChaCha20Poly1305_Mode::key_schedule(const uint8_t key[], size_t length) { m_chacha->set_key(key, length); } void ChaCha20Poly1305_Mode::set_associated_data(const uint8_t ad[], size_t length) { if(m_ctext_len > 0 || m_nonce_len > 0) throw Invalid_State("Cannot set AD for ChaCha20Poly1305 while processing a message"); m_ad.assign(ad, ad + length); } void ChaCha20Poly1305_Mode::update_len(size_t len) { uint8_t len8[8] = { 0 }; store_le(static_cast<uint64_t>(len), len8); m_poly1305->update(len8, 8); } void ChaCha20Poly1305_Mode::start_msg(const uint8_t nonce[], size_t nonce_len) { if(!valid_nonce_length(nonce_len)) throw Invalid_IV_Length(name(), nonce_len); m_ctext_len = 0; m_nonce_len = nonce_len; m_chacha->set_iv(nonce, nonce_len); uint8_t first_block[64]; m_chacha->write_keystream(first_block, sizeof(first_block)); m_poly1305->set_key(first_block, 32); // Remainder of first block is discarded secure_scrub_memory(first_block, sizeof(first_block)); m_poly1305->update(m_ad); if(cfrg_version()) { if(m_ad.size() % 16) { const uint8_t zeros[16] = { 0 }; m_poly1305->update(zeros, 16 - m_ad.size() % 16); } } else { update_len(m_ad.size()); } } size_t ChaCha20Poly1305_Encryption::process(uint8_t buf[], size_t sz) { m_chacha->cipher1(buf, sz); m_poly1305->update(buf, sz); // poly1305 of ciphertext m_ctext_len += sz; return sz; } void ChaCha20Poly1305_Encryption::finish(secure_vector<uint8_t>& buffer, size_t offset) { update(buffer, offset); if(cfrg_version()) { if(m_ctext_len % 16) { const uint8_t zeros[16] = { 0 }; m_poly1305->update(zeros, 16 - m_ctext_len % 16); } update_len(m_ad.size()); } update_len(m_ctext_len); buffer.resize(buffer.size() + tag_size()); m_poly1305->final(&buffer[buffer.size() - tag_size()]); m_ctext_len = 0; m_nonce_len = 0; } size_t ChaCha20Poly1305_Decryption::process(uint8_t buf[], size_t sz) { m_poly1305->update(buf, sz); // poly1305 of ciphertext m_chacha->cipher1(buf, sz); m_ctext_len += sz; return sz; } void ChaCha20Poly1305_Decryption::finish(secure_vector<uint8_t>& buffer, size_t offset) { BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane"); const size_t sz = buffer.size() - offset; uint8_t* buf = buffer.data() + offset; BOTAN_ASSERT(sz >= tag_size(), "Have the tag as part of final input"); const size_t remaining = sz - tag_size(); if(remaining) { m_poly1305->update(buf, remaining); // poly1305 of ciphertext m_chacha->cipher1(buf, remaining); m_ctext_len += remaining; } if(cfrg_version()) { if(m_ctext_len % 16) { const uint8_t zeros[16] = { 0 }; m_poly1305->update(zeros, 16 - m_ctext_len % 16); } update_len(m_ad.size()); } update_len(m_ctext_len); uint8_t mac[16]; m_poly1305->final(mac); const uint8_t* included_tag = &buf[remaining]; m_ctext_len = 0; m_nonce_len = 0; if(!constant_time_compare(mac, included_tag, tag_size())) throw Invalid_Authentication_Tag("ChaCha20Poly1305 tag check failed"); buffer.resize(offset + remaining); } } <|endoftext|>
<commit_before>// @(#)root/tmva $Id$ // Author: Kim Albertsson /************************************************************************* * Copyright (C) 2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TMVA/CvSplit.h" #include "TMVA/DataSet.h" #include "TMVA/DataSetFactory.h" #include "TMVA/DataSetInfo.h" #include "TMVA/Event.h" #include "TMVA/MsgLogger.h" #include "TMVA/Tools.h" #include <TString.h> #include <TFormula.h> #include <algorithm> #include <numeric> #include <stdexcept> ClassImp(TMVA::CvSplit); ClassImp(TMVA::CvSplitKFolds); /* ============================================================================= TMVA::CvSplit ============================================================================= */ //////////////////////////////////////////////////////////////////////////////// /// TMVA::CvSplit::CvSplit(UInt_t numFolds) : fNumFolds(numFolds), fMakeFoldDataSet(kFALSE) {} //////////////////////////////////////////////////////////////////////////////// /// \brief Set training and test set vectors of dataset described by `dsi`. /// \param[in] dsi DataSetInfo for data set to be split /// \param[in] foldNumber Ordinal of fold to prepare /// \param[in] tt The set used to prepare fold. If equal to `Types::kTraining` /// splitting will be based off the original train set. If instead /// equal to `Types::kTesting` the test set will be used. /// The original training/test set is the set as defined by /// `DataLoader::PrepareTrainingAndTestSet`. /// /// Sets the training and test set vectors of the DataSet described by `dsi` as /// defined by the split. If `tt` is eqal to `Types::kTraining` the split will /// be based off of the original training set. /// /// Note: Requires `MakeKFoldDataSet` to have been called first. /// void TMVA::CvSplit::PrepareFoldDataSet(DataSetInfo &dsi, UInt_t foldNumber, Types::ETreeType tt) { if (foldNumber >= fNumFolds) { Log() << kFATAL << "DataSet prepared for \"" << fNumFolds << "\" folds, requested fold \"" << foldNumber << "\" is outside of range." << Endl; return; } auto prepareDataSetInternal = [this, &dsi, foldNumber](std::vector<std::vector<Event *>> vec) { UInt_t numFolds = fTrainEvents.size(); // Events in training set (excludes current fold) UInt_t nTotal = std::accumulate(vec.begin(), vec.end(), 0, [&](UInt_t sum, std::vector<TMVA::Event *> v) { return sum + v.size(); }); UInt_t nTrain = nTotal - vec.at(foldNumber).size(); UInt_t nTest = vec.at(foldNumber).size(); std::vector<Event *> tempTrain; std::vector<Event *> tempTest; tempTrain.reserve(nTrain); tempTest.reserve(nTest); // Insert data into training set for (UInt_t i = 0; i < numFolds; ++i) { if (i == foldNumber) { continue; } tempTrain.insert(tempTrain.end(), vec.at(i).begin(), vec.at(i).end()); } // Insert data into test set tempTest.insert(tempTest.end(), vec.at(foldNumber).begin(), vec.at(foldNumber).end()); Log() << kDEBUG << "Fold prepared, num events in training set: " << tempTrain.size() << Endl; Log() << kDEBUG << "Fold prepared, num events in test set: " << tempTest.size() << Endl; // Assign the vectors of the events to rebuild the dataset dsi.GetDataSet()->SetEventCollection(&tempTrain, Types::kTraining, false); dsi.GetDataSet()->SetEventCollection(&tempTest, Types::kTesting, false); }; if (tt == Types::kTraining) { prepareDataSetInternal(fTrainEvents); } else if (tt == Types::kTesting) { prepareDataSetInternal(fTestEvents); } else { Log() << kFATAL << "PrepareFoldDataSet can only work with training and testing data sets." << std::endl; return; } } //////////////////////////////////////////////////////////////////////////////// /// void TMVA::CvSplit::RecombineKFoldDataSet(DataSetInfo &dsi, Types::ETreeType tt) { if (tt != Types::kTraining) { Log() << kFATAL << "Only kTraining is supported for CvSplit::RecombineKFoldDataSet currently." << std::endl; } std::vector<Event *> *tempVec = new std::vector<Event *>; for (UInt_t i = 0; i < fNumFolds; ++i) { tempVec->insert(tempVec->end(), fTrainEvents.at(i).begin(), fTrainEvents.at(i).end()); } dsi.GetDataSet()->SetEventCollection(tempVec, Types::kTraining, false); dsi.GetDataSet()->SetEventCollection(tempVec, Types::kTesting, false); delete tempVec; } /* ============================================================================= TMVA::CvSplitKFoldsExpr ============================================================================= */ //////////////////////////////////////////////////////////////////////////////// /// TMVA::CvSplitKFoldsExpr::CvSplitKFoldsExpr(DataSetInfo &dsi, TString expr) : fDsi(dsi), fIdxFormulaParNumFolds(std::numeric_limits<UInt_t>::max()), fSplitFormula("", expr), fParValues(fSplitFormula.GetNpar()) { if (not fSplitFormula.IsValid()) { throw std::runtime_error("Split expression \"" + std::string(fSplitExpr.Data()) + "\" is not a valid TFormula."); } for (Int_t iFormulaPar = 0; iFormulaPar < fSplitFormula.GetNpar(); ++iFormulaPar) { TString name = fSplitFormula.GetParName(iFormulaPar); // std::cout << "Found variable with name \"" << name << "\"." << std::endl; if (name == "NumFolds" or name == "numFolds") { // std::cout << "NumFolds|numFolds is a reserved variable! Adding to context." << std::endl; fIdxFormulaParNumFolds = iFormulaPar; } else { fFormulaParIdxToDsiSpecIdx.push_back(std::make_pair(iFormulaPar, GetSpectatorIndexForName(fDsi, name))); } } } //////////////////////////////////////////////////////////////////////////////// /// UInt_t TMVA::CvSplitKFoldsExpr::Eval(UInt_t numFolds, const Event *ev) { for (auto &p : fFormulaParIdxToDsiSpecIdx) { auto iFormulaPar = p.first; auto iSpectator = p.second; fParValues.at(iFormulaPar) = ev->GetSpectator(iSpectator); } if (fIdxFormulaParNumFolds < fSplitFormula.GetNpar()) { fParValues[fIdxFormulaParNumFolds] = numFolds; } Double_t iFold = fSplitFormula.EvalPar(nullptr, &fParValues[0]); if (fabs(iFold - (double)((UInt_t)iFold)) > 1e-5) { throw std::runtime_error( "Output of splitExpr should be a non-negative integer between 0 and numFolds-1 inclusive."); } return iFold; } //////////////////////////////////////////////////////////////////////////////// /// Bool_t TMVA::CvSplitKFoldsExpr::Validate(TString expr) { return TFormula("", expr).IsValid(); } //////////////////////////////////////////////////////////////////////////////// /// UInt_t TMVA::CvSplitKFoldsExpr::GetSpectatorIndexForName(DataSetInfo &dsi, TString name) { std::vector<VariableInfo> spectatorInfos = dsi.GetSpectatorInfos(); for (UInt_t iSpectator = 0; iSpectator < spectatorInfos.size(); ++iSpectator) { VariableInfo vi = spectatorInfos[iSpectator]; if (vi.GetName() == name) { return iSpectator; } else if (vi.GetLabel() == name) { return iSpectator; } else if (vi.GetExpression() == name) { return iSpectator; } } throw std::runtime_error("Spectator \"" + std::string(name.Data()) + "\" not found."); } /* ============================================================================= TMVA::CvSplitKFolds ============================================================================= */ //////////////////////////////////////////////////////////////////////////////// /// \brief Splits a dataset into k folds, ready for use in cross validation. /// \param numFolds[in] Number of folds to split data into /// \param stratified[in] If true, use stratified splitting, balancing the /// number of events across classes and folds. If false, /// no such balancing is done. For /// \param splitExpr[in] Expression used to split data into folds. If `""` a /// random assignment will be done. Otherwise the /// expression is fed into a TFormula and evaluated per /// event. The resulting value is the the fold assignment. /// \param seed[in] Used only when using random splitting (i.e. when /// `splitExpr` is `""`). Seed is used to initialise the random /// number generator when assigning events to folds. /// TMVA::CvSplitKFolds::CvSplitKFolds(UInt_t numFolds, TString splitExpr, Bool_t stratified, UInt_t seed) : CvSplit(numFolds), fSeed(seed), fSplitExprString(splitExpr), fStratified(stratified) { if (not CvSplitKFoldsExpr::Validate(fSplitExprString) and (splitExpr != TString(""))) { Log() << kFATAL << "Split expression \"" << fSplitExprString << "\" is not a valid TFormula." << Endl; } if (stratified) { Log() << kFATAL << "Stratified KFolds not currently implemented." << std::endl; } } //////////////////////////////////////////////////////////////////////////////// /// \brief Prepares a DataSet for cross validation void TMVA::CvSplitKFolds::MakeKFoldDataSet(DataSetInfo &dsi) { // Validate spectator // fSpectatorIdx = GetSpectatorIndexForName(dsi, fSpectatorName); if (fSplitExprString != TString("")) { fSplitExpr = std::unique_ptr<CvSplitKFoldsExpr>(new CvSplitKFoldsExpr(dsi, fSplitExprString)); } // No need to do it again if the sets have already been split. if (fMakeFoldDataSet) { Log() << kINFO << "Splitting in k-folds has been already done" << Endl; return; } fMakeFoldDataSet = kTRUE; // Get the original event vectors for testing and training from the dataset. std::vector<Event *> trainData = dsi.GetDataSet()->GetEventCollection(Types::kTraining); std::vector<Event *> testData = dsi.GetDataSet()->GetEventCollection(Types::kTesting); // Split the sets into the number of folds. fTrainEvents = SplitSets(trainData, fNumFolds); fTestEvents = SplitSets(testData, fNumFolds); } //////////////////////////////////////////////////////////////////////////////// /// \brief Generates a vector of fold assignments /// \param nEntires[in] Number of events in range /// \param numFolds[in] Number of folds to split data into /// \param seed[in] Random seed /// /// Randomly assigns events to `numFolds` folds. Each fold will hold at most /// `nEntries / numFolds + 1` events. /// std::vector<UInt_t> TMVA::CvSplitKFolds::GetEventIndexToFoldMapping(UInt_t nEntries, UInt_t numFolds, UInt_t seed) { // Generate assignment of the pattern `0, 1, 2, 0, 1, 2, 0, 1 ...` for // `numFolds = 3`. std::vector<UInt_t> fOrigToFoldMapping; fOrigToFoldMapping.reserve(nEntries); for (UInt_t iEvent = 0; iEvent < nEntries; ++iEvent) { fOrigToFoldMapping.push_back(iEvent % numFolds); } // Shuffle assignment TMVA::RandomGenerator<TRandom3> rng(seed); std::shuffle(fOrigToFoldMapping.begin(), fOrigToFoldMapping.end(), rng); return fOrigToFoldMapping; } //////////////////////////////////////////////////////////////////////////////// /// \brief Split sets for into k-folds /// \param oldSet[in] Original, unsplit, events /// \param numFolds[in] Number of folds to split data into /// std::vector<std::vector<TMVA::Event *>> TMVA::CvSplitKFolds::SplitSets(std::vector<TMVA::Event *> &oldSet, UInt_t numFolds) { const ULong64_t nEntries = oldSet.size(); const ULong64_t foldSize = nEntries / numFolds; std::vector<std::vector<Event *>> tempSets; tempSets.reserve(fNumFolds); for (UInt_t iFold = 0; iFold < numFolds; ++iFold) { tempSets.emplace_back(); tempSets.at(iFold).reserve(foldSize); } Bool_t useSplitExpr = not(fSplitExpr == nullptr or fSplitExprString == ""); if (useSplitExpr) { // Deterministic split for (ULong64_t i = 0; i < nEntries; i++) { TMVA::Event *ev = oldSet[i]; UInt_t iFold = fSplitExpr->Eval(numFolds, ev); tempSets.at((UInt_t)iFold).push_back(ev); } } else { // Random split std::vector<UInt_t> fOrigToFoldMapping = GetEventIndexToFoldMapping(nEntries, numFolds, fSeed); for (UInt_t iEvent = 0; iEvent < nEntries; ++iEvent) { UInt_t iFold = fOrigToFoldMapping[iEvent]; TMVA::Event *ev = oldSet[iEvent]; tempSets.at(iFold).push_back(ev); fEventToFoldMapping[ev] = iFold; } } return tempSets; } <commit_msg>[TMVA] CVSplit -- Improve fold assignment for large values<commit_after>// @(#)root/tmva $Id$ // Author: Kim Albertsson /************************************************************************* * Copyright (C) 2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TMVA/CvSplit.h" #include "TMVA/DataSet.h" #include "TMVA/DataSetFactory.h" #include "TMVA/DataSetInfo.h" #include "TMVA/Event.h" #include "TMVA/MsgLogger.h" #include "TMVA/Tools.h" #include <TString.h> #include <TFormula.h> #include <algorithm> #include <numeric> #include <stdexcept> ClassImp(TMVA::CvSplit); ClassImp(TMVA::CvSplitKFolds); /* ============================================================================= TMVA::CvSplit ============================================================================= */ //////////////////////////////////////////////////////////////////////////////// /// TMVA::CvSplit::CvSplit(UInt_t numFolds) : fNumFolds(numFolds), fMakeFoldDataSet(kFALSE) {} //////////////////////////////////////////////////////////////////////////////// /// \brief Set training and test set vectors of dataset described by `dsi`. /// \param[in] dsi DataSetInfo for data set to be split /// \param[in] foldNumber Ordinal of fold to prepare /// \param[in] tt The set used to prepare fold. If equal to `Types::kTraining` /// splitting will be based off the original train set. If instead /// equal to `Types::kTesting` the test set will be used. /// The original training/test set is the set as defined by /// `DataLoader::PrepareTrainingAndTestSet`. /// /// Sets the training and test set vectors of the DataSet described by `dsi` as /// defined by the split. If `tt` is eqal to `Types::kTraining` the split will /// be based off of the original training set. /// /// Note: Requires `MakeKFoldDataSet` to have been called first. /// void TMVA::CvSplit::PrepareFoldDataSet(DataSetInfo &dsi, UInt_t foldNumber, Types::ETreeType tt) { if (foldNumber >= fNumFolds) { Log() << kFATAL << "DataSet prepared for \"" << fNumFolds << "\" folds, requested fold \"" << foldNumber << "\" is outside of range." << Endl; return; } auto prepareDataSetInternal = [this, &dsi, foldNumber](std::vector<std::vector<Event *>> vec) { UInt_t numFolds = fTrainEvents.size(); // Events in training set (excludes current fold) UInt_t nTotal = std::accumulate(vec.begin(), vec.end(), 0, [&](UInt_t sum, std::vector<TMVA::Event *> v) { return sum + v.size(); }); UInt_t nTrain = nTotal - vec.at(foldNumber).size(); UInt_t nTest = vec.at(foldNumber).size(); std::vector<Event *> tempTrain; std::vector<Event *> tempTest; tempTrain.reserve(nTrain); tempTest.reserve(nTest); // Insert data into training set for (UInt_t i = 0; i < numFolds; ++i) { if (i == foldNumber) { continue; } tempTrain.insert(tempTrain.end(), vec.at(i).begin(), vec.at(i).end()); } // Insert data into test set tempTest.insert(tempTest.end(), vec.at(foldNumber).begin(), vec.at(foldNumber).end()); Log() << kDEBUG << "Fold prepared, num events in training set: " << tempTrain.size() << Endl; Log() << kDEBUG << "Fold prepared, num events in test set: " << tempTest.size() << Endl; // Assign the vectors of the events to rebuild the dataset dsi.GetDataSet()->SetEventCollection(&tempTrain, Types::kTraining, false); dsi.GetDataSet()->SetEventCollection(&tempTest, Types::kTesting, false); }; if (tt == Types::kTraining) { prepareDataSetInternal(fTrainEvents); } else if (tt == Types::kTesting) { prepareDataSetInternal(fTestEvents); } else { Log() << kFATAL << "PrepareFoldDataSet can only work with training and testing data sets." << std::endl; return; } } //////////////////////////////////////////////////////////////////////////////// /// void TMVA::CvSplit::RecombineKFoldDataSet(DataSetInfo &dsi, Types::ETreeType tt) { if (tt != Types::kTraining) { Log() << kFATAL << "Only kTraining is supported for CvSplit::RecombineKFoldDataSet currently." << std::endl; } std::vector<Event *> *tempVec = new std::vector<Event *>; for (UInt_t i = 0; i < fNumFolds; ++i) { tempVec->insert(tempVec->end(), fTrainEvents.at(i).begin(), fTrainEvents.at(i).end()); } dsi.GetDataSet()->SetEventCollection(tempVec, Types::kTraining, false); dsi.GetDataSet()->SetEventCollection(tempVec, Types::kTesting, false); delete tempVec; } /* ============================================================================= TMVA::CvSplitKFoldsExpr ============================================================================= */ //////////////////////////////////////////////////////////////////////////////// /// TMVA::CvSplitKFoldsExpr::CvSplitKFoldsExpr(DataSetInfo &dsi, TString expr) : fDsi(dsi), fIdxFormulaParNumFolds(std::numeric_limits<UInt_t>::max()), fSplitFormula("", expr), fParValues(fSplitFormula.GetNpar()) { if (not fSplitFormula.IsValid()) { throw std::runtime_error("Split expression \"" + std::string(fSplitExpr.Data()) + "\" is not a valid TFormula."); } for (Int_t iFormulaPar = 0; iFormulaPar < fSplitFormula.GetNpar(); ++iFormulaPar) { TString name = fSplitFormula.GetParName(iFormulaPar); // std::cout << "Found variable with name \"" << name << "\"." << std::endl; if (name == "NumFolds" or name == "numFolds") { // std::cout << "NumFolds|numFolds is a reserved variable! Adding to context." << std::endl; fIdxFormulaParNumFolds = iFormulaPar; } else { fFormulaParIdxToDsiSpecIdx.push_back(std::make_pair(iFormulaPar, GetSpectatorIndexForName(fDsi, name))); } } } //////////////////////////////////////////////////////////////////////////////// /// UInt_t TMVA::CvSplitKFoldsExpr::Eval(UInt_t numFolds, const Event *ev) { for (auto &p : fFormulaParIdxToDsiSpecIdx) { auto iFormulaPar = p.first; auto iSpectator = p.second; fParValues.at(iFormulaPar) = ev->GetSpectator(iSpectator); } if (fIdxFormulaParNumFolds < fSplitFormula.GetNpar()) { fParValues[fIdxFormulaParNumFolds] = numFolds; } // NOTE: We are using a double to represent an integer here. This _will_ // lead to problems if the norm of the double grows too large. A quick test // with python suggests that problems arise at a magnitude of ~1e16. Double_t iFold_d = fSplitFormula.EvalPar(nullptr, &fParValues[0]); if (iFold_d < 0) { throw std::runtime_error("Output of splitExpr must be non-negative."); } UInt_t iFold = std::lround(iFold_d); if (iFold >= numFolds) { throw std::runtime_error("Output of splitExpr should be a non-negative" "integer between 0 and numFolds-1 inclusive."); } return iFold; } //////////////////////////////////////////////////////////////////////////////// /// Bool_t TMVA::CvSplitKFoldsExpr::Validate(TString expr) { return TFormula("", expr).IsValid(); } //////////////////////////////////////////////////////////////////////////////// /// UInt_t TMVA::CvSplitKFoldsExpr::GetSpectatorIndexForName(DataSetInfo &dsi, TString name) { std::vector<VariableInfo> spectatorInfos = dsi.GetSpectatorInfos(); for (UInt_t iSpectator = 0; iSpectator < spectatorInfos.size(); ++iSpectator) { VariableInfo vi = spectatorInfos[iSpectator]; if (vi.GetName() == name) { return iSpectator; } else if (vi.GetLabel() == name) { return iSpectator; } else if (vi.GetExpression() == name) { return iSpectator; } } throw std::runtime_error("Spectator \"" + std::string(name.Data()) + "\" not found."); } /* ============================================================================= TMVA::CvSplitKFolds ============================================================================= */ //////////////////////////////////////////////////////////////////////////////// /// \brief Splits a dataset into k folds, ready for use in cross validation. /// \param numFolds[in] Number of folds to split data into /// \param stratified[in] If true, use stratified splitting, balancing the /// number of events across classes and folds. If false, /// no such balancing is done. For /// \param splitExpr[in] Expression used to split data into folds. If `""` a /// random assignment will be done. Otherwise the /// expression is fed into a TFormula and evaluated per /// event. The resulting value is the the fold assignment. /// \param seed[in] Used only when using random splitting (i.e. when /// `splitExpr` is `""`). Seed is used to initialise the random /// number generator when assigning events to folds. /// TMVA::CvSplitKFolds::CvSplitKFolds(UInt_t numFolds, TString splitExpr, Bool_t stratified, UInt_t seed) : CvSplit(numFolds), fSeed(seed), fSplitExprString(splitExpr), fStratified(stratified) { if (not CvSplitKFoldsExpr::Validate(fSplitExprString) and (splitExpr != TString(""))) { Log() << kFATAL << "Split expression \"" << fSplitExprString << "\" is not a valid TFormula." << Endl; } if (stratified) { Log() << kFATAL << "Stratified KFolds not currently implemented." << std::endl; } } //////////////////////////////////////////////////////////////////////////////// /// \brief Prepares a DataSet for cross validation void TMVA::CvSplitKFolds::MakeKFoldDataSet(DataSetInfo &dsi) { // Validate spectator // fSpectatorIdx = GetSpectatorIndexForName(dsi, fSpectatorName); if (fSplitExprString != TString("")) { fSplitExpr = std::unique_ptr<CvSplitKFoldsExpr>(new CvSplitKFoldsExpr(dsi, fSplitExprString)); } // No need to do it again if the sets have already been split. if (fMakeFoldDataSet) { Log() << kINFO << "Splitting in k-folds has been already done" << Endl; return; } fMakeFoldDataSet = kTRUE; // Get the original event vectors for testing and training from the dataset. std::vector<Event *> trainData = dsi.GetDataSet()->GetEventCollection(Types::kTraining); std::vector<Event *> testData = dsi.GetDataSet()->GetEventCollection(Types::kTesting); // Split the sets into the number of folds. fTrainEvents = SplitSets(trainData, fNumFolds); fTestEvents = SplitSets(testData, fNumFolds); } //////////////////////////////////////////////////////////////////////////////// /// \brief Generates a vector of fold assignments /// \param nEntires[in] Number of events in range /// \param numFolds[in] Number of folds to split data into /// \param seed[in] Random seed /// /// Randomly assigns events to `numFolds` folds. Each fold will hold at most /// `nEntries / numFolds + 1` events. /// std::vector<UInt_t> TMVA::CvSplitKFolds::GetEventIndexToFoldMapping(UInt_t nEntries, UInt_t numFolds, UInt_t seed) { // Generate assignment of the pattern `0, 1, 2, 0, 1, 2, 0, 1 ...` for // `numFolds = 3`. std::vector<UInt_t> fOrigToFoldMapping; fOrigToFoldMapping.reserve(nEntries); for (UInt_t iEvent = 0; iEvent < nEntries; ++iEvent) { fOrigToFoldMapping.push_back(iEvent % numFolds); } // Shuffle assignment TMVA::RandomGenerator<TRandom3> rng(seed); std::shuffle(fOrigToFoldMapping.begin(), fOrigToFoldMapping.end(), rng); return fOrigToFoldMapping; } //////////////////////////////////////////////////////////////////////////////// /// \brief Split sets for into k-folds /// \param oldSet[in] Original, unsplit, events /// \param numFolds[in] Number of folds to split data into /// std::vector<std::vector<TMVA::Event *>> TMVA::CvSplitKFolds::SplitSets(std::vector<TMVA::Event *> &oldSet, UInt_t numFolds) { const ULong64_t nEntries = oldSet.size(); const ULong64_t foldSize = nEntries / numFolds; std::vector<std::vector<Event *>> tempSets; tempSets.reserve(fNumFolds); for (UInt_t iFold = 0; iFold < numFolds; ++iFold) { tempSets.emplace_back(); tempSets.at(iFold).reserve(foldSize); } Bool_t useSplitExpr = not(fSplitExpr == nullptr or fSplitExprString == ""); if (useSplitExpr) { // Deterministic split for (ULong64_t i = 0; i < nEntries; i++) { TMVA::Event *ev = oldSet[i]; UInt_t iFold = fSplitExpr->Eval(numFolds, ev); tempSets.at((UInt_t)iFold).push_back(ev); } } else { // Random split std::vector<UInt_t> fOrigToFoldMapping = GetEventIndexToFoldMapping(nEntries, numFolds, fSeed); for (UInt_t iEvent = 0; iEvent < nEntries; ++iEvent) { UInt_t iFold = fOrigToFoldMapping[iEvent]; TMVA::Event *ev = oldSet[iEvent]; tempSets.at(iFold).push_back(ev); fEventToFoldMapping[ev] = iFold; } } return tempSets; } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * ddl client implementation * * Revision history: * 2015-12-30, xiaotz, first version */ #include <dsn/dist/replication.h> #include <dsn/dist/replication/replication_other_types.h> #include "client_ddl.h" #include <iostream> #include <fstream> #include <iomanip> namespace dsn{ namespace replication{ client_ddl::client_ddl(const std::vector<dsn::rpc_address>& meta_servers) { _meta_servers.assign_group(dsn_group_build("meta.servers")); for (auto& m : meta_servers) dsn_group_add(_meta_servers.group_handle(), m.c_addr()); } dsn::error_code client_ddl::create_app(const std::string& app_name, const std::string& app_type, int partition_count, int replica_count) { if(partition_count < 1) return ERR_INVALID_PARAMETERS; if(replica_count < 3) return ERR_INVALID_PARAMETERS; if(app_name.empty() || !std::all_of(app_name.cbegin(),app_name.cend(),(bool (*)(int)) client_ddl::valid_app_char)) return ERR_INVALID_PARAMETERS; if(app_type.empty() || !std::all_of(app_type.cbegin(),app_type.cend(),(bool (*)(int)) client_ddl::valid_app_char)) return ERR_INVALID_PARAMETERS; std::shared_ptr<configuration_create_app_request> req(new configuration_create_app_request()); req->app_name = app_name; req->options.partition_count = partition_count; req->options.replica_count = replica_count; req->options.success_if_exist = true; req->options.app_type = app_type; auto resp_task = request_meta<configuration_create_app_request>( RPC_CM_CREATE_APP, req ); resp_task->wait(); if (resp_task->error() != dsn::ERR_OK) { return resp_task->error(); } dsn::replication::configuration_create_app_response resp; ::unmarshall(resp_task->response(), resp); if(resp.err != dsn::ERR_OK) { return resp.err; } std::cout << "create app " << app_name << " succeed, waiting for app ready." << std::endl; int sleep_sec = 2; while(true) { std::shared_ptr<configuration_query_by_index_request> query_req(new configuration_query_by_index_request()); query_req->app_name = app_name; auto query_task = request_meta<configuration_query_by_index_request>( RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX, query_req ); query_task->wait(); if (query_task->error() != dsn::ERR_OK) { return dsn::ERR_IO_PENDING; } dsn::replication::configuration_query_by_index_response query_resp; ::unmarshall(query_task->response(), query_resp); if(query_resp.err != dsn::ERR_OK) { return resp.err; } bool ready = true; dassert(partition_count == query_resp.partition_count, "partition count not equal"); for(int i =0; i < partition_count; i++) { partition_configuration pc = query_resp.partitions[i]; if(pc.primary.is_invalid() || ((pc.secondaries.size() * 2 + 2) < replica_count)) { ready = false; break; } } if(ready) break; std::cout << app_name << " not ready yet, still waiting." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(sleep_sec)); } std::cout << app_name << " is ready now!" << std::endl; return dsn::ERR_OK; } dsn::error_code client_ddl::drop_app(const std::string& app_name) { if(app_name.empty() || !std::all_of(app_name.cbegin(),app_name.cend(),(bool (*)(int)) client_ddl::valid_app_char)) return ERR_INVALID_PARAMETERS; std::shared_ptr<configuration_drop_app_request> req(new configuration_drop_app_request()); req->app_name = app_name; req->options.success_if_not_exist = true; auto resp_task = request_meta<configuration_drop_app_request>( RPC_CM_DROP_APP, req ); resp_task->wait(); if (resp_task->error() != dsn::ERR_OK) { return resp_task->error(); } dsn::replication::configuration_drop_app_response resp; ::unmarshall(resp_task->response(), resp); if(resp.err != dsn::ERR_OK) { return resp.err; } return dsn::ERR_OK; } dsn::error_code client_ddl::list_apps(const dsn::replication::app_status status, const std::string& file_name) { std::shared_ptr<configuration_list_apps_request> req(new configuration_list_apps_request()); req->status = status; auto resp_task = request_meta<configuration_list_apps_request>( RPC_CM_LIST_APPS, req ); resp_task->wait(); if (resp_task->error() != dsn::ERR_OK) { return resp_task->error(); } dsn::replication::configuration_list_apps_response resp; ::unmarshall(resp_task->response(), resp); if(resp.err != dsn::ERR_OK) { return resp.err; } // print configuration_list_apps_response std::streambuf * buf; std::ofstream of; if(!file_name.empty()) { of.open(file_name); buf = of.rdbuf(); } else { buf = std::cout.rdbuf(); } std::ostream out(buf); out << std::setw(10) << std::left << "app_id" << std::setw(20) << std::left << "status" << std::setw(20) << std::left << "app_name" << std::setw(20) << std::left << "app_type" << std::setw(10) << std::left << "partition_count" << std::endl; for(int i = 0; i < resp.infos.size(); i++) { dsn::replication::app_info info = resp.infos[i]; out << std::setw(10) << std::left << info.app_id << std::setw(20) << std::left << enum_to_string(info.status) << std::setw(20) << std::left << info.app_name << std::setw(20) << std::left << info.app_type << std::setw(10) << std::left << info.partition_count << std::endl; } out << std::endl << std::flush; return dsn::ERR_OK; } dsn::error_code client_ddl::list_nodes(const dsn::replication::node_status status, const std::string& file_name) { std::shared_ptr<configuration_list_nodes_request> req(new configuration_list_nodes_request()); req->status = status; auto resp_task = request_meta<configuration_list_nodes_request>( RPC_CM_LIST_NODES, req ); resp_task->wait(); if (resp_task->error() != dsn::ERR_OK) { return resp_task->error(); } dsn::replication::configuration_list_nodes_response resp; ::unmarshall(resp_task->response(), resp); if(resp.err != dsn::ERR_OK) { return resp.err; } // print configuration_list_nodes_response std::streambuf * buf; std::ofstream of; if(!file_name.empty()) { of.open(file_name); buf = of.rdbuf(); } else { buf = std::cout.rdbuf(); } std::ostream out(buf); out << std::setw(25) << std::left << "address" << std::setw(20) << std::left << "status" << std::endl; for(int i = 0; i < resp.infos.size(); i++) { dsn::replication::node_info info = resp.infos[i]; out << std::setw(25) << std::left << info.address.to_string() << std::setw(20) << std::left << enum_to_string(info.status) << std::endl; } out << std::endl << std::flush; return dsn::ERR_OK; } dsn::error_code client_ddl::list_app(const std::string& app_name, bool detailed, const std::string& file_name) { if(app_name.empty() || !std::all_of(app_name.cbegin(),app_name.cend(),(bool (*)(int)) client_ddl::valid_app_char)) return ERR_INVALID_PARAMETERS; std::shared_ptr<configuration_query_by_index_request> req(new configuration_query_by_index_request()); req->app_name = app_name; auto resp_task = request_meta<configuration_query_by_index_request>( RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX, req ); resp_task->wait(); if (resp_task->error() != dsn::ERR_OK) { return resp_task->error(); } dsn::replication::configuration_query_by_index_response resp; ::unmarshall(resp_task->response(), resp); if(resp.err != dsn::ERR_OK) { return resp.err; } // print configuration_query_by_index_response std::streambuf * buf; std::ofstream of; if(!file_name.empty()) { of.open(file_name); buf = of.rdbuf(); } else { buf = std::cout.rdbuf(); } std::ostream out(buf); out << "app name:" << app_name << std::endl << "app id:" << resp.app_id << std::endl << "app partition count:" << resp.partition_count << std::endl; if(detailed) { out << "details:" << std::endl << std::setw(10) << std::left << "pidx" << std::setw(10) << std::left << "ballot" << std::setw(15) << std::left << "commmitdecree" << std::setw(25) << std::left << "primary" << std::setw(40) << std::left << "secondaries" << std::endl; for(int i = 0; i < resp.partitions.size(); i++) { const dsn::replication::partition_configuration& p = resp.partitions[i]; out << std::setw(10) << std::left << p.gpid.pidx << std::setw(10) << std::left << p.ballot << std::setw(15) << std::left << p.last_committed_decree << std::setw(25) << std::left << p.primary.to_std_string() << std::left<< p.secondaries.size() << ":["; for(int j = 0; j < p.secondaries.size(); j++) { if(j!= 0) out << ","; out << p.secondaries[j].to_std_string(); } out << "]" << std::endl; } } out << std::endl; return dsn::ERR_OK; } bool client_ddl::valid_app_char(int c) { return (bool)std::isalnum(c) || c == '_' || c == '.'; } void client_ddl::end_meta_request(task_ptr callback, int retry_times, error_code err, dsn_message_t request, dsn_message_t resp) { if(err == dsn::ERR_TIMEOUT && retry_times < 5) { rpc_address leader = dsn_group_get_leader(_meta_servers.group_handle()); rpc_address next = dsn_group_next(_meta_servers.group_handle(), leader.c_addr()); dsn_group_set_leader(_meta_servers.group_handle(), next.c_addr()); rpc::call( _meta_servers, request, this, [=, callback_capture = std::move(callback)](error_code err, dsn_message_t request, dsn_message_t response) { end_meta_request(std::move(callback_capture), retry_times + 1, err, request, response); }, 0 ); } else callback->enqueue_rpc_response(err, resp); } }} // namespace <commit_msg>improve client_dll to print table creating process<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * ddl client implementation * * Revision history: * 2015-12-30, xiaotz, first version */ #include <dsn/dist/replication.h> #include <dsn/dist/replication/replication_other_types.h> #include "client_ddl.h" #include <iostream> #include <fstream> #include <iomanip> namespace dsn{ namespace replication{ client_ddl::client_ddl(const std::vector<dsn::rpc_address>& meta_servers) { _meta_servers.assign_group(dsn_group_build("meta.servers")); for (auto& m : meta_servers) dsn_group_add(_meta_servers.group_handle(), m.c_addr()); } dsn::error_code client_ddl::create_app(const std::string& app_name, const std::string& app_type, int partition_count, int replica_count) { if(partition_count < 1) return ERR_INVALID_PARAMETERS; if(replica_count < 3) return ERR_INVALID_PARAMETERS; if(app_name.empty() || !std::all_of(app_name.cbegin(),app_name.cend(),(bool (*)(int)) client_ddl::valid_app_char)) return ERR_INVALID_PARAMETERS; if(app_type.empty() || !std::all_of(app_type.cbegin(),app_type.cend(),(bool (*)(int)) client_ddl::valid_app_char)) return ERR_INVALID_PARAMETERS; std::shared_ptr<configuration_create_app_request> req(new configuration_create_app_request()); req->app_name = app_name; req->options.partition_count = partition_count; req->options.replica_count = replica_count; req->options.success_if_exist = true; req->options.app_type = app_type; auto resp_task = request_meta<configuration_create_app_request>( RPC_CM_CREATE_APP, req ); resp_task->wait(); if (resp_task->error() != dsn::ERR_OK) { return resp_task->error(); } dsn::replication::configuration_create_app_response resp; ::unmarshall(resp_task->response(), resp); if(resp.err != dsn::ERR_OK) { return resp.err; } std::cout << "create app " << app_name << " succeed, waiting for app ready." << std::endl; int sleep_sec = 2; while(true) { std::shared_ptr<configuration_query_by_index_request> query_req(new configuration_query_by_index_request()); query_req->app_name = app_name; auto query_task = request_meta<configuration_query_by_index_request>( RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX, query_req ); query_task->wait(); if (query_task->error() != dsn::ERR_OK) { return dsn::ERR_IO_PENDING; } dsn::replication::configuration_query_by_index_response query_resp; ::unmarshall(query_task->response(), query_resp); if(query_resp.err != dsn::ERR_OK) { return resp.err; } dassert(partition_count == query_resp.partition_count, "partition count not equal"); int ready_count = 0; for(int i =0; i < partition_count; i++) { partition_configuration pc = query_resp.partitions[i]; if (!pc.primary.is_invalid() && (pc.secondaries.size() >= replica_count / 2)) { ready_count++; } } if(ready_count == partition_count) { break; } std::cout << app_name << " not ready yet, still waiting... (" << ready_count << "/" << partition_count << ")" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(sleep_sec)); } std::cout << app_name << " is ready now!" << std::endl; return dsn::ERR_OK; } dsn::error_code client_ddl::drop_app(const std::string& app_name) { if(app_name.empty() || !std::all_of(app_name.cbegin(),app_name.cend(),(bool (*)(int)) client_ddl::valid_app_char)) return ERR_INVALID_PARAMETERS; std::shared_ptr<configuration_drop_app_request> req(new configuration_drop_app_request()); req->app_name = app_name; req->options.success_if_not_exist = true; auto resp_task = request_meta<configuration_drop_app_request>( RPC_CM_DROP_APP, req ); resp_task->wait(); if (resp_task->error() != dsn::ERR_OK) { return resp_task->error(); } dsn::replication::configuration_drop_app_response resp; ::unmarshall(resp_task->response(), resp); if(resp.err != dsn::ERR_OK) { return resp.err; } return dsn::ERR_OK; } dsn::error_code client_ddl::list_apps(const dsn::replication::app_status status, const std::string& file_name) { std::shared_ptr<configuration_list_apps_request> req(new configuration_list_apps_request()); req->status = status; auto resp_task = request_meta<configuration_list_apps_request>( RPC_CM_LIST_APPS, req ); resp_task->wait(); if (resp_task->error() != dsn::ERR_OK) { return resp_task->error(); } dsn::replication::configuration_list_apps_response resp; ::unmarshall(resp_task->response(), resp); if(resp.err != dsn::ERR_OK) { return resp.err; } // print configuration_list_apps_response std::streambuf * buf; std::ofstream of; if(!file_name.empty()) { of.open(file_name); buf = of.rdbuf(); } else { buf = std::cout.rdbuf(); } std::ostream out(buf); out << std::setw(10) << std::left << "app_id" << std::setw(20) << std::left << "status" << std::setw(20) << std::left << "app_name" << std::setw(20) << std::left << "app_type" << std::setw(10) << std::left << "partition_count" << std::endl; for(int i = 0; i < resp.infos.size(); i++) { dsn::replication::app_info info = resp.infos[i]; out << std::setw(10) << std::left << info.app_id << std::setw(20) << std::left << enum_to_string(info.status) << std::setw(20) << std::left << info.app_name << std::setw(20) << std::left << info.app_type << std::setw(10) << std::left << info.partition_count << std::endl; } out << std::endl << std::flush; return dsn::ERR_OK; } dsn::error_code client_ddl::list_nodes(const dsn::replication::node_status status, const std::string& file_name) { std::shared_ptr<configuration_list_nodes_request> req(new configuration_list_nodes_request()); req->status = status; auto resp_task = request_meta<configuration_list_nodes_request>( RPC_CM_LIST_NODES, req ); resp_task->wait(); if (resp_task->error() != dsn::ERR_OK) { return resp_task->error(); } dsn::replication::configuration_list_nodes_response resp; ::unmarshall(resp_task->response(), resp); if(resp.err != dsn::ERR_OK) { return resp.err; } // print configuration_list_nodes_response std::streambuf * buf; std::ofstream of; if(!file_name.empty()) { of.open(file_name); buf = of.rdbuf(); } else { buf = std::cout.rdbuf(); } std::ostream out(buf); out << std::setw(25) << std::left << "address" << std::setw(20) << std::left << "status" << std::endl; for(int i = 0; i < resp.infos.size(); i++) { dsn::replication::node_info info = resp.infos[i]; out << std::setw(25) << std::left << info.address.to_string() << std::setw(20) << std::left << enum_to_string(info.status) << std::endl; } out << std::endl << std::flush; return dsn::ERR_OK; } dsn::error_code client_ddl::list_app(const std::string& app_name, bool detailed, const std::string& file_name) { if(app_name.empty() || !std::all_of(app_name.cbegin(),app_name.cend(),(bool (*)(int)) client_ddl::valid_app_char)) return ERR_INVALID_PARAMETERS; std::shared_ptr<configuration_query_by_index_request> req(new configuration_query_by_index_request()); req->app_name = app_name; auto resp_task = request_meta<configuration_query_by_index_request>( RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX, req ); resp_task->wait(); if (resp_task->error() != dsn::ERR_OK) { return resp_task->error(); } dsn::replication::configuration_query_by_index_response resp; ::unmarshall(resp_task->response(), resp); if(resp.err != dsn::ERR_OK) { return resp.err; } // print configuration_query_by_index_response std::streambuf * buf; std::ofstream of; if(!file_name.empty()) { of.open(file_name); buf = of.rdbuf(); } else { buf = std::cout.rdbuf(); } std::ostream out(buf); out << "app name:" << app_name << std::endl << "app id:" << resp.app_id << std::endl << "app partition count:" << resp.partition_count << std::endl; if(detailed) { out << "details:" << std::endl << std::setw(10) << std::left << "pidx" << std::setw(10) << std::left << "ballot" << std::setw(15) << std::left << "commmitdecree" << std::setw(25) << std::left << "primary" << std::setw(40) << std::left << "secondaries" << std::endl; for(int i = 0; i < resp.partitions.size(); i++) { const dsn::replication::partition_configuration& p = resp.partitions[i]; out << std::setw(10) << std::left << p.gpid.pidx << std::setw(10) << std::left << p.ballot << std::setw(15) << std::left << p.last_committed_decree << std::setw(25) << std::left << p.primary.to_std_string() << std::left<< p.secondaries.size() << ":["; for(int j = 0; j < p.secondaries.size(); j++) { if(j!= 0) out << ","; out << p.secondaries[j].to_std_string(); } out << "]" << std::endl; } } out << std::endl; return dsn::ERR_OK; } bool client_ddl::valid_app_char(int c) { return (bool)std::isalnum(c) || c == '_' || c == '.'; } void client_ddl::end_meta_request(task_ptr callback, int retry_times, error_code err, dsn_message_t request, dsn_message_t resp) { if(err == dsn::ERR_TIMEOUT && retry_times < 5) { rpc_address leader = dsn_group_get_leader(_meta_servers.group_handle()); rpc_address next = dsn_group_next(_meta_servers.group_handle(), leader.c_addr()); dsn_group_set_leader(_meta_servers.group_handle(), next.c_addr()); rpc::call( _meta_servers, request, this, [=, callback_capture = std::move(callback)](error_code err, dsn_message_t request, dsn_message_t response) { end_meta_request(std::move(callback_capture), retry_times + 1, err, request, response); }, 0 ); } else callback->enqueue_rpc_response(err, resp); } }} // namespace <|endoftext|>
<commit_before>/*============================================================================= Copyright (c) 2012-2014 Richard Otis Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // Declarations for global minimization of a thermodynamic potential #ifndef INCLUDED_GLOBAL_MINIMIZATION #define INCLUDED_GLOBAL_MINIMIZATION #include "libgibbs/include/compositionset.hpp" #include "libgibbs/include/models.hpp" #include "libgibbs/include/optimizer/utils/hull_mapping.hpp" #include "libgibbs/include/utils/for_each_pair.hpp" #include "libgibbs/include/utils/site_fraction_convert.hpp" #include "libtdb/include/logging.hpp" #include <boost/assert.hpp> #include <boost/noncopyable.hpp> #include <functional> #include <list> #include <limits> #include <set> namespace Optimizer { /* GlobalMinimizer performs global minimization of the specified * thermodynamic potential. Energy manifolds are calculated for * all phases in the global composition space and each phase's * internal degrees of freedom. Constraints can be added incrementally * to identify the equilibrium tie hyperplane and fix a position in it. */ template < typename FacetType, typename CoordinateType = double, typename EnergyType = CoordinateType > class GlobalMinimizer : private boost::noncopyable { public: typedef details::ConvexHullMap<CoordinateType,EnergyType> HullMapType; private: HullMapType hull_map; std::vector<FacetType> candidate_facets; mutable logger class_log; public: /* * The type definitions here get a bit intense. We do this so we keep our * global minimization code flexible and extensible. By farming out pieces of the * process to functors, we retain the ability to swap out and try different sampling * methods, minimization methods, etc., without modifying the class definition. */ typedef typename HullMapType::PointType PointType; typedef typename HullMapType::GlobalPointType GlobalPointType; typedef std::function<EnergyType(PointType const&)> CalculateEnergyFunctor; typedef std::function<double(const std::size_t, const std::size_t)> CalculateGlobalEnergyFunctor; typedef std::function<std::vector<PointType>(CompositionSet const&, sublattice_set const&, evalconditions const&)> PointSampleFunctor; typedef std::function<std::vector<PointType>(std::vector<PointType> const&, std::set<std::size_t> const&, CalculateEnergyFunctor const&)> InternalHullFunctor; typedef std::function<std::vector<FacetType>(std::vector<PointType> const&, CalculateGlobalEnergyFunctor const&)> GlobalHullFunctor; /* GlobalMinimizer works by taking the phase information for the system and a * list of functors that implement point sampling and convex hull calculation. * Once GlobalMinimizer is constructed, the user can filter against the calculated grid. */ GlobalMinimizer ( std::map<std::string,CompositionSet> const &phase_list, sublattice_set const &sublset, evalconditions const& conditions, PointSampleFunctor &sample_points, InternalHullFunctor &phase_internal_hull, GlobalHullFunctor &global_hull ) { BOOST_LOG_NAMED_SCOPE ( "GlobalMinimizer::GlobalMinimizer" ); BOOST_LOG_CHANNEL_SEV ( class_log, "optimizer", debug ) << "enter ctor"; std::vector<PointType> temporary_hull_storage; for ( auto comp_set = phase_list.begin(); comp_set != phase_list.end(); ++comp_set ) { std::set<std::size_t> dependent_dimensions; std::size_t current_dependent_dimension = 0; // Determine the indices of the dependent dimensions boost::multi_index::index<sublattice_set,phase_subl>::type::iterator ic0,ic1; int sublindex = 0; ic0 = boost::multi_index::get<phase_subl> ( sublset ).lower_bound ( boost::make_tuple ( comp_set->first, sublindex ) ); ic1 = boost::multi_index::get<phase_subl> ( sublset ).upper_bound ( boost::make_tuple ( comp_set->first, sublindex ) ); while ( ic0 != ic1 ) { const std::size_t number_of_species = std::distance ( ic0,ic1 ); if ( number_of_species > 0 ) { // Last component is dependent dimension current_dependent_dimension += (number_of_species-1); dependent_dimensions.insert(current_dependent_dimension); ++current_dependent_dimension; } // Next sublattice ++sublindex; ic0 = boost::multi_index::get<phase_subl> ( sublset ).lower_bound ( boost::make_tuple ( comp_set->first, sublindex ) ); ic1 = boost::multi_index::get<phase_subl> ( sublset ).upper_bound ( boost::make_tuple ( comp_set->first, sublindex ) ); } // Sample the composition space of this phase auto phase_points = sample_points ( comp_set->second, sublset, conditions ); // Create a callback function for energy calculation for this phase auto calculate_energy = [comp_set,&conditions] (const PointType& point) { return comp_set->second.evaluate_objective(conditions,comp_set->second.get_variable_map(),const_cast<EnergyType*>(&point[0])); }; // Calculate the phase's internal convex hull and store the result auto phase_hull_points = phase_internal_hull ( phase_points, dependent_dimensions, calculate_energy ); // TODO: Apply phase-specific constraints to internal dof and globally // Add all points from this phase's convex hull to our internal hull map for ( auto point : phase_hull_points ) { // All points added to the hull_map could possibly be on the global hull auto global_point = convert_site_fractions_to_mole_fractions ( comp_set->first, sublset, point ); PointType ordered_global_point; ordered_global_point.reserve ( global_point.size()+1 ); for ( auto pt : global_point ) ordered_global_point.push_back ( pt.second ); double energy = calculate_energy ( point ); hull_map.insert_point ( comp_set->first, energy, point, global_point ); ordered_global_point.push_back ( energy ); temporary_hull_storage.push_back ( std::move ( ordered_global_point ) ); } } // Calculate the "true energy" of the midpoint of two points, based on their IDs // If the phases are distinct, the "true energy" is infinite (indicates true line) auto calculate_global_midpoint_energy = [this,&conditions,&phase_list] (const std::size_t point1_id, const std::size_t point2_id) { BOOST_ASSERT ( point1_id < hull_map.size() ); BOOST_ASSERT ( point2_id < hull_map.size() ); if ( point1_id == point2_id) return hull_map[point1_id].energy; if (hull_map[point1_id].phase_name != hull_map[point2_id].phase_name) { // Can't calculate a "true energy" if the tie points are different phases return std::numeric_limits<EnergyType>::max(); } // Return the energy of the average of the internal degrees of freedom else { PointType midpoint ( hull_map[point1_id].internal_coordinates ); PointType point2 ( hull_map[point2_id].internal_coordinates ); auto current_comp_set = phase_list.find ( hull_map[point1_id].phase_name ); std::transform ( point2.begin(), point2.end(), midpoint.begin(), midpoint.begin(), std::plus<EnergyType>() ); // sum points together for (auto &coord : midpoint) coord /= 2; // divide by two auto calculate_energy = [&] (const PointType& point) { return current_comp_set->second.evaluate_objective(conditions,current_comp_set->second.get_variable_map(),const_cast<EnergyType*>(&point[0])); }; return calculate_energy ( midpoint ); } }; // TODO: Add points and set options related to activity constraints here // Determine the facets on the global convex hull of all phase's energy landscapes candidate_facets = global_hull ( temporary_hull_storage, calculate_global_midpoint_energy ); BOOST_LOG_SEV ( class_log, debug ) << "candidate_facets.size() = " << candidate_facets.size(); } std::vector<typename HullMapType::HullEntryType> find_tie_points ( evalconditions const& conditions, const std::size_t critical_edge_length ) { BOOST_LOG_NAMED_SCOPE ( "GlobalMinimizer::find_tie_points" ); // Filter candidate facets based on user-specified constraints std::set<std::size_t> candidate_ids; // ensures returned points are unique std::vector<typename HullMapType::HullEntryType> candidates; BOOST_LOG_SEV ( class_log, debug ) << "candidate_facets.size() = " << candidate_facets.size(); for ( auto facet : candidate_facets ) { BOOST_LOG_SEV ( class_log, debug ) << "facet.vertices.size() = " << facet.vertices.size(); bool failed_conditions = false; for ( auto species : conditions.xfrac ) { BOOST_LOG_SEV ( class_log, debug ) << "check conditions: X(" << species.first << ") = " << species.second; double min_extent = 1, max_extent = 0; // extents of this coordinate for ( auto point = facet.vertices.begin(); point != facet.vertices.end(); ++point ) { const std::size_t point_id = *point; auto point_entry = hull_map [ point_id ]; auto point_coordinate = point_entry.global_coordinates [ species.first ]; //BOOST_LOG_SEV ( class_log, debug ) << "point_coordinate = " << point_coordinate; min_extent = std::min ( min_extent, point_coordinate ); max_extent = std::max ( max_extent, point_coordinate ); } //BOOST_LOG_SEV ( class_log, debug ) << "min_extent = " << min_extent; //BOOST_LOG_SEV ( class_log, debug ) << "max_extent = " << max_extent; if ( species.second >= min_extent && species.second <= max_extent ) { //BOOST_LOG_SEV ( class_log, debug ) << "conditions passed"; } else { //BOOST_LOG_SEV ( class_log, debug ) << "conditions failed"; failed_conditions = true; break; } } if (!failed_conditions) { std::stringstream logbuf; logbuf << "Candidate facet "; for ( auto point : facet.vertices ) { const std::size_t point_id = point; auto point_entry = hull_map [ point_id ]; logbuf << "["; for ( auto coord : point_entry.internal_coordinates ) { logbuf << coord << ","; } logbuf << "]"; logbuf << "{"; for ( auto coord : point_entry.global_coordinates ) { logbuf << coord.first << ":" << coord.second << ","; } logbuf << "}"; } BOOST_LOG_SEV ( class_log, debug ) << logbuf.str(); // this facet satisfies all the conditions; return it for_each_pair (facet.vertices.begin(), facet.vertices.end(), [this,&candidate_ids,critical_edge_length]( decltype( facet.vertices.begin() ) point1, decltype( facet.vertices.begin() ) point2 ) { const std::size_t point1_id = *point1; const std::size_t point2_id = *point2; auto point1_entry = hull_map [ point1_id ]; auto point2_entry = hull_map [ point2_id ]; if ( point1_entry.phase_name != point2_entry.phase_name ) { // phases differ; definitely a tie line candidate_ids.insert ( point1_id ); candidate_ids.insert ( point2_id ); } else { // phases are the same -- does a tie line span a miscibility gap? // use internal coordinates to check CoordinateType distance = 0; auto difference = point2_entry.internal_coordinates ; auto diff_iter = difference.begin(); for ( auto coord : point1_entry.internal_coordinates ) { *(diff_iter++) -= coord; } for (auto coord : difference) distance += std::pow(coord,2); if (distance > critical_edge_length) { // the tie line is sufficiently long candidate_ids.insert ( point1_id ); candidate_ids.insert ( point2_id ); } // Not a tie line; just add one point to ensure the phase appears else { candidate_ids.insert ( point1_id ); } } }); } } for (auto point_id : candidate_ids) { candidates.push_back ( hull_map [ point_id ] ); } return std::move( candidates ); } }; } //namespace Optimizer #endif<commit_msg>Increase verbosity of logging for facet filter.<commit_after>/*============================================================================= Copyright (c) 2012-2014 Richard Otis Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // Declarations for global minimization of a thermodynamic potential #ifndef INCLUDED_GLOBAL_MINIMIZATION #define INCLUDED_GLOBAL_MINIMIZATION #include "libgibbs/include/compositionset.hpp" #include "libgibbs/include/models.hpp" #include "libgibbs/include/optimizer/utils/hull_mapping.hpp" #include "libgibbs/include/utils/for_each_pair.hpp" #include "libgibbs/include/utils/site_fraction_convert.hpp" #include "libtdb/include/logging.hpp" #include <boost/assert.hpp> #include <boost/noncopyable.hpp> #include <functional> #include <list> #include <limits> #include <set> namespace Optimizer { /* GlobalMinimizer performs global minimization of the specified * thermodynamic potential. Energy manifolds are calculated for * all phases in the global composition space and each phase's * internal degrees of freedom. Constraints can be added incrementally * to identify the equilibrium tie hyperplane and fix a position in it. */ template < typename FacetType, typename CoordinateType = double, typename EnergyType = CoordinateType > class GlobalMinimizer : private boost::noncopyable { public: typedef details::ConvexHullMap<CoordinateType,EnergyType> HullMapType; private: HullMapType hull_map; std::vector<FacetType> candidate_facets; mutable logger class_log; public: /* * The type definitions here get a bit intense. We do this so we keep our * global minimization code flexible and extensible. By farming out pieces of the * process to functors, we retain the ability to swap out and try different sampling * methods, minimization methods, etc., without modifying the class definition. */ typedef typename HullMapType::PointType PointType; typedef typename HullMapType::GlobalPointType GlobalPointType; typedef std::function<EnergyType(PointType const&)> CalculateEnergyFunctor; typedef std::function<double(const std::size_t, const std::size_t)> CalculateGlobalEnergyFunctor; typedef std::function<std::vector<PointType>(CompositionSet const&, sublattice_set const&, evalconditions const&)> PointSampleFunctor; typedef std::function<std::vector<PointType>(std::vector<PointType> const&, std::set<std::size_t> const&, CalculateEnergyFunctor const&)> InternalHullFunctor; typedef std::function<std::vector<FacetType>(std::vector<PointType> const&, CalculateGlobalEnergyFunctor const&)> GlobalHullFunctor; /* GlobalMinimizer works by taking the phase information for the system and a * list of functors that implement point sampling and convex hull calculation. * Once GlobalMinimizer is constructed, the user can filter against the calculated grid. */ GlobalMinimizer ( std::map<std::string,CompositionSet> const &phase_list, sublattice_set const &sublset, evalconditions const& conditions, PointSampleFunctor &sample_points, InternalHullFunctor &phase_internal_hull, GlobalHullFunctor &global_hull ) { BOOST_LOG_NAMED_SCOPE ( "GlobalMinimizer::GlobalMinimizer" ); BOOST_LOG_CHANNEL_SEV ( class_log, "optimizer", debug ) << "enter ctor"; std::vector<PointType> temporary_hull_storage; for ( auto comp_set = phase_list.begin(); comp_set != phase_list.end(); ++comp_set ) { std::set<std::size_t> dependent_dimensions; std::size_t current_dependent_dimension = 0; // Determine the indices of the dependent dimensions boost::multi_index::index<sublattice_set,phase_subl>::type::iterator ic0,ic1; int sublindex = 0; ic0 = boost::multi_index::get<phase_subl> ( sublset ).lower_bound ( boost::make_tuple ( comp_set->first, sublindex ) ); ic1 = boost::multi_index::get<phase_subl> ( sublset ).upper_bound ( boost::make_tuple ( comp_set->first, sublindex ) ); while ( ic0 != ic1 ) { const std::size_t number_of_species = std::distance ( ic0,ic1 ); if ( number_of_species > 0 ) { // Last component is dependent dimension current_dependent_dimension += (number_of_species-1); dependent_dimensions.insert(current_dependent_dimension); ++current_dependent_dimension; } // Next sublattice ++sublindex; ic0 = boost::multi_index::get<phase_subl> ( sublset ).lower_bound ( boost::make_tuple ( comp_set->first, sublindex ) ); ic1 = boost::multi_index::get<phase_subl> ( sublset ).upper_bound ( boost::make_tuple ( comp_set->first, sublindex ) ); } // Sample the composition space of this phase auto phase_points = sample_points ( comp_set->second, sublset, conditions ); // Create a callback function for energy calculation for this phase auto calculate_energy = [comp_set,&conditions] (const PointType& point) { return comp_set->second.evaluate_objective(conditions,comp_set->second.get_variable_map(),const_cast<EnergyType*>(&point[0])); }; // Calculate the phase's internal convex hull and store the result auto phase_hull_points = phase_internal_hull ( phase_points, dependent_dimensions, calculate_energy ); // TODO: Apply phase-specific constraints to internal dof and globally // Add all points from this phase's convex hull to our internal hull map for ( auto point : phase_hull_points ) { // All points added to the hull_map could possibly be on the global hull auto global_point = convert_site_fractions_to_mole_fractions ( comp_set->first, sublset, point ); PointType ordered_global_point; ordered_global_point.reserve ( global_point.size()+1 ); for ( auto pt : global_point ) ordered_global_point.push_back ( pt.second ); double energy = calculate_energy ( point ); hull_map.insert_point ( comp_set->first, energy, point, global_point ); ordered_global_point.push_back ( energy ); temporary_hull_storage.push_back ( std::move ( ordered_global_point ) ); } } // Calculate the "true energy" of the midpoint of two points, based on their IDs // If the phases are distinct, the "true energy" is infinite (indicates true line) auto calculate_global_midpoint_energy = [this,&conditions,&phase_list] (const std::size_t point1_id, const std::size_t point2_id) { BOOST_ASSERT ( point1_id < hull_map.size() ); BOOST_ASSERT ( point2_id < hull_map.size() ); if ( point1_id == point2_id) return hull_map[point1_id].energy; if (hull_map[point1_id].phase_name != hull_map[point2_id].phase_name) { // Can't calculate a "true energy" if the tie points are different phases return std::numeric_limits<EnergyType>::max(); } // Return the energy of the average of the internal degrees of freedom else { PointType midpoint ( hull_map[point1_id].internal_coordinates ); PointType point2 ( hull_map[point2_id].internal_coordinates ); auto current_comp_set = phase_list.find ( hull_map[point1_id].phase_name ); std::transform ( point2.begin(), point2.end(), midpoint.begin(), midpoint.begin(), std::plus<EnergyType>() ); // sum points together for (auto &coord : midpoint) coord /= 2; // divide by two auto calculate_energy = [&] (const PointType& point) { return current_comp_set->second.evaluate_objective(conditions,current_comp_set->second.get_variable_map(),const_cast<EnergyType*>(&point[0])); }; return calculate_energy ( midpoint ); } }; // TODO: Add points and set options related to activity constraints here // Determine the facets on the global convex hull of all phase's energy landscapes candidate_facets = global_hull ( temporary_hull_storage, calculate_global_midpoint_energy ); BOOST_LOG_SEV ( class_log, debug ) << "candidate_facets.size() = " << candidate_facets.size(); } std::vector<typename HullMapType::HullEntryType> find_tie_points ( evalconditions const& conditions, const std::size_t critical_edge_length ) { BOOST_LOG_NAMED_SCOPE ( "GlobalMinimizer::find_tie_points" ); // Filter candidate facets based on user-specified constraints std::set<std::size_t> candidate_ids; // ensures returned points are unique std::vector<typename HullMapType::HullEntryType> candidates; BOOST_LOG_SEV ( class_log, debug ) << "candidate_facets.size() = " << candidate_facets.size(); for ( auto facet : candidate_facets ) { BOOST_LOG_SEV ( class_log, debug ) << "facet.vertices.size() = " << facet.vertices.size(); bool failed_conditions = false; for ( auto species : conditions.xfrac ) { BOOST_LOG_SEV ( class_log, debug ) << "check conditions: X(" << species.first << ") = " << species.second; double min_extent = 1, max_extent = 0; // extents of this coordinate for ( auto point = facet.vertices.begin(); point != facet.vertices.end(); ++point ) { const std::size_t point_id = *point; auto point_entry = hull_map [ point_id ]; auto point_coordinate = point_entry.global_coordinates [ species.first ]; BOOST_LOG_SEV ( class_log, debug ) << "point_coordinate = " << point_coordinate; min_extent = std::min ( min_extent, point_coordinate ); max_extent = std::max ( max_extent, point_coordinate ); } BOOST_LOG_SEV ( class_log, debug ) << "min_extent = " << min_extent; BOOST_LOG_SEV ( class_log, debug ) << "max_extent = " << max_extent; if ( species.second >= min_extent && species.second <= max_extent ) { BOOST_LOG_SEV ( class_log, debug ) << "conditions passed"; } else { BOOST_LOG_SEV ( class_log, debug ) << "conditions failed"; failed_conditions = true; break; } } if (!failed_conditions) { std::stringstream logbuf; logbuf << "Candidate facet "; for ( auto point : facet.vertices ) { const std::size_t point_id = point; auto point_entry = hull_map [ point_id ]; logbuf << "["; for ( auto coord : point_entry.internal_coordinates ) { logbuf << coord << ","; } logbuf << "]"; logbuf << "{"; for ( auto coord : point_entry.global_coordinates ) { logbuf << coord.first << ":" << coord.second << ","; } logbuf << "}"; } BOOST_LOG_SEV ( class_log, debug ) << logbuf.str(); // this facet satisfies all the conditions; return it for_each_pair (facet.vertices.begin(), facet.vertices.end(), [this,&candidate_ids,critical_edge_length]( decltype( facet.vertices.begin() ) point1, decltype( facet.vertices.begin() ) point2 ) { const std::size_t point1_id = *point1; const std::size_t point2_id = *point2; auto point1_entry = hull_map [ point1_id ]; auto point2_entry = hull_map [ point2_id ]; if ( point1_entry.phase_name != point2_entry.phase_name ) { // phases differ; definitely a tie line candidate_ids.insert ( point1_id ); candidate_ids.insert ( point2_id ); } else { // phases are the same -- does a tie line span a miscibility gap? // use internal coordinates to check CoordinateType distance = 0; auto difference = point2_entry.internal_coordinates ; auto diff_iter = difference.begin(); for ( auto coord : point1_entry.internal_coordinates ) { *(diff_iter++) -= coord; } for (auto coord : difference) distance += std::pow(coord,2); if (distance > critical_edge_length) { // the tie line is sufficiently long candidate_ids.insert ( point1_id ); candidate_ids.insert ( point2_id ); } // Not a tie line; just add one point to ensure the phase appears else { candidate_ids.insert ( point1_id ); } } }); } } for (auto point_id : candidate_ids) { candidates.push_back ( hull_map [ point_id ] ); } return std::move( candidates ); } }; } //namespace Optimizer #endif<|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/shell/platform/windows/flutter_windows_view.h" #include <comdef.h> #include <comutil.h> #include <oleacc.h> #include <iostream> #include <vector> #include "flutter/shell/platform/common/json_message_codec.h" #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/flutter_windows_texture_registrar.h" #include "flutter/shell/platform/windows/testing/engine_modifier.h" #include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h" #include "flutter/shell/platform/windows/testing/test_keyboard.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace flutter { namespace testing { constexpr uint64_t kScanCodeKeyA = 0x1e; constexpr uint64_t kVirtualKeyA = 0x41; namespace { // A struct to use as a FlutterPlatformMessageResponseHandle so it can keep the // callbacks and user data passed to the engine's // PlatformMessageCreateResponseHandle for use in the SendPlatformMessage // overridden function. struct TestResponseHandle { FlutterDesktopBinaryReply callback; void* user_data; }; static bool test_response = false; constexpr uint64_t kKeyEventFromChannel = 0x11; constexpr uint64_t kKeyEventFromEmbedder = 0x22; static std::vector<int> key_event_logs; std::unique_ptr<std::vector<uint8_t>> keyHandlingResponse(bool handled) { rapidjson::Document document; auto& allocator = document.GetAllocator(); document.SetObject(); document.AddMember("handled", test_response, allocator); return flutter::JsonMessageCodec::GetInstance().EncodeMessage(document); } // Returns an engine instance configured with dummy project path values, and // overridden methods for sending platform messages, so that the engine can // respond as if the framework were connected. std::unique_ptr<FlutterWindowsEngine> GetTestEngine() { FlutterDesktopEngineProperties properties = {}; properties.assets_path = L"C:\\foo\\flutter_assets"; properties.icu_data_path = L"C:\\foo\\icudtl.dat"; properties.aot_library_path = L"C:\\foo\\aot.so"; FlutterProjectBundle project(properties); auto engine = std::make_unique<FlutterWindowsEngine>(project); EngineModifier modifier(engine.get()); MockEmbedderApiForKeyboard( modifier, [] { key_event_logs.push_back(kKeyEventFromChannel); return test_response; }, [](const FlutterKeyEvent* event) { key_event_logs.push_back(kKeyEventFromEmbedder); return test_response; }); engine->RunWithEntrypoint(nullptr); return engine; } } // namespace TEST(FlutterWindowsViewTest, KeySequence) { std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine(); test_response = false; auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); FlutterWindowsView view(std::move(window_binding_handler)); view.SetEngine(std::move(engine)); view.OnKey(kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false); EXPECT_EQ(key_event_logs.size(), 2); EXPECT_EQ(key_event_logs[0], kKeyEventFromEmbedder); EXPECT_EQ(key_event_logs[1], kKeyEventFromChannel); key_event_logs.clear(); } TEST(FlutterWindowsViewTest, RestartClearsKeyboardState) { std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine(); auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); FlutterWindowsView view(std::move(window_binding_handler)); view.SetEngine(std::move(engine)); test_response = false; // Receives a KeyA down. Events are dispatched and decided unhandled. Now the // keyboard key handler is waiting for the redispatched event. view.OnKey(kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false); EXPECT_EQ(key_event_logs.size(), 2); EXPECT_EQ(key_event_logs[0], kKeyEventFromEmbedder); EXPECT_EQ(key_event_logs[1], kKeyEventFromChannel); key_event_logs.clear(); // Resets state so that the keyboard key handler is no longer waiting. view.OnPreEngineRestart(); // Receives another KeyA down. If the state had not been cleared, this event // will be considered the redispatched event and ignored. view.OnKey(kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false); EXPECT_EQ(key_event_logs.size(), 2); EXPECT_EQ(key_event_logs[0], kKeyEventFromEmbedder); EXPECT_EQ(key_event_logs[1], kKeyEventFromChannel); key_event_logs.clear(); } TEST(FlutterWindowsViewTest, EnableSemantics) { std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine(); EngineModifier modifier(engine.get()); bool semantics_enabled = false; modifier.embedder_api().UpdateSemanticsEnabled = MOCK_ENGINE_PROC( UpdateSemanticsEnabled, [&semantics_enabled](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) { semantics_enabled = enabled; return kSuccess; }); auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); FlutterWindowsView view(std::move(window_binding_handler)); view.SetEngine(std::move(engine)); view.OnUpdateSemanticsEnabled(true); EXPECT_TRUE(semantics_enabled); } TEST(FlutterWindowsEngine, AddSemanticsNodeUpdate) { std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine(); EngineModifier modifier(engine.get()); modifier.embedder_api().UpdateSemanticsEnabled = [](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) { return kSuccess; }; auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); FlutterWindowsView view(std::move(window_binding_handler)); view.SetEngine(std::move(engine)); // Enable semantics to instantiate accessibility bridge. view.OnUpdateSemanticsEnabled(true); auto bridge = view.GetEngine()->accessibility_bridge().lock(); ASSERT_TRUE(bridge); // Add root node. FlutterSemanticsNode node{sizeof(FlutterSemanticsNode), 0}; node.label = "name"; node.value = "value"; node.platform_view_id = -1; bridge->AddFlutterSemanticsNodeUpdate(&node); bridge->CommitUpdates(); // Look up the root windows node delegate. auto node_delegate = bridge ->GetFlutterPlatformNodeDelegateFromID( AccessibilityBridge::kRootNodeId) .lock(); ASSERT_TRUE(node_delegate); EXPECT_EQ(node_delegate->GetChildCount(), 0); // Get the native IAccessible object. IAccessible* native_view = node_delegate->GetNativeViewAccessible(); ASSERT_TRUE(native_view != nullptr); // Property lookups will be made against this node itself. VARIANT varchild{}; varchild.vt = VT_I4; varchild.lVal = CHILDID_SELF; // Verify node name matches our label. BSTR bname = nullptr; ASSERT_EQ(native_view->get_accName(varchild, &bname), S_OK); std::string name(_com_util::ConvertBSTRToString(bname)); EXPECT_EQ(name, "name"); // Verify node value matches. BSTR bvalue = nullptr; ASSERT_EQ(native_view->get_accValue(varchild, &bvalue), S_OK); std::string value(_com_util::ConvertBSTRToString(bvalue)); EXPECT_EQ(value, "value"); // Verify node type is a group. VARIANT varrole{}; varrole.vt = VT_I4; ASSERT_EQ(native_view->get_accRole(varchild, &varrole), S_OK); EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_STATICTEXT); } } // namespace testing } // namespace flutter <commit_msg>Win32: add test of native a11y tree nodes (#29993)<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/shell/platform/windows/flutter_windows_view.h" #include <comdef.h> #include <comutil.h> #include <oleacc.h> #include <iostream> #include <vector> #include "flutter/shell/platform/common/json_message_codec.h" #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/flutter_windows_texture_registrar.h" #include "flutter/shell/platform/windows/testing/engine_modifier.h" #include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h" #include "flutter/shell/platform/windows/testing/test_keyboard.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace flutter { namespace testing { constexpr uint64_t kScanCodeKeyA = 0x1e; constexpr uint64_t kVirtualKeyA = 0x41; namespace { // A struct to use as a FlutterPlatformMessageResponseHandle so it can keep the // callbacks and user data passed to the engine's // PlatformMessageCreateResponseHandle for use in the SendPlatformMessage // overridden function. struct TestResponseHandle { FlutterDesktopBinaryReply callback; void* user_data; }; static bool test_response = false; constexpr uint64_t kKeyEventFromChannel = 0x11; constexpr uint64_t kKeyEventFromEmbedder = 0x22; static std::vector<int> key_event_logs; std::unique_ptr<std::vector<uint8_t>> keyHandlingResponse(bool handled) { rapidjson::Document document; auto& allocator = document.GetAllocator(); document.SetObject(); document.AddMember("handled", test_response, allocator); return flutter::JsonMessageCodec::GetInstance().EncodeMessage(document); } // Returns an engine instance configured with dummy project path values, and // overridden methods for sending platform messages, so that the engine can // respond as if the framework were connected. std::unique_ptr<FlutterWindowsEngine> GetTestEngine() { FlutterDesktopEngineProperties properties = {}; properties.assets_path = L"C:\\foo\\flutter_assets"; properties.icu_data_path = L"C:\\foo\\icudtl.dat"; properties.aot_library_path = L"C:\\foo\\aot.so"; FlutterProjectBundle project(properties); auto engine = std::make_unique<FlutterWindowsEngine>(project); EngineModifier modifier(engine.get()); MockEmbedderApiForKeyboard( modifier, [] { key_event_logs.push_back(kKeyEventFromChannel); return test_response; }, [](const FlutterKeyEvent* event) { key_event_logs.push_back(kKeyEventFromEmbedder); return test_response; }); engine->RunWithEntrypoint(nullptr); return engine; } } // namespace TEST(FlutterWindowsViewTest, KeySequence) { std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine(); test_response = false; auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); FlutterWindowsView view(std::move(window_binding_handler)); view.SetEngine(std::move(engine)); view.OnKey(kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false); EXPECT_EQ(key_event_logs.size(), 2); EXPECT_EQ(key_event_logs[0], kKeyEventFromEmbedder); EXPECT_EQ(key_event_logs[1], kKeyEventFromChannel); key_event_logs.clear(); } TEST(FlutterWindowsViewTest, RestartClearsKeyboardState) { std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine(); auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); FlutterWindowsView view(std::move(window_binding_handler)); view.SetEngine(std::move(engine)); test_response = false; // Receives a KeyA down. Events are dispatched and decided unhandled. Now the // keyboard key handler is waiting for the redispatched event. view.OnKey(kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false); EXPECT_EQ(key_event_logs.size(), 2); EXPECT_EQ(key_event_logs[0], kKeyEventFromEmbedder); EXPECT_EQ(key_event_logs[1], kKeyEventFromChannel); key_event_logs.clear(); // Resets state so that the keyboard key handler is no longer waiting. view.OnPreEngineRestart(); // Receives another KeyA down. If the state had not been cleared, this event // will be considered the redispatched event and ignored. view.OnKey(kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false); EXPECT_EQ(key_event_logs.size(), 2); EXPECT_EQ(key_event_logs[0], kKeyEventFromEmbedder); EXPECT_EQ(key_event_logs[1], kKeyEventFromChannel); key_event_logs.clear(); } TEST(FlutterWindowsViewTest, EnableSemantics) { std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine(); EngineModifier modifier(engine.get()); bool semantics_enabled = false; modifier.embedder_api().UpdateSemanticsEnabled = MOCK_ENGINE_PROC( UpdateSemanticsEnabled, [&semantics_enabled](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) { semantics_enabled = enabled; return kSuccess; }); auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); FlutterWindowsView view(std::move(window_binding_handler)); view.SetEngine(std::move(engine)); view.OnUpdateSemanticsEnabled(true); EXPECT_TRUE(semantics_enabled); } TEST(FlutterWindowsEngine, AddSemanticsNodeUpdate) { std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine(); EngineModifier modifier(engine.get()); modifier.embedder_api().UpdateSemanticsEnabled = [](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) { return kSuccess; }; auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); FlutterWindowsView view(std::move(window_binding_handler)); view.SetEngine(std::move(engine)); // Enable semantics to instantiate accessibility bridge. view.OnUpdateSemanticsEnabled(true); auto bridge = view.GetEngine()->accessibility_bridge().lock(); ASSERT_TRUE(bridge); // Add root node. FlutterSemanticsNode node{sizeof(FlutterSemanticsNode), 0}; node.label = "name"; node.value = "value"; node.platform_view_id = -1; bridge->AddFlutterSemanticsNodeUpdate(&node); bridge->CommitUpdates(); // Look up the root windows node delegate. auto node_delegate = bridge ->GetFlutterPlatformNodeDelegateFromID( AccessibilityBridge::kRootNodeId) .lock(); ASSERT_TRUE(node_delegate); EXPECT_EQ(node_delegate->GetChildCount(), 0); // Get the native IAccessible object. IAccessible* native_view = node_delegate->GetNativeViewAccessible(); ASSERT_TRUE(native_view != nullptr); // Property lookups will be made against this node itself. VARIANT varchild{}; varchild.vt = VT_I4; varchild.lVal = CHILDID_SELF; // Verify node name matches our label. BSTR bname = nullptr; ASSERT_EQ(native_view->get_accName(varchild, &bname), S_OK); std::string name(_com_util::ConvertBSTRToString(bname)); EXPECT_EQ(name, "name"); // Verify node value matches. BSTR bvalue = nullptr; ASSERT_EQ(native_view->get_accValue(varchild, &bvalue), S_OK); std::string value(_com_util::ConvertBSTRToString(bvalue)); EXPECT_EQ(value, "value"); // Verify node type is static text. VARIANT varrole{}; varrole.vt = VT_I4; ASSERT_EQ(native_view->get_accRole(varchild, &varrole), S_OK); EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_STATICTEXT); } // Verify the native IAccessible COM object tree is an accurate reflection of // the platform-agnostic tree. Verify both a root node with children as well as // a non-root node with children, since the AX tree includes special handling // for the root. // // node0 // / \ // node1 node2 // | // node3 // // node0 and node2 are grouping nodes. node1 and node2 are static text nodes. TEST(FlutterWindowsEngine, AddSemanticsNodeUpdateWithChildren) { std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine(); EngineModifier modifier(engine.get()); modifier.embedder_api().UpdateSemanticsEnabled = [](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) { return kSuccess; }; auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); FlutterWindowsView view(std::move(window_binding_handler)); view.SetEngine(std::move(engine)); // Enable semantics to instantiate accessibility bridge. view.OnUpdateSemanticsEnabled(true); auto bridge = view.GetEngine()->accessibility_bridge().lock(); ASSERT_TRUE(bridge); // Add root node. FlutterSemanticsNode node0{sizeof(FlutterSemanticsNode), 0}; std::vector<int32_t> node0_children{1, 2}; node0.child_count = node0_children.size(); node0.children_in_traversal_order = node0_children.data(); node0.children_in_hit_test_order = node0_children.data(); FlutterSemanticsNode node1{sizeof(FlutterSemanticsNode), 1}; node1.label = "prefecture"; node1.value = "Kyoto"; FlutterSemanticsNode node2{sizeof(FlutterSemanticsNode), 2}; std::vector<int32_t> node2_children{3}; node2.child_count = node2_children.size(); node2.children_in_traversal_order = node2_children.data(); node2.children_in_hit_test_order = node2_children.data(); FlutterSemanticsNode node3{sizeof(FlutterSemanticsNode), 3}; node3.label = "city"; node3.value = "Uji"; bridge->AddFlutterSemanticsNodeUpdate(&node0); bridge->AddFlutterSemanticsNodeUpdate(&node1); bridge->AddFlutterSemanticsNodeUpdate(&node2); bridge->AddFlutterSemanticsNodeUpdate(&node3); bridge->CommitUpdates(); // Look up the root windows node delegate. auto node_delegate = bridge ->GetFlutterPlatformNodeDelegateFromID( AccessibilityBridge::kRootNodeId) .lock(); ASSERT_TRUE(node_delegate); EXPECT_EQ(node_delegate->GetChildCount(), 2); // Get the native IAccessible object. IAccessible* node0_accessible = node_delegate->GetNativeViewAccessible(); ASSERT_TRUE(node0_accessible != nullptr); // Property lookups will be made against this node itself. VARIANT varchild{}; varchild.vt = VT_I4; varchild.lVal = CHILDID_SELF; // Verify node type is a group. VARIANT varrole{}; varrole.vt = VT_I4; ASSERT_EQ(node0_accessible->get_accRole(varchild, &varrole), S_OK); EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_GROUPING); // Verify child count. long node0_child_count = 0; ASSERT_EQ(node0_accessible->get_accChildCount(&node0_child_count), S_OK); EXPECT_EQ(node0_child_count, 2); { // Look up first child of node0 (node1), a static text node. varchild.lVal = 1; IDispatch* node1_dispatch = nullptr; ASSERT_EQ(node0_accessible->get_accChild(varchild, &node1_dispatch), S_OK); ASSERT_TRUE(node1_dispatch != nullptr); IAccessible* node1_accessible = nullptr; ASSERT_EQ(node1_dispatch->QueryInterface( IID_IAccessible, reinterpret_cast<void**>(&node1_accessible)), S_OK); ASSERT_TRUE(node1_accessible != nullptr); // Verify node name matches our label. varchild.lVal = CHILDID_SELF; BSTR bname = nullptr; ASSERT_EQ(node1_accessible->get_accName(varchild, &bname), S_OK); std::string name(_com_util::ConvertBSTRToString(bname)); EXPECT_EQ(name, "prefecture"); // Verify node value matches. BSTR bvalue = nullptr; ASSERT_EQ(node1_accessible->get_accValue(varchild, &bvalue), S_OK); std::string value(_com_util::ConvertBSTRToString(bvalue)); EXPECT_EQ(value, "Kyoto"); // Verify node type is static text. VARIANT varrole{}; varrole.vt = VT_I4; ASSERT_EQ(node1_accessible->get_accRole(varchild, &varrole), S_OK); EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_STATICTEXT); // Verify the parent node is the root. IDispatch* parent_dispatch; node1_accessible->get_accParent(&parent_dispatch); IAccessible* parent_accessible; ASSERT_EQ( parent_dispatch->QueryInterface( IID_IAccessible, reinterpret_cast<void**>(&parent_accessible)), S_OK); EXPECT_EQ(parent_accessible, node0_accessible); } // Look up second child of node0 (node2), a parent group for node3. varchild.lVal = 2; IDispatch* node2_dispatch = nullptr; ASSERT_EQ(node0_accessible->get_accChild(varchild, &node2_dispatch), S_OK); ASSERT_TRUE(node2_dispatch != nullptr); IAccessible* node2_accessible = nullptr; ASSERT_EQ(node2_dispatch->QueryInterface( IID_IAccessible, reinterpret_cast<void**>(&node2_accessible)), S_OK); ASSERT_TRUE(node2_accessible != nullptr); { // Verify child count. long node2_child_count = 0; ASSERT_EQ(node2_accessible->get_accChildCount(&node2_child_count), S_OK); EXPECT_EQ(node2_child_count, 1); // Verify node type is static text. varchild.lVal = CHILDID_SELF; VARIANT varrole{}; varrole.vt = VT_I4; ASSERT_EQ(node2_accessible->get_accRole(varchild, &varrole), S_OK); EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_GROUPING); // Verify the parent node is the root. IDispatch* parent_dispatch; node2_accessible->get_accParent(&parent_dispatch); IAccessible* parent_accessible; ASSERT_EQ( parent_dispatch->QueryInterface( IID_IAccessible, reinterpret_cast<void**>(&parent_accessible)), S_OK); EXPECT_EQ(parent_accessible, node0_accessible); } { // Look up only child of node2 (node3), a static text node. varchild.lVal = 1; IDispatch* node3_dispatch = nullptr; ASSERT_EQ(node2_accessible->get_accChild(varchild, &node3_dispatch), S_OK); ASSERT_TRUE(node3_dispatch != nullptr); IAccessible* node3_accessible = nullptr; ASSERT_EQ(node3_dispatch->QueryInterface( IID_IAccessible, reinterpret_cast<void**>(&node3_accessible)), S_OK); ASSERT_TRUE(node3_accessible != nullptr); // Verify node name matches our label. varchild.lVal = CHILDID_SELF; BSTR bname = nullptr; ASSERT_EQ(node3_accessible->get_accName(varchild, &bname), S_OK); std::string name(_com_util::ConvertBSTRToString(bname)); EXPECT_EQ(name, "city"); // Verify node value matches. BSTR bvalue = nullptr; ASSERT_EQ(node3_accessible->get_accValue(varchild, &bvalue), S_OK); std::string value(_com_util::ConvertBSTRToString(bvalue)); EXPECT_EQ(value, "Uji"); // Verify node type is static text. VARIANT varrole{}; varrole.vt = VT_I4; ASSERT_EQ(node3_accessible->get_accRole(varchild, &varrole), S_OK); EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_STATICTEXT); // Verify the parent node is node2. IDispatch* parent_dispatch; node3_accessible->get_accParent(&parent_dispatch); IAccessible* parent_accessible; ASSERT_EQ( parent_dispatch->QueryInterface( IID_IAccessible, reinterpret_cast<void**>(&parent_accessible)), S_OK); EXPECT_EQ(parent_accessible, node2_accessible); } } } // namespace testing } // namespace flutter <|endoftext|>
<commit_before>/* Q Light Controller Plus gradient.cpp Copyright (c) Giorgio Rebecchi Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "gradient.h" #include <QImage> #include <QColor> #include <QPainter> #include <QLinearGradient> QImage Gradient::m_rgb = QImage(); QImage Gradient::getRGBGradient() { initialize(); return m_rgb; } QColor Gradient::getRGBColor(const quint32 x, const quint32 y) { initialize(); return QColor(m_rgb.pixel(qMin(x, (quint32)255), qMin(y,(quint32)255))); } void Gradient::fillWithGradient(int r, int g, int b, QPainter *painter, int x) { QColor top = Qt::black; QColor col(r, g , b); QColor bottom = Qt::white; QLinearGradient blackGrad(QPointF(0, 0), QPointF(0, 127)); blackGrad.setColorAt(0, top); blackGrad.setColorAt(1, col); QLinearGradient whiteGrad(QPointF(0, 128), QPointF(0, 255)); whiteGrad.setColorAt(0, col); whiteGrad.setColorAt(1, bottom); painter->fillRect(x, 0, x + 1, 128, blackGrad); painter->fillRect(x, 128, x + 1, 256, whiteGrad); } void Gradient::initialize() { if( m_rgb.isNull() == false ) return; m_rgb = QImage(256, 256, QImage::Format_RGB32); QPainter painter(&m_rgb); int x = 0; QList<int> baseColors; baseColors << 0xFF0000 << 0xFFFF00 << 0x00FF00 << 0x00FFFF << 0x0000FF << 0xFF00FF << 0xFF0000; for (int c = 0; c < 6; c++) { float r = (baseColors[c] >> 16) & 0x00FF; float g = (baseColors[c] >> 8) & 0x00FF; float b = baseColors[c] & 0x00FF; int nr = (baseColors[c + 1] >> 16) & 0x00FF; int ng = (baseColors[c + 1] >> 8) & 0x00FF; int nb = baseColors[c + 1] & 0x00FF; float rD = (nr - r) / 42; float gD = (ng - g) / 42; float bD = (nb - b) / 42; for (int i = x; i < x + 42; i++) { fillWithGradient(r, g, b, &painter, i); r+=rD; g+=gD; b+=bD; } x+=42; } } <commit_msg>Fix gradient rgb image width bug.<commit_after>/* Q Light Controller Plus gradient.cpp Copyright (c) Giorgio Rebecchi Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "gradient.h" #include <QImage> #include <QColor> #include <QPainter> #include <QLinearGradient> QImage Gradient::m_rgb = QImage(); QImage Gradient::getRGBGradient() { initialize(); return m_rgb; } QColor Gradient::getRGBColor(const quint32 x, const quint32 y) { initialize(); return QColor(m_rgb.pixel(qMin(x, (quint32)m_rgb.width ()-1), qMin(y,(quint32)m_rgb.height ()-1))); } void Gradient::fillWithGradient(int r, int g, int b, QPainter *painter, int x) { QColor top = Qt::black; QColor col(r, g , b); QColor bottom = Qt::white; QLinearGradient blackGrad(QPointF(0, 0), QPointF(0, 127)); blackGrad.setColorAt(0, top); blackGrad.setColorAt(1, col); QLinearGradient whiteGrad(QPointF(0, 128), QPointF(0, 255)); whiteGrad.setColorAt(0, col); whiteGrad.setColorAt(1, bottom); painter->fillRect(x, 0, x + 1, 128, blackGrad); painter->fillRect(x, 128, x + 1, 256, whiteGrad); } void Gradient::initialize() { if( m_rgb.isNull() == false ) return; m_rgb = QImage(256, 256, QImage::Format_RGB32); QPainter painter(&m_rgb); int x = 0; QList<int> baseColors; baseColors << 0xFF0000 << 0xFFFF00 << 0x00FF00 << 0x00FFFF << 0x0000FF << 0xFF00FF << 0xFF0000; for (int c = 0; c < 6; c++) { float r = (baseColors[c] >> 16) & 0x00FF; float g = (baseColors[c] >> 8) & 0x00FF; float b = baseColors[c] & 0x00FF; int nr = (baseColors[c + 1] >> 16) & 0x00FF; int ng = (baseColors[c + 1] >> 8) & 0x00FF; int nb = baseColors[c + 1] & 0x00FF; float rD = (nr - r) / 42; float gD = (ng - g) / 42; float bD = (nb - b) / 42; for (int i = x; i < x + 42; i++) { fillWithGradient(r, g, b, &painter, i); r+=rD; g+=gD; b+=bD; } x+=42; } } <|endoftext|>
<commit_before>// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 <string> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <ros/ros.h> #include <nodelet/nodelet.h> #include <image_transport/image_transport.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/Image.h> #include <cv_bridge/cv_bridge.h> #include <swri_image_util/image_normalization.h> #include <swri_math_util/math_util.h> namespace swri_image_util { class ContrastStretchNodelet : public nodelet::Nodelet { public: ContrastStretchNodelet() : bins_(8), max_min_(0.0), min_max_(0.0) { } ~ContrastStretchNodelet() { } void onInit() { ros::NodeHandle &node = getNodeHandle(); ros::NodeHandle &priv = getPrivateNodeHandle(); priv.param("bins", bins_, bins_); priv.param("max_min", max_min_, max_min_); priv.param("min_max", min_max_, min_max_); std::string mask; priv.param("mask", mask, std::string("")); if (!mask.empty()) { mask_ = cv::imread(mask, 0); } image_transport::ImageTransport it(node); image_pub_ = it.advertise("normalized_image", 1); image_sub_ = it.subscribe("image", 1, &ContrastStretchNodelet::ImageCallback, this); } void ImageCallback(const sensor_msgs::ImageConstPtr& image) { cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image); swri_image_util::ContrastStretch(bins_, cv_image->image, cv_image->image, mask_, max_min_, min_max_); image_pub_.publish(cv_image->toImageMsg()); } private: int32_t bins_; double max_min_; double min_max_; cv::Mat mask_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; }; } // Register nodelet plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_DECLARE_CLASS( swri_image_util, contrast_stretch, swri_image_util::ContrastStretchNodelet, nodelet::Nodelet) <commit_msg>Add parameters for masking out over exposed areas out of the contrast stretch processing.<commit_after>// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 <string> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <ros/ros.h> #include <nodelet/nodelet.h> #include <image_transport/image_transport.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/Image.h> #include <cv_bridge/cv_bridge.h> #include <swri_image_util/image_normalization.h> #include <swri_math_util/math_util.h> namespace swri_image_util { class ContrastStretchNodelet : public nodelet::Nodelet { public: ContrastStretchNodelet() : bins_(8), max_min_(0.0), min_max_(0.0), over_exposure_threshold_(255.0), over_exposure_dilation_(3) { } ~ContrastStretchNodelet() { } void onInit() { ros::NodeHandle &node = getNodeHandle(); ros::NodeHandle &priv = getPrivateNodeHandle(); priv.param("bins", bins_, bins_); priv.param("max_min", max_min_, max_min_); priv.param("min_max", min_max_, min_max_); priv.param("over_exposure_threshold", over_exposure_threshold_, over_exposure_threshold_); priv.param("over_exposure_dilation", over_exposure_dilation_, over_exposure_dilation_); std::string mask; priv.param("mask", mask, std::string("")); if (!mask.empty()) { mask_ = cv::imread(mask, 0); } image_transport::ImageTransport it(node); image_pub_ = it.advertise("normalized_image", 1); image_sub_ = it.subscribe("image", 1, &ContrastStretchNodelet::ImageCallback, this); } void ImageCallback(const sensor_msgs::ImageConstPtr& image) { cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image); cv::Mat mask; if (over_exposure_threshold_ < 255 && over_exposure_threshold_ > 0) { cv::Mat over_exposed = cv_image->image > over_exposure_threshold_; cv::Mat element = cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size(2 * over_exposure_dilation_ + 1, 2 * over_exposure_dilation_ + 1 ), cv::Point(over_exposure_dilation_, over_exposure_dilation_ )); cv::dilate(over_exposed, over_exposed, element); mask = mask_.clone(); mask.setTo(0, over_exposed); } else { mask = mask_; } swri_image_util::ContrastStretch(bins_, cv_image->image, cv_image->image, mask, max_min_, min_max_); image_pub_.publish(cv_image->toImageMsg()); } private: int32_t bins_; double max_min_; double min_max_; double over_exposure_threshold_; int32_t over_exposure_dilation_; cv::Mat mask_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; }; } // Register nodelet plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_DECLARE_CLASS( swri_image_util, contrast_stretch, swri_image_util::ContrastStretchNodelet, nodelet::Nodelet) <|endoftext|>
<commit_before>// Copyright (c) 2021 The Orbit 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 "Api/EnableInTracee.h" #include <absl/base/casts.h> #include <absl/container/flat_hash_map.h> #include <absl/strings/match.h> #include <functional> #include "Api/Orbit.h" #include "ObjectUtils/LinuxMap.h" #include "OrbitBase/ExecutablePath.h" #include "OrbitBase/Logging.h" #include "OrbitBase/UniqueResource.h" #include "UserSpaceInstrumentation/Attach.h" #include "UserSpaceInstrumentation/ExecuteInProcess.h" #include "UserSpaceInstrumentation/InjectLibraryInTracee.h" using orbit_grpc_protos::ApiFunction; using orbit_grpc_protos::CaptureOptions; using orbit_grpc_protos::ModuleInfo; using orbit_user_space_instrumentation::AttachAndStopProcess; using orbit_user_space_instrumentation::DetachAndContinueProcess; using orbit_user_space_instrumentation::DlopenInTracee; using orbit_user_space_instrumentation::DlsymInTracee; using orbit_user_space_instrumentation::ExecuteInProcess; namespace { ErrorMessageOr<absl::flat_hash_map<std::string, ModuleInfo>> GetModulesByPathForPid(int32_t pid) { OUTCOME_TRY(module_infos, orbit_object_utils::ReadModules(pid)); absl::flat_hash_map<std::string, ModuleInfo> result; for (ModuleInfo& module_info : module_infos) { result.emplace(module_info.file_path(), std::move(module_info)); } return result; } [[nodiscard]] const ModuleInfo* FindModuleInfoForApiFunction( const ApiFunction& api_function, const absl::flat_hash_map<std::string, ModuleInfo>& modules_by_path) { auto module_info_it = modules_by_path.find(api_function.module_path()); if (module_info_it == modules_by_path.end()) { ERROR("Could not find module \"%s\" when initializing Orbit Api.", api_function.module_path()); return nullptr; } const ModuleInfo& module_info = module_info_it->second; if (module_info.build_id() != api_function.module_build_id()) { ERROR("Build-id mismatch for \"%s\" when initializing Orbit Api", api_function.module_path()); return nullptr; } return &module_info; } ErrorMessageOr<std::string> GetLibOrbitPath() { // When packaged, liborbit.so is found alongside OrbitService. In development, it is found in // "../lib", relative to OrbitService. constexpr const char* kLibOrbitName = "liborbit.so"; const std::filesystem::path exe_dir = orbit_base::GetExecutableDir(); std::vector<std::filesystem::path> potential_paths = {exe_dir / kLibOrbitName, exe_dir / "../lib" / kLibOrbitName}; for (const auto& path : potential_paths) { if (std::filesystem::exists(path)) { return path; } } return ErrorMessage("Liborbit.so not found on system."); } ErrorMessageOr<void> SetApiEnabledInTracee(const CaptureOptions& capture_options, bool enabled) { SCOPED_TIMED_LOG("%s Api in tracee", enabled ? "Enabling" : "Disabling"); if (capture_options.api_functions().empty()) { return ErrorMessage("No api table to initialize."); } int32_t pid = capture_options.pid(); OUTCOME_TRY(AttachAndStopProcess(pid)); // Make sure we resume the target process, even on early-outs. orbit_base::unique_resource scope_exit{pid, [](int32_t pid) { if (DetachAndContinueProcess(pid).has_error()) { ERROR("Detaching from %i", pid); } }}; // Load liborbit.so and find api table initialization function. OUTCOME_TRY(liborbit_path, GetLibOrbitPath()); constexpr const char* kSetEnabledFunction = "orbit_api_set_enabled"; OUTCOME_TRY(handle, DlopenInTracee(pid, liborbit_path, RTLD_NOW)); OUTCOME_TRY(orbit_api_set_enabled_function, DlsymInTracee(pid, handle, kSetEnabledFunction)); // Initialize all api function tables. OUTCOME_TRY(modules_by_path, GetModulesByPathForPid(pid)); for (const ApiFunction& api_function : capture_options.api_functions()) { // Filter api functions. constexpr const char* kOrbitApiGetAddressPrefix = "orbit_api_get_function_table_address_v"; if (!absl::StrContains(api_function.name(), kOrbitApiGetAddressPrefix)) continue; // Get ModuleInfo associated with function. const ModuleInfo* module_info = FindModuleInfoForApiFunction(api_function, modules_by_path); if (module_info == nullptr) continue; // Get address of function table by calling "orbit_api_get_function_table_address_vN" in tracee. void* api_function_address = absl::bit_cast<void*>( module_info->address_start() + api_function.address() - module_info->load_bias()); OUTCOME_TRY(function_table_address, ExecuteInProcess(pid, api_function_address)); // Call "orbit_api_set_enabled" in tracee. OUTCOME_TRY(ExecuteInProcess(pid, orbit_api_set_enabled_function, function_table_address, api_function.api_version(), enabled ? 1 : 0)); } return outcome::success(); } } // namespace namespace orbit_api { ErrorMessageOr<void> EnableApiInTracee(const orbit_grpc_protos::CaptureOptions& capture_options) { return ::SetApiEnabledInTracee(capture_options, /*enabled*/ true); } ErrorMessageOr<void> DisableApiInTracee(const orbit_grpc_protos::CaptureOptions& capture_options) { return ::SetApiEnabledInTracee(capture_options, /*enabled*/ false); } } // namespace orbit_api <commit_msg>Don't report "No api table to initialize" as an error<commit_after>// Copyright (c) 2021 The Orbit 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 "Api/EnableInTracee.h" #include <absl/base/casts.h> #include <absl/container/flat_hash_map.h> #include <absl/strings/match.h> #include <functional> #include "Api/Orbit.h" #include "ObjectUtils/LinuxMap.h" #include "OrbitBase/ExecutablePath.h" #include "OrbitBase/Logging.h" #include "OrbitBase/UniqueResource.h" #include "UserSpaceInstrumentation/Attach.h" #include "UserSpaceInstrumentation/ExecuteInProcess.h" #include "UserSpaceInstrumentation/InjectLibraryInTracee.h" using orbit_grpc_protos::ApiFunction; using orbit_grpc_protos::CaptureOptions; using orbit_grpc_protos::ModuleInfo; using orbit_user_space_instrumentation::AttachAndStopProcess; using orbit_user_space_instrumentation::DetachAndContinueProcess; using orbit_user_space_instrumentation::DlopenInTracee; using orbit_user_space_instrumentation::DlsymInTracee; using orbit_user_space_instrumentation::ExecuteInProcess; namespace { ErrorMessageOr<absl::flat_hash_map<std::string, ModuleInfo>> GetModulesByPathForPid(int32_t pid) { OUTCOME_TRY(module_infos, orbit_object_utils::ReadModules(pid)); absl::flat_hash_map<std::string, ModuleInfo> result; for (ModuleInfo& module_info : module_infos) { result.emplace(module_info.file_path(), std::move(module_info)); } return result; } [[nodiscard]] const ModuleInfo* FindModuleInfoForApiFunction( const ApiFunction& api_function, const absl::flat_hash_map<std::string, ModuleInfo>& modules_by_path) { auto module_info_it = modules_by_path.find(api_function.module_path()); if (module_info_it == modules_by_path.end()) { ERROR("Could not find module \"%s\" when initializing Orbit Api.", api_function.module_path()); return nullptr; } const ModuleInfo& module_info = module_info_it->second; if (module_info.build_id() != api_function.module_build_id()) { ERROR("Build-id mismatch for \"%s\" when initializing Orbit Api", api_function.module_path()); return nullptr; } return &module_info; } ErrorMessageOr<std::string> GetLibOrbitPath() { // When packaged, liborbit.so is found alongside OrbitService. In development, it is found in // "../lib", relative to OrbitService. constexpr const char* kLibOrbitName = "liborbit.so"; const std::filesystem::path exe_dir = orbit_base::GetExecutableDir(); std::vector<std::filesystem::path> potential_paths = {exe_dir / kLibOrbitName, exe_dir / "../lib" / kLibOrbitName}; for (const auto& path : potential_paths) { if (std::filesystem::exists(path)) { return path; } } return ErrorMessage("Liborbit.so not found on system."); } ErrorMessageOr<void> SetApiEnabledInTracee(const CaptureOptions& capture_options, bool enabled) { SCOPED_TIMED_LOG("%s Api in tracee", enabled ? "Enabling" : "Disabling"); if (capture_options.api_functions().empty()) { LOG("No api table to initialize"); return outcome::success(); } int32_t pid = capture_options.pid(); OUTCOME_TRY(AttachAndStopProcess(pid)); // Make sure we resume the target process, even on early-outs. orbit_base::unique_resource scope_exit{pid, [](int32_t pid) { if (DetachAndContinueProcess(pid).has_error()) { ERROR("Detaching from %i", pid); } }}; // Load liborbit.so and find api table initialization function. OUTCOME_TRY(liborbit_path, GetLibOrbitPath()); constexpr const char* kSetEnabledFunction = "orbit_api_set_enabled"; OUTCOME_TRY(handle, DlopenInTracee(pid, liborbit_path, RTLD_NOW)); OUTCOME_TRY(orbit_api_set_enabled_function, DlsymInTracee(pid, handle, kSetEnabledFunction)); // Initialize all api function tables. OUTCOME_TRY(modules_by_path, GetModulesByPathForPid(pid)); for (const ApiFunction& api_function : capture_options.api_functions()) { // Filter api functions. constexpr const char* kOrbitApiGetAddressPrefix = "orbit_api_get_function_table_address_v"; if (!absl::StrContains(api_function.name(), kOrbitApiGetAddressPrefix)) continue; // Get ModuleInfo associated with function. const ModuleInfo* module_info = FindModuleInfoForApiFunction(api_function, modules_by_path); if (module_info == nullptr) continue; // Get address of function table by calling "orbit_api_get_function_table_address_vN" in tracee. void* api_function_address = absl::bit_cast<void*>( module_info->address_start() + api_function.address() - module_info->load_bias()); OUTCOME_TRY(function_table_address, ExecuteInProcess(pid, api_function_address)); // Call "orbit_api_set_enabled" in tracee. OUTCOME_TRY(ExecuteInProcess(pid, orbit_api_set_enabled_function, function_table_address, api_function.api_version(), enabled ? 1 : 0)); } return outcome::success(); } } // namespace namespace orbit_api { ErrorMessageOr<void> EnableApiInTracee(const orbit_grpc_protos::CaptureOptions& capture_options) { return ::SetApiEnabledInTracee(capture_options, /*enabled*/ true); } ErrorMessageOr<void> DisableApiInTracee(const orbit_grpc_protos::CaptureOptions& capture_options) { return ::SetApiEnabledInTracee(capture_options, /*enabled*/ false); } } // namespace orbit_api <|endoftext|>
<commit_before>#include <SofaValidation/Monitor.h> using sofa::component::misc::Monitor; #include <SofaBaseMechanics/MechanicalObject.h> using sofa::component::container::MechanicalObject; #include <SofaTest/Sofa_test.h> #include <SofaSimulationGraph/DAGSimulation.h> #include <sofa/simulation/Simulation.h> using sofa::core::objectmodel::BaseObject; using sofa::simulation::Simulation; using sofa::simulation::Node; #include <SofaSimulationCommon/SceneLoaderXML.h> using sofa::simulation::SceneLoaderXML; using sofa::core::ExecParams; #include <fstream> #include <streambuf> #include <string> #include <cstdio> namespace sofa { struct MonitorTest : public Monitor<Rigid3> { void testInit(MechanicalObject<Rigid3>* mo) { const Rigid3::VecCoord& i1 = *m_X; const Rigid3::VecCoord& i2 = mo->x.getValue(); EXPECT_TRUE(i1.size() == i2.size()); for (size_t i = 0; i < i1.size(); ++i) EXPECT_EQ(i1[i], i2[i]); } void testModif(MechanicalObject<Rigid3>* mo) { helper::vector<unsigned int> idx = d_indices.getValue(); const Rigid3::VecCoord& i1 = *m_X; const Rigid3::VecCoord& i2 = mo->x.getValue(); const Rigid3::VecDeriv& f1 = *m_F; const Rigid3::VecDeriv& f2 = mo->f.getValue(); const Rigid3::VecDeriv& v1 = *m_V; const Rigid3::VecDeriv& v2 = mo->v.getValue(); EXPECT_TRUE(idx.size() <= i2.size()); for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(i1[idx[i]], i2[idx[i]]); for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(f1[idx[i]], f2[idx[i]]); for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(v1[idx[i]], v2[idx[i]]); } }; struct Monitor_test : public sofa::Sofa_test<> { sofa::simulation::Node::SPtr root; sofa::simulation::SceneLoaderXML loader; MonitorTest* monitor; MechanicalObject<Rigid3>::SPtr mo; Monitor_test() {} void testInit() { // Checks that monitor gets the correct values at init monitor->testInit(mo.get()); } std::string readWholeFile(const std::string& fileName) { std::ifstream t(fileName); std::string str; EXPECT_TRUE(t.is_open()); t.seekg(0, std::ios::end); str.reserve(t.tellg()); t.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); return str; } void testModif() { std::string str_x = "# Gnuplot File : positions of 1 particle(s) Monitored\n# 1st Column : " "time, others : particle(s) number 0 \n1 -3.5 -12.4182 -3.5 0 0 " "0 1 \n2 -3.5 -29.4438 -3.5 0 0 0 1 \n3 -3.5 -53.8398 " "-3.5 0 0 0 1 \n4 -3.5 -84.9362 -3.5 0 0 0 1 \n5 -3.5 " "-122.124 -3.5 0 0 0 1 \n6 -3.5 -164.849 -3.5 0 0 0 1 " "\n7 " "-3.5 -212.608 -3.5 0 0 0 1 \n8 -3.5 -264.944 -3.5 0 0 0 " "1 " "\n9 -3.5 -321.44 -3.5 0 0 0 1 \n10 -3.5 -381.718 -3.5 0 0 " "0 1 \n"; std::string str_f = "# Gnuplot File : forces of 1 particle(s) Monitored\n# 1st Column : " "time, others : particle(s) number 0 \n1 0 -0.363333 0 0 0 " "0 " "\n2 0 -0.363333 0 0 0 0 \n3 0 -0.363333 0 0 0 0 " "\n4 " "0 -0.363333 0 0 0 0 \n5 0 -0.363333 0 0 0 0 \n6 0 " "-0.363333 0 0 0 0 \n7 0 -0.363333 0 0 0 0 \n8 0 " "-0.363333 0 0 0 0 \n9 0 -0.363333 0 0 0 0 \n10 0 " "-0.363333 0 0 0 0 \n"; std::string str_v = "# Gnuplot File : velocities of 1 particle(s) Monitored\n# 1st Column " ": time, others : particle(s) number 0 \n1 0 -8.91818 0 0 0 " "0 " "\n2 0 -17.0256 0 0 0 0 \n3 0 -24.396 0 0 0 0 " "\n4 " "0 -31.0964 0 0 0 0 \n5 0 -37.1876 0 0 0 0 \n6 0 " "-42.7251 0 0 0 0 \n7 0 -47.7592 0 0 0 0 \n8 0 " "-52.3356 0 0 0 0 \n9 0 -56.496 0 0 0 0 \n10 0 " "-60.2782 0 0 0 0 \n"; // make a few steps before checkinf if values are correctly updated in // Monitor for (int i = 0; i < 10; ++i) simulation::getSimulation()->animate(root.get(), 1.0); monitor->testModif(mo.get()); std::string s_x = readWholeFile(monitor->d_fileName.getFullPath() + "_x.txt"); std::string s_f = readWholeFile(monitor->d_fileName.getFullPath() + "_f.txt"); std::string s_v = readWholeFile(monitor->d_fileName.getFullPath() + "_v.txt"); EXPECT_EQ(s_x, str_x); EXPECT_EQ(s_f, str_f); EXPECT_EQ(s_v, str_v); std::remove(std::string(monitor->d_fileName.getFullPath() + "_x.txt").c_str()); std::remove(std::string(monitor->d_fileName.getFullPath() + "_f.txt").c_str()); std::remove(std::string(monitor->d_fileName.getFullPath() + "_v.txt").c_str()); } void SetUp() { std::string scene = "<Node name='root' gravity='0 -9.81 0'>" "<DefaultAnimationLoop/>" "<Node name='node'>" "<EulerImplicit rayleighStiffness='0' printLog='false' />" "<CGLinearSolver iterations='100' threshold='0.00000001' " "tolerance='1e-5'/>" "<MeshGmshLoader name='loader' filename='mesh/smCube27.msh' " "createSubelements='true' />" "<MechanicalObject template='Rigid3d' src='@loader' name='MO' />" "<Monitor template='Rigid3d' name='monitor' listening='1' indices='0' " "ExportPositions='true' ExportVelocities='true' ExportForces='true' />" "<UniformMass totalmass='1' />" "</Node>" "</Node>"; root = SceneLoaderXML::loadFromMemory("MonitorTest", scene.c_str(), scene.size()); root->init(sofa::core::ExecParams::defaultInstance()); std::string s = "/node/monitor"; Monitor<Rigid3>* ptr = NULL; ptr = root->get<Monitor<Rigid3> >(s); EXPECT_FALSE(ptr == NULL); monitor = reinterpret_cast<MonitorTest*>(ptr); EXPECT_FALSE(monitor == 0); root->get<MechanicalObject<Rigid3> >(mo, "/node/MO"); EXPECT_FALSE(mo == 0); } void TearDown() { } }; /// Checks whether the video is well loaded and 1st frame retrieved at init() TEST_F(Monitor_test, testInit) { this->testInit(); } TEST_F(Monitor_test, testModif) { this->testModif(); } } // namespace sofa <commit_msg>[SofaValidation] CLEAN Monitor_test indentation<commit_after>#include <SofaValidation/Monitor.h> using sofa::component::misc::Monitor; #include <SofaBaseMechanics/MechanicalObject.h> using sofa::component::container::MechanicalObject; #include <SofaTest/Sofa_test.h> #include <SofaSimulationGraph/DAGSimulation.h> #include <sofa/simulation/Simulation.h> using sofa::core::objectmodel::BaseObject; using sofa::simulation::Simulation; using sofa::simulation::Node; #include <SofaSimulationCommon/SceneLoaderXML.h> using sofa::simulation::SceneLoaderXML; using sofa::core::ExecParams; #include <fstream> #include <streambuf> #include <string> #include <cstdio> namespace sofa { struct MonitorTest : public Monitor<Rigid3> { void testInit(MechanicalObject<Rigid3>* mo) { const Rigid3::VecCoord& i1 = *m_X; const Rigid3::VecCoord& i2 = mo->x.getValue(); EXPECT_TRUE(i1.size() == i2.size()); for (size_t i = 0; i < i1.size(); ++i) EXPECT_EQ(i1[i], i2[i]); } void testModif(MechanicalObject<Rigid3>* mo) { helper::vector<unsigned int> idx = d_indices.getValue(); const Rigid3::VecCoord& i1 = *m_X; const Rigid3::VecCoord& i2 = mo->x.getValue(); const Rigid3::VecDeriv& f1 = *m_F; const Rigid3::VecDeriv& f2 = mo->f.getValue(); const Rigid3::VecDeriv& v1 = *m_V; const Rigid3::VecDeriv& v2 = mo->v.getValue(); EXPECT_TRUE(idx.size() <= i2.size()); for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(i1[idx[i]], i2[idx[i]]); for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(f1[idx[i]], f2[idx[i]]); for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(v1[idx[i]], v2[idx[i]]); } }; struct Monitor_test : public sofa::Sofa_test<> { sofa::simulation::Node::SPtr root; sofa::simulation::SceneLoaderXML loader; MonitorTest* monitor; MechanicalObject<Rigid3>::SPtr mo; Monitor_test() {} void testInit() { // Checks that monitor gets the correct values at init monitor->testInit(mo.get()); } std::string readWholeFile(const std::string& fileName) { std::ifstream t(fileName); std::string str; EXPECT_TRUE(t.is_open()); t.seekg(0, std::ios::end); str.reserve(t.tellg()); t.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); return str; } void testModif() { std::string str_x = "# Gnuplot File : positions of 1 particle(s) Monitored\n# 1st Column : " "time, others : particle(s) number 0 \n1 -3.5 -12.4182 -3.5 0 0 " "0 1 \n2 -3.5 -29.4438 -3.5 0 0 0 1 \n3 -3.5 -53.8398 " "-3.5 0 0 0 1 \n4 -3.5 -84.9362 -3.5 0 0 0 1 \n5 -3.5 " "-122.124 -3.5 0 0 0 1 \n6 -3.5 -164.849 -3.5 0 0 0 1 " "\n7 " "-3.5 -212.608 -3.5 0 0 0 1 \n8 -3.5 -264.944 -3.5 0 0 0 " "1 " "\n9 -3.5 -321.44 -3.5 0 0 0 1 \n10 -3.5 -381.718 -3.5 0 0 " "0 1 \n"; std::string str_f = "# Gnuplot File : forces of 1 particle(s) Monitored\n# 1st Column : " "time, others : particle(s) number 0 \n1 0 -0.363333 0 0 0 " "0 " "\n2 0 -0.363333 0 0 0 0 \n3 0 -0.363333 0 0 0 0 " "\n4 " "0 -0.363333 0 0 0 0 \n5 0 -0.363333 0 0 0 0 \n6 0 " "-0.363333 0 0 0 0 \n7 0 -0.363333 0 0 0 0 \n8 0 " "-0.363333 0 0 0 0 \n9 0 -0.363333 0 0 0 0 \n10 0 " "-0.363333 0 0 0 0 \n"; std::string str_v = "# Gnuplot File : velocities of 1 particle(s) Monitored\n# 1st Column " ": time, others : particle(s) number 0 \n1 0 -8.91818 0 0 0 " "0 " "\n2 0 -17.0256 0 0 0 0 \n3 0 -24.396 0 0 0 0 " "\n4 " "0 -31.0964 0 0 0 0 \n5 0 -37.1876 0 0 0 0 \n6 0 " "-42.7251 0 0 0 0 \n7 0 -47.7592 0 0 0 0 \n8 0 " "-52.3356 0 0 0 0 \n9 0 -56.496 0 0 0 0 \n10 0 " "-60.2782 0 0 0 0 \n"; // make a few steps before checkinf if values are correctly updated in // Monitor for (int i = 0; i < 10; ++i) simulation::getSimulation()->animate(root.get(), 1.0); monitor->testModif(mo.get()); std::string s_x = readWholeFile(monitor->d_fileName.getFullPath() + "_x.txt"); std::string s_f = readWholeFile(monitor->d_fileName.getFullPath() + "_f.txt"); std::string s_v = readWholeFile(monitor->d_fileName.getFullPath() + "_v.txt"); EXPECT_EQ(s_x, str_x); EXPECT_EQ(s_f, str_f); EXPECT_EQ(s_v, str_v); std::remove(std::string(monitor->d_fileName.getFullPath() + "_x.txt").c_str()); std::remove(std::string(monitor->d_fileName.getFullPath() + "_f.txt").c_str()); std::remove(std::string(monitor->d_fileName.getFullPath() + "_v.txt").c_str()); } void SetUp() { std::string scene = "<Node name='root' gravity='0 -9.81 0'>" "<DefaultAnimationLoop/>" "<Node name='node'>" "<EulerImplicit rayleighStiffness='0' printLog='false'/>" "<CGLinearSolver iterations='100' threshold='0.00000001' " "tolerance='1e-5'/>" "<MeshGmshLoader name='loader' filename='mesh/smCube27.msh' " "createSubelements='true' />" "<MechanicalObject template='Rigid3d' src='@loader' name='MO' />" "<Monitor template='Rigid3d' name='monitor' listening='1' indices='0' " "ExportPositions='true' ExportVelocities='true' ExportForces='true' />" "<UniformMass totalmass='1' />" "</Node>" "</Node>"; root = SceneLoaderXML::loadFromMemory("MonitorTest", scene.c_str(), scene.size()); root->init(sofa::core::ExecParams::defaultInstance()); std::string s = "/node/monitor"; Monitor<Rigid3>* ptr = NULL; ptr = root->get<Monitor<Rigid3> >(s); EXPECT_FALSE(ptr == NULL); monitor = reinterpret_cast<MonitorTest*>(ptr); EXPECT_FALSE(monitor == 0); root->get<MechanicalObject<Rigid3> >(mo, "/node/MO"); EXPECT_FALSE(mo == 0); } void TearDown() { } }; /// Checks whether the video is well loaded and 1st frame retrieved at init() TEST_F(Monitor_test, testInit) { this->testInit(); } TEST_F(Monitor_test, testModif) { this->testModif(); } } // namespace sofa <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: indexentrysupplier_ja_phonetic.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: khong $Date: 2002/06/18 22:29:26 $ * * 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): _______________________________________ * * ************************************************************************/ #define INDEXENTRYSUPPLIER_ja_phonetic #include <indexentrysupplier_asian.hxx> #include <data/indexdata_ja_phonetic.h> #include <strings.h> namespace com { namespace sun { namespace star { namespace i18n { rtl::OUString SAL_CALL IndexEntrySupplier_ja_phonetic::getIndexCharacter( const rtl::OUString& rIndexEntry, const lang::Locale& rLocale, const rtl::OUString& rSortAlgorithm ) throw (com::sun::star::uno::RuntimeException) { return IndexEntrySupplier_CJK::getIndexString(rIndexEntry.toChar(), idx, strstr(implementationName, "syllable") ? syllable : consonant); } rtl::OUString SAL_CALL IndexEntrySupplier_ja_phonetic::getIndexKey( const rtl::OUString& IndexEntry, const rtl::OUString& PhoneticEntry, const lang::Locale& rLocale ) throw (com::sun::star::uno::RuntimeException) { return IndexEntrySupplier_CJK::getIndexString( PhoneticEntry.getLength() > 0 ? PhoneticEntry.toChar() : IndexEntry.toChar(), idx, strstr(implementationName, "syllable") ? syllable : consonant); } sal_Int16 SAL_CALL IndexEntrySupplier_ja_phonetic::compareIndexEntry( const rtl::OUString& IndexEntry1, const rtl::OUString& PhoneticEntry1, const lang::Locale& rLocale1, const rtl::OUString& IndexEntry2, const rtl::OUString& PhoneticEntry2, const lang::Locale& rLocale2 ) throw (com::sun::star::uno::RuntimeException) { sal_Int16 result = collator->compareString( IndexEntrySupplier_ja_phonetic::getIndexKey(IndexEntry1, PhoneticEntry1, rLocale1), IndexEntrySupplier_ja_phonetic::getIndexKey(IndexEntry2, PhoneticEntry2, rLocale2)); if (result == 0) return collator->compareString( PhoneticEntry1.getLength() > 0 ? PhoneticEntry1 : IndexEntry1, PhoneticEntry2.getLength() > 0 ? PhoneticEntry2 : IndexEntry2); else return result; } static sal_Char first[] = "ja_phonetic_alphanumeric_first"; sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_first_by_syllable::loadAlgorithm( const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm, sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException) { aSortAlgorithm = SortAlgorithm; aLocale = rLocale; return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(first), rLocale, collatorOptions) == 0; } sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_first_by_consonant::loadAlgorithm( const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm, sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException) { aSortAlgorithm = SortAlgorithm; aLocale = rLocale; return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(first), rLocale, collatorOptions) == 0; } static sal_Char last[] = "ja_phonetic_alphanumeric_last"; sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_last_by_syllable::loadAlgorithm( const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm, sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException) { aSortAlgorithm = SortAlgorithm; aLocale = rLocale; return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(last), rLocale, collatorOptions) == 0; } sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_last_by_consonant::loadAlgorithm( const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm, sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException) { aSortAlgorithm = SortAlgorithm; aLocale = rLocale; return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(last), rLocale, collatorOptions) == 0; } } } } } <commit_msg>#100000# changed include file<commit_after>/************************************************************************* * * $RCSfile: indexentrysupplier_ja_phonetic.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $Date: 2002/07/25 04:38:11 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #define INDEXENTRYSUPPLIER_ja_phonetic #include <indexentrysupplier_asian.hxx> #include <data/indexdata_ja_phonetic.h> #include <string.h> namespace com { namespace sun { namespace star { namespace i18n { rtl::OUString SAL_CALL IndexEntrySupplier_ja_phonetic::getIndexCharacter( const rtl::OUString& rIndexEntry, const lang::Locale& rLocale, const rtl::OUString& rSortAlgorithm ) throw (com::sun::star::uno::RuntimeException) { return IndexEntrySupplier_CJK::getIndexString(rIndexEntry.toChar(), idx, strstr(implementationName, "syllable") ? syllable : consonant); } rtl::OUString SAL_CALL IndexEntrySupplier_ja_phonetic::getIndexKey( const rtl::OUString& IndexEntry, const rtl::OUString& PhoneticEntry, const lang::Locale& rLocale ) throw (com::sun::star::uno::RuntimeException) { return IndexEntrySupplier_CJK::getIndexString( PhoneticEntry.getLength() > 0 ? PhoneticEntry.toChar() : IndexEntry.toChar(), idx, strstr(implementationName, "syllable") ? syllable : consonant); } sal_Int16 SAL_CALL IndexEntrySupplier_ja_phonetic::compareIndexEntry( const rtl::OUString& IndexEntry1, const rtl::OUString& PhoneticEntry1, const lang::Locale& rLocale1, const rtl::OUString& IndexEntry2, const rtl::OUString& PhoneticEntry2, const lang::Locale& rLocale2 ) throw (com::sun::star::uno::RuntimeException) { sal_Int16 result = collator->compareString( IndexEntrySupplier_ja_phonetic::getIndexKey(IndexEntry1, PhoneticEntry1, rLocale1), IndexEntrySupplier_ja_phonetic::getIndexKey(IndexEntry2, PhoneticEntry2, rLocale2)); if (result == 0) return collator->compareString( PhoneticEntry1.getLength() > 0 ? PhoneticEntry1 : IndexEntry1, PhoneticEntry2.getLength() > 0 ? PhoneticEntry2 : IndexEntry2); else return result; } static sal_Char first[] = "ja_phonetic_alphanumeric_first"; sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_first_by_syllable::loadAlgorithm( const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm, sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException) { aSortAlgorithm = SortAlgorithm; aLocale = rLocale; return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(first), rLocale, collatorOptions) == 0; } sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_first_by_consonant::loadAlgorithm( const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm, sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException) { aSortAlgorithm = SortAlgorithm; aLocale = rLocale; return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(first), rLocale, collatorOptions) == 0; } static sal_Char last[] = "ja_phonetic_alphanumeric_last"; sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_last_by_syllable::loadAlgorithm( const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm, sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException) { aSortAlgorithm = SortAlgorithm; aLocale = rLocale; return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(last), rLocale, collatorOptions) == 0; } sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_last_by_consonant::loadAlgorithm( const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm, sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException) { aSortAlgorithm = SortAlgorithm; aLocale = rLocale; return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(last), rLocale, collatorOptions) == 0; } } } } } <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "OpenWireFormat.h" #include <decaf/lang/Boolean.h> #include <decaf/lang/Integer.h> #include <decaf/lang/Long.h> #include <decaf/util/UUID.h> #include <decaf/lang/Math.h> #include <decaf/io/ByteArrayOutputStream.h> #include <activemq/wireformat/openwire/OpenWireFormatNegotiator.h> #include <activemq/wireformat/openwire/utils/BooleanStream.h> #include <activemq/wireformat/MarshalAware.h> #include <activemq/commands/WireFormatInfo.h> #include <activemq/commands/DataStructure.h> #include <activemq/wireformat/openwire/marshal/DataStreamMarshaller.h> #include <activemq/wireformat/openwire/marshal/v3/MarshallerFactory.h> #include <activemq/wireformat/openwire/marshal/v2/MarshallerFactory.h> #include <activemq/wireformat/openwire/marshal/v1/MarshallerFactory.h> #include <activemq/exceptions/ActiveMQException.h> using namespace std; using namespace activemq; using namespace activemq::util; using namespace activemq::commands; using namespace activemq::transport; using namespace activemq::exceptions; using namespace activemq::wireformat; using namespace activemq::wireformat::openwire; using namespace activemq::wireformat::openwire::marshal; using namespace activemq::wireformat::openwire::utils; using namespace decaf::io; using namespace decaf::util; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// const unsigned char OpenWireFormat::NULL_TYPE = 0; //////////////////////////////////////////////////////////////////////////////// OpenWireFormat::OpenWireFormat( const decaf::util::Properties& properties ) { // Copy config data this->properties.copy( &properties ); // Fill in that DataStreamMarshallers collection this->dataMarshallers.resize( 256 ); // Generate an ID this->id = UUID::randomUUID().toString(); // Set defaults for initial WireFormat negotiation this->version = 0; this->stackTraceEnabled = false; this->cacheEnabled = false; this->tcpNoDelayEnabled = false; this->tightEncodingEnabled = false; this->sizePrefixDisabled = false; // Set to Default as lowest common denominator, then we will try // and move up to the preferred when the wireformat is negotiated. this->setVersion( DEFAULT_VERSION ); } //////////////////////////////////////////////////////////////////////////////// OpenWireFormat::~OpenWireFormat() { try { this->destroyMarshalers(); } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// WireFormatNegotiator* OpenWireFormat::createNegotiator( transport::Transport* transport ) throw( decaf::lang::exceptions::UnsupportedOperationException ) { try{ return new OpenWireFormatNegotiator( this, transport, false ); } AMQ_CATCH_RETHROW( UnsupportedOperationException ) AMQ_CATCHALL_THROW( UnsupportedOperationException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::destroyMarshalers() { try { for( size_t i = 0; i < dataMarshallers.size(); ++i ) { delete dataMarshallers[i]; dataMarshallers[i] = NULL; } } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::setVersion( int version ) throw ( IllegalArgumentException ) { try{ if( version == this->getVersion() ){ return; } // Clear old marshalers in preparation for the new set. this->destroyMarshalers(); this->version = version; switch( this->version ){ case 1: v1::MarshallerFactory().configure( this ); break; case 2: v2::MarshallerFactory().configure( this ); break; case 3: v3::MarshallerFactory().configure( this ); break; default: throw IllegalArgumentException( __FILE__, __LINE__, "OpenWireFormat::setVersion - " "Given Version: %d , is not supported", version ); } } AMQ_CATCH_RETHROW( IllegalArgumentException ) AMQ_CATCHALL_THROW( IllegalArgumentException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::addMarshaller( DataStreamMarshaller* marshaller ) { unsigned char type = marshaller->getDataStructureType(); dataMarshallers[type & 0xFF] = marshaller; } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::setPreferedWireFormatInfo( commands::WireFormatInfo* info ) throw ( IllegalStateException ) { this->preferedWireFormatInfo.reset( info ); } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::marshal( commands::Command* command, decaf::io::DataOutputStream* dataOut ) throw ( decaf::io::IOException ) { try { int size = 1; if( command != NULL ) { DataStructure* dataStructure = dynamic_cast< DataStructure* >( command ); unsigned char type = dataStructure->getDataStructureType(); DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } if( tightEncodingEnabled ) { BooleanStream bs; size += dsm->tightMarshal1( this, dataStructure, &bs ); size += bs.marshalledSize(); if( !sizePrefixDisabled ) { dataOut->writeInt( size ); } dataOut->writeByte( type ); bs.marshal( dataOut ); dsm->tightMarshal2( this, dataStructure, dataOut, &bs ); } else { DataOutputStream* looseOut = dataOut; ByteArrayOutputStream* baos = NULL; if( !sizePrefixDisabled ) { baos = new ByteArrayOutputStream(); looseOut = new DataOutputStream( baos ); } looseOut->writeByte( type ); dsm->looseMarshal( this, dataStructure, looseOut ); if( !sizePrefixDisabled ) { looseOut->close(); dataOut->writeInt( (int)baos->size() ); dataOut->write( baos->toByteArray(), 0, baos->size() ); // Delete allocated resource delete baos; delete looseOut; } } } else { dataOut->writeInt( size ); dataOut->writeByte( NULL_TYPE ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// commands::Command* OpenWireFormat::unmarshal( decaf::io::DataInputStream* dis ) throw ( decaf::io::IOException ) { try { if( !sizePrefixDisabled ) { dis->readInt(); } // Get the unmarshalled DataStructure DataStructure* data = doUnmarshal( dis ); if( data == NULL ) { throw IOException( __FILE__, __LINE__, "OpenWireFormat::doUnmarshal - " "Failed to unmarshal an Object" ); } // Now all unmarshals from this level should result in an object // that is a commands::Command type, if its not then we throw an // exception. commands::Command* command = dynamic_cast< commands::Command* >( data ); if( command == NULL ) { delete data; throw IOException( __FILE__, __LINE__, "OpenWireFormat::doUnmarshal - " "Unmarshalled a non Command Type" ); } return command; } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// commands::DataStructure* OpenWireFormat::doUnmarshal( DataInputStream* dis ) throw ( IOException ) { try { unsigned char dataType = dis->readByte(); if( dataType != NULL_TYPE ) { DataStreamMarshaller* dsm = dynamic_cast< DataStreamMarshaller* >( dataMarshallers[dataType & 0xFF] ); if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } // Ask the DataStreamMarshaller to create a new instance of its // command so that we can fill in its data. DataStructure* data = dsm->createObject(); if( this->tightEncodingEnabled ) { BooleanStream bs; bs.unmarshal( dis ); dsm->tightUnmarshal( this, data, dis, &bs ); } else { dsm->looseUnmarshal( this, data, dis ); } return data; } return NULL; } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// int OpenWireFormat::tightMarshalNestedObject1( commands::DataStructure* object, utils::BooleanStream* bs ) throw ( decaf::io::IOException ) { try { bs->writeBoolean( object != NULL ); if( object == NULL ) { return 0; } if( object->isMarshalAware() ) { std::vector<unsigned char> sequence = object->getMarshaledForm(this); bs->writeBoolean( !sequence.empty() ); if( !sequence.empty() ) { return (int)(1 + sequence.size()); } } unsigned char type = object->getDataStructureType(); if( type == 0 ) { throw IOException( __FILE__, __LINE__, "No valid data structure type for object of this type"); } DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } return 1 + dsm->tightMarshal1( this, object, bs ); } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::tightMarshalNestedObject2( DataStructure* o, DataOutputStream* ds, BooleanStream* bs ) throw ( IOException ) { try { if( !bs->readBoolean() ) { return; } unsigned char type = o->getDataStructureType(); ds->writeByte(type); if( o->isMarshalAware() && bs->readBoolean() ) { MarshalAware* ma = dynamic_cast< MarshalAware* >( o ); vector<unsigned char> sequence = ma->getMarshaledForm( this ); ds->write( &sequence[0], 0, sequence.size() ); } else { DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } dsm->tightMarshal2( this, o, ds, bs ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// DataStructure* OpenWireFormat::tightUnmarshalNestedObject( DataInputStream* dis, BooleanStream* bs ) throw ( decaf::io::IOException ) { try { if( bs->readBoolean() ) { const unsigned char dataType = dis->readByte(); DataStreamMarshaller* dsm = dataMarshallers[dataType & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } DataStructure* data = dsm->createObject(); if( data->isMarshalAware() && bs->readBoolean() ) { dis->readInt(); dis->readByte(); BooleanStream bs2; bs2.unmarshal( dis ); dsm->tightUnmarshal( this, data, dis, &bs2 ); } else { dsm->tightUnmarshal( this, data, dis, bs ); } return data; } else { return NULL; } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// DataStructure* OpenWireFormat::looseUnmarshalNestedObject( decaf::io::DataInputStream* dis ) throw ( IOException ) { try{ if( dis->readBoolean() ) { unsigned char dataType = dis->readByte(); DataStreamMarshaller* dsm = dataMarshallers[dataType & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } DataStructure* data = dsm->createObject(); dsm->looseUnmarshal( this, data, dis ); return data; } else { return NULL; } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::looseMarshalNestedObject( commands::DataStructure* o, decaf::io::DataOutputStream* dataOut ) throw ( decaf::io::IOException ) { try{ dataOut->writeBoolean( o != NULL ); if( o != NULL ) { unsigned char dataType = o->getDataStructureType(); dataOut->writeByte( dataType ); DataStreamMarshaller* dsm = dataMarshallers[dataType & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } dsm->looseMarshal( this, o, dataOut ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::renegotiateWireFormat( WireFormatInfo* info ) throw ( IllegalStateException ) { if( preferedWireFormatInfo.get() == NULL ) { throw IllegalStateException( __FILE__, __LINE__, "OpenWireFormat::renegotiateWireFormat - " "Wireformat cannot not be renegotiated." ); } this->setVersion( Math::min( preferedWireFormatInfo->getVersion(), info->getVersion() ) ); this->stackTraceEnabled = info->isStackTraceEnabled() && preferedWireFormatInfo->isStackTraceEnabled(); this->tcpNoDelayEnabled = info->isTcpNoDelayEnabled() && preferedWireFormatInfo->isTcpNoDelayEnabled(); this->cacheEnabled = info->isCacheEnabled() && preferedWireFormatInfo->isCacheEnabled(); this->tightEncodingEnabled = info->isTightEncodingEnabled() && preferedWireFormatInfo->isTightEncodingEnabled(); this->sizePrefixDisabled = info->isSizePrefixDisabled() && preferedWireFormatInfo->isSizePrefixDisabled(); } <commit_msg>Fix some memory leaks<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "OpenWireFormat.h" #include <decaf/lang/Boolean.h> #include <decaf/lang/Integer.h> #include <decaf/lang/Long.h> #include <decaf/util/UUID.h> #include <decaf/lang/Math.h> #include <decaf/io/ByteArrayOutputStream.h> #include <activemq/wireformat/openwire/OpenWireFormatNegotiator.h> #include <activemq/wireformat/openwire/utils/BooleanStream.h> #include <activemq/wireformat/MarshalAware.h> #include <activemq/commands/WireFormatInfo.h> #include <activemq/commands/DataStructure.h> #include <activemq/wireformat/openwire/marshal/DataStreamMarshaller.h> #include <activemq/wireformat/openwire/marshal/v3/MarshallerFactory.h> #include <activemq/wireformat/openwire/marshal/v2/MarshallerFactory.h> #include <activemq/wireformat/openwire/marshal/v1/MarshallerFactory.h> #include <activemq/exceptions/ActiveMQException.h> using namespace std; using namespace activemq; using namespace activemq::util; using namespace activemq::commands; using namespace activemq::transport; using namespace activemq::exceptions; using namespace activemq::wireformat; using namespace activemq::wireformat::openwire; using namespace activemq::wireformat::openwire::marshal; using namespace activemq::wireformat::openwire::utils; using namespace decaf::io; using namespace decaf::util; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// const unsigned char OpenWireFormat::NULL_TYPE = 0; //////////////////////////////////////////////////////////////////////////////// OpenWireFormat::OpenWireFormat( const decaf::util::Properties& properties ) { // Copy config data this->properties.copy( &properties ); // Fill in that DataStreamMarshallers collection this->dataMarshallers.resize( 256 ); // Generate an ID this->id = UUID::randomUUID().toString(); // Set defaults for initial WireFormat negotiation this->version = 0; this->stackTraceEnabled = false; this->cacheEnabled = false; this->tcpNoDelayEnabled = false; this->tightEncodingEnabled = false; this->sizePrefixDisabled = false; // Set to Default as lowest common denominator, then we will try // and move up to the preferred when the wireformat is negotiated. this->setVersion( DEFAULT_VERSION ); } //////////////////////////////////////////////////////////////////////////////// OpenWireFormat::~OpenWireFormat() { try { this->destroyMarshalers(); } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// WireFormatNegotiator* OpenWireFormat::createNegotiator( transport::Transport* transport ) throw( decaf::lang::exceptions::UnsupportedOperationException ) { try{ return new OpenWireFormatNegotiator( this, transport, true ); } AMQ_CATCH_RETHROW( UnsupportedOperationException ) AMQ_CATCHALL_THROW( UnsupportedOperationException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::destroyMarshalers() { try { for( size_t i = 0; i < dataMarshallers.size(); ++i ) { delete dataMarshallers[i]; dataMarshallers[i] = NULL; } } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::setVersion( int version ) throw ( IllegalArgumentException ) { try{ if( version == this->getVersion() ){ return; } // Clear old marshalers in preparation for the new set. this->destroyMarshalers(); this->version = version; switch( this->version ){ case 1: v1::MarshallerFactory().configure( this ); break; case 2: v2::MarshallerFactory().configure( this ); break; case 3: v3::MarshallerFactory().configure( this ); break; default: throw IllegalArgumentException( __FILE__, __LINE__, "OpenWireFormat::setVersion - " "Given Version: %d , is not supported", version ); } } AMQ_CATCH_RETHROW( IllegalArgumentException ) AMQ_CATCHALL_THROW( IllegalArgumentException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::addMarshaller( DataStreamMarshaller* marshaller ) { unsigned char type = marshaller->getDataStructureType(); dataMarshallers[type & 0xFF] = marshaller; } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::setPreferedWireFormatInfo( commands::WireFormatInfo* info ) throw ( IllegalStateException ) { this->preferedWireFormatInfo.reset( info ); } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::marshal( commands::Command* command, decaf::io::DataOutputStream* dataOut ) throw ( decaf::io::IOException ) { try { int size = 1; if( command != NULL ) { DataStructure* dataStructure = dynamic_cast< DataStructure* >( command ); unsigned char type = dataStructure->getDataStructureType(); DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } if( tightEncodingEnabled ) { BooleanStream bs; size += dsm->tightMarshal1( this, dataStructure, &bs ); size += bs.marshalledSize(); if( !sizePrefixDisabled ) { dataOut->writeInt( size ); } dataOut->writeByte( type ); bs.marshal( dataOut ); dsm->tightMarshal2( this, dataStructure, dataOut, &bs ); } else { DataOutputStream* looseOut = dataOut; ByteArrayOutputStream* baos = NULL; if( !sizePrefixDisabled ) { baos = new ByteArrayOutputStream(); looseOut = new DataOutputStream( baos ); } looseOut->writeByte( type ); dsm->looseMarshal( this, dataStructure, looseOut ); if( !sizePrefixDisabled ) { looseOut->close(); dataOut->writeInt( (int)baos->size() ); dataOut->write( baos->toByteArray(), 0, baos->size() ); // Delete allocated resource delete baos; delete looseOut; } } } else { dataOut->writeInt( size ); dataOut->writeByte( NULL_TYPE ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// commands::Command* OpenWireFormat::unmarshal( decaf::io::DataInputStream* dis ) throw ( decaf::io::IOException ) { try { if( !sizePrefixDisabled ) { dis->readInt(); } // Get the unmarshalled DataStructure DataStructure* data = doUnmarshal( dis ); if( data == NULL ) { throw IOException( __FILE__, __LINE__, "OpenWireFormat::doUnmarshal - " "Failed to unmarshal an Object" ); } // Now all unmarshals from this level should result in an object // that is a commands::Command type, if its not then we throw an // exception. commands::Command* command = dynamic_cast< commands::Command* >( data ); if( command == NULL ) { delete data; throw IOException( __FILE__, __LINE__, "OpenWireFormat::doUnmarshal - " "Unmarshalled a non Command Type" ); } return command; } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// commands::DataStructure* OpenWireFormat::doUnmarshal( DataInputStream* dis ) throw ( IOException ) { try { unsigned char dataType = dis->readByte(); if( dataType != NULL_TYPE ) { DataStreamMarshaller* dsm = dynamic_cast< DataStreamMarshaller* >( dataMarshallers[dataType & 0xFF] ); if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } // Ask the DataStreamMarshaller to create a new instance of its // command so that we can fill in its data. DataStructure* data = dsm->createObject(); if( this->tightEncodingEnabled ) { BooleanStream bs; bs.unmarshal( dis ); dsm->tightUnmarshal( this, data, dis, &bs ); } else { dsm->looseUnmarshal( this, data, dis ); } return data; } return NULL; } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// int OpenWireFormat::tightMarshalNestedObject1( commands::DataStructure* object, utils::BooleanStream* bs ) throw ( decaf::io::IOException ) { try { bs->writeBoolean( object != NULL ); if( object == NULL ) { return 0; } if( object->isMarshalAware() ) { std::vector<unsigned char> sequence = object->getMarshaledForm(this); bs->writeBoolean( !sequence.empty() ); if( !sequence.empty() ) { return (int)(1 + sequence.size()); } } unsigned char type = object->getDataStructureType(); if( type == 0 ) { throw IOException( __FILE__, __LINE__, "No valid data structure type for object of this type"); } DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } return 1 + dsm->tightMarshal1( this, object, bs ); } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::tightMarshalNestedObject2( DataStructure* o, DataOutputStream* ds, BooleanStream* bs ) throw ( IOException ) { try { if( !bs->readBoolean() ) { return; } unsigned char type = o->getDataStructureType(); ds->writeByte(type); if( o->isMarshalAware() && bs->readBoolean() ) { MarshalAware* ma = dynamic_cast< MarshalAware* >( o ); vector<unsigned char> sequence = ma->getMarshaledForm( this ); ds->write( &sequence[0], 0, sequence.size() ); } else { DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } dsm->tightMarshal2( this, o, ds, bs ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// DataStructure* OpenWireFormat::tightUnmarshalNestedObject( DataInputStream* dis, BooleanStream* bs ) throw ( decaf::io::IOException ) { try { if( bs->readBoolean() ) { const unsigned char dataType = dis->readByte(); DataStreamMarshaller* dsm = dataMarshallers[dataType & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } DataStructure* data = dsm->createObject(); if( data->isMarshalAware() && bs->readBoolean() ) { dis->readInt(); dis->readByte(); BooleanStream bs2; bs2.unmarshal( dis ); dsm->tightUnmarshal( this, data, dis, &bs2 ); } else { dsm->tightUnmarshal( this, data, dis, bs ); } return data; } else { return NULL; } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// DataStructure* OpenWireFormat::looseUnmarshalNestedObject( decaf::io::DataInputStream* dis ) throw ( IOException ) { try{ if( dis->readBoolean() ) { unsigned char dataType = dis->readByte(); DataStreamMarshaller* dsm = dataMarshallers[dataType & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } DataStructure* data = dsm->createObject(); dsm->looseUnmarshal( this, data, dis ); return data; } else { return NULL; } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::looseMarshalNestedObject( commands::DataStructure* o, decaf::io::DataOutputStream* dataOut ) throw ( decaf::io::IOException ) { try{ dataOut->writeBoolean( o != NULL ); if( o != NULL ) { unsigned char dataType = o->getDataStructureType(); dataOut->writeByte( dataType ); DataStreamMarshaller* dsm = dataMarshallers[dataType & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } dsm->looseMarshal( this, o, dataOut ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::renegotiateWireFormat( WireFormatInfo* info ) throw ( IllegalStateException ) { if( preferedWireFormatInfo.get() == NULL ) { throw IllegalStateException( __FILE__, __LINE__, "OpenWireFormat::renegotiateWireFormat - " "Wireformat cannot not be renegotiated." ); } this->setVersion( Math::min( preferedWireFormatInfo->getVersion(), info->getVersion() ) ); this->stackTraceEnabled = info->isStackTraceEnabled() && preferedWireFormatInfo->isStackTraceEnabled(); this->tcpNoDelayEnabled = info->isTcpNoDelayEnabled() && preferedWireFormatInfo->isTcpNoDelayEnabled(); this->cacheEnabled = info->isCacheEnabled() && preferedWireFormatInfo->isCacheEnabled(); this->tightEncodingEnabled = info->isTightEncodingEnabled() && preferedWireFormatInfo->isTightEncodingEnabled(); this->sizePrefixDisabled = info->isSizePrefixDisabled() && preferedWireFormatInfo->isSizePrefixDisabled(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fuolbull.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-01-20 11:07:24 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "fuolbull.hxx" #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #ifndef _OUTLINER_HXX #include <svx/outliner.hxx> #endif #ifndef _EEITEM_HXX //autogen #include <svx/eeitem.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #include <svx/editdata.hxx> #include <svx/svxids.hrc> #ifndef SD_OUTLINE_VIEW_HXX #include "OutlineView.hxx" #endif #ifndef SD_OUTLINE_VIEW_SHELL_HXX #include "OutlineViewShell.hxx" #endif #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif #ifndef SD_OUTLINE_BULLET_DLG_HXX #include "OutlineBulletDlg.hxx" #endif #include "drawdoc.hxx" namespace sd { TYPEINIT1( FuOutlineBullet, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuOutlineBullet::FuOutlineBullet(ViewShell* pViewShell, ::sd::Window* pWindow, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewShell, pWindow, pView, pDoc, rReq) { const SfxItemSet* pArgs = rReq.GetArgs(); if( !pArgs ) { // ItemSet fuer Dialog fuellen SfxItemSet aEditAttr( pDoc->GetPool() ); pView->GetAttributes( aEditAttr ); SfxItemSet aNewAttr( pViewShell->GetPool(), EE_ITEMS_START, EE_ITEMS_END ); aNewAttr.Put( aEditAttr, FALSE ); // Dialog hochfahren und ausfuehren OutlineBulletDlg* pDlg = new OutlineBulletDlg( NULL, &aNewAttr, pView ); USHORT nResult = pDlg->Execute(); switch( nResult ) { case RET_OK: { SfxItemSet aSet( *pDlg->GetOutputItemSet() ); if (pView->ISA(DrawViewShell) && pView->GetMarkList().GetMarkCount() == 0) { SfxUInt16Item aBulletState( EE_PARA_BULLETSTATE, 0 ); aSet.Put(aBulletState); } rReq.Done( aSet ); pArgs = rReq.GetArgs(); } break; default: { delete pDlg; return; } } delete pDlg; } // nicht direkt an pOlView, damit SdDrawView::SetAttributes // Aenderungen auf der Masterpage abfangen und in eine // Vorlage umleiten kann pView->SetAttributes(*pArgs); // evtl. Betroffene Felder invalidieren pViewShell->Invalidate( FN_NUM_BULLET_ON ); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuOutlineBullet::~FuOutlineBullet() { } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuOutlineBullet::Activate() { FuPoor::Activate(); } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuOutlineBullet::Deactivate() { FuPoor::Deactivate(); } } // end of namespace sd <commit_msg>INTEGRATION: CWS dialogdiet01 (1.2.34); FILE MERGED 2004/04/22 02:01:32 mwu 1.2.34.1: dialogdiet01 m33 sd 20040422<commit_after>/************************************************************************* * * $RCSfile: fuolbull.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-05-10 15:47:39 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "fuolbull.hxx" #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #ifndef _OUTLINER_HXX #include <svx/outliner.hxx> #endif #ifndef _EEITEM_HXX //autogen #include <svx/eeitem.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #include <svx/editdata.hxx> #include <svx/svxids.hrc> #ifndef SD_OUTLINE_VIEW_HXX #include "OutlineView.hxx" #endif #ifndef SD_OUTLINE_VIEW_SHELL_HXX #include "OutlineViewShell.hxx" #endif #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif //CHINA001 #ifndef SD_OUTLINE_BULLET_DLG_HXX //CHINA001 #include "OutlineBulletDlg.hxx" //CHINA001 #endif #include "drawdoc.hxx" #include "sdabstdlg.hxx" //CHINA001 #include "dlgolbul.hrc" //CHINA001 namespace sd { TYPEINIT1( FuOutlineBullet, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuOutlineBullet::FuOutlineBullet(ViewShell* pViewShell, ::sd::Window* pWindow, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewShell, pWindow, pView, pDoc, rReq) { const SfxItemSet* pArgs = rReq.GetArgs(); if( !pArgs ) { // ItemSet fuer Dialog fuellen SfxItemSet aEditAttr( pDoc->GetPool() ); pView->GetAttributes( aEditAttr ); SfxItemSet aNewAttr( pViewShell->GetPool(), EE_ITEMS_START, EE_ITEMS_END ); aNewAttr.Put( aEditAttr, FALSE ); // Dialog hochfahren und ausfuehren //CHINA001 OutlineBulletDlg* pDlg = new OutlineBulletDlg( NULL, &aNewAttr, pView ); SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001 DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001 SfxAbstractTabDialog* pDlg = pFact->CreateSdItemSetTabDlg(ResId( TAB_OUTLINEBULLET ), NULL, &aNewAttr, pView ); DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001 USHORT nResult = pDlg->Execute(); switch( nResult ) { case RET_OK: { SfxItemSet aSet( *pDlg->GetOutputItemSet() ); if (pView->ISA(DrawViewShell) && pView->GetMarkList().GetMarkCount() == 0) { SfxUInt16Item aBulletState( EE_PARA_BULLETSTATE, 0 ); aSet.Put(aBulletState); } rReq.Done( aSet ); pArgs = rReq.GetArgs(); } break; default: { delete pDlg; return; } } delete pDlg; } // nicht direkt an pOlView, damit SdDrawView::SetAttributes // Aenderungen auf der Masterpage abfangen und in eine // Vorlage umleiten kann pView->SetAttributes(*pArgs); // evtl. Betroffene Felder invalidieren pViewShell->Invalidate( FN_NUM_BULLET_ON ); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuOutlineBullet::~FuOutlineBullet() { } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuOutlineBullet::Activate() { FuPoor::Activate(); } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuOutlineBullet::Deactivate() { FuPoor::Deactivate(); } } // end of namespace sd <|endoftext|>
<commit_before>// // FacebookRequestDelegate.cpp // ee_x_mobile_facebook // // Created by eps on 3/21/18. // #include "ee/facebook/internal/FacebookRequestDelegate.hpp" #include "ee/core/IMessageBridge.hpp" #include <ee/nlohmann/json.hpp> namespace ee { namespace facebook { using Self = RequestDelegate; namespace { std::string k__onSuccess(int tag) { return "FacebookRequestDelegate_onSuccess_" + std::to_string(tag); } std::string k__onFailure(int tag) { return "FacebookRequestDelegate_onFailure_" + std::to_string(tag); } std::string k__onCancel(int tag) { return "FacebookRequestDelegate_onCancel_" + std::to_string(tag); } } // namespace Self::RequestDelegate(IMessageBridge& bridge, int tag) : bridge_(bridge) , tag_(tag) { bridge_.registerHandler( [this](const std::string& message) { if (successCallback_) { auto json = nlohmann::json::parse(message); auto&& requestId = json["requestId"]; auto&& requestRecipients = json["requestRecipients"]; successCallback_(requestId, requestRecipients); } self_.reset(); return ""; }, k__onSuccess(tag_)); bridge_.registerHandler( [this](const std::string& message) { if (failureCallback_) { failureCallback_(message); } self_.reset(); return ""; }, k__onFailure(tag_)); bridge_.registerHandler( [this](const std::string& message) { if (cancelCallback_) { cancelCallback_(); } self_.reset(); return ""; }, k__onCancel(tag_)); } Self::~RequestDelegate() { bridge_.deregisterHandler(k__onSuccess(tag_)); bridge_.deregisterHandler(k__onFailure(tag_)); bridge_.deregisterHandler(k__onCancel(tag_)); } Self& Self::onSuccess(const SuccessCallback& callback) { successCallback_ = callback; return *this; } Self& Self::onFailure(const FailureCallback& callback) { failureCallback_ = callback; return *this; } Self& Self::onCancel(const CancelCallback& callback) { cancelCallback_ = callback; return *this; } } // namespace facebook } // namespace ee <commit_msg>Fix empty response ios.<commit_after>// // FacebookRequestDelegate.cpp // ee_x_mobile_facebook // // Created by eps on 3/21/18. // #include "ee/facebook/internal/FacebookRequestDelegate.hpp" #include "ee/core/IMessageBridge.hpp" #include <ee/nlohmann/json.hpp> namespace ee { namespace facebook { using Self = RequestDelegate; namespace { std::string k__onSuccess(int tag) { return "FacebookRequestDelegate_onSuccess_" + std::to_string(tag); } std::string k__onFailure(int tag) { return "FacebookRequestDelegate_onFailure_" + std::to_string(tag); } std::string k__onCancel(int tag) { return "FacebookRequestDelegate_onCancel_" + std::to_string(tag); } } // namespace Self::RequestDelegate(IMessageBridge& bridge, int tag) : bridge_(bridge) , tag_(tag) { bridge_.registerHandler( [this](const std::string& message) { if (successCallback_) { auto json = nlohmann::json::parse(message); auto&& requestId = json.value("requestId", std::string()); // Null iOS. auto&& requestRecipients = json.value("requestRecipients", std::vector<std::string>()); // Null iOS. successCallback_(requestId, requestRecipients); } self_.reset(); return ""; }, k__onSuccess(tag_)); bridge_.registerHandler( [this](const std::string& message) { if (failureCallback_) { failureCallback_(message); } self_.reset(); return ""; }, k__onFailure(tag_)); bridge_.registerHandler( [this](const std::string& message) { if (cancelCallback_) { cancelCallback_(); } self_.reset(); return ""; }, k__onCancel(tag_)); } Self::~RequestDelegate() { bridge_.deregisterHandler(k__onSuccess(tag_)); bridge_.deregisterHandler(k__onFailure(tag_)); bridge_.deregisterHandler(k__onCancel(tag_)); } Self& Self::onSuccess(const SuccessCallback& callback) { successCallback_ = callback; return *this; } Self& Self::onFailure(const FailureCallback& callback) { failureCallback_ = callback; return *this; } Self& Self::onCancel(const CancelCallback& callback) { cancelCallback_ = callback; return *this; } } // namespace facebook } // namespace ee <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include <config_folders.h> #include "odbcconfig.hxx" #ifdef SYSTEM_ODBC_HEADERS #include <sqltypes.h> #else #include <odbc/sqltypes.h> #endif #include <rtl/bootstrap.hxx> #include <rtl/ustring.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/process.h> #include <osl/thread.hxx> #include <tools/debug.hxx> #include <vcl/svapp.hxx> #ifdef HAVE_ODBC_SUPPORT #if defined WNT #define ODBC_LIBRARY "ODBC32.DLL" #endif #ifdef UNX #ifdef MACOSX #define ODBC_LIBRARY "libiodbc.dylib" #else #define ODBC_LIBRARY_1 "libodbc.so.1" #define ODBC_LIBRARY "libodbc.so" #endif #endif // just to go with calling convention of windows // so don't touch this #if defined(WNT) #undef SQL_API #define SQL_API __stdcall // At least under some circumstances, the below #include <odbc/sqlext.h> re- // defines SQL_API to an empty string, leading to a compiler warning on MSC; to // not break the current behavior, this is worked around by locally disabling // that warning: #if defined _MSC_VER #pragma warning(push) #pragma warning(disable: 4005) #endif #endif // defined(WNT) #ifdef SYSTEM_ODBC_HEADERS #include <sqlext.h> #else #include <odbc/sqlext.h> #endif #if defined(WNT) #if defined _MSC_VER #pragma warning(pop) #endif #undef SQL_API #define SQL_API __stdcall #endif // defined(WNT) // from here on you can do what you want to #else #define ODBC_LIBRARY "" #endif // HAVE_ODBC_SUPPORT namespace dbaui { #ifdef HAVE_ODBC_SUPPORT typedef SQLRETURN (SQL_API* TSQLManageDataSource) (SQLHWND hwndParent); typedef SQLRETURN (SQL_API* TSQLAllocHandle) (SQLSMALLINT HandleType, SQLHANDLE InputHandle, SQLHANDLE* OutputHandlePtr); typedef SQLRETURN (SQL_API* TSQLFreeHandle) (SQLSMALLINT HandleType, SQLHANDLE Handle); typedef SQLRETURN (SQL_API* TSQLSetEnvAttr) (SQLHENV EnvironmentHandle, SQLINTEGER Attribute, SQLPOINTER ValuePtr, SQLINTEGER StringLength); typedef SQLRETURN (SQL_API* TSQLDataSources) (SQLHENV EnvironmentHandle, SQLUSMALLINT Direction, SQLCHAR* ServerName, SQLSMALLINT BufferLength1, SQLSMALLINT* NameLength1Ptr, SQLCHAR* Description, SQLSMALLINT BufferLength2, SQLSMALLINT* NameLength2Ptr); #define NSQLAllocHandle(a,b,c) (*(TSQLAllocHandle)(m_pAllocHandle))(a,b,c) #define NSQLFreeHandle(a,b) (*(TSQLFreeHandle)(m_pFreeHandle))(a,b) #define NSQLSetEnvAttr(a,b,c,d) (*(TSQLSetEnvAttr)(m_pSetEnvAttr))(a,b,c,d) #define NSQLDataSources(a,b,c,d,e,f,g,h) (*(TSQLDataSources)(m_pDataSources))(a,b,c,d,e,f,g,h) #endif // OOdbcLibWrapper #ifdef HAVE_ODBC_SUPPORT OOdbcLibWrapper::OOdbcLibWrapper() :m_pOdbcLib(NULL) { } #endif sal_Bool OOdbcLibWrapper::load(const sal_Char* _pLibPath) { m_sLibPath = OUString::createFromAscii(_pLibPath); #ifdef HAVE_ODBC_SUPPORT // load the module m_pOdbcLib = osl_loadModule(m_sLibPath.pData, SAL_LOADMODULE_NOW); return (NULL != m_pOdbcLib); #else return sal_False; #endif } void OOdbcLibWrapper::unload() { #ifdef HAVE_ODBC_SUPPORT if (isLoaded()) { osl_unloadModule(m_pOdbcLib); m_pOdbcLib = NULL; } #endif } oslGenericFunction OOdbcLibWrapper::loadSymbol(const sal_Char* _pFunctionName) { return osl_getFunctionSymbol(m_pOdbcLib, OUString::createFromAscii(_pFunctionName).pData); } OOdbcLibWrapper::~OOdbcLibWrapper() { unload(); } // OOdbcEnumeration struct OdbcTypesImpl { #ifdef HAVE_ODBC_SUPPORT SQLHANDLE hEnvironment; OdbcTypesImpl() : hEnvironment(0) { } #else void* pDummy; #endif }; OOdbcEnumeration::OOdbcEnumeration() #ifdef HAVE_ODBC_SUPPORT :m_pAllocHandle(NULL) ,m_pSetEnvAttr(NULL) ,m_pDataSources(NULL) ,m_pImpl(new OdbcTypesImpl) #endif { sal_Bool bLoaded = load(ODBC_LIBRARY); #ifdef ODBC_LIBRARY_1 if ( !bLoaded ) bLoaded = load(ODBC_LIBRARY_1); #endif if ( bLoaded ) { #ifdef HAVE_ODBC_SUPPORT // load the generic functions m_pAllocHandle = loadSymbol("SQLAllocHandle"); m_pFreeHandle = loadSymbol("SQLFreeHandle"); m_pSetEnvAttr = loadSymbol("SQLSetEnvAttr"); m_pDataSources = loadSymbol("SQLDataSources"); // all or nothing if (!m_pAllocHandle || !m_pSetEnvAttr || !m_pDataSources || !m_pFreeHandle) { unload(); m_pAllocHandle = m_pFreeHandle = m_pSetEnvAttr = m_pDataSources = NULL; } #endif } } OOdbcEnumeration::~OOdbcEnumeration() { freeEnv(); delete m_pImpl; } sal_Bool OOdbcEnumeration::allocEnv() { OSL_ENSURE(isLoaded(), "OOdbcEnumeration::allocEnv: not loaded!"); if (!isLoaded()) return sal_False; #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) // nothing to do return sal_True; SQLRETURN nResult = NSQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_pImpl->hEnvironment); if (SQL_SUCCESS != nResult) // can't do anything without environment return sal_False; NSQLSetEnvAttr(m_pImpl->hEnvironment, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER); return sal_True; #else return sal_False; #endif } void OOdbcEnumeration::freeEnv() { #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) NSQLFreeHandle(SQL_HANDLE_ENV, m_pImpl->hEnvironment); m_pImpl->hEnvironment = 0; #endif } void OOdbcEnumeration::getDatasourceNames(StringBag& _rNames) { OSL_ENSURE(isLoaded(), "OOdbcEnumeration::getDatasourceNames: not loaded!"); if (!isLoaded()) return; if (!allocEnv()) { OSL_FAIL("OOdbcEnumeration::getDatasourceNames: could not allocate an ODBC environment!"); return; } #ifdef HAVE_ODBC_SUPPORT // now that we have an environment collect the data source names UCHAR szDSN[SQL_MAX_DSN_LENGTH+1]; SWORD pcbDSN; UCHAR szDescription[1024+1]; SWORD pcbDescription; SQLRETURN nResult = SQL_SUCCESS; rtl_TextEncoding nTextEncoding = osl_getThreadTextEncoding(); for ( nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_FIRST, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription)-1, &pcbDescription); ; nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_NEXT, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription)-1, &pcbDescription) ) { if (nResult != SQL_SUCCESS) // no further error handling break; else { OUString aCurrentDsn(reinterpret_cast<const char*>(szDSN),pcbDSN, nTextEncoding); _rNames.insert(aCurrentDsn); } } #else (void) _rNames; #endif } #ifdef HAVE_ODBC_ADMINISTRATION // ProcessTerminationWait class ProcessTerminationWait : public ::osl::Thread { oslProcess m_hProcessHandle; Link m_aFinishHdl; public: ProcessTerminationWait( oslProcess _hProcessHandle, const Link& _rFinishHdl ) :m_hProcessHandle( _hProcessHandle ) ,m_aFinishHdl( _rFinishHdl ) { } protected: virtual void SAL_CALL run() { osl_joinProcess( m_hProcessHandle ); osl_freeProcessHandle( m_hProcessHandle ); Application::PostUserEvent( m_aFinishHdl ); } }; // OOdbcManagement OOdbcManagement::OOdbcManagement( const Link& _rAsyncFinishCallback ) :m_pProcessWait( NULL ) ,m_aAsyncFinishCallback( _rAsyncFinishCallback ) { } OOdbcManagement::~OOdbcManagement() { // wait for our thread to be finished if ( m_pProcessWait.get() ) m_pProcessWait->join(); } bool OOdbcManagement::manageDataSources_async() { OSL_PRECOND( !isRunning(), "OOdbcManagement::manageDataSources_async: still running from the previous call!" ); if ( isRunning() ) return false; // this is done in an external process, due to #i78733# // (and note this whole functionality is supported on Windows only, ATM) OUString sExecutableName( "$BRAND_BASE_DIR/" LIBO_LIBEXEC_FOLDER "/odbcconfig.exe" ); ::rtl::Bootstrap::expandMacros( sExecutableName ); //TODO: detect failure oslProcess hProcessHandle(0); oslProcessError eError = osl_executeProcess( sExecutableName.pData, NULL, 0, 0, NULL, NULL, NULL, 0, &hProcessHandle ); if ( eError != osl_Process_E_None ) return false; m_pProcessWait.reset( new ProcessTerminationWait( hProcessHandle, m_aAsyncFinishCallback ) ); m_pProcessWait->create(); return true; } bool OOdbcManagement::isRunning() const { return ( m_pProcessWait.get() && m_pProcessWait->isRunning() ); } #endif // HAVE_ODBC_ADMINISTRATION } // namespace dbaui /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#738615 Uninitialized pointer field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include <config_folders.h> #include "odbcconfig.hxx" #ifdef SYSTEM_ODBC_HEADERS #include <sqltypes.h> #else #include <odbc/sqltypes.h> #endif #include <rtl/bootstrap.hxx> #include <rtl/ustring.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/process.h> #include <osl/thread.hxx> #include <tools/debug.hxx> #include <vcl/svapp.hxx> #ifdef HAVE_ODBC_SUPPORT #if defined WNT #define ODBC_LIBRARY "ODBC32.DLL" #endif #ifdef UNX #ifdef MACOSX #define ODBC_LIBRARY "libiodbc.dylib" #else #define ODBC_LIBRARY_1 "libodbc.so.1" #define ODBC_LIBRARY "libodbc.so" #endif #endif // just to go with calling convention of windows // so don't touch this #if defined(WNT) #undef SQL_API #define SQL_API __stdcall // At least under some circumstances, the below #include <odbc/sqlext.h> re- // defines SQL_API to an empty string, leading to a compiler warning on MSC; to // not break the current behavior, this is worked around by locally disabling // that warning: #if defined _MSC_VER #pragma warning(push) #pragma warning(disable: 4005) #endif #endif // defined(WNT) #ifdef SYSTEM_ODBC_HEADERS #include <sqlext.h> #else #include <odbc/sqlext.h> #endif #if defined(WNT) #if defined _MSC_VER #pragma warning(pop) #endif #undef SQL_API #define SQL_API __stdcall #endif // defined(WNT) // from here on you can do what you want to #else #define ODBC_LIBRARY "" #endif // HAVE_ODBC_SUPPORT namespace dbaui { #ifdef HAVE_ODBC_SUPPORT typedef SQLRETURN (SQL_API* TSQLManageDataSource) (SQLHWND hwndParent); typedef SQLRETURN (SQL_API* TSQLAllocHandle) (SQLSMALLINT HandleType, SQLHANDLE InputHandle, SQLHANDLE* OutputHandlePtr); typedef SQLRETURN (SQL_API* TSQLFreeHandle) (SQLSMALLINT HandleType, SQLHANDLE Handle); typedef SQLRETURN (SQL_API* TSQLSetEnvAttr) (SQLHENV EnvironmentHandle, SQLINTEGER Attribute, SQLPOINTER ValuePtr, SQLINTEGER StringLength); typedef SQLRETURN (SQL_API* TSQLDataSources) (SQLHENV EnvironmentHandle, SQLUSMALLINT Direction, SQLCHAR* ServerName, SQLSMALLINT BufferLength1, SQLSMALLINT* NameLength1Ptr, SQLCHAR* Description, SQLSMALLINT BufferLength2, SQLSMALLINT* NameLength2Ptr); #define NSQLAllocHandle(a,b,c) (*(TSQLAllocHandle)(m_pAllocHandle))(a,b,c) #define NSQLFreeHandle(a,b) (*(TSQLFreeHandle)(m_pFreeHandle))(a,b) #define NSQLSetEnvAttr(a,b,c,d) (*(TSQLSetEnvAttr)(m_pSetEnvAttr))(a,b,c,d) #define NSQLDataSources(a,b,c,d,e,f,g,h) (*(TSQLDataSources)(m_pDataSources))(a,b,c,d,e,f,g,h) #endif // OOdbcLibWrapper #ifdef HAVE_ODBC_SUPPORT OOdbcLibWrapper::OOdbcLibWrapper() :m_pOdbcLib(NULL) { } #endif sal_Bool OOdbcLibWrapper::load(const sal_Char* _pLibPath) { m_sLibPath = OUString::createFromAscii(_pLibPath); #ifdef HAVE_ODBC_SUPPORT // load the module m_pOdbcLib = osl_loadModule(m_sLibPath.pData, SAL_LOADMODULE_NOW); return (NULL != m_pOdbcLib); #else return sal_False; #endif } void OOdbcLibWrapper::unload() { #ifdef HAVE_ODBC_SUPPORT if (isLoaded()) { osl_unloadModule(m_pOdbcLib); m_pOdbcLib = NULL; } #endif } oslGenericFunction OOdbcLibWrapper::loadSymbol(const sal_Char* _pFunctionName) { return osl_getFunctionSymbol(m_pOdbcLib, OUString::createFromAscii(_pFunctionName).pData); } OOdbcLibWrapper::~OOdbcLibWrapper() { unload(); } // OOdbcEnumeration struct OdbcTypesImpl { #ifdef HAVE_ODBC_SUPPORT SQLHANDLE hEnvironment; OdbcTypesImpl() : hEnvironment(0) { } #else void* pDummy; #endif }; OOdbcEnumeration::OOdbcEnumeration() #ifdef HAVE_ODBC_SUPPORT :m_pAllocHandle(NULL) ,m_pFreeHandle(NULL) ,m_pSetEnvAttr(NULL) ,m_pDataSources(NULL) ,m_pImpl(new OdbcTypesImpl) #endif { sal_Bool bLoaded = load(ODBC_LIBRARY); #ifdef ODBC_LIBRARY_1 if ( !bLoaded ) bLoaded = load(ODBC_LIBRARY_1); #endif if ( bLoaded ) { #ifdef HAVE_ODBC_SUPPORT // load the generic functions m_pAllocHandle = loadSymbol("SQLAllocHandle"); m_pFreeHandle = loadSymbol("SQLFreeHandle"); m_pSetEnvAttr = loadSymbol("SQLSetEnvAttr"); m_pDataSources = loadSymbol("SQLDataSources"); // all or nothing if (!m_pAllocHandle || !m_pSetEnvAttr || !m_pDataSources || !m_pFreeHandle) { unload(); m_pAllocHandle = m_pFreeHandle = m_pSetEnvAttr = m_pDataSources = NULL; } #endif } } OOdbcEnumeration::~OOdbcEnumeration() { freeEnv(); delete m_pImpl; } sal_Bool OOdbcEnumeration::allocEnv() { OSL_ENSURE(isLoaded(), "OOdbcEnumeration::allocEnv: not loaded!"); if (!isLoaded()) return sal_False; #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) // nothing to do return sal_True; SQLRETURN nResult = NSQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_pImpl->hEnvironment); if (SQL_SUCCESS != nResult) // can't do anything without environment return sal_False; NSQLSetEnvAttr(m_pImpl->hEnvironment, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER); return sal_True; #else return sal_False; #endif } void OOdbcEnumeration::freeEnv() { #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) NSQLFreeHandle(SQL_HANDLE_ENV, m_pImpl->hEnvironment); m_pImpl->hEnvironment = 0; #endif } void OOdbcEnumeration::getDatasourceNames(StringBag& _rNames) { OSL_ENSURE(isLoaded(), "OOdbcEnumeration::getDatasourceNames: not loaded!"); if (!isLoaded()) return; if (!allocEnv()) { OSL_FAIL("OOdbcEnumeration::getDatasourceNames: could not allocate an ODBC environment!"); return; } #ifdef HAVE_ODBC_SUPPORT // now that we have an environment collect the data source names UCHAR szDSN[SQL_MAX_DSN_LENGTH+1]; SWORD pcbDSN; UCHAR szDescription[1024+1]; SWORD pcbDescription; SQLRETURN nResult = SQL_SUCCESS; rtl_TextEncoding nTextEncoding = osl_getThreadTextEncoding(); for ( nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_FIRST, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription)-1, &pcbDescription); ; nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_NEXT, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription)-1, &pcbDescription) ) { if (nResult != SQL_SUCCESS) // no further error handling break; else { OUString aCurrentDsn(reinterpret_cast<const char*>(szDSN),pcbDSN, nTextEncoding); _rNames.insert(aCurrentDsn); } } #else (void) _rNames; #endif } #ifdef HAVE_ODBC_ADMINISTRATION // ProcessTerminationWait class ProcessTerminationWait : public ::osl::Thread { oslProcess m_hProcessHandle; Link m_aFinishHdl; public: ProcessTerminationWait( oslProcess _hProcessHandle, const Link& _rFinishHdl ) :m_hProcessHandle( _hProcessHandle ) ,m_aFinishHdl( _rFinishHdl ) { } protected: virtual void SAL_CALL run() { osl_joinProcess( m_hProcessHandle ); osl_freeProcessHandle( m_hProcessHandle ); Application::PostUserEvent( m_aFinishHdl ); } }; // OOdbcManagement OOdbcManagement::OOdbcManagement( const Link& _rAsyncFinishCallback ) :m_pProcessWait( NULL ) ,m_aAsyncFinishCallback( _rAsyncFinishCallback ) { } OOdbcManagement::~OOdbcManagement() { // wait for our thread to be finished if ( m_pProcessWait.get() ) m_pProcessWait->join(); } bool OOdbcManagement::manageDataSources_async() { OSL_PRECOND( !isRunning(), "OOdbcManagement::manageDataSources_async: still running from the previous call!" ); if ( isRunning() ) return false; // this is done in an external process, due to #i78733# // (and note this whole functionality is supported on Windows only, ATM) OUString sExecutableName( "$BRAND_BASE_DIR/" LIBO_LIBEXEC_FOLDER "/odbcconfig.exe" ); ::rtl::Bootstrap::expandMacros( sExecutableName ); //TODO: detect failure oslProcess hProcessHandle(0); oslProcessError eError = osl_executeProcess( sExecutableName.pData, NULL, 0, 0, NULL, NULL, NULL, 0, &hProcessHandle ); if ( eError != osl_Process_E_None ) return false; m_pProcessWait.reset( new ProcessTerminationWait( hProcessHandle, m_aAsyncFinishCallback ) ); m_pProcessWait->create(); return true; } bool OOdbcManagement::isRunning() const { return ( m_pProcessWait.get() && m_pProcessWait->isRunning() ); } #endif // HAVE_ODBC_ADMINISTRATION } // namespace dbaui /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- inline bool MarkContext::AddMarkedObject(void * objectAddress, size_t objectSize) { Assert(objectAddress != nullptr); Assert(objectSize > 0); Assert(objectSize % sizeof(void *) == 0); FAULTINJECT_MEMORY_MARK_NOTHROW(_u("AddMarkedObject"), objectSize); #if DBG_DUMP if (recycler->forceTraceMark || recycler->GetRecyclerFlagsTable().Trace.IsEnabled(Js::MarkPhase)) { Output::Print(_u(" %p"), objectAddress); } #endif RECYCLER_STATS_INTERLOCKED_INC(recycler, scanCount); MarkCandidate markCandidate; #if defined(_WIN64) && defined(_M_X64) // Enabling store forwards. The intrinsic generates stores matching the load in size. // This enables skipping caches and forwarding the store data to the following load. *(__m128i *)&markCandidate = _mm_set_epi64x(objectSize, (__int64)objectAddress); #else markCandidate.obj = (void**)objectAddress; markCandidate.byteCount = objectSize; #endif return markStack.Push(markCandidate); } inline bool MarkContext::AddPreciselyTracedObject(IRecyclerVisitedObject* obj) { FAULTINJECT_MEMORY_MARK_NOTHROW(_u("AddPreciselyTracedObject"), 0); return preciseStack.Push(obj); } #if ENABLE_CONCURRENT_GC inline bool MarkContext::AddTrackedObject(FinalizableObject * obj) { Assert(obj != nullptr); #if ENABLE_CONCURRENT_GC Assert(recycler->DoQueueTrackedObject()); #endif #if ENABLE_PARTIAL_GC Assert(!recycler->inPartialCollectMode); #endif FAULTINJECT_MEMORY_MARK_NOTHROW(_u("AddTrackedObject"), 0); return trackStack.Push(obj); } #endif template <bool parallel, bool interior, bool doSpecialMark> NO_SANITIZE_ADDRESS inline void MarkContext::ScanMemory(void ** obj, size_t byteCount) { Assert(byteCount != 0); Assert(byteCount % sizeof(void *) == 0); void ** objEnd = obj + (byteCount / sizeof(void *)); void * parentObject = (void*)obj; #if DBG_DUMP if (recycler->forceTraceMark || recycler->GetRecyclerFlagsTable().Trace.IsEnabled(Js::MarkPhase)) { Output::Print(_u("Scanning %p(%8d): "), obj, byteCount); } #endif do { // We need to ensure that the compiler does not reintroduce reads to the object after inlining. // This could cause the value to change after the marking checks (e.g., the null/low address check). // Intrinsics avoid the expensive memory barrier on ARM (due to /volatile:ms). #if defined(_M_ARM64) void * candidate = reinterpret_cast<void *>(__iso_volatile_load64(reinterpret_cast<volatile __int64 *>(obj))); #elif defined(_M_ARM) void * candidate = reinterpret_cast<void *>(__iso_volatile_load32(reinterpret_cast<volatile __int32 *>(obj))); #else void * candidate = *(static_cast<void * volatile *>(obj)); #endif #if DBG this->parentRef = obj; #endif Mark<parallel, interior, doSpecialMark>(candidate, parentObject); obj++; } while (obj != objEnd); #if DBG this->parentRef = nullptr; #endif #if DBG_DUMP if (recycler->forceTraceMark || recycler->GetRecyclerFlagsTable().Trace.IsEnabled(Js::MarkPhase)) { Output::Print(_u("\n")); Output::Flush(); } #endif } template <bool parallel, bool interior> inline void MarkContext::ScanObject(void ** obj, size_t byteCount) { BEGIN_DUMP_OBJECT(recycler, obj); ScanMemory<parallel, interior, false>(obj, byteCount); END_DUMP_OBJECT(recycler); } template <bool parallel, bool interior, bool doSpecialMark> inline void MarkContext::Mark(void * candidate, void * parentReference) { // We should never reach here while we are processing Rescan. // Otherwise our rescanState could be out of sync with mark state. Assert(!recycler->isProcessingRescan); #if defined(RECYCLER_STATS) || !defined(_M_X64) if ((size_t)candidate < 0x10000) { RECYCLER_STATS_INTERLOCKED_INC(recycler, tryMarkNullCount); return; } #endif if (interior) { recycler->heapBlockMap.MarkInterior<parallel>(candidate, this); return; } #if defined(RECYCLER_STATS) || !defined(_M_X64) if (!HeapInfo::IsAlignedAddress(candidate)) { RECYCLER_STATS_INTERLOCKED_INC(recycler, tryMarkUnalignedCount); return; } #endif recycler->heapBlockMap.Mark<parallel, doSpecialMark>(candidate, this); #ifdef RECYCLER_MARK_TRACK this->OnObjectMarked(candidate, parentReference); #endif } inline void MarkContext::MarkTrackedObject(FinalizableObject * trackedObject) { #if ENABLE_CONCURRENT_GC Assert(!recycler->queueTrackedObject); Assert(!recycler->IsConcurrentExecutingState()); #endif #if ENABLE_PARTIAL_GC Assert(!recycler->inPartialCollectMode); #endif Assert(!(recycler->collectionState == CollectionStateParallelMark)); // Mark is not expected to throw. BEGIN_NO_EXCEPTION { trackedObject->Mark(recycler); } END_NO_EXCEPTION } template <bool parallel, bool interior> inline void MarkContext::ProcessMark() { #ifdef RECYCLER_STRESS if (recycler->GetRecyclerFlagsTable().RecyclerInduceFalsePositives) { // InduceFalsePositives logic doesn't support parallel marking if (!parallel) { recycler->heapBlockMap.InduceFalsePositives(recycler); } } #endif #if defined(_M_IX86) || defined(_M_X64) // Flip between processing the generic mark stack (conservatively traced with ScanMemory) and // the precise stack (precisely traced via IRecyclerVisitedObject::Trace). Each of those // operations on an object has the potential to add new marked objects to either or both // stacks so we must loop until they are both empty. while (!markStack.IsEmpty() || !preciseStack.IsEmpty()) { MarkCandidate current, next; while (markStack.Pop(&current)) { // Process entries and prefetch as we go. while (markStack.Pop(&next)) { // Prefetch the next entry so it's ready when we need it. _mm_prefetch((char *)next.obj, _MM_HINT_T0); // Process the previously retrieved entry. ScanObject<parallel, interior>(current.obj, current.byteCount); _mm_prefetch((char *)*(next.obj), _MM_HINT_T0); current = next; } // The stack is empty, but we still have a previously retrieved entry; process it now. ScanObject<parallel, interior>(current.obj, current.byteCount); // Processing that entry may have generated more entries in the mark stack, so continue the loop. } #else // _mm_prefetch intrinsic is specific to Intel platforms. // CONSIDER: There does seem to be a compiler intrinsic for prefetch on ARM, // however, the information on this is scarce, so for now just don't do prefetch on ARM. MarkCandidate current; while (markStack.Pop(&current)) { ScanObject<parallel, interior>(current.obj, current.byteCount); } #endif Assert(markStack.IsEmpty()); if (!preciseStack.IsEmpty()) { MarkContextWrapper<parallel> markContextWrapper(this); IRecyclerVisitedObject* tracedObject; while (preciseStack.Pop(&tracedObject)) { tracedObject->Trace(&markContextWrapper); } } Assert(preciseStack.IsEmpty()); } } <commit_msg>Fix bad merge in ProcessMark for ARM builds<commit_after>//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- inline bool MarkContext::AddMarkedObject(void * objectAddress, size_t objectSize) { Assert(objectAddress != nullptr); Assert(objectSize > 0); Assert(objectSize % sizeof(void *) == 0); FAULTINJECT_MEMORY_MARK_NOTHROW(_u("AddMarkedObject"), objectSize); #if DBG_DUMP if (recycler->forceTraceMark || recycler->GetRecyclerFlagsTable().Trace.IsEnabled(Js::MarkPhase)) { Output::Print(_u(" %p"), objectAddress); } #endif RECYCLER_STATS_INTERLOCKED_INC(recycler, scanCount); MarkCandidate markCandidate; #if defined(_WIN64) && defined(_M_X64) // Enabling store forwards. The intrinsic generates stores matching the load in size. // This enables skipping caches and forwarding the store data to the following load. *(__m128i *)&markCandidate = _mm_set_epi64x(objectSize, (__int64)objectAddress); #else markCandidate.obj = (void**)objectAddress; markCandidate.byteCount = objectSize; #endif return markStack.Push(markCandidate); } inline bool MarkContext::AddPreciselyTracedObject(IRecyclerVisitedObject* obj) { FAULTINJECT_MEMORY_MARK_NOTHROW(_u("AddPreciselyTracedObject"), 0); return preciseStack.Push(obj); } #if ENABLE_CONCURRENT_GC inline bool MarkContext::AddTrackedObject(FinalizableObject * obj) { Assert(obj != nullptr); #if ENABLE_CONCURRENT_GC Assert(recycler->DoQueueTrackedObject()); #endif #if ENABLE_PARTIAL_GC Assert(!recycler->inPartialCollectMode); #endif FAULTINJECT_MEMORY_MARK_NOTHROW(_u("AddTrackedObject"), 0); return trackStack.Push(obj); } #endif template <bool parallel, bool interior, bool doSpecialMark> NO_SANITIZE_ADDRESS inline void MarkContext::ScanMemory(void ** obj, size_t byteCount) { Assert(byteCount != 0); Assert(byteCount % sizeof(void *) == 0); void ** objEnd = obj + (byteCount / sizeof(void *)); void * parentObject = (void*)obj; #if DBG_DUMP if (recycler->forceTraceMark || recycler->GetRecyclerFlagsTable().Trace.IsEnabled(Js::MarkPhase)) { Output::Print(_u("Scanning %p(%8d): "), obj, byteCount); } #endif do { // We need to ensure that the compiler does not reintroduce reads to the object after inlining. // This could cause the value to change after the marking checks (e.g., the null/low address check). // Intrinsics avoid the expensive memory barrier on ARM (due to /volatile:ms). #if defined(_M_ARM64) void * candidate = reinterpret_cast<void *>(__iso_volatile_load64(reinterpret_cast<volatile __int64 *>(obj))); #elif defined(_M_ARM) void * candidate = reinterpret_cast<void *>(__iso_volatile_load32(reinterpret_cast<volatile __int32 *>(obj))); #else void * candidate = *(static_cast<void * volatile *>(obj)); #endif #if DBG this->parentRef = obj; #endif Mark<parallel, interior, doSpecialMark>(candidate, parentObject); obj++; } while (obj != objEnd); #if DBG this->parentRef = nullptr; #endif #if DBG_DUMP if (recycler->forceTraceMark || recycler->GetRecyclerFlagsTable().Trace.IsEnabled(Js::MarkPhase)) { Output::Print(_u("\n")); Output::Flush(); } #endif } template <bool parallel, bool interior> inline void MarkContext::ScanObject(void ** obj, size_t byteCount) { BEGIN_DUMP_OBJECT(recycler, obj); ScanMemory<parallel, interior, false>(obj, byteCount); END_DUMP_OBJECT(recycler); } template <bool parallel, bool interior, bool doSpecialMark> inline void MarkContext::Mark(void * candidate, void * parentReference) { // We should never reach here while we are processing Rescan. // Otherwise our rescanState could be out of sync with mark state. Assert(!recycler->isProcessingRescan); #if defined(RECYCLER_STATS) || !defined(_M_X64) if ((size_t)candidate < 0x10000) { RECYCLER_STATS_INTERLOCKED_INC(recycler, tryMarkNullCount); return; } #endif if (interior) { recycler->heapBlockMap.MarkInterior<parallel>(candidate, this); return; } #if defined(RECYCLER_STATS) || !defined(_M_X64) if (!HeapInfo::IsAlignedAddress(candidate)) { RECYCLER_STATS_INTERLOCKED_INC(recycler, tryMarkUnalignedCount); return; } #endif recycler->heapBlockMap.Mark<parallel, doSpecialMark>(candidate, this); #ifdef RECYCLER_MARK_TRACK this->OnObjectMarked(candidate, parentReference); #endif } inline void MarkContext::MarkTrackedObject(FinalizableObject * trackedObject) { #if ENABLE_CONCURRENT_GC Assert(!recycler->queueTrackedObject); Assert(!recycler->IsConcurrentExecutingState()); #endif #if ENABLE_PARTIAL_GC Assert(!recycler->inPartialCollectMode); #endif Assert(!(recycler->collectionState == CollectionStateParallelMark)); // Mark is not expected to throw. BEGIN_NO_EXCEPTION { trackedObject->Mark(recycler); } END_NO_EXCEPTION } template <bool parallel, bool interior> inline void MarkContext::ProcessMark() { #ifdef RECYCLER_STRESS if (recycler->GetRecyclerFlagsTable().RecyclerInduceFalsePositives) { // InduceFalsePositives logic doesn't support parallel marking if (!parallel) { recycler->heapBlockMap.InduceFalsePositives(recycler); } } #endif // Flip between processing the generic mark stack (conservatively traced with ScanMemory) and // the precise stack (precisely traced via IRecyclerVisitedObject::Trace). Each of those // operations on an object has the potential to add new marked objects to either or both // stacks so we must loop until they are both empty. while (!markStack.IsEmpty() || !preciseStack.IsEmpty()) { #if defined(_M_IX86) || defined(_M_X64) MarkCandidate current, next; while (markStack.Pop(&current)) { // Process entries and prefetch as we go. while (markStack.Pop(&next)) { // Prefetch the next entry so it's ready when we need it. _mm_prefetch((char *)next.obj, _MM_HINT_T0); // Process the previously retrieved entry. ScanObject<parallel, interior>(current.obj, current.byteCount); _mm_prefetch((char *)*(next.obj), _MM_HINT_T0); current = next; } // The stack is empty, but we still have a previously retrieved entry; process it now. ScanObject<parallel, interior>(current.obj, current.byteCount); // Processing that entry may have generated more entries in the mark stack, so continue the loop. } #else // _mm_prefetch intrinsic is specific to Intel platforms. // CONSIDER: There does seem to be a compiler intrinsic for prefetch on ARM, // however, the information on this is scarce, so for now just don't do prefetch on ARM. MarkCandidate current; while (markStack.Pop(&current)) { ScanObject<parallel, interior>(current.obj, current.byteCount); } #endif Assert(markStack.IsEmpty()); if (!preciseStack.IsEmpty()) { MarkContextWrapper<parallel> markContextWrapper(this); IRecyclerVisitedObject* tracedObject; while (preciseStack.Pop(&tracedObject)) { tracedObject->Trace(&markContextWrapper); } } Assert(preciseStack.IsEmpty()); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: undoback.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:28:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "undoback.hxx" #include "sdpage.hxx" #include "sdresid.hxx" #include "strings.hrc" // --------------------------- // - BackgroundObjUndoAction - // --------------------------- TYPEINIT1( SdBackgroundObjUndoAction, SdUndoAction ); // ----------------------------------------------------------------------------- SdBackgroundObjUndoAction::SdBackgroundObjUndoAction( SdDrawDocument& rDoc, SdPage& rPage, const SdrObject* pBackgroundObj ) : SdUndoAction( &rDoc ), mrPage( rPage ), mpBackgroundObj( pBackgroundObj ? pBackgroundObj->Clone() : NULL ) { String aString( SdResId( STR_UNDO_CHANGE_PAGEFORMAT ) ); SetComment( aString ); } // ----------------------------------------------------------------------------- SdBackgroundObjUndoAction::~SdBackgroundObjUndoAction() { delete mpBackgroundObj; } // ----------------------------------------------------------------------------- void SdBackgroundObjUndoAction::ImplRestoreBackgroundObj() { SdrObject* pOldObj = mrPage.GetBackgroundObj(); if( pOldObj ) pOldObj = pOldObj->Clone(); mrPage.SetBackgroundObj( mpBackgroundObj ); mpBackgroundObj = pOldObj; // #110094#-15 // tell the page that it's visualization has changed mrPage.ActionChanged(); } // ----------------------------------------------------------------------------- void SdBackgroundObjUndoAction::Undo() { ImplRestoreBackgroundObj(); } // ----------------------------------------------------------------------------- void SdBackgroundObjUndoAction::Redo() { ImplRestoreBackgroundObj(); } // ----------------------------------------------------------------------------- SdUndoAction* SdBackgroundObjUndoAction::Clone() const { return new SdBackgroundObjUndoAction( *mpDoc, mrPage, mpBackgroundObj ); } <commit_msg>INTEGRATION: CWS oj14 (1.6.130); FILE MERGED 2007/06/26 20:33:54 fs 1.6.130.1: #i78908# ~SdrObject inaccessible now, need to use SdrObject::Free instead<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: undoback.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2007-07-06 09:49:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "undoback.hxx" #include "sdpage.hxx" #include "sdresid.hxx" #include "strings.hrc" // --------------------------- // - BackgroundObjUndoAction - // --------------------------- TYPEINIT1( SdBackgroundObjUndoAction, SdUndoAction ); // ----------------------------------------------------------------------------- SdBackgroundObjUndoAction::SdBackgroundObjUndoAction( SdDrawDocument& rDoc, SdPage& rPage, const SdrObject* pBackgroundObj ) : SdUndoAction( &rDoc ), mrPage( rPage ), mpBackgroundObj( pBackgroundObj ? pBackgroundObj->Clone() : NULL ) { String aString( SdResId( STR_UNDO_CHANGE_PAGEFORMAT ) ); SetComment( aString ); } // ----------------------------------------------------------------------------- SdBackgroundObjUndoAction::~SdBackgroundObjUndoAction() { SdrObject::Free( mpBackgroundObj ); } // ----------------------------------------------------------------------------- void SdBackgroundObjUndoAction::ImplRestoreBackgroundObj() { SdrObject* pOldObj = mrPage.GetBackgroundObj(); if( pOldObj ) pOldObj = pOldObj->Clone(); mrPage.SetBackgroundObj( mpBackgroundObj ); mpBackgroundObj = pOldObj; // #110094#-15 // tell the page that it's visualization has changed mrPage.ActionChanged(); } // ----------------------------------------------------------------------------- void SdBackgroundObjUndoAction::Undo() { ImplRestoreBackgroundObj(); } // ----------------------------------------------------------------------------- void SdBackgroundObjUndoAction::Redo() { ImplRestoreBackgroundObj(); } // ----------------------------------------------------------------------------- SdUndoAction* SdBackgroundObjUndoAction::Clone() const { return new SdBackgroundObjUndoAction( *mpDoc, mrPage, mpBackgroundObj ); } <|endoftext|>
<commit_before>//===-- DWARFDebugFrame.h - Parsing of .debug_frame -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DWARFDebugFrame.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/Format.h" using namespace llvm; using namespace dwarf; class llvm::FrameEntry { public: enum FrameKind {FK_CIE, FK_FDE}; FrameEntry(FrameKind K, DataExtractor D, uint64_t Offset, uint64_t Length) : Kind(K), Data(D), Offset(Offset), Length(Length) {} FrameKind getKind() const { return Kind; } virtual void dumpHeader(raw_ostream &OS) const = 0; protected: const FrameKind Kind; DataExtractor Data; uint64_t Offset; uint64_t Length; }; class CIE : public FrameEntry { public: // CIEs (and FDEs) are simply container classes, so the only sensible way to // create them is by providing the full parsed contents in the constructor. CIE(DataExtractor D, uint64_t Offset, uint64_t Length, uint8_t Version, SmallString<8> Augmentation, uint64_t CodeAlignmentFactor, int64_t DataAlignmentFactor, uint64_t ReturnAddressRegister) : FrameEntry(FK_CIE, D, Offset, Length), Version(Version), Augmentation(Augmentation), CodeAlignmentFactor(CodeAlignmentFactor), DataAlignmentFactor(DataAlignmentFactor), ReturnAddressRegister(ReturnAddressRegister) {} void dumpHeader(raw_ostream &OS) const { OS << format("%08x %08x %08x CIE", Offset, Length, DW_CIE_ID) << "\n"; OS << format(" Version: %d\n", Version); OS << " Augmentation: \"" << Augmentation << "\"\n"; OS << format(" Code alignment factor: %u\n", CodeAlignmentFactor); OS << format(" Data alignment factor: %d\n", DataAlignmentFactor); OS << format(" Return address column: %d\n", ReturnAddressRegister); OS << "\n"; } static bool classof(const FrameEntry *FE) { return FE->getKind() == FK_CIE; } private: uint8_t Version; SmallString<8> Augmentation; uint64_t CodeAlignmentFactor; int64_t DataAlignmentFactor; uint64_t ReturnAddressRegister; }; class FDE : public FrameEntry { public: // Each FDE has a CIE it's "linked to". Our FDE contains is constructed with // an offset to the CIE (provided by parsing the FDE header). The CIE itself // is obtained lazily once it's actually required. FDE(DataExtractor D, uint64_t Offset, uint64_t Length, int64_t LinkedCIEOffset, uint64_t InitialLocation, uint64_t AddressRange) : FrameEntry(FK_FDE, D, Offset, Length), LinkedCIEOffset(LinkedCIEOffset), InitialLocation(InitialLocation), AddressRange(AddressRange), LinkedCIE(NULL) {} void dumpHeader(raw_ostream &OS) const { OS << format("%08x %08x %08x FDE ", Offset, Length, LinkedCIEOffset); OS << format("cie=%08x pc=%08x...%08x\n", LinkedCIEOffset, InitialLocation, InitialLocation + AddressRange); OS << "\n"; } static bool classof(const FrameEntry *FE) { return FE->getKind() == FK_FDE; } private: uint64_t LinkedCIEOffset; uint64_t InitialLocation; uint64_t AddressRange; CIE *LinkedCIE; }; DWARFDebugFrame::DWARFDebugFrame() { } DWARFDebugFrame::~DWARFDebugFrame() { for (EntryVector::iterator I = Entries.begin(), E = Entries.end(); I != E; ++I) { delete *I; } } static void LLVM_ATTRIBUTE_UNUSED dumpDataAux(DataExtractor Data, uint32_t Offset, int Length) { errs() << "DUMP: "; for (int i = 0; i < Length; ++i) { uint8_t c = Data.getU8(&Offset); errs().write_hex(c); errs() << " "; } errs() << "\n"; } void DWARFDebugFrame::parse(DataExtractor Data) { uint32_t Offset = 0; while (Data.isValidOffset(Offset)) { uint32_t StartOffset = Offset; bool IsDWARF64 = false; uint64_t Length = Data.getU32(&Offset); uint64_t Id; if (Length == UINT32_MAX) { // DWARF-64 is distinguished by the first 32 bits of the initial length // field being 0xffffffff. Then, the next 64 bits are the actual entry // length. IsDWARF64 = true; Length = Data.getU64(&Offset); } // At this point, Offset points to the next field after Length. // Length is the structure size excluding itself. Compute an offset one // past the end of the structure (needed to know how many instructions to // read). // TODO: For honest DWARF64 support, DataExtractor will have to treat // offset_ptr as uint64_t* uint32_t EndStructureOffset = Offset + static_cast<uint32_t>(Length); // The Id field's size depends on the DWARF format Id = Data.getUnsigned(&Offset, IsDWARF64 ? 8 : 4); bool IsCIE = ((IsDWARF64 && Id == DW64_CIE_ID) || Id == DW_CIE_ID); if (IsCIE) { // Note: this is specifically DWARFv3 CIE header structure. It was // changed in DWARFv4. uint8_t Version = Data.getU8(&Offset); const char *Augmentation = Data.getCStr(&Offset); uint64_t CodeAlignmentFactor = Data.getULEB128(&Offset); int64_t DataAlignmentFactor = Data.getSLEB128(&Offset); uint64_t ReturnAddressRegister = Data.getULEB128(&Offset); CIE *NewCIE = new CIE(Data, StartOffset, Length, Version, StringRef(Augmentation), CodeAlignmentFactor, DataAlignmentFactor, ReturnAddressRegister); Entries.push_back(NewCIE); } else { // FDE uint64_t CIEPointer = Id; uint64_t InitialLocation = Data.getAddress(&Offset); uint64_t AddressRange = Data.getAddress(&Offset); FDE *NewFDE = new FDE(Data, StartOffset, Length, CIEPointer, InitialLocation, AddressRange); Entries.push_back(NewFDE); } Offset = EndStructureOffset; } } void DWARFDebugFrame::dump(raw_ostream &OS) const { OS << "\n"; for (EntryVector::const_iterator I = Entries.begin(), E = Entries.end(); I != E; ++I) { (*I)->dumpHeader(OS); } } <commit_msg>Fix some formatting & add comments, following Eric's review<commit_after>//===-- DWARFDebugFrame.h - Parsing of .debug_frame -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DWARFDebugFrame.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/Format.h" using namespace llvm; using namespace dwarf; class llvm::FrameEntry { public: enum FrameKind {FK_CIE, FK_FDE}; FrameEntry(FrameKind K, DataExtractor D, uint64_t Offset, uint64_t Length) : Kind(K), Data(D), Offset(Offset), Length(Length) {} FrameKind getKind() const { return Kind; } virtual void dumpHeader(raw_ostream &OS) const = 0; protected: const FrameKind Kind; /// \brief The data stream holding the section from which the entry was /// parsed. DataExtractor Data; /// \brief Offset of this entry in the section. uint64_t Offset; /// \brief Entry length as specified in DWARF. uint64_t Length; }; class CIE : public FrameEntry { public: // CIEs (and FDEs) are simply container classes, so the only sensible way to // create them is by providing the full parsed contents in the constructor. CIE(DataExtractor D, uint64_t Offset, uint64_t Length, uint8_t Version, SmallString<8> Augmentation, uint64_t CodeAlignmentFactor, int64_t DataAlignmentFactor, uint64_t ReturnAddressRegister) : FrameEntry(FK_CIE, D, Offset, Length), Version(Version), Augmentation(Augmentation), CodeAlignmentFactor(CodeAlignmentFactor), DataAlignmentFactor(DataAlignmentFactor), ReturnAddressRegister(ReturnAddressRegister) {} void dumpHeader(raw_ostream &OS) const { OS << format("%08x %08x %08x CIE", Offset, Length, DW_CIE_ID) << "\n"; OS << format(" Version: %d\n", Version); OS << " Augmentation: \"" << Augmentation << "\"\n"; OS << format(" Code alignment factor: %u\n", CodeAlignmentFactor); OS << format(" Data alignment factor: %d\n", DataAlignmentFactor); OS << format(" Return address column: %d\n", ReturnAddressRegister); OS << "\n"; } static bool classof(const FrameEntry *FE) { return FE->getKind() == FK_CIE; } private: /// The following fields are defined in section 6.4.1 of the DWARF standard v3 uint8_t Version; SmallString<8> Augmentation; uint64_t CodeAlignmentFactor; int64_t DataAlignmentFactor; uint64_t ReturnAddressRegister; }; class FDE : public FrameEntry { public: // Each FDE has a CIE it's "linked to". Our FDE contains is constructed with // an offset to the CIE (provided by parsing the FDE header). The CIE itself // is obtained lazily once it's actually required. FDE(DataExtractor D, uint64_t Offset, uint64_t Length, int64_t LinkedCIEOffset, uint64_t InitialLocation, uint64_t AddressRange) : FrameEntry(FK_FDE, D, Offset, Length), LinkedCIEOffset(LinkedCIEOffset), InitialLocation(InitialLocation), AddressRange(AddressRange), LinkedCIE(NULL) {} void dumpHeader(raw_ostream &OS) const { OS << format("%08x %08x %08x FDE ", Offset, Length, LinkedCIEOffset); OS << format("cie=%08x pc=%08x...%08x\n", LinkedCIEOffset, InitialLocation, InitialLocation + AddressRange); OS << "\n"; } static bool classof(const FrameEntry *FE) { return FE->getKind() == FK_FDE; } private: /// The following fields are defined in section 6.4.1 of the DWARF standard v3 uint64_t LinkedCIEOffset; uint64_t InitialLocation; uint64_t AddressRange; CIE *LinkedCIE; }; DWARFDebugFrame::DWARFDebugFrame() { } DWARFDebugFrame::~DWARFDebugFrame() { for (EntryVector::iterator I = Entries.begin(), E = Entries.end(); I != E; ++I) { delete *I; } } static void LLVM_ATTRIBUTE_UNUSED dumpDataAux(DataExtractor Data, uint32_t Offset, int Length) { errs() << "DUMP: "; for (int i = 0; i < Length; ++i) { uint8_t c = Data.getU8(&Offset); errs().write_hex(c); errs() << " "; } errs() << "\n"; } void DWARFDebugFrame::parse(DataExtractor Data) { uint32_t Offset = 0; while (Data.isValidOffset(Offset)) { uint32_t StartOffset = Offset; bool IsDWARF64 = false; uint64_t Length = Data.getU32(&Offset); uint64_t Id; if (Length == UINT32_MAX) { // DWARF-64 is distinguished by the first 32 bits of the initial length // field being 0xffffffff. Then, the next 64 bits are the actual entry // length. IsDWARF64 = true; Length = Data.getU64(&Offset); } // At this point, Offset points to the next field after Length. // Length is the structure size excluding itself. Compute an offset one // past the end of the structure (needed to know how many instructions to // read). // TODO: For honest DWARF64 support, DataExtractor will have to treat // offset_ptr as uint64_t* uint32_t EndStructureOffset = Offset + static_cast<uint32_t>(Length); // The Id field's size depends on the DWARF format Id = Data.getUnsigned(&Offset, IsDWARF64 ? 8 : 4); bool IsCIE = ((IsDWARF64 && Id == DW64_CIE_ID) || Id == DW_CIE_ID); if (IsCIE) { // Note: this is specifically DWARFv3 CIE header structure. It was // changed in DWARFv4. uint8_t Version = Data.getU8(&Offset); const char *Augmentation = Data.getCStr(&Offset); uint64_t CodeAlignmentFactor = Data.getULEB128(&Offset); int64_t DataAlignmentFactor = Data.getSLEB128(&Offset); uint64_t ReturnAddressRegister = Data.getULEB128(&Offset); CIE *NewCIE = new CIE(Data, StartOffset, Length, Version, StringRef(Augmentation), CodeAlignmentFactor, DataAlignmentFactor, ReturnAddressRegister); Entries.push_back(NewCIE); } else { // FDE uint64_t CIEPointer = Id; uint64_t InitialLocation = Data.getAddress(&Offset); uint64_t AddressRange = Data.getAddress(&Offset); FDE *NewFDE = new FDE(Data, StartOffset, Length, CIEPointer, InitialLocation, AddressRange); Entries.push_back(NewFDE); } Offset = EndStructureOffset; } } void DWARFDebugFrame::dump(raw_ostream &OS) const { OS << "\n"; for (EntryVector::const_iterator I = Entries.begin(), E = Entries.end(); I != E; ++I) { (*I)->dumpHeader(OS); } } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "DeclCollector.h" #include "IncrementalParser.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" using namespace clang; namespace { ///\brief Return true if this decl (which comes from an AST file) should /// not be sent to CodeGen. The module is assumed to describe the contents /// of a library; symbols inside the library must thus not be reemitted / /// duplicated by CodeGen. /// static bool shouldIgnore(const Decl* D) { // This function is called for all "deserialized" decls, where the // "deserialized" decl either really comes from an AST file or from // a header that's loaded to import the AST for a library with a dictionary // (the non-PCM case). // // Functions that are inlined must be sent to CodeGen - they will not have a // symbol in the library. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) { if (D->isFromASTFile()) { return !FD->hasBody(); } else { // If the decl must be emitted then it will be in the library. // If not, we must expose it to CodeGen now because it might // not be in the library. Does this correspond to a weak symbol // by definition? return !(FD->isInlined() || FD->isTemplateInstantiation()); } } // Don't codegen statics coming in from a module; they are already part of // the library. // We do need to expose static variables from template instantiations. if (const VarDecl* VD = dyn_cast<VarDecl>(D)) if (VD->hasGlobalStorage() && !VD->getType().isConstQualified() && VD->getTemplateSpecializationKind() == TSK_Undeclared) return true; return false; } } namespace cling { ///\brief Serves as DeclCollector's connector to the PPCallbacks interface. /// class DeclCollector::PPAdapter : public clang::PPCallbacks { cling::DeclCollector* m_Parent; void MacroDirective(const clang::Token& MacroNameTok, const clang::MacroDirective* MD) { assert(m_Parent->m_CurTransaction && "Missing transction"); Transaction::MacroDirectiveInfo MDE(MacroNameTok.getIdentifierInfo(), MD); m_Parent->m_CurTransaction->append(MDE); } public: PPAdapter(cling::DeclCollector* P) : m_Parent(P) {} /// \name PPCallbacks overrides /// Macro support void MacroDefined(const clang::Token& MacroNameTok, const clang::MacroDirective* MD) final { MacroDirective(MacroNameTok, MD); } /// \name PPCallbacks overrides /// Macro support void MacroUndefined(const clang::Token& MacroNameTok, const clang::MacroDefinition& MD, const clang::MacroDirective* Undef) final { if (Undef) MacroDirective(MacroNameTok, Undef); } }; void DeclCollector::Setup(IncrementalParser* IncrParser, ASTConsumer* Consumer, clang::Preprocessor& PP) { m_IncrParser = IncrParser; m_Consumer = Consumer; PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(new PPAdapter(this))); } bool DeclCollector::comesFromASTReader(DeclGroupRef DGR) const { assert(!DGR.isNull() && "DeclGroupRef is Null!"); assert(m_CurTransaction && "No current transaction when deserializing"); if (m_CurTransaction->getCompilationOpts().CodeGenerationForModule) return true; // Take the first/only decl in the group. Decl* D = *DGR.begin(); return D->isFromASTFile(); } bool DeclCollector::comesFromASTReader(const Decl* D) const { // The operation is const but clang::DeclGroupRef doesn't allow us to // express it. return comesFromASTReader(DeclGroupRef(const_cast<Decl*>(D))); } // pin the vtable here. DeclCollector::~DeclCollector() { } ASTTransformer::Result DeclCollector::TransformDecl(Decl* D) const { // We are sure it's safe to pipe it through the transformers // Consume late transformers init for (size_t i = 0; D && i < m_TransactionTransformers.size(); ++i) { ASTTransformer::Result NewDecl = m_TransactionTransformers[i]->Transform(D, m_CurTransaction); if (!NewDecl.getInt()) { m_CurTransaction->setIssuedDiags(Transaction::kErrors); return NewDecl; } D = NewDecl.getPointer(); } if (FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D)) { if (utils::Analyze::IsWrapper(FD)) { for (size_t i = 0; D && i < m_WrapperTransformers.size(); ++i) { ASTTransformer::Result NewDecl = m_WrapperTransformers[i]->Transform(D, m_CurTransaction); if (!NewDecl.getInt()) { m_CurTransaction->setIssuedDiags(Transaction::kErrors); return NewDecl; } D = NewDecl.getPointer(); } } } return ASTTransformer::Result(D, true); } bool DeclCollector::Transform(DeclGroupRef& DGR) { // Do not tranform recursively, e.g. when emitting a DeclExtracted decl. if (m_Transforming) return true; struct TransformingRAII { bool& m_Transforming; TransformingRAII(bool& Transforming): m_Transforming(Transforming) { m_Transforming = true; } ~TransformingRAII() { m_Transforming = false; } } transformingUpdater(m_Transforming); llvm::SmallVector<Decl*, 4> ReplacedDecls; bool HaveReplacement = false; for (Decl* D: DGR) { ASTTransformer::Result NewDecl = TransformDecl(D); if (!NewDecl.getInt()) return false; HaveReplacement |= (NewDecl.getPointer() != D); if (NewDecl.getPointer()) ReplacedDecls.push_back(NewDecl.getPointer()); } if (HaveReplacement) DGR = DeclGroupRef::Create((*DGR.begin())->getASTContext(), ReplacedDecls.data(), ReplacedDecls.size()); return true; } bool DeclCollector::HandleTopLevelDecl(DeclGroupRef DGR) { if (!Transform(DGR)) return false; if (DGR.isNull()) return true; assert(m_CurTransaction && "Missing transction"); Transaction::DelayCallInfo DCI(DGR, Transaction::kCCIHandleTopLevelDecl); m_CurTransaction->append(DCI); if (!m_Consumer || getTransaction()->getIssuedDiags() == Transaction::kErrors) return true; if (comesFromASTReader(DGR)) { for (DeclGroupRef::iterator DI = DGR.begin(), DE = DGR.end(); DI != DE; ++DI) { DeclGroupRef SplitDGR(*DI); // FIXME: The special namespace treatment (not sending itself to // CodeGen, but only its content - if the contained decl should be // emitted) works around issue with the static initialization when // having a PCH and loading a library. We don't want to generate // code for the static that will come through the library. // // This will be fixed with the clang::Modules. Make sure we remember. // assert(!getCI()->getLangOpts().Modules && "Please revisit!"); if (NamespaceDecl* ND = dyn_cast<NamespaceDecl>(*DI)) { for (NamespaceDecl::decl_iterator NDI = ND->decls_begin(), EN = ND->decls_end(); NDI != EN; ++NDI) { // Recurse over decls inside the namespace, like // CodeGenModule::EmitNamespace() does. if (!shouldIgnore(*NDI)) m_Consumer->HandleTopLevelDecl(DeclGroupRef(*NDI)); } } else if (!shouldIgnore(*DI)) { m_Consumer->HandleTopLevelDecl(DeclGroupRef(*DI)); } continue; } } else { m_Consumer->HandleTopLevelDecl(DGR); } return true; } void DeclCollector::HandleInterestingDecl(DeclGroupRef DGR) { assert(m_CurTransaction && "Missing transction"); Transaction::DelayCallInfo DCI(DGR, Transaction::kCCIHandleInterestingDecl); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DGR) || !shouldIgnore(*DGR.begin()))) m_Consumer->HandleTopLevelDecl(DGR); } void DeclCollector::HandleTagDeclDefinition(TagDecl* TD) { assert(m_CurTransaction && "Missing transction"); Transaction::DelayCallInfo DCI(DeclGroupRef(TD), Transaction::kCCIHandleTagDeclDefinition); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(TD)) || !shouldIgnore(TD))) m_Consumer->HandleTagDeclDefinition(TD); } void DeclCollector::HandleInvalidTagDeclDefinition(clang::TagDecl *TD){ assert(m_CurTransaction && "Missing transction"); Transaction::DelayCallInfo DCI(DeclGroupRef(TD), Transaction::kCCIHandleTagDeclDefinition); m_CurTransaction->append(DCI); m_CurTransaction->setIssuedDiags(Transaction::kErrors); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(TD)) || !shouldIgnore(TD))) m_Consumer->HandleInvalidTagDeclDefinition(TD); } void DeclCollector::HandleVTable(CXXRecordDecl* RD) { assert(m_CurTransaction && "Missing transction"); Transaction::DelayCallInfo DCI(DeclGroupRef(RD), Transaction::kCCIHandleVTable); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(RD)) || !shouldIgnore(RD))) m_Consumer->HandleVTable(RD); // Intentional no-op. It comes through Sema::DefineUsedVTables, which // comes either Sema::ActOnEndOfTranslationUnit or while instantiating a // template. In our case we will do it on transaction commit, without // keeping track of used vtables, because we have cases where we bypass the // clang/AST and directly ask the module so that we have to generate // everything without extra smartness. } void DeclCollector::CompleteTentativeDefinition(VarDecl* VD) { assert(m_CurTransaction && "Missing transction"); // C has tentative definitions which we might need to deal with when running // in C mode. Transaction::DelayCallInfo DCI(DeclGroupRef(VD), Transaction::kCCICompleteTentativeDefinition); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(VD)) || !shouldIgnore(VD))) m_Consumer->CompleteTentativeDefinition(VD); } void DeclCollector::HandleTranslationUnit(ASTContext& Ctx) { //if (m_Consumer) // m_Consumer->HandleTranslationUnit(Ctx); } void DeclCollector::HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) { assert(m_CurTransaction && "Missing transction"); Transaction::DelayCallInfo DCI(DeclGroupRef(D), Transaction::kCCIHandleCXXImplicitFunctionInstantiation); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(D)) || !shouldIgnore(D))) m_Consumer->HandleCXXImplicitFunctionInstantiation(D); } void DeclCollector::HandleCXXStaticMemberVarInstantiation(VarDecl *D) { assert(m_CurTransaction && "Missing transction"); Transaction::DelayCallInfo DCI(DeclGroupRef(D), Transaction::kCCIHandleCXXStaticMemberVarInstantiation); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(D)) || !shouldIgnore(D))) m_Consumer->HandleCXXStaticMemberVarInstantiation(D); } } // namespace cling <commit_msg>Print stacktrace before aborting on a missing exception.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "DeclCollector.h" #include "IncrementalParser.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" #include "llvm/Support/Signals.h" using namespace clang; namespace { ///\brief Return true if this decl (which comes from an AST file) should /// not be sent to CodeGen. The module is assumed to describe the contents /// of a library; symbols inside the library must thus not be reemitted / /// duplicated by CodeGen. /// static bool shouldIgnore(const Decl* D) { // This function is called for all "deserialized" decls, where the // "deserialized" decl either really comes from an AST file or from // a header that's loaded to import the AST for a library with a dictionary // (the non-PCM case). // // Functions that are inlined must be sent to CodeGen - they will not have a // symbol in the library. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) { if (D->isFromASTFile()) { return !FD->hasBody(); } else { // If the decl must be emitted then it will be in the library. // If not, we must expose it to CodeGen now because it might // not be in the library. Does this correspond to a weak symbol // by definition? return !(FD->isInlined() || FD->isTemplateInstantiation()); } } // Don't codegen statics coming in from a module; they are already part of // the library. // We do need to expose static variables from template instantiations. if (const VarDecl* VD = dyn_cast<VarDecl>(D)) if (VD->hasGlobalStorage() && !VD->getType().isConstQualified() && VD->getTemplateSpecializationKind() == TSK_Undeclared) return true; return false; } /// \brief Asserts that the given transaction is not null, otherwise prints a /// stack trace to stderr and aborts execution. static void assertHasTransaction(const cling::Transaction* T) { if (!T) { llvm::sys::PrintStackTrace(llvm::errs()); llvm_unreachable("Missing transaction during deserialization!"); } } } namespace cling { ///\brief Serves as DeclCollector's connector to the PPCallbacks interface. /// class DeclCollector::PPAdapter : public clang::PPCallbacks { cling::DeclCollector* m_Parent; void MacroDirective(const clang::Token& MacroNameTok, const clang::MacroDirective* MD) { assertHasTransaction(m_Parent->m_CurTransaction); Transaction::MacroDirectiveInfo MDE(MacroNameTok.getIdentifierInfo(), MD); m_Parent->m_CurTransaction->append(MDE); } public: PPAdapter(cling::DeclCollector* P) : m_Parent(P) {} /// \name PPCallbacks overrides /// Macro support void MacroDefined(const clang::Token& MacroNameTok, const clang::MacroDirective* MD) final { MacroDirective(MacroNameTok, MD); } /// \name PPCallbacks overrides /// Macro support void MacroUndefined(const clang::Token& MacroNameTok, const clang::MacroDefinition& MD, const clang::MacroDirective* Undef) final { if (Undef) MacroDirective(MacroNameTok, Undef); } }; void DeclCollector::Setup(IncrementalParser* IncrParser, ASTConsumer* Consumer, clang::Preprocessor& PP) { m_IncrParser = IncrParser; m_Consumer = Consumer; PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(new PPAdapter(this))); } bool DeclCollector::comesFromASTReader(DeclGroupRef DGR) const { assert(!DGR.isNull() && "DeclGroupRef is Null!"); assertHasTransaction(m_CurTransaction); if (m_CurTransaction->getCompilationOpts().CodeGenerationForModule) return true; // Take the first/only decl in the group. Decl* D = *DGR.begin(); return D->isFromASTFile(); } bool DeclCollector::comesFromASTReader(const Decl* D) const { // The operation is const but clang::DeclGroupRef doesn't allow us to // express it. return comesFromASTReader(DeclGroupRef(const_cast<Decl*>(D))); } // pin the vtable here. DeclCollector::~DeclCollector() { } ASTTransformer::Result DeclCollector::TransformDecl(Decl* D) const { // We are sure it's safe to pipe it through the transformers // Consume late transformers init for (size_t i = 0; D && i < m_TransactionTransformers.size(); ++i) { ASTTransformer::Result NewDecl = m_TransactionTransformers[i]->Transform(D, m_CurTransaction); if (!NewDecl.getInt()) { m_CurTransaction->setIssuedDiags(Transaction::kErrors); return NewDecl; } D = NewDecl.getPointer(); } if (FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D)) { if (utils::Analyze::IsWrapper(FD)) { for (size_t i = 0; D && i < m_WrapperTransformers.size(); ++i) { ASTTransformer::Result NewDecl = m_WrapperTransformers[i]->Transform(D, m_CurTransaction); if (!NewDecl.getInt()) { m_CurTransaction->setIssuedDiags(Transaction::kErrors); return NewDecl; } D = NewDecl.getPointer(); } } } return ASTTransformer::Result(D, true); } bool DeclCollector::Transform(DeclGroupRef& DGR) { // Do not tranform recursively, e.g. when emitting a DeclExtracted decl. if (m_Transforming) return true; struct TransformingRAII { bool& m_Transforming; TransformingRAII(bool& Transforming): m_Transforming(Transforming) { m_Transforming = true; } ~TransformingRAII() { m_Transforming = false; } } transformingUpdater(m_Transforming); llvm::SmallVector<Decl*, 4> ReplacedDecls; bool HaveReplacement = false; for (Decl* D: DGR) { ASTTransformer::Result NewDecl = TransformDecl(D); if (!NewDecl.getInt()) return false; HaveReplacement |= (NewDecl.getPointer() != D); if (NewDecl.getPointer()) ReplacedDecls.push_back(NewDecl.getPointer()); } if (HaveReplacement) DGR = DeclGroupRef::Create((*DGR.begin())->getASTContext(), ReplacedDecls.data(), ReplacedDecls.size()); return true; } bool DeclCollector::HandleTopLevelDecl(DeclGroupRef DGR) { if (!Transform(DGR)) return false; if (DGR.isNull()) return true; assertHasTransaction(m_CurTransaction); Transaction::DelayCallInfo DCI(DGR, Transaction::kCCIHandleTopLevelDecl); m_CurTransaction->append(DCI); if (!m_Consumer || getTransaction()->getIssuedDiags() == Transaction::kErrors) return true; if (comesFromASTReader(DGR)) { for (DeclGroupRef::iterator DI = DGR.begin(), DE = DGR.end(); DI != DE; ++DI) { DeclGroupRef SplitDGR(*DI); // FIXME: The special namespace treatment (not sending itself to // CodeGen, but only its content - if the contained decl should be // emitted) works around issue with the static initialization when // having a PCH and loading a library. We don't want to generate // code for the static that will come through the library. // // This will be fixed with the clang::Modules. Make sure we remember. // assert(!getCI()->getLangOpts().Modules && "Please revisit!"); if (NamespaceDecl* ND = dyn_cast<NamespaceDecl>(*DI)) { for (NamespaceDecl::decl_iterator NDI = ND->decls_begin(), EN = ND->decls_end(); NDI != EN; ++NDI) { // Recurse over decls inside the namespace, like // CodeGenModule::EmitNamespace() does. if (!shouldIgnore(*NDI)) m_Consumer->HandleTopLevelDecl(DeclGroupRef(*NDI)); } } else if (!shouldIgnore(*DI)) { m_Consumer->HandleTopLevelDecl(DeclGroupRef(*DI)); } continue; } } else { m_Consumer->HandleTopLevelDecl(DGR); } return true; } void DeclCollector::HandleInterestingDecl(DeclGroupRef DGR) { assertHasTransaction(m_CurTransaction); Transaction::DelayCallInfo DCI(DGR, Transaction::kCCIHandleInterestingDecl); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DGR) || !shouldIgnore(*DGR.begin()))) m_Consumer->HandleTopLevelDecl(DGR); } void DeclCollector::HandleTagDeclDefinition(TagDecl* TD) { assertHasTransaction(m_CurTransaction); Transaction::DelayCallInfo DCI(DeclGroupRef(TD), Transaction::kCCIHandleTagDeclDefinition); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(TD)) || !shouldIgnore(TD))) m_Consumer->HandleTagDeclDefinition(TD); } void DeclCollector::HandleInvalidTagDeclDefinition(clang::TagDecl *TD){ assertHasTransaction(m_CurTransaction); Transaction::DelayCallInfo DCI(DeclGroupRef(TD), Transaction::kCCIHandleTagDeclDefinition); m_CurTransaction->append(DCI); m_CurTransaction->setIssuedDiags(Transaction::kErrors); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(TD)) || !shouldIgnore(TD))) m_Consumer->HandleInvalidTagDeclDefinition(TD); } void DeclCollector::HandleVTable(CXXRecordDecl* RD) { assertHasTransaction(m_CurTransaction); Transaction::DelayCallInfo DCI(DeclGroupRef(RD), Transaction::kCCIHandleVTable); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(RD)) || !shouldIgnore(RD))) m_Consumer->HandleVTable(RD); // Intentional no-op. It comes through Sema::DefineUsedVTables, which // comes either Sema::ActOnEndOfTranslationUnit or while instantiating a // template. In our case we will do it on transaction commit, without // keeping track of used vtables, because we have cases where we bypass the // clang/AST and directly ask the module so that we have to generate // everything without extra smartness. } void DeclCollector::CompleteTentativeDefinition(VarDecl* VD) { assertHasTransaction(m_CurTransaction); // C has tentative definitions which we might need to deal with when running // in C mode. Transaction::DelayCallInfo DCI(DeclGroupRef(VD), Transaction::kCCICompleteTentativeDefinition); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(VD)) || !shouldIgnore(VD))) m_Consumer->CompleteTentativeDefinition(VD); } void DeclCollector::HandleTranslationUnit(ASTContext& Ctx) { //if (m_Consumer) // m_Consumer->HandleTranslationUnit(Ctx); } void DeclCollector::HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) { assertHasTransaction(m_CurTransaction); Transaction::DelayCallInfo DCI(DeclGroupRef(D), Transaction::kCCIHandleCXXImplicitFunctionInstantiation); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(D)) || !shouldIgnore(D))) m_Consumer->HandleCXXImplicitFunctionInstantiation(D); } void DeclCollector::HandleCXXStaticMemberVarInstantiation(VarDecl *D) { assertHasTransaction(m_CurTransaction); Transaction::DelayCallInfo DCI(DeclGroupRef(D), Transaction::kCCIHandleCXXStaticMemberVarInstantiation); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(D)) || !shouldIgnore(D))) m_Consumer->HandleCXXStaticMemberVarInstantiation(D); } } // namespace cling <|endoftext|>
<commit_before>#include "ImGuiEntityEditorSystem.hpp" #include "EntityManager.hpp" #include "components/ImGuiComponent.hpp" #include "components/SelectedComponent.hpp" #include "functions/Basic.hpp" #include "functions/ImGuiEditor.hpp" #include "packets/AddImGuiTool.hpp" #include "imgui.h" auto ImGuiEntityEditor(kengine::EntityManager & em) { return [&](kengine::Entity & e) { static bool display = true; em.send(kengine::packets::AddImGuiTool{ "Entity editor", display }); e += kengine::ImGuiComponent([&] { if (!display) return; for (auto &[selected, _] : em.getEntities<kengine::SelectedComponent>()) { bool open = true; if (ImGui::Begin(putils::string<64>("[%d] Entity editor", selected.id), &open)) { static char nameSearch[1024] = ""; ImGui::InputText("Component", nameSearch, sizeof(nameSearch)); const auto components = em.getComponentFunctionMaps(); if (ImGui::CollapsingHeader("Edit")) for (const auto comp : components) { const auto has = comp->getFunction<kengine::functions::Has>(); const auto edit = comp->getFunction<kengine::functions::EditImGui>(); if (has != nullptr && edit != nullptr && strstr(comp->name, nameSearch) && has(selected)) if (ImGui::TreeNode(comp->name)) { edit(selected); ImGui::TreePop(); } } if (ImGui::CollapsingHeader("Add")) for (const auto comp : components) { const auto has = comp->getFunction<kengine::functions::Has>(); const auto add = comp->getFunction<kengine::functions::Attach>(); if (has != nullptr && add != nullptr && strstr(comp->name, nameSearch) && !has(selected)) if (ImGui::Button(comp->name)) add(selected); } if (ImGui::CollapsingHeader("Remove")) for (const auto comp : components) { const auto has = comp->getFunction<kengine::functions::Has>(); const auto remove = comp->getFunction<kengine::functions::Detach>(); if (has != nullptr && remove != nullptr && strstr(comp->name, nameSearch) && has(selected)) if (ImGui::Button(putils::string<64>(comp->name) + "##remove")) remove(selected); } } ImGui::End(); if (!open) selected.detach<kengine::SelectedComponent>(); } }); }; } void kengine::ImGuiEntityEditorSystem::onLoad(const char * directory) noexcept { _em += ImGuiEntityEditor(_em); } <commit_msg>improved entity editor layout<commit_after>#include "ImGuiEntityEditorSystem.hpp" #include "EntityManager.hpp" #include "components/ImGuiComponent.hpp" #include "components/SelectedComponent.hpp" #include "functions/Basic.hpp" #include "functions/ImGuiEditor.hpp" #include "packets/AddImGuiTool.hpp" #include "imgui.h" auto ImGuiEntityEditor(kengine::EntityManager & em) { return [&](kengine::Entity & e) { static bool display = true; em.send(kengine::packets::AddImGuiTool{ "Entity editor", display }); e += kengine::ImGuiComponent([&] { if (!display) return; for (auto &[selected, _] : em.getEntities<kengine::SelectedComponent>()) { ImGui::SetNextWindowSize({ 200.f, 200.f}, ImGuiCond_FirstUseEver); if (ImGui::Begin(putils::string<64>("[%d] Entity editor", selected.id), nullptr, ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar)) { if (ImGui::Button("x")) selected.detach<kengine::SelectedComponent>(); ImGui::SameLine(); ImGui::Text("Search"); ImGui::SameLine(); static char nameSearch[1024] = ""; ImGui::PushItemWidth(-1.f); ImGui::InputText("##Search", nameSearch, sizeof(nameSearch)); ImGui::PopItemWidth(); { ImGui::BeginChild("##child"); const auto components = em.getComponentFunctionMaps(); if (ImGui::CollapsingHeader("Edit")) for (const auto comp : components) { const auto has = comp->getFunction<kengine::functions::Has>(); const auto edit = comp->getFunction<kengine::functions::EditImGui>(); if (has != nullptr && edit != nullptr && strstr(comp->name, nameSearch) && has(selected)) if (ImGui::TreeNode(putils::string<64>(comp->name) + "##edit")) { edit(selected); ImGui::TreePop(); } } if (ImGui::CollapsingHeader("Add")) for (const auto comp : components) { const auto has = comp->getFunction<kengine::functions::Has>(); const auto add = comp->getFunction<kengine::functions::Attach>(); if (has != nullptr && add != nullptr && strstr(comp->name, nameSearch) && !has(selected)) if (ImGui::Button(putils::string<64>(comp->name) + "##add")) add(selected); } if (ImGui::CollapsingHeader("Remove")) for (const auto comp : components) { const auto has = comp->getFunction<kengine::functions::Has>(); const auto remove = comp->getFunction<kengine::functions::Detach>(); if (has != nullptr && remove != nullptr && strstr(comp->name, nameSearch) && has(selected)) if (ImGui::Button(putils::string<64>(comp->name) + "##remove")) remove(selected); } ImGui::EndChild(); } } ImGui::End(); } }); }; } void kengine::ImGuiEntityEditorSystem::onLoad(const char * directory) noexcept { _em += ImGuiEntityEditor(_em); } <|endoftext|>
<commit_before>#include "CameraAim.h" #include "Subsystems/Chassis.h" #include "Subsystems/Catapult.h" #include "OI.h" #include "Misc/Video.h" CameraAim::CameraAim(Target_side side) : m_side(side) , m_prevAngle(0) , m_gotVisual(false) { Requires(Chassis::GetInstance()); } // Called just before this Command runs the first time void CameraAim::Initialize() { frame_timer.Reset(); frame_timer.Start(); m_prevAngle = Chassis::GetInstance()->GetAngle(); cycle_timer.Reset(); cycle_timer.Start(); RobotVideo::GetInstance()->SetHeadingQueueSize(0); RobotVideo::GetInstance()->SetLocationQueueSize(10); Chassis::GetInstance()->Shift(true); m_gotVisual = false; } /** * \brief Magic function that returns desired stop angle in rope inches * * The data collected from repeated shooting at the last night of the build * season suggest that the stop angle of the catapult is pretty much a linear * function. Here we are going to account for the robot's velocity related * to the tower. */ double calculateStop(double dist, double speed=0) { // Interpolated by Google Spreadsheets return -1.99e-4 * dist*dist + 0.08 * dist + 10.752; } // Called repeatedly when this Command is scheduled to run void CameraAim::Execute() { Chassis *chassis = Chassis::GetInstance(); OI* oi = OI::GetInstance(); if (chassis == nullptr or oi == nullptr) return; if (!m_gotVisual or frame_timer.Get() > Preferences::GetInstance()->GetDouble("CameraLag", AIM_COOLDOWN)) { float turn = 0; float dist = 0; size_t nTurns = 0; RobotVideo::GetInstance()->mutex_lock(); nTurns = RobotVideo::GetInstance()->HaveHeading(); if(nTurns > 0) { turn = RobotVideo::GetInstance()->GetTurn(0); dist = RobotVideo::GetInstance()->GetDistance(0); } if(m_side == kRight and nTurns > 1) { turn = RobotVideo::GetInstance()->GetTurn(1); dist = RobotVideo::GetInstance()->GetDistance(1); } RobotVideo::GetInstance()->mutex_unlock(); if (nTurns > 0) { if (dist > 0) { // Call the Magic function to determine the stop angle. float catStop = calculateStop(dist); if (catStop > Catapult::TOP_ZONE) catStop = Catapult::TOP_ZONE; if (catStop < Catapult::SLOW_ZONE) catStop = Catapult::SLOW_ZONE; Catapult::GetInstance()->toSetpoint(catStop); // The camera offset over the distance is the adjustment angle's tangent turn += atan2f(Preferences::GetInstance()->GetFloat("CameraOffset",RobotVideo::CAMERA_OFFSET), dist); } chassis->HoldAngle(turn); frame_timer.Reset(); m_gotVisual = true; } else { m_gotVisual = false; } } else if (cycle_timer.Get() > 0) { double angular_v = (chassis->GetAngle() - m_prevAngle) / cycle_timer.Get(); if (fabs(angular_v) > Preferences::GetInstance()->GetDouble("AngularVelocity", MAX_ANGULAR_V)) frame_timer.Reset(); // Take this measurement for tuning purposes. Remove after the tuning is done SmartDashboard::PutNumber("Angular Velocity", angular_v); } m_prevAngle = chassis->GetAngle(); cycle_timer.Reset(); // Check the catapult output current for safety if (Catapult::GetInstance()->WatchCurrent()) Catapult::GetInstance()->moveCatapult(0); // Drive forward or back while aiming double moveSpeed = -oi->stickL->GetY(); if (m_gotVisual) { moveSpeed *= fabs(moveSpeed); // Square it here so the drivers will feel like it's squared chassis->DriveStraight(moveSpeed); } else { // If we still have no visual the chassis is not in PID mode yet, so drive Arcade chassis->DriveArcade(moveSpeed, 0, true); } } // Make this return true when this Command no longer needs to run execute() bool CameraAim::IsFinished() { return false; } // Called once after isFinished returns true void CameraAim::End() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run void CameraAim::Interrupted() { } <commit_msg>Updated stop angle magic function<commit_after>#include "CameraAim.h" #include "Subsystems/Chassis.h" #include "Subsystems/Catapult.h" #include "OI.h" #include "Misc/Video.h" CameraAim::CameraAim(Target_side side) : m_side(side) , m_prevAngle(0) , m_gotVisual(false) { Requires(Chassis::GetInstance()); } // Called just before this Command runs the first time void CameraAim::Initialize() { frame_timer.Reset(); frame_timer.Start(); m_prevAngle = Chassis::GetInstance()->GetAngle(); cycle_timer.Reset(); cycle_timer.Start(); RobotVideo::GetInstance()->SetHeadingQueueSize(0); RobotVideo::GetInstance()->SetLocationQueueSize(10); Chassis::GetInstance()->Shift(true); m_gotVisual = false; } /** * \brief Magic function that returns desired stop angle in rope inches * * The data collected from repeated shooting at the last night of the build * season suggest that the stop angle of the catapult is pretty much a linear * function. Here we are going to account for the robot's velocity related * to the tower. */ double calculateStop(double dist, double speed=0) { // Top slider sets the bias from "New" (0) to "Old" (5) balls double bias = SmartDashboard::GetNumber("DB/Slider 0", 0) / 5; // Interpolated by Google Spreadsheets double a = -2.573e-4 -6e-7 * bias; double b = 0.088 -2e-3 * bias; double c = 10.696 +0.042 * bias; return a * dist * dist + b * dist + c; } // Called repeatedly when this Command is scheduled to run void CameraAim::Execute() { Chassis *chassis = Chassis::GetInstance(); OI* oi = OI::GetInstance(); if (chassis == nullptr or oi == nullptr) return; if (!m_gotVisual or frame_timer.Get() > Preferences::GetInstance()->GetDouble("CameraLag", AIM_COOLDOWN)) { float turn = 0; float dist = 0; size_t nTurns = 0; RobotVideo::GetInstance()->mutex_lock(); nTurns = RobotVideo::GetInstance()->HaveHeading(); if(nTurns > 0) { turn = RobotVideo::GetInstance()->GetTurn(0); dist = RobotVideo::GetInstance()->GetDistance(0); } if(m_side == kRight and nTurns > 1) { turn = RobotVideo::GetInstance()->GetTurn(1); dist = RobotVideo::GetInstance()->GetDistance(1); } RobotVideo::GetInstance()->mutex_unlock(); if (nTurns > 0) { if (dist > 0) { // Call the Magic function to determine the stop angle. float catStop = calculateStop(dist); if (catStop > Catapult::TOP_ZONE) catStop = Catapult::TOP_ZONE; if (catStop < Catapult::SLOW_ZONE) catStop = Catapult::SLOW_ZONE; Catapult::GetInstance()->toSetpoint(catStop); // The camera offset over the distance is the adjustment angle's tangent turn += atan2f(Preferences::GetInstance()->GetFloat("CameraOffset",RobotVideo::CAMERA_OFFSET), dist); } chassis->HoldAngle(turn); frame_timer.Reset(); m_gotVisual = true; } else { m_gotVisual = false; } } else if (cycle_timer.Get() > 0) { double angular_v = (chassis->GetAngle() - m_prevAngle) / cycle_timer.Get(); if (fabs(angular_v) > Preferences::GetInstance()->GetDouble("AngularVelocity", MAX_ANGULAR_V)) frame_timer.Reset(); // Take this measurement for tuning purposes. Remove after the tuning is done SmartDashboard::PutNumber("Angular Velocity", angular_v); } m_prevAngle = chassis->GetAngle(); cycle_timer.Reset(); // Check the catapult output current for safety if (Catapult::GetInstance()->WatchCurrent()) Catapult::GetInstance()->moveCatapult(0); // Drive forward or back while aiming double moveSpeed = -oi->stickL->GetY(); if (m_gotVisual) { moveSpeed *= fabs(moveSpeed); // Square it here so the drivers will feel like it's squared chassis->DriveStraight(moveSpeed); } else { // If we still have no visual the chassis is not in PID mode yet, so drive Arcade chassis->DriveArcade(moveSpeed, 0, true); } } // Make this return true when this Command no longer needs to run execute() bool CameraAim::IsFinished() { return false; } // Called once after isFinished returns true void CameraAim::End() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run void CameraAim::Interrupted() { } <|endoftext|>
<commit_before>/* * GLShaderSourcePatcher.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "GLShaderSourcePatcher.h" #include <LLGL/ShaderFlags.h> #include <string.h> namespace LLGL { static bool IsWhitespace(char c) { return c == ' ' || c == '\t'; } static bool ScanToken(const char*& s, char tokenChar) { if (s[0] == tokenChar) { s += 1; return true; } return false; } static bool ScanToken(const char*& s, char tokenChar0, char tokenChar1) { if (s[0] == tokenChar0 && s[1] == tokenChar1) { s += 2; return true; } return false; } static bool ScanToken(const char*& s, const char* token) { const auto tokenLen = ::strlen(token); if (::strncmp(s, token, tokenLen) == 0) { s += tokenLen; return true; } return false; } static void SkipUntilToken(const char*& s, char tokenChar) { while (!ScanToken(s, tokenChar)) ++s; } static void SkipUntilToken(const char*& s, char tokenChar0, char tokenChar1) { while (!ScanToken(s, tokenChar0, tokenChar1)) ++s; } static void SkipWhitespaces(const char*& s) { while (IsWhitespace(*s)) ++s; } static bool SkipComment(const char*& s) { if (ScanToken(s, "//")) { /* Ignore single line comment */ SkipUntilToken(s, '\n'); return true; } else if (ScanToken(s, "/*")) { /* Ignore multi line comment */ SkipUntilToken(s, '*', '/'); return true; } return false; } // Returns the source position after the '#version'-directive. This is always at the beginning of a new line. static std::size_t FindEndOfVersionDirective(const char* source) { const char* s = source; while (*s != '\0') { if (SkipComment(s)) { /* Ignore comments */ continue; } else if (ScanToken(s, "#")) { /* Ignore whitespaces after '#' token */ SkipWhitespaces(s); /* Scan for "version" token */ if (ScanToken(s, "version")) { /* There has to be at least one more whitespace */ if (IsWhitespace(*s)) { /* Jump to end of line */ for (++s; *s != '\0'; ++s) { if (ScanToken(s, '\n')) return static_cast<std::size_t>(s - source); } } } } else { /* Move to next character */ ++s; } } return std::string::npos; } GLShaderSourcePatcher::GLShaderSourcePatcher(const char* source) : source_ { source } { const auto posAfterVersion = FindEndOfVersionDirective(source); if (posAfterVersion != std::string::npos) statementInsertPos_ = posAfterVersion; } void GLShaderSourcePatcher::AddDefines(const ShaderMacro* defines) { if (defines != nullptr) { /* Generate macro definition code */ std::string defineCode; for (; defines->name != nullptr; ++defines) { defineCode += "#define "; defineCode += defines->name; if (defines->definition != nullptr) { defineCode += ' '; defineCode += defines->definition; } defineCode += '\n'; } /* Insert macro definitions into source */ InsertAfterVersionDirective(defineCode); } } void GLShaderSourcePatcher::AddPragmaDirective(const char* statement) { if (statement != nullptr && *statement != '\0') { /* Generate '#pragma'-directive code and insert into source */ std::string pragmaCode = "#pragma "; pragmaCode += statement; pragmaCode += '\n'; InsertAfterVersionDirective(pragmaCode); } } struct SourceScanState { std::string patched; std::size_t codeBlockDepth = 0; const char* head = nullptr; const char* lastPatched = nullptr; const char* lastToken = nullptr; const char* lastIndentRange[2] = {}; const char* currentIndentRange[2] = {}; SourceScanState(const char* source, std::size_t entryPointStartPos) : head { source + entryPointStartPos }, lastPatched { source }, currentIndentRange { head, nullptr } { } void Append(const char* to) { patched.append(lastPatched, to); lastPatched = to; } void AppendStatement(const char* statement, bool currentIndent = false) { /* Append input source from last patched position to end of previous line (before current indentation start) */ Append(currentIndentRange[0]); /* If last token was not the end of the current indentation range, also add everything to that last token */ if (lastToken != currentIndentRange[1]) Append(lastToken); /* Append indentation from previous or current line */ if (currentIndent) patched.append(currentIndentRange[0], currentIndentRange[1] - currentIndentRange[0]); else patched.append(lastIndentRange[0], lastIndentRange[1] - lastIndentRange[0]); /* Append statement with newline */ patched += statement; patched += '\n'; } void AppendRemainder() { /* Append remaining source until current head position */ patched.append(lastPatched, head); lastPatched = head; } }; void GLShaderSourcePatcher::AddFinalVertexTransformStatements(const char* statement) { if (statement != nullptr && *statement != '\0') { CacheEntryPointSourceLocation(); /* Scan source from entry point start location */ SourceScanState scan{ GetSource(), entryPointStartPos_ }; for (auto& s = scan.head; *s != '\0'; scan.lastToken = scan.head) { if (SkipComment(s)) { /* Ignore comments */ continue; } else if (scan.currentIndentRange[0] > scan.currentIndentRange[1]) { /* Record end of current indentation */ if (IsWhitespace(*s)) { SkipWhitespaces(s); scan.currentIndentRange[1] = scan.head; } else scan.currentIndentRange[1] = scan.currentIndentRange[0]; } else if (ScanToken(s, '\n')) { /* Record previous indentation range */ scan.lastIndentRange[0] = scan.currentIndentRange[0]; scan.lastIndentRange[1] = scan.currentIndentRange[1]; /* Record new indentation range */ scan.currentIndentRange[0] = scan.head; } else if (ScanToken(s, '{')) { /* Record stepping into a code block */ scan.codeBlockDepth++; } else if (ScanToken(s, '}')) { /* Record stepping out of a code block and write last statement as we left the main entry point */ scan.codeBlockDepth--; if (scan.codeBlockDepth == 0) { scan.AppendStatement(statement); break; } } else if (ScanToken(s, "return")) { /* Append vertex transform statement before return statement */ scan.AppendStatement(statement, true); } else { /* Move to next character */ ++s; } } /* Replace source with finalized patched source */ scan.AppendRemainder(); source_ = std::move(scan.patched); } } /* * ======= Private: ======= */ void GLShaderSourcePatcher::InsertAfterVersionDirective(const std::string& statement) { /* Insert statement into source after version */ source_.insert(statementInsertPos_, statement); /* Move source location for next insertion at the end of newly added code */ statementInsertPos_ += statement.size(); /* Move source loation of previously cached entry point by the length of newly added code */ if (entryPointStartPos_ != std::string::npos) entryPointStartPos_ += statement.size(); } static std::size_t FindEntryPointSourceLocation(const char* source, std::size_t start) { const char* s = source + start; while (*s != '\0') { if (ScanToken(s, "//")) { /* Ignore single line comment */ SkipUntilToken(s, '\n'); } else if (ScanToken(s, "/*")) { /* Ignore multi line comment */ SkipUntilToken(s, '*', '/'); } else if (ScanToken(s, "void")) { /* Store position at start of current token */ const auto startPos = static_cast<std::size_t>(s - source - 4); /* Ignore whitespaces after 'void' token */ SkipWhitespaces(s); /* Scan for "main" identifier */ if (ScanToken(s, "main")) { SkipWhitespaces(s); if (ScanToken(s, '(')) { SkipWhitespaces(s); if (ScanToken(s, ')')) { /* Entry point found => return start position of main function */ return startPos; } } } } else { /* Move to next character */ ++s; } } return std::string::npos; } void GLShaderSourcePatcher::CacheEntryPointSourceLocation() { if (entryPointStartPos_ == std::string::npos) entryPointStartPos_ = FindEntryPointSourceLocation(GetSource(), statementInsertPos_); } } // /namespace LLGL // ================================================================================ <commit_msg>Fixed token scanning loop in GLShaderSourcePatcher.<commit_after>/* * GLShaderSourcePatcher.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "GLShaderSourcePatcher.h" #include <LLGL/ShaderFlags.h> #include <string.h> namespace LLGL { static bool IsWhitespace(char c) { return c == ' ' || c == '\t'; } static bool ScanToken(const char*& s, char tokenChar) { if (s[0] == tokenChar) { s += 1; return true; } return false; } static bool ScanToken(const char*& s, char tokenChar0, char tokenChar1) { if (s[0] == tokenChar0 && s[1] == tokenChar1) { s += 2; return true; } return false; } static bool ScanToken(const char*& s, const char* token) { const auto tokenLen = ::strlen(token); if (::strncmp(s, token, tokenLen) == 0) { s += tokenLen; return true; } return false; } static void SkipUntilToken(const char*& s, char tokenChar) { while (*s != '\0' && !ScanToken(s, tokenChar)) ++s; } static void SkipUntilToken(const char*& s, char tokenChar0, char tokenChar1) { while (*s != '\0' && !ScanToken(s, tokenChar0, tokenChar1)) ++s; } static void SkipWhitespaces(const char*& s) { while (IsWhitespace(*s)) ++s; } static bool SkipComment(const char*& s) { if (ScanToken(s, "//")) { /* Ignore single line comment */ SkipUntilToken(s, '\n'); return true; } else if (ScanToken(s, "/*")) { /* Ignore multi line comment */ SkipUntilToken(s, '*', '/'); return true; } return false; } // Returns the source position after the '#version'-directive. This is always at the beginning of a new line. static std::size_t FindEndOfVersionDirective(const char* source) { const char* s = source; while (*s != '\0') { if (SkipComment(s)) { /* Ignore comments */ continue; } else if (ScanToken(s, "#")) { /* Ignore whitespaces after '#' token */ SkipWhitespaces(s); /* Scan for "version" token */ if (ScanToken(s, "version")) { /* There has to be at least one more whitespace */ if (IsWhitespace(*s)) { /* Jump to end of line */ for (++s; *s != '\0'; ++s) { if (ScanToken(s, '\n')) return static_cast<std::size_t>(s - source); } } } } else { /* Move to next character */ ++s; } } return std::string::npos; } GLShaderSourcePatcher::GLShaderSourcePatcher(const char* source) : source_ { source } { const auto posAfterVersion = FindEndOfVersionDirective(source); if (posAfterVersion != std::string::npos) statementInsertPos_ = posAfterVersion; } void GLShaderSourcePatcher::AddDefines(const ShaderMacro* defines) { if (defines != nullptr) { /* Generate macro definition code */ std::string defineCode; for (; defines->name != nullptr; ++defines) { defineCode += "#define "; defineCode += defines->name; if (defines->definition != nullptr) { defineCode += ' '; defineCode += defines->definition; } defineCode += '\n'; } /* Insert macro definitions into source */ InsertAfterVersionDirective(defineCode); } } void GLShaderSourcePatcher::AddPragmaDirective(const char* statement) { if (statement != nullptr && *statement != '\0') { /* Generate '#pragma'-directive code and insert into source */ std::string pragmaCode = "#pragma "; pragmaCode += statement; pragmaCode += '\n'; InsertAfterVersionDirective(pragmaCode); } } struct SourceScanState { std::string patched; std::size_t codeBlockDepth = 0; const char* head = nullptr; const char* lastPatched = nullptr; const char* lastToken = nullptr; const char* lastIndentRange[2] = {}; const char* currentIndentRange[2] = {}; SourceScanState(const char* source, std::size_t entryPointStartPos) : head { source + entryPointStartPos }, lastPatched { source }, currentIndentRange { head, nullptr } { } void Append(const char* to) { patched.append(lastPatched, to); lastPatched = to; } void AppendStatement(const char* statement, bool currentIndent = false) { /* Append input source from last patched position to end of previous line (before current indentation start) */ Append(currentIndentRange[0]); /* If last token was not the end of the current indentation range, also add everything to that last token */ if (lastToken != currentIndentRange[1]) Append(lastToken); /* Append indentation from previous or current line */ if (currentIndent) patched.append(currentIndentRange[0], currentIndentRange[1] - currentIndentRange[0]); else patched.append(lastIndentRange[0], lastIndentRange[1] - lastIndentRange[0]); /* Append statement with newline */ patched += statement; patched += '\n'; } void AppendRemainder() { /* Append remaining source until current head position */ patched.append(lastPatched, head); lastPatched = head; } }; void GLShaderSourcePatcher::AddFinalVertexTransformStatements(const char* statement) { if (statement != nullptr && *statement != '\0') { CacheEntryPointSourceLocation(); /* Scan source from entry point start location */ SourceScanState scan{ GetSource(), entryPointStartPos_ }; for (auto& s = scan.head; *s != '\0'; scan.lastToken = scan.head) { if (SkipComment(s)) { /* Ignore comments */ continue; } else if (scan.currentIndentRange[0] > scan.currentIndentRange[1]) { /* Record end of current indentation */ if (IsWhitespace(*s)) { SkipWhitespaces(s); scan.currentIndentRange[1] = scan.head; } else scan.currentIndentRange[1] = scan.currentIndentRange[0]; } else if (ScanToken(s, '\n')) { /* Record previous indentation range */ scan.lastIndentRange[0] = scan.currentIndentRange[0]; scan.lastIndentRange[1] = scan.currentIndentRange[1]; /* Record new indentation range */ scan.currentIndentRange[0] = scan.head; } else if (ScanToken(s, '{')) { /* Record stepping into a code block */ scan.codeBlockDepth++; } else if (ScanToken(s, '}')) { /* Record stepping out of a code block and write last statement as we left the main entry point */ scan.codeBlockDepth--; if (scan.codeBlockDepth == 0) { scan.AppendStatement(statement); break; } } else if (ScanToken(s, "return")) { /* Append vertex transform statement before return statement */ scan.AppendStatement(statement, true); } else { /* Move to next character */ ++s; } } /* Replace source with finalized patched source */ scan.AppendRemainder(); source_ = std::move(scan.patched); } } /* * ======= Private: ======= */ void GLShaderSourcePatcher::InsertAfterVersionDirective(const std::string& statement) { /* Insert statement into source after version */ source_.insert(statementInsertPos_, statement); /* Move source location for next insertion at the end of newly added code */ statementInsertPos_ += statement.size(); /* Move source loation of previously cached entry point by the length of newly added code */ if (entryPointStartPos_ != std::string::npos) entryPointStartPos_ += statement.size(); } static std::size_t FindEntryPointSourceLocation(const char* source, std::size_t start) { const char* s = source + start; while (*s != '\0') { if (ScanToken(s, "//")) { /* Ignore single line comment */ SkipUntilToken(s, '\n'); } else if (ScanToken(s, "/*")) { /* Ignore multi line comment */ SkipUntilToken(s, '*', '/'); } else if (ScanToken(s, "void")) { /* Store position at start of current token */ const auto startPos = static_cast<std::size_t>(s - source - 4); /* Ignore whitespaces after 'void' token */ SkipWhitespaces(s); /* Scan for "main" identifier */ if (ScanToken(s, "main")) { SkipWhitespaces(s); if (ScanToken(s, '(')) { SkipWhitespaces(s); if (ScanToken(s, ')')) { /* Entry point found => return start position of main function */ return startPos; } } } } else { /* Move to next character */ ++s; } } return std::string::npos; } void GLShaderSourcePatcher::CacheEntryPointSourceLocation() { if (entryPointStartPos_ == std::string::npos) entryPointStartPos_ = FindEntryPointSourceLocation(GetSource(), statementInsertPos_); } } // /namespace LLGL // ================================================================================ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_getecid.C /// /// @brief Get ECID string from target using SCOM //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : sunil kumar <[email protected]> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ #include "p9_getecid.H" #include <p9_misc_scom_addresses.H> #include <p9_misc_scom_addresses_fld.H> #include <p9_const_common.H> // The bit locations in ecid_part02 where the DD Level is found. These correspond to ECID bits 173:175 constexpr uint64_t DD_LEVEL(45); constexpr uint64_t DD_LEVEL_LEN(3); static fapi2::ReturnCode setup_memory_work_around_attributes( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const fapi2::buffer<uint64_t>& i_ecid_part) { uint8_t l_version = 0; i_ecid_part.extractToRight<DD_LEVEL, DD_LEVEL_LEN>(l_version); // Workarounds for modules which are before 1.02 (memory part 1) if (l_version < ddLevelMemoryPart1) { FAPI_DBG("seeing version < 1.02 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_WR_VREF, i_target, l_value) ); FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_VREF_DAC, i_target, l_value) ); } // Workarounds for modules which are before 1.03 (memory part 2) if (l_version < ddLevelMemoryPart2) { FAPI_DBG("seeing version < 1.03 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_TRAINING_BAD_BITS, i_target, l_value) ); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, fapi2::variable_buffer& o_fuseString) { uint64_t attr_data[2]; fapi2::buffer<uint64_t> l_ecid_part0_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part1_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part2_data64 = 0; fapi2::variable_buffer l_fuseString(fuseString_len); FAPI_INF("Entering ..."); FAPI_DBG("extract and manipulate ECID data"); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART0_REGISTER, l_ecid_part0_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART1_REGISTER, l_ecid_part1_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART2_REGISTER, l_ecid_part2_data64)); l_ecid_part0_data64.reverse(); l_ecid_part1_data64.reverse(); l_ecid_part2_data64.reverse(); attr_data[0] = l_ecid_part0_data64(); attr_data[1] = l_ecid_part1_data64(); FAPI_TRY(l_fuseString.insert(l_ecid_part0_data64(), 0, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part1_data64(), 64, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part2_data64(), 128, 48)); o_fuseString = l_fuseString; FAPI_DBG("push fuse string into attribute"); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_ECID, i_target_chip, attr_data)); // Set some attributes memory can used to make work-around decisions. FAPI_TRY( setup_memory_work_around_attributes(i_target_chip, l_ecid_part2_data64) ); FAPI_INF("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <commit_msg>p9_getecid -- set PCIE DD1.0x workaround attributes<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_getecid.C /// /// @brief Get ECID string from target using SCOM //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : sunil kumar <[email protected]> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ #include "p9_getecid.H" #include <p9_misc_scom_addresses.H> #include <p9_misc_scom_addresses_fld.H> #include <p9_const_common.H> // The bit locations in ecid_part02 where the DD Level is found. These correspond to ECID bits 173:175 constexpr uint64_t DD_LEVEL(45); constexpr uint64_t DD_LEVEL_LEN(3); static fapi2::ReturnCode setup_pcie_work_around_attributes( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const fapi2::buffer<uint64_t>& i_ecid_part) { uint8_t l_version = 0; i_ecid_part.extractToRight<DD_LEVEL, DD_LEVEL_LEN>(l_version); { // Workarounds for DD1.00 modulues fapi2::ATTR_CHIP_EC_FEATURE_PCIE_LOCK_PHASE_ROTATOR_Type l_ec_feature_pcie_lock_phase_rotator = 0; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_PCIE_LOCK_PHASE_ROTATOR, i_target, l_ec_feature_pcie_lock_phase_rotator), "Error from FAPI_ATTR_GET (ATTR_CHIP_EC_FEATURE_PCIE_LOCK_PHASE_ROTATOR)"); if (l_ec_feature_pcie_lock_phase_rotator && (l_version < ddLevelPciePart)) { FAPI_DBG("seeing version 1.00 (0x%x) setting attributes", l_version); uint8_t l_value = 1; for (auto& l_pec_trgt : i_target.getChildren<fapi2::TARGET_TYPE_PEC>(fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PROC_PCIE_PCS_RX_ROT_EXTEL, l_pec_trgt, l_value), "Error from FAPI_ATTR_SET (ATTR_PROC_PCIE_PCS_RX_ROT_EXTEL)"); } } } { // Workarounds for DD1.01/DD1.02 modules fapi2::ATTR_CHIP_EC_FEATURE_PCIE_DISABLE_FDDC_Type l_ec_feature_pcie_disable_fddc = 0; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_PCIE_DISABLE_FDDC, i_target, l_ec_feature_pcie_disable_fddc), "Error from FAPI_ATTR_GET (ATTR_CHIP_EC_FEATURE_PCIE_DISABLE_FDDC)"); if (l_ec_feature_pcie_disable_fddc && (l_version >= ddLevelPciePart)) { FAPI_DBG("seeing version >= 1.01 (0x%x) setting attributes", l_version); uint8_t l_value = 0; for (auto& l_pec_trgt : i_target.getChildren<fapi2::TARGET_TYPE_PEC>(fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PROC_PCIE_PCS_RX_DFE_FDDC, l_pec_trgt, l_value), "Error from FAPI_ATTR_SET (ATTR_PROC_PCIE_PCS_RX_DFE_FDDC)"); } } } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } static fapi2::ReturnCode setup_memory_work_around_attributes( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const fapi2::buffer<uint64_t>& i_ecid_part) { uint8_t l_version = 0; i_ecid_part.extractToRight<DD_LEVEL, DD_LEVEL_LEN>(l_version); // Workarounds for modules which are before 1.02 (memory part 1) if (l_version < ddLevelMemoryPart1) { FAPI_DBG("seeing version < 1.02 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_WR_VREF, i_target, l_value) ); FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_VREF_DAC, i_target, l_value) ); } // Workarounds for modules which are before 1.03 (memory part 2) if (l_version < ddLevelMemoryPart2) { FAPI_DBG("seeing version < 1.03 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_TRAINING_BAD_BITS, i_target, l_value) ); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, fapi2::variable_buffer& o_fuseString) { uint64_t attr_data[2]; fapi2::buffer<uint64_t> l_ecid_part0_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part1_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part2_data64 = 0; fapi2::variable_buffer l_fuseString(fuseString_len); FAPI_INF("Entering ..."); FAPI_DBG("extract and manipulate ECID data"); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART0_REGISTER, l_ecid_part0_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART1_REGISTER, l_ecid_part1_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART2_REGISTER, l_ecid_part2_data64)); l_ecid_part0_data64.reverse(); l_ecid_part1_data64.reverse(); l_ecid_part2_data64.reverse(); attr_data[0] = l_ecid_part0_data64(); attr_data[1] = l_ecid_part1_data64(); FAPI_TRY(l_fuseString.insert(l_ecid_part0_data64(), 0, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part1_data64(), 64, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part2_data64(), 128, 48)); o_fuseString = l_fuseString; FAPI_DBG("push fuse string into attribute"); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_ECID, i_target_chip, attr_data)); // Set some attributes memory can used to make work-around decisions. FAPI_TRY( setup_memory_work_around_attributes(i_target_chip, l_ecid_part2_data64) ); FAPI_TRY( setup_pcie_work_around_attributes(i_target_chip, l_ecid_part2_data64) ); FAPI_INF("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_getecid.C /// /// @brief Get ECID string from target using SCOM //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : sunil kumar <[email protected]> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ #include "p9_getecid.H" #include <p9_misc_scom_addresses.H> #include <p9_misc_scom_addresses_fld.H> #include <p9_const_common.H> // The bit locations in ecid_part02 where the DD Level is found. These correspond to ECID bits 173:175 constexpr uint64_t DD_LEVEL(45); constexpr uint64_t DD_LEVEL_LEN(3); static fapi2::ReturnCode setup_memory_work_around_attributes( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const fapi2::buffer<uint64_t>& i_ecid_part) { uint8_t l_version = 0; i_ecid_part.extractToRight<DD_LEVEL, DD_LEVEL_LEN>(l_version); // Workarounds for modules which are before 1.02 (memory part 1) if (l_version < ddLevelMemoryPart1) { FAPI_DBG("seeing version < 1.02 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_WR_VREF, i_target, l_value) ); FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_VCCD_OVERRIDE, i_target, l_value) ); FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_VREF_DAC, i_target, l_value) ); FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_VREG_COARSE, i_target, l_value) ); FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_TRAINING_BAD_BITS, i_target, l_value) ); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, fapi2::variable_buffer& o_fuseString) { uint64_t attr_data[2]; fapi2::buffer<uint64_t> l_ecid_part0_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part1_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part2_data64 = 0; fapi2::variable_buffer l_fuseString(fuseString_len); FAPI_INF("Entering ..."); FAPI_DBG("extract and manipulate ECID data"); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART0_REGISTER, l_ecid_part0_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART1_REGISTER, l_ecid_part1_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART2_REGISTER, l_ecid_part2_data64)); l_ecid_part0_data64.reverse(); l_ecid_part1_data64.reverse(); l_ecid_part2_data64.reverse(); attr_data[0] = l_ecid_part0_data64(); attr_data[1] = l_ecid_part1_data64(); FAPI_TRY(l_fuseString.insert(l_ecid_part0_data64(), 0, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part1_data64(), 64, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part2_data64(), 128, 48)); o_fuseString = l_fuseString; FAPI_DBG("push fuse string into attribute"); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_ECID, i_target_chip, attr_data)); // Set some attributes memory can used to make work-around decisions. FAPI_TRY( setup_memory_work_around_attributes(i_target_chip, l_ecid_part2_data64) ); FAPI_INF("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <commit_msg>Add MSS customization support from CRP0 Lx MVPD<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_getecid.C /// /// @brief Get ECID string from target using SCOM //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : sunil kumar <[email protected]> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ #include "p9_getecid.H" #include <p9_misc_scom_addresses.H> #include <p9_misc_scom_addresses_fld.H> #include <p9_const_common.H> // The bit locations in ecid_part02 where the DD Level is found. These correspond to ECID bits 173:175 constexpr uint64_t DD_LEVEL(45); constexpr uint64_t DD_LEVEL_LEN(3); static fapi2::ReturnCode setup_memory_work_around_attributes( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const fapi2::buffer<uint64_t>& i_ecid_part) { uint8_t l_version = 0; i_ecid_part.extractToRight<DD_LEVEL, DD_LEVEL_LEN>(l_version); // Workarounds for modules which are before 1.02 (memory part 1) if (l_version < ddLevelMemoryPart1) { FAPI_DBG("seeing version < 1.02 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_WR_VREF, i_target, l_value) ); FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_VREF_DAC, i_target, l_value) ); } // Workarounds for modules which are before 1.03 (memory part 2) if (l_version < ddLevelMemoryPart2) { FAPI_DBG("seeing version < 1.03 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_TRAINING_BAD_BITS, i_target, l_value) ); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, fapi2::variable_buffer& o_fuseString) { uint64_t attr_data[2]; fapi2::buffer<uint64_t> l_ecid_part0_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part1_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part2_data64 = 0; fapi2::variable_buffer l_fuseString(fuseString_len); FAPI_INF("Entering ..."); FAPI_DBG("extract and manipulate ECID data"); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART0_REGISTER, l_ecid_part0_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART1_REGISTER, l_ecid_part1_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART2_REGISTER, l_ecid_part2_data64)); l_ecid_part0_data64.reverse(); l_ecid_part1_data64.reverse(); l_ecid_part2_data64.reverse(); attr_data[0] = l_ecid_part0_data64(); attr_data[1] = l_ecid_part1_data64(); FAPI_TRY(l_fuseString.insert(l_ecid_part0_data64(), 0, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part1_data64(), 64, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part2_data64(), 128, 48)); o_fuseString = l_fuseString; FAPI_DBG("push fuse string into attribute"); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_ECID, i_target_chip, attr_data)); // Set some attributes memory can used to make work-around decisions. FAPI_TRY( setup_memory_work_around_attributes(i_target_chip, l_ecid_part2_data64) ); FAPI_INF("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AccessiblePresentationShape.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: af $ $Date: 2002-02-08 17:01:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PRESENTATION_SHAPE_HXX #include "AccessiblePresentationShape.hxx" #endif #include "SdShapeTypes.hxx" using namespace accessibility; using namespace ::rtl; using namespace ::com::sun::star; using namespace ::drafts::com::sun::star::accessibility; //===== internal ============================================================ AccessiblePresentationShape::AccessiblePresentationShape (const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape>& rxShape, const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible>& rxParent) : AccessibleShape (rxShape, rxParent) { } AccessiblePresentationShape::~AccessiblePresentationShape (void) { } //===== XServiceInfo ======================================================== ::rtl::OUString SAL_CALL AccessiblePresentationShape::getImplementationName (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM ("AccessiblePresentationShape")); } /// Set this object's name if is different to the current name. ::rtl::OUString AccessiblePresentationShape::createAccessibleName (void) throw (::com::sun::star::uno::RuntimeException) { ::rtl::OUString sName; ShapeTypeId nShapeType = ShapeTypeHandler::Instance().getTypeId (mxShape); switch (nShapeType) { case PRESENTATION_TITLE: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressTitle")); break; case PRESENTATION_OUTLINER: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressOutliner")); break; case PRESENTATION_SUBTITLE: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressSubtitle")); break; case PRESENTATION_GRAPHIC_OBJECT: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressGraphicObject")); break; case PRESENTATION_PAGE: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressPage")); break; case PRESENTATION_OLE: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressOLE")); break; case PRESENTATION_CHART: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressChart")); break; case PRESENTATION_TABLE: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressTable")); break; case PRESENTATION_NOTES: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressNotes")); break; case PRESENTATION_HANDOUT: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressHandout")); break; default: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ( "UnknownAccessibleImpressShape")); uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY); if (xDescriptor.is()) sName += ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM (": ")) + xDescriptor->getShapeType(); } return sName; } ::rtl::OUString AccessiblePresentationShape::createAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException) { return createAccessibleName (); } <commit_msg>#65293# Make Solaris compiler happy.<commit_after>/************************************************************************* * * $RCSfile: AccessiblePresentationShape.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: af $ $Date: 2002-02-08 18:08:49 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PRESENTATION_SHAPE_HXX #include "AccessiblePresentationShape.hxx" #endif #include "SdShapeTypes.hxx" using namespace accessibility; using namespace ::rtl; using namespace ::com::sun::star; using namespace ::drafts::com::sun::star::accessibility; //===== internal ============================================================ AccessiblePresentationShape::AccessiblePresentationShape (const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape>& rxShape, const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible>& rxParent) : AccessibleShape (rxShape, rxParent) { } AccessiblePresentationShape::~AccessiblePresentationShape (void) { } //===== XServiceInfo ======================================================== ::rtl::OUString SAL_CALL AccessiblePresentationShape::getImplementationName (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM ("AccessiblePresentationShape")); } /// Set this object's name if is different to the current name. ::rtl::OUString AccessiblePresentationShape::createAccessibleName (void) throw (::com::sun::star::uno::RuntimeException) { ::rtl::OUString sName; ShapeTypeId nShapeType = ShapeTypeHandler::Instance().getTypeId (mxShape); switch (nShapeType) { case PRESENTATION_TITLE: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressTitle")); break; case PRESENTATION_OUTLINER: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressOutliner")); break; case PRESENTATION_SUBTITLE: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressSubtitle")); break; case PRESENTATION_GRAPHIC_OBJECT: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressGraphicObject")); break; case PRESENTATION_PAGE: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressPage")); break; case PRESENTATION_OLE: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressOLE")); break; case PRESENTATION_CHART: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressChart")); break; case PRESENTATION_TABLE: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressTable")); break; case PRESENTATION_NOTES: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressNotes")); break; case PRESENTATION_HANDOUT: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("ImpressHandout")); break; default: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM ("UnknownAccessibleImpressShape")); uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY); if (xDescriptor.is()) sName += ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM (": ")) + xDescriptor->getShapeType(); } return sName; } ::rtl::OUString AccessiblePresentationShape::createAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException) { return createAccessibleName (); } <|endoftext|>
<commit_before>#include "pch.h" #include "aiInternal.h" #include "aiContext.h" #include "aiObject.h" #include "aiAsync.h" #include <istream> #ifdef WIN32 #include <windows.h> #include <io.h> #include <fcntl.h> #endif static std::wstring L(const std::string& s) { return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().from_bytes(s); } static std::string S(const std::wstring& w) { return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().to_bytes(w); } static std::string NormalizePath(const char *in_path) { std::wstring path; if (in_path != nullptr) { path = L(in_path); #ifdef _WIN32 size_t n = path.length(); for (size_t i = 0; i < n; ++i) { auto c = path[i]; if (c == L'\\') { path[i] = L'/'; } else if (c >= L'A' && c <= L'Z') { path[i] = L'a' + (c - L'A'); } } #endif } return S(path); } #ifdef WIN32 class lockFreeIStream : public std::ifstream { private: HANDLE _handle; FILE *Init(const wchar_t *name) { _handle = CreateFileW(name, GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (_handle == INVALID_HANDLE_VALUE) { return nullptr; } int nHandle = _open_osfhandle((long)_handle, _O_RDONLY); if (nHandle == -1) { ::CloseHandle(_handle); return nullptr; } auto fh = _fdopen(nHandle, "rb"); if (!fh) { ::CloseHandle(_handle); } return fh; } public: lockFreeIStream(const wchar_t *name) : std::ifstream(Init(name)) // Beware of constructors, initializers: Init changes the state of the class itself {} ~lockFreeIStream() { if (_handle != INVALID_HANDLE_VALUE) { ::CloseHandle(_handle); } } }; #endif aiContextManager aiContextManager::s_instance; aiContext* aiContextManager::getContext(int uid) { auto it = s_instance.m_contexts.find(uid); if (it != s_instance.m_contexts.end()) { DebugLog("Using already created context for gameObject with ID %d", uid); return it->second.get(); } auto ctx = new aiContext(uid); s_instance.m_contexts[uid].reset(ctx); DebugLog("Register context for gameObject with ID %d", uid); return ctx; } void aiContextManager::destroyContext(int uid) { auto it = s_instance.m_contexts.find(uid); if (it != s_instance.m_contexts.end()) { DebugLog("Unregister context for gameObject with ID %d", uid); s_instance.m_contexts.erase(it); } } void aiContextManager::destroyContextsWithPath(const char* asset_path) { auto path = NormalizePath(asset_path); for (auto it = s_instance.m_contexts.begin(); it != s_instance.m_contexts.end();) { if (it->second->getPath() == path) { DebugLog("Unregister context for gameObject with ID %s", it->second->getPath().c_str()); s_instance.m_contexts.erase(it++); } else { ++it; } } } aiContextManager::~aiContextManager() { if (m_contexts.size()) { DebugWarning("%lu remaining context(s) registered", m_contexts.size()); } m_contexts.clear(); } aiContext::aiContext(int uid) : m_uid(uid) { } aiContext::~aiContext() { reset(); } Abc::IArchive aiContext::getArchive() const { return m_archive; } const std::string& aiContext::getPath() const { return m_path; } int aiContext::getTimeSamplingCount() const { return (int)m_timesamplings.size(); } aiTimeSampling * aiContext::getTimeSampling(int i) { return m_timesamplings[i].get(); } void aiContext::getTimeRange(double& begin, double& end) const { begin = end = 0.0; for (size_t i = 1; i < m_timesamplings.size(); ++i) { double tmp_begin, tmp_end; m_timesamplings[i]->getTimeRange(tmp_begin, tmp_end); if (i == 1) { begin = tmp_begin; end = tmp_end; } else { begin = std::min(begin, tmp_begin); end = std::max(end, tmp_end); } } } int aiContext::getTimeSamplingCount() { return (int)m_timesamplings.size(); } int aiContext::getTimeSamplingIndex(Abc::TimeSamplingPtr ts) { int n = m_archive.getNumTimeSamplings(); for (int i = 0; i < n; ++i) { if (m_archive.getTimeSampling(i) == ts) { return i; } } return 0; } int aiContext::getUid() const { return m_uid; } const aiConfig& aiContext::getConfig() const { return m_config; } void aiContext::setConfig(const aiConfig &config) { m_config = config; } void aiContext::gatherNodesRecursive(aiObject *n) { auto& abc = n->getAbcObject(); size_t num_children = abc.getNumChildren(); for (size_t i = 0; i < num_children; ++i) { auto *child = n->newChild(abc.getChild(i)); gatherNodesRecursive(child); } } void aiContext::reset() { waitAsync(); m_top_node.reset(); m_timesamplings.clear(); m_archive.reset(); m_path.clear(); for (auto s : m_streams) { delete s; } m_streams.clear(); // m_config is not reset intentionally } bool aiContext::load(const char *in_path) { auto path = NormalizePath(in_path); auto wpath = L(in_path); DebugLogW(L"aiContext::load: '%s'", wpath.c_str()); if (path == m_path && m_archive) { DebugLog("Context already loaded for gameObject with id %d", m_uid); return true; } reset(); if (path.empty()) { return false; } m_path = path; if (!m_archive.valid()) { try { // Abc::IArchive doesn't accept wide string path. so create file stream with wide string path and pass it. // (VisualC++'s std::ifstream accepts wide string) m_streams.push_back( #ifdef WIN32 new lockFreeIStream(wpath.c_str()) #elif __linux__ new std::ifstream(in_path, std::ios::in | std::ios::binary) #else new std::ifstream(path.c_str(), std::ios::in | std::ios::binary) #endif ); Alembic::AbcCoreOgawa::ReadArchive archive_reader(m_streams); m_archive = Abc::IArchive(archive_reader(m_path), Abc::kWrapExisting, Abc::ErrorHandler::kThrowPolicy); DebugLog("Successfully opened Ogawa archive"); } catch (Alembic::Util::Exception e) { // HDF5 archive doesn't accept external stream. so close it. // (that means if path contains wide characters, it can't be opened. I couldn't find solution..) for (auto s : m_streams) { delete s; } m_streams.clear(); try { m_archive = Abc::IArchive(AbcCoreHDF5::ReadArchive(), path); DebugLog("Successfully opened HDF5 archive"); } catch (Alembic::Util::Exception e2) { auto message = L(e2.what()); DebugLogW(L"Failed to open archive: %s", message.c_str()); } } } else { DebugLogW(L"Archive '%s' already opened", wpath.c_str()); } if (m_archive.valid()) { abcObject abc_top = m_archive.getTop(); m_top_node.reset(new aiObject(this, nullptr, abc_top)); gatherNodesRecursive(m_top_node.get()); m_timesamplings.clear(); auto num_time_samplings = (int)m_archive.getNumTimeSamplings(); for (int i = 0; i < num_time_samplings; ++i) { m_timesamplings.emplace_back(aiCreateTimeSampling(m_archive, i)); } return true; } else { reset(); return false; } } aiObject* aiContext::getTopObject() const { return m_top_node.get(); } void aiContext::updateSamples(double time) { waitAsync(); auto ss = aiTimeToSampleSelector(time); eachNodes([ss](aiObject& o) { o.updateSample(ss); }); // kick async tasks! if (!m_async_tasks.empty()) { aiAsyncManager::instance().queue(m_async_tasks.data(), m_async_tasks.size()); } } void aiContext::queueAsync(aiAsync& task) { m_async_tasks.push_back(&task); } void aiContext::waitAsync() { for (auto task : m_async_tasks) task->wait(); m_async_tasks.clear(); } <commit_msg>More error handling<commit_after>#include "pch.h" #include "aiInternal.h" #include "aiContext.h" #include "aiObject.h" #include "aiAsync.h" #include <istream> #ifdef WIN32 #include <windows.h> #include <io.h> #include <fcntl.h> #endif static std::wstring L(const std::string& s) { return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().from_bytes(s); } static std::string S(const std::wstring& w) { return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().to_bytes(w); } static std::string NormalizePath(const char *in_path) { std::wstring path; if (in_path != nullptr) { path = L(in_path); #ifdef _WIN32 size_t n = path.length(); for (size_t i = 0; i < n; ++i) { auto c = path[i]; if (c == L'\\') { path[i] = L'/'; } else if (c >= L'A' && c <= L'Z') { path[i] = L'a' + (c - L'A'); } } #endif } return S(path); } #ifdef WIN32 class lockFreeIStream : public std::ifstream { private: HANDLE _handle; FILE *Init(const wchar_t *name) { _handle = CreateFileW(name, GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (_handle == INVALID_HANDLE_VALUE) { auto errorMsg = GetLastErrorAsString(); std::cerr << "Alembic cannot open:" << name <<":"<<errorMsg << std::endl; return nullptr; } int nHandle = _open_osfhandle((long)_handle, _O_RDONLY); if (nHandle == -1) { ::CloseHandle(_handle); return nullptr; } auto fh = _fdopen(nHandle, "rb"); if (!fh) { ::CloseHandle(_handle); } return fh; } public: lockFreeIStream(const wchar_t *name) : std::ifstream(Init(name)) // Beware of constructors, initializers: Init changes the state of the class itself {} ~lockFreeIStream() { if (_handle != INVALID_HANDLE_VALUE) { auto errorMsg = GetLastErrorAsString(); std::cerr << "Alembic cannot close HANDLE:" << errorMsg << std::endl; ::CloseHandle(_handle); } } private: std::string GetLastErrorAsString() { DWORD errorMessageID = ::GetLastError(); if (errorMessageID == 0) return std::string(); LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); std::string message(messageBuffer, size); LocalFree(messageBuffer); return message; } }; #endif aiContextManager aiContextManager::s_instance; aiContext* aiContextManager::getContext(int uid) { auto it = s_instance.m_contexts.find(uid); if (it != s_instance.m_contexts.end()) { DebugLog("Using already created context for gameObject with ID %d", uid); return it->second.get(); } auto ctx = new aiContext(uid); s_instance.m_contexts[uid].reset(ctx); DebugLog("Register context for gameObject with ID %d", uid); return ctx; } void aiContextManager::destroyContext(int uid) { auto it = s_instance.m_contexts.find(uid); if (it != s_instance.m_contexts.end()) { DebugLog("Unregister context for gameObject with ID %d", uid); s_instance.m_contexts.erase(it); } } void aiContextManager::destroyContextsWithPath(const char* asset_path) { auto path = NormalizePath(asset_path); for (auto it = s_instance.m_contexts.begin(); it != s_instance.m_contexts.end();) { if (it->second->getPath() == path) { DebugLog("Unregister context for gameObject with ID %s", it->second->getPath().c_str()); s_instance.m_contexts.erase(it++); } else { ++it; } } } aiContextManager::~aiContextManager() { if (m_contexts.size()) { DebugWarning("%lu remaining context(s) registered", m_contexts.size()); } m_contexts.clear(); } aiContext::aiContext(int uid) : m_uid(uid) { } aiContext::~aiContext() { reset(); } Abc::IArchive aiContext::getArchive() const { return m_archive; } const std::string& aiContext::getPath() const { return m_path; } int aiContext::getTimeSamplingCount() const { return (int)m_timesamplings.size(); } aiTimeSampling * aiContext::getTimeSampling(int i) { return m_timesamplings[i].get(); } void aiContext::getTimeRange(double& begin, double& end) const { begin = end = 0.0; for (size_t i = 1; i < m_timesamplings.size(); ++i) { double tmp_begin, tmp_end; m_timesamplings[i]->getTimeRange(tmp_begin, tmp_end); if (i == 1) { begin = tmp_begin; end = tmp_end; } else { begin = std::min(begin, tmp_begin); end = std::max(end, tmp_end); } } } int aiContext::getTimeSamplingCount() { return (int)m_timesamplings.size(); } int aiContext::getTimeSamplingIndex(Abc::TimeSamplingPtr ts) { int n = m_archive.getNumTimeSamplings(); for (int i = 0; i < n; ++i) { if (m_archive.getTimeSampling(i) == ts) { return i; } } return 0; } int aiContext::getUid() const { return m_uid; } const aiConfig& aiContext::getConfig() const { return m_config; } void aiContext::setConfig(const aiConfig &config) { m_config = config; } void aiContext::gatherNodesRecursive(aiObject *n) { auto& abc = n->getAbcObject(); size_t num_children = abc.getNumChildren(); for (size_t i = 0; i < num_children; ++i) { auto *child = n->newChild(abc.getChild(i)); gatherNodesRecursive(child); } } void aiContext::reset() { waitAsync(); m_top_node.reset(); m_timesamplings.clear(); m_archive.reset(); m_path.clear(); for (auto s : m_streams) { delete s; } m_streams.clear(); // m_config is not reset intentionally } bool aiContext::load(const char *in_path) { auto path = NormalizePath(in_path); auto wpath = L(in_path); DebugLogW(L"aiContext::load: '%s'", wpath.c_str()); if (path == m_path && m_archive) { DebugLog("Context already loaded for gameObject with id %d", m_uid); return true; } reset(); if (path.empty()) { return false; } m_path = path; if (!m_archive.valid()) { try { // Abc::IArchive doesn't accept wide string path. so create file stream with wide string path and pass it. // (VisualC++'s std::ifstream accepts wide string) m_streams.push_back( #ifdef WIN32 new lockFreeIStream(wpath.c_str()) #elif __linux__ new std::ifstream(in_path, std::ios::in | std::ios::binary) #else new std::ifstream(path.c_str(), std::ios::in | std::ios::binary) #endif ); Alembic::AbcCoreOgawa::ReadArchive archive_reader(m_streams); m_archive = Abc::IArchive(archive_reader(m_path), Abc::kWrapExisting, Abc::ErrorHandler::kThrowPolicy); DebugLog("Successfully opened Ogawa archive"); } catch (Alembic::Util::Exception e) { // HDF5 archive doesn't accept external stream. so close it. // (that means if path contains wide characters, it can't be opened. I couldn't find solution..) for (auto s : m_streams) { delete s; } m_streams.clear(); try { m_archive = Abc::IArchive(AbcCoreHDF5::ReadArchive(), path); DebugLog("Successfully opened HDF5 archive"); } catch (Alembic::Util::Exception e2) { auto message = L(e2.what()); DebugLogW(L"Failed to open archive: %s", message.c_str()); } } } else { DebugLogW(L"Archive '%s' already opened", wpath.c_str()); } if (m_archive.valid()) { abcObject abc_top = m_archive.getTop(); m_top_node.reset(new aiObject(this, nullptr, abc_top)); gatherNodesRecursive(m_top_node.get()); m_timesamplings.clear(); auto num_time_samplings = (int)m_archive.getNumTimeSamplings(); for (int i = 0; i < num_time_samplings; ++i) { m_timesamplings.emplace_back(aiCreateTimeSampling(m_archive, i)); } return true; } else { reset(); return false; } } aiObject* aiContext::getTopObject() const { return m_top_node.get(); } void aiContext::updateSamples(double time) { waitAsync(); auto ss = aiTimeToSampleSelector(time); eachNodes([ss](aiObject& o) { o.updateSample(ss); }); // kick async tasks! if (!m_async_tasks.empty()) { aiAsyncManager::instance().queue(m_async_tasks.data(), m_async_tasks.size()); } } void aiContext::queueAsync(aiAsync& task) { m_async_tasks.push_back(&task); } void aiContext::waitAsync() { for (auto task : m_async_tasks) task->wait(); m_async_tasks.clear(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/fileapi/FileReader.h" #include "core/dom/CrossThreadTask.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ProgressEvent.h" #include "core/dom/ScriptExecutionContext.h" #include "core/fileapi/File.h" #include "core/platform/Logging.h" #include <wtf/ArrayBuffer.h> #include <wtf/CurrentTime.h> #include <wtf/text/CString.h> namespace WebCore { static const double progressNotificationIntervalMS = 50; PassRefPtr<FileReader> FileReader::create(ScriptExecutionContext* context) { RefPtr<FileReader> fileReader(adoptRef(new FileReader(context))); fileReader->suspendIfNeeded(); return fileReader.release(); } FileReader::FileReader(ScriptExecutionContext* context) : ActiveDOMObject(context) , m_state(EMPTY) , m_aborting(false) , m_readType(FileReaderLoader::ReadAsBinaryString) , m_lastProgressNotificationTimeMS(0) { ScriptWrappable::init(this); } FileReader::~FileReader() { terminate(); } const AtomicString& FileReader::interfaceName() const { return eventNames().interfaceForFileReader; } bool FileReader::canSuspend() const { // FIXME: It is not currently possible to suspend a FileReader, so pages with FileReader can not go into page cache. return false; } void FileReader::stop() { terminate(); } void FileReader::readAsArrayBuffer(Blob* blob, ExceptionCode& ec) { if (!blob) return; LOG(FileAPI, "FileReader: reading as array buffer: %s %s\n", blob->url().string().utf8().data(), blob->isFile() ? toFile(blob)->path().utf8().data() : ""); readInternal(blob, FileReaderLoader::ReadAsArrayBuffer, ec); } void FileReader::readAsBinaryString(Blob* blob, ExceptionCode& ec) { if (!blob) return; LOG(FileAPI, "FileReader: reading as binary: %s %s\n", blob->url().string().utf8().data(), blob->isFile() ? toFile(blob)->path().utf8().data() : ""); readInternal(blob, FileReaderLoader::ReadAsBinaryString, ec); } void FileReader::readAsText(Blob* blob, const String& encoding, ExceptionCode& ec) { if (!blob) return; LOG(FileAPI, "FileReader: reading as text: %s %s\n", blob->url().string().utf8().data(), blob->isFile() ? toFile(blob)->path().utf8().data() : ""); m_encoding = encoding; readInternal(blob, FileReaderLoader::ReadAsText, ec); } void FileReader::readAsText(Blob* blob, ExceptionCode& ec) { readAsText(blob, String(), ec); } void FileReader::readAsDataURL(Blob* blob, ExceptionCode& ec) { if (!blob) return; LOG(FileAPI, "FileReader: reading as data URL: %s %s\n", blob->url().string().utf8().data(), blob->isFile() ? toFile(blob)->path().utf8().data() : ""); readInternal(blob, FileReaderLoader::ReadAsDataURL, ec); } void FileReader::readInternal(Blob* blob, FileReaderLoader::ReadType type, ExceptionCode& ec) { // If multiple concurrent read methods are called on the same FileReader, INVALID_STATE_ERR should be thrown when the state is LOADING. if (m_state == LOADING) { ec = INVALID_STATE_ERR; return; } setPendingActivity(this); m_blob = blob; m_readType = type; m_state = LOADING; m_error = 0; m_loader = adoptPtr(new FileReaderLoader(m_readType, this)); m_loader->setEncoding(m_encoding); m_loader->setDataType(m_blob->type()); m_loader->start(scriptExecutionContext(), m_blob.get()); } static void delayedAbort(ScriptExecutionContext*, FileReader* reader) { reader->doAbort(); } void FileReader::abort() { LOG(FileAPI, "FileReader: aborting\n"); if (m_aborting || m_state != LOADING) return; m_aborting = true; // Schedule to have the abort done later since abort() might be called from the event handler and we do not want the resource loading code to be in the stack. scriptExecutionContext()->postTask( createCallbackTask(&delayedAbort, AllowAccessLater(this))); } void FileReader::doAbort() { ASSERT(m_state != DONE); terminate(); m_aborting = false; m_error = FileError::create(FileError::ABORT_ERR); fireEvent(eventNames().errorEvent); fireEvent(eventNames().abortEvent); fireEvent(eventNames().loadendEvent); // All possible events have fired and we're done, no more pending activity. unsetPendingActivity(this); } void FileReader::terminate() { if (m_loader) { m_loader->cancel(); m_loader = nullptr; } m_state = DONE; } void FileReader::didStartLoading() { fireEvent(eventNames().loadstartEvent); } void FileReader::didReceiveData() { // Fire the progress event at least every 50ms. double now = currentTimeMS(); if (!m_lastProgressNotificationTimeMS) m_lastProgressNotificationTimeMS = now; else if (now - m_lastProgressNotificationTimeMS > progressNotificationIntervalMS) { fireEvent(eventNames().progressEvent); m_lastProgressNotificationTimeMS = now; } } void FileReader::didFinishLoading() { if (m_aborting) return; ASSERT(m_state != DONE); m_state = DONE; fireEvent(eventNames().progressEvent); fireEvent(eventNames().loadEvent); fireEvent(eventNames().loadendEvent); // All possible events have fired and we're done, no more pending activity. unsetPendingActivity(this); } void FileReader::didFail(int errorCode) { // If we're aborting, do not proceed with normal error handling since it is covered in aborting code. if (m_aborting) return; ASSERT(m_state != DONE); m_state = DONE; m_error = FileError::create(static_cast<FileError::ErrorCode>(errorCode)); fireEvent(eventNames().errorEvent); fireEvent(eventNames().loadendEvent); // All possible events have fired and we're done, no more pending activity. unsetPendingActivity(this); } void FileReader::fireEvent(const AtomicString& type) { dispatchEvent(ProgressEvent::create(type, true, m_loader ? m_loader->bytesLoaded() : 0, m_loader ? m_loader->totalBytes() : 0)); } PassRefPtr<ArrayBuffer> FileReader::arrayBufferResult() const { if (!m_loader || m_error) return 0; return m_loader->arrayBufferResult(); } String FileReader::stringResult() { if (!m_loader || m_error) return String(); return m_loader->stringResult(); } } // namespace WebCore <commit_msg>Factor out blob to UTF-8 url/path conversion into helper functions.<commit_after>/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/fileapi/FileReader.h" #include "core/dom/CrossThreadTask.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ProgressEvent.h" #include "core/dom/ScriptExecutionContext.h" #include "core/fileapi/File.h" #include "core/platform/Logging.h" #include <wtf/ArrayBuffer.h> #include <wtf/CurrentTime.h> #include <wtf/text/CString.h> namespace WebCore { namespace { const CString utf8BlobURL(Blob* blob) { return blob->url().string().utf8(); } const CString utf8FilePath(Blob* blob) { return blob->isFile() ? toFile(blob)->path().utf8() : ""; } } // namespace static const double progressNotificationIntervalMS = 50; PassRefPtr<FileReader> FileReader::create(ScriptExecutionContext* context) { RefPtr<FileReader> fileReader(adoptRef(new FileReader(context))); fileReader->suspendIfNeeded(); return fileReader.release(); } FileReader::FileReader(ScriptExecutionContext* context) : ActiveDOMObject(context) , m_state(EMPTY) , m_aborting(false) , m_readType(FileReaderLoader::ReadAsBinaryString) , m_lastProgressNotificationTimeMS(0) { ScriptWrappable::init(this); } FileReader::~FileReader() { terminate(); } const AtomicString& FileReader::interfaceName() const { return eventNames().interfaceForFileReader; } bool FileReader::canSuspend() const { // FIXME: It is not currently possible to suspend a FileReader, so pages with FileReader can not go into page cache. return false; } void FileReader::stop() { terminate(); } void FileReader::readAsArrayBuffer(Blob* blob, ExceptionCode& ec) { if (!blob) return; LOG(FileAPI, "FileReader: reading as array buffer: %s %s\n", utf8BlobURL(blob).data(), utf8FilePath(blob).data()); readInternal(blob, FileReaderLoader::ReadAsArrayBuffer, ec); } void FileReader::readAsBinaryString(Blob* blob, ExceptionCode& ec) { if (!blob) return; LOG(FileAPI, "FileReader: reading as binary: %s %s\n", utf8BlobURL(blob).data(), utf8FilePath(blob).data()); readInternal(blob, FileReaderLoader::ReadAsBinaryString, ec); } void FileReader::readAsText(Blob* blob, const String& encoding, ExceptionCode& ec) { if (!blob) return; LOG(FileAPI, "FileReader: reading as text: %s %s\n", utf8BlobURL(blob).data(), utf8FilePath(blob).data()); m_encoding = encoding; readInternal(blob, FileReaderLoader::ReadAsText, ec); } void FileReader::readAsText(Blob* blob, ExceptionCode& ec) { readAsText(blob, String(), ec); } void FileReader::readAsDataURL(Blob* blob, ExceptionCode& ec) { if (!blob) return; LOG(FileAPI, "FileReader: reading as data URL: %s %s\n", utf8BlobURL(blob).data(), utf8FilePath(blob).data()); readInternal(blob, FileReaderLoader::ReadAsDataURL, ec); } void FileReader::readInternal(Blob* blob, FileReaderLoader::ReadType type, ExceptionCode& ec) { // If multiple concurrent read methods are called on the same FileReader, INVALID_STATE_ERR should be thrown when the state is LOADING. if (m_state == LOADING) { ec = INVALID_STATE_ERR; return; } setPendingActivity(this); m_blob = blob; m_readType = type; m_state = LOADING; m_error = 0; m_loader = adoptPtr(new FileReaderLoader(m_readType, this)); m_loader->setEncoding(m_encoding); m_loader->setDataType(m_blob->type()); m_loader->start(scriptExecutionContext(), m_blob.get()); } static void delayedAbort(ScriptExecutionContext*, FileReader* reader) { reader->doAbort(); } void FileReader::abort() { LOG(FileAPI, "FileReader: aborting\n"); if (m_aborting || m_state != LOADING) return; m_aborting = true; // Schedule to have the abort done later since abort() might be called from the event handler and we do not want the resource loading code to be in the stack. scriptExecutionContext()->postTask( createCallbackTask(&delayedAbort, AllowAccessLater(this))); } void FileReader::doAbort() { ASSERT(m_state != DONE); terminate(); m_aborting = false; m_error = FileError::create(FileError::ABORT_ERR); fireEvent(eventNames().errorEvent); fireEvent(eventNames().abortEvent); fireEvent(eventNames().loadendEvent); // All possible events have fired and we're done, no more pending activity. unsetPendingActivity(this); } void FileReader::terminate() { if (m_loader) { m_loader->cancel(); m_loader = nullptr; } m_state = DONE; } void FileReader::didStartLoading() { fireEvent(eventNames().loadstartEvent); } void FileReader::didReceiveData() { // Fire the progress event at least every 50ms. double now = currentTimeMS(); if (!m_lastProgressNotificationTimeMS) m_lastProgressNotificationTimeMS = now; else if (now - m_lastProgressNotificationTimeMS > progressNotificationIntervalMS) { fireEvent(eventNames().progressEvent); m_lastProgressNotificationTimeMS = now; } } void FileReader::didFinishLoading() { if (m_aborting) return; ASSERT(m_state != DONE); m_state = DONE; fireEvent(eventNames().progressEvent); fireEvent(eventNames().loadEvent); fireEvent(eventNames().loadendEvent); // All possible events have fired and we're done, no more pending activity. unsetPendingActivity(this); } void FileReader::didFail(int errorCode) { // If we're aborting, do not proceed with normal error handling since it is covered in aborting code. if (m_aborting) return; ASSERT(m_state != DONE); m_state = DONE; m_error = FileError::create(static_cast<FileError::ErrorCode>(errorCode)); fireEvent(eventNames().errorEvent); fireEvent(eventNames().loadendEvent); // All possible events have fired and we're done, no more pending activity. unsetPendingActivity(this); } void FileReader::fireEvent(const AtomicString& type) { dispatchEvent(ProgressEvent::create(type, true, m_loader ? m_loader->bytesLoaded() : 0, m_loader ? m_loader->totalBytes() : 0)); } PassRefPtr<ArrayBuffer> FileReader::arrayBufferResult() const { if (!m_loader || m_error) return 0; return m_loader->arrayBufferResult(); } String FileReader::stringResult() { if (!m_loader || m_error) return String(); return m_loader->stringResult(); } } // namespace WebCore <|endoftext|>
<commit_before>#include <stdlib.h> #include <Arduino.h> #include <avr/pgmspace.h> #include "generator.h" void g_generator_init(void *_self, g_method method, int32_t period, int32_t phase, int32_t amplitude, int32_t offset) { generator_t *self = (generator_t *)_self; self->method = method; self->period = period; self->phase = phase; self->amplitude = amplitude; self->offset = offset; } void g_sin_init(void *_self, g_method method, int32_t period, int32_t phase, int32_t amplitude, int32_t offset) { generator_t *self = (generator_t *)_self; self->period = (int32_t)S_PIM2 * (int32_t)SCALE_FACTOR / period; self->phase = -S_PID2 + (S_PIM2 * phase / SCALE_FACTOR); self->method = method; self->amplitude = amplitude; self->offset = offset; } void g_square_init(void *_self, g_method method, int32_t period, int32_t phase, int32_t amplitude, int32_t offset, int32_t duty) { square_t *self = (square_t *)_self; self->method = method; self->period = period; self->phase = phase; self->amplitude = amplitude; self->offset = offset; self->duty = duty; } void g_sawtooth_init(void *_self, g_method method, int32_t period, int32_t phase, int32_t amplitude, int32_t offset) { generator_t *self = (generator_t *)_self; self->period = SCALE_FACTOR / period; self->phase = phase; self->method = method; self->amplitude = amplitude; self->offset = offset; } int32_t g_sin(void *_self, uint32_t t) { int16_t value; generator_t *self = (generator_t *)_self; int32_t index = (((int32_t)t * self->period / SCALE_FACTOR + self->phase) % S_PIM2) * NUM_SIN_TABLE_ENTRIES / S_PIM2; if (index < 0) index += NUM_SIN_TABLE_ENTRIES; // first explicitly cast to int16_t, to make sure negative numbers are handled correctly value = (int16_t)pgm_read_word_near(sin_table + index); return (int32_t)value * self->amplitude / SCALE_FACTOR + self->offset; } int32_t g_square(void *_self, uint32_t t) { square_t *self = (square_t *)_self; int32_t v = ((int32_t)t * SCALE_FACTOR / self->period) + self->phase; if (v % SCALE_FACTOR < self->duty) return self->amplitude + self->offset; else return self->offset; } int32_t g_sawtooth(void *_self, uint32_t t) { generator_t *self = (generator_t *)_self; int32_t v = (((int32_t)t * self->period / SCALE_FACTOR) + self->phase) % SCALE_FACTOR; return v * self->amplitude / SCALE_FACTOR + self->offset; } int32_t g_step(void *_self, uint32_t t) { generator_t *self = (generator_t *)_self; int32_t v = ((int32_t)t * SCALE_FACTOR / self->period) + self->phase; if (v >= 0) return self->amplitude + self->offset; else return self->offset; } int32_t g_impulse(void *_self, uint32_t t) { generator_t *self = (generator_t *)_self; int32_t v = ((int32_t)t * SCALE_FACTOR / self->period) + self->phase; if (v >= 0 && v < SCALE_FACTOR) return self->amplitude + self->offset; else return self->offset; } int32_t g_line(void *_self, uint32_t t) { generator_t *self = (generator_t *)_self; return ((int32_t)t * self->amplitude / SCALE_FACTOR) + self->offset; } void g_generator_op_init(void *_self, uint8_t op, generator_t *g, generator_t *g2) { generator_op_t *self = (generator_op_t *)_self; self->method = g_generator_op_get; self->g = g; self->g2 = g2; self->op = op; } int32_t g_generator_op_get(void *_self, uint32_t t) { generator_op_t *self = (generator_op_t *)_self; int32_t v1, v2; v1 = self->g->method(self->g, t); v2 = self->g2->method(self->g2, t); switch(self->op) { case OP_ADD: return v1 + v2; case OP_SUB: return v1 - v2; case OP_MUL: return v1 * v2; case OP_DIV: return v1 * SCALE_FACTOR / v2; case OP_MOD: return v1 % v2; } return 0; } void g_abs_init(void *_self, generator_t *g) { g_abs_t *self = (g_abs_t *)_self; self->method = g_abs_get; self->g = g; } int32_t g_abs_get(void *_self, uint32_t t) { generator_op_t *self = (generator_op_t *)_self; return abs(self->g->method(self->g, t)); } void g_constant_init(void *_self, int32_t value) { g_constant_t *self = (g_constant_t *)_self; self->method = g_constant_get; self->value = value; } int32_t g_constant_get(void *_self, uint32_t t) { g_constant_t *self = (g_constant_t *)_self; return self->value; } <commit_msg>Fix the sawtooth period correctly<commit_after>#include <stdlib.h> #include <Arduino.h> #include <avr/pgmspace.h> #include "generator.h" void g_generator_init(void *_self, g_method method, int32_t period, int32_t phase, int32_t amplitude, int32_t offset) { generator_t *self = (generator_t *)_self; self->method = method; self->period = period; self->phase = phase; self->amplitude = amplitude; self->offset = offset; } void g_sin_init(void *_self, g_method method, int32_t period, int32_t phase, int32_t amplitude, int32_t offset) { generator_t *self = (generator_t *)_self; self->period = (int32_t)S_PIM2 * (int32_t)SCALE_FACTOR / period; self->phase = -S_PID2 + (S_PIM2 * phase / SCALE_FACTOR); self->method = method; self->amplitude = amplitude; self->offset = offset; } void g_square_init(void *_self, g_method method, int32_t period, int32_t phase, int32_t amplitude, int32_t offset, int32_t duty) { square_t *self = (square_t *)_self; self->method = method; self->period = period; self->phase = phase; self->amplitude = amplitude; self->offset = offset; self->duty = duty; } void g_sawtooth_init(void *_self, g_method method, int32_t period, int32_t phase, int32_t amplitude, int32_t offset) { generator_t *self = (generator_t *)_self; self->period = (int32_t)SCALE_FACTOR * (int32_t)SCALE_FACTOR/ period; self->phase = phase; self->method = method; self->amplitude = amplitude; self->offset = offset; } int32_t g_sin(void *_self, uint32_t t) { int16_t value; generator_t *self = (generator_t *)_self; int32_t index = (((int32_t)t * self->period / SCALE_FACTOR + self->phase) % S_PIM2) * NUM_SIN_TABLE_ENTRIES / S_PIM2; if (index < 0) index += NUM_SIN_TABLE_ENTRIES; // first explicitly cast to int16_t, to make sure negative numbers are handled correctly value = (int16_t)pgm_read_word_near(sin_table + index); return (int32_t)value * self->amplitude / SCALE_FACTOR + self->offset; } int32_t g_square(void *_self, uint32_t t) { square_t *self = (square_t *)_self; int32_t v = ((int32_t)t * SCALE_FACTOR / self->period) + self->phase; if (v % SCALE_FACTOR < self->duty) return self->amplitude + self->offset; else return self->offset; } int32_t g_sawtooth(void *_self, uint32_t t) { generator_t *self = (generator_t *)_self; int32_t v = (((int32_t)t * self->period / SCALE_FACTOR) + self->phase) % SCALE_FACTOR; return v * self->amplitude / SCALE_FACTOR + self->offset; } int32_t g_step(void *_self, uint32_t t) { generator_t *self = (generator_t *)_self; int32_t v = ((int32_t)t * SCALE_FACTOR / self->period) + self->phase; if (v >= 0) return self->amplitude + self->offset; else return self->offset; } int32_t g_impulse(void *_self, uint32_t t) { generator_t *self = (generator_t *)_self; int32_t v = ((int32_t)t * SCALE_FACTOR / self->period) + self->phase; if (v >= 0 && v < SCALE_FACTOR) return self->amplitude + self->offset; else return self->offset; } int32_t g_line(void *_self, uint32_t t) { generator_t *self = (generator_t *)_self; return ((int32_t)t * self->amplitude / SCALE_FACTOR) + self->offset; } void g_generator_op_init(void *_self, uint8_t op, generator_t *g, generator_t *g2) { generator_op_t *self = (generator_op_t *)_self; self->method = g_generator_op_get; self->g = g; self->g2 = g2; self->op = op; } int32_t g_generator_op_get(void *_self, uint32_t t) { generator_op_t *self = (generator_op_t *)_self; int32_t v1, v2; v1 = self->g->method(self->g, t); v2 = self->g2->method(self->g2, t); switch(self->op) { case OP_ADD: return v1 + v2; case OP_SUB: return v1 - v2; case OP_MUL: return v1 * v2; case OP_DIV: return v1 * SCALE_FACTOR / v2; case OP_MOD: return v1 % v2; } return 0; } void g_abs_init(void *_self, generator_t *g) { g_abs_t *self = (g_abs_t *)_self; self->method = g_abs_get; self->g = g; } int32_t g_abs_get(void *_self, uint32_t t) { generator_op_t *self = (generator_op_t *)_self; return abs(self->g->method(self->g, t)); } void g_constant_init(void *_self, int32_t value) { g_constant_t *self = (g_constant_t *)_self; self->method = g_constant_get; self->value = value; } int32_t g_constant_get(void *_self, uint32_t t) { g_constant_t *self = (g_constant_t *)_self; return self->value; } <|endoftext|>
<commit_before>#include "dgltreeview.h" #include "dglgui.h" #include <set> #include <climits> DGLTreeView::DGLTreeView(QWidget* parrent, DglController* controller):QDockWidget(tr("State Tree"), parrent), m_TreeWidget(this),m_controller(controller) { setObjectName("DGLTreeView"); m_TreeWidget.setMinimumSize(QSize(200, 0)); setConnected(false); setWidget(&m_TreeWidget); //inbound CONNASSERT(connect(controller, SIGNAL(setConnected(bool)), this, SLOT(setConnected(bool)))); CONNASSERT(connect(controller, SIGNAL(debugeeInfo(const std::string&)), this, SLOT(debugeeInfo(const std::string&)))); CONNASSERT(connect(controller, SIGNAL(setBreaked(bool)), &m_TreeWidget, SLOT(setEnabled(bool)))); CONNASSERT(connect(controller, SIGNAL(breakedWithStateReports(uint, const std::vector<dglnet::ContextReport>&)), this, SLOT(breakedWithStateReports(uint, const std::vector<dglnet::ContextReport>&)))); //internal CONNASSERT(QObject::connect(&m_TreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(onDoubleClicked(QTreeWidgetItem*, int)))); } DGLTreeView::~DGLTreeView() {} void DGLTreeView::setConnected(bool connected) { m_Connected = connected; if (!connected) { m_TreeWidget.setHeaderLabel(""); while (m_TreeWidget.topLevelItemCount()) { delete m_TreeWidget.takeTopLevelItem(0); } } } void QClickableTreeWidgetItem::handleDoubleClick(DglController*) {} class DGLTextureWidget: public QClickableTreeWidgetItem { public: DGLTextureWidget() {} DGLTextureWidget(ContextObjectName name, QString iconPath):m_name(name) { setText(0, QString("Texture ") + QString::number(name.m_Name) + QString::fromStdString(" (" + GetTextureTargetName(name.m_Target) + ")")); setIcon(0, QIcon(iconPath)); } virtual void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_name, DGLResource::ObjectTypeTexture); } private: ContextObjectName m_name; }; class DGLBufferWidget: public QClickableTreeWidgetItem { public: DGLBufferWidget() {} DGLBufferWidget(ContextObjectName name, QString iconPath):m_name(name) { setText(0, QString("Buffer ") + QString::number(name.m_Name)); setIcon(0, QIcon(iconPath)); } void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_name, DGLResource::ObjectTypeBuffer); } private: ContextObjectName m_name; }; class DGLFBOWidget: public QClickableTreeWidgetItem { public: DGLFBOWidget() {} DGLFBOWidget(ContextObjectName name, QString iconPath):m_name(name) { setText(0, QString("FBO ") + QString::number(name.m_Name)); } void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_name, DGLResource::ObjectTypeFBO); } private: ContextObjectName m_name; }; class DGLShaderWidget: public QClickableTreeWidgetItem { public: DGLShaderWidget() {} DGLShaderWidget(ContextObjectName name, QString iconPath):m_name(name) { setText(0, QString("Shader ") + QString::number(name.m_Name) + QString::fromStdString(" (" + GetShaderStageName(name.m_Target) + ")")); setIcon(0, QIcon(iconPath)); } void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_name, DGLResource::ObjectTypeShader); } private: ContextObjectName m_name; }; class DGLProgramWidget: public QClickableTreeWidgetItem { public: DGLProgramWidget() {} DGLProgramWidget(ContextObjectName name, QString iconPath):m_name(name) { setText(0, QString(" Shader Program ") + QString::number(name.m_Name)); setIcon(0, QIcon(iconPath)); } void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_name, DGLResource::ObjectTypeProgram); } private: ContextObjectName m_name; }; class DGLFramebufferWidget: public QClickableTreeWidgetItem { public: DGLFramebufferWidget() {} DGLFramebufferWidget(ContextObjectName type, QString iconPath):m_type(type) { std::string name = "unknown"; switch (type.m_Name) { case GL_FRONT_RIGHT: name = "Front right buffer"; break; case GL_BACK_RIGHT: name = "Back right buffer"; break; case GL_FRONT: name = "Front buffer"; break; case GL_BACK: name = "Back buffer"; break; } setText(0, QString(name.c_str())); setIcon(0, QIcon(iconPath)); } void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_type, DGLResource::ObjectTypeFramebuffer); } ContextObjectName m_type; }; template<typename ObjType> class DGLObjectNodeWidget: public QClickableTreeWidgetItem { public: DGLObjectNodeWidget(uint ctxId, QString header, QString iconPath):m_CtxId(ctxId),m_IconPath(iconPath) { setText(0, header); setIcon(0, QIcon(iconPath)); } template<typename T> void update(const std::set<T>& names) { typedef typename std::set<T>::iterator set_iter; for (set_iter i = names.begin(); i != names.end(); i++) { if (m_Childs.find(i->m_Name) == m_Childs.end()) { m_Childs[i->m_Name] = ObjType(*i, m_IconPath); addChild(&m_Childs[i->m_Name]); } } typedef typename std::map<uint, ObjType>::iterator map_iter; map_iter i = m_Childs.begin(); while (i != m_Childs.end()) { map_iter next = i; next++; if (names.find(T(m_CtxId, i->first)) == names.end()) { removeChild(&(i->second)); m_Childs.erase(i); } i = next; } } private: std::map<uint, ObjType> m_Childs; uint m_CtxId; QString m_IconPath; }; class DGLCtxTreeWidget: public QClickableTreeWidgetItem { public: DGLCtxTreeWidget(uint ctxId):m_Id(ctxId), m_TextureNode(ctxId, "Textures", ":/icons/texture.png"), m_BufferNode(ctxId, "Vertex Buffers", ":/icons/buffer.png"), m_FBONode(ctxId, "Framebuffer objects", ":/icons/fbo.png"), m_ShaderNode(ctxId, "Shaders", ":/icons/shader.png"), m_ProgramNode(ctxId, "Shader Programs", ":/icons/program.png"), m_FramebufferNode(ctxId, "Frame Buffers", ":/icons/framebuffer.png") { addChild(&m_TextureNode); addChild(&m_BufferNode); addChild(&m_FBONode); addChild(&m_ShaderNode); addChild(&m_ProgramNode); addChild(&m_FramebufferNode); setIcon(0, QIcon(":/icons/context.png")); } uint getId() { return m_Id; } void update(const dglnet::ContextReport& report, bool current) { QFont fnt = font(0); fnt.setBold(current); setFont(0,fnt); assert(m_Id = report.m_Id); setText(0, QString("Context 0x") + QString::number(report.m_Id, 16) + (current?QString(" (current)"):QString(""))); m_TextureNode.update(report.m_TextureSpace); m_BufferNode.update(report.m_BufferSpace); m_FBONode.update(report.m_FBOSpace); m_ShaderNode.update(report.m_ShaderSpace); m_ProgramNode.update(report.m_ProgramSpace); m_BufferNode.update(report.m_BufferSpace); m_FramebufferNode.update(report.m_FramebufferSpace); } private: uint m_Id; DGLObjectNodeWidget<DGLTextureWidget> m_TextureNode; DGLObjectNodeWidget<DGLBufferWidget> m_BufferNode; DGLObjectNodeWidget<DGLFBOWidget> m_FBONode; DGLObjectNodeWidget<DGLShaderWidget> m_ShaderNode; DGLObjectNodeWidget<DGLProgramWidget> m_ProgramNode; DGLObjectNodeWidget<DGLFramebufferWidget> m_FramebufferNode; }; void DGLTreeView::breakedWithStateReports(uint currentContextId, const std::vector<dglnet::ContextReport>& report) { for(size_t i = 0; i < report.size(); i++) { DGLCtxTreeWidget* widget = 0; for (uint j = 0; j < m_TreeWidget.topLevelItemCount(); j++) { DGLCtxTreeWidget* thisWidget = dynamic_cast<DGLCtxTreeWidget*>(m_TreeWidget.topLevelItem(j)); if ( thisWidget && thisWidget->getId() == report[i].m_Id) { widget = thisWidget; break; } } if (!widget) { widget = new DGLCtxTreeWidget(report[i].m_Id); m_TreeWidget.addTopLevelItem(widget); } widget->update(report[i], report[i].m_Id == currentContextId); } for (uint j = 0; j < m_TreeWidget.topLevelItemCount(); j++) { DGLCtxTreeWidget* thisWidget = dynamic_cast<DGLCtxTreeWidget*>(m_TreeWidget.topLevelItem(j)); bool found = false; for(size_t i = 0; i < report.size(); i++) { if ( thisWidget && thisWidget->getId() == report[i].m_Id) { found = true; break; } } if (!found) { delete m_TreeWidget.takeTopLevelItem(j--); } } } void DGLTreeView::onDoubleClicked(QTreeWidgetItem* item, int) { QClickableTreeWidgetItem* clickableItem = dynamic_cast<QClickableTreeWidgetItem*>(item); if (clickableItem) { clickableItem->handleDoubleClick(m_controller); } } void DGLTreeView::debugeeInfo(const std::string& processName) { m_TreeWidget.setHeaderLabel(processName.c_str()); } <commit_msg>Fix bug with missing texture icon in tree view.<commit_after>#include "dgltreeview.h" #include "dglgui.h" #include <set> #include <climits> DGLTreeView::DGLTreeView(QWidget* parrent, DglController* controller):QDockWidget(tr("State Tree"), parrent), m_TreeWidget(this),m_controller(controller) { setObjectName("DGLTreeView"); m_TreeWidget.setMinimumSize(QSize(200, 0)); setConnected(false); setWidget(&m_TreeWidget); //inbound CONNASSERT(connect(controller, SIGNAL(setConnected(bool)), this, SLOT(setConnected(bool)))); CONNASSERT(connect(controller, SIGNAL(debugeeInfo(const std::string&)), this, SLOT(debugeeInfo(const std::string&)))); CONNASSERT(connect(controller, SIGNAL(setBreaked(bool)), &m_TreeWidget, SLOT(setEnabled(bool)))); CONNASSERT(connect(controller, SIGNAL(breakedWithStateReports(uint, const std::vector<dglnet::ContextReport>&)), this, SLOT(breakedWithStateReports(uint, const std::vector<dglnet::ContextReport>&)))); //internal CONNASSERT(QObject::connect(&m_TreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(onDoubleClicked(QTreeWidgetItem*, int)))); } DGLTreeView::~DGLTreeView() {} void DGLTreeView::setConnected(bool connected) { m_Connected = connected; if (!connected) { m_TreeWidget.setHeaderLabel(""); while (m_TreeWidget.topLevelItemCount()) { delete m_TreeWidget.takeTopLevelItem(0); } } } void QClickableTreeWidgetItem::handleDoubleClick(DglController*) {} class DGLTextureWidget: public QClickableTreeWidgetItem { public: DGLTextureWidget() {} DGLTextureWidget(ContextObjectName name, QString iconPath):m_name(name) { setText(0, QString("Texture ") + QString::number(name.m_Name) + QString::fromStdString(" (" + GetTextureTargetName(name.m_Target) + ")")); setIcon(0, QIcon(iconPath)); } virtual void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_name, DGLResource::ObjectTypeTexture); } private: ContextObjectName m_name; }; class DGLBufferWidget: public QClickableTreeWidgetItem { public: DGLBufferWidget() {} DGLBufferWidget(ContextObjectName name, QString iconPath):m_name(name) { setText(0, QString("Buffer ") + QString::number(name.m_Name)); setIcon(0, QIcon(iconPath)); } void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_name, DGLResource::ObjectTypeBuffer); } private: ContextObjectName m_name; }; class DGLFBOWidget: public QClickableTreeWidgetItem { public: DGLFBOWidget() {} DGLFBOWidget(ContextObjectName name, QString iconPath):m_name(name) { setText(0, QString("FBO ") + QString::number(name.m_Name)); } void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_name, DGLResource::ObjectTypeFBO); } private: ContextObjectName m_name; }; class DGLShaderWidget: public QClickableTreeWidgetItem { public: DGLShaderWidget() {} DGLShaderWidget(ContextObjectName name, QString iconPath):m_name(name) { setText(0, QString("Shader ") + QString::number(name.m_Name) + QString::fromStdString(" (" + GetShaderStageName(name.m_Target) + ")")); setIcon(0, QIcon(iconPath)); } void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_name, DGLResource::ObjectTypeShader); } private: ContextObjectName m_name; }; class DGLProgramWidget: public QClickableTreeWidgetItem { public: DGLProgramWidget() {} DGLProgramWidget(ContextObjectName name, QString iconPath):m_name(name) { setText(0, QString(" Shader Program ") + QString::number(name.m_Name)); setIcon(0, QIcon(iconPath)); } void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_name, DGLResource::ObjectTypeProgram); } private: ContextObjectName m_name; }; class DGLFramebufferWidget: public QClickableTreeWidgetItem { public: DGLFramebufferWidget() {} DGLFramebufferWidget(ContextObjectName type, QString iconPath):m_type(type) { std::string name = "unknown"; switch (type.m_Name) { case GL_FRONT_RIGHT: name = "Front right buffer"; break; case GL_BACK_RIGHT: name = "Back right buffer"; break; case GL_FRONT: name = "Front buffer"; break; case GL_BACK: name = "Back buffer"; break; } setText(0, QString(name.c_str())); setIcon(0, QIcon(iconPath)); } void handleDoubleClick(DglController* controller) { controller->getViewRouter()->show(m_type, DGLResource::ObjectTypeFramebuffer); } ContextObjectName m_type; }; template<typename ObjType> class DGLObjectNodeWidget: public QClickableTreeWidgetItem { public: DGLObjectNodeWidget(uint ctxId, QString header, QString iconPath):m_CtxId(ctxId),m_IconPath(iconPath) { setText(0, header); setIcon(0, QIcon(iconPath)); } template<typename T> void update(const std::set<T>& names) { typedef typename std::set<T>::iterator set_iter; for (set_iter i = names.begin(); i != names.end(); i++) { if (m_Childs.find(i->m_Name) == m_Childs.end()) { m_Childs[i->m_Name] = ObjType(*i, m_IconPath); addChild(&m_Childs[i->m_Name]); } } typedef typename std::map<uint, ObjType>::iterator map_iter; map_iter i = m_Childs.begin(); while (i != m_Childs.end()) { map_iter next = i; next++; if (names.find(T(m_CtxId, i->first)) == names.end()) { removeChild(&(i->second)); m_Childs.erase(i); } i = next; } } private: std::map<uint, ObjType> m_Childs; uint m_CtxId; QString m_IconPath; }; class DGLCtxTreeWidget: public QClickableTreeWidgetItem { public: DGLCtxTreeWidget(uint ctxId):m_Id(ctxId), m_TextureNode(ctxId, "Textures", ":/icons/textures.png"), m_BufferNode(ctxId, "Vertex Buffers", ":/icons/buffer.png"), m_FBONode(ctxId, "Framebuffer objects", ":/icons/fbo.png"), m_ShaderNode(ctxId, "Shaders", ":/icons/shader.png"), m_ProgramNode(ctxId, "Shader Programs", ":/icons/program.png"), m_FramebufferNode(ctxId, "Frame Buffers", ":/icons/framebuffer.png") { addChild(&m_TextureNode); addChild(&m_BufferNode); addChild(&m_FBONode); addChild(&m_ShaderNode); addChild(&m_ProgramNode); addChild(&m_FramebufferNode); setIcon(0, QIcon(":/icons/context.png")); } uint getId() { return m_Id; } void update(const dglnet::ContextReport& report, bool current) { QFont fnt = font(0); fnt.setBold(current); setFont(0,fnt); assert(m_Id = report.m_Id); setText(0, QString("Context 0x") + QString::number(report.m_Id, 16) + (current?QString(" (current)"):QString(""))); m_TextureNode.update(report.m_TextureSpace); m_BufferNode.update(report.m_BufferSpace); m_FBONode.update(report.m_FBOSpace); m_ShaderNode.update(report.m_ShaderSpace); m_ProgramNode.update(report.m_ProgramSpace); m_BufferNode.update(report.m_BufferSpace); m_FramebufferNode.update(report.m_FramebufferSpace); } private: uint m_Id; DGLObjectNodeWidget<DGLTextureWidget> m_TextureNode; DGLObjectNodeWidget<DGLBufferWidget> m_BufferNode; DGLObjectNodeWidget<DGLFBOWidget> m_FBONode; DGLObjectNodeWidget<DGLShaderWidget> m_ShaderNode; DGLObjectNodeWidget<DGLProgramWidget> m_ProgramNode; DGLObjectNodeWidget<DGLFramebufferWidget> m_FramebufferNode; }; void DGLTreeView::breakedWithStateReports(uint currentContextId, const std::vector<dglnet::ContextReport>& report) { for(size_t i = 0; i < report.size(); i++) { DGLCtxTreeWidget* widget = 0; for (uint j = 0; j < m_TreeWidget.topLevelItemCount(); j++) { DGLCtxTreeWidget* thisWidget = dynamic_cast<DGLCtxTreeWidget*>(m_TreeWidget.topLevelItem(j)); if ( thisWidget && thisWidget->getId() == report[i].m_Id) { widget = thisWidget; break; } } if (!widget) { widget = new DGLCtxTreeWidget(report[i].m_Id); m_TreeWidget.addTopLevelItem(widget); } widget->update(report[i], report[i].m_Id == currentContextId); } for (uint j = 0; j < m_TreeWidget.topLevelItemCount(); j++) { DGLCtxTreeWidget* thisWidget = dynamic_cast<DGLCtxTreeWidget*>(m_TreeWidget.topLevelItem(j)); bool found = false; for(size_t i = 0; i < report.size(); i++) { if ( thisWidget && thisWidget->getId() == report[i].m_Id) { found = true; break; } } if (!found) { delete m_TreeWidget.takeTopLevelItem(j--); } } } void DGLTreeView::onDoubleClicked(QTreeWidgetItem* item, int) { QClickableTreeWidgetItem* clickableItem = dynamic_cast<QClickableTreeWidgetItem*>(item); if (clickableItem) { clickableItem->handleDoubleClick(m_controller); } } void DGLTreeView::debugeeInfo(const std::string& processName) { m_TreeWidget.setHeaderLabel(processName.c_str()); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Matias Fontanini * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <algorithm> #include "sniffer.h" using std::string; using std::runtime_error; namespace Tins { BaseSniffer::BaseSniffer() : handle(0), mask(0) { } BaseSniffer::~BaseSniffer() { if(handle) pcap_close(handle); } void BaseSniffer::init(pcap_t *phandle, const std::string &filter, bpf_u_int32 if_mask) { handle = phandle; mask = if_mask; if(!filter.empty() && !set_filter(filter)) throw runtime_error("Invalid filter"); } PtrPacket BaseSniffer::next_packet() { pcap_pkthdr header; PDU *ret = 0; while(!ret) { const u_char *content = pcap_next(handle, &header); const int iface_type = pcap_datalink(handle); if(content) { try { if(iface_type == DLT_EN10MB) { if(Internals::is_dot3((const uint8_t*)content, header.caplen)) ret = new Dot3((const uint8_t*)content, header.caplen); else ret = new EthernetII((const uint8_t*)content, header.caplen); } else if(iface_type == DLT_IEEE802_11_RADIO) ret = new RadioTap((const uint8_t*)content, header.caplen); else if(iface_type == DLT_IEEE802_11) ret = Dot11::from_bytes((const uint8_t*)content, header.caplen); else if(iface_type == DLT_LOOP) ret = new Tins::Loopback((const uint8_t*)content, header.caplen); else if(iface_type == DLT_LINUX_SLL) ret = new Tins::SLL((const uint8_t*)content, header.caplen); else if(iface_type == DLT_PPI) ret = new Tins::PPI((const uint8_t*)content, header.caplen); else throw unknown_link_type(); } catch(malformed_packet&) {} } else break; } return PtrPacket(ret, header.ts); } void BaseSniffer::stop_sniff() { pcap_breakloop(handle); } int BaseSniffer::get_fd() { return pcap_get_selectable_fd(handle); } int BaseSniffer::link_type() const { return pcap_datalink(handle); } BaseSniffer::iterator BaseSniffer::begin() { return iterator(this); } BaseSniffer::iterator BaseSniffer::end() { return iterator(0); } bool BaseSniffer::set_filter(const std::string &filter) { bpf_program prog; if(pcap_compile(handle, &prog, filter.c_str(), 0, mask) == -1) return false; bool result = pcap_setfilter(handle, &prog) != -1; pcap_freecode(&prog); return result; } // ****************************** Sniffer ****************************** Sniffer::Sniffer(const string &device, unsigned max_packet_size, bool promisc, const string &filter) { char error[PCAP_ERRBUF_SIZE]; bpf_u_int32 ip, if_mask; if (pcap_lookupnet(device.c_str(), &ip, &if_mask, error) == -1) { ip = 0; if_mask = 0; } pcap_t *phandle = pcap_open_live(device.c_str(), max_packet_size, promisc, 0, error); if(!phandle) throw runtime_error(error); init(phandle, filter, if_mask); } // **************************** FileSniffer **************************** FileSniffer::FileSniffer(const string &file_name, const string &filter) { char error[PCAP_ERRBUF_SIZE]; pcap_t *phandle = pcap_open_offline(file_name.c_str(), error); if(!phandle) throw std::runtime_error(error); init(phandle, filter, 0); } } <commit_msg>BaseSniffer::next_packet now uses pcap_dispatch.<commit_after>/* * Copyright (c) 2012, Matias Fontanini * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <algorithm> #include "sniffer.h" using std::string; using std::runtime_error; namespace Tins { BaseSniffer::BaseSniffer() : handle(0), mask(0) { } BaseSniffer::~BaseSniffer() { if(handle) pcap_close(handle); } void BaseSniffer::init(pcap_t *phandle, const std::string &filter, bpf_u_int32 if_mask) { handle = phandle; mask = if_mask; if(!filter.empty() && !set_filter(filter)) throw runtime_error("Invalid filter"); } struct sniff_data { struct timeval tv; PDU *pdu; sniff_data() : pdu(0) { } }; template<typename T> T *safe_alloc(const u_char *bytes, bpf_u_int32 len) { try { return new T((const uint8_t*)bytes, len); } catch(malformed_packet&) { return 0; } } template<typename T> void sniff_loop_handler(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) { sniff_data *data = (sniff_data*)user; data->tv = h->ts; data->pdu = safe_alloc<T>(bytes, h->caplen); } void sniff_loop_eth_handler(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) { sniff_data *data = (sniff_data*)user; data->tv = h->ts; if(Internals::is_dot3((const uint8_t*)bytes, h->caplen)) data->pdu = safe_alloc<Dot3>((const uint8_t*)bytes, h->caplen); else data->pdu = safe_alloc<EthernetII>((const uint8_t*)bytes, h->caplen); } void sniff_loop_dot11_handler(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) { sniff_data *data = (sniff_data*)user; data->tv = h->ts; try { data->pdu = Dot11::from_bytes(bytes, h->caplen); } catch(malformed_packet&) { } } PtrPacket BaseSniffer::next_packet() { sniff_data data; const int iface_type = pcap_datalink(handle); pcap_handler handler = 0; if(iface_type == DLT_EN10MB) handler = sniff_loop_eth_handler; else if(iface_type == DLT_IEEE802_11_RADIO) handler = &sniff_loop_handler<RadioTap>; else if(iface_type == DLT_IEEE802_11) handler = sniff_loop_dot11_handler; else if(iface_type == DLT_LOOP) handler = &sniff_loop_handler<Tins::Loopback>; else if(iface_type == DLT_LINUX_SLL) handler = &sniff_loop_handler<SLL>; else if(iface_type == DLT_PPI) handler = &sniff_loop_handler<PPI>; else throw unknown_link_type(); // keep calling pcap_loop until a well-formed packet is found. while(data.pdu == 0) { if(pcap_dispatch(handle, 1, handler, (u_char*)&data) != 1) return PtrPacket(0, Timestamp()); } return PtrPacket(data.pdu, data.tv); } void BaseSniffer::stop_sniff() { pcap_breakloop(handle); } int BaseSniffer::get_fd() { return pcap_get_selectable_fd(handle); } int BaseSniffer::link_type() const { return pcap_datalink(handle); } BaseSniffer::iterator BaseSniffer::begin() { return iterator(this); } BaseSniffer::iterator BaseSniffer::end() { return iterator(0); } bool BaseSniffer::set_filter(const std::string &filter) { bpf_program prog; if(pcap_compile(handle, &prog, filter.c_str(), 0, mask) == -1) return false; bool result = pcap_setfilter(handle, &prog) != -1; pcap_freecode(&prog); return result; } // ****************************** Sniffer ****************************** Sniffer::Sniffer(const string &device, unsigned max_packet_size, bool promisc, const string &filter) { char error[PCAP_ERRBUF_SIZE]; bpf_u_int32 ip, if_mask; if (pcap_lookupnet(device.c_str(), &ip, &if_mask, error) == -1) { ip = 0; if_mask = 0; } pcap_t *phandle = pcap_open_live(device.c_str(), max_packet_size, promisc, 0, error); if(!phandle) throw runtime_error(error); init(phandle, filter, if_mask); } // **************************** FileSniffer **************************** FileSniffer::FileSniffer(const string &file_name, const string &filter) { char error[PCAP_ERRBUF_SIZE]; pcap_t *phandle = pcap_open_offline(file_name.c_str(), error); if(!phandle) throw std::runtime_error(error); init(phandle, filter, 0); } } <|endoftext|>
<commit_before>// Author: Danilo Piparo, Stefan Wunsch, Massimiliano Galli CERN 08/2018 // Original PyROOT code by Wim Lavrijsen, LBL /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "CPyCppyy.h" #include "CPPInstance.h" #include "PyROOTPythonize.h" #include "ProxyWrappers.h" #include "Utility.h" #include "PyzCppHelpers.hxx" #include "TClass.h" #include "TNamed.h" #include "TDirectory.h" #include "TKey.h" #include "Python.h" using namespace CPyCppyy; //////////////////////////////////////////////////////////////////////////////// /// \brief Implements the WriteObject method of TDirectory /// This method allows to write objects into TDirectory instances with this /// syntax: /// ~~~{.py} /// myDir.WriteObject(myObj, "myKeyName") /// ~~~ PyObject *TDirectoryWriteObject(CPPInstance *self, PyObject *args) { CPPInstance *wrt = nullptr; PyObject *name = nullptr; PyObject *option = nullptr; Int_t bufsize = 0; if (!PyArg_ParseTuple(args, const_cast<char *>("O!O!|O!i:TDirectory::WriteObject"), &CPPInstance_Type, &wrt, &CPyCppyy_PyText_Type, &name, &CPyCppyy_PyText_Type, &option, &bufsize)) return nullptr; auto dir = (TDirectory *)GetTClass(self)->DynamicCast(TDirectory::Class(), self->GetObject()); if (!dir) { PyErr_SetString(PyExc_TypeError, "TDirectory::WriteObject must be called with a TDirectory instance as first argument"); return nullptr; } // Implement a check on whether the object is derived from TObject or not. Similarly to what is done in // TDirectory::WriteObject with SFINAE. Unfortunately, 'wrt' is a void* in this scope and can't be casted to its // concrete type. auto *wrtclass = GetTClass(wrt); void *wrtobj = wrt->GetObject(); Int_t result = 0; if (wrtclass->IsTObject()) { // If the found TClass is derived from TObject, cast the object to a TNamed since we are just interested in the // object title for the purposes of the WriteTObject function. auto objtowrite = static_cast<TNamed *>(wrtclass->DynamicCast(TNamed::Class(), wrtobj)); if (option != nullptr) { result = dir->WriteTObject(objtowrite, CPyCppyy_PyText_AsString(name), CPyCppyy_PyText_AsString(option), bufsize); } else { result = dir->WriteTObject(objtowrite, CPyCppyy_PyText_AsString(name)); } } else { if (option != nullptr) { result = dir->WriteObjectAny(wrtobj, wrtclass, CPyCppyy_PyText_AsString(name), CPyCppyy_PyText_AsString(option), bufsize); } else { result = dir->WriteObjectAny(wrtobj, wrtclass, CPyCppyy_PyText_AsString(name)); } } return PyInt_FromLong((Long_t)result); } //////////////////////////////////////////////////////////////////////////////// /// \brief Implements a getter to assign to TDirectory.__getattr__ /// Method that is assigned to TDirectory.__getattr__. It relies on Get to /// obtain the object from the TDirectory and adds on top: /// - Raising an AttributeError if the object does not exist /// - Caching the result of a successful get for future re-attempts. /// Once cached, the same object is retrieved every time. /// This pythonisation is inherited by TDirectoryFile and TFile. PyObject *TDirectoryGetAttr(PyObject *self, PyObject *attr) { // Injection of TDirectory.__getattr__ that raises AttributeError on failure. PyObject *result = CallPyObjMethod(self, "Get", attr); if (!result) return result; if (!PyObject_IsTrue(result)) { PyObject *astr = PyObject_Str(attr); PyObject *stypestr = PyObject_Str(PyObject_Type(self)); PyErr_Format(PyExc_AttributeError, "%s object has no attribute \'%s\'", CPyCppyy_PyText_AsString(stypestr), CPyCppyy_PyText_AsString(astr)); Py_DECREF(astr); Py_DECREF(result); return nullptr; } // Caching behavior seems to be more clear to the user; can always override said // behavior (i.e. re-read from file) with an explicit Get() call PyObject_SetAttr(self, attr, result); return result; } //////////////////////////////////////////////////////////////////////////// /// \brief Add attr syntax to TDirectory /// \param[in] self Always null, since this is a module function. /// \param[in] args Pointer to a Python tuple object containing the arguments /// This allows to use TDirectory and daughters (such as TDirectoryFile and TFile) /// as follows /// ~~~{.py} /// myfile.mydir.mysubdir.myHist.Draw() /// ~~~ PyObject *PyROOT::AddDirectoryGetAttrPyz(PyObject * /* self */, PyObject *args) { PyObject *pyclass = PyTuple_GetItem(args, 0); Utility::AddToClass(pyclass, "__getattr__", (PyCFunction)TDirectoryGetAttr, METH_O); Py_RETURN_NONE; } //////////////////////////////////////////////////////////////////////////// /// \brief Add pythonisation of TDirectory::WriteObject /// \param[in] self Always null, since this is a module function. /// \param[in] args Pointer to a Python tuple object containing the arguments PyObject *PyROOT::AddDirectoryWritePyz(PyObject * /* self */, PyObject *args) { PyObject *pyclass = PyTuple_GetItem(args, 0); Utility::AddToClass(pyclass, "WriteObject", (PyCFunction)TDirectoryWriteObject); Py_RETURN_NONE; } <commit_msg>[PyROOT] Cast TObject-derived object to TObject, not TNamed<commit_after>// Author: Danilo Piparo, Stefan Wunsch, Massimiliano Galli CERN 08/2018 // Original PyROOT code by Wim Lavrijsen, LBL /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "CPyCppyy.h" #include "CPPInstance.h" #include "PyROOTPythonize.h" #include "ProxyWrappers.h" #include "Utility.h" #include "PyzCppHelpers.hxx" #include "TClass.h" #include "TDirectory.h" #include "TKey.h" #include "TObject.h" #include "Python.h" using namespace CPyCppyy; //////////////////////////////////////////////////////////////////////////////// /// \brief Implements the WriteObject method of TDirectory /// This method allows to write objects into TDirectory instances with this /// syntax: /// ~~~{.py} /// myDir.WriteObject(myObj, "myKeyName") /// ~~~ PyObject *TDirectoryWriteObject(CPPInstance *self, PyObject *args) { CPPInstance *wrt = nullptr; PyObject *name = nullptr; PyObject *option = nullptr; Int_t bufsize = 0; if (!PyArg_ParseTuple(args, const_cast<char *>("O!O!|O!i:TDirectory::WriteObject"), &CPPInstance_Type, &wrt, &CPyCppyy_PyText_Type, &name, &CPyCppyy_PyText_Type, &option, &bufsize)) return nullptr; auto dir = (TDirectory *)GetTClass(self)->DynamicCast(TDirectory::Class(), self->GetObject()); if (!dir) { PyErr_SetString(PyExc_TypeError, "TDirectory::WriteObject must be called with a TDirectory instance as first argument"); return nullptr; } // Implement a check on whether the object is derived from TObject or not. Similarly to what is done in // TDirectory::WriteObject with SFINAE. Unfortunately, 'wrt' is a void* in this scope and can't be casted to its // concrete type. auto *wrtclass = GetTClass(wrt); void *wrtobj = wrt->GetObject(); Int_t result = 0; if (wrtclass->IsTObject()) { // If the found TClass is derived from TObject, cast the object to a TObject since we are just interested in the // object title for the purposes of the WriteTObject function. auto objtowrite = static_cast<TObject *>(wrtclass->DynamicCast(TObject::Class(), wrtobj)); if (option != nullptr) { result = dir->WriteTObject(objtowrite, CPyCppyy_PyText_AsString(name), CPyCppyy_PyText_AsString(option), bufsize); } else { result = dir->WriteTObject(objtowrite, CPyCppyy_PyText_AsString(name)); } } else { if (option != nullptr) { result = dir->WriteObjectAny(wrtobj, wrtclass, CPyCppyy_PyText_AsString(name), CPyCppyy_PyText_AsString(option), bufsize); } else { result = dir->WriteObjectAny(wrtobj, wrtclass, CPyCppyy_PyText_AsString(name)); } } return PyInt_FromLong((Long_t)result); } //////////////////////////////////////////////////////////////////////////////// /// \brief Implements a getter to assign to TDirectory.__getattr__ /// Method that is assigned to TDirectory.__getattr__. It relies on Get to /// obtain the object from the TDirectory and adds on top: /// - Raising an AttributeError if the object does not exist /// - Caching the result of a successful get for future re-attempts. /// Once cached, the same object is retrieved every time. /// This pythonisation is inherited by TDirectoryFile and TFile. PyObject *TDirectoryGetAttr(PyObject *self, PyObject *attr) { // Injection of TDirectory.__getattr__ that raises AttributeError on failure. PyObject *result = CallPyObjMethod(self, "Get", attr); if (!result) return result; if (!PyObject_IsTrue(result)) { PyObject *astr = PyObject_Str(attr); PyObject *stypestr = PyObject_Str(PyObject_Type(self)); PyErr_Format(PyExc_AttributeError, "%s object has no attribute \'%s\'", CPyCppyy_PyText_AsString(stypestr), CPyCppyy_PyText_AsString(astr)); Py_DECREF(astr); Py_DECREF(result); return nullptr; } // Caching behavior seems to be more clear to the user; can always override said // behavior (i.e. re-read from file) with an explicit Get() call PyObject_SetAttr(self, attr, result); return result; } //////////////////////////////////////////////////////////////////////////// /// \brief Add attr syntax to TDirectory /// \param[in] self Always null, since this is a module function. /// \param[in] args Pointer to a Python tuple object containing the arguments /// This allows to use TDirectory and daughters (such as TDirectoryFile and TFile) /// as follows /// ~~~{.py} /// myfile.mydir.mysubdir.myHist.Draw() /// ~~~ PyObject *PyROOT::AddDirectoryGetAttrPyz(PyObject * /* self */, PyObject *args) { PyObject *pyclass = PyTuple_GetItem(args, 0); Utility::AddToClass(pyclass, "__getattr__", (PyCFunction)TDirectoryGetAttr, METH_O); Py_RETURN_NONE; } //////////////////////////////////////////////////////////////////////////// /// \brief Add pythonisation of TDirectory::WriteObject /// \param[in] self Always null, since this is a module function. /// \param[in] args Pointer to a Python tuple object containing the arguments PyObject *PyROOT::AddDirectoryWritePyz(PyObject * /* self */, PyObject *args) { PyObject *pyclass = PyTuple_GetItem(args, 0); Utility::AddToClass(pyclass, "WriteObject", (PyCFunction)TDirectoryWriteObject); Py_RETURN_NONE; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MDriver.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 06:18:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONNECTIVITY_SDRIVER_HXX #define CONNECTIVITY_SDRIVER_HXX #ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_ #include <com/sun/star/sdbc/XDriver.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase2.hxx> #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include "connectivity/CommonTools.hxx" #endif #ifndef _OSL_MODULE_H_ #include <osl/module.h> #endif #define MOZAB_MOZILLA_SCHEMA "mozilla" #define MOZAB_THUNDERBIRD_SCHEMA "thunderbird" #define MOZAB_LDAP_SCHEMA "ldap" #define MOZAB_OUTLOOK_SCHEMA "outlook" #define MOZAB_OUTLOOKEXP_SCHEMA "outlookexp" #define MOZAB_DRIVER_IMPL_NAME "com.sun.star.comp.sdbc.MozabDriver" namespace connectivity { namespace mozab { ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL MozabDriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception ); typedef void* (SAL_CALL * OMozabConnection_CreateInstanceFunction)(void* _pDriver ); typedef void (SAL_CALL * OSetMozabServiceFactory)( void* _pFactory ); typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::sdbc::XDriver, ::com::sun::star::lang::XServiceInfo > ODriver_BASE; enum EDriverType { Mozilla, ThunderBird, LDAP, Outlook, OutlookExpress, Unknown }; class MozabDriver : public ODriver_BASE { protected: const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xMSFactory; ::osl::Mutex m_aMutex; // mutex is need to control member access connectivity::OWeakRefArray m_xConnections; // vector containing a list // of all the Connection objects // for this Driver oslModule s_hModule; OMozabConnection_CreateInstanceFunction s_pCreationFunc; void registerClient(); virtual ~MozabDriver(); public: MozabDriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory); // OComponentHelper virtual void SAL_CALL disposing(void); // XInterface static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static( ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); // XDriver virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMajorVersion( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMinorVersion( ) throw(::com::sun::star::uno::RuntimeException); const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & getMSFactory(void) const { return m_xMSFactory; } static EDriverType acceptsURL_Stat( const ::rtl::OUString& url ); // static methods to return the names of the uri static const sal_Char* getSDBC_SCHEME_MOZILLA(); static const sal_Char* getSDBC_SCHEME_THUNDERBIRD(); static const sal_Char* getSDBC_SCHEME_LDAP(); static const sal_Char* getSDBC_SCHEME_OUTLOOK_MAPI(); static const sal_Char* getSDBC_SCHEME_OUTLOOK_EXPRESS(); }; } } #endif // CONNECTIVITY_SDRIVER_HXX <commit_msg>INTEGRATION: CWS warnings01 (1.7.30); FILE MERGED 2006/05/18 12:06:21 fs 1.7.30.3: #i65444# 2006/03/29 12:39:24 fs 1.7.30.2: getSdbcSceme not reachable for the driver - need to locate symbol on demand 2005/11/21 10:07:51 fs 1.7.30.1: #i57457# warning-free code on unx*<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MDriver.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-06-20 01:43:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONNECTIVITY_SDRIVER_HXX #define CONNECTIVITY_SDRIVER_HXX #ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_ #include <com/sun/star/sdbc/XDriver.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase2.hxx> #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include "connectivity/CommonTools.hxx" #endif #ifndef _OSL_MODULE_H_ #include <osl/module.h> #endif #define MOZAB_DRIVER_IMPL_NAME "com.sun.star.comp.sdbc.MozabDriver" namespace connectivity { namespace mozab { ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL MozabDriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception ); typedef void* (SAL_CALL * OMozabConnection_CreateInstanceFunction)(void* _pDriver ); typedef void (SAL_CALL * OSetMozabServiceFactory)( void* _pFactory ); typedef const void* (SAL_CALL * OGetSdbcScheme_Function)( short ); typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::sdbc::XDriver, ::com::sun::star::lang::XServiceInfo > ODriver_BASE; enum EDriverType { Mozilla, ThunderBird, LDAP, Outlook, OutlookExpress, Unknown }; class MozabDriver : public ODriver_BASE { protected: const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xMSFactory; ::osl::Mutex m_aMutex; // mutex is need to control member access connectivity::OWeakRefArray m_xConnections; // vector containing a list // of all the Connection objects // for this Driver oslModule m_hModule; OMozabConnection_CreateInstanceFunction m_pCreationFunc; OGetSdbcScheme_Function m_pSchemeFunction; bool ensureInit(); virtual ~MozabDriver(); public: MozabDriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory); // OComponentHelper virtual void SAL_CALL disposing(void); // XInterface static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static( ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); // XDriver virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMajorVersion( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMinorVersion( ) throw(::com::sun::star::uno::RuntimeException); const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & getMSFactory(void) const { return m_xMSFactory; } private: EDriverType impl_classifyURL( const ::rtl::OUString& url ); }; } } #endif // CONNECTIVITY_SDRIVER_HXX <|endoftext|>
<commit_before>/*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de =========================================================================== Copyright (C) 2010 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 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. =========================================================================== Author: Manuel Holtgrewe <[email protected]> =========================================================================== A simple tool for pairwise local and alignment given at the command line. Currently works for type DnaString only. ===========================================================================*/ #include <iostream> #include <seqan/align.h> // Banner to print at top of program output. const char *kBanner = ( "********************************\n" " arg_align -- Simple Alignment \n" "********************************\n" "\n" "We use edit distance scoring\n"); // Usage help message. const char *kUsageStr = ( "Align two strings, given on the command line.\n" "\n" "Usage: local_align SEQ1 SEQ2"); // Program return codes. const int kRetOk = 0; // No error. const int kRetArgErr = 1; // Argument error. using namespace seqan; typedef Dna5String TSequenceType; // The sequence type used below. // Parse parameters. // // Return true iff the parameters were valid. bool parseParameters(int argc, char **argv, TSequenceType &seq1, TSequenceType &seq2) { if (argc != 3) return false; // Simply assign parameters. // TODO(holtgrew): Checking for valid characters. seq1 = argv[1]; seq2 = argv[2]; return true; } int main(int argc, char **argv) { std::cout << kBanner << std::endl; // Get parameter from args. TSequenceType seq1, seq2; if (not parseParameters(argc, argv, seq1, seq2)) { std::cerr << kUsageStr << std::endl; return kRetArgErr; } // Perform local alignments. // // First, setup the book-keeping objects. Align<TSequenceType> ali; appendValue(rows(ali), seq1); appendValue(rows(ali), seq2); Score<int> scoring;//(0, -1, -1); // Then, find the best local alignment. // TODO(holtgrew): Score always seems to be 0. { int scoreValue = localAlignment(ali, scoring, SmithWaterman()); std::cout << "Local alignment with score " << scoreValue << std::endl; std::cout << ali << std::endl; } // Then, find the best local alignment. { int scoreValue = globalAlignment(ali, scoring, NeedlemanWunsch()); std::cout << "Global alignment with score " << scoreValue << std::endl; std::cout << ali << std::endl; } return kRetOk; } <commit_msg>`s/not/!/g` in arg_align.cpp<commit_after>/*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de =========================================================================== Copyright (C) 2010 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 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. =========================================================================== Author: Manuel Holtgrewe <[email protected]> =========================================================================== A simple tool for pairwise local and alignment given at the command line. Currently works for type DnaString only. ===========================================================================*/ #include <iostream> #include <seqan/align.h> // Banner to print at top of program output. const char *kBanner = ( "********************************\n" " arg_align -- Simple Alignment \n" "********************************\n" "\n" "We use edit distance scoring\n"); // Usage help message. const char *kUsageStr = ( "Align two strings, given on the command line.\n" "\n" "Usage: local_align SEQ1 SEQ2"); // Program return codes. const int kRetOk = 0; // No error. const int kRetArgErr = 1; // Argument error. using namespace seqan; typedef Dna5String TSequenceType; // The sequence type used below. // Parse parameters. // // Return true iff the parameters were valid. bool parseParameters(int argc, char **argv, TSequenceType &seq1, TSequenceType &seq2) { if (argc != 3) return false; // Simply assign parameters. // TODO(holtgrew): Checking for valid characters. seq1 = argv[1]; seq2 = argv[2]; return true; } int main(int argc, char **argv) { std::cout << kBanner << std::endl; // Get parameter from args. TSequenceType seq1, seq2; if (!parseParameters(argc, argv, seq1, seq2)) { std::cerr << kUsageStr << std::endl; return kRetArgErr; } // Perform local alignments. // // First, setup the book-keeping objects. Align<TSequenceType> ali; appendValue(rows(ali), seq1); appendValue(rows(ali), seq2); Score<int> scoring;//(0, -1, -1); // Then, find the best local alignment. // TODO(holtgrew): Score always seems to be 0. { int scoreValue = localAlignment(ali, scoring, SmithWaterman()); std::cout << "Local alignment with score " << scoreValue << std::endl; std::cout << ali << std::endl; } // Then, find the best local alignment. { int scoreValue = globalAlignment(ali, scoring, NeedlemanWunsch()); std::cout << "Global alignment with score " << scoreValue << std::endl; std::cout << ali << std::endl; } return kRetOk; } <|endoftext|>
<commit_before>#include <agency/future.hpp> #include <agency/new_executor_traits.hpp> #include <iostream> #include <cassert> #include "test_executors.hpp" template<class Executor> void test() { using executor_type = Executor; size_t n = 1; auto int_ready = agency::detail::make_ready_future(0); auto void_ready = agency::detail::make_ready_future(); auto futures = std::make_tuple(std::move(void_ready), std::move(int_ready)); std::mutex mut; executor_type exec; std::future<int> fut = agency::new_executor_traits<executor_type>::template when_all_execute_and_select<1>(exec, [&mut](int& x) { mut.lock(); x += 1; mut.unlock(); }, std::move(futures)); auto got = fut.get(); assert(got == n); assert(exec.valid()); } int main() { using namespace test_executors; test<empty_executor>(); test<single_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_executor>(); test<single_agent_then_execute_executor>(); test<multi_agent_execute_returning_user_defined_container_executor>(); test<multi_agent_execute_returning_default_container_executor>(); test<multi_agent_execute_returning_void_executor>(); test<multi_agent_async_execute_returning_user_defined_container_executor>(); test<multi_agent_async_execute_returning_default_container_executor>(); std::cout << "OK" << std::endl; return 0; } <commit_msg>Test multi_agent_async_execute_returning_void_executor with test_single_agent_when_all_execute_and_select.cpp<commit_after>#include <agency/future.hpp> #include <agency/new_executor_traits.hpp> #include <iostream> #include <cassert> #include "test_executors.hpp" template<class Executor> void test() { using executor_type = Executor; size_t n = 1; auto int_ready = agency::detail::make_ready_future(0); auto void_ready = agency::detail::make_ready_future(); auto futures = std::make_tuple(std::move(void_ready), std::move(int_ready)); std::mutex mut; executor_type exec; std::future<int> fut = agency::new_executor_traits<executor_type>::template when_all_execute_and_select<1>(exec, [&mut](int& x) { mut.lock(); x += 1; mut.unlock(); }, std::move(futures)); auto got = fut.get(); assert(got == n); assert(exec.valid()); } int main() { using namespace test_executors; test<empty_executor>(); test<single_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_executor>(); test<single_agent_then_execute_executor>(); test<multi_agent_execute_returning_user_defined_container_executor>(); test<multi_agent_execute_returning_default_container_executor>(); test<multi_agent_execute_returning_void_executor>(); test<multi_agent_async_execute_returning_user_defined_container_executor>(); test<multi_agent_async_execute_returning_default_container_executor>(); test<multi_agent_async_execute_returning_void_executor>(); std::cout << "OK" << std::endl; return 0; } <|endoftext|>
<commit_before>#include <Arduino.h> /* SPLODER - a connected button for blowing stuff up. Or whatever else you want to do with it. Check the README.md for info on the Sploder circuit. Copyright (C) 2015 George White <[email protected]>. All rights reserved. See https://raw.githubusercontent.com/stonehippo/sploder/master/LICENSE.txt for license details. */ // Override enabling of logging and debug output #define DEBUG false #include <FiniteStateMachine.h> #include <SPI.h> #include "Adafruit_BLE_UART.h" #include "LogHelpers.h" #include "TimingHelpers.h" #include "sploder.h" // Hold the state of the arming switch boolean armed = false; // Pins configs for the buttons and switches const byte ARMING_SWITCH = 8; const byte TRIGGER_BUTTON = 3; const byte POWERED_LED = 7; const byte FIRING_LED = 5; // current brightness of the firing LED (to enable pulsing); see the helpers for a little more detail const float START_RADIAN = 4.712; // Start at the mid-point of the sine wave (all the way off) const float MAX_RADIAN = 10.995; const float RADIAN_STEP = 0.00045; // how many radians do we step the sine wave per loop? optimized for 3.3v, 8mHz set to 0.000225 for a 16mHz Arduino const float SIN_OFFSET = 127.5; // the offset to map the sin values back to 0-255 for analogWrite float firingLEDBrightness = START_RADIAN; // Pin configs for the Adafruit nrf8001 breakout board const byte BLE_REQUEST = 10; const byte BLE_READY = 2; const byte BLE_RESET = 9; // Create a Bluetooth LE UART instance to set up the basic connection Adafruit_BLE_UART BluetoothLESerial = Adafruit_BLE_UART(BLE_REQUEST, BLE_READY, BLE_RESET); // Global to monitor the state of the nrf8001 Bluetooth board aci_evt_opcode_t bleLastStatus = ACI_EVT_DISCONNECTED; // Managing debounce of the button used to FIRE! long lastDebounceTime = 0; long debounceDelay = 1000; // This needs to be fairly large for the big dome button; that large spring is pretty bouncy // We'll hold timing information about certain states here long timerStartupState = 0; long timerFiringState = 0; // FSM states State startupState = State(enterStartupState,updateStartupState,leaveStartupState); State readyState = State(enterReadyState,updateReadyState,leaveReadyState); State armedState = State(enterArmedState,updateArmedState,leaveArmedState); State firingState = State(enterFiringState,updateFiringState,leaveFiringState); // Kicking off the FSM FSM stateMachine = FSM(startupState); // ******************* BASIC ARDUINO SETUP & LOOP ******************* void setup() { pinMode(TRIGGER_BUTTON, INPUT_PULLUP); pinMode(ARMING_SWITCH, INPUT_PULLUP); pinMode(POWERED_LED, OUTPUT); pinMode(FIRING_LED, OUTPUT); attachInterrupt(1,fireEvent,HIGH); startLog(); BluetoothLESerial.begin(); } void loop() { // What's up, Bluetooth? BluetoothLESerial.pollACI(); //check the status of the Bluetooth LE connection aci_evt_opcode_t bleStatus = BluetoothLESerial.getState(); if (bleStatus != bleLastStatus) { if (bleStatus == ACI_EVT_DEVICE_STARTED) { info("BLE advertising started"); } if (bleStatus == ACI_EVT_CONNECTED) { info("BLE connected"); // Immediately send the current state of the FSM // Have to use the library print() helper, as the current status has not been updated yet if (stateMachine.isInState(readyState)) { BluetoothLESerial.print("ready"); } if (stateMachine.isInState(armedState)) { BluetoothLESerial.print("armed"); } if (stateMachine.isInState(firingState)) { BluetoothLESerial.print("firing"); } } if (bleStatus == ACI_EVT_DISCONNECTED) { info("BLE disconnected"); } bleLastStatus = bleStatus; } // Time to handle the state machine stateMachine.update(); } // ******************* INTERRUPT EVENTS ******************* void fireEvent() { if ((millis() - lastDebounceTime) > debounceDelay) { if (stateMachine.isInState(armedState)) { stateMachine.transitionTo(firingState); } lastDebounceTime = millis(); } } // ******************* FSM state callback methods ******************* // -------------- Startup State --------------- void enterStartupState() { digitalWrite(POWERED_LED, HIGH); note("starting up"); startTimer(timerStartupState); } void updateStartupState() { if(isTimerExpired(timerStartupState, 1000)) { stateMachine.transitionTo(readyState); } } void leaveStartupState() { note("startup complete"); clearTimer(timerStartupState); } // -------------- Ready State --------------- void enterReadyState() { blePrint("ready"); } void updateReadyState() { armedStatus(); if (armed) { stateMachine.transitionTo(armedState); } } void leaveReadyState() {} // -------------- Armed State --------------- void enterArmedState() { armedStatus(); if (armed) { blePrint("armed"); beginPulsingFiringLED(); } } void updateArmedState() { armedStatus(); if (armed) { pulseFiringLED(); } if (!armed) { blePrint("disarmed"); stateMachine.transitionTo(readyState); } } void leaveArmedState() { endPulsingFiringLED(); } // -------------- Firing State --------------- void enterFiringState () { blePrint("firing"); firingLEDOn(); startTimer(timerFiringState); } void updateFiringState() { delay(100); if (isFiringLEDOn()) { firingLEDOff(); } else { firingLEDOn(); } if(isTimerExpired(timerFiringState, 5000)) { stateMachine.transitionTo(armedState); } } void leaveFiringState() { blePrint("fired"); firingLEDOff(); clearTimer(timerFiringState); } // ******************* HELPERS ******************* // Switch state helpers void armedStatus() { if (digitalRead(ARMING_SWITCH) == HIGH) { armed = false; } else { armed = true; } } // Firing LED helpers void firingLEDOff() { digitalWrite(FIRING_LED, LOW); } void firingLEDOn() { digitalWrite(FIRING_LED, HIGH); } // Firing LED animation helpers void beginPulsingFiringLED() { firingLEDBrightness = START_RADIAN; } boolean isFiringLEDOn() { if (digitalRead(FIRING_LED) == HIGH) { return true; } return false; } // We use a sine wave to get a nice, clean pulse for the LED // Rather than using an explicit loop, we use the existing Arduino loop, the LED gets updated // at the speed of the microcontroller in a minimally-blocking manner // See https://www.sparkfun.com/tutorials/329 for more void pulseFiringLED() { if (firingLEDBrightness < MAX_RADIAN) { firingLEDBrightness = firingLEDBrightness + RADIAN_STEP; } else { beginPulsingFiringLED(); } float currentBrightness = sin(firingLEDBrightness) * SIN_OFFSET + SIN_OFFSET; analogWrite(FIRING_LED, currentBrightness); } void endPulsingFiringLED() { firingLEDOff(); } // Bluetooth UART helpers boolean bleIsConnected() { if (bleLastStatus == ACI_EVT_CONNECTED) { return true; } return false; } /* The nrf8001 breakout has a maximum send buffer of 20 bytes, so we need to convert message strings into a byte array for buffering. I'm also using my own helper so I can check the status of the modem easily to prevent hanging when there's no connection. */ void blePrint(String message) { if (bleIsConnected()) { uint8_t sendBuffer[20]; message.getBytes(sendBuffer, 20); char sendBufferSize = min(20, message.length()); BluetoothLESerial.write(sendBuffer, sendBufferSize); } // echo out the message to the serial console, regardless of BLE status note(message); } <commit_msg>Customize BLE device name<commit_after>#include <Arduino.h> /* SPLODER - a connected button for blowing stuff up. Or whatever else you want to do with it. Check the README.md for info on the Sploder circuit. Copyright (C) 2015 George White <[email protected]>. All rights reserved. See https://raw.githubusercontent.com/stonehippo/sploder/master/LICENSE.txt for license details. */ // Override enabling of logging and debug output #define DEBUG false #include <FiniteStateMachine.h> #include <SPI.h> #include "Adafruit_BLE_UART.h" #include "LogHelpers.h" #include "TimingHelpers.h" #include "sploder.h" // Hold the state of the arming switch boolean armed = false; // Pins configs for the buttons and switches const byte ARMING_SWITCH = 8; const byte TRIGGER_BUTTON = 3; const byte POWERED_LED = 7; const byte FIRING_LED = 5; // current brightness of the firing LED (to enable pulsing); see the helpers for a little more detail const float START_RADIAN = 4.712; // Start at the mid-point of the sine wave (all the way off) const float MAX_RADIAN = 10.995; const float RADIAN_STEP = 0.00045; // how many radians do we step the sine wave per loop? optimized for 3.3v, 8mHz set to 0.000225 for a 16mHz Arduino const float SIN_OFFSET = 127.5; // the offset to map the sin values back to 0-255 for analogWrite float firingLEDBrightness = START_RADIAN; // Pin configs for the Adafruit nrf8001 breakout board const byte BLE_REQUEST = 10; const byte BLE_READY = 2; const byte BLE_RESET = 9; // Create a Bluetooth LE UART instance to set up the basic connection Adafruit_BLE_UART BluetoothLESerial = Adafruit_BLE_UART(BLE_REQUEST, BLE_READY, BLE_RESET); // Global to monitor the state of the nrf8001 Bluetooth board aci_evt_opcode_t bleLastStatus = ACI_EVT_DISCONNECTED; // Managing debounce of the button used to FIRE! long lastDebounceTime = 0; long debounceDelay = 1000; // This needs to be fairly large for the big dome button; that large spring is pretty bouncy // We'll hold timing information about certain states here long timerStartupState = 0; long timerFiringState = 0; // FSM states State startupState = State(enterStartupState,updateStartupState,leaveStartupState); State readyState = State(enterReadyState,updateReadyState,leaveReadyState); State armedState = State(enterArmedState,updateArmedState,leaveArmedState); State firingState = State(enterFiringState,updateFiringState,leaveFiringState); // Kicking off the FSM FSM stateMachine = FSM(startupState); // ******************* BASIC ARDUINO SETUP & LOOP ******************* void setup() { pinMode(TRIGGER_BUTTON, INPUT_PULLUP); pinMode(ARMING_SWITCH, INPUT_PULLUP); pinMode(POWERED_LED, OUTPUT); pinMode(FIRING_LED, OUTPUT); attachInterrupt(1,fireEvent,HIGH); startLog(); BluetoothLESerial.begin(); BluetoothLESerial.setDeviceName("Sploder"); } void loop() { // What's up, Bluetooth? BluetoothLESerial.pollACI(); //check the status of the Bluetooth LE connection aci_evt_opcode_t bleStatus = BluetoothLESerial.getState(); if (bleStatus != bleLastStatus) { if (bleStatus == ACI_EVT_DEVICE_STARTED) { info("BLE advertising started"); } if (bleStatus == ACI_EVT_CONNECTED) { info("BLE connected"); // Immediately send the current state of the FSM // Have to use the library print() helper, as the current status has not been updated yet if (stateMachine.isInState(readyState)) { BluetoothLESerial.print("ready"); } if (stateMachine.isInState(armedState)) { BluetoothLESerial.print("armed"); } if (stateMachine.isInState(firingState)) { BluetoothLESerial.print("firing"); } } if (bleStatus == ACI_EVT_DISCONNECTED) { info("BLE disconnected"); } bleLastStatus = bleStatus; } // Time to handle the state machine stateMachine.update(); } // ******************* INTERRUPT EVENTS ******************* void fireEvent() { if ((millis() - lastDebounceTime) > debounceDelay) { if (stateMachine.isInState(armedState)) { stateMachine.transitionTo(firingState); } lastDebounceTime = millis(); } } // ******************* FSM state callback methods ******************* // -------------- Startup State --------------- void enterStartupState() { digitalWrite(POWERED_LED, HIGH); note("starting up"); startTimer(timerStartupState); } void updateStartupState() { if(isTimerExpired(timerStartupState, 1000)) { stateMachine.transitionTo(readyState); } } void leaveStartupState() { note("startup complete"); clearTimer(timerStartupState); } // -------------- Ready State --------------- void enterReadyState() { blePrint("ready"); } void updateReadyState() { armedStatus(); if (armed) { stateMachine.transitionTo(armedState); } } void leaveReadyState() {} // -------------- Armed State --------------- void enterArmedState() { armedStatus(); if (armed) { blePrint("armed"); beginPulsingFiringLED(); } } void updateArmedState() { armedStatus(); if (armed) { pulseFiringLED(); } if (!armed) { blePrint("disarmed"); stateMachine.transitionTo(readyState); } } void leaveArmedState() { endPulsingFiringLED(); } // -------------- Firing State --------------- void enterFiringState () { blePrint("firing"); firingLEDOn(); startTimer(timerFiringState); } void updateFiringState() { delay(100); if (isFiringLEDOn()) { firingLEDOff(); } else { firingLEDOn(); } if(isTimerExpired(timerFiringState, 5000)) { stateMachine.transitionTo(armedState); } } void leaveFiringState() { blePrint("fired"); firingLEDOff(); clearTimer(timerFiringState); } // ******************* HELPERS ******************* // Switch state helpers void armedStatus() { if (digitalRead(ARMING_SWITCH) == HIGH) { armed = false; } else { armed = true; } } // Firing LED helpers void firingLEDOff() { digitalWrite(FIRING_LED, LOW); } void firingLEDOn() { digitalWrite(FIRING_LED, HIGH); } // Firing LED animation helpers void beginPulsingFiringLED() { firingLEDBrightness = START_RADIAN; } boolean isFiringLEDOn() { if (digitalRead(FIRING_LED) == HIGH) { return true; } return false; } // We use a sine wave to get a nice, clean pulse for the LED // Rather than using an explicit loop, we use the existing Arduino loop, the LED gets updated // at the speed of the microcontroller in a minimally-blocking manner // See https://www.sparkfun.com/tutorials/329 for more void pulseFiringLED() { if (firingLEDBrightness < MAX_RADIAN) { firingLEDBrightness = firingLEDBrightness + RADIAN_STEP; } else { beginPulsingFiringLED(); } float currentBrightness = sin(firingLEDBrightness) * SIN_OFFSET + SIN_OFFSET; analogWrite(FIRING_LED, currentBrightness); } void endPulsingFiringLED() { firingLEDOff(); } // Bluetooth UART helpers boolean bleIsConnected() { if (bleLastStatus == ACI_EVT_CONNECTED) { return true; } return false; } /* The nrf8001 breakout has a maximum send buffer of 20 bytes, so we need to convert message strings into a byte array for buffering. I'm also using my own helper so I can check the status of the modem easily to prevent hanging when there's no connection. */ void blePrint(String message) { if (bleIsConnected()) { uint8_t sendBuffer[20]; message.getBytes(sendBuffer, 20); char sendBufferSize = min(20, message.length()); BluetoothLESerial.write(sendBuffer, sendBufferSize); } // echo out the message to the serial console, regardless of BLE status note(message); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2015. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include "config.hpp" #include "washington.hpp" namespace { int command_train(const config& conf){ if(conf.files.empty()){ std::cout << "Train needs the path to the dataset" << std::endl; return -1; } auto dataset = read_dataset(conf.files.front()); std::cout << dataset.line_images.size() << " line images loaded" << std::endl; std::cout << dataset.word_images.size() << " word images loaded" << std::endl; return 0; } } //end of anonymous namespace int main(int argc, char** argv){ if(argc < 2){ print_usage(); return -1; } auto conf = parse_args(argc, argv); if(!conf.method_1){ std::cout << "error: One method must be selected" << std::endl; print_usage(); return -1; } if(conf.command == "train"){ return command_train(conf); } print_usage(); return -1; } <commit_msg>Separate datasets<commit_after>//======================================================================= // Copyright Baptiste Wicht 2015. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include "config.hpp" #include "washington.hpp" namespace { int command_train(const config& conf){ if(conf.files.size() < 2){ std::cout << "Train needs the path to the dataset and the cv set to use" << std::endl; return -1; } auto& dataset_path = conf.files[0]; auto& cv_set = conf.files[1]; std::cout << "Dataset: " << dataset_path << std::endl; std::cout << " Set: " << cv_set << std::endl; auto dataset = read_dataset(dataset_path); std::cout << dataset.line_images.size() << " line images loaded from the dataset" << std::endl; std::cout << dataset.word_images.size() << " word images loaded from the dataset" << std::endl; if(!dataset.sets.count(cv_set)){ std::cout << "The subset \"" << cv_set << "\" does not exist" << std::endl; return -1; } auto& set = dataset.sets[cv_set]; std::cout << set.train_set.size() << " training line images in set" << std::endl; std::cout << set.validation_set.size() << " validation line images in set" << std::endl; std::cout << set.test_set.size() << " test line images in set" << std::endl; std::vector<std::string> train_image_names; std::vector<std::string> test_image_names; std::vector<std::string> valid_image_names; for(auto& word_image : dataset.word_images){ auto& name = word_image.first; for(auto& train_image : set.train_set){ if(name.find(std::string(train_image.begin(), train_image.end() - 4)) == 0){ train_image_names.push_back(name); break; } } for(auto& test_image : set.test_set){ if(name.find(std::string(test_image.begin(), test_image.end() - 4)) == 0){ test_image_names.push_back(name); break; } } for(auto& valid_image : set.validation_set){ if(name.find(std::string(valid_image.begin(), valid_image.end() - 4)) == 0){ valid_image_names.push_back(name); break; } } } std::cout << train_image_names.size() << " training word images in set" << std::endl; std::cout << valid_image_names.size() << " validation word images in set" << std::endl; std::cout << test_image_names.size() << " test word images in set" << std::endl; return 0; } } //end of anonymous namespace int main(int argc, char** argv){ if(argc < 2){ print_usage(); return -1; } auto conf = parse_args(argc, argv); if(!conf.method_1){ std::cout << "error: One method must be selected" << std::endl; print_usage(); return -1; } if(conf.command == "train"){ return command_train(conf); } print_usage(); return -1; } <|endoftext|>
<commit_before>#define P(p) const point3d &p #define L(p0, p1) P(p0), P(p1) #define PL(p0, p1, p2) P(p0), P(p1), P(p2) struct point3d { double x, y, z; point3d() : x(0), y(0), z(0) {} point3d(double _x, double _y, double _z) : x(_x), y(_y), z(_z) {} point3d operator+(P(p)) const { return point3d(x + p.x, y + p.y, z + p.z); } point3d operator-(P(p)) const { return point3d(x - p.x, y - p.y, z - p.z); } point3d operator-() const { return point3d(-x, -y, -z); } point3d operator*(double k) const { return point3d(x * k, y * k, z * k); } point3d operator/(double k) const { return point3d(x / k, y / k, z / k); } double operator%(P(p)) const { return x * p.x + y * p.y + z * p.z; } point3d operator*(P(p)) const { return point3d(y*p.z - z*p.y, z*p.x - x*p.z, x*p.y - y*p.x); } double length() const { return sqrt(*this % *this); } double distTo(P(p)) const { return (*this - p).length(); } double distTo(P(A), P(B)) const { // A and B must be two different points return ((*this - A) * (*this - B)).length() / A.distTo(B);} double signedDistTo(PL(A,B,C)) const { // A, B and C must not be collinear point3d N = (B-A)*(C-A); double D = A%N; return ((*this)%N - D)/N.length();} point3d normalize(double k = 1) const { // length() must not return 0 return (*this) * (k / length()); } point3d getProjection(P(A), P(B)) const { point3d v = B - A; return A + v.normalize((v % (*this - A)) / v.length()); } point3d rotate(P(normal)) const { //normal must have length 1 and be orthogonal to the vector return (*this) * normal; } point3d rotate(double alpha, P(normal)) const { return (*this) * cos(alpha) + rotate(normal) * sin(alpha);} point3d rotatePoint(P(O), P(axe), double alpha) const{ point3d Z = axe.normalize(axe % (*this - O)); return O + Z + (*this - O - Z).rotate(alpha, O); } bool isZero() const { return abs(x) < EPS && abs(y) < EPS && abs(z) < EPS; } bool isOnLine(L(A, B)) const { return ((A - *this) * (B - *this)).isZero(); } bool isInSegment(L(A, B)) const { return isOnLine(A, B) && ((A - *this) % (B - *this))<EPS;} bool isInSegmentStrictly(L(A, B)) const { return isOnLine(A, B) && ((A - *this) % (B - *this))<-EPS;} double getAngle() const { return atan2(y, x); } double getAngle(P(u)) const { return atan2((*this * u).length(), *this % u); } bool isOnPlane(PL(A, B, C)) const { return abs((A - *this) * (B - *this) % (C - *this)) < EPS; } }; int line_line_intersect(L(A, B), L(C, D), point3d &O){ if (abs((B - A) * (C - A) % (D - A)) > EPS) return 0; if (((A - B) * (C - D)).length() < EPS) return A.isOnLine(C, D) ? 2 : 0; point3d normal = ((A - B) * (C - B)).normalize(); double s1 = (C - A) * (D - A) % normal; O = A + ((B - A) / (s1 + ((D - B) * (C - B) % normal))) * s1; return 1; } int line_plane_intersect(L(A, B), PL(C, D, E), point3d & O) { double V1 = (C - A) * (D - A) % (E - A); double V2 = (D - B) * (C - B) % (E - B); if (abs(V1 + V2) < EPS) return A.isOnPlane(C, D, E) ? 2 : 0; O = A + ((B - A) / (V1 + V2)) * V1; return 1; } bool plane_plane_intersect(P(A), P(nA), P(B), P(nB), point3d &P, point3d &Q) { point3d n = nA * nB; if (n.isZero()) return false; point3d v = n * nA; P = A + (n * nA) * ((B - A) % nB / (v % nB)); Q = P + n; return true; } // vim: cc=60 ts=2 sts=2 sw=2: <commit_msg>point3d: signed dist to plane<commit_after>#define P(p) const point3d &p #define L(p0, p1) P(p0), P(p1) #define PL(p0, p1, p2) P(p0), P(p1), P(p2) struct point3d { double x, y, z; point3d() : x(0), y(0), z(0) {} point3d(double _x, double _y, double _z) : x(_x), y(_y), z(_z) {} point3d operator+(P(p)) const { return point3d(x + p.x, y + p.y, z + p.z); } point3d operator-(P(p)) const { return point3d(x - p.x, y - p.y, z - p.z); } point3d operator-() const { return point3d(-x, -y, -z); } point3d operator*(double k) const { return point3d(x * k, y * k, z * k); } point3d operator/(double k) const { return point3d(x / k, y / k, z / k); } double operator%(P(p)) const { return x * p.x + y * p.y + z * p.z; } point3d operator*(P(p)) const { return point3d(y*p.z - z*p.y, z*p.x - x*p.z, x*p.y - y*p.x); } double length() const { return sqrt(*this % *this); } double distTo(P(p)) const { return (*this - p).length(); } double distTo(P(A), P(B)) const { // A and B must be two different points return ((*this - A) * (*this - B)).length() / A.distTo(B);} double signedDistTo(PL(A,B,C)) const { // A, B and C must not be collinear point3d N = (B-A)*(C-A); double D = A%N; return ((*this)%N - D)/N.length();} point3d normalize(double k = 1) const { // length() must not return 0 return (*this) * (k / length()); } point3d getProjection(P(A), P(B)) const { point3d v = B - A; return A + v.normalize((v % (*this - A)) / v.length()); } point3d rotate(P(normal)) const { //normal must have length 1 and be orthogonal to the vector return (*this) * normal; } point3d rotate(double alpha, P(normal)) const { return (*this) * cos(alpha) + rotate(normal) * sin(alpha);} point3d rotatePoint(P(O), P(axe), double alpha) const{ point3d Z = axe.normalize(axe % (*this - O)); return O + Z + (*this - O - Z).rotate(alpha, O); } bool isZero() const { return abs(x) < EPS && abs(y) < EPS && abs(z) < EPS; } bool isOnLine(L(A, B)) const { return ((A - *this) * (B - *this)).isZero(); } bool isInSegment(L(A, B)) const { return isOnLine(A, B) && ((A - *this) % (B - *this))<EPS;} bool isInSegmentStrictly(L(A, B)) const { return isOnLine(A, B) && ((A - *this) % (B - *this))<-EPS;} double getAngle() const { return atan2(y, x); } double getAngle(P(u)) const { return atan2((*this * u).length(), *this % u); } bool isOnPlane(PL(A, B, C)) const { return abs((A - *this) * (B - *this) % (C - *this)) < EPS; } }; int line_line_intersect(L(A, B), L(C, D), point3d &O){ if (abs((B - A) * (C - A) % (D - A)) > EPS) return 0; if (((A - B) * (C - D)).length() < EPS) return A.isOnLine(C, D) ? 2 : 0; point3d normal = ((A - B) * (C - B)).normalize(); double s1 = (C - A) * (D - A) % normal; O = A + ((B - A) / (s1 + ((D - B) * (C - B) % normal))) * s1; return 1; } int line_plane_intersect(L(A, B), PL(C, D, E), point3d & O) { double V1 = (C - A) * (D - A) % (E - A); double V2 = (D - B) * (C - B) % (E - B); if (abs(V1 + V2) < EPS) return A.isOnPlane(C, D, E) ? 2 : 0; O = A + ((B - A) / (V1 + V2)) * V1; return 1; } bool plane_plane_intersect(P(A), P(nA), P(B), P(nB), point3d &P, point3d &Q) { point3d n = nA * nB; if (n.isZero()) return false; point3d v = n * nA; P = A + (n * nA) * ((B - A) % nB / (v % nB)); Q = P + n; return true; } // vim: cc=60 ts=2 sts=2 sw=2: <|endoftext|>
<commit_before>#include "dg/analysis/PointsTo/Pointer.h" #include "dg/analysis/PointsTo/PSNode.h" #ifndef NDEBUG #include <iostream> namespace dg { namespace analysis { namespace pta { void Pointer::dump() const { target->dump(); std::cout << " + "; offset.dump(); } void Pointer::print() const { dump(); std::cout << "\n"; } #endif // not NDEBUG } // namespace pta } // namespace analysis } // namespace dg <commit_msg>fix release build<commit_after>#include "dg/analysis/PointsTo/Pointer.h" #include "dg/analysis/PointsTo/PSNode.h" #ifndef NDEBUG #include <iostream> namespace dg { namespace analysis { namespace pta { void Pointer::dump() const { target->dump(); std::cout << " + "; offset.dump(); } void Pointer::print() const { dump(); std::cout << "\n"; } } // namespace pta } // namespace analysis } // namespace dg #endif // not NDEBUG <|endoftext|>
<commit_before>#include <stdio.h> #include <cmath> #include <stdlib.h> #include <stdbool.h> #include <signal.h> #include <unistd.h> #include <assert.h> #include <math.h> #include <poll.h> #include <sys/mman.h> #include "common/util.h" #include "common/swaglog.h" #include "common/visionimg.h" #include "common/utilpp.h" #include "ui.hpp" #include "paint.hpp" extern volatile sig_atomic_t do_exit; int write_param_float(float param, const char* param_name, bool persistent_param) { char s[16]; int size = snprintf(s, sizeof(s), "%f", param); return Params(persistent_param).write_db_value(param_name, s, size < sizeof(s) ? size : sizeof(s)); } void ui_init(UIState *s) { s->sm = new SubMaster({"modelV2", "controlsState", "uiLayoutState", "liveCalibration", "radarState", "thermal", "frame", "health", "carParams", "ubloxGnss", "driverState", "dMonitoringState", "sensorEvents"}); s->started = false; s->status = STATUS_OFFROAD; s->scene.satelliteCount = -1; read_param(&s->is_metric, "IsMetric"); s->fb = framebuffer_init("ui", 0, true, &s->fb_w, &s->fb_h); assert(s->fb); ui_nvg_init(s); } static void ui_init_vision(UIState *s) { // Invisible until we receive a calibration message. s->scene.world_objects_visible = false; for (int i = 0; i < UI_BUF_COUNT; i++) { if (s->khr[i] != 0) { visionimg_destroy_gl(s->khr[i], s->priv_hnds[i]); glDeleteTextures(1, &s->frame_texs[i]); } VisionImg img = { .fd = s->stream.bufs[i].fd, .format = VISIONIMG_FORMAT_RGB24, .width = s->stream.bufs_info.width, .height = s->stream.bufs_info.height, .stride = s->stream.bufs_info.stride, .bpp = 3, .size = s->stream.bufs_info.buf_len, }; #ifndef QCOM s->priv_hnds[i] = s->stream.bufs[i].addr; #endif s->frame_texs[i] = visionimg_to_gl(&img, &s->khr[i], &s->priv_hnds[i]); glBindTexture(GL_TEXTURE_2D, s->frame_texs[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // BGR glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); } assert(glGetError() == GL_NO_ERROR); } void ui_update_vision(UIState *s) { if (!s->vision_connected && s->started) { const VisionStreamType type = s->scene.frontview ? VISION_STREAM_RGB_FRONT : VISION_STREAM_RGB_BACK; int err = visionstream_init(&s->stream, type, true, nullptr); if (err == 0) { ui_init_vision(s); s->vision_connected = true; } } if (s->vision_connected) { if (!s->started) goto destroy; // poll for a new frame struct pollfd fds[1] = {{ .fd = s->stream.ipc_fd, .events = POLLOUT, }}; int ret = poll(fds, 1, 100); if (ret > 0) { if (!visionstream_get(&s->stream, nullptr)) goto destroy; } } return; destroy: visionstream_destroy(&s->stream); s->vision_connected = false; } void update_sockets(UIState *s) { UIScene &scene = s->scene; SubMaster &sm = *(s->sm); if (sm.update(0) == 0){ return; } if (s->started && sm.updated("controlsState")) { auto event = sm["controlsState"]; scene.controls_state = event.getControlsState(); // TODO: the alert stuff shouldn't be handled here auto alert_sound = scene.controls_state.getAlertSound(); if (scene.alert_type.compare(scene.controls_state.getAlertType()) != 0) { if (alert_sound == AudibleAlert::NONE) { s->sound->stop(); } else { s->sound->play(alert_sound); } } scene.alert_text1 = scene.controls_state.getAlertText1(); scene.alert_text2 = scene.controls_state.getAlertText2(); scene.alert_size = scene.controls_state.getAlertSize(); scene.alert_type = scene.controls_state.getAlertType(); auto alertStatus = scene.controls_state.getAlertStatus(); if (alertStatus == cereal::ControlsState::AlertStatus::USER_PROMPT) { s->status = STATUS_WARNING; } else if (alertStatus == cereal::ControlsState::AlertStatus::CRITICAL) { s->status = STATUS_ALERT; } else { s->status = scene.controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; } float alert_blinkingrate = scene.controls_state.getAlertBlinkingRate(); if (alert_blinkingrate > 0.) { if (s->alert_blinked) { if (s->alert_blinking_alpha > 0.0 && s->alert_blinking_alpha < 1.0) { s->alert_blinking_alpha += (0.05*alert_blinkingrate); } else { s->alert_blinked = false; } } else { if (s->alert_blinking_alpha > 0.25) { s->alert_blinking_alpha -= (0.05*alert_blinkingrate); } else { s->alert_blinking_alpha += 0.25; s->alert_blinked = true; } } } } if (sm.updated("radarState")) { auto data = sm["radarState"].getRadarState(); scene.lead_data[0] = data.getLeadOne(); scene.lead_data[1] = data.getLeadTwo(); } if (sm.updated("liveCalibration")) { scene.world_objects_visible = true; auto extrinsicl = sm["liveCalibration"].getLiveCalibration().getExtrinsicMatrix(); for (int i = 0; i < 3 * 4; i++) { scene.extrinsic_matrix.v[i] = extrinsicl[i]; } } if (sm.updated("modelV2")) { scene.model = sm["modelV2"].getModelV2(); scene.max_distance = fmin(scene.model.getPosition().getX()[TRAJECTORY_SIZE - 1], MAX_DRAW_DISTANCE); for (int ll_idx = 0; ll_idx < 4; ll_idx++) { if (scene.model.getLaneLineProbs().size() > ll_idx) { scene.lane_line_probs[ll_idx] = scene.model.getLaneLineProbs()[ll_idx]; } else { scene.lane_line_probs[ll_idx] = 0.0; } } for (int re_idx = 0; re_idx < 2; re_idx++) { if (scene.model.getRoadEdgeStds().size() > re_idx) { scene.road_edge_stds[re_idx] = scene.model.getRoadEdgeStds()[re_idx]; } else { scene.road_edge_stds[re_idx] = 1.0; } } } if (sm.updated("uiLayoutState")) { auto data = sm["uiLayoutState"].getUiLayoutState(); s->active_app = data.getActiveApp(); scene.uilayout_sidebarcollapsed = data.getSidebarCollapsed(); } if (sm.updated("thermal")) { scene.thermal = sm["thermal"].getThermal(); } if (sm.updated("ubloxGnss")) { auto data = sm["ubloxGnss"].getUbloxGnss(); if (data.which() == cereal::UbloxGnss::MEASUREMENT_REPORT) { scene.satelliteCount = data.getMeasurementReport().getNumMeas(); } } if (sm.updated("health")) { auto health = sm["health"].getHealth(); scene.hwType = health.getHwType(); s->ignition = health.getIgnitionLine() || health.getIgnitionCan(); } else if ((s->sm->frame - s->sm->rcv_frame("health")) > 5*UI_FREQ) { scene.hwType = cereal::HealthData::HwType::UNKNOWN; } if (sm.updated("carParams")) { s->longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); } if (sm.updated("driverState")) { scene.driver_state = sm["driverState"].getDriverState(); } if (sm.updated("dMonitoringState")) { scene.dmonitoring_state = sm["dMonitoringState"].getDMonitoringState(); scene.is_rhd = scene.dmonitoring_state.getIsRHD(); scene.frontview = scene.dmonitoring_state.getIsPreview(); } else if ((sm.frame - sm.rcv_frame("dMonitoringState")) > UI_FREQ/2) { scene.frontview = false; } if (sm.updated("sensorEvents")) { for (auto sensor : sm["sensorEvents"].getSensorEvents()) { if (sensor.which() == cereal::SensorEventData::LIGHT) { s->light_sensor = sensor.getLight(); } else if (!s->started && sensor.which() == cereal::SensorEventData::ACCELERATION) { s->accel_sensor = sensor.getAcceleration().getV()[2]; } else if (!s->started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) { s->gyro_sensor = sensor.getGyroUncalibrated().getV()[1]; } } } s->started = scene.thermal.getStarted() || scene.frontview; } void ui_update(UIState *s) { update_sockets(s); ui_update_vision(s); // Handle onroad/offroad transition if (!s->started && s->status != STATUS_OFFROAD) { s->status = STATUS_OFFROAD; s->active_app = cereal::UiLayoutState::App::HOME; s->scene.uilayout_sidebarcollapsed = false; s->sound->stop(); } else if (s->started && s->status == STATUS_OFFROAD) { s->status = STATUS_DISENGAGED; s->started_frame = s->sm->frame; s->active_app = cereal::UiLayoutState::App::NONE; s->scene.uilayout_sidebarcollapsed = true; s->alert_blinked = false; s->alert_blinking_alpha = 1.0; s->scene.alert_size = cereal::ControlsState::AlertSize::NONE; } // Handle controls/fcamera timeout if (s->started && !s->scene.frontview && ((s->sm)->frame - s->started_frame) > 5*UI_FREQ) { if ((s->sm)->rcv_frame("controlsState") < s->started_frame) { // car is started, but controlsState hasn't been seen at all s->scene.alert_text1 = "openpilot Unavailable"; s->scene.alert_text2 = "Waiting for controls to start"; s->scene.alert_size = cereal::ControlsState::AlertSize::MID; } else if (((s->sm)->frame - (s->sm)->rcv_frame("controlsState")) > 5*UI_FREQ) { // car is started, but controls is lagging or died if (s->scene.alert_text2 != "Controls Unresponsive" && s->scene.alert_text1 != "Camera Malfunction") { s->sound->play(AudibleAlert::CHIME_WARNING_REPEAT); LOGE("Controls unresponsive"); } s->scene.alert_text1 = "TAKE CONTROL IMMEDIATELY"; s->scene.alert_text2 = "Controls Unresponsive"; s->scene.alert_size = cereal::ControlsState::AlertSize::FULL; s->status = STATUS_ALERT; } const uint64_t frame_pkt = (s->sm)->rcv_frame("frame"); const uint64_t frame_delayed = (s->sm)->frame - frame_pkt; if ((frame_pkt > s->started_frame && frame_delayed > 5 * UI_FREQ) || frame_delayed > 35 * UI_FREQ) { // controls is fine, but rear camera is lagging or died s->scene.alert_text1 = "Camera Malfunction"; s->scene.alert_text2 = "Contact Support"; s->scene.alert_size = cereal::ControlsState::AlertSize::FULL; s->status = STATUS_DISENGAGED; s->sound->stop(); } } // Read params if ((s->sm)->frame % (5*UI_FREQ) == 0) { read_param(&s->is_metric, "IsMetric"); } else if ((s->sm)->frame % (6*UI_FREQ) == 0) { int param_read = read_param(&s->last_athena_ping, "LastAthenaPingTime"); if (param_read != 0) { // Failed to read param s->scene.athenaStatus = NET_DISCONNECTED; } else if (nanos_since_boot() - s->last_athena_ping < 70e9) { s->scene.athenaStatus = NET_CONNECTED; } else { s->scene.athenaStatus = NET_ERROR; } } } <commit_msg>fix camera malfunction ui timeout<commit_after>#include <stdio.h> #include <cmath> #include <stdlib.h> #include <stdbool.h> #include <signal.h> #include <unistd.h> #include <assert.h> #include <math.h> #include <poll.h> #include <sys/mman.h> #include "common/util.h" #include "common/swaglog.h" #include "common/visionimg.h" #include "common/utilpp.h" #include "ui.hpp" #include "paint.hpp" extern volatile sig_atomic_t do_exit; int write_param_float(float param, const char* param_name, bool persistent_param) { char s[16]; int size = snprintf(s, sizeof(s), "%f", param); return Params(persistent_param).write_db_value(param_name, s, size < sizeof(s) ? size : sizeof(s)); } void ui_init(UIState *s) { s->sm = new SubMaster({"modelV2", "controlsState", "uiLayoutState", "liveCalibration", "radarState", "thermal", "frame", "health", "carParams", "ubloxGnss", "driverState", "dMonitoringState", "sensorEvents"}); s->started = false; s->status = STATUS_OFFROAD; s->scene.satelliteCount = -1; read_param(&s->is_metric, "IsMetric"); s->fb = framebuffer_init("ui", 0, true, &s->fb_w, &s->fb_h); assert(s->fb); ui_nvg_init(s); } static void ui_init_vision(UIState *s) { // Invisible until we receive a calibration message. s->scene.world_objects_visible = false; for (int i = 0; i < UI_BUF_COUNT; i++) { if (s->khr[i] != 0) { visionimg_destroy_gl(s->khr[i], s->priv_hnds[i]); glDeleteTextures(1, &s->frame_texs[i]); } VisionImg img = { .fd = s->stream.bufs[i].fd, .format = VISIONIMG_FORMAT_RGB24, .width = s->stream.bufs_info.width, .height = s->stream.bufs_info.height, .stride = s->stream.bufs_info.stride, .bpp = 3, .size = s->stream.bufs_info.buf_len, }; #ifndef QCOM s->priv_hnds[i] = s->stream.bufs[i].addr; #endif s->frame_texs[i] = visionimg_to_gl(&img, &s->khr[i], &s->priv_hnds[i]); glBindTexture(GL_TEXTURE_2D, s->frame_texs[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // BGR glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); } assert(glGetError() == GL_NO_ERROR); } void ui_update_vision(UIState *s) { if (!s->vision_connected && s->started) { const VisionStreamType type = s->scene.frontview ? VISION_STREAM_RGB_FRONT : VISION_STREAM_RGB_BACK; int err = visionstream_init(&s->stream, type, true, nullptr); if (err == 0) { ui_init_vision(s); s->vision_connected = true; } } if (s->vision_connected) { if (!s->started) goto destroy; // poll for a new frame struct pollfd fds[1] = {{ .fd = s->stream.ipc_fd, .events = POLLOUT, }}; int ret = poll(fds, 1, 100); if (ret > 0) { if (!visionstream_get(&s->stream, nullptr)) goto destroy; } } return; destroy: visionstream_destroy(&s->stream); s->vision_connected = false; } void update_sockets(UIState *s) { UIScene &scene = s->scene; SubMaster &sm = *(s->sm); if (sm.update(0) == 0){ return; } if (s->started && sm.updated("controlsState")) { auto event = sm["controlsState"]; scene.controls_state = event.getControlsState(); // TODO: the alert stuff shouldn't be handled here auto alert_sound = scene.controls_state.getAlertSound(); if (scene.alert_type.compare(scene.controls_state.getAlertType()) != 0) { if (alert_sound == AudibleAlert::NONE) { s->sound->stop(); } else { s->sound->play(alert_sound); } } scene.alert_text1 = scene.controls_state.getAlertText1(); scene.alert_text2 = scene.controls_state.getAlertText2(); scene.alert_size = scene.controls_state.getAlertSize(); scene.alert_type = scene.controls_state.getAlertType(); auto alertStatus = scene.controls_state.getAlertStatus(); if (alertStatus == cereal::ControlsState::AlertStatus::USER_PROMPT) { s->status = STATUS_WARNING; } else if (alertStatus == cereal::ControlsState::AlertStatus::CRITICAL) { s->status = STATUS_ALERT; } else { s->status = scene.controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; } float alert_blinkingrate = scene.controls_state.getAlertBlinkingRate(); if (alert_blinkingrate > 0.) { if (s->alert_blinked) { if (s->alert_blinking_alpha > 0.0 && s->alert_blinking_alpha < 1.0) { s->alert_blinking_alpha += (0.05*alert_blinkingrate); } else { s->alert_blinked = false; } } else { if (s->alert_blinking_alpha > 0.25) { s->alert_blinking_alpha -= (0.05*alert_blinkingrate); } else { s->alert_blinking_alpha += 0.25; s->alert_blinked = true; } } } } if (sm.updated("radarState")) { auto data = sm["radarState"].getRadarState(); scene.lead_data[0] = data.getLeadOne(); scene.lead_data[1] = data.getLeadTwo(); } if (sm.updated("liveCalibration")) { scene.world_objects_visible = true; auto extrinsicl = sm["liveCalibration"].getLiveCalibration().getExtrinsicMatrix(); for (int i = 0; i < 3 * 4; i++) { scene.extrinsic_matrix.v[i] = extrinsicl[i]; } } if (sm.updated("modelV2")) { scene.model = sm["modelV2"].getModelV2(); scene.max_distance = fmin(scene.model.getPosition().getX()[TRAJECTORY_SIZE - 1], MAX_DRAW_DISTANCE); for (int ll_idx = 0; ll_idx < 4; ll_idx++) { if (scene.model.getLaneLineProbs().size() > ll_idx) { scene.lane_line_probs[ll_idx] = scene.model.getLaneLineProbs()[ll_idx]; } else { scene.lane_line_probs[ll_idx] = 0.0; } } for (int re_idx = 0; re_idx < 2; re_idx++) { if (scene.model.getRoadEdgeStds().size() > re_idx) { scene.road_edge_stds[re_idx] = scene.model.getRoadEdgeStds()[re_idx]; } else { scene.road_edge_stds[re_idx] = 1.0; } } } if (sm.updated("uiLayoutState")) { auto data = sm["uiLayoutState"].getUiLayoutState(); s->active_app = data.getActiveApp(); scene.uilayout_sidebarcollapsed = data.getSidebarCollapsed(); } if (sm.updated("thermal")) { scene.thermal = sm["thermal"].getThermal(); } if (sm.updated("ubloxGnss")) { auto data = sm["ubloxGnss"].getUbloxGnss(); if (data.which() == cereal::UbloxGnss::MEASUREMENT_REPORT) { scene.satelliteCount = data.getMeasurementReport().getNumMeas(); } } if (sm.updated("health")) { auto health = sm["health"].getHealth(); scene.hwType = health.getHwType(); s->ignition = health.getIgnitionLine() || health.getIgnitionCan(); } else if ((s->sm->frame - s->sm->rcv_frame("health")) > 5*UI_FREQ) { scene.hwType = cereal::HealthData::HwType::UNKNOWN; } if (sm.updated("carParams")) { s->longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); } if (sm.updated("driverState")) { scene.driver_state = sm["driverState"].getDriverState(); } if (sm.updated("dMonitoringState")) { scene.dmonitoring_state = sm["dMonitoringState"].getDMonitoringState(); scene.is_rhd = scene.dmonitoring_state.getIsRHD(); scene.frontview = scene.dmonitoring_state.getIsPreview(); } else if ((sm.frame - sm.rcv_frame("dMonitoringState")) > UI_FREQ/2) { scene.frontview = false; } if (sm.updated("sensorEvents")) { for (auto sensor : sm["sensorEvents"].getSensorEvents()) { if (sensor.which() == cereal::SensorEventData::LIGHT) { s->light_sensor = sensor.getLight(); } else if (!s->started && sensor.which() == cereal::SensorEventData::ACCELERATION) { s->accel_sensor = sensor.getAcceleration().getV()[2]; } else if (!s->started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) { s->gyro_sensor = sensor.getGyroUncalibrated().getV()[1]; } } } s->started = scene.thermal.getStarted() || scene.frontview; } void ui_update(UIState *s) { update_sockets(s); ui_update_vision(s); // Handle onroad/offroad transition if (!s->started && s->status != STATUS_OFFROAD) { s->status = STATUS_OFFROAD; s->active_app = cereal::UiLayoutState::App::HOME; s->scene.uilayout_sidebarcollapsed = false; s->sound->stop(); } else if (s->started && s->status == STATUS_OFFROAD) { s->status = STATUS_DISENGAGED; s->started_frame = s->sm->frame; s->active_app = cereal::UiLayoutState::App::NONE; s->scene.uilayout_sidebarcollapsed = true; s->alert_blinked = false; s->alert_blinking_alpha = 1.0; s->scene.alert_size = cereal::ControlsState::AlertSize::NONE; } // Handle controls/fcamera timeout if (s->started && !s->scene.frontview && ((s->sm)->frame - s->started_frame) > 5*UI_FREQ) { if ((s->sm)->rcv_frame("controlsState") < s->started_frame) { // car is started, but controlsState hasn't been seen at all s->scene.alert_text1 = "openpilot Unavailable"; s->scene.alert_text2 = "Waiting for controls to start"; s->scene.alert_size = cereal::ControlsState::AlertSize::MID; } else if (((s->sm)->frame - (s->sm)->rcv_frame("controlsState")) > 5*UI_FREQ) { // car is started, but controls is lagging or died if (s->scene.alert_text2 != "Controls Unresponsive" && s->scene.alert_text1 != "Camera Malfunction") { s->sound->play(AudibleAlert::CHIME_WARNING_REPEAT); LOGE("Controls unresponsive"); } s->scene.alert_text1 = "TAKE CONTROL IMMEDIATELY"; s->scene.alert_text2 = "Controls Unresponsive"; s->scene.alert_size = cereal::ControlsState::AlertSize::FULL; s->status = STATUS_ALERT; } const uint64_t frame_pkt = (s->sm)->rcv_frame("frame"); const uint64_t frame_delayed = (s->sm)->frame - frame_pkt; const uint64_t since_started = (s->sm)->frame - s->started_frame; if ((frame_pkt > s->started_frame || since_started > 15*UI_FREQ) && frame_delayed > 5*UI_FREQ) { // controls is fine, but rear camera is lagging or died s->scene.alert_text1 = "Camera Malfunction"; s->scene.alert_text2 = "Contact Support"; s->scene.alert_size = cereal::ControlsState::AlertSize::FULL; s->status = STATUS_DISENGAGED; s->sound->stop(); } } // Read params if ((s->sm)->frame % (5*UI_FREQ) == 0) { read_param(&s->is_metric, "IsMetric"); } else if ((s->sm)->frame % (6*UI_FREQ) == 0) { int param_read = read_param(&s->last_athena_ping, "LastAthenaPingTime"); if (param_read != 0) { // Failed to read param s->scene.athenaStatus = NET_DISCONNECTED; } else if (nanos_since_boot() - s->last_athena_ping < 70e9) { s->scene.athenaStatus = NET_CONNECTED; } else { s->scene.athenaStatus = NET_ERROR; } } } <|endoftext|>
<commit_before>#include "RhoFromPressureTemperatureIC.h" #include "SinglePhaseFluidProperties.h" template <> InputParameters validParams<RhoFromPressureTemperatureIC>() { InputParameters params = validParams<InitialCondition>(); params.addRequiredParam<UserObjectName>("fp", "The name of fluid properties user object."); params.addRequiredCoupledVar("p", "The pressure"); params.addRequiredCoupledVar("T", "The temperature"); return params; } RhoFromPressureTemperatureIC::RhoFromPressureTemperatureIC(const InputParameters & parameters) : InitialCondition(parameters), _spfp(getUserObject<SinglePhaseFluidProperties>("fp")), _p(coupledValue("p")), _T(coupledValue("T")) { } Real RhoFromPressureTemperatureIC::value(const Point & /*p*/) { return _spfp.rho(_p[_qp], _T[_qp]); } <commit_msg>Updated fluid property calls to new interfaces<commit_after>#include "RhoFromPressureTemperatureIC.h" #include "SinglePhaseFluidProperties.h" template <> InputParameters validParams<RhoFromPressureTemperatureIC>() { InputParameters params = validParams<InitialCondition>(); params.addRequiredParam<UserObjectName>("fp", "The name of fluid properties user object."); params.addRequiredCoupledVar("p", "The pressure"); params.addRequiredCoupledVar("T", "The temperature"); return params; } RhoFromPressureTemperatureIC::RhoFromPressureTemperatureIC(const InputParameters & parameters) : InitialCondition(parameters), _spfp(getUserObject<SinglePhaseFluidProperties>("fp")), _p(coupledValue("p")), _T(coupledValue("T")) { } Real RhoFromPressureTemperatureIC::value(const Point & /*p*/) { return _spfp.rho_from_p_T(_p[_qp], _T[_qp]); } <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIOgreRenderer.cpp created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUIOgreRenderer.h" #include "CEGUIOgreGeometryBuffer.h" #include "CEGUIOgreTextureTarget.h" #include "CEGUIOgreTexture.h" #include "CEGUIOgreWindowTarget.h" #include "CEGUIRenderingRoot.h" #include "CEGUIExceptions.h" #include "CEGUISystem.h" #include "CEGUIOgreResourceProvider.h" #include "CEGUIOgreImageCodec.h" #include <OgreRoot.h> #include <OgreRenderSystem.h> #include <OgreRenderWindow.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // Internal Ogre::FrameListener based class. This is how we noew hook into the // rendering process (as opposed to render queues previously) static class OgreGUIFrameListener : public Ogre::FrameListener { public: OgreGUIFrameListener(); void setCEGUIRenderEnabled(bool enabled); bool isCEGUIRenderEnabled() const; bool frameRenderingQueued(const Ogre::FrameEvent& evt); private: bool d_enabled; } S_frameListener; //----------------------------------------------------------------------------// String OgreRenderer::d_rendererID( "CEGUI::OgreRenderer - Official OGRE based 2nd generation renderer module."); //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::bootstrapSystem() { if (System::getSingletonPtr()) throw InvalidRequestException("OgreRenderer::bootstrapSystem: " "CEGUI::System object is already initialised."); OgreRenderer& renderer = create(); OgreResourceProvider& rp = createOgreResourceProvider(); OgreImageCodec& ic = createOgreImageCodec(); System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic); return renderer; } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::bootstrapSystem(Ogre::RenderTarget& target) { if (System::getSingletonPtr()) throw InvalidRequestException("OgreRenderer::bootstrapSystem: " "CEGUI::System object is already initialised."); OgreRenderer& renderer = OgreRenderer::create(target); OgreResourceProvider& rp = createOgreResourceProvider(); OgreImageCodec& ic = createOgreImageCodec(); System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic); return renderer; } //----------------------------------------------------------------------------// void OgreRenderer::destroySystem() { System* sys; if (!(sys = System::getSingletonPtr())) throw InvalidRequestException("OgreRenderer::destroySystem: " "CEGUI::System object is not created or was already destroyed."); OgreRenderer* renderer = static_cast<OgreRenderer*>(sys->getRenderer()); OgreResourceProvider* rp = static_cast<OgreResourceProvider*>(sys->getResourceProvider()); OgreImageCodec* ic = &static_cast<OgreImageCodec&>(sys->getImageCodec()); System::destroy(); destroyOgreImageCodec(*ic); destroyOgreResourceProvider(*rp); destroy(*renderer); } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::create() { return *new OgreRenderer; } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::create(Ogre::RenderTarget& target) { return *new OgreRenderer(target); } //----------------------------------------------------------------------------// void OgreRenderer::destroy(OgreRenderer& renderer) { delete &renderer; } //----------------------------------------------------------------------------// OgreResourceProvider& OgreRenderer::createOgreResourceProvider() { return *new OgreResourceProvider; } //----------------------------------------------------------------------------// void OgreRenderer::destroyOgreResourceProvider(OgreResourceProvider& rp) { delete &rp; } //----------------------------------------------------------------------------// OgreImageCodec& OgreRenderer::createOgreImageCodec() { return *new OgreImageCodec; } //----------------------------------------------------------------------------// void OgreRenderer::destroyOgreImageCodec(OgreImageCodec& ic) { delete &ic; } //----------------------------------------------------------------------------// void OgreRenderer::setRenderingEnabled(const bool enabled) { S_frameListener.setCEGUIRenderEnabled(enabled); } //----------------------------------------------------------------------------// bool OgreRenderer::isRenderingEnabled() const { return S_frameListener.isCEGUIRenderEnabled(); } //----------------------------------------------------------------------------// RenderingRoot& OgreRenderer::getDefaultRenderingRoot() { return *d_defaultRoot; } //----------------------------------------------------------------------------// GeometryBuffer& OgreRenderer::createGeometryBuffer() { OgreGeometryBuffer* gb = new OgreGeometryBuffer(*d_renderSystem); d_geometryBuffers.push_back(gb); return *gb; } //----------------------------------------------------------------------------// void OgreRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer) { GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), d_geometryBuffers.end(), &buffer); if (d_geometryBuffers.end() != i) { d_geometryBuffers.erase(i); delete &buffer; } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllGeometryBuffers() { while (!d_geometryBuffers.empty()) destroyGeometryBuffer(**d_geometryBuffers.begin()); } //----------------------------------------------------------------------------// TextureTarget* OgreRenderer::createTextureTarget() { TextureTarget* tt = new OgreTextureTarget(*this, *d_renderSystem); d_textureTargets.push_back(tt); return tt; } //----------------------------------------------------------------------------// void OgreRenderer::destroyTextureTarget(TextureTarget* target) { TextureTargetList::iterator i = std::find(d_textureTargets.begin(), d_textureTargets.end(), target); if (d_textureTargets.end() != i) { d_textureTargets.erase(i); delete target; } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllTextureTargets() { while (!d_textureTargets.empty()) destroyTextureTarget(*d_textureTargets.begin()); } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture() { OgreTexture* t = new OgreTexture; d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(const String& filename, const String& resourceGroup) { OgreTexture* t = new OgreTexture(filename, resourceGroup); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(const Size& size) { OgreTexture* t = new OgreTexture(size); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(Ogre::TexturePtr& tex, bool take_ownership) { OgreTexture* t = new OgreTexture(tex, take_ownership); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// void OgreRenderer::destroyTexture(Texture& texture) { TextureList::iterator i = std::find(d_textures.begin(), d_textures.end(), &texture); if (d_textures.end() != i) { d_textures.erase(i); delete &static_cast<OgreTexture&>(texture); } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllTextures() { while (!d_textures.empty()) destroyTexture(**d_textures.begin()); } //----------------------------------------------------------------------------// void OgreRenderer::beginRendering() { using namespace Ogre; // initialise render settings d_renderSystem->setLightingEnabled(false); d_renderSystem->_setDepthBufferParams(false, false); d_renderSystem->_setDepthBias(0, 0); d_renderSystem->_setCullingMode(CULL_NONE); d_renderSystem->_setFog(FOG_NONE); d_renderSystem->_setColourBufferWriteEnabled(true, true, true, true); d_renderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM); d_renderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM); d_renderSystem->setShadingType(SO_GOURAUD); d_renderSystem->_setPolygonMode(PM_SOLID); // enable alpha blending d_renderSystem->_setSceneBlending(SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA); d_renderSystem->_beginFrame(); } //----------------------------------------------------------------------------// void OgreRenderer::endRendering() { d_renderSystem->_endFrame(); } //----------------------------------------------------------------------------// const Size& OgreRenderer::getDisplaySize() const { return d_displaySize; } //----------------------------------------------------------------------------// const Vector2& OgreRenderer::getDisplayDPI() const { return d_displayDPI; } //----------------------------------------------------------------------------// uint OgreRenderer::getMaxTextureSize() const { return d_maxTextureSize; } //----------------------------------------------------------------------------// const String& OgreRenderer::getIdentifierString() const { return d_rendererID; } //----------------------------------------------------------------------------// OgreRenderer::OgreRenderer() : d_displayDPI(96, 96), // TODO: should be set to correct value d_maxTextureSize(2048), d_ogreRoot(Ogre::Root::getSingletonPtr()) { checkOgreInitialised(); // get auto created window Ogre::RenderWindow* rwnd = d_ogreRoot->getAutoCreatedWindow(); if (!rwnd) throw RendererException("Ogre was not initialised to automatically " "create a window, you should therefore be " "explicitly specifying a Ogre::RenderTarget in " "the OgreRenderer::create function."); constructor_impl(*rwnd); } //----------------------------------------------------------------------------// OgreRenderer::OgreRenderer(Ogre::RenderTarget& target) : d_displayDPI(96, 96), // TODO: should be set to correct value d_maxTextureSize(2048), d_ogreRoot(Ogre::Root::getSingletonPtr()) { checkOgreInitialised(); constructor_impl(target); } //----------------------------------------------------------------------------// OgreRenderer::~OgreRenderer() { d_ogreRoot->removeFrameListener(&S_frameListener); destroyAllGeometryBuffers(); destroyAllTextureTargets(); destroyAllTextures(); delete d_defaultRoot; delete d_defaultTarget; } //----------------------------------------------------------------------------// void OgreRenderer::checkOgreInitialised() { if (!d_ogreRoot) throw RendererException("The Ogre::Root object has not been created. " "You must initialise Ogre first!"); if (!d_ogreRoot->isInitialised()) throw RendererException("Ogre has not been initialised. You must " "initialise Ogre first!"); } //----------------------------------------------------------------------------// void OgreRenderer::constructor_impl(Ogre::RenderTarget& target) { d_renderSystem = d_ogreRoot->getRenderSystem(); d_displaySize.d_width = target.getWidth(); d_displaySize.d_height = target.getHeight(); // create default target & rendering root (surface) that uses it d_defaultTarget = new OgreWindowTarget(*this, *d_renderSystem, target); d_defaultRoot = new RenderingRoot(*d_defaultTarget); // hook into the rendering process d_ogreRoot->addFrameListener(&S_frameListener); } //----------------------------------------------------------------------------// void OgreRenderer::setDisplaySize(const Size& sz) { if (sz != d_displaySize) { d_displaySize = sz; // FIXME: This is probably not the right thing to do in all cases. Rect area(d_defaultTarget->getArea()); area.setSize(sz); d_defaultTarget->setArea(area); } } //----------------------------------------------------------------------------// OgreGUIFrameListener::OgreGUIFrameListener() : d_enabled(true) { } //----------------------------------------------------------------------------// void OgreGUIFrameListener::setCEGUIRenderEnabled(bool enabled) { d_enabled = enabled; } //----------------------------------------------------------------------------// bool OgreGUIFrameListener::isCEGUIRenderEnabled() const { return d_enabled; } //----------------------------------------------------------------------------// bool OgreGUIFrameListener::frameRenderingQueued(const Ogre::FrameEvent&) { if (d_enabled) System::getSingleton().renderGUI(); return true; } } // End of CEGUI namespace section <commit_msg>FIX: Alpha blend issue for the Ogre renderer.<commit_after>/*********************************************************************** filename: CEGUIOgreRenderer.cpp created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUIOgreRenderer.h" #include "CEGUIOgreGeometryBuffer.h" #include "CEGUIOgreTextureTarget.h" #include "CEGUIOgreTexture.h" #include "CEGUIOgreWindowTarget.h" #include "CEGUIRenderingRoot.h" #include "CEGUIExceptions.h" #include "CEGUISystem.h" #include "CEGUIOgreResourceProvider.h" #include "CEGUIOgreImageCodec.h" #include <OgreRoot.h> #include <OgreRenderSystem.h> #include <OgreRenderWindow.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // Internal Ogre::FrameListener based class. This is how we noew hook into the // rendering process (as opposed to render queues previously) static class OgreGUIFrameListener : public Ogre::FrameListener { public: OgreGUIFrameListener(); void setCEGUIRenderEnabled(bool enabled); bool isCEGUIRenderEnabled() const; bool frameRenderingQueued(const Ogre::FrameEvent& evt); private: bool d_enabled; } S_frameListener; //----------------------------------------------------------------------------// String OgreRenderer::d_rendererID( "CEGUI::OgreRenderer - Official OGRE based 2nd generation renderer module."); //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::bootstrapSystem() { if (System::getSingletonPtr()) throw InvalidRequestException("OgreRenderer::bootstrapSystem: " "CEGUI::System object is already initialised."); OgreRenderer& renderer = create(); OgreResourceProvider& rp = createOgreResourceProvider(); OgreImageCodec& ic = createOgreImageCodec(); System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic); return renderer; } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::bootstrapSystem(Ogre::RenderTarget& target) { if (System::getSingletonPtr()) throw InvalidRequestException("OgreRenderer::bootstrapSystem: " "CEGUI::System object is already initialised."); OgreRenderer& renderer = OgreRenderer::create(target); OgreResourceProvider& rp = createOgreResourceProvider(); OgreImageCodec& ic = createOgreImageCodec(); System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic); return renderer; } //----------------------------------------------------------------------------// void OgreRenderer::destroySystem() { System* sys; if (!(sys = System::getSingletonPtr())) throw InvalidRequestException("OgreRenderer::destroySystem: " "CEGUI::System object is not created or was already destroyed."); OgreRenderer* renderer = static_cast<OgreRenderer*>(sys->getRenderer()); OgreResourceProvider* rp = static_cast<OgreResourceProvider*>(sys->getResourceProvider()); OgreImageCodec* ic = &static_cast<OgreImageCodec&>(sys->getImageCodec()); System::destroy(); destroyOgreImageCodec(*ic); destroyOgreResourceProvider(*rp); destroy(*renderer); } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::create() { return *new OgreRenderer; } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::create(Ogre::RenderTarget& target) { return *new OgreRenderer(target); } //----------------------------------------------------------------------------// void OgreRenderer::destroy(OgreRenderer& renderer) { delete &renderer; } //----------------------------------------------------------------------------// OgreResourceProvider& OgreRenderer::createOgreResourceProvider() { return *new OgreResourceProvider; } //----------------------------------------------------------------------------// void OgreRenderer::destroyOgreResourceProvider(OgreResourceProvider& rp) { delete &rp; } //----------------------------------------------------------------------------// OgreImageCodec& OgreRenderer::createOgreImageCodec() { return *new OgreImageCodec; } //----------------------------------------------------------------------------// void OgreRenderer::destroyOgreImageCodec(OgreImageCodec& ic) { delete &ic; } //----------------------------------------------------------------------------// void OgreRenderer::setRenderingEnabled(const bool enabled) { S_frameListener.setCEGUIRenderEnabled(enabled); } //----------------------------------------------------------------------------// bool OgreRenderer::isRenderingEnabled() const { return S_frameListener.isCEGUIRenderEnabled(); } //----------------------------------------------------------------------------// RenderingRoot& OgreRenderer::getDefaultRenderingRoot() { return *d_defaultRoot; } //----------------------------------------------------------------------------// GeometryBuffer& OgreRenderer::createGeometryBuffer() { OgreGeometryBuffer* gb = new OgreGeometryBuffer(*d_renderSystem); d_geometryBuffers.push_back(gb); return *gb; } //----------------------------------------------------------------------------// void OgreRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer) { GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), d_geometryBuffers.end(), &buffer); if (d_geometryBuffers.end() != i) { d_geometryBuffers.erase(i); delete &buffer; } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllGeometryBuffers() { while (!d_geometryBuffers.empty()) destroyGeometryBuffer(**d_geometryBuffers.begin()); } //----------------------------------------------------------------------------// TextureTarget* OgreRenderer::createTextureTarget() { TextureTarget* tt = new OgreTextureTarget(*this, *d_renderSystem); d_textureTargets.push_back(tt); return tt; } //----------------------------------------------------------------------------// void OgreRenderer::destroyTextureTarget(TextureTarget* target) { TextureTargetList::iterator i = std::find(d_textureTargets.begin(), d_textureTargets.end(), target); if (d_textureTargets.end() != i) { d_textureTargets.erase(i); delete target; } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllTextureTargets() { while (!d_textureTargets.empty()) destroyTextureTarget(*d_textureTargets.begin()); } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture() { OgreTexture* t = new OgreTexture; d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(const String& filename, const String& resourceGroup) { OgreTexture* t = new OgreTexture(filename, resourceGroup); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(const Size& size) { OgreTexture* t = new OgreTexture(size); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(Ogre::TexturePtr& tex, bool take_ownership) { OgreTexture* t = new OgreTexture(tex, take_ownership); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// void OgreRenderer::destroyTexture(Texture& texture) { TextureList::iterator i = std::find(d_textures.begin(), d_textures.end(), &texture); if (d_textures.end() != i) { d_textures.erase(i); delete &static_cast<OgreTexture&>(texture); } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllTextures() { while (!d_textures.empty()) destroyTexture(**d_textures.begin()); } //----------------------------------------------------------------------------// void OgreRenderer::beginRendering() { using namespace Ogre; // initialise render settings d_renderSystem->setLightingEnabled(false); d_renderSystem->_setDepthBufferParams(false, false); d_renderSystem->_setDepthBias(0, 0); d_renderSystem->_setCullingMode(CULL_NONE); d_renderSystem->_setFog(FOG_NONE); d_renderSystem->_setColourBufferWriteEnabled(true, true, true, true); d_renderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM); d_renderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM); d_renderSystem->setShadingType(SO_GOURAUD); d_renderSystem->_setPolygonMode(PM_SOLID); // enable alpha blending d_renderSystem->_setSeparateSceneBlending(SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA, SBF_SOURCE_ALPHA, SBF_ONE); d_renderSystem->_beginFrame(); } //----------------------------------------------------------------------------// void OgreRenderer::endRendering() { d_renderSystem->_endFrame(); } //----------------------------------------------------------------------------// const Size& OgreRenderer::getDisplaySize() const { return d_displaySize; } //----------------------------------------------------------------------------// const Vector2& OgreRenderer::getDisplayDPI() const { return d_displayDPI; } //----------------------------------------------------------------------------// uint OgreRenderer::getMaxTextureSize() const { return d_maxTextureSize; } //----------------------------------------------------------------------------// const String& OgreRenderer::getIdentifierString() const { return d_rendererID; } //----------------------------------------------------------------------------// OgreRenderer::OgreRenderer() : d_displayDPI(96, 96), // TODO: should be set to correct value d_maxTextureSize(2048), d_ogreRoot(Ogre::Root::getSingletonPtr()) { checkOgreInitialised(); // get auto created window Ogre::RenderWindow* rwnd = d_ogreRoot->getAutoCreatedWindow(); if (!rwnd) throw RendererException("Ogre was not initialised to automatically " "create a window, you should therefore be " "explicitly specifying a Ogre::RenderTarget in " "the OgreRenderer::create function."); constructor_impl(*rwnd); } //----------------------------------------------------------------------------// OgreRenderer::OgreRenderer(Ogre::RenderTarget& target) : d_displayDPI(96, 96), // TODO: should be set to correct value d_maxTextureSize(2048), d_ogreRoot(Ogre::Root::getSingletonPtr()) { checkOgreInitialised(); constructor_impl(target); } //----------------------------------------------------------------------------// OgreRenderer::~OgreRenderer() { d_ogreRoot->removeFrameListener(&S_frameListener); destroyAllGeometryBuffers(); destroyAllTextureTargets(); destroyAllTextures(); delete d_defaultRoot; delete d_defaultTarget; } //----------------------------------------------------------------------------// void OgreRenderer::checkOgreInitialised() { if (!d_ogreRoot) throw RendererException("The Ogre::Root object has not been created. " "You must initialise Ogre first!"); if (!d_ogreRoot->isInitialised()) throw RendererException("Ogre has not been initialised. You must " "initialise Ogre first!"); } //----------------------------------------------------------------------------// void OgreRenderer::constructor_impl(Ogre::RenderTarget& target) { d_renderSystem = d_ogreRoot->getRenderSystem(); d_displaySize.d_width = target.getWidth(); d_displaySize.d_height = target.getHeight(); // create default target & rendering root (surface) that uses it d_defaultTarget = new OgreWindowTarget(*this, *d_renderSystem, target); d_defaultRoot = new RenderingRoot(*d_defaultTarget); // hook into the rendering process d_ogreRoot->addFrameListener(&S_frameListener); } //----------------------------------------------------------------------------// void OgreRenderer::setDisplaySize(const Size& sz) { if (sz != d_displaySize) { d_displaySize = sz; // FIXME: This is probably not the right thing to do in all cases. Rect area(d_defaultTarget->getArea()); area.setSize(sz); d_defaultTarget->setArea(area); } } //----------------------------------------------------------------------------// OgreGUIFrameListener::OgreGUIFrameListener() : d_enabled(true) { } //----------------------------------------------------------------------------// void OgreGUIFrameListener::setCEGUIRenderEnabled(bool enabled) { d_enabled = enabled; } //----------------------------------------------------------------------------// bool OgreGUIFrameListener::isCEGUIRenderEnabled() const { return d_enabled; } //----------------------------------------------------------------------------// bool OgreGUIFrameListener::frameRenderingQueued(const Ogre::FrameEvent&) { if (d_enabled) System::getSingleton().renderGUI(); return true; } } // End of CEGUI namespace section <|endoftext|>
<commit_before>#include "../include/json_generator.hpp" #include "../../grammar/include/grammar.hpp" #include "../../grammar/include/nonterminal.hpp" #include "../../grammar/include/production.hpp" #include "../../grammar/include/token.hpp" #include "../../grammar/include/nonterminal.hpp" #include "../../table/include/state.hpp" #include "../../table/include/table.hpp" #include <iostream> #include <stdexcept> using namespace asparserations; using namespace grammar; using namespace table; using namespace codegen; JSON_Generator::JSON_Generator(const Table& table, bool pretty_print, const std::string& tab) : _table(table), _grammar(table.grammar()), _pretty_print(pretty_print), _indent_depth(0), _tab(tab) { _generate(); } const std::string& JSON_Generator::code() const {return _code;} void JSON_Generator::_break_and_indent() { if(_indent_depth > 10) { std::cout << _code << std::endl; throw std::runtime_error("Int underflow"); } if(_pretty_print) { _code += "\n"; for(unsigned int i = 0; i < _indent_depth; ++i) { _code += _tab; } } } void JSON_Generator::_generate() { _code += "{"; ++_indent_depth; _break_and_indent(); _code += "\"grammar\" : "; _generate_grammar(_grammar); _code += ","; _break_and_indent(); _code += "\"table\" : "; //std::cout << "Entering _generate_table" << std::endl; _generate_table(_table); //std::cout << "Exiting _generate_table" << std::endl; --_indent_depth; _break_and_indent(); _code += "}"; } void JSON_Generator::_generate_token(const Token& token) { _break_and_indent(); _code += "\"" + token.id() + "\""; } void JSON_Generator::_generate_nonterminal(const Nonterminal& n) { _code += "\"" + n.id() + "\" : {"; ++_indent_depth; bool needs_comma = false; for(auto& pair : n.productions()) { const Production& production = pair.second; if(needs_comma) { _code += ","; } else { needs_comma = true; } _break_and_indent(); _code += "\"" + production.id() + "\" : ["; ++_indent_depth; bool needs_comma2 = false; for(const Symbol* const symbol : production.symbols()) { if(needs_comma2) { _code += ","; } else { needs_comma2 = true; } _break_and_indent(); _code += "{"; ++_indent_depth; _break_and_indent(); _code += "\"id\" : \"" + symbol->id() + "\","; _break_and_indent(); _code += "\"isToken\" : " + std::to_string(symbol->is_token()); --_indent_depth; _break_and_indent(); _code += "}"; } --_indent_depth; _break_and_indent(); _code += "]"; } --_indent_depth; _break_and_indent(); _code += "}"; } void JSON_Generator::_generate_grammar(const Grammar& grammar) { _code += "{"; ++_indent_depth; _break_and_indent(); //Tokens _code += "\"tokens\" : ["; ++_indent_depth; _generate_token(grammar.end()); for(const Token* token : grammar.tokens()) { _code += ","; _generate_token(*token); } --_indent_depth; _break_and_indent(); _code += "],"; _break_and_indent(); //Nonterminals _code += "\"nonterminals\" : ["; ++_indent_depth; _break_and_indent(); _generate_nonterminal(grammar.accept()); for(const Nonterminal* nonterminal : grammar.nonterminals()) { _code += ","; _break_and_indent(); _generate_nonterminal(*nonterminal); } --_indent_depth; _break_and_indent(); _code += "]"; --_indent_depth; _break_and_indent(); _code += "}"; } void JSON_Generator::_generate_state(const State& state) { _code += "{"; ++_indent_depth; _break_and_indent(); _code += "\"shifts\" : {"; ++_indent_depth; bool needs_comma = false; for(auto& transition : state.transitions()) { const Symbol& symbol = *transition.first; const State& state = *transition.second; if(symbol.is_token()) { if(needs_comma) { _code += ","; } else { needs_comma = true; } _break_and_indent(); _code += "\"" + symbol.id() + "\" : " + std::to_string(state.index()); } } --_indent_depth; _break_and_indent(); _code += "},"; _break_and_indent(); _code += "\"reductions\" : {"; ++_indent_depth; needs_comma = false; for(auto& reduction : state.reductions()) { const Symbol& symbol = *reduction.first; if(needs_comma) { _code += ","; } else { needs_comma = true; } _break_and_indent(); _code += "\"" + symbol.id() + "\" : ["; ++_indent_depth; for(auto& production : reduction.second) { _break_and_indent(); _code += "{"; ++_indent_depth; _break_and_indent(); _code += "\"nonterminal\" : \"" + production->nonterminal().id() + "\","; _break_and_indent(); _code += "\"production\" : \"" + production->id() + "\""; --_indent_depth; _break_and_indent(); _code += "}"; } //std::cout << "Ending loop over productions" << std::endl; --_indent_depth; _break_and_indent(); _code += "]"; } --_indent_depth; _break_and_indent(); _code += "},"; _break_and_indent(); _code += "\"gotos\" : {"; ++_indent_depth; needs_comma = false; for(auto& transition : state.transitions()) { const Symbol& symbol = *transition.first; const State& state = *transition.second; if(!symbol.is_token()) { if(needs_comma) { _code += ","; } else { needs_comma = true; } _break_and_indent(); _code += "\"" + symbol.id() + "\" : " + std::to_string(state.index()); } } --_indent_depth; _break_and_indent(); _code += "}"; --_indent_depth; _break_and_indent(); _code += "}"; }; void JSON_Generator::_generate_table(const Table& table) { _code += "["; ++_indent_depth; bool insert_comma = false; for(const State& state : table.states()) { if(insert_comma) { _code += ","; } else { insert_comma = true; } _break_and_indent(); _generate_state(state); } --_indent_depth; _break_and_indent(); _code += "]"; } <commit_msg>Fixed bug in JSON generator<commit_after>#include "../include/json_generator.hpp" #include "../../grammar/include/grammar.hpp" #include "../../grammar/include/nonterminal.hpp" #include "../../grammar/include/production.hpp" #include "../../grammar/include/token.hpp" #include "../../grammar/include/nonterminal.hpp" #include "../../table/include/state.hpp" #include "../../table/include/table.hpp" #include <iostream> #include <stdexcept> using namespace asparserations; using namespace grammar; using namespace table; using namespace codegen; JSON_Generator::JSON_Generator(const Table& table, bool pretty_print, const std::string& tab) : _table(table), _grammar(table.grammar()), _pretty_print(pretty_print), _indent_depth(0), _tab(tab) { _generate(); } const std::string& JSON_Generator::code() const {return _code;} void JSON_Generator::_break_and_indent() { if(_indent_depth > 10) { std::cout << _code << std::endl; throw std::runtime_error("Int underflow"); } if(_pretty_print) { _code += "\n"; for(unsigned int i = 0; i < _indent_depth; ++i) { _code += _tab; } } } void JSON_Generator::_generate() { _code += "{"; ++_indent_depth; _break_and_indent(); _code += "\"grammar\" : "; _generate_grammar(_grammar); _code += ","; _break_and_indent(); _code += "\"table\" : "; //std::cout << "Entering _generate_table" << std::endl; _generate_table(_table); //std::cout << "Exiting _generate_table" << std::endl; --_indent_depth; _break_and_indent(); _code += "}"; } void JSON_Generator::_generate_token(const Token& token) { _break_and_indent(); _code += "\"" + token.id() + "\""; } void JSON_Generator::_generate_nonterminal(const Nonterminal& n) { _code += "\"" + n.id() + "\" : {"; ++_indent_depth; bool needs_comma = false; for(auto& pair : n.productions()) { const Production& production = pair.second; if(needs_comma) { _code += ","; } else { needs_comma = true; } _break_and_indent(); _code += "\"" + production.id() + "\" : ["; ++_indent_depth; bool needs_comma2 = false; for(const Symbol* const symbol : production.symbols()) { if(needs_comma2) { _code += ","; } else { needs_comma2 = true; } _break_and_indent(); _code += "{"; ++_indent_depth; _break_and_indent(); _code += "\"id\" : \"" + symbol->id() + "\","; _break_and_indent(); _code += "\"isToken\" : " + std::to_string(symbol->is_token()); --_indent_depth; _break_and_indent(); _code += "}"; } --_indent_depth; _break_and_indent(); _code += "]"; } --_indent_depth; _break_and_indent(); _code += "}"; } void JSON_Generator::_generate_grammar(const Grammar& grammar) { _code += "{"; ++_indent_depth; _break_and_indent(); //Tokens _code += "\"tokens\" : ["; ++_indent_depth; _generate_token(grammar.end()); for(const Token* token : grammar.tokens()) { _code += ","; _generate_token(*token); } --_indent_depth; _break_and_indent(); _code += "],"; _break_and_indent(); //Nonterminals _code += "\"nonterminals\" : {"; ++_indent_depth; _break_and_indent(); _generate_nonterminal(grammar.accept()); for(const Nonterminal* nonterminal : grammar.nonterminals()) { _code += ","; _break_and_indent(); _generate_nonterminal(*nonterminal); } --_indent_depth; _break_and_indent(); _code += "}"; --_indent_depth; _break_and_indent(); _code += "}"; } void JSON_Generator::_generate_state(const State& state) { _code += "{"; ++_indent_depth; _break_and_indent(); _code += "\"shifts\" : {"; ++_indent_depth; bool needs_comma = false; for(auto& transition : state.transitions()) { const Symbol& symbol = *transition.first; const State& state = *transition.second; if(symbol.is_token()) { if(needs_comma) { _code += ","; } else { needs_comma = true; } _break_and_indent(); _code += "\"" + symbol.id() + "\" : " + std::to_string(state.index()); } } --_indent_depth; _break_and_indent(); _code += "},"; _break_and_indent(); _code += "\"reductions\" : {"; ++_indent_depth; needs_comma = false; for(auto& reduction : state.reductions()) { const Symbol& symbol = *reduction.first; if(needs_comma) { _code += ","; } else { needs_comma = true; } _break_and_indent(); _code += "\"" + symbol.id() + "\" : ["; ++_indent_depth; for(auto& production : reduction.second) { _break_and_indent(); _code += "{"; ++_indent_depth; _break_and_indent(); _code += "\"nonterminal\" : \"" + production->nonterminal().id() + "\","; _break_and_indent(); _code += "\"production\" : \"" + production->id() + "\""; --_indent_depth; _break_and_indent(); _code += "}"; } //std::cout << "Ending loop over productions" << std::endl; --_indent_depth; _break_and_indent(); _code += "]"; } --_indent_depth; _break_and_indent(); _code += "},"; _break_and_indent(); _code += "\"gotos\" : {"; ++_indent_depth; needs_comma = false; for(auto& transition : state.transitions()) { const Symbol& symbol = *transition.first; const State& state = *transition.second; if(!symbol.is_token()) { if(needs_comma) { _code += ","; } else { needs_comma = true; } _break_and_indent(); _code += "\"" + symbol.id() + "\" : " + std::to_string(state.index()); } } --_indent_depth; _break_and_indent(); _code += "}"; --_indent_depth; _break_and_indent(); _code += "}"; }; void JSON_Generator::_generate_table(const Table& table) { _code += "["; ++_indent_depth; bool insert_comma = false; for(const State& state : table.states()) { if(insert_comma) { _code += ","; } else { insert_comma = true; } _break_and_indent(); _generate_state(state); } --_indent_depth; _break_and_indent(); _code += "]"; } <|endoftext|>
<commit_before>/* * This file is part of TelepathyQt4 * * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2008 Nokia Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/Client/DBusProxy> #include "TelepathyQt4/Client/_gen/dbus-proxy.moc.hpp" #include "TelepathyQt4/debug-internal.h" #include <QtCore/QTimer> #include <QtDBus/QDBusConnectionInterface> namespace Telepathy { namespace Client { // ==== DBusProxy ====================================================== class DBusProxy::Private { public: // Public object DBusProxy &parent; QDBusConnection dbusConnection; QString busName; QString objectPath; Private(const QDBusConnection &dbusConnection, const QString &busName, const QString &objectPath, DBusProxy &p) : parent(p), dbusConnection(dbusConnection), busName(busName), objectPath(objectPath) { debug() << "Creating new DBusProxy"; } }; DBusProxy::DBusProxy(const QDBusConnection &dbusConnection, const QString &busName, const QString &path, QObject *parent) : QObject(parent), mPriv(new Private(dbusConnection, busName, path, *this)) { } DBusProxy::~DBusProxy() { delete mPriv; } QDBusConnection DBusProxy::dbusConnection() const { return mPriv->dbusConnection; } QString DBusProxy::objectPath() const { return mPriv->objectPath; } QString DBusProxy::busName() const { return mPriv->busName; } // ==== StatelessDBusProxy ============================================= StatelessDBusProxy::StatelessDBusProxy(const QDBusConnection& dbusConnection, const QString &busName, const QString &objectPath, QObject *parent) : DBusProxy(dbusConnection, busName, objectPath, parent) { } // ==== StatefulDBusProxy ============================================== class StatefulDBusProxy::Private { public: // Public object StatefulDBusProxy &parent; QString invalidationReason; QString invalidationMessage; Private(StatefulDBusProxy &p) : parent(p), invalidationReason(QString()), invalidationMessage(QString()) { debug() << "Creating new StatefulDBusProxy"; } }; StatefulDBusProxy::StatefulDBusProxy(const QDBusConnection &dbusConnection, const QString &busName, const QString &objectPath, QObject *parent) : DBusProxy(dbusConnection, busName, objectPath, parent) { // FIXME: Am I on crack? connect(dbusConnection.interface(), SIGNAL(serviceOwnerChanged(QString, QString, QString)), this, SLOT(onServiceOwnerChanged(QString, QString, QString))); } bool StatefulDBusProxy::isValid() const { return mPriv->invalidationReason.isEmpty(); } QString StatefulDBusProxy::invalidationReason() const { return mPriv->invalidationReason; } QString StatefulDBusProxy::invalidationMessage() const { return mPriv->invalidationMessage; } void StatefulDBusProxy::invalidate(const QString &reason, const QString &message) { Q_ASSERT(isValid()); Q_ASSERT(!reason.isEmpty()); mPriv->invalidationReason = reason; mPriv->invalidationMessage = message; Q_ASSERT(!isValid()); // Defer emitting the invalidated signal until we next // return to the mainloop. QTimer::singleShot(0, this, SLOT(emitInvalidated())); } void StatefulDBusProxy::emitInvalidated() { Q_ASSERT(!isValid()); emit invalidated(this, mPriv->invalidationReason, mPriv->invalidationMessage); } void StatefulDBusProxy::onServiceOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner) { // We only want to invalidate this object if it is not already invalidated, // and it's (not any other object's) name owner changed signal is emitted. if (isValid() && (name == busName())) { // FIXME: where do the error texts come from? the spec? invalidate("NAME_OWNER_CHANGED", "NameOwnerChanged() received for this object."); } } } } <commit_msg>StatefulDBusProxy: raise NameHasNoOwner if the service dies<commit_after>/* * This file is part of TelepathyQt4 * * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2008 Nokia Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/Client/DBusProxy> #include "TelepathyQt4/Client/_gen/dbus-proxy.moc.hpp" #include "TelepathyQt4/debug-internal.h" #include <TelepathyQt4/Constants> #include <QtCore/QTimer> #include <QtDBus/QDBusConnectionInterface> namespace Telepathy { namespace Client { // ==== DBusProxy ====================================================== class DBusProxy::Private { public: // Public object DBusProxy &parent; QDBusConnection dbusConnection; QString busName; QString objectPath; Private(const QDBusConnection &dbusConnection, const QString &busName, const QString &objectPath, DBusProxy &p) : parent(p), dbusConnection(dbusConnection), busName(busName), objectPath(objectPath) { debug() << "Creating new DBusProxy"; } }; DBusProxy::DBusProxy(const QDBusConnection &dbusConnection, const QString &busName, const QString &path, QObject *parent) : QObject(parent), mPriv(new Private(dbusConnection, busName, path, *this)) { } DBusProxy::~DBusProxy() { delete mPriv; } QDBusConnection DBusProxy::dbusConnection() const { return mPriv->dbusConnection; } QString DBusProxy::objectPath() const { return mPriv->objectPath; } QString DBusProxy::busName() const { return mPriv->busName; } // ==== StatelessDBusProxy ============================================= StatelessDBusProxy::StatelessDBusProxy(const QDBusConnection& dbusConnection, const QString &busName, const QString &objectPath, QObject *parent) : DBusProxy(dbusConnection, busName, objectPath, parent) { } // ==== StatefulDBusProxy ============================================== class StatefulDBusProxy::Private { public: // Public object StatefulDBusProxy &parent; QString invalidationReason; QString invalidationMessage; Private(StatefulDBusProxy &p) : parent(p), invalidationReason(QString()), invalidationMessage(QString()) { debug() << "Creating new StatefulDBusProxy"; } }; StatefulDBusProxy::StatefulDBusProxy(const QDBusConnection &dbusConnection, const QString &busName, const QString &objectPath, QObject *parent) : DBusProxy(dbusConnection, busName, objectPath, parent) { // FIXME: Am I on crack? connect(dbusConnection.interface(), SIGNAL(serviceOwnerChanged(QString, QString, QString)), this, SLOT(onServiceOwnerChanged(QString, QString, QString))); } bool StatefulDBusProxy::isValid() const { return mPriv->invalidationReason.isEmpty(); } QString StatefulDBusProxy::invalidationReason() const { return mPriv->invalidationReason; } QString StatefulDBusProxy::invalidationMessage() const { return mPriv->invalidationMessage; } void StatefulDBusProxy::invalidate(const QString &reason, const QString &message) { Q_ASSERT(isValid()); Q_ASSERT(!reason.isEmpty()); mPriv->invalidationReason = reason; mPriv->invalidationMessage = message; Q_ASSERT(!isValid()); // Defer emitting the invalidated signal until we next // return to the mainloop. QTimer::singleShot(0, this, SLOT(emitInvalidated())); } void StatefulDBusProxy::emitInvalidated() { Q_ASSERT(!isValid()); emit invalidated(this, mPriv->invalidationReason, mPriv->invalidationMessage); } void StatefulDBusProxy::onServiceOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner) { // We only want to invalidate this object if it is not already invalidated, // and it's (not any other object's) name owner changed signal is emitted. if (isValid() && (name == busName())) { invalidate(TELEPATHY_DBUS_ERROR_NAME_HAS_NO_OWNER, "Name owner lost (service crashed?)"); } } } } <|endoftext|>
<commit_before>/* * CoinSpark asset tracking server 1.0 beta * * Copyright (c) 2014 Coin Sciences Ltd - coinspark.org * * Distributed under the AGPLv3 software license, see the accompanying * file COPYING or http://www.gnu.org/licenses/agpl-3.0.txt */ #include "bitcoin.h" void SHA256(void *src,cs_int32 len,cs_uchar *hash) { CoinSparkCalcSHA256Hash((cs_uchar*)src,len,hash); } void cs_Message::Zero() { m_lpBuf=NULL; m_BufSize=CS_DCT_MSG_BUFFERSIZE; m_Size=CS_DCT_MSG_HEADERSIZE; m_lpArgs=NULL; m_BitcoinMagicValue=CS_DCT_MSG_NETWORK_MAIN; } cs_int32 cs_Message::Initialize(cs_Arguments *lpArgs,cs_int32 Size) { Destroy(); if(Size>0)m_BufSize=Size; m_lpBuf=(cs_uchar *)cs_New(sizeof(cs_uchar)*m_BufSize,NULL,CS_ALT_DEFAULT); if(m_lpBuf==NULL) return CS_ERR_ALLOCATION | CS_ERR_BITCOIN_PREFIX; m_lpArgs=lpArgs; if(m_lpArgs) { if(strcmp(lpArgs->m_BitcoinNetwork,"testnet") == 0) { m_BitcoinMagicValue=CS_DCT_MSG_NETWORK_TESTNET; } if(strcmp(lpArgs->m_BitcoinNetwork,"testnet3") == 0) { m_BitcoinMagicValue=CS_DCT_MSG_NETWORK_TESTNET3; } if(strcmp(lpArgs->m_BitcoinNetwork,"namecoin") == 0) { m_BitcoinMagicValue=CS_DCT_MSG_NETWORK_NAMECOIN; } } return CS_ERR_NOERROR; } cs_int32 cs_Message::Destroy() { cs_Delete(m_lpBuf,NULL,CS_ALT_DEFAULT); Zero(); return CS_ERR_NOERROR; } cs_int32 cs_Message::Clear() { m_Size=CS_DCT_MSG_HEADERSIZE; return CS_ERR_NOERROR; } cs_int32 cs_Message::PutVarInt(cs_uint64 value) { cs_int32 size; cs_uchar buf[9]; if(value<0xfd) { buf[0]=(cs_uchar)value; size=0; } else { if(value<0xffff) { buf[0]=0xfd;size=2; } else { if(value<0xffffffff) { buf[0]=0xfe;size=4; } else { buf[0]=0xff;size=8; } } cs_PutNumberLittleEndian(buf+1,&value,size,sizeof(value)); } return PutData(buf,size+1); } cs_int32 cs_Message::PutData(void *lpData,cs_int32 len) { cs_uchar *lpNewBuffer; cs_int32 NewSize; if(m_Size+len+1>m_BufSize) { NewSize=((m_Size+len)/CS_DCT_MSG_BUFFERSIZE + 1) * CS_DCT_MSG_BUFFERSIZE; lpNewBuffer=(cs_uchar*)cs_New(NewSize,NULL,CS_ALT_DEFAULT); if(lpNewBuffer == NULL) { return CS_ERR_ALLOCATION; } cs_Delete(m_lpBuf,NULL,CS_ALT_DEFAULT); m_lpBuf=lpNewBuffer; m_BufSize=NewSize; } memcpy(m_lpBuf+m_Size,lpData,len); m_Size+=len; m_lpBuf[m_Size]=0; return CS_ERR_NOERROR; } void *cs_Message::GetData() { return m_lpBuf; } cs_int32 cs_Message::GetSize() { return m_Size; } cs_int32 cs_Message::Complete(cs_char *lpCommand) { cs_int32 len; cs_uchar hash[SHA256_DIGEST_LENGTH]; cs_PutNumberLittleEndian(m_lpBuf+0,&m_BitcoinMagicValue,4,sizeof(m_BitcoinMagicValue)); len=strlen(lpCommand); memset(m_lpBuf+4,0,12); memcpy(m_lpBuf+4,lpCommand,len); m_lpBuf[4+len]=0; len=m_Size-CS_DCT_MSG_HEADERSIZE; cs_PutNumberLittleEndian(m_lpBuf+16,&len,4,sizeof(len)); SHA256(m_lpBuf+CS_DCT_MSG_HEADERSIZE, len, hash); SHA256(hash, SHA256_DIGEST_LENGTH, hash); memcpy(m_lpBuf+20,hash,4); return m_Size; } void bitcoin_block_hash(cs_uchar *block_header) { SHA256(block_header+CS_DCT_BLOCK_HEAD_OFFSET, 80, block_header); SHA256(block_header, SHA256_DIGEST_LENGTH, block_header); } void bitcoin_tx_hash(cs_uchar *lpTxHash,cs_uchar *lpTx,cs_int32 TxSize) { SHA256(lpTx, TxSize, lpTxHash); SHA256(lpTxHash, SHA256_DIGEST_LENGTH, lpTxHash); } void bitcoin_hash_to_string(cs_char *out,cs_uchar *hash) { cs_int32 i; for(i=0;i<CS_DCT_HASH_BYTES;i++) { sprintf(out+(i*2),"%02x",hash[CS_DCT_HASH_BYTES-1-i]); } out[64]=0; } void bitcoin_string_to_hash(cs_char *out,cs_uchar *hash) { cs_int32 i; for(i=0;i<CS_DCT_HASH_BYTES;i++) { hash[CS_DCT_HASH_BYTES-1-i]=cs_HexToUChar(out+i*2); } } cs_int32 bitcoin_get_varint_size(cs_uchar byte) { if(byte<0xfd)return 0; if(byte==0xfd)return 2; if(byte==0xfe)return 4; return 8; } cs_int32 bitcoin_put_varint(cs_uchar *buf,cs_int64 value) { cs_int32 varint_size,shift; varint_size=1; shift=0; if(value>=0xfd) { shift=1; if(value>=0xffff) { if(value>=0xffffffff) { buf[0]=0xff; varint_size=8; } else { buf[0]=0xfe; varint_size=4; } } else { buf[0]=0xfd; varint_size=2; } } cs_PutNumberLittleEndian(buf+shift,&value,varint_size,sizeof(value)); return shift+varint_size; } cs_int32 bitcoin_wait_for_message(cs_Connection *lpConnection,cs_char *lpCommand,cs_uint64 *payload_size,cs_handle Log) { cs_int32 StopTime; cs_int32 err; cs_uint64 size,total; cs_char *ptr; err=CS_ERR_NOERROR; StopTime=(cs_int32)cs_TimeNow()+CS_DCT_MSG_TIMEOUT; while((cs_int32)cs_TimeNow()<StopTime) { size=lpConnection->GetSize(); while(size<CS_DCT_MSG_HEADERSIZE) { err=lpConnection->Recv(); if(err) { return err; } size=lpConnection->GetSize(); } ptr=(cs_char*)(lpConnection->GetData(CS_DCT_MSG_HEADERSIZE)); *payload_size=cs_GetUInt64LittleEndian(ptr+16,4); cs_LogMessage(Log,CS_LOG_MINOR,"C-0078","Bitcoin message: ",ptr+4); if(strcmp(ptr+4,lpCommand) == 0) { return CS_ERR_NOERROR; } size=lpConnection->GetSize(); ptr=(cs_char*)(lpConnection->GetData(size)); total=size; while(total<*payload_size) { err=lpConnection->Recv(); if(err) { return err; } if((cs_int32)cs_TimeNow()>=StopTime) { return CS_ERR_TIMEOUT; } size=lpConnection->GetSize(); if(total+size>*payload_size) { size=*payload_size-total; } ptr=(cs_char*)(lpConnection->GetData(size)); total+=size; } } return CS_ERR_TIMEOUT; } void bitcoin_prepare_address(cs_uchar* dest,cs_char* lpAddress,cs_int32 Port,cs_int32 SetTimestamp) { cs_uint64 value; cs_int32 pos; cs_char *ptr; if(SetTimestamp) { value=(cs_uint64)cs_TimeNow(); cs_PutNumberLittleEndian(dest+0,&value,4,sizeof(value)); } value=1; cs_PutNumberLittleEndian(dest+4,&value,8,sizeof(value)); memset(dest+12,0,10); value=0xFFFF; cs_PutNumberLittleEndian(dest+22,&value,2,sizeof(value)); ptr=lpAddress; pos=4; while(pos) { value=0; while((*ptr != '.') && (*ptr!=0x00)) { value=value*10+(*ptr-0x30); ptr++; } ptr++; cs_PutNumberLittleEndian(dest+28-pos,&value,1,sizeof(value)); pos--; } cs_PutNumberBigEndian(dest+28,&Port,2,sizeof(Port)); } cs_int32 bitcoin_prepare_message_version(cs_Message *lpMessage,cs_int32 PretendRealNode) { cs_uint64 value; cs_uchar buf[128]; lpMessage->Clear(); value=CS_DCT_MSG_PROTOCOL_VERSION; cs_PutNumberLittleEndian(buf+0,&value,4,sizeof(value)); value=1; cs_PutNumberLittleEndian(buf+4,&value,8,sizeof(value)); value=(cs_uint64)cs_TimeNow(); cs_PutNumberLittleEndian(buf+12,&value,8,sizeof(value)); bitcoin_prepare_address(buf+20-4,lpMessage->m_lpArgs->m_BitcoinClientAddress,lpMessage->m_lpArgs->m_BitcoinClientPort,0); if(PretendRealNode) { bitcoin_prepare_address(buf+46-4,"127.0.0.1",8333,0); } else { bitcoin_prepare_address(buf+46-4,"0.0.0.0",0,0); } value=(cs_uint64)cs_TimeNow(); cs_PutNumberLittleEndian(buf+72,&value,8,sizeof(value)); value=0; cs_PutNumberLittleEndian(buf+80,&value,1,sizeof(value)); value=0; cs_PutNumberLittleEndian(buf+81,&value,4,sizeof(value)); value=0; cs_PutNumberLittleEndian(buf+85,&value,1,sizeof(value)); lpMessage->PutData(buf,86); return lpMessage->Complete("version"); } cs_int32 bitcoin_prepare_message_getdata(cs_Message *lpMessage,cs_int32 type,cs_uchar *lpHash) { cs_uint64 value; cs_uchar buf[128]; lpMessage->Clear(); value=1; cs_PutNumberLittleEndian(buf+0,&value,1,sizeof(value)); value=type; cs_PutNumberLittleEndian(buf+1,&value,4,sizeof(value)); lpMessage->PutData(buf,5); lpMessage->PutData(lpHash,32); return lpMessage->Complete("getdata"); } cs_int32 bitcoin_prepare_message_mempool(cs_Message *lpMessage) { lpMessage->Clear(); return lpMessage->Complete("mempool"); } cs_int32 bitcoin_find_op_return(cs_uchar *script,cs_int32 size) { cs_uchar *ptr; cs_uchar *ptrEnd; ptr=script; ptrEnd=ptr+size; while(ptr<ptrEnd) { if(*ptr==0x6a) { return ptr+1-script; } if(*ptr>=1) { if(*ptr<76) { ptr+=*ptr; } else { if(*ptr<79) { if(*ptr==76) { ptr+=*(ptr+1)+1; } if(*ptr==77) { ptr+=cs_GetUInt64LittleEndian(ptr+1,2)+2; } if(*ptr==78) { ptr+=cs_GetUInt64LittleEndian(ptr+1,4)+4; } } } } ptr++; } return ptr-script; } <commit_msg>Fixing crash on non-standard output script<commit_after>/* * CoinSpark asset tracking server 1.0 beta * * Copyright (c) 2014 Coin Sciences Ltd - coinspark.org * * Distributed under the AGPLv3 software license, see the accompanying * file COPYING or http://www.gnu.org/licenses/agpl-3.0.txt */ #include "bitcoin.h" void SHA256(void *src,cs_int32 len,cs_uchar *hash) { CoinSparkCalcSHA256Hash((cs_uchar*)src,len,hash); } void cs_Message::Zero() { m_lpBuf=NULL; m_BufSize=CS_DCT_MSG_BUFFERSIZE; m_Size=CS_DCT_MSG_HEADERSIZE; m_lpArgs=NULL; m_BitcoinMagicValue=CS_DCT_MSG_NETWORK_MAIN; } cs_int32 cs_Message::Initialize(cs_Arguments *lpArgs,cs_int32 Size) { Destroy(); if(Size>0)m_BufSize=Size; m_lpBuf=(cs_uchar *)cs_New(sizeof(cs_uchar)*m_BufSize,NULL,CS_ALT_DEFAULT); if(m_lpBuf==NULL) return CS_ERR_ALLOCATION | CS_ERR_BITCOIN_PREFIX; m_lpArgs=lpArgs; if(m_lpArgs) { if(strcmp(lpArgs->m_BitcoinNetwork,"testnet") == 0) { m_BitcoinMagicValue=CS_DCT_MSG_NETWORK_TESTNET; } if(strcmp(lpArgs->m_BitcoinNetwork,"testnet3") == 0) { m_BitcoinMagicValue=CS_DCT_MSG_NETWORK_TESTNET3; } if(strcmp(lpArgs->m_BitcoinNetwork,"namecoin") == 0) { m_BitcoinMagicValue=CS_DCT_MSG_NETWORK_NAMECOIN; } } return CS_ERR_NOERROR; } cs_int32 cs_Message::Destroy() { cs_Delete(m_lpBuf,NULL,CS_ALT_DEFAULT); Zero(); return CS_ERR_NOERROR; } cs_int32 cs_Message::Clear() { m_Size=CS_DCT_MSG_HEADERSIZE; return CS_ERR_NOERROR; } cs_int32 cs_Message::PutVarInt(cs_uint64 value) { cs_int32 size; cs_uchar buf[9]; if(value<0xfd) { buf[0]=(cs_uchar)value; size=0; } else { if(value<0xffff) { buf[0]=0xfd;size=2; } else { if(value<0xffffffff) { buf[0]=0xfe;size=4; } else { buf[0]=0xff;size=8; } } cs_PutNumberLittleEndian(buf+1,&value,size,sizeof(value)); } return PutData(buf,size+1); } cs_int32 cs_Message::PutData(void *lpData,cs_int32 len) { cs_uchar *lpNewBuffer; cs_int32 NewSize; if(m_Size+len+1>m_BufSize) { NewSize=((m_Size+len)/CS_DCT_MSG_BUFFERSIZE + 1) * CS_DCT_MSG_BUFFERSIZE; lpNewBuffer=(cs_uchar*)cs_New(NewSize,NULL,CS_ALT_DEFAULT); if(lpNewBuffer == NULL) { return CS_ERR_ALLOCATION; } cs_Delete(m_lpBuf,NULL,CS_ALT_DEFAULT); m_lpBuf=lpNewBuffer; m_BufSize=NewSize; } memcpy(m_lpBuf+m_Size,lpData,len); m_Size+=len; m_lpBuf[m_Size]=0; return CS_ERR_NOERROR; } void *cs_Message::GetData() { return m_lpBuf; } cs_int32 cs_Message::GetSize() { return m_Size; } cs_int32 cs_Message::Complete(cs_char *lpCommand) { cs_int32 len; cs_uchar hash[SHA256_DIGEST_LENGTH]; cs_PutNumberLittleEndian(m_lpBuf+0,&m_BitcoinMagicValue,4,sizeof(m_BitcoinMagicValue)); len=strlen(lpCommand); memset(m_lpBuf+4,0,12); memcpy(m_lpBuf+4,lpCommand,len); m_lpBuf[4+len]=0; len=m_Size-CS_DCT_MSG_HEADERSIZE; cs_PutNumberLittleEndian(m_lpBuf+16,&len,4,sizeof(len)); SHA256(m_lpBuf+CS_DCT_MSG_HEADERSIZE, len, hash); SHA256(hash, SHA256_DIGEST_LENGTH, hash); memcpy(m_lpBuf+20,hash,4); return m_Size; } void bitcoin_block_hash(cs_uchar *block_header) { SHA256(block_header+CS_DCT_BLOCK_HEAD_OFFSET, 80, block_header); SHA256(block_header, SHA256_DIGEST_LENGTH, block_header); } void bitcoin_tx_hash(cs_uchar *lpTxHash,cs_uchar *lpTx,cs_int32 TxSize) { SHA256(lpTx, TxSize, lpTxHash); SHA256(lpTxHash, SHA256_DIGEST_LENGTH, lpTxHash); } void bitcoin_hash_to_string(cs_char *out,cs_uchar *hash) { cs_int32 i; for(i=0;i<CS_DCT_HASH_BYTES;i++) { sprintf(out+(i*2),"%02x",hash[CS_DCT_HASH_BYTES-1-i]); } out[64]=0; } void bitcoin_string_to_hash(cs_char *out,cs_uchar *hash) { cs_int32 i; for(i=0;i<CS_DCT_HASH_BYTES;i++) { hash[CS_DCT_HASH_BYTES-1-i]=cs_HexToUChar(out+i*2); } } cs_int32 bitcoin_get_varint_size(cs_uchar byte) { if(byte<0xfd)return 0; if(byte==0xfd)return 2; if(byte==0xfe)return 4; return 8; } cs_int32 bitcoin_put_varint(cs_uchar *buf,cs_int64 value) { cs_int32 varint_size,shift; varint_size=1; shift=0; if(value>=0xfd) { shift=1; if(value>=0xffff) { if(value>=0xffffffff) { buf[0]=0xff; varint_size=8; } else { buf[0]=0xfe; varint_size=4; } } else { buf[0]=0xfd; varint_size=2; } } cs_PutNumberLittleEndian(buf+shift,&value,varint_size,sizeof(value)); return shift+varint_size; } cs_int32 bitcoin_wait_for_message(cs_Connection *lpConnection,cs_char *lpCommand,cs_uint64 *payload_size,cs_handle Log) { cs_int32 StopTime; cs_int32 err; cs_uint64 size,total; cs_char *ptr; err=CS_ERR_NOERROR; StopTime=(cs_int32)cs_TimeNow()+CS_DCT_MSG_TIMEOUT; while((cs_int32)cs_TimeNow()<StopTime) { size=lpConnection->GetSize(); while(size<CS_DCT_MSG_HEADERSIZE) { err=lpConnection->Recv(); if(err) { return err; } size=lpConnection->GetSize(); } ptr=(cs_char*)(lpConnection->GetData(CS_DCT_MSG_HEADERSIZE)); *payload_size=cs_GetUInt64LittleEndian(ptr+16,4); cs_LogMessage(Log,CS_LOG_MINOR,"C-0078","Bitcoin message: ",ptr+4); if(strcmp(ptr+4,lpCommand) == 0) { return CS_ERR_NOERROR; } size=lpConnection->GetSize(); ptr=(cs_char*)(lpConnection->GetData(size)); total=size; while(total<*payload_size) { err=lpConnection->Recv(); if(err) { return err; } if((cs_int32)cs_TimeNow()>=StopTime) { return CS_ERR_TIMEOUT; } size=lpConnection->GetSize(); if(total+size>*payload_size) { size=*payload_size-total; } ptr=(cs_char*)(lpConnection->GetData(size)); total+=size; } } return CS_ERR_TIMEOUT; } void bitcoin_prepare_address(cs_uchar* dest,cs_char* lpAddress,cs_int32 Port,cs_int32 SetTimestamp) { cs_uint64 value; cs_int32 pos; cs_char *ptr; if(SetTimestamp) { value=(cs_uint64)cs_TimeNow(); cs_PutNumberLittleEndian(dest+0,&value,4,sizeof(value)); } value=1; cs_PutNumberLittleEndian(dest+4,&value,8,sizeof(value)); memset(dest+12,0,10); value=0xFFFF; cs_PutNumberLittleEndian(dest+22,&value,2,sizeof(value)); ptr=lpAddress; pos=4; while(pos) { value=0; while((*ptr != '.') && (*ptr!=0x00)) { value=value*10+(*ptr-0x30); ptr++; } ptr++; cs_PutNumberLittleEndian(dest+28-pos,&value,1,sizeof(value)); pos--; } cs_PutNumberBigEndian(dest+28,&Port,2,sizeof(Port)); } cs_int32 bitcoin_prepare_message_version(cs_Message *lpMessage,cs_int32 PretendRealNode) { cs_uint64 value; cs_uchar buf[128]; lpMessage->Clear(); value=CS_DCT_MSG_PROTOCOL_VERSION; cs_PutNumberLittleEndian(buf+0,&value,4,sizeof(value)); value=1; cs_PutNumberLittleEndian(buf+4,&value,8,sizeof(value)); value=(cs_uint64)cs_TimeNow(); cs_PutNumberLittleEndian(buf+12,&value,8,sizeof(value)); bitcoin_prepare_address(buf+20-4,lpMessage->m_lpArgs->m_BitcoinClientAddress,lpMessage->m_lpArgs->m_BitcoinClientPort,0); if(PretendRealNode) { bitcoin_prepare_address(buf+46-4,"127.0.0.1",8333,0); } else { bitcoin_prepare_address(buf+46-4,"0.0.0.0",0,0); } value=(cs_uint64)cs_TimeNow(); cs_PutNumberLittleEndian(buf+72,&value,8,sizeof(value)); value=0; cs_PutNumberLittleEndian(buf+80,&value,1,sizeof(value)); value=0; cs_PutNumberLittleEndian(buf+81,&value,4,sizeof(value)); value=0; cs_PutNumberLittleEndian(buf+85,&value,1,sizeof(value)); lpMessage->PutData(buf,86); return lpMessage->Complete("version"); } cs_int32 bitcoin_prepare_message_getdata(cs_Message *lpMessage,cs_int32 type,cs_uchar *lpHash) { cs_uint64 value; cs_uchar buf[128]; lpMessage->Clear(); value=1; cs_PutNumberLittleEndian(buf+0,&value,1,sizeof(value)); value=type; cs_PutNumberLittleEndian(buf+1,&value,4,sizeof(value)); lpMessage->PutData(buf,5); lpMessage->PutData(lpHash,32); return lpMessage->Complete("getdata"); } cs_int32 bitcoin_prepare_message_mempool(cs_Message *lpMessage) { lpMessage->Clear(); return lpMessage->Complete("mempool"); } cs_int32 bitcoin_find_op_return(cs_uchar *script,cs_int32 size) { cs_uchar *ptr; cs_uchar *ptrEnd; ptr=script; ptrEnd=ptr+size; while(ptr<ptrEnd) { if(*ptr==0x6a) { return ptr+1-script; } if(*ptr>=1) { if(*ptr<76) { ptr+=*ptr; } else { if(*ptr<79) { if(*ptr==76) { if(ptr+1 >= ptrEnd) { return ptrEnd-script; } ptr+=*(ptr+1)+1; } if(*ptr==77) { if(ptr+2 >= ptrEnd) { return ptrEnd-script; } ptr+=cs_GetUInt64LittleEndian(ptr+1,2)+2; } if(*ptr==78) { if(ptr+4 >= ptrEnd) { return ptrEnd-script; } ptr+=cs_GetUInt64LittleEndian(ptr+1,4)+4; } } } } ptr++; } return ptr-script; } <|endoftext|>
<commit_before>// // Name: StyleDlg.cpp // // Copyright (c) 2004 Virtual Terrain Project. // Free for all uses, see license.txt for details. // #ifdef __GNUG__ #pragma implementation "StyleDlg.cpp" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #include "wx/colordlg.h" #include "StyleDlg.h" #include "vtlib/vtlib.h" #include "vtlib/core/TerrainScene.h" #include "vtdata/Features.h" #include "vtui/wxString2.h" #include "vtui/Helper.h" // WDR: class implementations //---------------------------------------------------------------------------- // StyleDlg //---------------------------------------------------------------------------- // WDR: event table for StyleDlg BEGIN_EVENT_TABLE(StyleDlg,AutoDialog) EVT_INIT_DIALOG (StyleDlg::OnInitDialog) EVT_BUTTON( ID_GEOM_COLOR, StyleDlg::OnGeomColor ) EVT_BUTTON( ID_LABEL_COLOR, StyleDlg::OnLabelColor ) EVT_CHECKBOX( ID_GEOMETRY, StyleDlg::OnCheck ) EVT_CHECKBOX( ID_TEXT_LABELS, StyleDlg::OnCheck ) END_EVENT_TABLE() StyleDlg::StyleDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : AutoDialog( parent, id, title, position, size, style ) { // WDR: dialog function StyleDialogFunc for StyleDlg StyleDialogFunc( this, TRUE ); m_bGeometry = true; m_GeomColor.Set(255,255,255); m_bTextLabels = false; m_LabelColor.Set(255,255,255); m_iTextField = 0; m_iColorField = 0; m_fLabelHeight = 0.0f; m_fLabelSize = 0.0f; AddValidator(ID_FEATURE_TYPE, &m_strFeatureType); AddValidator(ID_GEOMETRY, &m_bGeometry); AddValidator(ID_TEXT_LABELS, &m_bTextLabels); AddValidator(ID_TEXT_FIELD, &m_iTextField); AddValidator(ID_COLOR_FIELD, &m_iColorField); AddNumValidator(ID_LABEL_HEIGHT, &m_fLabelHeight); AddNumValidator(ID_LABEL_SIZE, &m_fLabelSize); } void StyleDlg::OnInitDialog(wxInitDialogEvent& event) { RefreshFields(); UpdateEnabling(); UpdateColorButtons(); wxDialog::OnInitDialog(event); } void StyleDlg::SetOptions(vtStringArray &datapaths, const vtTagArray &Layer) { // for our purposes, we need the actual file location m_strFilename = Layer.GetValueString("Filename"); m_bGeometry = Layer.GetValueBool("Geometry"); if (!Layer.GetValueRGBi("GeomColor", m_GeomColor)) m_GeomColor.Set(255,255,255); m_bTextLabels = Layer.GetValueBool("Labels"); if (!Layer.GetValueRGBi("LabelColor", m_LabelColor)) m_LabelColor.Set(255,255,255); if (!Layer.GetValueInt("TextFieldIndex", m_iTextField)) m_iTextField = -1; if (!Layer.GetValueInt("ColorFieldIndex", m_iColorField)) m_iColorField = -1; if (!Layer.GetValueFloat("Elevation", m_fLabelHeight)) m_fLabelHeight= 0; if (!Layer.GetValueFloat("LabelSize", m_fLabelSize)) m_fLabelSize = 20; m_strResolved = m_strFilename; m_strResolved = FindFileOnPaths(datapaths, m_strResolved); if (m_strResolved == "") { vtString path = "PointData/"; m_strResolved = path + m_strFilename; m_strResolved = FindFileOnPaths(datapaths, m_strResolved); } } void StyleDlg::GetOptions(vtTagArray &pLayer) { pLayer.SetValueBool("Geometry", m_bGeometry); if (m_bGeometry) pLayer.SetValueRGBi("GeomColor", m_GeomColor); else pLayer.RemoveTag("GeomColor"); pLayer.SetValueBool("Labels", m_bTextLabels); if (m_bTextLabels) { pLayer.SetValueRGBi("LabelColor", m_LabelColor); pLayer.SetValueBool("TextFieldIndex", m_bTextLabels); pLayer.SetValueInt("ColorFieldIndex", m_iColorField); pLayer.SetValueFloat("Elevation", m_fLabelHeight); pLayer.SetValueFloat("LabelSize", m_fLabelSize); } else { pLayer.RemoveTag("LabelColor"); pLayer.RemoveTag("TextFieldIndex"); pLayer.RemoveTag("ColorFieldIndex"); pLayer.RemoveTag("Elevation"); pLayer.RemoveTag("LabelSize"); } } void StyleDlg::RefreshFields() { GetTextField()->Clear(); GetColorField()->Clear(); GetColorField()->Append(_("(none)")); m_type = GetFeatureGeomType(m_strResolved); m_strFeatureType = OGRGeometryTypeToName(m_type); if (m_Fields.LoadFieldInfoFromDBF(m_strResolved)) { int i, num = m_Fields.GetNumFields(); for (i = 0; i < num; i++) { Field *field = m_Fields.GetField(i); wxString2 field_name = field->m_name; GetTextField()->Append(field_name); GetColorField()->Append(field_name); } if (num) { if (m_iTextField < 0) m_iTextField = 0; if (m_iTextField > num-1) m_iTextField = num-1; if (m_iColorField < 0) m_iColorField = 0; if (m_iColorField > num-1) m_iColorField = num-1; } } } void StyleDlg::UpdateEnabling() { GetGeomColor()->Enable(m_bGeometry); GetLabelColor()->Enable(m_bTextLabels); GetTextField()->Enable(m_bTextLabels); GetColorField()->Enable(m_bTextLabels && m_Fields.GetNumFields() > 1); GetLabelSize()->Enable(m_bTextLabels); GetLabelHeight()->Enable(m_bTextLabels); } void StyleDlg::UpdateColorButtons() { FillWithColor(GetGeomColor(), m_GeomColor); FillWithColor(GetLabelColor(), m_LabelColor); } RGBi StyleDlg::AskColor(const RGBi &input) { m_Colour.Set(input.r, input.g, input.b); m_ColourData.SetChooseFull(true); m_ColourData.SetColour(m_Colour); wxColourDialog dlg(this, &m_ColourData); if (dlg.ShowModal() == wxID_OK) { m_ColourData = dlg.GetColourData(); m_Colour = m_ColourData.GetColour(); return RGBi(m_Colour.Red(), m_Colour.Green(), m_Colour.Blue()); } else return RGBi(-1,-1,-1); } // WDR: handler implementations for StyleDlg void StyleDlg::OnCheck( wxCommandEvent &event ) { TransferDataFromWindow(); UpdateEnabling(); } void StyleDlg::OnGeomColor( wxCommandEvent &event ) { RGBi result = AskColor(m_GeomColor); if (result.r == -1) return; m_GeomColor = result; UpdateColorButtons(); } void StyleDlg::OnLabelColor( wxCommandEvent &event ) { RGBi result = AskColor(m_LabelColor); if (result.r == -1) return; m_LabelColor = result; UpdateColorButtons(); } <commit_msg>suppress 'creating' warning on adding elements<commit_after>// // Name: StyleDlg.cpp // // Copyright (c) 2004 Virtual Terrain Project. // Free for all uses, see license.txt for details. // #ifdef __GNUG__ #pragma implementation "StyleDlg.cpp" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #include "wx/colordlg.h" #include "StyleDlg.h" #include "vtlib/vtlib.h" #include "vtlib/core/TerrainScene.h" #include "vtdata/Features.h" #include "vtui/wxString2.h" #include "vtui/Helper.h" // WDR: class implementations //---------------------------------------------------------------------------- // StyleDlg //---------------------------------------------------------------------------- // WDR: event table for StyleDlg BEGIN_EVENT_TABLE(StyleDlg,AutoDialog) EVT_INIT_DIALOG (StyleDlg::OnInitDialog) EVT_BUTTON( ID_GEOM_COLOR, StyleDlg::OnGeomColor ) EVT_BUTTON( ID_LABEL_COLOR, StyleDlg::OnLabelColor ) EVT_CHECKBOX( ID_GEOMETRY, StyleDlg::OnCheck ) EVT_CHECKBOX( ID_TEXT_LABELS, StyleDlg::OnCheck ) END_EVENT_TABLE() StyleDlg::StyleDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : AutoDialog( parent, id, title, position, size, style ) { // WDR: dialog function StyleDialogFunc for StyleDlg StyleDialogFunc( this, TRUE ); m_bGeometry = true; m_GeomColor.Set(255,255,255); m_bTextLabels = false; m_LabelColor.Set(255,255,255); m_iTextField = 0; m_iColorField = 0; m_fLabelHeight = 0.0f; m_fLabelSize = 0.0f; AddValidator(ID_FEATURE_TYPE, &m_strFeatureType); AddValidator(ID_GEOMETRY, &m_bGeometry); AddValidator(ID_TEXT_LABELS, &m_bTextLabels); AddValidator(ID_TEXT_FIELD, &m_iTextField); AddValidator(ID_COLOR_FIELD, &m_iColorField); AddNumValidator(ID_LABEL_HEIGHT, &m_fLabelHeight); AddNumValidator(ID_LABEL_SIZE, &m_fLabelSize); } void StyleDlg::OnInitDialog(wxInitDialogEvent& event) { RefreshFields(); UpdateEnabling(); UpdateColorButtons(); wxDialog::OnInitDialog(event); } void StyleDlg::SetOptions(vtStringArray &datapaths, const vtTagArray &Layer) { // for our purposes, we need the actual file location m_strFilename = Layer.GetValueString("Filename"); m_bGeometry = Layer.GetValueBool("Geometry"); if (!Layer.GetValueRGBi("GeomColor", m_GeomColor)) m_GeomColor.Set(255,255,255); m_bTextLabels = Layer.GetValueBool("Labels"); if (!Layer.GetValueRGBi("LabelColor", m_LabelColor)) m_LabelColor.Set(255,255,255); if (!Layer.GetValueInt("TextFieldIndex", m_iTextField)) m_iTextField = -1; if (!Layer.GetValueInt("ColorFieldIndex", m_iColorField)) m_iColorField = -1; if (!Layer.GetValueFloat("Elevation", m_fLabelHeight)) m_fLabelHeight= 0; if (!Layer.GetValueFloat("LabelSize", m_fLabelSize)) m_fLabelSize = 20; m_strResolved = m_strFilename; m_strResolved = FindFileOnPaths(datapaths, m_strResolved); if (m_strResolved == "") { vtString path = "PointData/"; m_strResolved = path + m_strFilename; m_strResolved = FindFileOnPaths(datapaths, m_strResolved); } } void StyleDlg::GetOptions(vtTagArray &pLayer) { pLayer.SetValueBool("Geometry", m_bGeometry, true); if (m_bGeometry) pLayer.SetValueRGBi("GeomColor", m_GeomColor, true); else pLayer.RemoveTag("GeomColor"); pLayer.SetValueBool("Labels", m_bTextLabels, true); if (m_bTextLabels) { pLayer.SetValueRGBi("LabelColor", m_LabelColor, true); pLayer.SetValueBool("TextFieldIndex", m_bTextLabels, true); pLayer.SetValueInt("ColorFieldIndex", m_iColorField, true); pLayer.SetValueFloat("Elevation", m_fLabelHeight, true); pLayer.SetValueFloat("LabelSize", m_fLabelSize, true); } else { pLayer.RemoveTag("LabelColor"); pLayer.RemoveTag("TextFieldIndex"); pLayer.RemoveTag("ColorFieldIndex"); pLayer.RemoveTag("Elevation"); pLayer.RemoveTag("LabelSize"); } } void StyleDlg::RefreshFields() { GetTextField()->Clear(); GetColorField()->Clear(); GetColorField()->Append(_("(none)")); m_type = GetFeatureGeomType(m_strResolved); m_strFeatureType = OGRGeometryTypeToName(m_type); if (m_Fields.LoadFieldInfoFromDBF(m_strResolved)) { int i, num = m_Fields.GetNumFields(); for (i = 0; i < num; i++) { Field *field = m_Fields.GetField(i); wxString2 field_name = field->m_name; GetTextField()->Append(field_name); GetColorField()->Append(field_name); } if (num) { if (m_iTextField < 0) m_iTextField = 0; if (m_iTextField > num-1) m_iTextField = num-1; if (m_iColorField < 0) m_iColorField = 0; if (m_iColorField > num-1) m_iColorField = num-1; } } } void StyleDlg::UpdateEnabling() { GetGeomColor()->Enable(m_bGeometry); GetLabelColor()->Enable(m_bTextLabels); GetTextField()->Enable(m_bTextLabels); GetColorField()->Enable(m_bTextLabels && m_Fields.GetNumFields() > 1); GetLabelSize()->Enable(m_bTextLabels); GetLabelHeight()->Enable(m_bTextLabels); } void StyleDlg::UpdateColorButtons() { FillWithColor(GetGeomColor(), m_GeomColor); FillWithColor(GetLabelColor(), m_LabelColor); } RGBi StyleDlg::AskColor(const RGBi &input) { m_Colour.Set(input.r, input.g, input.b); m_ColourData.SetChooseFull(true); m_ColourData.SetColour(m_Colour); wxColourDialog dlg(this, &m_ColourData); if (dlg.ShowModal() == wxID_OK) { m_ColourData = dlg.GetColourData(); m_Colour = m_ColourData.GetColour(); return RGBi(m_Colour.Red(), m_Colour.Green(), m_Colour.Blue()); } else return RGBi(-1,-1,-1); } // WDR: handler implementations for StyleDlg void StyleDlg::OnCheck( wxCommandEvent &event ) { TransferDataFromWindow(); UpdateEnabling(); } void StyleDlg::OnGeomColor( wxCommandEvent &event ) { RGBi result = AskColor(m_GeomColor); if (result.r == -1) return; m_GeomColor = result; UpdateColorButtons(); } void StyleDlg::OnLabelColor( wxCommandEvent &event ) { RGBi result = AskColor(m_LabelColor); if (result.r == -1) return; m_LabelColor = result; UpdateColorButtons(); } <|endoftext|>
<commit_before>// Copyright (c) 2016 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions 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 materialsprovided 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 <assert.h> #include <errno.h> #include <poll.h> #include <sys/epoll.h> #include "../../basic/TTypes.h" #include "../../basic/TLogging.h" #include "../TChannel.h" #include "TAsyncPollerLinux.h" namespace tyr { namespace net { static_assert(EPOLLIN == POLLIN, "`epoll` uses same flag values as `poll`"); static_assert(EPOLLPRI == POLLPRI, "`epoll` uses same flag values as `poll`"); static_assert(EPOLLOUT == POLLOUT, "`epoll` uses same flag values as `poll`"); static_assert(EPOLLRDHUP == POLLRDHUP, "`epoll` uses same flag values as `poll`"); static_assert(EPOLLERR == POLLERR, "`epoll` uses same flag values as `poll`"); static_assert(EPOLLHUP == POLLHUP, "`epoll` uses same flag values as `poll`"); AsyncPoller::AsyncPoller(EventLoop* loop) : Poller(loop) , epollfd_(epoll_create1(EPOLL_CLOEXEC)) , epoll_events_(kInitNumEvents) { if (epollfd_ < 0) TYRLOG_SYSFATAL << "AsyncPoller::AsyncPoller"; } AsyncPoller::~AsyncPoller(void) { close(epollfd_); } basic::Timestamp AsyncPoller::poll(int timeout, std::vector<Channel*>* active_channels) { TYRLOG_TRACE << "AsyncPoller::poll - fd total count " << channels_.size(); int events_count = static_cast<int>(epoll_events_.size()); int num_events = epoll_wait(epollfd_, &*epoll_events_.begin(), events_count, timeout); int saved_errno = errno; if (num_events > 0) { TYRLOG_TRACE << "AsyncPoller::poll - " << num_events << " events happened"; fill_active_channels(num_events, active_channels); if (num_events == events_count) epoll_events_.resize(events_count * 2); } else if (num_events == 0) { TYRLOG_TRACE << "AsyncPoller::poll - nothing happened"; } else { if (saved_errno != EINTR) { errno = saved_errno; TYRLOG_SYSERR << "AsyncPoller::poll - errno=" << saved_errno; } } return basic::Timestamp::now(); } void AsyncPoller::update_channel(Channel* channel) { assert_in_loopthread(); int fd = channel->get_fd(); const int index = channel->get_index(); TYRLOG_TRACE << "AsyncPoller::update_channel - fd=" << fd << " index=" << index << " events=" << channel->get_events(); if (index == POLLER_EVENT_NEW || index == POLLER_EVENT_DEL) { if (index == POLLER_EVENT_NEW) { assert(channels_.find(fd) == channels_.end()); channels_[fd] = channel; } else { assert(channels_.find(fd) != channels_.end()); assert(channels_[fd] == channel); } channel->set_index(POLLER_EVENT_ADD); update(EPOLL_CTL_ADD, channel); } else { assert(channels_.find(fd) != channels_.end()); assert(channels_[fd] == channel); assert(index == POLLER_EVENT_ADD); if (channel->is_none_event()) { update(EPOLL_CTL_DEL, channel); channel->set_index(POLLER_EVENT_DEL); } else { update(EPOLL_CTL_MOD, channel); } } } void AsyncPoller::remove_channel(Channel* channel) { assert_in_loopthread(); int fd = channel->get_fd(); const int index = channel->get_index(); TYRLOG_TRACE << "AsyncPoller::remove_channel - fd=" << fd; assert(channels_.find(fd) != channels_.end()); assert(channels_[fd] == channel); assert(channel->is_none_event()); assert(index == POLLER_EVENT_ADD || index == POLLER_EVENT_DEL); size_t n = channels_.erase(fd); assert(n == 1); UNUSED(n); if (index == POLLER_EVENT_ADD) update(EPOLL_CTL_DEL, channel); channel->set_index(POLLER_EVENT_NEW); } const char* AsyncPoller::operation_to_string(int op) { switch (op) { case EPOLL_CTL_ADD: return "ADD"; case EPOLL_CTL_DEL: return "DEL"; case EPOLL_CTL_MOD: return "MOD"; default: return "Unknown Operation"; } } void AsyncPoller::update(int operation, Channel* channel) { int fd = channel->get_fd(); TYRLOG_TRACE << "AsyncPoller::update - epoll_ctl op=" << operation_to_string(operation) << " fd=" << fd << " event={" << channel->events_to_string() << "}"; struct epoll_event event = {0}; event.events = channel->get_events(); event.data.ptr = channel; if (epoll_ctl(epollfd_, operation, fd, &event) < 0) { if (operation == EPOLL_CTL_DEL) TYRLOG_SYSERR << "AsyncPoller::update - epoll_ctl op=" << operation_to_string(operation) << " fd=" << fd; else TYRLOG_SYSFATAL << "AsyncPoller::update - epoll_ctl op=" << operation_to_string(operation) << " fd=" << fd; } } void AsyncPoller::fill_active_channels(int nevents, std::vector<Channel*>* active_channels) const { assert(basic::implicit_cast<size_t>(nevents) <= epoll_events_.size()); for (auto i = 0; i < num_events; ++i) { Channel* channel = static_cast<Channel*>(epoll_events_[i].data.ptr); channel->set_revents(epoll_events_[i].events); active_channels->push_back(channel); } } }} <commit_msg>:penguin: fix(epoll): fixed async-poller with epoll for linux<commit_after>// Copyright (c) 2016 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions 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 materialsprovided 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 <assert.h> #include <errno.h> #include <poll.h> #include <sys/epoll.h> #include <unistd.h> #include "../../basic/TTypes.h" #include "../../basic/TLogging.h" #include "../TChannel.h" #include "TAsyncPollerLinux.h" namespace tyr { namespace net { static_assert(EPOLLIN == POLLIN, "`epoll` uses same flag values as `poll`"); static_assert(EPOLLPRI == POLLPRI, "`epoll` uses same flag values as `poll`"); static_assert(EPOLLOUT == POLLOUT, "`epoll` uses same flag values as `poll`"); static_assert(EPOLLRDHUP == POLLRDHUP, "`epoll` uses same flag values as `poll`"); static_assert(EPOLLERR == POLLERR, "`epoll` uses same flag values as `poll`"); static_assert(EPOLLHUP == POLLHUP, "`epoll` uses same flag values as `poll`"); AsyncPoller::AsyncPoller(EventLoop* loop) : Poller(loop) , epollfd_(epoll_create1(EPOLL_CLOEXEC)) , epoll_events_(kInitNumEvents) { if (epollfd_ < 0) TYRLOG_SYSFATAL << "AsyncPoller::AsyncPoller"; } AsyncPoller::~AsyncPoller(void) { close(epollfd_); } basic::Timestamp AsyncPoller::poll(int timeout, std::vector<Channel*>* active_channels) { TYRLOG_TRACE << "AsyncPoller::poll - fd total count " << channels_.size(); int events_count = static_cast<int>(epoll_events_.size()); int num_events = epoll_wait(epollfd_, &*epoll_events_.begin(), events_count, timeout); int saved_errno = errno; if (num_events > 0) { TYRLOG_TRACE << "AsyncPoller::poll - " << num_events << " events happened"; fill_active_channels(num_events, active_channels); if (num_events == events_count) epoll_events_.resize(events_count * 2); } else if (num_events == 0) { TYRLOG_TRACE << "AsyncPoller::poll - nothing happened"; } else { if (saved_errno != EINTR) { errno = saved_errno; TYRLOG_SYSERR << "AsyncPoller::poll - errno=" << saved_errno; } } return basic::Timestamp::now(); } void AsyncPoller::update_channel(Channel* channel) { assert_in_loopthread(); int fd = channel->get_fd(); const int index = channel->get_index(); TYRLOG_TRACE << "AsyncPoller::update_channel - fd=" << fd << " index=" << index << " events=" << channel->get_events(); if (index == POLLER_EVENT_NEW || index == POLLER_EVENT_DEL) { if (index == POLLER_EVENT_NEW) { assert(channels_.find(fd) == channels_.end()); channels_[fd] = channel; } else { assert(channels_.find(fd) != channels_.end()); assert(channels_[fd] == channel); } channel->set_index(POLLER_EVENT_ADD); update(EPOLL_CTL_ADD, channel); } else { assert(channels_.find(fd) != channels_.end()); assert(channels_[fd] == channel); assert(index == POLLER_EVENT_ADD); if (channel->is_none_event()) { update(EPOLL_CTL_DEL, channel); channel->set_index(POLLER_EVENT_DEL); } else { update(EPOLL_CTL_MOD, channel); } } } void AsyncPoller::remove_channel(Channel* channel) { assert_in_loopthread(); int fd = channel->get_fd(); const int index = channel->get_index(); TYRLOG_TRACE << "AsyncPoller::remove_channel - fd=" << fd; assert(channels_.find(fd) != channels_.end()); assert(channels_[fd] == channel); assert(channel->is_none_event()); assert(index == POLLER_EVENT_ADD || index == POLLER_EVENT_DEL); size_t n = channels_.erase(fd); assert(n == 1); UNUSED(n); if (index == POLLER_EVENT_ADD) update(EPOLL_CTL_DEL, channel); channel->set_index(POLLER_EVENT_NEW); } const char* AsyncPoller::operation_to_string(int op) { switch (op) { case EPOLL_CTL_ADD: return "ADD"; case EPOLL_CTL_DEL: return "DEL"; case EPOLL_CTL_MOD: return "MOD"; default: return "Unknown Operation"; } } void AsyncPoller::update(int operation, Channel* channel) { int fd = channel->get_fd(); TYRLOG_TRACE << "AsyncPoller::update - epoll_ctl op=" << operation_to_string(operation) << " fd=" << fd << " event={" << channel->events_to_string() << "}"; struct epoll_event event{}; event.events = channel->get_events(); event.data.ptr = channel; if (epoll_ctl(epollfd_, operation, fd, &event) < 0) { if (operation == EPOLL_CTL_DEL) TYRLOG_SYSERR << "AsyncPoller::update - epoll_ctl op=" << operation_to_string(operation) << " fd=" << fd; else TYRLOG_SYSFATAL << "AsyncPoller::update - epoll_ctl op=" << operation_to_string(operation) << " fd=" << fd; } } void AsyncPoller::fill_active_channels(int nevents, std::vector<Channel*>* active_channels) const { assert(basic::implicit_cast<size_t>(nevents) <= epoll_events_.size()); for (auto i = 0; i < nevents; ++i) { Channel* channel = static_cast<Channel*>(epoll_events_[i].data.ptr); channel->set_revents(epoll_events_[i].events); active_channels->push_back(channel); } } }} <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2010 Digital Bazaar, Inc. All rights reserved. */ #include "bitmunk/eventreactor/DefaultObserverContainer.h" #include "bitmunk/common/Logging.h" #include "monarch/event/ObserverDelegate.h" #include <algorithm> using namespace std; using namespace monarch::event; using namespace monarch::rt; using namespace bitmunk::common; using namespace bitmunk::protocol; using namespace bitmunk::node; using namespace bitmunk::eventreactor; DefaultObserverContainer::DefaultObserverContainer( Node* node, EventReactor* er) : mNode(node), mEventReactor(er) { } DefaultObserverContainer::~DefaultObserverContainer() { // remove all observer lists for(UserObserverMap::iterator i = mUserObserverMap.begin(); i != mUserObserverMap.end(); i++) { i->second->unregisterFrom(mNode->getEventController()); delete i->second; } mUserObserverMap.clear(); } void DefaultObserverContainer::registerUser(UserId userId) { mUserObserverMapLock.lock(); { if(mUserObserverMap.empty()) { // register to receive logged out events mLogoutObserver = new ObserverDelegate<DefaultObserverContainer>( this, &DefaultObserverContainer::userLoggedOut); mNode->getEventController()->registerObserver( &(*mLogoutObserver), "bitmunk.common.User.loggedOut"); } // only register user if observer list doesn't already exist, // else assume user is registered and return UserObserverMap::iterator i = mUserObserverMap.find(userId); if(i == mUserObserverMap.end()) { mUserObserverMap.insert(make_pair(userId, new ObserverList())); mEventReactor->addUser(userId); } } mUserObserverMapLock.unlock(); } bool DefaultObserverContainer::unregisterUser(UserId userId) { bool rval; mUserObserverMapLock.lock(); { // remove user mEventReactor->removeUser(userId); // remove all observers for user ID and unregister user rval = removeObservers(userId, true); if(mUserObserverMap.empty()) { // unregister handling logged out events mNode->getEventController()->unregisterObserver(&(*mLogoutObserver)); mLogoutObserver.setNull(); } } mUserObserverMapLock.unlock(); return rval; } void DefaultObserverContainer::userLoggedOut(Event& e) { // unregister user unregisterUser(BM_USER_ID(e["details"]["userId"])); } void DefaultObserverContainer::addObserver(UserId userId, ObserverRef& ob) { // only add observer if observer list exists UserObserverMap::iterator i = mUserObserverMap.find(userId); if(i != mUserObserverMap.end()) { i->second->add(ob); } } bool DefaultObserverContainer::removeObservers(UserId userId, bool unregister) { bool rval = false; UserObserverMap::iterator i = mUserObserverMap.find(userId); if(i != mUserObserverMap.end()) { rval = true; ObserverList* list = i->second; list->unregisterFrom(mNode->getEventController()); if(unregister) { // unregistering user, so erase list mUserObserverMap.erase(i); delete list; } else { // simply clear list list->clear(); } } return rval; } <commit_msg>Reused unregister user code when destructing observer container. This also ensures that user logged out observer is unregistered.<commit_after>/* * Copyright (c) 2008-2010 Digital Bazaar, Inc. All rights reserved. */ #include "bitmunk/eventreactor/DefaultObserverContainer.h" #include "bitmunk/common/Logging.h" #include "monarch/event/ObserverDelegate.h" #include <algorithm> using namespace std; using namespace monarch::event; using namespace monarch::rt; using namespace bitmunk::common; using namespace bitmunk::protocol; using namespace bitmunk::node; using namespace bitmunk::eventreactor; DefaultObserverContainer::DefaultObserverContainer( Node* node, EventReactor* er) : mNode(node), mEventReactor(er) { } DefaultObserverContainer::~DefaultObserverContainer() { // force unregister all users mUserObserverMapLock.lock(); while(!mUserObserverMap.empty()) { unregisterUser(mUserObserverMap.begin()->first); } mUserObserverMapLock.unlock(); } void DefaultObserverContainer::registerUser(UserId userId) { mUserObserverMapLock.lock(); { if(mUserObserverMap.empty()) { // register to receive logged out events mLogoutObserver = new ObserverDelegate<DefaultObserverContainer>( this, &DefaultObserverContainer::userLoggedOut); mNode->getEventController()->registerObserver( &(*mLogoutObserver), "bitmunk.common.User.loggedOut"); } // only register user if observer list doesn't already exist, // else assume user is registered and return UserObserverMap::iterator i = mUserObserverMap.find(userId); if(i == mUserObserverMap.end()) { mUserObserverMap.insert(make_pair(userId, new ObserverList())); mEventReactor->addUser(userId); } } mUserObserverMapLock.unlock(); } bool DefaultObserverContainer::unregisterUser(UserId userId) { bool rval; mUserObserverMapLock.lock(); { // remove user mEventReactor->removeUser(userId); // remove all observers for user ID and unregister user rval = removeObservers(userId, true); if(mUserObserverMap.empty()) { // unregister handling logged out events mNode->getEventController()->unregisterObserver(&(*mLogoutObserver)); mLogoutObserver.setNull(); } } mUserObserverMapLock.unlock(); return rval; } void DefaultObserverContainer::userLoggedOut(Event& e) { // unregister user unregisterUser(BM_USER_ID(e["details"]["userId"])); } void DefaultObserverContainer::addObserver(UserId userId, ObserverRef& ob) { // only add observer if observer list exists UserObserverMap::iterator i = mUserObserverMap.find(userId); if(i != mUserObserverMap.end()) { i->second->add(ob); } } bool DefaultObserverContainer::removeObservers(UserId userId, bool unregister) { bool rval = false; UserObserverMap::iterator i = mUserObserverMap.find(userId); if(i != mUserObserverMap.end()) { rval = true; ObserverList* list = i->second; list->unregisterFrom(mNode->getEventController()); if(unregister) { // unregistering user, so erase list mUserObserverMap.erase(i); delete list; } else { // simply clear list list->clear(); } } return rval; } <|endoftext|>
<commit_before>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <stdlib.h> #include <vpr/Util/Assert.h> #include <vpr/Util/Debug.h> #include <vpr/md/POSIX/DynLoad/LibraryUNIX.h> namespace vpr { vpr::ReturnStatus LibraryUNIX::load() { vpr::ReturnStatus status; if ( std::string("") != mName ) { mLibrary = dlopen(mName.c_str(), RTLD_NOW | RTLD_GLOBAL); } else { mLibrary = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL); } if ( NULL == mLibrary ) { vprDEBUG_CONT(vprDBG_ALL, vprDBG_WARNING_LVL) << std::endl << vprDEBUG_FLUSH; vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << clrOutNORM(clrYELLOW, "WARNING:") << " Could not load '" << mName << "'\n" << vprDEBUG_FLUSH; vprDEBUG_NEXT(vprDBG_ALL, vprDBG_WARNING_LVL) << dlerror() << std::endl << vprDEBUG_FLUSH; status.setCode(vpr::ReturnStatus::Fail); } return status; } vpr::ReturnStatus LibraryUNIX::unload() { vprASSERT(mLibrary != NULL && "No library to unload"); vpr::ReturnStatus status; if ( dlclose(mLibrary) != 0 ) { status.setCode(vpr::ReturnStatus::Fail); } else { mLibrary = NULL; } return status; } void* LibraryUNIX::findSymbolAndLibrary(const char* symbolName, LibraryUNIX& lib) { boost::ignore_unused_variable_warning(symbolName); boost::ignore_unused_variable_warning(lib); vprASSERT(false && "Not implemented yet"); return NULL; } } // End of vpr namespace <commit_msg>Added a missing #include.<commit_after>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <stdlib.h> #include <boost/concept_check.hpp> #include <vpr/Util/Assert.h> #include <vpr/Util/Debug.h> #include <vpr/md/POSIX/DynLoad/LibraryUNIX.h> namespace vpr { vpr::ReturnStatus LibraryUNIX::load() { vpr::ReturnStatus status; if ( std::string("") != mName ) { mLibrary = dlopen(mName.c_str(), RTLD_NOW | RTLD_GLOBAL); } else { mLibrary = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL); } if ( NULL == mLibrary ) { vprDEBUG_CONT(vprDBG_ALL, vprDBG_WARNING_LVL) << std::endl << vprDEBUG_FLUSH; vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << clrOutNORM(clrYELLOW, "WARNING:") << " Could not load '" << mName << "'\n" << vprDEBUG_FLUSH; vprDEBUG_NEXT(vprDBG_ALL, vprDBG_WARNING_LVL) << dlerror() << std::endl << vprDEBUG_FLUSH; status.setCode(vpr::ReturnStatus::Fail); } return status; } vpr::ReturnStatus LibraryUNIX::unload() { vprASSERT(mLibrary != NULL && "No library to unload"); vpr::ReturnStatus status; if ( dlclose(mLibrary) != 0 ) { status.setCode(vpr::ReturnStatus::Fail); } else { mLibrary = NULL; } return status; } void* LibraryUNIX::findSymbolAndLibrary(const char* symbolName, LibraryUNIX& lib) { boost::ignore_unused_variable_warning(symbolName); boost::ignore_unused_variable_warning(lib); vprASSERT(false && "Not implemented yet"); return NULL; } } // End of vpr namespace <|endoftext|>
<commit_before>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <string.h> #include <errno.h> #include <vpr/md/POSIX/Util/ErrorImplPosix.h> namespace vpr { void ErrorImplPosix::outputCurrentError (std::ostream& out, const std::string& prefix) { extern int errno; const char* err_str = strerror(errno); out << "Error (POSIX): " << prefix << " (" << errno; if ( err_str != NULL ) { out << ", " << err_str; } out << ")" << std::endl; } } <commit_msg>Fixed linking error.<commit_after>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <string.h> #include <errno.h> #include <vpr/md/POSIX/Util/ErrorImplPosix.h> extern int errno; namespace vpr { void ErrorImplPosix::outputCurrentError (std::ostream& out, const std::string& prefix) { const char* err_str = strerror(errno); out << "Error (POSIX): " << prefix << " (" << errno; if ( err_str != NULL ) { out << ", " << err_str; } out << ")" << std::endl; } } <|endoftext|>
<commit_before>/* -*- mode: C++; c-file-style: "gnu" -*- gnupgprocessbase.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Libkleopatra 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "gnupgprocessbase.h" #include <kdebug.h> #include <qsocketnotifier.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <assert.h> struct Kleo::GnuPGProcessBase::Private { Private() : useStatusFD( false ), statnot( 0 ) { statusFD[0] = statusFD[1] = -1; } bool useStatusFD; int statusFD[2]; QSocketNotifier * statnot; }; Kleo::GnuPGProcessBase::GnuPGProcessBase( QObject * parent, const char * name ) : KProcess( parent, name ) { d = new Private(); } Kleo::GnuPGProcessBase::~GnuPGProcessBase() { delete d; d = 0; } void Kleo::GnuPGProcessBase::setUseStatusFD( bool use ) { assert( d ); d->useStatusFD = use; } bool Kleo::GnuPGProcessBase::start( RunMode runmode, Communication comm ) { if ( d->useStatusFD ) { // set up the status-fd. This should be in setupCommunication(), // but then it's too late: we need the fd of the pipe to pass it // as argument to the --status-fd option: // PENDING(marc) find out why KProcess uses both pipe() and socketpair()... if ( ::pipe( d->statusFD ) < 0 ) { kdDebug( 5150 ) << "Kleo::GnuPGProcessBase::start: pipe(2) failed: " << perror << endl; return false; } ::fcntl( d->statusFD[0], F_SETFD, FD_CLOEXEC ); // don't ask me why we don't need this. // "gpgme doesn't do it and it doesn't work otherwise" would be my answer :) //::fcntl( d->statusFD[1], F_SETFD, FD_CLOEXEC ); if ( !arguments.empty() ) { QValueList<QCString>::iterator it = arguments.begin(); ++it; arguments.insert( it, "--status-fd" ); char buf[25]; sprintf( buf, "%d", d->statusFD[1] ); arguments.insert( it, buf ); arguments.insert( it, "--no-tty" ); //arguments.insert( it, "--enable-progress-filter" ); // gpgsm doesn't know this } } return KProcess::start( runmode, comm ); } int Kleo::GnuPGProcessBase::setupCommunication( Communication comm ) { if ( int ok = KProcess::setupCommunication( comm ) ) return ok; if ( d->useStatusFD ) { // base class impl returned error, so close our fd's, too ::close( d->statusFD[0] ); ::close( d->statusFD[1] ); d->statusFD[0] = d->statusFD[1] = -1; } return 0; // Error } int Kleo::GnuPGProcessBase::commSetupDoneP() { if ( d->useStatusFD ) { ::close( d->statusFD[1] ); // close the input end of the pipe, we're the reader d->statnot = new QSocketNotifier( d->statusFD[0], QSocketNotifier::Read, this ); connect( d->statnot, SIGNAL(activated(int)), SLOT(slotChildStatus(int)) ); } return KProcess::commSetupDoneP(); } int Kleo::GnuPGProcessBase::commSetupDoneC() { if ( d->useStatusFD ) ::close( d->statusFD[0] ); // close the output end of the pipe, we're the writer return KProcess::commSetupDoneC(); } void Kleo::GnuPGProcessBase::slotChildStatus( int fd ) { if ( !childStatus(fd) ) closeStatus(); } bool Kleo::GnuPGProcessBase::closeStatus() { if ( !d->useStatusFD ) return false; d->useStatusFD = false; delete d->statnot; d->statnot = 0; ::close( d->statusFD[0] ); d->statusFD[0] = -1; return true; } int Kleo::GnuPGProcessBase::childStatus( int fd ) { char buf[1024]; const int len = ::read( fd, buf, sizeof(buf)-1 ); if ( len > 0 ) { buf[len] = 0; // Just in case. emit receivedStatus( this, buf, len ); // fixme: parse it } return len; } void Kleo::GnuPGProcessBase::virtual_hook( int id, void * data ) { KProcess::virtual_hook( id, data ); } #include "gnupgprocessbase.moc" <commit_msg>safer (but untested, i wouldn't know how wihout spending a lot of time on it). hallo marc. ;)<commit_after>/* -*- mode: C++; c-file-style: "gnu" -*- gnupgprocessbase.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Libkleopatra 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "gnupgprocessbase.h" #include <kdebug.h> #include <qsocketnotifier.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <assert.h> struct Kleo::GnuPGProcessBase::Private { Private() : useStatusFD( false ), statnot( 0 ) { statusFD[0] = statusFD[1] = -1; } bool useStatusFD; int statusFD[2]; QSocketNotifier * statnot; }; Kleo::GnuPGProcessBase::GnuPGProcessBase( QObject * parent, const char * name ) : KProcess( parent, name ) { d = new Private(); } Kleo::GnuPGProcessBase::~GnuPGProcessBase() { delete d; d = 0; } void Kleo::GnuPGProcessBase::setUseStatusFD( bool use ) { assert( d ); d->useStatusFD = use; } bool Kleo::GnuPGProcessBase::start( RunMode runmode, Communication comm ) { if ( d->useStatusFD ) { // set up the status-fd. This should be in setupCommunication(), // but then it's too late: we need the fd of the pipe to pass it // as argument to the --status-fd option: // PENDING(marc) find out why KProcess uses both pipe() and socketpair()... if ( ::pipe( d->statusFD ) < 0 ) { kdDebug( 5150 ) << "Kleo::GnuPGProcessBase::start: pipe(2) failed: " << perror << endl; return false; } ::fcntl( d->statusFD[0], F_SETFD, FD_CLOEXEC ); ::fcntl( d->statusFD[1], F_SETFD, FD_CLOEXEC ); if ( !arguments.empty() ) { QValueList<QCString>::iterator it = arguments.begin(); ++it; arguments.insert( it, "--status-fd" ); char buf[25]; sprintf( buf, "%d", d->statusFD[1] ); arguments.insert( it, buf ); arguments.insert( it, "--no-tty" ); //arguments.insert( it, "--enable-progress-filter" ); // gpgsm doesn't know this } } return KProcess::start( runmode, comm ); } int Kleo::GnuPGProcessBase::setupCommunication( Communication comm ) { if ( int ok = KProcess::setupCommunication( comm ) ) return ok; if ( d->useStatusFD ) { // base class impl returned error, so close our fd's, too ::close( d->statusFD[0] ); ::close( d->statusFD[1] ); d->statusFD[0] = d->statusFD[1] = -1; } return 0; // Error } int Kleo::GnuPGProcessBase::commSetupDoneP() { if ( d->useStatusFD ) { ::close( d->statusFD[1] ); // close the input end of the pipe, we're the reader d->statnot = new QSocketNotifier( d->statusFD[0], QSocketNotifier::Read, this ); connect( d->statnot, SIGNAL(activated(int)), SLOT(slotChildStatus(int)) ); } return KProcess::commSetupDoneP(); } int Kleo::GnuPGProcessBase::commSetupDoneC() { if ( d->useStatusFD ) ::fcntl( d->statusFD[1], F_SETFD, 0 ); return KProcess::commSetupDoneC(); } void Kleo::GnuPGProcessBase::slotChildStatus( int fd ) { if ( !childStatus(fd) ) closeStatus(); } bool Kleo::GnuPGProcessBase::closeStatus() { if ( !d->useStatusFD ) return false; d->useStatusFD = false; delete d->statnot; d->statnot = 0; ::close( d->statusFD[0] ); d->statusFD[0] = -1; return true; } int Kleo::GnuPGProcessBase::childStatus( int fd ) { char buf[1024]; const int len = ::read( fd, buf, sizeof(buf)-1 ); if ( len > 0 ) { buf[len] = 0; // Just in case. emit receivedStatus( this, buf, len ); // fixme: parse it } return len; } void Kleo::GnuPGProcessBase::virtual_hook( int id, void * data ) { KProcess::virtual_hook( id, data ); } #include "gnupgprocessbase.moc" <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include "tp_RangeChooser.hxx" #include "Strings.hrc" #include "ResId.hxx" #include "macros.hxx" #include "DataSourceHelper.hxx" #include "DiagramHelper.hxx" #include "ChartTypeTemplateProvider.hxx" #include "DialogModel.hxx" #include "RangeSelectionHelper.hxx" #include <com/sun/star/awt/XTopWindow.hpp> #include <com/sun/star/embed/EmbedStates.hpp> #include <com/sun/star/embed/XComponentSupplier.hpp> namespace { void lcl_ShowChooserButton( PushButton& rChooserButton, bool bShow) { if( rChooserButton.IsVisible() != bShow ) { rChooserButton.Show( bShow ); } } void lcl_enableRangeChoosing( bool bEnable, Dialog * pDialog ) { if( pDialog ) { pDialog->Show( bEnable ? sal_False : sal_True ); pDialog->SetModalInputMode( bEnable ? sal_False : sal_True ); } } } // anonymous namespace namespace chart { using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; RangeChooserTabPage::RangeChooserTabPage( Window* pParent , DialogModel & rDialogModel , ChartTypeTemplateProvider* pTemplateProvider , Dialog * pParentDialog , bool bHideDescription /* = false */ ) : OWizardPage( pParent ,"tp_RangeChooser" ,"modules/schart/ui/tp_RangeChooser.ui") , m_nChangingControlCalls(0) , m_bIsDirty(false) , m_xDataProvider( 0 ) , m_aLastValidRangeString() , m_xCurrentChartTypeTemplate(0) , m_pTemplateProvider(pTemplateProvider) , m_rDialogModel( rDialogModel ) , m_pParentDialog( pParentDialog ) , m_pTabPageNotifiable( dynamic_cast< TabPageNotifiable * >( pParentDialog )) { get(m_pFT_Caption, "FT_CAPTION_FOR_WIZARD"); get(m_pFT_Range, "FT_RANGE"); get(m_pED_Range, "ED_RANGE"); get(m_pIB_Range, "IB_RANGE"); get(m_pRB_Rows, "RB_DATAROWS"); get(m_pRB_Columns, "RB_DATACOLS"); get(m_pCB_FirstRowAsLabel, "CB_FIRST_ROW_ASLABELS"); get(m_pCB_FirstColumnAsLabel, "CB_FIRST_COLUMN_ASLABELS"); get(m_pFTTitle, "STR_PAGE_DATA_RANGE");// OH:remove later with dialog title m_pFT_Caption->Show(!bHideDescription); this->SetText( m_pFTTitle->GetText());// OH:remove later with dialog // set defaults as long as DetectArguments does not work m_pRB_Columns->Check(); m_pCB_FirstColumnAsLabel->Check(); m_pCB_FirstRowAsLabel->Check(); // BM: Note, that the range selection is not available, if there is no view. // This happens for charts having their own embedded spreadsheet. If you // force to get the range selection here, this would mean when entering this // page the calc view would be created in this case. So, I enable the // button here, and in the worst case nothing happens when it is pressed. // Not nice, but I see no better solution for the moment. m_pIB_Range->SetClickHdl( LINK( this, RangeChooserTabPage, ChooseRangeHdl )); // #i75179# enable setting the background to a different color m_pED_Range->SetStyle( m_pED_Range->GetStyle() | WB_FORCECTRLBACKGROUND ); m_pED_Range->SetUpdateDataHdl( LINK( this, RangeChooserTabPage, ControlChangedHdl )); m_pED_Range->SetModifyHdl( LINK( this, RangeChooserTabPage, ControlEditedHdl )); m_pRB_Rows->SetToggleHdl( LINK( this, RangeChooserTabPage, ControlChangedHdl ) ); m_pCB_FirstRowAsLabel->SetToggleHdl( LINK( this, RangeChooserTabPage, ControlChangedHdl ) ); m_pCB_FirstColumnAsLabel->SetToggleHdl( LINK( this, RangeChooserTabPage, ControlChangedHdl ) ); } RangeChooserTabPage::~RangeChooserTabPage() { } void RangeChooserTabPage::ActivatePage() { OWizardPage::ActivatePage(); initControlsFromModel(); } void RangeChooserTabPage::initControlsFromModel() { m_nChangingControlCalls++; if(m_pTemplateProvider) m_xCurrentChartTypeTemplate = m_pTemplateProvider->getCurrentTemplate(); bool bUseColumns = ! m_pRB_Rows->IsChecked(); bool bFirstCellAsLabel = bUseColumns ? m_pCB_FirstRowAsLabel->IsChecked() : m_pCB_FirstColumnAsLabel->IsChecked(); bool bHasCategories = bUseColumns ? m_pCB_FirstColumnAsLabel->IsChecked() : m_pCB_FirstRowAsLabel->IsChecked(); bool bIsValid = m_rDialogModel.allArgumentsForRectRangeDetected(); if( bIsValid ) m_rDialogModel.detectArguments(m_aLastValidRangeString, bUseColumns, bFirstCellAsLabel, bHasCategories ); else m_aLastValidRangeString = ""; m_pED_Range->SetText( m_aLastValidRangeString ); m_pRB_Rows->Check( !bUseColumns ); m_pRB_Columns->Check( bUseColumns ); m_pCB_FirstRowAsLabel->Check( m_pRB_Rows->IsChecked()?bHasCategories:bFirstCellAsLabel ); m_pCB_FirstColumnAsLabel->Check( m_pRB_Columns->IsChecked()?bHasCategories:bFirstCellAsLabel ); isValid(); m_nChangingControlCalls--; } void RangeChooserTabPage::DeactivatePage() { commitPage(); svt::OWizardPage::DeactivatePage(); } void RangeChooserTabPage::commitPage() { commitPage(::svt::WizardTypes::eFinish); } sal_Bool RangeChooserTabPage::commitPage( ::svt::WizardTypes::CommitPageReason /*eReason*/ ) { //ranges may have been edited in the meanwhile (dirty is true in that case here) if( isValid() ) { changeDialogModelAccordingToControls(); return sal_True;//return false if this page should not be left } else return sal_False; } void RangeChooserTabPage::changeDialogModelAccordingToControls() { if(m_nChangingControlCalls>0) return; if( !m_xCurrentChartTypeTemplate.is() ) { if(m_pTemplateProvider) m_xCurrentChartTypeTemplate.set( m_pTemplateProvider->getCurrentTemplate()); if( !m_xCurrentChartTypeTemplate.is()) { OSL_FAIL( "Need a template to change data source" ); return; } } if( m_bIsDirty ) { sal_Bool bFirstCellAsLabel = ( m_pCB_FirstColumnAsLabel->IsChecked() && !m_pRB_Columns->IsChecked() ) || ( m_pCB_FirstRowAsLabel->IsChecked() && !m_pRB_Rows->IsChecked() ); sal_Bool bHasCategories = ( m_pCB_FirstColumnAsLabel->IsChecked() && m_pRB_Columns->IsChecked() ) || ( m_pCB_FirstRowAsLabel->IsChecked() && m_pRB_Rows->IsChecked() ); Sequence< beans::PropertyValue > aArguments( DataSourceHelper::createArguments( m_pRB_Columns->IsChecked(), bFirstCellAsLabel, bHasCategories ) ); // only if range is valid if( m_aLastValidRangeString.equals(m_pED_Range->GetText())) { m_rDialogModel.setTemplate( m_xCurrentChartTypeTemplate ); aArguments.realloc( aArguments.getLength() + 1 ); aArguments[aArguments.getLength() - 1] = beans::PropertyValue( "CellRangeRepresentation" , -1, uno::makeAny( m_aLastValidRangeString ), beans::PropertyState_DIRECT_VALUE ); m_rDialogModel.setData( aArguments ); m_bIsDirty = false; } //@todo warn user that the selected range is not valid //@todo better: disable OK-Button if range is invalid } } bool RangeChooserTabPage::isValid() { OUString aRange( m_pED_Range->GetText()); sal_Bool bFirstCellAsLabel = ( m_pCB_FirstColumnAsLabel->IsChecked() && !m_pRB_Columns->IsChecked() ) || ( m_pCB_FirstRowAsLabel->IsChecked() && !m_pRB_Rows->IsChecked() ); sal_Bool bHasCategories = ( m_pCB_FirstColumnAsLabel->IsChecked() && m_pRB_Columns->IsChecked() ) || ( m_pCB_FirstRowAsLabel->IsChecked() && m_pRB_Rows->IsChecked() ); bool bIsValid = ( aRange.isEmpty() ) || m_rDialogModel.getRangeSelectionHelper()->verifyArguments( DataSourceHelper::createArguments( aRange, Sequence< sal_Int32 >(), m_pRB_Columns->IsChecked(), bFirstCellAsLabel, bHasCategories )); if( bIsValid ) { m_pED_Range->SetControlForeground(); m_pED_Range->SetControlBackground(); if( m_pTabPageNotifiable ) m_pTabPageNotifiable->setValidPage( this ); m_aLastValidRangeString = aRange; } else { m_pED_Range->SetControlBackground( RANGE_SELECTION_INVALID_RANGE_BACKGROUND_COLOR ); m_pED_Range->SetControlForeground( RANGE_SELECTION_INVALID_RANGE_FOREGROUND_COLOR ); if( m_pTabPageNotifiable ) m_pTabPageNotifiable->setInvalidPage( this ); } // enable/disable controls // #i79531# if the range is valid but an action of one of these buttons // would render it invalid, the button should be disabled if( bIsValid ) { bool bDataInColumns = m_pRB_Columns->IsChecked(); bool bIsSwappedRangeValid = m_rDialogModel.getRangeSelectionHelper()->verifyArguments( DataSourceHelper::createArguments( aRange, Sequence< sal_Int32 >(), ! bDataInColumns, bHasCategories, bFirstCellAsLabel )); m_pRB_Rows->Enable( bIsSwappedRangeValid ); m_pRB_Columns->Enable( bIsSwappedRangeValid ); m_pCB_FirstRowAsLabel->Enable( m_rDialogModel.getRangeSelectionHelper()->verifyArguments( DataSourceHelper::createArguments( aRange, Sequence< sal_Int32 >(), m_pRB_Columns->IsChecked(), bDataInColumns ? ! bFirstCellAsLabel : bFirstCellAsLabel, bDataInColumns ? bHasCategories : ! bHasCategories ))); m_pCB_FirstColumnAsLabel->Enable( m_rDialogModel.getRangeSelectionHelper()->verifyArguments( DataSourceHelper::createArguments( aRange, Sequence< sal_Int32 >(), m_pRB_Columns->IsChecked(), bDataInColumns ? bFirstCellAsLabel : ! bFirstCellAsLabel, bDataInColumns ? ! bHasCategories : bHasCategories ))); } else { m_pRB_Rows->Enable( bIsValid ); m_pRB_Columns->Enable( bIsValid ); m_pCB_FirstRowAsLabel->Enable( bIsValid ); m_pCB_FirstColumnAsLabel->Enable( bIsValid ); } bool bShowIB = m_rDialogModel.getRangeSelectionHelper()->hasRangeSelection(); lcl_ShowChooserButton( *m_pIB_Range, bShowIB ); return bIsValid; } IMPL_LINK_NOARG(RangeChooserTabPage, ControlEditedHdl) { setDirty(); isValid(); return 0; } IMPL_LINK_NOARG(RangeChooserTabPage, ControlChangedHdl) { setDirty(); if( isValid()) changeDialogModelAccordingToControls(); return 0; } IMPL_LINK_NOARG(RangeChooserTabPage, ChooseRangeHdl) { OUString aRange = m_pED_Range->GetText(); // using assignment for broken gcc 3.3 OUString aTitle = m_pFTTitle->GetText(); lcl_enableRangeChoosing( true, m_pParentDialog ); m_rDialogModel.getRangeSelectionHelper()->chooseRange( aRange, aTitle, *this ); return 0; } void RangeChooserTabPage::listeningFinished( const OUString & rNewRange ) { //user has selected a new range OUString aRange( rNewRange ); m_rDialogModel.startControllerLockTimer(); // stop listening m_rDialogModel.getRangeSelectionHelper()->stopRangeListening(); //update dialog state ToTop(); GrabFocus(); m_pED_Range->SetText( aRange ); m_pED_Range->GrabFocus(); setDirty(); if( isValid()) changeDialogModelAccordingToControls(); lcl_enableRangeChoosing( false, m_pParentDialog ); } void RangeChooserTabPage::disposingRangeSelection() { m_rDialogModel.getRangeSelectionHelper()->stopRangeListening( false ); } void RangeChooserTabPage::setDirty() { if( m_nChangingControlCalls == 0 ) m_bIsDirty = true; } } //namespace chart /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>WaE: C4805: '!=' : unsafe mix of type 'sal_Bool' and type 'bool' in operation<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include "tp_RangeChooser.hxx" #include "Strings.hrc" #include "ResId.hxx" #include "macros.hxx" #include "DataSourceHelper.hxx" #include "DiagramHelper.hxx" #include "ChartTypeTemplateProvider.hxx" #include "DialogModel.hxx" #include "RangeSelectionHelper.hxx" #include <com/sun/star/awt/XTopWindow.hpp> #include <com/sun/star/embed/EmbedStates.hpp> #include <com/sun/star/embed/XComponentSupplier.hpp> namespace { void lcl_ShowChooserButton( PushButton& rChooserButton, bool bShow) { if( rChooserButton.IsVisible() != (sal_Bool) bShow ) { rChooserButton.Show( bShow ); } } void lcl_enableRangeChoosing( bool bEnable, Dialog * pDialog ) { if( pDialog ) { pDialog->Show( bEnable ? sal_False : sal_True ); pDialog->SetModalInputMode( bEnable ? sal_False : sal_True ); } } } // anonymous namespace namespace chart { using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; RangeChooserTabPage::RangeChooserTabPage( Window* pParent , DialogModel & rDialogModel , ChartTypeTemplateProvider* pTemplateProvider , Dialog * pParentDialog , bool bHideDescription /* = false */ ) : OWizardPage( pParent ,"tp_RangeChooser" ,"modules/schart/ui/tp_RangeChooser.ui") , m_nChangingControlCalls(0) , m_bIsDirty(false) , m_xDataProvider( 0 ) , m_aLastValidRangeString() , m_xCurrentChartTypeTemplate(0) , m_pTemplateProvider(pTemplateProvider) , m_rDialogModel( rDialogModel ) , m_pParentDialog( pParentDialog ) , m_pTabPageNotifiable( dynamic_cast< TabPageNotifiable * >( pParentDialog )) { get(m_pFT_Caption, "FT_CAPTION_FOR_WIZARD"); get(m_pFT_Range, "FT_RANGE"); get(m_pED_Range, "ED_RANGE"); get(m_pIB_Range, "IB_RANGE"); get(m_pRB_Rows, "RB_DATAROWS"); get(m_pRB_Columns, "RB_DATACOLS"); get(m_pCB_FirstRowAsLabel, "CB_FIRST_ROW_ASLABELS"); get(m_pCB_FirstColumnAsLabel, "CB_FIRST_COLUMN_ASLABELS"); get(m_pFTTitle, "STR_PAGE_DATA_RANGE");// OH:remove later with dialog title m_pFT_Caption->Show(!bHideDescription); this->SetText( m_pFTTitle->GetText());// OH:remove later with dialog // set defaults as long as DetectArguments does not work m_pRB_Columns->Check(); m_pCB_FirstColumnAsLabel->Check(); m_pCB_FirstRowAsLabel->Check(); // BM: Note, that the range selection is not available, if there is no view. // This happens for charts having their own embedded spreadsheet. If you // force to get the range selection here, this would mean when entering this // page the calc view would be created in this case. So, I enable the // button here, and in the worst case nothing happens when it is pressed. // Not nice, but I see no better solution for the moment. m_pIB_Range->SetClickHdl( LINK( this, RangeChooserTabPage, ChooseRangeHdl )); // #i75179# enable setting the background to a different color m_pED_Range->SetStyle( m_pED_Range->GetStyle() | WB_FORCECTRLBACKGROUND ); m_pED_Range->SetUpdateDataHdl( LINK( this, RangeChooserTabPage, ControlChangedHdl )); m_pED_Range->SetModifyHdl( LINK( this, RangeChooserTabPage, ControlEditedHdl )); m_pRB_Rows->SetToggleHdl( LINK( this, RangeChooserTabPage, ControlChangedHdl ) ); m_pCB_FirstRowAsLabel->SetToggleHdl( LINK( this, RangeChooserTabPage, ControlChangedHdl ) ); m_pCB_FirstColumnAsLabel->SetToggleHdl( LINK( this, RangeChooserTabPage, ControlChangedHdl ) ); } RangeChooserTabPage::~RangeChooserTabPage() { } void RangeChooserTabPage::ActivatePage() { OWizardPage::ActivatePage(); initControlsFromModel(); } void RangeChooserTabPage::initControlsFromModel() { m_nChangingControlCalls++; if(m_pTemplateProvider) m_xCurrentChartTypeTemplate = m_pTemplateProvider->getCurrentTemplate(); bool bUseColumns = ! m_pRB_Rows->IsChecked(); bool bFirstCellAsLabel = bUseColumns ? m_pCB_FirstRowAsLabel->IsChecked() : m_pCB_FirstColumnAsLabel->IsChecked(); bool bHasCategories = bUseColumns ? m_pCB_FirstColumnAsLabel->IsChecked() : m_pCB_FirstRowAsLabel->IsChecked(); bool bIsValid = m_rDialogModel.allArgumentsForRectRangeDetected(); if( bIsValid ) m_rDialogModel.detectArguments(m_aLastValidRangeString, bUseColumns, bFirstCellAsLabel, bHasCategories ); else m_aLastValidRangeString = ""; m_pED_Range->SetText( m_aLastValidRangeString ); m_pRB_Rows->Check( !bUseColumns ); m_pRB_Columns->Check( bUseColumns ); m_pCB_FirstRowAsLabel->Check( m_pRB_Rows->IsChecked()?bHasCategories:bFirstCellAsLabel ); m_pCB_FirstColumnAsLabel->Check( m_pRB_Columns->IsChecked()?bHasCategories:bFirstCellAsLabel ); isValid(); m_nChangingControlCalls--; } void RangeChooserTabPage::DeactivatePage() { commitPage(); svt::OWizardPage::DeactivatePage(); } void RangeChooserTabPage::commitPage() { commitPage(::svt::WizardTypes::eFinish); } sal_Bool RangeChooserTabPage::commitPage( ::svt::WizardTypes::CommitPageReason /*eReason*/ ) { //ranges may have been edited in the meanwhile (dirty is true in that case here) if( isValid() ) { changeDialogModelAccordingToControls(); return sal_True;//return false if this page should not be left } else return sal_False; } void RangeChooserTabPage::changeDialogModelAccordingToControls() { if(m_nChangingControlCalls>0) return; if( !m_xCurrentChartTypeTemplate.is() ) { if(m_pTemplateProvider) m_xCurrentChartTypeTemplate.set( m_pTemplateProvider->getCurrentTemplate()); if( !m_xCurrentChartTypeTemplate.is()) { OSL_FAIL( "Need a template to change data source" ); return; } } if( m_bIsDirty ) { sal_Bool bFirstCellAsLabel = ( m_pCB_FirstColumnAsLabel->IsChecked() && !m_pRB_Columns->IsChecked() ) || ( m_pCB_FirstRowAsLabel->IsChecked() && !m_pRB_Rows->IsChecked() ); sal_Bool bHasCategories = ( m_pCB_FirstColumnAsLabel->IsChecked() && m_pRB_Columns->IsChecked() ) || ( m_pCB_FirstRowAsLabel->IsChecked() && m_pRB_Rows->IsChecked() ); Sequence< beans::PropertyValue > aArguments( DataSourceHelper::createArguments( m_pRB_Columns->IsChecked(), bFirstCellAsLabel, bHasCategories ) ); // only if range is valid if( m_aLastValidRangeString.equals(m_pED_Range->GetText())) { m_rDialogModel.setTemplate( m_xCurrentChartTypeTemplate ); aArguments.realloc( aArguments.getLength() + 1 ); aArguments[aArguments.getLength() - 1] = beans::PropertyValue( "CellRangeRepresentation" , -1, uno::makeAny( m_aLastValidRangeString ), beans::PropertyState_DIRECT_VALUE ); m_rDialogModel.setData( aArguments ); m_bIsDirty = false; } //@todo warn user that the selected range is not valid //@todo better: disable OK-Button if range is invalid } } bool RangeChooserTabPage::isValid() { OUString aRange( m_pED_Range->GetText()); sal_Bool bFirstCellAsLabel = ( m_pCB_FirstColumnAsLabel->IsChecked() && !m_pRB_Columns->IsChecked() ) || ( m_pCB_FirstRowAsLabel->IsChecked() && !m_pRB_Rows->IsChecked() ); sal_Bool bHasCategories = ( m_pCB_FirstColumnAsLabel->IsChecked() && m_pRB_Columns->IsChecked() ) || ( m_pCB_FirstRowAsLabel->IsChecked() && m_pRB_Rows->IsChecked() ); bool bIsValid = ( aRange.isEmpty() ) || m_rDialogModel.getRangeSelectionHelper()->verifyArguments( DataSourceHelper::createArguments( aRange, Sequence< sal_Int32 >(), m_pRB_Columns->IsChecked(), bFirstCellAsLabel, bHasCategories )); if( bIsValid ) { m_pED_Range->SetControlForeground(); m_pED_Range->SetControlBackground(); if( m_pTabPageNotifiable ) m_pTabPageNotifiable->setValidPage( this ); m_aLastValidRangeString = aRange; } else { m_pED_Range->SetControlBackground( RANGE_SELECTION_INVALID_RANGE_BACKGROUND_COLOR ); m_pED_Range->SetControlForeground( RANGE_SELECTION_INVALID_RANGE_FOREGROUND_COLOR ); if( m_pTabPageNotifiable ) m_pTabPageNotifiable->setInvalidPage( this ); } // enable/disable controls // #i79531# if the range is valid but an action of one of these buttons // would render it invalid, the button should be disabled if( bIsValid ) { bool bDataInColumns = m_pRB_Columns->IsChecked(); bool bIsSwappedRangeValid = m_rDialogModel.getRangeSelectionHelper()->verifyArguments( DataSourceHelper::createArguments( aRange, Sequence< sal_Int32 >(), ! bDataInColumns, bHasCategories, bFirstCellAsLabel )); m_pRB_Rows->Enable( bIsSwappedRangeValid ); m_pRB_Columns->Enable( bIsSwappedRangeValid ); m_pCB_FirstRowAsLabel->Enable( m_rDialogModel.getRangeSelectionHelper()->verifyArguments( DataSourceHelper::createArguments( aRange, Sequence< sal_Int32 >(), m_pRB_Columns->IsChecked(), bDataInColumns ? ! bFirstCellAsLabel : bFirstCellAsLabel, bDataInColumns ? bHasCategories : ! bHasCategories ))); m_pCB_FirstColumnAsLabel->Enable( m_rDialogModel.getRangeSelectionHelper()->verifyArguments( DataSourceHelper::createArguments( aRange, Sequence< sal_Int32 >(), m_pRB_Columns->IsChecked(), bDataInColumns ? bFirstCellAsLabel : ! bFirstCellAsLabel, bDataInColumns ? ! bHasCategories : bHasCategories ))); } else { m_pRB_Rows->Enable( bIsValid ); m_pRB_Columns->Enable( bIsValid ); m_pCB_FirstRowAsLabel->Enable( bIsValid ); m_pCB_FirstColumnAsLabel->Enable( bIsValid ); } bool bShowIB = m_rDialogModel.getRangeSelectionHelper()->hasRangeSelection(); lcl_ShowChooserButton( *m_pIB_Range, bShowIB ); return bIsValid; } IMPL_LINK_NOARG(RangeChooserTabPage, ControlEditedHdl) { setDirty(); isValid(); return 0; } IMPL_LINK_NOARG(RangeChooserTabPage, ControlChangedHdl) { setDirty(); if( isValid()) changeDialogModelAccordingToControls(); return 0; } IMPL_LINK_NOARG(RangeChooserTabPage, ChooseRangeHdl) { OUString aRange = m_pED_Range->GetText(); // using assignment for broken gcc 3.3 OUString aTitle = m_pFTTitle->GetText(); lcl_enableRangeChoosing( true, m_pParentDialog ); m_rDialogModel.getRangeSelectionHelper()->chooseRange( aRange, aTitle, *this ); return 0; } void RangeChooserTabPage::listeningFinished( const OUString & rNewRange ) { //user has selected a new range OUString aRange( rNewRange ); m_rDialogModel.startControllerLockTimer(); // stop listening m_rDialogModel.getRangeSelectionHelper()->stopRangeListening(); //update dialog state ToTop(); GrabFocus(); m_pED_Range->SetText( aRange ); m_pED_Range->GrabFocus(); setDirty(); if( isValid()) changeDialogModelAccordingToControls(); lcl_enableRangeChoosing( false, m_pParentDialog ); } void RangeChooserTabPage::disposingRangeSelection() { m_rDialogModel.getRangeSelectionHelper()->stopRangeListening( false ); } void RangeChooserTabPage::setDirty() { if( m_nChangingControlCalls == 0 ) m_bIsDirty = true; } } //namespace chart /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "rodsClient.hpp" #include "reFuncDefs.hpp" #include "rods.hpp" #include "reGlobalsExtern.hpp" #include "rsGlobalExtern.hpp" #include "rcGlobalExtern.hpp" extern "C" { /** * \fn msiobjput_slink(msParam_t* inMSOPath, msParam_t* inCacheFilename, msParam_t* inFileSize, ruleExecInfo_t* rei ) * * \brief Puts an SLINK object * * \module msoDrivers_slink * * \since 3.0 * * \author Arcot Rajasekar * \date 2011 * * \usage See clients/icommands/test/rules3.0/ * * \param[in] inMSOPath - a STR_MS_T path string to external resource * \param[in] inCacheFilename - a STR_MS_T cache file containing data to be written out * \param[in] inFileSize - a STR_MS_T size of inCacheFilename * \param[in,out] rei - The RuleExecInfo structure that is automatically * handled by the rule engine. The user does not include rei as a * parameter in the rule invocation. * * \DolVarDependence none * \DolVarModified none * \iCatAttrDependence none * \iCatAttrModified none * \sideeffect none * * \return integer * \retval 0 on success * \pre none * \post none * \sa none **/ int msiobjput_slink( msParam_t* inMSOPath, msParam_t* inCacheFilename, msParam_t* inFileSize, ruleExecInfo_t* rei ) { char *reqStr; char *str, *t; char *cacheFilename; rodsLong_t dataSize; int status, i; int srcFd; char *myBuf; int bytesRead; openedDataObjInp_t dataObjWriteInp; int bytesWritten; openedDataObjInp_t dataObjCloseInp; dataObjInp_t dataObjInp; int outDesc; bytesBuf_t writeBuf; int writeBufLen; rsComm_t *rsComm; RE_TEST_MACRO( " Calling msiobjput_slink" ); /* check for input parameters */ if ( inMSOPath == NULL || strcmp( inMSOPath->type , STR_MS_T ) != 0 || inMSOPath->inOutStruct == NULL ) { return USER_PARAM_TYPE_ERR; } if ( inCacheFilename == NULL || strcmp( inCacheFilename->type , STR_MS_T ) != 0 || inCacheFilename->inOutStruct == NULL ) { return USER_PARAM_TYPE_ERR; } if ( inFileSize == NULL || strcmp( inFileSize->type , STR_MS_T ) != 0 || inFileSize->inOutStruct == NULL ) { return USER_PARAM_TYPE_ERR; } /* coerce input to local variables */ str = strdup( ( char * ) inMSOPath->inOutStruct ); if ( ( t = strstr( str, ":" ) ) != NULL ) { reqStr = t + 1; } else { free( str ); return USER_INPUT_FORMAT_ERR; } cacheFilename = ( char * ) inCacheFilename->inOutStruct; dataSize = atol( ( char * ) inFileSize->inOutStruct ); rsComm = rei->rsComm; /* Read the cache and Do the upload*/ srcFd = open( cacheFilename, O_RDONLY, 0 ); if ( srcFd < 0 ) { status = UNIX_FILE_OPEN_ERR - errno; printf( "msiputobj_slink: open error for %s, status = %d\n", cacheFilename, status ); free( str ); return status; } bzero( &dataObjInp, sizeof( dataObjInp_t ) ); bzero( &dataObjWriteInp, sizeof( dataObjWriteInp ) ); bzero( &dataObjCloseInp, sizeof( dataObjCloseInp ) ); rstrcpy( dataObjInp.objPath, reqStr, MAX_NAME_LEN ); addKeyVal( &dataObjInp.condInput, FORCE_FLAG_KW, "" ); free( str ); outDesc = rsDataObjCreate( rsComm, &dataObjInp ); if ( outDesc < 0 ) { printf( "msiputobj_slink: Unable to open file %s:%i\n", dataObjInp.objPath, outDesc ); return outDesc; } dataObjWriteInp.l1descInx = outDesc; dataObjCloseInp.l1descInx = outDesc; if ( dataSize > MAX_SZ_FOR_SINGLE_BUF ) { writeBufLen = MAX_SZ_FOR_SINGLE_BUF; } else { writeBufLen = dataSize; } myBuf = ( char * ) malloc( writeBufLen ); writeBuf.buf = myBuf; while ( ( bytesRead = read( srcFd, ( void * ) myBuf, writeBufLen ) ) > 0 ) { writeBuf.len = bytesRead; dataObjWriteInp.len = bytesRead; bytesWritten = rsDataObjWrite( rsComm, &dataObjWriteInp, &writeBuf ); if ( bytesWritten != bytesRead ) { free( myBuf ); close( srcFd ); rsDataObjClose( rsComm, &dataObjCloseInp ); printf( "msiputobj_slink: Write Error: bytesRead %d != bytesWritten %d\n", bytesRead, bytesWritten ); return SYS_COPY_LEN_ERR; } } free( myBuf ); close( srcFd ); i = rsDataObjClose( rsComm, &dataObjCloseInp ); return i; } // =-=-=-=-=-=-=- // plugin factory irods::ms_table_entry* plugin_factory( ) { // =-=-=-=-=-=-=- // instantiate a new msvc plugin irods::ms_table_entry* msvc = new irods::ms_table_entry( 3 ); // =-=-=-=-=-=-=- // wire the implementation to the plugin instance msvc->add_operation( "msiobjput_slink", "msiobjput_slink" ); // =-=-=-=-=-=-=- // hand it over to the system return msvc; } // plugin_factory } // extern "C" <commit_msg>[#2212] CID43798:<commit_after>#include "rodsClient.hpp" #include "reFuncDefs.hpp" #include "rods.hpp" #include "reGlobalsExtern.hpp" #include "rsGlobalExtern.hpp" #include "rcGlobalExtern.hpp" extern "C" { /** * \fn msiobjput_slink(msParam_t* inMSOPath, msParam_t* inCacheFilename, msParam_t* inFileSize, ruleExecInfo_t* rei ) * * \brief Puts an SLINK object * * \module msoDrivers_slink * * \since 3.0 * * \author Arcot Rajasekar * \date 2011 * * \usage See clients/icommands/test/rules3.0/ * * \param[in] inMSOPath - a STR_MS_T path string to external resource * \param[in] inCacheFilename - a STR_MS_T cache file containing data to be written out * \param[in] inFileSize - a STR_MS_T size of inCacheFilename * \param[in,out] rei - The RuleExecInfo structure that is automatically * handled by the rule engine. The user does not include rei as a * parameter in the rule invocation. * * \DolVarDependence none * \DolVarModified none * \iCatAttrDependence none * \iCatAttrModified none * \sideeffect none * * \return integer * \retval 0 on success * \pre none * \post none * \sa none **/ int msiobjput_slink( msParam_t* inMSOPath, msParam_t* inCacheFilename, msParam_t* inFileSize, ruleExecInfo_t* rei ) { RE_TEST_MACRO( " Calling msiobjput_slink" ); /* check for input parameters */ if ( inMSOPath == NULL || strcmp( inMSOPath->type , STR_MS_T ) != 0 || inMSOPath->inOutStruct == NULL ) { return USER_PARAM_TYPE_ERR; } if ( inCacheFilename == NULL || strcmp( inCacheFilename->type , STR_MS_T ) != 0 || inCacheFilename->inOutStruct == NULL ) { return USER_PARAM_TYPE_ERR; } if ( inFileSize == NULL || strcmp( inFileSize->type , STR_MS_T ) != 0 || inFileSize->inOutStruct == NULL ) { return USER_PARAM_TYPE_ERR; } /* coerce input to local variables */ char * str = strdup( ( char * ) inMSOPath->inOutStruct ); char * reqStr = strstr( str, ":" ); if ( reqStr == NULL ) { free( str ); return USER_INPUT_FORMAT_ERR; } reqStr = reqStr + 1; dataObjInp_t dataObjInp; memset( &dataObjInp, 0, sizeof( dataObjInp_t ) ); rstrcpy( dataObjInp.objPath, reqStr, MAX_NAME_LEN ); addKeyVal( &dataObjInp.condInput, FORCE_FLAG_KW, "" ); free( str ); rsComm_t * rsComm = rei->rsComm; int outDesc = rsDataObjCreate( rsComm, &dataObjInp ); if ( outDesc < 0 ) { printf( "msiputobj_slink: Unable to open file %s:%i\n", dataObjInp.objPath, outDesc ); return outDesc; } /* Read the cache and Do the upload*/ char * cacheFilename = ( char * ) inCacheFilename->inOutStruct; int srcFd = open( cacheFilename, O_RDONLY, 0 ); if ( srcFd < 0 ) { int status = UNIX_FILE_OPEN_ERR - errno; printf( "msiputobj_slink: open error for %s, status = %d\n", cacheFilename, status ); return status; } size_t dataSize = atol( ( char * ) inFileSize->inOutStruct ); if ( dataSize > MAX_SZ_FOR_SINGLE_BUF ) { dataSize = MAX_SZ_FOR_SINGLE_BUF; } openedDataObjInp_t dataObjWriteInp; memset( &dataObjWriteInp, 0, sizeof( dataObjWriteInp ) ); dataObjWriteInp.l1descInx = outDesc; openedDataObjInp_t dataObjCloseInp; memset( &dataObjCloseInp, 0, sizeof( dataObjCloseInp ) ); dataObjCloseInp.l1descInx = outDesc; char * myBuf = ( char * ) malloc( dataSize ); bytesBuf_t writeBuf; writeBuf.buf = myBuf; int bytesRead; for ( bytesRead = read( srcFd, ( void * ) myBuf, dataSize ); bytesRead > 0; bytesRead = read( srcFd, ( void * ) myBuf, dataSize ) ) { writeBuf.len = bytesRead; dataObjWriteInp.len = bytesRead; int bytesWritten = rsDataObjWrite( rsComm, &dataObjWriteInp, &writeBuf ); if ( bytesWritten != bytesRead ) { free( myBuf ); close( srcFd ); rsDataObjClose( rsComm, &dataObjCloseInp ); printf( "msiputobj_slink: Write Error: bytesRead %d != bytesWritten %d\n", bytesRead, bytesWritten ); return SYS_COPY_LEN_ERR; } } free( myBuf ); close( srcFd ); return rsDataObjClose( rsComm, &dataObjCloseInp ); } // =-=-=-=-=-=-=- // plugin factory irods::ms_table_entry* plugin_factory( ) { // =-=-=-=-=-=-=- // instantiate a new msvc plugin irods::ms_table_entry* msvc = new irods::ms_table_entry( 3 ); // =-=-=-=-=-=-=- // wire the implementation to the plugin instance msvc->add_operation( "msiobjput_slink", "msiobjput_slink" ); // =-=-=-=-=-=-=- // hand it over to the system return msvc; } // plugin_factory } // extern "C" <|endoftext|>
<commit_before>/* * The Biomechanical ToolKit * Copyright (c) 2009-2012, Arnaud Barré * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name(s) of the copyright holders nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "FilterAnalog.h" #include "FilterAnalogDialog.h" #include "UndoCommands.h" #include <btkEigen/SignalProcessing/IIRFilterDesign.h> #include <btkEigen/SignalProcessing/FiltFilt.h> #include <btkEigen/SignalProcessing/Filter.h> #include <QDoubleSpinBox> #include <QComboBox> void FilterAnalog::RegisterTool(ToolsManager* manager) { manager->addAnalogTool(tr("Filter Analog (Butterworth)"), ToolFactory<FilterAnalog>); }; FilterAnalog::FilterAnalog(QWidget* parent) : AbstractTool("Butterworth Analog Filter", parent) {}; AbstractTool::RunState FilterAnalog::run(ToolCommands* cmds, ToolsData* const data) { FilterAnalogDialog dialog(this->parentWidget()); dialog.initialize(data); if (dialog.exec() == QDialog::Accepted) { QString detail = "Filtered by a "; detail += (dialog.zeroLagComboBox->currentIndex() == 0) ? "zero lag" : "non-zero lag"; if (dialog.typeComboBox->currentIndex() == 0) detail += QString(" low pass butterworth filter (n = %1, fc = %2 Hz)").arg(dialog.orderSpinBox->value()).arg(dialog.lowerCutOffSpinBox->value()); else if (dialog.typeComboBox->currentIndex() == 1) detail += QString(" high pass butterworth filter (n = %1, fc = %2 Hz)").arg(dialog.orderSpinBox->value()).arg(dialog.lowerCutOffSpinBox->value()); else detail += QString(" band pass butterworth filter (n = %1, fcl = %2 Hz, fcu = %3 Hz)").arg(dialog.orderSpinBox->value()).arg(dialog.lowerCutOffSpinBox->value()).arg(dialog.upperCutOffSpinBox->value()); btk::AnalogCollection::Pointer analogs = btk::AnalogCollection::New(); QList<int> ids = dialog.extractSelectedAnalogChannels(analogs, "_Filtered", detail, data, cmds); QString log; QString log_; if (ids.count() == 1) { log = "The channel "; log_ = " was " + detail.toLower(); } else { log = "The channels "; log_ = " were " + detail.toLower(); } Eigen::Matrix<double,Eigen::Dynamic,1> a,b; const double hfs = 2.0 * data->acquisition()->pointFrequency(); int n = dialog.orderSpinBox->value(); bool zeroLagFilter = (dialog.zeroLagComboBox->currentIndex() == 0); if (dialog.typeComboBox->currentIndex() == 0) { double wn = dialog.lowerCutOffSpinBox->value() / hfs; if (zeroLagFilter) btkEigen::adjustZeroLagButterworth(n, wn); btkEigen::butter(&b, &a, n, wn, btkEigen::LowPass); } else if (dialog.typeComboBox->currentIndex() == 1) { double wn = dialog.lowerCutOffSpinBox->value() / hfs; if (zeroLagFilter) btkEigen::adjustZeroLagButterworth(n, wn); btkEigen::butter(&b, &a, n, wn, btkEigen::HighPass); } else { double wn[2] = {dialog.lowerCutOffSpinBox->value() / hfs, dialog.upperCutOffSpinBox->value() / hfs}; if (zeroLagFilter) btkEigen::adjustZeroLagButterworth(n, &wn); btkEigen::butter(&b, &a, n, wn, btkEigen::BandPass); } int inc = 0; QSharedPointer< QList<btk::Analog::Values> > values(new QList<btk::Analog::Values>()); for (btk::AnalogCollection::ConstIterator it = analogs->Begin() ; it != analogs->End() ; ++it) { if (zeroLagFilter) values->push_back(btkEigen::filtfilt(b,a,(*it)->GetValues())); else values->push_back(btkEigen::filter(b,a,(*it)->GetValues())); log += (inc != 0 ? ", '" : "'") + QString::fromStdString((*it)->GetLabel()) + "'"; ++inc; } new SetAnalogsValues(data->acquisition(), ids, values, cmds->acquisitionCommand()); TOOL_LOG_INFO(log + log_); return Success; } return Cancel; }; // ------------------------------------------------------------------------- // FilterAnalogDialog::FilterAnalogDialog(QWidget* parent) : AnalogToolOptionDialog("Filter Analog", parent) { QWidget* filterDesign = new QWidget(this); QLabel* typeLabel = new QLabel(this); typeLabel->setText(tr("Type:")); this->typeComboBox = new QComboBox(this); this->typeComboBox->addItems(QStringList() << tr("Low Pass") << tr("High Pass") << tr("Band Pass")); QLabel* cutoffLabel = new QLabel(this); cutoffLabel->setText(tr("Cutoff:")); this->lowerCutOffSpinBox = new QDoubleSpinBox(this); this->lowerCutOffSpinBox->setSuffix(" Hz"); this->lowerCutOffLabel = new QLabel(this); this->lowerCutOffLabel->setText(tr("(lower)")); this->upperCutOffSpinBox = new QDoubleSpinBox(this); this->upperCutOffSpinBox->setSuffix(" Hz"); this->upperCutOffLabel = new QLabel(this); this->upperCutOffLabel->setText(tr("(upper)")); QLabel* orderLabel = new QLabel(this); orderLabel->setText(tr("Order:")); this->orderSpinBox = new QSpinBox(this); this->orderSpinBox->setRange(2,10); this->orderSpinBox->setValue(2); QLabel* zeroLagLabel = new QLabel(this); zeroLagLabel->setText(tr("Zero Lag:")); this->zeroLagComboBox = new QComboBox(this); this->zeroLagComboBox->addItems(QStringList() << tr("Yes") << tr("No")); QLabel* informations = new QLabel(this); informations->setText(tr("Note: the order and cutoff(s) are final.")); informations->setWordWrap(true); informations->setAlignment(Qt::AlignJustify | Qt::AlignBottom); QHBoxLayout* hboxLayout1 = new QHBoxLayout; hboxLayout1->addWidget(this->typeComboBox); QSpacerItem* horizontalSpacer1 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout1->addItem(horizontalSpacer1); QHBoxLayout* hboxLayout2 = new QHBoxLayout; hboxLayout2->addWidget(this->orderSpinBox); QSpacerItem* horizontalSpacer2 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout2->addItem(horizontalSpacer2); QHBoxLayout* hboxLayout3 = new QHBoxLayout; hboxLayout3->addWidget(this->lowerCutOffSpinBox); hboxLayout3->addWidget(lowerCutOffLabel); QSpacerItem* horizontalSpacer3 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout3->addItem(horizontalSpacer3); QHBoxLayout* hboxLayout4 = new QHBoxLayout; hboxLayout4->addWidget(this->upperCutOffSpinBox); hboxLayout4->addWidget(upperCutOffLabel); QSpacerItem* horizontalSpacer4 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout4->addItem(horizontalSpacer4); QHBoxLayout* hboxLayout5 = new QHBoxLayout; hboxLayout5->addWidget(this->zeroLagComboBox); QSpacerItem* horizontalSpacer5 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout5->addItem(horizontalSpacer5); QFrame* line = new QFrame(this); line->setObjectName(QString::fromUtf8("line")); line->setGeometry(QRect(320, 150, 118, 3)); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); #ifndef Q_OS_WIN line->setMinimumHeight(12); #endif QGridLayout* gridLayout = new QGridLayout(filterDesign); gridLayout->addWidget(typeLabel, 0, 0, 1, 1); gridLayout->addLayout(hboxLayout1, 0, 1, 1, 1); gridLayout->addWidget(zeroLagLabel, 1, 0, 1, 1); gridLayout->addLayout(hboxLayout5, 1, 1, 1, 1); gridLayout->addWidget(line, 2, 0, 1, -1); gridLayout->addWidget(informations, 3, 0, 1, -1); gridLayout->addWidget(orderLabel, 4, 0, 1, 1); gridLayout->addLayout(hboxLayout2, 4, 1, 1, 1); gridLayout->addWidget(cutoffLabel, 5, 0, 1, 1); gridLayout->addLayout(hboxLayout3, 5, 1, 1, 1); gridLayout->addLayout(hboxLayout4, 6, 1, 1, 1); QSpacerItem* verticalSpacer = new QSpacerItem(10, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout->addItem(verticalSpacer, 7, 1, 1, 1); #ifndef Q_OS_WIN QFont f = this->font(); f.setPointSize(11); typeLabel->setFont(f); this->typeComboBox->setFont(f); cutoffLabel->setFont(f); lowerCutOffLabel->setFont(f); upperCutOffLabel->setFont(f); this->zeroLagComboBox->setFont(f); orderLabel->setFont(f); this->orderSpinBox->setFont(f); zeroLagLabel->setFont(f); this->lowerCutOffSpinBox->setStyleSheet("QDoubleSpinBox {font-size: 12px;};"); this->upperCutOffSpinBox->setStyleSheet("QDoubleSpinBox {font-size: 12px;};"); this->orderSpinBox->setStyleSheet("QSpinBox {font-size: 12px;};"); gridLayout->setVerticalSpacing(3); f.setItalic(true); informations->setFont(f); informations->setStyleSheet("margin-bottom: 3px;"); #else QFont f = this->font(); f.setItalic(true); informations->setFont(f); #endif connect(this->typeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(adaptCutoffDisplay(int))); this->addOption(tr("Butterworth filter design"), filterDesign); }; void FilterAnalogDialog::initializeOptions(const Acquisition* const acq) { QSettings settings; this->typeComboBox->setCurrentIndex(settings.value(this->toolSettingsPath() + "lastType", 0).toInt()); // 0: Low pass this->orderSpinBox->setValue(settings.value(this->toolSettingsPath() + "lastOrder", 2).toInt()); this->zeroLagComboBox->setCurrentIndex(settings.value(this->toolSettingsPath() + "lastZeroLag", 0).toInt()); // 0: Yes this->adaptCutoffDisplay(this->typeComboBox->currentIndex()); this->lowerCutOffSpinBox->setRange(0.01, acq->pointFrequency() / 2.0); this->upperCutOffSpinBox->setRange(0.01, acq->pointFrequency() / 2.0); }; void FilterAnalogDialog::saveOptionsSettings() { int index = this->typeComboBox->currentIndex(); QSettings settings; settings.setValue(this->toolSettingsPath() + "lastType", index); settings.setValue(this->toolSettingsPath() + "lastOrder", this->orderSpinBox->value()); settings.setValue(this->toolSettingsPath() + "lastZeroLag", this->zeroLagComboBox->currentIndex()); if (index == 0) // Low pass { settings.setValue(this->toolSettingsPath() + "lowPassCutoffFrequency", this->lowerCutOffSpinBox->value()); } else if (index == 1) // High pass { settings.setValue(this->toolSettingsPath() + "highPassCutoffFrequency", this->lowerCutOffSpinBox->value()); } else // Band pass { settings.setValue(this->toolSettingsPath() + "bandPassLowerCutoffFrequency", this->lowerCutOffSpinBox->value()); settings.setValue(this->toolSettingsPath() + "bandPassUpperCutoffFrequency", this->upperCutOffSpinBox->value()); } }; void FilterAnalogDialog::adaptCutoffDisplay(int index) { QSettings settings; if (index == 0) // Low pass { this->lowerCutOffLabel->setVisible(false); this->upperCutOffSpinBox->setVisible(false); this->upperCutOffLabel->setVisible(false); this->lowerCutOffSpinBox->setValue(settings.value(this->toolSettingsPath() + "lowPassCutoffFrequency", 6.0).toDouble()); } else if (index == 1) // High pass { this->lowerCutOffLabel->setVisible(false); this->upperCutOffSpinBox->setVisible(false); this->upperCutOffLabel->setVisible(false); this->lowerCutOffSpinBox->setValue(settings.value(this->toolSettingsPath() + "highPassCutoffFrequency", 20.0).toDouble()); } else // Band pass { this->lowerCutOffLabel->setVisible(true); this->upperCutOffSpinBox->setVisible(true); this->upperCutOffLabel->setVisible(true); this->lowerCutOffSpinBox->setValue(settings.value(this->toolSettingsPath() + "bandPassLowerCutoffFrequency", 10.0).toDouble()); this->upperCutOffSpinBox->setValue(settings.value(this->toolSettingsPath() + "bandPassUpperCutoffFrequency", 500.0).toDouble()); } }; bool FilterAnalogDialog::testOptionsValidity() { if (this->upperCutOffSpinBox->isVisible() && (this->lowerCutOffSpinBox->value() > this->upperCutOffSpinBox->value())) return false; return true; };<commit_msg>[FIX] Mokka: Critical issue on the computation of the cut-off frequency (video frequency used instead of analog frequency).<commit_after>/* * The Biomechanical ToolKit * Copyright (c) 2009-2012, Arnaud Barré * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name(s) of the copyright holders nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "FilterAnalog.h" #include "FilterAnalogDialog.h" #include "UndoCommands.h" #include <btkEigen/SignalProcessing/IIRFilterDesign.h> #include <btkEigen/SignalProcessing/FiltFilt.h> #include <btkEigen/SignalProcessing/Filter.h> #include <QDoubleSpinBox> #include <QComboBox> void FilterAnalog::RegisterTool(ToolsManager* manager) { manager->addAnalogTool(tr("Filter Analog (Butterworth)"), ToolFactory<FilterAnalog>); }; FilterAnalog::FilterAnalog(QWidget* parent) : AbstractTool("Butterworth Analog Filter", parent) {}; AbstractTool::RunState FilterAnalog::run(ToolCommands* cmds, ToolsData* const data) { FilterAnalogDialog dialog(this->parentWidget()); dialog.initialize(data); if (dialog.exec() == QDialog::Accepted) { QString detail = "Filtered by a "; detail += (dialog.zeroLagComboBox->currentIndex() == 0) ? "zero lag" : "non-zero lag"; if (dialog.typeComboBox->currentIndex() == 0) detail += QString(" low pass butterworth filter (n = %1, fc = %2 Hz)").arg(dialog.orderSpinBox->value()).arg(dialog.lowerCutOffSpinBox->value()); else if (dialog.typeComboBox->currentIndex() == 1) detail += QString(" high pass butterworth filter (n = %1, fc = %2 Hz)").arg(dialog.orderSpinBox->value()).arg(dialog.lowerCutOffSpinBox->value()); else detail += QString(" band pass butterworth filter (n = %1, fcl = %2 Hz, fcu = %3 Hz)").arg(dialog.orderSpinBox->value()).arg(dialog.lowerCutOffSpinBox->value()).arg(dialog.upperCutOffSpinBox->value()); btk::AnalogCollection::Pointer analogs = btk::AnalogCollection::New(); QList<int> ids = dialog.extractSelectedAnalogChannels(analogs, "_Filtered", detail, data, cmds); QString log; QString log_; if (ids.count() == 1) { log = "The channel "; log_ = " was " + detail.toLower(); } else { log = "The channels "; log_ = " were " + detail.toLower(); } Eigen::Matrix<double,Eigen::Dynamic,1> a,b; const double hfs = data->acquisition()->analogFrequency() / 2.0; int n = dialog.orderSpinBox->value(); bool zeroLagFilter = (dialog.zeroLagComboBox->currentIndex() == 0); if (dialog.typeComboBox->currentIndex() == 0) { double wn = dialog.lowerCutOffSpinBox->value() / hfs; if (zeroLagFilter) btkEigen::adjustZeroLagButterworth(n, wn); btkEigen::butter(&b, &a, n, wn, btkEigen::LowPass); } else if (dialog.typeComboBox->currentIndex() == 1) { double wn = dialog.lowerCutOffSpinBox->value() / hfs; if (zeroLagFilter) btkEigen::adjustZeroLagButterworth(n, wn); btkEigen::butter(&b, &a, n, wn, btkEigen::HighPass); } else { double wn[2] = {dialog.lowerCutOffSpinBox->value() / hfs, dialog.upperCutOffSpinBox->value() / hfs}; if (zeroLagFilter) btkEigen::adjustZeroLagButterworth(n, &wn); btkEigen::butter(&b, &a, n, wn, btkEigen::BandPass); } int inc = 0; QSharedPointer< QList<btk::Analog::Values> > values(new QList<btk::Analog::Values>()); for (btk::AnalogCollection::ConstIterator it = analogs->Begin() ; it != analogs->End() ; ++it) { if (zeroLagFilter) values->push_back(btkEigen::filtfilt(b,a,(*it)->GetValues())); else values->push_back(btkEigen::filter(b,a,(*it)->GetValues())); log += (inc != 0 ? ", '" : "'") + QString::fromStdString((*it)->GetLabel()) + "'"; ++inc; } new SetAnalogsValues(data->acquisition(), ids, values, cmds->acquisitionCommand()); TOOL_LOG_INFO(log + log_); return Success; } return Cancel; }; // ------------------------------------------------------------------------- // FilterAnalogDialog::FilterAnalogDialog(QWidget* parent) : AnalogToolOptionDialog("Filter Analog", parent) { QWidget* filterDesign = new QWidget(this); QLabel* typeLabel = new QLabel(this); typeLabel->setText(tr("Type:")); this->typeComboBox = new QComboBox(this); this->typeComboBox->addItems(QStringList() << tr("Low Pass") << tr("High Pass") << tr("Band Pass")); QLabel* cutoffLabel = new QLabel(this); cutoffLabel->setText(tr("Cutoff:")); this->lowerCutOffSpinBox = new QDoubleSpinBox(this); this->lowerCutOffSpinBox->setSuffix(" Hz"); this->lowerCutOffLabel = new QLabel(this); this->lowerCutOffLabel->setText(tr("(lower)")); this->upperCutOffSpinBox = new QDoubleSpinBox(this); this->upperCutOffSpinBox->setSuffix(" Hz"); this->upperCutOffLabel = new QLabel(this); this->upperCutOffLabel->setText(tr("(upper)")); QLabel* orderLabel = new QLabel(this); orderLabel->setText(tr("Order:")); this->orderSpinBox = new QSpinBox(this); this->orderSpinBox->setRange(2,10); this->orderSpinBox->setValue(2); QLabel* zeroLagLabel = new QLabel(this); zeroLagLabel->setText(tr("Zero Lag:")); this->zeroLagComboBox = new QComboBox(this); this->zeroLagComboBox->addItems(QStringList() << tr("Yes") << tr("No")); QLabel* informations = new QLabel(this); informations->setText(tr("Note: the order and cutoff(s) are final.")); informations->setWordWrap(true); informations->setAlignment(Qt::AlignJustify | Qt::AlignBottom); QHBoxLayout* hboxLayout1 = new QHBoxLayout; hboxLayout1->addWidget(this->typeComboBox); QSpacerItem* horizontalSpacer1 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout1->addItem(horizontalSpacer1); QHBoxLayout* hboxLayout2 = new QHBoxLayout; hboxLayout2->addWidget(this->orderSpinBox); QSpacerItem* horizontalSpacer2 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout2->addItem(horizontalSpacer2); QHBoxLayout* hboxLayout3 = new QHBoxLayout; hboxLayout3->addWidget(this->lowerCutOffSpinBox); hboxLayout3->addWidget(lowerCutOffLabel); QSpacerItem* horizontalSpacer3 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout3->addItem(horizontalSpacer3); QHBoxLayout* hboxLayout4 = new QHBoxLayout; hboxLayout4->addWidget(this->upperCutOffSpinBox); hboxLayout4->addWidget(upperCutOffLabel); QSpacerItem* horizontalSpacer4 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout4->addItem(horizontalSpacer4); QHBoxLayout* hboxLayout5 = new QHBoxLayout; hboxLayout5->addWidget(this->zeroLagComboBox); QSpacerItem* horizontalSpacer5 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout5->addItem(horizontalSpacer5); QFrame* line = new QFrame(this); line->setObjectName(QString::fromUtf8("line")); line->setGeometry(QRect(320, 150, 118, 3)); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); #ifndef Q_OS_WIN line->setMinimumHeight(12); #endif QGridLayout* gridLayout = new QGridLayout(filterDesign); gridLayout->addWidget(typeLabel, 0, 0, 1, 1); gridLayout->addLayout(hboxLayout1, 0, 1, 1, 1); gridLayout->addWidget(zeroLagLabel, 1, 0, 1, 1); gridLayout->addLayout(hboxLayout5, 1, 1, 1, 1); gridLayout->addWidget(line, 2, 0, 1, -1); gridLayout->addWidget(informations, 3, 0, 1, -1); gridLayout->addWidget(orderLabel, 4, 0, 1, 1); gridLayout->addLayout(hboxLayout2, 4, 1, 1, 1); gridLayout->addWidget(cutoffLabel, 5, 0, 1, 1); gridLayout->addLayout(hboxLayout3, 5, 1, 1, 1); gridLayout->addLayout(hboxLayout4, 6, 1, 1, 1); QSpacerItem* verticalSpacer = new QSpacerItem(10, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout->addItem(verticalSpacer, 7, 1, 1, 1); #ifndef Q_OS_WIN QFont f = this->font(); f.setPointSize(11); typeLabel->setFont(f); this->typeComboBox->setFont(f); cutoffLabel->setFont(f); lowerCutOffLabel->setFont(f); upperCutOffLabel->setFont(f); this->zeroLagComboBox->setFont(f); orderLabel->setFont(f); this->orderSpinBox->setFont(f); zeroLagLabel->setFont(f); this->lowerCutOffSpinBox->setStyleSheet("QDoubleSpinBox {font-size: 12px;};"); this->upperCutOffSpinBox->setStyleSheet("QDoubleSpinBox {font-size: 12px;};"); this->orderSpinBox->setStyleSheet("QSpinBox {font-size: 12px;};"); gridLayout->setVerticalSpacing(3); f.setItalic(true); informations->setFont(f); informations->setStyleSheet("margin-bottom: 3px;"); #else QFont f = this->font(); f.setItalic(true); informations->setFont(f); #endif connect(this->typeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(adaptCutoffDisplay(int))); this->addOption(tr("Butterworth filter design"), filterDesign); }; void FilterAnalogDialog::initializeOptions(const Acquisition* const acq) { QSettings settings; this->typeComboBox->setCurrentIndex(settings.value(this->toolSettingsPath() + "lastType", 0).toInt()); // 0: Low pass this->orderSpinBox->setValue(settings.value(this->toolSettingsPath() + "lastOrder", 2).toInt()); this->zeroLagComboBox->setCurrentIndex(settings.value(this->toolSettingsPath() + "lastZeroLag", 0).toInt()); // 0: Yes this->adaptCutoffDisplay(this->typeComboBox->currentIndex()); this->lowerCutOffSpinBox->setRange(0.01, acq->analogFrequency() / 2.0); this->upperCutOffSpinBox->setRange(0.01, acq->analogFrequency() / 2.0); }; void FilterAnalogDialog::saveOptionsSettings() { int index = this->typeComboBox->currentIndex(); QSettings settings; settings.setValue(this->toolSettingsPath() + "lastType", index); settings.setValue(this->toolSettingsPath() + "lastOrder", this->orderSpinBox->value()); settings.setValue(this->toolSettingsPath() + "lastZeroLag", this->zeroLagComboBox->currentIndex()); if (index == 0) // Low pass { settings.setValue(this->toolSettingsPath() + "lowPassCutoffFrequency", this->lowerCutOffSpinBox->value()); } else if (index == 1) // High pass { settings.setValue(this->toolSettingsPath() + "highPassCutoffFrequency", this->lowerCutOffSpinBox->value()); } else // Band pass { settings.setValue(this->toolSettingsPath() + "bandPassLowerCutoffFrequency", this->lowerCutOffSpinBox->value()); settings.setValue(this->toolSettingsPath() + "bandPassUpperCutoffFrequency", this->upperCutOffSpinBox->value()); } }; void FilterAnalogDialog::adaptCutoffDisplay(int index) { QSettings settings; if (index == 0) // Low pass { this->lowerCutOffLabel->setVisible(false); this->upperCutOffSpinBox->setVisible(false); this->upperCutOffLabel->setVisible(false); this->lowerCutOffSpinBox->setValue(settings.value(this->toolSettingsPath() + "lowPassCutoffFrequency", 6.0).toDouble()); } else if (index == 1) // High pass { this->lowerCutOffLabel->setVisible(false); this->upperCutOffSpinBox->setVisible(false); this->upperCutOffLabel->setVisible(false); this->lowerCutOffSpinBox->setValue(settings.value(this->toolSettingsPath() + "highPassCutoffFrequency", 20.0).toDouble()); } else // Band pass { this->lowerCutOffLabel->setVisible(true); this->upperCutOffSpinBox->setVisible(true); this->upperCutOffLabel->setVisible(true); this->lowerCutOffSpinBox->setValue(settings.value(this->toolSettingsPath() + "bandPassLowerCutoffFrequency", 10.0).toDouble()); this->upperCutOffSpinBox->setValue(settings.value(this->toolSettingsPath() + "bandPassUpperCutoffFrequency", 500.0).toDouble()); } }; bool FilterAnalogDialog::testOptionsValidity() { if (this->upperCutOffSpinBox->isVisible() && (this->lowerCutOffSpinBox->value() > this->upperCutOffSpinBox->value())) return false; return true; };<|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/app_list_view_delegate.h" #include <vector> #include "base/callback.h" #include "base/files/file_path.h" #include "base/metrics/user_metrics.h" #include "base/stl_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/feedback/feedback_util.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/app_list/app_list_controller_delegate.h" #include "chrome/browser/ui/app_list/app_list_service.h" #include "chrome/browser/ui/app_list/app_list_syncable_service.h" #include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h" #include "chrome/browser/ui/app_list/search/search_controller.h" #include "chrome/browser/ui/app_list/start_page_service.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/scoped_tabbed_browser_displayer.h" #include "chrome/browser/ui/web_applications/web_app_ui.h" #include "chrome/browser/web_applications/web_app.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/url_constants.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/user_metrics.h" #include "grit/theme_resources.h" #include "ui/app_list/app_list_view_delegate_observer.h" #include "ui/app_list/search_box_model.h" #include "ui/app_list/speech_ui_model.h" #include "ui/base/resource/resource_bundle.h" #if defined(USE_ASH) #include "chrome/browser/ui/ash/app_list/app_sync_ui_state_watcher.h" #endif #if defined(OS_WIN) #include "chrome/browser/web_applications/web_app_win.h" #endif namespace { const int kAutoLaunchDefaultTimeoutSec = 3; #if defined(OS_WIN) void CreateShortcutInWebAppDir( const base::FilePath& app_data_dir, base::Callback<void(const base::FilePath&)> callback, const ShellIntegration::ShortcutInfo& info) { content::BrowserThread::PostTaskAndReplyWithResult( content::BrowserThread::FILE, FROM_HERE, base::Bind(web_app::CreateShortcutInWebAppDir, app_data_dir, info), callback); } #endif void PopulateUsers(const ProfileInfoCache& profile_info, const base::FilePath& active_profile_path, app_list::AppListViewDelegate::Users* users) { users->clear(); const size_t count = profile_info.GetNumberOfProfiles(); for (size_t i = 0; i < count; ++i) { // Don't display managed users. if (profile_info.ProfileIsManagedAtIndex(i)) continue; app_list::AppListViewDelegate::User user; user.name = profile_info.GetNameOfProfileAtIndex(i); user.email = profile_info.GetUserNameOfProfileAtIndex(i); user.profile_path = profile_info.GetPathOfProfileAtIndex(i); user.active = active_profile_path == user.profile_path; users->push_back(user); } } } // namespace AppListViewDelegate::AppListViewDelegate(Profile* profile, AppListControllerDelegate* controller) : controller_(controller), profile_(profile), model_(NULL) { CHECK(controller_); RegisterForNotifications(); g_browser_process->profile_manager()->GetProfileInfoCache().AddObserver(this); app_list::StartPageService* service = app_list::StartPageService::Get(profile_); speech_ui_.reset(new app_list::SpeechUIModel( service ? service->state() : app_list::SPEECH_RECOGNITION_OFF)); #if defined(GOOGLE_CHROME_BUILD) speech_ui_->set_logo( *ui::ResourceBundle::GetSharedInstance(). GetImageSkiaNamed(IDR_APP_LIST_GOOGLE_LOGO_VOICE_SEARCH)); #endif OnProfileChanged(); // sets model_ if (service) service->AddObserver(this); } AppListViewDelegate::~AppListViewDelegate() { app_list::StartPageService* service = app_list::StartPageService::Get(profile_); if (service) service->RemoveObserver(this); g_browser_process-> profile_manager()->GetProfileInfoCache().RemoveObserver(this); // Ensure search controller is released prior to speech_ui_. search_controller_.reset(); } void AppListViewDelegate::RegisterForNotifications() { registrar_.RemoveAll(); DCHECK(profile_); registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_SIGNED_OUT, content::NotificationService::AllSources()); } void AppListViewDelegate::OnProfileChanged() { model_ = app_list::AppListSyncableServiceFactory::GetForProfile( profile_)->model(); search_controller_.reset(new app_list::SearchController( profile_, model_->search_box(), model_->results(), speech_ui_.get(), controller_)); signin_delegate_.SetProfile(profile_); #if defined(USE_ASH) app_sync_ui_state_watcher_.reset(new AppSyncUIStateWatcher(profile_, model_)); #endif // Don't populate the app list users if we are on the ash desktop. chrome::HostDesktopType desktop = chrome::GetHostDesktopTypeForNativeWindow( controller_->GetAppListWindow()); if (desktop == chrome::HOST_DESKTOP_TYPE_ASH) return; // Populate the app list users. PopulateUsers(g_browser_process->profile_manager()->GetProfileInfoCache(), profile_->GetPath(), &users_); FOR_EACH_OBSERVER(app_list::AppListViewDelegateObserver, observers_, OnProfilesChanged()); } bool AppListViewDelegate::ForceNativeDesktop() const { return controller_->ForceNativeDesktop(); } void AppListViewDelegate::SetProfileByPath(const base::FilePath& profile_path) { DCHECK(model_); // The profile must be loaded before this is called. profile_ = g_browser_process->profile_manager()->GetProfileByPath(profile_path); DCHECK(profile_); RegisterForNotifications(); OnProfileChanged(); // Clear search query. model_->search_box()->SetText(base::string16()); } app_list::AppListModel* AppListViewDelegate::GetModel() { return model_; } app_list::SigninDelegate* AppListViewDelegate::GetSigninDelegate() { return &signin_delegate_; } app_list::SpeechUIModel* AppListViewDelegate::GetSpeechUI() { return speech_ui_.get(); } void AppListViewDelegate::GetShortcutPathForApp( const std::string& app_id, const base::Callback<void(const base::FilePath&)>& callback) { #if defined(OS_WIN) ExtensionService* service = profile_->GetExtensionService(); DCHECK(service); const extensions::Extension* extension = service->GetInstalledExtension(app_id); if (!extension) { callback.Run(base::FilePath()); return; } base::FilePath app_data_dir( web_app::GetWebAppDataDirectory(profile_->GetPath(), extension->id(), GURL())); web_app::UpdateShortcutInfoAndIconForApp( *extension, profile_, base::Bind(CreateShortcutInWebAppDir, app_data_dir, callback)); #else callback.Run(base::FilePath()); #endif } void AppListViewDelegate::StartSearch() { if (search_controller_) search_controller_->Start(); } void AppListViewDelegate::StopSearch() { if (search_controller_) search_controller_->Stop(); } void AppListViewDelegate::OpenSearchResult( app_list::SearchResult* result, bool auto_launch, int event_flags) { if (auto_launch) base::RecordAction(base::UserMetricsAction("AppList_AutoLaunched")); search_controller_->OpenResult(result, event_flags); } void AppListViewDelegate::InvokeSearchResultAction( app_list::SearchResult* result, int action_index, int event_flags) { search_controller_->InvokeResultAction(result, action_index, event_flags); } base::TimeDelta AppListViewDelegate::GetAutoLaunchTimeout() { return auto_launch_timeout_; } void AppListViewDelegate::AutoLaunchCanceled() { base::RecordAction(base::UserMetricsAction("AppList_AutoLaunchCanceled")); auto_launch_timeout_ = base::TimeDelta(); } void AppListViewDelegate::ViewInitialized() { content::WebContents* contents = GetSpeechRecognitionContents(); if (contents) { contents->GetWebUI()->CallJavascriptFunction( "appList.startPage.onAppListShown"); } } void AppListViewDelegate::Dismiss() { controller_->DismissView(); } void AppListViewDelegate::ViewClosing() { controller_->ViewClosing(); content::WebContents* contents = GetSpeechRecognitionContents(); if (contents) { contents->GetWebUI()->CallJavascriptFunction( "appList.startPage.onAppListHidden"); } } gfx::ImageSkia AppListViewDelegate::GetWindowIcon() { return controller_->GetWindowIcon(); } void AppListViewDelegate::OpenSettings() { ExtensionService* service = profile_->GetExtensionService(); DCHECK(service); const extensions::Extension* extension = service->GetInstalledExtension( extension_misc::kSettingsAppId); DCHECK(extension); controller_->ActivateApp(profile_, extension, AppListControllerDelegate::LAUNCH_FROM_UNKNOWN, 0); } void AppListViewDelegate::OpenHelp() { chrome::HostDesktopType desktop = chrome::GetHostDesktopTypeForNativeWindow( controller_->GetAppListWindow()); chrome::ScopedTabbedBrowserDisplayer displayer(profile_, desktop); content::OpenURLParams params(GURL(chrome::kAppLauncherHelpURL), content::Referrer(), NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_LINK, false); displayer.browser()->OpenURL(params); } void AppListViewDelegate::OpenFeedback() { chrome::HostDesktopType desktop = chrome::GetHostDesktopTypeForNativeWindow( controller_->GetAppListWindow()); Browser* browser = chrome::FindTabbedBrowser(profile_, false, desktop); chrome::ShowFeedbackPage(browser, std::string(), chrome::kAppLauncherCategoryTag); } void AppListViewDelegate::ToggleSpeechRecognition() { app_list::StartPageService* service = app_list::StartPageService::Get(profile_); if (service) service->ToggleSpeechRecognition(); } void AppListViewDelegate::ShowForProfileByPath( const base::FilePath& profile_path) { controller_->ShowForProfileByPath(profile_path); } void AppListViewDelegate::OnSpeechResult(const base::string16& result, bool is_final) { speech_ui_->SetSpeechResult(result, is_final); if (is_final) { auto_launch_timeout_ = base::TimeDelta::FromSeconds( kAutoLaunchDefaultTimeoutSec); model_->search_box()->SetText(result); } } void AppListViewDelegate::OnSpeechSoundLevelChanged(int16 level) { speech_ui_->UpdateSoundLevel(level); } void AppListViewDelegate::OnSpeechRecognitionStateChanged( app_list::SpeechRecognitionState new_state) { speech_ui_->SetSpeechRecognitionState(new_state); } void AppListViewDelegate::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { OnProfileChanged(); } void AppListViewDelegate::OnProfileAdded(const base::FilePath& profile_path) { OnProfileChanged(); } void AppListViewDelegate::OnProfileWasRemoved( const base::FilePath& profile_path, const base::string16& profile_name) { OnProfileChanged(); } void AppListViewDelegate::OnProfileNameChanged( const base::FilePath& profile_path, const base::string16& old_profile_name) { OnProfileChanged(); } content::WebContents* AppListViewDelegate::GetStartPageContents() { app_list::StartPageService* service = app_list::StartPageService::Get(profile_); if (!service) return NULL; return service->GetStartPageContents(); } content::WebContents* AppListViewDelegate::GetSpeechRecognitionContents() { app_list::StartPageService* service = app_list::StartPageService::Get(profile_); if (!service) return NULL; return service->GetSpeechRecognitionContents(); } const app_list::AppListViewDelegate::Users& AppListViewDelegate::GetUsers() const { return users_; } void AppListViewDelegate::AddObserver( app_list::AppListViewDelegateObserver* observer) { observers_.AddObserver(observer); } void AppListViewDelegate::RemoveObserver( app_list::AppListViewDelegateObserver* observer) { observers_.RemoveObserver(observer); } <commit_msg>Shorter timeout to auto-launch from the voice search.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/app_list_view_delegate.h" #include <vector> #include "base/callback.h" #include "base/files/file_path.h" #include "base/metrics/user_metrics.h" #include "base/stl_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/feedback/feedback_util.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/app_list/app_list_controller_delegate.h" #include "chrome/browser/ui/app_list/app_list_service.h" #include "chrome/browser/ui/app_list/app_list_syncable_service.h" #include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h" #include "chrome/browser/ui/app_list/search/search_controller.h" #include "chrome/browser/ui/app_list/start_page_service.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/scoped_tabbed_browser_displayer.h" #include "chrome/browser/ui/web_applications/web_app_ui.h" #include "chrome/browser/web_applications/web_app.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/url_constants.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/user_metrics.h" #include "grit/theme_resources.h" #include "ui/app_list/app_list_view_delegate_observer.h" #include "ui/app_list/search_box_model.h" #include "ui/app_list/speech_ui_model.h" #include "ui/base/resource/resource_bundle.h" #if defined(USE_ASH) #include "chrome/browser/ui/ash/app_list/app_sync_ui_state_watcher.h" #endif #if defined(OS_WIN) #include "chrome/browser/web_applications/web_app_win.h" #endif namespace { const int kAutoLaunchDefaultTimeoutMilliSec = 50; #if defined(OS_WIN) void CreateShortcutInWebAppDir( const base::FilePath& app_data_dir, base::Callback<void(const base::FilePath&)> callback, const ShellIntegration::ShortcutInfo& info) { content::BrowserThread::PostTaskAndReplyWithResult( content::BrowserThread::FILE, FROM_HERE, base::Bind(web_app::CreateShortcutInWebAppDir, app_data_dir, info), callback); } #endif void PopulateUsers(const ProfileInfoCache& profile_info, const base::FilePath& active_profile_path, app_list::AppListViewDelegate::Users* users) { users->clear(); const size_t count = profile_info.GetNumberOfProfiles(); for (size_t i = 0; i < count; ++i) { // Don't display managed users. if (profile_info.ProfileIsManagedAtIndex(i)) continue; app_list::AppListViewDelegate::User user; user.name = profile_info.GetNameOfProfileAtIndex(i); user.email = profile_info.GetUserNameOfProfileAtIndex(i); user.profile_path = profile_info.GetPathOfProfileAtIndex(i); user.active = active_profile_path == user.profile_path; users->push_back(user); } } } // namespace AppListViewDelegate::AppListViewDelegate(Profile* profile, AppListControllerDelegate* controller) : controller_(controller), profile_(profile), model_(NULL) { CHECK(controller_); RegisterForNotifications(); g_browser_process->profile_manager()->GetProfileInfoCache().AddObserver(this); app_list::StartPageService* service = app_list::StartPageService::Get(profile_); speech_ui_.reset(new app_list::SpeechUIModel( service ? service->state() : app_list::SPEECH_RECOGNITION_OFF)); #if defined(GOOGLE_CHROME_BUILD) speech_ui_->set_logo( *ui::ResourceBundle::GetSharedInstance(). GetImageSkiaNamed(IDR_APP_LIST_GOOGLE_LOGO_VOICE_SEARCH)); #endif OnProfileChanged(); // sets model_ if (service) service->AddObserver(this); } AppListViewDelegate::~AppListViewDelegate() { app_list::StartPageService* service = app_list::StartPageService::Get(profile_); if (service) service->RemoveObserver(this); g_browser_process-> profile_manager()->GetProfileInfoCache().RemoveObserver(this); // Ensure search controller is released prior to speech_ui_. search_controller_.reset(); } void AppListViewDelegate::RegisterForNotifications() { registrar_.RemoveAll(); DCHECK(profile_); registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_SIGNED_OUT, content::NotificationService::AllSources()); } void AppListViewDelegate::OnProfileChanged() { model_ = app_list::AppListSyncableServiceFactory::GetForProfile( profile_)->model(); search_controller_.reset(new app_list::SearchController( profile_, model_->search_box(), model_->results(), speech_ui_.get(), controller_)); signin_delegate_.SetProfile(profile_); #if defined(USE_ASH) app_sync_ui_state_watcher_.reset(new AppSyncUIStateWatcher(profile_, model_)); #endif // Don't populate the app list users if we are on the ash desktop. chrome::HostDesktopType desktop = chrome::GetHostDesktopTypeForNativeWindow( controller_->GetAppListWindow()); if (desktop == chrome::HOST_DESKTOP_TYPE_ASH) return; // Populate the app list users. PopulateUsers(g_browser_process->profile_manager()->GetProfileInfoCache(), profile_->GetPath(), &users_); FOR_EACH_OBSERVER(app_list::AppListViewDelegateObserver, observers_, OnProfilesChanged()); } bool AppListViewDelegate::ForceNativeDesktop() const { return controller_->ForceNativeDesktop(); } void AppListViewDelegate::SetProfileByPath(const base::FilePath& profile_path) { DCHECK(model_); // The profile must be loaded before this is called. profile_ = g_browser_process->profile_manager()->GetProfileByPath(profile_path); DCHECK(profile_); RegisterForNotifications(); OnProfileChanged(); // Clear search query. model_->search_box()->SetText(base::string16()); } app_list::AppListModel* AppListViewDelegate::GetModel() { return model_; } app_list::SigninDelegate* AppListViewDelegate::GetSigninDelegate() { return &signin_delegate_; } app_list::SpeechUIModel* AppListViewDelegate::GetSpeechUI() { return speech_ui_.get(); } void AppListViewDelegate::GetShortcutPathForApp( const std::string& app_id, const base::Callback<void(const base::FilePath&)>& callback) { #if defined(OS_WIN) ExtensionService* service = profile_->GetExtensionService(); DCHECK(service); const extensions::Extension* extension = service->GetInstalledExtension(app_id); if (!extension) { callback.Run(base::FilePath()); return; } base::FilePath app_data_dir( web_app::GetWebAppDataDirectory(profile_->GetPath(), extension->id(), GURL())); web_app::UpdateShortcutInfoAndIconForApp( *extension, profile_, base::Bind(CreateShortcutInWebAppDir, app_data_dir, callback)); #else callback.Run(base::FilePath()); #endif } void AppListViewDelegate::StartSearch() { if (search_controller_) search_controller_->Start(); } void AppListViewDelegate::StopSearch() { if (search_controller_) search_controller_->Stop(); } void AppListViewDelegate::OpenSearchResult( app_list::SearchResult* result, bool auto_launch, int event_flags) { if (auto_launch) base::RecordAction(base::UserMetricsAction("AppList_AutoLaunched")); search_controller_->OpenResult(result, event_flags); } void AppListViewDelegate::InvokeSearchResultAction( app_list::SearchResult* result, int action_index, int event_flags) { search_controller_->InvokeResultAction(result, action_index, event_flags); } base::TimeDelta AppListViewDelegate::GetAutoLaunchTimeout() { return auto_launch_timeout_; } void AppListViewDelegate::AutoLaunchCanceled() { base::RecordAction(base::UserMetricsAction("AppList_AutoLaunchCanceled")); auto_launch_timeout_ = base::TimeDelta(); } void AppListViewDelegate::ViewInitialized() { content::WebContents* contents = GetSpeechRecognitionContents(); if (contents) { contents->GetWebUI()->CallJavascriptFunction( "appList.startPage.onAppListShown"); } } void AppListViewDelegate::Dismiss() { controller_->DismissView(); } void AppListViewDelegate::ViewClosing() { controller_->ViewClosing(); content::WebContents* contents = GetSpeechRecognitionContents(); if (contents) { contents->GetWebUI()->CallJavascriptFunction( "appList.startPage.onAppListHidden"); } } gfx::ImageSkia AppListViewDelegate::GetWindowIcon() { return controller_->GetWindowIcon(); } void AppListViewDelegate::OpenSettings() { ExtensionService* service = profile_->GetExtensionService(); DCHECK(service); const extensions::Extension* extension = service->GetInstalledExtension( extension_misc::kSettingsAppId); DCHECK(extension); controller_->ActivateApp(profile_, extension, AppListControllerDelegate::LAUNCH_FROM_UNKNOWN, 0); } void AppListViewDelegate::OpenHelp() { chrome::HostDesktopType desktop = chrome::GetHostDesktopTypeForNativeWindow( controller_->GetAppListWindow()); chrome::ScopedTabbedBrowserDisplayer displayer(profile_, desktop); content::OpenURLParams params(GURL(chrome::kAppLauncherHelpURL), content::Referrer(), NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_LINK, false); displayer.browser()->OpenURL(params); } void AppListViewDelegate::OpenFeedback() { chrome::HostDesktopType desktop = chrome::GetHostDesktopTypeForNativeWindow( controller_->GetAppListWindow()); Browser* browser = chrome::FindTabbedBrowser(profile_, false, desktop); chrome::ShowFeedbackPage(browser, std::string(), chrome::kAppLauncherCategoryTag); } void AppListViewDelegate::ToggleSpeechRecognition() { app_list::StartPageService* service = app_list::StartPageService::Get(profile_); if (service) service->ToggleSpeechRecognition(); } void AppListViewDelegate::ShowForProfileByPath( const base::FilePath& profile_path) { controller_->ShowForProfileByPath(profile_path); } void AppListViewDelegate::OnSpeechResult(const base::string16& result, bool is_final) { speech_ui_->SetSpeechResult(result, is_final); if (is_final) { auto_launch_timeout_ = base::TimeDelta::FromMilliseconds( kAutoLaunchDefaultTimeoutMilliSec); model_->search_box()->SetText(result); } } void AppListViewDelegate::OnSpeechSoundLevelChanged(int16 level) { speech_ui_->UpdateSoundLevel(level); } void AppListViewDelegate::OnSpeechRecognitionStateChanged( app_list::SpeechRecognitionState new_state) { speech_ui_->SetSpeechRecognitionState(new_state); } void AppListViewDelegate::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { OnProfileChanged(); } void AppListViewDelegate::OnProfileAdded(const base::FilePath& profile_path) { OnProfileChanged(); } void AppListViewDelegate::OnProfileWasRemoved( const base::FilePath& profile_path, const base::string16& profile_name) { OnProfileChanged(); } void AppListViewDelegate::OnProfileNameChanged( const base::FilePath& profile_path, const base::string16& old_profile_name) { OnProfileChanged(); } content::WebContents* AppListViewDelegate::GetStartPageContents() { app_list::StartPageService* service = app_list::StartPageService::Get(profile_); if (!service) return NULL; return service->GetStartPageContents(); } content::WebContents* AppListViewDelegate::GetSpeechRecognitionContents() { app_list::StartPageService* service = app_list::StartPageService::Get(profile_); if (!service) return NULL; return service->GetSpeechRecognitionContents(); } const app_list::AppListViewDelegate::Users& AppListViewDelegate::GetUsers() const { return users_; } void AppListViewDelegate::AddObserver( app_list::AppListViewDelegateObserver* observer) { observers_.AddObserver(observer); } void AppListViewDelegate::RemoveObserver( app_list::AppListViewDelegateObserver* observer) { observers_.RemoveObserver(observer); } <|endoftext|>
<commit_before>// Filename: dcparse.cxx // Created by: drose (05Oct00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // [email protected] . // //////////////////////////////////////////////////////////////////// #include "dcbase.h" #include "dcFile.h" #ifndef HAVE_GETOPT #include "gnu_getopt.h" #else #include <getopt.h> #endif void usage() { cerr << "\n" "Usage:\n\n" "dcparse [-v | -b] [file1 file2 ...]\n" "dcparse -h\n\n"; } void help() { usage(); cerr << "This program reads one or more DC files, which are used to describe the\n" "communication channels in the distributed class system. By default,\n" "the file(s) are read and concatenated, and a single hash code is printed\n" "corresponding to the file's contents.\n\n" "With -b, this writes a brief version of the file to standard output\n" "instead. With -v, this writes a more verbose version.\n\n"; } int main(int argc, char *argv[]) { // extern char *optarg; extern int optind; const char *optstr = "bvh"; bool dump_verbose = false; bool dump_brief = false; int flag = getopt(argc, argv, optstr); while (flag != EOF) { switch (flag) { case 'b': dump_brief = true; break; case 'v': dump_verbose = true; break; case 'h': help(); exit(1); default: exit(1); } flag = getopt(argc, argv, optstr); } argc -= (optind-1); argv += (optind-1); if (argc < 2) { usage(); exit(1); } DCFile file; for (int i = 1; i < argc; i++) { if (!file.read(argv[i])) { return (1); } } if (!file.all_classes_valid() && !dump_brief) { cerr << "File is incomplete. The following classes are undefined:\n"; int num_classes = file.get_num_classes(); for (int i = 0; i < num_classes; i++) { DCClass *dclass = file.get_class(i); if (dclass->is_bogus_class()) { cerr << " " << dclass->get_name() << "\n"; } } return (1); } if (dump_verbose || dump_brief) { if (!file.write(cout, dump_brief)) { return (1); } } else { long hash = file.get_hash(); cerr << "File hash is " << hash << "\n"; } return (0); } <commit_msg>allow undefined typedefs like classes<commit_after>// Filename: dcparse.cxx // Created by: drose (05Oct00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // [email protected] . // //////////////////////////////////////////////////////////////////// #include "dcbase.h" #include "dcFile.h" #include "dcClass.h" #include "dcTypedef.h" #ifndef HAVE_GETOPT #include "gnu_getopt.h" #else #include <getopt.h> #endif void usage() { cerr << "\n" "Usage:\n\n" "dcparse [-v | -b] [file1 file2 ...]\n" "dcparse -h\n\n"; } void help() { usage(); cerr << "This program reads one or more DC files, which are used to describe the\n" "communication channels in the distributed class system. By default,\n" "the file(s) are read and concatenated, and a single hash code is printed\n" "corresponding to the file's contents.\n\n" "With -b, this writes a brief version of the file to standard output\n" "instead. With -v, this writes a more verbose version.\n\n"; } int main(int argc, char *argv[]) { // extern char *optarg; extern int optind; const char *optstr = "bvh"; bool dump_verbose = false; bool dump_brief = false; int flag = getopt(argc, argv, optstr); while (flag != EOF) { switch (flag) { case 'b': dump_brief = true; break; case 'v': dump_verbose = true; break; case 'h': help(); exit(1); default: exit(1); } flag = getopt(argc, argv, optstr); } argc -= (optind-1); argv += (optind-1); if (argc < 2) { usage(); exit(1); } DCFile file; for (int i = 1; i < argc; i++) { if (!file.read(argv[i])) { return (1); } } if (!file.all_objects_valid() && !dump_brief) { cerr << "File is incomplete. The following objects are undefined:\n"; int num_typedefs = file.get_num_typedefs(); for (int i = 0; i < num_typedefs; i++) { DCTypedef *dtypedef = file.get_typedef(i); if (dtypedef->is_bogus_typedef()) { cerr << " " << dtypedef->get_name() << "\n"; } } int num_classes = file.get_num_classes(); for (int i = 0; i < num_classes; i++) { DCClass *dclass = file.get_class(i); if (dclass->is_bogus_class()) { cerr << " " << dclass->get_name() << "\n"; } } return (1); } if (dump_verbose || dump_brief) { if (!file.write(cout, dump_brief)) { return (1); } } else { long hash = file.get_hash(); cerr << "File hash is " << hash << "\n"; } return (0); } <|endoftext|>
<commit_before>/* * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "IconLoader.h" #include "Document.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" #include "IconDatabase.h" #include "Logging.h" #include "ResourceHandle.h" #include "ResourceResponse.h" #include "ResourceRequest.h" #include "SubresourceLoader.h" using namespace std; namespace WebCore { IconLoader::IconLoader(Frame* frame) : m_frame(frame) , m_loadIsInProgress(false) { } auto_ptr<IconLoader> IconLoader::create(Frame* frame) { return auto_ptr<IconLoader>(new IconLoader(frame)); } IconLoader::~IconLoader() { } void IconLoader::startLoading() { if (m_resourceLoader) return; // FIXME: http://bugs.webkit.org/show_bug.cgi?id=10902 // Once ResourceHandle will load without a DocLoader, we can remove this check. // A frame may be documentless - one example is a frame containing only a PDF. if (!m_frame->document()) { LOG(IconDatabase, "Documentless-frame - icon won't be loaded"); return; } // Set flag so we can detect the case where the load completes before // SubresourceLoader::create returns. m_loadIsInProgress = true; RefPtr<SubresourceLoader> loader = SubresourceLoader::create(m_frame, this, m_frame->loader()->iconURL()); if (!loader) LOG_ERROR("Failed to start load for icon at url %s", m_frame->loader()->iconURL().url().ascii()); // Store the handle so we can cancel the load if stopLoading is called later. // But only do it if the load hasn't already completed. if (m_loadIsInProgress) m_resourceLoader = loader.release(); } void IconLoader::stopLoading() { clearLoadingState(); } void IconLoader::didReceiveResponse(SubresourceLoader* resourceLoader, const ResourceResponse& response) { // If we got a status code indicating an invalid response, then lets // ignore the data and not try to decode the error page as an icon. int status = response.httpStatusCode(); LOG(IconDatabase, "IconLoader::didReceiveResponse() - Loader %p, response %i", resourceLoader, status); if (status && (status < 200 || status > 299)) { ResourceHandle* handle = resourceLoader->handle(); finishLoading(handle ? handle->url() : KURL()); m_resourceLoader = 0; } } void IconLoader::didReceiveData(SubresourceLoader* loader, const char*, int size) { LOG(IconDatabase, "IconLoader::didReceiveData() - Loader %p, number of bytes %i", loader, size); } void IconLoader::didFail(SubresourceLoader* resourceLoader, const ResourceError&) { LOG(IconDatabase, "IconLoader::didFail() - Loader %p", resourceLoader); ASSERT(resourceLoader == m_resourceLoader); ASSERT(m_loadIsInProgress); ResourceHandle* handle = resourceLoader->handle(); finishLoading(handle ? handle->url() : KURL()); } void IconLoader::didFinishLoading(SubresourceLoader* resourceLoader) { LOG(IconDatabase, "IconLoader::didFinishLoading() - Loader %p", resourceLoader); // If the icon load resulted in an error-response earlier, the ResourceHandle was killed and icon data commited via finishLoading(). // In that case this didFinishLoading callback is pointless and we bail. Otherwise, finishLoading() as expected if (m_loadIsInProgress) { ASSERT(resourceLoader == m_resourceLoader); ResourceHandle* handle = resourceLoader->handle(); finishLoading(handle ? handle->url() : KURL()); } } void IconLoader::finishLoading(const KURL& iconURL) { // <rdar://5071341> - Crash in IconLoader::finishLoading() // In certain circumstance where there is no favicon and the site's 404 page is large and complex, the IconLoader can get // cancelled/failed twice. Reproducibility of this phenomenom is unknown, so we'd like to catch this case in debug builds, // but must handle it gracefully in release ASSERT(m_resourceLoader); if (!iconURL.isEmpty() && m_resourceLoader) { iconDatabase()->setIconDataForIconURL(m_resourceLoader->resourceData(), iconURL.url()); LOG(IconDatabase, "IconLoader::finishLoading() - Committing iconURL %s to database", iconURL.url().ascii()); m_frame->loader()->commitIconURLToIconDatabase(iconURL); m_frame->loader()->client()->dispatchDidReceiveIcon(); } clearLoadingState(); } void IconLoader::clearLoadingState() { m_resourceLoader = 0; m_loadIsInProgress = false; } } <commit_msg>Fix spelling.<commit_after>/* * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "IconLoader.h" #include "Document.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" #include "IconDatabase.h" #include "Logging.h" #include "ResourceHandle.h" #include "ResourceResponse.h" #include "ResourceRequest.h" #include "SubresourceLoader.h" using namespace std; namespace WebCore { IconLoader::IconLoader(Frame* frame) : m_frame(frame) , m_loadIsInProgress(false) { } auto_ptr<IconLoader> IconLoader::create(Frame* frame) { return auto_ptr<IconLoader>(new IconLoader(frame)); } IconLoader::~IconLoader() { } void IconLoader::startLoading() { if (m_resourceLoader) return; // FIXME: http://bugs.webkit.org/show_bug.cgi?id=10902 // Once ResourceHandle will load without a DocLoader, we can remove this check. // A frame may be documentless - one example is a frame containing only a PDF. if (!m_frame->document()) { LOG(IconDatabase, "Documentless-frame - icon won't be loaded"); return; } // Set flag so we can detect the case where the load completes before // SubresourceLoader::create returns. m_loadIsInProgress = true; RefPtr<SubresourceLoader> loader = SubresourceLoader::create(m_frame, this, m_frame->loader()->iconURL()); if (!loader) LOG_ERROR("Failed to start load for icon at url %s", m_frame->loader()->iconURL().url().ascii()); // Store the handle so we can cancel the load if stopLoading is called later. // But only do it if the load hasn't already completed. if (m_loadIsInProgress) m_resourceLoader = loader.release(); } void IconLoader::stopLoading() { clearLoadingState(); } void IconLoader::didReceiveResponse(SubresourceLoader* resourceLoader, const ResourceResponse& response) { // If we got a status code indicating an invalid response, then lets // ignore the data and not try to decode the error page as an icon. int status = response.httpStatusCode(); LOG(IconDatabase, "IconLoader::didReceiveResponse() - Loader %p, response %i", resourceLoader, status); if (status && (status < 200 || status > 299)) { ResourceHandle* handle = resourceLoader->handle(); finishLoading(handle ? handle->url() : KURL()); m_resourceLoader = 0; } } void IconLoader::didReceiveData(SubresourceLoader* loader, const char*, int size) { LOG(IconDatabase, "IconLoader::didReceiveData() - Loader %p, number of bytes %i", loader, size); } void IconLoader::didFail(SubresourceLoader* resourceLoader, const ResourceError&) { LOG(IconDatabase, "IconLoader::didFail() - Loader %p", resourceLoader); ASSERT(resourceLoader == m_resourceLoader); ASSERT(m_loadIsInProgress); ResourceHandle* handle = resourceLoader->handle(); finishLoading(handle ? handle->url() : KURL()); } void IconLoader::didFinishLoading(SubresourceLoader* resourceLoader) { LOG(IconDatabase, "IconLoader::didFinishLoading() - Loader %p", resourceLoader); // If the icon load resulted in an error-response earlier, the ResourceHandle was killed and icon data commited via finishLoading(). // In that case this didFinishLoading callback is pointless and we bail. Otherwise, finishLoading() as expected if (m_loadIsInProgress) { ASSERT(resourceLoader == m_resourceLoader); ResourceHandle* handle = resourceLoader->handle(); finishLoading(handle ? handle->url() : KURL()); } } void IconLoader::finishLoading(const KURL& iconURL) { // <rdar://5071341> - Crash in IconLoader::finishLoading() // In certain circumstance where there is no favicon and the site's 404 page is large and complex, the IconLoader can get // cancelled/failed twice. Reproducibility of this phenomenon is unknown, so we'd like to catch this case in debug builds, // but must handle it gracefully in release ASSERT(m_resourceLoader); if (!iconURL.isEmpty() && m_resourceLoader) { iconDatabase()->setIconDataForIconURL(m_resourceLoader->resourceData(), iconURL.url()); LOG(IconDatabase, "IconLoader::finishLoading() - Committing iconURL %s to database", iconURL.url().ascii()); m_frame->loader()->commitIconURLToIconDatabase(iconURL); m_frame->loader()->client()->dispatchDidReceiveIcon(); } clearLoadingState(); } void IconLoader::clearLoadingState() { m_resourceLoader = 0; m_loadIsInProgress = false; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "triangle_list_marker.h" #include "marker_selection_handler.h" #include "rviz/default_plugin/marker_display.h" #include "rviz/selection/selection_manager.h" #include "rviz/uniform_string_stream.h" #include "rviz/display_context.h" #include "rviz/mesh_loader.h" #include "marker_display.h" #include <OgreSceneNode.h> #include <OgreSceneManager.h> #include <OgreManualObject.h> #include <OgreMaterialManager.h> #include <OgreTextureManager.h> #include <OgreTechnique.h> namespace rviz { TriangleListMarker::TriangleListMarker(MarkerDisplay* owner, DisplayContext* context, Ogre::SceneNode* parent_node) : MarkerBase(owner, context, parent_node) , manual_object_(0) { } TriangleListMarker::~TriangleListMarker() { context_->getSceneManager()->destroyManualObject(manual_object_); material_->unload(); Ogre::MaterialManager::getSingleton().remove(material_->getName()); } void TriangleListMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message) { ROS_ASSERT(new_message->type == visualization_msgs::Marker::TRIANGLE_LIST); size_t num_points = new_message->points.size(); if( (num_points % 3) != 0 || num_points == 0 ) { std::stringstream ss; if( num_points == 0 ) { ss << "TriMesh marker [" << getStringID() << "] has no points."; } else { ss << "TriMesh marker [" << getStringID() << "] has a point count which is not divisible by 3 [" << num_points <<"]"; } if ( owner_ ) { owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str()); } ROS_DEBUG("%s", ss.str().c_str()); scene_node_->setVisible( false ); return; } else { scene_node_->setVisible( true ); } if (!manual_object_) { static uint32_t count = 0; UniformStringStream ss; ss << "Triangle List Marker" << count++; manual_object_ = context_->getSceneManager()->createManualObject(ss.str()); scene_node_->attachObject(manual_object_); ss << "Material"; material_name_ = ss.str(); material_ = Ogre::MaterialManager::getSingleton().create( material_name_, ROS_PACKAGE_NAME ); material_->setReceiveShadows(false); material_->getTechnique(0)->setLightingEnabled(true); material_->setCullingMode(Ogre::CULL_NONE); handler_.reset( new MarkerSelectionHandler( this, MarkerID( new_message->ns, new_message->id ), context_ )); } Ogre::Vector3 pos, scale; Ogre::Quaternion orient; if (!transform(new_message, pos, orient, scale)) { ROS_DEBUG("Unable to transform marker message"); scene_node_->setVisible( false ); return; } if ( owner_ && (new_message->scale.x * new_message->scale.y * new_message->scale.z == 0.0f) ) { owner_->setMarkerStatus(getID(), StatusProperty::Warn, "Scale of 0 in one of x/y/z"); } setPosition(pos); setOrientation(orient); scene_node_->setScale(scale); // If we have the same number of tris as previously, just update the object if (old_message && num_points == old_message->points.size()) { manual_object_->beginUpdate(0); } else // Otherwise clear it and begin anew { manual_object_->clear(); manual_object_->estimateVertexCount(num_points); manual_object_->begin(material_name_, Ogre::RenderOperation::OT_TRIANGLE_LIST); } bool has_vertex_colors = new_message->colors.size() == num_points; bool has_face_colors = new_message->colors.size() == num_points / 3; bool any_vertex_has_alpha = false; const std::vector<geometry_msgs::Point>& points = new_message->points; for(size_t i = 0; i < num_points; i += 3) { std::vector<Ogre::Vector3> corners(3); for(size_t c = 0; c < 3; c++) { corners[c] = Ogre::Vector3(points[i+c].x, points[i+c].y, points[i+c].z); } Ogre::Vector3 normal = (corners[1] - corners[0]).crossProduct(corners[2] - corners[0]); normal.normalise(); for(size_t c = 0; c < 3; c++) { manual_object_->position(corners[c]); manual_object_->normal(normal); if(has_vertex_colors) { any_vertex_has_alpha = any_vertex_has_alpha || (new_message->colors[i+c].a < 0.9998); manual_object_->colour(new_message->colors[i+c].r, new_message->colors[i+c].g, new_message->colors[i+c].b, new_message->color.a * new_message->colors[i+c].a); } else if (has_face_colors) { any_vertex_has_alpha = any_vertex_has_alpha || (new_message->colors[i/3].a < 0.9998); manual_object_->colour(new_message->colors[i/3].r, new_message->colors[i/3].g, new_message->colors[i/3].b, new_message->color.a * new_message->colors[i/3].a); } } } manual_object_->end(); if (has_vertex_colors || has_face_colors) { material_->getTechnique(0)->setLightingEnabled(false); } else { material_->getTechnique(0)->setLightingEnabled(true); float r,g,b,a; r = new_message->color.r; g = new_message->color.g; b = new_message->color.b; a = new_message->color.a; material_->getTechnique(0)->setAmbient( r/2,g/2,b/2 ); material_->getTechnique(0)->setDiffuse( r,g,b,a ); } if( (!has_vertex_colors && new_message->color.a < 0.9998) || (has_vertex_colors && any_vertex_has_alpha)) { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA ); material_->getTechnique(0)->setDepthWriteEnabled( false ); } else { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE ); material_->getTechnique(0)->setDepthWriteEnabled( true ); } handler_->addTrackedObject( manual_object_ ); } S_MaterialPtr TriangleListMarker::getMaterials() { S_MaterialPtr materials; materials.insert( material_ ); return materials; } } <commit_msg>Only tear down objects if they've been created #1163 (#1164)<commit_after>/* * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "triangle_list_marker.h" #include "marker_selection_handler.h" #include "rviz/default_plugin/marker_display.h" #include "rviz/selection/selection_manager.h" #include "rviz/uniform_string_stream.h" #include "rviz/display_context.h" #include "rviz/mesh_loader.h" #include "marker_display.h" #include <OgreSceneNode.h> #include <OgreSceneManager.h> #include <OgreManualObject.h> #include <OgreMaterialManager.h> #include <OgreTextureManager.h> #include <OgreTechnique.h> namespace rviz { TriangleListMarker::TriangleListMarker(MarkerDisplay* owner, DisplayContext* context, Ogre::SceneNode* parent_node) : MarkerBase(owner, context, parent_node) , manual_object_(0) { } TriangleListMarker::~TriangleListMarker() { if (manual_object_) { context_->getSceneManager()->destroyManualObject(manual_object_); material_->unload(); Ogre::MaterialManager::getSingleton().remove(material_->getName()); } } void TriangleListMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message) { ROS_ASSERT(new_message->type == visualization_msgs::Marker::TRIANGLE_LIST); size_t num_points = new_message->points.size(); if( (num_points % 3) != 0 || num_points == 0 ) { std::stringstream ss; if( num_points == 0 ) { ss << "TriMesh marker [" << getStringID() << "] has no points."; } else { ss << "TriMesh marker [" << getStringID() << "] has a point count which is not divisible by 3 [" << num_points <<"]"; } if ( owner_ ) { owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str()); } ROS_DEBUG("%s", ss.str().c_str()); scene_node_->setVisible( false ); return; } else { scene_node_->setVisible( true ); } if (!manual_object_) { static uint32_t count = 0; UniformStringStream ss; ss << "Triangle List Marker" << count++; manual_object_ = context_->getSceneManager()->createManualObject(ss.str()); scene_node_->attachObject(manual_object_); ss << "Material"; material_name_ = ss.str(); material_ = Ogre::MaterialManager::getSingleton().create( material_name_, ROS_PACKAGE_NAME ); material_->setReceiveShadows(false); material_->getTechnique(0)->setLightingEnabled(true); material_->setCullingMode(Ogre::CULL_NONE); handler_.reset( new MarkerSelectionHandler( this, MarkerID( new_message->ns, new_message->id ), context_ )); } Ogre::Vector3 pos, scale; Ogre::Quaternion orient; if (!transform(new_message, pos, orient, scale)) { ROS_DEBUG("Unable to transform marker message"); scene_node_->setVisible( false ); return; } if ( owner_ && (new_message->scale.x * new_message->scale.y * new_message->scale.z == 0.0f) ) { owner_->setMarkerStatus(getID(), StatusProperty::Warn, "Scale of 0 in one of x/y/z"); } setPosition(pos); setOrientation(orient); scene_node_->setScale(scale); // If we have the same number of tris as previously, just update the object if (old_message && num_points == old_message->points.size()) { manual_object_->beginUpdate(0); } else // Otherwise clear it and begin anew { manual_object_->clear(); manual_object_->estimateVertexCount(num_points); manual_object_->begin(material_name_, Ogre::RenderOperation::OT_TRIANGLE_LIST); } bool has_vertex_colors = new_message->colors.size() == num_points; bool has_face_colors = new_message->colors.size() == num_points / 3; bool any_vertex_has_alpha = false; const std::vector<geometry_msgs::Point>& points = new_message->points; for(size_t i = 0; i < num_points; i += 3) { std::vector<Ogre::Vector3> corners(3); for(size_t c = 0; c < 3; c++) { corners[c] = Ogre::Vector3(points[i+c].x, points[i+c].y, points[i+c].z); } Ogre::Vector3 normal = (corners[1] - corners[0]).crossProduct(corners[2] - corners[0]); normal.normalise(); for(size_t c = 0; c < 3; c++) { manual_object_->position(corners[c]); manual_object_->normal(normal); if(has_vertex_colors) { any_vertex_has_alpha = any_vertex_has_alpha || (new_message->colors[i+c].a < 0.9998); manual_object_->colour(new_message->colors[i+c].r, new_message->colors[i+c].g, new_message->colors[i+c].b, new_message->color.a * new_message->colors[i+c].a); } else if (has_face_colors) { any_vertex_has_alpha = any_vertex_has_alpha || (new_message->colors[i/3].a < 0.9998); manual_object_->colour(new_message->colors[i/3].r, new_message->colors[i/3].g, new_message->colors[i/3].b, new_message->color.a * new_message->colors[i/3].a); } } } manual_object_->end(); if (has_vertex_colors || has_face_colors) { material_->getTechnique(0)->setLightingEnabled(false); } else { material_->getTechnique(0)->setLightingEnabled(true); float r,g,b,a; r = new_message->color.r; g = new_message->color.g; b = new_message->color.b; a = new_message->color.a; material_->getTechnique(0)->setAmbient( r/2,g/2,b/2 ); material_->getTechnique(0)->setDiffuse( r,g,b,a ); } if( (!has_vertex_colors && new_message->color.a < 0.9998) || (has_vertex_colors && any_vertex_has_alpha)) { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA ); material_->getTechnique(0)->setDepthWriteEnabled( false ); } else { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE ); material_->getTechnique(0)->setDepthWriteEnabled( true ); } handler_->addTrackedObject( manual_object_ ); } S_MaterialPtr TriangleListMarker::getMaterials() { S_MaterialPtr materials; materials.insert( material_ ); return materials; } } <|endoftext|>
<commit_before>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "models/sagtension/line_cable_to_catenary_cable_converter.h" #include "models/transmissionline/cable_unit_load_calculator.h" #include "models/transmissionline/line_cable_to_catenary_converter.h" LineCableToCatenaryCableConverter::LineCableToCatenaryCableConverter() { case_stretch_ = nullptr; line_cable_ = nullptr; is_updated_catenarycable_ = false; } LineCableToCatenaryCableConverter::~LineCableToCatenaryCableConverter() { } CatenaryCable LineCableToCatenaryCableConverter::GetCatenaryCable() const { // updates class if necessary if (IsUpdated() == false) { if (Update() == false) { return CatenaryCable(); } } return catenary_cable_; } bool LineCableToCatenaryCableConverter::Validate( const bool& is_included_warnings, std::list<std::string>* messages_error) const { // initializes bool is_valid = true; // validates case-stretch if (case_stretch_ == nullptr) { is_valid = false; if (messages_error != nullptr) { messages_error->push_back("LINE CABLE TO CATENARY CABLE CONVERTER - " "Invalid stretch case"); } } else { if (case_stretch_->Validate(is_included_warnings, messages_error) == false) { is_valid = false; } } // validates line cable if (line_cable_ == nullptr) { is_valid = false; if (messages_error != nullptr) { messages_error->push_back("LINE CABLE TO CATENARY CABLE CONVERTER - " "Invalid line cable"); } } else { if (line_cable_->Validate(is_included_warnings, messages_error) == false) { is_valid = false; } } // validates type-stretch if ((type_stretch_ != CableConditionType::kCreep) && (type_stretch_ != CableConditionType::kLoad)) { is_valid = false; if (messages_error != nullptr) { messages_error->push_back("LINE CABLE TO CATENARY CABLE CONVERTER - " "Invalid stretch type"); } } // further validates if (is_valid == true) { // validates update process if (Update() == false) { is_valid = false; if (messages_error != nullptr) { messages_error->push_back("LINE CABLE TO CATENARY CABLE CONVERTER - " "Error updating class"); } } } return is_valid; } const WeatherLoadCase* LineCableToCatenaryCableConverter::case_stretch() const { return case_stretch_; } const LineCable* LineCableToCatenaryCableConverter::line_cable() const { return line_cable_; } void LineCableToCatenaryCableConverter::set_line_cable( const LineCable* line_cable) { line_cable_ = line_cable; is_updated_catenarycable_ = false; } void LineCableToCatenaryCableConverter::set_case_stretch( const WeatherLoadCase* case_stretch) { case_stretch_ = case_stretch; CableState state; state.temperature_stretch = case_stretch->temperature_cable; catenary_cable_.set_state(state); is_updated_catenarycable_ = false; } void LineCableToCatenaryCableConverter::set_type_stretch( const CableConditionType& type_stretch) { type_stretch_ = type_stretch; is_updated_catenarycable_ = false; } CableConditionType LineCableToCatenaryCableConverter::type_stretch() const { return type_stretch_; } double LineCableToCatenaryCableConverter::LoadStretchDifference( const double& load_stretch) const { // updates catenary cable and reloader with new stretch load UpdateCatenaryCableState(load_stretch); reloader_.set_catenary_cable(&catenary_cable_); // reloads the catenary cable at the stretch load case const CatenaryCable catenary_cable_reloaded = reloader_.CatenaryCableReloaded(); const double tension_average_reloaded = catenary_cable_reloaded.TensionAverage(); // calculates difference between reloaded and defined stretch load return tension_average_reloaded - load_stretch; } bool LineCableToCatenaryCableConverter::InitializeReloader() const { // builds state CableState state_reloader; state_reloader.load_stretch = 0; state_reloader.temperature = case_stretch_->temperature_cable; state_reloader.temperature_stretch = 0; // solves for reloaded unit weight CableUnitLoadCalculator calculator_unitload; calculator_unitload.set_diameter_cable(&line_cable_->cable->diameter); calculator_unitload.set_weight_unit_cable(&line_cable_->cable->weight_unit); const Vector3d weight_unit_reloaded = calculator_unitload.UnitCableLoad(*case_stretch_); // initializes reloader reloader_.set_state_reloaded(state_reloader); reloader_.set_weight_unit_reloaded(weight_unit_reloaded); return true; } bool LineCableToCatenaryCableConverter::IsUpdated() const { if (is_updated_catenarycable_ == true) { return true; } else { return false; } } /// This function is an iterative solution that reloads the section cable at /// the stretch load case until the load of the reloaded catenary matches the /// stretch load that defines it. bool LineCableToCatenaryCableConverter::SolveStateLoadStretch() const { // x = stretch load // y = stretch load difference // i.e.(reloaded stretch load - defined stretch load) // iterative routine to determine solution // solution reached when y = 0 const double target_solution = 0; // initializes the reloader InitializeReloader(); // initializes left point Point2d point_left; point_left.x = 0; point_left.y = LoadStretchDifference(point_left.x); // initializes right point Point2d point_right; point_right.x = catenary_cable_.cable()->strength_rated; point_right.y = LoadStretchDifference(point_right.x); // initializes current point Point2d point_current; // iterates until target solution is reached unsigned int iter = 1; const int iter_max = 100; const double precision = 0.1; double slope_line = -999999; while ((precision < abs(point_current.y - target_solution)) && (iter < iter_max)) { // solves for new stretch value is calculated for current point slope_line = (point_right.y - point_left.y) / (point_right.x - point_left.x); point_current.x = point_left.x + ((target_solution - point_left.y) / slope_line); // solves for new horizontal tension value for current point point_current.y = LoadStretchDifference(point_current.x); // current point is left of left/right points if (point_current.x < point_left.x) { point_right.x = point_left.x; point_right.y = point_left.y; point_left.x = point_current.x; point_left.y = point_current.y; // current point is between left/right points } else if ((point_left.x <= point_current.x) && (point_current.x <= point_right.x)) { if (point_current.y < target_solution) { point_right.x = point_current.x; point_right.y = point_current.y; } else if (target_solution < point_current.y) { point_left.x = point_current.x; point_left.y = point_current.y; } // current point is right of left/right points } else if (point_right.x < point_current.x) { point_left.x = point_right.x; point_left.y = point_right.y; point_right.x = point_current.x; point_right.y = point_current.y; } iter++; } // returns success status and caches result CableState state = *catenary_cable_.state(); if (iter < iter_max) { state.load_stretch = point_current.x; catenary_cable_.set_state(state); return true; } else { state.load_stretch = -999999; catenary_cable_.set_state(state); return false; } } bool LineCableToCatenaryCableConverter::Update() const { // updates catenary cable if (is_updated_catenarycable_ == false) { is_updated_catenarycable_ = UpdateCatenaryCable(); if (is_updated_catenarycable_ == false) { return false; } } // if it reaches this point, update was successful return true; } bool LineCableToCatenaryCableConverter::UpdateCatenaryCable() const { // updates catenary LineCableToCatenaryConverter converter; converter.set_line_cable(line_cable_); Catenary3d catenary; if (converter.Validate() == false) { return false; } else { catenary = converter.Catenary(); } catenary_cable_.set_spacing_endpoints(catenary.spacing_endpoints()); catenary_cable_.set_tension_horizontal(catenary.tension_horizontal()); catenary_cable_.set_weight_unit(catenary.weight_unit()); // updates cable catenary_cable_.set_cable(line_cable_->cable); // updates state CableState state; state.temperature = line_cable_->constraint.case_weather->temperature_cable; state.temperature_stretch = case_stretch_->temperature_cable; catenary_cable_.set_state(state); if (line_cable_->constraint.condition == CableConditionType::kInitial) { state.load_stretch = 0; catenary_cable_.set_state(state); } else { if (SolveStateLoadStretch() == false) { return false; } } return true; } bool LineCableToCatenaryCableConverter::UpdateCatenaryCableState( const double& load_stretch) const { // extracts catenary cable state, modifies, and updates CableState state = *catenary_cable_.state(); state.load_stretch = load_stretch; catenary_cable_.set_state(state); return true; } <commit_msg>Removed file that has been replaced by CatenaryCableSolver.<commit_after><|endoftext|>
<commit_before>#include <config.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/select.h> #include "concurrency/Monitor.h" #include "TSocket.h" #include "TTransportException.h" namespace facebook { namespace thrift { namespace transport { using namespace std; using namespace facebook::thrift::concurrency; // Global var to track total socket sys calls uint32_t g_socket_syscalls = 0; /** * TSocket implementation. * * @author Mark Slee <[email protected]> */ // Mutex to protect syscalls to netdb static Monitor s_netdb_monitor; // TODO(mcslee): Make this an option to the socket class #define MAX_RECV_RETRIES 20 TSocket::TSocket(string host, int port) : host_(host), port_(port), socket_(0), connTimeout_(0), sendTimeout_(0), recvTimeout_(0), lingerOn_(1), lingerVal_(0), noDelay_(1) { recvTimeval_.tv_sec = (int)(recvTimeout_/1000); recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000); } TSocket::TSocket() : host_(""), port_(0), socket_(0), connTimeout_(0), sendTimeout_(0), recvTimeout_(0), lingerOn_(1), lingerVal_(0), noDelay_(1) { recvTimeval_.tv_sec = (int)(recvTimeout_/1000); recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000); } TSocket::TSocket(int socket) : host_(""), port_(0), socket_(socket), connTimeout_(0), sendTimeout_(0), recvTimeout_(0), lingerOn_(1), lingerVal_(0), noDelay_(1) { recvTimeval_.tv_sec = (int)(recvTimeout_/1000); recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000); } TSocket::~TSocket() { close(); } bool TSocket::isOpen() { return (socket_ > 0); } bool TSocket::peek() { if (!isOpen()) { return false; } uint8_t buf; int r = recv(socket_, &buf, 1, MSG_PEEK); if (r == -1) { perror("TSocket::peek()"); close(); throw TTransportException(TTX_UNKNOWN, "recv() ERROR:" + errno); } return (r > 0); } void TSocket::open() { // Create socket socket_ = socket(AF_INET, SOCK_STREAM, 0); if (socket_ == -1) { perror("TSocket::open() socket"); close(); throw TTransportException(TTX_NOT_OPEN, "socket() ERROR:" + errno); } // Send timeout if (sendTimeout_ > 0) { setSendTimeout(sendTimeout_); } // Recv timeout if (recvTimeout_ > 0) { setRecvTimeout(recvTimeout_); } // Linger setLinger(lingerOn_, lingerVal_); // No delay setNoDelay(noDelay_); // Lookup the hostname struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port_); { // Scope lock on host entry lookup Synchronized s(s_netdb_monitor); struct hostent *host_entry = gethostbyname(host_.c_str()); if (host_entry == NULL) { perror("TSocket: dns error: failed call to gethostbyname."); close(); throw TTransportException(TTX_NOT_OPEN, "gethostbyname() failed"); } addr.sin_port = htons(port_); memcpy(&addr.sin_addr.s_addr, host_entry->h_addr_list[0], host_entry->h_length); } // Set the socket to be non blocking for connect if a timeout exists int flags = fcntl(socket_, F_GETFL, 0); if (connTimeout_ > 0) { fcntl(socket_, F_SETFL, flags | O_NONBLOCK); } else { fcntl(socket_, F_SETFL, flags | ~O_NONBLOCK); } // Conn timeout struct timeval c = {(int)(connTimeout_/1000), (int)((connTimeout_%1000)*1000)}; // Connect the socket int ret = connect(socket_, (struct sockaddr *)&addr, sizeof(addr)); if (ret == 0) { goto done; } if (errno != EINPROGRESS) { close(); char buff[1024]; sprintf(buff, "TSocket::open() connect %s %d", host_.c_str(), port_); perror(buff); throw TTransportException(TTX_NOT_OPEN, "open() ERROR: " + errno); } fd_set fds; FD_ZERO(&fds); FD_SET(socket_, &fds); ret = select(socket_+1, NULL, &fds, NULL, &c); if (ret > 0) { // Ensure connected int val; socklen_t lon; lon = sizeof(int); int ret2 = getsockopt(socket_, SOL_SOCKET, SO_ERROR, (void *)&val, &lon); if (ret2 == -1) { close(); perror("TSocket::open() getsockopt SO_ERROR"); throw TTransportException(TTX_NOT_OPEN, "open() ERROR: " + errno); } if (val == 0) { goto done; } close(); perror("TSocket::open() SO_ERROR was set"); throw TTransportException(TTX_NOT_OPEN, "open() ERROR: " + errno); } else if (ret == 0) { close(); perror("TSocket::open() timeed out"); throw TTransportException(TTX_NOT_OPEN, "open() ERROR: " + errno); } else { close(); perror("TSocket::open() select error"); throw TTransportException(TTX_NOT_OPEN, "open() ERROR: " + errno); } done: // Set socket back to normal mode (blocking) fcntl(socket_, F_SETFL, flags); } void TSocket::close() { if (socket_ > 0) { shutdown(socket_, SHUT_RDWR); ::close(socket_); } socket_ = 0; } uint32_t TSocket::read(uint8_t* buf, uint32_t len) { if (socket_ <= 0) { throw TTransportException(TTX_NOT_OPEN, "Called read on non-open socket"); } uint32_t retries = 0; try_again: // Read from the socket int got = recv(socket_, buf, len, 0); ++g_socket_syscalls; // Check for error on read if (got < 0) { perror("TSocket::read()"); // If temporarily out of resources, sleep a bit and try again if (errno == EAGAIN && retries++ < MAX_RECV_RETRIES) { usleep(50); goto try_again; } // If interrupted, try again if (errno == EINTR && retries++ < MAX_RECV_RETRIES) { goto try_again; } // If we disconnect with no linger time if (errno == ECONNRESET) { throw TTransportException(TTX_NOT_OPEN, "ECONNRESET"); } // This ish isn't open if (errno == ENOTCONN) { throw TTransportException(TTX_NOT_OPEN, "ENOTCONN"); } // Timed out! if (errno == ETIMEDOUT) { throw TTransportException(TTX_TIMED_OUT, "ETIMEDOUT"); } // Some other error, whatevz throw TTransportException(TTX_UNKNOWN, "ERROR:" + errno); } // The remote host has closed the socket if (got == 0) { close(); return 0; } // Pack data into string return got; } void TSocket::write(const uint8_t* buf, uint32_t len) { if (socket_ <= 0) { throw TTransportException(TTX_NOT_OPEN, "Called write on non-open socket"); } uint32_t sent = 0; while (sent < len) { int flags = 0; #ifdef MSG_NOSIGNAL // Note the use of MSG_NOSIGNAL to suppress SIGPIPE errors, instead we // check for the EPIPE return condition and close the socket in that case flags |= MSG_NOSIGNAL; #endif // ifdef MSG_NOSIGNAL int b = send(socket_, buf + sent, len - sent, flags); ++g_socket_syscalls; // Fail on a send error if (b < 0) { if (errno == EPIPE) { close(); throw TTransportException(TTX_NOT_OPEN, "EPIPE"); } if (errno == ECONNRESET) { close(); throw TTransportException(TTX_NOT_OPEN, "ECONNRESET"); } if (errno == ENOTCONN) { close(); throw TTransportException(TTX_NOT_OPEN, "ENOTCONN"); } perror("TSocket::write() send < 0"); throw TTransportException(TTX_UNKNOWN, "ERROR:" + errno); } // Fail on blocked send if (b == 0) { throw TTransportException(TTX_NOT_OPEN, "Socket send returned 0."); } sent += b; } } void TSocket::setHost(string host) { host_ = host; } void TSocket::setPort(int port) { port_ = port; } void TSocket::setLinger(bool on, int linger) { lingerOn_ = on; lingerVal_ = linger; if (socket_ <= 0) { return; } struct linger l = {(lingerOn_ ? 1 : 0), lingerVal_}; int ret = setsockopt(socket_, SOL_SOCKET, SO_LINGER, &l, sizeof(l)); if (ret == -1) { perror("TSocket::setLinger()"); } } void TSocket::setNoDelay(bool noDelay) { noDelay_ = noDelay; if (socket_ <= 0) { return; } // Set socket to NODELAY int v = noDelay_ ? 1 : 0; int ret = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v)); if (ret == -1) { perror("TSocket::setNoDelay()"); } } void TSocket::setConnTimeout(int ms) { connTimeout_ = ms; } void TSocket::setRecvTimeout(int ms) { recvTimeout_ = ms; recvTimeval_.tv_sec = (int)(recvTimeout_/1000); recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000); if (socket_ <= 0) { return; } // Copy because select may modify struct timeval r = recvTimeval_; int ret = setsockopt(socket_, SOL_SOCKET, SO_RCVTIMEO, &r, sizeof(r)); if (ret == -1) { perror("TSocket::setRecvTimeout()"); } } void TSocket::setSendTimeout(int ms) { sendTimeout_ = ms; if (socket_ <= 0) { return; } struct timeval s = {(int)(sendTimeout_/1000), (int)((sendTimeout_%1000)*1000)}; int ret = setsockopt(socket_, SOL_SOCKET, SO_SNDTIMEO, &s, sizeof(s)); if (ret == -1) { perror("TSocket::setSendTimeout()"); } } }}} // facebook::thrift::transport <commit_msg>Thrift socket should not perror in the TRYAGAIN state<commit_after>#include <config.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/select.h> #include "concurrency/Monitor.h" #include "TSocket.h" #include "TTransportException.h" namespace facebook { namespace thrift { namespace transport { using namespace std; using namespace facebook::thrift::concurrency; // Global var to track total socket sys calls uint32_t g_socket_syscalls = 0; /** * TSocket implementation. * * @author Mark Slee <[email protected]> */ // Mutex to protect syscalls to netdb static Monitor s_netdb_monitor; // TODO(mcslee): Make this an option to the socket class #define MAX_RECV_RETRIES 20 TSocket::TSocket(string host, int port) : host_(host), port_(port), socket_(0), connTimeout_(0), sendTimeout_(0), recvTimeout_(0), lingerOn_(1), lingerVal_(0), noDelay_(1) { recvTimeval_.tv_sec = (int)(recvTimeout_/1000); recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000); } TSocket::TSocket() : host_(""), port_(0), socket_(0), connTimeout_(0), sendTimeout_(0), recvTimeout_(0), lingerOn_(1), lingerVal_(0), noDelay_(1) { recvTimeval_.tv_sec = (int)(recvTimeout_/1000); recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000); } TSocket::TSocket(int socket) : host_(""), port_(0), socket_(socket), connTimeout_(0), sendTimeout_(0), recvTimeout_(0), lingerOn_(1), lingerVal_(0), noDelay_(1) { recvTimeval_.tv_sec = (int)(recvTimeout_/1000); recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000); } TSocket::~TSocket() { close(); } bool TSocket::isOpen() { return (socket_ > 0); } bool TSocket::peek() { if (!isOpen()) { return false; } uint8_t buf; int r = recv(socket_, &buf, 1, MSG_PEEK); if (r == -1) { perror("TSocket::peek()"); close(); throw TTransportException(TTX_UNKNOWN, "recv() ERROR:" + errno); } return (r > 0); } void TSocket::open() { // Create socket socket_ = socket(AF_INET, SOCK_STREAM, 0); if (socket_ == -1) { perror("TSocket::open() socket"); close(); throw TTransportException(TTX_NOT_OPEN, "socket() ERROR:" + errno); } // Send timeout if (sendTimeout_ > 0) { setSendTimeout(sendTimeout_); } // Recv timeout if (recvTimeout_ > 0) { setRecvTimeout(recvTimeout_); } // Linger setLinger(lingerOn_, lingerVal_); // No delay setNoDelay(noDelay_); // Lookup the hostname struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port_); { // Scope lock on host entry lookup Synchronized s(s_netdb_monitor); struct hostent *host_entry = gethostbyname(host_.c_str()); if (host_entry == NULL) { perror("TSocket: dns error: failed call to gethostbyname."); close(); throw TTransportException(TTX_NOT_OPEN, "gethostbyname() failed"); } addr.sin_port = htons(port_); memcpy(&addr.sin_addr.s_addr, host_entry->h_addr_list[0], host_entry->h_length); } // Set the socket to be non blocking for connect if a timeout exists int flags = fcntl(socket_, F_GETFL, 0); if (connTimeout_ > 0) { fcntl(socket_, F_SETFL, flags | O_NONBLOCK); } else { fcntl(socket_, F_SETFL, flags | ~O_NONBLOCK); } // Conn timeout struct timeval c = {(int)(connTimeout_/1000), (int)((connTimeout_%1000)*1000)}; // Connect the socket int ret = connect(socket_, (struct sockaddr *)&addr, sizeof(addr)); if (ret == 0) { goto done; } if (errno != EINPROGRESS) { close(); char buff[1024]; sprintf(buff, "TSocket::open() connect %s %d", host_.c_str(), port_); perror(buff); throw TTransportException(TTX_NOT_OPEN, "open() ERROR: " + errno); } fd_set fds; FD_ZERO(&fds); FD_SET(socket_, &fds); ret = select(socket_+1, NULL, &fds, NULL, &c); if (ret > 0) { // Ensure connected int val; socklen_t lon; lon = sizeof(int); int ret2 = getsockopt(socket_, SOL_SOCKET, SO_ERROR, (void *)&val, &lon); if (ret2 == -1) { close(); perror("TSocket::open() getsockopt SO_ERROR"); throw TTransportException(TTX_NOT_OPEN, "open() ERROR: " + errno); } if (val == 0) { goto done; } close(); perror("TSocket::open() SO_ERROR was set"); throw TTransportException(TTX_NOT_OPEN, "open() ERROR: " + errno); } else if (ret == 0) { close(); perror("TSocket::open() timeed out"); throw TTransportException(TTX_NOT_OPEN, "open() ERROR: " + errno); } else { close(); perror("TSocket::open() select error"); throw TTransportException(TTX_NOT_OPEN, "open() ERROR: " + errno); } done: // Set socket back to normal mode (blocking) fcntl(socket_, F_SETFL, flags); } void TSocket::close() { if (socket_ > 0) { shutdown(socket_, SHUT_RDWR); ::close(socket_); } socket_ = 0; } uint32_t TSocket::read(uint8_t* buf, uint32_t len) { if (socket_ <= 0) { throw TTransportException(TTX_NOT_OPEN, "Called read on non-open socket"); } uint32_t retries = 0; try_again: // Read from the socket int got = recv(socket_, buf, len, 0); ++g_socket_syscalls; // Check for error on read if (got < 0) { // If temporarily out of resources, sleep a bit and try again if (errno == EAGAIN && retries++ < MAX_RECV_RETRIES) { usleep(50); goto try_again; } // If interrupted, try again if (errno == EINTR && retries++ < MAX_RECV_RETRIES) { goto try_again; } // Now it's not a try again case, but a real probblez perror("TSocket::read()"); // If we disconnect with no linger time if (errno == ECONNRESET) { throw TTransportException(TTX_NOT_OPEN, "ECONNRESET"); } // This ish isn't open if (errno == ENOTCONN) { throw TTransportException(TTX_NOT_OPEN, "ENOTCONN"); } // Timed out! if (errno == ETIMEDOUT) { throw TTransportException(TTX_TIMED_OUT, "ETIMEDOUT"); } // Some other error, whatevz throw TTransportException(TTX_UNKNOWN, "ERROR:" + errno); } // The remote host has closed the socket if (got == 0) { close(); return 0; } // Pack data into string return got; } void TSocket::write(const uint8_t* buf, uint32_t len) { if (socket_ <= 0) { throw TTransportException(TTX_NOT_OPEN, "Called write on non-open socket"); } uint32_t sent = 0; while (sent < len) { int flags = 0; #ifdef MSG_NOSIGNAL // Note the use of MSG_NOSIGNAL to suppress SIGPIPE errors, instead we // check for the EPIPE return condition and close the socket in that case flags |= MSG_NOSIGNAL; #endif // ifdef MSG_NOSIGNAL int b = send(socket_, buf + sent, len - sent, flags); ++g_socket_syscalls; // Fail on a send error if (b < 0) { if (errno == EPIPE) { close(); throw TTransportException(TTX_NOT_OPEN, "EPIPE"); } if (errno == ECONNRESET) { close(); throw TTransportException(TTX_NOT_OPEN, "ECONNRESET"); } if (errno == ENOTCONN) { close(); throw TTransportException(TTX_NOT_OPEN, "ENOTCONN"); } perror("TSocket::write() send < 0"); throw TTransportException(TTX_UNKNOWN, "ERROR:" + errno); } // Fail on blocked send if (b == 0) { throw TTransportException(TTX_NOT_OPEN, "Socket send returned 0."); } sent += b; } } void TSocket::setHost(string host) { host_ = host; } void TSocket::setPort(int port) { port_ = port; } void TSocket::setLinger(bool on, int linger) { lingerOn_ = on; lingerVal_ = linger; if (socket_ <= 0) { return; } struct linger l = {(lingerOn_ ? 1 : 0), lingerVal_}; int ret = setsockopt(socket_, SOL_SOCKET, SO_LINGER, &l, sizeof(l)); if (ret == -1) { perror("TSocket::setLinger()"); } } void TSocket::setNoDelay(bool noDelay) { noDelay_ = noDelay; if (socket_ <= 0) { return; } // Set socket to NODELAY int v = noDelay_ ? 1 : 0; int ret = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v)); if (ret == -1) { perror("TSocket::setNoDelay()"); } } void TSocket::setConnTimeout(int ms) { connTimeout_ = ms; } void TSocket::setRecvTimeout(int ms) { recvTimeout_ = ms; recvTimeval_.tv_sec = (int)(recvTimeout_/1000); recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000); if (socket_ <= 0) { return; } // Copy because select may modify struct timeval r = recvTimeval_; int ret = setsockopt(socket_, SOL_SOCKET, SO_RCVTIMEO, &r, sizeof(r)); if (ret == -1) { perror("TSocket::setRecvTimeout()"); } } void TSocket::setSendTimeout(int ms) { sendTimeout_ = ms; if (socket_ <= 0) { return; } struct timeval s = {(int)(sendTimeout_/1000), (int)((sendTimeout_%1000)*1000)}; int ret = setsockopt(socket_, SOL_SOCKET, SO_SNDTIMEO, &s, sizeof(s)); if (ret == -1) { perror("TSocket::setSendTimeout()"); } } }}} // facebook::thrift::transport <|endoftext|>
<commit_before>#include <gtest/gtest.h> #ifdef __APPLE__ # include <libkern/OSByteOrder.h> # define htobe32(x) OSSwapHostToBigInt32(x) # define htobe64(x) OSSwapHostToBigInt64(x) #else # include <endian.h> #endif #include "receiver.h" #include "stream.h" #include "buffer.h" #include <cstdio> #include <inttypes.h> ////////////////////////////////////////////////////////////////////// // Test utility functions. ////////////////////////////////////////////////////////////////////// static struct Receiver* create_test_receiver() { const int num_buffers_max = 1; const int num_times_in_buffer = 4; const int num_threads_recv = 1; const int num_threads_write = 1; const int num_streams = 1; const unsigned short int port_start = 41000; const int num_channels_per_file = 1; const char* output_root = ""; struct Receiver* receiver = receiver_create(num_buffers_max, num_times_in_buffer, num_threads_recv, num_threads_write, num_streams, port_start, num_channels_per_file, output_root); return receiver; } ////////////////////////////////////////////////////////////////////// // Tests. ////////////////////////////////////////////////////////////////////// TEST(Receiver, test_create) { struct Receiver* receiver = create_test_receiver(); ASSERT_TRUE(receiver != NULL); receiver_free(receiver); } TEST(Stream, test_stream_decode) { // Verify stream_decode() function can handle a simple SPEAD packet. // SPEAD packet item IDs. const unsigned int item_ids[] = { 0x1, // Heap counter. 0x2, // Heap size. 0x3 // Heap offset. }; // Dummy values for items. const int item_val[] = { 4, 10, 55 }; const unsigned int num_items = sizeof(item_ids) / sizeof(unsigned int); // Allocate memory for a SPEAD packet. unsigned char* buf = (unsigned char*) malloc(8 + num_items * 8); ASSERT_TRUE(buf != NULL); // Define SPEAD flavour. const unsigned char heap_address_bits = 48; const unsigned char item_id_bits = 64 - heap_address_bits - 1; // Construct SPEAD packet header. buf[0] = 'S'; buf[1] = 4; buf[2] = (item_id_bits + 1) / 8; buf[3] = heap_address_bits / 8; buf[4] = 0; buf[5] = 0; buf[6] = 0; buf[7] = (unsigned char) num_items; // Construct SPEAD packet payload containing items in // "immediate addressing mode". uint64_t* items = (uint64_t*) &buf[8]; for (unsigned int i = 0; i < num_items; i++) { const uint64_t item_id = (uint64_t) item_ids[i]; const uint64_t item_addr_or_val = (uint64_t) item_val[i]; const uint64_t item = (1ull << 63) | (item_id << heap_address_bits) | item_addr_or_val; items[i] = htobe64(item); } // Create a test receiver. struct Receiver* receiver = create_test_receiver(); ASSERT_TRUE(receiver != NULL); // Call stream_decode(). stream_decode(receiver->streams[0], buf, 0); // Clean up. receiver_free(receiver); free(buf); } TEST(Stream, test_stream_receive) { /* Verify stream_decode() function and verify if correct data is received */ typedef enum _item_ids { heap_counter=0x01, heap_size, heap_offset, packet_payload_length, visibility_baseline_count=0x6005, scan_ID=0x6008, visibility_data=0x600A } item_id; typedef struct _item_block { item_id id; uint64_t val; uint64_t imm; } item_block; int num_baselines = 512 *513 / 2; struct DataType vis_data = {0,0,{{1.5,2.5},{3.5,4.5},{5.5,6.5},{7.5,8.5}}}; // float vis_data[2]; // vis_data[0] = (float)rand()/(float)(RAND_MAX/10.); // vis_data[1] = (float)rand()/(float)(RAND_MAX/10.); uint64_t scan_id=0, *scan_ptr=NULL; void *heap_start; struct DataType * vis_ptr; const item_block p_items[] = { {heap_counter, 2, 1}, {heap_size, 16, 1}, {heap_offset, 0, 1}, {packet_payload_length, 16, 1}, {visibility_baseline_count, (uint64_t) num_baselines, 1}, {scan_ID, 0, 0}, {visibility_data, 8, 0} }; const unsigned int num_items = sizeof(p_items) / sizeof(item_block); // Allocate memory for a SPEAD packet. unsigned char* buf = (unsigned char*) malloc(8 + num_items * 8 + 8 + sizeof(vis_data)); ASSERT_TRUE(buf != NULL); // Define SPEAD flavour. const unsigned char heap_address_bits = 48; const unsigned char item_id_bits = 64 - heap_address_bits - 1; // Construct SPEAD packet header. buf[0] = 'S'; buf[1] = 4; buf[2] = (item_id_bits + 1) / 8; buf[3] = heap_address_bits / 8; buf[4] = 0; buf[5] = 0; buf[6] = 0; buf[7] = (unsigned char) num_items; // Construct SPEAD packet payload containing items in // "immediate addressing mode". uint64_t* items = (uint64_t*) &buf[8]; uint64_t heap_count; for (unsigned int i = 0; i < num_items; i++) { const uint64_t item_id = (uint64_t) p_items[i].id; const uint64_t item_addr_or_val = (uint64_t) p_items[i].val; const uint64_t imm_or_abs = p_items[i].imm << 63; //printf("Item Value: %i\n", item_val[i]); const uint64_t item = imm_or_abs | (item_id << heap_address_bits) | item_addr_or_val; items[i] = htobe64(item); switch (p_items[i].id) { case heap_counter : heap_count = p_items[i].val; break; } } // get start of heap heap_start = buf + 8 + num_items * sizeof(uint64_t); // insert scan_id at heap_start, 8 bytes scan_ptr = (uint64_t *) heap_start; *scan_ptr = scan_id; *scan_ptr = htobe64(scan_id); ++scan_ptr; vis_ptr = (struct DataType *) scan_ptr; memcpy((void *)vis_ptr, (void *) &vis_data, sizeof(vis_data)); // Create a test receiver. struct Receiver* receiver = create_test_receiver(); ASSERT_TRUE(receiver != NULL); // Passing the buffer and stream to stream decode stream_decode(receiver->streams[0], buf, 0); // Testing ASSERT_TRUE(receiver->streams[0] != NULL); ASSERT_TRUE(receiver->buffers[0] != NULL); ASSERT_TRUE(receiver->num_buffers != 0); ASSERT_TRUE(num_baselines == receiver->buffers[0]->num_baselines); ASSERT_TRUE(vis_ptr->fd == receiver->buffers[0]->vis_data->fd); ASSERT_TRUE(vis_ptr->tci == receiver->buffers[0]->vis_data->tci); // Clean up. receiver_free(receiver); free(buf); } <commit_msg>Reverted Tests.cpp to master version<commit_after>#include <gtest/gtest.h> #ifdef __APPLE__ # include <libkern/OSByteOrder.h> # define htobe32(x) OSSwapHostToBigInt32(x) # define htobe64(x) OSSwapHostToBigInt64(x) #else # include <endian.h> #endif #include "receiver.h" #include "stream.h" #include <cstdio> #include <inttypes.h> ////////////////////////////////////////////////////////////////////// // Test utility functions. ////////////////////////////////////////////////////////////////////// static struct Receiver* create_test_receiver() { const int num_buffers_max = 1; const int num_times_in_buffer = 4; const int num_threads_recv = 1; const int num_threads_write = 1; const int num_streams = 1; const unsigned short int port_start = 41000; const int num_channels_per_file = 1; const char* output_root = ""; struct Receiver* receiver = receiver_create(num_buffers_max, num_times_in_buffer, num_threads_recv, num_threads_write, num_streams, port_start, num_channels_per_file, output_root); return receiver; } ////////////////////////////////////////////////////////////////////// // Tests. ////////////////////////////////////////////////////////////////////// TEST(Receiver, test_create) { struct Receiver* receiver = create_test_receiver(); ASSERT_TRUE(receiver != NULL); receiver_free(receiver); } TEST(Stream, test_stream_decode) { // Verify stream_decode() function can handle a simple SPEAD packet. // SPEAD packet item IDs. const unsigned int item_ids[] = { 0x1, // Heap counter. 0x2, // Heap size. 0x3 // Heap offset. }; // Dummy values for items. const int item_val[] = { 4, 10, 55 }; const unsigned int num_items = sizeof(item_ids) / sizeof(unsigned int); // Allocate memory for a SPEAD packet. unsigned char* buf = (unsigned char*) malloc(8 + num_items * 8); ASSERT_TRUE(buf != NULL); // Define SPEAD flavour. const unsigned char heap_address_bits = 48; const unsigned char item_id_bits = 64 - heap_address_bits - 1; // Construct SPEAD packet header. buf[0] = 'S'; buf[1] = 4; buf[2] = (item_id_bits + 1) / 8; buf[3] = heap_address_bits / 8; buf[4] = 0; buf[5] = 0; buf[6] = 0; buf[7] = (unsigned char) num_items; // Construct SPEAD packet payload containing items in // "immediate addressing mode". uint64_t* items = (uint64_t*) &buf[8]; for (unsigned int i = 0; i < num_items; i++) { const uint64_t item_id = (uint64_t) item_ids[i]; const uint64_t item_addr_or_val = (uint64_t) item_val[i]; const uint64_t item = (1ull << 63) | (item_id << heap_address_bits) | item_addr_or_val; items[i] = htobe64(item); } // Create a test receiver. struct Receiver* receiver = create_test_receiver(); ASSERT_TRUE(receiver != NULL); // Call stream_decode(). stream_decode(receiver->streams[0], buf, 0); // Clean up. receiver_free(receiver); free(buf); }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: about.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:52:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ABOUT_HXX #define _ABOUT_HXX // include --------------------------------------------------------------- #ifndef _RESARY_HXX //autogen #include <vcl/resary.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _ACCEL_HXX //autogen #include <vcl/accel.hxx> #endif #ifndef _LIST_HXX //autogen #include <tools/list.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #include "basedlgs.hxx" // SfxModalDialog DECLARE_LIST( AccelList, Accelerator* ) // class AboutDialog ----------------------------------------------------- class AboutDialog : public SfxModalDialog { private: OKButton aOKButton; Image aAppLogo; FixedInfo aVersionText; FixedInfo aCopyrightText; ResStringArray aDeveloperAry; String aDevVersionStr; String aAccelStr; AccelList aAccelList; AutoTimer aTimer; long nOff; long nEnd; BOOL bNormal; protected: virtual BOOL Close(); virtual void Paint( const Rectangle& ); public: AboutDialog( Window* pParent, const ResId& rId, const String& rVerStr ); ~AboutDialog(); DECL_LINK( TimerHdl, Timer * ); DECL_LINK( AccelSelectHdl, Accelerator * ); }; #endif // #ifndef _ABOUT_HXX <commit_msg>INTEGRATION: CWS vclcleanup02 (1.1.1.1.378); FILE MERGED 2003/12/11 09:08:15 mt 1.1.1.1.378.1: #i23061# VCL cleanup, removed headers, methods and types...<commit_after>/************************************************************************* * * $RCSfile: about.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2004-01-06 16:16:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ABOUT_HXX #define _ABOUT_HXX // include --------------------------------------------------------------- #ifndef _RESARY_HXX //autogen #include <tools/resary.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _ACCEL_HXX //autogen #include <vcl/accel.hxx> #endif #ifndef _LIST_HXX //autogen #include <tools/list.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #include "basedlgs.hxx" // SfxModalDialog DECLARE_LIST( AccelList, Accelerator* ) // class AboutDialog ----------------------------------------------------- class AboutDialog : public SfxModalDialog { private: OKButton aOKButton; Image aAppLogo; FixedInfo aVersionText; FixedInfo aCopyrightText; ResStringArray aDeveloperAry; String aDevVersionStr; String aAccelStr; AccelList aAccelList; AutoTimer aTimer; long nOff; long nEnd; BOOL bNormal; protected: virtual BOOL Close(); virtual void Paint( const Rectangle& ); public: AboutDialog( Window* pParent, const ResId& rId, const String& rVerStr ); ~AboutDialog(); DECL_LINK( TimerHdl, Timer * ); DECL_LINK( AccelSelectHdl, Accelerator * ); }; #endif // #ifndef _ABOUT_HXX <|endoftext|>
<commit_before>#include "demoloop.h" #include <SDL_ttf.h> #include <GL/glew.h> #include <SDL_opengl.h> #include "cleanup.h" #include <glm/gtc/matrix_transform.hpp> #ifdef EMSCRIPTEN #include <AL/al.h> #include <AL/alc.h> #else #include <al.h> #include <alc.h> #endif #ifdef EMSCRIPTEN #include <emscripten.h> #endif namespace demoloop { const int SCREEN_WIDTH = 640, SCREEN_HEIGHT = 480; Demoloop::Demoloop() : Demoloop(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0) {} Demoloop::Demoloop(int r, int g, int b) : Demoloop(SCREEN_WIDTH, SCREEN_HEIGHT, r, g, b) {} // implementation of constructor Demoloop::Demoloop(int width, int height, int r, int g, int b) :width(width), height(height), quit(false), bg_r(r), bg_g(g), bg_b(b) { if (SDL_Init(SDL_INIT_VIDEO) != 0){ logSDLError("SDL_Init"); // return 1; } // SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16); const auto WINDOW_FLAGS = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL; window = SDL_CreateWindow("Demoloop", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, WINDOW_FLAGS); if (window == nullptr){ logSDLError("CreateWindow"); SDL_Quit(); // return 1; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == nullptr){ logSDLError("CreateRenderer"); cleanup(window); SDL_Quit(); // return 1; } states.reserve(10); states.push_back(DisplayState()); auto contextGL = SDL_GL_CreateContext(window); if (contextGL == NULL) { logSDLError("SDL_GL_CreateContext"); } else { //Initialize GLEW glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK) { printf("Error initializing GLEW! %s\n", glewGetErrorString(glewError)); } gl.initContext(); setBlendMode(BLEND_ALPHA, BLENDALPHA_MULTIPLY); setViewportSize(width, height); //Use Vsync if (SDL_GL_SetSwapInterval(1) < 0) { logSDLError("SDL_GL_SetSwapInterval"); } } if (TTF_Init() != 0){ logSDLError("TTF_Init"); SDL_Quit(); // return 1; } ALCdevice* deviceAL = alcOpenDevice(NULL); ALCcontext* contextAL = alcCreateContext(deviceAL, NULL); alcMakeContextCurrent(contextAL); ALfloat listenerPos[] = {0.0, 0.0, 0.0}; ALfloat listenerVel[] = {0.0, 0.0, 0.0}; ALfloat listenerOri[] = {0.0, 0.0, -1.0, 0.0, 1.0, 0.0}; alListenerfv(AL_POSITION, listenerPos); alListenerfv(AL_VELOCITY, listenerVel); alListenerfv(AL_ORIENTATION, listenerOri); } Demoloop::~Demoloop() { cleanup(renderer, window); TTF_Quit(); SDL_Quit(); } void Demoloop::setColor(const RGB& rgb, uint8_t a) { setColor(rgb.r, rgb.g, rgb.b, a); } void Demoloop::setColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { glVertexAttrib4f(ATTRIB_CONSTANTCOLOR, r / 255.0, g / 255.0, b / 255.0, a / 255.0); } void Demoloop::setCanvas(Canvas *canvas) { if (canvas == nullptr) return setCanvas(); DisplayState &state = states.back(); canvas->startGrab(); std::vector<StrongRef<Canvas>> canvasref; canvasref.push_back(canvas); std::swap(state.canvases, canvasref); } // void Demoloop::setCanvas(const std::vector<Canvas *> &canvases) // { // if (canvases.size() == 0) // return setCanvas(); // else if (canvases.size() == 1) // return setCanvas(canvases[0]); // DisplayState &state = states.back(); // auto attachments = std::vector<Canvas *>(canvases.begin() + 1, canvases.end()); // canvases[0]->startGrab(attachments); // std::vector<Canvas> canvasrefs; // canvasrefs.reserve(canvases.size()); // for (Canvas *c : canvases) // canvasrefs.push_back(c); // std::swap(state.canvases, canvasrefs); // } void Demoloop::setCanvas() { DisplayState &state = states.back(); if (Canvas::current != nullptr) Canvas::current->stopGrab(); state.canvases.clear(); } std::vector<Canvas *> Demoloop::getCanvas() const { std::vector<Canvas *> canvases; canvases.reserve(states.back().canvases.size()); for (const StrongRef<Canvas> &c : states.back().canvases) canvases.push_back(c.get()); return canvases; } void Demoloop::setViewportSize(int width, int height) { this->width = width; this->height = height; // We want to affect the main screen, not any Canvas that's currently active // (not that any *should* be active when this is called.) // std::vector<StrongRef<Canvas>> canvases = states.back().canvases; // setCanvas(); // Set the viewport to top-left corner. gl.setViewport({0, 0, width, height}); // If a canvas was bound before this function was called, it needs to be // made aware of the new system viewport size. Canvas::systemViewport = gl.getViewport(); // Set up the projection matrix gl.matrices.projection.back() = glm::ortho(0.0f, (float) width, (float) height, 0.0f, 0.1f, 100.0f); const glm::vec3 eye = {0, 0, 100}; const glm::vec3 center = {0, 0, 0}; const glm::vec3 up = {0, 1, 0}; gl.matrices.transform.back() = glm::lookAt(eye, center, up); // Restore the previously active Canvas. // setCanvas(canvases); } void Demoloop::setBlendMode(BlendMode mode, BlendAlpha alphamode) { GLenum func = GL_FUNC_ADD; GLenum srcRGB = GL_ONE; GLenum srcA = GL_ONE; GLenum dstRGB = GL_ZERO; GLenum dstA = GL_ZERO; // if (mode == BLEND_LIGHTEN || mode == BLEND_DARKEN) // { // if (!isSupported(SUPPORT_LIGHTEN)) // throw love::Exception("The 'lighten' and 'darken' blend modes are not supported on this system."); // } // if (alphamode != BLENDALPHA_PREMULTIPLIED) // { // const char *modestr = "unknown"; // switch (mode) // { // case BLEND_LIGHTEN: // case BLEND_DARKEN: // /*case BLEND_MULTIPLY:*/ // FIXME: Uncomment for 0.11.0 // getConstant(mode, modestr); // throw love::Exception("The '%s' blend mode must be used with premultiplied alpha.", modestr); // break; // default: // break; // } // } switch (mode) { case BLEND_ALPHA: srcRGB = srcA = GL_ONE; dstRGB = dstA = GL_ONE_MINUS_SRC_ALPHA; break; case BLEND_MULTIPLY: srcRGB = srcA = GL_DST_COLOR; dstRGB = dstA = GL_ZERO; break; case BLEND_SUBTRACT: func = GL_FUNC_REVERSE_SUBTRACT; case BLEND_ADD: srcRGB = GL_ONE; srcA = GL_ZERO; dstRGB = dstA = GL_ONE; break; case BLEND_LIGHTEN: func = GL_MAX; break; case BLEND_DARKEN: func = GL_MIN; break; case BLEND_SCREEN: srcRGB = srcA = GL_ONE; dstRGB = dstA = GL_ONE_MINUS_SRC_COLOR; break; case BLEND_REPLACE: default: srcRGB = srcA = GL_ONE; dstRGB = dstA = GL_ZERO; break; } // We can only do alpha-multiplication when srcRGB would have been unmodified. if (srcRGB == GL_ONE && alphamode == BLENDALPHA_MULTIPLY) srcRGB = GL_SRC_ALPHA; glBlendEquation(func); glBlendFuncSeparate(srcRGB, dstRGB, srcA, dstA); states.back().blendMode = mode; states.back().blendAlphaMode = alphamode; } Demoloop::BlendMode Demoloop::getBlendMode(BlendAlpha &alphamode) const { alphamode = states.back().blendAlphaMode; return states.back().blendMode; } int Demoloop::getMouseX() const { return mouse_x; } int Demoloop::getMouseY() const { return mouse_y; } int Demoloop::getMouseDeltaX() const { return mouse_x - prev_mouse_x; } int Demoloop::getMouseDeltaY() const { return mouse_y - prev_mouse_y; } bool Demoloop::isMouseDown(uint8_t button) const { return SDL_BUTTON(button) & mouse_state; } void Demoloop::InternalUpdate() { while (SDL_PollEvent(&e)){ //If user closes the window if (e.type == SDL_QUIT){ quit = true; } //If user presses any key if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE){ quit = true; } } prev_mouse_x = mouse_x, prev_mouse_y = mouse_y; mouse_state = SDL_GetMouseState(&mouse_x, &mouse_y); glClearColor( bg_r / 255.0, bg_g / 255.0, bg_b / 255.0, 1.f ); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); auto now = std::chrono::high_resolution_clock::now(); auto delta = std::chrono::duration_cast<std::chrono::duration<float>>(now - previous_frame); previous_frame = now; Update(delta.count()); SDL_GL_SwapWindow(window); } void Demoloop::Run() { previous_frame = std::chrono::high_resolution_clock::now(); #ifdef __EMSCRIPTEN__ emscripten_set_main_loop_arg([](void *arg) { Demoloop *self = static_cast<Demoloop*>(arg); self->InternalUpdate(); }, (void *)this, 0, 1); #else const std::chrono::duration<float> interval(1.0f / 60.0f); while (!quit) { auto start = std::chrono::high_resolution_clock::now(); InternalUpdate(); while((std::chrono::high_resolution_clock::now() - start) < interval){} } // const std::chrono::seconds CYCLE_LENGTH(10); // const std::chrono::duration<float> interval(1.0f / 50.0f); // char* pixels = new char [3 * width * height]; // SDL_Surface* temp = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0); // uint32_t index = 0; // for (std::chrono::duration<float> elapsed(0); elapsed <= CYCLE_LENGTH; elapsed += interval) { // glClearColor( bg_r / 255.0, bg_g / 255.0, bg_b / 255.0, 1.f ); // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Update(interval.count()); // SDL_GL_SwapWindow(window); // glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); // for (int i = 0 ; i < height ; i++) // std::memcpy( ((char *) temp->pixels) + temp->pitch * i, pixels + 3 * width * (height-i - 1), width*3 ); // auto numString = std::to_string(index++); // numString = std::string(4 - numString.length(), '0') + numString; // SDL_SaveBMP(temp, ("frames/frame" + numString + ".bmp").c_str()); // } // cleanup(temp); // delete [] pixels; #endif } } <commit_msg>protect against a lack of audio features<commit_after>#include "demoloop.h" #include <SDL_ttf.h> #include <GL/glew.h> #include <SDL_opengl.h> #include "cleanup.h" #include <glm/gtc/matrix_transform.hpp> #ifdef EMSCRIPTEN #include <AL/al.h> #include <AL/alc.h> #else #include <al.h> #include <alc.h> #endif #ifdef EMSCRIPTEN #include <emscripten.h> #endif namespace demoloop { const int SCREEN_WIDTH = 640, SCREEN_HEIGHT = 480; Demoloop::Demoloop() : Demoloop(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0) {} Demoloop::Demoloop(int r, int g, int b) : Demoloop(SCREEN_WIDTH, SCREEN_HEIGHT, r, g, b) {} // implementation of constructor Demoloop::Demoloop(int width, int height, int r, int g, int b) :width(width), height(height), quit(false), bg_r(r), bg_g(g), bg_b(b) { if (SDL_Init(SDL_INIT_VIDEO) != 0){ logSDLError("SDL_Init"); // return 1; } // SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16); const auto WINDOW_FLAGS = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL; window = SDL_CreateWindow("Demoloop", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, WINDOW_FLAGS); if (window == nullptr){ logSDLError("CreateWindow"); SDL_Quit(); // return 1; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == nullptr){ logSDLError("CreateRenderer"); cleanup(window); SDL_Quit(); // return 1; } states.reserve(10); states.push_back(DisplayState()); auto contextGL = SDL_GL_CreateContext(window); if (contextGL == NULL) { logSDLError("SDL_GL_CreateContext"); } else { //Initialize GLEW glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK) { printf("Error initializing GLEW! %s\n", glewGetErrorString(glewError)); } gl.initContext(); setBlendMode(BLEND_ALPHA, BLENDALPHA_MULTIPLY); setViewportSize(width, height); //Use Vsync if (SDL_GL_SetSwapInterval(1) < 0) { logSDLError("SDL_GL_SetSwapInterval"); } } if (TTF_Init() != 0){ logSDLError("TTF_Init"); SDL_Quit(); // return 1; } ALCdevice* deviceAL = alcOpenDevice(NULL); if (deviceAL == nullptr) { printf("Could not open audio device\n"); } else { ALCcontext* contextAL = alcCreateContext(deviceAL, NULL); if (contextAL == nullptr) { printf("Could not create audio context.\n"); } else { if (!alcMakeContextCurrent(contextAL) || alcGetError(deviceAL) != ALC_NO_ERROR) { printf("Could not make audio context current."); } else { ALfloat listenerPos[] = {0.0, 0.0, 0.0}; ALfloat listenerVel[] = {0.0, 0.0, 0.0}; ALfloat listenerOri[] = {0.0, 0.0, -1.0, 0.0, 1.0, 0.0}; alListenerfv(AL_POSITION, listenerPos); alListenerfv(AL_VELOCITY, listenerVel); alListenerfv(AL_ORIENTATION, listenerOri); } } } } Demoloop::~Demoloop() { cleanup(renderer, window); TTF_Quit(); SDL_Quit(); // alcMakeContextCurrent(nullptr); // alcDestroyContext(context); // //if (capture) alcCaptureCloseDevice(capture); // alcCloseDevice(device); } void Demoloop::setColor(const RGB& rgb, uint8_t a) { setColor(rgb.r, rgb.g, rgb.b, a); } void Demoloop::setColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { glVertexAttrib4f(ATTRIB_CONSTANTCOLOR, r / 255.0, g / 255.0, b / 255.0, a / 255.0); } void Demoloop::setCanvas(Canvas *canvas) { if (canvas == nullptr) return setCanvas(); DisplayState &state = states.back(); canvas->startGrab(); std::vector<StrongRef<Canvas>> canvasref; canvasref.push_back(canvas); std::swap(state.canvases, canvasref); } // void Demoloop::setCanvas(const std::vector<Canvas *> &canvases) // { // if (canvases.size() == 0) // return setCanvas(); // else if (canvases.size() == 1) // return setCanvas(canvases[0]); // DisplayState &state = states.back(); // auto attachments = std::vector<Canvas *>(canvases.begin() + 1, canvases.end()); // canvases[0]->startGrab(attachments); // std::vector<Canvas> canvasrefs; // canvasrefs.reserve(canvases.size()); // for (Canvas *c : canvases) // canvasrefs.push_back(c); // std::swap(state.canvases, canvasrefs); // } void Demoloop::setCanvas() { DisplayState &state = states.back(); if (Canvas::current != nullptr) Canvas::current->stopGrab(); state.canvases.clear(); } std::vector<Canvas *> Demoloop::getCanvas() const { std::vector<Canvas *> canvases; canvases.reserve(states.back().canvases.size()); for (const StrongRef<Canvas> &c : states.back().canvases) canvases.push_back(c.get()); return canvases; } void Demoloop::setViewportSize(int width, int height) { this->width = width; this->height = height; // We want to affect the main screen, not any Canvas that's currently active // (not that any *should* be active when this is called.) // std::vector<StrongRef<Canvas>> canvases = states.back().canvases; // setCanvas(); // Set the viewport to top-left corner. gl.setViewport({0, 0, width, height}); // If a canvas was bound before this function was called, it needs to be // made aware of the new system viewport size. Canvas::systemViewport = gl.getViewport(); // Set up the projection matrix gl.matrices.projection.back() = glm::ortho(0.0f, (float) width, (float) height, 0.0f, 0.1f, 100.0f); const glm::vec3 eye = {0, 0, 100}; const glm::vec3 center = {0, 0, 0}; const glm::vec3 up = {0, 1, 0}; gl.matrices.transform.back() = glm::lookAt(eye, center, up); // Restore the previously active Canvas. // setCanvas(canvases); } void Demoloop::setBlendMode(BlendMode mode, BlendAlpha alphamode) { GLenum func = GL_FUNC_ADD; GLenum srcRGB = GL_ONE; GLenum srcA = GL_ONE; GLenum dstRGB = GL_ZERO; GLenum dstA = GL_ZERO; // if (mode == BLEND_LIGHTEN || mode == BLEND_DARKEN) // { // if (!isSupported(SUPPORT_LIGHTEN)) // throw love::Exception("The 'lighten' and 'darken' blend modes are not supported on this system."); // } // if (alphamode != BLENDALPHA_PREMULTIPLIED) // { // const char *modestr = "unknown"; // switch (mode) // { // case BLEND_LIGHTEN: // case BLEND_DARKEN: // /*case BLEND_MULTIPLY:*/ // FIXME: Uncomment for 0.11.0 // getConstant(mode, modestr); // throw love::Exception("The '%s' blend mode must be used with premultiplied alpha.", modestr); // break; // default: // break; // } // } switch (mode) { case BLEND_ALPHA: srcRGB = srcA = GL_ONE; dstRGB = dstA = GL_ONE_MINUS_SRC_ALPHA; break; case BLEND_MULTIPLY: srcRGB = srcA = GL_DST_COLOR; dstRGB = dstA = GL_ZERO; break; case BLEND_SUBTRACT: func = GL_FUNC_REVERSE_SUBTRACT; case BLEND_ADD: srcRGB = GL_ONE; srcA = GL_ZERO; dstRGB = dstA = GL_ONE; break; case BLEND_LIGHTEN: func = GL_MAX; break; case BLEND_DARKEN: func = GL_MIN; break; case BLEND_SCREEN: srcRGB = srcA = GL_ONE; dstRGB = dstA = GL_ONE_MINUS_SRC_COLOR; break; case BLEND_REPLACE: default: srcRGB = srcA = GL_ONE; dstRGB = dstA = GL_ZERO; break; } // We can only do alpha-multiplication when srcRGB would have been unmodified. if (srcRGB == GL_ONE && alphamode == BLENDALPHA_MULTIPLY) srcRGB = GL_SRC_ALPHA; glBlendEquation(func); glBlendFuncSeparate(srcRGB, dstRGB, srcA, dstA); states.back().blendMode = mode; states.back().blendAlphaMode = alphamode; } Demoloop::BlendMode Demoloop::getBlendMode(BlendAlpha &alphamode) const { alphamode = states.back().blendAlphaMode; return states.back().blendMode; } int Demoloop::getMouseX() const { return mouse_x; } int Demoloop::getMouseY() const { return mouse_y; } int Demoloop::getMouseDeltaX() const { return mouse_x - prev_mouse_x; } int Demoloop::getMouseDeltaY() const { return mouse_y - prev_mouse_y; } bool Demoloop::isMouseDown(uint8_t button) const { return SDL_BUTTON(button) & mouse_state; } void Demoloop::InternalUpdate() { while (SDL_PollEvent(&e)){ //If user closes the window if (e.type == SDL_QUIT){ quit = true; } //If user presses any key if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE){ quit = true; } } prev_mouse_x = mouse_x, prev_mouse_y = mouse_y; mouse_state = SDL_GetMouseState(&mouse_x, &mouse_y); glClearColor( bg_r / 255.0, bg_g / 255.0, bg_b / 255.0, 1.f ); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); auto now = std::chrono::high_resolution_clock::now(); auto delta = std::chrono::duration_cast<std::chrono::duration<float>>(now - previous_frame); previous_frame = now; Update(delta.count()); SDL_GL_SwapWindow(window); } void Demoloop::Run() { previous_frame = std::chrono::high_resolution_clock::now(); #ifdef __EMSCRIPTEN__ emscripten_set_main_loop_arg([](void *arg) { Demoloop *self = static_cast<Demoloop*>(arg); self->InternalUpdate(); }, (void *)this, 0, 1); #else const std::chrono::duration<float> interval(1.0f / 60.0f); while (!quit) { auto start = std::chrono::high_resolution_clock::now(); InternalUpdate(); while((std::chrono::high_resolution_clock::now() - start) < interval){} } // const std::chrono::seconds CYCLE_LENGTH(10); // const std::chrono::duration<float> interval(1.0f / 50.0f); // char* pixels = new char [3 * width * height]; // SDL_Surface* temp = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0); // uint32_t index = 0; // for (std::chrono::duration<float> elapsed(0); elapsed <= CYCLE_LENGTH; elapsed += interval) { // glClearColor( bg_r / 255.0, bg_g / 255.0, bg_b / 255.0, 1.f ); // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Update(interval.count()); // SDL_GL_SwapWindow(window); // glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); // for (int i = 0 ; i < height ; i++) // std::memcpy( ((char *) temp->pixels) + temp->pitch * i, pixels + 3 * width * (height-i - 1), width*3 ); // auto numString = std::to_string(index++); // numString = std::string(4 - numString.length(), '0') + numString; // SDL_SaveBMP(temp, ("frames/frame" + numString + ".bmp").c_str()); // } // cleanup(temp); // delete [] pixels; #endif } } <|endoftext|>
<commit_before>//===-- GDBRemoteCommunicationReplayServer.cpp ------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <errno.h> #include "lldb/Host/Config.h" #include "GDBRemoteCommunicationReplayServer.h" #include "ProcessGDBRemoteLog.h" // C Includes // C++ Includes #include <cstring> // Project includes #include "lldb/Host/ThreadLauncher.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/Event.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/StringExtractorGDBRemote.h" using namespace llvm; using namespace lldb; using namespace lldb_private; using namespace lldb_private::process_gdb_remote; /// Check if the given expected packet matches the actual packet. static bool unexpected(llvm::StringRef expected, llvm::StringRef actual) { // The 'expected' string contains the raw data, including the leading $ and // trailing checksum. The 'actual' string contains only the packet's content. if (expected.contains(actual)) return false; // Contains a PID which might be different. if (expected.contains("vAttach")) return false; // Contains a ascii-hex-path. if (expected.contains("QSetSTD")) return false; // Contains environment values. if (expected.contains("QEnvironment")) return false; return true; } /// Check if we should reply to the given packet. static bool skip(llvm::StringRef data) { assert(!data.empty() && "Empty packet?"); // We've already acknowledge the '+' packet so we're done here. if (data == "+") return true; /// Don't 't reply to ^C. We need this because of stop reply packets, which /// are only returned when the target halts. Reproducers synchronize these /// 'asynchronous' replies, by recording them as a regular replies to the /// previous packet (e.g. vCont). As a result, we should ignore real /// asynchronous requests. if (data.data()[0] == 0x03) return true; return false; } GDBRemoteCommunicationReplayServer::GDBRemoteCommunicationReplayServer() : GDBRemoteCommunication("gdb-replay", "gdb-replay.rx_packet"), m_async_broadcaster(nullptr, "lldb.gdb-replay.async-broadcaster"), m_async_listener_sp( Listener::MakeListener("lldb.gdb-replay.async-listener")), m_async_thread_state_mutex(), m_skip_acks(false) { m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue, "async thread continue"); m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit, "async thread should exit"); const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit; m_async_listener_sp->StartListeningForEvents(&m_async_broadcaster, async_event_mask); } GDBRemoteCommunicationReplayServer::~GDBRemoteCommunicationReplayServer() { StopAsyncThread(); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationReplayServer::GetPacketAndSendResponse( Timeout<std::micro> timeout, Status &error, bool &interrupt, bool &quit) { std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); StringExtractorGDBRemote packet; PacketResult packet_result = WaitForPacketNoLock(packet, timeout, false); if (packet_result != PacketResult::Success) { if (!IsConnected()) { error.SetErrorString("lost connection"); quit = true; } else { error.SetErrorString("timeout"); } return packet_result; } m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue); // Check if we should reply to this packet. if (skip(packet.GetStringRef())) return PacketResult::Success; // This completes the handshake. Since m_send_acks was true, we can unset it // already. if (packet.GetStringRef() == "QStartNoAckMode") m_send_acks = false; // A QEnvironment packet is sent for every environment variable. If the // number of environment variables is different during replay, the replies // become out of sync. if (packet.GetStringRef().find("QEnvironment") == 0) return SendRawPacketNoLock("$OK#9a"); Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); while (!m_packet_history.empty()) { // Pop last packet from the history. GDBRemoteCommunicationHistory::Entry entry = m_packet_history.back(); m_packet_history.pop_back(); // We've handled the handshake implicitly before. Skip the packet and move // on. if (entry.packet.data == "+") continue; if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeSend) { if (unexpected(entry.packet.data, packet.GetStringRef())) { LLDB_LOG(log, "GDBRemoteCommunicationReplayServer expected packet: '{0}'", entry.packet.data); LLDB_LOG(log, "GDBRemoteCommunicationReplayServer actual packet: '{0}'", packet.GetStringRef()); assert(false && "Encountered unexpected packet during replay"); return PacketResult::ErrorSendFailed; } // Ignore QEnvironment packets as they're handled earlier. if (entry.packet.data.find("QEnvironment") == 1) { assert(m_packet_history.back().type == GDBRemoteCommunicationHistory::ePacketTypeRecv); m_packet_history.pop_back(); } continue; } if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeInvalid) { LLDB_LOG( log, "GDBRemoteCommunicationReplayServer skipped invalid packet: '{0}'", packet.GetStringRef()); continue; } LLDB_LOG(log, "GDBRemoteCommunicationReplayServer replied to '{0}' with '{1}'", packet.GetStringRef(), entry.packet.data); return SendRawPacketNoLock(entry.packet.data); } quit = true; return packet_result; } LLVM_YAML_IS_DOCUMENT_LIST_VECTOR( std::vector< lldb_private::process_gdb_remote::GDBRemoteCommunicationHistory::Entry>) llvm::Error GDBRemoteCommunicationReplayServer::LoadReplayHistory(const FileSpec &path) { auto error_or_file = MemoryBuffer::getFile(path.GetPath()); if (auto err = error_or_file.getError()) return errorCodeToError(err); yaml::Input yin((*error_or_file)->getBuffer()); yin >> m_packet_history; if (auto err = yin.error()) return errorCodeToError(err); // We want to manipulate the vector like a stack so we need to reverse the // order of the packets to have the oldest on at the back. std::reverse(m_packet_history.begin(), m_packet_history.end()); return Error::success(); } bool GDBRemoteCommunicationReplayServer::StartAsyncThread() { std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); if (!m_async_thread.IsJoinable()) { // Create a thread that watches our internal state and controls which // events make it to clients (into the DCProcess event queue). llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread( "<lldb.gdb-replay.async>", GDBRemoteCommunicationReplayServer::AsyncThread, this); if (!async_thread) { LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), "failed to launch host thread: {}", llvm::toString(async_thread.takeError())); return false; } m_async_thread = *async_thread; } // Wait for handshake. m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue); return m_async_thread.IsJoinable(); } void GDBRemoteCommunicationReplayServer::StopAsyncThread() { std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); if (!m_async_thread.IsJoinable()) return; // Request thread to stop. m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit); // Disconnect client. Disconnect(); // Stop the thread. m_async_thread.Join(nullptr); m_async_thread.Reset(); } void GDBRemoteCommunicationReplayServer::ReceivePacket( GDBRemoteCommunicationReplayServer &server, bool &done) { Status error; bool interrupt; auto packet_result = server.GetPacketAndSendResponse(std::chrono::seconds(1), error, interrupt, done); if (packet_result != GDBRemoteCommunication::PacketResult::Success && packet_result != GDBRemoteCommunication::PacketResult::ErrorReplyTimeout) { done = true; } else { server.m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue); } } thread_result_t GDBRemoteCommunicationReplayServer::AsyncThread(void *arg) { GDBRemoteCommunicationReplayServer *server = (GDBRemoteCommunicationReplayServer *)arg; EventSP event_sp; bool done = false; while (true) { if (server->m_async_listener_sp->GetEvent(event_sp, llvm::None)) { const uint32_t event_type = event_sp->GetType(); if (event_sp->BroadcasterIs(&server->m_async_broadcaster)) { switch (event_type) { case eBroadcastBitAsyncContinue: ReceivePacket(*server, done); if (done) return {}; break; case eBroadcastBitAsyncThreadShouldExit: default: return {}; } } } } return {}; } <commit_msg>[Reproducer] Disconnect when the replay server is out of packets.<commit_after>//===-- GDBRemoteCommunicationReplayServer.cpp ------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <errno.h> #include "lldb/Host/Config.h" #include "llvm/ADT/ScopeExit.h" #include "GDBRemoteCommunicationReplayServer.h" #include "ProcessGDBRemoteLog.h" // C Includes // C++ Includes #include <cstring> // Project includes #include "lldb/Host/ThreadLauncher.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/Event.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/StringExtractorGDBRemote.h" using namespace llvm; using namespace lldb; using namespace lldb_private; using namespace lldb_private::process_gdb_remote; /// Check if the given expected packet matches the actual packet. static bool unexpected(llvm::StringRef expected, llvm::StringRef actual) { // The 'expected' string contains the raw data, including the leading $ and // trailing checksum. The 'actual' string contains only the packet's content. if (expected.contains(actual)) return false; // Contains a PID which might be different. if (expected.contains("vAttach")) return false; // Contains a ascii-hex-path. if (expected.contains("QSetSTD")) return false; // Contains environment values. if (expected.contains("QEnvironment")) return false; return true; } /// Check if we should reply to the given packet. static bool skip(llvm::StringRef data) { assert(!data.empty() && "Empty packet?"); // We've already acknowledge the '+' packet so we're done here. if (data == "+") return true; /// Don't 't reply to ^C. We need this because of stop reply packets, which /// are only returned when the target halts. Reproducers synchronize these /// 'asynchronous' replies, by recording them as a regular replies to the /// previous packet (e.g. vCont). As a result, we should ignore real /// asynchronous requests. if (data.data()[0] == 0x03) return true; return false; } GDBRemoteCommunicationReplayServer::GDBRemoteCommunicationReplayServer() : GDBRemoteCommunication("gdb-replay", "gdb-replay.rx_packet"), m_async_broadcaster(nullptr, "lldb.gdb-replay.async-broadcaster"), m_async_listener_sp( Listener::MakeListener("lldb.gdb-replay.async-listener")), m_async_thread_state_mutex(), m_skip_acks(false) { m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue, "async thread continue"); m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit, "async thread should exit"); const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit; m_async_listener_sp->StartListeningForEvents(&m_async_broadcaster, async_event_mask); } GDBRemoteCommunicationReplayServer::~GDBRemoteCommunicationReplayServer() { StopAsyncThread(); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationReplayServer::GetPacketAndSendResponse( Timeout<std::micro> timeout, Status &error, bool &interrupt, bool &quit) { std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); StringExtractorGDBRemote packet; PacketResult packet_result = WaitForPacketNoLock(packet, timeout, false); if (packet_result != PacketResult::Success) { if (!IsConnected()) { error.SetErrorString("lost connection"); quit = true; } else { error.SetErrorString("timeout"); } return packet_result; } m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue); // Check if we should reply to this packet. if (skip(packet.GetStringRef())) return PacketResult::Success; // This completes the handshake. Since m_send_acks was true, we can unset it // already. if (packet.GetStringRef() == "QStartNoAckMode") m_send_acks = false; // A QEnvironment packet is sent for every environment variable. If the // number of environment variables is different during replay, the replies // become out of sync. if (packet.GetStringRef().find("QEnvironment") == 0) return SendRawPacketNoLock("$OK#9a"); Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); while (!m_packet_history.empty()) { // Pop last packet from the history. GDBRemoteCommunicationHistory::Entry entry = m_packet_history.back(); m_packet_history.pop_back(); // We've handled the handshake implicitly before. Skip the packet and move // on. if (entry.packet.data == "+") continue; if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeSend) { if (unexpected(entry.packet.data, packet.GetStringRef())) { LLDB_LOG(log, "GDBRemoteCommunicationReplayServer expected packet: '{0}'", entry.packet.data); LLDB_LOG(log, "GDBRemoteCommunicationReplayServer actual packet: '{0}'", packet.GetStringRef()); assert(false && "Encountered unexpected packet during replay"); return PacketResult::ErrorSendFailed; } // Ignore QEnvironment packets as they're handled earlier. if (entry.packet.data.find("QEnvironment") == 1) { assert(m_packet_history.back().type == GDBRemoteCommunicationHistory::ePacketTypeRecv); m_packet_history.pop_back(); } continue; } if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeInvalid) { LLDB_LOG( log, "GDBRemoteCommunicationReplayServer skipped invalid packet: '{0}'", packet.GetStringRef()); continue; } LLDB_LOG(log, "GDBRemoteCommunicationReplayServer replied to '{0}' with '{1}'", packet.GetStringRef(), entry.packet.data); return SendRawPacketNoLock(entry.packet.data); } quit = true; return packet_result; } LLVM_YAML_IS_DOCUMENT_LIST_VECTOR( std::vector< lldb_private::process_gdb_remote::GDBRemoteCommunicationHistory::Entry>) llvm::Error GDBRemoteCommunicationReplayServer::LoadReplayHistory(const FileSpec &path) { auto error_or_file = MemoryBuffer::getFile(path.GetPath()); if (auto err = error_or_file.getError()) return errorCodeToError(err); yaml::Input yin((*error_or_file)->getBuffer()); yin >> m_packet_history; if (auto err = yin.error()) return errorCodeToError(err); // We want to manipulate the vector like a stack so we need to reverse the // order of the packets to have the oldest on at the back. std::reverse(m_packet_history.begin(), m_packet_history.end()); return Error::success(); } bool GDBRemoteCommunicationReplayServer::StartAsyncThread() { std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); if (!m_async_thread.IsJoinable()) { // Create a thread that watches our internal state and controls which // events make it to clients (into the DCProcess event queue). llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread( "<lldb.gdb-replay.async>", GDBRemoteCommunicationReplayServer::AsyncThread, this); if (!async_thread) { LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), "failed to launch host thread: {}", llvm::toString(async_thread.takeError())); return false; } m_async_thread = *async_thread; } // Wait for handshake. m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue); return m_async_thread.IsJoinable(); } void GDBRemoteCommunicationReplayServer::StopAsyncThread() { std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); if (!m_async_thread.IsJoinable()) return; // Request thread to stop. m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit); // Disconnect client. Disconnect(); // Stop the thread. m_async_thread.Join(nullptr); m_async_thread.Reset(); } void GDBRemoteCommunicationReplayServer::ReceivePacket( GDBRemoteCommunicationReplayServer &server, bool &done) { Status error; bool interrupt; auto packet_result = server.GetPacketAndSendResponse(std::chrono::seconds(1), error, interrupt, done); if (packet_result != GDBRemoteCommunication::PacketResult::Success && packet_result != GDBRemoteCommunication::PacketResult::ErrorReplyTimeout) { done = true; } else { server.m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue); } } thread_result_t GDBRemoteCommunicationReplayServer::AsyncThread(void *arg) { GDBRemoteCommunicationReplayServer *server = (GDBRemoteCommunicationReplayServer *)arg; auto D = make_scope_exit([&]() { server->Disconnect(); }); EventSP event_sp; bool done = false; while (!done) { if (server->m_async_listener_sp->GetEvent(event_sp, llvm::None)) { const uint32_t event_type = event_sp->GetType(); if (event_sp->BroadcasterIs(&server->m_async_broadcaster)) { switch (event_type) { case eBroadcastBitAsyncContinue: ReceivePacket(*server, done); if (done) return {}; break; case eBroadcastBitAsyncThreadShouldExit: default: return {}; } } } } return {}; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" #include "content/common/gpu/media/h264_bit_reader.h" using content::H264BitReader; TEST(H264BitReaderTest, ReadStreamWithoutEscapeAndTrailingZeroBytes) { H264BitReader reader; const unsigned char rbsp[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xa0}; int dummy = 0; EXPECT_TRUE(reader.Initialize(rbsp, sizeof(rbsp))); EXPECT_TRUE(reader.ReadBits(1, &dummy)); EXPECT_EQ(dummy, 0x00); EXPECT_EQ(reader.NumBitsLeft(), 47); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(8, &dummy)); EXPECT_EQ(dummy, 0x02); EXPECT_EQ(reader.NumBitsLeft(), 39); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(31, &dummy)); EXPECT_EQ(dummy, 0x23456789); EXPECT_EQ(reader.NumBitsLeft(), 8); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(1, &dummy)); EXPECT_EQ(dummy, 1); EXPECT_EQ(reader.NumBitsLeft(), 7); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(1, &dummy)); EXPECT_EQ(dummy, 0); EXPECT_EQ(reader.NumBitsLeft(), 6); EXPECT_FALSE(reader.HasMoreRBSPData()); } TEST(H264BitReaderTest, EmptyStream) { H264BitReader reader; const unsigned char rbsp[] = {0x80, 0x00, 0x00}; EXPECT_FALSE(reader.Initialize(rbsp, 0)); EXPECT_FALSE(reader.Initialize(rbsp, 1)); EXPECT_FALSE(reader.Initialize(rbsp, sizeof(rbsp))); } TEST(H264BitReaderTest, SingleByteStream) { H264BitReader reader; const unsigned char rbsp[] = {0x18}; int dummy = 0; EXPECT_TRUE(reader.Initialize(rbsp, sizeof(rbsp))); EXPECT_EQ(reader.NumBitsLeft(), 8); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(4, &dummy)); EXPECT_EQ(dummy, 0x01); EXPECT_EQ(reader.NumBitsLeft(), 4); EXPECT_FALSE(reader.HasMoreRBSPData()); } TEST(H264BitReaderTest, StopBitOccupyFullByte) { H264BitReader reader; const unsigned char rbsp[] = {0xab, 0x80}; int dummy = 0; EXPECT_TRUE(reader.Initialize(rbsp, sizeof(rbsp))); EXPECT_EQ(reader.NumBitsLeft(), 16); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(8, &dummy)); EXPECT_EQ(dummy, 0xab); EXPECT_EQ(reader.NumBitsLeft(), 8); EXPECT_FALSE(reader.HasMoreRBSPData()); } TEST(H264BitReaderTest, ReadFailure) { H264BitReader reader; const unsigned char rbsp[] = {0x18}; int dummy = 0; EXPECT_TRUE(reader.Initialize(rbsp, 1)); EXPECT_FALSE(reader.ReadBits(5, &dummy)); } TEST(H264BitReaderTest, MalformedStream) { const unsigned char rbsp[] = {0x00, 0x00, 0x03, 0x00, 0x00}; H264BitReader reader; EXPECT_FALSE(reader.Initialize(rbsp, 1)); EXPECT_FALSE(reader.Initialize(rbsp, sizeof(rbsp))); } TEST(H264BitReaderTest, EscapeSequence) { H264BitReader reader; const unsigned char rbsp[] = {0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x03}; int dummy = 0; EXPECT_TRUE(reader.Initialize(rbsp, sizeof(rbsp))); EXPECT_TRUE(reader.ReadBits(8, &dummy)); EXPECT_EQ(dummy, 0x00); EXPECT_EQ(reader.NumBitsLeft(), 80); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(24, &dummy)); EXPECT_EQ(dummy, 0x00); EXPECT_EQ(reader.NumBitsLeft(), 48); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(15, &dummy)); EXPECT_EQ(dummy, 0x01); EXPECT_EQ(reader.NumBitsLeft(), 25); EXPECT_FALSE(reader.HasMoreRBSPData()); } TEST(H264BitReaderTest, NonEscapeFollowedByStopBit) { H264BitReader reader; const unsigned char rbsp[] = {0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00}; int dummy = 0; EXPECT_TRUE(reader.Initialize(rbsp, sizeof(rbsp))); EXPECT_TRUE(reader.ReadBits(23, &dummy)); EXPECT_EQ(dummy, 0x03); EXPECT_EQ(reader.NumBitsLeft(), 33); EXPECT_FALSE(reader.HasMoreRBSPData()); } TEST(H264BitReaderTest, TrailingZero) { H264BitReader reader; const unsigned char rbsp[] = {0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}; int dummy = 0; EXPECT_TRUE(reader.Initialize(rbsp, sizeof(rbsp))); EXPECT_TRUE(reader.ReadBits(8, &dummy)); EXPECT_EQ(dummy, 0x01); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(15, &dummy)); EXPECT_EQ(dummy, 0x01); EXPECT_FALSE(reader.HasMoreRBSPData()); } <commit_msg>Remove failed tests for H264BitReader.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" #include "content/common/gpu/media/h264_bit_reader.h" using content::H264BitReader; TEST(H264BitReaderTest, ReadStreamWithoutEscapeAndTrailingZeroBytes) { H264BitReader reader; const unsigned char rbsp[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xa0}; int dummy = 0; EXPECT_TRUE(reader.Initialize(rbsp, sizeof(rbsp))); EXPECT_TRUE(reader.ReadBits(1, &dummy)); EXPECT_EQ(dummy, 0x00); EXPECT_EQ(reader.NumBitsLeft(), 47); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(8, &dummy)); EXPECT_EQ(dummy, 0x02); EXPECT_EQ(reader.NumBitsLeft(), 39); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(31, &dummy)); EXPECT_EQ(dummy, 0x23456789); EXPECT_EQ(reader.NumBitsLeft(), 8); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(1, &dummy)); EXPECT_EQ(dummy, 1); EXPECT_EQ(reader.NumBitsLeft(), 7); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(1, &dummy)); EXPECT_EQ(dummy, 0); EXPECT_EQ(reader.NumBitsLeft(), 6); EXPECT_FALSE(reader.HasMoreRBSPData()); } TEST(H264BitReaderTest, SingleByteStream) { H264BitReader reader; const unsigned char rbsp[] = {0x18}; int dummy = 0; EXPECT_TRUE(reader.Initialize(rbsp, sizeof(rbsp))); EXPECT_EQ(reader.NumBitsLeft(), 8); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(4, &dummy)); EXPECT_EQ(dummy, 0x01); EXPECT_EQ(reader.NumBitsLeft(), 4); EXPECT_FALSE(reader.HasMoreRBSPData()); } TEST(H264BitReaderTest, StopBitOccupyFullByte) { H264BitReader reader; const unsigned char rbsp[] = {0xab, 0x80}; int dummy = 0; EXPECT_TRUE(reader.Initialize(rbsp, sizeof(rbsp))); EXPECT_EQ(reader.NumBitsLeft(), 16); EXPECT_TRUE(reader.HasMoreRBSPData()); EXPECT_TRUE(reader.ReadBits(8, &dummy)); EXPECT_EQ(dummy, 0xab); EXPECT_EQ(reader.NumBitsLeft(), 8); EXPECT_FALSE(reader.HasMoreRBSPData()); } <|endoftext|>
<commit_before>#include "sprite_importer.h" #include "halley/tools/assets/import_assets_database.h" #include "halley/bytes/byte_serializer.h" #include "halley/resources/metadata.h" #include "halley/file_formats/image.h" #include "halley/tools/file/filesystem.h" #include "halley/core/graphics/sprite/sprite_sheet.h" #include "halley/core/graphics/sprite/animation.h" #include "halley/data_structures/bin_pack.h" #include "halley/text/string_converter.h" #include "../../sprites/aseprite_reader.h" #include "halley/support/logger.h" using namespace Halley; bool ImageData::operator==(const ImageData& other) const { return frameNumber == other.frameNumber && duration == other.duration && sequenceName == other.sequenceName && clip == other.clip && pivot == other.pivot && slices == other.slices && filenames == other.filenames && img->getSize() == other.img->getSize(); } bool ImageData::operator!=(const ImageData& other) const { return !(*this == other); } void SpriteImporter::import(const ImportingAsset& asset, IAssetCollector& collector) { String atlasName = asset.assetId; String spriteSheetName = Path(asset.assetId).replaceExtension("").string(); std::vector<ImageData> totalFrames; Maybe<Metadata> startMeta; Maybe<String> palette; for (auto& inputFile: asset.inputFiles) { auto fileInputId = Path(inputFile.name).dropFront(1); const String spriteName = fileInputId.replaceExtension("").string(); // Meta Metadata meta = inputFile.metadata; if (!startMeta) { startMeta = meta; } Vector2i pivot; pivot.x = meta.getInt("pivotX", 0); pivot.y = meta.getInt("pivotY", 0); Vector4s slices; slices.x = gsl::narrow<short, int>(meta.getInt("slice_left", 0)); slices.y = gsl::narrow<short, int>(meta.getInt("slice_top", 0)); slices.z = gsl::narrow<short, int>(meta.getInt("slice_right", 0)); slices.w = gsl::narrow<short, int>(meta.getInt("slice_bottom", 0)); bool trim = meta.getBool("trim", true); // Palette auto thisPalette = meta.getString("palette", ""); if (palette) { if (thisPalette != palette.get()) { throw Exception("Incompatible palettes in atlas \"" + atlasName + "\". Previously using \"" + palette.get() + "\", now trying to use \"" + thisPalette + "\"", HalleyExceptions::Tools); } } else { palette = thisPalette; } // Import image data std::vector<ImageData> frames; if (inputFile.name.getExtension() == ".ase") { // Import Aseprite file frames = AsepriteReader::importAseprite(spriteName, gsl::as_bytes(gsl::span<const Byte>(inputFile.data)), trim); } else { // Bitmap auto span = gsl::as_bytes(gsl::span<const Byte>(inputFile.data)); auto image = std::make_unique<Image>(span, fromString<Image::Format>(meta.getString("format", "undefined"))); frames.emplace_back(); auto& imgData = frames.back(); imgData.clip = trim ? image->getTrimRect() : image->getRect(); // Be careful, make sure this is done before the std::move() below imgData.img = std::move(image); imgData.duration = 100; imgData.filenames.emplace_back(":img:" + fileInputId.toString()); imgData.frameNumber = 0; imgData.sequenceName = ""; } // Update frames with pivot and slices for (auto& f: frames) { f.pivot = pivot; f.slices = slices; } // Split into a grid const Vector2i grid(meta.getInt("tileWidth", 0), meta.getInt("tileHeight", 0)); if (grid.x > 0 && grid.y > 0) { frames = splitImagesInGrid(frames, grid); } // Write animation Animation animation = generateAnimation(spriteName, spriteSheetName, meta.getString("material", "Halley/Sprite"), frames); collector.output(spriteName, AssetType::Animation, Serializer::toBytes(animation)); std::move(frames.begin(), frames.end(), std::back_inserter(totalFrames)); } // Generate atlas + spritesheet SpriteSheet spriteSheet; auto atlasImage = generateAtlas(atlasName, totalFrames, spriteSheet); spriteSheet.setTextureName(atlasName); // Image metafile auto size = atlasImage->getSize(); Metadata meta; if (startMeta) { meta = startMeta.get(); } if (palette) { meta.set("palette", palette.get()); } meta.set("width", size.x); meta.set("height", size.y); meta.set("compression", "raw_image"); // Write atlas image ImportingAsset image; image.assetId = atlasName; image.assetType = ImportAssetType::Image; image.inputFiles.emplace_back(ImportingAssetFile(atlasName, Serializer::toBytes(*atlasImage), meta)); collector.addAdditionalAsset(std::move(image)); // Write spritesheet collector.output(spriteSheetName, AssetType::SpriteSheet, Serializer::toBytes(spriteSheet)); } String SpriteImporter::getAssetId(const Path& file, const Maybe<Metadata>& metadata) const { if (metadata) { String atlas = metadata.get().getString("atlas", ""); if (atlas != "") { return atlas; } } return IAssetImporter::getAssetId(file, metadata); } Animation SpriteImporter::generateAnimation(const String& spriteName, const String& spriteSheetName, const String& materialName, const std::vector<ImageData>& frameData) { Animation animation; animation.setName(spriteName); animation.setMaterialName(materialName); animation.setSpriteSheetName(spriteSheetName); std::map<String, AnimationSequence> sequences; animation.addDirection(AnimationDirection("right", "forward", false, 0)); animation.addDirection(AnimationDirection("left", "forward", true, 0)); for (auto& frame: frameData) { auto i = sequences.find(frame.sequenceName); if (i == sequences.end()) { sequences[frame.sequenceName] = AnimationSequence(frame.sequenceName, true, false); } auto& seq = sequences[frame.sequenceName]; seq.addFrame(AnimationFrameDefinition(frame.frameNumber, frame.duration, frame.filenames.at(0))); } for (auto& seq: sequences) { animation.addSequence(seq.second); } return animation; } std::unique_ptr<Image> SpriteImporter::generateAtlas(const String& atlasName, std::vector<ImageData>& images, SpriteSheet& spriteSheet) { if (images.size() > 1) { Logger::logInfo("Generating atlas \"" + atlasName + "\" with " + toString(images.size()) + " sprites..."); } // Generate entries int64_t totalImageArea = 0; std::vector<BinPackEntry> entries; entries.reserve(images.size()); for (auto& img: images) { auto size = img.clip.getSize(); totalImageArea += size.x * size.y; entries.emplace_back(size, &img); } // Figure out a reasonable pack size to start with const int minSize = nextPowerOf2(int(sqrt(double(totalImageArea)))) / 2; const int64_t guessArea = int64_t(minSize) * int64_t(minSize); const int maxSize = 4096; int curSize = std::min(maxSize, std::max(32, int(minSize))); // Try packing bool wide = guessArea > 2 * totalImageArea; while (true) { Vector2i size(curSize * (wide ? 2 : 1), curSize); if (size.x > maxSize || size.y > maxSize) { // Give up! throw Exception("Unable to pack " + toString(images.size()) + " sprites in a reasonably sized atlas! curSize at " + toString(curSize) + ", maxSize is " + toString(maxSize) + ". Total image area is " + toString(totalImageArea) + " px^2, sqrt = " + toString(lround(sqrt(totalImageArea))) + " px.", HalleyExceptions::Tools); } Logger::logInfo("Trying " + toString(size.x) + "x" + toString(size.y) + " px..."); auto res = BinPack::pack(entries, size); if (res.is_initialized()) { // Found a pack if (images.size() > 1) { Logger::logInfo("Atlas \"" + atlasName + "\" generated at " + toString(size.x) + "x" + toString(size.y) + " px with " + toString(images.size()) + " sprites. Total image area is " + toString(totalImageArea) + " px^2, sqrt = " + toString(lround(sqrt(totalImageArea))) + " px."); } return makeAtlas(res.get(), size, spriteSheet); } else { // Try 64x64, then 128x64, 128x128, 256x128, etc if (wide) { wide = false; curSize *= 2; } else { wide = true; } } } } std::unique_ptr<Image> SpriteImporter::makeAtlas(const std::vector<BinPackResult>& result, Vector2i origSize, SpriteSheet& spriteSheet) { Vector2i size = shrinkAtlas(result); auto image = std::make_unique<Image>(Image::Format::RGBA, size); image->clear(0); for (auto& packedImg: result) { ImageData* img = reinterpret_cast<ImageData*>(packedImg.data); image->blitFrom(packedImg.rect.getTopLeft(), *img->img, img->clip, packedImg.rotated); const auto borderTL = img->clip.getTopLeft(); const auto borderBR = img->img->getSize() - img->clip.getSize() - borderTL; const auto offset = Vector2f(0.0001f, 0.0001f); SpriteSheetEntry entry; entry.size = Vector2f(img->clip.getSize()); entry.rotated = packedImg.rotated; entry.pivot = Vector2f(img->pivot - img->clip.getTopLeft()) / entry.size; entry.origPivot = img->pivot; entry.coords = (Rect4f(Vector2f(packedImg.rect.getTopLeft()) + offset, Vector2f(packedImg.rect.getBottomRight()) + offset)) / Vector2f(size); entry.trimBorder = Vector4s(short(borderTL.x), short(borderTL.y), short(borderBR.x), short(borderBR.y)); entry.slices = img->slices; for (auto& filename: img->filenames) { spriteSheet.addSprite(filename, entry); } } return image; } Vector2i SpriteImporter::shrinkAtlas(const std::vector<BinPackResult>& results) const { int w = 0; int h = 0; for (auto& r: results) { w = std::max(w, r.rect.getRight()); h = std::max(h, r.rect.getBottom()); } return Vector2i(nextPowerOf2(w), nextPowerOf2(h)); } std::vector<ImageData> SpriteImporter::splitImagesInGrid(const std::vector<ImageData>& images, Vector2i grid) { std::vector<ImageData> result; for (auto& src: images) { auto imgSize = src.img->getSize(); int nX = imgSize.x / grid.x; int nY = imgSize.y / grid.y; for (int y = 0; y < nY; ++y) { for (int x = 0; x < nX; ++x) { auto img = std::make_unique<Image>(Image::Format::RGBA, grid); img->blitFrom(Vector2i(), *src.img, Rect4i(Vector2i(x, y) * grid, grid.x, grid.y)); Rect4i trimRect = img->getTrimRect(); if (trimRect.getWidth() > 0 && trimRect.getHeight() > 0) { result.emplace_back(); auto& dst = result.back(); String suffix = "_" + toString(x) + "_" + toString(y); dst.duration = src.duration; dst.frameNumber = src.frameNumber; dst.filenames.emplace_back(src.filenames.at(0) + suffix); dst.sequenceName = src.sequenceName + suffix; dst.img = std::move(img); dst.clip = Rect4i({}, grid); } } } } return result; } <commit_msg>Allow importing .aseprite<commit_after>#include "sprite_importer.h" #include "halley/tools/assets/import_assets_database.h" #include "halley/bytes/byte_serializer.h" #include "halley/resources/metadata.h" #include "halley/file_formats/image.h" #include "halley/tools/file/filesystem.h" #include "halley/core/graphics/sprite/sprite_sheet.h" #include "halley/core/graphics/sprite/animation.h" #include "halley/data_structures/bin_pack.h" #include "halley/text/string_converter.h" #include "../../sprites/aseprite_reader.h" #include "halley/support/logger.h" using namespace Halley; bool ImageData::operator==(const ImageData& other) const { return frameNumber == other.frameNumber && duration == other.duration && sequenceName == other.sequenceName && clip == other.clip && pivot == other.pivot && slices == other.slices && filenames == other.filenames && img->getSize() == other.img->getSize(); } bool ImageData::operator!=(const ImageData& other) const { return !(*this == other); } void SpriteImporter::import(const ImportingAsset& asset, IAssetCollector& collector) { String atlasName = asset.assetId; String spriteSheetName = Path(asset.assetId).replaceExtension("").string(); std::vector<ImageData> totalFrames; Maybe<Metadata> startMeta; Maybe<String> palette; for (auto& inputFile: asset.inputFiles) { auto fileInputId = Path(inputFile.name).dropFront(1); const String spriteName = fileInputId.replaceExtension("").string(); // Meta Metadata meta = inputFile.metadata; if (!startMeta) { startMeta = meta; } Vector2i pivot; pivot.x = meta.getInt("pivotX", 0); pivot.y = meta.getInt("pivotY", 0); Vector4s slices; slices.x = gsl::narrow<short, int>(meta.getInt("slice_left", 0)); slices.y = gsl::narrow<short, int>(meta.getInt("slice_top", 0)); slices.z = gsl::narrow<short, int>(meta.getInt("slice_right", 0)); slices.w = gsl::narrow<short, int>(meta.getInt("slice_bottom", 0)); bool trim = meta.getBool("trim", true); // Palette auto thisPalette = meta.getString("palette", ""); if (palette) { if (thisPalette != palette.get()) { throw Exception("Incompatible palettes in atlas \"" + atlasName + "\". Previously using \"" + palette.get() + "\", now trying to use \"" + thisPalette + "\"", HalleyExceptions::Tools); } } else { palette = thisPalette; } // Import image data std::vector<ImageData> frames; if (inputFile.name.getExtension() == ".ase" || inputFile.name.getExtension() == ".aseprite") { // Import Aseprite file frames = AsepriteReader::importAseprite(spriteName, gsl::as_bytes(gsl::span<const Byte>(inputFile.data)), trim); } else { // Bitmap auto span = gsl::as_bytes(gsl::span<const Byte>(inputFile.data)); auto image = std::make_unique<Image>(span, fromString<Image::Format>(meta.getString("format", "undefined"))); frames.emplace_back(); auto& imgData = frames.back(); imgData.clip = trim ? image->getTrimRect() : image->getRect(); // Be careful, make sure this is done before the std::move() below imgData.img = std::move(image); imgData.duration = 100; imgData.filenames.emplace_back(":img:" + fileInputId.toString()); imgData.frameNumber = 0; imgData.sequenceName = ""; } // Update frames with pivot and slices for (auto& f: frames) { f.pivot = pivot; f.slices = slices; } // Split into a grid const Vector2i grid(meta.getInt("tileWidth", 0), meta.getInt("tileHeight", 0)); if (grid.x > 0 && grid.y > 0) { frames = splitImagesInGrid(frames, grid); } // Write animation Animation animation = generateAnimation(spriteName, spriteSheetName, meta.getString("material", "Halley/Sprite"), frames); collector.output(spriteName, AssetType::Animation, Serializer::toBytes(animation)); std::move(frames.begin(), frames.end(), std::back_inserter(totalFrames)); } // Generate atlas + spritesheet SpriteSheet spriteSheet; auto atlasImage = generateAtlas(atlasName, totalFrames, spriteSheet); spriteSheet.setTextureName(atlasName); // Image metafile auto size = atlasImage->getSize(); Metadata meta; if (startMeta) { meta = startMeta.get(); } if (palette) { meta.set("palette", palette.get()); } meta.set("width", size.x); meta.set("height", size.y); meta.set("compression", "raw_image"); // Write atlas image ImportingAsset image; image.assetId = atlasName; image.assetType = ImportAssetType::Image; image.inputFiles.emplace_back(ImportingAssetFile(atlasName, Serializer::toBytes(*atlasImage), meta)); collector.addAdditionalAsset(std::move(image)); // Write spritesheet collector.output(spriteSheetName, AssetType::SpriteSheet, Serializer::toBytes(spriteSheet)); } String SpriteImporter::getAssetId(const Path& file, const Maybe<Metadata>& metadata) const { if (metadata) { String atlas = metadata.get().getString("atlas", ""); if (atlas != "") { return atlas; } } return IAssetImporter::getAssetId(file, metadata); } Animation SpriteImporter::generateAnimation(const String& spriteName, const String& spriteSheetName, const String& materialName, const std::vector<ImageData>& frameData) { Animation animation; animation.setName(spriteName); animation.setMaterialName(materialName); animation.setSpriteSheetName(spriteSheetName); std::map<String, AnimationSequence> sequences; animation.addDirection(AnimationDirection("right", "forward", false, 0)); animation.addDirection(AnimationDirection("left", "forward", true, 0)); for (auto& frame: frameData) { auto i = sequences.find(frame.sequenceName); if (i == sequences.end()) { sequences[frame.sequenceName] = AnimationSequence(frame.sequenceName, true, false); } auto& seq = sequences[frame.sequenceName]; seq.addFrame(AnimationFrameDefinition(frame.frameNumber, frame.duration, frame.filenames.at(0))); } for (auto& seq: sequences) { animation.addSequence(seq.second); } return animation; } std::unique_ptr<Image> SpriteImporter::generateAtlas(const String& atlasName, std::vector<ImageData>& images, SpriteSheet& spriteSheet) { if (images.size() > 1) { Logger::logInfo("Generating atlas \"" + atlasName + "\" with " + toString(images.size()) + " sprites..."); } // Generate entries int64_t totalImageArea = 0; std::vector<BinPackEntry> entries; entries.reserve(images.size()); for (auto& img: images) { auto size = img.clip.getSize(); totalImageArea += size.x * size.y; entries.emplace_back(size, &img); } // Figure out a reasonable pack size to start with const int minSize = nextPowerOf2(int(sqrt(double(totalImageArea)))) / 2; const int64_t guessArea = int64_t(minSize) * int64_t(minSize); const int maxSize = 4096; int curSize = std::min(maxSize, std::max(32, int(minSize))); // Try packing bool wide = guessArea > 2 * totalImageArea; while (true) { Vector2i size(curSize * (wide ? 2 : 1), curSize); if (size.x > maxSize || size.y > maxSize) { // Give up! throw Exception("Unable to pack " + toString(images.size()) + " sprites in a reasonably sized atlas! curSize at " + toString(curSize) + ", maxSize is " + toString(maxSize) + ". Total image area is " + toString(totalImageArea) + " px^2, sqrt = " + toString(lround(sqrt(totalImageArea))) + " px.", HalleyExceptions::Tools); } Logger::logInfo("Trying " + toString(size.x) + "x" + toString(size.y) + " px..."); auto res = BinPack::pack(entries, size); if (res.is_initialized()) { // Found a pack if (images.size() > 1) { Logger::logInfo("Atlas \"" + atlasName + "\" generated at " + toString(size.x) + "x" + toString(size.y) + " px with " + toString(images.size()) + " sprites. Total image area is " + toString(totalImageArea) + " px^2, sqrt = " + toString(lround(sqrt(totalImageArea))) + " px."); } return makeAtlas(res.get(), size, spriteSheet); } else { // Try 64x64, then 128x64, 128x128, 256x128, etc if (wide) { wide = false; curSize *= 2; } else { wide = true; } } } } std::unique_ptr<Image> SpriteImporter::makeAtlas(const std::vector<BinPackResult>& result, Vector2i origSize, SpriteSheet& spriteSheet) { Vector2i size = shrinkAtlas(result); auto image = std::make_unique<Image>(Image::Format::RGBA, size); image->clear(0); for (auto& packedImg: result) { ImageData* img = reinterpret_cast<ImageData*>(packedImg.data); image->blitFrom(packedImg.rect.getTopLeft(), *img->img, img->clip, packedImg.rotated); const auto borderTL = img->clip.getTopLeft(); const auto borderBR = img->img->getSize() - img->clip.getSize() - borderTL; const auto offset = Vector2f(0.0001f, 0.0001f); SpriteSheetEntry entry; entry.size = Vector2f(img->clip.getSize()); entry.rotated = packedImg.rotated; entry.pivot = Vector2f(img->pivot - img->clip.getTopLeft()) / entry.size; entry.origPivot = img->pivot; entry.coords = (Rect4f(Vector2f(packedImg.rect.getTopLeft()) + offset, Vector2f(packedImg.rect.getBottomRight()) + offset)) / Vector2f(size); entry.trimBorder = Vector4s(short(borderTL.x), short(borderTL.y), short(borderBR.x), short(borderBR.y)); entry.slices = img->slices; for (auto& filename: img->filenames) { spriteSheet.addSprite(filename, entry); } } return image; } Vector2i SpriteImporter::shrinkAtlas(const std::vector<BinPackResult>& results) const { int w = 0; int h = 0; for (auto& r: results) { w = std::max(w, r.rect.getRight()); h = std::max(h, r.rect.getBottom()); } return Vector2i(nextPowerOf2(w), nextPowerOf2(h)); } std::vector<ImageData> SpriteImporter::splitImagesInGrid(const std::vector<ImageData>& images, Vector2i grid) { std::vector<ImageData> result; for (auto& src: images) { auto imgSize = src.img->getSize(); int nX = imgSize.x / grid.x; int nY = imgSize.y / grid.y; for (int y = 0; y < nY; ++y) { for (int x = 0; x < nX; ++x) { auto img = std::make_unique<Image>(Image::Format::RGBA, grid); img->blitFrom(Vector2i(), *src.img, Rect4i(Vector2i(x, y) * grid, grid.x, grid.y)); Rect4i trimRect = img->getTrimRect(); if (trimRect.getWidth() > 0 && trimRect.getHeight() > 0) { result.emplace_back(); auto& dst = result.back(); String suffix = "_" + toString(x) + "_" + toString(y); dst.duration = src.duration; dst.frameNumber = src.frameNumber; dst.filenames.emplace_back(src.filenames.at(0) + suffix); dst.sequenceName = src.sequenceName + suffix; dst.img = std::move(img); dst.clip = Rect4i({}, grid); } } } } return result; } <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2016 Northeastern University // // 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 <stdio.h> #include <iostream> #include "Eigen/Dense" #include "gtest/gtest.h" #include "include/cpu_operations.h" #include "include/matrix.h" template<class T> class MatrixSubtractTest : public ::testing::Test { public: Nice::Matrix<T> m1; Nice::Matrix<T> m2; Nice::Matrix<T> result; Nice::Matrix<T> testMatrix; void MatrixSubtract() { result = Nice::CpuOperations<T>::Subtract(m1, m2); } }; typedef ::testing::Types<int, double, float> MyTypes; TYPED_TEST_CASE(MatrixSubtractTest, MyTypes); TYPED_TEST(MatrixSubtractTest, MatrixSubtractFunctionality) { this->m1.resize(2, 2); this->m2.resize(2, 2); this->testMatrix.resize(2, 2); this->m1 << 2, 3, 4, 5; this->m2 << 1, 2, 3, 2; this->MatrixSubtract(); this->testMatrix << 1, 1, 1, 3; ASSERT_TRUE(this->result.isApprox(this->testMatrix)); } TYPED_TEST(MatrixSubtractTest, DifferentSizeMatrix) { this->m1.resize(2, 2); this->m2.resize(3, 2); this->m1.setZero(); this->m2.setZero(); ASSERT_DEATH(this->MatrixSubtract(), ".*"); } TYPED_TEST(MatrixSubtractTest, EmptyMatrix) { ASSERT_DEATH(this->MatrixSubtract(), ".*"); } <commit_msg>Matrix scalar subtract test<commit_after>// The MIT License (MIT) // // Copyright (c) 2016 Northeastern University // // 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 <stdio.h> #include <iostream> #include "Eigen/Dense" #include "gtest/gtest.h" #include "include/cpu_operations.h" #include "include/matrix.h" template<class T> class MatrixSubtractTest : public ::testing::Test { public: Nice::T scalar; Nice::Matrix<T> m1; Nice::Matrix<T> m2; Nice::Matrix<T> result; Nice::Matrix<T> testMatrix; void MatrixSubtract() { result = Nice::CpuOperations<T>::Subtract(m1, m2); } void MatrixScalarSubtract() { result = Nice::CpuOperations<T>::Subtract(m1, scalar); } }; typedef ::testing::Types<int, double, float> MyTypes; TYPED_TEST_CASE(MatrixSubtractTest, MyTypes); TYPED_TEST(MatrixSubtractTest, MatrixSubtractFunctionality) { this->m1.resize(2, 2); this->m2.resize(2, 2); this->testMatrix.resize(2, 2); this->m1 << 2, 3, 4, 5; this->m2 << 1, 2, 3, 2; this->MatrixSubtract(); this->testMatrix << 1, 1, 1, 3; ASSERT_TRUE(this->result.isApprox(this->testMatrix)); } TYPED_TEST(MatrixScalarSubtractTest, MatrixScalarSubtractFunctionality) { this->m1.resize(2, 2); this->scalar == 2; this->testMatrix.resize(2, 2); this->m1 << 4, 5, 3, 6; this->MatrixScalarSubtract(); this->testMatrix << 2, 3, 1, 4; ASSERT_TRUE(this->result.isApprox(this->testMatrix)); } TYPED_TEST(MatrixSubtractTest, DifferentSizeMatrix) { this->m1.resize(2, 2); this->m2.resize(3, 2); this->m1.setZero(); this->m2.setZero(); ASSERT_DEATH(this->MatrixSubtract(), ".*"); } TYPED_TEST(MatrixSubtractTest, EmptyMatrix) { ASSERT_DEATH(this->MatrixSubtract(), ".*"); } TYPED_TEST(MatrixScalarSubtractTest, EmptyMatrix) { ASSERT_DEATH(this->MatrixScalarSubtract(), "."); } <|endoftext|>
<commit_before>// breaker.cc see license.txt for copyright and terms of use // code for breaker.h // Scott McPeak, 1997,1998 This file is public domain. #include "breaker.h" // this module #ifdef __BORLANDC__ # pragma warn -use #endif void ackackack(int*) {} void breaker() { static int i=0; int a=1; // all this junk is just to make sure // that this function has a complete ackackack(&a); // stack frame, so the debugger can unwind i++; // the stack } #ifdef __BORLANDC__ # pragma warn .use #endif <commit_msg>testing..<commit_after>// breaker.cc see license.txt for copyright and terms of use // code for breaker.h // Scott McPeak, 1997,1998 This file is public domain. #include "breaker.h" // this module #ifdef __BORLANDC__ # pragma warn -use #endif void ackackack(int*) {} void breaker() { static int i=0; int a=1; // all this junk is just to make sure // that this function has a complete ackackack(&a); // stack frame, so the debugger can unwind i++; // the stack } #ifdef __BORLANDC__ # pragma warn .use #endif // (tweak for CVS) <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 "mountain_user.H" #include "fclaw2d_forestclaw.h" #include "fclaw2d_clawpatch.h" #include "fc2d_clawpack46.h" static void * options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt) { user_options_t* user = (user_options_t*) package; /* [user] User options */ sc_options_add_int (opt, 0, "example", &user->example, 1, "[user] 1 - cut cell; 2 - terrain following [1]"); user->is_registered = 1; return NULL; } static fclaw_exit_type_t options_check_user (fclaw_app_t * app, void *package, void *registered) { user_options_t* user = (user_options_t*) package; if (user->example < 0 || user->example > 2) { fclaw_global_essentialf ("Option --user:example must be 1 or 2\n"); return FCLAW_EXIT_QUIET; } return FCLAW_NOEXIT; } static const fclaw_app_options_vtable_t options_vtable_user = { options_register_user, NULL, options_check_user, NULL }; static void register_user_options (fclaw_app_t * app, const char *configfile, user_options_t* user) { FCLAW_ASSERT (app != NULL); fclaw_app_options_register (app,"user", configfile, &options_vtable_user, user); } void run_program(fclaw_app_t* app) { sc_MPI_Comm mpicomm; p4est_connectivity_t *conn = NULL; fclaw2d_domain_t *domain; fclaw2d_map_context_t *cont = NULL, *brick = NULL; amr_options_t *gparms; user_options_t *user; int mi,mj,a,b; mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL); gparms = fclaw_forestclaw_get_options(app); user = (user_options_t*) fclaw_app_get_user(app); a = gparms->periodic_x; b = gparms->periodic_y; mi = gparms->mi; mj = gparms->mj; conn = p4est_connectivity_new_brick(mi,mj,a,b); brick = fclaw2d_map_new_brick(conn,mi,mj); switch (user->example) { case 0: case 1: /* A terrain following grid */ cont = fclaw2d_map_new_mountain (brick,gparms->scale,gparms->shift); break; case 2: /* A cut cell mesh */ cont = fclaw2d_map_new_identity (brick,gparms->scale,gparms->shift); break; default: SC_ABORT_NOT_REACHED (); } domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont); fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO); fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG); fclaw2d_domain_data_new(domain); fclaw2d_domain_set_app(domain,app); mountain_link_solvers(domain); fclaw2d_initialize(&domain); fclaw2d_run(&domain); fclaw2d_finalize(&domain); fclaw2d_map_destroy(cont); /* This destroys the brick as well */ } int main (int argc, char **argv) { fclaw_app_t *app; int first_arg; fclaw_exit_type_t vexit; /* Options */ sc_options_t *options; user_options_t suser_options, *user = &suser_options; int retval; /* Initialize application */ app = fclaw_app_new (&argc, &argv, user); /* Register packages */ fclaw_forestclaw_register(app,"fclaw_options.ini"); fc2d_clawpack46_register(app,"fclaw_options.ini"); register_user_options (app, "fclaw_options.ini", user); /* Read configuration file(s) */ options = fclaw_app_get_options (app); retval = fclaw_options_read_from_file(options); vexit = fclaw_app_options_parse (app, &first_arg,NULL); fclaw2d_clawpatch_link_app(app); if (!retval & !vexit) { run_program(app); } fclaw_forestclaw_destroy(app); fclaw_app_destroy (app); return 0; } <commit_msg>(mountain) Fix header h/H issue<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 "mountain_user.h" #include "fclaw2d_forestclaw.h" #include "fclaw2d_clawpatch.h" #include "fc2d_clawpack46.h" static void * options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt) { user_options_t* user = (user_options_t*) package; /* [user] User options */ sc_options_add_int (opt, 0, "example", &user->example, 1, "[user] 1 - cut cell; 2 - terrain following [1]"); user->is_registered = 1; return NULL; } static fclaw_exit_type_t options_check_user (fclaw_app_t * app, void *package, void *registered) { user_options_t* user = (user_options_t*) package; if (user->example < 0 || user->example > 2) { fclaw_global_essentialf ("Option --user:example must be 1 or 2\n"); return FCLAW_EXIT_QUIET; } return FCLAW_NOEXIT; } static const fclaw_app_options_vtable_t options_vtable_user = { options_register_user, NULL, options_check_user, NULL }; static void register_user_options (fclaw_app_t * app, const char *configfile, user_options_t* user) { FCLAW_ASSERT (app != NULL); fclaw_app_options_register (app,"user", configfile, &options_vtable_user, user); } void run_program(fclaw_app_t* app) { sc_MPI_Comm mpicomm; p4est_connectivity_t *conn = NULL; fclaw2d_domain_t *domain; fclaw2d_map_context_t *cont = NULL, *brick = NULL; amr_options_t *gparms; user_options_t *user; int mi,mj,a,b; mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL); gparms = fclaw_forestclaw_get_options(app); user = (user_options_t*) fclaw_app_get_user(app); a = gparms->periodic_x; b = gparms->periodic_y; mi = gparms->mi; mj = gparms->mj; conn = p4est_connectivity_new_brick(mi,mj,a,b); brick = fclaw2d_map_new_brick(conn,mi,mj); switch (user->example) { case 0: case 1: /* A terrain following grid */ cont = fclaw2d_map_new_mountain (brick,gparms->scale,gparms->shift); break; case 2: /* A cut cell mesh */ cont = fclaw2d_map_new_identity (brick,gparms->scale,gparms->shift); break; default: SC_ABORT_NOT_REACHED (); } domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont); fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO); fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG); fclaw2d_domain_data_new(domain); fclaw2d_domain_set_app(domain,app); mountain_link_solvers(domain); fclaw2d_initialize(&domain); fclaw2d_run(&domain); fclaw2d_finalize(&domain); fclaw2d_map_destroy(cont); /* This destroys the brick as well */ } int main (int argc, char **argv) { fclaw_app_t *app; int first_arg; fclaw_exit_type_t vexit; /* Options */ sc_options_t *options; user_options_t suser_options, *user = &suser_options; int retval; /* Initialize application */ app = fclaw_app_new (&argc, &argv, user); /* Register packages */ fclaw_forestclaw_register(app,"fclaw_options.ini"); fc2d_clawpack46_register(app,"fclaw_options.ini"); register_user_options (app, "fclaw_options.ini", user); /* Read configuration file(s) */ options = fclaw_app_get_options (app); retval = fclaw_options_read_from_file(options); vexit = fclaw_app_options_parse (app, &first_arg,NULL); fclaw2d_clawpatch_link_app(app); if (!retval & !vexit) { run_program(app); } fclaw_forestclaw_destroy(app); fclaw_app_destroy (app); return 0; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/sbe/p10_sbe_ext_defs.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file p10_sbe_ext_defs.H /// @brief This file will has structures and constants that can be treated as // the external interfaces of the SBE. #ifndef _P10_SBE_EXT_DEFS_H_ #define _P10_SBE_EXT_DEFS_H_ /// @brief A structure (bitfield) representing the SBE messaging register typedef union sbeMsgReg { struct { #ifdef _BIG_ENDIAN uint32_t sbeBooted : 1; ///< SBE control loop initialized uint32_t asyncFFDC : 1; // < async ffdc present on sbe uint32_t reserved1 : 2; ///< Reserved uint32_t prevState : 4; ///< Previous SBE state uint32_t currState : 4; ///< Current SBE state uint32_t majorStep : 8; ///< Last major istep executed by the SBE uint32_t minorStep : 6; ///< Last minor istep executed by the SBE uint32_t reserved2 : 6; ///< Reserved #else uint32_t reserved2 : 6; ///< Reserved uint32_t minorStep : 6; ///< Last minor istep executed by the SBE uint32_t majorStep : 8; ///< Last major istep executed by the SBE uint32_t currState : 4; ///< Current SBE state uint32_t prevState : 4; ///< Previous SBE state uint32_t reserved1 : 2; ///< Reserved uint32_t asyncFFDC : 1; // < async ffdc present on sbe uint32_t sbeBooted : 1; ///< SBE control loop initialized #endif }; uint32_t reg; ///< The complete SBE messaging register as a uint32 } sbeMsgReg_t; /** * @brief Enumeration of SBE states */ typedef enum sbeState { SBE_STATE_UNKNOWN = 0x0, // Unkown, initial state SBE_STATE_IPLING = 0x1, // IPL'ing - autonomous mode (transient) SBE_STATE_ISTEP = 0x2, // ISTEP - Running IPL by steps (transient) SBE_STATE_MPIPL = 0x3, // MPIPL SBE_STATE_RUNTIME = 0x4, // SBE Runtime SBE_STATE_DMT = 0x5, // Dead Man Timer State (transient) SBE_STATE_DUMP = 0x6, // Dumping SBE_STATE_FAILURE = 0x7, // Internal SBE failure SBE_STATE_QUIESCE = 0x8, // Final state - needs SBE reset to get out // Max States, Always keep it at the last of the enum and sequential SBE_MAX_STATE = 0x9, // Don't count this in the state, just to intialize the state variables SBE_INVALID_STATE = 0xF, } sbeState_t; #endif //_P10_SBE_EXT_DEFS_H_ <commit_msg>Update SBE States enum and 2809 reg bitfield<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/sbe/p10_sbe_ext_defs.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file p10_sbe_ext_defs.H /// @brief This file will has structures and constants that can be treated as // the external interfaces of the SBE. #ifndef _P10_SBE_EXT_DEFS_H_ #define _P10_SBE_EXT_DEFS_H_ /// @brief A structure (bitfield) representing the SBE messaging register typedef union sbeMsgReg { struct { #ifdef _BIG_ENDIAN uint32_t sbeBooted : 1; ///< SBE control loop initialized uint32_t asyncFFDC : 1; // < async ffdc present on sbe uint32_t reserved1 : 2; ///< Reserved uint32_t prevState : 4; ///< Previous SBE state uint32_t currState : 4; ///< Current SBE state uint32_t majorStep : 8; ///< Last major istep executed by the SBE uint32_t minorStep : 6; ///< Last minor istep executed by the SBE uint32_t reserved2 : 2; ///< Reserved uint32_t iv_progressCode : 4; #else uint32_t iv_progressCode : 4; uint32_t reserved2 : 2; ///< Reserved uint32_t minorStep : 6; ///< Last minor istep executed by the SBE uint32_t majorStep : 8; ///< Last major istep executed by the SBE uint32_t currState : 4; ///< Current SBE state uint32_t prevState : 4; ///< Previous SBE state uint32_t reserved1 : 2; ///< Reserved uint32_t asyncFFDC : 1; // < async ffdc present on sbe uint32_t sbeBooted : 1; ///< SBE control loop initialized #endif }; uint32_t reg; ///< The complete SBE messaging register as a uint32 } sbeMsgReg_t; /** * @brief Enumeration of SBE states */ typedef enum sbeState { SBE_STATE_UNKNOWN = 0x0, // Unkown, initial state SBE_STATE_IPLING = 0x1, // IPL'ing - autonomous mode (transient) SBE_STATE_ISTEP = 0x2, // ISTEP - Running IPL by steps (transient) SBE_STATE_MPIPL = 0x3, // MPIPL SBE_STATE_RUNTIME = 0x4, // SBE Runtime SBE_STATE_DMT = 0x5, // Dead Man Timer State (transient) SBE_STATE_DUMP = 0x6, // Dumping SBE_STATE_FAILURE = 0x7, // Internal SBE failure SBE_STATE_QUIESCE = 0x8, // This state quiesces any seeprom access SBE_STATE_HALT = 0x9, // SBE halted via chip-op driven from Hostboot.Needs SBE reset to get out // Max States, Always keep it at the last of the enum and sequential SBE_MAX_STATE = 0xA, // Don't count this in the state, just to intialize the state variables SBE_INVALID_STATE = 0xF, } sbeState_t; #endif //_P10_SBE_EXT_DEFS_H_ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_cxa_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_cxa_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_0x801B1F98D8717000 = 0x801B1F98D8717000; constexpr uint64_t literal_0x0000000000000 = 0x0000000000000; constexpr uint64_t literal_0x2080000020080 = 0x2080000020080; constexpr uint64_t literal_0b0000 = 0b0000; constexpr uint64_t literal_0b111 = 0b111; constexpr uint64_t literal_0b0010 = 0b0010; constexpr uint64_t literal_0b0001 = 0b0001; fapi2::ReturnCode p9_cxa_scom(const fapi2::Target<fapi2::TARGET_TYPE_CAPP>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec)); fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x2010803ull, l_scom_buffer )); l_scom_buffer.insert<0, 53, 0, uint64_t>(literal_0x801B1F98D8717000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x2010803ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010806ull, l_scom_buffer )); if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<0, 52, 12, uint64_t>(literal_0x0000000000000 ); } else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<0, 53, 11, uint64_t>(literal_0x0000000000000 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010806ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010807ull, l_scom_buffer )); if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<0, 52, 12, uint64_t>(literal_0x2080000020080 ); } else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<0, 53, 11, uint64_t>(literal_0x2080000020080 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010807ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010818ull, l_scom_buffer )); constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_ADR_BAR_MODE_OFF = 0x0; l_scom_buffer.insert<1, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_ADR_BAR_MODE_OFF ); if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP)) { constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_ON = 0x1; l_scom_buffer.insert<6, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_ON ); } else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE)) { constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_OFF = 0x0; l_scom_buffer.insert<6, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_OFF ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010818ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010819ull, l_scom_buffer )); l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0b0000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x2010819ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x201081bull, l_scom_buffer )); if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<45, 3, 61, uint64_t>(literal_0b111 ); } if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<45, 3, 61, uint64_t>(literal_0b111 ); } if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<48, 4, 60, uint64_t>(literal_0b0010 ); } if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<48, 4, 60, uint64_t>(literal_0b0010 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x201081bull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x201081cull, l_scom_buffer )); l_scom_buffer.insert<18, 4, 60, uint64_t>(literal_0b0001 ); FAPI_TRY(fapi2::putScom(TGT0, 0x201081cull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <commit_msg>HW414700 checkstop on UEs and disable core ECC counter<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_cxa_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_cxa_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_0 = 0; constexpr uint64_t literal_0x801B1F98C8717000 = 0x801B1F98C8717000; constexpr uint64_t literal_1 = 1; constexpr uint64_t literal_0x801B1F98D8717000 = 0x801B1F98D8717000; constexpr uint64_t literal_0x0000000000000 = 0x0000000000000; constexpr uint64_t literal_0x2080000020080 = 0x2080000020080; constexpr uint64_t literal_0b0000 = 0b0000; constexpr uint64_t literal_0b111 = 0b111; constexpr uint64_t literal_0b0010 = 0b0010; constexpr uint64_t literal_0b0001 = 0b0001; fapi2::ReturnCode p9_cxa_scom(const fapi2::Target<fapi2::TARGET_TYPE_CAPP>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec)); fapi2::ATTR_CHIP_EC_FEATURE_HW414700_Type l_TGT2_ATTR_CHIP_EC_FEATURE_HW414700; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW414700, TGT2, l_TGT2_ATTR_CHIP_EC_FEATURE_HW414700)); fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x2010803ull, l_scom_buffer )); if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW414700 != literal_0)) { l_scom_buffer.insert<0, 53, 0, uint64_t>(literal_0x801B1F98C8717000 ); } else if (literal_1) { l_scom_buffer.insert<0, 53, 0, uint64_t>(literal_0x801B1F98D8717000 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010803ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010806ull, l_scom_buffer )); if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<0, 52, 12, uint64_t>(literal_0x0000000000000 ); } else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<0, 53, 11, uint64_t>(literal_0x0000000000000 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010806ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010807ull, l_scom_buffer )); if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<0, 52, 12, uint64_t>(literal_0x2080000020080 ); } else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<0, 53, 11, uint64_t>(literal_0x2080000020080 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010807ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010818ull, l_scom_buffer )); constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_ADR_BAR_MODE_OFF = 0x0; l_scom_buffer.insert<1, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_ADR_BAR_MODE_OFF ); if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP)) { constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_ON = 0x1; l_scom_buffer.insert<6, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_ON ); } else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE)) { constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_OFF = 0x0; l_scom_buffer.insert<6, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_OFF ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010818ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010819ull, l_scom_buffer )); l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0b0000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x2010819ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x201081bull, l_scom_buffer )); if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<45, 3, 61, uint64_t>(literal_0b111 ); } if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<45, 3, 61, uint64_t>(literal_0b111 ); } if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<48, 4, 60, uint64_t>(literal_0b0010 ); } if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<48, 4, 60, uint64_t>(literal_0b0010 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x201081bull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x201081cull, l_scom_buffer )); l_scom_buffer.insert<18, 4, 60, uint64_t>(literal_0b0001 ); FAPI_TRY(fapi2::putScom(TGT0, 0x201081cull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>#ifndef INTERSECTION_BASED_CALLER #define INTERSECTION_BASED_CALLER #include <opengm/opengm.hxx> #include <opengm/inference/intersection_based_inf.hxx> #include "inference_caller_base.hxx" #include "../argument/argument.hxx" namespace opengm { namespace interface { template <class IO, class GM, class ACC> class IntersectionBasedCaller : public InferenceCallerBase<IO, GM, ACC, IntersectionBasedCaller<IO, GM, ACC> > { protected: typedef InferenceCallerBase<IO, GM, ACC, IntersectionBasedCaller<IO, GM, ACC> > BaseClass; typedef opengm::proposal_gen::WeightRandomization<typename GM::ValueType> WRand; typedef typename WRand::Parameter WRandParam; typedef PermutableLabelFusionMove<GM, ACC> FusionMoverType; typedef typename FusionMoverType::Parameter FusionParameter; typedef typename BaseClass::OutputBase OutputBase; using BaseClass::addArgument; using BaseClass::io_; using BaseClass::infer; virtual void runImpl(GM& model, OutputBase& output, const bool verbose); template<class INF> void setParam(typename INF::Parameter & param); size_t numIt_; size_t numStopIt_; size_t parallelProposals_; std::string selectedNoise_; WRandParam wRand_; int numberOfThreads_; std::string selectedGenType_; // fusion param std::string selectedFusionType_; FusionParameter fusionParam_; bool planar_; // RHC SPECIFIC param float stopWeight_; float nodeStopNum_; // for ws float seedFraction_; bool ingoreNegativeWeights_; bool seedFromNegativeEdges_; public: const static std::string name_; IntersectionBasedCaller(IO& ioIn); ~IntersectionBasedCaller(); }; template <class IO, class GM, class ACC> inline IntersectionBasedCaller<IO, GM, ACC>::IntersectionBasedCaller(IO& ioIn) : BaseClass(name_, "detailed description of SelfFusion caller...", ioIn) { std::vector<std::string> fusion; fusion.push_back("MC"); fusion.push_back("CGC"); fusion.push_back("HC"); std::vector<std::string> gen; gen.push_back("RHC"); gen.push_back("R2C"); gen.push_back("RWS"); std::vector<std::string> noise; noise.push_back("NA"); noise.push_back("UA"); noise.push_back("NM"); noise.push_back("NONE"); addArgument(StringArgument<>(selectedGenType_, "g", "gen", "Selected proposal generator", gen.front(), gen)); addArgument(StringArgument<>(selectedFusionType_, "f", "fusion", "Select fusion method", fusion.front(), fusion)); addArgument(BoolArgument(fusionParam_.planar_,"pl","planar", "is problem planar")); //addArgument(IntArgument<>(numberOfThreads_, "", "threads", "number of threads", static_cast<int>(1))); addArgument(Size_TArgument<>(numIt_, "", "numIt", "number of iterations", static_cast<size_t>(100))); addArgument(Size_TArgument<>(numStopIt_, "", "numStopIt", "number of iterations with no improvment that cause stopping (0=auto)", static_cast<size_t>(0))); addArgument(Size_TArgument<>(parallelProposals_, "pp", "parallelProposals", "number of parallel proposals (1)", static_cast<size_t>(1))); // parameter for weight randomizer_ addArgument(StringArgument<>(selectedNoise_, "nt", "noiseType", "selected noise type", noise.front(), noise)); addArgument(FloatArgument<>(wRand_.noiseParam_, "temp", "temperature", "temperature for non uniform random proposal generator", 1.0f)); addArgument(Size_TArgument<>(wRand_.seed_, "", "seed", "seed", size_t(42))); addArgument(BoolArgument(wRand_.ignoreSeed_,"is","ignoreSeed", "ignore seed and use auto generated seed (based on time )")); // parameter for h addArgument(FloatArgument<>(stopWeight_, "stopW", "stopWeight", "stop hc merging when this weight is reached", 0.0f)); addArgument(FloatArgument<>(nodeStopNum_, "stopNN", "stopNodeNum", "stop hc merging when this (maybe relativ) number of nodes is reached", 0.1f)); // param for ws addArgument(FloatArgument<>(seedFraction_, "", "nSeeds", "(maybe relative) number of seeds ", 20.0f)); addArgument(BoolArgument(seedFromNegativeEdges_, "sfn", "seedFromNegative", "use only nodes of negative edges as random seed")); } template <class IO, class GM, class ACC> IntersectionBasedCaller<IO, GM, ACC>::~IntersectionBasedCaller() {;} template <class IO, class GM, class ACC> template <class INF> inline void IntersectionBasedCaller<IO, GM, ACC>::setParam( typename INF::Parameter & param ){ param.numIt_ = numIt_; param.numStopIt_ = numStopIt_; param.fusionParam_ = fusionParam_; param.proposalParam_.randomizer_ = wRand_; } template <class IO, class GM, class ACC> inline void IntersectionBasedCaller<IO, GM, ACC>::runImpl(GM& model, OutputBase& output, const bool verbose) { std::cout << "running Intersection Based caller" << std::endl; typedef opengm::proposal_gen::RandomizedHierarchicalClustering<GM, opengm::Minimizer> RHC; typedef opengm::proposal_gen::RandomizedWatershed<GM, opengm::Minimizer> RWS; typedef opengm::proposal_gen::QpboBased<GM, opengm::Minimizer> R2C; // noise if(selectedNoise_ == "NA"){ wRand_.noiseType_ = WRandParam::NormalAdd; } else if(selectedNoise_ == "UA"){ wRand_.noiseType_ = WRandParam::UniformAdd; } else if(selectedNoise_ == "NM"){ wRand_.noiseType_ = WRandParam::NormalMult; } else if(selectedNoise_ == "NONE"){ wRand_.noiseType_ = WRandParam::None; } // fusion solver if(selectedFusionType_ == "MC"){ fusionParam_.fusionSolver_ = FusionMoverType::MulticutSolver; } else if(selectedFusionType_ == "CGC"){ fusionParam_.fusionSolver_ = FusionMoverType::CgcSolver; } else if(selectedFusionType_ == "HC"){ fusionParam_.fusionSolver_ = FusionMoverType::HierachicalClusteringSolver; } // proposal if(selectedGenType_=="RHC"){ typedef RHC Gen; typedef opengm::IntersectionBasedInf<GM, Gen> INF; typename INF::Parameter para; setParam<INF>(para); para.proposalParam_.stopWeight_ = stopWeight_; para.proposalParam_.nodeStopNum_ = nodeStopNum_; this-> template infer<INF, typename INF::TimingVisitorType, typename INF::Parameter>(model, output, verbose, para); } else if(selectedGenType_=="RWS"){ typedef RWS Gen; typedef opengm::IntersectionBasedInf<GM, Gen> INF; typename INF::Parameter para; setParam<INF>(para); para.proposalParam_.seedFraction_ = seedFraction_; para.proposalParam_.seedFromNegativeEdges_ = seedFromNegativeEdges_; this-> template infer<INF, typename INF::TimingVisitorType, typename INF::Parameter>(model, output, verbose, para); } else if(selectedGenType_=="R2C"){ typedef R2C Gen; typedef opengm::IntersectionBasedInf<GM, Gen> INF; typename INF::Parameter para; setParam<INF>(para); //para.proposalParam_.sigma_ = sigma_; this-> template infer<INF, typename INF::TimingVisitorType, typename INF::Parameter>(model, output, verbose, para); } } template <class IO, class GM, class ACC> const std::string IntersectionBasedCaller<IO, GM, ACC>::name_ = "IntersectionBased"; } // namespace interface } // namespace opengm #endif /* INTERSECTION_BASED_CALLER */ <commit_msg>improved caller<commit_after>#ifndef INTERSECTION_BASED_CALLER #define INTERSECTION_BASED_CALLER #include <opengm/opengm.hxx> #include <opengm/inference/intersection_based_inf.hxx> #include "inference_caller_base.hxx" #include "../argument/argument.hxx" namespace opengm { namespace interface { template <class IO, class GM, class ACC> class IntersectionBasedCaller : public InferenceCallerBase<IO, GM, ACC, IntersectionBasedCaller<IO, GM, ACC> > { protected: typedef InferenceCallerBase<IO, GM, ACC, IntersectionBasedCaller<IO, GM, ACC> > BaseClass; typedef opengm::proposal_gen::WeightRandomization<typename GM::ValueType> WRand; typedef typename WRand::Parameter WRandParam; typedef PermutableLabelFusionMove<GM, ACC> FusionMoverType; typedef typename FusionMoverType::Parameter FusionParameter; typedef typename BaseClass::OutputBase OutputBase; using BaseClass::addArgument; using BaseClass::io_; using BaseClass::infer; virtual void runImpl(GM& model, OutputBase& output, const bool verbose); template<class INF> void setParam(typename INF::Parameter & param); size_t numIt_; size_t numStopIt_; size_t parallelProposals_; std::string selectedNoise_; WRandParam wRand_; int numberOfThreads_; std::string selectedGenType_; // fusion param std::string selectedFusionType_; FusionParameter fusionParam_; bool planar_; // RHC SPECIFIC param float stopWeight_; float nodeStopNum_; // for ws float seedFraction_; bool ingoreNegativeWeights_; bool seedFromNegativeEdges_; public: const static std::string name_; IntersectionBasedCaller(IO& ioIn); ~IntersectionBasedCaller(); }; template <class IO, class GM, class ACC> inline IntersectionBasedCaller<IO, GM, ACC>::IntersectionBasedCaller(IO& ioIn) : BaseClass(name_, "detailed description of SelfFusion caller...", ioIn) { std::vector<std::string> fusion; fusion.push_back("MC"); fusion.push_back("CGC"); fusion.push_back("HC"); std::vector<std::string> gen; gen.push_back("RHC"); gen.push_back("R2C"); gen.push_back("RWS"); std::vector<std::string> noise; noise.push_back("NA"); noise.push_back("UA"); noise.push_back("NM"); noise.push_back("NONE"); addArgument(StringArgument<>(selectedGenType_, "g", "gen", "Selected proposal generator", gen.front(), gen)); addArgument(StringArgument<>(selectedFusionType_, "f", "fusion", "Select fusion method", fusion.front(), fusion)); addArgument(BoolArgument(fusionParam_.planar_,"pl","planar", "is problem planar")); //addArgument(IntArgument<>(numberOfThreads_, "", "threads", "number of threads", static_cast<int>(1))); addArgument(Size_TArgument<>(numIt_, "", "numIt", "number of iterations", static_cast<size_t>(100))); addArgument(Size_TArgument<>(numStopIt_, "", "numStopIt", "number of iterations with no improvment that cause stopping (0=auto)", static_cast<size_t>(20))); addArgument(Size_TArgument<>(parallelProposals_, "pp", "parallelProposals", "number of parallel proposals (1)", static_cast<size_t>(1))); // parameter for weight randomizer_ addArgument(StringArgument<>(selectedNoise_, "nt", "noiseType", "selected noise type", noise.front(), noise)); addArgument(FloatArgument<>(wRand_.noiseParam_, "temp", "temperature", "temperature for non uniform random proposal generator", 1.0f)); addArgument(Size_TArgument<>(wRand_.seed_, "", "seed", "seed", size_t(42))); addArgument(BoolArgument(wRand_.ignoreSeed_,"is","ignoreSeed", "ignore seed and use auto generated seed (based on time )")); // parameter for h addArgument(FloatArgument<>(stopWeight_, "stopW", "stopWeight", "stop hc merging when this weight is reached", 0.0f)); addArgument(FloatArgument<>(nodeStopNum_, "stopNN", "stopNodeNum", "stop hc merging when this (maybe relativ) number of nodes is reached", 0.1f)); // param for ws addArgument(FloatArgument<>(seedFraction_, "", "nSeeds", "(maybe relative) number of seeds ", 20.0f)); addArgument(BoolArgument(seedFromNegativeEdges_, "sfn", "seedFromNegative", "use only nodes of negative edges as random seed")); } template <class IO, class GM, class ACC> IntersectionBasedCaller<IO, GM, ACC>::~IntersectionBasedCaller() {;} template <class IO, class GM, class ACC> template <class INF> inline void IntersectionBasedCaller<IO, GM, ACC>::setParam( typename INF::Parameter & param ){ param.numIt_ = numIt_; param.numStopIt_ = numStopIt_; param.fusionParam_ = fusionParam_; param.proposalParam_.randomizer_ = wRand_; } template <class IO, class GM, class ACC> inline void IntersectionBasedCaller<IO, GM, ACC>::runImpl(GM& model, OutputBase& output, const bool verbose) { std::cout << "running Intersection Based caller" << std::endl; typedef opengm::proposal_gen::RandomizedHierarchicalClustering<GM, opengm::Minimizer> RHC; typedef opengm::proposal_gen::RandomizedWatershed<GM, opengm::Minimizer> RWS; typedef opengm::proposal_gen::QpboBased<GM, opengm::Minimizer> R2C; // noise if(selectedNoise_ == "NA"){ wRand_.noiseType_ = WRandParam::NormalAdd; } else if(selectedNoise_ == "UA"){ wRand_.noiseType_ = WRandParam::UniformAdd; } else if(selectedNoise_ == "NM"){ wRand_.noiseType_ = WRandParam::NormalMult; } else if(selectedNoise_ == "NONE"){ wRand_.noiseType_ = WRandParam::None; } // fusion solver if(selectedFusionType_ == "MC"){ fusionParam_.fusionSolver_ = FusionMoverType::MulticutSolver; } else if(selectedFusionType_ == "CGC"){ fusionParam_.fusionSolver_ = FusionMoverType::CgcSolver; } else if(selectedFusionType_ == "HC"){ fusionParam_.fusionSolver_ = FusionMoverType::HierachicalClusteringSolver; } // proposal if(selectedGenType_=="RHC"){ typedef RHC Gen; typedef opengm::IntersectionBasedInf<GM, Gen> INF; typename INF::Parameter para; setParam<INF>(para); para.proposalParam_.stopWeight_ = stopWeight_; para.proposalParam_.nodeStopNum_ = nodeStopNum_; this-> template infer<INF, typename INF::TimingVisitorType, typename INF::Parameter>(model, output, verbose, para); } else if(selectedGenType_=="RWS"){ typedef RWS Gen; typedef opengm::IntersectionBasedInf<GM, Gen> INF; typename INF::Parameter para; setParam<INF>(para); para.proposalParam_.seedFraction_ = seedFraction_; para.proposalParam_.seedFromNegativeEdges_ = seedFromNegativeEdges_; this-> template infer<INF, typename INF::TimingVisitorType, typename INF::Parameter>(model, output, verbose, para); } else if(selectedGenType_=="R2C"){ typedef R2C Gen; typedef opengm::IntersectionBasedInf<GM, Gen> INF; typename INF::Parameter para; setParam<INF>(para); //para.proposalParam_.sigma_ = sigma_; this-> template infer<INF, typename INF::TimingVisitorType, typename INF::Parameter>(model, output, verbose, para); } } template <class IO, class GM, class ACC> const std::string IntersectionBasedCaller<IO, GM, ACC>::name_ = "IntersectionBased"; } // namespace interface } // namespace opengm #endif /* INTERSECTION_BASED_CALLER */ <|endoftext|>
<commit_before>#include <stdio.h> #include <queue> #include <vector> #include <utility> #include <iostream> #include <string> #include <stack> #include <queue> using namespace std; queue<string> lv1; queue<string> lv2; queue<string> lv3; queue<string> lv4; string temp; int templv; int temptime=0; int usernum; int users=0; int read(int now){ if(now < temptime || users>usernum) return 0; do{ if(temp.empty()){ }else{ switch(templv){ case 1: lv1.push(temp);break; case 2: lv2.push(temp);break; case 3: lv3.push(temp);break; case 4: lv4.push(temp);break; } } users++; if(users<=usernum){ temp.resize(21); //需要预先分配空间 scanf("%d%d%s",&temptime,&templv,&temp[0]); } else return 0; }while(temptime<=now); } int pop(){ if(lv4.size()>0){ printf("%s\n",lv4.front().c_str()); lv4.pop(); return 4; } if(lv3.size()>0){ printf("%s\n",lv3.front().c_str()); lv3.pop(); return 3; } if(lv2.size()>0){ printf("%s\n",lv2.front().c_str()); lv2.pop(); return 2; } if(lv1.size()>0){ printf("%s\n",lv1.front().c_str()); lv1.pop(); return 1; } return 0; } int main(int argc, char const *argv[]) { int time; scanf("%d%d",&usernum,&time); for (int i = 0; i < time && i< usernum *5; ++i) { read(i); //cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl; if(i%5==0) pop(); } //while(pop()){} return 0; }<commit_msg>update uoj2254<commit_after>#include <stdio.h> #include <queue> #include <vector> #include <utility> #include <iostream> #include <string> #include <stack> #include <queue> using namespace std; queue<string> lv1; queue<string> lv2; queue<string> lv3; queue<string> lv4; string temp; int templv; int temptime=0; int usernum; int users=0; int read(int now){ if(now < temptime || users>usernum) return 0; do{ if(temp.empty()){ }else{ switch(templv){ case 1: lv1.push(temp);break; case 2: lv2.push(temp);break; case 3: lv3.push(temp);break; case 4: lv4.push(temp);break; } } users++; if(users<=usernum){ temp.resize(21); //需要预先分配空间 scanf("%d%d%s",&temptime,&templv,&temp[0]); } else return 0; }while(temptime<=now); } int pop(){ printf("pop"); if(lv4.size()>0){ printf("%s\n",lv4.front().c_str()); lv4.pop(); return 4; } if(lv3.size()>0){ printf("%s\n",lv3.front().c_str()); lv3.pop(); return 3; } if(lv2.size()>0){ printf("%s\n",lv2.front().c_str()); lv2.pop(); return 2; } if(lv1.size()>0){ printf("%s\n",lv1.front().c_str()); lv1.pop(); return 1; } return 0; } int main(int argc, char const *argv[]) { int time; scanf("%d%d",&usernum,&time); for (int i = 0; i < time && i< usernum *5; ++i) { read(i); //cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl; if(i%5==0) pop(); } //while(pop()){} return 0; }<|endoftext|>
<commit_before>/* kopeteavatarmanager.cpp - Global avatar manager Copyright (c) 2007 by Michaël Larouche <[email protected]> Kopete (c) 2002-2007 by the Kopete developers <[email protected]> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopeteavatarmanager.h" // Qt includes #include <QtCore/QLatin1String> #include <QtCore/QBuffer> #include <QtCore/QCoreApplication> #include <QtCore/QFile> #include <QtCore/QPointer> #include <QtCore/QStringList> #include <QtCore/QDir> // KDE includes #include <kdebug.h> #include <kstandarddirs.h> #include <kconfig.h> #include <kcodecs.h> #include <kurl.h> #include <kio/job.h> #include <klocale.h> // Kopete includes #include <kopetecontact.h> #include <kopeteprotocol.h> namespace Kopete { //BEGIN AvatarManager AvatarManager *AvatarManager::s_self = 0; AvatarManager *AvatarManager::self() { if( !s_self ) { s_self = new AvatarManager; } return s_self; } class AvatarManager::Private { public: KUrl baseDir; /** * Create directory if needed * @param directory URL of the directory to create */ void createDirectory(const KUrl &directory); /** * Scale the given image to 96x96. * @param source Original image */ QImage scaleImage(const QImage &source); }; static const QString UserDir("User"); static const QString ContactDir("Contacts"); static const QString AvatarConfig("avatarconfig.rc"); AvatarManager::AvatarManager(QObject *parent) : QObject(parent), d(new Private) { // Locate avatar data dir on disk d->baseDir = KUrl( KStandardDirs::locateLocal("appdata", QLatin1String("avatars") ) ); // Create directory on disk, if necessary d->createDirectory( d->baseDir ); } AvatarManager::~AvatarManager() { delete d; } void AvatarManager::add(Kopete::AvatarManager::AvatarEntry newEntry) { Q_ASSERT(!newEntry.name.isEmpty()); KUrl avatarUrl(d->baseDir); // First find where to save the file switch(newEntry.category) { case AvatarManager::User: avatarUrl.addPath( UserDir ); d->createDirectory( avatarUrl ); break; case AvatarManager::Contact: avatarUrl.addPath( ContactDir ); d->createDirectory( avatarUrl ); // Use the plugin name for protocol sub directory if( newEntry.contact && newEntry.contact->protocol() ) { QString protocolName = newEntry.contact->protocol()->pluginId(); avatarUrl.addPath( protocolName ); d->createDirectory( avatarUrl ); } break; default: break; } kDebug(14010) << k_funcinfo << "Base directory: " << avatarUrl.path() << endl; // Second, open the avatar configuration in current directory. KUrl configUrl = avatarUrl; configUrl.addPath( AvatarConfig ); QImage avatar; if( !newEntry.path.isEmpty() && newEntry.image.isNull() ) { avatar = QImage(newEntry.path); } else { avatar = newEntry.image; } // Scale avatar avatar = d->scaleImage(avatar); QString avatarFilename; // Find MD5 hash for filename // MD5 always contain ASCII caracteres so it is more save for a filename. // Name can use UTF-8 caracters. QByteArray tempArray; QBuffer tempBuffer(&tempArray); tempBuffer.open( QIODevice::WriteOnly ); avatar.save(&tempBuffer, "PNG"); KMD5 context(tempArray); avatarFilename = context.hexDigest() + QLatin1String(".png"); // Save image on disk kDebug(14010) << k_funcinfo << "Saving " << avatarFilename << " on disk." << endl; avatarUrl.addPath( avatarFilename ); if( !avatar.save( avatarUrl.path(), "PNG") ) { kDebug(14010) << k_funcinfo << "Saving of " << avatarUrl.path() << " failed !" << endl; return; } else { // Save metadata of image KSimpleConfig *avatarConfig = new KConfig( configUrl.path(), KConfig::OnlyLocal); avatarConfig->setGroup( newEntry.name ); avatarConfig->writeEntry( "Filename", avatarFilename ); avatarConfig->writeEntry( "Category", int(newEntry.category) ); avatarConfig->sync(); delete avatarConfig; // Add final path to the new entry for avatarAdded signal newEntry.path = avatarUrl.path(); emit avatarAdded(newEntry); } } void AvatarManager::remove(Kopete::AvatarManager::AvatarEntry entryToRemove) { Q_UNUSED(entryToRemove); emit avatarRemoved(entryToRemove); } void AvatarManager::Private::createDirectory(const KUrl &directory) { if( !QFile::exists(directory.path()) ) { kDebug(14010) << k_funcinfo << "Creating directory: " << directory.path() << endl; KIO::Job *job = KIO::mkdir(directory); job->exec(); if( job->error() ) { kDebug(14010) << "Directory creating failed: " << job->errorText() << endl; } } } QImage AvatarManager::Private::scaleImage(const QImage &source) { QImage result; if( source.width() > 96 || source.height() > 96 ) { // Scale and crop the picture. result = source.scaled( 96, 96, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation ); // crop image if not square if( result.width() < result.height() ) result = result.copy( (result.width()-result.height())/2, 0, 96, 96 ); else if( result.width() > result.height() ) result = result.copy( 0, (result.height()-result.width())/2, 96, 96 ); } else if( source.width() < 32 || source.height() < 32 ) { // Scale and crop the picture. result = source.scaled( 96, 96, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation ); // crop image if not square if( result.width() < result.height() ) result = result.copy( (result.width()-result.height())/2, 0, 32, 32 ); else if( result.width() > result.height() ) result = result.copy( 0, (result.height()-result.width())/2, 32, 32 ); } else if( source.width() != source.height() ) { if(source.width() < source.height()) result = source.copy((source.width()-source.height())/2, 0, source.height(), source.height()); else if (source.width() > source.height()) result = source.copy(0, (source.height()-source.width())/2, source.height(), source.height()); } return result; } //END AvatarManager //BEGIN AvatarQueryJob class AvatarQueryJob::Private { public: Private(AvatarQueryJob *parent) : queryJob(parent), category(AvatarManager::All) {} QPointer<AvatarQueryJob> queryJob; AvatarManager::AvatarCategory category; QList<AvatarManager::AvatarEntry> avatarList; KUrl baseDir; void listAvatarDirectory(const QString &path); }; AvatarQueryJob::AvatarQueryJob(QObject *parent) : KJob(parent), d(new Private(this)) { } AvatarQueryJob::~AvatarQueryJob() { delete d; } void AvatarQueryJob::setQueryFilter(Kopete::AvatarManager::AvatarCategory category) { d->category = category; } void AvatarQueryJob::start() { d->baseDir = KUrl( KStandardDirs::locateLocal("appdata", QLatin1String("avatars") ) ); if( d->category & Kopete::AvatarManager::User ) { d->listAvatarDirectory( UserDir ); } if( d->category & Kopete::AvatarManager::Contact ) { KUrl contactUrl(d->baseDir); contactUrl.addPath( ContactDir ); QDir contactDir(contactUrl.path()); QStringList subdirsList = contactDir.entryList( QDir::AllDirs | QDir::NoDotAndDotDot ); QString subdir; foreach(subdir, subdirsList) { d->listAvatarDirectory( ContactDir + QDir::separator() + subdir ); } } // Finish the job emitResult(); } QList<Kopete::AvatarManager::AvatarEntry> AvatarQueryJob::avatarList() const { return d->avatarList; } void AvatarQueryJob::Private::listAvatarDirectory(const QString &relativeDirectory) { KUrl avatarDirectory = baseDir; avatarDirectory.addPath(relativeDirectory); kDebug(14010) << k_funcinfo << "Listing avatars in " << avatarDirectory.path() << endl; // Look for Avatar configuration KUrl avatarConfigUrl = avatarDirectory; avatarConfigUrl.addPath( AvatarConfig ); if( QFile::exists(avatarConfigUrl.path()) ) { KSimpleConfig *avatarConfig = new KConfig( avatarConfigUrl.path(), KConfig::OnlyLocal); // Each avatar entry in configuration is a group QStringList groupEntryList = avatarConfig->groupList(); QString groupEntry; foreach(groupEntry, groupEntryList) { avatarConfig->setGroup(groupEntry); Kopete::AvatarManager::AvatarEntry listedEntry; listedEntry.name = groupEntry; listedEntry.category = static_cast<Kopete::AvatarManager::AvatarCategory>( avatarConfig->readEntry("Category", 0) ); QString filename = avatarConfig->readEntry( "Filename", QString() ); KUrl avatarPath(avatarDirectory); avatarPath.addPath( filename ); listedEntry.path = avatarPath.path(); avatarList << listedEntry; } } else { queryJob->setError( UserDefinedError ); queryJob->setErrorText( i18n("Avatar configuration hasn't been found on disk for category %1.", relativeDirectory) ); } } //END AvatarQueryJob } #include "kopeteavatarmanager.moc" <commit_msg>KSimpleConfig -> KConfig<commit_after>/* kopeteavatarmanager.cpp - Global avatar manager Copyright (c) 2007 by Michaël Larouche <[email protected]> Kopete (c) 2002-2007 by the Kopete developers <[email protected]> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopeteavatarmanager.h" // Qt includes #include <QtCore/QLatin1String> #include <QtCore/QBuffer> #include <QtCore/QCoreApplication> #include <QtCore/QFile> #include <QtCore/QPointer> #include <QtCore/QStringList> #include <QtCore/QDir> // KDE includes #include <kdebug.h> #include <kstandarddirs.h> #include <kconfig.h> #include <kcodecs.h> #include <kurl.h> #include <kio/job.h> #include <klocale.h> // Kopete includes #include <kopetecontact.h> #include <kopeteprotocol.h> namespace Kopete { //BEGIN AvatarManager AvatarManager *AvatarManager::s_self = 0; AvatarManager *AvatarManager::self() { if( !s_self ) { s_self = new AvatarManager; } return s_self; } class AvatarManager::Private { public: KUrl baseDir; /** * Create directory if needed * @param directory URL of the directory to create */ void createDirectory(const KUrl &directory); /** * Scale the given image to 96x96. * @param source Original image */ QImage scaleImage(const QImage &source); }; static const QString UserDir("User"); static const QString ContactDir("Contacts"); static const QString AvatarConfig("avatarconfig.rc"); AvatarManager::AvatarManager(QObject *parent) : QObject(parent), d(new Private) { // Locate avatar data dir on disk d->baseDir = KUrl( KStandardDirs::locateLocal("appdata", QLatin1String("avatars") ) ); // Create directory on disk, if necessary d->createDirectory( d->baseDir ); } AvatarManager::~AvatarManager() { delete d; } void AvatarManager::add(Kopete::AvatarManager::AvatarEntry newEntry) { Q_ASSERT(!newEntry.name.isEmpty()); KUrl avatarUrl(d->baseDir); // First find where to save the file switch(newEntry.category) { case AvatarManager::User: avatarUrl.addPath( UserDir ); d->createDirectory( avatarUrl ); break; case AvatarManager::Contact: avatarUrl.addPath( ContactDir ); d->createDirectory( avatarUrl ); // Use the plugin name for protocol sub directory if( newEntry.contact && newEntry.contact->protocol() ) { QString protocolName = newEntry.contact->protocol()->pluginId(); avatarUrl.addPath( protocolName ); d->createDirectory( avatarUrl ); } break; default: break; } kDebug(14010) << k_funcinfo << "Base directory: " << avatarUrl.path() << endl; // Second, open the avatar configuration in current directory. KUrl configUrl = avatarUrl; configUrl.addPath( AvatarConfig ); QImage avatar; if( !newEntry.path.isEmpty() && newEntry.image.isNull() ) { avatar = QImage(newEntry.path); } else { avatar = newEntry.image; } // Scale avatar avatar = d->scaleImage(avatar); QString avatarFilename; // Find MD5 hash for filename // MD5 always contain ASCII caracteres so it is more save for a filename. // Name can use UTF-8 caracters. QByteArray tempArray; QBuffer tempBuffer(&tempArray); tempBuffer.open( QIODevice::WriteOnly ); avatar.save(&tempBuffer, "PNG"); KMD5 context(tempArray); avatarFilename = context.hexDigest() + QLatin1String(".png"); // Save image on disk kDebug(14010) << k_funcinfo << "Saving " << avatarFilename << " on disk." << endl; avatarUrl.addPath( avatarFilename ); if( !avatar.save( avatarUrl.path(), "PNG") ) { kDebug(14010) << k_funcinfo << "Saving of " << avatarUrl.path() << " failed !" << endl; return; } else { // Save metadata of image KConfig *avatarConfig = new KConfig( configUrl.path(), KConfig::OnlyLocal); avatarConfig->setGroup( newEntry.name ); avatarConfig->writeEntry( "Filename", avatarFilename ); avatarConfig->writeEntry( "Category", int(newEntry.category) ); avatarConfig->sync(); delete avatarConfig; // Add final path to the new entry for avatarAdded signal newEntry.path = avatarUrl.path(); emit avatarAdded(newEntry); } } void AvatarManager::remove(Kopete::AvatarManager::AvatarEntry entryToRemove) { Q_UNUSED(entryToRemove); emit avatarRemoved(entryToRemove); } void AvatarManager::Private::createDirectory(const KUrl &directory) { if( !QFile::exists(directory.path()) ) { kDebug(14010) << k_funcinfo << "Creating directory: " << directory.path() << endl; KIO::Job *job = KIO::mkdir(directory); job->exec(); if( job->error() ) { kDebug(14010) << "Directory creating failed: " << job->errorText() << endl; } } } QImage AvatarManager::Private::scaleImage(const QImage &source) { QImage result; if( source.width() > 96 || source.height() > 96 ) { // Scale and crop the picture. result = source.scaled( 96, 96, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation ); // crop image if not square if( result.width() < result.height() ) result = result.copy( (result.width()-result.height())/2, 0, 96, 96 ); else if( result.width() > result.height() ) result = result.copy( 0, (result.height()-result.width())/2, 96, 96 ); } else if( source.width() < 32 || source.height() < 32 ) { // Scale and crop the picture. result = source.scaled( 96, 96, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation ); // crop image if not square if( result.width() < result.height() ) result = result.copy( (result.width()-result.height())/2, 0, 32, 32 ); else if( result.width() > result.height() ) result = result.copy( 0, (result.height()-result.width())/2, 32, 32 ); } else if( source.width() != source.height() ) { if(source.width() < source.height()) result = source.copy((source.width()-source.height())/2, 0, source.height(), source.height()); else if (source.width() > source.height()) result = source.copy(0, (source.height()-source.width())/2, source.height(), source.height()); } return result; } //END AvatarManager //BEGIN AvatarQueryJob class AvatarQueryJob::Private { public: Private(AvatarQueryJob *parent) : queryJob(parent), category(AvatarManager::All) {} QPointer<AvatarQueryJob> queryJob; AvatarManager::AvatarCategory category; QList<AvatarManager::AvatarEntry> avatarList; KUrl baseDir; void listAvatarDirectory(const QString &path); }; AvatarQueryJob::AvatarQueryJob(QObject *parent) : KJob(parent), d(new Private(this)) { } AvatarQueryJob::~AvatarQueryJob() { delete d; } void AvatarQueryJob::setQueryFilter(Kopete::AvatarManager::AvatarCategory category) { d->category = category; } void AvatarQueryJob::start() { d->baseDir = KUrl( KStandardDirs::locateLocal("appdata", QLatin1String("avatars") ) ); if( d->category & Kopete::AvatarManager::User ) { d->listAvatarDirectory( UserDir ); } if( d->category & Kopete::AvatarManager::Contact ) { KUrl contactUrl(d->baseDir); contactUrl.addPath( ContactDir ); QDir contactDir(contactUrl.path()); QStringList subdirsList = contactDir.entryList( QDir::AllDirs | QDir::NoDotAndDotDot ); QString subdir; foreach(subdir, subdirsList) { d->listAvatarDirectory( ContactDir + QDir::separator() + subdir ); } } // Finish the job emitResult(); } QList<Kopete::AvatarManager::AvatarEntry> AvatarQueryJob::avatarList() const { return d->avatarList; } void AvatarQueryJob::Private::listAvatarDirectory(const QString &relativeDirectory) { KUrl avatarDirectory = baseDir; avatarDirectory.addPath(relativeDirectory); kDebug(14010) << k_funcinfo << "Listing avatars in " << avatarDirectory.path() << endl; // Look for Avatar configuration KUrl avatarConfigUrl = avatarDirectory; avatarConfigUrl.addPath( AvatarConfig ); if( QFile::exists(avatarConfigUrl.path()) ) { KConfig *avatarConfig = new KConfig( avatarConfigUrl.path(), KConfig::OnlyLocal); // Each avatar entry in configuration is a group QStringList groupEntryList = avatarConfig->groupList(); QString groupEntry; foreach(groupEntry, groupEntryList) { avatarConfig->setGroup(groupEntry); Kopete::AvatarManager::AvatarEntry listedEntry; listedEntry.name = groupEntry; listedEntry.category = static_cast<Kopete::AvatarManager::AvatarCategory>( avatarConfig->readEntry("Category", 0) ); QString filename = avatarConfig->readEntry( "Filename", QString() ); KUrl avatarPath(avatarDirectory); avatarPath.addPath( filename ); listedEntry.path = avatarPath.path(); avatarList << listedEntry; } } else { queryJob->setError( UserDefinedError ); queryJob->setErrorText( i18n("Avatar configuration hasn't been found on disk for category %1.", relativeDirectory) ); } } //END AvatarQueryJob } #include "kopeteavatarmanager.moc" <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("WICHCoin"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("WICHCoin"); // Client version number #define CLIENT_VERSION_SUFFIX "-omega" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 0 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Name release<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Kiwi"); // Client version number #define CLIENT_VERSION_SUFFIX "" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 0 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>#include <cstdarg> #include <string> #include <cstring> #include <functional> #include "toy/Log.hpp" #include "toy/Windows.hpp" #include "toy/Utf.hpp" #ifdef TOY_ANDROID #include <android/log.h> #endif //----------------PrintStr let you choose the way to print string----------------start namespace toy{ namespace log{ #if defined(TOY_WINDOWS) static std::function<void(const char*)> PrintStr = [](const char *str) { auto word = utf::UTF8ToWChar(std::string(str)); DWORD ws; WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),word.c_str(),word.size(),&ws,nullptr); }; static std::function<void(const wchar_t*)> PrintStrW = [](const wchar_t *str) { DWORD ws; WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),str,std::wcslen(str),&ws,nullptr); }; #elif defined(TOY_ANDROID) static std::function<void(const char*)> PrintStr = [](const char *str) { __android_log_print(ANDROID_LOG_DEBUG, "toybox", "%s", str); }; static std::function<void(const wchar_t*)> PrintStrW = [](const wchar_t *str) { __android_log_print(ANDROID_LOG_DEBUG, "toybox", "%s", utf::WCharToUTF8(std::wstring(str)).c_str()); // __android_log_print(ANDROID_LOG_DEBUG, "toybox", "%ls", str); }; #else static std::function<void(const char*)> PrintStr = [](const char *str) { printf("%s",str); }; static std::function<void(const wchar_t*)> PrintStrW = [](const wchar_t *str) { //wprintf(L"%ls",str); // No. It doesn't works on Linux. printf("%s",utf::WCharToUTF8(std::wstring(str)).c_str()); }; #endif }//namespace log }//namespace toy void toy::log::SetDevice(std::function<void(const char*)> func) { toy::log::PrintStr = std::move(func); } void toy::log::SetDevice(std::function<void(const wchar_t*)> func) { toy::log::PrintStrW = std::move(func); } //----------------PrintStr let you choose the way to print string----------------end #define STRING_SIZE 128 void toy::Log(const char *fmt, ... ) { va_list argptr; va_start(argptr, fmt); char buffer[STRING_SIZE]; vsnprintf(buffer,STRING_SIZE,fmt,argptr); toy::log::PrintStr(buffer); va_end(argptr); } void toy::Log(const wchar_t *fmt, ... ) { va_list argptr; va_start(argptr, fmt); wchar_t buffer[STRING_SIZE]; #if defined(TOY_MSVC) _vsnwprintf_s(buffer,STRING_SIZE,(int)STRING_SIZE-1,fmt,argptr); #elif defined(TOY_MINGW) vsnwprintf(buffer,STRING_SIZE,fmt,argptr); #else vswprintf(buffer,STRING_SIZE,fmt,argptr); // Just in case. #endif toy::log::PrintStrW(buffer); va_end(argptr); } void toy::Log(const std::exception &except) { toy::Log("%s\n",except.what()); } #undef STRING_SIZE <commit_msg>Just in case.<commit_after>#include <cstdarg> #include <string> #include <cstring> #include <functional> #include "toy/Log.hpp" #include "toy/Windows.hpp" #include "toy/Utf.hpp" #ifdef TOY_ANDROID #include <android/log.h> #endif //----------------PrintStr let you choose the way to print string----------------start namespace toy{ namespace log{ #if defined(TOY_WINDOWS) static std::function<void(const char*)> PrintStr = [](const char *str) { auto word = utf::UTF8ToWChar(std::string(str)); DWORD ws; WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),word.c_str(),word.size(),&ws,nullptr); }; static std::function<void(const wchar_t*)> PrintStrW = [](const wchar_t *str) { DWORD ws; WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),str,std::wcslen(str),&ws,nullptr); }; #elif defined(TOY_ANDROID) static std::function<void(const char*)> PrintStr = [](const char *str) { __android_log_print(ANDROID_LOG_DEBUG, "toybox", "%s", str); }; static std::function<void(const wchar_t*)> PrintStrW = [](const wchar_t *str) { __android_log_print(ANDROID_LOG_DEBUG, "toybox", "%s", utf::WCharToUTF8(std::wstring(str)).c_str()); // __android_log_print(ANDROID_LOG_DEBUG, "toybox", "%ls", str); }; #else static std::function<void(const char*)> PrintStr = [](const char *str) { printf("%s",str); }; static std::function<void(const wchar_t*)> PrintStrW = [](const wchar_t *str) { //wprintf(L"%ls",str); // No. It doesn't works on Linux. printf("%s",utf::WCharToUTF8(std::wstring(str)).c_str()); }; #endif }//namespace log }//namespace toy void toy::log::SetDevice(std::function<void(const char*)> func) { toy::log::PrintStr = std::move(func); } void toy::log::SetDevice(std::function<void(const wchar_t*)> func) { toy::log::PrintStrW = std::move(func); } //----------------PrintStr let you choose the way to print string----------------end #define STRING_SIZE 128 void toy::Log(const char *fmt, ... ) { va_list argptr; va_start(argptr, fmt); char buffer[STRING_SIZE]; vsnprintf(buffer,STRING_SIZE,fmt,argptr); buffer[STRING_SIZE-1] = '\0'; toy::log::PrintStr(buffer); va_end(argptr); } void toy::Log(const wchar_t *fmt, ... ) { va_list argptr; va_start(argptr, fmt); wchar_t buffer[STRING_SIZE]; #if defined(TOY_MSVC) _vsnwprintf_s(buffer,STRING_SIZE,(int)STRING_SIZE-1,fmt,argptr); #elif defined(TOY_MINGW) vsnwprintf(buffer,STRING_SIZE,fmt,argptr); #else vswprintf(buffer,STRING_SIZE,fmt,argptr); // Just in case. #endif buffer[STRING_SIZE-1] = L'\0'; toy::log::PrintStrW(buffer); va_end(argptr); } void toy::Log(const std::exception &except) { toy::Log("%s\n",except.what()); } #undef STRING_SIZE <|endoftext|>
<commit_before>#include <string> #include <iostream> #include <fstream> #include "Matrix.hpp" Matrix::Matrix(const Matrix &matrix) : m_rows(matrix.m_rows), m_columns(matrix.m_columns) { setElements(matrix.m_elements); } Matrix::Matrix(unsigned int rows, unsigned int columns) : m_rows(rows), m_columns(columns) { std::cout << __PRETTY_FUNCTION__ << std::endl; fill(nullptr); } Matrix::Matrix(unsigned int rows, unsigned int columns, int **elements) : m_rows(rows), m_columns(columns) { std::cout << __PRETTY_FUNCTION__ << std::endl; fill(elements); } void Matrix::fill(int **elements) { m_elements = new int *[m_columns]; for (unsigned int i = 0; i < m_columns; ++i) { m_elements[i] = new int[m_rows]; for (unsigned int j = 0; j < m_rows; ++j) { m_elements[i][j] = elements ? elements[i][j] : 0; } } } Matrix & Matrix::operator=(const Matrix &matrix) { if ( this != &matrix ) { Matrix(matrix).swap(*this); } return *this; } void Matrix::swap(Matrix &matrix) { std::swap(m_rows, matrix.m_rows); std::swap(m_columns, matrix.m_columns); std::swap(m_elements, matrix.m_elements); } Matrix::~Matrix() { for (unsigned int i = 0; i < m_rows; ++i) { delete [] m_elements[i]; } delete [] m_elements; } unsigned int Matrix::rows() const { return m_rows; } unsigned int Matrix::columns() const { return m_columns; } bool Matrix::fill(const std::string filePath) { std::ifstream input; input.open(filePath); bool isSucess = true; if ( input.is_open() ) { for (unsigned int i = 0; i < m_rows; ++i) { for (unsigned int j = 0; j < m_columns; ++j) { input >> m_elements[i][j]; } } } else { isSucess = false; } input.close(); return isSucess; } const int *Matrix::operator[](unsigned int index) const { if ( index >= m_rows ) { throw std::invalid_argument("index goes abroad"); } return m_elements[index]; } Matrix Matrix::operator *(const Matrix &matrix) const { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_columns != matrix.m_rows ) { throw std::invalid_argument("matrix sizes do not match"); } unsigned int n = m_rows; unsigned int m = matrix.m_columns; unsigned int s = m_columns; int **elements = new int *[n]; for (unsigned int i = 0; i < n; ++i) { elements[i] = new int[m]; for (unsigned int j = 0; j < m; ++j) { int value = 0; for (unsigned int k = 0; k < s; ++k) { value += m_elements[i][k] * matrix.m_elements[k][j]; } elements[i][j] = value; } } return Matrix(n, m, elements); } Matrix Matrix::operator +(const Matrix &matrix) const { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) { throw std::invalid_argument("matrix sizes do not match"); } unsigned int n = m_rows; unsigned int m = m_columns; int **data = new int *[n]; for (unsigned int i = 0; i < n; ++i) { data[i] = new int[m]; for (unsigned int j = 0; j < m; ++j) { data[i][j] = m_elements[i][j] + matrix.m_elements[i][j]; } } return Matrix(n, m, data); } bool Matrix::operator==(const Matrix &matrix) const { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) { return false; } for (unsigned int i = 0; i < m_rows; ++i) { for (unsigned int j = 0; j < m_columns; ++j) { if ( m_elements[i][j] != matrix.m_elements[i][j] ) { return false; } } } return true; } void Matrix::show() const { std::cout << __PRETTY_FUNCTION__ << std::endl; std::cout << m_rows << " * " << m_columns << std::endl; for (unsigned int i = 0; i < m_rows; ++i) { for (unsigned int j = 0; j < m_columns; ++j) { std::cout << m_elements[i][j] << "\t"; } std::cout << std::endl; } } <commit_msg>fixed bug<commit_after>#include <string> #include <iostream> #include <fstream> #include "Matrix.hpp" Matrix::Matrix(const Matrix &matrix) : m_rows(matrix.m_rows), m_columns(matrix.m_columns) { fill(matrix.m_elements); } Matrix::Matrix(unsigned int rows, unsigned int columns) : m_rows(rows), m_columns(columns) { std::cout << __PRETTY_FUNCTION__ << std::endl; fill(nullptr); } Matrix::Matrix(unsigned int rows, unsigned int columns, int **elements) : m_rows(rows), m_columns(columns) { std::cout << __PRETTY_FUNCTION__ << std::endl; fill(elements); } void Matrix::fill(int **elements) { m_elements = new int *[m_columns]; for (unsigned int i = 0; i < m_columns; ++i) { m_elements[i] = new int[m_rows]; for (unsigned int j = 0; j < m_rows; ++j) { m_elements[i][j] = elements ? elements[i][j] : 0; } } } Matrix & Matrix::operator=(const Matrix &matrix) { if ( this != &matrix ) { Matrix(matrix).swap(*this); } return *this; } void Matrix::swap(Matrix &matrix) { std::swap(m_rows, matrix.m_rows); std::swap(m_columns, matrix.m_columns); std::swap(m_elements, matrix.m_elements); } Matrix::~Matrix() { for (unsigned int i = 0; i < m_rows; ++i) { delete [] m_elements[i]; } delete [] m_elements; } unsigned int Matrix::rows() const { return m_rows; } unsigned int Matrix::columns() const { return m_columns; } bool Matrix::fill(const std::string filePath) { std::ifstream input; input.open(filePath); bool isSucess = true; if ( input.is_open() ) { for (unsigned int i = 0; i < m_rows; ++i) { for (unsigned int j = 0; j < m_columns; ++j) { input >> m_elements[i][j]; } } } else { isSucess = false; } input.close(); return isSucess; } const int *Matrix::operator[](unsigned int index) const { if ( index >= m_rows ) { throw std::invalid_argument("index goes abroad"); } return m_elements[index]; } Matrix Matrix::operator *(const Matrix &matrix) const { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_columns != matrix.m_rows ) { throw std::invalid_argument("matrix sizes do not match"); } unsigned int n = m_rows; unsigned int m = matrix.m_columns; unsigned int s = m_columns; int **elements = new int *[n]; for (unsigned int i = 0; i < n; ++i) { elements[i] = new int[m]; for (unsigned int j = 0; j < m; ++j) { int value = 0; for (unsigned int k = 0; k < s; ++k) { value += m_elements[i][k] * matrix.m_elements[k][j]; } elements[i][j] = value; } } return Matrix(n, m, elements); } Matrix Matrix::operator +(const Matrix &matrix) const { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) { throw std::invalid_argument("matrix sizes do not match"); } unsigned int n = m_rows; unsigned int m = m_columns; int **data = new int *[n]; for (unsigned int i = 0; i < n; ++i) { data[i] = new int[m]; for (unsigned int j = 0; j < m; ++j) { data[i][j] = m_elements[i][j] + matrix.m_elements[i][j]; } } return Matrix(n, m, data); } bool Matrix::operator==(const Matrix &matrix) const { std::cout << __PRETTY_FUNCTION__ << std::endl; if ( m_rows != matrix.m_rows || m_columns != matrix.m_columns ) { return false; } for (unsigned int i = 0; i < m_rows; ++i) { for (unsigned int j = 0; j < m_columns; ++j) { if ( m_elements[i][j] != matrix.m_elements[i][j] ) { return false; } } } return true; } void Matrix::show() const { std::cout << __PRETTY_FUNCTION__ << std::endl; std::cout << m_rows << " * " << m_columns << std::endl; for (unsigned int i = 0; i < m_rows; ++i) { for (unsigned int j = 0; j < m_columns; ++j) { std::cout << m_elements[i][j] << "\t"; } std::cout << std::endl; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include "qsysteminfo.h" QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkStatus); Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkMode); class tst_QSystemNetworkInfo : public QObject { Q_OBJECT private slots: void initTestCase(); void tst_networkStatus(); void tst_networkSignalStrength_data(); void tst_networkSignalStrength(); void tst_cellId(); void tst_locationAreaCode(); void tst_currentMobileCountryCode(); // Mobile Country Code void tst_currentMobileNetworkCode(); // Mobile Network Code void tst_homeMobileCountryCode(); void tst_homeMobileNetworkCode(); void tst_networkName(); void tst_macAddress_data(); void tst_macAddress(); void tst_interfaceForMode(); }; //signal todo: // void networkStatusChanged(QSystemNetworkInfo::NetworkMode netmode, QSystemNetworkInfo::CellNetworkStatus netStatus); void tst_QSystemNetworkInfo::initTestCase() { qRegisterMetaType<QSystemNetworkInfo::NetworkStatus>("QSystemNetworkInfo::NetworkStatus"); qRegisterMetaType<QSystemNetworkInfo::NetworkMode>("QSystemNetworkInfo::NetworkMode"); } void tst_QSystemNetworkInfo::tst_networkStatus() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QSystemNetworkInfo::NetworkStatus status = ni.networkStatus(mode); QVERIFY( status == QSystemNetworkInfo::UndefinedStatus || status == QSystemNetworkInfo::NoNetworkAvailable || status == QSystemNetworkInfo::EmergencyOnly || status == QSystemNetworkInfo::Searching || status == QSystemNetworkInfo::Busy || status == QSystemNetworkInfo::Connected || status == QSystemNetworkInfo::HomeNetwork || status == QSystemNetworkInfo::Denied || status == QSystemNetworkInfo::Roaming); } } void tst_QSystemNetworkInfo::tst_networkSignalStrength_data() { QTest::addColumn<QSystemNetworkInfo::NetworkMode>("mode"); QTest::newRow("GsmMode") << QSystemNetworkInfo::GsmMode; QTest::newRow("CdmaMode") << QSystemNetworkInfo::CdmaMode; QTest::newRow("WcdmaMode") << QSystemNetworkInfo::WcdmaMode; QTest::newRow("WlanMode") << QSystemNetworkInfo::WlanMode; QTest::newRow("EthernetMode") << QSystemNetworkInfo::EthernetMode; QTest::newRow("BluetoothMode") << QSystemNetworkInfo::BluetoothMode; QTest::newRow("WimaxMode") << QSystemNetworkInfo::WimaxMode; } void tst_QSystemNetworkInfo::tst_networkSignalStrength() { { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; qint32 strength = ni.networkSignalStrength(mode); QVERIFY( strength > -2 && strength < 101); } } void tst_QSystemNetworkInfo::tst_cellId() { QSystemNetworkInfo ni; qint32 id = ni.cellId(); QVERIFY(id > -2); } void tst_QSystemNetworkInfo::tst_locationAreaCode() { QSystemNetworkInfo ni; qint32 lac = ni.locationAreaCode(); QVERIFY(lac > -2); } void tst_QSystemNetworkInfo::tst_currentMobileCountryCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::GsmMode) && QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::CdmaMode) && QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.currentMobileCountryCode().isEmpty()); } else { QVERIFY(ni.currentMobileCountryCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_currentMobileNetworkCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::GsmMode) && QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::CdmaMode) && QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.currentMobileNetworkCode().isEmpty()); } else { QVERIFY(ni.currentMobileNetworkCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_homeMobileCountryCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::GsmMode) && QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::CdmaMode) && QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.homeMobileCountryCode().isEmpty()); } else { QVERIFY(ni.homeMobileCountryCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_homeMobileNetworkCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::GsmMode) && QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::CdmaMode) && QSystemNetworkInfo::NoNetworkAvailable != ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.homeMobileNetworkCode().isEmpty()); } else { QVERIFY(ni.homeMobileNetworkCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_networkName() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.networkName(mode).isEmpty() ||ni.networkName(mode).isEmpty()); } } void tst_QSystemNetworkInfo::tst_macAddress_data() { tst_networkSignalStrength_data(); } void tst_QSystemNetworkInfo::tst_macAddress() { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; QString mac = ni.macAddress(mode); if (!mac.isEmpty()) { QVERIFY(mac.length() == 17); QVERIFY(mac.contains(":")); } } void tst_QSystemNetworkInfo::tst_interfaceForMode() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.interfaceForMode(mode).name().isEmpty() || !ni.interfaceForMode(mode).isValid()); } } QTEST_MAIN(tst_QSystemNetworkInfo) #include "tst_qsystemnetworkinfo.moc" <commit_msg>need to be connected to be able to get this info<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include "qsysteminfo.h" QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkStatus); Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkMode); class tst_QSystemNetworkInfo : public QObject { Q_OBJECT private slots: void initTestCase(); void tst_networkStatus(); void tst_networkSignalStrength_data(); void tst_networkSignalStrength(); void tst_cellId(); void tst_locationAreaCode(); void tst_currentMobileCountryCode(); // Mobile Country Code void tst_currentMobileNetworkCode(); // Mobile Network Code void tst_homeMobileCountryCode(); void tst_homeMobileNetworkCode(); void tst_networkName(); void tst_macAddress_data(); void tst_macAddress(); void tst_interfaceForMode(); }; //signal todo: // void networkStatusChanged(QSystemNetworkInfo::NetworkMode netmode, QSystemNetworkInfo::CellNetworkStatus netStatus); void tst_QSystemNetworkInfo::initTestCase() { qRegisterMetaType<QSystemNetworkInfo::NetworkStatus>("QSystemNetworkInfo::NetworkStatus"); qRegisterMetaType<QSystemNetworkInfo::NetworkMode>("QSystemNetworkInfo::NetworkMode"); } void tst_QSystemNetworkInfo::tst_networkStatus() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QSystemNetworkInfo::NetworkStatus status = ni.networkStatus(mode); QVERIFY( status == QSystemNetworkInfo::UndefinedStatus || status == QSystemNetworkInfo::NoNetworkAvailable || status == QSystemNetworkInfo::EmergencyOnly || status == QSystemNetworkInfo::Searching || status == QSystemNetworkInfo::Busy || status == QSystemNetworkInfo::Connected || status == QSystemNetworkInfo::HomeNetwork || status == QSystemNetworkInfo::Denied || status == QSystemNetworkInfo::Roaming); } } void tst_QSystemNetworkInfo::tst_networkSignalStrength_data() { QTest::addColumn<QSystemNetworkInfo::NetworkMode>("mode"); QTest::newRow("GsmMode") << QSystemNetworkInfo::GsmMode; QTest::newRow("CdmaMode") << QSystemNetworkInfo::CdmaMode; QTest::newRow("WcdmaMode") << QSystemNetworkInfo::WcdmaMode; QTest::newRow("WlanMode") << QSystemNetworkInfo::WlanMode; QTest::newRow("EthernetMode") << QSystemNetworkInfo::EthernetMode; QTest::newRow("BluetoothMode") << QSystemNetworkInfo::BluetoothMode; QTest::newRow("WimaxMode") << QSystemNetworkInfo::WimaxMode; } void tst_QSystemNetworkInfo::tst_networkSignalStrength() { { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; qint32 strength = ni.networkSignalStrength(mode); QVERIFY( strength > -2 && strength < 101); } } void tst_QSystemNetworkInfo::tst_cellId() { QSystemNetworkInfo ni; qint32 id = ni.cellId(); QVERIFY(id > -2); } void tst_QSystemNetworkInfo::tst_locationAreaCode() { QSystemNetworkInfo ni; qint32 lac = ni.locationAreaCode(); QVERIFY(lac > -2); } void tst_QSystemNetworkInfo::tst_currentMobileCountryCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.currentMobileCountryCode().isEmpty()); } else { QVERIFY(ni.currentMobileCountryCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_currentMobileNetworkCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.currentMobileNetworkCode().isEmpty()); } else { QVERIFY(ni.currentMobileNetworkCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_homeMobileCountryCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.homeMobileCountryCode().isEmpty()); } else { QVERIFY(ni.homeMobileCountryCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_homeMobileNetworkCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::Connected == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.homeMobileNetworkCode().isEmpty()); } else { QVERIFY(ni.homeMobileNetworkCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_networkName() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.networkName(mode).isEmpty() ||ni.networkName(mode).isEmpty()); } } void tst_QSystemNetworkInfo::tst_macAddress_data() { tst_networkSignalStrength_data(); } void tst_QSystemNetworkInfo::tst_macAddress() { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; QString mac = ni.macAddress(mode); if (!mac.isEmpty()) { QVERIFY(mac.length() == 17); QVERIFY(mac.contains(":")); } } void tst_QSystemNetworkInfo::tst_interfaceForMode() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.interfaceForMode(mode).name().isEmpty() || !ni.interfaceForMode(mode).isValid()); } } QTEST_MAIN(tst_QSystemNetworkInfo) #include "tst_qsystemnetworkinfo.moc" <|endoftext|>
<commit_before><commit_msg>Change the zoom factor to 2^(1/6), hopefully it fits all :-)<commit_after><|endoftext|>
<commit_before>/* * statswindow.cpp * PHD Guiding * * Created by Andy Galasso * Copyright (c) 2014 Andy Galasso * All rights reserved. * * This source code is distributed under the following "BSD" 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. * Neither the name of Craig Stark, Stark Labs nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "phd.h" #include "statswindow.h" enum { TIMER_ID_COOLER = 101, }; wxBEGIN_EVENT_TABLE(StatsWindow, wxWindow) EVT_BUTTON(BUTTON_GRAPH_LENGTH, StatsWindow::OnButtonLength) EVT_MENU_RANGE(MENU_LENGTH_BEGIN, MENU_LENGTH_END, StatsWindow::OnMenuLength) EVT_BUTTON(BUTTON_GRAPH_CLEAR, StatsWindow::OnButtonClear) EVT_TIMER(TIMER_ID_COOLER, StatsWindow::OnTimerCooler) wxEND_EVENT_TABLE() StatsWindow::StatsWindow(wxWindow *parent) : wxWindow(parent, wxID_ANY), m_visible(false), m_coolerTimer(this, TIMER_ID_COOLER), m_lastFrameSize(wxDefaultSize) { SetBackgroundColour(*wxBLACK); m_grid1 = new wxGrid(this, wxID_ANY); m_grid1->CreateGrid(4, 3); m_grid1->SetRowLabelSize(1); m_grid1->SetColLabelSize(1); m_grid1->EnableEditing(false); m_grid1->SetDefaultCellBackgroundColour(*wxBLACK); m_grid1->SetDefaultCellTextColour(*wxLIGHT_GREY); m_grid1->SetGridLineColour(wxColour(40, 40, 40)); int col = 0; int row = 0; m_grid1->SetCellValue(row, col++, ""); m_grid1->SetCellValue(row, col++, _("RMS")); m_grid1->SetCellValue(row, col++, _("Peak")); ++row, col = 0; m_grid1->SetCellValue(row, col++, _("RA")); m_grid1->SetCellValue(row, col++, _T(" 99.99 (99.99'')")); m_grid1->SetCellValue(row, col++, _(" 99.99 (99.99'')")); ++row, col = 0; m_grid1->SetCellValue(row, col++, _("Dec")); ++row, col = 0; m_grid1->SetCellValue(row, col++, _("Total")); m_grid1->AutoSize(); m_grid1->SetCellValue(1, 1, ""); m_grid1->SetCellValue(1, 2, ""); m_grid1->ClearSelection(); m_grid2 = new wxGrid(this, wxID_ANY); m_grid2->CreateGrid(11, 2); m_grid2->SetRowLabelSize(1); m_grid2->SetColLabelSize(1); m_grid2->EnableEditing(false); m_grid2->SetDefaultCellBackgroundColour(*wxBLACK); m_grid2->SetDefaultCellTextColour(*wxLIGHT_GREY); m_grid2->SetGridLineColour(wxColour(40, 40, 40)); row = 0, col = 0; m_grid2->SetCellValue(row, col++, _("RA Osc")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("RA Limited")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Dec Limited")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Star lost")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Declination")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Pier Side")); m_grid2->SetCellValue(3, 1, _T("MMMMMM")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Rotator Pos")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Camera binning")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Image size")); m_frameSizeRow = row; ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Field of View")); // Make sure the column is big enough m_grid2->SetCellValue(row, col, _("nnn.n x nnn.n arc-min")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Camera cooler")); m_grid2->SetCellValue(row, col, "-99" DEGREES_SYMBOL " / -99" DEGREES_SYMBOL ", 999%"); m_coolerRow = row; m_grid2->AutoSize(); m_grid2->SetCellValue(3, 1, _T("")); m_grid2->SetCellValue(m_frameSizeRow + 1, 1, _T("")); m_grid2->ClearSelection(); wxSizer *sizer1 = new wxBoxSizer(wxHORIZONTAL); wxButton *clearButton = new wxButton(this, BUTTON_GRAPH_CLEAR, _("Clear")); clearButton->SetToolTip(_("Clear graph data and stats")); clearButton->SetBackgroundStyle(wxBG_STYLE_TRANSPARENT); sizer1->Add(clearButton, 0, wxALL, 10); m_pLengthButton = new OptionsButton(this, BUTTON_GRAPH_LENGTH, _T("XXXXXXX:888888"), wxDefaultPosition, wxSize(220, -1)); m_pLengthButton->SetToolTip(_("Select the number of frames of history for stats and the graph")); m_length = dynamic_cast<MyFrame *>(parent)->pGraphLog->GetLength(); m_pLengthButton->SetLabel(wxString::Format(_T("x:%3d"), m_length)); sizer1->Add(m_pLengthButton, 0, wxALL, 10); wxSizer *sizer2 = new wxBoxSizer(wxVERTICAL); sizer2->Add(sizer1, 0, wxEXPAND, 10); sizer2->Add(m_grid1, wxSizerFlags(0).Border(wxALL, 10)); sizer2->Add(m_grid2, wxSizerFlags(0).Border(wxALL, 10)); SetSizerAndFit(sizer2); } StatsWindow::~StatsWindow(void) { } void StatsWindow::SetState(bool is_active) { m_visible = is_active; if (m_visible) { UpdateStats(); UpdateCooler(); } } static wxString arcsecs(double px, double sampling) { if (sampling != 1.0) return wxString::Format("% 4.2f (%.2f'')", px, px * sampling); else return wxString::Format("% 4.2f", px); } void StatsWindow::UpdateStats(void) { if (!m_visible) return; if (!pFrame || !pFrame->pGraphLog) return; int length = pFrame->pGraphLog->GetLength(); if (m_length != length) { m_pLengthButton->SetLabel(wxString::Format(_T("x:%3d"), length)); m_length = length; } const SummaryStats& stats = pFrame->pGraphLog->Stats(); const double sampling = pFrame ? pFrame->GetCameraPixelScale() : 1.0; m_grid1->BeginBatch(); m_grid2->BeginBatch(); int row = 1, col = 1; m_grid1->SetCellValue(row++, col, arcsecs(stats.rms_ra, sampling)); m_grid1->SetCellValue(row++, col, arcsecs(stats.rms_dec, sampling)); m_grid1->SetCellValue(row++, col, arcsecs(stats.rms_tot, sampling)); row = 1, col = 2; m_grid1->SetCellValue(row++, col, arcsecs(stats.ra_peak, sampling)); m_grid1->SetCellValue(row++, col, arcsecs(stats.dec_peak, sampling)); row = 0, col = 1; if (stats.osc_alert) m_grid2->SetCellTextColour(row, col, wxColour(185, 20, 0)); else m_grid2->SetCellTextColour(row, col, *wxLIGHT_GREY); m_grid2->SetCellValue(row++, col, wxString::Format("% .02f", stats.osc_index)); unsigned int historyItems = wxMax(pFrame->pGraphLog->GetHistoryItemCount(), 1); // avoid divide-by-zero if (stats.ra_limit_cnt > 0) m_grid2->SetCellTextColour(row, col, wxColour(185, 20, 0)); else m_grid2->SetCellTextColour(row, col, *wxLIGHT_GREY); m_grid2->SetCellValue(row++, col, wxString::Format(" %u (%.f%%)", stats.ra_limit_cnt, stats.ra_limit_cnt * 100. / historyItems)); if (stats.dec_limit_cnt > 0) m_grid2->SetCellTextColour(row, col, wxColour(185, 20, 0)); else m_grid2->SetCellTextColour(row, col, *wxLIGHT_GREY); m_grid2->SetCellValue(row++, col, wxString::Format(" %u (%.f%%)", stats.dec_limit_cnt, stats.dec_limit_cnt * 100. / historyItems)); m_grid2->SetCellValue(row++, col, wxString::Format(" %u", stats.star_lost_cnt)); m_grid1->EndBatch(); m_grid2->EndBatch(); } static wxString CamCoolerStatus() { bool on; double setpt, power, temp; bool err = pCamera->GetCoolerStatus(&on, &setpt, &power, &temp); if (err) return _("Camera error"); else if (on) return wxString::Format(_("%.f" DEGREES_SYMBOL " / %.f" DEGREES_SYMBOL ", %.f%%"), temp, setpt, power); else return wxString::Format(_("%.f" DEGREES_SYMBOL ", Off"), temp); } void StatsWindow::UpdateCooler() { m_coolerTimer.Stop(); if (!m_visible) return; wxString s; if (pCamera && pCamera->Connected) { if (pCamera->HasCooler) { s = CamCoolerStatus(); enum { COOLER_POLL_INTERVAL_MS = 10000 }; m_coolerTimer.StartOnce(COOLER_POLL_INTERVAL_MS); } else s = _("None"); } m_grid2->SetCellValue(m_coolerRow, 1, s); } static wxString fov(const wxSize& sensorFormat, double sampling) { if (sampling != 1.0) return wxString::Format("% 4.1f x % 4.1f %s", sensorFormat.x * sampling / 60.0, sensorFormat.y * sampling / 60.0, _(" arc-min")); else return " "; } void StatsWindow::UpdateImageSize(const wxSize& frameSize) { if (m_visible && frameSize != m_lastFrameSize) { wxString sensorStr = wxString::Format("%d x %d %s", frameSize.x, frameSize.y, _("px")); m_grid2->SetCellValue(m_frameSizeRow, 1, sensorStr); const double sampling = pFrame ? pFrame->GetCameraPixelScale() : 1.0; m_grid2->SetCellValue(m_frameSizeRow + 1, 1, fov(frameSize, sampling)); m_lastFrameSize = frameSize; } } void StatsWindow::ResetImageSize() { m_lastFrameSize = wxDefaultSize; m_grid2->SetCellValue(m_frameSizeRow, 1, wxEmptyString); m_grid2->SetCellValue(m_frameSizeRow + 1, 1, wxEmptyString); } void StatsWindow::OnTimerCooler(wxTimerEvent&) { UpdateCooler(); } static wxString RotatorPosStr() { if (!pRotator) return _("N/A"); double pos = Rotator::RotatorPosition(); if (pos == Rotator::POSITION_UNKNOWN) return _("Unknown"); else return wxString::Format("%5.1f", norm(pos, 0.0, 360.0)); } void StatsWindow::UpdateScopePointing() { if (pPointingSource) { double declination = pPointingSource->GetDeclination(); PierSide pierSide = pPointingSource->SideOfPier(); m_grid2->BeginBatch(); int row = 4, col = 1; m_grid2->SetCellValue(row++, col, Mount::DeclinationStr(declination, "% .1f" DEGREES_SYMBOL)); m_grid2->SetCellValue(row++, col, Mount::PierSideStr(pierSide)); m_grid2->SetCellValue(row++, col, RotatorPosStr()); m_grid2->SetCellValue(row++, col, wxString::Format("%hu", pCamera->Binning)); m_grid2->EndBatch(); } } void StatsWindow::OnButtonLength(wxCommandEvent& WXUNUSED(evt)) { wxMenu *menu = pFrame->pGraphLog->GetLengthMenu(); PopupMenu(menu, m_pLengthButton->GetPosition().x, m_pLengthButton->GetPosition().y + m_pLengthButton->GetSize().GetHeight()); delete menu; } void StatsWindow::OnMenuLength(wxCommandEvent& evt) { pFrame->pGraphLog->OnMenuLength(evt); } void StatsWindow::OnButtonClear(wxCommandEvent& evt) { pFrame->pGraphLog->OnButtonClear(evt); } <commit_msg>fix crash when stats window is updated and Camera = None<commit_after>/* * statswindow.cpp * PHD Guiding * * Created by Andy Galasso * Copyright (c) 2014 Andy Galasso * All rights reserved. * * This source code is distributed under the following "BSD" 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. * Neither the name of Craig Stark, Stark Labs nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "phd.h" #include "statswindow.h" enum { TIMER_ID_COOLER = 101, }; wxBEGIN_EVENT_TABLE(StatsWindow, wxWindow) EVT_BUTTON(BUTTON_GRAPH_LENGTH, StatsWindow::OnButtonLength) EVT_MENU_RANGE(MENU_LENGTH_BEGIN, MENU_LENGTH_END, StatsWindow::OnMenuLength) EVT_BUTTON(BUTTON_GRAPH_CLEAR, StatsWindow::OnButtonClear) EVT_TIMER(TIMER_ID_COOLER, StatsWindow::OnTimerCooler) wxEND_EVENT_TABLE() StatsWindow::StatsWindow(wxWindow *parent) : wxWindow(parent, wxID_ANY), m_visible(false), m_coolerTimer(this, TIMER_ID_COOLER), m_lastFrameSize(wxDefaultSize) { SetBackgroundColour(*wxBLACK); m_grid1 = new wxGrid(this, wxID_ANY); m_grid1->CreateGrid(4, 3); m_grid1->SetRowLabelSize(1); m_grid1->SetColLabelSize(1); m_grid1->EnableEditing(false); m_grid1->SetDefaultCellBackgroundColour(*wxBLACK); m_grid1->SetDefaultCellTextColour(*wxLIGHT_GREY); m_grid1->SetGridLineColour(wxColour(40, 40, 40)); int col = 0; int row = 0; m_grid1->SetCellValue(row, col++, ""); m_grid1->SetCellValue(row, col++, _("RMS")); m_grid1->SetCellValue(row, col++, _("Peak")); ++row, col = 0; m_grid1->SetCellValue(row, col++, _("RA")); m_grid1->SetCellValue(row, col++, _T(" 99.99 (99.99'')")); m_grid1->SetCellValue(row, col++, _(" 99.99 (99.99'')")); ++row, col = 0; m_grid1->SetCellValue(row, col++, _("Dec")); ++row, col = 0; m_grid1->SetCellValue(row, col++, _("Total")); m_grid1->AutoSize(); m_grid1->SetCellValue(1, 1, ""); m_grid1->SetCellValue(1, 2, ""); m_grid1->ClearSelection(); m_grid2 = new wxGrid(this, wxID_ANY); m_grid2->CreateGrid(11, 2); m_grid2->SetRowLabelSize(1); m_grid2->SetColLabelSize(1); m_grid2->EnableEditing(false); m_grid2->SetDefaultCellBackgroundColour(*wxBLACK); m_grid2->SetDefaultCellTextColour(*wxLIGHT_GREY); m_grid2->SetGridLineColour(wxColour(40, 40, 40)); row = 0, col = 0; m_grid2->SetCellValue(row, col++, _("RA Osc")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("RA Limited")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Dec Limited")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Star lost")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Declination")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Pier Side")); m_grid2->SetCellValue(3, 1, _T("MMMMMM")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Rotator Pos")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Camera binning")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Image size")); m_frameSizeRow = row; ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Field of View")); // Make sure the column is big enough m_grid2->SetCellValue(row, col, _("nnn.n x nnn.n arc-min")); ++row, col = 0; m_grid2->SetCellValue(row, col++, _("Camera cooler")); m_grid2->SetCellValue(row, col, "-99" DEGREES_SYMBOL " / -99" DEGREES_SYMBOL ", 999%"); m_coolerRow = row; m_grid2->AutoSize(); m_grid2->SetCellValue(3, 1, _T("")); m_grid2->SetCellValue(m_frameSizeRow + 1, 1, _T("")); m_grid2->ClearSelection(); wxSizer *sizer1 = new wxBoxSizer(wxHORIZONTAL); wxButton *clearButton = new wxButton(this, BUTTON_GRAPH_CLEAR, _("Clear")); clearButton->SetToolTip(_("Clear graph data and stats")); clearButton->SetBackgroundStyle(wxBG_STYLE_TRANSPARENT); sizer1->Add(clearButton, 0, wxALL, 10); m_pLengthButton = new OptionsButton(this, BUTTON_GRAPH_LENGTH, _T("XXXXXXX:888888"), wxDefaultPosition, wxSize(220, -1)); m_pLengthButton->SetToolTip(_("Select the number of frames of history for stats and the graph")); m_length = dynamic_cast<MyFrame *>(parent)->pGraphLog->GetLength(); m_pLengthButton->SetLabel(wxString::Format(_T("x:%3d"), m_length)); sizer1->Add(m_pLengthButton, 0, wxALL, 10); wxSizer *sizer2 = new wxBoxSizer(wxVERTICAL); sizer2->Add(sizer1, 0, wxEXPAND, 10); sizer2->Add(m_grid1, wxSizerFlags(0).Border(wxALL, 10)); sizer2->Add(m_grid2, wxSizerFlags(0).Border(wxALL, 10)); SetSizerAndFit(sizer2); } StatsWindow::~StatsWindow(void) { } void StatsWindow::SetState(bool is_active) { m_visible = is_active; if (m_visible) { UpdateStats(); UpdateCooler(); } } static wxString arcsecs(double px, double sampling) { if (sampling != 1.0) return wxString::Format("% 4.2f (%.2f'')", px, px * sampling); else return wxString::Format("% 4.2f", px); } void StatsWindow::UpdateStats(void) { if (!m_visible) return; if (!pFrame || !pFrame->pGraphLog) return; int length = pFrame->pGraphLog->GetLength(); if (m_length != length) { m_pLengthButton->SetLabel(wxString::Format(_T("x:%3d"), length)); m_length = length; } const SummaryStats& stats = pFrame->pGraphLog->Stats(); const double sampling = pFrame ? pFrame->GetCameraPixelScale() : 1.0; m_grid1->BeginBatch(); m_grid2->BeginBatch(); int row = 1, col = 1; m_grid1->SetCellValue(row++, col, arcsecs(stats.rms_ra, sampling)); m_grid1->SetCellValue(row++, col, arcsecs(stats.rms_dec, sampling)); m_grid1->SetCellValue(row++, col, arcsecs(stats.rms_tot, sampling)); row = 1, col = 2; m_grid1->SetCellValue(row++, col, arcsecs(stats.ra_peak, sampling)); m_grid1->SetCellValue(row++, col, arcsecs(stats.dec_peak, sampling)); row = 0, col = 1; if (stats.osc_alert) m_grid2->SetCellTextColour(row, col, wxColour(185, 20, 0)); else m_grid2->SetCellTextColour(row, col, *wxLIGHT_GREY); m_grid2->SetCellValue(row++, col, wxString::Format("% .02f", stats.osc_index)); unsigned int historyItems = wxMax(pFrame->pGraphLog->GetHistoryItemCount(), 1); // avoid divide-by-zero if (stats.ra_limit_cnt > 0) m_grid2->SetCellTextColour(row, col, wxColour(185, 20, 0)); else m_grid2->SetCellTextColour(row, col, *wxLIGHT_GREY); m_grid2->SetCellValue(row++, col, wxString::Format(" %u (%.f%%)", stats.ra_limit_cnt, stats.ra_limit_cnt * 100. / historyItems)); if (stats.dec_limit_cnt > 0) m_grid2->SetCellTextColour(row, col, wxColour(185, 20, 0)); else m_grid2->SetCellTextColour(row, col, *wxLIGHT_GREY); m_grid2->SetCellValue(row++, col, wxString::Format(" %u (%.f%%)", stats.dec_limit_cnt, stats.dec_limit_cnt * 100. / historyItems)); m_grid2->SetCellValue(row++, col, wxString::Format(" %u", stats.star_lost_cnt)); m_grid1->EndBatch(); m_grid2->EndBatch(); } static wxString CamCoolerStatus() { bool on; double setpt, power, temp; bool err = pCamera->GetCoolerStatus(&on, &setpt, &power, &temp); if (err) return _("Camera error"); else if (on) return wxString::Format(_("%.f" DEGREES_SYMBOL " / %.f" DEGREES_SYMBOL ", %.f%%"), temp, setpt, power); else return wxString::Format(_("%.f" DEGREES_SYMBOL ", Off"), temp); } void StatsWindow::UpdateCooler() { m_coolerTimer.Stop(); if (!m_visible) return; wxString s; if (pCamera && pCamera->Connected) { if (pCamera->HasCooler) { s = CamCoolerStatus(); enum { COOLER_POLL_INTERVAL_MS = 10000 }; m_coolerTimer.StartOnce(COOLER_POLL_INTERVAL_MS); } else s = _("None"); } m_grid2->SetCellValue(m_coolerRow, 1, s); } static wxString fov(const wxSize& sensorFormat, double sampling) { if (sampling != 1.0) return wxString::Format("% 4.1f x % 4.1f %s", sensorFormat.x * sampling / 60.0, sensorFormat.y * sampling / 60.0, _(" arc-min")); else return " "; } void StatsWindow::UpdateImageSize(const wxSize& frameSize) { if (m_visible && frameSize != m_lastFrameSize) { wxString sensorStr = wxString::Format("%d x %d %s", frameSize.x, frameSize.y, _("px")); m_grid2->SetCellValue(m_frameSizeRow, 1, sensorStr); const double sampling = pFrame ? pFrame->GetCameraPixelScale() : 1.0; m_grid2->SetCellValue(m_frameSizeRow + 1, 1, fov(frameSize, sampling)); m_lastFrameSize = frameSize; } } void StatsWindow::ResetImageSize() { m_lastFrameSize = wxDefaultSize; m_grid2->SetCellValue(m_frameSizeRow, 1, wxEmptyString); m_grid2->SetCellValue(m_frameSizeRow + 1, 1, wxEmptyString); } void StatsWindow::OnTimerCooler(wxTimerEvent&) { UpdateCooler(); } static wxString RotatorPosStr() { if (!pRotator) return _("N/A"); double pos = Rotator::RotatorPosition(); if (pos == Rotator::POSITION_UNKNOWN) return _("Unknown"); else return wxString::Format("%5.1f", norm(pos, 0.0, 360.0)); } void StatsWindow::UpdateScopePointing() { if (pPointingSource) { double declination = pPointingSource->GetDeclination(); PierSide pierSide = pPointingSource->SideOfPier(); m_grid2->BeginBatch(); int row = 4, col = 1; m_grid2->SetCellValue(row++, col, Mount::DeclinationStr(declination, "% .1f" DEGREES_SYMBOL)); m_grid2->SetCellValue(row++, col, Mount::PierSideStr(pierSide)); m_grid2->SetCellValue(row++, col, RotatorPosStr()); m_grid2->SetCellValue(row++, col, pCamera ? wxString::Format("%hu", pCamera->Binning) : _("N/A")); m_grid2->EndBatch(); } } void StatsWindow::OnButtonLength(wxCommandEvent& WXUNUSED(evt)) { wxMenu *menu = pFrame->pGraphLog->GetLengthMenu(); PopupMenu(menu, m_pLengthButton->GetPosition().x, m_pLengthButton->GetPosition().y + m_pLengthButton->GetSize().GetHeight()); delete menu; } void StatsWindow::OnMenuLength(wxCommandEvent& evt) { pFrame->pGraphLog->OnMenuLength(evt); } void StatsWindow::OnButtonClear(wxCommandEvent& evt) { pFrame->pGraphLog->OnButtonClear(evt); } <|endoftext|>
<commit_before>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program 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. * * This program 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 General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Cell.h" #include "CellImpl.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "TaskScheduler.h" #include "temple_of_ahnqiraj.h" enum Spells { // Ouro SPELL_SWEEP = 26103, SPELL_SAND_BLAST = 26102, SPELL_GROUND_RUPTURE = 26100, SPELL_BERSERK = 26615, SPELL_BOULDER = 26616, SPELL_OURO_SUBMERGE_VISUAL = 26063, SPELL_SUMMON_SANDWORM_BASE = 26133, // Misc - Mounds, Ouro Spawner SPELL_BIRTH = 26586, SPELL_DIRTMOUND_PASSIVE = 26092, SPELL_SUMMON_OURO = 26061, SPELL_SUMMON_OURO_MOUNDS = 26058, SPELL_QUAKE = 26093, SPELL_SUMMON_SCARABS = 26060, SPELL_SUMMON_OURO_AURA = 26642, SPELL_DREAM_FOG = 24780 }; enum Misc { GROUP_EMERGED = 0, GROUP_PHASE_TRANSITION = 1, NPC_DIRT_MOUND = 15712, GO_SANDWORM_BASE = 180795, DATA_OURO_HEALTH = 0 }; struct npc_ouro_spawner : public ScriptedAI { npc_ouro_spawner(Creature* creature) : ScriptedAI(creature) { Reset(); } bool hasSummoned; void Reset() override { hasSummoned = false; DoCastSelf(SPELL_DIRTMOUND_PASSIVE); } void MoveInLineOfSight(Unit* who) override { // Spawn Ouro on LoS check if (!hasSummoned && who->GetTypeId() == TYPEID_PLAYER && me->IsWithinDistInMap(who, 40.0f) && !who->ToPlayer()->IsGameMaster()) { if (InstanceScript* instance = me->GetInstanceScript()) { Creature* ouro = instance->GetCreature(DATA_OURO); if (instance->GetBossState(DATA_OURO) != IN_PROGRESS && !ouro) { DoCastSelf(SPELL_SUMMON_OURO); hasSummoned = true; } } } ScriptedAI::MoveInLineOfSight(who); } void JustSummoned(Creature* creature) override { // Despawn when Ouro is spawned if (creature->GetEntry() == NPC_OURO) { creature->SetInCombatWithZone(); me->DespawnOrUnsummon(); } } }; struct boss_ouro : public BossAI { boss_ouro(Creature* creature) : BossAI(creature, DATA_OURO) { SetCombatMovement(false); me->SetControlled(true, UNIT_STATE_ROOT); _scheduler.SetValidator([this] { return !me->HasUnitState(UNIT_STATE_CASTING); }); } void DamageTaken(Unit* /*attacker*/, uint32& damage, DamageEffectType, SpellSchoolMask) override { if (me->HealthBelowPctDamaged(20, damage) && !_enraged) { DoCastSelf(SPELL_BERSERK, true); _enraged = true; _scheduler.CancelGroup(GROUP_PHASE_TRANSITION); _scheduler.Schedule(1s, [this](TaskContext context) { if (!IsPlayerWithinMeleeRange()) DoSpellAttackToRandomTargetIfReady(SPELL_BOULDER); context.Repeat(); }) .Schedule(20s, [this](TaskContext context) { DoCastSelf(SPELL_SUMMON_OURO_MOUNDS, true); context.Repeat(); }); } } void Submerge() { if (_enraged || _submerged) return; me->AttackStop(); me->SetReactState(REACT_PASSIVE); me->SetUnitFlag(UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); _submergeMelee = 0; _submerged = true; DoCastSelf(SPELL_OURO_SUBMERGE_VISUAL); _scheduler.CancelGroup(GROUP_EMERGED); _scheduler.CancelGroup(GROUP_PHASE_TRANSITION); if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 10.f)) { base->Use(me); base->DespawnOrUnsummon(6s); } DoCastSelf(SPELL_SUMMON_OURO_MOUNDS, true); // According to sniffs, Ouro uses his mounds to respawn. The health management could be a little scuffed. std::list<Creature*> ouroMounds; me->GetCreatureListWithEntryInGrid(ouroMounds, NPC_DIRT_MOUND, 200.f); if (!ouroMounds.empty()) // This can't be possible, but just to be sure. { if (Creature* mound = Acore::Containers::SelectRandomContainerElement(ouroMounds)) { mound->AddAura(SPELL_SUMMON_OURO_AURA, mound); mound->AI()->SetData(DATA_OURO_HEALTH, me->GetHealth()); } } me->DespawnOrUnsummon(1000); } void CastGroundRupture() { std::list<WorldObject*> targets; Acore::AllWorldObjectsInRange checker(me, 10.0f); Acore::WorldObjectListSearcher<Acore::AllWorldObjectsInRange> searcher(me, targets, checker); Cell::VisitAllObjects(me, searcher, 10.0f); for (WorldObject* target : targets) { if (Unit* unitTarget = target->ToUnit()) { if (unitTarget->IsHostileTo(me)) DoCast(unitTarget, SPELL_GROUND_RUPTURE, true); } } } void SpellHitTarget(Unit* target, SpellInfo const* spellInfo) override { if (spellInfo->Id == SPELL_SAND_BLAST && target) me->GetThreatMgr().ModifyThreatByPercent(target, 100); } void Emerge() { DoCastSelf(SPELL_BIRTH); DoCastSelf(SPELL_SUMMON_SANDWORM_BASE, true); me->SetReactState(REACT_AGGRESSIVE); CastGroundRupture(); _scheduler .Schedule(20s, GROUP_EMERGED, [this](TaskContext context) { DoCastVictim(SPELL_SAND_BLAST); context.Repeat(); }) .Schedule(22s, GROUP_EMERGED, [this](TaskContext context) { DoCastVictim(SPELL_SWEEP); context.Repeat(); }) .Schedule(90s, GROUP_PHASE_TRANSITION, [this](TaskContext /*context*/) { Submerge(); }) .Schedule(3s, GROUP_PHASE_TRANSITION, [this](TaskContext context) { if (_enraged) return; if (!IsPlayerWithinMeleeRange() && !_submerged) { if (_submergeMelee < 10) { _submergeMelee++; } else { Submerge(); _submergeMelee = 0; } } else { _submergeMelee = 0; } if (!_submerged) context.Repeat(1s); }); } void Reset() override { instance->SetBossState(DATA_OURO, NOT_STARTED); _scheduler.CancelAll(); _submergeMelee = 0; _submerged = false; _enraged = false; } void EnterEvadeMode(EvadeReason /*why*/) override { DoCastSelf(SPELL_OURO_SUBMERGE_VISUAL); me->DespawnOrUnsummon(1000); instance->SetBossState(DATA_OURO, FAIL); if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 200.f)) base->DespawnOrUnsummon(); } void EnterCombat(Unit* who) override { Emerge(); BossAI::EnterCombat(who); } void UpdateAI(uint32 diff) override { //Return since we have no target if (!UpdateVictim()) return; _scheduler.Update(diff, [this] { DoMeleeAttackIfReady(); }); } protected: TaskScheduler _scheduler; bool _enraged; uint8 _submergeMelee; bool _submerged; bool IsPlayerWithinMeleeRange() const { return me->IsWithinMeleeRange(me->GetVictim()); } }; struct npc_dirt_mound : ScriptedAI { npc_dirt_mound(Creature* creature) : ScriptedAI(creature) { _instance = creature->GetInstanceScript(); } void JustSummoned(Creature* creature) override { if (creature->GetEntry() == NPC_OURO) { creature->SetInCombatWithZone(); creature->SetHealth(_ouroHealth); creature->LowerPlayerDamageReq(creature->GetMaxHealth() - creature->GetHealth()); } } void SetData(uint32 type, uint32 data) override { if (type == DATA_OURO_HEALTH) _ouroHealth = data; } void EnterCombat(Unit* /*who*/) override { DoZoneInCombat(); _scheduler.Schedule(30s, [this](TaskContext /*context*/) { DoCastSelf(SPELL_SUMMON_SCARABS, true); me->DespawnOrUnsummon(1000); }) .Schedule(100ms, [this](TaskContext context) { ChaseNewTarget(); context.Repeat(5s, 10s); }); } void ChaseNewTarget() { DoResetThreat(); if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 200.f, true)) { me->AddThreat(target, 1000000.f); AttackStart(target); } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _scheduler.Update(diff); } void Reset() override { DoCastSelf(SPELL_DIRTMOUND_PASSIVE, true); DoCastSelf(SPELL_DREAM_FOG, true); DoCastSelf(SPELL_QUAKE, true); } void EnterEvadeMode(EvadeReason /*why*/) override { if (_instance) { _instance->SetBossState(DATA_OURO, FAIL); } if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 200.f)) base->DespawnOrUnsummon(); me->DespawnOrUnsummon(); } protected: TaskScheduler _scheduler; uint32 _ouroHealth; InstanceScript* _instance; }; void AddSC_boss_ouro() { RegisterTempleOfAhnQirajCreatureAI(npc_ouro_spawner); RegisterTempleOfAhnQirajCreatureAI(boss_ouro); RegisterTempleOfAhnQirajCreatureAI(npc_dirt_mound); } <commit_msg>fix(Scripts/TempleOfAhnQiraj): Sand Blast threat-wipe mechanic (#13577)<commit_after>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program 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. * * This program 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 General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Cell.h" #include "CellImpl.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "TaskScheduler.h" #include "temple_of_ahnqiraj.h" enum Spells { // Ouro SPELL_SWEEP = 26103, SPELL_SAND_BLAST = 26102, SPELL_GROUND_RUPTURE = 26100, SPELL_BERSERK = 26615, SPELL_BOULDER = 26616, SPELL_OURO_SUBMERGE_VISUAL = 26063, SPELL_SUMMON_SANDWORM_BASE = 26133, // Misc - Mounds, Ouro Spawner SPELL_BIRTH = 26586, SPELL_DIRTMOUND_PASSIVE = 26092, SPELL_SUMMON_OURO = 26061, SPELL_SUMMON_OURO_MOUNDS = 26058, SPELL_QUAKE = 26093, SPELL_SUMMON_SCARABS = 26060, SPELL_SUMMON_OURO_AURA = 26642, SPELL_DREAM_FOG = 24780 }; enum Misc { GROUP_EMERGED = 0, GROUP_PHASE_TRANSITION = 1, NPC_DIRT_MOUND = 15712, GO_SANDWORM_BASE = 180795, DATA_OURO_HEALTH = 0 }; struct npc_ouro_spawner : public ScriptedAI { npc_ouro_spawner(Creature* creature) : ScriptedAI(creature) { Reset(); } bool hasSummoned; void Reset() override { hasSummoned = false; DoCastSelf(SPELL_DIRTMOUND_PASSIVE); } void MoveInLineOfSight(Unit* who) override { // Spawn Ouro on LoS check if (!hasSummoned && who->GetTypeId() == TYPEID_PLAYER && me->IsWithinDistInMap(who, 40.0f) && !who->ToPlayer()->IsGameMaster()) { if (InstanceScript* instance = me->GetInstanceScript()) { Creature* ouro = instance->GetCreature(DATA_OURO); if (instance->GetBossState(DATA_OURO) != IN_PROGRESS && !ouro) { DoCastSelf(SPELL_SUMMON_OURO); hasSummoned = true; } } } ScriptedAI::MoveInLineOfSight(who); } void JustSummoned(Creature* creature) override { // Despawn when Ouro is spawned if (creature->GetEntry() == NPC_OURO) { creature->SetInCombatWithZone(); me->DespawnOrUnsummon(); } } }; struct boss_ouro : public BossAI { boss_ouro(Creature* creature) : BossAI(creature, DATA_OURO) { SetCombatMovement(false); me->SetControlled(true, UNIT_STATE_ROOT); _scheduler.SetValidator([this] { return !me->HasUnitState(UNIT_STATE_CASTING); }); } void DamageTaken(Unit* /*attacker*/, uint32& damage, DamageEffectType, SpellSchoolMask) override { if (me->HealthBelowPctDamaged(20, damage) && !_enraged) { DoCastSelf(SPELL_BERSERK, true); _enraged = true; _scheduler.CancelGroup(GROUP_PHASE_TRANSITION); _scheduler.Schedule(1s, [this](TaskContext context) { if (!IsPlayerWithinMeleeRange()) DoSpellAttackToRandomTargetIfReady(SPELL_BOULDER); context.Repeat(); }) .Schedule(20s, [this](TaskContext context) { DoCastSelf(SPELL_SUMMON_OURO_MOUNDS, true); context.Repeat(); }); } } void Submerge() { if (_enraged || _submerged) return; me->AttackStop(); me->SetReactState(REACT_PASSIVE); me->SetUnitFlag(UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); _submergeMelee = 0; _submerged = true; DoCastSelf(SPELL_OURO_SUBMERGE_VISUAL); _scheduler.CancelGroup(GROUP_EMERGED); _scheduler.CancelGroup(GROUP_PHASE_TRANSITION); if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 10.f)) { base->Use(me); base->DespawnOrUnsummon(6s); } DoCastSelf(SPELL_SUMMON_OURO_MOUNDS, true); // According to sniffs, Ouro uses his mounds to respawn. The health management could be a little scuffed. std::list<Creature*> ouroMounds; me->GetCreatureListWithEntryInGrid(ouroMounds, NPC_DIRT_MOUND, 200.f); if (!ouroMounds.empty()) // This can't be possible, but just to be sure. { if (Creature* mound = Acore::Containers::SelectRandomContainerElement(ouroMounds)) { mound->AddAura(SPELL_SUMMON_OURO_AURA, mound); mound->AI()->SetData(DATA_OURO_HEALTH, me->GetHealth()); } } me->DespawnOrUnsummon(1000); } void CastGroundRupture() { std::list<WorldObject*> targets; Acore::AllWorldObjectsInRange checker(me, 10.0f); Acore::WorldObjectListSearcher<Acore::AllWorldObjectsInRange> searcher(me, targets, checker); Cell::VisitAllObjects(me, searcher, 10.0f); for (WorldObject* target : targets) { if (Unit* unitTarget = target->ToUnit()) { if (unitTarget->IsHostileTo(me)) DoCast(unitTarget, SPELL_GROUND_RUPTURE, true); } } } void SpellHitTarget(Unit* target, SpellInfo const* spellInfo) override { if (spellInfo->Id == SPELL_SAND_BLAST && target) { me->GetThreatMgr().ModifyThreatByPercent(target, -100); } } void Emerge() { DoCastSelf(SPELL_BIRTH); DoCastSelf(SPELL_SUMMON_SANDWORM_BASE, true); me->SetReactState(REACT_AGGRESSIVE); CastGroundRupture(); _scheduler .Schedule(20s, GROUP_EMERGED, [this](TaskContext context) { DoCastVictim(SPELL_SAND_BLAST); context.Repeat(); }) .Schedule(22s, GROUP_EMERGED, [this](TaskContext context) { DoCastVictim(SPELL_SWEEP); context.Repeat(); }) .Schedule(90s, GROUP_PHASE_TRANSITION, [this](TaskContext /*context*/) { Submerge(); }) .Schedule(3s, GROUP_PHASE_TRANSITION, [this](TaskContext context) { if (_enraged) return; if (!IsPlayerWithinMeleeRange() && !_submerged) { if (_submergeMelee < 10) { _submergeMelee++; } else { Submerge(); _submergeMelee = 0; } } else { _submergeMelee = 0; } if (!_submerged) context.Repeat(1s); }); } void Reset() override { instance->SetBossState(DATA_OURO, NOT_STARTED); _scheduler.CancelAll(); _submergeMelee = 0; _submerged = false; _enraged = false; } void EnterEvadeMode(EvadeReason /*why*/) override { DoCastSelf(SPELL_OURO_SUBMERGE_VISUAL); me->DespawnOrUnsummon(1000); instance->SetBossState(DATA_OURO, FAIL); if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 200.f)) base->DespawnOrUnsummon(); } void EnterCombat(Unit* who) override { Emerge(); BossAI::EnterCombat(who); } void UpdateAI(uint32 diff) override { //Return since we have no target if (!UpdateVictim()) return; _scheduler.Update(diff, [this] { DoMeleeAttackIfReady(); }); } protected: TaskScheduler _scheduler; bool _enraged; uint8 _submergeMelee; bool _submerged; bool IsPlayerWithinMeleeRange() const { return me->IsWithinMeleeRange(me->GetVictim()); } }; struct npc_dirt_mound : ScriptedAI { npc_dirt_mound(Creature* creature) : ScriptedAI(creature) { _instance = creature->GetInstanceScript(); } void JustSummoned(Creature* creature) override { if (creature->GetEntry() == NPC_OURO) { creature->SetInCombatWithZone(); creature->SetHealth(_ouroHealth); creature->LowerPlayerDamageReq(creature->GetMaxHealth() - creature->GetHealth()); } } void SetData(uint32 type, uint32 data) override { if (type == DATA_OURO_HEALTH) _ouroHealth = data; } void EnterCombat(Unit* /*who*/) override { DoZoneInCombat(); _scheduler.Schedule(30s, [this](TaskContext /*context*/) { DoCastSelf(SPELL_SUMMON_SCARABS, true); me->DespawnOrUnsummon(1000); }) .Schedule(100ms, [this](TaskContext context) { ChaseNewTarget(); context.Repeat(5s, 10s); }); } void ChaseNewTarget() { DoResetThreat(); if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 200.f, true)) { me->AddThreat(target, 1000000.f); AttackStart(target); } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _scheduler.Update(diff); } void Reset() override { DoCastSelf(SPELL_DIRTMOUND_PASSIVE, true); DoCastSelf(SPELL_DREAM_FOG, true); DoCastSelf(SPELL_QUAKE, true); } void EnterEvadeMode(EvadeReason /*why*/) override { if (_instance) { _instance->SetBossState(DATA_OURO, FAIL); } if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 200.f)) base->DespawnOrUnsummon(); me->DespawnOrUnsummon(); } protected: TaskScheduler _scheduler; uint32 _ouroHealth; InstanceScript* _instance; }; void AddSC_boss_ouro() { RegisterTempleOfAhnQirajCreatureAI(npc_ouro_spawner); RegisterTempleOfAhnQirajCreatureAI(boss_ouro); RegisterTempleOfAhnQirajCreatureAI(npc_dirt_mound); } <|endoftext|>
<commit_before>// Test ../include/Spectra/LinAlg/BKLDLT.h #include <Eigen/Core> #include <Spectra/LinAlg/BKLDLT.h> using namespace Spectra; #define CATCH_CONFIG_MAIN #include "catch.hpp" using Eigen::MatrixXd; using Eigen::VectorXd; // Solve (A - s * I)x = b void run_test(const MatrixXd& A, const VectorXd& b, double s) { BKLDLT<double> decompL(A, Eigen::Lower, s); REQUIRE(decompL.info() == SUCCESSFUL); BKLDLT<double> decompU(A, Eigen::Upper, s); REQUIRE( decompU.info() == SUCCESSFUL ); VectorXd solL = decompL.solve(b); VectorXd solU = decompU.solve(b); REQUIRE( (solL - solU).cwiseAbs().maxCoeff() == 0.0 ); const double tol = 1e-9; VectorXd resid = A * solL - s * solL - b; INFO( "||(A - s * I)x - b||_inf = " << resid.cwiseAbs().maxCoeff() ); REQUIRE( resid.cwiseAbs().maxCoeff() == Approx(0.0).margin(tol) ); } TEST_CASE("BKLDLT decomposition of symmetric real matrix [10x10]", "[BKLDLT]") { std::srand(123); const int n = 10; MatrixXd A = MatrixXd::Random(n, n); A = (A + A.transpose()).eval(); VectorXd b = VectorXd::Random(n); const double shift = 1.0; run_test(A, b, shift); } TEST_CASE("BKLDLT decomposition of symmetric real matrix [100x100]", "[BKLDLT]") { std::srand(123); const int n = 100; MatrixXd A = MatrixXd::Random(n, n); A = (A + A.transpose()).eval(); VectorXd b = VectorXd::Random(n); const double shift = 1.0; run_test(A, b, shift); } TEST_CASE("BKLDLT decomposition of symmetric real matrix [1000x1000]", "[BKLDLT]") { std::srand(123); const int n = 1000; MatrixXd A = MatrixXd::Random(n, n); A = (A + A.transpose()).eval(); VectorXd b = VectorXd::Random(n); const double shift = 1.0; run_test(A, b, shift); } <commit_msg>Test bugfix bkldlt on (Travis) Linux.<commit_after>// Test ../include/Spectra/LinAlg/BKLDLT.h #include <Eigen/Core> #include <Spectra/LinAlg/BKLDLT.h> using namespace Spectra; #define CATCH_CONFIG_MAIN #include "catch.hpp" using Eigen::MatrixXd; using Eigen::VectorXd; // Solve (A - s * I)x = b void run_test(const MatrixXd& A, const VectorXd& b, double s) { BKLDLT<double> decompL(A, Eigen::Lower, s); REQUIRE(decompL.info() == SUCCESSFUL); BKLDLT<double> decompU(A, Eigen::Upper, s); REQUIRE( decompU.info() == SUCCESSFUL ); VectorXd solL = decompL.solve(b); VectorXd solU = decompU.solve(b); REQUIRE( (solL - solU).cwiseAbs().maxCoeff() == 0.0 ); const double tol = 1e-9; VectorXd resid = A * solL - s * solL - b; INFO( "||(A - s * I)x - b||_inf = " << resid.cwiseAbs().maxCoeff() ); REQUIRE( resid.cwiseAbs().maxCoeff() == Approx(0.0).margin(tol) ); } TEST_CASE("BKLDLT decomposition of symmetric real matrix [10x10]", "[BKLDLT]") { std::srand(123); const int n = 10; MatrixXd A = MatrixXd::Random(n, n); A = (A + A.transpose()).eval(); VectorXd b = VectorXd::Random(n); const double shift = 1.0; run_test(A, b, shift); } TEST_CASE("BKLDLT decomposition of symmetric real matrix [100x100]", "[BKLDLT]") { std::srand(123); const int n = 100; MatrixXd A = MatrixXd::Random(n, n); A = (A + A.transpose()).eval(); VectorXd b = VectorXd::Random(n); const double shift = 1.0; run_test(A, b, shift); } TEST_CASE("BKLDLT decomposition of symmetric real matrix [1000x1000]", "[BKLDLT]") { std::srand(3); const int n = 1000; MatrixXd A = MatrixXd::Random(n, n); A = (A + A.transpose()).eval(); VectorXd b = VectorXd::Random(n); const double shift = 1.0; run_test(A, b, shift); } <|endoftext|>
<commit_before>#include "jsaubase.h" #include <cmath> #include <set> using namespace std; // PARAMETERS GO HERE enum { kParam_VolumeLevel }; // PROPERTIES GO HERE // see oscilloscope example for how to use these - this // simple volume example has none. enum { }; class Audio; // This is the main plug in class. class Audio : public JSAudioUnitBase { public: Audio(AudioUnit component); virtual OSStatus Version() { return 0xFFFFFF; } virtual OSStatus GetProperty(AudioUnitPropertyID id, AudioUnitScope scope, AudioUnitElement elem, void* data); virtual OSStatus GetPropertyInfo (AudioUnitPropertyID id, AudioUnitScope scope, AudioUnitElement elem, UInt32 & size, Boolean & writable); virtual OSStatus GetParameterInfo( AudioUnitScope inScope, AudioUnitParameterID inParameterID, AudioUnitParameterInfo &outParameterInfo ); virtual UInt32 SupportedNumChannels (const AUChannelInfo** outInfo); virtual OSStatus Reset( AudioUnitScope inScope, AudioUnitElement inElement); virtual OSStatus ProcessBufferLists (AudioUnitRenderActionFlags& ioActionFlags, const AudioBufferList& inBuffer, AudioBufferList& outBuffer, UInt32 numSamples); virtual OSStatus HandleNoteOn(UInt8 inChannel, UInt8 inNoteNumber, UInt8 inVelocity, UInt32 inStartFrame); virtual OSStatus HandleNoteOff(UInt8 inChannel, UInt8 inNoteNumber, UInt8 inVelocity, UInt32 inStartFrame); virtual vector<JSPropDesc> GetPropertyDescriptionList(); private: set<uint8_t> mActiveKeys; vector<pair<uint32_t, pair<bool, uint8_t> > > mNoteEventsToHandle; double mPhase; double mPhaseIncr; }; // this boilerplate has to be here so that the system can know about the // class we just made. AUDIOCOMPONENT_ENTRY(AUMIDIEffectFactory, Audio) void DoRegister(OSType Type, OSType Subtype, OSType Manufacturer, CFStringRef name, UInt32 vers) { AUMIDIEffectFactory<Audio>::Register(Type, Subtype, Manufacturer, name, vers, 0); } Audio::Audio(AudioUnit component) : JSAudioUnitBase(component) { SetParameter(kParam_VolumeLevel, 0.5); } // Processing stuff. // this lets the host know how many channels are allowed. // return 0 to indicate that this is an N-to-N effect. UInt32 Audio::SupportedNumChannels (const AUChannelInfo** outInfo) { /* //this is how you would indicate that this is a stereo-in/stereo-out effect: static const AUChannelInfo channelConfigs[] = {{2,2}}; if(outInfo) *outInfo = channelConfigs; return sizeof(channelConfigs)/sizeof(AUChannelInfo); */ // this indicates we are an N-to-N effect. return 0; } // Reset the state of any reverb tails, etc. OSStatus Audio::Reset( AudioUnitScope inScope, AudioUnitElement inElement) { mActiveKeys.clear(); mPhase = 0; mPhaseIncr = 0; mNoteEventsToHandle.clear(); return noErr; }; OSStatus Audio::ProcessBufferLists (AudioUnitRenderActionFlags& ioActionFlags, const AudioBufferList& inBuffer, AudioBufferList& outBuffer, UInt32 numSamples) { // watch out! buffers could be interleaved or not interleaved! SInt16 channels = GetOutput(0)->GetStreamFormat().mChannelsPerFrame; // check for silence bool silentInput = IsInputSilent (ioActionFlags, numSamples); if(silentInput) { ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence; return noErr; } // Gather per-buffer parameters here double v = GetParameter(kParam_VolumeLevel); // bind v to 1.0 v = fmin(fmax(v, 0.0), 1.0); auto noteIt = mNoteEventsToHandle.begin(); // do processing here. for(int s = 0; s < numSamples; ++s) { // handle any note messages! while(noteIt != mNoteEventsToHandle.end() and noteIt->first <= s) { if(noteIt->second.first) mActiveKeys.insert(noteIt->second.second); else mActiveKeys.erase(noteIt->second.second); if(mActiveKeys.size()){ auto topNote = mActiveKeys.end(); --topNote; // equal temperament equation. double freq = pow(2, (static_cast<double>(*topNote) - 69) / 12) * 440; mPhaseIncr = freq / GetSampleRate(); } else { mPhaseIncr = 0; } ++noteIt; } mPhase += mPhaseIncr; if(mPhase > 1) mPhase -= 1; for(int b = 0; b < inBuffer.mNumberBuffers; ++b) { UInt32 numChans = inBuffer.mBuffers[b].mNumberChannels; for(int c = 0; c < numChans; ++c) { UInt32 chan = (b*numChans) + c; // Per-sample processing here Float32& inSamp = reinterpret_cast<Float32*>(inBuffer.mBuffers[b].mData)[s*numChans + c]; Float32& outSamp = reinterpret_cast<Float32*>(outBuffer.mBuffers[b].mData)[s*numChans + c]; if(mPhaseIncr > 0) outSamp = sin(mPhase * 2 * 3.145159) * v; else outSamp = 0; //end per-sample processing } } } mNoteEventsToHandle.clear(); return noErr; } OSStatus Audio::HandleNoteOn(UInt8 inChannel, UInt8 inNoteNumber, UInt8 inVelocity, UInt32 inStartFrame) { mNoteEventsToHandle.push_back(make_pair(inStartFrame, make_pair(inVelocity, inNoteNumber))); return noErr; } OSStatus Audio::HandleNoteOff(UInt8 inChannel, UInt8 inNoteNumber, UInt8 inVelocity, UInt32 inStartFrame) { mNoteEventsToHandle.push_back(make_pair(inStartFrame, make_pair(false, inNoteNumber))); return noErr; } // Parameter stuff OSStatus Audio::GetParameterInfo( AudioUnitScope inScope, AudioUnitParameterID inParameterID, AudioUnitParameterInfo &outParameterInfo ) { OSStatus result = noErr; outParameterInfo.flags = kAudioUnitParameterFlag_IsWritable + kAudioUnitParameterFlag_IsReadable; if (inScope == kAudioUnitScope_Global) { switch(inParameterID) { case kParam_VolumeLevel: AUBase::FillInParameterName (outParameterInfo, CFSTR("Volume"), false); outParameterInfo.unit = kAudioUnitParameterUnit_LinearGain; outParameterInfo.minValue = 0.0; outParameterInfo.maxValue = 1.0; outParameterInfo.defaultValue = 0; outParameterInfo.flags += kAudioUnitParameterFlag_IsHighResolution; break; default: result = kAudioUnitErr_InvalidParameter; break; } } else { result = kAudioUnitErr_InvalidParameter; } return result; } // Property stuff // this lets javascript know which properties are available. vector<JSPropDesc> Audio::GetPropertyDescriptionList() { vector<JSPropDesc> propList; // currently no properties return propList; } // this gets the size and writability of individual properties OSStatus Audio::GetPropertyInfo (AudioUnitPropertyID id, AudioUnitScope scope, AudioUnitElement elem, UInt32 & size, Boolean & writable) { if(scope == kAudioUnitScope_Global) { // you'd fill in property information here. } return JSAudioUnitBase::GetPropertyInfo(id, scope, elem, size, writable); } // this actually gets the properties OSStatus Audio::GetProperty(AudioUnitPropertyID id, AudioUnitScope scope, AudioUnitElement elem, void* data) { if (scope == kAudioUnitScope_Global) { // you'd fill in the property here - see the oscilloscope example // for information on how. } return JSAudioUnitBase::GetProperty(id, scope, elem, data); } <commit_msg>interleaved<commit_after>#include "jsaubase.h" #include <cmath> #include <set> using namespace std; // PARAMETERS GO HERE enum { kParam_VolumeLevel }; // PROPERTIES GO HERE // see oscilloscope example for how to use these - this // simple volume example has none. enum { }; class Audio; // This is the main plug in class. class Audio : public JSAudioUnitBase { public: Audio(AudioUnit component); virtual OSStatus Version() { return 0xFFFFFF; } virtual OSStatus GetProperty(AudioUnitPropertyID id, AudioUnitScope scope, AudioUnitElement elem, void* data); virtual OSStatus GetPropertyInfo (AudioUnitPropertyID id, AudioUnitScope scope, AudioUnitElement elem, UInt32 & size, Boolean & writable); virtual OSStatus GetParameterInfo( AudioUnitScope inScope, AudioUnitParameterID inParameterID, AudioUnitParameterInfo &outParameterInfo ); virtual UInt32 SupportedNumChannels (const AUChannelInfo** outInfo); virtual OSStatus Reset( AudioUnitScope inScope, AudioUnitElement inElement); virtual OSStatus ProcessBufferLists (AudioUnitRenderActionFlags& ioActionFlags, const AudioBufferList& inBuffer, AudioBufferList& outBuffer, UInt32 numSamples); virtual OSStatus HandleNoteOn(UInt8 inChannel, UInt8 inNoteNumber, UInt8 inVelocity, UInt32 inStartFrame); virtual OSStatus HandleNoteOff(UInt8 inChannel, UInt8 inNoteNumber, UInt8 inVelocity, UInt32 inStartFrame); virtual vector<JSPropDesc> GetPropertyDescriptionList(); private: set<uint8_t> mActiveKeys; vector<pair<uint32_t, pair<bool, uint8_t> > > mNoteEventsToHandle; double mPhase; double mPhaseIncr; }; // this boilerplate has to be here so that the system can know about the // class we just made. AUDIOCOMPONENT_ENTRY(AUMIDIEffectFactory, Audio) void DoRegister(OSType Type, OSType Subtype, OSType Manufacturer, CFStringRef name, UInt32 vers) { AUMIDIEffectFactory<Audio>::Register(Type, Subtype, Manufacturer, name, vers, 0); } Audio::Audio(AudioUnit component) : JSAudioUnitBase(component) { SetParameter(kParam_VolumeLevel, 0.5); } // Processing stuff. // this lets the host know how many channels are allowed. // return 0 to indicate that this is an N-to-N effect. UInt32 Audio::SupportedNumChannels (const AUChannelInfo** outInfo) { /* //this is how you would indicate that this is a stereo-in/stereo-out effect: static const AUChannelInfo channelConfigs[] = {{2,2}}; if(outInfo) *outInfo = channelConfigs; return sizeof(channelConfigs)/sizeof(AUChannelInfo); */ // this indicates we are an N-to-N effect. return 0; } // Reset the state of any reverb tails, etc. OSStatus Audio::Reset( AudioUnitScope inScope, AudioUnitElement inElement) { mActiveKeys.clear(); mPhase = 0; mPhaseIncr = 0; mNoteEventsToHandle.clear(); return noErr; }; OSStatus Audio::ProcessBufferLists (AudioUnitRenderActionFlags& ioActionFlags, const AudioBufferList& inBuffer, AudioBufferList& outBuffer, UInt32 numSamples) { // Gather per-buffer parameters here double v = GetParameter(kParam_VolumeLevel); // bind v to 1.0 v = fmin(fmax(v, 0.0), 1.0); auto noteIt = mNoteEventsToHandle.begin(); // do processing here. for(int s = 0; s < numSamples; ++s) { // handle any note messages! while(noteIt != mNoteEventsToHandle.end() and noteIt->first <= s) { if(noteIt->second.first) mActiveKeys.insert(noteIt->second.second); else mActiveKeys.erase(noteIt->second.second); if(mActiveKeys.size()){ auto topNote = mActiveKeys.end(); --topNote; // equal temperament equation. double freq = pow(2, (static_cast<double>(*topNote) - 69) / 12) * 440; mPhaseIncr = freq / GetSampleRate(); } else { mPhaseIncr = 0; } ++noteIt; } mPhase += mPhaseIncr; if(mPhase > 1) mPhase -= 1; for(int b = 0; b < inBuffer.mNumberBuffers; ++b) { // Per-sample processing here Float32& inSamp = reinterpret_cast<Float32*>(inBuffer.mBuffers[b].mData)[s]; Float32& outSamp = reinterpret_cast<Float32*>(outBuffer.mBuffers[b].mData)[s]; if(mPhaseIncr > 0) outSamp = sin(mPhase * 2 * 3.145159) * v; else outSamp = 0; //end per-sample processing } } mNoteEventsToHandle.clear(); return noErr; } OSStatus Audio::HandleNoteOn(UInt8 inChannel, UInt8 inNoteNumber, UInt8 inVelocity, UInt32 inStartFrame) { mNoteEventsToHandle.push_back(make_pair(inStartFrame, make_pair(inVelocity, inNoteNumber))); return noErr; } OSStatus Audio::HandleNoteOff(UInt8 inChannel, UInt8 inNoteNumber, UInt8 inVelocity, UInt32 inStartFrame) { mNoteEventsToHandle.push_back(make_pair(inStartFrame, make_pair(false, inNoteNumber))); return noErr; } // Parameter stuff OSStatus Audio::GetParameterInfo( AudioUnitScope inScope, AudioUnitParameterID inParameterID, AudioUnitParameterInfo &outParameterInfo ) { OSStatus result = noErr; outParameterInfo.flags = kAudioUnitParameterFlag_IsWritable + kAudioUnitParameterFlag_IsReadable; if (inScope == kAudioUnitScope_Global) { switch(inParameterID) { case kParam_VolumeLevel: AUBase::FillInParameterName (outParameterInfo, CFSTR("Volume"), false); outParameterInfo.unit = kAudioUnitParameterUnit_LinearGain; outParameterInfo.minValue = 0.0; outParameterInfo.maxValue = 1.0; outParameterInfo.defaultValue = 0; outParameterInfo.flags += kAudioUnitParameterFlag_IsHighResolution; break; default: result = kAudioUnitErr_InvalidParameter; break; } } else { result = kAudioUnitErr_InvalidParameter; } return result; } // Property stuff // this lets javascript know which properties are available. vector<JSPropDesc> Audio::GetPropertyDescriptionList() { vector<JSPropDesc> propList; // currently no properties return propList; } // this gets the size and writability of individual properties OSStatus Audio::GetPropertyInfo (AudioUnitPropertyID id, AudioUnitScope scope, AudioUnitElement elem, UInt32 & size, Boolean & writable) { if(scope == kAudioUnitScope_Global) { // you'd fill in property information here. } return JSAudioUnitBase::GetPropertyInfo(id, scope, elem, size, writable); } // this actually gets the properties OSStatus Audio::GetProperty(AudioUnitPropertyID id, AudioUnitScope scope, AudioUnitElement elem, void* data) { if (scope == kAudioUnitScope_Global) { // you'd fill in the property here - see the oscilloscope example // for information on how. } return JSAudioUnitBase::GetProperty(id, scope, elem, data); } <|endoftext|>
<commit_before>//----------------------------------------------------------- // // Copyright (C) 2015 by the deal2lkit authors // // This file is part of the deal2lkit library. // // The deal2lkit library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal2lkit distribution. // //----------------------------------------------------------- #include <deal2lkit/parameter_acceptor.h> #include <deal2lkit/parsed_grid_generator.h> #include <deal2lkit/parsed_finite_element.h> #include <deal2lkit/parsed_data_out.h> #include <deal2lkit/parsed_dirichlet_bcs.h> #include <deal2lkit/error_handler.h> #include <deal2lkit/parsed_solver.h> #include <deal2lkit/utilities.h> #include <deal.II/lac/sparse_direct.h> #include <deal.II/lac/precondition.h> #include <deal.II/lac/sparsity_pattern.h> #include <deal.II/lac/dynamic_sparsity_pattern.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/lac/vector.h> #include <deal.II/lac/constraint_matrix.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/numerics/matrix_tools.h> #include <deal.II/lac/linear_operator.h> #include <deal.II/lac/packaged_operation.h> #include <fstream> using namespace deal2lkit; using namespace dealii; /** Solve the problem * * \f[ * -\nabla\cdot(kappa \nabla u) = f * \f] */ class PoissonParameters : public ParameterAcceptor { public: virtual void declare_parameters(ParameterHandler &prm) { add_parameter(prm, &n_cycles, "Number of cycles", "4"); add_parameter(prm, &initial_refinement, "Initial refinement", "3"); } unsigned int n_cycles; unsigned int initial_refinement; }; int main(int argc, char **argv) { Utilities::MPI::MPI_InitFinalize mpi_init(argc, argv); // Change this if you want a three dimensional simulation const unsigned int dim = 2; const unsigned int spacedim = 2; PoissonParameters par; ParsedGridGenerator<dim,spacedim> pgg; ParsedFiniteElement<dim,spacedim> pfe; ParsedDirichletBCs<dim,dim,1> bcs; ParsedFunction<spacedim> kappa("Kappa", "1.0"); ParsedFunction<spacedim> force("Forcing term"); ParsedFunction<spacedim> exact("Exact solution"); SparsityPattern sparsity; SparseMatrix<double> matrix; ConstraintMatrix constraints; Vector<double> solution; Vector<double> rhs; PreconditionIdentity prec; ParsedSolver<Vector<double> > inverse("Solver", "cg", 1000, 1e-8, linear_operator<Vector<double> >(matrix), linear_operator<Vector<double> >(matrix, prec)); shared_ptr<Triangulation<dim,spacedim> > tria; shared_ptr<FiniteElement<dim,spacedim> > fe; ErrorHandler<1> eh; ParsedDataOut<dim,spacedim> pdo; // Generate Triangulation, DoFHandler, and FE ParameterAcceptor::initialize("poisson.prm", "used_parameters.prm"); tria = SP(pgg.serial()); pgg.write(*tria); fe = SP(pfe()); DoFHandler<dim,spacedim> dh(*tria); tria->refine_global(par.initial_refinement); QGauss<dim> quad(2*fe->degree+1); for (unsigned int i=0; i<par.n_cycles; ++i) { dh.distribute_dofs(*fe); std::cout << "Cycle " << i << ", cells: " << tria->n_active_cells() << ", dofs: " << dh.n_dofs() << std::endl; DynamicSparsityPattern dsp(dh.n_dofs()); DoFTools::make_sparsity_pattern (dh, dsp); sparsity.copy_from(dsp); matrix.reinit (sparsity); solution.reinit (dh.n_dofs()); rhs.reinit (dh.n_dofs()); constraints.clear(); bcs.interpolate_boundary_values(dh, constraints); constraints.close(); MatrixCreator::create_laplace_matrix(dh, quad, matrix, force, rhs, &kappa); constraints.condense(matrix, rhs); // solution = inverse*rhs; SparseDirectUMFPACK solver; solver.initialize(matrix); solver.vmult(solution, rhs); constraints.distribute(solution); pdo.prepare_data_output(dh, std::to_string(i)); pdo.add_data_vector(solution, "solution"); pdo.write_data_and_clear(); eh.error_from_exact(dh, solution, exact); tria->refine_global(1); } eh.output_table(); return 0; } <commit_msg>Made use of parsed solver and sparse ILU.<commit_after>//----------------------------------------------------------- // // Copyright (C) 2015 by the deal2lkit authors // // This file is part of the deal2lkit library. // // The deal2lkit library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal2lkit distribution. // //----------------------------------------------------------- #include <deal2lkit/parameter_acceptor.h> #include <deal2lkit/parsed_grid_generator.h> #include <deal2lkit/parsed_finite_element.h> #include <deal2lkit/parsed_data_out.h> #include <deal2lkit/parsed_dirichlet_bcs.h> #include <deal2lkit/error_handler.h> #include <deal2lkit/parsed_solver.h> #include <deal2lkit/utilities.h> #include <deal.II/lac/sparse_ilu.h> #include <deal.II/lac/precondition.h> #include <deal.II/lac/sparsity_pattern.h> #include <deal.II/lac/dynamic_sparsity_pattern.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/lac/vector.h> #include <deal.II/lac/constraint_matrix.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/numerics/matrix_tools.h> #include <deal.II/lac/linear_operator.h> #include <deal.II/lac/packaged_operation.h> #include <fstream> using namespace deal2lkit; using namespace dealii; /** Solve the problem * * \f[ * -\nabla\cdot(kappa \nabla u) = f * \f] */ class PoissonParameters : public ParameterAcceptor { public: virtual void declare_parameters(ParameterHandler &prm) { add_parameter(prm, &n_cycles, "Number of cycles", "4"); add_parameter(prm, &initial_refinement, "Initial refinement", "3"); } unsigned int n_cycles; unsigned int initial_refinement; }; int main(int argc, char **argv) { Utilities::MPI::MPI_InitFinalize mpi_init(argc, argv); // Change this if you want a three dimensional simulation const unsigned int dim = 2; const unsigned int spacedim = 2; PoissonParameters par; ParsedGridGenerator<dim,spacedim> pgg; ParsedFiniteElement<dim,spacedim> pfe; ParsedDirichletBCs<dim,dim,1> bcs; ParsedFunction<spacedim> kappa("Kappa", "1.0"); ParsedFunction<spacedim> force("Forcing term"); ParsedFunction<spacedim> exact("Exact solution"); SparsityPattern sparsity; SparseMatrix<double> matrix; ConstraintMatrix constraints; Vector<double> solution; Vector<double> rhs; SparseILU<double> prec; ParsedSolver<Vector<double> > inverse("Solver", "cg", 1000, 1e-8, linear_operator<Vector<double> >(matrix), linear_operator<Vector<double> >(matrix, prec)); shared_ptr<Triangulation<dim,spacedim> > tria; shared_ptr<FiniteElement<dim,spacedim> > fe; ErrorHandler<1> eh; ParsedDataOut<dim,spacedim> pdo; // Generate Triangulation, DoFHandler, and FE ParameterAcceptor::initialize("poisson.prm", "used_parameters.prm"); tria = SP(pgg.serial()); pgg.write(*tria); fe = SP(pfe()); DoFHandler<dim,spacedim> dh(*tria); tria->refine_global(par.initial_refinement); QGauss<dim> quad(2*fe->degree+1); for (unsigned int i=0; i<par.n_cycles; ++i) { dh.distribute_dofs(*fe); std::cout << "Cycle " << i << ", cells: " << tria->n_active_cells() << ", dofs: " << dh.n_dofs() << std::endl; DynamicSparsityPattern dsp(dh.n_dofs()); DoFTools::make_sparsity_pattern (dh, dsp); sparsity.copy_from(dsp); matrix.reinit (sparsity); solution.reinit (dh.n_dofs()); rhs.reinit (dh.n_dofs()); constraints.clear(); bcs.interpolate_boundary_values(dh, constraints); constraints.close(); MatrixCreator::create_laplace_matrix(dh, quad, matrix, force, rhs, &kappa); constraints.condense(matrix, rhs); prec.initialize(matrix); solution = inverse*rhs; constraints.distribute(solution); pdo.prepare_data_output(dh, std::to_string(i)); pdo.add_data_vector(solution, "solution"); pdo.write_data_and_clear(); eh.error_from_exact(dh, solution, exact); tria->refine_global(1); } eh.output_table(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2021-present ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "generic_server.hh" #include "to_string.hh" #include <seastar/core/when_all.hh> #include <seastar/core/reactor.hh> namespace generic_server { connection::connection(server& server, connected_socket&& fd) : _server{server} , _fd{std::move(fd)} , _read_buf(_fd.input()) , _write_buf(_fd.output()) { ++_server._total_connections; ++_server._current_connections; _server._connections_list.push_back(*this); } connection::~connection() { --_server._current_connections; _server._connections_list.erase(_server._connections_list.iterator_to(*this)); _server.maybe_stop(); } static bool is_broken_pipe_or_connection_reset(std::exception_ptr ep) { try { std::rethrow_exception(ep); } catch (const std::system_error& e) { return e.code().category() == std::system_category() && (e.code().value() == EPIPE || e.code().value() == ECONNRESET); } catch (...) {} return false; } future<> connection::process() { return with_gate(_pending_requests_gate, [this] { return do_until([this] { return _read_buf.eof(); }, [this] { return process_request(); }).then_wrapped([this] (future<> f) { handle_error(std::move(f)); }); }).finally([this] { return _pending_requests_gate.close().then([this] { on_connection_close(); return _ready_to_respond.handle_exception([] (std::exception_ptr ep) { if (is_broken_pipe_or_connection_reset(ep)) { // expected if another side closes a connection or we're shutting down return; } std::rethrow_exception(ep); }).finally([this] { return _write_buf.close(); }); }); }); } void connection::on_connection_close() { } future<> connection::shutdown() { try { _fd.shutdown_input(); _fd.shutdown_output(); } catch (...) { } return make_ready_future<>(); } server::server(const sstring& server_name, logging::logger& logger) : _server_name{server_name} , _logger{logger} { } server::~server() { } future<> server::stop() { _stopping = true; size_t nr = 0; size_t nr_total = _listeners.size(); _logger.debug("abort accept nr_total={}", nr_total); for (auto&& l : _listeners) { l.abort_accept(); _logger.debug("abort accept {} out of {} done", ++nr, nr_total); } auto nr_conn = make_lw_shared<size_t>(0); auto nr_conn_total = _connections_list.size(); _logger.debug("shutdown connection nr_total={}", nr_conn_total); return parallel_for_each(_connections_list.begin(), _connections_list.end(), [this, nr_conn, nr_conn_total] (auto&& c) { return c.shutdown().then([this, nr_conn, nr_conn_total] { _logger.debug("shutdown connection {} out of {} done", ++(*nr_conn), nr_conn_total); }); }).then([this] { return std::move(_stopped); }); } future<> server::listen(socket_address addr, std::shared_ptr<seastar::tls::credentials_builder> creds, bool is_shard_aware, bool keepalive) { auto f = make_ready_future<shared_ptr<seastar::tls::server_credentials>>(nullptr); if (creds) { f = creds->build_reloadable_server_credentials([this](const std::unordered_set<sstring>& files, std::exception_ptr ep) { if (ep) { _logger.warn("Exception loading {}: {}", files, ep); } else { _logger.info("Reloaded {}", files); } }); } return f.then([this, addr, is_shard_aware, keepalive](shared_ptr<seastar::tls::server_credentials> creds) { listen_options lo; lo.reuse_address = true; if (is_shard_aware) { lo.lba = server_socket::load_balancing_algorithm::port; } server_socket ss; try { ss = creds ? seastar::tls::listen(std::move(creds), addr, lo) : seastar::listen(addr, lo); } catch (...) { throw std::runtime_error(format("{} error while listening on {} -> {}", _server_name, addr, std::current_exception())); } _listeners.emplace_back(std::move(ss)); _stopped = when_all(std::move(_stopped), do_accepts(_listeners.size() - 1, keepalive, addr)).discard_result(); }); } future<> server::do_accepts(int which, bool keepalive, socket_address server_addr) { return repeat([this, which, keepalive, server_addr] { ++_connections_being_accepted; return _listeners[which].accept().then_wrapped([this, which, keepalive, server_addr] (future<accept_result> f_cs_sa) mutable { --_connections_being_accepted; if (_stopping) { f_cs_sa.ignore_ready_future(); maybe_stop(); return stop_iteration::yes; } auto cs_sa = f_cs_sa.get0(); auto fd = std::move(cs_sa.connection); auto addr = std::move(cs_sa.remote_address); fd.set_nodelay(true); fd.set_keepalive(keepalive); auto conn = make_connection(server_addr, std::move(fd), std::move(addr)); // Move the processing into the background. (void)futurize_invoke([this, conn] { return advertise_new_connection(conn); // Notify any listeners about new connection. }).then_wrapped([this, conn] (future<> f) { try { f.get(); } catch (...) { _logger.info("exception while advertising new connection: {}", std::current_exception()); } // Block while monitoring for lifetime/errors. return conn->process().finally([this, conn] { return unadvertise_connection(conn); }).handle_exception([this] (std::exception_ptr ep) { if (is_broken_pipe_or_connection_reset(ep)) { // expected if another side closes a connection or we're shutting down return; } _logger.info("exception while processing connection: {}", ep); }); }); return stop_iteration::no; }).handle_exception([this] (auto ep) { _logger.debug("accept failed: {}", ep); return stop_iteration::no; }); }); } future<> server::advertise_new_connection(shared_ptr<generic_server::connection> raw_conn) { return make_ready_future<>(); } future<> server::unadvertise_connection(shared_ptr<generic_server::connection> raw_conn) { return make_ready_future<>(); } // Signal that all connections are stopped if the server is stopping and can be stopped. void server::maybe_stop() { if (_stopping && !_connections_being_accepted && !_current_connections) { _all_connections_stopped.set_value(); } } } <commit_msg>generic_server: Keep server alive during conn background processing<commit_after>/* * Copyright (C) 2021-present ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "generic_server.hh" #include "to_string.hh" #include <seastar/core/when_all.hh> #include <seastar/core/reactor.hh> namespace generic_server { connection::connection(server& server, connected_socket&& fd) : _server{server} , _fd{std::move(fd)} , _read_buf(_fd.input()) , _write_buf(_fd.output()) { ++_server._total_connections; ++_server._current_connections; _server._connections_list.push_back(*this); } connection::~connection() { --_server._current_connections; _server._connections_list.erase(_server._connections_list.iterator_to(*this)); _server.maybe_stop(); } static bool is_broken_pipe_or_connection_reset(std::exception_ptr ep) { try { std::rethrow_exception(ep); } catch (const std::system_error& e) { return e.code().category() == std::system_category() && (e.code().value() == EPIPE || e.code().value() == ECONNRESET); } catch (...) {} return false; } future<> connection::process() { return with_gate(_pending_requests_gate, [this] { return do_until([this] { return _read_buf.eof(); }, [this] { return process_request(); }).then_wrapped([this] (future<> f) { handle_error(std::move(f)); }); }).finally([this] { return _pending_requests_gate.close().then([this] { on_connection_close(); return _ready_to_respond.handle_exception([] (std::exception_ptr ep) { if (is_broken_pipe_or_connection_reset(ep)) { // expected if another side closes a connection or we're shutting down return; } std::rethrow_exception(ep); }).finally([this] { return _write_buf.close(); }); }); }); } void connection::on_connection_close() { } future<> connection::shutdown() { try { _fd.shutdown_input(); _fd.shutdown_output(); } catch (...) { } return make_ready_future<>(); } server::server(const sstring& server_name, logging::logger& logger) : _server_name{server_name} , _logger{logger} { } server::~server() { } future<> server::stop() { _stopping = true; size_t nr = 0; size_t nr_total = _listeners.size(); _logger.debug("abort accept nr_total={}", nr_total); for (auto&& l : _listeners) { l.abort_accept(); _logger.debug("abort accept {} out of {} done", ++nr, nr_total); } auto nr_conn = make_lw_shared<size_t>(0); auto nr_conn_total = _connections_list.size(); _logger.debug("shutdown connection nr_total={}", nr_conn_total); return parallel_for_each(_connections_list.begin(), _connections_list.end(), [this, nr_conn, nr_conn_total] (auto&& c) { return c.shutdown().then([this, nr_conn, nr_conn_total] { _logger.debug("shutdown connection {} out of {} done", ++(*nr_conn), nr_conn_total); }); }).then([this] { return std::move(_stopped); }); } future<> server::listen(socket_address addr, std::shared_ptr<seastar::tls::credentials_builder> creds, bool is_shard_aware, bool keepalive) { auto f = make_ready_future<shared_ptr<seastar::tls::server_credentials>>(nullptr); if (creds) { f = creds->build_reloadable_server_credentials([this](const std::unordered_set<sstring>& files, std::exception_ptr ep) { if (ep) { _logger.warn("Exception loading {}: {}", files, ep); } else { _logger.info("Reloaded {}", files); } }); } return f.then([this, addr, is_shard_aware, keepalive](shared_ptr<seastar::tls::server_credentials> creds) { listen_options lo; lo.reuse_address = true; if (is_shard_aware) { lo.lba = server_socket::load_balancing_algorithm::port; } server_socket ss; try { ss = creds ? seastar::tls::listen(std::move(creds), addr, lo) : seastar::listen(addr, lo); } catch (...) { throw std::runtime_error(format("{} error while listening on {} -> {}", _server_name, addr, std::current_exception())); } _listeners.emplace_back(std::move(ss)); _stopped = when_all(std::move(_stopped), do_accepts(_listeners.size() - 1, keepalive, addr)).discard_result(); }); } future<> server::do_accepts(int which, bool keepalive, socket_address server_addr) { return repeat([this, which, keepalive, server_addr] { ++_connections_being_accepted; return _listeners[which].accept().then_wrapped([this, which, keepalive, server_addr] (future<accept_result> f_cs_sa) mutable { --_connections_being_accepted; if (_stopping) { f_cs_sa.ignore_ready_future(); maybe_stop(); return stop_iteration::yes; } auto cs_sa = f_cs_sa.get0(); auto fd = std::move(cs_sa.connection); auto addr = std::move(cs_sa.remote_address); fd.set_nodelay(true); fd.set_keepalive(keepalive); auto conn = make_connection(server_addr, std::move(fd), std::move(addr)); // Move the processing into the background. (void)futurize_invoke([this, conn] { return advertise_new_connection(conn); // Notify any listeners about new connection. }).then_wrapped([this, conn] (future<> f) { try { f.get(); } catch (...) { _logger.info("exception while advertising new connection: {}", std::current_exception()); } // Block while monitoring for lifetime/errors. return conn->process().then_wrapped([this, conn] (auto f) { try { f.get(); } catch (...) { auto ep = std::current_exception(); if (!is_broken_pipe_or_connection_reset(ep)) { // some exceptions are expected if another side closes a connection // or we're shutting down _logger.info("exception while processing connection: {}", ep); } } return unadvertise_connection(conn); }); }); return stop_iteration::no; }).handle_exception([this] (auto ep) { _logger.debug("accept failed: {}", ep); return stop_iteration::no; }); }); } future<> server::advertise_new_connection(shared_ptr<generic_server::connection> raw_conn) { return make_ready_future<>(); } future<> server::unadvertise_connection(shared_ptr<generic_server::connection> raw_conn) { return make_ready_future<>(); } // Signal that all connections are stopped if the server is stopping and can be stopped. void server::maybe_stop() { if (_stopping && !_connections_being_accepted && !_current_connections) { _all_connections_stopped.set_value(); } } } <|endoftext|>
<commit_before> // General-purpose timestamp-based log utility // Leigh Garbs #if !defined LOG_HPP #define LOG_HPP #include <iostream> class Log { public: // Log constructor; initializes output_stream Log(std::ostream& output_stream = std::cout); // Log destructor; does nothing ~Log(); // Sets the output stream to write log messages to void setOutputStream(std::ostream& output_stream); // Returns the output stream to write log messages to std::ostream& getOutputStream() const; // Writes a standard log message void write(const std::string& message); // Writes a warning log message void writeWarning(const std::string& message); // Writes an error log message void writeError(const std::string& message); // Flushes the current output stream void flush(); // Causes log timestamps to be generated in GMT void useGreenwichMeanTime(); // Causes log timestamps to be generated in local time void useLocalTime(); // Should the log flush the output stream after every write? void flushAfterWrite(bool flush_after_write); private: // Enumerates the different supported time formats enum TimeFormat { GMT, LOCAL }; // Generates a timestamp to prepend to log messages void generateTimestamp(std::string& timestamp); // The output stream to write log messages to std::ostream* output_stream; // The time format log timestamps are currently generated in TimeFormat current_time_format; // Whether or not the log flushes the output stream after every write bool flush_after_write; }; inline void Log::setOutputStream(std::ostream& output_stream) { this->output_stream = &output_stream; } inline std::ostream& Log::getOutputStream() const { return *output_stream; } inline void Log::useGreenwichMeanTime() { current_time_format = GMT; } inline void Log::useLocalTime() { current_time_format = LOCAL; } inline void Log::flushAfterWrite(bool flush_after_write) { this->flush_after_write = flush_after_write; } #endif <commit_msg>Removed spurious spaces<commit_after> // General-purpose timestamp-based log utility // Leigh Garbs #if !defined LOG_HPP #define LOG_HPP #include <iostream> class Log { public: // Log constructor; initializes output_stream Log(std::ostream& output_stream = std::cout); // Log destructor; does nothing ~Log(); // Sets the output stream to write log messages to void setOutputStream(std::ostream& output_stream); // Returns the output stream to write log messages to std::ostream& getOutputStream() const; // Writes a standard log message void write(const std::string& message); // Writes a warning log message void writeWarning(const std::string& message); // Writes an error log message void writeError(const std::string& message); // Flushes the current output stream void flush(); // Causes log timestamps to be generated in GMT void useGreenwichMeanTime(); // Causes log timestamps to be generated in local time void useLocalTime(); // Should the log flush the output stream after every write? void flushAfterWrite(bool flush_after_write); private: // Enumerates the different supported time formats enum TimeFormat { GMT, LOCAL }; // Generates a timestamp to prepend to log messages void generateTimestamp(std::string& timestamp); // The output stream to write log messages to std::ostream* output_stream; // The time format log timestamps are currently generated in TimeFormat current_time_format; // Whether or not the log flushes the output stream after every write bool flush_after_write; }; inline void Log::setOutputStream(std::ostream& output_stream) { this->output_stream = &output_stream; } inline std::ostream& Log::getOutputStream() const { return *output_stream; } inline void Log::useGreenwichMeanTime() { current_time_format = GMT; } inline void Log::useLocalTime() { current_time_format = LOCAL; } inline void Log::flushAfterWrite(bool flush_after_write) { this->flush_after_write = flush_after_write; } #endif <|endoftext|>
<commit_before>#ifndef ANN_ENGINE #define ANN_ENGINE #undef DLL //windows DLL #ifdef DLLDIR_EX #define DLL __declspec(dllexport) // export DLL information #else #define DLL __declspec(dllimport) // import DLL information #endif //bypass on linux #ifdef __gnu_linux__ #undef DLL #define DLL #endif //C++ STD & STL #include <vector> #include <sstream> //Ogre 3D #include <Ogre.h> #include <OIS.h> //Bullet #include <btBulletCollisionCommon.h> #include <BulletCollision/CollisionDispatch/btGhostObject.h> #include <btBulletDynamicsCommon.h> //CEGUI #include <CEGUI/CEGUI.h> #include <CEGUI/RendererModules/Ogre/Renderer.h> //OgreOculus by kojack #include "OgreOculus.h" //btOgre #include "BtOgrePG.h" #include "BtOgreGP.h" #include "BtOgreExtras.h" //Annwvyn #include "AnnGameObject.hpp" #include "AnnTriggerObject.hpp" #include "AnnTypes.h" #include "AnnTools.h" #include "AnnAudioEngine.hpp" #ifdef __gnu_linux__ #include <unistd.h> #endif namespace Annwvyn { class DLL AnnEngine { public: //Class constructor. take the name of the window AnnEngine(const char title[] = "Annwvyn Game Engine"); //Class destructor. Do clean up stuff. ~AnnEngine(); AnnEngine* getAddress() {return this;} void initCEGUI(); //display config window and return an ogre root (create a new one by default) Ogre::Root* askSetUpOgre(Ogre::Root* root = new Ogre::Root); //load data to the ressource group manager void loadZip(const char path[]); void loadDir(const char path[]); void loadResFile(const char path[]); //init ressources groups void initRessources(); //init OgreOculus stuff void oculusInit(); //init the BodyParams variable static void initBodyParams(Annwvyn::bodyParams* bodyP, float eyeHeight = 1.70f, float walkSpeed = 1.2f, float turnSpeed = 0.003f, float mass = 80.0f, Ogre::Vector3 Position = Ogre::Vector3(0,0,10), Ogre::Quaternion HeadOrientation = Ogre::Quaternion(1,0,0,0), btCollisionShape* Shape = NULL, btRigidBody* Body = NULL); //create a bullet shape for player's body void createVirtualBodyShape(); //create a bullet rigid body for the player void createPlayerPhysicalVirtualBody(); //add player rigid body to the bullet world void addPlayerPhysicalBodyToDynamicsWorld(); //do all player related physics stuff for you void initPlayerPhysics(); //update player location/orientation from the bullet body void updatePlayerFromPhysics(); //translate the player (DONT DETECT COLLISIONS HERE !!!) void translatePhysicBody(Ogre::Vector3 translation); //set player linear speed from a 3D vector void setPhysicBodyLinearSpeed(Ogre::Vector3 V); //create a game object form the name of an entity loaded on the ressource group manager. AnnGameObject* createGameObject(const char entityName[]); //set the ambiant light void setAmbiantLight(Ogre::ColourValue v); //add a light to the scene. return a pointer to the new light AnnLightObject* addLight(); //calculate one frame of the game void renderOneFrame(); //display bullet debuging drawing void setDebugPhysicState(bool state);//if state == true, display physics debug void runPhysics(); //return true if the game want to terminate the program bool requestStop(); //log something to the console. If flag = true (by default), will print "Annwvyn - " in front of the message static void log(std::string message, bool flag = true); //update camera position/orientation from rift and virtual body void updateCamera(); //refresh all for you void refresh(); //return a vector depending on WASD keys pressed bool processWASD(Ogre::Vector3* translate);//return the translation vector to aply on the body //caputre event form keyboard and mouse void captureEvents();//keyboard and mouse //update program time. retur the delay between the last call of this method float updateTime(); //return deltaT float getTime(); //Step Objects animation void playObjectsAnnimation(); //set the ground object void setGround(AnnGameObject* Ground); //return the Annwvyn OpenAL simplified audio engine AnnAudioEngine* getAudioEngine(); //get lowlevel OIS access OIS::Mouse* getOISMouse(); OIS::Keyboard* getOISKeyboard(); OIS::JoyStick* getOISJoyStick(); //is key 'key' pressed ? (see OIS headers for KeyCode, generaly 'OIS::KC_X' where X is the key you want. bool isKeyDown(OIS::KeyCode key); //this is simplier to use if you are on the OIS namespace ;-) //return true if you touch the ground bool collisionWithGround(); //process collision test form bullet manifold and objects collision mask void processCollisionTesting(); //get the dynamicsWorld btDiscreteDynamicsWorld* getDynamicsWorld(); //create a trigger object AnnTriggerObject* createTriggerObject(); //process contact test with triggers void processTriggersContacts(); //get ogre scene manager Ogre::SceneManager* getSceneManager(); //set the ogre material for the skydime with params void setSkyDomeMaterial(bool activate, const char materialName[], float curvature = 2.0f, float tiling = 1.0f); //get the AnnObject the player is looking at Annwvyn::AnnGameObject* playerLookingAt(); //get bodyParams Annwvyn::bodyParams* getBodyParams(); //get ogre camera scene node Ogre::SceneNode* getCamera(); float getCentreOffset(); void setReferenceQuaternion(Ogre::Quaternion q); Ogre::Quaternion getReferenceQuaternion(); private: Annwvyn::bodyParams* m_bodyParams; Ogre::Root* m_Root; Ogre::RenderWindow* m_Window; Ogre::SceneManager* m_SceneManager; Ogre::SceneNode* m_Camera; bool readyForLoadingRessources; Ogre::Entity* m_ent; //only used for creating nodes into the smgr Oculus oculus; //dynamic container for games objects std::vector <AnnGameObject*> objects; std::vector <AnnTriggerObject*> triggers; //Events processing : OIS::InputManager *m_InputManager ; OIS::Keyboard *m_Keyboard; OIS::Mouse *m_Mouse; OIS::JoyStick *m_Joystick; OIS::ParamList pl; size_t windowHnd; std::ostringstream windowHndStr; bool activateWASD; bool activateJump; float jumpForce; //time unsigned long last,now; //Milisec float deltaT; //Sec //bullet btBroadphaseInterface* m_Broadphase; btDefaultCollisionConfiguration* m_CollisionConfiguration; btCollisionDispatcher* m_Dispatcher; btSequentialImpulseConstraintSolver* m_Solver; btGhostPairCallback* m_ghostPairCallback; btDiscreteDynamicsWorld* m_DynamicsWorld; bool debugPhysics; BtOgre::DebugDrawer* m_debugDrawer; btQuaternion fixedBodyOrient; Ogre::Quaternion QuatReference; AnnGameObject* m_Ground; //Audio AnnAudioEngine* AudioEngine; //gui CEGUI::OgreRenderer* m_CEGUI_Renderer; }; } #endif //ANN_ENGINE <commit_msg>Change a vector type description<commit_after>#ifndef ANN_ENGINE #define ANN_ENGINE #undef DLL //windows DLL #ifdef DLLDIR_EX #define DLL __declspec(dllexport) // export DLL information #else #define DLL __declspec(dllimport) // import DLL information #endif //bypass on linux #ifdef __gnu_linux__ #undef DLL #define DLL #endif //C++ STD & STL #include <vector> #include <sstream> //Ogre 3D #include <Ogre.h> #include <OIS.h> //Bullet #include <btBulletCollisionCommon.h> #include <BulletCollision/CollisionDispatch/btGhostObject.h> #include <btBulletDynamicsCommon.h> //CEGUI #include <CEGUI/CEGUI.h> #include <CEGUI/RendererModules/Ogre/Renderer.h> //OgreOculus by kojack #include "OgreOculus.h" //btOgre #include "BtOgrePG.h" #include "BtOgreGP.h" #include "BtOgreExtras.h" //Annwvyn #include "AnnGameObject.hpp" #include "AnnTriggerObject.hpp" #include "AnnTypes.h" #include "AnnTools.h" #include "AnnAudioEngine.hpp" #ifdef __gnu_linux__ #include <unistd.h> #endif namespace Annwvyn { class DLL AnnEngine { public: //Class constructor. take the name of the window AnnEngine(const char title[] = "Annwvyn Game Engine"); //Class destructor. Do clean up stuff. ~AnnEngine(); AnnEngine* getAddress() {return this;} void initCEGUI(); //display config window and return an ogre root (create a new one by default) Ogre::Root* askSetUpOgre(Ogre::Root* root = new Ogre::Root); //load data to the ressource group manager void loadZip(const char path[]); void loadDir(const char path[]); void loadResFile(const char path[]); //init ressources groups void initRessources(); //init OgreOculus stuff void oculusInit(); //init the BodyParams variable static void initBodyParams(Annwvyn::bodyParams* bodyP, float eyeHeight = 1.70f, float walkSpeed = 1.2f, float turnSpeed = 0.003f, float mass = 80.0f, Ogre::Vector3 Position = Ogre::Vector3(0,0,10), Ogre::Quaternion HeadOrientation = Ogre::Quaternion(1,0,0,0), btCollisionShape* Shape = NULL, btRigidBody* Body = NULL); //create a bullet shape for player's body void createVirtualBodyShape(); //create a bullet rigid body for the player void createPlayerPhysicalVirtualBody(); //add player rigid body to the bullet world void addPlayerPhysicalBodyToDynamicsWorld(); //do all player related physics stuff for you void initPlayerPhysics(); //update player location/orientation from the bullet body void updatePlayerFromPhysics(); //translate the player (DONT DETECT COLLISIONS HERE !!!) void translatePhysicBody(Ogre::Vector3 translation); //set player linear speed from a 3D vector void setPhysicBodyLinearSpeed(Ogre::Vector3 V); //create a game object form the name of an entity loaded on the ressource group manager. AnnGameObject* createGameObject(const char entityName[]); //set the ambiant light void setAmbiantLight(Ogre::ColourValue v); //add a light to the scene. return a pointer to the new light AnnLightObject* addLight(); //calculate one frame of the game void renderOneFrame(); //display bullet debuging drawing void setDebugPhysicState(bool state);//if state == true, display physics debug void runPhysics(); //return true if the game want to terminate the program bool requestStop(); //log something to the console. If flag = true (by default), will print "Annwvyn - " in front of the message static void log(std::string message, bool flag = true); //update camera position/orientation from rift and virtual body void updateCamera(); //refresh all for you void refresh(); //return a vector depending on WASD keys pressed bool processWASD(Ogre::Vector3* translate);//return the translation vector to aply on the body //caputre event form keyboard and mouse void captureEvents();//keyboard and mouse //update program time. retur the delay between the last call of this method float updateTime(); //return deltaT float getTime(); //Step Objects animation void playObjectsAnnimation(); //set the ground object void setGround(AnnGameObject* Ground); //return the Annwvyn OpenAL simplified audio engine AnnAudioEngine* getAudioEngine(); //get lowlevel OIS access OIS::Mouse* getOISMouse(); OIS::Keyboard* getOISKeyboard(); OIS::JoyStick* getOISJoyStick(); //is key 'key' pressed ? (see OIS headers for KeyCode, generaly 'OIS::KC_X' where X is the key you want. bool isKeyDown(OIS::KeyCode key); //this is simplier to use if you are on the OIS namespace ;-) //return true if you touch the ground bool collisionWithGround(); //process collision test form bullet manifold and objects collision mask void processCollisionTesting(); //get the dynamicsWorld btDiscreteDynamicsWorld* getDynamicsWorld(); //create a trigger object AnnTriggerObject* createTriggerObject(); //process contact test with triggers void processTriggersContacts(); //get ogre scene manager Ogre::SceneManager* getSceneManager(); //set the ogre material for the skydime with params void setSkyDomeMaterial(bool activate, const char materialName[], float curvature = 2.0f, float tiling = 1.0f); //get the AnnObject the player is looking at Annwvyn::AnnGameObject* playerLookingAt(); //get bodyParams Annwvyn::bodyParams* getBodyParams(); //get ogre camera scene node Ogre::SceneNode* getCamera(); float getCentreOffset(); void setReferenceQuaternion(Ogre::Quaternion q); Ogre::Quaternion getReferenceQuaternion(); private: Annwvyn::bodyParams* m_bodyParams; Ogre::Root* m_Root; Ogre::RenderWindow* m_Window; Ogre::SceneManager* m_SceneManager; Ogre::SceneNode* m_Camera; bool readyForLoadingRessources; Ogre::Entity* m_ent; //only used for creating nodes into the smgr Oculus oculus; //dynamic container for games objects AnnGameObjectVect objects; std::vector <AnnTriggerObject*> triggers; //Events processing : OIS::InputManager *m_InputManager ; OIS::Keyboard *m_Keyboard; OIS::Mouse *m_Mouse; OIS::JoyStick *m_Joystick; OIS::ParamList pl; size_t windowHnd; std::ostringstream windowHndStr; bool activateWASD; bool activateJump; float jumpForce; //time unsigned long last,now; //Milisec float deltaT; //Sec //bullet btBroadphaseInterface* m_Broadphase; btDefaultCollisionConfiguration* m_CollisionConfiguration; btCollisionDispatcher* m_Dispatcher; btSequentialImpulseConstraintSolver* m_Solver; btGhostPairCallback* m_ghostPairCallback; btDiscreteDynamicsWorld* m_DynamicsWorld; bool debugPhysics; BtOgre::DebugDrawer* m_debugDrawer; btQuaternion fixedBodyOrient; Ogre::Quaternion QuatReference; AnnGameObject* m_Ground; //Audio AnnAudioEngine* AudioEngine; //gui CEGUI::OgreRenderer* m_CEGUI_Renderer; }; } #endif //ANN_ENGINE <|endoftext|>
<commit_before>#include "evpp/inner_pre.h" #include "evpp/connector.h" #include "evpp/event_loop.h" #include "evpp/fd_channel.h" #include "evpp/sockets.h" #include "evpp/libevent_headers.h" #include "evpp/dns_resolver.h" namespace evpp { Connector::Connector(EventLoop* l, const std::string& raddr, Duration timeout) : status_(kDisconnected), loop_(l), remote_addr_(raddr), timeout_(timeout), fd_(-1), own_fd_(false) { LOG_INFO << "Connector::Connector this=" << this << " raddr=" << raddr; raddr_ = sock::ParseFromIPPort(remote_addr_.data()); } Connector::~Connector() { loop_->AssertInLoopThread(); if (!IsConnected()) { // A connected tcp-connection's sockfd has been transfered to TCPConn. // But the sockfd of unconnected tcp-connections need to be closed by myself. LOG_TRACE << "Connector::~Connector close(" << chan_->fd() << ")"; assert(own_fd_); assert(chan_->fd() == fd_); EVUTIL_CLOSESOCKET(fd_); fd_ = INVALID_SOCKET; } assert(fd_ < 0); chan_.reset(); } void Connector::Start() { LOG_INFO << "Try to connect " << remote_addr_ << " status=" << StatusToString(); loop_->AssertInLoopThread(); timer_.reset(new TimerEventWatcher(loop_, std::bind(&Connector::OnConnectTimeout, this), timeout_)); timer_->Init(); timer_->AsyncWait(); if (raddr_.sin_addr.s_addr == 0) { status_ = kDNSResolving; auto index = remote_addr_.rfind(':'); assert(index != std::string::npos); auto host = std::string(remote_addr_.data(), index); dns_resolver_.reset(new DNSResolver(loop_, host, timeout_, std::bind(&Connector::OnDNSResolved, this, std::placeholders::_1))); dns_resolver_->Start(); return; } Connect(); } void Connector::Cancel() { LOG_INFO << "Cancel to connect " << remote_addr_ << " status=" << StatusToString(); loop_->AssertInLoopThread(); if (dns_resolver_) { dns_resolver_->Cancel(); } assert(timer_); timer_->Cancel(); chan_->DisableAllEvent(); chan_->Close(); } void Connector::Connect() { fd_ = sock::CreateNonblockingSocket(); own_fd_ = true; assert(fd_ >= 0); int rc = ::connect(fd_, sock::sockaddr_cast(&raddr_), sizeof(raddr_)); if (rc != 0) { int serrno = errno; if (!EVUTIL_ERR_CONNECT_RETRIABLE(serrno)) { HandleError(); return; } } status_ = kConnecting; chan_.reset(new FdChannel(loop_, fd_, false, true)); LOG_TRACE << "this=" << this << " new FdChannel p=" << chan_.get() << " fd=" << chan_->fd(); chan_->SetWriteCallback(std::bind(&Connector::HandleWrite, this)); chan_->AttachToLoop(); } void Connector::HandleWrite() { if (status_ == kDisconnected) { // пdzʱˣصʱѾɷУŵá LOG_INFO << "fd=" << chan_->fd() << " remote_addr=" << remote_addr_ << " receive write event when socket is closed"; return; } assert(status_ == kConnecting); int err = 0; socklen_t len = sizeof(len); if (getsockopt(chan_->fd(), SOL_SOCKET, SO_ERROR, (char*)&err, (socklen_t*)&len) != 0) { err = errno; LOG_ERROR << "getsockopt failed err=" << err << " " << strerror(err); } if (err != 0) { EVUTIL_SET_SOCKET_ERROR(err); HandleError(); return; } assert(fd_ == chan_->fd()); struct sockaddr_in addr = sock::GetLocalAddr(chan_->fd()); std::string laddr = sock::ToIPPort(&addr); conn_fn_(chan_->fd(), laddr); timer_->Cancel(); chan_->DisableAllEvent(); chan_->Close(); own_fd_ = false; // fdȨתƸTCPConn fd_ = INVALID_SOCKET; status_ = kConnected; } void Connector::HandleError() { int serrno = errno; LOG_ERROR << "status=" << StatusToString() << " errno=" << serrno << " " << strerror(serrno); status_ = kDisconnected; if (chan_) { chan_->DisableAllEvent(); chan_->Close(); } timer_->Cancel(); if (EVUTIL_ERR_CONNECT_REFUSED(serrno)) { conn_fn_(-1, ""); } else { loop_->RunAfter(1000, std::bind(&Connector::Start, this));//TODO Add retry times. } } void Connector::OnConnectTimeout() { assert(status_ == kConnecting || status_ == kDNSResolving); EVUTIL_SET_SOCKET_ERROR(ETIMEDOUT); HandleError(); } void Connector::OnDNSResolved(const std::vector <struct in_addr>& addrs) { if (addrs.empty()) { LOG_ERROR << "DNS Resolve failed. host=" << remote_addr_; HandleError(); return; } raddr_.sin_addr = addrs[0]; // TODO random index status_ = kDNSResolved; Connect(); } std::string Connector::StatusToString() const { H_CASE_STRING_BIGIN(status_); H_CASE_STRING(kDisconnected); H_CASE_STRING(kDNSResolving); H_CASE_STRING(kDNSResolved); H_CASE_STRING(kConnecting); H_CASE_STRING(kConnected); H_CASE_STRING_END(); } } <commit_msg>Change magic number to a named variable<commit_after>#include "evpp/inner_pre.h" #include "evpp/connector.h" #include "evpp/event_loop.h" #include "evpp/fd_channel.h" #include "evpp/sockets.h" #include "evpp/libevent_headers.h" #include "evpp/dns_resolver.h" namespace evpp { Connector::Connector(EventLoop* l, const std::string& raddr, Duration timeout) : status_(kDisconnected), loop_(l), remote_addr_(raddr), timeout_(timeout), fd_(-1), own_fd_(false) { LOG_INFO << "Connector::Connector this=" << this << " raddr=" << raddr; raddr_ = sock::ParseFromIPPort(remote_addr_.data()); } Connector::~Connector() { loop_->AssertInLoopThread(); if (!IsConnected()) { // A connected tcp-connection's sockfd has been transfered to TCPConn. // But the sockfd of unconnected tcp-connections need to be closed by myself. LOG_TRACE << "Connector::~Connector close(" << chan_->fd() << ")"; assert(own_fd_); assert(chan_->fd() == fd_); EVUTIL_CLOSESOCKET(fd_); fd_ = INVALID_SOCKET; } assert(fd_ < 0); chan_.reset(); } void Connector::Start() { LOG_INFO << "Try to connect " << remote_addr_ << " status=" << StatusToString(); loop_->AssertInLoopThread(); timer_.reset(new TimerEventWatcher(loop_, std::bind(&Connector::OnConnectTimeout, this), timeout_)); timer_->Init(); timer_->AsyncWait(); if (raddr_.sin_addr.s_addr == 0) { status_ = kDNSResolving; auto index = remote_addr_.rfind(':'); assert(index != std::string::npos); auto host = std::string(remote_addr_.data(), index); dns_resolver_.reset(new DNSResolver(loop_, host, timeout_, std::bind(&Connector::OnDNSResolved, this, std::placeholders::_1))); dns_resolver_->Start(); return; } Connect(); } void Connector::Cancel() { LOG_INFO << "Cancel to connect " << remote_addr_ << " status=" << StatusToString(); loop_->AssertInLoopThread(); if (dns_resolver_) { dns_resolver_->Cancel(); } assert(timer_); timer_->Cancel(); chan_->DisableAllEvent(); chan_->Close(); } void Connector::Connect() { fd_ = sock::CreateNonblockingSocket(); own_fd_ = true; assert(fd_ >= 0); int rc = ::connect(fd_, sock::sockaddr_cast(&raddr_), sizeof(raddr_)); if (rc != 0) { int serrno = errno; if (!EVUTIL_ERR_CONNECT_RETRIABLE(serrno)) { HandleError(); return; } } status_ = kConnecting; chan_.reset(new FdChannel(loop_, fd_, false, true)); LOG_TRACE << "this=" << this << " new FdChannel p=" << chan_.get() << " fd=" << chan_->fd(); chan_->SetWriteCallback(std::bind(&Connector::HandleWrite, this)); chan_->AttachToLoop(); } void Connector::HandleWrite() { if (status_ == kDisconnected) { // пdzʱˣصʱѾɷУŵá LOG_INFO << "fd=" << chan_->fd() << " remote_addr=" << remote_addr_ << " receive write event when socket is closed"; return; } assert(status_ == kConnecting); int err = 0; socklen_t len = sizeof(len); if (getsockopt(chan_->fd(), SOL_SOCKET, SO_ERROR, (char*)&err, (socklen_t*)&len) != 0) { err = errno; LOG_ERROR << "getsockopt failed err=" << err << " " << strerror(err); } if (err != 0) { EVUTIL_SET_SOCKET_ERROR(err); HandleError(); return; } assert(fd_ == chan_->fd()); struct sockaddr_in addr = sock::GetLocalAddr(chan_->fd()); std::string laddr = sock::ToIPPort(&addr); conn_fn_(chan_->fd(), laddr); timer_->Cancel(); chan_->DisableAllEvent(); chan_->Close(); own_fd_ = false; // fdȨתƸTCPConn fd_ = INVALID_SOCKET; status_ = kConnected; } void Connector::HandleError() { int serrno = errno; LOG_ERROR << "status=" << StatusToString() << " errno=" << serrno << " " << strerror(serrno); status_ = kDisconnected; if (chan_) { chan_->DisableAllEvent(); chan_->Close(); } timer_->Cancel(); if (EVUTIL_ERR_CONNECT_REFUSED(serrno)) { conn_fn_(-1, ""); } else { auto interval = Duration(3.0); loop_->RunAfter(interval, std::bind(&Connector::Start, this));//TODO Add retry times. } } void Connector::OnConnectTimeout() { assert(status_ == kConnecting || status_ == kDNSResolving); EVUTIL_SET_SOCKET_ERROR(ETIMEDOUT); HandleError(); } void Connector::OnDNSResolved(const std::vector <struct in_addr>& addrs) { if (addrs.empty()) { LOG_ERROR << "DNS Resolve failed. host=" << remote_addr_; HandleError(); return; } raddr_.sin_addr = addrs[0]; // TODO random index status_ = kDNSResolved; Connect(); } std::string Connector::StatusToString() const { H_CASE_STRING_BIGIN(status_); H_CASE_STRING(kDisconnected); H_CASE_STRING(kDNSResolving); H_CASE_STRING(kDNSResolved); H_CASE_STRING(kConnecting); H_CASE_STRING(kConnected); H_CASE_STRING_END(); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef MTAC_LOOP_H #define MTAC_LOOP_H #include <memory> #include <set> #include <map> #include "mtac/forward.hpp" namespace eddic { class Variable; namespace mtac { struct LinearEquation { std::size_t def; std::shared_ptr<Variable> i; int e; int d; bool generated; }; typedef std::map<std::shared_ptr<Variable>, LinearEquation> InductionVariables; class Loop { public: typedef std::set<mtac::basic_block_p>::iterator iterator; Loop(const std::set<mtac::basic_block_p>& blocks); iterator begin(); iterator end(); std::set<mtac::basic_block_p>& blocks(); bool has_estimate(); long& estimate(); long& initial_value(); InductionVariables& basic_induction_variables(); InductionVariables& dependent_induction_variables(); private: InductionVariables biv; InductionVariables div; std::set<mtac::basic_block_p> m_blocks; long m_estimate = -1; long m_initial; }; /*! * \brief Find the basic block that is the entry to the Loop * \param loop The loop to find the entry of. * \return The entry basic block. */ mtac::basic_block_p find_entry(mtac::Loop& loop); /*! * \brief Find or create a preheader for the given loop. * \param loop The loop to find the preheader for * \param function The function the loop is located in * \return The preheader basic block of the Loop */ mtac::basic_block_p find_pre_header(mtac::Loop& loop, mtac::Function& function); } //end of mtac } //end of eddic #endif <commit_msg>Add support for division inside LinearEquation<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef MTAC_LOOP_H #define MTAC_LOOP_H #include <memory> #include <set> #include <map> #include "mtac/forward.hpp" namespace eddic { class Variable; namespace mtac { struct LinearEquation { std::size_t def; std::shared_ptr<Variable> i; int e; int d; bool generated; bool div; LinearEquation() : def(0), i(nullptr), e(0), d(0), generated(false), div(false){ //Nothing to init } LinearEquation(std::size_t def, std::shared_ptr<Variable> i, int e, int d, bool generated, bool div = false) : def(def), i(i), e(e), d(d), generated(generated), div(div) { //Nothing } }; typedef std::map<std::shared_ptr<Variable>, LinearEquation> InductionVariables; class Loop { public: typedef std::set<mtac::basic_block_p>::iterator iterator; Loop(const std::set<mtac::basic_block_p>& blocks); iterator begin(); iterator end(); std::set<mtac::basic_block_p>& blocks(); bool has_estimate(); long& estimate(); long& initial_value(); InductionVariables& basic_induction_variables(); InductionVariables& dependent_induction_variables(); private: InductionVariables biv; InductionVariables div; std::set<mtac::basic_block_p> m_blocks; long m_estimate = -1; long m_initial; }; /*! * \brief Find the basic block that is the entry to the Loop * \param loop The loop to find the entry of. * \return The entry basic block. */ mtac::basic_block_p find_entry(mtac::Loop& loop); /*! * \brief Find or create a preheader for the given loop. * \param loop The loop to find the preheader for * \param function The function the loop is located in * \return The preheader basic block of the Loop */ mtac::basic_block_p find_pre_header(mtac::Loop& loop, mtac::Function& function); } //end of mtac } //end of eddic #endif <|endoftext|>
<commit_before>#include "csound.h" #include "winsound.h" extern int do_exit; extern Fl_Double_Window *ew, *xw, *uw; CSOUND *csound; int cs_compile_run(void); int main(int argc, char **argv) { Fl_Double_Window* mw = make_mainwindow(); ew = make_environ(); uw = make_utils(); xw = make_extras(); csoundInitialize(&argc, &argv, CSOUNDINIT_NO_SIGNAL_HANDLER); csound = csoundCreate(NULL); csoundPreCompile(csound); mw->show(); do_exit = 0; while (!do_exit) { do_perf = 0; while (!do_exit && !do_perf) Fl::wait(); if (do_perf) cs_compile_run(); } } int cs_compile_run(void) { int res=0; if (do_load) { char *argv[100]; char b1[6], b2[6], b3[6], b4[6], b5[6], b6[6], b7[6]; int nxt=1; int n; argv[0] = "winsound5"; argv[nxt++] = (char *)orchname->value(); if (strstr(argv[nxt-1], ".csd")==NULL) argv[nxt++] = (char *)scorename->value(); if (strlen(output->value())!=0) { argv[nxt++] = "-o"; argv[nxt++] = (char *)output->value(); } if (wav->value()) argv[nxt++] = "-W"; else if (aiff->value()) argv[nxt++] = "-A"; else if (ircam->value()) argv[nxt++] = "-J"; else if (raw->value()) argv[nxt++] = "-h"; if (mI->value()) argv[nxt++] = "-I"; if (mn->value()) argv[nxt++] = "-n"; if (strlen(mi->value())!=0) { argv[nxt++] = "-F"; argv[nxt++] = (char *)mi->value(); } if (mb->value()>0) { sprintf(b1, "-b%d", (int)mb->value()); argv[nxt++] = b1; } if (mB->value()>0) { sprintf(b2, "-B%d", (int)mb->value()); argv[nxt++] = b2; } if (size_8->value()) argv[nxt++] = "-c"; else if (size_16->value()) argv[nxt++] = "-s"; else if (size_32->value()) argv[nxt++] = "-l"; else if (size_f->value()) argv[nxt++] = "-f"; else if (size_24->value()) argv[nxt++] = "-3"; if (mr->value()>0) { sprintf(b3, "-r%d", (int)mr->value()); argv[nxt++] = b3; } if (mk->value()>0) { sprintf(b4, "-k%d",(int)mk->value()); argv[nxt++] = b4; } if (mK->value()==0) argv[nxt++] = "-K"; if (mv->value()) argv[nxt++] = "-v"; if (mm->value()>0) { sprintf(b5, "-m%d", (int)mm->value()); argv[nxt++] = b5; } if (mt->value()>0) { sprintf(b6, "-t%d", (int)mt->value()); argv[nxt++] = b6; } if (mSave->value()) argv[nxt++] = "-t0"; if (strlen(mM->value())>0) { argv[nxt++] = "-M"; argv[nxt++] = (char *)mM->value(); } if (mR->value()) argv[nxt++] = "-R"; if (mH->value()>0) { sprintf(b7, "-H%d", (int)mH->value()); argv[nxt++] = b7; } if (mN->value()) argv[nxt++] = "-N"; if (mZ->value()) argv[nxt++] = "-Z"; for (n=1; n<nxt; n++) printf("arg %d: %s\n", n, argv[n]); csoundReset(csound); res = csoundCompile(csound, nxt-1, argv); } else csoundRewindScore(csound); if (res==0) csoundPerform(csound); csoundCleanup(csound); } void cs_util_sndinfo(void) { Fl_Double_Window *siw = make_info(); char *argv[2]; siw->show(); while (do_util==0) Fl::wait(); siw->hide(); if (do_util>0) { argv[0] = "sndinfo"; argv[1] = (char *)sndinfo_file->value(); csoundPreCompile(csound); csoundRunUtility(csound, "sndinfo", 2, argv); csoundReset(csound); } } extern "C" { void list_opcodes(CSOUND *csound, int level); int csoundLoadExternals(CSOUND *csound); int csoundInitModules(CSOUND *csound); } void cs_util_opc(int full) { csoundPreCompile(csound); csoundLoadExternals(csound); if (csoundInitModules(csound) == 0) list_opcodes(csound, full); csoundReset(csound); } <commit_msg>Removed use of internal functions<commit_after>#include "csound.h" #include "winsound.h" extern int do_exit; extern Fl_Double_Window *ew, *xw, *uw; CSOUND *csound; int cs_compile_run(void); int main(int argc, char **argv) { Fl_Double_Window* mw = make_mainwindow(); ew = make_environ(); uw = make_utils(); xw = make_extras(); csoundInitialize(&argc, &argv, CSOUNDINIT_NO_SIGNAL_HANDLER); csound = csoundCreate(NULL); csoundPreCompile(csound); mw->show(); do_exit = 0; while (!do_exit) { do_perf = 0; while (!do_exit && !do_perf) Fl::wait(); if (do_perf) cs_compile_run(); } } int cs_compile_run(void) { int res=0; if (do_load) { char *argv[100]; char b1[6], b2[6], b3[6], b4[6], b5[6], b6[6], b7[6]; int nxt=1; int n; argv[0] = "winsound5"; argv[nxt++] = (char *)orchname->value(); if (strstr(argv[nxt-1], ".csd")==NULL) argv[nxt++] = (char *)scorename->value(); if (strlen(output->value())!=0) { argv[nxt++] = "-o"; argv[nxt++] = (char *)output->value(); } if (wav->value()) argv[nxt++] = "-W"; else if (aiff->value()) argv[nxt++] = "-A"; else if (ircam->value()) argv[nxt++] = "-J"; else if (raw->value()) argv[nxt++] = "-h"; if (mI->value()) argv[nxt++] = "-I"; if (mn->value()) argv[nxt++] = "-n"; if (strlen(mi->value())!=0) { argv[nxt++] = "-F"; argv[nxt++] = (char *)mi->value(); } if (mb->value()>0) { sprintf(b1, "-b%d", (int)mb->value()); argv[nxt++] = b1; } if (mB->value()>0) { sprintf(b2, "-B%d", (int)mb->value()); argv[nxt++] = b2; } if (size_8->value()) argv[nxt++] = "-c"; else if (size_16->value()) argv[nxt++] = "-s"; else if (size_32->value()) argv[nxt++] = "-l"; else if (size_f->value()) argv[nxt++] = "-f"; else if (size_24->value()) argv[nxt++] = "-3"; if (mr->value()>0) { sprintf(b3, "-r%d", (int)mr->value()); argv[nxt++] = b3; } if (mk->value()>0) { sprintf(b4, "-k%d",(int)mk->value()); argv[nxt++] = b4; } if (mK->value()==0) argv[nxt++] = "-K"; if (mv->value()) argv[nxt++] = "-v"; if (mm->value()>0) { sprintf(b5, "-m%d", (int)mm->value()); argv[nxt++] = b5; } if (mt->value()>0) { sprintf(b6, "-t%d", (int)mt->value()); argv[nxt++] = b6; } if (mSave->value()) argv[nxt++] = "-t0"; if (strlen(mM->value())>0) { argv[nxt++] = "-M"; argv[nxt++] = (char *)mM->value(); } if (mR->value()) argv[nxt++] = "-R"; if (mH->value()>0) { sprintf(b7, "-H%d", (int)mH->value()); argv[nxt++] = b7; } if (mN->value()) argv[nxt++] = "-N"; if (mZ->value()) argv[nxt++] = "-Z"; for (n=1; n<nxt; n++) printf("arg %d: %s\n", n, argv[n]); csoundReset(csound); res = csoundCompile(csound, nxt-1, argv); } else csoundRewindScore(csound); if (res == 0) res = csoundPerform(csound); // csoundCleanup(csound); return res; } void cs_util_sndinfo(void) { Fl_Double_Window *siw = make_info(); char *argv[2]; siw->show(); while (do_util==0) Fl::wait(); siw->hide(); if (do_util>0) { argv[0] = "sndinfo"; argv[1] = (char *)sndinfo_file->value(); csoundPreCompile(csound); csoundRunUtility(csound, "sndinfo", 2, argv); csoundReset(csound); } } #if 0 extern "C" { void list_opcodes(CSOUND *csound, int level); int csoundLoadExternals(CSOUND *csound); int csoundInitModules(CSOUND *csound); } #endif static const char *listOpcodesArgV0[3] = { "csound", "-z", (char*) 0 }; static const char *listOpcodesArgV1[3] = { "csound", "-z1", (char*) 0 }; void cs_util_opc(int full) { #if 0 csoundPreCompile(csound); csoundLoadExternals(csound); if (csoundInitModules(csound) == 0) list_opcodes(csound, full); csoundReset(csound); #endif csoundPreCompile(csound); csoundCompile(csound, 2, (full ? (char**) &(listOpcodesArgV1[0]) : (char**) &(listOpcodesArgV0[0]))); csoundReset(csound); } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------- /// \file pcap.hpp /// \author Serge Aleynikov //---------------------------------------------------------------------------- /// \brief Support for PCAP file format writing. //---------------------------------------------------------------------------- // Copyright (c) 2010 Serge Aleynikov <[email protected]> // Created: 2010-10-21 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #ifndef _UTXX_PCAP_HPP_ #define _UTXX_PCAP_HPP_ #include <utxx/error.hpp> #include <utxx/endian.hpp> #include <boost/cstdint.hpp> #include <boost/static_assert.hpp> #include <stdio.h> #include <arpa/inet.h> namespace utxx { namespace detail { #include <netinet/ip.h> #include <netinet/udp.h> #include <netinet/if_ether.h> } /** * PCAP file reader/writer */ struct pcap { struct file_header { uint32_t magic_number; /* magic number */ uint16_t version_major; /* major version number */ uint16_t version_minor; /* minor version number */ int32_t thiszone; /* GMT to local correction */ uint32_t sigfigs; /* accuracy of timestamps */ uint32_t snaplen; /* max length of captured packets, in octets */ uint32_t network; /* data link type */ }; struct packet_header { uint32_t ts_sec; /* timestamp seconds */ uint32_t ts_usec; /* timestamp microseconds */ uint32_t incl_len; /* number of octets of packet saved in file */ uint32_t orig_len; /* actual length of packet */ }; struct udp_frame { struct detail::ethhdr eth; struct detail::iphdr ip; struct detail::udphdr udp; uint8_t protocol() const { return ip.protocol; } uint32_t src_ip() const { return ntohl(ip.saddr); } uint32_t dst_ip() const { return ntohl(ip.daddr); } uint16_t src_port() const { return ntohs(udp.source); } uint16_t dst_port() const { return ntohs(udp.dest); } std::string src() const { char buf[32]; return std::string(fmt(buf, src_ip(), src_port())); } std::string dst() const { char buf[32]; return std::string(fmt(buf, dst_ip(), dst_port())); } private: static const char* fmt(char* buf, uint32_t ip, uint16_t port) { sprintf(buf, "%u.%u.%u.%u:%d", ip >> 24 & 0xFF, ip >> 16 & 0xFF, ip >> 8 & 0xFF, ip & 0xFF, port); return buf; } } __attribute__ ((__packed__)); BOOST_STATIC_ASSERT(sizeof(detail::ethhdr) == 14); BOOST_STATIC_ASSERT(sizeof(detail::iphdr) == 20); BOOST_STATIC_ASSERT(sizeof(detail::udphdr) == 8); BOOST_STATIC_ASSERT(sizeof(udp_frame) == 42); pcap() : m_big_endian(true), m_file(NULL), m_own_handle(false) {} long open_read(const std::string& a_filename) { return open(a_filename.c_str(), "rb"); } long open_write(const std::string& a_filename) { long sz = open(a_filename.c_str(), "wb+"); if (sz < 0) return sz; write_file_header(); return sz; } long open(const char* a_filename, const std::string& a_mode) { close(); m_file = fopen(a_filename, a_mode.c_str()); if (!m_file) return -1; m_own_handle = true; if (fseek(m_file, 0, SEEK_END) < 0) return -1; long sz = ftell(m_file); if (fseek(m_file, 0, SEEK_SET) < 0) return -1; return (m_file == NULL) ? -1 : sz; } ~pcap() { close(); } static bool is_pcap_header(const char* buf, size_t sz) { return sz >= 4 && ( *reinterpret_cast<const uint32_t*>(buf) == 0xa1b2c3d4 || *reinterpret_cast<const uint32_t*>(buf) == 0xd4c3b2a1); } static int set_file_header(char* buf, size_t sz) { BOOST_ASSERT(sz >= sizeof(file_header)); file_header* p = reinterpret_cast<file_header*>(buf); p->magic_number = 0xa1b2c3d4; p->version_major = 2; p->version_minor = 4; p->thiszone = 0; p->sigfigs = 0; p->snaplen = 65535; p->network = 1; return sizeof(file_header); } template <size_t N> static int set_packet_header(char (&buf)[N], const struct timeval& tv, size_t len) { BOOST_STATIC_ASSERT(N >= sizeof(packet_header)); packet_header* p = reinterpret_cast<packet_header*>(buf); p->ts_sec = tv.tv_sec; p->ts_usec = tv.tv_usec; p->incl_len = len; p->orig_len = len; return sizeof(packet_header); } int read_file_header() { char buf[sizeof(file_header)]; const char* p = buf; size_t n = read(buf, sizeof(buf)); if (n < sizeof(buf)) return -1; return read_file_header(p, sizeof(buf)); } int read_file_header(const char*& buf, size_t sz) { if (sz < sizeof(file_header) || !is_pcap_header(buf, sz)) return -1; m_big_endian = buf[0] == 0xa1 && buf[1] == 0xb2 && buf[2] == 0xc3 && buf[3] == 0xd4; if (!m_big_endian) { m_file_header = *reinterpret_cast<const file_header*>(buf); buf += sizeof(file_header); } else { m_file_header.magic_number = get32be(buf); m_file_header.version_major = get16be(buf); m_file_header.version_minor = get16be(buf); m_file_header.thiszone = (int32_t)get32be(buf); m_file_header.sigfigs = get32be(buf); m_file_header.snaplen = get32be(buf); m_file_header.network = get32be(buf); } return 0; } int read_packet_header(const char*& buf, size_t sz) { if (sz < sizeof(packet_header)) return -1; if (!m_big_endian) { m_pkt_header = *reinterpret_cast<const packet_header*>(buf); buf += sizeof(packet_header); } else { m_pkt_header.ts_sec = get32be(buf); m_pkt_header.ts_usec = get32be(buf); m_pkt_header.incl_len = get32be(buf); m_pkt_header.orig_len = get32be(buf); } return m_pkt_header.incl_len; } int parse_udp_frame(const char*&buf, size_t sz) { if (sz < 42) return -2; memcpy(&m_frame, buf, sizeof(m_frame)); buf += sizeof(m_frame); return m_frame.ip.protocol != IPPROTO_UDP ? -1 : 42; } /// @param a_mask is an IP address mask in network byte order. bool match_dst_ip(uint32_t a_ip_mask, uint16_t a_port = 0) { uint8_t b = a_ip_mask >> 24 & 0xFF; if (b != 0 && (b != (m_frame.ip.daddr >> 24 & 0xFF))) return false; b = a_ip_mask >> 16 & 0xFF; if (b != 0 && (b != (m_frame.ip.daddr >> 16 & 0xFF))) return false; b = a_ip_mask >> 8 & 0xFF; if (b != 0 && (b != (m_frame.ip.daddr >> 8 & 0xFF))) return false; b = a_ip_mask & 0xFF; if (b != 0 && (b != (m_frame.ip.daddr & 0xFF))) return false; if (a_port != 0 && (a_port != m_frame.udp.dest)) return false; return true; } size_t read(char* buf, size_t sz) { return fread(buf, 1, sz, m_file); } int write_file_header() { char buf[sizeof(file_header)]; int n = set_file_header(buf, sizeof(buf)); return fwrite(buf, 1, n, m_file); } int write_packet_header( const struct timeval& a_timestamp, size_t a_packet_size) { char buf[sizeof(packet_header)]; int n = set_packet_header(buf, a_timestamp, a_packet_size); return fwrite(buf, 1, n, m_file); } int write_packet_header(const packet_header& a_header) { return fwrite(&a_header, 1, sizeof(packet_header), m_file); } int write_udp_frame(const udp_frame& a_frame) { return fwrite(&a_frame, 1, sizeof(udp_frame), m_file); } int write(const char* buf, size_t sz) { return fwrite(buf, 1, sz, m_file); } bool is_open() const { return m_file != NULL; } uint64_t tell() const { return m_file ? ftell(m_file) : 0; } const file_header& header() const { return m_file_header; } const packet_header& packet() const { return m_pkt_header; } const udp_frame& frame() const { return m_frame; } void set_handle(FILE* a_handle) { close(); m_own_handle = false; m_file = a_handle; } private: void close() { if (m_file && m_own_handle) { fclose(m_file); m_file = NULL; } } udp_frame m_frame; file_header m_file_header; packet_header m_pkt_header; bool m_big_endian; FILE* m_file; bool m_own_handle; }; } // namespace utxx #endif // _UTXX_PCAP_HPP_ <commit_msg>Add popen(3) to pcap support<commit_after>//---------------------------------------------------------------------------- /// \file pcap.hpp /// \author Serge Aleynikov //---------------------------------------------------------------------------- /// \brief Support for PCAP file format writing. //---------------------------------------------------------------------------- // Copyright (c) 2010 Serge Aleynikov <[email protected]> // Created: 2010-10-21 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #ifndef _UTXX_PCAP_HPP_ #define _UTXX_PCAP_HPP_ #include <utxx/error.hpp> #include <utxx/endian.hpp> #include <boost/cstdint.hpp> #include <boost/static_assert.hpp> #include <stdio.h> #include <arpa/inet.h> namespace utxx { namespace detail { #include <netinet/ip.h> #include <netinet/udp.h> #include <netinet/if_ether.h> } /** * PCAP file reader/writer */ struct pcap { struct file_header { uint32_t magic_number; /* magic number */ uint16_t version_major; /* major version number */ uint16_t version_minor; /* minor version number */ int32_t thiszone; /* GMT to local correction */ uint32_t sigfigs; /* accuracy of timestamps */ uint32_t snaplen; /* max length of captured packets, in octets */ uint32_t network; /* data link type */ }; struct packet_header { uint32_t ts_sec; /* timestamp seconds */ uint32_t ts_usec; /* timestamp microseconds */ uint32_t incl_len; /* number of octets of packet saved in file */ uint32_t orig_len; /* actual length of packet */ }; struct udp_frame { struct detail::ethhdr eth; struct detail::iphdr ip; struct detail::udphdr udp; uint8_t protocol() const { return ip.protocol; } uint32_t src_ip() const { return ntohl(ip.saddr); } uint32_t dst_ip() const { return ntohl(ip.daddr); } uint16_t src_port() const { return ntohs(udp.source); } uint16_t dst_port() const { return ntohs(udp.dest); } std::string src() const { char buf[32]; return std::string(fmt(buf, src_ip(), src_port())); } std::string dst() const { char buf[32]; return std::string(fmt(buf, dst_ip(), dst_port())); } private: static const char* fmt(char* buf, uint32_t ip, uint16_t port) { sprintf(buf, "%u.%u.%u.%u:%d", ip >> 24 & 0xFF, ip >> 16 & 0xFF, ip >> 8 & 0xFF, ip & 0xFF, port); return buf; } } __attribute__ ((__packed__)); BOOST_STATIC_ASSERT(sizeof(detail::ethhdr) == 14); BOOST_STATIC_ASSERT(sizeof(detail::iphdr) == 20); BOOST_STATIC_ASSERT(sizeof(detail::udphdr) == 8); BOOST_STATIC_ASSERT(sizeof(udp_frame) == 42); pcap() : m_big_endian(true), m_file(NULL), m_own_handle(false) {} long open_read(const std::string& a_filename, bool a_is_pipe = false) { return open(a_filename.c_str(), a_is_pipe ? "r" : "rb"); } long open_write(const std::string& a_filename, bool a_is_pipe = false) { long sz = open(a_filename.c_str(), a_is_pipe ? "w" : "wb+", a_is_pipe); if (sz < 0) return sz; write_file_header(); return sz; } long popen(const char* a_filename, const std::string& a_mode) { return open(a_filename, a_mode, true); } long open(const char* a_filename, const std::string& a_mode) { return open(a_filename, a_mode, false); } ~pcap() { close(); } static bool is_pcap_header(const char* buf, size_t sz) { return sz >= 4 && ( *reinterpret_cast<const uint32_t*>(buf) == 0xa1b2c3d4 || *reinterpret_cast<const uint32_t*>(buf) == 0xd4c3b2a1); } static int set_file_header(char* buf, size_t sz) { BOOST_ASSERT(sz >= sizeof(file_header)); file_header* p = reinterpret_cast<file_header*>(buf); p->magic_number = 0xa1b2c3d4; p->version_major = 2; p->version_minor = 4; p->thiszone = 0; p->sigfigs = 0; p->snaplen = 65535; p->network = 1; return sizeof(file_header); } template <size_t N> static int set_packet_header(char (&buf)[N], const struct timeval& tv, size_t len) { BOOST_STATIC_ASSERT(N >= sizeof(packet_header)); packet_header* p = reinterpret_cast<packet_header*>(buf); p->ts_sec = tv.tv_sec; p->ts_usec = tv.tv_usec; p->incl_len = len; p->orig_len = len; return sizeof(packet_header); } int read_file_header() { char buf[sizeof(file_header)]; const char* p = buf; size_t n = read(buf, sizeof(buf)); if (n < sizeof(buf)) return -1; return read_file_header(p, sizeof(buf)); } int read_file_header(const char*& buf, size_t sz) { if (sz < sizeof(file_header) || !is_pcap_header(buf, sz)) return -1; m_big_endian = buf[0] == 0xa1 && buf[1] == 0xb2 && buf[2] == 0xc3 && buf[3] == 0xd4; if (!m_big_endian) { m_file_header = *reinterpret_cast<const file_header*>(buf); buf += sizeof(file_header); } else { m_file_header.magic_number = get32be(buf); m_file_header.version_major = get16be(buf); m_file_header.version_minor = get16be(buf); m_file_header.thiszone = (int32_t)get32be(buf); m_file_header.sigfigs = get32be(buf); m_file_header.snaplen = get32be(buf); m_file_header.network = get32be(buf); } return 0; } int read_packet_header(const char*& buf, size_t sz) { if (sz < sizeof(packet_header)) return -1; if (!m_big_endian) { m_pkt_header = *reinterpret_cast<const packet_header*>(buf); buf += sizeof(packet_header); } else { m_pkt_header.ts_sec = get32be(buf); m_pkt_header.ts_usec = get32be(buf); m_pkt_header.incl_len = get32be(buf); m_pkt_header.orig_len = get32be(buf); } return m_pkt_header.incl_len; } int parse_udp_frame(const char*&buf, size_t sz) { if (sz < 42) return -2; memcpy(&m_frame, buf, sizeof(m_frame)); buf += sizeof(m_frame); return m_frame.ip.protocol != IPPROTO_UDP ? -1 : 42; } /// @param a_mask is an IP address mask in network byte order. bool match_dst_ip(uint32_t a_ip_mask, uint16_t a_port = 0) { uint8_t b = a_ip_mask >> 24 & 0xFF; if (b != 0 && (b != (m_frame.ip.daddr >> 24 & 0xFF))) return false; b = a_ip_mask >> 16 & 0xFF; if (b != 0 && (b != (m_frame.ip.daddr >> 16 & 0xFF))) return false; b = a_ip_mask >> 8 & 0xFF; if (b != 0 && (b != (m_frame.ip.daddr >> 8 & 0xFF))) return false; b = a_ip_mask & 0xFF; if (b != 0 && (b != (m_frame.ip.daddr & 0xFF))) return false; if (a_port != 0 && (a_port != m_frame.udp.dest)) return false; return true; } size_t read(char* buf, size_t sz) { return fread(buf, 1, sz, m_file); } int write_file_header() { char buf[sizeof(file_header)]; int n = set_file_header(buf, sizeof(buf)); return fwrite(buf, 1, n, m_file); } int write_packet_header( const struct timeval& a_timestamp, size_t a_packet_size) { char buf[sizeof(packet_header)]; int n = set_packet_header(buf, a_timestamp, a_packet_size); return fwrite(buf, 1, n, m_file); } int write_packet_header(const packet_header& a_header) { return fwrite(&a_header, 1, sizeof(packet_header), m_file); } int write_udp_frame(const udp_frame& a_frame) { return fwrite(&a_frame, 1, sizeof(udp_frame), m_file); } int write(const char* buf, size_t sz) { return fwrite(buf, 1, sz, m_file); } bool is_open() const { return m_file != NULL; } uint64_t tell() const { return m_file ? ftell(m_file) : 0; } const file_header& header() const { return m_file_header; } const packet_header& packet() const { return m_pkt_header; } const udp_frame& frame() const { return m_frame; } void set_handle(FILE* a_handle) { close(); m_own_handle = false; m_file = a_handle; } private: void close() { if (m_file && m_own_handle) { m_is_pipe ? pclose(m_file) : fclose(m_file); m_is_pipe = false; m_file = NULL; } } long open(const char* a_filename, const std::string& a_mode, bool a_is_pipe) { close(); if (a_is_pipe) m_file = ::popen(a_filename, a_mode.c_str()); else m_file = ::fopen(a_filename, a_mode.c_str()); if (!m_file) return -1; m_is_pipe = a_is_pipe; m_own_handle = true; if (fseek(m_file, 0, SEEK_END) < 0) return -1; long sz = ftell(m_file); if (fseek(m_file, 0, SEEK_SET) < 0) return -1; return (m_file == NULL) ? -1 : sz; } udp_frame m_frame; file_header m_file_header; packet_header m_pkt_header; bool m_big_endian; FILE* m_file; bool m_own_handle; bool m_is_pipe; }; } // namespace utxx #endif // _UTXX_PCAP_HPP_ <|endoftext|>
<commit_before>#include <fcntl.h> #include "au/ThreadManager.h" #include "gtest/gtest.h" #include "samson/worker/SamsonWorker.h" #include "unitTest/TestClasses.h" TEST(samson_worker_SamsonWorker, basic) { EXPECT_EQ(0, au::Singleton<au::ThreadManager>::shared()->num_threads()); // Init engine engine::Engine::InitEngine(4, 10 * 1000000000, 1); // Create a worker samson::SamsonWorker *worker = new samson::SamsonWorker("no_zk_host", 9000, 9001); // Stop engine engine::Engine::StopEngine(); // Remove worker delete worker; // Destroyinh engine engine::Engine::DestroyEngine(); // Make sure no background threads are left there EXPECT_EQ(0, au::Singleton<au::ThreadManager>::shared()->num_threads()); } <commit_msg>Fix bug<commit_after>#include <fcntl.h> #include "au/ThreadManager.h" #include "gtest/gtest.h" #include "samson/worker/SamsonWorker.h" #include "unitTest/TestClasses.h" TEST(samson_worker_SamsonWorker, basic) { EXPECT_EQ(0, au::Singleton<au::ThreadManager>::shared()->num_threads()); // Init engine engine::Engine::InitEngine(4, 10000000, 1); // Create a worker samson::SamsonWorker *worker = new samson::SamsonWorker("no_zk_host", 9000, 9001); // Stop engine engine::Engine::StopEngine(); // Remove worker delete worker; // Destroyinh engine engine::Engine::DestroyEngine(); // Make sure no background threads are left there EXPECT_EQ(0, au::Singleton<au::ThreadManager>::shared()->num_threads()); } <|endoftext|>