text
stringlengths
54
60.6k
<commit_before>#include "ui.hpp" #include "../utils/utils.hpp" #include <cstdio> #include <cerrno> #include <SDL/SDL.h> #include <SDL/SDL_image.h> #include <SDL/SDL_opengl.h> Ui::Ui(unsigned int w, unsigned int h, bool r) : scene(w, h), record(r) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) fatal("failed to initialiaze SDL: %s", SDL_GetError()); int flags = IMG_INIT_PNG; int inited = IMG_Init(flags); if ((inited & flags) != flags) fatal("Failed to initialize .png support"); flags = SDL_GL_DOUBLEBUFFER | SDL_OPENGL; unsigned int color = 32; screen = SDL_SetVideoMode(scene.width, scene.height, color, flags); if (!screen) fatal("failed to create a window: %s", SDL_GetError()); fprintf(stderr, "Vendor: %s\nRenderer: %s\nVersion: %s\nShade Lang. Version: %s\n", glGetString(GL_VENDOR), glGetString(GL_RENDERER), glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); glDisable(GL_DEPTH_TEST); glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTranslated(-1.0, -1.0, 0.0); glScaled(2.0 / scene.width, 2.0 / scene.height, 0.0); glClearColor(1.0, 1.0, 1.0, 0.0); chkerror("after initialization"); } void Ui::run(unsigned long frametime) { std::vector<std::string> frames; for (unsigned long n = 0; ; n++) { long tick = SDL_GetTicks(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (!frame()) break; scene.render(); glFlush(); if (record) frames.push_back(saveframe(n)); SDL_GL_SwapBuffers(); chkerror("after swap buffers"); if (handleevents()) break; long delay = tick + frametime - SDL_GetTicks(); if (delay > 0) SDL_Delay(delay); } if (record) { if (fileexists("anim.mp4")) remove("anim.mp4"); std::string cmd = "ffmpeg"; char ratestr[128]; snprintf(ratestr, sizeof(ratestr), "%lu", 1000/frametime); cmd += " -r " + std::string(ratestr); cmd += " -b 4096k -i /tmp/%08d.ppm anim.mp4"; printf("%s\n", cmd.c_str()); if (system(cmd.c_str()) != 0) fatal("%s failed", cmd.c_str()); for (auto f = frames.begin(); f != frames.end(); f++) remove(f->c_str()); } } void Ui::chkerror(const char *str) { GLenum err = glGetError(); switch (err) { case GL_NO_ERROR: break; case GL_INVALID_ENUM: fatal("GL error %s: GL_INVALID_ENUM (%d)", str, err); case GL_INVALID_VALUE: fatal("GL error %s: GL_INVALID_VALUE (%d)", str, err); case GL_INVALID_OPERATION: fatal("GL error %s: GL_INVALID_OPERATION (%d)", str, err); case GL_STACK_OVERFLOW: fatal("GL error %s: GL_STACK_OVERFLOW (%d)", str, err); case GL_STACK_UNDERFLOW: fatal("GL error %s: GL_STACK_UNDERFLOW (%d)", str, err); case GL_OUT_OF_MEMORY: fatal("GL error %s: GL_OUT_OF_MEMORY (%d)", str, err); case GL_TABLE_TOO_LARGE: fatal("GL error %s: GL_TABLE_TOO_LARGE (%d)", str, err); default: fatal("Unknow GL error %s: %d\n", err); } } bool Ui::handleevents() { for ( ; ; ) { SDL_Event e; int p = SDL_PollEvent(&e); if (!p) break; switch(e.type) { case SDL_QUIT: return true; case SDL_KEYDOWN: key(e.key.keysym.sym, true); break; case SDL_KEYUP: key(e.key.keysym.sym, false); break; case SDL_MOUSEMOTION: motion(e.motion.x, e.motion.y, e.motion.xrel, e.motion.yrel); break; case SDL_MOUSEBUTTONDOWN: click(e.button.x, e.button.y, e.button.button, true); break; case SDL_MOUSEBUTTONUP: click(e.button.x, e.button.y, e.button.button, false); break; default: break; } } return false; } bool Ui::frame() { scene.clear(); geom2d::Pt center(scene.width / 2, scene.height / 2); unsigned int color = 0; geom2d::Poly p = geom2d::Poly::random(10, 0, 0, 1); p.scale(scene.width / 2, scene.height / 2); p.translate(scene.width / 2, scene.height / 2); scene.add(new Scene::Poly(p, somecolors[color++ % Nsomecolors], 1)); geom2d::Arc a = geom2d::Arc(center, scene.width / 10, 0, M_PI); scene.add(new Scene::Arc(a, somecolors[color++ % Nsomecolors], 1)); scene.add(new Scene::Pt(geom2d::Pt(0.0, 0.0), Image::blue, 10, 1)); scene.add(new Scene::Pt(geom2d::Pt(scene.width, scene.height), Image::green, 10, 1)); return true; } void Ui::key(int key, bool down) { printf("key %d %s\n", key, down ? "down" : "up"); } void Ui::motion(int x, int y, int dx, int dy) { printf("mouse motion: (%d, %d) delta=(%d, %d)\n", x, y, dx, dy); } void Ui::click(int x ,int y, int button, bool down) { printf("mouse click: button %d at (%d, %d) %s\n", button, x, y, down ? "down" : "up"); } std::string Ui::saveframe(unsigned long n) { char name[128]; snprintf(name, sizeof(name), "/tmp/%08lu.ppm", n); FILE *out = fopen(name, "w"); if (!out) fatalx(errno, "Failed to open %s for writing", name); fprintf(out, "P6\n"); fprintf(out, "%d %d\n", screen->w, screen->h); fprintf(out, "255\n"); char *pixels = new char[3*screen->w]; for (int y = screen->h-1; y >= 0; y--) { glReadPixels(0, y, screen->w, 1, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)pixels); size_t rem = screen->w; do { size_t n = fwrite(pixels, 3, rem, out); if (n < rem && ferror(out)) fatal("Failed to write the pixel data"); rem -= n; } while (rem > 0); } delete pixels; fclose(out); return name; } <commit_msg>graphics: constant quality in generated videos.<commit_after>#include "ui.hpp" #include "../utils/utils.hpp" #include <cstdio> #include <cerrno> #include <SDL/SDL.h> #include <SDL/SDL_image.h> #include <SDL/SDL_opengl.h> Ui::Ui(unsigned int w, unsigned int h, bool r) : scene(w, h), record(r) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) fatal("failed to initialiaze SDL: %s", SDL_GetError()); int flags = IMG_INIT_PNG; int inited = IMG_Init(flags); if ((inited & flags) != flags) fatal("Failed to initialize .png support"); flags = SDL_GL_DOUBLEBUFFER | SDL_OPENGL; unsigned int color = 32; screen = SDL_SetVideoMode(scene.width, scene.height, color, flags); if (!screen) fatal("failed to create a window: %s", SDL_GetError()); fprintf(stderr, "Vendor: %s\nRenderer: %s\nVersion: %s\nShade Lang. Version: %s\n", glGetString(GL_VENDOR), glGetString(GL_RENDERER), glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); glDisable(GL_DEPTH_TEST); glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTranslated(-1.0, -1.0, 0.0); glScaled(2.0 / scene.width, 2.0 / scene.height, 0.0); glClearColor(1.0, 1.0, 1.0, 0.0); chkerror("after initialization"); } void Ui::run(unsigned long frametime) { std::vector<std::string> frames; for (unsigned long n = 0; ; n++) { long tick = SDL_GetTicks(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (!frame()) break; scene.render(); glFlush(); if (record) frames.push_back(saveframe(n)); SDL_GL_SwapBuffers(); chkerror("after swap buffers"); if (handleevents()) break; long delay = tick + frametime - SDL_GetTicks(); if (delay > 0) SDL_Delay(delay); } if (record) { if (fileexists("anim.mp4")) remove("anim.mp4"); std::string cmd = "ffmpeg"; char ratestr[128]; snprintf(ratestr, sizeof(ratestr), "%lu", 1000/frametime); cmd += " -r " + std::string(ratestr); cmd += " -qscale 1"; cmd += " -i /tmp/%08d.ppm anim.mp4"; printf("%s\n", cmd.c_str()); if (system(cmd.c_str()) != 0) fatal("%s failed", cmd.c_str()); for (auto f = frames.begin(); f != frames.end(); f++) remove(f->c_str()); } } void Ui::chkerror(const char *str) { GLenum err = glGetError(); switch (err) { case GL_NO_ERROR: break; case GL_INVALID_ENUM: fatal("GL error %s: GL_INVALID_ENUM (%d)", str, err); case GL_INVALID_VALUE: fatal("GL error %s: GL_INVALID_VALUE (%d)", str, err); case GL_INVALID_OPERATION: fatal("GL error %s: GL_INVALID_OPERATION (%d)", str, err); case GL_STACK_OVERFLOW: fatal("GL error %s: GL_STACK_OVERFLOW (%d)", str, err); case GL_STACK_UNDERFLOW: fatal("GL error %s: GL_STACK_UNDERFLOW (%d)", str, err); case GL_OUT_OF_MEMORY: fatal("GL error %s: GL_OUT_OF_MEMORY (%d)", str, err); case GL_TABLE_TOO_LARGE: fatal("GL error %s: GL_TABLE_TOO_LARGE (%d)", str, err); default: fatal("Unknow GL error %s: %d\n", err); } } bool Ui::handleevents() { for ( ; ; ) { SDL_Event e; int p = SDL_PollEvent(&e); if (!p) break; switch(e.type) { case SDL_QUIT: return true; case SDL_KEYDOWN: key(e.key.keysym.sym, true); break; case SDL_KEYUP: key(e.key.keysym.sym, false); break; case SDL_MOUSEMOTION: motion(e.motion.x, e.motion.y, e.motion.xrel, e.motion.yrel); break; case SDL_MOUSEBUTTONDOWN: click(e.button.x, e.button.y, e.button.button, true); break; case SDL_MOUSEBUTTONUP: click(e.button.x, e.button.y, e.button.button, false); break; default: break; } } return false; } bool Ui::frame() { scene.clear(); geom2d::Pt center(scene.width / 2, scene.height / 2); unsigned int color = 0; geom2d::Poly p = geom2d::Poly::random(10, 0, 0, 1); p.scale(scene.width / 2, scene.height / 2); p.translate(scene.width / 2, scene.height / 2); scene.add(new Scene::Poly(p, somecolors[color++ % Nsomecolors], 1)); geom2d::Arc a = geom2d::Arc(center, scene.width / 10, 0, M_PI); scene.add(new Scene::Arc(a, somecolors[color++ % Nsomecolors], 1)); scene.add(new Scene::Pt(geom2d::Pt(0.0, 0.0), Image::blue, 10, 1)); scene.add(new Scene::Pt(geom2d::Pt(scene.width, scene.height), Image::green, 10, 1)); return true; } void Ui::key(int key, bool down) { printf("key %d %s\n", key, down ? "down" : "up"); } void Ui::motion(int x, int y, int dx, int dy) { printf("mouse motion: (%d, %d) delta=(%d, %d)\n", x, y, dx, dy); } void Ui::click(int x ,int y, int button, bool down) { printf("mouse click: button %d at (%d, %d) %s\n", button, x, y, down ? "down" : "up"); } std::string Ui::saveframe(unsigned long n) { char name[128]; snprintf(name, sizeof(name), "/tmp/%08lu.ppm", n); FILE *out = fopen(name, "w"); if (!out) fatalx(errno, "Failed to open %s for writing", name); fprintf(out, "P6\n"); fprintf(out, "%d %d\n", screen->w, screen->h); fprintf(out, "255\n"); char *pixels = new char[3*screen->w]; for (int y = screen->h-1; y >= 0; y--) { glReadPixels(0, y, screen->w, 1, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)pixels); size_t rem = screen->w; do { size_t n = fwrite(pixels, 3, rem, out); if (n < rem && ferror(out)) fatal("Failed to write the pixel data"); rem -= n; } while (rem > 0); } delete pixels; fclose(out); return name; } <|endoftext|>
<commit_before>#include <GL/glew.h> #include <GLFW/glfw3.h> #include <Engine/MainWindow.hpp> #include "Editor.hpp" #include "Util/EditorSettings.hpp" #include <Engine/Util/Input.hpp> #include <Engine/Util/FileSystem.hpp> #include <Utility/Log.hpp> #include <Engine/Input/Input.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ScriptManager.hpp> #include <Engine/Manager/ProfilingManager.hpp> #include <Engine/Manager/ParticleManager.hpp> #include <Engine/Manager/DebugDrawingManager.hpp> #include <Engine/Util/Profiling.hpp> #include <Engine/Hymn.hpp> #include <thread> #include "ImGui/OpenGLImplementation.hpp" #include <imgui.h> #ifdef VR_SUPPORT #include <openvr.h> #endif int main() { // Enable logging if requested. if (EditorSettings::GetInstance().GetBool("Logging")){ FILE* file = freopen(FileSystem::DataPath("Hymn to Beauty", "log.txt").c_str(), "a", stderr); if (file == nullptr) Log() << "Could not open logging file!"; } Log() << "Editor started - " << time(nullptr) << "\n"; if (!glfwInit()) return 1; MainWindow* window = new MainWindow(EditorSettings::GetInstance().GetLong("Width"), EditorSettings::GetInstance().GetLong("Height"), false, false, "Hymn to Beauty", EditorSettings::GetInstance().GetBool("Debug Context")); glewInit(); window->Init(false); // Init VR. #ifdef VR_SUPPORT vr::EVRInitError error; vr::IVRSystem* vrSystem = vr::VR_Init(&error, vr::VRApplication_Scene); Log() << "VR init: " << error << "\n"; #endif Input::GetInstance().SetWindow(window->GetGLFWWindow()); Managers().StartUp(); Editor* editor = new Editor(); // Setup imgui implementation. ImGuiImplementation::Init(window->GetGLFWWindow()); bool profiling = false; // Main loop. double targetFPS = 60.0; double lastTime = glfwGetTime(); double lastTimeRender = glfwGetTime(); while (!window->ShouldClose() || !editor->ReadyToClose()) { float deltaTime = static_cast<float>(glfwGetTime() - lastTime); lastTime = glfwGetTime(); // Begin new profiling frame. Managers().profilingManager->BeginFrame(); { PROFILE("Frame"); glfwPollEvents(); if (Input()->Triggered(InputHandler::PROFILE)) profiling = !profiling; // Start new frame. ImGuiImplementation::NewFrame(); window->Update(); if (editor->IsVisible()) { Hymn().world.ClearKilled(); Managers().particleManager->Update(Hymn().world, deltaTime, true); Managers().debugDrawingManager->Update(deltaTime); Hymn().Render(editor->GetCamera(), EditorSettings::GetInstance().GetBool("Sound Source Icons"), EditorSettings::GetInstance().GetBool("Particle Emitter Icons"), EditorSettings::GetInstance().GetBool("Light Source Icons"), EditorSettings::GetInstance().GetBool("Camera Icons"), EditorSettings::GetInstance().GetBool("Physics Volumes"), EditorSettings::GetInstance().GetBool("Grid Settings")); if (window->ShouldClose()) editor->Close(); editor->Show(deltaTime); if (window->ShouldClose() && !editor->isClosing()) window->CancelClose(); } else { { PROFILE("Update"); Hymn().Update(deltaTime); } { PROFILE("Render"); Hymn().Render(); } if (Input()->Triggered(InputHandler::PLAYTEST)) { // Rollback to the editor state. editor->LoadEditorState(); // Turn editor back on. editor->SetVisible(true); } } } if (profiling) Managers().profilingManager->ShowResults(); ImGui::Render(); // Swap buffers and wait until next frame. window->SwapBuffers(); long wait = static_cast<long>((1.0 / targetFPS + lastTimeRender - glfwGetTime()) * 1000000.0); if (wait > 0) std::this_thread::sleep_for(std::chrono::microseconds(wait)); lastTimeRender = glfwGetTime(); } // Save. EditorSettings::GetInstance().Save(); if (editor->IsVisible()) editor->Save(); // Shut down and cleanup. ImGuiImplementation::Shutdown(); delete editor; Hymn().world.Clear(); Managers().ShutDown(); delete window; glfwTerminate(); Log() << "Editor ended - " << time(nullptr) << "\n"; return 0; } <commit_msg>Update main.cpp<commit_after>#include <GL/glew.h> #include <GLFW/glfw3.h> #include <Engine/MainWindow.hpp> #include "Editor.hpp" #include "Util/EditorSettings.hpp" #include <Engine/Util/Input.hpp> #include <Engine/Util/FileSystem.hpp> #include <Utility/Log.hpp> #include <Engine/Input/Input.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ScriptManager.hpp> #include <Engine/Manager/ProfilingManager.hpp> #include <Engine/Manager/ParticleManager.hpp> #include <Engine/Manager/DebugDrawingManager.hpp> #include <Engine/Util/Profiling.hpp> #include <Engine/Hymn.hpp> #include <thread> #include "ImGui/OpenGLImplementation.hpp" #include <imgui.h> #ifdef VR_SUPPORT #include <openvr.h> #endif int main() { // Enable logging if requested. if (EditorSettings::GetInstance().GetBool("Logging")){ FILE* file = freopen(FileSystem::DataPath("Hymn to Beauty", "log.txt").c_str(), "a", stderr); if (file == nullptr) Log() << "Could not open logging file!\n"; } Log() << "Editor started - " << time(nullptr) << "\n"; if (!glfwInit()) return 1; MainWindow* window = new MainWindow(EditorSettings::GetInstance().GetLong("Width"), EditorSettings::GetInstance().GetLong("Height"), false, false, "Hymn to Beauty", EditorSettings::GetInstance().GetBool("Debug Context")); glewInit(); window->Init(false); // Init VR. #ifdef VR_SUPPORT vr::EVRInitError error; vr::IVRSystem* vrSystem = vr::VR_Init(&error, vr::VRApplication_Scene); Log() << "VR init: " << error << "\n"; #endif Input::GetInstance().SetWindow(window->GetGLFWWindow()); Managers().StartUp(); Editor* editor = new Editor(); // Setup imgui implementation. ImGuiImplementation::Init(window->GetGLFWWindow()); bool profiling = false; // Main loop. double targetFPS = 60.0; double lastTime = glfwGetTime(); double lastTimeRender = glfwGetTime(); while (!window->ShouldClose() || !editor->ReadyToClose()) { float deltaTime = static_cast<float>(glfwGetTime() - lastTime); lastTime = glfwGetTime(); // Begin new profiling frame. Managers().profilingManager->BeginFrame(); { PROFILE("Frame"); glfwPollEvents(); if (Input()->Triggered(InputHandler::PROFILE)) profiling = !profiling; // Start new frame. ImGuiImplementation::NewFrame(); window->Update(); if (editor->IsVisible()) { Hymn().world.ClearKilled(); Managers().particleManager->Update(Hymn().world, deltaTime, true); Managers().debugDrawingManager->Update(deltaTime); Hymn().Render(editor->GetCamera(), EditorSettings::GetInstance().GetBool("Sound Source Icons"), EditorSettings::GetInstance().GetBool("Particle Emitter Icons"), EditorSettings::GetInstance().GetBool("Light Source Icons"), EditorSettings::GetInstance().GetBool("Camera Icons"), EditorSettings::GetInstance().GetBool("Physics Volumes"), EditorSettings::GetInstance().GetBool("Grid Settings")); if (window->ShouldClose()) editor->Close(); editor->Show(deltaTime); if (window->ShouldClose() && !editor->isClosing()) window->CancelClose(); } else { { PROFILE("Update"); Hymn().Update(deltaTime); } { PROFILE("Render"); Hymn().Render(); } if (Input()->Triggered(InputHandler::PLAYTEST)) { // Rollback to the editor state. editor->LoadEditorState(); // Turn editor back on. editor->SetVisible(true); } } } if (profiling) Managers().profilingManager->ShowResults(); ImGui::Render(); // Swap buffers and wait until next frame. window->SwapBuffers(); long wait = static_cast<long>((1.0 / targetFPS + lastTimeRender - glfwGetTime()) * 1000000.0); if (wait > 0) std::this_thread::sleep_for(std::chrono::microseconds(wait)); lastTimeRender = glfwGetTime(); } // Save. EditorSettings::GetInstance().Save(); if (editor->IsVisible()) editor->Save(); // Shut down and cleanup. ImGuiImplementation::Shutdown(); delete editor; Hymn().world.Clear(); Managers().ShutDown(); delete window; glfwTerminate(); Log() << "Editor ended - " << time(nullptr) << "\n"; return 0; } <|endoftext|>
<commit_before>/*********************************************************************** created: 21/2/2004 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 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 "CEGUI/Font.h" #include "CEGUI/Exceptions.h" #include "CEGUI/Font_xmlHandler.h" #include "CEGUI/PropertyHelper.h" #include "CEGUI/System.h" #include "CEGUI/Image.h" #include "CEGUI/BitmapImage.h" #include <iterator> namespace CEGUI { //----------------------------------------------------------------------------// // amount of bits in a uint #define BITS_PER_UINT (sizeof (unsigned int) * 8) // must be a power of two #define GLYPHS_PER_PAGE 256 //----------------------------------------------------------------------------// const argb_t Font::DefaultColour = 0xFFFFFFFF; String Font::d_defaultResourceGroup; //----------------------------------------------------------------------------// const String Font::EventNamespace("Font"); const String Font::EventRenderSizeChanged("RenderSizeChanged"); //----------------------------------------------------------------------------// Font::Font(const String& name, const String& type_name, const String& filename, const String& resource_group, const AutoScaledMode auto_scaled, const Sizef& native_res): d_name(name), d_type(type_name), d_filename(filename), d_resourceGroup(resource_group), d_ascender(0), d_descender(0), d_height(0), d_autoScaled(auto_scaled), d_nativeResolution(native_res), d_maxCodepoint(0), d_loadedGlyphPages(0) { addFontProperties(); const Sizef size(System::getSingleton().getRenderer()->getDisplaySize()); Image::computeScalingFactors(d_autoScaled, size, d_nativeResolution, d_horzScaling, d_vertScaling); } //----------------------------------------------------------------------------// Font::~Font() { } //----------------------------------------------------------------------------// const String& Font::getName() const { return d_name; } //----------------------------------------------------------------------------// const String& Font::getTypeName() const { return d_type; } //----------------------------------------------------------------------------// const String& Font::getFileName() const { return d_filename; } //----------------------------------------------------------------------------// void Font::addFontProperties() { const String propertyOrigin("Font"); CEGUI_DEFINE_PROPERTY(Font, Sizef, "NativeRes", "Native screen resolution for this font." "Value uses the 'w:# h:#' format.", &Font::setNativeResolution, &Font::getNativeResolution, Sizef::zero() ); CEGUI_DEFINE_PROPERTY(Font, String, "Name", "This is font name. Value is a string.", 0, &Font::getName, "" ); CEGUI_DEFINE_PROPERTY(Font, AutoScaledMode, "AutoScaled", "This indicating whether and how to autoscale font depending on " "resolution. Value can be 'false', 'vertical', 'horizontal' or 'true'.", &Font::setAutoScaled, &Font::getAutoScaled, ASM_Disabled ); } //----------------------------------------------------------------------------// void Font::setMaxCodepoint(char32_t codepoint) { d_maxCodepoint = codepoint; const unsigned int npages = (codepoint + GLYPHS_PER_PAGE) / GLYPHS_PER_PAGE; const unsigned int size = (npages + BITS_PER_UINT - 1) / BITS_PER_UINT; d_loadedGlyphPages.resize(size); std::fill(d_loadedGlyphPages.begin(), d_loadedGlyphPages.end(), 0); } //----------------------------------------------------------------------------// const FontGlyph* Font::getGlyphData(char32_t codepoint) const { if (codepoint > d_maxCodepoint) return 0; const FontGlyph* const glyph = findFontGlyph(codepoint); if (!d_loadedGlyphPages.empty()) { // Check if glyph page has been rasterised unsigned int page = codepoint / GLYPHS_PER_PAGE; unsigned int mask = 1 << (page & (BITS_PER_UINT - 1)); if (!(d_loadedGlyphPages[page / BITS_PER_UINT] & mask)) { d_loadedGlyphPages[page / BITS_PER_UINT] |= mask; rasterise(codepoint & ~(GLYPHS_PER_PAGE - 1), codepoint | (GLYPHS_PER_PAGE - 1)); } } return glyph; } //----------------------------------------------------------------------------// const FontGlyph* Font::findFontGlyph(const char32_t codepoint) const { CodepointMap::const_iterator pos = d_cp_map.find(codepoint); return (pos != d_cp_map.end()) ? &pos->second : 0; } float Font::getTextExtent(const String& text, float x_scale) const { float cur_extent = 0.0f; float adv_extent = 0.0f; #if (CEGUI_STRING_CLASS != CEGUI_STRING_CLASS_UTF_8) for (size_t c = 0; c < text.length(); ++c) { char32_t currentCodePoint = text[c]; getGlyphExtents(currentCodePoint, cur_extent, adv_extent, x_scale); } #else String::codepoint_iterator currentCodePointIter(text.begin(), text.begin(), text.end()); while (!currentCodePointIter.isAtEnd()) { char32_t currentCodePoint = *currentCodePointIter; getGlyphExtents(currentCodePoint, cur_extent, adv_extent, x_scale); ++currentCodePointIter; } #endif return std::max(adv_extent, cur_extent); } void Font::getGlyphExtents(char32_t currentCodePoint, float& cur_extent, float& adv_extent, float x_scale) const { const FontGlyph* glyph = getGlyphData(currentCodePoint); if (glyph != nullptr) { float width = glyph->getRenderedAdvance(x_scale); if (adv_extent + width > cur_extent) { cur_extent = adv_extent + width; } adv_extent += glyph->getAdvance(x_scale); } } //----------------------------------------------------------------------------// float Font::getTextAdvance(const String& text, float x_scale) const { float advance = 0.0f; #if (CEGUI_STRING_CLASS != CEGUI_STRING_CLASS_UTF_8) for (size_t c = 0; c < text.length(); ++c) { if (const FontGlyph* glyph = getGlyphData(text[c])) { advance += glyph->getAdvance(x_scale); } } #else String::codepoint_iterator currentCodePointIter(text.begin(), text.begin(), text.end()); while (!currentCodePointIter.isAtEnd()) { char32_t currentCodePoint = *currentCodePointIter; if (const FontGlyph* glyph = getGlyphData(currentCodePoint)) { advance += glyph->getAdvance(x_scale); } ++currentCodePointIter; } #endif return advance; } //----------------------------------------------------------------------------// size_t Font::getCharAtPixel(const String& text, size_t start_char, float pixel, float x_scale) const { const FontGlyph* glyph; float cur_extent = 0; size_t char_count = text.length(); // handle simple cases if ((pixel <= 0) || (char_count <= start_char)) return start_char; #if (CEGUI_STRING_CLASS != CEGUI_STRING_CLASS_UTF_8) for (size_t c = start_char; c < char_count; ++c) { glyph = getGlyphData(text[c]); if (glyph) { cur_extent += glyph->getAdvance(x_scale); if (pixel < cur_extent) return c; } } #else String::codepoint_iterator currentCodePointIter(text.begin(), text.begin(), text.end()); currentCodePointIter.increment(start_char); while (!currentCodePointIter.isAtEnd()) { char32_t currentCodePoint = *currentCodePointIter; glyph = getGlyphData(currentCodePoint); if (glyph) { cur_extent += glyph->getAdvance(x_scale); if (pixel < cur_extent) return currentCodePointIter.getCodeUnitIndexFromStart(); } ++currentCodePointIter; } #endif return char_count; } //----------------------------------------------------------------------------// float Font::drawText(std::vector<GeometryBuffer*>& geom_buffers, const String& text, const glm::vec2& position, const Rectf* clip_rect, const bool clipping_enabled, const ColourRect& colours, const float space_extra, const float x_scale, const float y_scale) const { const float base_y = position.y + getBaseline(y_scale); glm::vec2 glyph_pos(position); #if (CEGUI_STRING_CLASS != CEGUI_STRING_CLASS_UTF_8) for (size_t c = 0; c < text.length(); ++c) { char32_t& currentCodePoint = text[c]; #else String::codepoint_iterator currentCodePointIter(text.begin(), text.begin(), text.end()); while (!currentCodePointIter.isAtEnd()) { char32_t currentCodePoint = *currentCodePointIter; #endif const FontGlyph* glyph = getGlyphData(currentCodePoint); if (glyph != nullptr) { const Image* const img = glyph->getImage(); glyph_pos.y = base_y - (img->getRenderedOffset().y - img->getRenderedOffset().y * y_scale); img->render(geom_buffers, glyph_pos, glyph->getSize(x_scale, y_scale), clip_rect, clipping_enabled, colours); glyph_pos.x += glyph->getAdvance(x_scale); // apply extra spacing to space chars if (currentCodePoint == ' ') glyph_pos.x += space_extra; } #if (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_8) ++currentCodePointIter; #endif } return glyph_pos.x; } //----------------------------------------------------------------------------// void Font::setNativeResolution(const Sizef& size) { d_nativeResolution = size; // re-calculate scaling factors & notify images as required notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } //----------------------------------------------------------------------------// const Sizef& Font::getNativeResolution() const { return d_nativeResolution; } //----------------------------------------------------------------------------// void Font::setAutoScaled(const AutoScaledMode auto_scaled) { if (auto_scaled == d_autoScaled) return; d_autoScaled = auto_scaled; updateFont(); FontEventArgs args(this); onRenderSizeChanged(args); } //----------------------------------------------------------------------------// AutoScaledMode Font::getAutoScaled() const { return d_autoScaled; } //----------------------------------------------------------------------------// void Font::notifyDisplaySizeChanged(const Sizef& size) { Image::computeScalingFactors(d_autoScaled, size, d_nativeResolution, d_horzScaling, d_vertScaling); if (d_autoScaled != ASM_Disabled) { updateFont(); FontEventArgs args(this); onRenderSizeChanged(args); } } //----------------------------------------------------------------------------// void Font::rasterise(char32_t, char32_t) const { // do nothing by default } //----------------------------------------------------------------------------// void Font::writeXMLToStream(XMLSerializer& xml_stream) const { // output starting <Font ... > element xml_stream.openTag("Font") .attribute(Font_xmlHandler::FontNameAttribute, d_name) .attribute(Font_xmlHandler::FontFilenameAttribute, d_filename); if (!d_resourceGroup.empty()) xml_stream.attribute(Font_xmlHandler::FontResourceGroupAttribute, d_resourceGroup); if (d_nativeResolution.d_width != DefaultNativeHorzRes) xml_stream.attribute(Font_xmlHandler::FontNativeHorzResAttribute, PropertyHelper<std::uint32_t>::toString(static_cast<std::uint32_t>(d_nativeResolution.d_width))); if (d_nativeResolution.d_height != DefaultNativeVertRes) xml_stream.attribute(Font_xmlHandler::FontNativeVertResAttribute, PropertyHelper<std::uint32_t>::toString(static_cast<std::uint32_t>(d_nativeResolution.d_height))); if (d_autoScaled != ASM_Disabled) xml_stream.attribute(Font_xmlHandler::FontAutoScaledAttribute, PropertyHelper<AutoScaledMode>::toString(d_autoScaled)); writeXMLToStream_impl(xml_stream); // output closing </Font> element. xml_stream.closeTag(); } //----------------------------------------------------------------------------// void Font::onRenderSizeChanged(FontEventArgs& e) { fireEvent(EventRenderSizeChanged, e, EventNamespace); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>MOD: ASCII/UTF32 String compile fix<commit_after>/*********************************************************************** created: 21/2/2004 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 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 "CEGUI/Font.h" #include "CEGUI/Exceptions.h" #include "CEGUI/Font_xmlHandler.h" #include "CEGUI/PropertyHelper.h" #include "CEGUI/System.h" #include "CEGUI/Image.h" #include "CEGUI/BitmapImage.h" #include <iterator> namespace CEGUI { //----------------------------------------------------------------------------// // amount of bits in a uint #define BITS_PER_UINT (sizeof (unsigned int) * 8) // must be a power of two #define GLYPHS_PER_PAGE 256 //----------------------------------------------------------------------------// const argb_t Font::DefaultColour = 0xFFFFFFFF; String Font::d_defaultResourceGroup; //----------------------------------------------------------------------------// const String Font::EventNamespace("Font"); const String Font::EventRenderSizeChanged("RenderSizeChanged"); //----------------------------------------------------------------------------// Font::Font(const String& name, const String& type_name, const String& filename, const String& resource_group, const AutoScaledMode auto_scaled, const Sizef& native_res): d_name(name), d_type(type_name), d_filename(filename), d_resourceGroup(resource_group), d_ascender(0), d_descender(0), d_height(0), d_autoScaled(auto_scaled), d_nativeResolution(native_res), d_maxCodepoint(0), d_loadedGlyphPages(0) { addFontProperties(); const Sizef size(System::getSingleton().getRenderer()->getDisplaySize()); Image::computeScalingFactors(d_autoScaled, size, d_nativeResolution, d_horzScaling, d_vertScaling); } //----------------------------------------------------------------------------// Font::~Font() { } //----------------------------------------------------------------------------// const String& Font::getName() const { return d_name; } //----------------------------------------------------------------------------// const String& Font::getTypeName() const { return d_type; } //----------------------------------------------------------------------------// const String& Font::getFileName() const { return d_filename; } //----------------------------------------------------------------------------// void Font::addFontProperties() { const String propertyOrigin("Font"); CEGUI_DEFINE_PROPERTY(Font, Sizef, "NativeRes", "Native screen resolution for this font." "Value uses the 'w:# h:#' format.", &Font::setNativeResolution, &Font::getNativeResolution, Sizef::zero() ); CEGUI_DEFINE_PROPERTY(Font, String, "Name", "This is font name. Value is a string.", 0, &Font::getName, "" ); CEGUI_DEFINE_PROPERTY(Font, AutoScaledMode, "AutoScaled", "This indicating whether and how to autoscale font depending on " "resolution. Value can be 'false', 'vertical', 'horizontal' or 'true'.", &Font::setAutoScaled, &Font::getAutoScaled, ASM_Disabled ); } //----------------------------------------------------------------------------// void Font::setMaxCodepoint(char32_t codepoint) { d_maxCodepoint = codepoint; const unsigned int npages = (codepoint + GLYPHS_PER_PAGE) / GLYPHS_PER_PAGE; const unsigned int size = (npages + BITS_PER_UINT - 1) / BITS_PER_UINT; d_loadedGlyphPages.resize(size); std::fill(d_loadedGlyphPages.begin(), d_loadedGlyphPages.end(), 0); } //----------------------------------------------------------------------------// const FontGlyph* Font::getGlyphData(char32_t codepoint) const { if (codepoint > d_maxCodepoint) return 0; const FontGlyph* const glyph = findFontGlyph(codepoint); if (!d_loadedGlyphPages.empty()) { // Check if glyph page has been rasterised unsigned int page = codepoint / GLYPHS_PER_PAGE; unsigned int mask = 1 << (page & (BITS_PER_UINT - 1)); if (!(d_loadedGlyphPages[page / BITS_PER_UINT] & mask)) { d_loadedGlyphPages[page / BITS_PER_UINT] |= mask; rasterise(codepoint & ~(GLYPHS_PER_PAGE - 1), codepoint | (GLYPHS_PER_PAGE - 1)); } } return glyph; } //----------------------------------------------------------------------------// const FontGlyph* Font::findFontGlyph(const char32_t codepoint) const { CodepointMap::const_iterator pos = d_cp_map.find(codepoint); return (pos != d_cp_map.end()) ? &pos->second : 0; } float Font::getTextExtent(const String& text, float x_scale) const { float cur_extent = 0.0f; float adv_extent = 0.0f; #if (CEGUI_STRING_CLASS != CEGUI_STRING_CLASS_UTF_8) for (size_t c = 0; c < text.length(); ++c) { char32_t currentCodePoint = text[c]; getGlyphExtents(currentCodePoint, cur_extent, adv_extent, x_scale); } #else String::codepoint_iterator currentCodePointIter(text.begin(), text.begin(), text.end()); while (!currentCodePointIter.isAtEnd()) { char32_t currentCodePoint = *currentCodePointIter; getGlyphExtents(currentCodePoint, cur_extent, adv_extent, x_scale); ++currentCodePointIter; } #endif return std::max(adv_extent, cur_extent); } void Font::getGlyphExtents(char32_t currentCodePoint, float& cur_extent, float& adv_extent, float x_scale) const { const FontGlyph* glyph = getGlyphData(currentCodePoint); if (glyph != nullptr) { float width = glyph->getRenderedAdvance(x_scale); if (adv_extent + width > cur_extent) { cur_extent = adv_extent + width; } adv_extent += glyph->getAdvance(x_scale); } } //----------------------------------------------------------------------------// float Font::getTextAdvance(const String& text, float x_scale) const { float advance = 0.0f; #if (CEGUI_STRING_CLASS != CEGUI_STRING_CLASS_UTF_8) for (size_t c = 0; c < text.length(); ++c) { if (const FontGlyph* glyph = getGlyphData(text[c])) { advance += glyph->getAdvance(x_scale); } } #else String::codepoint_iterator currentCodePointIter(text.begin(), text.begin(), text.end()); while (!currentCodePointIter.isAtEnd()) { char32_t currentCodePoint = *currentCodePointIter; if (const FontGlyph* glyph = getGlyphData(currentCodePoint)) { advance += glyph->getAdvance(x_scale); } ++currentCodePointIter; } #endif return advance; } //----------------------------------------------------------------------------// size_t Font::getCharAtPixel(const String& text, size_t start_char, float pixel, float x_scale) const { const FontGlyph* glyph; float cur_extent = 0; size_t char_count = text.length(); // handle simple cases if ((pixel <= 0) || (char_count <= start_char)) return start_char; #if (CEGUI_STRING_CLASS != CEGUI_STRING_CLASS_UTF_8) for (size_t c = start_char; c < char_count; ++c) { glyph = getGlyphData(text[c]); if (glyph) { cur_extent += glyph->getAdvance(x_scale); if (pixel < cur_extent) return c; } } #else String::codepoint_iterator currentCodePointIter(text.begin(), text.begin(), text.end()); currentCodePointIter.increment(start_char); while (!currentCodePointIter.isAtEnd()) { char32_t currentCodePoint = *currentCodePointIter; glyph = getGlyphData(currentCodePoint); if (glyph) { cur_extent += glyph->getAdvance(x_scale); if (pixel < cur_extent) return currentCodePointIter.getCodeUnitIndexFromStart(); } ++currentCodePointIter; } #endif return char_count; } //----------------------------------------------------------------------------// float Font::drawText(std::vector<GeometryBuffer*>& geom_buffers, const String& text, const glm::vec2& position, const Rectf* clip_rect, const bool clipping_enabled, const ColourRect& colours, const float space_extra, const float x_scale, const float y_scale) const { const float base_y = position.y + getBaseline(y_scale); glm::vec2 glyph_pos(position); #if (CEGUI_STRING_CLASS != CEGUI_STRING_CLASS_UTF_8) for (size_t c = 0; c < text.length(); ++c) { const char32_t& currentCodePoint = text[c]; #else String::codepoint_iterator currentCodePointIter(text.begin(), text.begin(), text.end()); while (!currentCodePointIter.isAtEnd()) { char32_t currentCodePoint = *currentCodePointIter; #endif const FontGlyph* glyph = getGlyphData(currentCodePoint); if (glyph != nullptr) { const Image* const img = glyph->getImage(); glyph_pos.y = base_y - (img->getRenderedOffset().y - img->getRenderedOffset().y * y_scale); img->render(geom_buffers, glyph_pos, glyph->getSize(x_scale, y_scale), clip_rect, clipping_enabled, colours); glyph_pos.x += glyph->getAdvance(x_scale); // apply extra spacing to space chars if (currentCodePoint == ' ') glyph_pos.x += space_extra; } #if (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_8) ++currentCodePointIter; #endif } return glyph_pos.x; } //----------------------------------------------------------------------------// void Font::setNativeResolution(const Sizef& size) { d_nativeResolution = size; // re-calculate scaling factors & notify images as required notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } //----------------------------------------------------------------------------// const Sizef& Font::getNativeResolution() const { return d_nativeResolution; } //----------------------------------------------------------------------------// void Font::setAutoScaled(const AutoScaledMode auto_scaled) { if (auto_scaled == d_autoScaled) return; d_autoScaled = auto_scaled; updateFont(); FontEventArgs args(this); onRenderSizeChanged(args); } //----------------------------------------------------------------------------// AutoScaledMode Font::getAutoScaled() const { return d_autoScaled; } //----------------------------------------------------------------------------// void Font::notifyDisplaySizeChanged(const Sizef& size) { Image::computeScalingFactors(d_autoScaled, size, d_nativeResolution, d_horzScaling, d_vertScaling); if (d_autoScaled != ASM_Disabled) { updateFont(); FontEventArgs args(this); onRenderSizeChanged(args); } } //----------------------------------------------------------------------------// void Font::rasterise(char32_t, char32_t) const { // do nothing by default } //----------------------------------------------------------------------------// void Font::writeXMLToStream(XMLSerializer& xml_stream) const { // output starting <Font ... > element xml_stream.openTag("Font") .attribute(Font_xmlHandler::FontNameAttribute, d_name) .attribute(Font_xmlHandler::FontFilenameAttribute, d_filename); if (!d_resourceGroup.empty()) xml_stream.attribute(Font_xmlHandler::FontResourceGroupAttribute, d_resourceGroup); if (d_nativeResolution.d_width != DefaultNativeHorzRes) xml_stream.attribute(Font_xmlHandler::FontNativeHorzResAttribute, PropertyHelper<std::uint32_t>::toString(static_cast<std::uint32_t>(d_nativeResolution.d_width))); if (d_nativeResolution.d_height != DefaultNativeVertRes) xml_stream.attribute(Font_xmlHandler::FontNativeVertResAttribute, PropertyHelper<std::uint32_t>::toString(static_cast<std::uint32_t>(d_nativeResolution.d_height))); if (d_autoScaled != ASM_Disabled) xml_stream.attribute(Font_xmlHandler::FontAutoScaledAttribute, PropertyHelper<AutoScaledMode>::toString(d_autoScaled)); writeXMLToStream_impl(xml_stream); // output closing </Font> element. xml_stream.closeTag(); } //----------------------------------------------------------------------------// void Font::onRenderSizeChanged(FontEventArgs& e) { fireEvent(EventRenderSizeChanged, e, EventNamespace); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>// // File: FileManager.hpp // Class: FileManager // Structs: CLTexture // Author: John Barbero Unenge // All code is my own except where credited to others. // // Date: 17/9-2012 // // Description: // The purpose of FileManager is to provide a system specific // filemanager. The C++ core declare the format in which it // wants the data and each platform that uses the C++ core // needs to implement this header in a suitable way. // // Methods: // // loadTextureFromFile // Loads a texture from a file with the given name. // The return of the function should be of the herin // declared struct CLTexture, which is what the core // needs for later binding OpenGL textures. #ifdef __APPLE__ #include <OpenGLES/ES1/gl.h> #include <OpenGLES/ES1/glext.h> #else #include <GLES/gl.h> #include <GLES/glext.h> #endif // CLTexture // A struct used to represent an Image in a way that is // relevant to OpenGL. It contains: // - internalFormat, which must be one of the following: // GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, GL_LUMINANCE_ALPHA // - width, the width of the image in pixels. // - height, the height of the image in pixels. // - type, can be one of the following: // GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5, // GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_5_5_5_1 // - data, a pointer to the image data in memory. struct CLTexture{ GLint internalFormat; GLsizei width; GLsizei height; GLenum type; const GLvoid* data; }; // FileManager // Used for managing the files (should have different // implementation on different devices). class FileManager { private: const char* m_basePath; public: FileManager(const char* basePath); ~FileManager(); // loadTextureFromFile // Loads a CLTexture from the given filename which // is then ready for use with OpenGL. CLTexture* loadTextureFromFile(const char* file); }; <commit_msg>Removed unused import.<commit_after>// // File: FileManager.hpp // Class: FileManager // Structs: CLTexture // Author: John Barbero Unenge // All code is my own except where credited to others. // // Date: 17/9-2012 // // Description: // The purpose of FileManager is to provide a system specific // filemanager. The C++ core declare the format in which it // wants the data and each platform that uses the C++ core // needs to implement this header in a suitable way. // // Methods: // // loadTextureFromFile // Loads a texture from a file with the given name. // The return of the function should be of the herin // declared struct CLTexture, which is what the core // needs for later binding OpenGL textures. #ifdef __APPLE__ #include <OpenGLES/ES1/gl.h> #include <OpenGLES/ES1/glext.h> #else #include <GLES/gl.h> #include <GLES/glext.h> #endif #include <Lodepng.hpp> // CLTexture // A struct used to represent an Image in a way that is // relevant to OpenGL. It contains: // - internalFormat, which must be one of the following: // GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, GL_LUMINANCE_ALPHA // - width, the width of the image in pixels. // - height, the height of the image in pixels. // - type, can be one of the following: // GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5, // GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_5_5_5_1 // - data, a pointer to the image data in memory. struct CLTexture{ GLint internalFormat; GLsizei width; GLsizei height; GLenum type; const GLvoid* data; }; // FileManager // Used for managing the files (should have different // implementation on different devices). class FileManager { private: const char* m_basePath; public: FileManager(const char* basePath); ~FileManager(); // loadTextureFromFile // Loads a CLTexture from the given filename which // is then ready for use with OpenGL. CLTexture* loadTextureFromFile(const char* file); }; <|endoftext|>
<commit_before>/* ____________________________________________________________________________ Scanner Component for the Micro A Compiler mscan.h Version 2007 - 2016 James L. Richards Last Update: August 28, 2007 Nelson A Castillo Last Update: January 31, 2016 The routines in this unit are based on those provided in the book "Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr., Benjamin Cummings Publishing Co. (1991). See Section 2.2, pp. 25-29. ____________________________________________________________________________ */ #include <iostream> #include <fstream> #include <string> using namespace std; extern ifstream sourceFile; extern ofstream outFile, listFile; #include "mscan.h" // ******************* // ** Constructor ** // ******************* Scanner::Scanner() { tokenBuffer = ""; lineBuffer = ""; lineNumber = 0; } // ******************************** // ** Private Member Functions ** // ******************************** void Scanner::BufferChar(char c) { if (tokenBuffer.length() < ID_STRING_LEN){ tokenBuffer += c; } //cerr << tokenBuffer << endl; } void Scanner::BufferString(char c) { stringBuffer += c; //cerr << tokenBuffer << endl; } Token Scanner::CheckReserved() { if (tolower(tokenBuffer) == "bool") return BOOL_SYM; if (tolower(tokenBuffer) == "break") return BREAK_SYM; if (tolower(tokenBuffer) == "case") return CASE_SYM; if (tolower(tokenBuffer) == "cheese") return CHEESE_SYM; if (tolower(tokenBuffer) == "decs") return DECS_SYM; if (tolower(tokenBuffer) == "do") return DO_SYM; if (tolower(tokenBuffer) == "else") return ELSE_SYM; if (tolower(tokenBuffer) == "end") return END_SYM; if (tolower(tokenBuffer) == "false") return FALSE_SYM; if (tolower(tokenBuffer) == "float") return FLOAT_SYM; if (tolower(tokenBuffer) == "for") return FOR_SYM; if (tolower(tokenBuffer) == "hiphip") return HIPHIP_SYM; if (tolower(tokenBuffer) == "if") return IF_SYM; if (tolower(tokenBuffer) == "int") return INT_SYM; if (tolower(tokenBuffer) == "listen") return LISTEN_SYM; if (tolower(tokenBuffer) == "otherwise") return OTHERWISE_SYM; if (tolower(tokenBuffer) == "select") return SELECT_SYM; if (tolower(tokenBuffer) == "shout") return SHOUT_SYM; if (tolower(tokenBuffer) == "then") return THEN_SYM; if (tolower(tokenBuffer) == "true") return TRUE_SYM; if (tolower(tokenBuffer) == "while") return WHILE_SYM; return ID; } void Scanner::ClearBuffer() { tokenBuffer = ""; stringBuffer = ""; } void Scanner::LexicalError(char& c, string& errorExp="") { cout << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << endl; listFile << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << endl; if (errorExp != "") { /*TODO: I was starting with the comment but * I need to ampliate the code */ } c = NextChar(); } char Scanner::NextChar() { char c; sourceFile.get(c); if (c == '\n') { listFile.width(6); listFile << ++lineNumber << " " << lineBuffer << endl; lineBuffer = ""; } else{ lineBuffer += c; } return c; } // ******************************* // ** Public Member Functions ** // ******************************* Token Scanner::GetNextToken() { char currentChar, c; ClearBuffer(); currentChar = NextChar(); while (!sourceFile.eof()) { if (isspace(currentChar)) { /* do nothing */ currentChar = NextChar(); } else if (isalpha(currentChar)) { /* identifier */ BufferChar(currentChar); c = sourceFile.peek(); while (isalnum(c) || c == '_') { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } return CheckReserved(); } else if (isdigit(currentChar)) { /* integer or float literals */ BufferChar(currentChar); c = sourceFile.peek(); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } /* check if it is a float */ if (c == '.') { currentChar = NextChar(); c = sourceFile.peek(); /* check for a digit after the '.' */ if (!isdigit(c)) LexicalError(currentChar); BufferChar(currentChar); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } /* check for power of 10 multipliers */ if (c == 'e' || c == 'E') { currentChar = NextChar(); c = sourceFile.peek(); if (c != '+' && c!= '-') { LexicalError(currentChar); } BufferChar(currentChar); currentChar = NextChar(); c = sourceFile.peek(); if (!isdigit(c)) LexicalError(currentChar); BufferChar(currentChar); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } } return FLOAT_LIT; } return INT_LIT; } else if (currentChar == '"') { // string literal // BufferString(currentChar); do { currentChar = NextChar(); // cout << currentChar <<endl; if (currentChar == '"' \ & sourceFile.peek() != '"') { // BufferString(currentChar); // cout << "________________________" <<endl; // cout << stringBuffer <<endl; // cout << "________________________" <<endl; return CHEESE_LIT; } else if (currentChar == '"' \ & sourceFile.peek() == '"') { currentChar = NextChar(); } BufferString(currentChar); } while (sourceFile.peek()!='\n'); return CHEESE_LIT; } else if (currentChar == '(') { return LBANANA; } else if (currentChar == ')') { return RBANANA; } else if (currentChar == '[') { return LSTAPLE; } else if (currentChar == ']') { return RSTAPLE; } else if (currentChar == '{') { return LMUSTACHE; } else if (currentChar == '}') { return RMUSTACHE; } else if (currentChar == ';') { return SEMICOLON; } else if (currentChar == ':') { return COLON; } else if (currentChar == ',') { return COMMA; } else if (currentChar == '+') { BufferChar(currentChar); return PLUS_OP; } else if (currentChar == '*') { BufferChar(currentChar); return MULT_OP; } else if (currentChar == '/') { /* check if it is a multiline comment */ if (sourceFile.peek() == ':') { do { /* skip comment */ currentChar = NextChar(); if (currentChar == ':') { currentChar = NextChar(); if (currentChar == '/') { break; } } } while (!sourceFile.eof()); } BufferChar(currentChar); return DIV_OP; } else if (currentChar == '=') { if (sourceFile.peek() == '=') { currentChar = NextChar(); return EQ_OP1; } currentChar = NextChar(); return ASSIGN_OP; } else if (currentChar == '!') { if (sourceFile.peek() == '!') { currentChar = NextChar(); return EQ_OP2; } else if (sourceFile.peek() == '=') { currentChar = NextChar(); return NE_OP; } } else if (currentChar == '<') { if (sourceFile.peek() == '=') { currentChar = NextChar(); return LE_OP; } currentChar = NextChar(); return LT_OP; } else if (currentChar == '>') { if (sourceFile.peek() == '=') { currentChar = NextChar(); return GE_OP; } currentChar = NextChar(); return GT_OP; } else if (currentChar == '-') { /* check if it is a comment or a minus symbol */ if (sourceFile.peek() == '-') { /* comment */ do { /* skip comment */ currentChar = NextChar(); } while (currentChar != '\n'); } else { /* minus operator */ BufferChar(currentChar); return MINUS_OP; } } else { /* Unrecognized character */ LexicalError(currentChar); } } /* end while */ return EOF_SYM; } <commit_msg>Fix the conversion of strings to lower case.<commit_after>/* ____________________________________________________________________________ Scanner Component for the Micro A Compiler mscan.h Version 2007 - 2016 James L. Richards Last Update: August 28, 2007 Nelson A Castillo Last Update: January 31, 2016 The routines in this unit are based on those provided in the book "Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr., Benjamin Cummings Publishing Co. (1991). See Section 2.2, pp. 25-29. ____________________________________________________________________________ */ #include <iostream> #include <fstream> #include <string> #include <algorithm> using namespace std; extern ifstream sourceFile; extern ofstream outFile, listFile; #include "mscan.h" // ******************* // ** Constructor ** // ******************* Scanner::Scanner() { tokenBuffer = ""; lineBuffer = ""; lineNumber = 0; } // ******************************** // ** Private Member Functions ** // ******************************** void Scanner::BufferChar(char c) { if (tokenBuffer.length() < ID_STRING_LEN){ tokenBuffer += c; } //cerr << tokenBuffer << endl; } void Scanner::BufferString(char c) { stringBuffer += c; //cerr << tokenBuffer << endl; } Token Scanner::CheckReserved() { /* Convert the string to lower case */ transform(tokenBuffer.begin(), tokenBuffer.end(), \ tokenBuffer.begin(), ::tolower); /* Check the converted words */ if ((tokenBuffer) == "bool") return BOOL_SYM; if ((tokenBuffer) == "break") return BREAK_SYM; if ((tokenBuffer) == "case") return CASE_SYM; if ((tokenBuffer) == "cheese") return CHEESE_SYM; if ((tokenBuffer) == "decs") return DECS_SYM; if ((tokenBuffer) == "do") return DO_SYM; if ((tokenBuffer) == "else") return ELSE_SYM; if ((tokenBuffer) == "end") return END_SYM; if ((tokenBuffer) == "false") return FALSE_SYM; if ((tokenBuffer) == "float") return FLOAT_SYM; if ((tokenBuffer) == "for") return FOR_SYM; if ((tokenBuffer) == "hiphip") return HIPHIP_SYM; if ((tokenBuffer) == "if") return IF_SYM; if ((tokenBuffer) == "int") return INT_SYM; if ((tokenBuffer) == "listen") return LISTEN_SYM; if ((tokenBuffer) == "otherwise") return OTHERWISE_SYM; if ((tokenBuffer) == "select") return SELECT_SYM; if ((tokenBuffer) == "shout") return SHOUT_SYM; if ((tokenBuffer) == "then") return THEN_SYM; if ((tokenBuffer) == "true") return TRUE_SYM; if ((tokenBuffer) == "while") return WHILE_SYM; return ID; } void Scanner::ClearBuffer() { tokenBuffer = ""; stringBuffer = ""; } void Scanner::LexicalError(char& c, string& errorExp="") { cout << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << endl; listFile << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << endl; if (errorExp != "") { /*TODO: I was starting with the comment but * I need to ampliate the code */ } c = NextChar(); } char Scanner::NextChar() { char c; sourceFile.get(c); if (c == '\n') { listFile.width(6); listFile << ++lineNumber << " " << lineBuffer << endl; lineBuffer = ""; } else{ lineBuffer += c; } return c; } // ******************************* // ** Public Member Functions ** // ******************************* Token Scanner::GetNextToken() { char currentChar, c; ClearBuffer(); currentChar = NextChar(); while (!sourceFile.eof()) { if (isspace(currentChar)) { /* do nothing */ currentChar = NextChar(); } else if (isalpha(currentChar)) { /* identifier */ BufferChar(currentChar); c = sourceFile.peek(); while (isalnum(c) || c == '_') { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } return CheckReserved(); } else if (isdigit(currentChar)) { /* integer or float literals */ BufferChar(currentChar); c = sourceFile.peek(); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } /* check if it is a float */ if (c == '.') { currentChar = NextChar(); c = sourceFile.peek(); /* check for a digit after the '.' */ if (!isdigit(c)) LexicalError(currentChar); BufferChar(currentChar); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } /* check for power of 10 multipliers */ if (c == 'e' || c == 'E') { currentChar = NextChar(); c = sourceFile.peek(); if (c != '+' && c!= '-') { LexicalError(currentChar); } BufferChar(currentChar); currentChar = NextChar(); c = sourceFile.peek(); if (!isdigit(c)) LexicalError(currentChar); BufferChar(currentChar); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } } return FLOAT_LIT; } return INT_LIT; } else if (currentChar == '"') { // string literal // BufferString(currentChar); do { currentChar = NextChar(); // cout << currentChar <<endl; if (currentChar == '"' \ & sourceFile.peek() != '"') { // BufferString(currentChar); // cout << "________________________" <<endl; // cout << stringBuffer <<endl; // cout << "________________________" <<endl; return CHEESE_LIT; } else if (currentChar == '"' \ & sourceFile.peek() == '"') { currentChar = NextChar(); } BufferString(currentChar); } while (sourceFile.peek()!='\n'); return CHEESE_LIT; } else if (currentChar == '(') { return LBANANA; } else if (currentChar == ')') { return RBANANA; } else if (currentChar == '[') { return LSTAPLE; } else if (currentChar == ']') { return RSTAPLE; } else if (currentChar == '{') { return LMUSTACHE; } else if (currentChar == '}') { return RMUSTACHE; } else if (currentChar == ';') { return SEMICOLON; } else if (currentChar == ':') { return COLON; } else if (currentChar == ',') { return COMMA; } else if (currentChar == '+') { BufferChar(currentChar); return PLUS_OP; } else if (currentChar == '*') { BufferChar(currentChar); return MULT_OP; } else if (currentChar == '/') { /* check if it is a multiline comment */ if (sourceFile.peek() == ':') { do { /* skip comment */ currentChar = NextChar(); if (currentChar == ':') { currentChar = NextChar(); if (currentChar == '/') { break; } } } while (!sourceFile.eof()); } BufferChar(currentChar); return DIV_OP; } else if (currentChar == '=') { if (sourceFile.peek() == '=') { currentChar = NextChar(); return EQ_OP1; } currentChar = NextChar(); return ASSIGN_OP; } else if (currentChar == '!') { if (sourceFile.peek() == '!') { currentChar = NextChar(); return EQ_OP2; } else if (sourceFile.peek() == '=') { currentChar = NextChar(); return NE_OP; } } else if (currentChar == '<') { if (sourceFile.peek() == '=') { currentChar = NextChar(); return LE_OP; } currentChar = NextChar(); return LT_OP; } else if (currentChar == '>') { if (sourceFile.peek() == '=') { currentChar = NextChar(); return GE_OP; } currentChar = NextChar(); return GT_OP; } else if (currentChar == '-') { /* check if it is a comment or a minus symbol */ if (sourceFile.peek() == '-') { /* comment */ do { /* skip comment */ currentChar = NextChar(); } while (currentChar != '\n'); } else { /* minus operator */ BufferChar(currentChar); return MINUS_OP; } } else { /* Unrecognized character */ LexicalError(currentChar); } } /* end while */ return EOF_SYM; } <|endoftext|>
<commit_before> #include <iostream> #include "window.h" #include "application.h" #include "style.h" #include <platform/window.h> #include <gl/opengl.h> namespace gui { //////////////////////////////////////// window::window( const std::shared_ptr<platform::window> &w ) : _window( w ) { precondition( bool(_window), "null window" ); _window->exposed.callback( [this] ( void ) { paint(); } ); _window->resized.callback( [this] ( double w, double h ) { resize( w, h ); } ); _window->mouse_pressed.callback( [this]( const std::shared_ptr<platform::mouse> &, const core::point &p, int b ) { mouse_press( p, b ); } ); _window->mouse_released.callback( [this]( const std::shared_ptr<platform::mouse> &, const core::point &p, int b ) { mouse_release( p, b ); } ); _window->mouse_moved.callback( [this]( const std::shared_ptr<platform::mouse> &, const core::point &p ) { mouse_moved( p ); } ); _window->key_pressed.callback( [this]( const std::shared_ptr<platform::keyboard> &, const platform::scancode &c ) { key_pressed( c ); } ); _window->key_released.callback( [this]( const std::shared_ptr<platform::keyboard> &, const platform::scancode &c ) { key_released( c ); } ); _window->text_entered.callback( [this]( const std::shared_ptr<platform::keyboard> &, const char32_t &c ) { text_entered( c ); } ); } //////////////////////////////////////// window::~window( void ) { } //////////////////////////////////////// void window::set_title( const std::string &t ) { _window->set_title( t ); } //////////////////////////////////////// void window::show( void ) { _window->show(); } //////////////////////////////////////// void window::set_widget( const std::shared_ptr<widget> &w ) { in_context( [&,this] { _widget = w; _widget->set_horizontal( 0.0, _window->width() - 1.0 ); _widget->set_vertical( 0.0, _window->height() - 1.0 ); _widget->compute_minimum(); } ); } //////////////////////////////////////// double window::width( void ) const { return _window->width(); } //////////////////////////////////////// double window::height( void ) const { return _window->height(); } //////////////////////////////////////// void window::invalidate( const core::rect &r ) { _window->invalidate( r ); } //////////////////////////////////////// void window::paint( void ) { auto canvas = _window->canvas(); glViewport( 0, 0, _window->width(), _window->height() ); canvas->ortho( 0, _window->width(), 0, _window->height() ); auto style = application::current()->get_style(); if ( style ) style->background( canvas ); if ( _widget ) in_context( [&,this] { _widget->compute_minimum(); _widget->compute_layout(); _widget->paint( canvas ); } ); } //////////////////////////////////////// void window::resize( double w, double h ) { if ( _widget ) in_context( [&,this] { _widget->set_horizontal( 0.0, w - 1.0 ); _widget->set_vertical( 0.0, h - 1.0 ); _widget->compute_layout(); } ); } //////////////////////////////////////// void window::mouse_press( const core::point &p, int b ) { if ( _widget ) in_context( [&,this] { _widget->mouse_press( p, b ); } ); } //////////////////////////////////////// void window::mouse_release( const core::point &p, int b ) { if ( _widget ) in_context( [&,this] { _widget->mouse_release( p, b ); } ); } //////////////////////////////////////// void window::mouse_moved( const core::point &p ) { if ( _widget ) in_context( [&,this] { _widget->mouse_move( p ); } ); } //////////////////////////////////////// void window::key_pressed( platform::scancode c ) { if ( _widget ) in_context( [&,this] { _widget->key_press( c ); } ); } //////////////////////////////////////// void window::key_released( platform::scancode c ) { if ( _widget ) in_context( [&,this] { _widget->key_release( c ); } ); } //////////////////////////////////////// void window::text_entered( char32_t c ) { if ( _widget ) in_context( [&,this] { _widget->text_input( c ); } ); } //////////////////////////////////////// } <commit_msg>Fixed problem with view matrix (on resize).<commit_after> #include <iostream> #include "window.h" #include "application.h" #include "style.h" #include <platform/window.h> #include <gl/opengl.h> namespace gui { //////////////////////////////////////// window::window( const std::shared_ptr<platform::window> &w ) : _window( w ) { precondition( bool(_window), "null window" ); _window->exposed.callback( [this] ( void ) { paint(); } ); _window->resized.callback( [this] ( double w, double h ) { resize( w, h ); } ); _window->mouse_pressed.callback( [this]( const std::shared_ptr<platform::mouse> &, const core::point &p, int b ) { mouse_press( p, b ); } ); _window->mouse_released.callback( [this]( const std::shared_ptr<platform::mouse> &, const core::point &p, int b ) { mouse_release( p, b ); } ); _window->mouse_moved.callback( [this]( const std::shared_ptr<platform::mouse> &, const core::point &p ) { mouse_moved( p ); } ); _window->key_pressed.callback( [this]( const std::shared_ptr<platform::keyboard> &, const platform::scancode &c ) { key_pressed( c ); } ); _window->key_released.callback( [this]( const std::shared_ptr<platform::keyboard> &, const platform::scancode &c ) { key_released( c ); } ); _window->text_entered.callback( [this]( const std::shared_ptr<platform::keyboard> &, const char32_t &c ) { text_entered( c ); } ); } //////////////////////////////////////// window::~window( void ) { } //////////////////////////////////////// void window::set_title( const std::string &t ) { _window->set_title( t ); } //////////////////////////////////////// void window::show( void ) { _window->show(); } //////////////////////////////////////// void window::set_widget( const std::shared_ptr<widget> &w ) { in_context( [&,this] { _widget = w; _widget->set_horizontal( 0.0, _window->width() - 1.0 ); _widget->set_vertical( 0.0, _window->height() - 1.0 ); _widget->compute_minimum(); } ); } //////////////////////////////////////// double window::width( void ) const { return _window->width(); } //////////////////////////////////////// double window::height( void ) const { return _window->height(); } //////////////////////////////////////// void window::invalidate( const core::rect &r ) { _window->invalidate( r ); } //////////////////////////////////////// void window::paint( void ) { auto canvas = _window->canvas(); glViewport( 0, 0, _window->width(), _window->height() ); auto style = application::current()->get_style(); if ( style ) style->background( canvas ); canvas->save(); canvas->ortho( 0, _window->width(), 0, _window->height() ); if ( _widget ) { in_context( [&,this] { _widget->compute_minimum(); _widget->compute_layout(); _widget->paint( canvas ); } ); } canvas->restore(); } //////////////////////////////////////// void window::resize( double w, double h ) { if ( _widget ) in_context( [&,this] { _widget->set_horizontal( 0.0, w - 1.0 ); _widget->set_vertical( 0.0, h - 1.0 ); _widget->compute_layout(); } ); } //////////////////////////////////////// void window::mouse_press( const core::point &p, int b ) { if ( _widget ) in_context( [&,this] { _widget->mouse_press( p, b ); } ); } //////////////////////////////////////// void window::mouse_release( const core::point &p, int b ) { if ( _widget ) in_context( [&,this] { _widget->mouse_release( p, b ); } ); } //////////////////////////////////////// void window::mouse_moved( const core::point &p ) { if ( _widget ) in_context( [&,this] { _widget->mouse_move( p ); } ); } //////////////////////////////////////// void window::key_pressed( platform::scancode c ) { if ( _widget ) in_context( [&,this] { _widget->key_press( c ); } ); } //////////////////////////////////////// void window::key_released( platform::scancode c ) { if ( _widget ) in_context( [&,this] { _widget->key_release( c ); } ); } //////////////////////////////////////// void window::text_entered( char32_t c ) { if ( _widget ) in_context( [&,this] { _widget->text_input( c ); } ); } //////////////////////////////////////// } <|endoftext|>
<commit_before><commit_msg>mask getter<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: numehelp.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-01-11 14:17:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef XMLOFF_NUMEHELP_HXX #define XMLOFF_NUMEHELP_HXX #ifndef _SAL_CONFIG_H_ #include "sal/config.h" #endif #ifndef INCLUDED_XMLOFF_DLLAPI_H #include "xmloff/dllapi.h" #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_ #include <com/sun/star/util/XNumberFormatsSupplier.hpp> #endif #ifndef __SGI_STL_SET #include <set> #endif class SvXMLExport; namespace rtl { class OUString; } struct XMLNumberFormat { rtl::OUString sCurrency; sal_Int32 nNumberFormat; sal_Int16 nType; sal_Bool bIsStandard : 1; XMLNumberFormat() : nNumberFormat(0), nType(0) {} XMLNumberFormat(const rtl::OUString& sTempCurrency, sal_Int32 nTempFormat, sal_Int16 nTempType) : sCurrency(sTempCurrency), nNumberFormat(nTempFormat), nType(nTempType) {} }; struct LessNumberFormat { sal_Bool operator() (const XMLNumberFormat& rValue1, const XMLNumberFormat& rValue2) const { return rValue1.nNumberFormat < rValue2.nNumberFormat; } }; typedef std::set<XMLNumberFormat, LessNumberFormat> XMLNumberFormatSet; class XMLOFF_DLLPUBLIC XMLNumberFormatAttributesExportHelper { ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats > xNumberFormats; SvXMLExport* pExport; const rtl::OUString sEmpty; const rtl::OUString sStandardFormat; const rtl::OUString sType; const rtl::OUString sAttrValueType; const rtl::OUString sAttrValue; const rtl::OUString sAttrDateValue; const rtl::OUString sAttrTimeValue; const rtl::OUString sAttrBooleanValue; const rtl::OUString sAttrStringValue; const rtl::OUString sAttrCurrency; XMLNumberFormatSet aNumberFormats; public : XMLNumberFormatAttributesExportHelper(::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier); XMLNumberFormatAttributesExportHelper(::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier, SvXMLExport& rExport ); ~XMLNumberFormatAttributesExportHelper(); void SetExport(SvXMLExport* pExport) { this->pExport = pExport; } sal_Int16 GetCellType(const sal_Int32 nNumberFormat, rtl::OUString& sCurrency, sal_Bool& bIsStandard); static void WriteAttributes(SvXMLExport& rXMLExport, const sal_Int16 nTypeKey, const double& rValue, const rtl::OUString& rCurrencySymbol, sal_Bool bExportValue = sal_True); static sal_Bool GetCurrencySymbol(const sal_Int32 nNumberFormat, rtl::OUString& rCurrencySymbol, ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > & xNumberFormatsSupplier); static sal_Int16 GetCellType(const sal_Int32 nNumberFormat, sal_Bool& bIsStandard, ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > & xNumberFormatsSupplier); static void SetNumberFormatAttributes(SvXMLExport& rXMLExport, const sal_Int32 nNumberFormat, const double& rValue, sal_Bool bExportValue = sal_True); static void SetNumberFormatAttributes(SvXMLExport& rXMLExport, const rtl::OUString& rValue, const rtl::OUString& rCharacters, sal_Bool bExportValue = sal_True, sal_Bool bExportTypeAttribute = sal_True); sal_Bool GetCurrencySymbol(const sal_Int32 nNumberFormat, rtl::OUString& rCurrencySymbol); sal_Int16 GetCellType(const sal_Int32 nNumberFormat, sal_Bool& bIsStandard); void WriteAttributes(const sal_Int16 nTypeKey, const double& rValue, const rtl::OUString& rCurrencySymbol, sal_Bool bExportValue = sal_True); void SetNumberFormatAttributes(const sal_Int32 nNumberFormat, const double& rValue, sal_Bool bExportValue = sal_True); void SetNumberFormatAttributes(const rtl::OUString& rValue, const rtl::OUString& rCharacters, sal_Bool bExportValue = sal_True, sal_Bool bExportTypeAttribute = sal_True); }; #endif <commit_msg>INTEGRATION: CWS calcuno01 (1.6.144); FILE MERGED 2005/01/27 16:34:59 sab 1.6.144.3: RESYNC: (1.7-1.8); FILE MERGED 2004/10/13 10:28:54 sab 1.6.144.2: RESYNC: (1.6-1.7); FILE MERGED 2004/02/12 17:38:49 sab 1.6.144.1: #i22706#; add members for propertynames<commit_after>/************************************************************************* * * $RCSfile: numehelp.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2005-03-23 12:40:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef XMLOFF_NUMEHELP_HXX #define XMLOFF_NUMEHELP_HXX #ifndef _SAL_CONFIG_H_ #include "sal/config.h" #endif #ifndef INCLUDED_XMLOFF_DLLAPI_H #include "xmloff/dllapi.h" #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_ #include <com/sun/star/util/XNumberFormatsSupplier.hpp> #endif #ifndef __SGI_STL_SET #include <set> #endif class SvXMLExport; namespace rtl { class OUString; } struct XMLNumberFormat { rtl::OUString sCurrency; sal_Int32 nNumberFormat; sal_Int16 nType; sal_Bool bIsStandard : 1; XMLNumberFormat() : nNumberFormat(0), nType(0) {} XMLNumberFormat(const rtl::OUString& sTempCurrency, sal_Int32 nTempFormat, sal_Int16 nTempType) : sCurrency(sTempCurrency), nNumberFormat(nTempFormat), nType(nTempType) {} }; struct LessNumberFormat { sal_Bool operator() (const XMLNumberFormat& rValue1, const XMLNumberFormat& rValue2) const { return rValue1.nNumberFormat < rValue2.nNumberFormat; } }; typedef std::set<XMLNumberFormat, LessNumberFormat> XMLNumberFormatSet; class XMLOFF_DLLPUBLIC XMLNumberFormatAttributesExportHelper { ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats > xNumberFormats; SvXMLExport* pExport; const rtl::OUString sEmpty; const rtl::OUString sStandardFormat; const rtl::OUString sType; const rtl::OUString sAttrValueType; const rtl::OUString sAttrValue; const rtl::OUString sAttrDateValue; const rtl::OUString sAttrTimeValue; const rtl::OUString sAttrBooleanValue; const rtl::OUString sAttrStringValue; const rtl::OUString sAttrCurrency; const rtl::OUString msCurrencySymbol; const rtl::OUString msCurrencyAbbreviation; XMLNumberFormatSet aNumberFormats; public : XMLNumberFormatAttributesExportHelper(::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier); XMLNumberFormatAttributesExportHelper(::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier, SvXMLExport& rExport ); ~XMLNumberFormatAttributesExportHelper(); void SetExport(SvXMLExport* pExport) { this->pExport = pExport; } sal_Int16 GetCellType(const sal_Int32 nNumberFormat, rtl::OUString& sCurrency, sal_Bool& bIsStandard); static void WriteAttributes(SvXMLExport& rXMLExport, const sal_Int16 nTypeKey, const double& rValue, const rtl::OUString& rCurrencySymbol, sal_Bool bExportValue = sal_True); static sal_Bool GetCurrencySymbol(const sal_Int32 nNumberFormat, rtl::OUString& rCurrencySymbol, ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > & xNumberFormatsSupplier); static sal_Int16 GetCellType(const sal_Int32 nNumberFormat, sal_Bool& bIsStandard, ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > & xNumberFormatsSupplier); static void SetNumberFormatAttributes(SvXMLExport& rXMLExport, const sal_Int32 nNumberFormat, const double& rValue, sal_Bool bExportValue = sal_True); static void SetNumberFormatAttributes(SvXMLExport& rXMLExport, const rtl::OUString& rValue, const rtl::OUString& rCharacters, sal_Bool bExportValue = sal_True, sal_Bool bExportTypeAttribute = sal_True); sal_Bool GetCurrencySymbol(const sal_Int32 nNumberFormat, rtl::OUString& rCurrencySymbol); sal_Int16 GetCellType(const sal_Int32 nNumberFormat, sal_Bool& bIsStandard); void WriteAttributes(const sal_Int16 nTypeKey, const double& rValue, const rtl::OUString& rCurrencySymbol, sal_Bool bExportValue = sal_True); void SetNumberFormatAttributes(const sal_Int32 nNumberFormat, const double& rValue, sal_Bool bExportValue = sal_True); void SetNumberFormatAttributes(const rtl::OUString& rValue, const rtl::OUString& rCharacters, sal_Bool bExportValue = sal_True, sal_Bool bExportTypeAttribute = sal_True); }; #endif <|endoftext|>
<commit_before>/* The program includes the solutions to ex 5-23 and ex 5-24. */ #include <iostream> using namespace std; int main() { int dividend, divisor; while (cin >> dividend >> divisor) { try { if (divisor == 0) { throw runtime_error("Divisor cannot be zero."); } else { cout << dividend / divisor << endl; } } catch (runtime_error err) { cout << err.what() << endl; cout << "Try again? Enter y or n." << endl; char c; cin >> c; if (!cin || c == 'n') { break; } } } return 0; }<commit_msg>delete space<commit_after>/* The program includes the solutions to ex 5-23 and ex 5-24. */ #include <iostream> using namespace std; int main() { int dividend, divisor; while (cin >> dividend >> divisor) { try { if (divisor == 0) { throw runtime_error("Divisor cannot be zero."); } else { cout << dividend / divisor << endl; } } catch (runtime_error err) { cout << err.what() << endl; cout << "Try again? Enter y or n." << endl; char c; cin >> c; if (!cin || c == 'n') { break; } } } return 0; }<|endoftext|>
<commit_before>/// \file ROOT/TWebWindowWSHandler.hxx /// \ingroup WebGui ROOT7 /// \author Sergey Linev <s.linev@gsi.de> /// \date 2018-08-20 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TWebWindowWSHandler #define ROOT7_TWebWindowWSHandler #include "THttpWSHandler.h" #include <ROOT/TWebWindow.hxx> namespace ROOT { namespace Experimental { /// just wrapper to deliver websockets call-backs to the TWebWindow class class TWebWindowWSHandler : public THttpWSHandler { public: TWebWindow &fWindow; ///<! window reference /// constructor TWebWindowWSHandler(TWebWindow &wind, const char *name) : THttpWSHandler(name, "TWebWindow websockets handler"), fWindow(wind) { } virtual ~TWebWindowWSHandler() { } /// returns content of default web-page /// THttpWSHandler interface virtual TString GetDefaultPageContent() override { return IsDisabled() ? "" : fWindow.fDefaultPage.c_str(); } /// Process websocket request - called from THttpServer thread /// THttpWSHandler interface virtual Bool_t ProcessWS(THttpCallArg *arg) override { return arg && !IsDisabled() ? fWindow.ProcessWS(*arg) : kFALSE; } /// Allow processing of WS actions in arbitrary thread virtual Bool_t AllowMTProcess() const { return fWindow.fProcessMT; } /// Allows usage of multithreading in send operations virtual Bool_t AllowMTSend() const { return fWindow.fSendMT; } /// React on completion of multithreaded send operaiotn virtual void CompleteWSSend(UInt_t wsid) { if (!IsDisabled()) fWindow.CompleteWSSend(wsid); } }; } // namespace Experimental } // namespace ROOT #endif <commit_msg>webgui: use async websocket handler mode for TWebWindow<commit_after>/// \file ROOT/TWebWindowWSHandler.hxx /// \ingroup WebGui ROOT7 /// \author Sergey Linev <s.linev@gsi.de> /// \date 2018-08-20 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TWebWindowWSHandler #define ROOT7_TWebWindowWSHandler #include "THttpWSHandler.h" #include <ROOT/TWebWindow.hxx> namespace ROOT { namespace Experimental { /// just wrapper to deliver websockets call-backs to the TWebWindow class class TWebWindowWSHandler : public THttpWSHandler { public: TWebWindow &fWindow; ///<! window reference /// constructor TWebWindowWSHandler(TWebWindow &wind, const char *name) : THttpWSHandler(name, "TWebWindow websockets handler", kFALSE), fWindow(wind) { } virtual ~TWebWindowWSHandler() { } /// returns content of default web-page /// THttpWSHandler interface virtual TString GetDefaultPageContent() override { return IsDisabled() ? "" : fWindow.fDefaultPage.c_str(); } /// Process websocket request - called from THttpServer thread /// THttpWSHandler interface virtual Bool_t ProcessWS(THttpCallArg *arg) override { return arg && !IsDisabled() ? fWindow.ProcessWS(*arg) : kFALSE; } /// Allow processing of WS actions in arbitrary thread virtual Bool_t AllowMTProcess() const { return fWindow.fProcessMT; } /// Allows usage of multithreading in send operations virtual Bool_t AllowMTSend() const { return fWindow.fSendMT; } /// React on completion of multithreaded send operaiotn virtual void CompleteWSSend(UInt_t wsid) { if (!IsDisabled()) fWindow.CompleteWSSend(wsid); } }; } // namespace Experimental } // namespace ROOT #endif <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: newerverwarn.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SFX2_NEWERVERSIONWARNING_HXX #define _SFX2_NEWERVERSIONWARNING_HXX #include <vcl/button.hxx> #include <vcl/fixed.hxx> #include <sfx2/basedlgs.hxx> namespace sfx2 { class NewerVersionWarningDialog : public SfxModalDialog { private: FixedImage m_aImage; FixedText m_aInfoText; FixedLine m_aButtonLine; PushButton m_aUpdateBtn; CancelButton m_aLaterBtn; DECL_LINK( UpdateHdl, PushButton* ); DECL_LINK( LaterHdl, CancelButton* ); void InitButtonWidth(); public: NewerVersionWarningDialog( Window* pParent ); ~NewerVersionWarningDialog(); }; } // namespace sfx2 #endif // #ifndef _SFX2_NEWERVERSIONWARNING_HXX <commit_msg>INTEGRATION: CWS odfversion241_DEV300 (1.2.110); FILE MERGED 2008/05/21 07:38:50 pb 1.2.110.1: fix: #i89096# added sVersion (of ODF)<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: newerverwarn.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SFX2_NEWERVERSIONWARNING_HXX #define _SFX2_NEWERVERSIONWARNING_HXX #include <vcl/button.hxx> #include <vcl/fixed.hxx> #include <sfx2/basedlgs.hxx> namespace sfx2 { class NewerVersionWarningDialog : public SfxModalDialog { private: FixedImage m_aImage; FixedText m_aInfoText; FixedLine m_aButtonLine; PushButton m_aUpdateBtn; CancelButton m_aLaterBtn; ::rtl::OUString m_sVersion; DECL_LINK( UpdateHdl, PushButton* ); DECL_LINK( LaterHdl, CancelButton* ); void InitButtonWidth(); public: NewerVersionWarningDialog( Window* pParent, const ::rtl::OUString& rVersion ); ~NewerVersionWarningDialog(); }; } // namespace sfx2 #endif // #ifndef _SFX2_NEWERVERSIONWARNING_HXX <|endoftext|>
<commit_before>/*************************************************************************** * action.cpp * This file is part of the KDE project * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.org) * * This program 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 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 * Library General Public License for more details. * You should have received a copy of the GNU Library General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. ***************************************************************************/ #include "action.h" #include "actioncollection.h" #include "interpreter.h" #include "script.h" #include "manager.h" #include "wrapperinterface.h" #include "kross_debug.h" #include <QFile> #include <QFileInfo> #include <klocalizedstring.h> #include <qmimedatabase.h> using namespace Kross; namespace Kross { /// \internal d-pointer class. class Action::Private { public: /** * The \a Script instance the \a Action uses if initialized. It will * be NULL as long as we didn't initialized it what will be done on * demand. */ Script *script; /** * The version number this \a Action has. Those version number got * used internaly to deal with different releases of scripts. */ int version; /** * The optional description to provide some more details about the * Action to the user. */ QString description; /** * The name of the icon. */ QString iconname; /** * The scripting code. */ QByteArray code; /** * The name of the interpreter. This could be something * like for example "python" for the python binding. */ QString interpretername; /** * The name of the scriptfile that should be executed. Those * scriptfile will be readed and the content will be used to * set the scripting code and, if not defined, the used * interpreter. */ QString scriptfile; /** * The path list where the \a Script may be located. * \todo after BIC break: don't keep it all the time, * as it is now passed to [to|from]DomElement */ QStringList searchpath; /** * Map of options that overwritte the \a InterpreterInfo::Option::Map * standard options. */ QMap< QString, QVariant > options; Private() : script(nullptr), version(0) {} }; } enum InitOptions {Enable = 1}; void static init(Action *th, const QString &name, int options = 0) { th->setEnabled(options & Enable); th->setObjectName(name); #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << "Action::Action(QObject*,QString,QDir) Ctor name=" << th->objectName(); #endif QObject::connect(th, SIGNAL(triggered(bool)), th, SLOT(slotTriggered())); } Action::Action(QObject *parent, const QString &name, const QDir &packagepath) : QAction(parent) , QScriptable() , ChildrenInterface() , ErrorInterface() , d(new Private()) { init(this, name); d->searchpath = QStringList(packagepath.absolutePath()); } Action::Action(QObject *parent, const QUrl &url) : QAction(parent) , ChildrenInterface() , ErrorInterface() , d(new Private()) { init(this, url.path(), Enable); QFileInfo fi(url.toLocalFile()); setText(fi.fileName()); QMimeDatabase db; setIconName(db.mimeTypeForUrl(url).iconName()); setFile(url.toLocalFile()); } Action::~Action() { #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << QStringLiteral("Action::~Action() Dtor name='%1'").arg(objectName()); #endif finalize(); ActionCollection *coll = qobject_cast<ActionCollection *>(parent()); if (coll) { coll->removeAction(this); } delete d; } void Action::fromDomElement(const QDomElement &element) { fromDomElement(element, d->searchpath); } void Action::fromDomElement(const QDomElement &element, const QStringList &searchPath) { if (element.isNull()) { return; } QString file = element.attribute("file"); if (! file.isEmpty()) { if (QFileInfo(file).exists()) { setFile(file); } else { foreach (const QString &packagepath, searchPath) { QFileInfo fi(QDir(packagepath), file); if (fi.exists()) { setFile(fi.absoluteFilePath()); break; } } } } d->version = QVariant(element.attribute("version", QString(d->version))).toInt(); setText(i18nd(KLocalizedString::applicationDomain().constData(), element.attribute("text").toUtf8().constData())); setDescription(i18nd(KLocalizedString::applicationDomain().constData(), element.attribute("comment").toUtf8().constData())); setEnabled(true); setInterpreter(element.attribute("interpreter")); setEnabled(QVariant(element.attribute("enabled", "true")).toBool() && isEnabled()); QString icon = element.attribute("icon"); if (icon.isEmpty() && ! d->scriptfile.isNull()) { QMimeDatabase db; icon = db.mimeTypeForUrl(QUrl::fromLocalFile(d->scriptfile)).iconName(); } setIconName(icon); const QString code = element.attribute("code"); if (! code.isNull()) { setCode(code.toUtf8()); } for (QDomNode node = element.firstChild(); ! node.isNull(); node = node.nextSibling()) { QDomElement e = node.toElement(); if (! e.isNull()) { if (e.tagName() == "property") { const QString n = e.attribute("name", QString()); if (! n.isNull()) { #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << "Action::readDomElement: Setting property name=" << n << " value=" << e.text(); #endif setProperty(n.toLatin1().constData(), QVariant(e.text())); } } } } } QDomElement Action::toDomElement() const { return toDomElement(QStringList()); } QDomElement Action::toDomElement(const QStringList &searchPath) const { QDomDocument doc; QDomElement e = doc.createElement("script"); e.setAttribute("name", objectName()); if (d->version > 0) { e.setAttribute("version", QString(d->version)); } if (! text().isNull()) { e.setAttribute("text", text()); } if (! description().isNull()) { e.setAttribute("comment", description()); } if (! iconName().isNull()) { e.setAttribute("icon", iconName()); } if (! isEnabled()) { e.setAttribute("enabled", "false"); } if (! interpreter().isNull()) { e.setAttribute("interpreter", interpreter()); } QString fileName = file(); if (!searchPath.isEmpty()) { //fileName=QDir(searchPath.first()).relativeFilePath(fileName); //prefer absname if it is short? foreach (const QString &packagepath, searchPath) { QString nfn = QDir(packagepath).relativeFilePath(file()); if (nfn.length() < fileName.length()) { fileName = nfn; } } } if (! fileName.isNull()) { e.setAttribute("file", fileName); } QList<QByteArray> props = dynamicPropertyNames(); foreach (const QByteArray &prop, props) { QDomElement p = doc.createElement("property"); p.setAttribute("name", QString::fromLatin1(prop)); p.appendChild(doc.createTextNode(property(prop.constData()).toString())); e.appendChild(p); } /* else if( ! code().isNull() ) { e.setAttribute("code", code()); } */ return e; } Kross::Script *Action::script() const { return d->script; } QString Action::name() const { return objectName(); } int Action::version() const { return d->version; } QString Action::description() const { return d->description; } void Action::setDescription(const QString &description) { d->description = description; emit dataChanged(this); emit updated(); } QString Action::iconName() const { return d->iconname; } void Action::setIconName(const QString &iconname) { setIcon(QIcon::fromTheme(iconname)); d->iconname = iconname; emit dataChanged(this); emit updated(); } bool Action::isEnabled() const { return QAction::isEnabled(); } void Action::setEnabled(bool enabled) { QAction::setEnabled(enabled); emit dataChanged(this); emit updated(); } QByteArray Action::code() const { return d->code; } void Action::setCode(const QByteArray &code) { if (d->code != code) { finalize(); d->code = code; emit dataChanged(this); emit updated(); } } QString Action::interpreter() const { return d->interpretername; } void Action::setInterpreter(const QString &interpretername) { if (d->interpretername != interpretername) { finalize(); d->interpretername = interpretername; setEnabled(Manager::self().interpreters().contains(interpretername)); if (!isEnabled()) { qCWarning(KROSS_LOG) << "Action::setInterpreter: interpreter not found: " << interpretername; } emit dataChanged(this); emit updated(); } } QString Action::file() const { return d->scriptfile; } bool Action::setFile(const QString &scriptfile) { if (d->scriptfile != scriptfile) { finalize(); if (scriptfile.isNull()) { if (! d->scriptfile.isNull()) { d->interpretername.clear(); } d->scriptfile.clear(); d->searchpath.clear(); } else { d->scriptfile = scriptfile; d->interpretername = Manager::self().interpreternameForFile(scriptfile); if (d->interpretername.isNull()) { return false; } } } return true; } QString Action::currentPath() const { return file().isEmpty() ? QString() : QFileInfo(file()).absolutePath(); //obey Qt docs and don't cheat } QVariantMap Action::options() const { return d->options; } void Action::addQObject(QObject *obj, const QString &name) { this->addObject(obj, name); } QObject *Action::qobject(const QString &name) const { return this->object(name); } QStringList Action::qobjectNames() const { return this->objects().keys(); } QVariant Action::option(const QString &name, const QVariant &defaultvalue) { if (d->options.contains(name)) { return d->options[name]; } InterpreterInfo *info = Manager::self().interpreterInfo(d->interpretername); return info ? info->optionValue(name, defaultvalue) : defaultvalue; } bool Action::setOption(const QString &name, const QVariant &value) { InterpreterInfo *info = Manager::self().interpreterInfo(d->interpretername); if (info) { if (info->hasOption(name)) { d->options.insert(name, value); return true; } else { qCWarning(KROSS_LOG) << QStringLiteral("Kross::Action::setOption(%1, %2): No such option") .arg(name).arg(value.toString()); } } else { qCWarning(KROSS_LOG) << QStringLiteral("Kross::Action::setOption(%1, %2): No such interpreterinfo") .arg(name).arg(value.toString()); } return false; } QStringList Action::functionNames() { if (! d->script) { if (! initialize()) { return QStringList(); } } return d->script->functionNames(); } QVariant Action::callFunction(const QString &name, const QVariantList &args) { if (! d->script) { if (! initialize()) { return QVariant(); } } return d->script->callFunction(name, args); } QVariant Action::evaluate(const QByteArray &code) { if (! d->script) { if (! initialize()) { return QVariant(); } } return d->script->evaluate(code); } bool Action::initialize() { finalize(); if (! d->scriptfile.isNull()) { QFile f(d->scriptfile); if (! f.exists()) { setError(i18n("Scriptfile \"%1\" does not exist.", d->scriptfile)); return false; } if (d->interpretername.isNull()) { setError(i18n("Failed to determine interpreter for scriptfile \"%1\"", d->scriptfile)); return false; } if (! f.open(QIODevice::ReadOnly)) { setError(i18n("Failed to open scriptfile \"%1\"", d->scriptfile)); return false; } d->code = f.readAll(); f.close(); } Interpreter *interpreter = Manager::self().interpreter(d->interpretername); if (! interpreter) { InterpreterInfo *info = Manager::self().interpreterInfo(d->interpretername); if (info) { setError(i18n("Failed to load interpreter \"%1\"", d->interpretername)); } else { setError(i18n("No such interpreter \"%1\"", d->interpretername)); } return false; } d->script = interpreter->createScript(this); if (! d->script) { setError(i18n("Failed to create script for interpreter \"%1\"", d->interpretername)); return false; } if (d->script->hadError()) { setError(d->script); finalize(); return false; } clearError(); // clear old exception return true; } void Action::finalize() { if (d->script) { emit finalized(this); } delete d->script; d->script = nullptr; } bool Action::isFinalized() const { return d->script == nullptr; } void Action::slotTriggered() { #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << "Action::slotTriggered() name=" << objectName(); #endif emit started(this); if (! d->script) { if (! initialize()) { Q_ASSERT(hadError()); } } if (hadError()) { #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << "Action::slotTriggered() on init, errorMessage=" << errorMessage(); #endif } else { d->script->execute(); if (d->script->hadError()) { #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << "Action::slotTriggered() after exec, errorMessage=" << errorMessage(); #endif setError(d->script); //emit finished(this); finalize(); //return; } } emit finished(this); } // -------- // interface files WrapperInterface::~WrapperInterface() { } <commit_msg>core: handle better comments for actions<commit_after>/*************************************************************************** * action.cpp * This file is part of the KDE project * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.org) * * This program 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 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 * Library General Public License for more details. * You should have received a copy of the GNU Library General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. ***************************************************************************/ #include "action.h" #include "actioncollection.h" #include "interpreter.h" #include "script.h" #include "manager.h" #include "wrapperinterface.h" #include "kross_debug.h" #include <QFile> #include <QFileInfo> #include <klocalizedstring.h> #include <qmimedatabase.h> using namespace Kross; namespace Kross { /// \internal d-pointer class. class Action::Private { public: /** * The \a Script instance the \a Action uses if initialized. It will * be NULL as long as we didn't initialized it what will be done on * demand. */ Script *script; /** * The version number this \a Action has. Those version number got * used internaly to deal with different releases of scripts. */ int version; /** * The optional description to provide some more details about the * Action to the user. */ QString description; /** * The name of the icon. */ QString iconname; /** * The scripting code. */ QByteArray code; /** * The name of the interpreter. This could be something * like for example "python" for the python binding. */ QString interpretername; /** * The name of the scriptfile that should be executed. Those * scriptfile will be readed and the content will be used to * set the scripting code and, if not defined, the used * interpreter. */ QString scriptfile; /** * The path list where the \a Script may be located. * \todo after BIC break: don't keep it all the time, * as it is now passed to [to|from]DomElement */ QStringList searchpath; /** * Map of options that overwritte the \a InterpreterInfo::Option::Map * standard options. */ QMap< QString, QVariant > options; Private() : script(nullptr), version(0) {} }; } enum InitOptions {Enable = 1}; void static init(Action *th, const QString &name, int options = 0) { th->setEnabled(options & Enable); th->setObjectName(name); #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << "Action::Action(QObject*,QString,QDir) Ctor name=" << th->objectName(); #endif QObject::connect(th, SIGNAL(triggered(bool)), th, SLOT(slotTriggered())); } Action::Action(QObject *parent, const QString &name, const QDir &packagepath) : QAction(parent) , QScriptable() , ChildrenInterface() , ErrorInterface() , d(new Private()) { init(this, name); d->searchpath = QStringList(packagepath.absolutePath()); } Action::Action(QObject *parent, const QUrl &url) : QAction(parent) , ChildrenInterface() , ErrorInterface() , d(new Private()) { init(this, url.path(), Enable); QFileInfo fi(url.toLocalFile()); setText(fi.fileName()); QMimeDatabase db; setIconName(db.mimeTypeForUrl(url).iconName()); setFile(url.toLocalFile()); } Action::~Action() { #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << QStringLiteral("Action::~Action() Dtor name='%1'").arg(objectName()); #endif finalize(); ActionCollection *coll = qobject_cast<ActionCollection *>(parent()); if (coll) { coll->removeAction(this); } delete d; } void Action::fromDomElement(const QDomElement &element) { fromDomElement(element, d->searchpath); } void Action::fromDomElement(const QDomElement &element, const QStringList &searchPath) { if (element.isNull()) { return; } QString file = element.attribute("file"); if (! file.isEmpty()) { if (QFileInfo(file).exists()) { setFile(file); } else { foreach (const QString &packagepath, searchPath) { QFileInfo fi(QDir(packagepath), file); if (fi.exists()) { setFile(fi.absoluteFilePath()); break; } } } } d->version = QVariant(element.attribute("version", QString(d->version))).toInt(); setText(i18nd(KLocalizedString::applicationDomain().constData(), element.attribute("text").toUtf8().constData())); const QString comment = element.attribute("comment"); if (!comment.isEmpty()) { setDescription(i18nd(KLocalizedString::applicationDomain().constData(), comment.toUtf8().constData())); } setEnabled(true); setInterpreter(element.attribute("interpreter")); setEnabled(QVariant(element.attribute("enabled", "true")).toBool() && isEnabled()); QString icon = element.attribute("icon"); if (icon.isEmpty() && ! d->scriptfile.isNull()) { QMimeDatabase db; icon = db.mimeTypeForUrl(QUrl::fromLocalFile(d->scriptfile)).iconName(); } setIconName(icon); const QString code = element.attribute("code"); if (! code.isNull()) { setCode(code.toUtf8()); } for (QDomNode node = element.firstChild(); ! node.isNull(); node = node.nextSibling()) { QDomElement e = node.toElement(); if (! e.isNull()) { if (e.tagName() == "property") { const QString n = e.attribute("name", QString()); if (! n.isNull()) { #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << "Action::readDomElement: Setting property name=" << n << " value=" << e.text(); #endif setProperty(n.toLatin1().constData(), QVariant(e.text())); } } } } } QDomElement Action::toDomElement() const { return toDomElement(QStringList()); } QDomElement Action::toDomElement(const QStringList &searchPath) const { QDomDocument doc; QDomElement e = doc.createElement("script"); e.setAttribute("name", objectName()); if (d->version > 0) { e.setAttribute("version", QString(d->version)); } if (! text().isNull()) { e.setAttribute("text", text()); } if (! description().isNull()) { e.setAttribute("comment", description()); } if (! iconName().isNull()) { e.setAttribute("icon", iconName()); } if (! isEnabled()) { e.setAttribute("enabled", "false"); } if (! interpreter().isNull()) { e.setAttribute("interpreter", interpreter()); } QString fileName = file(); if (!searchPath.isEmpty()) { //fileName=QDir(searchPath.first()).relativeFilePath(fileName); //prefer absname if it is short? foreach (const QString &packagepath, searchPath) { QString nfn = QDir(packagepath).relativeFilePath(file()); if (nfn.length() < fileName.length()) { fileName = nfn; } } } if (! fileName.isNull()) { e.setAttribute("file", fileName); } QList<QByteArray> props = dynamicPropertyNames(); foreach (const QByteArray &prop, props) { QDomElement p = doc.createElement("property"); p.setAttribute("name", QString::fromLatin1(prop)); p.appendChild(doc.createTextNode(property(prop.constData()).toString())); e.appendChild(p); } /* else if( ! code().isNull() ) { e.setAttribute("code", code()); } */ return e; } Kross::Script *Action::script() const { return d->script; } QString Action::name() const { return objectName(); } int Action::version() const { return d->version; } QString Action::description() const { return d->description; } void Action::setDescription(const QString &description) { d->description = description; emit dataChanged(this); emit updated(); } QString Action::iconName() const { return d->iconname; } void Action::setIconName(const QString &iconname) { setIcon(QIcon::fromTheme(iconname)); d->iconname = iconname; emit dataChanged(this); emit updated(); } bool Action::isEnabled() const { return QAction::isEnabled(); } void Action::setEnabled(bool enabled) { QAction::setEnabled(enabled); emit dataChanged(this); emit updated(); } QByteArray Action::code() const { return d->code; } void Action::setCode(const QByteArray &code) { if (d->code != code) { finalize(); d->code = code; emit dataChanged(this); emit updated(); } } QString Action::interpreter() const { return d->interpretername; } void Action::setInterpreter(const QString &interpretername) { if (d->interpretername != interpretername) { finalize(); d->interpretername = interpretername; setEnabled(Manager::self().interpreters().contains(interpretername)); if (!isEnabled()) { qCWarning(KROSS_LOG) << "Action::setInterpreter: interpreter not found: " << interpretername; } emit dataChanged(this); emit updated(); } } QString Action::file() const { return d->scriptfile; } bool Action::setFile(const QString &scriptfile) { if (d->scriptfile != scriptfile) { finalize(); if (scriptfile.isNull()) { if (! d->scriptfile.isNull()) { d->interpretername.clear(); } d->scriptfile.clear(); d->searchpath.clear(); } else { d->scriptfile = scriptfile; d->interpretername = Manager::self().interpreternameForFile(scriptfile); if (d->interpretername.isNull()) { return false; } } } return true; } QString Action::currentPath() const { return file().isEmpty() ? QString() : QFileInfo(file()).absolutePath(); //obey Qt docs and don't cheat } QVariantMap Action::options() const { return d->options; } void Action::addQObject(QObject *obj, const QString &name) { this->addObject(obj, name); } QObject *Action::qobject(const QString &name) const { return this->object(name); } QStringList Action::qobjectNames() const { return this->objects().keys(); } QVariant Action::option(const QString &name, const QVariant &defaultvalue) { if (d->options.contains(name)) { return d->options[name]; } InterpreterInfo *info = Manager::self().interpreterInfo(d->interpretername); return info ? info->optionValue(name, defaultvalue) : defaultvalue; } bool Action::setOption(const QString &name, const QVariant &value) { InterpreterInfo *info = Manager::self().interpreterInfo(d->interpretername); if (info) { if (info->hasOption(name)) { d->options.insert(name, value); return true; } else { qCWarning(KROSS_LOG) << QStringLiteral("Kross::Action::setOption(%1, %2): No such option") .arg(name).arg(value.toString()); } } else { qCWarning(KROSS_LOG) << QStringLiteral("Kross::Action::setOption(%1, %2): No such interpreterinfo") .arg(name).arg(value.toString()); } return false; } QStringList Action::functionNames() { if (! d->script) { if (! initialize()) { return QStringList(); } } return d->script->functionNames(); } QVariant Action::callFunction(const QString &name, const QVariantList &args) { if (! d->script) { if (! initialize()) { return QVariant(); } } return d->script->callFunction(name, args); } QVariant Action::evaluate(const QByteArray &code) { if (! d->script) { if (! initialize()) { return QVariant(); } } return d->script->evaluate(code); } bool Action::initialize() { finalize(); if (! d->scriptfile.isNull()) { QFile f(d->scriptfile); if (! f.exists()) { setError(i18n("Scriptfile \"%1\" does not exist.", d->scriptfile)); return false; } if (d->interpretername.isNull()) { setError(i18n("Failed to determine interpreter for scriptfile \"%1\"", d->scriptfile)); return false; } if (! f.open(QIODevice::ReadOnly)) { setError(i18n("Failed to open scriptfile \"%1\"", d->scriptfile)); return false; } d->code = f.readAll(); f.close(); } Interpreter *interpreter = Manager::self().interpreter(d->interpretername); if (! interpreter) { InterpreterInfo *info = Manager::self().interpreterInfo(d->interpretername); if (info) { setError(i18n("Failed to load interpreter \"%1\"", d->interpretername)); } else { setError(i18n("No such interpreter \"%1\"", d->interpretername)); } return false; } d->script = interpreter->createScript(this); if (! d->script) { setError(i18n("Failed to create script for interpreter \"%1\"", d->interpretername)); return false; } if (d->script->hadError()) { setError(d->script); finalize(); return false; } clearError(); // clear old exception return true; } void Action::finalize() { if (d->script) { emit finalized(this); } delete d->script; d->script = nullptr; } bool Action::isFinalized() const { return d->script == nullptr; } void Action::slotTriggered() { #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << "Action::slotTriggered() name=" << objectName(); #endif emit started(this); if (! d->script) { if (! initialize()) { Q_ASSERT(hadError()); } } if (hadError()) { #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << "Action::slotTriggered() on init, errorMessage=" << errorMessage(); #endif } else { d->script->execute(); if (d->script->hadError()) { #ifdef KROSS_ACTION_DEBUG qCDebug(KROSS_LOG) << "Action::slotTriggered() after exec, errorMessage=" << errorMessage(); #endif setError(d->script); //emit finished(this); finalize(); //return; } } emit finished(this); } // -------- // interface files WrapperInterface::~WrapperInterface() { } <|endoftext|>
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld 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 "flusspferd/getopt.hpp" #include "flusspferd/object.hpp" #include "flusspferd/array.hpp" #include "flusspferd/create.hpp" #include "flusspferd/property_iterator.hpp" #include <iostream> #include <map> using namespace flusspferd; void flusspferd::load_getopt_module(object container) { object exports = container.get_property_object("exports"); flusspferd::create_native_function(exports, "getopt", &flusspferd::getopt); } struct optspec { std::map<std::string, int> options; optspec(object const &spec) { for (property_iterator it = spec.begin(); it != spec.end(); ++it) { std::string name = it->to_std_string(); int data = 0; options.insert(std::make_pair(name, data)); std::cout << name << std::endl; object item = spec.get_property_object(name); if (!item.is_null()) { value aliases = item.get_property("alias"); if (aliases.is_undefined_or_null()) aliases = item.get_property("aliases"); if (!aliases.is_array()) { options.insert(std::make_pair(aliases.to_std_string(), data)); } else { array aliases_a(aliases.get_object()); } } } } }; object flusspferd::getopt( object spec_, boost::optional<array const &> const &arguments_) { if (!arguments_) { object sys = flusspferd::global().call("require", "system").to_object(); array args(sys.get_property_object("args")); return getopt(spec_, args); } array const &arguments = arguments_.get(); optspec spec(spec_); // TODO return flusspferd::object(); } <commit_msg>core/getopt: fix compilation issue<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld 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 "flusspferd/getopt.hpp" #include "flusspferd/object.hpp" #include "flusspferd/array.hpp" #include "flusspferd/create.hpp" #include "flusspferd/property_iterator.hpp" #include <iostream> #include <map> using namespace flusspferd; void flusspferd::load_getopt_module(object container) { object exports = container.get_property_object("exports"); flusspferd::create_native_function(exports, "getopt", &flusspferd::getopt); } struct optspec { std::map<std::string, int> options; optspec(object const &spec) { for (property_iterator it = spec.begin(); it != spec.end(); ++it) { std::string name = it->to_std_string(); int data = 0; options.insert(std::make_pair(name, data)); std::cout << name << std::endl; object item = spec.get_property_object(name); if (!item.is_null()) { value aliases = item.get_property("alias"); if (aliases.is_undefined_or_null()) aliases = item.get_property("aliases"); if (!aliases.is_object() || !aliases.get_object().is_array()) { options.insert(std::make_pair(aliases.to_std_string(), data)); } else { array aliases_a(aliases.get_object()); } } } } }; object flusspferd::getopt( object spec_, boost::optional<array const &> const &arguments_) { if (!arguments_) { object sys = flusspferd::global().call("require", "system").to_object(); array args(sys.get_property_object("args")); return getopt(spec_, args); } array const &arguments = arguments_.get(); optspec spec(spec_); // TODO return flusspferd::object(); } <|endoftext|>
<commit_before>/* Copyright (c) 2018 Anon authors, see AUTHORS file. 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 "aws_sqs.h" #include <aws/sqs/model/QueueAttributeName.h> #include <aws/sqs/model/SendMessageRequest.h> using namespace Aws::SQS; using json = nlohmann::json; aws_sqs_listener::aws_sqs_listener(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider, const Aws::Client::ClientConfiguration &client_config, const Aws::String &queue_url, const std::function<bool(const Aws::SQS::Model::Message &m)> &handler, bool single_concurrent_message, size_t stack_size) : _client(provider, client_config), _queue_url(queue_url), _num_fibers(0), _exit_now(false), _process_msg(handler), _consecutive_errors(0), _single_concurrent_message(single_concurrent_message), _stack_size(stack_size), _continue_after_timeout([]{return true;}) { } aws_sqs_listener::aws_sqs_listener(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider, const Aws::Client::ClientConfiguration &client_config, const Aws::String &queue_url, const std::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>&)> &handler, bool single_concurrent_message, size_t stack_size) : _client(provider, client_config), _queue_url(queue_url), _num_fibers(0), _exit_now(false), _process_msg_del(handler), _consecutive_errors(0), _single_concurrent_message(single_concurrent_message), _stack_size(stack_size), _continue_after_timeout([]{return true;}) { } void aws_sqs_listener::start() { std::weak_ptr<aws_sqs_listener> wp = shared_from_this(); fiber::run_in_fiber( [wp] { auto ths = wp.lock(); if (ths) ths->start_listen(); }, aws_sqs_listener::_simple_stack_size, "aws_sqs_listener::aws_sqs_listener, start_listen"); #if defined(ANON_DEBUG_TIMERS) anon_log("io_dispatch::schedule_task, aws_sqs_listener::start"); #endif _timer_task = io_dispatch::schedule_task( [wp] { fiber::run_in_fiber( [wp] { auto ths = wp.lock(); if (ths) ths->set_visibility_timeout(); }, aws_sqs_listener::_simple_stack_size, "aws_sqs_listener, set_visibility_timeout sweeper"); }, cur_time() + visibility_sweep_time); } aws_sqs_listener::~aws_sqs_listener() { { _exit_now = true; fiber_lock l(_mtx); while (_num_fibers > 0) _num_fibers_cond.wait(l); } io_dispatch::remove_task(_timer_task); } std::function<bool(const Aws::SQS::Model::Message &m)> aws_sqs_listener::js_wrap(const std::function<bool(const Aws::SQS::Model::Message &m, const nlohmann::json &body)> &fn) { return [fn](const Aws::SQS::Model::Message &m) -> bool { std::string body = get_body(m); try { json body_js = json::parse(body.begin(), body.end()); try { return fn(m, body_js); } catch (const inval_message& exc) { anon_log_error("caught exception processing message: " << exc.what() << ", message body: '" << body << "'"); return true; } catch (const std::exception &exc) { anon_log_error("caught exception processing message: " << exc.what() << ", message body: '" << body << "'"); return false; } catch (...) { anon_log_error("caught unknown exception processing message, message body: '" << body << "'"); return false; } } catch (const std::exception &exc) { anon_log_error("caught exception parsing message: " << exc.what() << ", message body: '" << body << "'"); return true; } catch (...) { anon_log_error("caught unknown exception parsing message, message body: '" << body << "'"); return true; } }; } std::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del)> aws_sqs_listener::js_wrap(const std::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del, const nlohmann::json &body)> &fn) { return [fn](const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del) -> bool { std::string body = get_body(m); try { json body_js = json::parse(body.begin(), body.end()); try { return fn(m, del, body_js); } catch (const inval_message& exc) { anon_log_error("caught exception processing message: " << exc.what() << ", message body: '" << body << "'"); del(true); return true; } catch (const std::exception &exc) { anon_log_error("caught exception processing message: " << exc.what() << ", message body: '" << body << "'"); return false; } catch (...) { anon_log_error("caught unknown exception processing message, message body: '" << body << "'"); return false; } } catch (const std::exception &exc) { anon_log_error("caught exception parsing message: " << exc.what() << ", message body: '" << body << "'"); del(true); return true; } catch (...) { anon_log_error("caught unknown exception parsing message, message body: '" << body << "'"); del(true); return true; } }; } void aws_sqs_listener::start_listen() { Model::ReceiveMessageRequest req; req.WithQueueUrl(_queue_url).WithMaxNumberOfMessages(_single_concurrent_message ? 1 : max_messages_per_read).WithWaitTimeSeconds(read_wait_time); Aws::Vector<Model::QueueAttributeName> att; att.push_back(Model::QueueAttributeName::All); req.WithAttributeNames(std::move(att)); std::weak_ptr<aws_sqs_listener> wp = shared_from_this(); _client.ReceiveMessageAsync(req, [wp](const SQSClient *, const Model::ReceiveMessageRequest &, const Model::ReceiveMessageOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) { auto ths = wp.lock(); if (!ths) return; fiber::rename_fiber("aws_sqs_listener::start_listen, ReceiveMessageAsync"); if (!out.IsSuccess()) { ++ths->_consecutive_errors; if (ths->_consecutive_errors > 10) { anon_log_error("SQS ReceiveMessage failed, _consecutive_errors: " << ths->_consecutive_errors << "\n" << out.GetError()); } else { anon_log("SQS ReceiveMessage failed, _consecutive_errors: " << ths->_consecutive_errors); } fiber::msleep(2000); } else { ths->_consecutive_errors = 0; auto &messages = out.GetResult().GetMessages(); auto num_messages = messages.size(); if (num_messages > 0) { ths->_num_fibers += num_messages; for (auto &m : messages) fiber::run_in_fiber( [wp, m] { auto ths = wp.lock(); if (!ths) return; anon_log("adding message " << m.GetMessageId() << " to keep_alive"); ths->add_to_keep_alive(m); bool success; if (ths->_process_msg) { success = ths->_process_msg(m); if (success) ths->delete_message(m); if (ths->_single_concurrent_message && !ths->_exit_now) ths->start_listen(); } else success = ths->_process_msg_del(m, [wp, m](bool delete_it) { auto ths = wp.lock(); if (ths) { if (delete_it) ths->delete_message(m); else ths->remove_from_keep_alive(m, true); } }); if (!success) ths->remove_from_keep_alive(m, true); }, ths->_stack_size, "aws_sqs_listener, process_msg"); } else { if (!ths->_continue_after_timeout()) ths->_exit_now = true; } } if (ths->_consecutive_errors < 1000) { if (!ths->_single_concurrent_message && !ths->_exit_now) { fiber_lock l(ths->_mtx); while (ths->_num_fibers >= max_in_flight_fibers) ths->_num_fibers_cond.wait(l); fiber::run_in_fiber( [wp] { auto ths = wp.lock(); if (ths) ths->start_listen(); }, aws_sqs_listener::_simple_stack_size, "aws_sqs_listener, restart_listen"); } } else anon_log_error("too many consecutive errors, giving up..."); }); } void aws_sqs_listener::set_visibility_timeout() { fiber_lock l(_mtx); auto numMessages = _alive_set.size(); if (numMessages > 0) { Model::ChangeMessageVisibilityBatchRequest req; Aws::Vector<Aws::Vector<Model::ChangeMessageVisibilityBatchRequestEntry>> entries_v; int index = 0; for (auto it : _alive_set) { Model::ChangeMessageVisibilityBatchRequestEntry ent; std::ostringstream str; if (index % 10 == 0) entries_v.push_back(Aws::Vector<Model::ChangeMessageVisibilityBatchRequestEntry>()); str << "message_" << ++index; ent.WithReceiptHandle(it.first).WithVisibilityTimeout(visibility_time).WithId(str.str()); entries_v.back().push_back(ent); } for (auto &entries : entries_v) { req.WithQueueUrl(_queue_url).WithEntries(entries); auto nMessages = entries.size(); _client.ChangeMessageVisibilityBatchAsync(req, [nMessages](const SQSClient *, const Model::ChangeMessageVisibilityBatchRequest &, const Model::ChangeMessageVisibilityBatchOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) { fiber::rename_fiber("aws_sqs_listener::set_visibility_timeout, ChangeMessageVisibilityBatchAsync"); if (out.IsSuccess()) { anon_log("batch visibilty reset for " << nMessages << " messages"); } else { do_error("batch reset visibility for " << nMessages << " messages: " << out.GetError().GetMessage()); } }); } } // schedule the sweep to run again in visibility_sweep_time seconds std::weak_ptr<aws_sqs_listener> wp = shared_from_this(); #if defined(ANON_DEBUG_TIMERS) anon_log("io_dispatch::schedule_task, aws_sqs_listener::set_visibility_timeout"); #endif _timer_task = io_dispatch::schedule_task( [wp] { fiber::run_in_fiber( [wp] { auto ths = wp.lock(); if (ths) ths->set_visibility_timeout(); }, aws_sqs_listener::_simple_stack_size, "aws_sqs_listener, set_visibility_timeout sweeper"); }, cur_time() + visibility_sweep_time); } void aws_sqs_listener::add_to_keep_alive(const Model::Message &m) { fiber_lock l(_mtx); _alive_set[m.GetReceiptHandle()] = m.GetMessageId(); } void aws_sqs_listener::remove_from_keep_alive(const Model::Message &m, bool reset_visibility) { { fiber_lock l(_mtx); _alive_set.erase(m.GetReceiptHandle()); } if (reset_visibility) { // encourage the system to try this message again soon by resetting its visility near 0 Model::ChangeMessageVisibilityRequest req; req.WithQueueUrl(_queue_url).WithReceiptHandle(m.GetReceiptHandle()).WithVisibilityTimeout(visibility_immediate_retry_time); auto messageId = m.GetMessageId(); _client.ChangeMessageVisibilityAsync(req, [messageId](const SQSClient *, const Model::ChangeMessageVisibilityRequest &, const Model::ChangeMessageVisibilityOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) { fiber::rename_fiber("aws_sqs_listener::remove_from_keep_alive, ChangeMessageVisibilityAsync"); if (out.IsSuccess()) { anon_log("reset message visibility near 0 for " << messageId); } else { do_error("reset message visibility near 0 for " << messageId << ", " << out.GetError().GetMessage()); } }); } } void aws_sqs_listener::delete_message(const Model::Message &m) { Model::DeleteMessageRequest req; req.WithQueueUrl(_queue_url).WithReceiptHandle(m.GetReceiptHandle()); auto messageId = m.GetMessageId(); std::weak_ptr<aws_sqs_listener> wp = shared_from_this(); _client.DeleteMessageAsync(req, [messageId, wp, m](const SQSClient *, const Model::DeleteMessageRequest &, const Model::DeleteMessageOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) { fiber::rename_fiber("aws_sqs_listener::delete_message, DeleteMessageAsync"); if (out.IsSuccess()) { anon_log("deleted SQS message " << messageId); } else { anon_log("delete SQS message failed, messageId:" << messageId << ", " << out.GetError().GetMessage()); } auto ths = wp.lock(); if (ths) ths->remove_from_keep_alive(m, false); }); } aws_sqs_sender::aws_sqs_sender(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider, const Aws::Client::ClientConfiguration &client_config, const Aws::String &queue_url) : _client(provider, client_config), _queue_url(queue_url) { } void aws_sqs_sender::send(const json &body, const std::function<void(const bool success, const std::string &id, const std::string &errorReason)> &response) { Model::SendMessageRequest req; req.WithQueueUrl(_queue_url).WithMessageBody(Aws::String(body.dump())); _client.SendMessageAsync(req, [response](const SQSClient *, const Model::SendMessageRequest &, const Model::SendMessageOutcome &outcome, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) { fiber::rename_fiber("aws_sqs_sender::send, SendMessageAsync"); response(outcome.IsSuccess(), std::string(outcome.GetResult().GetMessageId()), std::string(outcome.GetError().GetMessage())); }); } <commit_msg>removing log message<commit_after>/* Copyright (c) 2018 Anon authors, see AUTHORS file. 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 "aws_sqs.h" #include <aws/sqs/model/QueueAttributeName.h> #include <aws/sqs/model/SendMessageRequest.h> using namespace Aws::SQS; using json = nlohmann::json; aws_sqs_listener::aws_sqs_listener(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider, const Aws::Client::ClientConfiguration &client_config, const Aws::String &queue_url, const std::function<bool(const Aws::SQS::Model::Message &m)> &handler, bool single_concurrent_message, size_t stack_size) : _client(provider, client_config), _queue_url(queue_url), _num_fibers(0), _exit_now(false), _process_msg(handler), _consecutive_errors(0), _single_concurrent_message(single_concurrent_message), _stack_size(stack_size), _continue_after_timeout([]{return true;}) { } aws_sqs_listener::aws_sqs_listener(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider, const Aws::Client::ClientConfiguration &client_config, const Aws::String &queue_url, const std::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>&)> &handler, bool single_concurrent_message, size_t stack_size) : _client(provider, client_config), _queue_url(queue_url), _num_fibers(0), _exit_now(false), _process_msg_del(handler), _consecutive_errors(0), _single_concurrent_message(single_concurrent_message), _stack_size(stack_size), _continue_after_timeout([]{return true;}) { } void aws_sqs_listener::start() { std::weak_ptr<aws_sqs_listener> wp = shared_from_this(); fiber::run_in_fiber( [wp] { auto ths = wp.lock(); if (ths) ths->start_listen(); }, aws_sqs_listener::_simple_stack_size, "aws_sqs_listener::aws_sqs_listener, start_listen"); #if defined(ANON_DEBUG_TIMERS) anon_log("io_dispatch::schedule_task, aws_sqs_listener::start"); #endif _timer_task = io_dispatch::schedule_task( [wp] { fiber::run_in_fiber( [wp] { auto ths = wp.lock(); if (ths) ths->set_visibility_timeout(); }, aws_sqs_listener::_simple_stack_size, "aws_sqs_listener, set_visibility_timeout sweeper"); }, cur_time() + visibility_sweep_time); } aws_sqs_listener::~aws_sqs_listener() { { _exit_now = true; fiber_lock l(_mtx); while (_num_fibers > 0) _num_fibers_cond.wait(l); } io_dispatch::remove_task(_timer_task); } std::function<bool(const Aws::SQS::Model::Message &m)> aws_sqs_listener::js_wrap(const std::function<bool(const Aws::SQS::Model::Message &m, const nlohmann::json &body)> &fn) { return [fn](const Aws::SQS::Model::Message &m) -> bool { std::string body = get_body(m); try { json body_js = json::parse(body.begin(), body.end()); try { return fn(m, body_js); } catch (const inval_message& exc) { anon_log_error("caught exception processing message: " << exc.what() << ", message body: '" << body << "'"); return true; } catch (const std::exception &exc) { anon_log_error("caught exception processing message: " << exc.what() << ", message body: '" << body << "'"); return false; } catch (...) { anon_log_error("caught unknown exception processing message, message body: '" << body << "'"); return false; } } catch (const std::exception &exc) { anon_log_error("caught exception parsing message: " << exc.what() << ", message body: '" << body << "'"); return true; } catch (...) { anon_log_error("caught unknown exception parsing message, message body: '" << body << "'"); return true; } }; } std::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del)> aws_sqs_listener::js_wrap(const std::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del, const nlohmann::json &body)> &fn) { return [fn](const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del) -> bool { std::string body = get_body(m); try { json body_js = json::parse(body.begin(), body.end()); try { return fn(m, del, body_js); } catch (const inval_message& exc) { anon_log_error("caught exception processing message: " << exc.what() << ", message body: '" << body << "'"); del(true); return true; } catch (const std::exception &exc) { anon_log_error("caught exception processing message: " << exc.what() << ", message body: '" << body << "'"); return false; } catch (...) { anon_log_error("caught unknown exception processing message, message body: '" << body << "'"); return false; } } catch (const std::exception &exc) { anon_log_error("caught exception parsing message: " << exc.what() << ", message body: '" << body << "'"); del(true); return true; } catch (...) { anon_log_error("caught unknown exception parsing message, message body: '" << body << "'"); del(true); return true; } }; } void aws_sqs_listener::start_listen() { Model::ReceiveMessageRequest req; req.WithQueueUrl(_queue_url).WithMaxNumberOfMessages(_single_concurrent_message ? 1 : max_messages_per_read).WithWaitTimeSeconds(read_wait_time); Aws::Vector<Model::QueueAttributeName> att; att.push_back(Model::QueueAttributeName::All); req.WithAttributeNames(std::move(att)); std::weak_ptr<aws_sqs_listener> wp = shared_from_this(); _client.ReceiveMessageAsync(req, [wp](const SQSClient *, const Model::ReceiveMessageRequest &, const Model::ReceiveMessageOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) { auto ths = wp.lock(); if (!ths) return; fiber::rename_fiber("aws_sqs_listener::start_listen, ReceiveMessageAsync"); if (!out.IsSuccess()) { ++ths->_consecutive_errors; if (ths->_consecutive_errors > 10) { anon_log_error("SQS ReceiveMessage failed, _consecutive_errors: " << ths->_consecutive_errors << "\n" << out.GetError()); } else { anon_log("SQS ReceiveMessage failed, _consecutive_errors: " << ths->_consecutive_errors); } fiber::msleep(2000); } else { ths->_consecutive_errors = 0; auto &messages = out.GetResult().GetMessages(); auto num_messages = messages.size(); if (num_messages > 0) { ths->_num_fibers += num_messages; for (auto &m : messages) fiber::run_in_fiber( [wp, m] { auto ths = wp.lock(); if (!ths) return; anon_log("adding message " << m.GetMessageId() << " to keep_alive"); ths->add_to_keep_alive(m); bool success; if (ths->_process_msg) { success = ths->_process_msg(m); if (success) ths->delete_message(m); if (ths->_single_concurrent_message && !ths->_exit_now) ths->start_listen(); } else success = ths->_process_msg_del(m, [wp, m](bool delete_it) { auto ths = wp.lock(); if (ths) { if (delete_it) ths->delete_message(m); else ths->remove_from_keep_alive(m, true); } }); if (!success) ths->remove_from_keep_alive(m, true); }, ths->_stack_size, "aws_sqs_listener, process_msg"); } else { if (!ths->_continue_after_timeout()) ths->_exit_now = true; } } if (ths->_consecutive_errors < 1000) { if (!ths->_single_concurrent_message && !ths->_exit_now) { fiber_lock l(ths->_mtx); while (ths->_num_fibers >= max_in_flight_fibers) ths->_num_fibers_cond.wait(l); fiber::run_in_fiber( [wp] { auto ths = wp.lock(); if (ths) ths->start_listen(); }, aws_sqs_listener::_simple_stack_size, "aws_sqs_listener, restart_listen"); } } else anon_log_error("too many consecutive errors, giving up..."); }); } void aws_sqs_listener::set_visibility_timeout() { fiber_lock l(_mtx); auto numMessages = _alive_set.size(); if (numMessages > 0) { Model::ChangeMessageVisibilityBatchRequest req; Aws::Vector<Aws::Vector<Model::ChangeMessageVisibilityBatchRequestEntry>> entries_v; int index = 0; for (auto it : _alive_set) { Model::ChangeMessageVisibilityBatchRequestEntry ent; std::ostringstream str; if (index % 10 == 0) entries_v.push_back(Aws::Vector<Model::ChangeMessageVisibilityBatchRequestEntry>()); str << "message_" << ++index; ent.WithReceiptHandle(it.first).WithVisibilityTimeout(visibility_time).WithId(str.str()); entries_v.back().push_back(ent); } for (auto &entries : entries_v) { req.WithQueueUrl(_queue_url).WithEntries(entries); auto nMessages = entries.size(); _client.ChangeMessageVisibilityBatchAsync(req, [nMessages](const SQSClient *, const Model::ChangeMessageVisibilityBatchRequest &, const Model::ChangeMessageVisibilityBatchOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) { fiber::rename_fiber("aws_sqs_listener::set_visibility_timeout, ChangeMessageVisibilityBatchAsync"); if (out.IsSuccess()) { // anon_log("batch visibilty reset for " << nMessages << " messages"); } else { do_error("batch reset visibility for " << nMessages << " messages: " << out.GetError().GetMessage()); } }); } } // schedule the sweep to run again in visibility_sweep_time seconds std::weak_ptr<aws_sqs_listener> wp = shared_from_this(); #if defined(ANON_DEBUG_TIMERS) anon_log("io_dispatch::schedule_task, aws_sqs_listener::set_visibility_timeout"); #endif _timer_task = io_dispatch::schedule_task( [wp] { fiber::run_in_fiber( [wp] { auto ths = wp.lock(); if (ths) ths->set_visibility_timeout(); }, aws_sqs_listener::_simple_stack_size, "aws_sqs_listener, set_visibility_timeout sweeper"); }, cur_time() + visibility_sweep_time); } void aws_sqs_listener::add_to_keep_alive(const Model::Message &m) { fiber_lock l(_mtx); _alive_set[m.GetReceiptHandle()] = m.GetMessageId(); } void aws_sqs_listener::remove_from_keep_alive(const Model::Message &m, bool reset_visibility) { { fiber_lock l(_mtx); _alive_set.erase(m.GetReceiptHandle()); } if (reset_visibility) { // encourage the system to try this message again soon by resetting its visility near 0 Model::ChangeMessageVisibilityRequest req; req.WithQueueUrl(_queue_url).WithReceiptHandle(m.GetReceiptHandle()).WithVisibilityTimeout(visibility_immediate_retry_time); auto messageId = m.GetMessageId(); _client.ChangeMessageVisibilityAsync(req, [messageId](const SQSClient *, const Model::ChangeMessageVisibilityRequest &, const Model::ChangeMessageVisibilityOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) { fiber::rename_fiber("aws_sqs_listener::remove_from_keep_alive, ChangeMessageVisibilityAsync"); if (out.IsSuccess()) { anon_log("reset message visibility near 0 for " << messageId); } else { do_error("reset message visibility near 0 for " << messageId << ", " << out.GetError().GetMessage()); } }); } } void aws_sqs_listener::delete_message(const Model::Message &m) { Model::DeleteMessageRequest req; req.WithQueueUrl(_queue_url).WithReceiptHandle(m.GetReceiptHandle()); auto messageId = m.GetMessageId(); std::weak_ptr<aws_sqs_listener> wp = shared_from_this(); _client.DeleteMessageAsync(req, [messageId, wp, m](const SQSClient *, const Model::DeleteMessageRequest &, const Model::DeleteMessageOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) { fiber::rename_fiber("aws_sqs_listener::delete_message, DeleteMessageAsync"); if (out.IsSuccess()) { anon_log("deleted SQS message " << messageId); } else { anon_log("delete SQS message failed, messageId:" << messageId << ", " << out.GetError().GetMessage()); } auto ths = wp.lock(); if (ths) ths->remove_from_keep_alive(m, false); }); } aws_sqs_sender::aws_sqs_sender(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider, const Aws::Client::ClientConfiguration &client_config, const Aws::String &queue_url) : _client(provider, client_config), _queue_url(queue_url) { } void aws_sqs_sender::send(const json &body, const std::function<void(const bool success, const std::string &id, const std::string &errorReason)> &response) { Model::SendMessageRequest req; req.WithQueueUrl(_queue_url).WithMessageBody(Aws::String(body.dump())); _client.SendMessageAsync(req, [response](const SQSClient *, const Model::SendMessageRequest &, const Model::SendMessageOutcome &outcome, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) { fiber::rename_fiber("aws_sqs_sender::send, SendMessageAsync"); response(outcome.IsSuccess(), std::string(outcome.GetResult().GetMessageId()), std::string(outcome.GetError().GetMessage())); }); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2013 Zeex // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE 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 <cassert> #include <cstdarg> #include <cstdlib> #include <list> #include <map> #include <stack> #include <string> #include <amx/amx.h> #include <amx/amxaux.h> #include "amxdebuginfo.h" #include "amxerror.h" #include "amxpathfinder.h" #include "amxscript.h" #include "amxstacktrace.h" #include "compiler.h" #include "configreader.h" #include "crashdetect.h" #include "fileutils.h" #include "logprintf.h" #include "npcall.h" #include "os.h" #include "stacktrace.h" #define AMX_EXEC_GDK (-10) static const int kOpBounds = 121; static const int kOpSysreqC = 123; std::stack<NPCall*> CrashDetect::np_calls_; bool CrashDetect::error_detected_ = false; // static void CrashDetect::OnException(void *context) { if (!np_calls_.empty()) { CrashDetect::Get(np_calls_.top()->amx())->HandleException(); } else { Printf("Server crashed due to an unknown error"); } PrintSystemBacktrace(context); } // static void CrashDetect::OnInterrupt(void *context) { if (!np_calls_.empty()) { CrashDetect::Get(np_calls_.top()->amx())->HandleInterrupt(); } else { Printf("Server received interrupt signal"); } PrintSystemBacktrace(context); } // static void CrashDetect::PrintAmxBacktrace() { if (np_calls_.empty()) { return; } AMXScript topAmx = np_calls_.top()->amx(); cell frm = topAmx.GetFrm(); cell cip = topAmx.GetCip(); int level = 0; if (cip == 0) { return; } Printf("AMX backtrace:"); std::stack<NPCall*> np_calls = np_calls_; while (!np_calls.empty() && cip != 0) { const NPCall *call = np_calls.top(); AMXScript amx = call->amx(); // We don't trace calls across AMX bounds i.e. outside of top-level // function's AMX instance. if (amx != topAmx) { assert(level != 0); break; } if (call->IsNative()) { AMX_NATIVE address = reinterpret_cast<AMX_NATIVE>(amx.GetNativeAddr(call->index())); if (address != 0) { std::string module = fileutils::GetFileName(os::GetModulePathFromAddr((void*)address)); std::string from = " from " + module; if (module.empty()) { from.clear(); } const char *name = amx.GetNativeName(call->index()); if (name != 0) { Printf("#%d native %s () [%08x]%s", level++, name, address, from.c_str()); } } } else if (call->IsPublic()) { AMXDebugInfo &debug_info = CrashDetect::Get(amx)->debug_info_; amx.PushStack(cip); // push return address amx.PushStack(frm); // push frame pointer std::list<AMXStackFrame> frames; { AMXStackTrace trace(amx, amx.GetStk(), &debug_info); do { AMXStackFrame frame = trace.GetFrame(); if (frame) { frames.push_back(frame); } else { break; } } while (trace.Next()); } frm = amx.PopStack(); // pop frame pointer cip = amx.PopStack(); // pop return address if (frames.empty()) { ucell ep_addr = amx.GetPublicAddr(call->index()); frames.push_front(AMXStackFrame(amx, frm, 0, ep_addr, &debug_info)); } else { if (!debug_info.IsLoaded()) { AMXStackFrame &bottom = frames.back(); bottom = AMXStackFrame(amx, bottom.GetFrameAddr(), bottom.GetRetAddr(), amx.GetPublicAddr(call->index()), &debug_info); } } std::string &amx_name = CrashDetect::Get(amx)->amx_name_; for (std::list<AMXStackFrame>::const_iterator iterator = frames.begin(); iterator != frames.end(); ++iterator) { std::string from = " from " + amx_name; if (amx_name.empty() || debug_info.IsLoaded()) { from.clear(); } Printf("#%d %s%s", level++, iterator->AsString().c_str(), from.c_str()); } frm = call->frm(); cip = call->cip(); } np_calls.pop(); } } // static void CrashDetect::PrintSystemBacktrace(void *context) { Printf("System backtrace:"); int level = 0; StackTrace trace(context); std::deque<StackFrame> frames = trace.GetFrames(); for (std::deque<StackFrame>::const_iterator iterator = frames.begin(); iterator != frames.end(); ++iterator) { const StackFrame &frame = *iterator; std::string module = os::GetModulePathFromAddr(frame.GetRetAddr()); std::string from = " from " + module; if (module.empty()) { from.clear(); } Printf("#%d %s%s", level++, frame.AsString().c_str(), from.c_str()); } } // static void CrashDetect::Printf(const char *format, ...) { std::va_list va; va_start(va, format); std::string new_format; new_format.append("[debug] "); new_format.append(format); vlogprintf(new_format.c_str(), va); va_end(va); } CrashDetect::CrashDetect(AMX *amx) : AMXService<CrashDetect>(amx) , amx_(amx) , prev_callback_(0) , die_on_error_(false) , run_on_error_("") { ConfigReader server_cfg("server.cfg"); die_on_error_ = server_cfg.GetOption("die_on_error", false); run_on_error_ = server_cfg.GetOption("run_on_error", std::string()); } int CrashDetect::Load() { AMXPathFinder pathFinder; pathFinder.AddSearchPath("gamemodes"); pathFinder.AddSearchPath("filterscripts"); // Read a list of additional search paths from AMX_PATH. const char *AMX_PATH = getenv("AMX_PATH"); if (AMX_PATH != 0) { std::string var(AMX_PATH); std::string path; std::string::size_type begin = 0; while (begin < var.length()) { std::string::size_type end = var.find(fileutils::kNativePathListSepChar, begin); if (end == std::string::npos) { end = var.length(); } path.assign(var.begin() + begin, var.begin() + end); if (!path.empty()) { pathFinder.AddSearchPath(path); } begin = end + 1; } } amx_path_ = pathFinder.FindAMX(this->amx()); amx_name_ = fileutils::GetFileName(amx_path_); if (!amx_path_.empty() && AMXDebugInfo::IsPresent(this->amx())) { debug_info_.Load(amx_path_); } amx_.DisableSysreqD(); prev_callback_ = amx_.GetCallback(); return AMX_ERR_NONE; } int CrashDetect::Unload() { return AMX_ERR_NONE; } int CrashDetect::DoAmxCallback(cell index, cell *result, cell *params) { NPCall call = NPCall::Native(amx(), index); np_calls_.push(&call); int error = prev_callback_(amx(), index, result, params); np_calls_.pop(); return error; } int CrashDetect::DoAmxExec(cell *retval, int index) { NPCall call = NPCall::Public(amx(), index); np_calls_.push(&call); int error = ::amx_Exec(amx(), retval, index); if (error != AMX_ERR_NONE && !error_detected_) { HandleExecError(index, error); } else { error_detected_ = false; } np_calls_.pop(); return error; } void CrashDetect::HandleExecError(int index, const AMXError &error) { CrashDetect::error_detected_ = true; if (error.code() == AMX_ERR_INDEX && index == AMX_EXEC_GDK) { return; } PrintError(error); if (error.code() != AMX_ERR_NOTFOUND && error.code() != AMX_ERR_INDEX && error.code() != AMX_ERR_CALLBACK && error.code() != AMX_ERR_INIT) { PrintAmxBacktrace(); } if (!run_on_error_.empty()) { std::system(run_on_error_.c_str()); } if (die_on_error_) { Printf("Exiting"); std::exit(EXIT_FAILURE); } } void CrashDetect::HandleException() { Printf("Server crashed while executing %s", amx_name_.c_str()); PrintAmxBacktrace(); } void CrashDetect::HandleInterrupt() { Printf("Server received interrupt signal while executing %s", amx_name_.c_str()); PrintAmxBacktrace(); } void CrashDetect::PrintError(const AMXError &error) const { Printf("Run time error %d: \"%s\"", error.code(), error.GetString()); switch (error.code()) { case AMX_ERR_BOUNDS: { const cell *ip = reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip()); cell opcode = *ip; if (opcode == kOpBounds) { cell bound = *(ip + 1); cell index = amx_.GetPri(); if (index < 0) { Printf(" Accessing element at negative index %d", index); } else { Printf(" Accessing element at index %d past array upper bound %d", index, bound); } } break; } case AMX_ERR_NOTFOUND: { const AMX_FUNCSTUBNT *natives = amx_.GetNatives(); int num_natives = amx_.GetNumNatives(); for (int i = 0; i < num_natives; ++i) { if (natives[i].address == 0) { Printf(" %s", amx_.GetName(natives[i].nameofs)); } } break; } case AMX_ERR_STACKERR: Printf(" Stack pointer (STK) is 0x%X, heap pointer (HEA) is 0x%X", amx_.GetStk(), amx_.GetHea()); break; case AMX_ERR_STACKLOW: Printf(" Stack pointer (STK) is 0x%X, stack top (STP) is 0x%X", amx_.GetStk(), amx_.GetStp()); break; case AMX_ERR_HEAPLOW: Printf(" Heap pointer (HEA) is 0x%X, heap bottom (HLW) is 0x%X", amx_.GetHea(), amx_.GetHlw()); break; case AMX_ERR_INVINSTR: { cell opcode = *(reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip())); Printf(" Unknown opcode 0x%x at address 0x%08X", opcode , amx_.GetCip()); break; } case AMX_ERR_NATIVE: { const cell *ip = reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip()); cell opcode = *(ip - 2); if (opcode == kOpSysreqC) { cell index = *(ip - 1); Printf(" %s", amx_.GetNativeName(index)); } break; } } }<commit_msg>Add "Running command: XXX" message for run_on_error<commit_after>// Copyright (c) 2011-2013 Zeex // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE 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 <cassert> #include <cstdarg> #include <cstdlib> #include <list> #include <map> #include <stack> #include <string> #include <amx/amx.h> #include <amx/amxaux.h> #include "amxdebuginfo.h" #include "amxerror.h" #include "amxpathfinder.h" #include "amxscript.h" #include "amxstacktrace.h" #include "compiler.h" #include "configreader.h" #include "crashdetect.h" #include "fileutils.h" #include "logprintf.h" #include "npcall.h" #include "os.h" #include "stacktrace.h" #define AMX_EXEC_GDK (-10) static const int kOpBounds = 121; static const int kOpSysreqC = 123; std::stack<NPCall*> CrashDetect::np_calls_; bool CrashDetect::error_detected_ = false; // static void CrashDetect::OnException(void *context) { if (!np_calls_.empty()) { CrashDetect::Get(np_calls_.top()->amx())->HandleException(); } else { Printf("Server crashed due to an unknown error"); } PrintSystemBacktrace(context); } // static void CrashDetect::OnInterrupt(void *context) { if (!np_calls_.empty()) { CrashDetect::Get(np_calls_.top()->amx())->HandleInterrupt(); } else { Printf("Server received interrupt signal"); } PrintSystemBacktrace(context); } // static void CrashDetect::PrintAmxBacktrace() { if (np_calls_.empty()) { return; } AMXScript topAmx = np_calls_.top()->amx(); cell frm = topAmx.GetFrm(); cell cip = topAmx.GetCip(); int level = 0; if (cip == 0) { return; } Printf("AMX backtrace:"); std::stack<NPCall*> np_calls = np_calls_; while (!np_calls.empty() && cip != 0) { const NPCall *call = np_calls.top(); AMXScript amx = call->amx(); // We don't trace calls across AMX bounds i.e. outside of top-level // function's AMX instance. if (amx != topAmx) { assert(level != 0); break; } if (call->IsNative()) { AMX_NATIVE address = reinterpret_cast<AMX_NATIVE>(amx.GetNativeAddr(call->index())); if (address != 0) { std::string module = fileutils::GetFileName(os::GetModulePathFromAddr((void*)address)); std::string from = " from " + module; if (module.empty()) { from.clear(); } const char *name = amx.GetNativeName(call->index()); if (name != 0) { Printf("#%d native %s () [%08x]%s", level++, name, address, from.c_str()); } } } else if (call->IsPublic()) { AMXDebugInfo &debug_info = CrashDetect::Get(amx)->debug_info_; amx.PushStack(cip); // push return address amx.PushStack(frm); // push frame pointer std::list<AMXStackFrame> frames; { AMXStackTrace trace(amx, amx.GetStk(), &debug_info); do { AMXStackFrame frame = trace.GetFrame(); if (frame) { frames.push_back(frame); } else { break; } } while (trace.Next()); } frm = amx.PopStack(); // pop frame pointer cip = amx.PopStack(); // pop return address if (frames.empty()) { ucell ep_addr = amx.GetPublicAddr(call->index()); frames.push_front(AMXStackFrame(amx, frm, 0, ep_addr, &debug_info)); } else { if (!debug_info.IsLoaded()) { AMXStackFrame &bottom = frames.back(); bottom = AMXStackFrame(amx, bottom.GetFrameAddr(), bottom.GetRetAddr(), amx.GetPublicAddr(call->index()), &debug_info); } } std::string &amx_name = CrashDetect::Get(amx)->amx_name_; for (std::list<AMXStackFrame>::const_iterator iterator = frames.begin(); iterator != frames.end(); ++iterator) { std::string from = " from " + amx_name; if (amx_name.empty() || debug_info.IsLoaded()) { from.clear(); } Printf("#%d %s%s", level++, iterator->AsString().c_str(), from.c_str()); } frm = call->frm(); cip = call->cip(); } np_calls.pop(); } } // static void CrashDetect::PrintSystemBacktrace(void *context) { Printf("System backtrace:"); int level = 0; StackTrace trace(context); std::deque<StackFrame> frames = trace.GetFrames(); for (std::deque<StackFrame>::const_iterator iterator = frames.begin(); iterator != frames.end(); ++iterator) { const StackFrame &frame = *iterator; std::string module = os::GetModulePathFromAddr(frame.GetRetAddr()); std::string from = " from " + module; if (module.empty()) { from.clear(); } Printf("#%d %s%s", level++, frame.AsString().c_str(), from.c_str()); } } // static void CrashDetect::Printf(const char *format, ...) { std::va_list va; va_start(va, format); std::string new_format; new_format.append("[debug] "); new_format.append(format); vlogprintf(new_format.c_str(), va); va_end(va); } CrashDetect::CrashDetect(AMX *amx) : AMXService<CrashDetect>(amx) , amx_(amx) , prev_callback_(0) , die_on_error_(false) , run_on_error_("") { ConfigReader server_cfg("server.cfg"); die_on_error_ = server_cfg.GetOption("die_on_error", false); run_on_error_ = server_cfg.GetOption("run_on_error", std::string()); } int CrashDetect::Load() { AMXPathFinder pathFinder; pathFinder.AddSearchPath("gamemodes"); pathFinder.AddSearchPath("filterscripts"); // Read a list of additional search paths from AMX_PATH. const char *AMX_PATH = getenv("AMX_PATH"); if (AMX_PATH != 0) { std::string var(AMX_PATH); std::string path; std::string::size_type begin = 0; while (begin < var.length()) { std::string::size_type end = var.find(fileutils::kNativePathListSepChar, begin); if (end == std::string::npos) { end = var.length(); } path.assign(var.begin() + begin, var.begin() + end); if (!path.empty()) { pathFinder.AddSearchPath(path); } begin = end + 1; } } amx_path_ = pathFinder.FindAMX(this->amx()); amx_name_ = fileutils::GetFileName(amx_path_); if (!amx_path_.empty() && AMXDebugInfo::IsPresent(this->amx())) { debug_info_.Load(amx_path_); } amx_.DisableSysreqD(); prev_callback_ = amx_.GetCallback(); return AMX_ERR_NONE; } int CrashDetect::Unload() { return AMX_ERR_NONE; } int CrashDetect::DoAmxCallback(cell index, cell *result, cell *params) { NPCall call = NPCall::Native(amx(), index); np_calls_.push(&call); int error = prev_callback_(amx(), index, result, params); np_calls_.pop(); return error; } int CrashDetect::DoAmxExec(cell *retval, int index) { NPCall call = NPCall::Public(amx(), index); np_calls_.push(&call); int error = ::amx_Exec(amx(), retval, index); if (error != AMX_ERR_NONE && !error_detected_) { HandleExecError(index, error); } else { error_detected_ = false; } np_calls_.pop(); return error; } void CrashDetect::HandleExecError(int index, const AMXError &error) { CrashDetect::error_detected_ = true; if (error.code() == AMX_ERR_INDEX && index == AMX_EXEC_GDK) { return; } PrintError(error); if (error.code() != AMX_ERR_NOTFOUND && error.code() != AMX_ERR_INDEX && error.code() != AMX_ERR_CALLBACK && error.code() != AMX_ERR_INIT) { PrintAmxBacktrace(); } if (!run_on_error_.empty()) { Printf("Running command: %s", run_on_error_.c_str()); std::system(run_on_error_.c_str()); } if (die_on_error_) { Printf("Exiting"); std::exit(EXIT_FAILURE); } } void CrashDetect::HandleException() { Printf("Server crashed while executing %s", amx_name_.c_str()); PrintAmxBacktrace(); } void CrashDetect::HandleInterrupt() { Printf("Server received interrupt signal while executing %s", amx_name_.c_str()); PrintAmxBacktrace(); } void CrashDetect::PrintError(const AMXError &error) const { Printf("Run time error %d: \"%s\"", error.code(), error.GetString()); switch (error.code()) { case AMX_ERR_BOUNDS: { const cell *ip = reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip()); cell opcode = *ip; if (opcode == kOpBounds) { cell bound = *(ip + 1); cell index = amx_.GetPri(); if (index < 0) { Printf(" Accessing element at negative index %d", index); } else { Printf(" Accessing element at index %d past array upper bound %d", index, bound); } } break; } case AMX_ERR_NOTFOUND: { const AMX_FUNCSTUBNT *natives = amx_.GetNatives(); int num_natives = amx_.GetNumNatives(); for (int i = 0; i < num_natives; ++i) { if (natives[i].address == 0) { Printf(" %s", amx_.GetName(natives[i].nameofs)); } } break; } case AMX_ERR_STACKERR: Printf(" Stack pointer (STK) is 0x%X, heap pointer (HEA) is 0x%X", amx_.GetStk(), amx_.GetHea()); break; case AMX_ERR_STACKLOW: Printf(" Stack pointer (STK) is 0x%X, stack top (STP) is 0x%X", amx_.GetStk(), amx_.GetStp()); break; case AMX_ERR_HEAPLOW: Printf(" Heap pointer (HEA) is 0x%X, heap bottom (HLW) is 0x%X", amx_.GetHea(), amx_.GetHlw()); break; case AMX_ERR_INVINSTR: { cell opcode = *(reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip())); Printf(" Unknown opcode 0x%x at address 0x%08X", opcode , amx_.GetCip()); break; } case AMX_ERR_NATIVE: { const cell *ip = reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip()); cell opcode = *(ip - 2); if (opcode == kOpSysreqC) { cell index = *(ip - 1); Printf(" %s", amx_.GetNativeName(index)); } break; } } }<|endoftext|>
<commit_before>#include "AllocStuff.hpp" #include "core/src/global_debug.hpp" #include <stdlib.h> void* allocs::pfnAllocation( void* pUserData, size_t size, // bytes size_t alignment, VkSystemAllocationScope /*allocationScope*/) { allocs* info = reinterpret_cast<allocs*>(pUserData); info->normalUse.fetch_add(size, std::memory_order_relaxed); #if defined(PLATFORM_WINDOWS) return _aligned_malloc(size, alignment); #else return aligned_alloc(size, alignment); #endif }; void* allocs::pfnReallocation( void* /*pUserData*/, void* pOriginal, size_t size, #if defined(PLATFORM_WINDOWS) size_t alignment, VkSystemAllocationScope /*allocationScope*/) { return _aligned_realloc(pOriginal, size, alignment); #else size_t /*alignment*/, VkSystemAllocationScope /*allocationScope*/) { return realloc(pOriginal, size); #endif }; void allocs::pfnFree( void* /*pUserData*/, void* pMemory) { #if defined(PLATFORM_WINDOWS) _aligned_free(pMemory); #else free(pMemory); #endif }; void allocs::pfnInternalAllocation( void* pUserData, size_t size, VkInternalAllocationType /*allocationType*/, VkSystemAllocationScope /*allocationScope*/) { allocs* info = reinterpret_cast<allocs*>(pUserData); auto tmp = info->internalUse.fetch_add(size, std::memory_order_relaxed); F_LOG("internal memory used: %u bytes", tmp); }; void allocs::pfnInternalFree( void* pUserData, size_t size, VkInternalAllocationType /*allocationType*/, VkSystemAllocationScope /*allocationScope*/) { allocs* info = reinterpret_cast<allocs*>(pUserData); auto tmp = info->internalUse.fetch_sub(size, std::memory_order_relaxed); F_LOG("internal memory used: %u bytes", tmp); }; <commit_msg>made aligned allocators for linux<commit_after>#include "AllocStuff.hpp" #include "core/src/global_debug.hpp" #include <stdlib.h> #include <stdint.h> #include <cstring> constexpr uint32_t sizeBytes = sizeof(uint32_t) + sizeof(uint32_t); size_t calcOffset(size_t alignment) { return (sizeBytes/alignment) * alignment + alignment; } // alignment information is closest to ptr // size is after that. void getPtrInfo(void* ptr, uint32_t& size, uint32_t& alignment) { uint32_t* porig = reinterpret_cast<uint32_t*>(ptr); uint32_t* porigSize = reinterpret_cast<uint32_t*>(porig-1); alignment = *(porig-1); size = *(porigSize-1); } // stores size and alignment info close to orig pointer // used to calculate original address void* insertSizeAndReturn(void* ptr, uint32_t size, uint32_t alignment, uint32_t offset) { uint8_t* retPtr = reinterpret_cast<uint8_t*>(ptr)+offset; uint32_t* porig = reinterpret_cast<uint32_t*>(retPtr)-1; *(porig) = alignment; uint32_t* porigSize = porig -1; *(porigSize) = size; return reinterpret_cast<void*>(retPtr); } bool isAligned(void* ptr, size_t alignment) { uintptr_t p = reinterpret_cast<uintptr_t>(ptr); return (p % static_cast<uintptr_t>(alignment)) == 0; } void* allocs::pfnAllocation( void* pUserData, size_t size, // bytes size_t alignment, VkSystemAllocationScope /*allocationScope*/) { allocs* info = reinterpret_cast<allocs*>(pUserData); #if defined(PLATFORM_WINDOWS) info->normalUse.fetch_add(size, std::memory_order_relaxed); return _aligned_malloc(size, alignment); #else size_t offset = calcOffset(alignment); info->normalUse.fetch_add(size+offset, std::memory_order_relaxed); auto ptr = aligned_alloc(alignment, size+offset); return insertSizeAndReturn(ptr, static_cast<uint32_t>(size), static_cast<uint8_t>(alignment), offset); #endif }; void* allocs::pfnReallocation( void* pUserData, void* pOriginal, size_t size, size_t alignment, VkSystemAllocationScope /*allocationScope*/) { allocs* info = reinterpret_cast<allocs*>(pUserData); #if defined(PLATFORM_WINDOWS) info->normalUse.fetch_add(size, std::memory_order_relaxed); return _aligned_realloc(pOriginal, size, alignment); #else uint32_t sizeOld = 0; uint32_t alignOld = 0; getPtrInfo(pOriginal, sizeOld, alignOld); size_t offset_last = calcOffset(alignOld); size_t offset = calcOffset(alignment); void* origPtr = reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(pOriginal)-offset_last); void* ptr = nullptr; ptr = realloc(origPtr, size + offset); if (!isAligned(ptr, alignment)) { auto aligPtr = aligned_alloc(alignment, size+offset); auto realPtr = insertSizeAndReturn(aligPtr, size, alignment, offset); memcpy(realPtr, ptr, sizeOld); free(ptr); ptr = realPtr; } else { ptr = insertSizeAndReturn(ptr, size, alignment, offset); } info->normalUse.fetch_add(static_cast<int>(size+offset)-static_cast<int>(sizeOld+offset_last), std::memory_order_relaxed); return ptr; #endif }; void allocs::pfnFree( void* pUserData, void* pMemory) { allocs* info = reinterpret_cast<allocs*>(pUserData); #if defined(PLATFORM_WINDOWS) info->normalUse.fetch_sub(1, std::memory_order_relaxed); _aligned_free(pMemory); #else uint32_t sizeOld = 0; uint32_t alignOld = 0; getPtrInfo(pMemory, sizeOld, alignOld); uint32_t offset_last = calcOffset(alignOld); info->normalUse.fetch_sub(sizeOld+offset_last, std::memory_order_relaxed); void* origPtr = reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(pMemory)-offset_last); free(origPtr); #endif }; void allocs::pfnInternalAllocation( void* pUserData, size_t size, VkInternalAllocationType /*allocationType*/, VkSystemAllocationScope /*allocationScope*/) { allocs* info = reinterpret_cast<allocs*>(pUserData); auto tmp = info->internalUse.fetch_add(size, std::memory_order_relaxed); F_LOG("internal memory used: %u bytes", tmp); }; void allocs::pfnInternalFree( void* pUserData, size_t size, VkInternalAllocationType /*allocationType*/, VkSystemAllocationScope /*allocationScope*/) { allocs* info = reinterpret_cast<allocs*>(pUserData); auto tmp = info->internalUse.fetch_sub(size, std::memory_order_relaxed); F_LOG("internal memory used: %u bytes", tmp); }; <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // 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 "google/cloud/pubsub/internal/publisher_stub.h" #include "google/cloud/grpc_error_delegate.h" namespace google { namespace cloud { namespace pubsub_internal { inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS { class DefaultPublisherStub : public PublisherStub { public: explicit DefaultPublisherStub( std::unique_ptr<google::pubsub::v1::Publisher::StubInterface> grpc_stub) : grpc_stub_(std::move(grpc_stub)) {} ~DefaultPublisherStub() override = default; StatusOr<google::pubsub::v1::Topic> CreateTopic( grpc::ClientContext& context, google::pubsub::v1::Topic const& request) override { google::pubsub::v1::Topic response; auto status = grpc_stub_->CreateTopic(&context, request, &response); if (!status.ok()) { return MakeStatusFromRpcError(status); } return response; } StatusOr<google::pubsub::v1::ListTopicsResponse> ListTopics( grpc::ClientContext& context, google::pubsub::v1::ListTopicsRequest const& request) override { google::pubsub::v1::ListTopicsResponse response; auto status = grpc_stub_->ListTopics(&context, request, &response); if (!status.ok()) { return MakeStatusFromRpcError(status); } return response; } Status DeleteTopic( grpc::ClientContext& context, google::pubsub::v1::DeleteTopicRequest const& request) override { google::protobuf::Empty response; auto status = grpc_stub_->DeleteTopic(&context, request, &response); if (!status.ok()) { return MakeStatusFromRpcError(status); } return {}; } private: std::unique_ptr<google::pubsub::v1::Publisher::StubInterface> grpc_stub_; }; std::shared_ptr<PublisherStub> CreateDefaultPublisherStub( pubsub::ConnectionOptions const& options, int channel_id) { auto channel_arguments = options.CreateChannelArguments(); // Newer versions of gRPC include a macro (`GRPC_ARG_CHANNEL_ID`) but use // its value here to allow compiling against older versions. channel_arguments.SetInt("grpc.channel_id", channel_id); auto channel = grpc::CreateCustomChannel( options.endpoint(), options.credentials(), channel_arguments); auto grpc_stub = google::pubsub::v1::Publisher::NewStub(grpc::CreateCustomChannel( options.endpoint(), options.credentials(), channel_arguments)); return std::make_shared<DefaultPublisherStub>(std::move(grpc_stub)); } } // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS } // namespace pubsub_internal } // namespace cloud } // namespace google <commit_msg>cleanup: do not use ADL for MakeStatusFromRpcError (googleapis/google-cloud-cpp-pubsub#85)<commit_after>// Copyright 2020 Google LLC // // 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 "google/cloud/pubsub/internal/publisher_stub.h" #include "google/cloud/grpc_error_delegate.h" namespace google { namespace cloud { namespace pubsub_internal { inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS { class DefaultPublisherStub : public PublisherStub { public: explicit DefaultPublisherStub( std::unique_ptr<google::pubsub::v1::Publisher::StubInterface> grpc_stub) : grpc_stub_(std::move(grpc_stub)) {} ~DefaultPublisherStub() override = default; StatusOr<google::pubsub::v1::Topic> CreateTopic( grpc::ClientContext& context, google::pubsub::v1::Topic const& request) override { google::pubsub::v1::Topic response; auto status = grpc_stub_->CreateTopic(&context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::pubsub::v1::ListTopicsResponse> ListTopics( grpc::ClientContext& context, google::pubsub::v1::ListTopicsRequest const& request) override { google::pubsub::v1::ListTopicsResponse response; auto status = grpc_stub_->ListTopics(&context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } Status DeleteTopic( grpc::ClientContext& context, google::pubsub::v1::DeleteTopicRequest const& request) override { google::protobuf::Empty response; auto status = grpc_stub_->DeleteTopic(&context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return {}; } private: std::unique_ptr<google::pubsub::v1::Publisher::StubInterface> grpc_stub_; }; std::shared_ptr<PublisherStub> CreateDefaultPublisherStub( pubsub::ConnectionOptions const& options, int channel_id) { auto channel_arguments = options.CreateChannelArguments(); // Newer versions of gRPC include a macro (`GRPC_ARG_CHANNEL_ID`) but use // its value here to allow compiling against older versions. channel_arguments.SetInt("grpc.channel_id", channel_id); auto channel = grpc::CreateCustomChannel( options.endpoint(), options.credentials(), channel_arguments); auto grpc_stub = google::pubsub::v1::Publisher::NewStub(grpc::CreateCustomChannel( options.endpoint(), options.credentials(), channel_arguments)); return std::make_shared<DefaultPublisherStub>(std::move(grpc_stub)); } } // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS } // namespace pubsub_internal } // namespace cloud } // namespace google <|endoftext|>
<commit_before>/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Wiring project - http://wiring.org.co Copyright (c) 2004-06 Hernando Barragan Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/ 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 $Id$ */ extern "C" { #include "stdlib.h" } /* * Internal srandom() and random() implmentation, * a simple pseudo-random number generator is the Multiply-with-carry method invented by George Marsaglia. * It is computationally fast and has good (albeit not cryptographically strong) * From: http://en.wikipedia.org/wiki/Random_number_generation#Computational_methods */ static long m_w =123; /* must not be zero */ static long m_z =98765432; /* must not be zero */ static void srandom(long n) { m_w = 123 ^ n; m_z = 98765432 ^ n-1; } static unsigned long random() { m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); return (m_z << 16) + m_w; /* 32-bit result */ } void randomSeed(unsigned int seed) { if (seed != 0) { srandom(seed); } } long random(long howbig) { if (howbig == 0) { return 0; } return random() % howbig; } long random(long howsmall, long howbig) { if (howsmall >= howbig) { return howsmall; } long diff = howbig - howsmall; return random(diff) + howsmall; } long map(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } unsigned int makeWord(unsigned int w) { return w; } unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; } <commit_msg>Make sure seed cannot be zero<commit_after>/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Wiring project - http://wiring.org.co Copyright (c) 2004-06 Hernando Barragan Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/ 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 $Id$ */ extern "C" { #include "stdlib.h" } /* * Internal srandom() and random() implmentation, * a simple pseudo-random number generator is the Multiply-with-carry method invented by George Marsaglia. * It is computationally fast and has good (albeit not cryptographically strong) * From: http://en.wikipedia.org/wiki/Random_number_generation#Computational_methods */ static long m_w =123; /* must not be zero */ static long m_z =98765432; /* must not be zero */ static void srandom(long n) { m_w = 123 ^ n; m_z = 98765432 ^ n-1; if ( m_w == 0 ) m_w = 123; if ( m_z == 0 ) m_z = 98765432; } static unsigned long random() { m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); return (m_z << 16) + m_w; /* 32-bit result */ } void randomSeed(unsigned int seed) { if (seed != 0) { srandom(seed); } } long random(long howbig) { if (howbig == 0) { return 0; } return random() % howbig; } long random(long howsmall, long howbig) { if (howsmall >= howbig) { return howsmall; } long diff = howbig - howsmall; return random(diff) + howsmall; } long map(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } unsigned int makeWord(unsigned int w) { return w; } unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; } <|endoftext|>
<commit_before>#include <string.h> #include <math.h> #include "FireLog.h" #include "FireSight.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "jansson.h" #include "jo_util.hpp" #include "MatUtil.hpp" using namespace cv; using namespace std; using namespace firesight; bool Pipeline::apply_calcOffset(json_t *pStage, json_t *pStageModel, Model &model) { validateImage(model.image); string tmpltPath = jo_string(pStage, "template", "", model.argMap); Scalar offsetColor(32,32,255); offsetColor = jo_Scalar(pStage, "offsetColor", offsetColor, model.argMap); int xtol = jo_int(pStage, "xtol", 32, model.argMap); int ytol = jo_int(pStage, "ytol", 32, model.argMap); vector<int> channels = jo_vectori(pStage, "channels", vector<int>(), model.argMap); assert(model.image.cols > 2*xtol); assert(model.image.rows > 2*ytol); Rect roi= jo_Rect(pStage, "roi", Rect(xtol, ytol, model.image.cols-2*xtol, model.image.rows-2*ytol), model.argMap); if (roi.x == -1) { roi.x = (model.image.cols - roi.width)/2; } if (roi.y == -1) { roi.y = (model.image.rows - roi.height)/2; } Rect roiScan = Rect(roi.x-xtol, roi.y-ytol, roi.width+2*xtol, roi.height+2*ytol); float minval = jo_float(pStage, "minval", 0.7f, model.argMap); float corr = jo_float(pStage, "corr", 0.99f); string outputStr = jo_string(pStage, "output", "current", model.argMap); const char *errMsg = NULL; int flags = INTER_LINEAR; int method = CV_TM_CCOEFF_NORMED; Mat tmplt; int borderMode = BORDER_REPLICATE; if (roi.x < 0 || roi.y < 0 || model.image.cols < roi.x+roi.width || model.image.rows < roi.y+roi.height) { errMsg = "ROI must be within image"; } if (tmpltPath.empty()) { errMsg = "Expected template path for imread"; } else { if (model.image.channels() == 1) { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_GRAYSCALE); } else { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_COLOR); } if (tmplt.data) { LOGTRACE2("apply_calcOffset(%s) %s", tmpltPath.c_str(), matInfo(tmplt).c_str()); if (model.image.rows<tmplt.rows || model.image.cols<tmplt.cols) { errMsg = "Expected template smaller than image to match"; } } else { errMsg = "imread failed"; } } if (!errMsg) { if (model.image.channels() > 3) { errMsg = "Expected at most 3 channels for pipeline image"; } else if (tmplt.channels() != model.image.channels()) { errMsg = "Template and pipeline image must have same number of channels"; } else { for (int iChannel = 0; iChannel < channels.size(); iChannel++) { if (channels[iChannel] < 0 || model.image.channels() <= channels[iChannel]) { errMsg = "Referenced channel is not in image"; } } } } if (!errMsg) { Mat result; Mat imagePlanes[] = { Mat(), Mat(), Mat() }; Mat tmpltPlanes[] = { Mat(), Mat(), Mat() }; if (channels.size() == 0) { channels.push_back(0); if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { cvtColor(model.image, imagePlanes[0], CV_BGR2GRAY); cvtColor(tmplt, tmpltPlanes[0], CV_BGR2GRAY); } } else if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { split(model.image, imagePlanes); split(tmplt, tmpltPlanes); } json_t *pRects = json_array(); json_t *pChannels = json_object(); json_object_set(pStageModel, "channels", pChannels); json_object_set(pStageModel, "rects", pRects); json_t *pRect = json_object(); json_array_append(pRects, pRect); json_object_set(pRect, "x", json_integer(roiScan.x+roiScan.width/2)); json_object_set(pRect, "y", json_integer(roiScan.y+roiScan.height/2)); json_object_set(pRect, "width", json_integer(roiScan.width)); json_object_set(pRect, "height", json_integer(roiScan.height)); json_object_set(pRect, "angle", json_integer(0)); json_t *pOffsetColor = NULL; for (int iChannel=0; iChannel<channels.size(); iChannel++) { int channel = channels[iChannel]; Mat imageSource(imagePlanes[channel], roiScan); Mat tmpltSource(tmpltPlanes[channel], roi); matchTemplate(imageSource, tmpltSource, result, method); LOGTRACE4("apply_calcOffset() matchTemplate(%s,%s,%s,CV_TM_CCOEFF_NORMED) channel:%d", matInfo(imageSource).c_str(), matInfo(tmpltSource).c_str(), matInfo(result).c_str(), channel); vector<Point> matches; float maxVal = *max_element(result.begin<float>(),result.end<float>()); float rangeMin = corr * maxVal; float rangeMax = maxVal; matMaxima(result, matches, rangeMin, rangeMax); if (logLevel >= FIRELOG_TRACE) { for (size_t iMatch=0; iMatch<matches.size(); iMatch++) { int mx = matches[iMatch].x; int my = matches[iMatch].y; float val = result.at<float>(my,mx); if (val < minval) { LOGTRACE4("apply_calcOffset() ignoring (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } else { LOGTRACE4("apply_calcOffset() matched (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } } } json_t *pMatches = json_object(); char key[10]; snprintf(key, sizeof(key), "%d", channel); json_object_set(pChannels, key, pMatches); if (matches.size() == 1) { int mx = matches[0].x; int my = matches[0].y; float val = result.at<float>(my,mx); if (minval <= val) { int dx = xtol - mx; int dy = ytol - my; json_object_set(pMatches, "dx", json_integer(dx)); json_object_set(pMatches, "dy", json_integer(dy)); json_object_set(pMatches, "match", json_float(val)); if (dx || dy) { json_t *pOffsetRect = json_object(); json_array_append(pRects, pOffsetRect); json_object_set(pOffsetRect, "x", json_integer(roi.x+roi.width/2-dx)); json_object_set(pOffsetRect, "y", json_integer(roi.y+roi.height/2-dy)); json_object_set(pOffsetRect, "width", json_integer(roi.width)); json_object_set(pOffsetRect, "height", json_integer(roi.height)); json_object_set(pOffsetRect, "angle", json_integer(0)); if (!pOffsetColor) { pOffsetColor = json_array(); json_array_append(pOffsetColor, json_integer(offsetColor[0])); json_array_append(pOffsetColor, json_integer(offsetColor[1])); json_array_append(pOffsetColor, json_integer(offsetColor[2])); } } } } } json_t *pRoiRect = json_object(); json_array_append(pRects, pRoiRect); json_object_set(pRoiRect, "x", json_integer(roi.x+roi.width/2)); json_object_set(pRoiRect, "y", json_integer(roi.y+roi.height/2)); json_object_set(pRoiRect, "width", json_integer(roi.width)); json_object_set(pRoiRect, "height", json_integer(roi.height)); json_object_set(pRoiRect, "angle", json_integer(0)); if (pOffsetColor) { json_object_set(pRoiRect, "color", pOffsetColor); } normalize(result, result, 0, 255, NORM_MINMAX); result.convertTo(result, CV_8U); Mat corrInset = model.image.colRange(0,result.cols).rowRange(0,result.rows); switch (model.image.channels()) { case 3: cvtColor(result, corrInset, CV_GRAY2BGR); break; case 4: cvtColor(result, corrInset, CV_GRAY2BGRA); break; default: result.copyTo(corrInset); break; } } return stageOK("apply_calcOffset(%s) %s", errMsg, pStage, pStageModel); } <commit_msg>ROI error message<commit_after>#include <string.h> #include <math.h> #include "FireLog.h" #include "FireSight.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "jansson.h" #include "jo_util.hpp" #include "MatUtil.hpp" using namespace cv; using namespace std; using namespace firesight; bool Pipeline::apply_calcOffset(json_t *pStage, json_t *pStageModel, Model &model) { validateImage(model.image); string tmpltPath = jo_string(pStage, "template", "", model.argMap); Scalar offsetColor(32,32,255); offsetColor = jo_Scalar(pStage, "offsetColor", offsetColor, model.argMap); int xtol = jo_int(pStage, "xtol", 32, model.argMap); int ytol = jo_int(pStage, "ytol", 32, model.argMap); vector<int> channels = jo_vectori(pStage, "channels", vector<int>(), model.argMap); assert(model.image.cols > 2*xtol); assert(model.image.rows > 2*ytol); Rect roi= jo_Rect(pStage, "roi", Rect(xtol, ytol, model.image.cols-2*xtol, model.image.rows-2*ytol), model.argMap); if (roi.x == -1) { roi.x = (model.image.cols - roi.width)/2; } if (roi.y == -1) { roi.y = (model.image.rows - roi.height)/2; } Rect roiScan = Rect(roi.x-xtol, roi.y-ytol, roi.width+2*xtol, roi.height+2*ytol); float minval = jo_float(pStage, "minval", 0.7f, model.argMap); float corr = jo_float(pStage, "corr", 0.99f); string outputStr = jo_string(pStage, "output", "current", model.argMap); const char *errMsg = NULL; int flags = INTER_LINEAR; int method = CV_TM_CCOEFF_NORMED; Mat tmplt; int borderMode = BORDER_REPLICATE; if (roiScan.x < 0 || roiScan.y < 0 || model.image.cols < roiScan.x+roiScan.width || model.image.rows < roiScan.y+roiScan.height) { errMsg = "ROI with and surrounding xtol,ytol region must be within image"; } if (tmpltPath.empty()) { errMsg = "Expected template path for imread"; } else { if (model.image.channels() == 1) { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_GRAYSCALE); } else { tmplt = imread(tmpltPath.c_str(), CV_LOAD_IMAGE_COLOR); } if (tmplt.data) { LOGTRACE2("apply_calcOffset(%s) %s", tmpltPath.c_str(), matInfo(tmplt).c_str()); if (model.image.rows<tmplt.rows || model.image.cols<tmplt.cols) { errMsg = "Expected template smaller than image to match"; } } else { errMsg = "imread failed"; } } if (!errMsg) { if (model.image.channels() > 3) { errMsg = "Expected at most 3 channels for pipeline image"; } else if (tmplt.channels() != model.image.channels()) { errMsg = "Template and pipeline image must have same number of channels"; } else { for (int iChannel = 0; iChannel < channels.size(); iChannel++) { if (channels[iChannel] < 0 || model.image.channels() <= channels[iChannel]) { errMsg = "Referenced channel is not in image"; } } } } if (!errMsg) { Mat result; Mat imagePlanes[] = { Mat(), Mat(), Mat() }; Mat tmpltPlanes[] = { Mat(), Mat(), Mat() }; if (channels.size() == 0) { channels.push_back(0); if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { cvtColor(model.image, imagePlanes[0], CV_BGR2GRAY); cvtColor(tmplt, tmpltPlanes[0], CV_BGR2GRAY); } } else if (model.image.channels() == 1) { imagePlanes[0] = model.image; tmpltPlanes[0] = tmplt; } else { split(model.image, imagePlanes); split(tmplt, tmpltPlanes); } json_t *pRects = json_array(); json_t *pChannels = json_object(); json_object_set(pStageModel, "channels", pChannels); json_object_set(pStageModel, "rects", pRects); json_t *pRect = json_object(); json_array_append(pRects, pRect); json_object_set(pRect, "x", json_integer(roiScan.x+roiScan.width/2)); json_object_set(pRect, "y", json_integer(roiScan.y+roiScan.height/2)); json_object_set(pRect, "width", json_integer(roiScan.width)); json_object_set(pRect, "height", json_integer(roiScan.height)); json_object_set(pRect, "angle", json_integer(0)); json_t *pOffsetColor = NULL; for (int iChannel=0; iChannel<channels.size(); iChannel++) { int channel = channels[iChannel]; Mat imageSource(imagePlanes[channel], roiScan); Mat tmpltSource(tmpltPlanes[channel], roi); matchTemplate(imageSource, tmpltSource, result, method); LOGTRACE4("apply_calcOffset() matchTemplate(%s,%s,%s,CV_TM_CCOEFF_NORMED) channel:%d", matInfo(imageSource).c_str(), matInfo(tmpltSource).c_str(), matInfo(result).c_str(), channel); vector<Point> matches; float maxVal = *max_element(result.begin<float>(),result.end<float>()); float rangeMin = corr * maxVal; float rangeMax = maxVal; matMaxima(result, matches, rangeMin, rangeMax); if (logLevel >= FIRELOG_TRACE) { for (size_t iMatch=0; iMatch<matches.size(); iMatch++) { int mx = matches[iMatch].x; int my = matches[iMatch].y; float val = result.at<float>(my,mx); if (val < minval) { LOGTRACE4("apply_calcOffset() ignoring (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } else { LOGTRACE4("apply_calcOffset() matched (%d,%d) val:%g corr:%g", mx, my, val, val/maxVal); } } } json_t *pMatches = json_object(); char key[10]; snprintf(key, sizeof(key), "%d", channel); json_object_set(pChannels, key, pMatches); if (matches.size() == 1) { int mx = matches[0].x; int my = matches[0].y; float val = result.at<float>(my,mx); if (minval <= val) { int dx = xtol - mx; int dy = ytol - my; json_object_set(pMatches, "dx", json_integer(dx)); json_object_set(pMatches, "dy", json_integer(dy)); json_object_set(pMatches, "match", json_float(val)); if (dx || dy) { json_t *pOffsetRect = json_object(); json_array_append(pRects, pOffsetRect); json_object_set(pOffsetRect, "x", json_integer(roi.x+roi.width/2-dx)); json_object_set(pOffsetRect, "y", json_integer(roi.y+roi.height/2-dy)); json_object_set(pOffsetRect, "width", json_integer(roi.width)); json_object_set(pOffsetRect, "height", json_integer(roi.height)); json_object_set(pOffsetRect, "angle", json_integer(0)); if (!pOffsetColor) { pOffsetColor = json_array(); json_array_append(pOffsetColor, json_integer(offsetColor[0])); json_array_append(pOffsetColor, json_integer(offsetColor[1])); json_array_append(pOffsetColor, json_integer(offsetColor[2])); } } } } } json_t *pRoiRect = json_object(); json_array_append(pRects, pRoiRect); json_object_set(pRoiRect, "x", json_integer(roi.x+roi.width/2)); json_object_set(pRoiRect, "y", json_integer(roi.y+roi.height/2)); json_object_set(pRoiRect, "width", json_integer(roi.width)); json_object_set(pRoiRect, "height", json_integer(roi.height)); json_object_set(pRoiRect, "angle", json_integer(0)); if (pOffsetColor) { json_object_set(pRoiRect, "color", pOffsetColor); } normalize(result, result, 0, 255, NORM_MINMAX); result.convertTo(result, CV_8U); Mat corrInset = model.image.colRange(0,result.cols).rowRange(0,result.rows); switch (model.image.channels()) { case 3: cvtColor(result, corrInset, CV_GRAY2BGR); break; case 4: cvtColor(result, corrInset, CV_GRAY2BGRA); break; default: result.copyTo(corrInset); break; } } return stageOK("apply_calcOffset(%s) %s", errMsg, pStage, pStageModel); } <|endoftext|>
<commit_before>/* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: Frank Dellaert, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file LocalizationExample.cpp * @brief Simple robot localization example, with three "GPS-like" measurements * @author Frank Dellaert */ /** * A simple 2D pose slam example with "GPS" measurements * - The robot moves forward 2 meter each iteration * - The robot initially faces along the X axis (horizontal, to the right in 2D) * - We have full odometry between pose * - We have "GPS-like" measurements implemented with a custom factor */ // We will use Pose2 variables (x, y, theta) to represent the robot positions #include <gtsam/geometry/Pose2.h> #include <gtsam/geometry/Moses3.h> // We will use simple integer Keys to refer to the robot poses. #include <gtsam/inference/Key.h> // As in OdometryExample.cpp, we use a BetweenFactor to model odometry measurements. #include <gtsam/slam/BetweenFactor.h> #include <gtsam/slam/PriorFactor.h> // We add all facors to a Nonlinear Factor Graph, as our factors are nonlinear. #include <gtsam/nonlinear/NonlinearFactorGraph.h> // The nonlinear solvers within GTSAM are iterative solvers, meaning they linearize the // nonlinear functions around an initial linearization point, then solve the linear system // to update the linearization point. This happens repeatedly until the solver converges // to a consistent set of variable values. This requires us to specify an initial guess // for each variable, held in a Values container. #include <gtsam/nonlinear/Values.h> // Finally, once all of the factors have been added to our factor graph, we will want to // solve/optimize to graph to find the best (Maximum A Posteriori) set of variable values. // GTSAM includes several nonlinear optimizers to perform this step. Here we will use the // standard Levenberg-Marquardt solver #include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h> // Once the optimized values have been calculated, we can also calculate the marginal covariance // of desired variables #include <gtsam/nonlinear/Marginals.h> using namespace std; using namespace Sophus; using namespace gtsam; // Before we begin the example, we must create a custom unary factor to implement a // "GPS-like" functionality. Because standard GPS measurements provide information // only on the position, and not on the orientation, we cannot use a simple prior to // properly model this measurement. // // The factor will be a unary factor, affect only a single system variable. It will // also use a standard Gaussian noise model. Hence, we will derive our new factor from // the NoiseModelFactor1. #include <gtsam/nonlinear/NonlinearFactor.h> #define PI 3.14159265359f namespace gtsam{ class UnaryFactor: public NoiseModelFactor1<Moses3> { // The factor will hold a measurement consisting of an (X,Y) location // We could this with a Point2 but here we just use two doubles Point3 nT_; public: /// shorthand for a smart pointer to a factor typedef boost::shared_ptr<UnaryFactor> shared_ptr; // The constructor requires the variable key, the (X, Y) measurement value, and the noise model UnaryFactor(Key j, const Point3& gpsIn, const SharedNoiseModel& model): NoiseModelFactor1<Moses3>(model, j), nT_(gpsIn) {} virtual ~UnaryFactor() {} // Using the NoiseModelFactor1 base class there are two functions that must be overridden. // The first is the 'evaluateError' function. This function implements the desired measurement // function, returning a vector of errors when evaluated at the provided variable value. It // must also calculate the Jacobians for this measurement function, if requested. Vector evaluateError(const Moses3& q, boost::optional<Matrix&> H = boost::none) const { // The measurement function for a GPS-like measurement is simple: // error_x = pose.x - measurement.x // error_y = pose.y - measurement.y // Consequently, the Jacobians are: // [ derror_x/dx derror_x/dy derror_x/dtheta ] = [1 0 0] // [ derror_y/dx derror_y/dy derror_y/dtheta ] = [0 1 0] //if (H) (*H) = (Matrix(2,3) << 1.0,0.0,0.0, 0.0,1.0,0.0); //this is crap for moses3 //return (Vector(2) << q.x() - m_.x(), q.y() - m_.y()); //this is crap for moses3 if (H) { H->resize(3, 7); H->block < 3, 3 > (0, 0) << q.Sim3::rotation_matrix(); //deriv. trans NOT TESTED H->block < 3, 3 > (0, 3) << zeros(3, 3); //deriv. rot NOT TESTED H->block < 3, 1 > (0, 4) << zeros(3, 1); //or ones?? //deriv scale NOT TESTED } Vector3 res =nT_.localCoordinates(Point3(q.Sim3::translation())); cout << "****** "<<res.transpose() <<" "; cout << nT_.vector().transpose() << " "<< q.Sim3::translation().transpose() <<" ]]" << endl; return res; } // The second is a 'clone' function that allows the factor to be copied. Under most // circumstances, the following code that employs the default copy constructor should // work fine. virtual gtsam::NonlinearFactor::shared_ptr clone() const { return boost::static_pointer_cast<gtsam::NonlinearFactor>( gtsam::NonlinearFactor::shared_ptr(new UnaryFactor(*this))); } // Additionally, we encourage you the use of unit testing your custom factors, // (as all GTSAM factors are), in which you would need an equals and print, to satisfy the // GTSAM_CONCEPT_TESTABLE_INST(T) defined in Testable.h, but these are not needed below. }; // UnaryFactor } int main(int argc, char** argv) { // 1. Create a factor graph container and add factors to it NonlinearFactorGraph graph; // 2a. Add odometry factors // For simplicity, we will use the same noise model for each odometry factor noiseModel::Diagonal::shared_ptr odometryNoise = noiseModel::Diagonal::Sigmas((Vector(7) << 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1)); // Create odometry (Between) factors between consecutive poses //cout << Rot3::rodriguez(0.0, 0.0, PI/2)<<endl; //Intermediate constraints Rot3 R0 = Rot3(Rot3::rodriguez(0.0, 0.0, 0.0)); //Initial prior to origin Point3 Pp0(0.0, 0.0, 0.0); Rot3 R12 = Rot3(Rot3::rodriguez(0.0, 0.0, PI/2)); Point3 Pp12(1.0, 0.0, 0.0); Rot3 R23 = Rot3(Rot3::rodriguez(0.0, 0.0, -PI/2)); Point3 Pp23(2.0, 0.0, 0.0); Rot3 R34 = Rot3(Rot3::rodriguez(0.0, 0.0, 0.0)); Point3 Pp34(-1.0, -4.0, 0.0); float s0,s12,s23,s34; s0=1; //Initial Prior to origin. s12=2.0; s23=0.5; s34=1.0; //Unary priors Point3 Up1(0, 0, 0.0); Point3 Up2(1, 0, 0.0); Point3 Up3(1, 4, 0.0); Point3 Up4(0, 0, 0.0); //Initial Estimate values Point3 Pi1(0.0, 0.0, 0.0); Point3 Pi2(1.0, 1.0, 1.0); Point3 Pi3(1.0, 0.0, 0.0); Point3 Pi4(1.0, 2.0, 3.0); Rot3 Ri1 = Rot3::rodriguez(0.0, 0.0, PI/2.5); Rot3 Ri2 = Rot3::rodriguez(0.0, 0.0, 0.0); Rot3 Ri3 = Rot3::rodriguez(0.0, 0.0, 0.0); Rot3 Ri4 = Rot3::rodriguez(0.0, PI, 0.0); float si1,si2,si3,si4; si1=1; si2=1; si3=1; si4=1; // Add a prior on the first pose, setting it to the origin // A prior factor consists of a mean and a noise model (covariance matrix) Moses3 priorMean(ScSO3(s0*R0.matrix()),Pp0.vector()); // prior at origin noiseModel::Diagonal::shared_ptr priorNoise = noiseModel::Diagonal::Sigmas((Vector(7) << 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01)); graph.add(PriorFactor<Moses3>(1, priorMean, priorNoise)); graph.add(BetweenFactor<Moses3>(1, 2, Moses3(ScSO3(s12*R12.matrix()),Pp12.vector()), odometryNoise)); graph.add(BetweenFactor<Moses3>(2, 3, Moses3(ScSO3(s23*R23.matrix()),Pp23.vector()), odometryNoise)); graph.add(BetweenFactor<Moses3>(3, 4, Moses3(ScSO3(s34*R34.matrix()),Pp34.vector()), odometryNoise)); // 2b. Add "GPS-like" measurements // We will use our custom UnaryFactor for this. noiseModel::Diagonal::shared_ptr unaryNoise = noiseModel::Diagonal::Sigmas((Vector(3) << 0.01, 0.01, 0.01)); // 10cm std on x,y graph.add(boost::make_shared<UnaryFactor>(2, Up2, unaryNoise)); graph.add(boost::make_shared<UnaryFactor>(3, Up3, unaryNoise)); graph.add(boost::make_shared<UnaryFactor>(4, Up4, unaryNoise)); //graph.add(BetweenFactor<Pose2>(1, 2, Pose2(2.0, 0.0, 0.0), odometryNoise)); //graph.add(BetweenFactor<Pose2>(2, 3, Pose2(2.0, 0.0, 0.0), odometryNoise)); // 2b. Add "GPS-like" measurements // We will use our custom UnaryFactor for this. //noiseModel::Diagonal::shared_ptr unaryNoise = noiseModel::Diagonal::Sigmas((Vector(2) << 0.1, 0.1)); // 10cm std on x,y //graph.add(boost::make_shared<UnaryFactor>(1, 0.0, 0.0, unaryNoise)); //graph.add(boost::make_shared<UnaryFactor>(2, 2.0, 0.0, unaryNoise)); //graph.add(boost::make_shared<UnaryFactor>(3, 4.0, 0.0, unaryNoise)); graph.print("\nFactor Graph:\n"); // print // 3. Create the data structure to hold the initialEstimate estimate to the solution // For illustrative purposes, these have been deliberately set to incorrect values Values initialEstimate; initialEstimate.insert(1, Moses3(ScSO3(si1*Ri1.matrix()),Pi1.vector())); initialEstimate.insert(2, Moses3(ScSO3(si2*Ri2.matrix()),Pi2.vector())); initialEstimate.insert(3, Moses3(ScSO3(si3*Ri3.matrix()),Pi3.vector())); initialEstimate.insert(4, Moses3(ScSO3(si4*Ri4.matrix()),Pi4.vector())); //initialEstimate.insert(1, Pose2(0.5, 0.0, 0.2)); //initialEstimate.insert(2, Pose2(2.3, 0.1, -0.2)); //initialEstimate.insert(3, Pose2(4.1, 0.1, 0.1)); initialEstimate.print("\nInitial Estimate:\n"); // print // 4. Optimize using Levenberg-Marquardt optimization. The optimizer // accepts an optional set of configuration parameters, controlling // things like convergence criteria, the type of linear system solver // to use, and the amount of information displayed during optimization. // Here we will use the default set of parameters. See the // documentation for the full set of parameters. LevenbergMarquardtOptimizer optimizer(graph, initialEstimate); Values result = optimizer.optimize(); result.print("Final Result:\n"); // 5. Calculate and print marginal covariances for all variables Marginals marginals(graph, result); //cout << "x1 covariance:\n" << marginals.marginalCovariance(1) << endl; //cout << "x2 covariance:\n" << marginals.marginalCovariance(2) << endl; //cout << "x3 covariance:\n" << marginals.marginalCovariance(3) << endl; return 0; } <commit_msg>Testing GPS like constraint to Sim3. 2 Nodes. Rotated in 2D (about z axis). Initially non - consistent set of Sim3 between factors and GPS unary factors in 2D (rotation about z axis) with scale change verified. Incorrect scales from Sim3 are corrected by using GPS factors.<commit_after>/* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: Frank Dellaert, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file LocalizationExample.cpp * @brief Simple robot localization example, with three "GPS-like" measurements * @author Frank Dellaert */ /** * A simple 2D pose slam example with "GPS" measurements * - The robot moves forward 2 meter each iteration * - The robot initially faces along the X axis (horizontal, to the right in 2D) * - We have full odometry between pose * - We have "GPS-like" measurements implemented with a custom factor */ // We will use Pose2 variables (x, y, theta) to represent the robot positions #include <gtsam/geometry/Pose2.h> #include <gtsam/geometry/Moses3.h> // We will use simple integer Keys to refer to the robot poses. #include <gtsam/inference/Key.h> // As in OdometryExample.cpp, we use a BetweenFactor to model odometry measurements. #include <gtsam/slam/BetweenFactor.h> #include <gtsam/slam/PriorFactor.h> // We add all facors to a Nonlinear Factor Graph, as our factors are nonlinear. #include <gtsam/nonlinear/NonlinearFactorGraph.h> // The nonlinear solvers within GTSAM are iterative solvers, meaning they linearize the // nonlinear functions around an initial linearization point, then solve the linear system // to update the linearization point. This happens repeatedly until the solver converges // to a consistent set of variable values. This requires us to specify an initial guess // for each variable, held in a Values container. #include <gtsam/nonlinear/Values.h> // Finally, once all of the factors have been added to our factor graph, we will want to // solve/optimize to graph to find the best (Maximum A Posteriori) set of variable values. // GTSAM includes several nonlinear optimizers to perform this step. Here we will use the // standard Levenberg-Marquardt solver #include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h> // Once the optimized values have been calculated, we can also calculate the marginal covariance // of desired variables #include <gtsam/nonlinear/Marginals.h> using namespace std; using namespace Sophus; using namespace gtsam; // Before we begin the example, we must create a custom unary factor to implement a // "GPS-like" functionality. Because standard GPS measurements provide information // only on the position, and not on the orientation, we cannot use a simple prior to // properly model this measurement. // // The factor will be a unary factor, affect only a single system variable. It will // also use a standard Gaussian noise model. Hence, we will derive our new factor from // the NoiseModelFactor1. #include <gtsam/nonlinear/NonlinearFactor.h> #define PI 3.14159265359f namespace gtsam{ class UnaryFactor: public NoiseModelFactor1<Moses3> { // The factor will hold a measurement consisting of an (X,Y) location // We could this with a Point2 but here we just use two doubles Point3 nT_; public: /// shorthand for a smart pointer to a factor typedef boost::shared_ptr<UnaryFactor> shared_ptr; // The constructor requires the variable key, the (X, Y) measurement value, and the noise model UnaryFactor(Key j, const Point3& gpsIn, const SharedNoiseModel& model): NoiseModelFactor1<Moses3>(model, j), nT_(gpsIn) {} virtual ~UnaryFactor() {} // Using the NoiseModelFactor1 base class there are two functions that must be overridden. // The first is the 'evaluateError' function. This function implements the desired measurement // function, returning a vector of errors when evaluated at the provided variable value. It // must also calculate the Jacobians for this measurement function, if requested. Vector evaluateError(const Moses3& q, boost::optional<Matrix&> H = boost::none) const { // The measurement function for a GPS-like measurement is simple: // error_x = pose.x - measurement.x // error_y = pose.y - measurement.y // Consequently, the Jacobians are: // [ derror_x/dx derror_x/dy derror_x/dtheta ] = [1 0 0] // [ derror_y/dx derror_y/dy derror_y/dtheta ] = [0 1 0] //if (H) (*H) = (Matrix(2,3) << 1.0,0.0,0.0, 0.0,1.0,0.0); //this is crap for moses3 //return (Vector(2) << q.x() - m_.x(), q.y() - m_.y()); //this is crap for moses3 if (H) { H->resize(3, 7); H->block < 3, 3 > (0, 0) << q.Sim3::rotation_matrix(); //deriv. trans NOT TESTED H->block < 3, 3 > (0, 3) << zeros(3, 3); //deriv. rot NOT TESTED H->block < 3, 1 > (0, 4) << zeros(3, 1); //or ones?? //deriv scale NOT TESTED } Vector3 res =nT_.localCoordinates(Point3(q.Sim3::translation())); cout << "****** "<<res.transpose() <<" "; cout << nT_.vector().transpose() << " "<< q.Sim3::translation().transpose() <<" ]]" << endl; return res; } // The second is a 'clone' function that allows the factor to be copied. Under most // circumstances, the following code that employs the default copy constructor should // work fine. virtual gtsam::NonlinearFactor::shared_ptr clone() const { return boost::static_pointer_cast<gtsam::NonlinearFactor>( gtsam::NonlinearFactor::shared_ptr(new UnaryFactor(*this))); } // Additionally, we encourage you the use of unit testing your custom factors, // (as all GTSAM factors are), in which you would need an equals and print, to satisfy the // GTSAM_CONCEPT_TESTABLE_INST(T) defined in Testable.h, but these are not needed below. }; // UnaryFactor } int main(int argc, char** argv) { // 1. Create a factor graph container and add factors to it NonlinearFactorGraph graph; // 2a. Add odometry factors // For simplicity, we will use the same noise model for each odometry factor noiseModel::Diagonal::shared_ptr odometryNoise = noiseModel::Diagonal::Sigmas((Vector(7) << 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1)); // Create odometry (Between) factors between consecutive poses //cout << Rot3::rodriguez(0.0, 0.0, PI/2)<<endl; //Intermediate constraints Rot3 R0 = Rot3(Rot3::rodriguez(0.0, 0.0, 0.0)); //Initial prior to origin Point3 Pp0(0.0, 0.0, 0.0); Rot3 R12 = Rot3(Rot3::rodriguez(0.0, 0.0, PI/2)); Point3 Pp12(1.0, 0.0, 0.0); Rot3 R23 = Rot3(Rot3::rodriguez(0.0, 0.0, -PI/2)); Point3 Pp23(2.0, 0.0, 0.0); Rot3 R34 = Rot3(Rot3::rodriguez(0.0, 0.0, 0.0)); Point3 Pp34(-1.0, -4.0, 0.0); float s0,s12,s23,s34; s0=1; //Initial Prior to origin. s12=2.2; s23=0.55; s34=1.0; //Unary priors Point3 Up1(0, 0, 0.0); Point3 Up2(1, 0, 0.0); Point3 Up3(1, 4, 0.0); Point3 Up4(0, 0, 0.0); //Initial Estimate values Point3 Pi1(0.0, 0.0, 0.0); Point3 Pi2(1.0, 1.0, 1.0); Point3 Pi3(1.0, 0.0, 0.0); Point3 Pi4(1.0, 2.0, 3.0); Rot3 Ri1 = Rot3::rodriguez(0.0, 0.0, PI/2.5); Rot3 Ri2 = Rot3::rodriguez(0.0, 0.0, 0.0); Rot3 Ri3 = Rot3::rodriguez(0.0, 0.0, 0.0); Rot3 Ri4 = Rot3::rodriguez(0.0, PI, 0.0); float si1,si2,si3,si4; si1=1; si2=1; si3=1; si4=1; // Add a prior on the first pose, setting it to the origin // A prior factor consists of a mean and a noise model (covariance matrix) Moses3 priorMean(ScSO3(s0*R0.matrix()),Pp0.vector()); // prior at origin noiseModel::Diagonal::shared_ptr priorNoise = noiseModel::Diagonal::Sigmas((Vector(7) << 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 1)); graph.add(PriorFactor<Moses3>(1, priorMean, priorNoise)); graph.add(BetweenFactor<Moses3>(1, 2, Moses3(ScSO3(s12*R12.matrix()),Pp12.vector()), odometryNoise)); graph.add(BetweenFactor<Moses3>(2, 3, Moses3(ScSO3(s23*R23.matrix()),Pp23.vector()), odometryNoise)); graph.add(BetweenFactor<Moses3>(3, 4, Moses3(ScSO3(s34*R34.matrix()),Pp34.vector()), odometryNoise)); // 2b. Add "GPS-like" measurements // We will use our custom UnaryFactor for this. noiseModel::Diagonal::shared_ptr unaryNoise = noiseModel::Diagonal::Sigmas((Vector(3) << 0.001, 0.001, 0.001)); // 10cm std on x,y graph.add(boost::make_shared<UnaryFactor>(2, Up2, unaryNoise)); graph.add(boost::make_shared<UnaryFactor>(3, Up3, unaryNoise)); graph.add(boost::make_shared<UnaryFactor>(4, Up4, unaryNoise)); //graph.add(BetweenFactor<Pose2>(1, 2, Pose2(2.0, 0.0, 0.0), odometryNoise)); //graph.add(BetweenFactor<Pose2>(2, 3, Pose2(2.0, 0.0, 0.0), odometryNoise)); // 2b. Add "GPS-like" measurements // We will use our custom UnaryFactor for this. //noiseModel::Diagonal::shared_ptr unaryNoise = noiseModel::Diagonal::Sigmas((Vector(2) << 0.1, 0.1)); // 10cm std on x,y //graph.add(boost::make_shared<UnaryFactor>(1, 0.0, 0.0, unaryNoise)); //graph.add(boost::make_shared<UnaryFactor>(2, 2.0, 0.0, unaryNoise)); //graph.add(boost::make_shared<UnaryFactor>(3, 4.0, 0.0, unaryNoise)); graph.print("\nFactor Graph:\n"); // print // 3. Create the data structure to hold the initialEstimate estimate to the solution // For illustrative purposes, these have been deliberately set to incorrect values Values initialEstimate; initialEstimate.insert(1, Moses3(ScSO3(si1*Ri1.matrix()),Pi1.vector())); initialEstimate.insert(2, Moses3(ScSO3(si2*Ri2.matrix()),Pi2.vector())); initialEstimate.insert(3, Moses3(ScSO3(si3*Ri3.matrix()),Pi3.vector())); initialEstimate.insert(4, Moses3(ScSO3(si4*Ri4.matrix()),Pi4.vector())); //initialEstimate.insert(1, Pose2(0.5, 0.0, 0.2)); //initialEstimate.insert(2, Pose2(2.3, 0.1, -0.2)); //initialEstimate.insert(3, Pose2(4.1, 0.1, 0.1)); initialEstimate.print("\nInitial Estimate:\n"); // print // 4. Optimize using Levenberg-Marquardt optimization. The optimizer // accepts an optional set of configuration parameters, controlling // things like convergence criteria, the type of linear system solver // to use, and the amount of information displayed during optimization. // Here we will use the default set of parameters. See the // documentation for the full set of parameters. LevenbergMarquardtOptimizer optimizer(graph, initialEstimate); Values result = optimizer.optimize(); result.print("Final Result:\n"); // 5. Calculate and print marginal covariances for all variables Marginals marginals(graph, result); //cout << "x1 covariance:\n" << marginals.marginalCovariance(1) << endl; //cout << "x2 covariance:\n" << marginals.marginalCovariance(2) << endl; //cout << "x3 covariance:\n" << marginals.marginalCovariance(3) << endl; return 0; } <|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/. */ #include <GL3DBarChart.hxx> #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include "3DChartObjects.hxx" #include "GL3DRenderer.hxx" #include <ExplicitCategoriesProvider.hxx> #include <DataSeriesHelper.hxx> using namespace com::sun::star; namespace chart { GL3DBarChart::GL3DBarChart( const css::uno::Reference<css::chart2::XChartType>& xChartType, OpenGLWindow& rWindow) : mxChartType(xChartType), mpRenderer(new opengl3D::OpenGL3DRenderer()), mrWindow(rWindow), mpCamera(NULL) { Size aSize = mrWindow.GetSizePixel(); mpRenderer->SetSize(aSize); mrWindow.setRenderer(this); mpRenderer->init(); } GL3DBarChart::~GL3DBarChart() { mrWindow.setRenderer(NULL); } namespace { const float TEXT_HEIGHT = 15.0f; float calculateTextWidth(const OUString& rText) { return rText.getLength() * 7.5; } } void GL3DBarChart::create3DShapes(const boost::ptr_vector<VDataSeries>& rDataSeriesContainer, ExplicitCategoriesProvider& rCatProvider) { // Each series of data flows from left to right, and multiple series are // stacked vertically along y axis. // NOTE: These objects are created and positioned in a totally blind // fashion since we don't even have a way to see them on screen. So, no // guarantee they are positioned correctly. In fact, they are guaranteed // to be positioned incorrectly. const float nBarSizeX = 10; const float nBarSizeY = 10; const float nBarDistanceX = nBarSizeX / 2; const float nBarDistanceY = nBarSizeY / 2; sal_uInt32 nId = 1; float nXEnd = 0.0; float nYPos = 0.0; const Color aSeriesColor[] = { COL_RED, COL_GREEN, COL_YELLOW, COL_BROWN, COL_GRAY }; maShapes.clear(); maShapes.push_back(new opengl3D::Camera(mpRenderer.get())); mpCamera = static_cast<opengl3D::Camera*>(&maShapes.back()); sal_Int32 nSeriesIndex = 0; for (boost::ptr_vector<VDataSeries>::const_iterator itr = rDataSeriesContainer.begin(), itrEnd = rDataSeriesContainer.end(); itr != itrEnd; ++itr) { nYPos = nSeriesIndex * (nBarSizeY + nBarDistanceY); const VDataSeries& rDataSeries = *itr; sal_Int32 nPointCount = rDataSeries.getTotalPointCount(); bool bMappedFillProperty = rDataSeries.hasPropertyMapping("FillColor"); // Create series name text object. OUString aSeriesName = DataSeriesHelper::getDataSeriesLabel( rDataSeries.getModel(), mxChartType->getRoleOfSequenceForSeriesLabel()); maShapes.push_back(new opengl3D::Text(mpRenderer.get(), aSeriesName, nId++)); opengl3D::Text* p = static_cast<opengl3D::Text*>(&maShapes.back()); glm::vec3 aTopLeft, aTopRight, aBottomRight; aTopLeft.x = calculateTextWidth(aSeriesName) * -1.0; aTopLeft.y = nYPos; aTopRight.y = nYPos; aBottomRight = aTopRight; aBottomRight.y += TEXT_HEIGHT; p->setPosition(aTopLeft, aTopRight, aBottomRight); sal_Int32 nColor = aSeriesColor[nSeriesIndex % SAL_N_ELEMENTS(aSeriesColor)].GetColor(); for(sal_Int32 nIndex = 0; nIndex < nPointCount; ++nIndex) { if(bMappedFillProperty) { nColor = static_cast<sal_uInt32>(rDataSeries.getValueByProperty(nIndex, "FillColor")); } float nVal = rDataSeries.getYValue(nIndex); float nXPos = nIndex * (nBarSizeX + nBarDistanceX); glm::mat4 aScaleMatrix = glm::scale(nBarSizeX, nBarSizeY, nVal); glm::mat4 aTranslationMatrix = glm::translate(nXPos, nYPos, 0.0f); glm::mat4 aBarPosition = aTranslationMatrix * aScaleMatrix; maShapes.push_back(new opengl3D::Bar(mpRenderer.get(), aBarPosition, nColor, nId++)); } float nThisXEnd = nPointCount * (nBarSizeX + nBarDistanceX); if (nXEnd < nThisXEnd) nXEnd = nThisXEnd; ++nSeriesIndex; } nYPos += nBarSizeY + nBarDistanceY; // X axis maShapes.push_back(new opengl3D::Line(mpRenderer.get(), nId++)); opengl3D::Line* pAxis = static_cast<opengl3D::Line*>(&maShapes.back()); glm::vec3 aBegin; aBegin.y = nYPos; glm::vec3 aEnd = aBegin; aEnd.x = nXEnd; pAxis->setPosition(aBegin, aEnd); pAxis->setLineColor(COL_BLUE); // Y axis maShapes.push_back(new opengl3D::Line(mpRenderer.get(), nId++)); pAxis = static_cast<opengl3D::Line*>(&maShapes.back()); aBegin.x = aBegin.y = 0; aEnd = aBegin; aEnd.y = nYPos; pAxis->setPosition(aBegin, aEnd); pAxis->setLineColor(COL_BLUE); // Chart background. maShapes.push_back(new opengl3D::Rectangle(mpRenderer.get(), nId++)); opengl3D::Rectangle* pRect = static_cast<opengl3D::Rectangle*>(&maShapes.back()); glm::vec3 aTopLeft; glm::vec3 aTopRight = aTopLeft; aTopRight.x = nXEnd; glm::vec3 aBottomRight = aTopRight; aBottomRight.y = nYPos; pRect->setPosition(aTopLeft, aTopRight, aBottomRight); pRect->setFillColor(COL_BLACK); pRect->setLineColor(COL_BLUE); // Create category texts along X-axis at the bottom. uno::Sequence<OUString> aCats = rCatProvider.getSimpleCategories(); for (sal_Int32 i = 0; i < aCats.getLength(); ++i) { float nXPos = i * (nBarSizeX + nBarDistanceX); maShapes.push_back(new opengl3D::Text(mpRenderer.get(), aCats[i], nId++)); opengl3D::Text* p = static_cast<opengl3D::Text*>(&maShapes.back()); aTopLeft.x = nXPos; aTopLeft.y = nYPos; aTopRight = aTopLeft; aTopRight.x += calculateTextWidth(aCats[i]); aBottomRight = aTopRight; aBottomRight.y += TEXT_HEIGHT; p->setPosition(aTopLeft, aTopRight, aBottomRight); } } void GL3DBarChart::render() { mrWindow.getContext()->makeCurrent(); Size aSize = mrWindow.GetSizePixel(); mpRenderer->SetSize(aSize); mrWindow.getContext()->setWinSize(aSize); for(boost::ptr_vector<opengl3D::Renderable3DObject>::iterator itr = maShapes.begin(), itrEnd = maShapes.end(); itr != itrEnd; ++itr) { itr->render(); } mpRenderer->ProcessUnrenderedShape(); mrWindow.getContext()->swapBuffers(); } void GL3DBarChart::update() { render(); } namespace { class PickingModeSetter { private: opengl3D::OpenGL3DRenderer* mpRenderer; public: PickingModeSetter(opengl3D::OpenGL3DRenderer* pRenderer): mpRenderer(pRenderer) { mpRenderer->SetPickingMode(true); } ~PickingModeSetter() { mpRenderer->SetPickingMode(false); } }; } void GL3DBarChart::clickedAt(const Point& rPos) { sal_uInt32 nId = 1; { PickingModeSetter aPickingModeSetter(mpRenderer.get()); render(); nId = mpRenderer->GetPixelColorFromPoint(rPos.X(), rPos.Y()); } if (mpCamera && nId != COL_WHITE) mpCamera->zoom(nId); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>change the bar size a bit<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/. */ #include <GL3DBarChart.hxx> #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include "3DChartObjects.hxx" #include "GL3DRenderer.hxx" #include <ExplicitCategoriesProvider.hxx> #include <DataSeriesHelper.hxx> using namespace com::sun::star; namespace chart { GL3DBarChart::GL3DBarChart( const css::uno::Reference<css::chart2::XChartType>& xChartType, OpenGLWindow& rWindow) : mxChartType(xChartType), mpRenderer(new opengl3D::OpenGL3DRenderer()), mrWindow(rWindow), mpCamera(NULL) { Size aSize = mrWindow.GetSizePixel(); mpRenderer->SetSize(aSize); mrWindow.setRenderer(this); mpRenderer->init(); } GL3DBarChart::~GL3DBarChart() { mrWindow.setRenderer(NULL); } namespace { const float TEXT_HEIGHT = 15.0f; float calculateTextWidth(const OUString& rText) { return rText.getLength() * 7.5; } } void GL3DBarChart::create3DShapes(const boost::ptr_vector<VDataSeries>& rDataSeriesContainer, ExplicitCategoriesProvider& rCatProvider) { // Each series of data flows from left to right, and multiple series are // stacked vertically along y axis. // NOTE: These objects are created and positioned in a totally blind // fashion since we don't even have a way to see them on screen. So, no // guarantee they are positioned correctly. In fact, they are guaranteed // to be positioned incorrectly. const float nBarSizeX = 10.0f; const float nBarSizeY = 30.0f; const float nBarDistanceX = 5.0f; const float nBarDistanceY = 5.0; sal_uInt32 nId = 1; float nXEnd = 0.0; float nYPos = 0.0; const Color aSeriesColor[] = { COL_RED, COL_GREEN, COL_YELLOW, COL_BROWN, COL_GRAY }; maShapes.clear(); maShapes.push_back(new opengl3D::Camera(mpRenderer.get())); mpCamera = static_cast<opengl3D::Camera*>(&maShapes.back()); sal_Int32 nSeriesIndex = 0; for (boost::ptr_vector<VDataSeries>::const_iterator itr = rDataSeriesContainer.begin(), itrEnd = rDataSeriesContainer.end(); itr != itrEnd; ++itr) { nYPos = nSeriesIndex * (nBarSizeY + nBarDistanceY); const VDataSeries& rDataSeries = *itr; sal_Int32 nPointCount = rDataSeries.getTotalPointCount(); bool bMappedFillProperty = rDataSeries.hasPropertyMapping("FillColor"); // Create series name text object. OUString aSeriesName = DataSeriesHelper::getDataSeriesLabel( rDataSeries.getModel(), mxChartType->getRoleOfSequenceForSeriesLabel()); maShapes.push_back(new opengl3D::Text(mpRenderer.get(), aSeriesName, nId++)); opengl3D::Text* p = static_cast<opengl3D::Text*>(&maShapes.back()); glm::vec3 aTopLeft, aTopRight, aBottomRight; aTopLeft.x = calculateTextWidth(aSeriesName) * -1.0; aTopLeft.y = nYPos; aTopRight.y = nYPos; aBottomRight = aTopRight; aBottomRight.y += TEXT_HEIGHT; p->setPosition(aTopLeft, aTopRight, aBottomRight); sal_Int32 nColor = aSeriesColor[nSeriesIndex % SAL_N_ELEMENTS(aSeriesColor)].GetColor(); for(sal_Int32 nIndex = 0; nIndex < nPointCount; ++nIndex) { if(bMappedFillProperty) { nColor = static_cast<sal_uInt32>(rDataSeries.getValueByProperty(nIndex, "FillColor")); } float nVal = rDataSeries.getYValue(nIndex); float nXPos = nIndex * (nBarSizeX + nBarDistanceX); glm::mat4 aScaleMatrix = glm::scale(nBarSizeX, nBarSizeY, nVal); glm::mat4 aTranslationMatrix = glm::translate(nXPos, nYPos, 0.0f); glm::mat4 aBarPosition = aTranslationMatrix * aScaleMatrix; maShapes.push_back(new opengl3D::Bar(mpRenderer.get(), aBarPosition, nColor, nId++)); } float nThisXEnd = nPointCount * (nBarSizeX + nBarDistanceX); if (nXEnd < nThisXEnd) nXEnd = nThisXEnd; ++nSeriesIndex; } nYPos += nBarSizeY + nBarDistanceY; // X axis maShapes.push_back(new opengl3D::Line(mpRenderer.get(), nId++)); opengl3D::Line* pAxis = static_cast<opengl3D::Line*>(&maShapes.back()); glm::vec3 aBegin; aBegin.y = nYPos; glm::vec3 aEnd = aBegin; aEnd.x = nXEnd; pAxis->setPosition(aBegin, aEnd); pAxis->setLineColor(COL_BLUE); // Y axis maShapes.push_back(new opengl3D::Line(mpRenderer.get(), nId++)); pAxis = static_cast<opengl3D::Line*>(&maShapes.back()); aBegin.x = aBegin.y = 0; aEnd = aBegin; aEnd.y = nYPos; pAxis->setPosition(aBegin, aEnd); pAxis->setLineColor(COL_BLUE); // Chart background. maShapes.push_back(new opengl3D::Rectangle(mpRenderer.get(), nId++)); opengl3D::Rectangle* pRect = static_cast<opengl3D::Rectangle*>(&maShapes.back()); glm::vec3 aTopLeft; glm::vec3 aTopRight = aTopLeft; aTopRight.x = nXEnd; glm::vec3 aBottomRight = aTopRight; aBottomRight.y = nYPos; pRect->setPosition(aTopLeft, aTopRight, aBottomRight); pRect->setFillColor(COL_BLACK); pRect->setLineColor(COL_BLUE); // Create category texts along X-axis at the bottom. uno::Sequence<OUString> aCats = rCatProvider.getSimpleCategories(); for (sal_Int32 i = 0; i < aCats.getLength(); ++i) { float nXPos = i * (nBarSizeX + nBarDistanceX); maShapes.push_back(new opengl3D::Text(mpRenderer.get(), aCats[i], nId++)); opengl3D::Text* p = static_cast<opengl3D::Text*>(&maShapes.back()); aTopLeft.x = nXPos; aTopLeft.y = nYPos; aTopRight = aTopLeft; aTopRight.x += calculateTextWidth(aCats[i]); aBottomRight = aTopRight; aBottomRight.y += TEXT_HEIGHT; p->setPosition(aTopLeft, aTopRight, aBottomRight); } } void GL3DBarChart::render() { mrWindow.getContext()->makeCurrent(); Size aSize = mrWindow.GetSizePixel(); mpRenderer->SetSize(aSize); mrWindow.getContext()->setWinSize(aSize); for(boost::ptr_vector<opengl3D::Renderable3DObject>::iterator itr = maShapes.begin(), itrEnd = maShapes.end(); itr != itrEnd; ++itr) { itr->render(); } mpRenderer->ProcessUnrenderedShape(); mrWindow.getContext()->swapBuffers(); } void GL3DBarChart::update() { render(); } namespace { class PickingModeSetter { private: opengl3D::OpenGL3DRenderer* mpRenderer; public: PickingModeSetter(opengl3D::OpenGL3DRenderer* pRenderer): mpRenderer(pRenderer) { mpRenderer->SetPickingMode(true); } ~PickingModeSetter() { mpRenderer->SetPickingMode(false); } }; } void GL3DBarChart::clickedAt(const Point& rPos) { sal_uInt32 nId = 1; { PickingModeSetter aPickingModeSetter(mpRenderer.get()); render(); nId = mpRenderer->GetPixelColorFromPoint(rPos.X(), rPos.Y()); } if (mpCamera && nId != COL_WHITE) mpCamera->zoom(nId); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <unistd.h> #include <string> #include <string.h> #include <csignal> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/wait.h> #include <dirent.h> #include <fcntl.h> #include <errno.h> #include <functional> #include <unordered_map> #include <algorithm> #include <iostream> #include <sstream> #if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 49 #include <regex> #endif #include <cassert> #include <vector> #include <fstream> #include <future> #include <ctime> #define BUF_SIZE 4096 #define MAX_LISTEN 128 namespace Cappuccino { class Request; class Response; struct { time_t time; struct tm *t_st; int port = 1204; int sockfd = 0; int sessionfd = 0; fd_set mask1fds, mask2fds; std::shared_ptr<std::string> view_root; std::shared_ptr<std::string> static_root; std::unordered_map<std::string, std::function<Response(std::shared_ptr<Request>)> > routes; } context; namespace Log{ std::string current(){ char timestr[256]; time(&context.time); strftime(timestr, 255, "%Y-%m-%d %H:%M:%S %Z", localtime(&context.time)); return timestr; } static int LogLevel = 0; static void debug(std::string msg){ if(LogLevel >= 1){ std::cout <<current()<<"[debug] "<< msg << std::endl; } } static void info(std::string msg){ if(LogLevel >= 2){ std::cout <<current()<<"[info] "<< msg << std::endl; } } }; namespace signal_utils{ void signal_handler(int signal){ close(context.sessionfd); close(context.sockfd); exit(0); } void signal_handler_child(int SignalName){ while(waitpid(-1,NULL,WNOHANG)>0){} signal(SIGCHLD, signal_utils::signal_handler_child); } void init_signal(){ if(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){ exit(1); } if(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){ exit(1); } } } namespace utils{ std::vector<std::string> split(const std::string& str, std::string delim) noexcept{ std::vector<std::string> result; std::string::size_type pos = 0; while(pos != std::string::npos ){ std::string::size_type p = str.find(delim, pos); if(p == std::string::npos){ result.push_back(str.substr(pos)); break; }else{ result.push_back(str.substr(pos, p - pos)); } pos = p + delim.size(); } return result; } }; void init_socket(){ struct sockaddr_in server; if((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ exit(EXIT_FAILURE); } memset( &server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(context.port); char opt = 1; setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char)); int temp = 1; if(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, &temp, sizeof(int))){ } if (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) { exit(EXIT_FAILURE); } if(listen(context.sockfd, MAX_LISTEN) < 0) { exit(EXIT_FAILURE); } FD_ZERO(&context.mask1fds); FD_SET(context.sockfd, &context.mask1fds); } using namespace std; pair<string,string> openFile(string aFilename){ auto filename = aFilename; std::ifstream ifs( filename, std::ios::in | std::ios::binary); if(ifs.fail()){ throw std::runtime_error("No such file or directory \""+ filename +"\"\n"); } ifs.seekg( 0, std::ios::end); auto pos = ifs.tellg(); ifs.seekg( 0, std::ios::beg); std::vector<char> buf(pos); ifs.read(buf.data(), pos); string response(buf.cbegin(), buf.cend()); if( response[0] == '\xFF' && response[1] == '\xD8'){ return make_pair(response, "image/jpg"); }else if( response[0] == '\x89' && response[1] == 'P' && response[2] == 'N' && response[3] == 'G'){ return make_pair(response, "image/png"); }else if( response[0] == 'G' && response[1] == 'I' && response[2] == 'F' && response[3] == '8' && (response[4] == '7' || response[4] == '9') && response[2] == 'a'){ return make_pair(response, "image/gif"); }else{ return make_pair(response, "text/html"); } } void option(int argc, char *argv[]) noexcept{ char result; while((result = getopt(argc,argv,"dvp:")) != -1){ switch(result){ case 'd': Log::LogLevel = 1; break; case 'p': context.port = atoi(optarg); break; case 'v': Log::info("version 0.0.3"); exit(0); } } } class Request{ unordered_map<string, string> headerset; unordered_map<string, string> paramset; public: Request(string method, string url,string protocol): method(move(method)), url(move(url)), protocol(move(protocol)) {} const string method; const string url; const string protocol; void addHeader(string key,string value){ headerset[key] = move(value); } void addParams(string key,string value){ paramset[key] = move(value); } string header(string key){ if(headerset.find(key) == headerset.end()) return "INVALID"; return headerset[key]; } string params(string key){ if(paramset.find(key) == paramset.end()) return "INVALID"; return paramset[key]; } }; class Response{ unordered_map<string, string> headerset; int status_; string message_; string url_; string body_; string protocol_; public: Response(weak_ptr<Request> req){ auto r = req.lock(); if(r){ url_ = r->url; protocol_ = r->protocol; }else{ throw std::runtime_error("Request expired!\n"); } } Response(int st,string msg,string pro, string bod): status_(st), message_(msg), body_(bod), protocol_(pro) {} Response* message(string msg){ message_ = msg; return this; } Response* status(int st){ status_ = st; return this; } Response* headeer(string key,string val){ if(headerset.find(key)!= headerset.end()) Log::debug(key+" is already setted."); headerset[key] = val; return this; } Response* file(string filename){ auto file = openFile(*context.view_root + "/" + filename); body_ = file.first; headerset["Content-type"] = move(file.second); return this; } operator string(){ return protocol_ + " " + to_string(status_) +" "+ message_ + "\n\n" + body_; } }; string createResponse(char* req) noexcept{ auto lines = utils::split(string(req), "\n"); if(lines.empty()) return Response(400, "Bad Request", "HTTP/1.1", "NN"); auto tops = utils::split(lines[0], " "); if(tops.size() < 3) return Response(401, "Bad Request", "HTTP/1.1", "NN"); Log::debug(tops[0] +" "+ tops[1] +" "+ tops[2]); auto request = shared_ptr<Request>(new Request(tops[0],tops[1],tops[2])); if(context.routes.find(tops[1]) != context.routes.end()){ return context.routes[tops[1]](move(request)); } return Response( 404,"Not found", tops[2], "AA"); } string receiveProcess(int sessionfd){ char buf[BUF_SIZE] = {}; if (recv(sessionfd, buf, sizeof(buf), 0) < 0) { exit(EXIT_FAILURE); } do{ if(strstr(buf, "\r\n")){ break; } if (strlen(buf) >= sizeof(buf)) { memset(&buf, 0, sizeof(buf)); } }while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0); return createResponse(buf); } void load(string directory, string filename) noexcept{ if(filename == "." || filename == "..") return; if(filename!="") directory += "/" + move(filename); DIR* dir = opendir(directory.c_str()); if(dir != NULL){ struct dirent* dent; dent = readdir(dir); while(dent!=NULL){ dent = readdir(dir); if(dent!=NULL) load(directory, string(dent->d_name)); } if(dir!=NULL){ closedir(dir); //delete dent; //delete dir; } }else{ Log::debug("add "+directory); context.routes.insert( make_pair( "/" + directory, [directory,filename](std::shared_ptr<Request> request) -> Cappuccino::Response{ return Response(200,"OK","HTTP/1.1",openFile(directory).first); } )); } } void loadStaticFiles() noexcept{ load(*context.static_root,""); } void route(string url,std::function<Response(std::shared_ptr<Request>)> F){ context.routes.insert( make_pair( move(url), move(F) )); } void root(string r){ context.view_root = make_shared<string>(move(r)); } void resource(string s){ context.static_root = make_shared<string>(move(s)); } void run(){ init_socket(); signal_utils::init_signal(); loadStaticFiles(); int cd[FD_SETSIZE]; struct sockaddr_in client; int fd; struct timeval tv; for(int i = 0;i < FD_SETSIZE; i++){ cd[i] = 0; } int I = 0; while(1) { if(I>5){ return; } tv.tv_sec = 0; tv.tv_usec = 0; memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds)); int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv); if(select_result < 1) { for(fd = 0; fd < FD_SETSIZE; fd++) { if(cd[fd] == 1) { close(fd); FD_CLR(fd, &context.mask1fds); cd[fd] = 0; } } continue; } for(fd = 0; fd < FD_SETSIZE; fd++){ if(FD_ISSET(fd,&context.mask2fds)) { if(fd == context.sockfd) { memset( &client, 0, sizeof(client)); int len = sizeof(client); int clientfd = accept(context.sockfd, (struct sockaddr *)&client,(socklen_t *) &len); FD_SET(clientfd, &context.mask1fds); }else { if(cd[fd] == 1) { close(fd); FD_CLR(fd, &context.mask1fds); cd[fd] = 0; } else { string response = receiveProcess(fd); write(fd, response.c_str(), response.size()); cd[fd] = 1; I++; } } } } } } void Cappuccino(int argc, char *argv[]) { option(argc, argv); context.view_root = make_shared<string>(""); context.static_root = make_shared<string>("public"); } }; namespace Cocoa{ using namespace Cappuccino; using namespace std; // Unit Test void testOpenFile(){ auto res = openFile("html/index.html"); auto lines = utils::split(res.first, "\n"); assert(!lines.empty()); } void testOpenInvalidFile(){ try{ auto res = openFile("html/index"); }catch(std::runtime_error e){ cout<< e.what() << endl; } } }; <commit_msg>[FIX] remove code.<commit_after>#include <cstdio> #include <cstdlib> #include <unistd.h> #include <string> #include <string.h> #include <csignal> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/wait.h> #include <dirent.h> #include <fcntl.h> #include <errno.h> #include <functional> #include <unordered_map> #include <algorithm> #include <iostream> #include <sstream> #if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 49 #include <regex> #endif #include <cassert> #include <vector> #include <fstream> #include <future> #include <ctime> #define BUF_SIZE 4096 #define MAX_LISTEN 128 namespace Cappuccino { class Request; class Response; struct { time_t time; struct tm *t_st; int port = 1204; int sockfd = 0; int sessionfd = 0; fd_set mask1fds, mask2fds; std::shared_ptr<std::string> view_root; std::shared_ptr<std::string> static_root; std::unordered_map<std::string, std::function<Response(std::shared_ptr<Request>)> > routes; } context; namespace Log{ std::string current(){ char timestr[256]; time(&context.time); strftime(timestr, 255, "%Y-%m-%d %H:%M:%S %Z", localtime(&context.time)); return timestr; } static int LogLevel = 0; static void debug(std::string msg){ if(LogLevel >= 1){ std::cout <<current()<<"[debug] "<< msg << std::endl; } } static void info(std::string msg){ if(LogLevel >= 2){ std::cout <<current()<<"[info] "<< msg << std::endl; } } }; namespace signal_utils{ void signal_handler(int signal){ close(context.sessionfd); close(context.sockfd); exit(0); } void signal_handler_child(int SignalName){ while(waitpid(-1,NULL,WNOHANG)>0){} signal(SIGCHLD, signal_utils::signal_handler_child); } void init_signal(){ if(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){ exit(1); } if(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){ exit(1); } } } namespace utils{ std::vector<std::string> split(const std::string& str, std::string delim) noexcept{ std::vector<std::string> result; std::string::size_type pos = 0; while(pos != std::string::npos ){ std::string::size_type p = str.find(delim, pos); if(p == std::string::npos){ result.push_back(str.substr(pos)); break; }else{ result.push_back(str.substr(pos, p - pos)); } pos = p + delim.size(); } return result; } }; void init_socket(){ struct sockaddr_in server; if((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ exit(EXIT_FAILURE); } memset( &server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(context.port); char opt = 1; setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char)); int temp = 1; if(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, &temp, sizeof(int))){ } if (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) { exit(EXIT_FAILURE); } if(listen(context.sockfd, MAX_LISTEN) < 0) { exit(EXIT_FAILURE); } FD_ZERO(&context.mask1fds); FD_SET(context.sockfd, &context.mask1fds); } using namespace std; pair<string,string> openFile(string aFilename){ auto filename = aFilename; std::ifstream ifs( filename, std::ios::in | std::ios::binary); if(ifs.fail()){ throw std::runtime_error("No such file or directory \""+ filename +"\"\n"); } ifs.seekg( 0, std::ios::end); auto pos = ifs.tellg(); ifs.seekg( 0, std::ios::beg); std::vector<char> buf(pos); ifs.read(buf.data(), pos); string response(buf.cbegin(), buf.cend()); if( response[0] == '\xFF' && response[1] == '\xD8'){ return make_pair(response, "image/jpg"); }else if( response[0] == '\x89' && response[1] == 'P' && response[2] == 'N' && response[3] == 'G'){ return make_pair(response, "image/png"); }else if( response[0] == 'G' && response[1] == 'I' && response[2] == 'F' && response[3] == '8' && (response[4] == '7' || response[4] == '9') && response[2] == 'a'){ return make_pair(response, "image/gif"); }else{ return make_pair(response, "text/html"); } } void option(int argc, char *argv[]) noexcept{ char result; while((result = getopt(argc,argv,"dvp:")) != -1){ switch(result){ case 'd': Log::LogLevel = 1; break; case 'p': context.port = atoi(optarg); break; case 'v': Log::info("version 0.0.3"); exit(0); } } } class Request{ unordered_map<string, string> headerset; unordered_map<string, string> paramset; public: Request(string method, string url,string protocol): method(move(method)), url(move(url)), protocol(move(protocol)) {} const string method; const string url; const string protocol; void addHeader(string key,string value){ headerset[key] = move(value); } void addParams(string key,string value){ paramset[key] = move(value); } string header(string key){ if(headerset.find(key) == headerset.end()) return "INVALID"; return headerset[key]; } string params(string key){ if(paramset.find(key) == paramset.end()) return "INVALID"; return paramset[key]; } }; class Response{ unordered_map<string, string> headerset; int status_; string message_; string url_; string body_; string protocol_; public: Response(weak_ptr<Request> req){ auto r = req.lock(); if(r){ url_ = r->url; protocol_ = r->protocol; }else{ throw std::runtime_error("Request expired!\n"); } } Response(int st,string msg,string pro, string bod): status_(st), message_(msg), body_(bod), protocol_(pro) {} Response* message(string msg){ message_ = msg; return this; } Response* status(int st){ status_ = st; return this; } Response* headeer(string key,string val){ if(headerset.find(key)!= headerset.end()) Log::debug(key+" is already setted."); headerset[key] = val; return this; } Response* file(string filename){ auto file = openFile(*context.view_root + "/" + filename); body_ = file.first; headerset["Content-type"] = move(file.second); return this; } operator string(){ return protocol_ + " " + to_string(status_) +" "+ message_ + "\n\n" + body_; } }; string createResponse(char* req) noexcept{ auto lines = utils::split(string(req), "\n"); if(lines.empty()) return Response(400, "Bad Request", "HTTP/1.1", "NN"); auto tops = utils::split(lines[0], " "); if(tops.size() < 3) return Response(401, "Bad Request", "HTTP/1.1", "NN"); Log::debug(tops[0] +" "+ tops[1] +" "+ tops[2]); auto request = shared_ptr<Request>(new Request(tops[0],tops[1],tops[2])); if(context.routes.find(tops[1]) != context.routes.end()){ return context.routes[tops[1]](move(request)); } return Response( 404,"Not found", tops[2], "AA"); } string receiveProcess(int sessionfd){ char buf[BUF_SIZE] = {}; if (recv(sessionfd, buf, sizeof(buf), 0) < 0) { exit(EXIT_FAILURE); } do{ if(strstr(buf, "\r\n")){ break; } if (strlen(buf) >= sizeof(buf)) { memset(&buf, 0, sizeof(buf)); } }while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0); return createResponse(buf); } void load(string directory, string filename) noexcept{ if(filename == "." || filename == "..") return; if(filename!="") directory += "/" + move(filename); DIR* dir = opendir(directory.c_str()); if(dir != NULL){ struct dirent* dent; dent = readdir(dir); while(dent!=NULL){ dent = readdir(dir); if(dent!=NULL) load(directory, string(dent->d_name)); } if(dir!=NULL){ closedir(dir); //delete dent; //delete dir; } }else{ Log::debug("add "+directory); context.routes.insert( make_pair( "/" + directory, [directory,filename](std::shared_ptr<Request> request) -> Cappuccino::Response{ return Response(200,"OK","HTTP/1.1",openFile(directory).first); } )); } } void loadStaticFiles() noexcept{ load(*context.static_root,""); } void route(string url,std::function<Response(std::shared_ptr<Request>)> F){ context.routes.insert( make_pair( move(url), move(F) )); } void root(string r){ context.view_root = make_shared<string>(move(r)); } void resource(string s){ context.static_root = make_shared<string>(move(s)); } void run(){ init_socket(); signal_utils::init_signal(); loadStaticFiles(); int cd[FD_SETSIZE]; struct sockaddr_in client; int fd; struct timeval tv; for(int i = 0;i < FD_SETSIZE; i++){ cd[i] = 0; } while(1) { tv.tv_sec = 0; tv.tv_usec = 0; memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds)); int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv); if(select_result < 1) { for(fd = 0; fd < FD_SETSIZE; fd++) { if(cd[fd] == 1) { close(fd); FD_CLR(fd, &context.mask1fds); cd[fd] = 0; } } continue; } for(fd = 0; fd < FD_SETSIZE; fd++){ if(FD_ISSET(fd,&context.mask2fds)) { if(fd == context.sockfd) { memset( &client, 0, sizeof(client)); int len = sizeof(client); int clientfd = accept(context.sockfd, (struct sockaddr *)&client,(socklen_t *) &len); FD_SET(clientfd, &context.mask1fds); }else { if(cd[fd] == 1) { close(fd); FD_CLR(fd, &context.mask1fds); cd[fd] = 0; } else { string response = receiveProcess(fd); write(fd, response.c_str(), response.size()); cd[fd] = 1; I++; } } } } } } void Cappuccino(int argc, char *argv[]) { option(argc, argv); context.view_root = make_shared<string>(""); context.static_root = make_shared<string>("public"); } }; namespace Cocoa{ using namespace Cappuccino; using namespace std; // Unit Test void testOpenFile(){ auto res = openFile("html/index.html"); auto lines = utils::split(res.first, "\n"); assert(!lines.empty()); } void testOpenInvalidFile(){ try{ auto res = openFile("html/index"); }catch(std::runtime_error e){ cout<< e.what() << endl; } } }; <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/bookmarks/bookmark_node_data.h" #include <string> #include "base/basictypes.h" #include "base/pickle.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "net/base/escape.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #if defined(OS_MACOSX) #include "chrome/browser/bookmarks/bookmark_pasteboard_helper_mac.h" #else #include "chrome/browser/browser_process.h" #endif const char* BookmarkNodeData::kClipboardFormatString = "chromium/x-bookmark-entries"; BookmarkNodeData::Element::Element() : is_url(false), id_(0) { } BookmarkNodeData::Element::Element(const BookmarkNode* node) : is_url(node->is_url()), url(node->url()), title(node->GetTitle()), id_(node->id()) { for (int i = 0; i < node->child_count(); ++i) children.push_back(Element(node->GetChild(i))); } BookmarkNodeData::Element::~Element() { } void BookmarkNodeData::Element::WriteToPickle(Pickle* pickle) const { pickle->WriteBool(is_url); pickle->WriteString(url.spec()); pickle->WriteString16(title); pickle->WriteInt64(id_); if (!is_url) { pickle->WriteSize(children.size()); for (std::vector<Element>::const_iterator i = children.begin(); i != children.end(); ++i) { i->WriteToPickle(pickle); } } } bool BookmarkNodeData::Element::ReadFromPickle(Pickle* pickle, void** iterator) { std::string url_spec; if (!pickle->ReadBool(iterator, &is_url) || !pickle->ReadString(iterator, &url_spec) || !pickle->ReadString16(iterator, &title) || !pickle->ReadInt64(iterator, &id_)) { return false; } url = GURL(url_spec); children.clear(); if (!is_url) { size_t children_count; if (!pickle->ReadSize(iterator, &children_count)) return false; children.resize(children_count); for (std::vector<Element>::iterator i = children.begin(); i != children.end(); ++i) { if (!i->ReadFromPickle(pickle, iterator)) return false; } } return true; } #if defined(TOOLKIT_VIEWS) // static ui::OSExchangeData::CustomFormat BookmarkNodeData::GetBookmarkCustomFormat() { static ui::OSExchangeData::CustomFormat format; static bool format_valid = false; if (!format_valid) { format_valid = true; format = ui::OSExchangeData::RegisterCustomFormat( BookmarkNodeData::kClipboardFormatString); } return format; } #endif BookmarkNodeData::BookmarkNodeData() { } BookmarkNodeData::BookmarkNodeData(const BookmarkNode* node) { elements.push_back(Element(node)); } BookmarkNodeData::BookmarkNodeData( const std::vector<const BookmarkNode*>& nodes) { ReadFromVector(nodes); } BookmarkNodeData::~BookmarkNodeData() { } bool BookmarkNodeData::ReadFromVector( const std::vector<const BookmarkNode*>& nodes) { Clear(); if (nodes.empty()) return false; for (size_t i = 0; i < nodes.size(); ++i) elements.push_back(Element(nodes[i])); return true; } bool BookmarkNodeData::ReadFromTuple(const GURL& url, const string16& title) { Clear(); if (!url.is_valid()) return false; Element element; element.title = title; element.url = url; element.is_url = true; elements.push_back(element); return true; } #if !defined(OS_MACOSX) void BookmarkNodeData::WriteToClipboard(Profile* profile) const { ui::ScopedClipboardWriter scw(g_browser_process->clipboard()); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { const string16& title = elements[0].title; const std::string url = elements[0].url.spec(); scw.WriteBookmark(title, url); scw.WriteHyperlink(EscapeForHTML(title), url); // Also write the URL to the clipboard as text so that it can be pasted // into text fields. We use WriteText instead of WriteURL because we don't // want to clobber the X clipboard when the user copies out of the omnibox // on Linux (on Windows and Mac, there is no difference between these // functions). scw.WriteText(UTF8ToUTF16(url)); } Pickle pickle; WriteToPickle(profile, &pickle); scw.WritePickledData(pickle, kClipboardFormatString); } bool BookmarkNodeData::ReadFromClipboard() { std::string data; ui::Clipboard* clipboard = g_browser_process->clipboard(); clipboard->ReadData(kClipboardFormatString, &data); if (!data.empty()) { Pickle pickle(data.data(), data.size()); if (ReadFromPickle(&pickle)) return true; } string16 title; std::string url; clipboard->ReadBookmark(&title, &url); if (!url.empty()) { Element element; element.is_url = true; element.url = GURL(url); element.title = title; elements.clear(); elements.push_back(element); return true; } return false; } bool BookmarkNodeData::ClipboardContainsBookmarks() { #if defined(TOUCH_UI) // Temporarily disabling clipboard due to bug 96448. // TODO(wyck): Reenable when cause of message loop hang in // gtk_clipboard_wait_for_contents is determined and fixed. return false; #else return g_browser_process->clipboard()->IsFormatAvailableByString( BookmarkNodeData::kClipboardFormatString, ui::Clipboard::BUFFER_STANDARD); #endif } #else void BookmarkNodeData::WriteToClipboard(Profile* profile) const { bookmark_pasteboard_helper_mac::WriteToClipboard(elements, profile_path_.value()); } bool BookmarkNodeData::ReadFromClipboard() { // TODO(evan): bookmark_pasteboard_helper_mac should just use FilePaths. FilePath::StringType buf; if (!bookmark_pasteboard_helper_mac::ReadFromClipboard(elements, &buf)) return false; profile_path_ = FilePath(buf); return true; } bool BookmarkNodeData::ReadFromDragClipboard() { // TODO(evan): bookmark_pasteboard_helper_mac should just use FilePaths. FilePath::StringType buf; if (!bookmark_pasteboard_helper_mac::ReadFromDragClipboard(elements, &buf)) return false; profile_path_ = FilePath(buf); return true; } bool BookmarkNodeData::ClipboardContainsBookmarks() { return bookmark_pasteboard_helper_mac::ClipboardContainsBookmarks(); } #endif // !defined(OS_MACOSX) #if defined(TOOLKIT_VIEWS) void BookmarkNodeData::Write(Profile* profile, ui::OSExchangeData* data) const { DCHECK(data); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { if (elements[0].url.SchemeIs(chrome::kJavaScriptScheme)) { data->SetString(UTF8ToUTF16(elements[0].url.spec())); } else { data->SetURL(elements[0].url, elements[0].title); } } Pickle data_pickle; WriteToPickle(profile, &data_pickle); data->SetPickledData(GetBookmarkCustomFormat(), data_pickle); } bool BookmarkNodeData::Read(const ui::OSExchangeData& data) { elements.clear(); profile_path_.clear(); if (data.HasCustomFormat(GetBookmarkCustomFormat())) { Pickle drag_data_pickle; if (data.GetPickledData(GetBookmarkCustomFormat(), &drag_data_pickle)) { if (!ReadFromPickle(&drag_data_pickle)) return false; } } else { // See if there is a URL on the clipboard. Element element; GURL url; string16 title; if (data.GetURLAndTitle(&url, &title)) ReadFromTuple(url, title); } return is_valid(); } #endif void BookmarkNodeData::WriteToPickle(Profile* profile, Pickle* pickle) const { FilePath path = profile ? profile->GetPath() : FilePath(); path.WriteToPickle(pickle); pickle->WriteSize(elements.size()); for (size_t i = 0; i < elements.size(); ++i) elements[i].WriteToPickle(pickle); } bool BookmarkNodeData::ReadFromPickle(Pickle* pickle) { void* data_iterator = NULL; size_t element_count; if (profile_path_.ReadFromPickle(pickle, &data_iterator) && pickle->ReadSize(&data_iterator, &element_count)) { std::vector<Element> tmp_elements; tmp_elements.resize(element_count); for (size_t i = 0; i < element_count; ++i) { if (!tmp_elements[i].ReadFromPickle(pickle, &data_iterator)) { return false; } } elements.swap(tmp_elements); } return true; } std::vector<const BookmarkNode*> BookmarkNodeData::GetNodes( Profile* profile) const { std::vector<const BookmarkNode*> nodes; if (!IsFromProfile(profile)) return nodes; for (size_t i = 0; i < elements.size(); ++i) { const BookmarkNode* node = profile->GetBookmarkModel()->GetNodeByID(elements[i].id_); if (!node) { nodes.clear(); return nodes; } nodes.push_back(node); } return nodes; } const BookmarkNode* BookmarkNodeData::GetFirstNode(Profile* profile) const { std::vector<const BookmarkNode*> nodes = GetNodes(profile); return nodes.size() == 1 ? nodes[0] : NULL; } void BookmarkNodeData::Clear() { profile_path_.clear(); elements.clear(); } void BookmarkNodeData::SetOriginatingProfile(Profile* profile) { DCHECK(profile_path_.empty()); if (profile) profile_path_ = profile->GetPath(); } bool BookmarkNodeData::IsFromProfile(Profile* profile) const { // An empty path means the data is not associated with any profile. return !profile_path_.empty() && profile_path_ == profile->GetPath(); } <commit_msg>Revert 100991 - Disable clipboard for bookmarks in TOUCH_UI builds<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/bookmarks/bookmark_node_data.h" #include <string> #include "base/basictypes.h" #include "base/pickle.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "net/base/escape.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #if defined(OS_MACOSX) #include "chrome/browser/bookmarks/bookmark_pasteboard_helper_mac.h" #else #include "chrome/browser/browser_process.h" #endif const char* BookmarkNodeData::kClipboardFormatString = "chromium/x-bookmark-entries"; BookmarkNodeData::Element::Element() : is_url(false), id_(0) { } BookmarkNodeData::Element::Element(const BookmarkNode* node) : is_url(node->is_url()), url(node->url()), title(node->GetTitle()), id_(node->id()) { for (int i = 0; i < node->child_count(); ++i) children.push_back(Element(node->GetChild(i))); } BookmarkNodeData::Element::~Element() { } void BookmarkNodeData::Element::WriteToPickle(Pickle* pickle) const { pickle->WriteBool(is_url); pickle->WriteString(url.spec()); pickle->WriteString16(title); pickle->WriteInt64(id_); if (!is_url) { pickle->WriteSize(children.size()); for (std::vector<Element>::const_iterator i = children.begin(); i != children.end(); ++i) { i->WriteToPickle(pickle); } } } bool BookmarkNodeData::Element::ReadFromPickle(Pickle* pickle, void** iterator) { std::string url_spec; if (!pickle->ReadBool(iterator, &is_url) || !pickle->ReadString(iterator, &url_spec) || !pickle->ReadString16(iterator, &title) || !pickle->ReadInt64(iterator, &id_)) { return false; } url = GURL(url_spec); children.clear(); if (!is_url) { size_t children_count; if (!pickle->ReadSize(iterator, &children_count)) return false; children.resize(children_count); for (std::vector<Element>::iterator i = children.begin(); i != children.end(); ++i) { if (!i->ReadFromPickle(pickle, iterator)) return false; } } return true; } #if defined(TOOLKIT_VIEWS) // static ui::OSExchangeData::CustomFormat BookmarkNodeData::GetBookmarkCustomFormat() { static ui::OSExchangeData::CustomFormat format; static bool format_valid = false; if (!format_valid) { format_valid = true; format = ui::OSExchangeData::RegisterCustomFormat( BookmarkNodeData::kClipboardFormatString); } return format; } #endif BookmarkNodeData::BookmarkNodeData() { } BookmarkNodeData::BookmarkNodeData(const BookmarkNode* node) { elements.push_back(Element(node)); } BookmarkNodeData::BookmarkNodeData( const std::vector<const BookmarkNode*>& nodes) { ReadFromVector(nodes); } BookmarkNodeData::~BookmarkNodeData() { } bool BookmarkNodeData::ReadFromVector( const std::vector<const BookmarkNode*>& nodes) { Clear(); if (nodes.empty()) return false; for (size_t i = 0; i < nodes.size(); ++i) elements.push_back(Element(nodes[i])); return true; } bool BookmarkNodeData::ReadFromTuple(const GURL& url, const string16& title) { Clear(); if (!url.is_valid()) return false; Element element; element.title = title; element.url = url; element.is_url = true; elements.push_back(element); return true; } #if !defined(OS_MACOSX) void BookmarkNodeData::WriteToClipboard(Profile* profile) const { ui::ScopedClipboardWriter scw(g_browser_process->clipboard()); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { const string16& title = elements[0].title; const std::string url = elements[0].url.spec(); scw.WriteBookmark(title, url); scw.WriteHyperlink(EscapeForHTML(title), url); // Also write the URL to the clipboard as text so that it can be pasted // into text fields. We use WriteText instead of WriteURL because we don't // want to clobber the X clipboard when the user copies out of the omnibox // on Linux (on Windows and Mac, there is no difference between these // functions). scw.WriteText(UTF8ToUTF16(url)); } Pickle pickle; WriteToPickle(profile, &pickle); scw.WritePickledData(pickle, kClipboardFormatString); } bool BookmarkNodeData::ReadFromClipboard() { std::string data; ui::Clipboard* clipboard = g_browser_process->clipboard(); clipboard->ReadData(kClipboardFormatString, &data); if (!data.empty()) { Pickle pickle(data.data(), data.size()); if (ReadFromPickle(&pickle)) return true; } string16 title; std::string url; clipboard->ReadBookmark(&title, &url); if (!url.empty()) { Element element; element.is_url = true; element.url = GURL(url); element.title = title; elements.clear(); elements.push_back(element); return true; } return false; } bool BookmarkNodeData::ClipboardContainsBookmarks() { return g_browser_process->clipboard()->IsFormatAvailableByString( BookmarkNodeData::kClipboardFormatString, ui::Clipboard::BUFFER_STANDARD); } #else void BookmarkNodeData::WriteToClipboard(Profile* profile) const { bookmark_pasteboard_helper_mac::WriteToClipboard(elements, profile_path_.value()); } bool BookmarkNodeData::ReadFromClipboard() { // TODO(evan): bookmark_pasteboard_helper_mac should just use FilePaths. FilePath::StringType buf; if (!bookmark_pasteboard_helper_mac::ReadFromClipboard(elements, &buf)) return false; profile_path_ = FilePath(buf); return true; } bool BookmarkNodeData::ReadFromDragClipboard() { // TODO(evan): bookmark_pasteboard_helper_mac should just use FilePaths. FilePath::StringType buf; if (!bookmark_pasteboard_helper_mac::ReadFromDragClipboard(elements, &buf)) return false; profile_path_ = FilePath(buf); return true; } bool BookmarkNodeData::ClipboardContainsBookmarks() { return bookmark_pasteboard_helper_mac::ClipboardContainsBookmarks(); } #endif // !defined(OS_MACOSX) #if defined(TOOLKIT_VIEWS) void BookmarkNodeData::Write(Profile* profile, ui::OSExchangeData* data) const { DCHECK(data); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { if (elements[0].url.SchemeIs(chrome::kJavaScriptScheme)) { data->SetString(UTF8ToUTF16(elements[0].url.spec())); } else { data->SetURL(elements[0].url, elements[0].title); } } Pickle data_pickle; WriteToPickle(profile, &data_pickle); data->SetPickledData(GetBookmarkCustomFormat(), data_pickle); } bool BookmarkNodeData::Read(const ui::OSExchangeData& data) { elements.clear(); profile_path_.clear(); if (data.HasCustomFormat(GetBookmarkCustomFormat())) { Pickle drag_data_pickle; if (data.GetPickledData(GetBookmarkCustomFormat(), &drag_data_pickle)) { if (!ReadFromPickle(&drag_data_pickle)) return false; } } else { // See if there is a URL on the clipboard. Element element; GURL url; string16 title; if (data.GetURLAndTitle(&url, &title)) ReadFromTuple(url, title); } return is_valid(); } #endif void BookmarkNodeData::WriteToPickle(Profile* profile, Pickle* pickle) const { FilePath path = profile ? profile->GetPath() : FilePath(); path.WriteToPickle(pickle); pickle->WriteSize(elements.size()); for (size_t i = 0; i < elements.size(); ++i) elements[i].WriteToPickle(pickle); } bool BookmarkNodeData::ReadFromPickle(Pickle* pickle) { void* data_iterator = NULL; size_t element_count; if (profile_path_.ReadFromPickle(pickle, &data_iterator) && pickle->ReadSize(&data_iterator, &element_count)) { std::vector<Element> tmp_elements; tmp_elements.resize(element_count); for (size_t i = 0; i < element_count; ++i) { if (!tmp_elements[i].ReadFromPickle(pickle, &data_iterator)) { return false; } } elements.swap(tmp_elements); } return true; } std::vector<const BookmarkNode*> BookmarkNodeData::GetNodes( Profile* profile) const { std::vector<const BookmarkNode*> nodes; if (!IsFromProfile(profile)) return nodes; for (size_t i = 0; i < elements.size(); ++i) { const BookmarkNode* node = profile->GetBookmarkModel()->GetNodeByID(elements[i].id_); if (!node) { nodes.clear(); return nodes; } nodes.push_back(node); } return nodes; } const BookmarkNode* BookmarkNodeData::GetFirstNode(Profile* profile) const { std::vector<const BookmarkNode*> nodes = GetNodes(profile); return nodes.size() == 1 ? nodes[0] : NULL; } void BookmarkNodeData::Clear() { profile_path_.clear(); elements.clear(); } void BookmarkNodeData::SetOriginatingProfile(Profile* profile) { DCHECK(profile_path_.empty()); if (profile) profile_path_ = profile->GetPath(); } bool BookmarkNodeData::IsFromProfile(Profile* profile) const { // An empty path means the data is not associated with any profile. return !profile_path_.empty() && profile_path_ == profile->GetPath(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/bookmarks/bookmark_node_data.h" #include <string> #include "base/basictypes.h" #include "base/pickle.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "net/base/escape.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #if defined(OS_MACOSX) #include "chrome/browser/bookmarks/bookmark_pasteboard_helper_mac.h" #else #include "chrome/browser/browser_process.h" #endif const char* BookmarkNodeData::kClipboardFormatString = "chromium/x-bookmark-entries"; BookmarkNodeData::Element::Element() : is_url(false), id_(0) { } BookmarkNodeData::Element::Element(const BookmarkNode* node) : is_url(node->is_url()), url(node->url()), title(node->GetTitle()), id_(node->id()) { for (int i = 0; i < node->child_count(); ++i) children.push_back(Element(node->GetChild(i))); } BookmarkNodeData::Element::~Element() { } void BookmarkNodeData::Element::WriteToPickle(Pickle* pickle) const { pickle->WriteBool(is_url); pickle->WriteString(url.spec()); pickle->WriteString16(title); pickle->WriteInt64(id_); if (!is_url) { pickle->WriteSize(children.size()); for (std::vector<Element>::const_iterator i = children.begin(); i != children.end(); ++i) { i->WriteToPickle(pickle); } } } bool BookmarkNodeData::Element::ReadFromPickle(Pickle* pickle, void** iterator) { std::string url_spec; if (!pickle->ReadBool(iterator, &is_url) || !pickle->ReadString(iterator, &url_spec) || !pickle->ReadString16(iterator, &title) || !pickle->ReadInt64(iterator, &id_)) { return false; } url = GURL(url_spec); children.clear(); if (!is_url) { size_t children_count; if (!pickle->ReadSize(iterator, &children_count)) return false; children.resize(children_count); for (std::vector<Element>::iterator i = children.begin(); i != children.end(); ++i) { if (!i->ReadFromPickle(pickle, iterator)) return false; } } return true; } #if defined(TOOLKIT_VIEWS) // static ui::OSExchangeData::CustomFormat BookmarkNodeData::GetBookmarkCustomFormat() { static ui::OSExchangeData::CustomFormat format; static bool format_valid = false; if (!format_valid) { format_valid = true; format = ui::OSExchangeData::RegisterCustomFormat( BookmarkNodeData::kClipboardFormatString); } return format; } #endif BookmarkNodeData::BookmarkNodeData() { } BookmarkNodeData::BookmarkNodeData(const BookmarkNode* node) { elements.push_back(Element(node)); } BookmarkNodeData::BookmarkNodeData( const std::vector<const BookmarkNode*>& nodes) { ReadFromVector(nodes); } BookmarkNodeData::~BookmarkNodeData() { } bool BookmarkNodeData::ReadFromVector( const std::vector<const BookmarkNode*>& nodes) { Clear(); if (nodes.empty()) return false; for (size_t i = 0; i < nodes.size(); ++i) elements.push_back(Element(nodes[i])); return true; } bool BookmarkNodeData::ReadFromTuple(const GURL& url, const string16& title) { Clear(); if (!url.is_valid()) return false; Element element; element.title = title; element.url = url; element.is_url = true; elements.push_back(element); return true; } #if !defined(OS_MACOSX) void BookmarkNodeData::WriteToClipboard(Profile* profile) const { ui::ScopedClipboardWriter scw(g_browser_process->clipboard()); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { const string16& title = elements[0].title; const std::string url = elements[0].url.spec(); scw.WriteBookmark(title, url); scw.WriteHyperlink(EscapeForHTML(title), url); // Also write the URL to the clipboard as text so that it can be pasted // into text fields. We use WriteText instead of WriteURL because we don't // want to clobber the X clipboard when the user copies out of the omnibox // on Linux (on Windows and Mac, there is no difference between these // functions). scw.WriteText(UTF8ToUTF16(url)); } Pickle pickle; WriteToPickle(profile, &pickle); scw.WritePickledData(pickle, kClipboardFormatString); } bool BookmarkNodeData::ReadFromClipboard() { std::string data; ui::Clipboard* clipboard = g_browser_process->clipboard(); clipboard->ReadData(kClipboardFormatString, &data); if (!data.empty()) { Pickle pickle(data.data(), data.size()); if (ReadFromPickle(&pickle)) return true; } string16 title; std::string url; clipboard->ReadBookmark(&title, &url); if (!url.empty()) { Element element; element.is_url = true; element.url = GURL(url); element.title = title; elements.clear(); elements.push_back(element); return true; } return false; } bool BookmarkNodeData::ClipboardContainsBookmarks() { return g_browser_process->clipboard()->IsFormatAvailableByString( BookmarkNodeData::kClipboardFormatString, ui::Clipboard::BUFFER_STANDARD); } #else void BookmarkNodeData::WriteToClipboard(Profile* profile) const { bookmark_pasteboard_helper_mac::WriteToClipboard(elements, profile_path_.value()); } bool BookmarkNodeData::ReadFromClipboard() { // TODO(evan): bookmark_pasteboard_helper_mac should just use FilePaths. FilePath::StringType buf; if (!bookmark_pasteboard_helper_mac::ReadFromClipboard(elements, &buf)) return false; profile_path_ = FilePath(buf); return true; } bool BookmarkNodeData::ReadFromDragClipboard() { // TODO(evan): bookmark_pasteboard_helper_mac should just use FilePaths. FilePath::StringType buf; if (!bookmark_pasteboard_helper_mac::ReadFromDragClipboard(elements, &buf)) return false; profile_path_ = FilePath(buf); return true; } bool BookmarkNodeData::ClipboardContainsBookmarks() { return bookmark_pasteboard_helper_mac::ClipboardContainsBookmarks(); } #endif // !defined(OS_MACOSX) #if defined(TOOLKIT_VIEWS) void BookmarkNodeData::Write(Profile* profile, ui::OSExchangeData* data) const { DCHECK(data); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { if (elements[0].url.SchemeIs(chrome::kJavaScriptScheme)) { data->SetString(UTF8ToUTF16(elements[0].url.spec())); } else { data->SetURL(elements[0].url, elements[0].title); } } Pickle data_pickle; WriteToPickle(profile, &data_pickle); data->SetPickledData(GetBookmarkCustomFormat(), data_pickle); } bool BookmarkNodeData::Read(const ui::OSExchangeData& data) { elements.clear(); profile_path_.clear(); if (data.HasCustomFormat(GetBookmarkCustomFormat())) { Pickle drag_data_pickle; if (data.GetPickledData(GetBookmarkCustomFormat(), &drag_data_pickle)) { if (!ReadFromPickle(&drag_data_pickle)) return false; } } else { // See if there is a URL on the clipboard. Element element; GURL url; string16 title; if (data.GetURLAndTitle(&url, &title)) ReadFromTuple(url, title); } return is_valid(); } #endif void BookmarkNodeData::WriteToPickle(Profile* profile, Pickle* pickle) const { FilePath path = profile ? profile->GetPath() : FilePath(); path.WriteToPickle(pickle); pickle->WriteSize(elements.size()); for (size_t i = 0; i < elements.size(); ++i) elements[i].WriteToPickle(pickle); } bool BookmarkNodeData::ReadFromPickle(Pickle* pickle) { void* data_iterator = NULL; size_t element_count; if (profile_path_.ReadFromPickle(pickle, &data_iterator) && pickle->ReadSize(&data_iterator, &element_count)) { std::vector<Element> tmp_elements; tmp_elements.resize(element_count); for (size_t i = 0; i < element_count; ++i) { if (!tmp_elements[i].ReadFromPickle(pickle, &data_iterator)) { return false; } } elements.swap(tmp_elements); } return true; } std::vector<const BookmarkNode*> BookmarkNodeData::GetNodes( Profile* profile) const { std::vector<const BookmarkNode*> nodes; if (!IsFromProfile(profile)) return nodes; for (size_t i = 0; i < elements.size(); ++i) { const BookmarkNode* node = profile->GetBookmarkModel()->GetNodeByID(elements[i].id_); if (!node) { nodes.clear(); return nodes; } nodes.push_back(node); } return nodes; } const BookmarkNode* BookmarkNodeData::GetFirstNode(Profile* profile) const { std::vector<const BookmarkNode*> nodes = GetNodes(profile); return nodes.size() == 1 ? nodes[0] : NULL; } void BookmarkNodeData::Clear() { profile_path_.clear(); elements.clear(); } void BookmarkNodeData::SetOriginatingProfile(Profile* profile) { DCHECK(profile_path_.empty()); if (profile) profile_path_ = profile->GetPath(); } bool BookmarkNodeData::IsFromProfile(Profile* profile) const { // An empty path means the data is not associated with any profile. return !profile_path_.empty() && profile_path_ == profile->GetPath(); } <commit_msg>Disable clipboard for bookmarks in TOUCH_UI builds<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/bookmarks/bookmark_node_data.h" #include <string> #include "base/basictypes.h" #include "base/pickle.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "net/base/escape.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #if defined(OS_MACOSX) #include "chrome/browser/bookmarks/bookmark_pasteboard_helper_mac.h" #else #include "chrome/browser/browser_process.h" #endif const char* BookmarkNodeData::kClipboardFormatString = "chromium/x-bookmark-entries"; BookmarkNodeData::Element::Element() : is_url(false), id_(0) { } BookmarkNodeData::Element::Element(const BookmarkNode* node) : is_url(node->is_url()), url(node->url()), title(node->GetTitle()), id_(node->id()) { for (int i = 0; i < node->child_count(); ++i) children.push_back(Element(node->GetChild(i))); } BookmarkNodeData::Element::~Element() { } void BookmarkNodeData::Element::WriteToPickle(Pickle* pickle) const { pickle->WriteBool(is_url); pickle->WriteString(url.spec()); pickle->WriteString16(title); pickle->WriteInt64(id_); if (!is_url) { pickle->WriteSize(children.size()); for (std::vector<Element>::const_iterator i = children.begin(); i != children.end(); ++i) { i->WriteToPickle(pickle); } } } bool BookmarkNodeData::Element::ReadFromPickle(Pickle* pickle, void** iterator) { std::string url_spec; if (!pickle->ReadBool(iterator, &is_url) || !pickle->ReadString(iterator, &url_spec) || !pickle->ReadString16(iterator, &title) || !pickle->ReadInt64(iterator, &id_)) { return false; } url = GURL(url_spec); children.clear(); if (!is_url) { size_t children_count; if (!pickle->ReadSize(iterator, &children_count)) return false; children.resize(children_count); for (std::vector<Element>::iterator i = children.begin(); i != children.end(); ++i) { if (!i->ReadFromPickle(pickle, iterator)) return false; } } return true; } #if defined(TOOLKIT_VIEWS) // static ui::OSExchangeData::CustomFormat BookmarkNodeData::GetBookmarkCustomFormat() { static ui::OSExchangeData::CustomFormat format; static bool format_valid = false; if (!format_valid) { format_valid = true; format = ui::OSExchangeData::RegisterCustomFormat( BookmarkNodeData::kClipboardFormatString); } return format; } #endif BookmarkNodeData::BookmarkNodeData() { } BookmarkNodeData::BookmarkNodeData(const BookmarkNode* node) { elements.push_back(Element(node)); } BookmarkNodeData::BookmarkNodeData( const std::vector<const BookmarkNode*>& nodes) { ReadFromVector(nodes); } BookmarkNodeData::~BookmarkNodeData() { } bool BookmarkNodeData::ReadFromVector( const std::vector<const BookmarkNode*>& nodes) { Clear(); if (nodes.empty()) return false; for (size_t i = 0; i < nodes.size(); ++i) elements.push_back(Element(nodes[i])); return true; } bool BookmarkNodeData::ReadFromTuple(const GURL& url, const string16& title) { Clear(); if (!url.is_valid()) return false; Element element; element.title = title; element.url = url; element.is_url = true; elements.push_back(element); return true; } #if !defined(OS_MACOSX) void BookmarkNodeData::WriteToClipboard(Profile* profile) const { ui::ScopedClipboardWriter scw(g_browser_process->clipboard()); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { const string16& title = elements[0].title; const std::string url = elements[0].url.spec(); scw.WriteBookmark(title, url); scw.WriteHyperlink(EscapeForHTML(title), url); // Also write the URL to the clipboard as text so that it can be pasted // into text fields. We use WriteText instead of WriteURL because we don't // want to clobber the X clipboard when the user copies out of the omnibox // on Linux (on Windows and Mac, there is no difference between these // functions). scw.WriteText(UTF8ToUTF16(url)); } Pickle pickle; WriteToPickle(profile, &pickle); scw.WritePickledData(pickle, kClipboardFormatString); } bool BookmarkNodeData::ReadFromClipboard() { std::string data; ui::Clipboard* clipboard = g_browser_process->clipboard(); clipboard->ReadData(kClipboardFormatString, &data); if (!data.empty()) { Pickle pickle(data.data(), data.size()); if (ReadFromPickle(&pickle)) return true; } string16 title; std::string url; clipboard->ReadBookmark(&title, &url); if (!url.empty()) { Element element; element.is_url = true; element.url = GURL(url); element.title = title; elements.clear(); elements.push_back(element); return true; } return false; } bool BookmarkNodeData::ClipboardContainsBookmarks() { #if defined(TOUCH_UI) // Temporarily disabling clipboard due to bug 96448. // TODO(wyck): Reenable when cause of message loop hang in // gtk_clipboard_wait_for_contents is determined and fixed. return false; #else return g_browser_process->clipboard()->IsFormatAvailableByString( BookmarkNodeData::kClipboardFormatString, ui::Clipboard::BUFFER_STANDARD); #endif } #else void BookmarkNodeData::WriteToClipboard(Profile* profile) const { bookmark_pasteboard_helper_mac::WriteToClipboard(elements, profile_path_.value()); } bool BookmarkNodeData::ReadFromClipboard() { // TODO(evan): bookmark_pasteboard_helper_mac should just use FilePaths. FilePath::StringType buf; if (!bookmark_pasteboard_helper_mac::ReadFromClipboard(elements, &buf)) return false; profile_path_ = FilePath(buf); return true; } bool BookmarkNodeData::ReadFromDragClipboard() { // TODO(evan): bookmark_pasteboard_helper_mac should just use FilePaths. FilePath::StringType buf; if (!bookmark_pasteboard_helper_mac::ReadFromDragClipboard(elements, &buf)) return false; profile_path_ = FilePath(buf); return true; } bool BookmarkNodeData::ClipboardContainsBookmarks() { return bookmark_pasteboard_helper_mac::ClipboardContainsBookmarks(); } #endif // !defined(OS_MACOSX) #if defined(TOOLKIT_VIEWS) void BookmarkNodeData::Write(Profile* profile, ui::OSExchangeData* data) const { DCHECK(data); // If there is only one element and it is a URL, write the URL to the // clipboard. if (elements.size() == 1 && elements[0].is_url) { if (elements[0].url.SchemeIs(chrome::kJavaScriptScheme)) { data->SetString(UTF8ToUTF16(elements[0].url.spec())); } else { data->SetURL(elements[0].url, elements[0].title); } } Pickle data_pickle; WriteToPickle(profile, &data_pickle); data->SetPickledData(GetBookmarkCustomFormat(), data_pickle); } bool BookmarkNodeData::Read(const ui::OSExchangeData& data) { elements.clear(); profile_path_.clear(); if (data.HasCustomFormat(GetBookmarkCustomFormat())) { Pickle drag_data_pickle; if (data.GetPickledData(GetBookmarkCustomFormat(), &drag_data_pickle)) { if (!ReadFromPickle(&drag_data_pickle)) return false; } } else { // See if there is a URL on the clipboard. Element element; GURL url; string16 title; if (data.GetURLAndTitle(&url, &title)) ReadFromTuple(url, title); } return is_valid(); } #endif void BookmarkNodeData::WriteToPickle(Profile* profile, Pickle* pickle) const { FilePath path = profile ? profile->GetPath() : FilePath(); path.WriteToPickle(pickle); pickle->WriteSize(elements.size()); for (size_t i = 0; i < elements.size(); ++i) elements[i].WriteToPickle(pickle); } bool BookmarkNodeData::ReadFromPickle(Pickle* pickle) { void* data_iterator = NULL; size_t element_count; if (profile_path_.ReadFromPickle(pickle, &data_iterator) && pickle->ReadSize(&data_iterator, &element_count)) { std::vector<Element> tmp_elements; tmp_elements.resize(element_count); for (size_t i = 0; i < element_count; ++i) { if (!tmp_elements[i].ReadFromPickle(pickle, &data_iterator)) { return false; } } elements.swap(tmp_elements); } return true; } std::vector<const BookmarkNode*> BookmarkNodeData::GetNodes( Profile* profile) const { std::vector<const BookmarkNode*> nodes; if (!IsFromProfile(profile)) return nodes; for (size_t i = 0; i < elements.size(); ++i) { const BookmarkNode* node = profile->GetBookmarkModel()->GetNodeByID(elements[i].id_); if (!node) { nodes.clear(); return nodes; } nodes.push_back(node); } return nodes; } const BookmarkNode* BookmarkNodeData::GetFirstNode(Profile* profile) const { std::vector<const BookmarkNode*> nodes = GetNodes(profile); return nodes.size() == 1 ? nodes[0] : NULL; } void BookmarkNodeData::Clear() { profile_path_.clear(); elements.clear(); } void BookmarkNodeData::SetOriginatingProfile(Profile* profile) { DCHECK(profile_path_.empty()); if (profile) profile_path_ = profile->GetPath(); } bool BookmarkNodeData::IsFromProfile(Profile* profile) const { // An empty path means the data is not associated with any profile. return !profile_path_.empty() && profile_path_ == profile->GetPath(); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/new_user_view.h" #include <signal.h> #include <sys/types.h> #include <algorithm> #include <vector> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/callback.h" #include "base/command_line.h" #include "base/keyboard_codes.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/utf_string_conversions.h" #include "base/string_util.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/login/helper.h" #include "chrome/browser/chromeos/login/rounded_rect_painter.h" #include "chrome/browser/google_util.h" #include "grit/generated_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/label.h" #include "views/controls/throbber.h" #include "views/widget/widget_gtk.h" using views::Label; using views::Textfield; using views::View; using views::WidgetGtk; namespace { const int kTextfieldWidth = 286; const int kRowPad = 7; const int kColumnPad = 7; const int kLanguagesMenuWidth = 200; const int kLanguagesMenuHeight = 30; const SkColor kErrorColor = 0xFF8F384F; const char kDefaultDomain[] = "@gmail.com"; const char kAccountRecoveryHelpUrl[] = "http://www.google.com/support/accounts/bin/answer.py?answer=48598"; } // namespace namespace chromeos { NewUserView::NewUserView(Delegate* delegate, bool need_border) : username_field_(NULL), password_field_(NULL), title_label_(NULL), sign_in_button_(NULL), create_account_link_(NULL), cant_access_account_link_(NULL), browse_without_signin_link_(NULL), languages_menubutton_(NULL), throbber_(NULL), accel_focus_user_(views::Accelerator(base::VKEY_U, false, false, true)), accel_focus_pass_(views::Accelerator(base::VKEY_P, false, false, true)), delegate_(delegate), ALLOW_THIS_IN_INITIALIZER_LIST(focus_grabber_factory_(this)), focus_delayed_(false), login_in_process_(false), need_border_(need_border) { } NewUserView::~NewUserView() { } void NewUserView::Init() { if (need_border_) { // Use rounded rect background. set_border(CreateWizardBorder(&BorderDefinition::kScreenBorder)); views::Painter* painter = CreateWizardPainter( &BorderDefinition::kScreenBorder); set_background(views::Background::CreateBackgroundPainter(true, painter)); } else { set_background(views::Background::CreateSolidBackground( BorderDefinition::kScreenBorder.top_color)); } // Set up fonts. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); gfx::Font title_font = rb.GetFont(ResourceBundle::MediumBoldFont); title_label_ = new views::Label(); title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); title_label_->SetFont(title_font); title_label_->SetMultiLine(true); AddChildView(title_label_); username_field_ = new views::Textfield; AddChildView(username_field_); password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD); AddChildView(password_field_); throbber_ = CreateDefaultSmoothedThrobber(); AddChildView(throbber_); InitLink(&create_account_link_); InitLink(&cant_access_account_link_); InitLink(&browse_without_signin_link_); language_switch_model_.InitLanguageMenu(); languages_menubutton_ = new views::MenuButton( NULL, std::wstring(), &language_switch_model_, true); AddChildView(languages_menubutton_); AddAccelerator(accel_focus_user_); AddAccelerator(accel_focus_pass_); UpdateLocalizedStrings(); RequestFocus(); // Controller to handle events from textfields username_field_->SetController(this); password_field_->SetController(this); if (!CrosLibrary::Get()->EnsureLoaded()) { EnableInputControls(false); } } bool NewUserView::AcceleratorPressed(const views::Accelerator& accelerator) { if (accelerator == accel_focus_user_) { username_field_->RequestFocus(); return true; } if (accelerator == accel_focus_pass_) { password_field_->RequestFocus(); return true; } return false; } void NewUserView::RecreateNativeControls() { // There is no way to get native button preferred size after the button was // sized so delete and recreate the button on text update. delete sign_in_button_; sign_in_button_ = new views::NativeButton(this, std::wstring()); AddChildView(sign_in_button_); if (!CrosLibrary::Get()->EnsureLoaded()) sign_in_button_->SetEnabled(false); } void NewUserView::UpdateLocalizedStrings() { RecreateNativeControls(); title_label_->SetText(l10n_util::GetString(IDS_LOGIN_TITLE)); username_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_USERNAME)); password_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_PASSWORD)); sign_in_button_->SetLabel(l10n_util::GetString(IDS_LOGIN_BUTTON)); create_account_link_->SetText( l10n_util::GetString(IDS_CREATE_ACCOUNT_BUTTON)); cant_access_account_link_->SetText( l10n_util::GetString(IDS_CANT_ACCESS_ACCOUNT_BUTTON)); browse_without_signin_link_->SetText( l10n_util::GetString(IDS_BROWSE_WITHOUT_SIGNING_IN_BUTTON)); delegate_->ClearErrors(); languages_menubutton_->SetText(language_switch_model_.GetCurrentLocaleName()); } void NewUserView::LocaleChanged() { UpdateLocalizedStrings(); Layout(); SchedulePaint(); } void NewUserView::RequestFocus() { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &NewUserView::FocusFirstField)); } void NewUserView::ViewHierarchyChanged(bool is_add, View *parent, View *child) { if (is_add && child == this) { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &NewUserView::FocusFirstField)); } } void NewUserView::NativeViewHierarchyChanged(bool attached, gfx::NativeView native_view, views::RootView* root_view) { if (focus_delayed_ && attached) { focus_delayed_ = false; MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &NewUserView::FocusFirstField)); } } void NewUserView::FocusFirstField() { if (GetFocusManager()) { if (username_field_->text().empty()) username_field_->RequestFocus(); else password_field_->RequestFocus(); } else { // We are invisible - delay until it is no longer the case. focus_delayed_ = true; } } // Sets the bounds of the view, using x and y as the origin. // The width is determined by the min of width and the preferred size // of the view, unless force_width is true in which case it is always used. // The height is gotten from the preferred size and returned. static int setViewBounds( views::View* view, int x, int y, int width, bool force_width) { gfx::Size pref_size = view->GetPreferredSize(); if (!force_width) { if (pref_size.width() < width) { width = pref_size.width(); } } int height = pref_size.height(); view->SetBounds(x, y, width, height); return height; } void NewUserView::Layout() { gfx::Insets insets = GetInsets(); // Place language selection in top right corner. int x = std::max(0, this->width() - insets.right() - kLanguagesMenuWidth - kColumnPad); int y = insets.top() + kRowPad; int width = std::min(this->width() - insets.width() - 2 * kColumnPad, kLanguagesMenuWidth); int height = kLanguagesMenuHeight; languages_menubutton_->SetBounds(x, y, width, height); width = std::min(this->width() - insets.width() - 2 * kColumnPad, kTextfieldWidth); x = (this->width() - width) / 2; int max_width = this->width() - x - insets.right(); title_label_->SizeToFit(max_width); height = title_label_->GetPreferredSize().height() + username_field_->GetPreferredSize().height() + password_field_->GetPreferredSize().height() + sign_in_button_->GetPreferredSize().height() + create_account_link_->GetPreferredSize().height() + cant_access_account_link_->GetPreferredSize().height() + browse_without_signin_link_->GetPreferredSize().height() + 4 * kRowPad; y = (this->height() - height) / 2; y += (setViewBounds(title_label_, x, y, max_width, false) + kRowPad); y += (setViewBounds(username_field_, x, y, width, true) + kRowPad); y += (setViewBounds(password_field_, x, y, width, true) + kRowPad); int throbber_y = y; y += (setViewBounds(sign_in_button_, x, y, width, false) + kRowPad); setViewBounds(throbber_, x + width - throbber_->GetPreferredSize().width(), throbber_y + (sign_in_button_->GetPreferredSize().height() - throbber_->GetPreferredSize().height()) / 2, width, false); y += setViewBounds(create_account_link_, x, y, max_width, false); y += setViewBounds(cant_access_account_link_, x, y, max_width, false); y += setViewBounds(browse_without_signin_link_, x, y, max_width, false); SchedulePaint(); } gfx::Size NewUserView::GetPreferredSize() { return gfx::Size(width(), height()); } views::View* NewUserView::GetContentsView() { return this; } void NewUserView::SetUsername(const std::string& username) { username_field_->SetText(UTF8ToUTF16(username)); } void NewUserView::SetPassword(const std::string& password) { password_field_->SetText(UTF8ToUTF16(password)); } void NewUserView::Login() { if (login_in_process_ || username_field_->text().empty()) return; throbber_->Start(); login_in_process_ = true; EnableInputControls(false); std::string username = UTF16ToUTF8(username_field_->text()); // todo(cmasone) Need to sanitize memory used to store password. std::string password = UTF16ToUTF8(password_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } delegate_->OnLogin(username, password); } // Sign in button causes a login attempt. void NewUserView::ButtonPressed( views::Button* sender, const views::Event& event) { DCHECK(sender == sign_in_button_); Login(); } void NewUserView::LinkActivated(views::Link* source, int event_flags) { if (source == create_account_link_) { delegate_->OnCreateAccount(); } else if (source == browse_without_signin_link_) { delegate_->OnLoginOffTheRecord(); } else if (source == cant_access_account_link_) { // TODO(nkostylev): Display offline help when network is not connected. // http://crosbug.com/3874 dialog_.reset(new LoginHtmlDialog( this, GetNativeWindow(), l10n_util::GetString(IDS_LOGIN_OOBE_HELP_DIALOG_TITLE), google_util::AppendGoogleLocaleParam(GURL(kAccountRecoveryHelpUrl)))); dialog_->Show(); } } void NewUserView::ClearAndEnablePassword() { login_in_process_ = false; EnableInputControls(true); SetPassword(std::string()); password_field_->RequestFocus(); throbber_->Stop(); } gfx::Rect NewUserView::GetPasswordBounds() const { gfx::Rect screen_bounds(password_field_->bounds()); gfx::Point origin(screen_bounds.origin()); views::View::ConvertPointToScreen(password_field_->GetParent(), &origin); screen_bounds.set_origin(origin); return screen_bounds; } void NewUserView::StopThrobber() { throbber_->Stop(); } gfx::NativeWindow NewUserView::GetNativeWindow() const { return GTK_WINDOW(static_cast<WidgetGtk*>(GetWidget())->GetNativeView()); } bool NewUserView::HandleKeystroke(views::Textfield* s, const views::Textfield::Keystroke& keystroke) { if (!CrosLibrary::Get()->EnsureLoaded() || login_in_process_) return false; if (keystroke.GetKeyboardCode() == base::VKEY_TAB) { if (username_field_->text().length() != 0) { std::string username = UTF16ToUTF8(username_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } return false; } } else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) { Login(); // Return true so that processing ends return true; } else { delegate_->ClearErrors(); return false; } // Return false so that processing does not end return false; } void NewUserView::EnableInputControls(bool enabled) { username_field_->SetEnabled(enabled); password_field_->SetEnabled(enabled); sign_in_button_->SetEnabled(enabled); create_account_link_->SetEnabled(enabled); cant_access_account_link_->SetEnabled(enabled); browse_without_signin_link_->SetEnabled(enabled); } void NewUserView::InitLink(views::Link** link) { *link = new views::Link(std::wstring()); (*link)->SetController(this); AddChildView(*link); } } // namespace chromeos <commit_msg>Disable language menu during sign in process.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/new_user_view.h" #include <signal.h> #include <sys/types.h> #include <algorithm> #include <vector> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/callback.h" #include "base/command_line.h" #include "base/keyboard_codes.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/utf_string_conversions.h" #include "base/string_util.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/login/helper.h" #include "chrome/browser/chromeos/login/rounded_rect_painter.h" #include "chrome/browser/google_util.h" #include "grit/generated_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/label.h" #include "views/controls/throbber.h" #include "views/widget/widget_gtk.h" using views::Label; using views::Textfield; using views::View; using views::WidgetGtk; namespace { const int kTextfieldWidth = 286; const int kRowPad = 7; const int kColumnPad = 7; const int kLanguagesMenuWidth = 200; const int kLanguagesMenuHeight = 30; const SkColor kErrorColor = 0xFF8F384F; const char kDefaultDomain[] = "@gmail.com"; const char kAccountRecoveryHelpUrl[] = "http://www.google.com/support/accounts/bin/answer.py?answer=48598"; } // namespace namespace chromeos { NewUserView::NewUserView(Delegate* delegate, bool need_border) : username_field_(NULL), password_field_(NULL), title_label_(NULL), sign_in_button_(NULL), create_account_link_(NULL), cant_access_account_link_(NULL), browse_without_signin_link_(NULL), languages_menubutton_(NULL), throbber_(NULL), accel_focus_user_(views::Accelerator(base::VKEY_U, false, false, true)), accel_focus_pass_(views::Accelerator(base::VKEY_P, false, false, true)), delegate_(delegate), ALLOW_THIS_IN_INITIALIZER_LIST(focus_grabber_factory_(this)), focus_delayed_(false), login_in_process_(false), need_border_(need_border) { } NewUserView::~NewUserView() { } void NewUserView::Init() { if (need_border_) { // Use rounded rect background. set_border(CreateWizardBorder(&BorderDefinition::kScreenBorder)); views::Painter* painter = CreateWizardPainter( &BorderDefinition::kScreenBorder); set_background(views::Background::CreateBackgroundPainter(true, painter)); } else { set_background(views::Background::CreateSolidBackground( BorderDefinition::kScreenBorder.top_color)); } // Set up fonts. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); gfx::Font title_font = rb.GetFont(ResourceBundle::MediumBoldFont); title_label_ = new views::Label(); title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); title_label_->SetFont(title_font); title_label_->SetMultiLine(true); AddChildView(title_label_); username_field_ = new views::Textfield; AddChildView(username_field_); password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD); AddChildView(password_field_); throbber_ = CreateDefaultSmoothedThrobber(); AddChildView(throbber_); InitLink(&create_account_link_); InitLink(&cant_access_account_link_); InitLink(&browse_without_signin_link_); language_switch_model_.InitLanguageMenu(); languages_menubutton_ = new views::MenuButton( NULL, std::wstring(), &language_switch_model_, true); AddChildView(languages_menubutton_); AddAccelerator(accel_focus_user_); AddAccelerator(accel_focus_pass_); UpdateLocalizedStrings(); RequestFocus(); // Controller to handle events from textfields username_field_->SetController(this); password_field_->SetController(this); if (!CrosLibrary::Get()->EnsureLoaded()) { EnableInputControls(false); } } bool NewUserView::AcceleratorPressed(const views::Accelerator& accelerator) { if (accelerator == accel_focus_user_) { username_field_->RequestFocus(); return true; } if (accelerator == accel_focus_pass_) { password_field_->RequestFocus(); return true; } return false; } void NewUserView::RecreateNativeControls() { // There is no way to get native button preferred size after the button was // sized so delete and recreate the button on text update. delete sign_in_button_; sign_in_button_ = new views::NativeButton(this, std::wstring()); AddChildView(sign_in_button_); if (!CrosLibrary::Get()->EnsureLoaded()) sign_in_button_->SetEnabled(false); } void NewUserView::UpdateLocalizedStrings() { RecreateNativeControls(); title_label_->SetText(l10n_util::GetString(IDS_LOGIN_TITLE)); username_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_USERNAME)); password_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_PASSWORD)); sign_in_button_->SetLabel(l10n_util::GetString(IDS_LOGIN_BUTTON)); create_account_link_->SetText( l10n_util::GetString(IDS_CREATE_ACCOUNT_BUTTON)); cant_access_account_link_->SetText( l10n_util::GetString(IDS_CANT_ACCESS_ACCOUNT_BUTTON)); browse_without_signin_link_->SetText( l10n_util::GetString(IDS_BROWSE_WITHOUT_SIGNING_IN_BUTTON)); delegate_->ClearErrors(); languages_menubutton_->SetText(language_switch_model_.GetCurrentLocaleName()); } void NewUserView::LocaleChanged() { UpdateLocalizedStrings(); Layout(); SchedulePaint(); } void NewUserView::RequestFocus() { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &NewUserView::FocusFirstField)); } void NewUserView::ViewHierarchyChanged(bool is_add, View *parent, View *child) { if (is_add && child == this) { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &NewUserView::FocusFirstField)); } } void NewUserView::NativeViewHierarchyChanged(bool attached, gfx::NativeView native_view, views::RootView* root_view) { if (focus_delayed_ && attached) { focus_delayed_ = false; MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &NewUserView::FocusFirstField)); } } void NewUserView::FocusFirstField() { if (GetFocusManager()) { if (username_field_->text().empty()) username_field_->RequestFocus(); else password_field_->RequestFocus(); } else { // We are invisible - delay until it is no longer the case. focus_delayed_ = true; } } // Sets the bounds of the view, using x and y as the origin. // The width is determined by the min of width and the preferred size // of the view, unless force_width is true in which case it is always used. // The height is gotten from the preferred size and returned. static int setViewBounds( views::View* view, int x, int y, int width, bool force_width) { gfx::Size pref_size = view->GetPreferredSize(); if (!force_width) { if (pref_size.width() < width) { width = pref_size.width(); } } int height = pref_size.height(); view->SetBounds(x, y, width, height); return height; } void NewUserView::Layout() { gfx::Insets insets = GetInsets(); // Place language selection in top right corner. int x = std::max(0, this->width() - insets.right() - kLanguagesMenuWidth - kColumnPad); int y = insets.top() + kRowPad; int width = std::min(this->width() - insets.width() - 2 * kColumnPad, kLanguagesMenuWidth); int height = kLanguagesMenuHeight; languages_menubutton_->SetBounds(x, y, width, height); width = std::min(this->width() - insets.width() - 2 * kColumnPad, kTextfieldWidth); x = (this->width() - width) / 2; int max_width = this->width() - x - insets.right(); title_label_->SizeToFit(max_width); height = title_label_->GetPreferredSize().height() + username_field_->GetPreferredSize().height() + password_field_->GetPreferredSize().height() + sign_in_button_->GetPreferredSize().height() + create_account_link_->GetPreferredSize().height() + cant_access_account_link_->GetPreferredSize().height() + browse_without_signin_link_->GetPreferredSize().height() + 4 * kRowPad; y = (this->height() - height) / 2; y += (setViewBounds(title_label_, x, y, max_width, false) + kRowPad); y += (setViewBounds(username_field_, x, y, width, true) + kRowPad); y += (setViewBounds(password_field_, x, y, width, true) + kRowPad); int throbber_y = y; y += (setViewBounds(sign_in_button_, x, y, width, false) + kRowPad); setViewBounds(throbber_, x + width - throbber_->GetPreferredSize().width(), throbber_y + (sign_in_button_->GetPreferredSize().height() - throbber_->GetPreferredSize().height()) / 2, width, false); y += setViewBounds(create_account_link_, x, y, max_width, false); y += setViewBounds(cant_access_account_link_, x, y, max_width, false); y += setViewBounds(browse_without_signin_link_, x, y, max_width, false); SchedulePaint(); } gfx::Size NewUserView::GetPreferredSize() { return gfx::Size(width(), height()); } views::View* NewUserView::GetContentsView() { return this; } void NewUserView::SetUsername(const std::string& username) { username_field_->SetText(UTF8ToUTF16(username)); } void NewUserView::SetPassword(const std::string& password) { password_field_->SetText(UTF8ToUTF16(password)); } void NewUserView::Login() { if (login_in_process_ || username_field_->text().empty()) return; throbber_->Start(); login_in_process_ = true; EnableInputControls(false); std::string username = UTF16ToUTF8(username_field_->text()); // todo(cmasone) Need to sanitize memory used to store password. std::string password = UTF16ToUTF8(password_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } delegate_->OnLogin(username, password); } // Sign in button causes a login attempt. void NewUserView::ButtonPressed( views::Button* sender, const views::Event& event) { DCHECK(sender == sign_in_button_); Login(); } void NewUserView::LinkActivated(views::Link* source, int event_flags) { if (source == create_account_link_) { delegate_->OnCreateAccount(); } else if (source == browse_without_signin_link_) { delegate_->OnLoginOffTheRecord(); } else if (source == cant_access_account_link_) { // TODO(nkostylev): Display offline help when network is not connected. // http://crosbug.com/3874 dialog_.reset(new LoginHtmlDialog( this, GetNativeWindow(), l10n_util::GetString(IDS_LOGIN_OOBE_HELP_DIALOG_TITLE), google_util::AppendGoogleLocaleParam(GURL(kAccountRecoveryHelpUrl)))); dialog_->Show(); } } void NewUserView::ClearAndEnablePassword() { login_in_process_ = false; EnableInputControls(true); SetPassword(std::string()); password_field_->RequestFocus(); throbber_->Stop(); } gfx::Rect NewUserView::GetPasswordBounds() const { gfx::Rect screen_bounds(password_field_->bounds()); gfx::Point origin(screen_bounds.origin()); views::View::ConvertPointToScreen(password_field_->GetParent(), &origin); screen_bounds.set_origin(origin); return screen_bounds; } void NewUserView::StopThrobber() { throbber_->Stop(); } gfx::NativeWindow NewUserView::GetNativeWindow() const { return GTK_WINDOW(static_cast<WidgetGtk*>(GetWidget())->GetNativeView()); } bool NewUserView::HandleKeystroke(views::Textfield* s, const views::Textfield::Keystroke& keystroke) { if (!CrosLibrary::Get()->EnsureLoaded() || login_in_process_) return false; if (keystroke.GetKeyboardCode() == base::VKEY_TAB) { if (username_field_->text().length() != 0) { std::string username = UTF16ToUTF8(username_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } return false; } } else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) { Login(); // Return true so that processing ends return true; } else { delegate_->ClearErrors(); return false; } // Return false so that processing does not end return false; } void NewUserView::EnableInputControls(bool enabled) { languages_menubutton_->SetEnabled(enabled); username_field_->SetEnabled(enabled); password_field_->SetEnabled(enabled); sign_in_button_->SetEnabled(enabled); create_account_link_->SetEnabled(enabled); cant_access_account_link_->SetEnabled(enabled); browse_without_signin_link_->SetEnabled(enabled); } void NewUserView::InitLink(views::Link** link) { *link = new views::Link(std::wstring()); (*link)->SetController(this); AddChildView(*link); } } // namespace chromeos <|endoftext|>
<commit_before><commit_msg>The focus ring was not shown on Linux toolkit views. This is because on the renderer side the ring color was set to a value received from the browser, but on Linux toolkit view we are not initializing that value in the browser (just like we do on Windows, we keep the default WebKit value). So it would be 0, and the rings would not be shown.<commit_after><|endoftext|>
<commit_before> #ifndef __EIRODS_HASH_HPP__ #define __EIRODS_HASH_HPP__ // =-=-=-=-=-=-=- // hash_map include #ifdef _WIN32 #include <hash_map> #include <windows.h> using namespace stdext; #else #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) #if GCC_VERSION > 40200 // JMC - older compilers do not handle -std=c++0X very well so // using unordered_map will require more effort // #include <unordered_map> //#define EIRODS_HASH_TYPE std::unordered_map #include <backward/hash_map> #define EIRODS_HASH_TYPE __gnu_cxx::hash_map #else #include <ext/hash_map> #define EIRODS_HASH_TYPE __gnu_cxx::hash_map #endif using namespace __gnu_cxx; #endif #include <string.h> #include <string> namespace eirods { struct eirods_char_str_hash { enum { // parameters for hash table bucket_size = 4, // 0 < bucket_size min_buckets = 8 }; // min_buckets = 2 ^^ N, 0 < N size_t operator()(const char *s1) const { // hash string s1 to size_t value const unsigned char *p = (const unsigned char *)s1; size_t hashval = 0; while (*p != '\0') hashval = 31 * hashval + (*p++); // or whatever return (hashval); } bool operator()(const char* s1, const char* s2 ) const { return ( strcmp( s1, s2 ) < 0 ); } }; // struct eirods_char_str_hash struct eirods_string_hash { enum { // parameters for hash table bucket_size = 4, // 0 < bucket_size min_buckets = 8 }; // min_buckets = 2 ^^ N, 0 < N size_t operator()(const std::string s1) const { // hash string s1 to size_t value const unsigned char *p = (const unsigned char *)s1.c_str(); size_t hashval = 0; while (*p != '\0') hashval = 31 * hashval + (*p++); // or whatever return (hashval); } bool operator()(const std::string s1, const std::string s2 ) const { return ( s1 < s2 ); } }; // struct eirods_string_hash }; // namespace eirods #endif // __EIRODS_HASH_HPP__ <commit_msg>[#785] move to boost::unordered_map for our lookup table until such time as we can move to std::unordered_map<commit_after> #ifndef __EIRODS_HASH_HPP__ #define __EIRODS_HASH_HPP__ // =-=-=-=-=-=-=- // hash_map include #include <boost/unordered_map.hpp> #define EIRODS_HASH_TYPE boost::unordered_map #include <string.h> #include <string> namespace eirods { struct eirods_char_str_hash { enum { // parameters for hash table bucket_size = 4, // 0 < bucket_size min_buckets = 8 }; // min_buckets = 2 ^^ N, 0 < N size_t operator()(const char *s1) const { // hash string s1 to size_t value const unsigned char *p = (const unsigned char *)s1; size_t hashval = 0; while (*p != '\0') hashval = 31 * hashval + (*p++); // or whatever return (hashval); } bool operator()(const char* s1, const char* s2 ) const { return ( strcmp( s1, s2 ) < 0 ); } }; // struct eirods_char_str_hash struct eirods_string_hash { enum { // parameters for hash table bucket_size = 4, // 0 < bucket_size min_buckets = 8 }; // min_buckets = 2 ^^ N, 0 < N size_t operator()(const std::string s1) const { // hash string s1 to size_t value const unsigned char *p = (const unsigned char *)s1.c_str(); size_t hashval = 0; while (*p != '\0') hashval = 31 * hashval + (*p++); // or whatever return (hashval); } bool operator()(const std::string s1, const std::string s2 ) const { return ( s1 < s2 ); } }; // struct eirods_string_hash }; // namespace eirods #endif // __EIRODS_HASH_HPP__ <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); #if defined(OS_WIN) std::wstring pepper_plugin = plugin_lib.value(); #else std::wstring pepper_plugin = UTF8ToWide(plugin_lib.value()); #endif pepper_plugin.append(L";application/x-ppapi-tests"); launch_arguments_.AppendSwitchWithValue(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { const wchar_t kDocRoot[] = L"third_party/ppapi/tests"; scoped_refptr<HTTPTestServer> server( HTTPTestServer::CreateServer(kDocRoot)); ASSERT_TRUE(server); RunTestURL(server->TestServerPage("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_DeviceContext2D) { #else TEST_F(PPAPITest, DeviceContext2D) { #endif RunTest("DeviceContext2D"); } #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_ImageData) { #else TEST_F(PPAPITest, ImageData) { #endif RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } TEST_F(PPAPITest, URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_F(PPAPITest, PaintAgggregator) { RunTestViaHTTP("PaintAggregator"); } #if defined(OS_LINUX) // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { #else TEST_F(PPAPITest, Scrollbar) { #endif RunTest("Scrollbar"); } <commit_msg>Enable more PPAPI tests.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); #if defined(OS_WIN) std::wstring pepper_plugin = plugin_lib.value(); #else std::wstring pepper_plugin = UTF8ToWide(plugin_lib.value()); #endif pepper_plugin.append(L";application/x-ppapi-tests"); launch_arguments_.AppendSwitchWithValue(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { const wchar_t kDocRoot[] = L"third_party/ppapi/tests"; scoped_refptr<HTTPTestServer> server( HTTPTestServer::CreateServer(kDocRoot)); ASSERT_TRUE(server); RunTestURL(server->TestServerPage("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, DeviceContext2D) { RunTest("DeviceContext2D"); } TEST_F(PPAPITest, ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } TEST_F(PPAPITest, URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_F(PPAPITest, PaintAgggregator) { RunTestViaHTTP("PaintAggregator"); } #if defined(OS_LINUX) // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { #else TEST_F(PPAPITest, Scrollbar) { #endif RunTest("Scrollbar"); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL(test_server.GetURL("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } TEST_F(PPAPITest, Graphics2D) { RunTest("Graphics2D"); } // TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating. // Possibly all the image allocations slow things down on a loaded bot too much. TEST_F(PPAPITest, FLAKY_ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } // Flakey, http:L//crbug.com/57053 TEST_F(PPAPITest, FLAKY_URLLoader) { RunTestViaHTTP("URLLoader"); } // Flaky, http://crbug.com/51012 TEST_F(PPAPITest, FLAKY_PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, UrlUtil) { RunTest("UrlUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } TEST_F(PPAPITest, Var) { RunTest("Var"); } // TODO(dumi): figure out why this test is flaky on Mac and fix it. #if defined(OS_MACOSX) #define DISABLED_ON_MAC(test_name) DISABLED_##test_name #else #define DISABLED_ON_MAC(test_name) test_name #endif TEST_F(PPAPITest, DISABLED_ON_MAC(FileIO)) { RunTestViaHTTP("FileIO"); } TEST_F(PPAPITest, FileRef) { RunTestViaHTTP("FileRef"); } TEST_F(PPAPITest, DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } <commit_msg>Looks like PPAPITest.FileIO fails on Win XP (dbg) too, disable for now...<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL(test_server.GetURL("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } TEST_F(PPAPITest, Graphics2D) { RunTest("Graphics2D"); } // TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating. // Possibly all the image allocations slow things down on a loaded bot too much. TEST_F(PPAPITest, FLAKY_ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } // Flakey, http:L//crbug.com/57053 TEST_F(PPAPITest, FLAKY_URLLoader) { RunTestViaHTTP("URLLoader"); } // Flaky, http://crbug.com/51012 TEST_F(PPAPITest, FLAKY_PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, UrlUtil) { RunTest("UrlUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } TEST_F(PPAPITest, Var) { RunTest("Var"); } // TODO(dumi): figure out why this test is flaky on Mac and Win XP (dbg). #if defined(OS_MACOSX) || defined(OS_WIN) #define DISABLED_ON_MAC_AND_WIN(test_name) DISABLED_##test_name #else #define DISABLED_ON_MAC_AND_WIN(test_name) test_name #endif TEST_F(PPAPITest, DISABLED_ON_MAC_AND_WIN(FileIO)) { RunTestViaHTTP("FileIO"); } TEST_F(PPAPITest, FileRef) { RunTestViaHTTP("FileRef"); } TEST_F(PPAPITest, DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); #if defined(ENABLE_P2P_APIS) // Enable P2P API. launch_arguments_.AppendSwitch(switches::kEnableP2PApi); #endif // ENABLE_P2P_APIS } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // First wait for the "starting" signal. This cookie is set at the start // of every test. Waiting for this separately allows us to avoid a single // long timeout. Instead, we can have two timeouts which allow startup + // test execution time to take a while on a loaded computer, while also // making sure we're making forward progress. std::string startup_cookie = WaitUntilCookieNonEmpty(tab.get(), test_url, "STARTUP_COOKIE", TestTimeouts::action_max_timeout_ms()); // If this fails, the plugin couldn't be loaded in the given amount of // time. This may mean the plugin was not found or possibly the system // can't load it due to missing symbols, etc. ASSERT_STREQ("STARTED", startup_cookie.c_str()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", TestTimeouts::large_test_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; TEST_F(PPAPITest, Broker) { RunTest("Broker"); } TEST_F(PPAPITest, CursorControl) { RunTest("CursorControl"); } TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } TEST_F(PPAPITest, Graphics2D) { RunTest("Graphics2D"); } TEST_F(PPAPITest, ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } #if !defined(OS_MACOSX) TEST_F(OutOfProcessPPAPITest, Buffer) { RunTest("Buffer"); } #endif TEST_F(PPAPITest, URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_F(PPAPITest,PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Fails consistently on Windows. See crbug.com/85010 for details. #if defined(OS_WIN) #define MAYBE_Scrollbar FAILS_Scrollbar #else #define MAYBE_Scrollbar Scrollbar #endif TEST_F(PPAPITest, MAYBE_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, URLUtil) { RunTest("URLUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } TEST_F(PPAPITest, Var) { RunTest("Var"); } TEST_F(PPAPITest, VarDeprecated) { RunTest("VarDeprecated"); } TEST_F(PPAPITest, PostMessage) { RunTest("PostMessage"); } // http://crbug.com/83443 TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(PPAPITest, FileRef) { RunTestViaHTTP("FileRef"); } #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) TEST_F(PPAPITest, Transport) { RunTest("Transport"); } #endif // ENABLE_P2P_APIS <commit_msg>Re-enable PPAPITests.Scrollbar on Windows after fix to test. http://codereview.chromium.org/7064048/ BUG=85010 TEST=PPAPITests.Scrollbar Review URL: http://codereview.chromium.org/7044126<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); #if defined(ENABLE_P2P_APIS) // Enable P2P API. launch_arguments_.AppendSwitch(switches::kEnableP2PApi); #endif // ENABLE_P2P_APIS } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // First wait for the "starting" signal. This cookie is set at the start // of every test. Waiting for this separately allows us to avoid a single // long timeout. Instead, we can have two timeouts which allow startup + // test execution time to take a while on a loaded computer, while also // making sure we're making forward progress. std::string startup_cookie = WaitUntilCookieNonEmpty(tab.get(), test_url, "STARTUP_COOKIE", TestTimeouts::action_max_timeout_ms()); // If this fails, the plugin couldn't be loaded in the given amount of // time. This may mean the plugin was not found or possibly the system // can't load it due to missing symbols, etc. ASSERT_STREQ("STARTED", startup_cookie.c_str()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", TestTimeouts::large_test_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; TEST_F(PPAPITest, Broker) { RunTest("Broker"); } TEST_F(PPAPITest, CursorControl) { RunTest("CursorControl"); } TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } TEST_F(PPAPITest, Graphics2D) { RunTest("Graphics2D"); } TEST_F(PPAPITest, ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } #if !defined(OS_MACOSX) TEST_F(OutOfProcessPPAPITest, Buffer) { RunTest("Buffer"); } #endif TEST_F(PPAPITest, URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_F(PPAPITest,PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } TEST_F(PPAPITest, Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, URLUtil) { RunTest("URLUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } TEST_F(PPAPITest, Var) { RunTest("Var"); } TEST_F(PPAPITest, VarDeprecated) { RunTest("VarDeprecated"); } TEST_F(PPAPITest, PostMessage) { RunTest("PostMessage"); } // http://crbug.com/83443 TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(PPAPITest, FileRef) { RunTestViaHTTP("FileRef"); } #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) TEST_F(PPAPITest, Transport) { RunTest("Transport"); } #endif // ENABLE_P2P_APIS <|endoftext|>
<commit_before>// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Utility/IndexBuffer.hpp> #include <memory> #include <Nazara/Utility/Debug.hpp> namespace Nz { inline const std::shared_ptr<Buffer>& IndexBuffer::GetBuffer() const { return m_buffer; } inline UInt64 IndexBuffer::GetEndOffset() const { return m_endOffset; } inline UInt64 IndexBuffer::GetIndexCount() const { return m_indexCount; } inline IndexType IndexBuffer::GetIndexType() const { return m_indexType; } inline UInt64 IndexBuffer::GetStride() const { switch (m_indexType) { case IndexType::U8: return sizeof(UInt8); case IndexType::U16: return sizeof(UInt16); case IndexType::U32: return sizeof(UInt32); } NazaraError("invalid index size"); return 0; } inline UInt64 IndexBuffer::GetStartOffset() const { return m_startOffset; } inline bool IndexBuffer::IsValid() const { return m_buffer != nullptr; } inline void* IndexBuffer::Map(UInt64 startIndex, UInt64 length) { UInt64 stride = GetStride(); return MapRaw(startIndex * stride, length * stride); } inline void* IndexBuffer::Map(UInt64 startIndex, UInt64 length) const { UInt64 stride = GetStride(); return MapRaw(startIndex * stride, length * stride); } } #include <Nazara/Utility/DebugOff.hpp> <commit_msg>Fix compilation<commit_after>// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Utility/IndexBuffer.hpp> #include <Nazara/Core/Error.hpp> #include <memory> #include <Nazara/Utility/Debug.hpp> namespace Nz { inline const std::shared_ptr<Buffer>& IndexBuffer::GetBuffer() const { return m_buffer; } inline UInt64 IndexBuffer::GetEndOffset() const { return m_endOffset; } inline UInt64 IndexBuffer::GetIndexCount() const { return m_indexCount; } inline IndexType IndexBuffer::GetIndexType() const { return m_indexType; } inline UInt64 IndexBuffer::GetStride() const { switch (m_indexType) { case IndexType::U8: return sizeof(UInt8); case IndexType::U16: return sizeof(UInt16); case IndexType::U32: return sizeof(UInt32); } NazaraError("invalid index size"); return 0; } inline UInt64 IndexBuffer::GetStartOffset() const { return m_startOffset; } inline bool IndexBuffer::IsValid() const { return m_buffer != nullptr; } inline void* IndexBuffer::Map(UInt64 startIndex, UInt64 length) { UInt64 stride = GetStride(); return MapRaw(startIndex * stride, length * stride); } inline void* IndexBuffer::Map(UInt64 startIndex, UInt64 length) const { UInt64 stride = GetStride(); return MapRaw(startIndex * stride, length * stride); } } #include <Nazara/Utility/DebugOff.hpp> <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); #if defined(OS_WIN) std::wstring pepper_plugin = plugin_lib.value(); #else std::wstring pepper_plugin = UTF8ToWide(plugin_lib.value()); #endif pepper_plugin.append(L";application/x-ppapi-tests"); launch_arguments_.AppendSwitchWithValue(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { const wchar_t kDocRoot[] = L"third_party/ppapi/tests"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateForkingServer(kDocRoot); ASSERT_TRUE(server); RunTestURL(server->TestServerPage("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_DeviceContext2D) { #else TEST_F(PPAPITest, DeviceContext2D) { #endif RunTest("DeviceContext2D"); } #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_ImageData) { #else TEST_F(PPAPITest, ImageData) { #endif RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } TEST_F(PPAPITest, URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_F(PPAPITest, PaintAgggregator) { RunTestViaHTTP("PaintAggregator"); } // http://crbug.com/48544 #if defined(OS_LINUX) // TODO(jabdelmalek) this fails on Linux for unknown reasons. TEST_F(PPAPITest, FAILS_Scrollbar) { #else TEST_F(PPAPITest, Scrollbar) { #endif RunTest("Scrollbar"); } <commit_msg>Disable failing PPAPI test<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); #if defined(OS_WIN) std::wstring pepper_plugin = plugin_lib.value(); #else std::wstring pepper_plugin = UTF8ToWide(plugin_lib.value()); #endif pepper_plugin.append(L";application/x-ppapi-tests"); launch_arguments_.AppendSwitchWithValue(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { const wchar_t kDocRoot[] = L"third_party/ppapi/tests"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateForkingServer(kDocRoot); ASSERT_TRUE(server); RunTestURL(server->TestServerPage("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_DeviceContext2D) { #else TEST_F(PPAPITest, DeviceContext2D) { #endif RunTest("DeviceContext2D"); } #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_ImageData) { #else TEST_F(PPAPITest, ImageData) { #endif RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } TEST_F(PPAPITest, DISABLED_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_F(PPAPITest, PaintAgggregator) { RunTestViaHTTP("PaintAggregator"); } // http://crbug.com/48544 #if defined(OS_LINUX) // TODO(jabdelmalek) this fails on Linux for unknown reasons. TEST_F(PPAPITest, FAILS_Scrollbar) { #else TEST_F(PPAPITest, Scrollbar) { #endif RunTest("Scrollbar"); } <|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2001-2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : defines Unit Test Framework public API // *************************************************************************** #ifndef BOOST_TEST_UNIT_TEST_SUITE_HPP_071894GER #define BOOST_TEST_UNIT_TEST_SUITE_HPP_071894GER // Boost.Test #include <boost/test/framework.hpp> #include <boost/test/tree/auto_registration.hpp> #include <boost/test/tree/test_case_template.hpp> #include <boost/test/tree/global_fixture.hpp> //____________________________________________________________________________// // ************************************************************************** // // ************** Non-auto (explicit) test case interface ************** // // ************************************************************************** // #define BOOST_TEST_CASE( test_function ) \ boost::unit_test::make_test_case( boost::function<void ()>(test_function), BOOST_TEST_STRINGIZE( test_function ) ) #define BOOST_CLASS_TEST_CASE( test_function, tc_instance ) \ boost::unit_test::make_test_case((test_function), BOOST_TEST_STRINGIZE( test_function ), tc_instance ) // ************************************************************************** // // ************** BOOST_TEST_SUITE ************** // // ************************************************************************** // #define BOOST_TEST_SUITE( testsuite_name ) \ ( new boost::unit_test::test_suite( testsuite_name ) ) // ************************************************************************** // // ************** BOOST_AUTO_TEST_SUITE ************** // // ************************************************************************** // #define BOOST_AUTO_TEST_SUITE( suite_name ) \ namespace suite_name { \ BOOST_AUTO_TU_REGISTRAR( suite_name )( \ BOOST_STRINGIZE( suite_name ), \ boost::unit_test::decorator::collector::instance() ); \ /**/ // ************************************************************************** // // ************** BOOST_FIXTURE_TEST_SUITE ************** // // ************************************************************************** // #define BOOST_FIXTURE_TEST_SUITE( suite_name, F ) \ BOOST_AUTO_TEST_SUITE( suite_name ) \ typedef F BOOST_AUTO_TEST_CASE_FIXTURE; \ /**/ // ************************************************************************** // // ************** BOOST_AUTO_TEST_SUITE_END ************** // // ************************************************************************** // #define BOOST_AUTO_TEST_SUITE_END() \ BOOST_AUTO_TU_REGISTRAR( BOOST_JOIN( end_suite, __LINE__ ) )( 1 ); \ } \ /**/ // ************************************************************************** // // ************** BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES ************** // // ************************************************************************** // // deprecated; use decorator instead #define BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( test_name, n ) \ BOOST_TEST_DECORATOR( boost::unit_test::expected_failures( n ) ) /**/ // ************************************************************************** // // ************** BOOST_FIXTURE_TEST_CASE ************** // // ************************************************************************** // #define BOOST_FIXTURE_TEST_CASE( test_name, F ) \ struct test_name : public F { void test_method(); }; \ \ static void BOOST_AUTO_TC_INVOKER( test_name )() \ { \ test_name t; \ t.test_method(); \ } \ \ struct BOOST_AUTO_TC_UNIQUE_ID( test_name ) {}; \ \ BOOST_AUTO_TU_REGISTRAR( test_name )( \ boost::unit_test::make_test_case( \ &BOOST_AUTO_TC_INVOKER( test_name ), #test_name ), \ boost::unit_test::decorator::collector::instance() ); \ \ void test_name::test_method() \ /**/ // ************************************************************************** // // ************** BOOST_AUTO_TEST_CASE ************** // // ************************************************************************** // #define BOOST_AUTO_TEST_CASE( test_name ) \ BOOST_FIXTURE_TEST_CASE( test_name, BOOST_AUTO_TEST_CASE_FIXTURE ) /**/ // ************************************************************************** // // ************** BOOST_FIXTURE_TEST_CASE_TEMPLATE ************** // // ************************************************************************** // #define BOOST_FIXTURE_TEST_CASE_TEMPLATE( test_name, type_name, TL, F ) \ template<typename type_name> \ struct test_name : public F \ { void test_method(); }; \ \ struct BOOST_AUTO_TC_INVOKER( test_name ) { \ template<typename TestType> \ static void run( boost::type<TestType>* = 0 ) \ { \ test_name<TestType> t; \ t.test_method(); \ } \ }; \ \ BOOST_AUTO_TU_REGISTRAR( test_name )( \ boost::unit_test::ut_detail::template_test_case_gen< \ BOOST_AUTO_TC_INVOKER( test_name ),TL >( \ BOOST_STRINGIZE( test_name ) ), \ boost::unit_test::decorator::collector::instance() ); \ \ template<typename type_name> \ void test_name<type_name>::test_method() \ /**/ // ************************************************************************** // // ************** BOOST_AUTO_TEST_CASE_TEMPLATE ************** // // ************************************************************************** // #define BOOST_AUTO_TEST_CASE_TEMPLATE( test_name, type_name, TL ) \ BOOST_FIXTURE_TEST_CASE_TEMPLATE( test_name, type_name, TL, BOOST_AUTO_TEST_CASE_FIXTURE ) // ************************************************************************** // // ************** BOOST_TEST_CASE_TEMPLATE ************** // // ************************************************************************** // #define BOOST_TEST_CASE_TEMPLATE( name, typelist ) \ boost::unit_test::ut_detail::template_test_case_gen<name,typelist >(\ BOOST_TEST_STRINGIZE( name ) ) \ /**/ // ************************************************************************** // // ************** BOOST_TEST_CASE_TEMPLATE_FUNCTION ************** // // ************************************************************************** // #define BOOST_TEST_CASE_TEMPLATE_FUNCTION( name, type_name ) \ template<typename type_name> \ void BOOST_JOIN( name, _impl )( boost::type<type_name>* ); \ \ struct name { \ template<typename TestType> \ static void run( boost::type<TestType>* frwrd = 0 ) \ { \ BOOST_JOIN( name, _impl )( frwrd ); \ } \ }; \ \ template<typename type_name> \ void BOOST_JOIN( name, _impl )( boost::type<type_name>* ) \ /**/ // ************************************************************************** // // ************** BOOST_GLOBAL_FIXURE ************** // // ************************************************************************** // #define BOOST_GLOBAL_FIXTURE( F ) \ static boost::unit_test::ut_detail::global_fixture_impl<F> BOOST_JOIN( gf_, F ) ; \ /**/ // ************************************************************************** // // ************** BOOST_TEST_DECORATOR ************** // // ************************************************************************** // #define BOOST_TEST_DECORATOR( D ) \ static boost::unit_test::decorator::collector \ BOOST_JOIN(decorator_collector,__LINE__)( D ); \ /**/ // ************************************************************************** // // ************** BOOST_AUTO_TEST_CASE_FIXTURE ************** // // ************************************************************************** // namespace boost { namespace unit_test { namespace ut_detail { struct nil_t {}; } // namespace ut_detail } // unit_test } // namespace boost // Intentionally is in global namespace, so that FIXURE_TEST_SUITE can reset it in user code. typedef ::boost::unit_test::ut_detail::nil_t BOOST_AUTO_TEST_CASE_FIXTURE; // ************************************************************************** // // ************** Auto registration facility helper macros ************** // // ************************************************************************** // #define BOOST_AUTO_TU_REGISTRAR( test_name ) \ static boost::unit_test::ut_detail::auto_test_unit_registrar BOOST_JOIN( BOOST_JOIN( test_name, _registrar ), __LINE__ ) #define BOOST_AUTO_TC_INVOKER( test_name ) BOOST_JOIN( test_name, _invoker ) #define BOOST_AUTO_TC_UNIQUE_ID( test_name ) BOOST_JOIN( test_name, _id ) // ************************************************************************** // // ************** BOOST_TEST_MAIN ************** // // ************************************************************************** // #if defined(BOOST_TEST_MAIN) #ifdef BOOST_TEST_ALTERNATIVE_INIT_API bool init_unit_test() { #else ::boost::unit_test::test_suite* init_unit_test_suite( int, char* [] ) { #endif #ifdef BOOST_TEST_MODULE using namespace ::boost::unit_test; assign_op( framework::master_test_suite().p_name.value, BOOST_TEST_STRINGIZE( BOOST_TEST_MODULE ).trim( "\"" ), 0 ); #endif #ifdef BOOST_TEST_ALTERNATIVE_INIT_API return true; } #else return 0; } #endif #endif //____________________________________________________________________________// #endif // BOOST_TEST_UNIT_TEST_SUITE_HPP_071894GER <commit_msg>Added checkpoints at fixture entry points, test case entry point and test case exit point for auto registered test cases Fixes #5008<commit_after>// (C) Copyright Gennadiy Rozental 2001-2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : defines Unit Test Framework public API // *************************************************************************** #ifndef BOOST_TEST_UNIT_TEST_SUITE_HPP_071894GER #define BOOST_TEST_UNIT_TEST_SUITE_HPP_071894GER // Boost.Test #include <boost/test/framework.hpp> #include <boost/test/tree/auto_registration.hpp> #include <boost/test/tree/test_case_template.hpp> #include <boost/test/tree/global_fixture.hpp> //____________________________________________________________________________// // ************************************************************************** // // ************** Non-auto (explicit) test case interface ************** // // ************************************************************************** // #define BOOST_TEST_CASE( test_function ) \ boost::unit_test::make_test_case( boost::function<void ()>(test_function), BOOST_TEST_STRINGIZE( test_function ) ) #define BOOST_CLASS_TEST_CASE( test_function, tc_instance ) \ boost::unit_test::make_test_case((test_function), BOOST_TEST_STRINGIZE( test_function ), tc_instance ) // ************************************************************************** // // ************** BOOST_TEST_SUITE ************** // // ************************************************************************** // #define BOOST_TEST_SUITE( testsuite_name ) \ ( new boost::unit_test::test_suite( testsuite_name ) ) // ************************************************************************** // // ************** BOOST_AUTO_TEST_SUITE ************** // // ************************************************************************** // #define BOOST_AUTO_TEST_SUITE( suite_name ) \ namespace suite_name { \ BOOST_AUTO_TU_REGISTRAR( suite_name )( \ BOOST_STRINGIZE( suite_name ), \ boost::unit_test::decorator::collector::instance() ); \ /**/ // ************************************************************************** // // ************** BOOST_FIXTURE_TEST_SUITE ************** // // ************************************************************************** // #define BOOST_FIXTURE_TEST_SUITE( suite_name, F ) \ BOOST_AUTO_TEST_SUITE( suite_name ) \ typedef F BOOST_AUTO_TEST_CASE_FIXTURE; \ /**/ // ************************************************************************** // // ************** BOOST_AUTO_TEST_SUITE_END ************** // // ************************************************************************** // #define BOOST_AUTO_TEST_SUITE_END() \ BOOST_AUTO_TU_REGISTRAR( BOOST_JOIN( end_suite, __LINE__ ) )( 1 ); \ } \ /**/ // ************************************************************************** // // ************** BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES ************** // // ************************************************************************** // // deprecated; use decorator instead #define BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( test_name, n ) \ BOOST_TEST_DECORATOR( boost::unit_test::expected_failures( n ) ) /**/ // ************************************************************************** // // ************** BOOST_FIXTURE_TEST_CASE ************** // // ************************************************************************** // #define BOOST_FIXTURE_TEST_CASE( test_name, F ) \ struct test_name : public F { void test_method(); }; \ \ static void BOOST_AUTO_TC_INVOKER( test_name )() \ { \ BOOST_TEST_CHECKPOINT('"' << #test_name << "\" fixture entry."); \ test_name t; \ BOOST_TEST_CHECKPOINT('"' << #test_name << "\" entry."); \ t.test_method(); \ BOOST_TEST_CHECKPOINT('"' << #test_name << "\" exit."); \ } \ \ struct BOOST_AUTO_TC_UNIQUE_ID( test_name ) {}; \ \ BOOST_AUTO_TU_REGISTRAR( test_name )( \ boost::unit_test::make_test_case( \ &BOOST_AUTO_TC_INVOKER( test_name ), #test_name ), \ boost::unit_test::decorator::collector::instance() ); \ \ void test_name::test_method() \ /**/ // ************************************************************************** // // ************** BOOST_AUTO_TEST_CASE ************** // // ************************************************************************** // #define BOOST_AUTO_TEST_CASE( test_name ) \ BOOST_FIXTURE_TEST_CASE( test_name, BOOST_AUTO_TEST_CASE_FIXTURE ) /**/ // ************************************************************************** // // ************** BOOST_FIXTURE_TEST_CASE_TEMPLATE ************** // // ************************************************************************** // #define BOOST_FIXTURE_TEST_CASE_TEMPLATE( test_name, type_name, TL, F ) \ template<typename type_name> \ struct test_name : public F \ { void test_method(); }; \ \ struct BOOST_AUTO_TC_INVOKER( test_name ) { \ template<typename TestType> \ static void run( boost::type<TestType>* = 0 ) \ { \ BOOST_TEST_CHECKPOINT('"'<<#test_name <<"\" fixture entry."); \ test_name<TestType> t; \ BOOST_TEST_CHECKPOINT('"' << #test_name << "\" entry."); \ t.test_method(); \ BOOST_TEST_CHECKPOINT('"' << #test_name << "\" exit."); \ } \ }; \ \ BOOST_AUTO_TU_REGISTRAR( test_name )( \ boost::unit_test::ut_detail::template_test_case_gen< \ BOOST_AUTO_TC_INVOKER( test_name ),TL >( \ BOOST_STRINGIZE( test_name ) ), \ boost::unit_test::decorator::collector::instance() ); \ \ template<typename type_name> \ void test_name<type_name>::test_method() \ /**/ // ************************************************************************** // // ************** BOOST_AUTO_TEST_CASE_TEMPLATE ************** // // ************************************************************************** // #define BOOST_AUTO_TEST_CASE_TEMPLATE( test_name, type_name, TL ) \ BOOST_FIXTURE_TEST_CASE_TEMPLATE( test_name, type_name, TL, BOOST_AUTO_TEST_CASE_FIXTURE ) // ************************************************************************** // // ************** BOOST_TEST_CASE_TEMPLATE ************** // // ************************************************************************** // #define BOOST_TEST_CASE_TEMPLATE( name, typelist ) \ boost::unit_test::ut_detail::template_test_case_gen<name,typelist >(\ BOOST_TEST_STRINGIZE( name ) ) \ /**/ // ************************************************************************** // // ************** BOOST_TEST_CASE_TEMPLATE_FUNCTION ************** // // ************************************************************************** // #define BOOST_TEST_CASE_TEMPLATE_FUNCTION( name, type_name ) \ template<typename type_name> \ void BOOST_JOIN( name, _impl )( boost::type<type_name>* ); \ \ struct name { \ template<typename TestType> \ static void run( boost::type<TestType>* frwrd = 0 ) \ { \ BOOST_JOIN( name, _impl )( frwrd ); \ } \ }; \ \ template<typename type_name> \ void BOOST_JOIN( name, _impl )( boost::type<type_name>* ) \ /**/ // ************************************************************************** // // ************** BOOST_GLOBAL_FIXURE ************** // // ************************************************************************** // #define BOOST_GLOBAL_FIXTURE( F ) \ static boost::unit_test::ut_detail::global_fixture_impl<F> BOOST_JOIN( gf_, F ) ; \ /**/ // ************************************************************************** // // ************** BOOST_TEST_DECORATOR ************** // // ************************************************************************** // #define BOOST_TEST_DECORATOR( D ) \ static boost::unit_test::decorator::collector \ BOOST_JOIN(decorator_collector,__LINE__)( D ); \ /**/ // ************************************************************************** // // ************** BOOST_AUTO_TEST_CASE_FIXTURE ************** // // ************************************************************************** // namespace boost { namespace unit_test { namespace ut_detail { struct nil_t {}; } // namespace ut_detail } // unit_test } // namespace boost // Intentionally is in global namespace, so that FIXURE_TEST_SUITE can reset it in user code. typedef ::boost::unit_test::ut_detail::nil_t BOOST_AUTO_TEST_CASE_FIXTURE; // ************************************************************************** // // ************** Auto registration facility helper macros ************** // // ************************************************************************** // #define BOOST_AUTO_TU_REGISTRAR( test_name ) \ static boost::unit_test::ut_detail::auto_test_unit_registrar BOOST_JOIN( BOOST_JOIN( test_name, _registrar ), __LINE__ ) #define BOOST_AUTO_TC_INVOKER( test_name ) BOOST_JOIN( test_name, _invoker ) #define BOOST_AUTO_TC_UNIQUE_ID( test_name ) BOOST_JOIN( test_name, _id ) // ************************************************************************** // // ************** BOOST_TEST_MAIN ************** // // ************************************************************************** // #if defined(BOOST_TEST_MAIN) #ifdef BOOST_TEST_ALTERNATIVE_INIT_API bool init_unit_test() { #else ::boost::unit_test::test_suite* init_unit_test_suite( int, char* [] ) { #endif #ifdef BOOST_TEST_MODULE using namespace ::boost::unit_test; assign_op( framework::master_test_suite().p_name.value, BOOST_TEST_STRINGIZE( BOOST_TEST_MODULE ).trim( "\"" ), 0 ); #endif #ifdef BOOST_TEST_ALTERNATIVE_INIT_API return true; } #else return 0; } #endif #endif //____________________________________________________________________________// #endif // BOOST_TEST_UNIT_TEST_SUITE_HPP_071894GER <|endoftext|>
<commit_before>/*! \file boost_variant.hpp \brief Support for boost::variant \ingroup OtherTypes */ /* Copyright (c) 2014, Randolph Voorhies, Shane Grant 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 cereal 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 RANDOLPH VOORHIES OR SHANE GRANT 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. */ #ifndef CEREAL_TYPES_BOOST_VARIANT_HPP_ #define CEREAL_TYPES_BOOST_VARIANT_HPP_ //! @internal #if defined(_MSC_VER) && _MSC_VER < 1911 #define CEREAL_CONSTEXPR_LAMBDA #else // MSVC 2017 or newer, all other compilers #define CEREAL_CONSTEXPR_LAMBDA constexpr #endif #include "cereal/cereal.hpp" #include <boost/variant/variant_fwd.hpp> #include <boost/variant/static_visitor.hpp> namespace cereal { namespace boost_variant_detail { //! @internal template <class Archive> struct variant_save_visitor : boost::static_visitor<> { variant_save_visitor(Archive & ar_) : ar(ar_) {} template<class T> void operator()(T const & value) const { ar( CEREAL_NVP_("data", value) ); } Archive & ar; }; //! @internal template<class T, class Variant, class Archive> typename std::enable_if<std::is_default_constructible<T>::value>::type load_variant(Archive & ar, Variant & variant) { T value; ar( CEREAL_NVP_("data", value) ); variant = std::move(value); } //! @internal template <class Archive, class T> struct LoadAndConstructLoadWrapper { using ST = typename std::aligned_storage<sizeof(T), CEREAL_ALIGNOF(T)>::type; LoadAndConstructLoadWrapper() : construct( reinterpret_cast<T *>( &st ) ) { } ~LoadAndConstructLoadWrapper() { if (construct.itsValid) { construct->~T(); } } void CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar ) { ::cereal::detail::Construct<T, Archive>::load_andor_construct( ar, construct ); } ST st; ::cereal::construct<T> construct; }; //! @internal template<class T, class Variant, class Archive> typename std::enable_if<!std::is_default_constructible<T>::value>::type load_variant(Archive & ar, Variant & variant) { LoadAndConstructLoadWrapper<Archive, T> loadWrapper; ar( CEREAL_NVP_("data", loadWrapper) ); variant = std::move(*loadWrapper.construct.ptr()); } } // namespace boost_variant_detail //! Saving for boost::variant template <class Archive, typename ... VariantTypes> inline void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, boost::variant<VariantTypes...> const & variant ) { int32_t which = variant.which(); ar( CEREAL_NVP_("which", which) ); boost_variant_detail::variant_save_visitor<Archive> visitor(ar); variant.apply_visitor(visitor); } //! Loading for boost::variant template <class Archive, typename ... VariantTypes> inline void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, boost::variant<VariantTypes...> & variant ) { int32_t which; ar( CEREAL_NVP_("which", which) ); using LoadFuncType = void(*)(Archive &, boost::variant<VariantTypes...> &); CEREAL_CONSTEXPR_LAMBDA LoadFuncType loadFuncArray[] = {&boost_variant_detail::load_variant<VariantTypes>...}; if(which >= int32_t(sizeof(loadFuncArray)/sizeof(loadFuncArray[0]))) throw Exception("Invalid 'which' selector when deserializing boost::variant"); loadFuncArray[which](ar, variant); } } // namespace cereal #undef CEREAL_CONSTEXPR_LAMBDA #endif // CEREAL_TYPES_BOOST_VARIANT_HPP_ <commit_msg>MSVC variant support<commit_after>/*! \file boost_variant.hpp \brief Support for boost::variant \ingroup OtherTypes */ /* Copyright (c) 2014, Randolph Voorhies, Shane Grant 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 cereal 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 RANDOLPH VOORHIES OR SHANE GRANT 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. */ #ifndef CEREAL_TYPES_BOOST_VARIANT_HPP_ #define CEREAL_TYPES_BOOST_VARIANT_HPP_ //! @internal #if defined(_MSC_VER) && _MSC_VER < 1911 #define CEREAL_CONSTEXPR_LAMBDA #else // MSVC 2017 or newer, all other compilers #define CEREAL_CONSTEXPR_LAMBDA constexpr #endif #include "cereal/cereal.hpp" #include <boost/variant/variant_fwd.hpp> #include <boost/variant/static_visitor.hpp> namespace cereal { namespace boost_variant_detail { //! @internal template <class Archive> struct variant_save_visitor : boost::static_visitor<> { variant_save_visitor(Archive & ar_) : ar(ar_) {} template<class T> void operator()(T const & value) const { ar( CEREAL_NVP_("data", value) ); } Archive & ar; }; //! @internal template <class Archive, class T> struct LoadAndConstructLoadWrapper { using ST = typename std::aligned_storage<sizeof(T), CEREAL_ALIGNOF(T)>::type; LoadAndConstructLoadWrapper() : construct( reinterpret_cast<T *>( &st ) ) { } ~LoadAndConstructLoadWrapper() { if (construct.itsValid) { construct->~T(); } } void CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar ) { ::cereal::detail::Construct<T, Archive>::load_andor_construct( ar, construct ); } ST st; ::cereal::construct<T> construct; }; //! @internal template <class T> struct load_variant_wrapper; //! Avoid serializing variant void_ type /*! @internal */ template <> struct load_variant_wrapper<boost::detail::variant::void_> { template <class Variant, class Archive> static void load_variant( Archive &, Variant & ) { } }; //! @internal template <class T> struct load_variant_wrapper { // default constructible template <class Archive, class Variant> static void load_variant_impl( Archive & ar, Variant & variant, std::true_type ) { T value; ar( CEREAL_NVP_("data", value) ); variant = std::move(value); } // not default constructible template<class Variant, class Archive> static void load_variant_impl(Archive & ar, Variant & variant, std::false_type ) { LoadAndConstructLoadWrapper<Archive, T> loadWrapper; ar( CEREAL_NVP_("data", loadWrapper) ); variant = std::move(*loadWrapper.construct.ptr()); } //! @internal template<class Variant, class Archive> static void load_variant(Archive & ar, Variant & variant) { load_variant_impl( ar, variant, typename std::is_default_constructible<T>::type() ); } }; } // namespace boost_variant_detail //! Saving for boost::variant template <class Archive, typename ... VariantTypes> inline void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, boost::variant<VariantTypes...> const & variant ) { int32_t which = variant.which(); ar( CEREAL_NVP_("which", which) ); boost_variant_detail::variant_save_visitor<Archive> visitor(ar); variant.apply_visitor(visitor); } //! Loading for boost::variant template <class Archive, typename ... VariantTypes> inline void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, boost::variant<VariantTypes...> & variant ) { int32_t which; ar( CEREAL_NVP_("which", which) ); using LoadFuncType = void(*)(Archive &, boost::variant<VariantTypes...> &); CEREAL_CONSTEXPR_LAMBDA LoadFuncType loadFuncArray[] = {&boost_variant_detail::load_variant_wrapper<VariantTypes>::load_variant...}; if(which >= int32_t(sizeof(loadFuncArray)/sizeof(loadFuncArray[0]))) throw Exception("Invalid 'which' selector when deserializing boost::variant"); loadFuncArray[which](ar, variant); } } // namespace cereal #undef CEREAL_CONSTEXPR_LAMBDA #endif // CEREAL_TYPES_BOOST_VARIANT_HPP_ <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/http_negotiate.h" #include <atlbase.h> #include <atlcom.h> #include <htiframe.h> #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome_frame/bho.h" #include "chrome_frame/exception_barrier.h" #include "chrome_frame/html_utils.h" #include "chrome_frame/urlmon_url_request.h" #include "chrome_frame/urlmon_moniker.h" #include "chrome_frame/utils.h" #include "chrome_frame/vtable_patch_manager.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" bool HttpNegotiatePatch::modify_user_agent_ = true; const char kUACompatibleHttpHeader[] = "x-ua-compatible"; const char kLowerCaseUserAgent[] = "user-agent"; // From the latest urlmon.h. Symbol name prepended with LOCAL_ to // avoid conflict (and therefore build errors) for those building with // a newer Windows SDK. // TODO(robertshield): Remove this once we update our SDK version. const int LOCAL_BINDSTATUS_SERVER_MIMETYPEAVAILABLE = 54; static const int kHttpNegotiateBeginningTransactionIndex = 3; BEGIN_VTABLE_PATCHES(IHttpNegotiate) VTABLE_PATCH_ENTRY(kHttpNegotiateBeginningTransactionIndex, HttpNegotiatePatch::BeginningTransaction) END_VTABLE_PATCHES() namespace { class SimpleBindStatusCallback : public CComObjectRootEx<CComSingleThreadModel>, public IBindStatusCallback { public: BEGIN_COM_MAP(SimpleBindStatusCallback) COM_INTERFACE_ENTRY(IBindStatusCallback) END_COM_MAP() // IBindStatusCallback implementation STDMETHOD(OnStartBinding)(DWORD reserved, IBinding* binding) { return E_NOTIMPL; } STDMETHOD(GetPriority)(LONG* priority) { return E_NOTIMPL; } STDMETHOD(OnLowResource)(DWORD reserved) { return E_NOTIMPL; } STDMETHOD(OnProgress)(ULONG progress, ULONG max_progress, ULONG status_code, LPCWSTR status_text) { return E_NOTIMPL; } STDMETHOD(OnStopBinding)(HRESULT result, LPCWSTR error) { return E_NOTIMPL; } STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) { return E_NOTIMPL; } STDMETHOD(OnDataAvailable)(DWORD flags, DWORD size, FORMATETC* formatetc, STGMEDIUM* storage) { return E_NOTIMPL; } STDMETHOD(OnObjectAvailable)(REFIID iid, IUnknown* object) { return E_NOTIMPL; } }; } // end namespace std::string AppendCFUserAgentString(LPCWSTR headers, LPCWSTR additional_headers) { using net::HttpUtil; std::string ascii_headers; if (additional_headers) { ascii_headers = WideToASCII(additional_headers); } // Extract "User-Agent" from |additional_headers| or |headers|. HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(), ascii_headers.end(), "\r\n"); std::string user_agent_value; if (headers_iterator.AdvanceTo(kLowerCaseUserAgent)) { user_agent_value = headers_iterator.values(); } else if (headers != NULL) { // See if there's a user-agent header specified in the original headers. std::string original_headers(WideToASCII(headers)); HttpUtil::HeadersIterator original_it(original_headers.begin(), original_headers.end(), "\r\n"); if (original_it.AdvanceTo(kLowerCaseUserAgent)) user_agent_value = original_it.values(); } // Use the default "User-Agent" if none was provided. if (user_agent_value.empty()) user_agent_value = http_utils::GetDefaultUserAgent(); // Now add chromeframe to it. user_agent_value = http_utils::AddChromeFrameToUserAgentValue( user_agent_value); // Build new headers, skip the existing user agent value from // existing headers. std::string new_headers; headers_iterator.Reset(); while (headers_iterator.GetNext()) { std::string name(headers_iterator.name()); if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) { new_headers += name + ": " + headers_iterator.values() + "\r\n"; } } new_headers += "User-Agent: " + user_agent_value; new_headers += "\r\n"; return new_headers; } std::string ReplaceOrAddUserAgent(LPCWSTR headers, const std::string& user_agent_value) { DCHECK(headers); using net::HttpUtil; std::string new_headers; if (headers) { std::string ascii_headers(WideToASCII(headers)); // Extract "User-Agent" from the headers. HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(), ascii_headers.end(), "\r\n"); // Build new headers, skip the existing user agent value from // existing headers. while (headers_iterator.GetNext()) { std::string name(headers_iterator.name()); if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) { new_headers += name + ": " + headers_iterator.values() + "\r\n"; } } } new_headers += "User-Agent: " + user_agent_value; new_headers += "\r\n"; return new_headers; } HttpNegotiatePatch::HttpNegotiatePatch() { } HttpNegotiatePatch::~HttpNegotiatePatch() { } // static bool HttpNegotiatePatch::Initialize() { if (IS_PATCHED(IHttpNegotiate)) { DLOG(WARNING) << __FUNCTION__ << " called more than once."; return true; } // Use our SimpleBindStatusCallback class as we need a temporary object that // implements IBindStatusCallback. CComObjectStackEx<SimpleBindStatusCallback> request; ScopedComPtr<IBindCtx> bind_ctx; HRESULT hr = CreateAsyncBindCtx(0, &request, NULL, bind_ctx.Receive()); DCHECK(SUCCEEDED(hr)) << "CreateAsyncBindCtx"; if (bind_ctx) { ScopedComPtr<IUnknown> bscb_holder; bind_ctx->GetObjectParam(L"_BSCB_Holder_", bscb_holder.Receive()); if (bscb_holder) { hr = PatchHttpNegotiate(bscb_holder); } else { NOTREACHED() << "Failed to get _BSCB_Holder_"; hr = E_UNEXPECTED; } bind_ctx.Release(); } return SUCCEEDED(hr); } // static void HttpNegotiatePatch::Uninitialize() { vtable_patch::UnpatchInterfaceMethods(IHttpNegotiate_PatchInfo); } // static HRESULT HttpNegotiatePatch::PatchHttpNegotiate(IUnknown* to_patch) { DCHECK(to_patch); DCHECK_IS_NOT_PATCHED(IHttpNegotiate); ScopedComPtr<IHttpNegotiate> http; HRESULT hr = http.QueryFrom(to_patch); if (FAILED(hr)) { hr = DoQueryService(IID_IHttpNegotiate, to_patch, http.Receive()); } if (http) { hr = vtable_patch::PatchInterfaceMethods(http, IHttpNegotiate_PatchInfo); DLOG_IF(ERROR, FAILED(hr)) << base::StringPrintf("HttpNegotiate patch failed 0x%08X", hr); } else { DLOG(WARNING) << base::StringPrintf("IHttpNegotiate not supported 0x%08X", hr); } return hr; } // static HRESULT HttpNegotiatePatch::BeginningTransaction( IHttpNegotiate_BeginningTransaction_Fn original, IHttpNegotiate* me, LPCWSTR url, LPCWSTR headers, DWORD reserved, LPWSTR* additional_headers) { DVLOG(1) << __FUNCTION__ << " " << url << " headers:\n" << headers; HRESULT hr = original(me, url, headers, reserved, additional_headers); if (FAILED(hr)) { DLOG(WARNING) << __FUNCTION__ << " Delegate returned an error"; return hr; } if (modify_user_agent_) { std::string updated_headers; if (IsGcfDefaultRenderer() && RendererTypeForUrl(url) == RENDERER_TYPE_CHROME_DEFAULT_RENDERER) { // Replace the user-agent header with Chrome's. updated_headers = ReplaceOrAddUserAgent(*additional_headers, http_utils::GetChromeUserAgent()); } else { updated_headers = AppendCFUserAgentString(headers, *additional_headers); } *additional_headers = reinterpret_cast<wchar_t*>(::CoTaskMemRealloc( *additional_headers, (updated_headers.length() + 1) * sizeof(wchar_t))); lstrcpyW(*additional_headers, ASCIIToWide(updated_headers).c_str()); } return S_OK; } <commit_msg>Remove DCHECK for an argument that may be NULL.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/http_negotiate.h" #include <atlbase.h> #include <atlcom.h> #include <htiframe.h> #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome_frame/bho.h" #include "chrome_frame/exception_barrier.h" #include "chrome_frame/html_utils.h" #include "chrome_frame/urlmon_url_request.h" #include "chrome_frame/urlmon_moniker.h" #include "chrome_frame/utils.h" #include "chrome_frame/vtable_patch_manager.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" bool HttpNegotiatePatch::modify_user_agent_ = true; const char kUACompatibleHttpHeader[] = "x-ua-compatible"; const char kLowerCaseUserAgent[] = "user-agent"; // From the latest urlmon.h. Symbol name prepended with LOCAL_ to // avoid conflict (and therefore build errors) for those building with // a newer Windows SDK. // TODO(robertshield): Remove this once we update our SDK version. const int LOCAL_BINDSTATUS_SERVER_MIMETYPEAVAILABLE = 54; static const int kHttpNegotiateBeginningTransactionIndex = 3; BEGIN_VTABLE_PATCHES(IHttpNegotiate) VTABLE_PATCH_ENTRY(kHttpNegotiateBeginningTransactionIndex, HttpNegotiatePatch::BeginningTransaction) END_VTABLE_PATCHES() namespace { class SimpleBindStatusCallback : public CComObjectRootEx<CComSingleThreadModel>, public IBindStatusCallback { public: BEGIN_COM_MAP(SimpleBindStatusCallback) COM_INTERFACE_ENTRY(IBindStatusCallback) END_COM_MAP() // IBindStatusCallback implementation STDMETHOD(OnStartBinding)(DWORD reserved, IBinding* binding) { return E_NOTIMPL; } STDMETHOD(GetPriority)(LONG* priority) { return E_NOTIMPL; } STDMETHOD(OnLowResource)(DWORD reserved) { return E_NOTIMPL; } STDMETHOD(OnProgress)(ULONG progress, ULONG max_progress, ULONG status_code, LPCWSTR status_text) { return E_NOTIMPL; } STDMETHOD(OnStopBinding)(HRESULT result, LPCWSTR error) { return E_NOTIMPL; } STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) { return E_NOTIMPL; } STDMETHOD(OnDataAvailable)(DWORD flags, DWORD size, FORMATETC* formatetc, STGMEDIUM* storage) { return E_NOTIMPL; } STDMETHOD(OnObjectAvailable)(REFIID iid, IUnknown* object) { return E_NOTIMPL; } }; } // end namespace std::string AppendCFUserAgentString(LPCWSTR headers, LPCWSTR additional_headers) { using net::HttpUtil; std::string ascii_headers; if (additional_headers) { ascii_headers = WideToASCII(additional_headers); } // Extract "User-Agent" from |additional_headers| or |headers|. HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(), ascii_headers.end(), "\r\n"); std::string user_agent_value; if (headers_iterator.AdvanceTo(kLowerCaseUserAgent)) { user_agent_value = headers_iterator.values(); } else if (headers != NULL) { // See if there's a user-agent header specified in the original headers. std::string original_headers(WideToASCII(headers)); HttpUtil::HeadersIterator original_it(original_headers.begin(), original_headers.end(), "\r\n"); if (original_it.AdvanceTo(kLowerCaseUserAgent)) user_agent_value = original_it.values(); } // Use the default "User-Agent" if none was provided. if (user_agent_value.empty()) user_agent_value = http_utils::GetDefaultUserAgent(); // Now add chromeframe to it. user_agent_value = http_utils::AddChromeFrameToUserAgentValue( user_agent_value); // Build new headers, skip the existing user agent value from // existing headers. std::string new_headers; headers_iterator.Reset(); while (headers_iterator.GetNext()) { std::string name(headers_iterator.name()); if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) { new_headers += name + ": " + headers_iterator.values() + "\r\n"; } } new_headers += "User-Agent: " + user_agent_value; new_headers += "\r\n"; return new_headers; } std::string ReplaceOrAddUserAgent(LPCWSTR headers, const std::string& user_agent_value) { using net::HttpUtil; std::string new_headers; if (headers) { std::string ascii_headers(WideToASCII(headers)); // Extract "User-Agent" from the headers. HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(), ascii_headers.end(), "\r\n"); // Build new headers, skip the existing user agent value from // existing headers. while (headers_iterator.GetNext()) { std::string name(headers_iterator.name()); if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) { new_headers += name + ": " + headers_iterator.values() + "\r\n"; } } } new_headers += "User-Agent: " + user_agent_value; new_headers += "\r\n"; return new_headers; } HttpNegotiatePatch::HttpNegotiatePatch() { } HttpNegotiatePatch::~HttpNegotiatePatch() { } // static bool HttpNegotiatePatch::Initialize() { if (IS_PATCHED(IHttpNegotiate)) { DLOG(WARNING) << __FUNCTION__ << " called more than once."; return true; } // Use our SimpleBindStatusCallback class as we need a temporary object that // implements IBindStatusCallback. CComObjectStackEx<SimpleBindStatusCallback> request; ScopedComPtr<IBindCtx> bind_ctx; HRESULT hr = CreateAsyncBindCtx(0, &request, NULL, bind_ctx.Receive()); DCHECK(SUCCEEDED(hr)) << "CreateAsyncBindCtx"; if (bind_ctx) { ScopedComPtr<IUnknown> bscb_holder; bind_ctx->GetObjectParam(L"_BSCB_Holder_", bscb_holder.Receive()); if (bscb_holder) { hr = PatchHttpNegotiate(bscb_holder); } else { NOTREACHED() << "Failed to get _BSCB_Holder_"; hr = E_UNEXPECTED; } bind_ctx.Release(); } return SUCCEEDED(hr); } // static void HttpNegotiatePatch::Uninitialize() { vtable_patch::UnpatchInterfaceMethods(IHttpNegotiate_PatchInfo); } // static HRESULT HttpNegotiatePatch::PatchHttpNegotiate(IUnknown* to_patch) { DCHECK(to_patch); DCHECK_IS_NOT_PATCHED(IHttpNegotiate); ScopedComPtr<IHttpNegotiate> http; HRESULT hr = http.QueryFrom(to_patch); if (FAILED(hr)) { hr = DoQueryService(IID_IHttpNegotiate, to_patch, http.Receive()); } if (http) { hr = vtable_patch::PatchInterfaceMethods(http, IHttpNegotiate_PatchInfo); DLOG_IF(ERROR, FAILED(hr)) << base::StringPrintf("HttpNegotiate patch failed 0x%08X", hr); } else { DLOG(WARNING) << base::StringPrintf("IHttpNegotiate not supported 0x%08X", hr); } return hr; } // static HRESULT HttpNegotiatePatch::BeginningTransaction( IHttpNegotiate_BeginningTransaction_Fn original, IHttpNegotiate* me, LPCWSTR url, LPCWSTR headers, DWORD reserved, LPWSTR* additional_headers) { DVLOG(1) << __FUNCTION__ << " " << url << " headers:\n" << headers; HRESULT hr = original(me, url, headers, reserved, additional_headers); if (FAILED(hr)) { DLOG(WARNING) << __FUNCTION__ << " Delegate returned an error"; return hr; } if (modify_user_agent_) { std::string updated_headers; if (IsGcfDefaultRenderer() && RendererTypeForUrl(url) == RENDERER_TYPE_CHROME_DEFAULT_RENDERER) { // Replace the user-agent header with Chrome's. updated_headers = ReplaceOrAddUserAgent(*additional_headers, http_utils::GetChromeUserAgent()); } else { updated_headers = AppendCFUserAgentString(headers, *additional_headers); } *additional_headers = reinterpret_cast<wchar_t*>(::CoTaskMemRealloc( *additional_headers, (updated_headers.length() + 1) * sizeof(wchar_t))); lstrcpyW(*additional_headers, ASCIIToWide(updated_headers).c_str()); } return S_OK; } <|endoftext|>
<commit_before>#ifndef COBALT_UTILITY_ENUM_TRAITS_HPP_INCLUDED #define COBALT_UTILITY_ENUM_TRAITS_HPP_INCLUDED #pragma once #include <boost/preprocessor/variadic/size.hpp> #include <boost/assert.hpp> #include <type_traits> #include <ostream> #include <sstream> #include <cstdint> #include <cstring> namespace cobalt { template <typename EnumType> struct enum_traits { static constexpr bool is_enum = false; }; struct enum_item_info { std::string name() const { return std::string(_name, _name_length); } size_t value() const { return _value; } const char* _name; size_t _name_length; size_t _value; }; namespace detail { template <typename Tag, typename IntType = size_t> struct auto_enum_value { auto_enum_value(IntType v) : _value(v) { counter = _value + 1; } auto_enum_value() : _value(counter) { counter = _value + 1; } operator IntType() const { return _value; } private: IntType _value; static IntType counter; }; template <typename Tag, typename IntType> IntType auto_enum_value<Tag, IntType>::counter; template <int Dummy = 0> struct helper { // Handler(const char* name, size_t length) template <typename Handler> static void parse_enum_values_helper(const char* str, char separator, Handler handler) { auto is_identifier = [](char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; }; for (const char* b = str, *e = std::strchr(b, separator); b; (b = e) ? e = std::strchr(++b, separator) : (const char*)nullptr) { while (std::isspace(*b)) ++b; const char* name = b; while (is_identifier(*b)) ++b; handler(name, b - name); } } static void parse_enum_values(const char* str, enum_item_info* infos, size_t* values) { size_t i = 0; parse_enum_values_helper(str, ',', [&](const char* name, size_t length) { infos[i]._name = name; infos[i]._name_length = length; infos[i]._value = values[i]; i++; }); infos[i]._name = nullptr; infos[i]._value = 0; } static std::string to_string(const enum_item_info* const info, size_t value) { for (auto item = info; item->_name; ++item) { if (value == item->_value) { return item->name(); } } BOOST_ASSERT_MSG(false, "Couldn't find such a value"); return std::string(); } static std::string to_flags_string(const enum_item_info* const info, size_t value) { if (!value) return to_string(info, value); std::ostringstream ss; for (auto item = info; item->_name != nullptr; ++item) { if (item->_value && (value & item->_value) == item->_value) { value &= ~item->_value; if (item != info) ss << '|'; ss.rdbuf()->sputn(item->_name, item->_name_length); } } BOOST_ASSERT_MSG(!value, "Unknown value found"); // append unknown values as single hex if (value) { if (ss.tellp()) ss << '|'; ss << std::hex << std::showbase << value; } return ss.str(); } static size_t from_string(const enum_item_info* const info, const char* name, size_t length = 0) { if (!length) length = std::strlen(name); while (std::isspace(*name)) { ++name; --length; } while (std::isspace(name[length-1])) --length; for (auto item = info; item->_name; ++item) { if (item->_name_length == length && !std::strncmp(item->_name, name, length)) return item->_value; } BOOST_ASSERT_MSG(false, "Couldn't find such a value"); return 0; } static size_t from_flags_string(const enum_item_info* const info, const char* str, size_t /*length*/ = 0) { size_t value = 0; parse_enum_values_helper(str, '|', [&](const char* name, size_t length) { value |= from_string(info, name, length); }); return value; } }; template <typename T> struct type_name_helper { static std::string name() { constexpr size_t length = sizeof(__FUNCTION__) - sizeof("detail::type_name_helper<>::name"); constexpr size_t offset = sizeof("detail::type_name_helper<") - 1; // TODO: Use constexpr substring here return std::string(__FUNCTION__ + offset, length); } }; } // namespace detail template <typename T> std::string type_name() { return detail::type_name_helper<T>::name(); } } // namespace cobalt #define CO_DEFINE_ENUM_STRUCT(StructName, EnumName, UnderlyingType, ...) \ struct StructName { \ enum EnumName : UnderlyingType { \ __VA_ARGS__ \ }; \ }; \ namespace cobalt { \ CO_DEFINE_ENUM_STRUCT_TRAITS(StructName, EnumName, __VA_ARGS__) \ } \ #define CO_DEFINE_ENUM_FLAGS_STRUCT(StructName, EnumName, UnderlyingType, ...) \ struct StructName { \ enum EnumName : UnderlyingType { \ __VA_ARGS__ \ }; \ }; \ namespace cobalt { \ CO_DEFINE_ENUM_STRUCT_FLAGS_TRAITS(StructName, EnumName, __VA_ARGS__) \ } \ CO_DEFINE_ENUM_FLAGS_OPERATORS(StructName::EnumName) \ #define CO_DEFINE_ENUM_CLASS(EnumName, UnderlyingType, ...) \ enum class EnumName : UnderlyingType { \ __VA_ARGS__ \ }; \ namespace cobalt { \ CO_DEFINE_ENUM_CLASS_TRAITS(EnumName, __VA_ARGS__) \ } \ inline std::ostream& operator<<(std::ostream& os, EnumName e) { \ os << cobalt::enum_traits<EnumName>::to_string(e); \ return os; \ } #define CO_DEFINE_ENUM_FLAGS_CLASS(EnumName, UnderlyingType, ...) \ enum class EnumName : UnderlyingType { \ __VA_ARGS__ \ }; \ namespace cobalt { \ CO_DEFINE_ENUM_CLASS_FLAGS_TRAITS(EnumName, __VA_ARGS__) \ } \ inline std::ostream& operator<<(std::ostream& os, EnumName e) { \ os << cobalt::enum_traits<EnumName>::to_string(e); \ return os; \ } \ CO_DEFINE_ENUM_FLAGS_OPERATORS(EnumName) \ #define CO_DEFINE_ENUM_CLASS_TRAITS(EnumName, ...) \ template<> struct enum_traits<EnumName> { \ static constexpr bool is_enum = true; \ static constexpr bool is_flags = false; \ enum { num_items = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__) }; \ static const enum_item_info* const items() { \ static enum_item_info __infos[num_items + 1]; \ for (static bool __init = false; !__init && (__init = true); ) { \ detail::auto_enum_value<EnumName> __VA_ARGS__; \ size_t __values[] = { __VA_ARGS__ }; \ detail::helper<>::parse_enum_values(#__VA_ARGS__, __infos, __values); \ } \ return __infos; \ } \ static std::string to_string(EnumName value) \ { return detail::helper<>::to_string(items(), static_cast<size_t>(value)); } \ static EnumName from_string(const char* str, size_t length = 0) \ { return static_cast<EnumName>(detail::helper<>::from_string(items(), str, length)); } \ }; \ #define CO_DEFINE_ENUM_STRUCT_TRAITS(StructName, EnumName, ...) \ template<> struct enum_traits<StructName> { \ static constexpr bool is_enum = true; \ static constexpr bool is_flags = false; \ enum { num_items = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__) }; \ static const enum_item_info* const items() { \ static enum_item_info __infos[num_items + 1]; \ for (static bool __init = false; !__init && (__init = true); ) { \ detail::auto_enum_value<StructName> __VA_ARGS__; \ size_t __values[] = { __VA_ARGS__ }; \ detail::helper<>::parse_enum_values(#__VA_ARGS__, __infos, __values); \ } \ return __infos; \ } \ static std::string to_string(StructName::EnumName value) \ { return detail::helper<>::to_string(items(), static_cast<size_t>(value)); } \ static StructName::EnumName from_string(const char* str, size_t length = 0) \ { return static_cast<StructName::EnumName>(detail::helper<>::from_string(items(), str, length)); } \ }; \ #define CO_DEFINE_ENUM_CLASS_FLAGS_TRAITS(EnumName, ...) \ template<> struct enum_traits<EnumName> { \ static constexpr bool is_enum = true; \ static constexpr bool is_flags = true; \ enum { num_items = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__) }; \ static const enum_item_info* const items() { \ static enum_item_info __infos[num_items + 1]; \ for (static bool __init = false; !__init && (__init = true); ) { \ detail::auto_enum_value<EnumName> __VA_ARGS__; \ size_t __values[] = { __VA_ARGS__ }; \ detail::helper<>::parse_enum_values(#__VA_ARGS__, __infos, __values); \ } \ return __infos; \ } \ static std::string to_string(EnumName value) \ { return detail::helper<>::to_flags_string(items(), static_cast<size_t>(value)); } \ static EnumName from_string(const char* str, size_t length = 0) \ { return static_cast<EnumName>(detail::helper<>::from_flags_string(items(), str, length)); } \ }; \ #define CO_DEFINE_ENUM_STRUCT_FLAGS_TRAITS(StructName, EnumName, ...) \ template<> struct enum_traits<StructName> { \ static constexpr bool is_enum = true; \ static constexpr bool is_flags = true; \ enum { num_items = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__) }; \ static const enum_item_info* const items() { \ static enum_item_info __infos[num_items + 1]; \ for (static bool __init = false; !__init && (__init = true); ) { \ detail::auto_enum_value<StructName> __VA_ARGS__; \ size_t __values[] = { __VA_ARGS__ }; \ detail::helper<>::parse_enum_values(#__VA_ARGS__, __infos, __values); \ } \ return __infos; \ } \ static std::string to_string(StructName::EnumName value) \ { return detail::helper<>::to_flags_string(items(), static_cast<size_t>(value)); } \ static StructName::EnumName from_string(const char* str, size_t length = 0) \ { return static_cast<StructName::EnumName>(detail::helper<>::from_flags_string(items(), str, length)); } \ }; \ #define CO_ENUM_TO_VAL(EnumName, value) static_cast<std::underlying_type_t<EnumName>>(value) #define CO_ENUM_TO_REF(EnumName, value) reinterpret_cast<std::underlying_type_t<EnumName>&>(value) #define CO_DEFINE_ENUM_FLAGS_OPERATORS(EnumName) \ constexpr EnumName operator~(EnumName elem) noexcept \ { return static_cast<EnumName>(~CO_ENUM_TO_VAL(EnumName, elem)); } \ constexpr EnumName operator|(EnumName lhs, EnumName rhs) noexcept \ { return static_cast<EnumName>(CO_ENUM_TO_VAL(EnumName, lhs) | CO_ENUM_TO_VAL(EnumName, rhs)); } \ constexpr EnumName operator&(EnumName lhs, EnumName rhs) noexcept \ { return static_cast<EnumName>(CO_ENUM_TO_VAL(EnumName, lhs) & CO_ENUM_TO_VAL(EnumName, rhs)); } \ constexpr EnumName operator^(EnumName lhs, EnumName rhs) noexcept \ { return static_cast<EnumName>(CO_ENUM_TO_VAL(EnumName, lhs) ^ CO_ENUM_TO_VAL(EnumName, rhs)); } \ inline EnumName& operator|=(EnumName& lhs, EnumName rhs) noexcept \ { return reinterpret_cast<EnumName&>(CO_ENUM_TO_REF(EnumName, lhs) |= CO_ENUM_TO_VAL(EnumName, rhs)); } \ inline EnumName& operator&=(EnumName& lhs, EnumName rhs) noexcept \ { return reinterpret_cast<EnumName&>(CO_ENUM_TO_REF(EnumName, lhs) &= CO_ENUM_TO_VAL(EnumName, rhs)); } \ inline EnumName& operator^=(EnumName& lhs, EnumName rhs) noexcept \ { return reinterpret_cast<EnumName&>(CO_ENUM_TO_REF(EnumName, lhs) ^= CO_ENUM_TO_VAL(EnumName, rhs)); } \ #endif // COBALT_UTILITY_ENUM_TRAITS_HPP_INCLUDED <commit_msg>Changed name _name_length to _length<commit_after>#ifndef COBALT_UTILITY_ENUM_TRAITS_HPP_INCLUDED #define COBALT_UTILITY_ENUM_TRAITS_HPP_INCLUDED #pragma once #include <boost/preprocessor/variadic/size.hpp> #include <boost/assert.hpp> #include <type_traits> #include <ostream> #include <sstream> #include <cstdint> #include <cstring> namespace cobalt { template <typename EnumType> struct enum_traits { static constexpr bool is_enum = false; }; struct enum_item_info { std::string name() const { return std::string(_name, _length); } size_t value() const { return _value; } const char* _name; size_t _length; size_t _value; }; namespace detail { template <typename Tag, typename IntType = size_t> struct auto_enum_value { auto_enum_value(IntType v) : _value(v) { counter = _value + 1; } auto_enum_value() : _value(counter) { counter = _value + 1; } operator IntType() const { return _value; } private: IntType _value; static IntType counter; }; template <typename Tag, typename IntType> IntType auto_enum_value<Tag, IntType>::counter; template <int Dummy = 0> struct helper { // Handler(const char* name, size_t length) template <typename Handler> static void parse_enum_values_helper(const char* str, char separator, Handler handler) { auto is_identifier = [](char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; }; for (const char* b = str, *e = std::strchr(b, separator); b; (b = e) ? e = std::strchr(++b, separator) : (const char*)nullptr) { while (std::isspace(*b)) ++b; const char* name = b; while (is_identifier(*b)) ++b; handler(name, b - name); } } static void parse_enum_values(const char* str, enum_item_info* infos, size_t* values) { size_t i = 0; parse_enum_values_helper(str, ',', [&](const char* name, size_t length) { infos[i]._name = name; infos[i]._length = length; infos[i]._value = values[i]; i++; }); infos[i]._name = nullptr; infos[i]._value = 0; } static std::string to_string(const enum_item_info* const info, size_t value) { for (auto item = info; item->_name; ++item) { if (value == item->_value) { return item->name(); } } BOOST_ASSERT_MSG(false, "Couldn't find such a value"); return std::string(); } static std::string to_flags_string(const enum_item_info* const info, size_t value) { if (!value) return to_string(info, value); std::ostringstream ss; for (auto item = info; item->_name != nullptr; ++item) { if (item->_value && (value & item->_value) == item->_value) { value &= ~item->_value; if (item != info) ss << '|'; ss.rdbuf()->sputn(item->_name, item->_length); } } BOOST_ASSERT_MSG(!value, "Unknown value found"); // append unknown values as single hex if (value) { if (ss.tellp()) ss << '|'; ss << std::hex << std::showbase << value; } return ss.str(); } static size_t from_string(const enum_item_info* const info, const char* name, size_t length = 0) { if (!length) length = std::strlen(name); while (std::isspace(*name)) { ++name; --length; } while (std::isspace(name[length-1])) --length; for (auto item = info; item->_name; ++item) { if (item->_length == length && !std::strncmp(item->_name, name, length)) return item->_value; } BOOST_ASSERT_MSG(false, "Couldn't find such a value"); return 0; } static size_t from_flags_string(const enum_item_info* const info, const char* str, size_t /*length*/ = 0) { size_t value = 0; parse_enum_values_helper(str, '|', [&](const char* name, size_t length) { value |= from_string(info, name, length); }); return value; } }; template <typename T> struct type_name_helper { static std::string name() { constexpr size_t length = sizeof(__FUNCTION__) - sizeof("detail::type_name_helper<>::name"); constexpr size_t offset = sizeof("detail::type_name_helper<") - 1; // TODO: Use constexpr substring here return std::string(__FUNCTION__ + offset, length); } }; } // namespace detail template <typename T> std::string type_name() { return detail::type_name_helper<T>::name(); } } // namespace cobalt #define CO_DEFINE_ENUM_STRUCT(StructName, EnumName, UnderlyingType, ...) \ struct StructName { \ enum EnumName : UnderlyingType { \ __VA_ARGS__ \ }; \ }; \ namespace cobalt { \ CO_DEFINE_ENUM_STRUCT_TRAITS(StructName, EnumName, __VA_ARGS__) \ } \ #define CO_DEFINE_ENUM_FLAGS_STRUCT(StructName, EnumName, UnderlyingType, ...) \ struct StructName { \ enum EnumName : UnderlyingType { \ __VA_ARGS__ \ }; \ }; \ namespace cobalt { \ CO_DEFINE_ENUM_STRUCT_FLAGS_TRAITS(StructName, EnumName, __VA_ARGS__) \ } \ CO_DEFINE_ENUM_FLAGS_OPERATORS(StructName::EnumName) \ #define CO_DEFINE_ENUM_CLASS(EnumName, UnderlyingType, ...) \ enum class EnumName : UnderlyingType { \ __VA_ARGS__ \ }; \ namespace cobalt { \ CO_DEFINE_ENUM_CLASS_TRAITS(EnumName, __VA_ARGS__) \ } \ inline std::ostream& operator<<(std::ostream& os, EnumName e) { \ os << cobalt::enum_traits<EnumName>::to_string(e); \ return os; \ } #define CO_DEFINE_ENUM_FLAGS_CLASS(EnumName, UnderlyingType, ...) \ enum class EnumName : UnderlyingType { \ __VA_ARGS__ \ }; \ namespace cobalt { \ CO_DEFINE_ENUM_CLASS_FLAGS_TRAITS(EnumName, __VA_ARGS__) \ } \ inline std::ostream& operator<<(std::ostream& os, EnumName e) { \ os << cobalt::enum_traits<EnumName>::to_string(e); \ return os; \ } \ CO_DEFINE_ENUM_FLAGS_OPERATORS(EnumName) \ #define CO_DEFINE_ENUM_CLASS_TRAITS(EnumName, ...) \ template<> struct enum_traits<EnumName> { \ static constexpr bool is_enum = true; \ static constexpr bool is_flags = false; \ enum { num_items = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__) }; \ static const enum_item_info* const items() { \ static enum_item_info __infos[num_items + 1]; \ for (static bool __init = false; !__init && (__init = true); ) { \ detail::auto_enum_value<EnumName> __VA_ARGS__; \ size_t __values[] = { __VA_ARGS__ }; \ detail::helper<>::parse_enum_values(#__VA_ARGS__, __infos, __values); \ } \ return __infos; \ } \ static std::string to_string(EnumName value) \ { return detail::helper<>::to_string(items(), static_cast<size_t>(value)); } \ static EnumName from_string(const char* str, size_t length = 0) \ { return static_cast<EnumName>(detail::helper<>::from_string(items(), str, length)); } \ }; \ #define CO_DEFINE_ENUM_STRUCT_TRAITS(StructName, EnumName, ...) \ template<> struct enum_traits<StructName> { \ static constexpr bool is_enum = true; \ static constexpr bool is_flags = false; \ enum { num_items = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__) }; \ static const enum_item_info* const items() { \ static enum_item_info __infos[num_items + 1]; \ for (static bool __init = false; !__init && (__init = true); ) { \ detail::auto_enum_value<StructName> __VA_ARGS__; \ size_t __values[] = { __VA_ARGS__ }; \ detail::helper<>::parse_enum_values(#__VA_ARGS__, __infos, __values); \ } \ return __infos; \ } \ static std::string to_string(StructName::EnumName value) \ { return detail::helper<>::to_string(items(), static_cast<size_t>(value)); } \ static StructName::EnumName from_string(const char* str, size_t length = 0) \ { return static_cast<StructName::EnumName>(detail::helper<>::from_string(items(), str, length)); } \ }; \ #define CO_DEFINE_ENUM_CLASS_FLAGS_TRAITS(EnumName, ...) \ template<> struct enum_traits<EnumName> { \ static constexpr bool is_enum = true; \ static constexpr bool is_flags = true; \ enum { num_items = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__) }; \ static const enum_item_info* const items() { \ static enum_item_info __infos[num_items + 1]; \ for (static bool __init = false; !__init && (__init = true); ) { \ detail::auto_enum_value<EnumName> __VA_ARGS__; \ size_t __values[] = { __VA_ARGS__ }; \ detail::helper<>::parse_enum_values(#__VA_ARGS__, __infos, __values); \ } \ return __infos; \ } \ static std::string to_string(EnumName value) \ { return detail::helper<>::to_flags_string(items(), static_cast<size_t>(value)); } \ static EnumName from_string(const char* str, size_t length = 0) \ { return static_cast<EnumName>(detail::helper<>::from_flags_string(items(), str, length)); } \ }; \ #define CO_DEFINE_ENUM_STRUCT_FLAGS_TRAITS(StructName, EnumName, ...) \ template<> struct enum_traits<StructName> { \ static constexpr bool is_enum = true; \ static constexpr bool is_flags = true; \ enum { num_items = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__) }; \ static const enum_item_info* const items() { \ static enum_item_info __infos[num_items + 1]; \ for (static bool __init = false; !__init && (__init = true); ) { \ detail::auto_enum_value<StructName> __VA_ARGS__; \ size_t __values[] = { __VA_ARGS__ }; \ detail::helper<>::parse_enum_values(#__VA_ARGS__, __infos, __values); \ } \ return __infos; \ } \ static std::string to_string(StructName::EnumName value) \ { return detail::helper<>::to_flags_string(items(), static_cast<size_t>(value)); } \ static StructName::EnumName from_string(const char* str, size_t length = 0) \ { return static_cast<StructName::EnumName>(detail::helper<>::from_flags_string(items(), str, length)); } \ }; \ #define CO_ENUM_TO_VAL(EnumName, value) static_cast<std::underlying_type_t<EnumName>>(value) #define CO_ENUM_TO_REF(EnumName, value) reinterpret_cast<std::underlying_type_t<EnumName>&>(value) #define CO_DEFINE_ENUM_FLAGS_OPERATORS(EnumName) \ constexpr EnumName operator~(EnumName elem) noexcept \ { return static_cast<EnumName>(~CO_ENUM_TO_VAL(EnumName, elem)); } \ constexpr EnumName operator|(EnumName lhs, EnumName rhs) noexcept \ { return static_cast<EnumName>(CO_ENUM_TO_VAL(EnumName, lhs) | CO_ENUM_TO_VAL(EnumName, rhs)); } \ constexpr EnumName operator&(EnumName lhs, EnumName rhs) noexcept \ { return static_cast<EnumName>(CO_ENUM_TO_VAL(EnumName, lhs) & CO_ENUM_TO_VAL(EnumName, rhs)); } \ constexpr EnumName operator^(EnumName lhs, EnumName rhs) noexcept \ { return static_cast<EnumName>(CO_ENUM_TO_VAL(EnumName, lhs) ^ CO_ENUM_TO_VAL(EnumName, rhs)); } \ inline EnumName& operator|=(EnumName& lhs, EnumName rhs) noexcept \ { return reinterpret_cast<EnumName&>(CO_ENUM_TO_REF(EnumName, lhs) |= CO_ENUM_TO_VAL(EnumName, rhs)); } \ inline EnumName& operator&=(EnumName& lhs, EnumName rhs) noexcept \ { return reinterpret_cast<EnumName&>(CO_ENUM_TO_REF(EnumName, lhs) &= CO_ENUM_TO_VAL(EnumName, rhs)); } \ inline EnumName& operator^=(EnumName& lhs, EnumName rhs) noexcept \ { return reinterpret_cast<EnumName&>(CO_ENUM_TO_REF(EnumName, lhs) ^= CO_ENUM_TO_VAL(EnumName, rhs)); } \ #endif // COBALT_UTILITY_ENUM_TRAITS_HPP_INCLUDED <|endoftext|>
<commit_before> /* /~` _ _ _|_. _ _ |_ | _ \_,(_)| | | || ||_|(_||_)|(/_ https://github.com/Naios/continuable v3.0.0 Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #ifndef CONTINUABLE_DETAIL_TESTING_HPP_INCLUDED #define CONTINUABLE_DETAIL_TESTING_HPP_INCLUDED #include <type_traits> #include <utility> #include <gtest/gtest.h> #include <continuable/detail/features.hpp> #include <continuable/detail/traits.hpp> #include <continuable/detail/types.hpp> #include <continuable/detail/util.hpp> namespace cti { namespace detail { namespace testing { template <typename C> void assert_async_completion(C&& continuable) { auto called = std::make_shared<bool>(false); std::forward<C>(continuable) .then([called](auto&&... args) { ASSERT_FALSE(*called); *called = true; // Workaround for our known GCC bug. util::unused(std::forward<decltype(args)>(args)...); }) .fail([](cti::error_type /*error*/) { // ... FAIL(); }); ASSERT_TRUE(*called); } template <typename C> void assert_async_exception_completion(C&& continuable) { auto called = std::make_shared<bool>(false); std::forward<C>(continuable) .then([](auto&&... args) { // Workaround for our known GCC bug. util::unused(std::forward<decltype(args)>(args)...); // ... FAIL(); }) .fail([called](cti::error_type /*error*/) { ASSERT_FALSE(*called); *called = true; }); ASSERT_TRUE(*called); } template <typename C> void assert_async_never_completed(C&& continuable) { std::forward<C>(continuable) .then([](auto&&... args) { // Workaround for our known GCC bug. util::unused(std::forward<decltype(args)>(args)...); FAIL(); }) .fail([](cti::error_type /*error*/) { // ... FAIL(); }); } template <typename C, typename V> void assert_async_validation(C&& continuable, V&& validator) { assert_async_completion( std::forward<C>(continuable) .then([validator = std::forward<V>(validator)](auto&&... args) mutable { validator(std::forward<decltype(args)>(args)...); })); } /// Expects that the continuable is finished with the given arguments template <typename V, typename C, typename... Args> void assert_async_binary_validation(V&& validator, C&& continuable, Args&&... expected) { using size = std::integral_constant<std::size_t, sizeof...(expected)>; assert_async_validation(std::forward<C>(continuable), [ expected_pack = std::make_tuple(std::forward<Args>(expected)...), validator = std::forward<V>(validator) ](auto&&... args) mutable { static_assert(size::value == sizeof...(args), "Async completion handler called with a different count " "of arguments!"); validator(std::make_tuple(std::forward<decltype(args)>(args)...), expected_pack); }); } /// Expects that the continuable is finished with the given arguments template <typename V, typename C, typename Args> void assert_async_binary_exception_validation(V&& validator, C&& continuable, Args&& expected) { auto called = std::make_shared<bool>(false); std::forward<C>(continuable) .then([](auto&&... args) { // Workaround for our known GCC bug. util::unused(std::forward<decltype(args)>(args)...); // ... FAIL(); }) .fail([ called, validator = std::forward<decltype(validator)>(validator), expected = std::forward<decltype(expected)>(expected) ](types::error_type error) { ASSERT_FALSE(*called); *called = true; #if defined(CONTINUABLE_HAS_EXCEPTIONS) try { std::rethrow_exception(error); } catch (std::decay_t<decltype(expected)>& exception) { validator(exception, expected); } catch (...) { FAIL(); } #else validator(error, expected); #endif }); ASSERT_TRUE(*called); } inline auto expecting_eq_check() { return [](auto&& expected, auto&& actual) { EXPECT_EQ(std::forward<decltype(expected)>(expected), std::forward<decltype(actual)>(actual)); }; } inline auto asserting_eq_check() { return [](auto&& expected, auto&& actual) { ASSERT_EQ(std::forward<decltype(expected)>(expected), std::forward<decltype(actual)>(actual)); }; } template <typename C, typename... Args> void assert_async_types(C&& continuable, traits::identity<Args...> expected) { assert_async_validation( std::forward<C>(continuable), [&](auto... actualPack) { auto actual = traits::identity<decltype(actualPack)...>{}; util::unused(expected, actual, std::forward<decltype(actualPack)>(actualPack)...); static_assert( std::is_same<std::decay_t<decltype(expected)>, std::decay_t<decltype(actual)>>::value, "The called arguments don't match with the expected ones!"); }); } } // namespace testing } // namespace detail } // namespace cti #endif // CONTINUABLE_DETAIL_TESTING_HPP_INCLUDED <commit_msg>Some more permissive issues<commit_after> /* /~` _ _ _|_. _ _ |_ | _ \_,(_)| | | || ||_|(_||_)|(/_ https://github.com/Naios/continuable v3.0.0 Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #ifndef CONTINUABLE_DETAIL_TESTING_HPP_INCLUDED #define CONTINUABLE_DETAIL_TESTING_HPP_INCLUDED #include <type_traits> #include <utility> #include <gtest/gtest.h> #include <continuable/detail/features.hpp> #include <continuable/detail/traits.hpp> #include <continuable/detail/types.hpp> #include <continuable/detail/util.hpp> namespace cti { namespace detail { namespace testing { template <typename C> void assert_async_completion(C&& continuable) { auto called = std::make_shared<bool>(false); std::forward<C>(continuable) .then([called](auto&&... args) { ASSERT_FALSE(*called); *called = true; // Workaround for our known GCC bug. util::unused(std::forward<decltype(args)>(args)...); }) .fail([](cti::error_type /*error*/) { // ... FAIL(); }); ASSERT_TRUE(*called); } template <typename C> void assert_async_exception_completion(C&& continuable) { auto called = std::make_shared<bool>(false); std::forward<C>(continuable) .then([](auto&&... args) { // Workaround for our known GCC bug. util::unused(std::forward<decltype(args)>(args)...); // ... FAIL(); }) .fail([called](cti::error_type /*error*/) { ASSERT_FALSE(*called); *called = true; }); ASSERT_TRUE(*called); } template <typename C> void assert_async_never_completed(C&& continuable) { std::forward<C>(continuable) .then([](auto&&... args) { // Workaround for our known GCC bug. util::unused(std::forward<decltype(args)>(args)...); FAIL(); }) .fail([](cti::error_type /*error*/) { // ... FAIL(); }); } template <typename C, typename V> void assert_async_validation(C&& continuable, V&& validator) { assert_async_completion( std::forward<C>(continuable) .then([validator = std::forward<V>(validator)](auto&&... args) mutable { validator(std::forward<decltype(args)>(args)...); })); } /// Expects that the continuable is finished with the given arguments template <typename V, typename C, typename... Args> void assert_async_binary_validation(V&& validator, C&& continuable, Args&&... expected) { using size = std::integral_constant<std::size_t, sizeof...(expected)>; assert_async_validation(std::forward<C>(continuable), [ expected_pack = std::make_tuple(std::forward<Args>(expected)...), validator = std::forward<V>(validator) ](auto&&... args) mutable { static_assert(size::value == sizeof...(args), "Async completion handler called with a different count " "of arguments!"); validator(std::make_tuple(std::forward<decltype(args)>(args)...), expected_pack); }); } /// Expects that the continuable is finished with the given arguments template <typename V, typename C, typename Args> void assert_async_binary_exception_validation(V&& validator, C&& continuable, Args&& expected) { auto called = std::make_shared<bool>(false); std::forward<C>(continuable) .then([](auto&&... args) { // Workaround for our known GCC bug. util::unused(std::forward<decltype(args)>(args)...); // ... FAIL(); }) .fail([ called, validator = std::forward<decltype(validator)>(validator), expected = std::forward<decltype(expected)>(expected) ](types::error_type error) { ASSERT_FALSE(*called); *called = true; #if defined(CONTINUABLE_HAS_EXCEPTIONS) try { std::rethrow_exception(error); } catch (std::decay_t<decltype(expected)>& exception) { validator(exception, expected); } catch (...) { FAIL(); } #else validator(error, expected); #endif }); ASSERT_TRUE(*called); } inline auto expecting_eq_check() { return [](auto&& expected, auto&& actual) { EXPECT_EQ(std::forward<decltype(expected)>(expected), std::forward<decltype(actual)>(actual)); }; } inline auto asserting_eq_check() { return [](auto&& expected, auto&& actual) { ASSERT_EQ(std::forward<decltype(expected)>(expected), std::forward<decltype(actual)>(actual)); }; } template <typename... Expected> struct assert_async_types_validator { template <typename... Actual> void operator()(Actual...) { static_assert(std::is_same<traits::identity<Actual...>, traits::identity<Expected...>>::value, "The called arguments don't match with the expected ones!"); } }; template <typename C, typename... Args> void assert_async_types(C&& continuable, traits::identity<Args...> /*expected*/) { assert_async_validation(std::forward<C>(continuable), assert_async_types_validator<Args...>{}); } } // namespace testing } // namespace detail } // namespace cti #endif // CONTINUABLE_DETAIL_TESTING_HPP_INCLUDED <|endoftext|>
<commit_before>/** * This file defines the `dispatch_policy` class. */ #ifndef D2_SANDBOX_DISPATCH_POLICY_HPP #define D2_SANDBOX_DISPATCH_POLICY_HPP #include <boost/parameter.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_params_with_a_default.hpp> #include <boost/proto/proto.hpp> #include <boost/utility/result_of.hpp> namespace d2 { namespace sandbox { BOOST_PROTO_DEFINE_ENV_VAR(stream_type, stream_); BOOST_PROTO_DEFINE_ENV_VAR(event_type, event_); namespace dispatch_policy_detail { BOOST_PARAMETER_TEMPLATE_KEYWORD(stream_factory) BOOST_PARAMETER_TEMPLATE_KEYWORD(synchronize_locally_with) BOOST_PARAMETER_TEMPLATE_KEYWORD(before_writing) BOOST_PARAMETER_TEMPLATE_KEYWORD(write_with) BOOST_PARAMETER_TEMPLATE_KEYWORD(after_writing) typedef boost::parameter::parameters< boost::parameter::required<tag::stream_factory> , boost::parameter::optional<tag::synchronize_locally_with> , boost::parameter::optional<tag::before_writing> , boost::parameter::optional<tag::write_with> , boost::parameter::optional<tag::after_writing> > signature; template <typename Args> class dispatch_policy_impl : public boost::proto::transform<dispatch_policy_impl<Args> > { template <typename Tag, typename Default = boost::parameter::void_> struct arg : boost::parameter::value_type<Args, Tag, Default> { }; struct left_shift { template <typename Event, typename State, typename Data> void operator()(Event const& event, State const&, Data& data) const { data[stream_] << event; } }; struct null_scoped_lock { template <typename Event, typename State, typename Data> null_scoped_lock(Event const&, State const&, Data const&) { } }; typedef boost::proto::_void nothing; typedef typename arg<tag::stream_factory>::type StreamFactory; typedef typename arg< tag::synchronize_locally_with, null_scoped_lock >::type ScopedLock; typedef typename arg<tag::before_writing, nothing>::type BeforeWriting; typedef typename arg<tag::write_with, left_shift>::type Write; typedef typename arg<tag::after_writing, nothing>::type AfterWriting; public: template <typename Expr, typename State, typename Data> struct impl : boost::proto::transform_impl<Expr, State, Data> { typedef void result_type; result_type operator()(typename impl::expr_param event, typename impl::state_param state, typename impl::data_param data) const { // Make sure `data_param` is an environment. typedef typename boost::proto::result_of::as_env< typename impl::data_param >::type BaseEnv; // Add `event` to the environment. typedef boost::proto::env< event_type, typename impl::expr_param, BaseEnv > DataWithEvent; DataWithEvent with_event(event, boost::proto::as_env(data)); // Fetch the stream from the factory. typedef typename boost::result_of< StreamFactory(typename impl::expr_param, typename impl::state_param, DataWithEvent&) >::type Stream; Stream stream = StreamFactory()(event, state, with_event); // Add `stream` to the environment. typedef boost::proto::env< stream_type, Stream, DataWithEvent > DataWithStream; DataWithStream with_stream(stream, with_event); ScopedLock lock (event, state, with_stream); BeforeWriting() (event, state, with_stream); Write() (event, state, with_stream); AfterWriting() (event, state, with_stream); } }; }; } // end namespace dispatch_policy_detail using dispatch_policy_detail::stream_factory; using dispatch_policy_detail::synchronize_locally_with; using dispatch_policy_detail::before_writing; using dispatch_policy_detail::write_with; using dispatch_policy_detail::after_writing; template < typename A0, BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(4, typename B,boost::parameter::void_) > struct dispatch_policy : dispatch_policy_detail::dispatch_policy_impl< typename dispatch_policy_detail::signature::bind< A0, BOOST_PP_ENUM_PARAMS(4, B) >::type > { }; } // end namespace sandbox } // end namespace d2 #include <boost/mpl/bool.hpp> namespace boost { namespace proto { template <BOOST_PP_ENUM_PARAMS(5, typename A)> struct is_callable<d2::sandbox::dispatch_policy<BOOST_PP_ENUM_PARAMS(5, A)> > : boost::mpl::true_ { }; }} #endif // !D2_SANDBOX_DISPATCH_POLICY_HPP <commit_msg>Allow for transforms as arguments to the dispatch policy.<commit_after>/** * This file defines the `dispatch_policy` class. */ #ifndef D2_SANDBOX_DISPATCH_POLICY_HPP #define D2_SANDBOX_DISPATCH_POLICY_HPP #include <boost/parameter.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_params_with_a_default.hpp> #include <boost/proto/proto.hpp> #include <boost/utility/result_of.hpp> namespace d2 { namespace sandbox { BOOST_PROTO_DEFINE_ENV_VAR(stream_type, stream_); BOOST_PROTO_DEFINE_ENV_VAR(event_type, event_); namespace dispatch_policy_detail { BOOST_PARAMETER_TEMPLATE_KEYWORD(stream_factory) BOOST_PARAMETER_TEMPLATE_KEYWORD(synchronize_locally_with) BOOST_PARAMETER_TEMPLATE_KEYWORD(before_writing) BOOST_PARAMETER_TEMPLATE_KEYWORD(write_with) BOOST_PARAMETER_TEMPLATE_KEYWORD(after_writing) typedef boost::parameter::parameters< boost::parameter::required<tag::stream_factory> , boost::parameter::optional<tag::synchronize_locally_with> , boost::parameter::optional<tag::before_writing> , boost::parameter::optional<tag::write_with> , boost::parameter::optional<tag::after_writing> > signature; template <typename Args> class dispatch_policy_impl : public boost::proto::transform<dispatch_policy_impl<Args> > { template <typename Tag, typename Default = boost::parameter::void_> struct arg : boost::parameter::value_type<Args, Tag, Default> { }; struct left_shift { template <typename Event, typename State, typename Data> void operator()(Event const& event, State const&, Data& data) const { data[stream_] << event; } }; struct null_scoped_lock { template <typename Event, typename State, typename Data> null_scoped_lock(Event const&, State const&, Data const&) { } }; typedef boost::proto::_void nothing; public: template <typename Expr, typename State, typename Data> struct impl : boost::proto::transform_impl<Expr, State, Data> { typedef boost::proto::call< typename arg<tag::stream_factory>::type > StreamFactory; typedef typename arg< tag::synchronize_locally_with, null_scoped_lock >::type ScopedLock; typedef boost::proto::call< typename arg<tag::before_writing, nothing>::type > BeforeWriting; typedef boost::proto::call< typename arg<tag::write_with, left_shift>::type > Write; typedef boost::proto::call< typename arg<tag::after_writing, nothing>::type > AfterWriting; typedef void result_type; result_type operator()(typename impl::expr_param event, typename impl::state_param state, typename impl::data_param data) const { // Make sure `data_param` is an environment. typedef typename boost::proto::result_of::as_env< typename impl::data_param >::type BaseEnv; // Add `event` to the environment. typedef boost::proto::env< event_type, typename impl::expr_param, BaseEnv > DataWithEvent; DataWithEvent with_event(event, boost::proto::as_env(data)); // Fetch the stream from the factory. typedef typename boost::result_of< StreamFactory(typename impl::expr_param, typename impl::state_param, DataWithEvent&) >::type Stream; Stream stream = StreamFactory()(event, state, with_event); // Add `stream` to the environment. typedef boost::proto::env< stream_type, Stream, DataWithEvent > DataWithStream; DataWithStream with_stream(stream, with_event); ScopedLock lock (event, state, with_stream); BeforeWriting() (event, state, with_stream); Write() (event, state, with_stream); AfterWriting() (event, state, with_stream); } }; }; } // end namespace dispatch_policy_detail using dispatch_policy_detail::stream_factory; using dispatch_policy_detail::synchronize_locally_with; using dispatch_policy_detail::before_writing; using dispatch_policy_detail::write_with; using dispatch_policy_detail::after_writing; template < typename A0, BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(4, typename B,boost::parameter::void_) > struct dispatch_policy : dispatch_policy_detail::dispatch_policy_impl< typename dispatch_policy_detail::signature::bind< A0, BOOST_PP_ENUM_PARAMS(4, B) >::type > { }; } // end namespace sandbox } // end namespace d2 #include <boost/mpl/bool.hpp> namespace boost { namespace proto { template <BOOST_PP_ENUM_PARAMS(5, typename A)> struct is_callable<d2::sandbox::dispatch_policy<BOOST_PP_ENUM_PARAMS(5, A)> > : boost::mpl::true_ { }; }} #endif // !D2_SANDBOX_DISPATCH_POLICY_HPP <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief EGBLAS wrappers for the axdy operation. */ #pragma once #ifdef ETL_EGBLAS_MODE #include "etl/impl/cublas/cuda.hpp" #include <egblas.hpp> #endif namespace etl { namespace impl { namespace egblas { #ifdef EGBLAS_HAS_SCALAR_SADD static constexpr bool has_scalar_sadd = true; /*! * \brief Adds the scalar beta to each element of the single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(float* x, size_t n, size_t s, float* beta){ egblas_scalar_sadd(x, n, s, *beta); } #else static constexpr bool has_scalar_sadd = false; #endif #ifdef EGBLAS_HAS_SCALAR_DADD static constexpr bool has_scalar_dadd = true; /*! * \brief Adds the scalar beta to each element of the double-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(double* x, size_t n, size_t s, double* beta){ egblas_scalar_dadd(x, n, s, *beta); } #else static constexpr bool has_scalar_dadd = false; #endif #ifdef EGBLAS_HAS_SCALAR_CADD static constexpr bool has_scalar_cadd = true; /*! * \brief Adds the scalar beta to each element of the complex single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(etl::complex<float>* x, size_t n, size_t s, etl::complex<float>* beta){ egblas_scalar_cadd(reinterpret_cast<cuComplex*>(x), n, s, *reinterpret_cast<cuComplex*>(beta)); } /*! * \brief Adds the scalar beta to each element of the complex single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(std::complex<float>* x, size_t n, size_t s, std::complex<float>* beta){ egblas_scalar_cadd(reinterpret_cast<cuComplex*>(x), n, s, *reinterpret_cast<cuComplex*>(beta)); } #else static constexpr bool has_scalar_cadd = false; #endif #ifdef EGBLAS_HAS_SCALAR_ZADD static constexpr bool has_scalar_zadd = true; /*! * \brief Adds the scalar beta to each element of the complex single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(etl::complex<double>* x, size_t n, size_t s, etl::complex<double>* beta){ egblas_scalar_zadd(reinterpret_cast<cuDoubleComplex*>(x), n, s, *reinterpret_cast<cuDoubleComplex*>(beta)); } /*! * \brief Adds the scalar beta to each element of the complex single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(std::complex<double>* x, size_t n, size_t s, std::complex<double>* beta){ egblas_scalar_zadd(reinterpret_cast<cuDoubleComplex*>(x), n, s, *reinterpret_cast<cuDoubleComplex*>(beta)); } #else static constexpr bool has_scalar_zadd = false; #endif #ifndef ETL_EGBLAS_MODE /*! * \brief Adds the scalar beta to each element of the single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ template<typename T> inline void scalar_add(T* x, size_t n, size_t s, T* beta){ cpp_unused(x); cpp_unused(n); cpp_unused(s); cpp_unused(beta); cpp_unreachable("Invalid call to egblas::scalar_add"); } #endif } //end of namespace egblas } //end of namespace impl } //end of namespace etl <commit_msg>Fix typo<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief EGBLAS wrappers for the scalar_add operation. */ #pragma once #ifdef ETL_EGBLAS_MODE #include "etl/impl/cublas/cuda.hpp" #include <egblas.hpp> #endif namespace etl { namespace impl { namespace egblas { #ifdef EGBLAS_HAS_SCALAR_SADD static constexpr bool has_scalar_sadd = true; /*! * \brief Adds the scalar beta to each element of the single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(float* x, size_t n, size_t s, float* beta){ egblas_scalar_sadd(x, n, s, *beta); } #else static constexpr bool has_scalar_sadd = false; #endif #ifdef EGBLAS_HAS_SCALAR_DADD static constexpr bool has_scalar_dadd = true; /*! * \brief Adds the scalar beta to each element of the double-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(double* x, size_t n, size_t s, double* beta){ egblas_scalar_dadd(x, n, s, *beta); } #else static constexpr bool has_scalar_dadd = false; #endif #ifdef EGBLAS_HAS_SCALAR_CADD static constexpr bool has_scalar_cadd = true; /*! * \brief Adds the scalar beta to each element of the complex single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(etl::complex<float>* x, size_t n, size_t s, etl::complex<float>* beta){ egblas_scalar_cadd(reinterpret_cast<cuComplex*>(x), n, s, *reinterpret_cast<cuComplex*>(beta)); } /*! * \brief Adds the scalar beta to each element of the complex single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(std::complex<float>* x, size_t n, size_t s, std::complex<float>* beta){ egblas_scalar_cadd(reinterpret_cast<cuComplex*>(x), n, s, *reinterpret_cast<cuComplex*>(beta)); } #else static constexpr bool has_scalar_cadd = false; #endif #ifdef EGBLAS_HAS_SCALAR_ZADD static constexpr bool has_scalar_zadd = true; /*! * \brief Adds the scalar beta to each element of the complex single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(etl::complex<double>* x, size_t n, size_t s, etl::complex<double>* beta){ egblas_scalar_zadd(reinterpret_cast<cuDoubleComplex*>(x), n, s, *reinterpret_cast<cuDoubleComplex*>(beta)); } /*! * \brief Adds the scalar beta to each element of the complex single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ inline void scalar_add(std::complex<double>* x, size_t n, size_t s, std::complex<double>* beta){ egblas_scalar_zadd(reinterpret_cast<cuDoubleComplex*>(x), n, s, *reinterpret_cast<cuDoubleComplex*>(beta)); } #else static constexpr bool has_scalar_zadd = false; #endif #ifndef ETL_EGBLAS_MODE /*! * \brief Adds the scalar beta to each element of the single-precision vector x * \param x The vector to add the scalar to (GPU pointer) * \param n The size of the vector * \param s The stride of the vector * \param beta The scalar to add */ template<typename T> inline void scalar_add(T* x, size_t n, size_t s, T* beta){ cpp_unused(x); cpp_unused(n); cpp_unused(s); cpp_unused(beta); cpp_unreachable("Invalid call to egblas::scalar_add"); } #endif } //end of namespace egblas } //end of namespace impl } //end of namespace etl <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ #include "precomp.hpp" CV_IMPL void cvCanny( const void* srcarr, void* dstarr, double low_thresh, double high_thresh, int aperture_size ) { cv::Ptr<CvMat> dx, dy; cv::AutoBuffer<char> buffer; std::vector<uchar*> stack; uchar **stack_top = 0, **stack_bottom = 0; CvMat srcstub, *src = cvGetMat( srcarr, &srcstub ); CvMat dststub, *dst = cvGetMat( dstarr, &dststub ); CvSize size; int flags = aperture_size; int low, high; int* mag_buf[3]; uchar* map; int mapstep, maxsize; int i, j; CvMat mag_row; if( CV_MAT_TYPE( src->type ) != CV_8UC1 || CV_MAT_TYPE( dst->type ) != CV_8UC1 ) CV_Error( CV_StsUnsupportedFormat, "" ); if( !CV_ARE_SIZES_EQ( src, dst )) CV_Error( CV_StsUnmatchedSizes, "" ); if( low_thresh > high_thresh ) { double t; CV_SWAP( low_thresh, high_thresh, t ); } aperture_size &= INT_MAX; if( (aperture_size & 1) == 0 || aperture_size < 3 || aperture_size > 7 ) CV_Error( CV_StsBadFlag, "" ); size = cvGetMatSize( src ); dx = cvCreateMat( size.height, size.width, CV_16SC1 ); dy = cvCreateMat( size.height, size.width, CV_16SC1 ); cvSobel( src, dx, 1, 0, aperture_size ); cvSobel( src, dy, 0, 1, aperture_size ); /*if( icvCannyGetSize_p && icvCanny_16s8u_C1R_p && !(flags & CV_CANNY_L2_GRADIENT) ) { int buf_size= 0; IPPI_CALL( icvCannyGetSize_p( size, &buf_size )); CV_CALL( buffer = cvAlloc( buf_size )); IPPI_CALL( icvCanny_16s8u_C1R_p( (short*)dx->data.ptr, dx->step, (short*)dy->data.ptr, dy->step, dst->data.ptr, dst->step, size, (float)low_thresh, (float)high_thresh, buffer )); EXIT; }*/ if( flags & CV_CANNY_L2_GRADIENT ) { Cv32suf ul, uh; ul.f = (float)low_thresh; uh.f = (float)high_thresh; low = ul.i; high = uh.i; } else { low = cvFloor( low_thresh ); high = cvFloor( high_thresh ); } buffer.allocate( (size.width+2)*(size.height+2) + (size.width+2)*3*sizeof(int) ); mag_buf[0] = (int*)(char*)buffer; mag_buf[1] = mag_buf[0] + size.width + 2; mag_buf[2] = mag_buf[1] + size.width + 2; map = (uchar*)(mag_buf[2] + size.width + 2); mapstep = size.width + 2; maxsize = MAX( 1 << 10, size.width*size.height/10 ); stack.resize( maxsize ); stack_top = stack_bottom = &stack[0]; memset( mag_buf[0], 0, (size.width+2)*sizeof(int) ); memset( map, 1, mapstep ); memset( map + mapstep*(size.height + 1), 1, mapstep ); /* sector numbers (Top-Left Origin) 1 2 3 * * * * * * 0*******0 * * * * * * 3 2 1 */ #define CANNY_PUSH(d) *(d) = (uchar)2, *stack_top++ = (d) #define CANNY_POP(d) (d) = *--stack_top mag_row = cvMat( 1, size.width, CV_32F ); // calculate magnitude and angle of gradient, perform non-maxima supression. // fill the map with one of the following values: // 0 - the pixel might belong to an edge // 1 - the pixel can not belong to an edge // 2 - the pixel does belong to an edge for( i = 0; i <= size.height; i++ ) { int* _mag = mag_buf[(i > 0) + 1] + 1; float* _magf = (float*)_mag; const short* _dx = (short*)(dx->data.ptr + dx->step*i); const short* _dy = (short*)(dy->data.ptr + dy->step*i); uchar* _map; int x, y; int magstep1, magstep2; int prev_flag = 0; if( i < size.height ) { _mag[-1] = _mag[size.width] = 0; if( !(flags & CV_CANNY_L2_GRADIENT) ) for( j = 0; j < size.width; j++ ) _mag[j] = abs(_dx[j]) + abs(_dy[j]); /*else if( icvFilterSobelVert_8u16s_C1R_p != 0 ) // check for IPP { // use vectorized sqrt mag_row.data.fl = _magf; for( j = 0; j < size.width; j++ ) { x = _dx[j]; y = _dy[j]; _magf[j] = (float)((double)x*x + (double)y*y); } cvPow( &mag_row, &mag_row, 0.5 ); }*/ else { for( j = 0; j < size.width; j++ ) { x = _dx[j]; y = _dy[j]; _magf[j] = (float)std::sqrt((double)x*x + (double)y*y); } } } else memset( _mag-1, 0, (size.width + 2)*sizeof(int) ); // at the very beginning we do not have a complete ring // buffer of 3 magnitude rows for non-maxima suppression if( i == 0 ) continue; _map = map + mapstep*i + 1; _map[-1] = _map[size.width] = 1; _mag = mag_buf[1] + 1; // take the central row _dx = (short*)(dx->data.ptr + dx->step*(i-1)); _dy = (short*)(dy->data.ptr + dy->step*(i-1)); magstep1 = (int)(mag_buf[2] - mag_buf[1]); magstep2 = (int)(mag_buf[0] - mag_buf[1]); if( (stack_top - stack_bottom) + size.width > maxsize ) { int sz = (int)(stack_top - stack_bottom); maxsize = MAX( maxsize * 3/2, maxsize + 8 ); stack.resize(maxsize); stack_bottom = &stack[0]; stack_top = stack_bottom + sz; } for( j = 0; j < size.width; j++ ) { #define CANNY_SHIFT 15 #define TG22 (int)(0.4142135623730950488016887242097*(1<<CANNY_SHIFT) + 0.5) x = _dx[j]; y = _dy[j]; int s = x ^ y; int m = _mag[j]; x = abs(x); y = abs(y); if( m > low ) { int tg22x = x * TG22; int tg67x = tg22x + ((x + x) << CANNY_SHIFT); y <<= CANNY_SHIFT; if( y < tg22x ) { if( m > _mag[j-1] && m >= _mag[j+1] ) { if( m > high && !prev_flag && _map[j-mapstep] != 2 ) { CANNY_PUSH( _map + j ); prev_flag = 1; } else _map[j] = (uchar)0; continue; } } else if( y > tg67x ) { if( m > _mag[j+magstep2] && m >= _mag[j+magstep1] ) { if( m > high && !prev_flag && _map[j-mapstep] != 2 ) { CANNY_PUSH( _map + j ); prev_flag = 1; } else _map[j] = (uchar)0; continue; } } else { s = s < 0 ? -1 : 1; if( m > _mag[j+magstep2-s] && m > _mag[j+magstep1+s] ) { if( m > high && !prev_flag && _map[j-mapstep] != 2 ) { CANNY_PUSH( _map + j ); prev_flag = 1; } else _map[j] = (uchar)0; continue; } } } prev_flag = 0; _map[j] = (uchar)1; } // scroll the ring buffer _mag = mag_buf[0]; mag_buf[0] = mag_buf[1]; mag_buf[1] = mag_buf[2]; mag_buf[2] = _mag; } // now track the edges (hysteresis thresholding) while( stack_top > stack_bottom ) { uchar* m; if( (stack_top - stack_bottom) + 8 > maxsize ) { int sz = (int)(stack_top - stack_bottom); maxsize = MAX( maxsize * 3/2, maxsize + 8 ); stack.resize(maxsize); stack_bottom = &stack[0]; stack_top = stack_bottom + sz; } CANNY_POP(m); if( !m[-1] ) CANNY_PUSH( m - 1 ); if( !m[1] ) CANNY_PUSH( m + 1 ); if( !m[-mapstep-1] ) CANNY_PUSH( m - mapstep - 1 ); if( !m[-mapstep] ) CANNY_PUSH( m - mapstep ); if( !m[-mapstep+1] ) CANNY_PUSH( m - mapstep + 1 ); if( !m[mapstep-1] ) CANNY_PUSH( m + mapstep - 1 ); if( !m[mapstep] ) CANNY_PUSH( m + mapstep ); if( !m[mapstep+1] ) CANNY_PUSH( m + mapstep + 1 ); } // the final pass, form the final image for( i = 0; i < size.height; i++ ) { const uchar* _map = map + mapstep*(i+1) + 1; uchar* _dst = dst->data.ptr + dst->step*i; for( j = 0; j < size.width; j++ ) _dst[j] = (uchar)-(_map[j] >> 1); } } void cv::Canny( const Mat& image, Mat& edges, double threshold1, double threshold2, int apertureSize, bool L2gradient ) { Mat src = image; edges.create(src.size(), CV_8U); CvMat _src = src, _dst = edges; cvCanny( &_src, &_dst, threshold1, threshold2, apertureSize + (L2gradient ? CV_CANNY_L2_GRADIENT : 0)); } /* End of file. */ <commit_msg>try to make a more elegant workaround for the incorrectly generated code in Canny (ticket #157)<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ #include "precomp.hpp" CV_IMPL void cvCanny( const void* srcarr, void* dstarr, double low_thresh, double high_thresh, int aperture_size ) { cv::Ptr<CvMat> dx, dy; cv::AutoBuffer<char> buffer; std::vector<uchar*> stack; uchar **stack_top = 0, **stack_bottom = 0; CvMat srcstub, *src = cvGetMat( srcarr, &srcstub ); CvMat dststub, *dst = cvGetMat( dstarr, &dststub ); CvSize size; int flags = aperture_size; int low, high; int* mag_buf[3]; uchar* map; int mapstep, maxsize; int i, j; CvMat mag_row; if( CV_MAT_TYPE( src->type ) != CV_8UC1 || CV_MAT_TYPE( dst->type ) != CV_8UC1 ) CV_Error( CV_StsUnsupportedFormat, "" ); if( !CV_ARE_SIZES_EQ( src, dst )) CV_Error( CV_StsUnmatchedSizes, "" ); if( low_thresh > high_thresh ) { double t; CV_SWAP( low_thresh, high_thresh, t ); } aperture_size &= INT_MAX; if( (aperture_size & 1) == 0 || aperture_size < 3 || aperture_size > 7 ) CV_Error( CV_StsBadFlag, "" ); size = cvGetMatSize( src ); dx = cvCreateMat( size.height, size.width, CV_16SC1 ); dy = cvCreateMat( size.height, size.width, CV_16SC1 ); cvSobel( src, dx, 1, 0, aperture_size ); cvSobel( src, dy, 0, 1, aperture_size ); /*if( icvCannyGetSize_p && icvCanny_16s8u_C1R_p && !(flags & CV_CANNY_L2_GRADIENT) ) { int buf_size= 0; IPPI_CALL( icvCannyGetSize_p( size, &buf_size )); CV_CALL( buffer = cvAlloc( buf_size )); IPPI_CALL( icvCanny_16s8u_C1R_p( (short*)dx->data.ptr, dx->step, (short*)dy->data.ptr, dy->step, dst->data.ptr, dst->step, size, (float)low_thresh, (float)high_thresh, buffer )); EXIT; }*/ if( flags & CV_CANNY_L2_GRADIENT ) { Cv32suf ul, uh; ul.f = (float)low_thresh; uh.f = (float)high_thresh; low = ul.i; high = uh.i; } else { low = cvFloor( low_thresh ); high = cvFloor( high_thresh ); } buffer.allocate( (size.width+2)*(size.height+2) + (size.width+2)*3*sizeof(int) ); mag_buf[0] = (int*)(char*)buffer; mag_buf[1] = mag_buf[0] + size.width + 2; mag_buf[2] = mag_buf[1] + size.width + 2; map = (uchar*)(mag_buf[2] + size.width + 2); mapstep = size.width + 2; maxsize = MAX( 1 << 10, size.width*size.height/10 ); stack.resize( maxsize ); stack_top = stack_bottom = &stack[0]; memset( mag_buf[0], 0, (size.width+2)*sizeof(int) ); memset( map, 1, mapstep ); memset( map + mapstep*(size.height + 1), 1, mapstep ); /* sector numbers (Top-Left Origin) 1 2 3 * * * * * * 0*******0 * * * * * * 3 2 1 */ #define CANNY_PUSH(d) *(d) = (uchar)2, *stack_top++ = (d) #define CANNY_POP(d) (d) = *--stack_top mag_row = cvMat( 1, size.width, CV_32F ); // calculate magnitude and angle of gradient, perform non-maxima supression. // fill the map with one of the following values: // 0 - the pixel might belong to an edge // 1 - the pixel can not belong to an edge // 2 - the pixel does belong to an edge for( i = 0; i <= size.height; i++ ) { int* _mag = mag_buf[(i > 0) + 1] + 1; float* _magf = (float*)_mag; const short* _dx = (short*)(dx->data.ptr + dx->step*i); const short* _dy = (short*)(dy->data.ptr + dy->step*i); uchar* _map; int x, y; ptrdiff_t magstep1, magstep2; int prev_flag = 0; if( i < size.height ) { _mag[-1] = _mag[size.width] = 0; if( !(flags & CV_CANNY_L2_GRADIENT) ) for( j = 0; j < size.width; j++ ) _mag[j] = abs(_dx[j]) + abs(_dy[j]); /*else if( icvFilterSobelVert_8u16s_C1R_p != 0 ) // check for IPP { // use vectorized sqrt mag_row.data.fl = _magf; for( j = 0; j < size.width; j++ ) { x = _dx[j]; y = _dy[j]; _magf[j] = (float)((double)x*x + (double)y*y); } cvPow( &mag_row, &mag_row, 0.5 ); }*/ else { for( j = 0; j < size.width; j++ ) { x = _dx[j]; y = _dy[j]; _magf[j] = (float)std::sqrt((double)x*x + (double)y*y); } } } else memset( _mag-1, 0, (size.width + 2)*sizeof(int) ); // at the very beginning we do not have a complete ring // buffer of 3 magnitude rows for non-maxima suppression if( i == 0 ) continue; _map = map + mapstep*i + 1; _map[-1] = _map[size.width] = 1; _mag = mag_buf[1] + 1; // take the central row _dx = (short*)(dx->data.ptr + dx->step*(i-1)); _dy = (short*)(dy->data.ptr + dy->step*(i-1)); magstep1 = mag_buf[2] - mag_buf[1]; magstep2 = mag_buf[0] - mag_buf[1]; if( (stack_top - stack_bottom) + size.width > maxsize ) { int sz = (int)(stack_top - stack_bottom); maxsize = MAX( maxsize * 3/2, maxsize + 8 ); stack.resize(maxsize); stack_bottom = &stack[0]; stack_top = stack_bottom + sz; } for( j = 0; j < size.width; j++ ) { #define CANNY_SHIFT 15 #define TG22 (int)(0.4142135623730950488016887242097*(1<<CANNY_SHIFT) + 0.5) x = _dx[j]; y = _dy[j]; int s = x ^ y; int m = _mag[j]; x = abs(x); y = abs(y); if( m > low ) { int tg22x = x * TG22; int tg67x = tg22x + ((x + x) << CANNY_SHIFT); y <<= CANNY_SHIFT; if( y < tg22x ) { if( m > _mag[j-1] && m >= _mag[j+1] ) { if( m > high && !prev_flag && _map[j-mapstep] != 2 ) { CANNY_PUSH( _map + j ); prev_flag = 1; } else _map[j] = (uchar)0; continue; } } else if( y > tg67x ) { if( m > _mag[j+magstep2] && m >= _mag[j+magstep1] ) { if( m > high && !prev_flag && _map[j-mapstep] != 2 ) { CANNY_PUSH( _map + j ); prev_flag = 1; } else _map[j] = (uchar)0; continue; } } else { s = s < 0 ? -1 : 1; if( m > _mag[j+magstep2-s] && m > _mag[j+magstep1+s] ) { if( m > high && !prev_flag && _map[j-mapstep] != 2 ) { CANNY_PUSH( _map + j ); prev_flag = 1; } else _map[j] = (uchar)0; continue; } } } prev_flag = 0; _map[j] = (uchar)1; } // scroll the ring buffer _mag = mag_buf[0]; mag_buf[0] = mag_buf[1]; mag_buf[1] = mag_buf[2]; mag_buf[2] = _mag; } // now track the edges (hysteresis thresholding) while( stack_top > stack_bottom ) { uchar* m; if( (stack_top - stack_bottom) + 8 > maxsize ) { int sz = (int)(stack_top - stack_bottom); maxsize = MAX( maxsize * 3/2, maxsize + 8 ); stack.resize(maxsize); stack_bottom = &stack[0]; stack_top = stack_bottom + sz; } CANNY_POP(m); if( !m[-1] ) CANNY_PUSH( m - 1 ); if( !m[1] ) CANNY_PUSH( m + 1 ); if( !m[-mapstep-1] ) CANNY_PUSH( m - mapstep - 1 ); if( !m[-mapstep] ) CANNY_PUSH( m - mapstep ); if( !m[-mapstep+1] ) CANNY_PUSH( m - mapstep + 1 ); if( !m[mapstep-1] ) CANNY_PUSH( m + mapstep - 1 ); if( !m[mapstep] ) CANNY_PUSH( m + mapstep ); if( !m[mapstep+1] ) CANNY_PUSH( m + mapstep + 1 ); } // the final pass, form the final image for( i = 0; i < size.height; i++ ) { const uchar* _map = map + mapstep*(i+1) + 1; uchar* _dst = dst->data.ptr + dst->step*i; for( j = 0; j < size.width; j++ ) _dst[j] = (uchar)-(_map[j] >> 1); } } void cv::Canny( const Mat& image, Mat& edges, double threshold1, double threshold2, int apertureSize, bool L2gradient ) { Mat src = image; edges.create(src.size(), CV_8U); CvMat _src = src, _dst = edges; cvCanny( &_src, &_dst, threshold1, threshold2, apertureSize + (L2gradient ? CV_CANNY_L2_GRADIENT : 0)); } /* End of file. */ <|endoftext|>
<commit_before>// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_ISTRING_HPP #define TAO_PEGTL_INTERNAL_ISTRING_HPP #include <type_traits> #include "../config.hpp" #include "bump_help.hpp" #include "enable_control.hpp" #include "one.hpp" #include "result_on_found.hpp" #include "success.hpp" #include "../type_list.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< char C > inline constexpr bool is_alpha = ( ( 'a' <= C ) && ( C <= 'z' ) ) || ( ( 'A' <= C ) && ( C <= 'Z' ) ); template< char C > [[nodiscard]] bool ichar_equal( const char c ) noexcept { if constexpr( is_alpha< C > ) { return ( C | 0x20 ) == ( c | 0x20 ); } else { return c == C; } } template< char... Cs > [[nodiscard]] bool istring_equal( const char* r ) noexcept { return ( ichar_equal< Cs >( *r++ ) && ... ); } template< char... Cs > struct istring; template<> struct istring<> : success {}; template< char... Cs > struct istring { using rule_t = istring; using subs_t = empty_list; template< int Eol > static constexpr bool can_match_eol = one< result_on_found::success, peek_char, Cs... >::template can_match_eol< Eol >; template< typename ParseInput > [[nodiscard]] static bool match( ParseInput& in ) noexcept( noexcept( in.size( 0 ) ) ) { if( in.size( sizeof...( Cs ) ) >= sizeof...( Cs ) ) { if( istring_equal< Cs... >( in.current() ) ) { bump_help< istring >( in, sizeof...( Cs ) ); return true; } } return false; } }; template< char... Cs > inline constexpr bool enable_control< istring< Cs... > > = false; } // namespace TAO_PEGTL_NAMESPACE::internal #endif <commit_msg>More constexpr.<commit_after>// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_ISTRING_HPP #define TAO_PEGTL_INTERNAL_ISTRING_HPP #include <type_traits> #include "../config.hpp" #include "bump_help.hpp" #include "enable_control.hpp" #include "one.hpp" #include "result_on_found.hpp" #include "success.hpp" #include "../type_list.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< char C > inline constexpr bool is_alpha = ( ( 'a' <= C ) && ( C <= 'z' ) ) || ( ( 'A' <= C ) && ( C <= 'Z' ) ); template< char C > [[nodiscard]] constexpr bool ichar_equal( const char c ) noexcept { if constexpr( is_alpha< C > ) { return ( C | 0x20 ) == ( c | 0x20 ); } else { return c == C; } } template< char... Cs > [[nodiscard]] constexpr bool istring_equal( const char* r ) noexcept { return ( ichar_equal< Cs >( *r++ ) && ... ); } template< char... Cs > struct istring; template<> struct istring<> : success {}; // template< char C > // struct istring< C > // : std::conditional_t< is_alpha< C >, one< result_on_found::success, peek_char, C | 0x20, C & ~0x20 >, one< result_on_found::success, peek_char, C > > // {}; template< char... Cs > struct istring { using rule_t = istring; using subs_t = empty_list; template< int Eol > static constexpr bool can_match_eol = one< result_on_found::success, peek_char, Cs... >::template can_match_eol< Eol >; template< typename ParseInput > [[nodiscard]] static bool match( ParseInput& in ) noexcept( noexcept( in.size( 0 ) ) ) { if( in.size( sizeof...( Cs ) ) >= sizeof...( Cs ) ) { if( istring_equal< Cs... >( in.current() ) ) { bump_help< istring >( in, sizeof...( Cs ) ); return true; } } return false; } }; template< char... Cs > inline constexpr bool enable_control< istring< Cs... > > = false; } // namespace TAO_PEGTL_NAMESPACE::internal #endif <|endoftext|>
<commit_before>#pragma once #ifndef __VALIJSON_OPTIONAL_HPP #define __VALIJSON_OPTIONAL_HPP // This should be removed once C++17 is widely available #if __has_include(<optional>) && __cplusplus >= 201703 # include <optional> namespace opt = std; #else # include <compat/optional.hpp> namespace opt = std::experimental; #endif #endif <commit_msg>Minor change to internal/optional.hp so that __has_include is used only if __cplusplus >= 201703<commit_after>#pragma once #ifndef __VALIJSON_OPTIONAL_HPP #define __VALIJSON_OPTIONAL_HPP #if __cplusplus >= 201703 // Visual C++ only supports __has_include in versions 14.12 and greater # if !defined(_MSC_VER) || _MSC_VER >= 1912 # if __has_include(<optional>) # include <optional> namespace opt = std; # endif # endif #else # include <compat/optional.hpp> namespace opt = std::experimental; #endif #endif <|endoftext|>
<commit_before>//===-- io.cpp ------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // I/O routines for registered fd's // //===----------------------------------------------------------------------===// #include "ipcopt.h" #include "debug.h" #include "ipcd.h" #include "ipcreg_internal.h" #include "real.h" #include <cassert> #include <sched.h> const size_t TRANS_THRESHOLD = 1ULL << 20; const size_t MAX_SYNC_ATTEMPTS = 5; void copy_bufsize(int src, int dst, int buftype) { int bufsize; socklen_t sz = sizeof(bufsize); int ret = getsockopt(src, SOL_SOCKET, buftype, &bufsize, &sz); assert(!ret); // ipclog("Bufsize %d of fd %d: %d\n", buftype, src, bufsize); ret = setsockopt(dst, SOL_SOCKET, buftype, &bufsize, sz); assert(!ret); } void copy_bufsizes(int src, int dst) { copy_bufsize(src, dst, SO_RCVBUF); copy_bufsize(src, dst, SO_SNDBUF); } typedef ssize_t (*IOFunc)(...); template <typename buf_t> ssize_t do_ipc_io(int fd, buf_t buf, size_t count, int flags, IOFunc IO) { endpoint ep = getEP(fd); ipc_info &i = getInfo(ep); assert(i.state != STATE_INVALID); // If localized, just use fast socket: if (i.state == STATE_OPTIMIZED) { ssize_t ret = IO(i.localfd, buf, count, flags); if (ret != -1) { i.bytes_trans += ret; } return ret; } // Otherwise, use original fd: ssize_t rem = (TRANS_THRESHOLD - i.bytes_trans); if (rem > 0 && size_t(rem) <= count) { ssize_t ret = IO(fd, buf, rem, flags); if (ret == -1) { return ret; } i.bytes_trans += ret; if (i.bytes_trans == TRANS_THRESHOLD) { ipclog("Completed partial operation to sync at THRESHOLD for fd=%d!\n", fd); // TODO: Async! endpoint remote; size_t attempts = 0; while (((remote = ipcd_endpoint_kludge(ep)) == EP_INVALID) && ++attempts < MAX_SYNC_ATTEMPTS) { sched_yield(); } if (valid_ep(remote)) { ipclog("Found remote endpoint! Local=%d, Remote=%d Attempts=%zu!\n", ep, remote, attempts); bool success = ipcd_localize(ep, remote); assert(success && "Failed to localize! Sadtimes! :("); i.localfd = getlocalfd(fd); i.state = STATE_OPTIMIZED; // Configure localfd copy_bufsizes(fd, i.localfd); set_local_nonblocking(fd, i.non_blocking); } } return ret; } ssize_t ret = IO(fd, buf, count, flags); // We don't handle other states yet assert(i.state == STATE_UNOPT); if (ret == -1) return ret; // Successful operation, add to running total. i.bytes_trans += ret; return ret; } ssize_t do_ipc_send(int fd, const void *buf, size_t count, int flags) { return do_ipc_io(fd, buf, count, flags, (IOFunc)__real_send); } ssize_t do_ipc_recv(int fd, void *buf, size_t count, int flags) { return do_ipc_io(fd, buf, count, flags, (IOFunc)__real_recv); } ssize_t do_ipc_sendto(int fd, const void *message, size_t length, int flags, const struct sockaddr *dest_addr, socklen_t /* unused */) { // if (dest_addr) // return __real_sendto(fd, message, length, flags, dest_addr, dest_len); // Hardly safe, but if it's non-NULL there's a chance // the caller might want us to write something there. assert(!dest_addr); // As a bonus from the above check, we can forward to plain send() return do_ipc_send(fd, message, length, flags); } ssize_t do_ipc_recvfrom(int fd, void *buffer, size_t length, int flags, struct sockaddr *address, socklen_t * /* unused */) { // if (address) // return __real_recvfrom(fd, buffer, length, flags, address, address_len); // Hardly safe, but if it's non-NULL there's a chance // the caller might want us to write something there. assert(!address); // As a bonus from the above check, we can forward to plain recv() return do_ipc_recv(fd, buffer, length, flags); } <commit_msg>libipc: After first notifying ipcd of endpoint kludge, wait 100ms.<commit_after>//===-- io.cpp ------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // I/O routines for registered fd's // //===----------------------------------------------------------------------===// #include "ipcopt.h" #include "debug.h" #include "ipcd.h" #include "ipcreg_internal.h" #include "real.h" #include <cassert> #include <sched.h> const size_t TRANS_THRESHOLD = 1ULL << 20; const size_t MAX_SYNC_ATTEMPTS = 5; void copy_bufsize(int src, int dst, int buftype) { int bufsize; socklen_t sz = sizeof(bufsize); int ret = getsockopt(src, SOL_SOCKET, buftype, &bufsize, &sz); assert(!ret); // ipclog("Bufsize %d of fd %d: %d\n", buftype, src, bufsize); ret = setsockopt(dst, SOL_SOCKET, buftype, &bufsize, sz); assert(!ret); } void copy_bufsizes(int src, int dst) { copy_bufsize(src, dst, SO_RCVBUF); copy_bufsize(src, dst, SO_SNDBUF); } typedef ssize_t (*IOFunc)(...); template <typename buf_t> ssize_t do_ipc_io(int fd, buf_t buf, size_t count, int flags, IOFunc IO) { endpoint ep = getEP(fd); ipc_info &i = getInfo(ep); assert(i.state != STATE_INVALID); // If localized, just use fast socket: if (i.state == STATE_OPTIMIZED) { ssize_t ret = IO(i.localfd, buf, count, flags); if (ret != -1) { i.bytes_trans += ret; } return ret; } // Otherwise, use original fd: ssize_t rem = (TRANS_THRESHOLD - i.bytes_trans); if (rem > 0 && size_t(rem) <= count) { ssize_t ret = IO(fd, buf, rem, flags); if (ret == -1) { return ret; } i.bytes_trans += ret; if (i.bytes_trans == TRANS_THRESHOLD) { ipclog("Completed partial operation to sync at THRESHOLD for fd=%d!\n", fd); // TODO: Async! endpoint remote; size_t attempts = 0; remote = ipcd_endpoint_kludge(ep); if (remote == EP_INVALID) usleep(100000); while (((remote = ipcd_endpoint_kludge(ep)) == EP_INVALID) && ++attempts < MAX_SYNC_ATTEMPTS) { sched_yield(); } if (valid_ep(remote)) { ipclog("Found remote endpoint! Local=%d, Remote=%d Attempts=%zu!\n", ep, remote, attempts); bool success = ipcd_localize(ep, remote); assert(success && "Failed to localize! Sadtimes! :("); i.localfd = getlocalfd(fd); i.state = STATE_OPTIMIZED; // Configure localfd copy_bufsizes(fd, i.localfd); set_local_nonblocking(fd, i.non_blocking); } } return ret; } ssize_t ret = IO(fd, buf, count, flags); // We don't handle other states yet assert(i.state == STATE_UNOPT); if (ret == -1) return ret; // Successful operation, add to running total. i.bytes_trans += ret; return ret; } ssize_t do_ipc_send(int fd, const void *buf, size_t count, int flags) { return do_ipc_io(fd, buf, count, flags, (IOFunc)__real_send); } ssize_t do_ipc_recv(int fd, void *buf, size_t count, int flags) { return do_ipc_io(fd, buf, count, flags, (IOFunc)__real_recv); } ssize_t do_ipc_sendto(int fd, const void *message, size_t length, int flags, const struct sockaddr *dest_addr, socklen_t /* unused */) { // if (dest_addr) // return __real_sendto(fd, message, length, flags, dest_addr, dest_len); // Hardly safe, but if it's non-NULL there's a chance // the caller might want us to write something there. assert(!dest_addr); // As a bonus from the above check, we can forward to plain send() return do_ipc_send(fd, message, length, flags); } ssize_t do_ipc_recvfrom(int fd, void *buffer, size_t length, int flags, struct sockaddr *address, socklen_t * /* unused */) { // if (address) // return __real_recvfrom(fd, buffer, length, flags, address, address_len); // Hardly safe, but if it's non-NULL there's a chance // the caller might want us to write something there. assert(!address); // As a bonus from the above check, we can forward to plain recv() return do_ipc_recv(fd, buffer, length, flags); } <|endoftext|>
<commit_before>#include "SysControl.h" #include "ControlsApp.h" #include "ControlsXPad360.h" #include "Engine.h" #include "App.h" //ƽַ̨ #ifdef _WIN32 #pragma execution_character_set("utf-8") #endif using namespace MathLib; class CSysControlLocal : public CSysControl { public: CSysControlLocal(); virtual ~CSysControlLocal(); virtual void Init(); //ɫҪʼɫҪʼ virtual void Update(float ifps); virtual void Shutdown(); virtual int GetState(int state); //״̬״̬״̬ӵ״̬ȵȡ virtual int ClearState(int state); virtual float GetMouseDX(); virtual float GetMouseDY(); virtual void SetMouseGrab(int g); //Ƿʾ virtual int GetMouseGrab(); //ȡ״̬ʾػDzʾ״̬ virtual void SetControlMode(ControlMode mode); //ģʽ virtual ControlMode GetControlMode() const; //ȡģʽ private: void Update_Mouse(float ifps); void Update_Keyboard(float ifps); void Update_XPad360(float ifps); CControlsApp *m_pControlsApp; //Ϸƶ CControlsXPad360 *m_pControlsXPad360; ControlMode m_nControlMode; //ģʽ int m_nOldMouseX; //һX int m_nOldMouseY; //һY CObjectGui *m_pTest3DUI; CWidgetLabel *m_pTestMessageLabel; }; CSysControlLocal::CSysControlLocal() { } CSysControlLocal::~CSysControlLocal() { } void CSysControlLocal::Init() { m_pControlsApp = new CControlsApp; m_pControlsXPad360 = new CControlsXPad360(0); g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); SetControlMode(CONTROL_KEYBORAD_MOUSE); m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/"); m_pTest3DUI->SetMouseShow(0); m_pTest3DUI->SetBackground(1); m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f)); m_pTest3DUI->SetScreenSize(800, 400); m_pTest3DUI->SetControlDistance(1000.0f); m_pTest3DUI->CreateMaterial("gui_base"); //show in game m_nOldMouseX = 0; m_nOldMouseY = 0; } <commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "SysControl.h" #include "ControlsApp.h" #include "ControlsXPad360.h" #include "Engine.h" #include "App.h" //ƽַ̨ #ifdef _WIN32 #pragma execution_character_set("utf-8") #endif using namespace MathLib; class CSysControlLocal : public CSysControl { public: CSysControlLocal(); virtual ~CSysControlLocal(); virtual void Init(); //ɫҪʼɫҪʼ virtual void Update(float ifps); virtual void Shutdown(); virtual int GetState(int state); //״̬״̬״̬ӵ״̬ȵȡ virtual int ClearState(int state); virtual float GetMouseDX(); virtual float GetMouseDY(); virtual void SetMouseGrab(int g); //Ƿʾ virtual int GetMouseGrab(); //ȡ״̬ʾػDzʾ״̬ virtual void SetControlMode(ControlMode mode); //ģʽ virtual ControlMode GetControlMode() const; //ȡģʽ private: void Update_Mouse(float ifps); void Update_Keyboard(float ifps); void Update_XPad360(float ifps); CControlsApp *m_pControlsApp; //Ϸƶ CControlsXPad360 *m_pControlsXPad360; ControlMode m_nControlMode; //ģʽ int m_nOldMouseX; //һX int m_nOldMouseY; //һY CObjectGui *m_pTest3DUI; CWidgetLabel *m_pTestMessageLabel; }; CSysControlLocal::CSysControlLocal() { } CSysControlLocal::~CSysControlLocal() { } void CSysControlLocal::Init() { m_pControlsApp = new CControlsApp; m_pControlsXPad360 = new CControlsXPad360(0); g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); SetControlMode(CONTROL_KEYBORAD_MOUSE); m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/"); m_pTest3DUI->SetMouseShow(0); m_pTest3DUI->SetBackground(1); m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f)); m_pTest3DUI->SetScreenSize(800, 400); m_pTest3DUI->SetControlDistance(1000.0f); m_pTest3DUI->CreateMaterial("gui_base"); //show in game m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f))); m_nOldMouseX = 0; m_nOldMouseY = 0; } <|endoftext|>
<commit_before>/* * Thread.cpp 15.08.2006 (mueller) * * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. */ #include "vislib/Thread.h" #ifndef _WIN32 #include <unistd.h> #endif /* !_WIN32 */ #include "vislib/assert.h" #include "vislib/error.h" #include "vislib/IllegalParamException.h" #include "vislib/IllegalStateException.h" #include "vislib/SystemException.h" #include "vislib/Trace.h" #include "vislib/UnsupportedOperationException.h" #include "DynamicFunctionPointer.h" #include <cstdio> #include <iostream> #ifndef _WIN32 /** * Return code that marks a thread as still running. Make sure that the value * is the same as on Windows. */ #define STILL_ACTIVE (259) #endif /* !_WIN32 */ /* * vislib::sys::Thread::Sleep */ void vislib::sys::Thread::Sleep(const DWORD millis) { #ifdef _WIN32 ::Sleep(millis); #else /* _WIN32 */ if (millis >= 1000) { /* At least one second to sleep. Use ::sleep() for full seconds. */ ::sleep(millis / 1000); } ::usleep((millis % 1000) * 1000); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Reschedule */ void vislib::sys::Thread::Reschedule(void) { #ifdef _WIN32 #if (_WIN32_WINNT >= 0x0400) ::SwitchToThread(); #else DynamicFunctionPointer<BOOL (*)(void)> stt("kernel32", "SwitchToThread"); if (stt.IsValid()) { stt(); } else { ::Sleep(0); } #endif #else /* _WIN32 */ if (::sched_yield() != 0) { throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable *runnable) : id(0), runnable(runnable), runnableFunc(NULL) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable::Function runnableFunc) : id(0), runnable(NULL), runnableFunc(runnableFunc) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::~Thread */ vislib::sys::Thread::~Thread(void) { #ifdef _WIN32 if (this->handle != NULL) { ::CloseHandle(this->handle); } #else /* _WIIN32 */ ::pthread_detach(this->id); ::pthread_attr_destroy(&this->attribs); #endif /* _WIN32 */ } /* * vislib::sys::Thread::GetExitCode */ DWORD vislib::sys::Thread::GetExitCode(void) const { #ifdef _WIN32 DWORD retval = 0; if (::GetExitCodeThread(this->handle, &retval) == FALSE) { throw SystemException(__FILE__, __LINE__); } return retval; #else /* _WIN32 */ return this->exitCode; #endif /* _WIN32 */ } /* * vislib::sys::Thread::IsRunning */ bool vislib::sys::Thread::IsRunning(void) const { try { return (this->GetExitCode() == STILL_ACTIVE); } catch (SystemException) { return false; } } /* * vislib::sys::Thread::Join */ void vislib::sys::Thread::Join(void) { #ifdef _WIN32 if (this->handle != NULL) { if (::WaitForSingleObject(this->handle, INFINITE) == WAIT_FAILED) { throw SystemException(__FILE__, __LINE__); } } #else /* _WIN32 */ if (this->id != 0) { if (::pthread_join(this->id, NULL) != 0) { throw SystemException(__FILE__, __LINE__); } } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Start */ bool vislib::sys::Thread::Start(void *userData) { if (this->IsRunning()) { /* * The thread must not be started twice at the same time as this would * leave unclosed handles. */ return false; } /* Set the user data. */ this->threadFuncParam.userData = userData; #ifdef _WIN32 /* Close possible old handle. */ if (this->handle != NULL) { ::CloseHandle(this->handle); } if ((this->handle = ::CreateThread(NULL, 0, Thread::ThreadFunc, &this->threadFuncParam, 0, &this->id)) != NULL) { return true; } else { TRACE(Trace::LEVEL_VL_ERROR, "CreateThread() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #else /* _WIN32 */ if (::pthread_create(&this->id, &this->attribs, Thread::ThreadFunc, static_cast<void *>(&this->threadFuncParam)) == 0) { this->exitCode = STILL_ACTIVE; // Mark thread as running. return true; } else { TRACE(Trace::LEVEL_VL_ERROR, "pthread_create() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Terminate */ bool vislib::sys::Thread::Terminate(const bool forceTerminate, const int exitCode) { ASSERT(exitCode != STILL_ACTIVE); // User should never set this. if (forceTerminate) { /* Force immediate termination of the thread. */ #ifdef _WIN32 if (::TerminateThread(this->handle, exitCode) == FALSE) { TRACE(Trace::LEVEL_VL_ERROR, "TerminateThread() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #else /* _WIN32 */ if (::pthread_cancel(this->id) != 0) { TRACE(Trace::LEVEL_VL_ERROR, "pthread_cancel() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #endif /* _WIN32 */ } else { return this->TryTerminate(true); } /* end if (forceTerminate) */ } /* * vislib::sys::Thread::TryTerminate */ bool vislib::sys::Thread::TryTerminate(const bool doWait) { if (this->runnable == NULL) { throw IllegalStateException("TryTerminate can only be used, if the " "thread is using a Runnable.", __FILE__, __LINE__); } ASSERT(this->runnable != NULL); if (this->runnable->Terminate()) { /* * Wait for thread to finish, if Runnable acknowledged and waiting was * requested. */ if (doWait) { this->Join(); } return true; } else { /* Runnable did not acknowledge. */ return false; } } #ifndef _WIN32 /* * vislib::sys::Thread::CleanupFunc */ void vislib::sys::Thread::CleanupFunc(void *param) { ASSERT(param != NULL); Thread *t = static_cast<Thread *>(param); /* * In case the thread has still an exit code of STILL_ACTIVE, set a new one * to mark the thread as finished. */ if (t->exitCode == STILL_ACTIVE) { TRACE(Trace::LEVEL_VL_WARN, "CleanupFunc called with exit code " "STILL_ACTIVE"); t->exitCode = 0; } } #endif /* !_WIN32 */ /* * vislib::sys::Thread::ThreadFunc */ #ifdef _WIN32 DWORD WINAPI vislib::sys::Thread::ThreadFunc(void *param) { #else /* _WIN32 */ void *vislib::sys::Thread::ThreadFunc(void *param) { #endif /* _WIN32 */ ASSERT(param != NULL); int retval = 0; ThreadFuncParam *tfp = static_cast<ThreadFuncParam *>(param); Thread *t = tfp->thread; ASSERT(t != NULL); #ifndef _WIN32 pthread_cleanup_push(Thread::CleanupFunc, t); #endif /* !_WIN32 */ if (t->runnable != NULL) { retval = t->runnable->Run(tfp->userData); } else { ASSERT(t->runnableFunc != NULL); retval = t->runnableFunc(tfp->userData); } ASSERT(retval != STILL_ACTIVE); // Thread should never use STILL_ACTIVE! #ifndef _WIN32 t->exitCode = retval; pthread_cleanup_pop(1); #endif /* !_WIN32 */ TRACE(Trace::LEVEL_VL_INFO, "Thread [%u] has exited with code %d (0x%x).\n", t->id, retval, retval); #ifdef _WIN32 return static_cast<DWORD>(retval); #else /* _WIN32 */ return reinterpret_cast<void *>(retval); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(const Thread& rhs) { throw UnsupportedOperationException("vislib::sys::Thread::Thread", __FILE__, __LINE__); } /* * vislib::sys::Thread::operator = */ vislib::sys::Thread& vislib::sys::Thread::operator =(const Thread& rhs) { if (this != &rhs) { throw IllegalParamException("rhs_", __FILE__, __LINE__); } return *this; } <commit_msg>pthread_detach hotfix.<commit_after>/* * Thread.cpp 15.08.2006 (mueller) * * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. */ #include "vislib/Thread.h" #ifndef _WIN32 #include <unistd.h> #endif /* !_WIN32 */ #include "vislib/assert.h" #include "vislib/error.h" #include "vislib/IllegalParamException.h" #include "vislib/IllegalStateException.h" #include "vislib/SystemException.h" #include "vislib/Trace.h" #include "vislib/UnsupportedOperationException.h" #include "DynamicFunctionPointer.h" #include <cstdio> #include <iostream> #ifndef _WIN32 /** * Return code that marks a thread as still running. Make sure that the value * is the same as on Windows. */ #define STILL_ACTIVE (259) #endif /* !_WIN32 */ /* * vislib::sys::Thread::Sleep */ void vislib::sys::Thread::Sleep(const DWORD millis) { #ifdef _WIN32 ::Sleep(millis); #else /* _WIN32 */ if (millis >= 1000) { /* At least one second to sleep. Use ::sleep() for full seconds. */ ::sleep(millis / 1000); } ::usleep((millis % 1000) * 1000); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Reschedule */ void vislib::sys::Thread::Reschedule(void) { #ifdef _WIN32 #if (_WIN32_WINNT >= 0x0400) ::SwitchToThread(); #else DynamicFunctionPointer<BOOL (*)(void)> stt("kernel32", "SwitchToThread"); if (stt.IsValid()) { stt(); } else { ::Sleep(0); } #endif #else /* _WIN32 */ if (::sched_yield() != 0) { throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable *runnable) : id(0), runnable(runnable), runnableFunc(NULL) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable::Function runnableFunc) : id(0), runnable(NULL), runnableFunc(runnableFunc) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::~Thread */ vislib::sys::Thread::~Thread(void) { #ifdef _WIN32 if (this->handle != NULL) { ::CloseHandle(this->handle); } #else /* _WIIN32 */ // TODO: Dirty hack, don't know whether this is always working. if (this->id != 0) { ::pthread_detach(this->id); ::pthread_attr_destroy(&this->attribs); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::GetExitCode */ DWORD vislib::sys::Thread::GetExitCode(void) const { #ifdef _WIN32 DWORD retval = 0; if (::GetExitCodeThread(this->handle, &retval) == FALSE) { throw SystemException(__FILE__, __LINE__); } return retval; #else /* _WIN32 */ return this->exitCode; #endif /* _WIN32 */ } /* * vislib::sys::Thread::IsRunning */ bool vislib::sys::Thread::IsRunning(void) const { try { return (this->GetExitCode() == STILL_ACTIVE); } catch (SystemException) { return false; } } /* * vislib::sys::Thread::Join */ void vislib::sys::Thread::Join(void) { #ifdef _WIN32 if (this->handle != NULL) { if (::WaitForSingleObject(this->handle, INFINITE) == WAIT_FAILED) { throw SystemException(__FILE__, __LINE__); } } #else /* _WIN32 */ if (this->id != 0) { if (::pthread_join(this->id, NULL) != 0) { throw SystemException(__FILE__, __LINE__); } } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Start */ bool vislib::sys::Thread::Start(void *userData) { if (this->IsRunning()) { /* * The thread must not be started twice at the same time as this would * leave unclosed handles. */ return false; } /* Set the user data. */ this->threadFuncParam.userData = userData; #ifdef _WIN32 /* Close possible old handle. */ if (this->handle != NULL) { ::CloseHandle(this->handle); } if ((this->handle = ::CreateThread(NULL, 0, Thread::ThreadFunc, &this->threadFuncParam, 0, &this->id)) != NULL) { return true; } else { TRACE(Trace::LEVEL_VL_ERROR, "CreateThread() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #else /* _WIN32 */ if (::pthread_create(&this->id, &this->attribs, Thread::ThreadFunc, static_cast<void *>(&this->threadFuncParam)) == 0) { this->exitCode = STILL_ACTIVE; // Mark thread as running. return true; } else { TRACE(Trace::LEVEL_VL_ERROR, "pthread_create() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Terminate */ bool vislib::sys::Thread::Terminate(const bool forceTerminate, const int exitCode) { ASSERT(exitCode != STILL_ACTIVE); // User should never set this. if (forceTerminate) { /* Force immediate termination of the thread. */ #ifdef _WIN32 if (::TerminateThread(this->handle, exitCode) == FALSE) { TRACE(Trace::LEVEL_VL_ERROR, "TerminateThread() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #else /* _WIN32 */ if (::pthread_cancel(this->id) != 0) { TRACE(Trace::LEVEL_VL_ERROR, "pthread_cancel() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #endif /* _WIN32 */ } else { return this->TryTerminate(true); } /* end if (forceTerminate) */ } /* * vislib::sys::Thread::TryTerminate */ bool vislib::sys::Thread::TryTerminate(const bool doWait) { if (this->runnable == NULL) { throw IllegalStateException("TryTerminate can only be used, if the " "thread is using a Runnable.", __FILE__, __LINE__); } ASSERT(this->runnable != NULL); if (this->runnable->Terminate()) { /* * Wait for thread to finish, if Runnable acknowledged and waiting was * requested. */ if (doWait) { this->Join(); } return true; } else { /* Runnable did not acknowledge. */ return false; } } #ifndef _WIN32 /* * vislib::sys::Thread::CleanupFunc */ void vislib::sys::Thread::CleanupFunc(void *param) { ASSERT(param != NULL); Thread *t = static_cast<Thread *>(param); /* * In case the thread has still an exit code of STILL_ACTIVE, set a new one * to mark the thread as finished. */ if (t->exitCode == STILL_ACTIVE) { TRACE(Trace::LEVEL_VL_WARN, "CleanupFunc called with exit code " "STILL_ACTIVE"); t->exitCode = 0; } } #endif /* !_WIN32 */ /* * vislib::sys::Thread::ThreadFunc */ #ifdef _WIN32 DWORD WINAPI vislib::sys::Thread::ThreadFunc(void *param) { #else /* _WIN32 */ void *vislib::sys::Thread::ThreadFunc(void *param) { #endif /* _WIN32 */ ASSERT(param != NULL); int retval = 0; ThreadFuncParam *tfp = static_cast<ThreadFuncParam *>(param); Thread *t = tfp->thread; ASSERT(t != NULL); #ifndef _WIN32 pthread_cleanup_push(Thread::CleanupFunc, t); #endif /* !_WIN32 */ if (t->runnable != NULL) { retval = t->runnable->Run(tfp->userData); } else { ASSERT(t->runnableFunc != NULL); retval = t->runnableFunc(tfp->userData); } ASSERT(retval != STILL_ACTIVE); // Thread should never use STILL_ACTIVE! #ifndef _WIN32 t->exitCode = retval; pthread_cleanup_pop(1); #endif /* !_WIN32 */ TRACE(Trace::LEVEL_VL_INFO, "Thread [%u] has exited with code %d (0x%x).\n", t->id, retval, retval); #ifdef _WIN32 return static_cast<DWORD>(retval); #else /* _WIN32 */ return reinterpret_cast<void *>(retval); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(const Thread& rhs) { throw UnsupportedOperationException("vislib::sys::Thread::Thread", __FILE__, __LINE__); } /* * vislib::sys::Thread::operator = */ vislib::sys::Thread& vislib::sys::Thread::operator =(const Thread& rhs) { if (this != &rhs) { throw IllegalParamException("rhs_", __FILE__, __LINE__); } return *this; } <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org copyright : (C) 2010 by Alex Novichkov email : novichko@atnet.ru (added APE file support) ***************************************************************************/ /*************************************************************************** * 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., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tfile.h> #include <tstring.h> #include <tdebug.h> #include "trefcounter.h" #include "fileref.h" #include "asffile.h" #include "mpegfile.h" #include "vorbisfile.h" #include "flacfile.h" #include "oggflacfile.h" #include "mpcfile.h" #include "mp4file.h" #include "wavpackfile.h" #include "speexfile.h" #include "opusfile.h" #include "trueaudiofile.h" #include "aifffile.h" #include "wavfile.h" #include "apefile.h" #include "modfile.h" #include "s3mfile.h" #include "itfile.h" #include "xmfile.h" using namespace TagLib; class FileRef::FileRefPrivate : public RefCounter { public: FileRefPrivate(File *f) : RefCounter(), file(f) {} ~FileRefPrivate() { delete file; } File *file; static List<const FileTypeResolver *> fileTypeResolvers; }; List<const FileRef::FileTypeResolver *> FileRef::FileRefPrivate::fileTypeResolvers; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// FileRef::FileRef() { d = new FileRefPrivate(0); } FileRef::FileRef(FileName fileName, bool readAudioProperties, AudioProperties::ReadStyle audioPropertiesStyle) { d = new FileRefPrivate(create(fileName, readAudioProperties, audioPropertiesStyle)); } FileRef::FileRef(File *file) { d = new FileRefPrivate(file); } FileRef::FileRef(const FileRef &ref) : d(ref.d) { d->ref(); } FileRef::~FileRef() { if(d->deref()) delete d; } Tag *FileRef::tag() const { if(isNull()) { debug("FileRef::tag() - Called without a valid file."); return 0; } return d->file->tag(); } AudioProperties *FileRef::audioProperties() const { if(isNull()) { debug("FileRef::audioProperties() - Called without a valid file."); return 0; } return d->file->audioProperties(); } File *FileRef::file() const { return d->file; } bool FileRef::save() { if(isNull()) { debug("FileRef::save() - Called without a valid file."); return false; } return d->file->save(); } const FileRef::FileTypeResolver *FileRef::addFileTypeResolver(const FileRef::FileTypeResolver *resolver) // static { FileRefPrivate::fileTypeResolvers.prepend(resolver); return resolver; } StringList FileRef::defaultFileExtensions() { StringList l; l.append("ogg"); l.append("flac"); l.append("oga"); l.append("mp3"); l.append("mpc"); l.append("wv"); l.append("spx"); l.append("tta"); l.append("m4a"); l.append("m4r"); l.append("m4b"); l.append("m4p"); l.append("3g2"); l.append("mp4"); l.append("wma"); l.append("asf"); l.append("aif"); l.append("aiff"); l.append("wav"); l.append("ape"); l.append("mod"); l.append("module"); // alias for "mod" l.append("nst"); // alias for "mod" l.append("wow"); // alias for "mod" l.append("s3m"); l.append("it"); l.append("xm"); return l; } bool FileRef::isNull() const { return !d->file || !d->file->isValid(); } FileRef &FileRef::operator=(const FileRef &ref) { if(&ref == this) return *this; if(d->deref()) delete d; d = ref.d; d->ref(); return *this; } bool FileRef::operator==(const FileRef &ref) const { return ref.d->file == d->file; } bool FileRef::operator!=(const FileRef &ref) const { return ref.d->file != d->file; } File *FileRef::create(FileName fileName, bool readAudioProperties, AudioProperties::ReadStyle audioPropertiesStyle) // static { List<const FileTypeResolver *>::ConstIterator it = FileRefPrivate::fileTypeResolvers.begin(); for(; it != FileRefPrivate::fileTypeResolvers.end(); ++it) { File *file = (*it)->createFile(fileName, readAudioProperties, audioPropertiesStyle); if(file) return file; } // Ok, this is really dumb for now, but it works for testing. String ext; { #ifdef _WIN32 String s = fileName.toString(); #else String s = fileName; #endif const int pos = s.rfind("."); if(pos != -1) ext = s.substr(pos + 1).upper(); } // If this list is updated, the method defaultFileExtensions() should also be // updated. However at some point that list should be created at the same time // that a default file type resolver is created. if(!ext.isEmpty()) { if(ext == "MP3") return new MPEG::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "OGG") return new Ogg::Vorbis::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "OGA") { /* .oga can be any audio in the Ogg container. First try FLAC, then Vorbis. */ File *file = new Ogg::FLAC::File(fileName, readAudioProperties, audioPropertiesStyle); if (file->isValid()) return file; delete file; return new Ogg::Vorbis::File(fileName, readAudioProperties, audioPropertiesStyle); } if(ext == "FLAC") return new FLAC::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "MPC") return new MPC::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "WV") return new WavPack::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "SPX") return new Ogg::Speex::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "OPUS") return new Ogg::Opus::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "TTA") return new TrueAudio::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "M4A" || ext == "M4R" || ext == "M4B" || ext == "M4P" || ext == "MP4" || ext == "3G2") return new MP4::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "WMA" || ext == "ASF") return new ASF::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "AIF" || ext == "AIFF" || ext == "AFC" || ext == "AIFC") return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "WAV") return new RIFF::WAV::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "APE") return new APE::File(fileName, readAudioProperties, audioPropertiesStyle); // module, nst and wow are possible but uncommon extensions if(ext == "MOD" || ext == "MODULE" || ext == "NST" || ext == "WOW") return new Mod::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "S3M") return new S3M::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "IT") return new IT::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "XM") return new XM::File(fileName, readAudioProperties, audioPropertiesStyle); } return 0; } <commit_msg>Add support for M4V tag parsing<commit_after>/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org copyright : (C) 2010 by Alex Novichkov email : novichko@atnet.ru (added APE file support) ***************************************************************************/ /*************************************************************************** * 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., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tfile.h> #include <tstring.h> #include <tdebug.h> #include "trefcounter.h" #include "fileref.h" #include "asffile.h" #include "mpegfile.h" #include "vorbisfile.h" #include "flacfile.h" #include "oggflacfile.h" #include "mpcfile.h" #include "mp4file.h" #include "wavpackfile.h" #include "speexfile.h" #include "opusfile.h" #include "trueaudiofile.h" #include "aifffile.h" #include "wavfile.h" #include "apefile.h" #include "modfile.h" #include "s3mfile.h" #include "itfile.h" #include "xmfile.h" using namespace TagLib; class FileRef::FileRefPrivate : public RefCounter { public: FileRefPrivate(File *f) : RefCounter(), file(f) {} ~FileRefPrivate() { delete file; } File *file; static List<const FileTypeResolver *> fileTypeResolvers; }; List<const FileRef::FileTypeResolver *> FileRef::FileRefPrivate::fileTypeResolvers; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// FileRef::FileRef() { d = new FileRefPrivate(0); } FileRef::FileRef(FileName fileName, bool readAudioProperties, AudioProperties::ReadStyle audioPropertiesStyle) { d = new FileRefPrivate(create(fileName, readAudioProperties, audioPropertiesStyle)); } FileRef::FileRef(File *file) { d = new FileRefPrivate(file); } FileRef::FileRef(const FileRef &ref) : d(ref.d) { d->ref(); } FileRef::~FileRef() { if(d->deref()) delete d; } Tag *FileRef::tag() const { if(isNull()) { debug("FileRef::tag() - Called without a valid file."); return 0; } return d->file->tag(); } AudioProperties *FileRef::audioProperties() const { if(isNull()) { debug("FileRef::audioProperties() - Called without a valid file."); return 0; } return d->file->audioProperties(); } File *FileRef::file() const { return d->file; } bool FileRef::save() { if(isNull()) { debug("FileRef::save() - Called without a valid file."); return false; } return d->file->save(); } const FileRef::FileTypeResolver *FileRef::addFileTypeResolver(const FileRef::FileTypeResolver *resolver) // static { FileRefPrivate::fileTypeResolvers.prepend(resolver); return resolver; } StringList FileRef::defaultFileExtensions() { StringList l; l.append("ogg"); l.append("flac"); l.append("oga"); l.append("mp3"); l.append("mpc"); l.append("wv"); l.append("spx"); l.append("tta"); l.append("m4a"); l.append("m4r"); l.append("m4b"); l.append("m4p"); l.append("3g2"); l.append("mp4"); l.append("m4v"); l.append("wma"); l.append("asf"); l.append("aif"); l.append("aiff"); l.append("wav"); l.append("ape"); l.append("mod"); l.append("module"); // alias for "mod" l.append("nst"); // alias for "mod" l.append("wow"); // alias for "mod" l.append("s3m"); l.append("it"); l.append("xm"); return l; } bool FileRef::isNull() const { return !d->file || !d->file->isValid(); } FileRef &FileRef::operator=(const FileRef &ref) { if(&ref == this) return *this; if(d->deref()) delete d; d = ref.d; d->ref(); return *this; } bool FileRef::operator==(const FileRef &ref) const { return ref.d->file == d->file; } bool FileRef::operator!=(const FileRef &ref) const { return ref.d->file != d->file; } File *FileRef::create(FileName fileName, bool readAudioProperties, AudioProperties::ReadStyle audioPropertiesStyle) // static { List<const FileTypeResolver *>::ConstIterator it = FileRefPrivate::fileTypeResolvers.begin(); for(; it != FileRefPrivate::fileTypeResolvers.end(); ++it) { File *file = (*it)->createFile(fileName, readAudioProperties, audioPropertiesStyle); if(file) return file; } // Ok, this is really dumb for now, but it works for testing. String ext; { #ifdef _WIN32 String s = fileName.toString(); #else String s = fileName; #endif const int pos = s.rfind("."); if(pos != -1) ext = s.substr(pos + 1).upper(); } // If this list is updated, the method defaultFileExtensions() should also be // updated. However at some point that list should be created at the same time // that a default file type resolver is created. if(!ext.isEmpty()) { if(ext == "MP3") return new MPEG::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "OGG") return new Ogg::Vorbis::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "OGA") { /* .oga can be any audio in the Ogg container. First try FLAC, then Vorbis. */ File *file = new Ogg::FLAC::File(fileName, readAudioProperties, audioPropertiesStyle); if (file->isValid()) return file; delete file; return new Ogg::Vorbis::File(fileName, readAudioProperties, audioPropertiesStyle); } if(ext == "FLAC") return new FLAC::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "MPC") return new MPC::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "WV") return new WavPack::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "SPX") return new Ogg::Speex::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "OPUS") return new Ogg::Opus::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "TTA") return new TrueAudio::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "M4A" || ext == "M4R" || ext == "M4B" || ext == "M4P" || ext == "MP4" || ext == "3G2" || ext == "M4V") return new MP4::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "WMA" || ext == "ASF") return new ASF::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "AIF" || ext == "AIFF" || ext == "AFC" || ext == "AIFC") return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "WAV") return new RIFF::WAV::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "APE") return new APE::File(fileName, readAudioProperties, audioPropertiesStyle); // module, nst and wow are possible but uncommon extensions if(ext == "MOD" || ext == "MODULE" || ext == "NST" || ext == "WOW") return new Mod::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "S3M") return new S3M::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "IT") return new IT::File(fileName, readAudioProperties, audioPropertiesStyle); if(ext == "XM") return new XM::File(fileName, readAudioProperties, audioPropertiesStyle); } return 0; } <|endoftext|>
<commit_before>/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov 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 "Transform.h" DC_BEGIN_DREEMCHEST namespace Scene { // ------------------------------------------- MoveTo ------------------------------------------- // // ** MoveTo::target Vec3 MoveTo::target( void ) const { return m_target->get(); } // ** MoveTo::isContinuous bool MoveTo::isContinuous( void ) const { return m_isContinuous; } // ** MoveTo::type MoveTo::Type MoveTo::type( void ) const { return m_type; } // ** MoveTo::damping f32 MoveTo::damping( void ) const { return m_damping; } // ** MoveTo::springForce f32 MoveTo::springForce( void ) const { return m_springForce; } // ------------------------------------------ Transform ------------------------------------------ // // ** Transform::matrix const Matrix4& Transform::matrix( void ) const { return m_transform; } // ** Transform::setMatrix void Transform::setMatrix( const Matrix4& value ) { m_transform = value; } // ** Transform::parent const TransformWPtr& Transform::parent( void ) const { return m_parent; } // ** Transform::setParent void Transform::setParent( const TransformWPtr& value ) { m_parent = value; } // ** Transform::worldSpacePosition Vec3 Transform::worldSpacePosition( void ) const { return matrix() * Vec3::zero(); } // ** Transform::position const Vec3& Transform::position( void ) const { return m_position; } // ** Transform::setPosition void Transform::setPosition( const Vec3& value ) { m_position = value; } // ** Transform::axisX Vec3 Transform::axisX( void ) const { return m_rotation.rotate( Vec3::axisX() ); } // ** Transform::worldSpaceAxisX Vec3 Transform::worldSpaceAxisX( void ) const { Vec3 axis = Vec3::axisX(); return matrix() * Vec4( axis.x, axis.y, axis.z, 0.0f ); } // ** Transform::axisY Vec3 Transform::axisY( void ) const { return m_rotation.rotate( Vec3::axisY() ); } // ** Transform::worldSpaceAxisY Vec3 Transform::worldSpaceAxisY( void ) const { Vec3 axis = Vec3::axisY(); return matrix() * Vec4( axis.x, axis.y, axis.z, 0.0f ); } // ** Transform::axisZ Vec3 Transform::axisZ( void ) const { return m_rotation.rotate( Vec3::axisZ() ); } // ** Transform::worldSpaceAxisZ Vec3 Transform::worldSpaceAxisZ( void ) const { Vec3 axis = Vec3::axisZ(); return matrix() * Vec4( axis.x, axis.y, axis.z, 0.0f ); } // ** Transform::x f32 Transform::x( void ) const { return m_position.x; } // ** Transform::setX void Transform::setX( f32 value ) { m_position.x = value; } // ** Transform::y f32 Transform::y( void ) const { return m_position.y; } // ** Transform::setY void Transform::setY( f32 value ) { m_position.y = value; } // ** Transform::z f32 Transform::z( void ) const { return m_position.z; } // ** Transform::setZ void Transform::setZ( f32 value ) { m_position.z = value; } // ** Transform::rotation const Quat& Transform::rotation( void ) const { return m_rotation; } // ** Transform::rotate void Transform::rotate( f32 angle, f32 x, f32 y, f32 z ) { Quat r = Quat::rotateAroundAxis( angle, Vec3( x, y, z ) ); m_rotation = r * m_rotation; } // ** Transform::setRotation void Transform::setRotation( const Quat& value ) { m_rotation = value; } // ** Transform::rotationX f32 Transform::rotationX( void ) const { DC_NOT_IMPLEMENTED; return 0.0f; } // ** Transform::setRotationX void Transform::setRotationX( f32 value ) { m_rotation = Quat::rotateAroundAxis( value, Vec3( 1.0f, 0.0f, 0.0f ) ); } // ** Transform::rotationY f32 Transform::rotationY( void ) const { DC_NOT_IMPLEMENTED; return 0.0f; } // ** Transform::setRotationY void Transform::setRotationY( f32 value ) { m_rotation = Quat::rotateAroundAxis( value, Vec3( 0.0f, 1.0f, 0.0f ) ); } // ** Transform::rotationZ f32 Transform::rotationZ( void ) const { //!! This -1 multiplication looks like a bug in roll computation :( return m_rotation.roll() * (-1.0f); } // ** Transform::setRotationZ void Transform::setRotationZ( f32 value ) { m_rotation = Quat::rotateAroundAxis( value, Vec3( 0.0f, 0.0f, 1.0f ) ); } // ** Transform::setScale void Transform::setScale( const Vec3& value ) { m_scale = value; } // ** Transform::scale const Vec3& Transform::scale( void ) const { return m_scale; } // ** Transform::scaleX f32 Transform::scaleX( void ) const { return m_scale.x; } // ** Transform::setScaleX void Transform::setScaleX( f32 value ) { m_scale.x = value; } // ** Transform::scaleY f32 Transform::scaleY( void ) const { return m_scale.y; } // ** Transform::setScaleY void Transform::setScaleY( f32 value ) { m_scale.y = value; } // ** Transform::scaleZ f32 Transform::scaleZ( void ) const { return m_scale.z; } // ** Transform::setScaleZ void Transform::setScaleZ( f32 value ) { m_scale.z = value; } // ** Transform::serialize void Transform::serialize( Ecs::SerializationContext& ctx, Io::KeyValue& ar ) const { ar = Io::KeyValue::object() << "position" << position() << "rotation" << rotation() << "scale" << scale() << "parent" << m_parent.get(); } // ** Transform::deserialize void Transform::deserialize( Ecs::SerializationContext& ctx, const Io::KeyValue& ar ) { m_position = ar["position"].asVec3(); m_rotation = ar["rotation"].asQuat(); m_scale = ar["scale"].asVec3(); } // ----------------------------------------------- Identifier ------------------------------------------------ // // ** Identifier::name const String& Identifier::name( void ) const { return m_name; } // ** Identifier::setName void Identifier::setName( const String& value ) { m_name = value; } // ** Identifier::serialize void Identifier::serialize( Ecs::SerializationContext& ctx, Io::KeyValue& ar ) const { ar = Io::KeyValue::object() << "value" << name(); } // ** Identifier::deserialize void Identifier::deserialize( Ecs::SerializationContext& ctx, const Io::KeyValue& ar ) { m_name = ar["value"].asString(); } // --------------------------------------------- MoveAlongAxes --------------------------------------------- // // ** MoveAlongAxes::speed f32 MoveAlongAxes::speed( void ) const { return m_speed; } // ** MoveAlongAxes::coordinateSystem u8 MoveAlongAxes::coordinateSystem( void ) const { return m_coordinateSystem; } // ** MoveAlongAxes::delta Vec3 MoveAlongAxes::delta( void ) const { return m_delta->get(); } // ** MoveAlongAxes::rangeForAxis const Range& MoveAlongAxes::rangeForAxis( CoordinateSystemAxis axis ) const { return m_range[axis]; } // ** MoveAlongAxes::setRangeForAxis void MoveAlongAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value ) { m_range[axis] = value; } // --------------------------------------------- RotateAroundAxes --------------------------------------------- // // ** RotateAroundAxes::speed f32 RotateAroundAxes::speed( void ) const { return m_speed; } // ** RotateAroundAxes::setSpeed void RotateAroundAxes::setSpeed( f32 value ) { m_speed = value; } // ** RotateAroundAxes::coordinateSystem u8 RotateAroundAxes::coordinateSystem( void ) const { return m_coordinateSystem; } // ** RotateAroundAxes::delta Vec3 RotateAroundAxes::delta( void ) const { return m_delta->get(); } // ** RotateAroundAxes::binding Vec3BindingWPtr RotateAroundAxes::binding( void ) const { return m_delta; } // ** RotateAroundAxes::setBinding void RotateAroundAxes::setBinding( const Vec3BindingPtr& value ) { m_delta = value; } // ** RotateAroundAxes::rangeForAxis const Range& RotateAroundAxes::rangeForAxis( CoordinateSystemAxis axis ) const { return m_range[axis]; } // ** RotateAroundAxes::setRangeForAxis void RotateAroundAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value ) { m_range[axis] = value; } // ** RotateAroundAxes::rotationForAxis f32 RotateAroundAxes::rotationForAxis( CoordinateSystemAxis axis ) const { return m_rotation[axis]; } // ** RotateAroundAxes::setRotationForAxis void RotateAroundAxes::setRotationForAxis( CoordinateSystemAxis axis, f32 value ) { m_rotation[axis] = value; } } // namespace Scene DC_END_DREEMCHEST<commit_msg>Removed: workaround from Transform class<commit_after>/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov 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 "Transform.h" DC_BEGIN_DREEMCHEST namespace Scene { // ------------------------------------------- MoveTo ------------------------------------------- // // ** MoveTo::target Vec3 MoveTo::target( void ) const { return m_target->get(); } // ** MoveTo::isContinuous bool MoveTo::isContinuous( void ) const { return m_isContinuous; } // ** MoveTo::type MoveTo::Type MoveTo::type( void ) const { return m_type; } // ** MoveTo::damping f32 MoveTo::damping( void ) const { return m_damping; } // ** MoveTo::springForce f32 MoveTo::springForce( void ) const { return m_springForce; } // ------------------------------------------ Transform ------------------------------------------ // // ** Transform::matrix const Matrix4& Transform::matrix( void ) const { return m_transform; } // ** Transform::setMatrix void Transform::setMatrix( const Matrix4& value ) { m_transform = value; } // ** Transform::parent const TransformWPtr& Transform::parent( void ) const { return m_parent; } // ** Transform::setParent void Transform::setParent( const TransformWPtr& value ) { m_parent = value; } // ** Transform::worldSpacePosition Vec3 Transform::worldSpacePosition( void ) const { return matrix() * Vec3::zero(); } // ** Transform::position const Vec3& Transform::position( void ) const { return m_position; } // ** Transform::setPosition void Transform::setPosition( const Vec3& value ) { m_position = value; } // ** Transform::axisX Vec3 Transform::axisX( void ) const { return m_rotation.rotate( Vec3::axisX() ); } // ** Transform::worldSpaceAxisX Vec3 Transform::worldSpaceAxisX( void ) const { Vec3 axis = Vec3::axisX(); return matrix() * Vec4( axis.x, axis.y, axis.z, 0.0f ); } // ** Transform::axisY Vec3 Transform::axisY( void ) const { return m_rotation.rotate( Vec3::axisY() ); } // ** Transform::worldSpaceAxisY Vec3 Transform::worldSpaceAxisY( void ) const { Vec3 axis = Vec3::axisY(); return matrix() * Vec4( axis.x, axis.y, axis.z, 0.0f ); } // ** Transform::axisZ Vec3 Transform::axisZ( void ) const { return m_rotation.rotate( Vec3::axisZ() ); } // ** Transform::worldSpaceAxisZ Vec3 Transform::worldSpaceAxisZ( void ) const { Vec3 axis = Vec3::axisZ(); return matrix() * Vec4( axis.x, axis.y, axis.z, 0.0f ); } // ** Transform::x f32 Transform::x( void ) const { return m_position.x; } // ** Transform::setX void Transform::setX( f32 value ) { m_position.x = value; } // ** Transform::y f32 Transform::y( void ) const { return m_position.y; } // ** Transform::setY void Transform::setY( f32 value ) { m_position.y = value; } // ** Transform::z f32 Transform::z( void ) const { return m_position.z; } // ** Transform::setZ void Transform::setZ( f32 value ) { m_position.z = value; } // ** Transform::rotation const Quat& Transform::rotation( void ) const { return m_rotation; } // ** Transform::rotate void Transform::rotate( f32 angle, f32 x, f32 y, f32 z ) { Quat r = Quat::rotateAroundAxis( angle, Vec3( x, y, z ) ); m_rotation = r * m_rotation; } // ** Transform::setRotation void Transform::setRotation( const Quat& value ) { m_rotation = value; } // ** Transform::rotationX f32 Transform::rotationX( void ) const { DC_NOT_IMPLEMENTED; return 0.0f; } // ** Transform::setRotationX void Transform::setRotationX( f32 value ) { m_rotation = Quat::rotateAroundAxis( value, Vec3( 1.0f, 0.0f, 0.0f ) ); } // ** Transform::rotationY f32 Transform::rotationY( void ) const { DC_NOT_IMPLEMENTED; return 0.0f; } // ** Transform::setRotationY void Transform::setRotationY( f32 value ) { m_rotation = Quat::rotateAroundAxis( value, Vec3( 0.0f, 1.0f, 0.0f ) ); } // ** Transform::rotationZ f32 Transform::rotationZ( void ) const { return m_rotation.roll(); } // ** Transform::setRotationZ void Transform::setRotationZ( f32 value ) { m_rotation = Quat::rotateAroundAxis( value, Vec3( 0.0f, 0.0f, 1.0f ) ); } // ** Transform::setScale void Transform::setScale( const Vec3& value ) { m_scale = value; } // ** Transform::scale const Vec3& Transform::scale( void ) const { return m_scale; } // ** Transform::scaleX f32 Transform::scaleX( void ) const { return m_scale.x; } // ** Transform::setScaleX void Transform::setScaleX( f32 value ) { m_scale.x = value; } // ** Transform::scaleY f32 Transform::scaleY( void ) const { return m_scale.y; } // ** Transform::setScaleY void Transform::setScaleY( f32 value ) { m_scale.y = value; } // ** Transform::scaleZ f32 Transform::scaleZ( void ) const { return m_scale.z; } // ** Transform::setScaleZ void Transform::setScaleZ( f32 value ) { m_scale.z = value; } // ** Transform::serialize void Transform::serialize( Ecs::SerializationContext& ctx, Io::KeyValue& ar ) const { ar = Io::KeyValue::object() << "position" << position() << "rotation" << rotation() << "scale" << scale() << "parent" << m_parent.get(); } // ** Transform::deserialize void Transform::deserialize( Ecs::SerializationContext& ctx, const Io::KeyValue& ar ) { m_position = ar["position"].asVec3(); m_rotation = ar["rotation"].asQuat(); m_scale = ar["scale"].asVec3(); } // ----------------------------------------------- Identifier ------------------------------------------------ // // ** Identifier::name const String& Identifier::name( void ) const { return m_name; } // ** Identifier::setName void Identifier::setName( const String& value ) { m_name = value; } // ** Identifier::serialize void Identifier::serialize( Ecs::SerializationContext& ctx, Io::KeyValue& ar ) const { ar = Io::KeyValue::object() << "value" << name(); } // ** Identifier::deserialize void Identifier::deserialize( Ecs::SerializationContext& ctx, const Io::KeyValue& ar ) { m_name = ar["value"].asString(); } // --------------------------------------------- MoveAlongAxes --------------------------------------------- // // ** MoveAlongAxes::speed f32 MoveAlongAxes::speed( void ) const { return m_speed; } // ** MoveAlongAxes::coordinateSystem u8 MoveAlongAxes::coordinateSystem( void ) const { return m_coordinateSystem; } // ** MoveAlongAxes::delta Vec3 MoveAlongAxes::delta( void ) const { return m_delta->get(); } // ** MoveAlongAxes::rangeForAxis const Range& MoveAlongAxes::rangeForAxis( CoordinateSystemAxis axis ) const { return m_range[axis]; } // ** MoveAlongAxes::setRangeForAxis void MoveAlongAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value ) { m_range[axis] = value; } // --------------------------------------------- RotateAroundAxes --------------------------------------------- // // ** RotateAroundAxes::speed f32 RotateAroundAxes::speed( void ) const { return m_speed; } // ** RotateAroundAxes::setSpeed void RotateAroundAxes::setSpeed( f32 value ) { m_speed = value; } // ** RotateAroundAxes::coordinateSystem u8 RotateAroundAxes::coordinateSystem( void ) const { return m_coordinateSystem; } // ** RotateAroundAxes::delta Vec3 RotateAroundAxes::delta( void ) const { return m_delta->get(); } // ** RotateAroundAxes::binding Vec3BindingWPtr RotateAroundAxes::binding( void ) const { return m_delta; } // ** RotateAroundAxes::setBinding void RotateAroundAxes::setBinding( const Vec3BindingPtr& value ) { m_delta = value; } // ** RotateAroundAxes::rangeForAxis const Range& RotateAroundAxes::rangeForAxis( CoordinateSystemAxis axis ) const { return m_range[axis]; } // ** RotateAroundAxes::setRangeForAxis void RotateAroundAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value ) { m_range[axis] = value; } // ** RotateAroundAxes::rotationForAxis f32 RotateAroundAxes::rotationForAxis( CoordinateSystemAxis axis ) const { return m_rotation[axis]; } // ** RotateAroundAxes::setRotationForAxis void RotateAroundAxes::setRotationForAxis( CoordinateSystemAxis axis, f32 value ) { m_rotation[axis] = value; } } // namespace Scene DC_END_DREEMCHEST<|endoftext|>
<commit_before><commit_msg>liblo: use MediaDescriptor / clean-up<commit_after><|endoftext|>
<commit_before><commit_msg>#65293# exception specification<commit_after><|endoftext|>
<commit_before><commit_msg>Implemented abstract methods for Firebird database<commit_after><|endoftext|>
<commit_before>#include <set> #include <sstream> #include <iostream> #include <cassert> #include "CodeGen.h" #include "Compile.h" #include "IR.h" #include "Type.h" #include "Parser.h" using namespace Bish; class TypeAnnotator : public IRVisitor { public: TypeAnnotator(std::ostream &os) : stream(os), indent_level(0) {} void visit(Module *n) { if (visited(n)) return; visited_set.insert(n); for (std::vector<Function *>::const_iterator I = n->functions.begin(), E = n->functions.end(); I != E; ++I) { (*I)->accept(this); } for (std::vector<Assignment *>::const_iterator I = n->global_variables.begin(), E = n->global_variables.end(); I != E; ++I) { (*I)->accept(this); stream << ";\n"; } } void visit(ReturnStatement *n) { if (visited(n)) return; visited_set.insert(n); stream << "return "; n->value->accept(this); } void visit(Block *n) { if (visited(n)) return; visited_set.insert(n); stream << "{\n"; indent_level++; for (std::vector<IRNode *>::const_iterator I = n->nodes.begin(), E = n->nodes.end(); I != E; ++I) { indent(); (*I)->accept(this); if (!dynamic_cast<IfStatement*>(*I) && !dynamic_cast<ForLoop*>(*I)) stream << ";\n"; } indent_level--; indent(); stream << "}\n\n"; } void visit(Variable *n) { stream << n->name.str() << "[:" << strtype(n) << "]"; } void visit(IfStatement *n) { stream << "if ("; n->pblock->condition->accept(this); stream << ") "; n->pblock->body->accept(this); for (std::vector<PredicatedBlock *>::const_iterator I = n->elses.begin(), E = n->elses.end(); I != E; ++I) { indent(); stream << "else if ("; (*I)->condition->accept(this); stream << ") "; (*I)->body->accept(this); } if (n->elseblock) { indent(); stream << "else "; n->elseblock->accept(this); } } void visit(ForLoop *n) { stream << "for ("; n->variable->accept(this); stream << " in "; n->lower->accept(this); if (n->upper) { stream << " .. "; n->upper->accept(this); } stream << ") "; n->body->accept(this); } void visit(Function *n) { if (visited(n)) return; visited_set.insert(n); stream << "def " << n->name.str() << "[:" << strtype(n) << "] ("; const int nargs = n->args.size(); int i = 0; for (std::vector<Variable *>::const_iterator I = n->args.begin(), E = n->args.end(); I != E; ++I, ++i) { (*I)->accept(this); if (i < nargs - 1) stream << ", "; } stream << ") "; if (n->body) n->body->accept(this); } void visit(FunctionCall *n) { if (visited(n)) return; visited_set.insert(n); const int nargs = n->args.size(); stream << n->function->name.str() << "("; for (int i = 0; i < nargs; i++) { n->args[i]->accept(this); if (i < nargs - 1) stream << ", "; } stream << ")"; } void visit(ExternCall *n) { if (visited(n)) return; visited_set.insert(n); stream << "@("; for (InterpolatedString::const_iterator I = n->body->begin(), E = n->body->end(); I != E; ++I) { if ((*I).is_str()) { stream << (*I).str(); } else { assert((*I).is_var()); stream << "$"; (*I).var()->accept(this); } } stream << ")"; } void visit(IORedirection *n) { if (visited(n)) return; visited_set.insert(n); std::string bash_op; switch (n->op) { case IORedirection::Pipe: bash_op = "|"; break; default: assert(false && "Unimplemented redirection."); } n->a->accept(this); stream << " " << bash_op << " "; n->b->accept(this); } void visit(Assignment *n) { if (visited(n)) return; visited_set.insert(n); bool array_init = n->values.size() > 1; n->location->accept(this); stream << " = "; if (array_init) stream << "["; const unsigned sz = n->values.size(); for (unsigned i = 0; i < sz; i++) { n->values[i]->accept(this); if (i < sz - 1) stream << ", "; } if (array_init) stream << "]"; } void visit(BinOp *n) { std::string bash_op; switch (n->op) { case BinOp::Eq: bash_op = "=="; break; case BinOp::NotEq: bash_op = "!="; break; case BinOp::LT: bash_op = "<"; break; case BinOp::LTE: bash_op = "<="; break; case BinOp::GT: bash_op = ">"; break; case BinOp::GTE: bash_op = ">="; break; case BinOp::And: bash_op = "and"; break; case BinOp::Or: bash_op = "or"; break; case BinOp::Add: bash_op = "+"; break; case BinOp::Sub: bash_op = "-"; break; case BinOp::Mul: bash_op = "*"; break; case BinOp::Div: bash_op = "/"; break; case BinOp::Mod: bash_op = "%"; break; } n->a->accept(this); stream << " " << bash_op << " "; n->b->accept(this); } void visit(UnaryOp *n) { if (visited(n)) return; visited_set.insert(n); switch (n->op) { case UnaryOp::Negate: stream << "-"; break; case UnaryOp::Not: stream << "!"; break; } n->a->accept(this); } void visit(Integer *n) { stream << n->value; } void visit(Fractional *n) { stream << n->value; } void visit(String *n) { stream << "\"" << n->value << "\""; } void visit(Boolean *n) { stream << n->value; } private: unsigned indent_level; std::ostream &stream; std::set<IRNode *> visited_set; bool visited(IRNode *n) { return visited_set.find(n) != visited_set.end(); } void indent() { for (unsigned i = 0; i < indent_level; i++) { stream << " "; } } std::string strtype(IRNode *n) { return n->type().str(); } }; int main(int argc, char **argv) { if (argc < 2) { std::cerr << "USAGE: " << argv[0] << " <INPUT>\n"; std::cerr << " Annotates Bish file <INPUT> with inferred type information.\n"; return 1; } std::string path(argv[1]); Parser p; Module *m = p.parse(path); std::stringstream s; // Don't actually care about the output, just need the compile // pipeline to run. CodeGenerators::initialize(); CodeGenerators::CodeGeneratorConstructor cg_constructor = CodeGenerators::get("bash"); assert(cg_constructor); compile_to(m, cg_constructor(s)); TypeAnnotator annotate(std::cout); m->accept(&annotate); return 0; } <commit_msg>Update TypeAnnotator.<commit_after>#include <set> #include <sstream> #include <iostream> #include <cassert> #include "CodeGen.h" #include "Compile.h" #include "IR.h" #include "Type.h" #include "Parser.h" using namespace Bish; class TypeAnnotator : public IRVisitor { public: TypeAnnotator(std::ostream &os) : stream(os), indent_level(0) {} void visit(Module *n) { if (visited(n)) return; visited_set.insert(n); for (std::vector<Function *>::const_iterator I = n->functions.begin(), E = n->functions.end(); I != E; ++I) { (*I)->accept(this); } for (std::vector<Assignment *>::const_iterator I = n->global_variables.begin(), E = n->global_variables.end(); I != E; ++I) { (*I)->accept(this); stream << ";\n"; } } void visit(ReturnStatement *n) { if (visited(n)) return; visited_set.insert(n); stream << "return "; n->value->accept(this); } void visit(Block *n) { if (visited(n)) return; visited_set.insert(n); stream << "{\n"; indent_level++; for (std::vector<IRNode *>::const_iterator I = n->nodes.begin(), E = n->nodes.end(); I != E; ++I) { indent(); (*I)->accept(this); if (!dynamic_cast<IfStatement*>(*I) && !dynamic_cast<ForLoop*>(*I)) stream << ";\n"; } indent_level--; indent(); stream << "}\n\n"; } void visit(Variable *n) { stream << n->name.str() << strtype(n); } void visit(Location *n) { n->variable->accept(this); if (n->offset) { stream << "["; n->offset->accept(this); stream << "]"; stream << strtype(n); } } void visit(IfStatement *n) { stream << "if ("; n->pblock->condition->accept(this); stream << ") "; n->pblock->body->accept(this); for (std::vector<PredicatedBlock *>::const_iterator I = n->elses.begin(), E = n->elses.end(); I != E; ++I) { indent(); stream << "else if ("; (*I)->condition->accept(this); stream << ") "; (*I)->body->accept(this); } if (n->elseblock) { indent(); stream << "else "; n->elseblock->accept(this); } } void visit(ForLoop *n) { stream << "for ("; n->variable->accept(this); stream << " in "; n->lower->accept(this); if (n->upper) { stream << " .. "; n->upper->accept(this); } stream << ") "; n->body->accept(this); } void visit(Function *n) { if (visited(n)) return; visited_set.insert(n); stream << "def " << n->name.str() << strtype(n) << " ("; const int nargs = n->args.size(); int i = 0; for (std::vector<Variable *>::const_iterator I = n->args.begin(), E = n->args.end(); I != E; ++I, ++i) { (*I)->accept(this); if (i < nargs - 1) stream << ", "; } stream << ") "; if (n->body) n->body->accept(this); } void visit(FunctionCall *n) { if (visited(n)) return; visited_set.insert(n); const int nargs = n->args.size(); stream << n->function->name.str() << "("; for (int i = 0; i < nargs; i++) { n->args[i]->accept(this); if (i < nargs - 1) stream << ", "; } stream << ")"; } void visit(ExternCall *n) { if (visited(n)) return; visited_set.insert(n); stream << "@("; for (InterpolatedString::const_iterator I = n->body->begin(), E = n->body->end(); I != E; ++I) { if ((*I).is_str()) { stream << (*I).str(); } else { assert((*I).is_var()); stream << "$"; (*I).var()->accept(this); } } stream << ")"; } void visit(IORedirection *n) { if (visited(n)) return; visited_set.insert(n); std::string bash_op; switch (n->op) { case IORedirection::Pipe: bash_op = "|"; break; default: assert(false && "Unimplemented redirection."); } n->a->accept(this); stream << " " << bash_op << " "; n->b->accept(this); } void visit(Assignment *n) { if (visited(n)) return; visited_set.insert(n); bool array_init = n->values.size() > 1; n->location->accept(this); stream << " = "; if (array_init) stream << "["; const unsigned sz = n->values.size(); for (unsigned i = 0; i < sz; i++) { n->values[i]->accept(this); if (i < sz - 1) stream << ", "; } if (array_init) stream << "]"; } void visit(BinOp *n) { std::string bash_op; switch (n->op) { case BinOp::Eq: bash_op = "=="; break; case BinOp::NotEq: bash_op = "!="; break; case BinOp::LT: bash_op = "<"; break; case BinOp::LTE: bash_op = "<="; break; case BinOp::GT: bash_op = ">"; break; case BinOp::GTE: bash_op = ">="; break; case BinOp::And: bash_op = "and"; break; case BinOp::Or: bash_op = "or"; break; case BinOp::Add: bash_op = "+"; break; case BinOp::Sub: bash_op = "-"; break; case BinOp::Mul: bash_op = "*"; break; case BinOp::Div: bash_op = "/"; break; case BinOp::Mod: bash_op = "%"; break; } n->a->accept(this); stream << " " << bash_op << " "; n->b->accept(this); } void visit(UnaryOp *n) { if (visited(n)) return; visited_set.insert(n); switch (n->op) { case UnaryOp::Negate: stream << "-"; break; case UnaryOp::Not: stream << "!"; break; } n->a->accept(this); } void visit(Integer *n) { stream << n->value; } void visit(Fractional *n) { stream << n->value; } void visit(String *n) { stream << "\"" << n->value << "\""; } void visit(Boolean *n) { stream << n->value; } private: unsigned indent_level; std::ostream &stream; std::set<IRNode *> visited_set; bool visited(IRNode *n) { return visited_set.find(n) != visited_set.end(); } void indent() { for (unsigned i = 0; i < indent_level; i++) { stream << " "; } } std::string strtype(IRNode *n) { return "{:" + n->type().str() + "}"; } }; int main(int argc, char **argv) { if (argc < 2) { std::cerr << "USAGE: " << argv[0] << " <INPUT>\n"; std::cerr << " Annotates Bish file <INPUT> with inferred type information.\n"; return 1; } std::string path(argv[1]); Parser p; Module *m = p.parse(path); std::stringstream s; // Don't actually care about the output, just need the compile // pipeline to run. CodeGenerators::initialize(); CodeGenerators::CodeGeneratorConstructor cg_constructor = CodeGenerators::get("bash"); assert(cg_constructor); compile_to(m, cg_constructor(s)); TypeAnnotator annotate(std::cout); m->accept(&annotate); return 0; } <|endoftext|>
<commit_before>#include "stdafx.h" /* ============================================================================== This is an automatically generated file created by the Jucer! Creation date: 3 Apr 2012 10:45:28pm Be careful when adding custom code to these files, as only the code within the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded and re-saved. Jucer version: 1.12 ------------------------------------------------------------------------------ The Jucer is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-6 by Raw Material Software ltd. ============================================================================== */ //[Headers] You can add your own extra header files here... #include "CtrlrLuaManager.h" #include "CtrlrManager/CtrlrManager.h" #include "CtrlrPanel/CtrlrPanel.h" //[/Headers] #include "CtrlrLuaConsole.h" //[MiscUserDefs] You can add your own user definitions and misc code here... const StringArray joinFileArray (const Array<File> ar) { StringArray s; for (int i=0; i<ar.size(); i++) { s.add (ar[i].getFullPathName()); } return (s); } //[/MiscUserDefs] //============================================================================== CtrlrLuaConsole::CtrlrLuaConsole (CtrlrPanel &_owner) : owner(_owner), luaConsoleOutput (0), luaConsoleInput (0), resizer (0) { addAndMakeVisible (luaConsoleOutput = new CodeEditorComponent (outputDocument, 0)); luaConsoleOutput->setName (L"luaConsoleOutput"); addAndMakeVisible (luaConsoleInput = new CodeEditorComponent (inputDocument, 0)); luaConsoleInput->setName (L"luaConsoleInput"); addAndMakeVisible (resizer = new StretchableLayoutResizerBar (&layoutManager, 1, false)); //[UserPreSize] layoutManager.setItemLayout (0, -0.001, -1.0, -0.69); layoutManager.setItemLayout (1, -0.001, -0.01, -0.01); layoutManager.setItemLayout (2, -0.001, -1.0, -0.30); luaConsoleInput->setFont (Font(owner.getOwner().getFontManager().getDefaultMonoFontName(), 15, Font::plain)); luaConsoleOutput->setFont (Font(owner.getOwner().getFontManager().getDefaultMonoFontName(), 15, Font::plain)); luaConsoleInput->setColour (CodeEditorComponent::backgroundColourId, Colour(0xffffffff)); luaConsoleOutput->setColour (CodeEditorComponent::backgroundColourId, Colour(0xffffffff)); luaConsoleInput->addKeyListener (this); owner.getOwner().getCtrlrLog().addListener (this); nextUpKeyPressWillbeFirst = true; lastCommandNumInHistory = -1; lastMoveDirection = NONE; currentInputString = String::empty; luaConsoleOutput->setWantsKeyboardFocus(false); luaConsoleInput->grabKeyboardFocus(); //[/UserPreSize] setSize (600, 400); //[Constructor] You can add your own custom stuff here.. snips.addTokens (owner.getProperty(Ids::uiLuaConsoleSnips).toString(), "$", "\'\""); //[/Constructor] } CtrlrLuaConsole::~CtrlrLuaConsole() { //[Destructor_pre]. You can add your own custom destruction code here.. owner.getOwner().getCtrlrLog().removeListener (this); //[/Destructor_pre] deleteAndZero (luaConsoleOutput); deleteAndZero (luaConsoleInput); deleteAndZero (resizer); //[Destructor]. You can add your own custom destruction code here.. //[/Destructor] } //============================================================================== void CtrlrLuaConsole::paint (Graphics& g) { //[UserPrePaint] Add your own custom painting code here.. //[/UserPrePaint] //[UserPaint] Add your own custom painting code here.. //[/UserPaint] } void CtrlrLuaConsole::resized() { luaConsoleOutput->setBounds (0, 0, getWidth() - 0, proportionOfHeight (0.6900f)); luaConsoleInput->setBounds (0, proportionOfHeight (0.7000f), getWidth() - 0, proportionOfHeight (0.3000f)); resizer->setBounds (0, proportionOfHeight (0.6900f), getWidth() - 0, proportionOfHeight (0.0100f)); //[UserResized] Add your own custom resize handling here.. Component* comps[] = { luaConsoleOutput, resizer, luaConsoleInput }; layoutManager.layOutComponents (comps, 3, 0, 0, getWidth(), getHeight(), true, true); //[/UserResized] } bool CtrlrLuaConsole::keyPressed (const KeyPress& key) { //[UserCode_keyPressed] -- Add your code here... return false; // Return true if your handler uses this key event, or false to allow it to be passed-on. //[/UserCode_keyPressed] } //[MiscUserCode] You can add your own definitions of your custom methods or any other code here... bool CtrlrLuaConsole::keyPressed (const KeyPress& key, Component* originatingComponent) { if (key.getKeyCode() == 13 && originatingComponent == luaConsoleInput && !key.getModifiers().isCtrlDown()) { runCode(inputDocument.getAllContent()); if ((bool)owner.getProperty(Ids::uiLuaConsoleInputRemoveAfterRun)) { inputDocument.replaceAllContent(String::empty); } return (true); } else if (key.getKeyCode() == 13 && originatingComponent == luaConsoleInput && key.getModifiers().isCtrlDown()) { luaConsoleInput->insertTextAtCaret ("\n"); return (true); } else if (key.getKeyCode() == KeyPress::upKey && key.getModifiers().isCtrlDown() && originatingComponent == luaConsoleInput ) { if(inputHistory.size()) { // Prev command if (nextUpKeyPressWillbeFirst) { currentInputString = inputDocument.getAllContent(); nextUpKeyPressWillbeFirst = false; } luaConsoleInput->loadContent(inputHistory[lastCommandNumInHistory]); /* Put text at pointer into console */ lastCommandNumInHistory = ( ((lastCommandNumInHistory - 1) < 0) ? 0 : (lastCommandNumInHistory - 1) ); lastMoveDirection = UP; } return (true); } else if (key.getKeyCode() == KeyPress::downKey && key.getModifiers().isCtrlDown() && originatingComponent == luaConsoleInput) { if(inputHistory.size()) { // next command if (lastCommandNumInHistory == (inputHistory.size() - 1)) // at last command only { if (!currentInputString.isEmpty()) { luaConsoleInput->loadContent(currentInputString); nextUpKeyPressWillbeFirst = true; // if user changes this restored text we need to capture it at up key again } return true; } lastCommandNumInHistory += 1; luaConsoleInput->loadContent(inputHistory[lastCommandNumInHistory]); /* Put text at pointer into console */ lastMoveDirection = DOWN; } return (true); } return (false); } void CtrlrLuaConsole::runCode(const String &code) { luaConsoleOutput->moveCaretToEnd(false); luaConsoleOutput->insertTextAtCaret ("\n"); luaConsoleOutput->insertTextAtCaret (">>> " + code + "\n"); // add running code into history if (code.isNotEmpty()){ inputHistory.add(code); nextUpKeyPressWillbeFirst = true; lastCommandNumInHistory = inputHistory.size() - 1; lastMoveDirection = NONE; currentInputString = String::empty; } owner.getCtrlrLuaManager().runCode(code); // luaConsoleInput->clear(); } void CtrlrLuaConsole::messageLogged (CtrlrLog::CtrlrLogMessage message) { if (message.level == CtrlrLog::Lua) { // luaConsoleOutput->setCaretPosition (luaConsoleOutput->getText().length()); luaConsoleOutput->insertTextAtCaret (message.message + "\n"); } if (message.level == CtrlrLog::LuaError) { // luaConsoleOutput->setCaretPosition (luaConsoleOutput->getText().length()); luaConsoleOutput->insertTextAtCaret (message.message + "\n"); } } const PopupMenu CtrlrLuaConsole::getSnipsMenu(const int mask) { PopupMenu m; for (int i=0; i<snips.size(); i++) { m.addItem (mask+i, snips[i]); } return (m); } void CtrlrLuaConsole::snipsItemClicked(Button *b) { PopupMenu m; m.addItem (1, "Add input to snips"); m.addSubMenu ("Run snip", getSnipsMenu(1024)); m.addSubMenu ("Remove snip", getSnipsMenu(4096)); m.addItem (2, "Toggle input removal after run", true, (bool)owner.getProperty(Ids::uiLuaConsoleInputRemoveAfterRun)); const int ret = m.showAt(b); if (ret == 1) { snips.add (inputDocument.getAllContent()); } if (ret >= 1024 && ret < 4096) { runCode (snips[ret-1024]); } if (ret >= 4096) { snips.remove (ret-4096); } if (ret == 2) { owner.setProperty (Ids::uiLuaConsoleInputRemoveAfterRun, !owner.getProperty(Ids::uiLuaConsoleInputRemoveAfterRun)); } owner.setProperty (Ids::uiLuaConsoleSnips, snips.joinIntoString("$")); } StringArray CtrlrLuaConsole::getMenuBarNames() { const char* const names[] = { "File", "View", nullptr }; return StringArray (names); } PopupMenu CtrlrLuaConsole::getMenuForIndex(int topLevelMenuIndex, const String &menuName) { PopupMenu menu; if (topLevelMenuIndex == 0) { menu.addItem (2, "Add input to snips"); menu.addSubMenu ("Run snip", getSnipsMenu(1024)); menu.addSubMenu ("Remove snip", getSnipsMenu(4096)); menu.addSeparator(); menu.addItem (1, "Close"); } else if(topLevelMenuIndex == 1) { menu.addItem (3, "Toggle input removal after run", true, (bool)owner.getProperty(Ids::uiLuaConsoleInputRemoveAfterRun)); } return (menu); } void CtrlrLuaConsole::menuItemSelected(int menuItemID, int topLevelMenuIndex) { if (menuItemID == 2) { snips.add (inputDocument.getAllContent()); } if (menuItemID >= 1024 && menuItemID < 4096) { runCode (snips[menuItemID-1024]); } if (menuItemID >= 4096) { snips.remove (menuItemID-4096); } if (menuItemID == 3) { owner.setProperty (Ids::uiLuaConsoleInputRemoveAfterRun, !owner.getProperty(Ids::uiLuaConsoleInputRemoveAfterRun)); } owner.setProperty (Ids::uiLuaConsoleSnips, snips.joinIntoString("$")); } void CtrlrLuaConsole::focusGained(FocusChangeType cause) { luaConsoleInput->grabKeyboardFocus(); } //[/MiscUserCode] //============================================================================== #if 0 /* -- Jucer information section -- This is where the Jucer puts all of its metadata, so don't change anything in here! BEGIN_JUCER_METADATA <JUCER_COMPONENT documentType="Component" className="CtrlrLuaConsole" componentName="" parentClasses="public CtrlrChildWindowContent, public CtrlrLog::Listener, public KeyListener" constructorParams="CtrlrPanel &amp;_owner" variableInitialisers="owner(_owner)" snapPixels="8" snapActive="1" snapShown="1" overlayOpacity="0.330000013" fixedSize="1" initialWidth="600" initialHeight="400"> <METHODS> <METHOD name="keyPressed (const KeyPress&amp; key)"/> </METHODS> <BACKGROUND backgroundColour="0"/> <GENERICCOMPONENT name="luaConsoleOutput" id="cf0696d15c4f91e3" memberName="luaConsoleOutput" virtualName="" explicitFocusOrder="0" pos="0 0 0M 69%" class="CodeEditorComponent" params="outputDocument, 0"/> <GENERICCOMPONENT name="luaConsoleInput" id="9630267470906dc" memberName="luaConsoleInput" virtualName="" explicitFocusOrder="0" pos="0 70% 0M 30%" class="CodeEditorComponent" params="inputDocument, 0"/> <GENERICCOMPONENT name="" id="f4fe604fd1cb0e52" memberName="resizer" virtualName="" explicitFocusOrder="0" pos="0 69% 0M 1%" class="StretchableLayoutResizerBar" params="&amp;layoutManager, 1, false"/> </JUCER_COMPONENT> END_JUCER_METADATA */ #endif <commit_msg>from output console we can copy using keyboard shortcut. And history we should avoid adding same code.<commit_after>#include "stdafx.h" /* ============================================================================== This is an automatically generated file created by the Jucer! Creation date: 3 Apr 2012 10:45:28pm Be careful when adding custom code to these files, as only the code within the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded and re-saved. Jucer version: 1.12 ------------------------------------------------------------------------------ The Jucer is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-6 by Raw Material Software ltd. ============================================================================== */ //[Headers] You can add your own extra header files here... #include "CtrlrLuaManager.h" #include "CtrlrManager/CtrlrManager.h" #include "CtrlrPanel/CtrlrPanel.h" //[/Headers] #include "CtrlrLuaConsole.h" //[MiscUserDefs] You can add your own user definitions and misc code here... const StringArray joinFileArray (const Array<File> ar) { StringArray s; for (int i=0; i<ar.size(); i++) { s.add (ar[i].getFullPathName()); } return (s); } //[/MiscUserDefs] //============================================================================== CtrlrLuaConsole::CtrlrLuaConsole (CtrlrPanel &_owner) : owner(_owner), luaConsoleOutput (0), luaConsoleInput (0), resizer (0) { addAndMakeVisible (luaConsoleOutput = new CodeEditorComponent (outputDocument, 0)); luaConsoleOutput->setName (L"luaConsoleOutput"); addAndMakeVisible (luaConsoleInput = new CodeEditorComponent (inputDocument, 0)); luaConsoleInput->setName (L"luaConsoleInput"); addAndMakeVisible (resizer = new StretchableLayoutResizerBar (&layoutManager, 1, false)); //[UserPreSize] layoutManager.setItemLayout (0, -0.001, -1.0, -0.69); layoutManager.setItemLayout (1, -0.001, -0.01, -0.01); layoutManager.setItemLayout (2, -0.001, -1.0, -0.30); luaConsoleInput->setFont (Font(owner.getOwner().getFontManager().getDefaultMonoFontName(), 15, Font::plain)); luaConsoleOutput->setFont (Font(owner.getOwner().getFontManager().getDefaultMonoFontName(), 15, Font::plain)); luaConsoleInput->setColour (CodeEditorComponent::backgroundColourId, Colour(0xffffffff)); luaConsoleOutput->setColour (CodeEditorComponent::backgroundColourId, Colour(0xffffffff)); luaConsoleInput->addKeyListener (this); owner.getOwner().getCtrlrLog().addListener (this); nextUpKeyPressWillbeFirst = true; lastCommandNumInHistory = -1; lastMoveDirection = NONE; currentInputString = String::empty; //luaConsoleOutput->setWantsKeyboardFocus(false); luaConsoleInput->grabKeyboardFocus(); //[/UserPreSize] setSize (600, 400); //[Constructor] You can add your own custom stuff here.. snips.addTokens (owner.getProperty(Ids::uiLuaConsoleSnips).toString(), "$", "\'\""); //[/Constructor] } CtrlrLuaConsole::~CtrlrLuaConsole() { //[Destructor_pre]. You can add your own custom destruction code here.. owner.getOwner().getCtrlrLog().removeListener (this); //[/Destructor_pre] deleteAndZero (luaConsoleOutput); deleteAndZero (luaConsoleInput); deleteAndZero (resizer); //[Destructor]. You can add your own custom destruction code here.. //[/Destructor] } //============================================================================== void CtrlrLuaConsole::paint (Graphics& g) { //[UserPrePaint] Add your own custom painting code here.. //[/UserPrePaint] //[UserPaint] Add your own custom painting code here.. //[/UserPaint] } void CtrlrLuaConsole::resized() { luaConsoleOutput->setBounds (0, 0, getWidth() - 0, proportionOfHeight (0.6900f)); luaConsoleInput->setBounds (0, proportionOfHeight (0.7000f), getWidth() - 0, proportionOfHeight (0.3000f)); resizer->setBounds (0, proportionOfHeight (0.6900f), getWidth() - 0, proportionOfHeight (0.0100f)); //[UserResized] Add your own custom resize handling here.. Component* comps[] = { luaConsoleOutput, resizer, luaConsoleInput }; layoutManager.layOutComponents (comps, 3, 0, 0, getWidth(), getHeight(), true, true); //[/UserResized] } bool CtrlrLuaConsole::keyPressed (const KeyPress& key) { //[UserCode_keyPressed] -- Add your code here... return false; // Return true if your handler uses this key event, or false to allow it to be passed-on. //[/UserCode_keyPressed] } //[MiscUserCode] You can add your own definitions of your custom methods or any other code here... bool CtrlrLuaConsole::keyPressed (const KeyPress& key, Component* originatingComponent) { if (key.getKeyCode() == 13 && originatingComponent == luaConsoleInput && !key.getModifiers().isCtrlDown()) { runCode(inputDocument.getAllContent()); if ((bool)owner.getProperty(Ids::uiLuaConsoleInputRemoveAfterRun)) { inputDocument.replaceAllContent(String::empty); } return (true); } else if (key.getKeyCode() == 13 && originatingComponent == luaConsoleInput && key.getModifiers().isCtrlDown()) { luaConsoleInput->insertTextAtCaret ("\n"); return (true); } else if (key.getKeyCode() == KeyPress::upKey && key.getModifiers().isCtrlDown() && originatingComponent == luaConsoleInput ) { if(inputHistory.size()) { // Prev command if (nextUpKeyPressWillbeFirst) { currentInputString = inputDocument.getAllContent(); nextUpKeyPressWillbeFirst = false; } luaConsoleInput->loadContent(inputHistory[lastCommandNumInHistory]); /* Put text at pointer into console */ lastCommandNumInHistory = ( ((lastCommandNumInHistory - 1) < 0) ? 0 : (lastCommandNumInHistory - 1) ); lastMoveDirection = UP; } return (true); } else if (key.getKeyCode() == KeyPress::downKey && key.getModifiers().isCtrlDown() && originatingComponent == luaConsoleInput) { if(inputHistory.size()) { // next command if (lastCommandNumInHistory == (inputHistory.size() - 1)) // at last command only { if (!currentInputString.isEmpty()) { luaConsoleInput->loadContent(currentInputString); nextUpKeyPressWillbeFirst = true; // if user changes this restored text we need to capture it at up key again } return true; } lastCommandNumInHistory += 1; luaConsoleInput->loadContent(inputHistory[lastCommandNumInHistory]); /* Put text at pointer into console */ lastMoveDirection = DOWN; } return (true); } return (false); } void CtrlrLuaConsole::runCode(const String &code) { luaConsoleOutput->moveCaretToEnd(false); luaConsoleOutput->insertTextAtCaret ("\n"); luaConsoleOutput->insertTextAtCaret (">>> " + code + "\n"); // add running code into history if (code.isNotEmpty()){ inputHistory.addIfNotAlreadyThere(code); nextUpKeyPressWillbeFirst = true; lastCommandNumInHistory = inputHistory.size() - 1; lastMoveDirection = NONE; currentInputString = String::empty; } owner.getCtrlrLuaManager().runCode(code); // luaConsoleInput->clear(); } void CtrlrLuaConsole::messageLogged (CtrlrLog::CtrlrLogMessage message) { if (message.level == CtrlrLog::Lua) { // luaConsoleOutput->setCaretPosition (luaConsoleOutput->getText().length()); luaConsoleOutput->insertTextAtCaret (message.message + "\n"); } if (message.level == CtrlrLog::LuaError) { // luaConsoleOutput->setCaretPosition (luaConsoleOutput->getText().length()); luaConsoleOutput->insertTextAtCaret (message.message + "\n"); } } const PopupMenu CtrlrLuaConsole::getSnipsMenu(const int mask) { PopupMenu m; for (int i=0; i<snips.size(); i++) { m.addItem (mask+i, snips[i]); } return (m); } void CtrlrLuaConsole::snipsItemClicked(Button *b) { PopupMenu m; m.addItem (1, "Add input to snips"); m.addSubMenu ("Run snip", getSnipsMenu(1024)); m.addSubMenu ("Remove snip", getSnipsMenu(4096)); m.addItem (2, "Toggle input removal after run", true, (bool)owner.getProperty(Ids::uiLuaConsoleInputRemoveAfterRun)); const int ret = m.showAt(b); if (ret == 1) { snips.add (inputDocument.getAllContent()); } if (ret >= 1024 && ret < 4096) { runCode (snips[ret-1024]); } if (ret >= 4096) { snips.remove (ret-4096); } if (ret == 2) { owner.setProperty (Ids::uiLuaConsoleInputRemoveAfterRun, !owner.getProperty(Ids::uiLuaConsoleInputRemoveAfterRun)); } owner.setProperty (Ids::uiLuaConsoleSnips, snips.joinIntoString("$")); } StringArray CtrlrLuaConsole::getMenuBarNames() { const char* const names[] = { "File", "View", nullptr }; return StringArray (names); } PopupMenu CtrlrLuaConsole::getMenuForIndex(int topLevelMenuIndex, const String &menuName) { PopupMenu menu; if (topLevelMenuIndex == 0) { menu.addItem (2, "Add input to snips"); menu.addSubMenu ("Run snip", getSnipsMenu(1024)); menu.addSubMenu ("Remove snip", getSnipsMenu(4096)); menu.addSeparator(); menu.addItem (1, "Close"); } else if(topLevelMenuIndex == 1) { menu.addItem (3, "Toggle input removal after run", true, (bool)owner.getProperty(Ids::uiLuaConsoleInputRemoveAfterRun)); } return (menu); } void CtrlrLuaConsole::menuItemSelected(int menuItemID, int topLevelMenuIndex) { if (menuItemID == 2) { snips.add (inputDocument.getAllContent()); } if (menuItemID >= 1024 && menuItemID < 4096) { runCode (snips[menuItemID-1024]); } if (menuItemID >= 4096) { snips.remove (menuItemID-4096); } if (menuItemID == 3) { owner.setProperty (Ids::uiLuaConsoleInputRemoveAfterRun, !owner.getProperty(Ids::uiLuaConsoleInputRemoveAfterRun)); } owner.setProperty (Ids::uiLuaConsoleSnips, snips.joinIntoString("$")); } void CtrlrLuaConsole::focusGained(FocusChangeType cause) { luaConsoleInput->grabKeyboardFocus(); } //[/MiscUserCode] //============================================================================== #if 0 /* -- Jucer information section -- This is where the Jucer puts all of its metadata, so don't change anything in here! BEGIN_JUCER_METADATA <JUCER_COMPONENT documentType="Component" className="CtrlrLuaConsole" componentName="" parentClasses="public CtrlrChildWindowContent, public CtrlrLog::Listener, public KeyListener" constructorParams="CtrlrPanel &amp;_owner" variableInitialisers="owner(_owner)" snapPixels="8" snapActive="1" snapShown="1" overlayOpacity="0.330000013" fixedSize="1" initialWidth="600" initialHeight="400"> <METHODS> <METHOD name="keyPressed (const KeyPress&amp; key)"/> </METHODS> <BACKGROUND backgroundColour="0"/> <GENERICCOMPONENT name="luaConsoleOutput" id="cf0696d15c4f91e3" memberName="luaConsoleOutput" virtualName="" explicitFocusOrder="0" pos="0 0 0M 69%" class="CodeEditorComponent" params="outputDocument, 0"/> <GENERICCOMPONENT name="luaConsoleInput" id="9630267470906dc" memberName="luaConsoleInput" virtualName="" explicitFocusOrder="0" pos="0 70% 0M 30%" class="CodeEditorComponent" params="inputDocument, 0"/> <GENERICCOMPONENT name="" id="f4fe604fd1cb0e52" memberName="resizer" virtualName="" explicitFocusOrder="0" pos="0 69% 0M 1%" class="StretchableLayoutResizerBar" params="&amp;layoutManager, 1, false"/> </JUCER_COMPONENT> END_JUCER_METADATA */ #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2008, 2009, 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 "platform/clipboard/ClipboardUtilities.h" #include "core/platform/Pasteboard.h" #include "weborigin/KURL.h" #include "wtf/text/StringBuilder.h" #include "wtf/text/WTFString.h" namespace WebCore { #if OS(WIN) void replaceNewlinesWithWindowsStyleNewlines(String& str) { DEFINE_STATIC_LOCAL(String, windowsNewline, ("\r\n")); StringBuilder result; for (unsigned index = 0; index < str.length(); ++index) { if (str[index] != '\n' || (index > 0 && str[index - 1] == '\r')) result.append(str[index]); else result.append(windowsNewline); } str = result.toString(); } #endif void replaceNBSPWithSpace(String& str) { static const UChar NonBreakingSpaceCharacter = 0xA0; static const UChar SpaceCharacter = ' '; str.replace(NonBreakingSpaceCharacter, SpaceCharacter); } String convertURIListToURL(const String& uriList) { Vector<String> items; // Line separator is \r\n per RFC 2483 - however, for compatibility // reasons we allow just \n here. uriList.split('\n', items); // Process the input and return the first valid URL. In case no URLs can // be found, return an empty string. This is in line with the HTML5 spec. for (size_t i = 0; i < items.size(); ++i) { String& line = items[i]; line = line.stripWhiteSpace(); if (line.isEmpty()) continue; if (line[0] == '#') continue; KURL url = KURL(ParsedURLString, line); if (url.isValid()) return url; } return String(); } } // namespace WebCore <commit_msg>Remove unused header triggering check-blink-deps violation<commit_after>/* * Copyright (c) 2008, 2009, 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 "platform/clipboard/ClipboardUtilities.h" #include "weborigin/KURL.h" #include "wtf/text/StringBuilder.h" #include "wtf/text/WTFString.h" namespace WebCore { #if OS(WIN) void replaceNewlinesWithWindowsStyleNewlines(String& str) { DEFINE_STATIC_LOCAL(String, windowsNewline, ("\r\n")); StringBuilder result; for (unsigned index = 0; index < str.length(); ++index) { if (str[index] != '\n' || (index > 0 && str[index - 1] == '\r')) result.append(str[index]); else result.append(windowsNewline); } str = result.toString(); } #endif void replaceNBSPWithSpace(String& str) { static const UChar NonBreakingSpaceCharacter = 0xA0; static const UChar SpaceCharacter = ' '; str.replace(NonBreakingSpaceCharacter, SpaceCharacter); } String convertURIListToURL(const String& uriList) { Vector<String> items; // Line separator is \r\n per RFC 2483 - however, for compatibility // reasons we allow just \n here. uriList.split('\n', items); // Process the input and return the first valid URL. In case no URLs can // be found, return an empty string. This is in line with the HTML5 spec. for (size_t i = 0; i < items.size(); ++i) { String& line = items[i]; line = line.stripWhiteSpace(); if (line.isEmpty()) continue; if (line[0] == '#') continue; KURL url = KURL(ParsedURLString, line); if (url.isValid()) return url; } return String(); } } // namespace WebCore <|endoftext|>
<commit_before>/* opendatacon * * Copyright (c) 2014: * * DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi * yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA== * * 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. */ /* * main.cpp * * Created on: 14/07/2014 * Author: Neil Stephens <dearknarl@gmail.com> */ /*TODO: * -add config change commands * -cmd to apply config item from command line * -cmd to load config from file * -save config to file * -add a network interface to the console * -more dataports to implement: * -C37.118 * -NMEA 2k / CANv2 * -NMEA 0183 * -Gridlab-D * -JSONoHTML */ #include "DataConcentrator.h" #include "DaemonInterface.h" #include "ODCArgs.h" #include <opendatacon/Platform.h> #include <csignal> #include <cstdio> int main(int argc, char* argv[]) { int ret_val; std::string pidfile = ""; // Wrap everything in a try block. Do this every time, // because exceptions will be thrown for problems. try { // Turn command line arguments into easy to query struct ODCArgs Args(argc, argv); // If arg "-p <path>" is set, try and change directory to <path> if (Args.PathArg.isSet()) { std::string PathName = Args.PathArg.getValue(); if (ChangeWorkingDir(PathName)) { const size_t strmax = 80; char buf[strmax]; char* str = strerror_rp(errno, buf, strmax); std::string msg; if (str) { msg = "Unable to change working directory to '" + PathName + "' : " + str; } else { msg = "Unable to change working directory to '" + PathName + "' : UNKNOWN ERROR"; } throw std::runtime_error(msg); } } // If arg "-r" provided, unregister daemon (for platforms that provide support) if (Args.DaemonRemoveArg.isSet()) { daemon_remove(); } // If arg "-i" provided, register daemon (for platforms that provide support) if (Args.DaemonInstallArg.isSet()) { daemon_install(Args); } // If arg "-d" provided, daemonise (for platforms that provide support) if (Args.DaemonArg.isSet()) { daemonp(Args); if(Args.PIDFileArg.isSet()) pidfile = Args.PIDFileArg.getValue(); } // Construct and build opendatacon object // static shared ptr to use in signal handler static auto TheDataConcentrator = std::make_shared<DataConcentrator>(Args.ConfigFileArg.getValue()); TheDataConcentrator->Build(); // Configure signal handlers auto shutdown_func = [] (int signum) { TheDataConcentrator->Shutdown(); }; auto ignore_func = [] (int signum) { std::cout<<"Signal "<<signum<<" ignored. Not designed to be interrupted or suspended.\n" "To terminate, send a quit, kill, abort or break signal, or use a UI shutdown command.\n" "To run in the background, run as a daemon or service."<<std::endl; }; for (auto SIG : SIG_SHUTDOWN) { ::signal(SIG,shutdown_func); } for (auto SIG : SIG_IGNORE) { ::signal(SIG,ignore_func); } // Start opendatacon, returns after a clean shutdown auto run_thread = std::thread([=](){TheDataConcentrator->Run();}); while(!TheDataConcentrator->isShuttingDown()) std::this_thread::sleep_for(std::chrono::milliseconds(100)); //Shutting down - give some time for clean shutdown unsigned int i=0; while(!TheDataConcentrator->isShutDown() && i++ < 20) std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::string msg("opendatacon version '" ODC_VERSION_STRING); if(TheDataConcentrator->isShutDown()) { run_thread.join(); msg += "' shutdown cleanly."; ret_val = 0; TheDataConcentrator.reset(); } else { run_thread.detach(); msg += "' shutdown timed out."; ret_val = 1; } if(auto log = odc::spdlog_get("opendatacon")) log->critical(msg); else std::cout << msg << std::endl; } catch (TCLAP::ArgException &e) // catch command line argument exceptions { std::string msg = "Command line error: " + e.error() +" for arg " + e.argId(); if(auto log = odc::spdlog_get("opendatacon")) log->critical(msg); else std::cerr << msg << std::endl; ret_val = 1; } catch (std::exception& e) // catch opendatacon runtime exceptions { std::string msg = std::string("Caught exception: ") + e.what(); if(auto log = odc::spdlog_get("opendatacon")) log->critical(msg); else std::cerr << msg << std::endl; ret_val = 1; } if(pidfile != "") { if(std::remove(pidfile.c_str())) if(auto log = odc::spdlog_get("opendatacon")) log->info("PID file removed"); } if(auto log = odc::spdlog_get("opendatacon")) log->flush(); odc::spdlog_shutdown(); return ret_val; } <commit_msg>longer shutdown timeout<commit_after>/* opendatacon * * Copyright (c) 2014: * * DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi * yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA== * * 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. */ /* * main.cpp * * Created on: 14/07/2014 * Author: Neil Stephens <dearknarl@gmail.com> */ /*TODO: * -add config change commands * -cmd to apply config item from command line * -cmd to load config from file * -save config to file * -add a network interface to the console * -more dataports to implement: * -C37.118 * -NMEA 2k / CANv2 * -NMEA 0183 * -Gridlab-D * -JSONoHTML */ #include "DataConcentrator.h" #include "DaemonInterface.h" #include "ODCArgs.h" #include <opendatacon/Platform.h> #include <csignal> #include <cstdio> int main(int argc, char* argv[]) { int ret_val; std::string pidfile = ""; // Wrap everything in a try block. Do this every time, // because exceptions will be thrown for problems. try { // Turn command line arguments into easy to query struct ODCArgs Args(argc, argv); // If arg "-p <path>" is set, try and change directory to <path> if (Args.PathArg.isSet()) { std::string PathName = Args.PathArg.getValue(); if (ChangeWorkingDir(PathName)) { const size_t strmax = 80; char buf[strmax]; char* str = strerror_rp(errno, buf, strmax); std::string msg; if (str) { msg = "Unable to change working directory to '" + PathName + "' : " + str; } else { msg = "Unable to change working directory to '" + PathName + "' : UNKNOWN ERROR"; } throw std::runtime_error(msg); } } // If arg "-r" provided, unregister daemon (for platforms that provide support) if (Args.DaemonRemoveArg.isSet()) { daemon_remove(); } // If arg "-i" provided, register daemon (for platforms that provide support) if (Args.DaemonInstallArg.isSet()) { daemon_install(Args); } // If arg "-d" provided, daemonise (for platforms that provide support) if (Args.DaemonArg.isSet()) { daemonp(Args); if(Args.PIDFileArg.isSet()) pidfile = Args.PIDFileArg.getValue(); } // Construct and build opendatacon object // static shared ptr to use in signal handler static auto TheDataConcentrator = std::make_shared<DataConcentrator>(Args.ConfigFileArg.getValue()); TheDataConcentrator->Build(); // Configure signal handlers auto shutdown_func = [] (int signum) { TheDataConcentrator->Shutdown(); }; auto ignore_func = [] (int signum) { std::cout<<"Signal "<<signum<<" ignored. Not designed to be interrupted or suspended.\n" "To terminate, send a quit, kill, abort or break signal, or use a UI shutdown command.\n" "To run in the background, run as a daemon or service."<<std::endl; }; for (auto SIG : SIG_SHUTDOWN) { ::signal(SIG,shutdown_func); } for (auto SIG : SIG_IGNORE) { ::signal(SIG,ignore_func); } // Start opendatacon, returns after a clean shutdown auto run_thread = std::thread([=](){TheDataConcentrator->Run();}); while(!TheDataConcentrator->isShuttingDown()) std::this_thread::sleep_for(std::chrono::milliseconds(100)); //Shutting down - give some time for clean shutdown unsigned int i=0; while(!TheDataConcentrator->isShutDown() && i++ < 150) std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::string msg("opendatacon version '" ODC_VERSION_STRING); if(TheDataConcentrator->isShutDown()) { run_thread.join(); msg += "' shutdown cleanly."; ret_val = 0; TheDataConcentrator.reset(); } else { run_thread.detach(); msg += "' shutdown timed out."; ret_val = 1; } if(auto log = odc::spdlog_get("opendatacon")) log->critical(msg); else std::cout << msg << std::endl; } catch (TCLAP::ArgException &e) // catch command line argument exceptions { std::string msg = "Command line error: " + e.error() +" for arg " + e.argId(); if(auto log = odc::spdlog_get("opendatacon")) log->critical(msg); else std::cerr << msg << std::endl; ret_val = 1; } catch (std::exception& e) // catch opendatacon runtime exceptions { std::string msg = std::string("Caught exception: ") + e.what(); if(auto log = odc::spdlog_get("opendatacon")) log->critical(msg); else std::cerr << msg << std::endl; ret_val = 1; } if(pidfile != "") { if(std::remove(pidfile.c_str())) if(auto log = odc::spdlog_get("opendatacon")) log->info("PID file removed"); } if(auto log = odc::spdlog_get("opendatacon")) log->flush(); odc::spdlog_shutdown(); return ret_val; } <|endoftext|>
<commit_before>/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2010 Appcelerator, Inc. All Rights Reserved. */ #include "network_module.h" #include "common.h" static Logger* GetLogger() { return Logger::Get("Network"); } void SetCurlProxySettings(CURL* curlHandle, SharedProxy proxy) { if (proxy.isNull()) return; if (proxy->type == SOCKS) { SET_CURL_OPTION(curlHandle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); } else { SET_CURL_OPTION(curlHandle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); } SET_CURL_OPTION(curlHandle, CURLOPT_PROXY, proxy->host.c_str()); if (proxy->port != 0) { SET_CURL_OPTION(curlHandle, CURLOPT_PROXYPORT, proxy->port); } if (!proxy->username.empty() || !proxy->password.empty()) { // We are allowing any sort of authentication. This may not be the fastest // method, but at least the request will succeed. std::string proxyAuthString(proxy->username); proxyAuthString.append(":"); proxyAuthString.append(proxy->password.c_str()); SET_CURL_OPTION(curlHandle, CURLOPT_PROXYUSERPWD, proxyAuthString.c_str()); SET_CURL_OPTION(curlHandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); } } void SetStandardCurlHandleOptions(CURL* handle) { // non negative number means don't verify peer cert - we might want to // make this configurable in the future SET_CURL_OPTION(curlHandle, CURLOPT_SSL_VERIFYPEER, 1); SET_CURL_OPTION(handle, CURLOPT_CAINFO, ::UTF8ToSystem(ti::NetworkModule::GetRootCertPath()).c_str()); // If a timeout happens, this normally causes cURL to fire a signal. // Since we're running multiple threads and possibily have multiple HTTP // requests going at once, we need to disable this behavior. SET_CURL_OPTION(handle, CURLOPT_NOSIGNAL, 1); // Enable all supported Accept-Encoding values. SET_CURL_OPTION(handle, CURLOPT_ENCODING, ""); SET_CURL_OPTION(handle, CURLOPT_FOLLOWLOCATION, 1); SET_CURL_OPTION(handle, CURLOPT_AUTOREFERER, 1); static std::string cookieJarFilename; if (cookieJarFilename.empty()) { cookieJarFilename = FileUtils::Join( Host::GetInstance()->GetApplication()->GetDataPath().c_str(), "cookies.dat", 0); } // cURL doesn't have built in thread support, so we must handle thread-safety // via the CURLSH callback API. SET_CURL_OPTION(handle, CURLOPT_SHARE, ti::NetworkModule::GetCurlShareHandle()); SET_CURL_OPTION(handle, CURLOPT_COOKIEFILE, cookieJarFilename.c_str()); SET_CURL_OPTION(handle, CURLOPT_COOKIEJAR, cookieJarFilename.c_str()); } BytesRef ObjectToBytes(KObjectRef dataObject) { // If this object is a Bytes object, just do the cast and return. BytesRef bytes(dataObject.cast<Bytes>()); if (!bytes.isNull()) return bytes; // Now try to treat this object like as a file-like object with // a .read() method which returns a Bytes. If this fails we'll // return NULL. KMethodRef nativeReadMethod(dataObject->GetMethod("read", 0)); if (nativeReadMethod.isNull()) return 0; KValueRef readValue(nativeReadMethod->Call()); if (!readValue->IsObject()) return 0; // If this cast fails, it will return NULL, as we expect. return readValue->ToObject().cast<Bytes>(); } <commit_msg>Build fix in ti.Network<commit_after>/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2010 Appcelerator, Inc. All Rights Reserved. */ #include "network_module.h" #include "common.h" static Logger* GetLogger() { return Logger::Get("Network"); } void SetCurlProxySettings(CURL* curlHandle, SharedProxy proxy) { if (proxy.isNull()) return; if (proxy->type == SOCKS) { SET_CURL_OPTION(curlHandle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); } else { SET_CURL_OPTION(curlHandle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); } SET_CURL_OPTION(curlHandle, CURLOPT_PROXY, proxy->host.c_str()); if (proxy->port != 0) { SET_CURL_OPTION(curlHandle, CURLOPT_PROXYPORT, proxy->port); } if (!proxy->username.empty() || !proxy->password.empty()) { // We are allowing any sort of authentication. This may not be the fastest // method, but at least the request will succeed. std::string proxyAuthString(proxy->username); proxyAuthString.append(":"); proxyAuthString.append(proxy->password.c_str()); SET_CURL_OPTION(curlHandle, CURLOPT_PROXYUSERPWD, proxyAuthString.c_str()); SET_CURL_OPTION(curlHandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); } } void SetStandardCurlHandleOptions(CURL* handle) { // non negative number means don't verify peer cert - we might want to // make this configurable in the future SET_CURL_OPTION(handle, CURLOPT_SSL_VERIFYPEER, 1); SET_CURL_OPTION(handle, CURLOPT_CAINFO, ::UTF8ToSystem(ti::NetworkModule::GetRootCertPath()).c_str()); // If a timeout happens, this normally causes cURL to fire a signal. // Since we're running multiple threads and possibily have multiple HTTP // requests going at once, we need to disable this behavior. SET_CURL_OPTION(handle, CURLOPT_NOSIGNAL, 1); // Enable all supported Accept-Encoding values. SET_CURL_OPTION(handle, CURLOPT_ENCODING, ""); SET_CURL_OPTION(handle, CURLOPT_FOLLOWLOCATION, 1); SET_CURL_OPTION(handle, CURLOPT_AUTOREFERER, 1); static std::string cookieJarFilename; if (cookieJarFilename.empty()) { cookieJarFilename = FileUtils::Join( Host::GetInstance()->GetApplication()->GetDataPath().c_str(), "cookies.dat", 0); } // cURL doesn't have built in thread support, so we must handle thread-safety // via the CURLSH callback API. SET_CURL_OPTION(handle, CURLOPT_SHARE, ti::NetworkModule::GetCurlShareHandle()); SET_CURL_OPTION(handle, CURLOPT_COOKIEFILE, cookieJarFilename.c_str()); SET_CURL_OPTION(handle, CURLOPT_COOKIEJAR, cookieJarFilename.c_str()); } BytesRef ObjectToBytes(KObjectRef dataObject) { // If this object is a Bytes object, just do the cast and return. BytesRef bytes(dataObject.cast<Bytes>()); if (!bytes.isNull()) return bytes; // Now try to treat this object like as a file-like object with // a .read() method which returns a Bytes. If this fails we'll // return NULL. KMethodRef nativeReadMethod(dataObject->GetMethod("read", 0)); if (nativeReadMethod.isNull()) return 0; KValueRef readValue(nativeReadMethod->Call()); if (!readValue->IsObject()) return 0; // If this cast fails, it will return NULL, as we expect. return readValue->ToObject().cast<Bytes>(); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <iomanip> #include <cstdint> #include <string> #include <sys/types.h> #include <dirent.h> #include <sstream> #include <sys/stat.h> #include <cstring> #include "message.H" #include <time.h> #include <stddef.h> #include <cstdio> #include <syslog.h> const uint32_t g_eyecatcher = 0x4F424D43; // OBMC const uint16_t g_version = 1; struct logheader_t { uint32_t eyecatcher; uint16_t version; uint16_t logid; time_t timestamp; uint16_t detailsoffset; uint16_t messagelen; uint16_t severitylen; uint16_t associationlen; uint16_t reportedbylen; uint16_t debugdatalen; }; size_t get_file_size(string fn); event_manager::event_manager(string path, size_t reqmaxsize) { uint16_t x; eventpath = path; latestid = 0; dirp = NULL; logcount = 0; maxsize = -1; currentsize = 0; if (reqmaxsize) maxsize = reqmaxsize; // examine the files being managed and advance latestid to that value while ( (x = next_log()) ) { logcount++; if ( x > latestid ) latestid = x; } return; } event_manager::~event_manager() { if (dirp) closedir(dirp); return; } bool event_manager::is_logid_a_log(uint16_t logid) { std::ostringstream buffer; buffer << int(logid); return is_file_a_log(buffer.str()); } bool event_manager::is_file_a_log(string str) { std::ostringstream buffer; ifstream f; logheader_t hdr; if (!str.compare(".")) return 0; if (!str.compare("..")) return 0; buffer << eventpath << "/" << str; f.open( buffer.str(), ios::binary); if (!f.good()) { f.close(); return 0; } f.read((char*)&hdr, sizeof(hdr)); f.close(); if (hdr.eyecatcher != g_eyecatcher) return 0; return 1; } uint16_t event_manager::log_count(void) { return logcount; } uint16_t event_manager::latest_log_id(void) { return latestid; } uint16_t event_manager::new_log_id(void) { return ++latestid; } void event_manager::next_log_refresh(void) { if (dirp) { closedir(dirp); dirp = NULL; } return; } uint16_t event_manager::next_log(void) { std::ostringstream buffer; struct dirent *ent; uint16_t id; if (dirp == NULL) dirp = opendir(eventpath.c_str()); if (dirp) { do { ent = readdir(dirp); if (ent == NULL) break; string str(ent->d_name); if (is_file_a_log(str)) { id = (uint16_t) atoi(str.c_str()); break; } } while( 1 ); } else { cerr << "Error opening directory " << eventpath << endl; ent = NULL; id = 0; } if (ent == NULL) { closedir(dirp); dirp = NULL; } return ((ent == NULL) ? 0 : id); } uint16_t event_manager::create(event_record_t *rec) { rec->logid = new_log_id(); rec->timestamp = time(NULL); return create_log_event(rec); } inline uint16_t getlen(const char *s) { return (uint16_t) (1 + strlen(s)); } size_t get_file_size(string fn) { ifstream f; size_t len=0; f.open(fn, ios::in|ios::binary|ios::ate); len = f.tellg(); f.close(); return (len); } size_t event_manager::get_managed_size(void) { DIR *dirp; std::ostringstream buffer; struct dirent *ent; ifstream f; size_t db_size = 0; dirp = opendir(eventpath.c_str()); if (dirp) { while ( (ent = readdir(dirp)) != NULL ) { string str(ent->d_name); if (is_file_a_log(str)) { buffer.str(""); buffer << eventpath << "/" << str.c_str(); db_size += get_file_size(buffer.str()); } } } closedir(dirp); return (db_size); } uint16_t event_manager::create_log_event(event_record_t *rec) { std::ostringstream buffer; ofstream myfile; logheader_t hdr = {0}; size_t event_size=0; buffer << eventpath << "/" << int(rec->logid) ; hdr.eyecatcher = g_eyecatcher; hdr.version = g_version; hdr.logid = rec->logid; hdr.timestamp = rec->timestamp; hdr.detailsoffset = offsetof(logheader_t, messagelen); hdr.messagelen = getlen(rec->message); hdr.severitylen = getlen(rec->severity); hdr.associationlen = getlen(rec->association); hdr.reportedbylen = getlen(rec->reportedby); hdr.debugdatalen = rec->n; event_size = sizeof(logheader_t) + \ hdr.messagelen + \ hdr.severitylen + \ hdr.associationlen + \ hdr.reportedbylen + \ hdr.debugdatalen; if((event_size + currentsize) >= maxsize) { syslog(LOG_ERR, "event logger reached maximum capacity, event not logged"); rec->logid = 0; } else { currentsize += event_size; myfile.open(buffer.str() , ios::out|ios::binary); myfile.write((char*) &hdr, sizeof(hdr)); myfile.write((char*) rec->message, hdr.messagelen); myfile.write((char*) rec->severity, hdr.severitylen); myfile.write((char*) rec->association, hdr.associationlen); myfile.write((char*) rec->reportedby, hdr.reportedbylen); myfile.write((char*) rec->p, hdr.debugdatalen); myfile.close(); if (is_logid_a_log(rec->logid)) { logcount++; } else { cout << "Warning: Event not logged, failed to store data" << endl; rec->logid = 0; } } return rec->logid; } int event_manager::open(uint16_t logid, event_record_t **rec) { std::ostringstream buffer; ifstream f; logheader_t hdr; buffer << eventpath << "/" << int(logid); f.open( buffer.str(), ios::binary ); if (!f.good()) { return 0; } *rec = new event_record_t; f.read((char*)&hdr, sizeof(hdr)); (*rec)->logid = hdr.logid; (*rec)->timestamp = hdr.timestamp; (*rec)->message = new char[hdr.messagelen]; f.read((*rec)->message, hdr.messagelen); (*rec)->severity = new char[hdr.severitylen]; f.read((*rec)->severity, hdr.severitylen); (*rec)->association = new char[hdr.associationlen]; f.read((*rec)->association, hdr.associationlen); (*rec)->reportedby = new char[hdr.reportedbylen]; f.read((*rec)->reportedby, hdr.reportedbylen); (*rec)->p = new uint8_t[hdr.debugdatalen]; f.read((char*)(*rec)->p, hdr.debugdatalen); (*rec)->n = hdr.debugdatalen; f.close(); return logid; } void event_manager::close(event_record_t *rec) { delete[] rec->message; delete[] rec->severity; delete[] rec->association; delete[] rec->reportedby; delete[] rec->p; delete rec; logcount--; return ; } int event_manager::remove(uint16_t logid) { std::stringstream buffer; string s; size_t event_size; buffer << eventpath << "/" << int(logid); s = buffer.str(); event_size = get_file_size(s); std::remove(s.c_str()); /* If everything is working correctly deleting all the logs would */ /* result in currentsize being zero. But since size_t is unsigned */ /* it's kind of dangerous to assume life happens perfectly */ if (currentsize < event_size) currentsize = 0; else currentsize -= event_size; return 0; } <commit_msg>Limit logging<commit_after>#include <iostream> #include <fstream> #include <iomanip> #include <cstdint> #include <string> #include <sys/types.h> #include <dirent.h> #include <sstream> #include <sys/stat.h> #include <cstring> #include "message.H" #include <time.h> #include <stddef.h> #include <cstdio> #include <syslog.h> const uint32_t g_eyecatcher = 0x4F424D43; // OBMC const uint16_t g_version = 1; struct logheader_t { uint32_t eyecatcher; uint16_t version; uint16_t logid; time_t timestamp; uint16_t detailsoffset; uint16_t messagelen; uint16_t severitylen; uint16_t associationlen; uint16_t reportedbylen; uint16_t debugdatalen; }; size_t get_file_size(string fn); event_manager::event_manager(string path, size_t reqmaxsize) { uint16_t x; eventpath = path; latestid = 0; dirp = NULL; logcount = 0; maxsize = -1; currentsize = 0; if (reqmaxsize) maxsize = reqmaxsize; // examine the files being managed and advance latestid to that value while ( (x = next_log()) ) { logcount++; if ( x > latestid ) latestid = x; } return; } event_manager::~event_manager() { if (dirp) closedir(dirp); return; } bool event_manager::is_logid_a_log(uint16_t logid) { std::ostringstream buffer; buffer << int(logid); return is_file_a_log(buffer.str()); } bool event_manager::is_file_a_log(string str) { std::ostringstream buffer; ifstream f; logheader_t hdr; if (!str.compare(".")) return 0; if (!str.compare("..")) return 0; buffer << eventpath << "/" << str; f.open( buffer.str(), ios::binary); if (!f.good()) { f.close(); return 0; } f.read((char*)&hdr, sizeof(hdr)); f.close(); if (hdr.eyecatcher != g_eyecatcher) return 0; return 1; } uint16_t event_manager::log_count(void) { return logcount; } uint16_t event_manager::latest_log_id(void) { return latestid; } uint16_t event_manager::new_log_id(void) { return ++latestid; } void event_manager::next_log_refresh(void) { if (dirp) { closedir(dirp); dirp = NULL; } return; } uint16_t event_manager::next_log(void) { std::ostringstream buffer; struct dirent *ent; uint16_t id; if (dirp == NULL) dirp = opendir(eventpath.c_str()); if (dirp) { do { ent = readdir(dirp); if (ent == NULL) break; string str(ent->d_name); if (is_file_a_log(str)) { id = (uint16_t) atoi(str.c_str()); break; } } while( 1 ); } else { cerr << "Error opening directory " << eventpath << endl; ent = NULL; id = 0; } if (ent == NULL) { closedir(dirp); dirp = NULL; } return ((ent == NULL) ? 0 : id); } uint16_t event_manager::create(event_record_t *rec) { rec->logid = new_log_id(); rec->timestamp = time(NULL); return create_log_event(rec); } inline uint16_t getlen(const char *s) { return (uint16_t) (1 + strlen(s)); } /* If everything is working correctly, return file size, */ /* Otherwise return 0 */ size_t get_file_size(string fn) { struct stat f_stat; int r = -1; r = stat(fn.c_str(), &f_stat); if (r < 0) { fprintf(stderr, "Error get_file_size() for %s, %s\n", fn.c_str(), strerror(errno)); return 0; } return (f_stat.st_size); } size_t event_manager::get_managed_size(void) { DIR *dirp; std::ostringstream buffer; struct dirent *ent; ifstream f; size_t db_size = 0; dirp = opendir(eventpath.c_str()); if (dirp) { while ( (ent = readdir(dirp)) != NULL ) { string str(ent->d_name); if (is_file_a_log(str)) { buffer.str(""); buffer << eventpath << "/" << str.c_str(); db_size += get_file_size(buffer.str()); } } } closedir(dirp); return (db_size); } uint16_t event_manager::create_log_event(event_record_t *rec) { std::ostringstream buffer; ofstream myfile; logheader_t hdr = {0}; size_t event_size=0; buffer << eventpath << "/" << int(rec->logid) ; hdr.eyecatcher = g_eyecatcher; hdr.version = g_version; hdr.logid = rec->logid; hdr.timestamp = rec->timestamp; hdr.detailsoffset = offsetof(logheader_t, messagelen); hdr.messagelen = getlen(rec->message); hdr.severitylen = getlen(rec->severity); hdr.associationlen = getlen(rec->association); hdr.reportedbylen = getlen(rec->reportedby); hdr.debugdatalen = rec->n; event_size = sizeof(logheader_t) + \ hdr.messagelen + \ hdr.severitylen + \ hdr.associationlen + \ hdr.reportedbylen + \ hdr.debugdatalen; if((event_size + currentsize) >= maxsize) { syslog(LOG_ERR, "event logger reached maximum capacity, event not logged"); rec->logid = 0; } else { currentsize += event_size; myfile.open(buffer.str() , ios::out|ios::binary); myfile.write((char*) &hdr, sizeof(hdr)); myfile.write((char*) rec->message, hdr.messagelen); myfile.write((char*) rec->severity, hdr.severitylen); myfile.write((char*) rec->association, hdr.associationlen); myfile.write((char*) rec->reportedby, hdr.reportedbylen); myfile.write((char*) rec->p, hdr.debugdatalen); myfile.close(); if (is_logid_a_log(rec->logid)) { logcount++; } else { cout << "Warning: Event not logged, failed to store data" << endl; rec->logid = 0; } } return rec->logid; } int event_manager::open(uint16_t logid, event_record_t **rec) { std::ostringstream buffer; ifstream f; logheader_t hdr; buffer << eventpath << "/" << int(logid); f.open( buffer.str(), ios::binary ); if (!f.good()) { return 0; } *rec = new event_record_t; f.read((char*)&hdr, sizeof(hdr)); (*rec)->logid = hdr.logid; (*rec)->timestamp = hdr.timestamp; (*rec)->message = new char[hdr.messagelen]; f.read((*rec)->message, hdr.messagelen); (*rec)->severity = new char[hdr.severitylen]; f.read((*rec)->severity, hdr.severitylen); (*rec)->association = new char[hdr.associationlen]; f.read((*rec)->association, hdr.associationlen); (*rec)->reportedby = new char[hdr.reportedbylen]; f.read((*rec)->reportedby, hdr.reportedbylen); (*rec)->p = new uint8_t[hdr.debugdatalen]; f.read((char*)(*rec)->p, hdr.debugdatalen); (*rec)->n = hdr.debugdatalen; f.close(); return logid; } void event_manager::close(event_record_t *rec) { delete[] rec->message; delete[] rec->severity; delete[] rec->association; delete[] rec->reportedby; delete[] rec->p; delete rec; logcount--; return ; } int event_manager::remove(uint16_t logid) { std::stringstream buffer; string s; size_t event_size; buffer << eventpath << "/" << int(logid); s = buffer.str(); event_size = get_file_size(s); std::remove(s.c_str()); /* If everything is working correctly deleting all the logs would */ /* result in currentsize being zero. But since size_t is unsigned */ /* it's kind of dangerous to assume life happens perfectly */ if (currentsize < event_size) currentsize = 0; else currentsize -= event_size; return 0; } <|endoftext|>
<commit_before>//============================================================================== // Single cell simulation view graph panel widget //============================================================================== #include "singlecellsimulationviewgraphpanelwidget.h" //============================================================================== #include <QHBoxLayout> #include <QPaintEvent> //============================================================================== #include "qwt_plot.h" #include "qwt_plot_curve.h" #include "qwt_plot_grid.h" //============================================================================== #include "ui_singlecellsimulationviewgraphpanelwidget.h" //============================================================================== namespace OpenCOR { namespace SingleCellSimulationView { //============================================================================== SingleCellSimulationViewGraphPanelWidget::SingleCellSimulationViewGraphPanelWidget(QWidget *pParent) : Widget(pParent), mGui(new Ui::SingleCellSimulationViewGraphPanelWidget), mActive(false), mPlotCurves(QList<QwtPlotCurve *>()) { // Set up the GUI mGui->setupUi(this); // Create, customise and add a marker to our layout static const int MarkerWidth = 3; mMarker = new QFrame(this); mMarker->setFrameShape(QFrame::VLine); mMarker->setLineWidth(MarkerWidth); mMarker->setMinimumWidth(MarkerWidth); setActive(false); mGui->layout->addWidget(mMarker); // Create, customise and add a QwtPlot widget to our layout mPlot = new QwtPlot(this); mPlot->setCanvasBackground(Qt::white); mPlot->setCanvasLineWidth(0); mPlot->setFrameStyle(QFrame::NoFrame); QwtPlotGrid *grid = new QwtPlotGrid(); grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine)); grid->attach(mPlot); mGui->layout->addWidget(mPlot); // Allow the graph panel to be of any vertical size setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored); } //============================================================================== SingleCellSimulationViewGraphPanelWidget::~SingleCellSimulationViewGraphPanelWidget() { // Delete some internal objects resetCurves(); // Delete the GUI delete mGui; } //============================================================================== void SingleCellSimulationViewGraphPanelWidget::changeEvent(QEvent *pEvent) { // Default handling of the event Widget::changeEvent(pEvent); // Check whether the palette has changed and if so then update the colour // used to highlight the active graph panel if (pEvent->type() == QEvent::PaletteChange) setMarkerColor(); } //============================================================================== void SingleCellSimulationViewGraphPanelWidget::mousePressEvent(QMouseEvent *pEvent) { // Default handling of the event QWidget::mousePressEvent(pEvent); // Activate/inactivate the graph panel // Note: we do it through setActive() because we want the graph panel to let // people know that our active state has changed... setActive(true); } //============================================================================== QwtPlotCurve * SingleCellSimulationViewGraphPanelWidget::addCurve() { // Create a new curve QwtPlotCurve *res = new QwtPlotCurve(); // Customise it a bit res->setRenderHint(QwtPlotItem::RenderAntialiased); res->setPen(QPen(Qt::darkBlue)); // Attach it to ourselves res->attach(mPlot); // Add it to our list of curves mPlotCurves << res; // Return it to the caller return res; } //============================================================================== void SingleCellSimulationViewGraphPanelWidget::resetCurves() { // Remove any existing curve foreach (QwtPlotCurve *curve, mPlotCurves) { curve->detach(); delete curve; } mPlotCurves.clear(); // Refresh the graph panel mPlot->replot(); } //============================================================================== QwtPlot * SingleCellSimulationViewGraphPanelWidget::plot() { // Return the pointer to our plot widget return mPlot; } //============================================================================== bool SingleCellSimulationViewGraphPanelWidget::isActive() const { // Return whether the graph panel as active return mActive; } //============================================================================== void SingleCellSimulationViewGraphPanelWidget::setMarkerColor() { // Set the marker's colour based on whether the graph panel is active QPalette markerPalette = palette(); markerPalette.setColor(QPalette::WindowText, mActive? markerPalette.color(QPalette::Highlight): markerPalette.color(QPalette::Window)); mMarker->setPalette(markerPalette); } //============================================================================== void SingleCellSimulationViewGraphPanelWidget::setActive(const bool &pActive) { if (pActive == mActive) return; // Set the graph panel's active state mActive = pActive; // Update the marker's colour setMarkerColor(); // Let people know if the graph panel has been activated or inactivated if (pActive) emit activated(this); else emit inactivated(this); } //============================================================================== } // namespace SingleCellSimulationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up.<commit_after>//============================================================================== // Single cell simulation view graph panel widget //============================================================================== #include "singlecellsimulationviewgraphpanelwidget.h" //============================================================================== #include <QHBoxLayout> #include <QPaintEvent> //============================================================================== #include "qwt_plot.h" #include "qwt_plot_curve.h" #include "qwt_plot_grid.h" //============================================================================== #include "ui_singlecellsimulationviewgraphpanelwidget.h" //============================================================================== namespace OpenCOR { namespace SingleCellSimulationView { //============================================================================== SingleCellSimulationViewGraphPanelWidget::SingleCellSimulationViewGraphPanelWidget(QWidget *pParent) : Widget(pParent), mGui(new Ui::SingleCellSimulationViewGraphPanelWidget), mActive(false), mPlotCurves(QList<QwtPlotCurve *>()) { // Set up the GUI mGui->setupUi(this); // Create, customise and add a marker to our layout static const int MarkerWidth = 3; mMarker = new QFrame(this); mMarker->setFrameShape(QFrame::VLine); mMarker->setLineWidth(MarkerWidth); mMarker->setMinimumWidth(MarkerWidth); setActive(false); mGui->layout->addWidget(mMarker); // Create, customise and add a QwtPlot widget to our layout mPlot = new QwtPlot(this); mPlot->setCanvasBackground(Qt::white); mPlot->setCanvasLineWidth(0); mPlot->setFrameStyle(QFrame::NoFrame); QwtPlotGrid *grid = new QwtPlotGrid(); grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine)); grid->attach(mPlot); mGui->layout->addWidget(mPlot); // Allow the graph panel to be of any vertical size setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored); } //============================================================================== SingleCellSimulationViewGraphPanelWidget::~SingleCellSimulationViewGraphPanelWidget() { // Delete some internal objects resetCurves(); // Delete the GUI delete mGui; } //============================================================================== void SingleCellSimulationViewGraphPanelWidget::changeEvent(QEvent *pEvent) { // Default handling of the event Widget::changeEvent(pEvent); // Check whether the palette has changed and if so then update the colour // used to highlight the active graph panel if (pEvent->type() == QEvent::PaletteChange) setMarkerColor(); } //============================================================================== void SingleCellSimulationViewGraphPanelWidget::mousePressEvent(QMouseEvent *pEvent) { // Default handling of the event QWidget::mousePressEvent(pEvent); // Activate/inactivate the graph panel // Note: we do it through setActive() because we want the graph panel to let // people know that our active state has changed... setActive(true); } //============================================================================== QwtPlotCurve * SingleCellSimulationViewGraphPanelWidget::addCurve() { // Create a new curve QwtPlotCurve *res = new QwtPlotCurve(); // Customise it a bit res->setRenderHint(QwtPlotItem::RenderAntialiased); res->setPen(QPen(Qt::darkBlue)); // Attach it to ourselves res->attach(mPlot); // Add it to our list of curves mPlotCurves << res; // Return it to the caller return res; } //============================================================================== void SingleCellSimulationViewGraphPanelWidget::resetCurves() { // Remove any existing curve foreach (QwtPlotCurve *curve, mPlotCurves) { curve->detach(); delete curve; } mPlotCurves.clear(); // Refresh the graph panel mPlot->replot(); } //============================================================================== QwtPlot * SingleCellSimulationViewGraphPanelWidget::plot() { // Return the pointer to our plot widget return mPlot; } //============================================================================== bool SingleCellSimulationViewGraphPanelWidget::isActive() const { // Return whether the graph panel as active return mActive; } //============================================================================== void SingleCellSimulationViewGraphPanelWidget::setMarkerColor() { // Set the marker's colour based on whether the graph panel is active QPalette newPalette = palette(); newPalette.setColor(QPalette::WindowText, mActive? newPalette.color(QPalette::Highlight): newPalette.color(QPalette::Window)); mMarker->setPalette(newPalette); } //============================================================================== void SingleCellSimulationViewGraphPanelWidget::setActive(const bool &pActive) { if (pActive == mActive) return; // Set the graph panel's active state mActive = pActive; // Update the marker's colour setMarkerColor(); // Let people know if the graph panel has been activated or inactivated if (pActive) emit activated(this); else emit inactivated(this); } //============================================================================== } // namespace SingleCellSimulationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/** @file traits.hpp @brief Type traits and helpers. @author Tim Howard @copyright 2013 Tim Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_TRAITS_HPP_ #define HORD_TRAITS_HPP_ #include "./config.hpp" #include <type_traits> namespace Hord { // Forward declarations /** @addtogroup traits @{ */ /** Require a trait. @tparam Trait The trait to require. */ template<typename Trait> struct require_trait { static_assert( true==Trait::value, "required trait is not satisfied" ); }; /** Disallow a trait. @tparam Trait The trait to disallow. */ template<typename Trait> struct disallow_trait { static_assert( false==Trait::value, "disallowed trait is present" ); }; /** Whether a type is either copy constructible or copy assignable. @remarks OR of @c std::is_copy_constructible and @c std::is_copy_assignable. @tparam T Type to test. */ template<typename T> struct is_copy_constructible_or_assignable : public std::integral_constant<bool, // FIXME: libstdc++ 4.6.3 does not have // is_assignable nor the is_copy traits. std::is_constructible<T, T const&>::value //std::is_copy_constructible<T>::value || //std::is_copy_assignable<T>::value > {}; /** @} */ // end of doc-group traits } // namespace Hord #endif // HORD_TRAITS_HPP_ <commit_msg>traits: gave all traits and helpers the final specifier.<commit_after>/** @file traits.hpp @brief Type traits and helpers. @author Tim Howard @copyright 2013 Tim Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_TRAITS_HPP_ #define HORD_TRAITS_HPP_ #include "./config.hpp" #include <type_traits> namespace Hord { // Forward declarations /** @addtogroup traits @{ */ /** Require a trait. @tparam Trait The trait to require. */ template<typename Trait> struct require_trait final { static_assert( true==Trait::value, "required trait is not satisfied" ); }; /** Disallow a trait. @tparam Trait The trait to disallow. */ template<typename Trait> struct disallow_trait final { static_assert( false==Trait::value, "disallowed trait is present" ); }; /** Whether a type is either copy constructible or copy assignable. @remarks OR of @c std::is_copy_constructible and @c std::is_copy_assignable. @tparam T Type to test. */ template<typename T> struct is_copy_constructible_or_assignable final : public std::integral_constant<bool, // FIXME: libstdc++ 4.6.3 does not have // is_assignable nor the is_copy traits. std::is_constructible<T, T const&>::value //std::is_copy_constructible<T>::value || //std::is_copy_assignable<T>::value > {}; /** @} */ // end of doc-group traits } // namespace Hord #endif // HORD_TRAITS_HPP_ <|endoftext|>
<commit_before>/* * Copyright 2009-2015 The VOTCA Development Team (http://www.votca.org) * * 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 "h5mdtrajectoryreader.h" #include "hdf5.h" #include <vector> namespace votca { namespace csg { H5MDTrajectoryReader::H5MDTrajectoryReader(){ h5file_ = NULL; particle_group_ = NULL; atom_position_group_ = NULL; atom_force_group_ = NULL; atom_velocity_group_ = NULL; atom_id_group_ = NULL; time_set_ = NULL; step_set_ = NULL; has_velocity_ = false; has_force_ = false; has_id_group_ = false; } H5MDTrajectoryReader::~H5MDTrajectoryReader() { delete particle_group_; delete atom_position_group_; delete atom_force_group_; delete ds_atom_position_; if (has_force_) delete ds_atom_force_; if (has_velocity_) delete ds_atom_velocity_; if (has_id_group_) delete atom_id_group_; delete ds_time_; delete ds_step_; delete[] time_set_; delete[] step_set_; delete h5file_; } bool H5MDTrajectoryReader::Open(const string &file) { // Turn on exceptions instead of various messages. H5::Exception::dontPrint(); // Checks if we deal with hdf5 file. if (! H5::H5File::isHdf5(file) ) throw std::ios_base::failure("Error on open trajectory file: " + file); h5file_ = new H5::H5File(file, H5F_ACC_RDONLY); // Check the version of the file. H5::Group *g_h5md = new H5::Group(h5file_->openGroup("h5md")); H5::Attribute *at_version = new H5::Attribute(g_h5md->openAttribute("version")); int version[2]; at_version->read(at_version->getDataType(), &version); if (version[0] != 1 || (version[0] == 1 && version[1] > 0)) { h5file_->close(); std::cout << "Major version " << version[0] << std::endl; std::cout << "Minor version " << version[1] << std::endl; throw std::ios_base::failure("Wrong version of H5MD file."); } // Clean up. g_h5md->close(); delete at_version; delete g_h5md; // Checks if the particles group exists and what is the number of members. particle_group_ = new H5::Group(h5file_->openGroup("particles")); if (particle_group_->getNumObjs() == 0) { h5file_->close(); throw std::ios_base::failure("The particles group is empty."); } has_velocity_ = false; has_force_ = false; first_frame_ = true; return true; } void H5MDTrajectoryReader::Close() { h5file_->close(); } bool H5MDTrajectoryReader::FirstFrame(Topology &top) { // NOLINT const reference // First frame has access to topology so here we will check if the particle_group exists. if (first_frame_) { first_frame_ = false; std::string *particle_group_name = new std::string(top.getParticleGroup()); if(*particle_group_name == "") throw std::ios_base::failure("Missing particle group in topology. Please set h5md_particle_group tag with name \ attribute set to the particle group."); //particle_group_ = new H5::Group(h5file_->openGroup("particles")); try { atom_position_group_ = new H5::Group(particle_group_->openGroup( *particle_group_name + "/position")); } catch (H5::GroupIException not_found_error) { std::cout << "Error: The path '/particles/" << *particle_group_name << "/position' not found. Please check the name "; std::cout << "of particle group defined in topology" << std::endl; throw not_found_error; } idx_frame_ = -1; ds_atom_position_ = new H5::DataSet(atom_position_group_->openDataSet("value")); ds_step_ = new H5::DataSet(atom_position_group_->openDataSet("step")); ds_time_ = new H5::DataSet(atom_position_group_->openDataSet("time")); // Gets number of particles and dimensions. H5::DataSpace fs_atom_position_ = ds_atom_position_->getSpace(); hsize_t dims[3]; rank_ = fs_atom_position_.getSimpleExtentDims(dims); N_particles_ = dims[1]; variables_ = dims[2]; if(!has_id_group_ && N_particles_ != top.BeadCount()) { std::cout << "Warning: The number of beads (" << N_particles_ << ")"; std::cout << " in the trajectory is different than defined in the topology (" << top.BeadCount() << ")" << std::endl; std::cout << "The number of beads from topology will be used!" << std::endl; N_particles_ = top.BeadCount(); } chunk_rows_[0] = 1; chunk_rows_[1] = N_particles_; chunk_rows_[2] = variables_; // Reads the time set and step set. H5::DataSet *ds_pos_step = new H5::DataSet(atom_position_group_->openDataSet("step")); H5::DataSet *ds_pos_time = new H5::DataSet(atom_position_group_->openDataSet("time")); H5::DataSpace dsp_step = H5::DataSpace(ds_pos_step->getSpace()); H5::DataSpace dsp_time = H5::DataSpace(ds_pos_time->getSpace()); hsize_t step_dims[3]; dsp_step.getSimpleExtentDims(step_dims); time_set_ = new double[step_dims[0]]; step_set_ = new int[step_dims[0]]; ds_pos_step->read(step_set_, H5::PredType::NATIVE_INT, dsp_step, dsp_step); ds_pos_time->read(time_set_, H5::PredType::NATIVE_DOUBLE, dsp_time, dsp_time); delete ds_pos_step; delete ds_pos_time; // Reads the box information. H5::Group g_box = H5::Group(particle_group_->openGroup( *particle_group_name + "/box")); H5::Attribute at_box_dimension = H5::Attribute(g_box.openAttribute("dimension")); int dimension; at_box_dimension.read(at_box_dimension.getDataType(), &dimension); if (dimension != 3 ) { throw std::ios_base::failure("Wrong dimension " + boost::lexical_cast<string>(dimension)); } // Gets the force group. try { std::string force_group_name = *particle_group_name + "/force"; atom_force_group_ = new H5::Group(particle_group_->openGroup(force_group_name)); ds_atom_force_ = new H5::DataSet(atom_force_group_->openDataSet("value")); } catch (H5::GroupIException not_found) { has_force_ = false; } // Gets the velocity group. try { std::string velocity_group_name = *particle_group_name + "/velocity"; atom_velocity_group_ = new H5::Group(particle_group_->openGroup(velocity_group_name)); ds_atom_velocity_ = new H5::DataSet(atom_velocity_group_->openDataSet("value")); } catch (H5::GroupIException not_found) { has_velocity_ = false; } // Gets the id group so that the atom id is taken from this group. try { std::string id_group_name = *particle_group_name + "/id"; atom_id_group_ = new H5::Group(particle_group_->openGroup(id_group_name)); ds_atom_id_ = new H5::DataSet(atom_id_group_->openDataSet("value")); has_id_group_ = true; } catch (H5::GroupIException not_found) { has_id_group_ = false; } delete particle_group_name; } NextFrame(top); return true; } /// Reading the data. bool H5MDTrajectoryReader::NextFrame(Topology &top) { // NOLINT const reference // Reads the position row. H5::Exception::dontPrint(); idx_frame_++; std::cout << '\r' << "Reading frame: " << idx_frame_; std::cout.flush(); double *positions; try { positions = ReadVectorData<double>(ds_atom_position_, H5::PredType::NATIVE_DOUBLE, idx_frame_); } catch (H5::DataSetIException not_found) { return false; } double *forces = NULL; double *velocities = NULL; int *ids = NULL; if (has_velocity_) { velocities = ReadVectorData<double>(ds_atom_velocity_, H5::PredType::NATIVE_DOUBLE, idx_frame_); } if (has_force_) { forces = ReadVectorData<double>(ds_atom_force_, H5::PredType::NATIVE_DOUBLE, idx_frame_); } if (has_id_group_) { ids = ReadScalarData<int>(ds_atom_id_, H5::PredType::NATIVE_INT, idx_frame_); } //Process atoms. for (int at_idx = 0; at_idx < N_particles_; at_idx++) { double x, y, z; int array_index = at_idx*variables_; x = positions[array_index]; y = positions[array_index + 1]; z = positions[array_index + 2]; // Set atom id, or it is an index of a row in dataset or from id dataset. int atom_id = at_idx; if (has_id_group_) { if (ids[at_idx] == -1) // ignore values where id == -1 continue; atom_id = ids[at_idx] - 1; } // Topology has to be defined in the xml file or in other // topology files. The h5md only stores the trajectory data. Bead *b = top.getBead(atom_id); b->setPos(vec(x, y, z)); if (has_velocity_) { double vx, vy, vz; vx = velocities[array_index]; vy = velocities[array_index + 1]; vz = velocities[array_index + 2]; b->setVel(vec(vx, vy, vz)); } if (has_force_) { double fx, fy, fz; fx = forces[array_index]; fy = forces[array_index + 1]; fz = forces[array_index + 2]; b->setF(vec(fx, fy, fz)); } } // Clean up pointers. delete[] positions; delete[] forces; delete[] velocities; delete[] ids; return true; } } // end csg } // end votca <commit_msg>Fixed issue with number of particles when /id is available.<commit_after>/* * Copyright 2009-2015 The VOTCA Development Team (http://www.votca.org) * * 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 "h5mdtrajectoryreader.h" #include "hdf5.h" #include <vector> namespace votca { namespace csg { H5MDTrajectoryReader::H5MDTrajectoryReader(){ h5file_ = NULL; particle_group_ = NULL; atom_position_group_ = NULL; atom_force_group_ = NULL; atom_velocity_group_ = NULL; atom_id_group_ = NULL; time_set_ = NULL; step_set_ = NULL; has_velocity_ = false; has_force_ = false; has_id_group_ = false; } H5MDTrajectoryReader::~H5MDTrajectoryReader() { delete particle_group_; delete atom_position_group_; delete atom_force_group_; delete ds_atom_position_; if (has_force_) delete ds_atom_force_; if (has_velocity_) delete ds_atom_velocity_; if (has_id_group_) delete atom_id_group_; delete ds_time_; delete ds_step_; delete[] time_set_; delete[] step_set_; delete h5file_; } bool H5MDTrajectoryReader::Open(const string &file) { // Turn on exceptions instead of various messages. H5::Exception::dontPrint(); // Checks if we deal with hdf5 file. if (! H5::H5File::isHdf5(file) ) throw std::ios_base::failure("Error on open trajectory file: " + file); h5file_ = new H5::H5File(file, H5F_ACC_RDONLY); // Check the version of the file. H5::Group *g_h5md = new H5::Group(h5file_->openGroup("h5md")); H5::Attribute *at_version = new H5::Attribute(g_h5md->openAttribute("version")); int version[2]; at_version->read(at_version->getDataType(), &version); if (version[0] != 1 || (version[0] == 1 && version[1] > 0)) { h5file_->close(); std::cout << "Major version " << version[0] << std::endl; std::cout << "Minor version " << version[1] << std::endl; throw std::ios_base::failure("Wrong version of H5MD file."); } // Clean up. g_h5md->close(); delete at_version; delete g_h5md; // Checks if the particles group exists and what is the number of members. particle_group_ = new H5::Group(h5file_->openGroup("particles")); if (particle_group_->getNumObjs() == 0) { h5file_->close(); throw std::ios_base::failure("The particles group is empty."); } has_velocity_ = false; has_force_ = false; first_frame_ = true; return true; } void H5MDTrajectoryReader::Close() { h5file_->close(); } bool H5MDTrajectoryReader::FirstFrame(Topology &top) { // NOLINT const reference // First frame has access to topology so here we will check if the particle_group exists. if (first_frame_) { first_frame_ = false; std::string *particle_group_name = new std::string(top.getParticleGroup()); if(*particle_group_name == "") throw std::ios_base::failure("Missing particle group in topology. Please set h5md_particle_group tag with name \ attribute set to the particle group."); //particle_group_ = new H5::Group(h5file_->openGroup("particles")); try { atom_position_group_ = new H5::Group(particle_group_->openGroup( *particle_group_name + "/position")); } catch (H5::GroupIException not_found_error) { std::cout << "Error: The path '/particles/" << *particle_group_name << "/position' not found. Please check the name "; std::cout << "of particle group defined in topology" << std::endl; throw not_found_error; } idx_frame_ = -1; ds_atom_position_ = new H5::DataSet(atom_position_group_->openDataSet("value")); ds_step_ = new H5::DataSet(atom_position_group_->openDataSet("step")); ds_time_ = new H5::DataSet(atom_position_group_->openDataSet("time")); // Reads the time set and step set. H5::DataSet *ds_pos_step = new H5::DataSet(atom_position_group_->openDataSet("step")); H5::DataSet *ds_pos_time = new H5::DataSet(atom_position_group_->openDataSet("time")); H5::DataSpace dsp_step = H5::DataSpace(ds_pos_step->getSpace()); H5::DataSpace dsp_time = H5::DataSpace(ds_pos_time->getSpace()); hsize_t step_dims[3]; dsp_step.getSimpleExtentDims(step_dims); time_set_ = new double[step_dims[0]]; step_set_ = new int[step_dims[0]]; ds_pos_step->read(step_set_, H5::PredType::NATIVE_INT, dsp_step, dsp_step); ds_pos_time->read(time_set_, H5::PredType::NATIVE_DOUBLE, dsp_time, dsp_time); delete ds_pos_step; delete ds_pos_time; // Reads the box information. H5::Group g_box = H5::Group(particle_group_->openGroup( *particle_group_name + "/box")); H5::Attribute at_box_dimension = H5::Attribute(g_box.openAttribute("dimension")); int dimension; at_box_dimension.read(at_box_dimension.getDataType(), &dimension); if (dimension != 3 ) { throw std::ios_base::failure("Wrong dimension " + boost::lexical_cast<string>(dimension)); } // Gets the force group. try { std::string force_group_name = *particle_group_name + "/force"; atom_force_group_ = new H5::Group(particle_group_->openGroup(force_group_name)); ds_atom_force_ = new H5::DataSet(atom_force_group_->openDataSet("value")); has_force_ = true; std::cout << "H5MD: has /force" << std::endl; } catch (H5::GroupIException not_found) { has_force_ = false; } // Gets the velocity group. try { std::string velocity_group_name = *particle_group_name + "/velocity"; atom_velocity_group_ = new H5::Group(particle_group_->openGroup(velocity_group_name)); ds_atom_velocity_ = new H5::DataSet(atom_velocity_group_->openDataSet("value")); has_velocity_ = true; std::cout << "H5MD: has /velocity" << std::endl; } catch (H5::GroupIException not_found) { has_velocity_ = false; } // Gets the id group so that the atom id is taken from this group. try { std::string id_group_name = *particle_group_name + "/id"; atom_id_group_ = new H5::Group(particle_group_->openGroup(id_group_name)); ds_atom_id_ = new H5::DataSet(atom_id_group_->openDataSet("value")); has_id_group_ = true; std::cout << "H5MD: has /id group" << std::endl; } catch (H5::GroupIException not_found) { has_id_group_ = false; } // Gets number of particles and dimensions. H5::DataSpace fs_atom_position_ = ds_atom_position_->getSpace(); hsize_t dims[3]; rank_ = fs_atom_position_.getSimpleExtentDims(dims); N_particles_ = dims[1]; variables_ = dims[2]; if (!has_id_group_ && N_particles_ != top.BeadCount()) { std::cout << "Warning: The number of beads (" << N_particles_ << ")"; std::cout << " in the trajectory is different than defined in the topology (" << top.BeadCount() << ")" << std::endl; std::cout << "The number of beads from topology will be used!" << std::endl; N_particles_ = top.BeadCount(); } chunk_rows_[0] = 1; chunk_rows_[1] = N_particles_; chunk_rows_[2] = variables_; delete particle_group_name; } NextFrame(top); return true; } /// Reading the data. bool H5MDTrajectoryReader::NextFrame(Topology &top) { // NOLINT const reference // Reads the position row. H5::Exception::dontPrint(); idx_frame_++; std::cout << '\r' << "Reading frame: " << idx_frame_; std::cout.flush(); double *positions; try { positions = ReadVectorData<double>(ds_atom_position_, H5::PredType::NATIVE_DOUBLE, idx_frame_); } catch (H5::DataSetIException not_found) { return false; } double *forces = NULL; double *velocities = NULL; int *ids = NULL; if (has_velocity_) { velocities = ReadVectorData<double>(ds_atom_velocity_, H5::PredType::NATIVE_DOUBLE, idx_frame_); } if (has_force_) { forces = ReadVectorData<double>(ds_atom_force_, H5::PredType::NATIVE_DOUBLE, idx_frame_); } if (has_id_group_) { ids = ReadScalarData<int>(ds_atom_id_, H5::PredType::NATIVE_INT, idx_frame_); } //Process atoms. for (int at_idx = 0; at_idx < N_particles_; at_idx++) { double x, y, z; int array_index = at_idx*variables_; x = positions[array_index]; y = positions[array_index + 1]; z = positions[array_index + 2]; // Set atom id, or it is an index of a row in dataset or from id dataset. int atom_id = at_idx; if (has_id_group_) { if (ids[at_idx] == -1) // ignore values where id == -1 continue; atom_id = ids[at_idx] - 1; } // Topology has to be defined in the xml file or in other // topology files. The h5md only stores the trajectory data. Bead *b = top.getBead(atom_id); b->setPos(vec(x, y, z)); if (has_velocity_) { double vx, vy, vz; vx = velocities[array_index]; vy = velocities[array_index + 1]; vz = velocities[array_index + 2]; b->setVel(vec(vx, vy, vz)); } if (has_force_) { double fx, fy, fz; fx = forces[array_index]; fy = forces[array_index + 1]; fz = forces[array_index + 2]; b->setF(vec(fx, fy, fz)); } } // Clean up pointers. delete[] positions; delete[] forces; delete[] velocities; delete[] ids; return true; } } // end csg } // end votca <|endoftext|>
<commit_before>/* * Copyright (c) 2017 Deepsea * * This software may be modified and distributed under * the terms of the MIT license. See the LICENSE file * for details. * */ #include <stdlib.h> #include <atomic> #include <assert.h> #ifndef _CACTUS_STACK_PLUS_H_ #define _CACTUS_STACK_PLUS_H_ #ifndef CACTUS_STACK_BASIC_LG_K #define CACTUS_STACK_BASIC_LG_K 12 #endif namespace cactus_stack { namespace plus { namespace { /*------------------------------*/ /* Forward declarations */ struct frame_header_struct; /* Forward declarations */ /*------------------------------*/ /*------------------------------*/ /* Stack chunk */ static constexpr int lg_K = CACTUS_STACK_BASIC_LG_K; // size in bytes of a chunk static constexpr int K = 1 << lg_K; using chunk_header_type = struct { std::atomic<int> refcount; struct frame_header_struct* sp; struct frame_header_struct* lp; }; using chunk_type = struct { chunk_header_type hdr; char frames[K - sizeof(chunk_header_type)]; }; static inline void* aligned_alloc(size_t alignment, size_t size) { void* p; assert(alignment % sizeof(void*) == 0); if (posix_memalign(&p, alignment, size)) { p = nullptr; } return p; } static inline chunk_type* create_chunk(struct frame_header_struct* sp, struct frame_header_struct* lp) { chunk_type* c = (chunk_type*)aligned_alloc(K, K); new (c) chunk_type; c->hdr.refcount.store(1); c->hdr.sp = sp; c->hdr.lp = lp; return c; } template <class T> chunk_type* chunk_of(T* p) { uintptr_t v = (uintptr_t)(((char*)p) - 1); v = v & ~(K - 1); return (chunk_type*)v; } static inline char* chunk_data(chunk_type* c) { return &(c->frames[0]); } static inline void incr_refcount(chunk_type* c) { c->hdr.refcount++; } static inline void decr_refcount(chunk_type* c) { assert(c->hdr.refcount.load() >= 1); if (--c->hdr.refcount == 0) { free(c); } } /* Stack chunk */ /*------------------------------*/ /*------------------------------*/ /* Frame */ using call_link_type = enum { Call_link_async, Call_link_sync }; using loop_link_type = enum { Loop_link_child, Loop_link_none }; using shared_frame_type = enum { Shared_frame_direct, Shared_frame_indirect }; using frame_header_ext_type = struct { call_link_type clt; loop_link_type llt; shared_frame_type sft; struct frame_header_struct* pred; struct frame_header_struct* succ; }; using frame_header_type = struct frame_header_struct { struct frame_header_struct* pred; frame_header_ext_type ext; }; template <class T=char> T* frame_data(frame_header_type* p) { char* r = (char*)p; if (r != nullptr) { /* later: need to change sizeof(...) calculation if * we switch to using variable-length frame-headers */ r += sizeof(frame_header_type); } return (T*)r; } /* Frame */ /*------------------------------*/ } // end namespace /*------------------------------*/ /* Stack */ using stack_type = struct { frame_header_type* fp, * sp, * lp; frame_header_type* mhd, * mtl; }; stack_type create_stack() { return { .fp = nullptr, .sp = nullptr, .lp = nullptr, .mhd = nullptr, .mtl = nullptr }; } bool empty(stack_type s) { return s.fp == nullptr; } bool empty_mark(stack_type s) { return s.mhd == nullptr; } template <class Read_fn> void peek_back(stack_type s, const Read_fn& read_fn) { assert(! empty(s)); read_fn(s.fp->ext.sft, s.fp->ext.clt, frame_data(s.fp)); } template <class Read_fn> void peek_mark(stack_type s, const Read_fn& read_fn) { assert(! empty_mark(s)); auto sft = s.mhd->ext.sft; auto clt = s.mhd->ext.clt; auto _ar = frame_data(s.mhd); auto pred = s.mhd->pred; auto pred_sft = (pred == nullptr) ? Shared_frame_direct : pred->ext.sft; auto _pred_ar = (pred == nullptr) ? nullptr : frame_data(pred); read_fn(sft, clt, _ar, pred_sft, _pred_ar); } template <class Is_splittable_fn> stack_type update_marks_bkw(stack_type s, const Is_splittable_fn& is_splittable_fn) { stack_type t = s; if (t.mtl == nullptr) { return t; } bool is_async_mtl = (t.mtl->ext.clt == Call_link_async); bool is_splittable_mtl = is_splittable_fn(frame_data(t.mtl)); bool is_loop_child_mtl = (t.mtl->ext.llt == Loop_link_child); if (is_async_mtl || is_splittable_mtl || is_loop_child_mtl) { return t; } frame_header_type* pred = t.mtl->ext.pred; t.mtl = pred; if (pred != nullptr) { pred->ext.succ = nullptr; } if (s.mtl == s.mhd) { t.mhd = pred; } return t; } template <class Is_splittable_fn> stack_type update_marks_fwd(stack_type s, const Is_splittable_fn& is_splittable_fn) { stack_type t = s; if (t.mhd == nullptr) { return t; } bool is_async_mhd = (t.mhd->ext.clt == Call_link_async); bool is_splittable_mhd = is_splittable_fn(frame_data(t.mhd)); if (is_async_mhd || is_splittable_mhd) { return t; } frame_header_type* succ = t.mhd->ext.succ; t.mhd = succ; if (succ != nullptr) { succ->ext.pred = nullptr; } if (s.mtl == s.mhd) { t.mtl = succ; } if (t.mhd != nullptr) { t.mhd->ext.llt = Loop_link_none; } return t; } using parent_link_type = enum { Parent_link_async, Parent_link_sync }; template <int frame_szb, class Initialize_fn, class Is_splittable_fn> stack_type push_back(stack_type s, parent_link_type ty, const Initialize_fn& initialize_fn, const Is_splittable_fn& is_splittable_fn) { stack_type t = s; auto b = sizeof(frame_header_type) + frame_szb; assert(b + sizeof(chunk_header_type) <= K); t.fp = s.sp; t.sp = (frame_header_type*)((char*)t.fp + b); if (t.sp >= t.lp) { chunk_type* c = create_chunk(s.sp, s.lp); t.fp = (frame_header_type*)chunk_data(c); t.sp = (frame_header_type*)((char*)t.fp + b); t.lp = (frame_header_type*)((char*)c + K); } initialize_fn(frame_data(t.fp)); frame_header_ext_type ext; bool is_async_tfp = (ty == Parent_link_async); bool is_splittable_tfp = is_splittable_fn(frame_data(t.fp)); frame_header_type* pred = s.fp; bool is_loop_child_tfp = ((pred != nullptr) && is_splittable_fn(frame_data(pred))); if (is_async_tfp || is_splittable_tfp || is_loop_child_tfp) { ext.pred = s.mtl; if (s.mtl != nullptr) { s.mtl->ext.succ = t.fp; } t.mtl = t.fp; if (t.mhd == nullptr) { t.mhd = t.mtl; } } else { ext.pred = nullptr; } ext.sft = Shared_frame_direct; ext.clt = (is_async_tfp ? Call_link_async : Call_link_sync); ext.llt = (is_loop_child_tfp ? Loop_link_child : Loop_link_none); ext.succ = nullptr; t.fp->pred = pred; t.fp->ext = ext; return t; } template <class Is_splittable_fn, class Destruct_fn> stack_type pop_back(stack_type s, const Is_splittable_fn& is_splittable_fn, const Destruct_fn& destruct_fn) { stack_type t = s; destruct_fn(frame_data(s.fp)); bool is_splittable_sfp = is_splittable_fn(frame_data(s.fp)); bool is_async_sfp = (s.fp->ext.clt == Call_link_async); bool is_loop_child_sfp = (s.fp->ext.llt == Loop_link_child); if (is_async_sfp || is_splittable_sfp || is_loop_child_sfp) { frame_header_type* pred = s.fp->ext.pred; if (pred == nullptr) { t.mhd = nullptr; } else { pred->ext.succ = nullptr; } t.mtl = pred; } t.fp = s.fp->pred; chunk_type* cfp = chunk_of(s.fp); if (chunk_of(t.fp) == cfp) { t.sp = s.fp; t.lp = s.lp; } else { t.sp = cfp->hdr.sp; t.lp = cfp->hdr.lp; decr_refcount(cfp); } return update_marks_bkw(t, is_splittable_fn); } template <class Is_splittable_fn> std::pair<stack_type, stack_type> fork_mark(stack_type s, const Is_splittable_fn& is_splittable_fn) { stack_type s1 = s; stack_type s2 = create_stack(); if (empty_mark(s)) { return std::make_pair(s1, s2); } frame_header_type* pf1, * pf2; if (s.mhd->pred == nullptr) { pf2 = s.mhd->ext.succ; if (pf2 == nullptr) { return std::make_pair(s1, s2); } else { s.mhd->ext.pred = nullptr; s1.mhd = s.mhd; } } else { pf2 = s.mhd; s1.mhd = nullptr; } pf1 = pf2->pred; s1.fp = pf1; chunk_type* cf1 = chunk_of(pf1); if (cf1 == chunk_of(pf2)) { incr_refcount(cf1); } if (chunk_of(s.sp) == cf1) { s1.sp = pf2; } else { s1.sp = nullptr; } s1.lp = s1.sp; s1.mtl = s1.mhd; s2 = s; s2.mhd = pf2; pf2->pred = nullptr; pf2->ext.pred = nullptr; s1 = update_marks_bkw(s1, is_splittable_fn); s2 = update_marks_fwd(s2, is_splittable_fn); return std::make_pair(s1, s2); } template <class Is_splittable_fn> std::pair<stack_type, stack_type> split_mark(stack_type s, const Is_splittable_fn& is_splittable_fn) { stack_type s1 = s; stack_type s2 = create_stack(); frame_header_type* pf = s.mhd; if (pf == nullptr) { return std::make_pair(s1, s2); } frame_header_type* pg = pf->ext.succ; if (pg == nullptr) { return std::make_pair(s1, s2); } assert(pg->pred == pf); pf->ext.succ = nullptr; pg->ext.pred = nullptr; pg->pred = nullptr; s1.fp = pf; s1.sp = nullptr; s1.lp = nullptr; s1.mtl = pf; pf->ext.llt = Loop_link_none; s2 = s; s2.mhd = pg; if (s.mhd == s.mtl) { s2.mtl = s2.mhd; } s1 = update_marks_bkw(s1, is_splittable_fn); s2 = update_marks_fwd(s2, is_splittable_fn); chunk_type* cpf = chunk_of(pf); if (cpf == chunk_of(pg)) { incr_refcount(cpf); } return std::make_pair(s1, s2); } template <int frame_szb, class Initialize_fn, class Is_splittable_fn> stack_type create_stack(parent_link_type ty, const Initialize_fn& initialize_fn, const Is_splittable_fn& is_splittable_fn) { stack_type s = create_stack(); s = push_back<frame_szb>(s, ty, initialize_fn, is_splittable_fn); s.fp->ext.sft = Shared_frame_indirect; return s; } /* Stack */ /*------------------------------*/ } // end namespace } // end namespace #endif /*! _CACTUS_STACK_PLUS_H_ */ <commit_msg>working on loop splitting in encore<commit_after>/* * Copyright (c) 2017 Deepsea * * This software may be modified and distributed under * the terms of the MIT license. See the LICENSE file * for details. * */ #include <stdlib.h> #include <atomic> #include <assert.h> #ifndef _CACTUS_STACK_PLUS_H_ #define _CACTUS_STACK_PLUS_H_ #ifndef CACTUS_STACK_BASIC_LG_K #define CACTUS_STACK_BASIC_LG_K 12 #endif namespace cactus_stack { namespace plus { namespace { /*------------------------------*/ /* Forward declarations */ struct frame_header_struct; /* Forward declarations */ /*------------------------------*/ /*------------------------------*/ /* Stack chunk */ static constexpr int lg_K = CACTUS_STACK_BASIC_LG_K; // size in bytes of a chunk static constexpr int K = 1 << lg_K; using chunk_header_type = struct { std::atomic<int> refcount; struct frame_header_struct* sp; struct frame_header_struct* lp; }; using chunk_type = struct { chunk_header_type hdr; char frames[K - sizeof(chunk_header_type)]; }; static inline void* aligned_alloc(size_t alignment, size_t size) { void* p; assert(alignment % sizeof(void*) == 0); if (posix_memalign(&p, alignment, size)) { p = nullptr; } return p; } static inline chunk_type* create_chunk(struct frame_header_struct* sp, struct frame_header_struct* lp) { chunk_type* c = (chunk_type*)aligned_alloc(K, K); new (c) chunk_type; c->hdr.refcount.store(1); c->hdr.sp = sp; c->hdr.lp = lp; return c; } template <class T> chunk_type* chunk_of(T* p) { uintptr_t v = (uintptr_t)(((char*)p) - 1); v = v & ~(K - 1); return (chunk_type*)v; } static inline char* chunk_data(chunk_type* c) { return &(c->frames[0]); } static inline void incr_refcount(chunk_type* c) { c->hdr.refcount++; } static inline void decr_refcount(chunk_type* c) { assert(c->hdr.refcount.load() >= 1); if (--c->hdr.refcount == 0) { free(c); } } /* Stack chunk */ /*------------------------------*/ /*------------------------------*/ /* Frame */ using call_link_type = enum { Call_link_async, Call_link_sync }; using loop_link_type = enum { Loop_link_child, Loop_link_none }; using shared_frame_type = enum { Shared_frame_direct, Shared_frame_indirect }; using frame_header_ext_type = struct { call_link_type clt; loop_link_type llt; shared_frame_type sft; struct frame_header_struct* pred; struct frame_header_struct* succ; }; using frame_header_type = struct frame_header_struct { struct frame_header_struct* pred; frame_header_ext_type ext; }; template <class T=char> T* frame_data(frame_header_type* p) { char* r = (char*)p; if (r != nullptr) { /* later: need to change sizeof(...) calculation if * we switch to using variable-length frame-headers */ r += sizeof(frame_header_type); } return (T*)r; } /* Frame */ /*------------------------------*/ } // end namespace /*------------------------------*/ /* Stack */ using stack_type = struct { frame_header_type* fp, * sp, * lp; frame_header_type* mhd, * mtl; }; stack_type create_stack() { return { .fp = nullptr, .sp = nullptr, .lp = nullptr, .mhd = nullptr, .mtl = nullptr }; } bool empty(stack_type s) { return s.fp == nullptr; } bool empty_mark(stack_type s) { return s.mhd == nullptr; } template <class Read_fn> void peek_back(stack_type s, const Read_fn& read_fn) { assert(! empty(s)); read_fn(s.fp->ext.sft, s.fp->ext.clt, frame_data(s.fp)); } template <class Read_fn> void peek_mark(stack_type s, const Read_fn& read_fn) { assert(! empty_mark(s)); auto sft = s.mhd->ext.sft; auto clt = s.mhd->ext.clt; auto _ar = frame_data(s.mhd); auto pred = s.mhd->pred; auto pred_sft = (pred == nullptr) ? Shared_frame_direct : pred->ext.sft; auto _pred_ar = (pred == nullptr) ? nullptr : frame_data(pred); read_fn(sft, clt, _ar, pred_sft, _pred_ar); } template <class Is_splittable_fn> stack_type update_marks_bkw(stack_type s, const Is_splittable_fn& is_splittable_fn) { stack_type t = s; if (t.mtl == nullptr) { return t; } bool is_async_mtl = (t.mtl->ext.clt == Call_link_async); bool is_splittable_mtl = is_splittable_fn(frame_data(t.mtl)); bool is_loop_child_mtl = (t.mtl->ext.llt == Loop_link_child); if (is_async_mtl || is_splittable_mtl || is_loop_child_mtl) { return t; } frame_header_type* pred = t.mtl->ext.pred; t.mtl = pred; if (pred != nullptr) { pred->ext.succ = nullptr; } if (s.mtl == s.mhd) { t.mhd = pred; } return t; } template <class Is_splittable_fn> stack_type update_marks_fwd(stack_type s, const Is_splittable_fn& is_splittable_fn) { stack_type t = s; if (t.mhd == nullptr) { return t; } bool is_async_mhd = (t.mhd->ext.clt == Call_link_async); bool is_splittable_mhd = is_splittable_fn(frame_data(t.mhd)); if (is_async_mhd || is_splittable_mhd) { return t; } frame_header_type* succ = t.mhd->ext.succ; t.mhd = succ; if (succ != nullptr) { succ->ext.pred = nullptr; } if (s.mtl == s.mhd) { t.mtl = succ; } if (t.mhd != nullptr) { t.mhd->ext.llt = Loop_link_none; } return t; } template <class Is_splittable_fn> stack_type update_marks(stack_type s, const Is_splittable_fn& is_splittable_fn) { return update_marks_fwd(update_marks_bkw(s, is_splittable_fn), is_splittable_fn); } using parent_link_type = enum { Parent_link_async, Parent_link_sync }; template <int frame_szb, class Initialize_fn, class Is_splittable_fn> stack_type push_back(stack_type s, parent_link_type ty, const Initialize_fn& initialize_fn, const Is_splittable_fn& is_splittable_fn) { stack_type t = s; auto b = sizeof(frame_header_type) + frame_szb; assert(b + sizeof(chunk_header_type) <= K); t.fp = s.sp; t.sp = (frame_header_type*)((char*)t.fp + b); if (t.sp >= t.lp) { chunk_type* c = create_chunk(s.sp, s.lp); t.fp = (frame_header_type*)chunk_data(c); t.sp = (frame_header_type*)((char*)t.fp + b); t.lp = (frame_header_type*)((char*)c + K); } initialize_fn(frame_data(t.fp)); frame_header_ext_type ext; bool is_async_tfp = (ty == Parent_link_async); bool is_splittable_tfp = is_splittable_fn(frame_data(t.fp)); frame_header_type* pred = s.fp; bool is_loop_child_tfp = ((pred != nullptr) && is_splittable_fn(frame_data(pred))); if (is_async_tfp || is_splittable_tfp || is_loop_child_tfp) { ext.pred = s.mtl; if (s.mtl != nullptr) { s.mtl->ext.succ = t.fp; } t.mtl = t.fp; if (t.mhd == nullptr) { t.mhd = t.mtl; } } else { ext.pred = nullptr; } ext.sft = Shared_frame_direct; ext.clt = (is_async_tfp ? Call_link_async : Call_link_sync); ext.llt = (is_loop_child_tfp ? Loop_link_child : Loop_link_none); ext.succ = nullptr; t.fp->pred = pred; t.fp->ext = ext; return t; } template <class Is_splittable_fn, class Destruct_fn> stack_type pop_back(stack_type s, const Is_splittable_fn& is_splittable_fn, const Destruct_fn& destruct_fn) { stack_type t = s; destruct_fn(frame_data(s.fp), s.fp->ext.sft); bool is_splittable_sfp = is_splittable_fn(frame_data(s.fp)); bool is_async_sfp = (s.fp->ext.clt == Call_link_async); bool is_loop_child_sfp = (s.fp->ext.llt == Loop_link_child); if (is_async_sfp || is_splittable_sfp || is_loop_child_sfp) { frame_header_type* pred = s.fp->ext.pred; if (pred == nullptr) { t.mhd = nullptr; } else { pred->ext.succ = nullptr; } t.mtl = pred; } t.fp = s.fp->pred; chunk_type* cfp = chunk_of(s.fp); if (chunk_of(t.fp) == cfp) { t.sp = s.fp; t.lp = s.lp; } else { t.sp = cfp->hdr.sp; t.lp = cfp->hdr.lp; decr_refcount(cfp); } return update_marks_bkw(t, is_splittable_fn); } template <class Is_splittable_fn> std::pair<stack_type, stack_type> fork_mark(stack_type s, const Is_splittable_fn& is_splittable_fn) { stack_type s1 = s; stack_type s2 = create_stack(); if (empty_mark(s)) { return std::make_pair(s1, s2); } frame_header_type* pf1, * pf2; if (s.mhd->pred == nullptr) { pf2 = s.mhd->ext.succ; if (pf2 == nullptr) { return std::make_pair(s1, s2); } else { s.mhd->ext.pred = nullptr; s1.mhd = s.mhd; } } else { pf2 = s.mhd; s1.mhd = nullptr; } pf1 = pf2->pred; s1.fp = pf1; chunk_type* cf1 = chunk_of(pf1); if (cf1 == chunk_of(pf2)) { incr_refcount(cf1); } if (chunk_of(s.sp) == cf1) { s1.sp = pf2; } else { s1.sp = nullptr; } s1.lp = s1.sp; s1.mtl = s1.mhd; s2 = s; s2.mhd = pf2; pf2->pred = nullptr; pf2->ext.pred = nullptr; s1 = update_marks_bkw(s1, is_splittable_fn); s2 = update_marks_fwd(s2, is_splittable_fn); return std::make_pair(s1, s2); } template <class Is_splittable_fn> std::pair<stack_type, stack_type> split_mark(stack_type s, const Is_splittable_fn& is_splittable_fn) { stack_type s1 = s; stack_type s2 = create_stack(); frame_header_type* pf = s.mhd; if (pf == nullptr) { return std::make_pair(s1, s2); } frame_header_type* pg = pf->ext.succ; if (pg == nullptr) { return std::make_pair(s1, s2); } assert(pg->pred == pf); pf->ext.succ = nullptr; pg->ext.pred = nullptr; pg->pred = nullptr; s1.fp = pf; s1.sp = nullptr; s1.lp = nullptr; s1.mtl = pf; pf->ext.llt = Loop_link_none; s2 = s; s2.mhd = pg; if (s.mhd == s.mtl) { s2.mtl = s2.mhd; } s1 = update_marks_bkw(s1, is_splittable_fn); s2 = update_marks_fwd(s2, is_splittable_fn); chunk_type* cpf = chunk_of(pf); if (cpf == chunk_of(pg)) { incr_refcount(cpf); } return std::make_pair(s1, s2); } template <int frame_szb, class Initialize_fn, class Is_splittable_fn> stack_type create_stack(parent_link_type ty, const Initialize_fn& initialize_fn, const Is_splittable_fn& is_splittable_fn) { stack_type s = create_stack(); s = push_back<frame_szb>(s, ty, initialize_fn, is_splittable_fn); s.fp->ext.sft = Shared_frame_indirect; return s; } /* Stack */ /*------------------------------*/ } // end namespace } // end namespace #endif /*! _CACTUS_STACK_PLUS_H_ */ <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef COIN_DB_ENV_HPP #define COIN_DB_ENV_HPP #include <db_cxx.h> #include <cstdint> #include <map> #include <memory> #include <mutex> #include <string> #include <vector> #include <coin/filesystem.hpp> namespace coin { /** * Implements a berkley database DbEnv object wrapper. */ class db_env { public: /** * The default cache size. */ enum { default_cache_size = 128 }; /** * Constructor */ db_env(); /** * Destructor */ ~db_env(); /** * Opens the database environment. * @param data_path The data path. */ bool open(const std::string & data_path = filesystem::data_path() /** * Closes the DbEnv object. */ void close_DbEnv(); /** * Closes a Db object. * @param file_name The file name. */ void close_Db(const std::string & file_name); /** * Removes a Db object. * @param file_name The file name. */ bool remove_Db(const std::string & file_name); /** * Verifies that the database file is OK. * @param file_name The file name. */ bool verify(const std::string & file_name); /** * Attempts to salvage data from a file. * @param file_name The file name. * @param aggressive If true the DB_AGGRESSIVE will be used. * @param result The result. */ bool salvage( const std::string & file_name, const bool & aggressive, std::vector< std::pair< std::vector<std::uint8_t>, std::vector<std::uint8_t> > > & result ); /** * checkpoint_lsn * @param file_name The file name. */ void checkpoint_lsn(const std::string & file_name); /** * Flushes. */ void flush(); /** * The DbEnv. */ DbEnv & get_DbEnv(); /** * The file use counts. */ std::map<std::string, std::uint32_t> & file_use_counts(); /** * The Db objects. */ std::map<std::string, Db *> & Dbs(); /** * The std::mutex. */ std::recursive_mutex & mutex_DbEnv(); /** * txn_begin * @param flags The flags. */ DbTxn * txn_begin(int flags = DB_TXN_WRITE_NOSYNC); private: /** * The DbEnv. */ DbEnv m_DbEnv; /** * The file use counts. */ std::map<std::string, std::uint32_t> m_file_use_counts; /** * The Db objects. */ std::map<std::string, Db *> m_Dbs; /** * The m_DbEnv std::recursive_mutex. */ std::recursive_mutex m_mutex_DbEnv; protected: /** * The state. */ enum { state_opened, state_closed, } state_; /** * m_file_use_counts std::recursive_mutex. */ std::recursive_mutex mutex_file_use_counts_; /** * m_Dbs std::recursive_mutex. */ std::recursive_mutex mutex_m_Dbs_; }; } // namespace coin #endif // COIN_DB_ENV_HPP <commit_msg>0.4.5 partial merge<commit_after>/* * Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef COIN_DB_ENV_HPP #define COIN_DB_ENV_HPP #include <db_cxx.h> #include <cstdint> #include <map> #include <memory> #include <mutex> #include <string> #include <vector> #include <coin/filesystem.hpp> namespace coin { /** * Implements a berkley database DbEnv object wrapper. */ class db_env { public: /** * The default cache size. */ enum { default_cache_size = 128 }; /** * Constructor */ db_env(); /** * Destructor */ ~db_env(); /** * Opens the database environment. * @param data_path The data path. */ bool open(const std::string & data_path = filesystem::data_path()); /** * Closes the DbEnv object. */ void close_DbEnv(); /** * Closes a Db object. * @param file_name The file name. */ void close_Db(const std::string & file_name); /** * Removes a Db object. * @param file_name The file name. */ bool remove_Db(const std::string & file_name); /** * Verifies that the database file is OK. * @param file_name The file name. */ bool verify(const std::string & file_name); /** * Attempts to salvage data from a file. * @param file_name The file name. * @param aggressive If true the DB_AGGRESSIVE will be used. * @param result The result. */ bool salvage( const std::string & file_name, const bool & aggressive, std::vector< std::pair< std::vector<std::uint8_t>, std::vector<std::uint8_t> > > & result ); /** * checkpoint_lsn * @param file_name The file name. */ void checkpoint_lsn(const std::string & file_name); /** * Flushes. */ void flush(); /** * The DbEnv. */ DbEnv & get_DbEnv(); /** * The file use counts. */ std::map<std::string, std::uint32_t> & file_use_counts(); /** * The Db objects. */ std::map<std::string, Db *> & Dbs(); /** * The std::mutex. */ std::recursive_mutex & mutex_DbEnv(); /** * txn_begin * @param flags The flags. */ DbTxn * txn_begin(int flags = DB_TXN_WRITE_NOSYNC); private: /** * The DbEnv. */ DbEnv m_DbEnv; /** * The file use counts. */ std::map<std::string, std::uint32_t> m_file_use_counts; /** * The Db objects. */ std::map<std::string, Db *> m_Dbs; /** * The m_DbEnv std::recursive_mutex. */ std::recursive_mutex m_mutex_DbEnv; protected: /** * The state. */ enum { state_opened, state_closed, } state_; /** * m_file_use_counts std::recursive_mutex. */ std::recursive_mutex mutex_file_use_counts_; /** * m_Dbs std::recursive_mutex. */ std::recursive_mutex mutex_m_Dbs_; }; } // namespace coin #endif // COIN_DB_ENV_HPP <|endoftext|>
<commit_before>#include "generations.h" //TODO: time-based killing Generations::Generations(string input, string output){ this->population_id = 0; this->begin_exec = clock(); this->output = output; Instance instance; Chromosome chromosome; instance.read_instance(input); for(unsigned int i = 0; i < _POPULATION_SIZE; i++){ vector<Task> tasks(instance.get_tasks()); random_shuffle(tasks.begin(), tasks.end()); Order order; order.init(tasks, instance.get_maitenances()); chromosome.order = order; chromosome.rank = 0; this->population.push_back(chromosome); } sort_population(); this->previous_population = population; this->maintanance_v = instance.get_maitenances(); this->first_order = population[0].order.get_exectime(); } int Generations::average(){ int av = 0; for (unsigned i = 0; i < population.size(); i++ ){ av += previous_population[i].order.get_exectime(); } return av / _POPULATION_SIZE; } void Generations::selection(){ //unsigned int av; double r; //if (population_id == 0) av = 0; //else av = average(); for (unsigned i = 0; i < population.size(); i++ ){ r = population[i].order.get_exectime(); population[i].rank = r; } } void Generations::rebuild(vector<Task>& tasks, int resection){ vector<int> missing_tasks; vector<int> duplicates; vector<Task> all_tasks(this->previous_population[0].order.get_tasks()); for (int i = 0; i < resection; i++){ for (unsigned j = resection; j < tasks.size(); j++){ if(tasks[i].get_id() == tasks[j].get_id()) { duplicates.push_back(j); break; } } } for (unsigned int i = 0; i < all_tasks.size(); i++){ if(find(tasks.begin(), tasks.end(), all_tasks[i]) == tasks.end() && find(missing_tasks.begin(), missing_tasks.end(), i) == missing_tasks.end()) missing_tasks.push_back(i); } for (unsigned int i = 0; i < duplicates.size(); i++) tasks[duplicates[i]] = all_tasks[missing_tasks[i]]; time_exceeded(); } void Generations::remove_weak(){ int remove_count = floor(_POPULATION_SIZE * _REMOVE_PCT/100.0); random_device rd; mt19937_64 gen(rd()); uniform_int_distribution<int> dist(0, 99); vector<int> to_remove; sort_population(); for(int i = _POPULATION_SIZE - 1; i >= 0; i--){ if(dist(gen) >= _REMOVE_FAIL_PCT){ population.erase(population.begin() + i); remove_count--; } if (remove_count == 0) break; } time_exceeded(); this->previous_population = this->population; } bool Generations::crossing_over(int itterator){ random_device rd; mt19937_64 gen(rd()); uniform_int_distribution<int> random_resection(_MIN_RESECTION_PCT, _MAX_RESECTION_PCT); uniform_int_distribution<int> random_chromosome(0, floor(_POPULATION_SIZE * _REMOVE_PCT/100.0) - 1); int chromosome1_num = random_chromosome(gen); int chromosome2_num = random_chromosome(gen); while(chromosome1_num == chromosome2_num) chromosome2_num = random_chromosome(gen); vector<Task> tmp(previous_population[chromosome1_num].order.get_tasks()); int resection = floor(tmp.size() * random_resection(gen)/100.0); if (resection <= 0) return false; vector<Task> tasks(&tmp[0], &tmp[resection]); tmp = previous_population[chromosome2_num].order.get_tasks(); vector<Task> tasks2(&tmp[resection], &tmp[tmp.size()]); tasks.insert(tasks.end(), tasks2.begin(), tasks2.end()); this->rebuild(tasks, resection); Order order; order.init(tasks, this->maintanance_v); Chromosome new_chromosome; new_chromosome.order = order; new_chromosome.rank = 0; this->population.push_back(new_chromosome); time_exceeded(); return true; } void Generations::mutate(int chromosome_id){ random_device rd; mt19937_64 gen(rd()); vector<Task> tasks = population[chromosome_id].order.get_tasks(); uniform_int_distribution<int> random_task_id(0, tasks.size() - 1); int task_id[2]; task_id[0] = random_task_id(gen); task_id[1] = random_task_id(gen); while(task_id[0] == task_id[1]) task_id[1] = random_task_id(gen); iter_swap(tasks.begin() + task_id[0], tasks.begin() + task_id[1]); Order order; order.init(tasks, this->maintanance_v); Chromosome new_chromosome; new_chromosome.order = order; new_chromosome.rank = 0; population[chromosome_id] = new_chromosome; time_exceeded(); } inline bool Less_than_rank::operator() (const Chromosome& chromosome1, const Chromosome& chromosome2){ return (chromosome1.rank < chromosome2.rank); } void Generations::sort_population(){ sort(population.begin(), population.end(), Less_than_rank()); } void Generations::next_generation(){ random_device rd; mt19937_64 gen(rd()); uniform_int_distribution<int> random_mutation(0, 100); selection(); remove_weak(); this->population.clear(); for (unsigned int i = 0; i < _POPULATION_SIZE; i++){ // std::cout<<"du\n"; crossing_over(i); //std::cout<<"da\n"; if(random_mutation(gen) < _MUTATION_CHANCE_PCT) { mutate(i); } } this->population_id++; time_exceeded(); } void Generations::dump_generation(string filename){ ofstream dump; unsigned int m_iter = 0; int st = 0, tf = 0, m_sum = 0, idle = 0, idle_1_t = 0, idle_2_t = 0; //start time, to finish, maitanance iterator char d = ','; // delimiter dump.open(filename.c_str()); dump << "***" /*<< id*/ << "****" << endl; //rank sort_population(); dump << population[0].order.get_exectime() << d << first_order << endl; dump << "M1:"; vector <Task> t = population[0].order.get_tasks(); /*for (unsigned int i = 0; i < maintanance_v.size(); i++){ m_sum += maintanance_v[i].get_duration(); std::cout<< i << " " << maintanance_v[i].get_duration() << '\n'; }*/ st = 0; /* std::cout<<"************************\n"; for (unsigned int i = 0; i < t.size(); i++) { std::cout<< t[i].get_start_t(1) << " " << t[i].get_op_t(1) <<endl; }*/ std::cout<< "id" << "\t" << "start" << "\t" << "op_time" << "\t" << "end_time" << "\t" << "punished"<< endl; for (unsigned int i = 0; i < t.size(); i++) { int time; if (t[i].is_punished()==true){ time = t[i].get_punished_op_t(); } else{ time = t[i].get_op_t(1); } std::cout<< t[i].get_id() << "\t" << t[i].get_start_t(1) << "\t" << time << "\t" << t[i].get_start_t(1) + time << "\t\t" << t[i].is_punished() << endl; } std::cout<< "************\n"; for (unsigned int i = 0; i < maintanance_v.size(); i++){ m_sum += maintanance_v[i].get_duration(); std::cout<< i << "\t" << maintanance_v[i].get_start_t() << "\t" << maintanance_v[i].get_duration() << '\n'; } for (unsigned int i = 0; i < t.size(); i++){ if (m_iter < maintanance_v.size()){ if (t[i].is_punished()==false){ if (maintanance_v[m_iter].get_start_t() > t[i].get_start_t(1)){ if (st < t[i].get_start_t(1)){ dump << "idle1_" << idle << d << st << d << t[i].get_start_t(1) - st << d ; idle_1_t += t[i].get_start_t(1) - st; idle++; } dump << "op1_k" << t[i].get_id() << d << t[i].get_start_t(1) << d << t[i].get_op_t(1) << d; st = t[i].get_start_t(1) + t[i].get_op_t(1); }else{ if (st < maintanance_v[m_iter].get_start_t() ){ dump << "idle1_" << idle << d << st << d << maintanance_v[m_iter].get_start_t() - st << d; idle_1_t += maintanance_v[m_iter].get_start_t() - st; idle++; } dump << "maint1_" << m_iter <<d << maintanance_v[m_iter].get_start_t() << d << maintanance_v[m_iter].get_duration() << d; st = maintanance_v[m_iter].get_start_t() + maintanance_v[m_iter].get_duration(); m_iter++; if (st < t[i].get_start_t(1)){ dump << "idle1_" << idle << d << st << d << t[i].get_start_t(1) - st << d; idle_1_t += t[i].get_start_t(1) - st; idle ++; } dump << "op1_o" << t[i].get_id() << d << t[i].get_start_t(1) << d << t[i].get_op_t(1)<<d; st = t[i].get_start_t(1) + t[i].get_op_t(1); } }else{ // punished if (st < t[i].get_start_t(1)){ dump << "idle1_" << idle << d << st << d << t[i].get_start_t(1) - st << d; idle_1_t += t[i].get_start_t(1) - st; idle++; } tf = t[i].get_punished_op_t() - (maintanance_v[m_iter].get_start_t() - t[i].get_start_t(1)); dump << "op1_w" << t[i].get_id() << d << t[i].get_start_t(1) << d << maintanance_v[m_iter].get_start_t() - t[i].get_start_t(1) << d; dump << "maint1_" << m_iter << d << maintanance_v[m_iter].get_start_t() << d << maintanance_v[m_iter].get_duration() << d; dump << "op1_g" << t[i].get_id() << d << maintanance_v[m_iter].get_start_t() + maintanance_v[m_iter].get_duration() << d << tf << d; st = maintanance_v[m_iter].get_start_t() + maintanance_v[m_iter].get_duration() + tf; m_iter++; } }else{ if(st < t[i].get_start_t(1)){ dump << "idle1_" << idle << d << st << d << t[i].get_start_t(1) - st << d; idle++; idle_1_t += t[i].get_start_t(1) - st; } dump << "op1_" << t[i].get_id() << d << t[i].get_start_t(1) << d << t[i].get_op_t(1) << d; st = t[i].get_start_t(1) + t[i].get_op_t(1); } } st = 0; idle = 0; dump << endl; dump << "M2:"; t = population[0].order.get_tasks_2(); for( unsigned int i = 0; i< t.size(); i++){ if(st < t[i].get_start_t(2)){ dump << "idle2_" << idle << d << st << d << t[i].get_start_t(2) - st << d; idle++; idle_2_t += t[i].get_start_t(2) - st; } dump << "op2_" << t[i].get_id() << d << t[i].get_start_t(2) << d << t[i].get_op_t(2) << d; st = t[i].get_start_t(2) + t[i].get_op_t(2); } dump << endl; dump << m_sum <<'\n'; dump << 0 << '\n'; dump << idle_1_t << '\n'; dump << idle_2_t << '\n'; dump << "***EOF***"; dump.close(); } bool Generations::time_exceeded(){ clock_t end = clock(); double elapsed_secs = double(end - this->begin_exec) / CLOCKS_PER_SEC;; if(elapsed_secs > _EXEC_TIME_SECS){ dump_generation(this->output); exit(0); return true; } return false; } <commit_msg>dump fix<commit_after>#include "generations.h" //TODO: time-based killing Generations::Generations(string input, string output){ this->population_id = 0; this->begin_exec = clock(); this->output = output; Instance instance; Chromosome chromosome; instance.read_instance(input); for(unsigned int i = 0; i < _POPULATION_SIZE; i++){ vector<Task> tasks(instance.get_tasks()); random_shuffle(tasks.begin(), tasks.end()); Order order; order.init(tasks, instance.get_maitenances()); chromosome.order = order; chromosome.rank = 0; this->population.push_back(chromosome); } sort_population(); this->previous_population = population; this->maintanance_v = instance.get_maitenances(); this->first_order = population[0].order.get_exectime(); } int Generations::average(){ int av = 0; for (unsigned i = 0; i < population.size(); i++ ){ av += previous_population[i].order.get_exectime(); } return av / _POPULATION_SIZE; } void Generations::selection(){ //unsigned int av; double r; //if (population_id == 0) av = 0; //else av = average(); for (unsigned i = 0; i < population.size(); i++ ){ r = population[i].order.get_exectime(); population[i].rank = r; } } void Generations::rebuild(vector<Task>& tasks, int resection){ vector<int> missing_tasks; vector<int> duplicates; vector<Task> all_tasks(this->previous_population[0].order.get_tasks()); for (int i = 0; i < resection; i++){ for (unsigned j = resection; j < tasks.size(); j++){ if(tasks[i].get_id() == tasks[j].get_id()) { duplicates.push_back(j); break; } } } for (unsigned int i = 0; i < all_tasks.size(); i++){ if(find(tasks.begin(), tasks.end(), all_tasks[i]) == tasks.end() && find(missing_tasks.begin(), missing_tasks.end(), i) == missing_tasks.end()) missing_tasks.push_back(i); } for (unsigned int i = 0; i < duplicates.size(); i++) tasks[duplicates[i]] = all_tasks[missing_tasks[i]]; time_exceeded(); } void Generations::remove_weak(){ int remove_count = floor(_POPULATION_SIZE * _REMOVE_PCT/100.0); random_device rd; mt19937_64 gen(rd()); uniform_int_distribution<int> dist(0, 99); vector<int> to_remove; sort_population(); for(int i = _POPULATION_SIZE - 1; i >= 0; i--){ if(dist(gen) >= _REMOVE_FAIL_PCT){ population.erase(population.begin() + i); remove_count--; } if (remove_count == 0) break; } time_exceeded(); this->previous_population = this->population; } bool Generations::crossing_over(int itterator){ random_device rd; mt19937_64 gen(rd()); uniform_int_distribution<int> random_resection(_MIN_RESECTION_PCT, _MAX_RESECTION_PCT); uniform_int_distribution<int> random_chromosome(0, floor(_POPULATION_SIZE * _REMOVE_PCT/100.0) - 1); int chromosome1_num = random_chromosome(gen); int chromosome2_num = random_chromosome(gen); while(chromosome1_num == chromosome2_num) chromosome2_num = random_chromosome(gen); vector<Task> tmp(previous_population[chromosome1_num].order.get_tasks()); int resection = floor(tmp.size() * random_resection(gen)/100.0); if (resection <= 0) return false; vector<Task> tasks(&tmp[0], &tmp[resection]); tmp = previous_population[chromosome2_num].order.get_tasks(); vector<Task> tasks2(&tmp[resection], &tmp[tmp.size()]); tasks.insert(tasks.end(), tasks2.begin(), tasks2.end()); this->rebuild(tasks, resection); Order order; order.init(tasks, this->maintanance_v); Chromosome new_chromosome; new_chromosome.order = order; new_chromosome.rank = 0; this->population.push_back(new_chromosome); time_exceeded(); return true; } void Generations::mutate(int chromosome_id){ random_device rd; mt19937_64 gen(rd()); vector<Task> tasks = population[chromosome_id].order.get_tasks(); uniform_int_distribution<int> random_task_id(0, tasks.size() - 1); int task_id[2]; task_id[0] = random_task_id(gen); task_id[1] = random_task_id(gen); while(task_id[0] == task_id[1]) task_id[1] = random_task_id(gen); iter_swap(tasks.begin() + task_id[0], tasks.begin() + task_id[1]); Order order; order.init(tasks, this->maintanance_v); Chromosome new_chromosome; new_chromosome.order = order; new_chromosome.rank = 0; population[chromosome_id] = new_chromosome; time_exceeded(); } inline bool Less_than_rank::operator() (const Chromosome& chromosome1, const Chromosome& chromosome2){ return (chromosome1.rank < chromosome2.rank); } void Generations::sort_population(){ sort(population.begin(), population.end(), Less_than_rank()); } void Generations::next_generation(){ random_device rd; mt19937_64 gen(rd()); uniform_int_distribution<int> random_mutation(0, 100); selection(); remove_weak(); this->population.clear(); for (unsigned int i = 0; i < _POPULATION_SIZE; i++){ // std::cout<<"du\n"; crossing_over(i); //std::cout<<"da\n"; if(random_mutation(gen) < _MUTATION_CHANCE_PCT) { mutate(i); } } this->population_id++; time_exceeded(); } void Generations::dump_generation(string filename){ ofstream dump; unsigned int m_iter = 0; int st = 0, tf = 0, m_sum = 0, idle = 0, idle_1_t = 0, idle_2_t = 0; //start time, to finish, maitanance iterator char d = ','; // delimiter dump.open(filename.c_str()); dump << "***" /*<< id*/ << "****" << endl; //rank sort_population(); dump << population[0].order.get_exectime() << d << first_order << endl; dump << "M1:"; vector <Task> t = population[0].order.get_tasks(); /*for (unsigned int i = 0; i < maintanance_v.size(); i++){ m_sum += maintanance_v[i].get_duration(); std::cout<< i << " " << maintanance_v[i].get_duration() << '\n'; }*/ st = 0; /* std::cout<<"************************\n"; for (unsigned int i = 0; i < t.size(); i++) { std::cout<< t[i].get_start_t(1) << " " << t[i].get_op_t(1) <<endl; }*/ std::cout<< "id" << "\t" << "start" << "\t" << "op_time" << "\t" << "end_time" << "\t" << "punished"<< endl; for (unsigned int i = 0; i < t.size(); i++) { int time; if (t[i].is_punished()==true){ time = t[i].get_punished_op_t(); } else{ time = t[i].get_op_t(1); } std::cout<< t[i].get_id() << "\t" << t[i].get_start_t(1) << "\t" << time << "\t" << t[i].get_start_t(1) + time << "\t\t" << t[i].is_punished() << endl; } std::cout<< "************\n"; for (unsigned int i = 0; i < maintanance_v.size(); i++){ m_sum += maintanance_v[i].get_duration(); std::cout<< i << "\t" << maintanance_v[i].get_start_t() << "\t" << maintanance_v[i].get_duration() << '\n'; } for (unsigned int i = 0; i < t.size(); i++){ if (m_iter < maintanance_v.size()){ if (t[i].is_punished()==false){ if (maintanance_v[m_iter].get_start_t() > t[i].get_start_t(1)){ if (st < t[i].get_start_t(1)){ dump << "idle1_" << idle << d << st << d << t[i].get_start_t(1) - st << d ; idle_1_t += t[i].get_start_t(1) - st; idle++; } dump << "op1_k" << t[i].get_id() << d << t[i].get_start_t(1) << d << t[i].get_op_t(1) << d; st = t[i].get_start_t(1) + t[i].get_op_t(1); }else{ if (st < maintanance_v[m_iter].get_start_t() ){ dump << "idle1_" << idle << d << st << d << maintanance_v[m_iter].get_start_t() - st << d; idle_1_t += maintanance_v[m_iter].get_start_t() - st; idle++; } dump << "maint1_" << m_iter <<d << maintanance_v[m_iter].get_start_t() << d << maintanance_v[m_iter].get_duration() << d; st = maintanance_v[m_iter].get_start_t() + maintanance_v[m_iter].get_duration(); m_iter++; if (st < t[i].get_start_t(1)){ dump << "idle1_" << idle << d << st << d << t[i].get_start_t(1) - st << d; idle_1_t += t[i].get_start_t(1) - st; idle ++; } dump << "op1_o" << t[i].get_id() << d << t[i].get_start_t(1) << d << t[i].get_op_t(1)<<d; st = t[i].get_start_t(1) + t[i].get_op_t(1); } }else{ // punished if (maintanance_v[m_iter].get_start_t() < t[i].get_start_t(1)){ if (st < maintanance_v[m_iter].get_start_t() ){ dump << "idle1_" << idle << d << st << d << maintanance_v[m_iter].get_start_t() - st << d; idle_1_t += maintanance_v[m_iter].get_start_t() - st; idle++; } dump << "maint1_" << m_iter <<d << maintanance_v[m_iter].get_start_t() << d << maintanance_v[m_iter].get_duration() << d; st = maintanance_v[m_iter].get_start_t() + maintanance_v[m_iter].get_duration(); m_iter++; } if (st < t[i].get_start_t(1)){ dump << "idle1_" << idle << d << st << d << t[i].get_start_t(1) - st << d; idle_1_t += t[i].get_start_t(1) - st; idle++; } tf = t[i].get_punished_op_t() - (maintanance_v[m_iter].get_start_t() - t[i].get_start_t(1)); dump << "op1_w" << t[i].get_id() << d << t[i].get_start_t(1) << d << maintanance_v[m_iter].get_start_t() - t[i].get_start_t(1) << d; dump << "maint1_" << m_iter << d << maintanance_v[m_iter].get_start_t() << d << maintanance_v[m_iter].get_duration() << d; dump << "op1_g" << t[i].get_id() << d << maintanance_v[m_iter].get_start_t() + maintanance_v[m_iter].get_duration() << d << tf << d; st = maintanance_v[m_iter].get_start_t() + maintanance_v[m_iter].get_duration() + tf; m_iter++; } }else{ if(st < t[i].get_start_t(1)){ dump << "idle1_" << idle << d << st << d << t[i].get_start_t(1) - st << d; idle++; idle_1_t += t[i].get_start_t(1) - st; } dump << "op1_" << t[i].get_id() << d << t[i].get_start_t(1) << d << t[i].get_op_t(1) << d; st = t[i].get_start_t(1) + t[i].get_op_t(1); } } st = 0; idle = 0; dump << endl; dump << "M2:"; t = population[0].order.get_tasks_2(); for( unsigned int i = 0; i< t.size(); i++){ if(st < t[i].get_start_t(2)){ dump << "idle2_" << idle << d << st << d << t[i].get_start_t(2) - st << d; idle++; idle_2_t += t[i].get_start_t(2) - st; } dump << "op2_" << t[i].get_id() << d << t[i].get_start_t(2) << d << t[i].get_op_t(2) << d; st = t[i].get_start_t(2) + t[i].get_op_t(2); } dump << endl; dump << m_sum <<'\n'; dump << 0 << '\n'; dump << idle_1_t << '\n'; dump << idle_2_t << '\n'; dump << "***EOF***"; dump.close(); } bool Generations::time_exceeded(){ clock_t end = clock(); double elapsed_secs = double(end - this->begin_exec) / CLOCKS_PER_SEC;; if(elapsed_secs > _EXEC_TIME_SECS){ dump_generation(this->output); exit(0); return true; } return false; } <|endoftext|>
<commit_before>/* * * Author: Jeffrey Leung * Last edited: 2016-02-18 * * This C++ header file contains the function prototypes for the * exception logger Exceptional. * */ #pragma once #include <fstream> #include <iostream> #include <exception> #include <stdexcept> #include <string> namespace exceptional { class Logger { public: // Constructor Logger(); // Destructor ~Logger(); private: const std::string log_filename_ = "log.txt"; std::ofstream log_stream_; // This method logs a thrown value as a warning. template <class T> void LogWarning( const T& except ); // This method logs a thrown value as an error. template <class T> void LogError( const T& except ); }; } // End of namespace exceptional <commit_msg>Changing LogWarning and LogError to public methods.<commit_after>/* * * Author: Jeffrey Leung * Last edited: 2016-02-18 * * This C++ header file contains the function prototypes for the * exception logger Exceptional. * */ #pragma once #include <fstream> #include <iostream> #include <exception> #include <stdexcept> #include <string> namespace exceptional { class Logger { public: // Constructor Logger(); // Destructor ~Logger(); // This public method logs a thrown value as a warning. template <class T> void LogWarning( const T& except ); // This public method logs a thrown value as an error. template <class T> void LogError( const T& except ); private: const std::string log_filename_ = "log.txt"; std::ofstream log_stream_; }; } // End of namespace exceptional <|endoftext|>
<commit_before>// // inpal_prime.hpp // InversePalindrome // // Created by Bryan Triana on 7/13/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #ifndef inpal_prime_hpp #define inpal_prime_hpp #include <vector> #include <string> namespace inpal { class prime { public: static std::size_t max_prime(std::size_t range); static std::size_t prime_count(std::size_t range); static double prime_density(double range); static bool prime_test(std::size_t num); static bool twin_test(std::size_t num); static bool cousin_test(std::size_t num); static bool sexy_test(std::size_t num); static std::size_t max_palprime(std::size_t range); static std::size_t max_factor(std::size_t num); static std::size_t count_factors(std::size_t num); private: static std::vector<bool> prime_sieve(std::size_t range); static std::vector<std::size_t> factorizer(std::size_t num); static bool pal_test(std::size_t num); }; } #endif /* inpal_prime_hpp */ <commit_msg>added general purpose functions<commit_after>// // inpal_prime.hpp // InversePalindrome // // Created by Bryan Triana on 7/13/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #ifndef inpal_prime_hpp #define inpal_prime_hpp #include <vector> #include <string> namespace inpal { class prime { public: //general purpose functions static std::vector<std::size_t> factor_list(std::size_t num); static std::vector<std::size_t> prime_list(std::size_t num); //special purpose functions static std::size_t max_prime(std::size_t range); static std::size_t prime_count(std::size_t range); static double prime_density(double range); static bool prime_test(std::size_t num); static bool twin_test(std::size_t num); static bool cousin_test(std::size_t num); static bool sexy_test(std::size_t num); static std::size_t max_palprime(std::size_t range); static std::size_t max_factor(std::size_t num); static std::size_t factor_count(std::size_t num); private: //utility algorithms static std::vector<bool> prime_sieve(std::size_t range); static bool pal_test(std::size_t num); }; } #endif /* inpal_prime_hpp */ <|endoftext|>
<commit_before>#pragma once /** @file @brief pailler encryption @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <mcl/gmp_util.hpp> namespace mcl { namespace pailler { class PublicKey { size_t bitSize; mpz_class g; mpz_class n; mpz_class n2; public: PublicKey() : bitSize(0) {} void init(size_t _bitSize, const mpz_class& _n) { bitSize = _bitSize; n = _n; g = 1 + _n; n2 = _n * _n; } template<class RG> void enc(mpz_class& c, const mpz_class& m, RG& rg) const { if (bitSize == 0) throw cybozu::Exception("pailler:PublicKey:not init"); mpz_class r; mcl::gmp::getRand(r, bitSize, rg); mpz_class a, b; mcl::gmp::powMod(a, g, m, n2); mcl::gmp::powMod(b, r, n, n2); c = (a * b) % n2; } /* additive homomorphic encryption cz = cx + cy */ void add(mpz_class& cz, mpz_class& cx, mpz_class& cy) const { cz = (cx * cy) % n2; } }; class SecretKey { size_t bitSize; mpz_class n; mpz_class n2; mpz_class lambda; mpz_class invLambda; public: SecretKey() : bitSize(0) {} template<class RG> void init(size_t bitSize, RG& rg) { this->bitSize = bitSize; mpz_class p, q; mcl::gmp::getRandPrime(p, bitSize, rg); mcl::gmp::getRandPrime(q, bitSize, rg); lambda = (p - 1) * (q - 1); n = p * q; n2 = n * n; mcl::gmp::invMod(invLambda, lambda, n); } void getPublicKey(PublicKey& pub) const { pub.init(bitSize, n); } void dec(mpz_class& m, const mpz_class& c) const { mpz_class L; mcl::gmp::powMod(L, c, lambda, n2); L = ((L - 1) / n) % n; m = (L * invLambda) % n; } }; } } // mcl::pailler <commit_msg>primeSize is half of bitSize<commit_after>#pragma once /** @file @brief pailler encryption @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <mcl/gmp_util.hpp> namespace mcl { namespace pailler { class PublicKey { size_t primeBitSize; mpz_class g; mpz_class n; mpz_class n2; public: PublicKey() : primeBitSize(0) {} void init(size_t _primeBitSize, const mpz_class& _n) { primeBitSize = _primeBitSize; n = _n; g = 1 + _n; n2 = _n * _n; } template<class RG> void enc(mpz_class& c, const mpz_class& m, RG& rg) const { if (primeBitSize == 0) throw cybozu::Exception("pailler:PublicKey:not init"); mpz_class r; mcl::gmp::getRand(r, primeBitSize, rg); mpz_class a, b; mcl::gmp::powMod(a, g, m, n2); mcl::gmp::powMod(b, r, n, n2); c = (a * b) % n2; } /* additive homomorphic encryption cz = cx + cy */ void add(mpz_class& cz, mpz_class& cx, mpz_class& cy) const { cz = (cx * cy) % n2; } }; class SecretKey { size_t primeBitSize; mpz_class n; mpz_class n2; mpz_class lambda; mpz_class invLambda; public: SecretKey() : primeBitSize(0) {} /* the size of prime is half of bitSize */ template<class RG> void init(size_t bitSize, RG& rg) { primeBitSize = bitSize / 2; mpz_class p, q; mcl::gmp::getRandPrime(p, primeBitSize, rg); mcl::gmp::getRandPrime(q, primeBitSize, rg); lambda = (p - 1) * (q - 1); n = p * q; n2 = n * n; mcl::gmp::invMod(invLambda, lambda, n); } void getPublicKey(PublicKey& pub) const { pub.init(primeBitSize, n); } void dec(mpz_class& m, const mpz_class& c) const { mpz_class L; mcl::gmp::powMod(L, c, lambda, n2); L = ((L - 1) / n) % n; m = (L * invLambda) % n; } }; } } // mcl::pailler <|endoftext|>
<commit_before>/* * Copyright 2016 Ivan Ryabov * * 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. */ /******************************************************************************* * libSolace: atom * @file solace/atom.hpp ******************************************************************************/ #pragma once #ifndef SOLACE_ATOM_HPP #define SOLACE_ATOM_HPP #include "solace/types.hpp" #include "solace/stringView.hpp" #include "solace/result.hpp" //#include "solace/error.hpp" #include <type_traits> #include <climits> #include <cstdint> namespace Solace { /** * Atoms value type */ enum class AtomValue : std::uintmax_t { /// @cond PRIVATE _dirty_little_hack = 1337 /// @endcond }; namespace detail { template <typename T = std::uintmax_t> constexpr std::enable_if_t<std::is_integral<T>::value, T> wrap(char const* const str, std::size_t len = sizeof(T)) noexcept { constexpr auto N = sizeof(T); T n {}; std::size_t i{}; while (i < N && i < len && str[i]) { n = (n << CHAR_BIT) | str[i++]; } return (n << (N - i) * CHAR_BIT); } template <typename T> std::enable_if_t<std::is_integral<T>::value> unwrap(const T n, char *const buffer) noexcept { constexpr auto N = sizeof(T); constexpr auto lastbyte = static_cast<char>(~0); for (std::size_t i = 0UL; i < N; ++i) { buffer[i] = ((n >> (N - i - 1) * CHAR_BIT) & lastbyte); } buffer[N] = '\0'; } } // namespace detail /// Creates an atom value from a given short string literal. template <size_t Size> [[nodiscard]] AtomValue atom(char const (&str)[Size]) noexcept { // last character is the NULL terminator constexpr auto kMaxLiteralSize = sizeof(std::uintmax_t); static_assert(Size <= kMaxLiteralSize, "String literal too long"); return static_cast<AtomValue>(detail::wrap(str)); } inline void atomToString(AtomValue a, char *const buffer) noexcept { detail::unwrap<std::uintmax_t>(static_cast<std::uintmax_t>(a), buffer); } struct ParseError {}; Result<AtomValue, ParseError> tryParseAtom(StringView str) noexcept; } // End of namespace Solace #endif // SOLACE_ATOM_HPP <commit_msg>Zero string atom short circuit<commit_after>/* * Copyright 2016 Ivan Ryabov * * 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. */ /******************************************************************************* * libSolace: atom * @file solace/atom.hpp ******************************************************************************/ #pragma once #ifndef SOLACE_ATOM_HPP #define SOLACE_ATOM_HPP #include "solace/types.hpp" #include "solace/stringView.hpp" #include "solace/result.hpp" //#include "solace/error.hpp" #include <type_traits> #include <climits> #include <cstdint> namespace Solace { /** * Atoms value type */ enum class AtomValue : std::uintmax_t { /// @cond PRIVATE _dirty_little_hack = 1337 /// @endcond }; namespace detail { template <typename T = std::uintmax_t> constexpr std::enable_if_t<std::is_integral<T>::value, T> wrap(char const* const str, std::size_t len = sizeof(T)) noexcept { constexpr auto N = sizeof(T); T n {}; std::size_t i{}; while (i < N && i < len && str[i]) { n = (n << CHAR_BIT) | str[i++]; } return (i == 0) ? 0 : (n << (N - i) * CHAR_BIT); } template <typename T> std::enable_if_t<std::is_integral<T>::value> unwrap(const T n, char *const buffer) noexcept { constexpr auto N = sizeof(T); constexpr auto lastbyte = static_cast<char>(~0); for (std::size_t i = 0UL; i < N; ++i) { buffer[i] = ((n >> (N - i - 1) * CHAR_BIT) & lastbyte); } buffer[N] = '\0'; } } // namespace detail /// Creates an atom value from a given short string literal. template <size_t Size> [[nodiscard]] AtomValue atom(char const (&str)[Size]) noexcept { // last character is the NULL terminator constexpr auto kMaxLiteralSize = sizeof(std::uintmax_t); static_assert(Size <= kMaxLiteralSize, "String literal too long"); return static_cast<AtomValue>(detail::wrap(str)); } inline void atomToString(AtomValue a, char *const buffer) noexcept { detail::unwrap<std::uintmax_t>(static_cast<std::uintmax_t>(a), buffer); } struct ParseError {}; Result<AtomValue, ParseError> tryParseAtom(StringView str) noexcept; } // End of namespace Solace #endif // SOLACE_ATOM_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2012-2015 Christian Surlykke * * This file is part of qt-lightdm-greeter * It is distributed under the LGPL 2.1 or later license. * Please refer to the LICENSE file for a copy of the license. */ #include <QDebug> #include <QCompleter> #include <QAbstractListModel> #include <QModelIndex> #include <QFile> #include <QTextStream> #include <QStringList> #include <QPixmap> #include <QMessageBox> #include <QMenu> #include <QProcess> #include "loginform.h" #include "ui_loginform.h" #include "settings.h" const int NameRole = QLightDM::UsersModel::NameRole; const int KeyRole = QLightDM::SessionsModel::KeyRole; int rows(QAbstractItemModel& model) { return model.rowCount(QModelIndex()); } QString displayData(QAbstractItemModel& model, int row, int role) { QModelIndex modelIndex = model.index(row, 0); return model.data(modelIndex, role).toString(); } LoginForm::LoginForm(QWidget *parent) : QWidget(parent), ui(new Ui::LoginForm), m_Greeter(), power(this), usersModel(*this), sessionsModel() { if (!m_Greeter.connectSync()) { close(); } ui->setupUi(this); initialize(); } LoginForm::~LoginForm() { delete ui; } void LoginForm::setFocus(Qt::FocusReason reason) { if (ui->userCombo->currentIndex() == -1) { ui->userCombo->setFocus(reason); } else if (ui->userCombo->currentIndex() == ui->userCombo->count() - 1) { ui->otherUserInput->setFocus(reason); } else { ui->passwordInput->setFocus(reason); } } void LoginForm::initialize() { QPixmap icon(":/resources/rqt-2.png"); // This project came from Razor-qt ui->iconLabel->setPixmap(icon.scaled(ui->iconLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); ui->hostnameLabel->setText(m_Greeter.hostname()); ui->userCombo->setModel(&usersModel); ui->sessionCombo->setModel(&sessionsModel); ui->leaveButton->setMenu(new QMenu(this)); if (power.canShutdown()) { addLeaveEntry("system-shutdown", tr("Shutdown"), SLOT(shutdown())); } if (power.canRestart()) { addLeaveEntry("system-reboot", tr("Restart"), SLOT(restart())); } if (power.canHibernate()) { addLeaveEntry("system-suspend-hibernate", tr("Hibernate"), SLOT(hibernate())); } if (power.canSuspend()) { addLeaveEntry("system-suspend", tr("Suspend"), SLOT(suspend())); } ui->userCombo->setCurrentIndex(-1); ui->sessionCombo->setCurrentIndex(0); setCurrentSession(m_Greeter.defaultSessionHint()); connect(ui->userCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(userChanged())); connect(ui->otherUserInput, SIGNAL(editingFinished()), this, SLOT(userChanged())); connect(ui->loginButton, SIGNAL(clicked(bool)), this, SLOT(loginClicked())); connect(&m_Greeter, SIGNAL(showPrompt(QString, QLightDM::Greeter::PromptType)), this, SLOT(onPrompt(QString, QLightDM::Greeter::PromptType))); connect(&m_Greeter, SIGNAL(authenticationComplete()), this, SLOT(authenticationComplete())); if (m_Greeter.showManualLoginHint()) { ui->userCombo->setCurrentIndex(ui->userCombo->count() - 1); // 'other..' } else { QString user = Cache().getLastUser(); if (user.isEmpty()) { user = m_Greeter.selectUserHint(); } setCurrentUser(user); } ui->passwordInput->setEnabled(false); ui->passwordInput->clear(); } void LoginForm::userChanged() { setCurrentSession(Cache().getLastSession(currentUser())); if (m_Greeter.inAuthentication()) { m_Greeter.cancelAuthentication(); } if (! currentUser().isEmpty()) { m_Greeter.authenticate(currentUser()); ui->passwordInput->setFocus(); } else if (ui->userCombo->currentIndex() == ui->userCombo->count() - 1) { ui->otherUserInput->setFocus(); } } void LoginForm::loginClicked() { m_Greeter.respond(ui->passwordInput->text().trimmed()); ui->passwordInput->clear(); ui->passwordInput->setEnabled(false); } void LoginForm::onPrompt(QString prompt, QLightDM::Greeter::PromptType promptType) { ui->passwordInput->setEnabled(true); ui->passwordInput->setFocus(); } void LoginForm::addLeaveEntry(QString iconName, QString text, const char* slot) { QMenu* menu = ui->leaveButton->menu(); QAction *action = menu->addAction(QIcon::fromTheme(iconName), text); connect(action, SIGNAL(triggered(bool)), &power, slot); } QString LoginForm::currentUser() { QModelIndex index = usersModel.index(ui->userCombo->currentIndex(), 0, QModelIndex()); return usersModel.data(index, NameRole).toString(); } void LoginForm::setCurrentUser(QString user) { for (int i = 0; i < ui->userCombo->count() - 1; i++) { if (user == usersModel.data(usersModel.index(i, 0), NameRole).toString()) { ui->userCombo->setCurrentIndex(i); return; } } } QString LoginForm::currentSession() { QModelIndex index = sessionsModel.index(ui->sessionCombo->currentIndex(), 0, QModelIndex()); return sessionsModel.data(index, QLightDM::SessionsModel::KeyRole).toString(); } void LoginForm::setCurrentSession(QString session) { for (int i = 0; i < ui->sessionCombo->count(); i++) { if (session == sessionsModel.data(sessionsModel.index(i, 0), KeyRole).toString()) { ui->sessionCombo->setCurrentIndex(i); return; } } } void LoginForm::authenticationComplete() { if (m_Greeter.isAuthenticated()) { Cache settings; settings.setLastUser(currentUser()); settings.setLastSession(currentUser(), currentSession()); settings.sync(); m_Greeter.startSessionSync(currentSession()); } else { ui->passwordInput->clear(); } } void LoginForm::paintEvent(QPaintEvent *event) { ui->userCombo->setVisible(! m_Greeter.hideUsersHint()); ui->otherUserInput->setVisible(ui->userCombo->currentIndex() == usersModel.rowCount(QModelIndex()) - 1); adjustSize(); QWidget::paintEvent(event); } void LoginForm::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) { ui->loginButton->animateClick(); } else { QWidget::keyPressEvent(event); } } <commit_msg>Immediately initiate new authentication on authentication failed..<commit_after>/* * Copyright (c) 2012-2015 Christian Surlykke * * This file is part of qt-lightdm-greeter * It is distributed under the LGPL 2.1 or later license. * Please refer to the LICENSE file for a copy of the license. */ #include <QDebug> #include <QCompleter> #include <QAbstractListModel> #include <QModelIndex> #include <QFile> #include <QTextStream> #include <QStringList> #include <QPixmap> #include <QMessageBox> #include <QMenu> #include <QProcess> #include "loginform.h" #include "ui_loginform.h" #include "settings.h" const int NameRole = QLightDM::UsersModel::NameRole; const int KeyRole = QLightDM::SessionsModel::KeyRole; int rows(QAbstractItemModel& model) { return model.rowCount(QModelIndex()); } QString displayData(QAbstractItemModel& model, int row, int role) { QModelIndex modelIndex = model.index(row, 0); return model.data(modelIndex, role).toString(); } LoginForm::LoginForm(QWidget *parent) : QWidget(parent), ui(new Ui::LoginForm), m_Greeter(), power(this), usersModel(*this), sessionsModel() { if (!m_Greeter.connectSync()) { close(); } ui->setupUi(this); initialize(); } LoginForm::~LoginForm() { delete ui; } void LoginForm::setFocus(Qt::FocusReason reason) { if (ui->userCombo->currentIndex() == -1) { ui->userCombo->setFocus(reason); } else if (ui->userCombo->currentIndex() == ui->userCombo->count() - 1) { ui->otherUserInput->setFocus(reason); } else { ui->passwordInput->setFocus(reason); } } void LoginForm::initialize() { QPixmap icon(":/resources/rqt-2.png"); // This project came from Razor-qt ui->iconLabel->setPixmap(icon.scaled(ui->iconLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); ui->hostnameLabel->setText(m_Greeter.hostname()); ui->userCombo->setModel(&usersModel); ui->sessionCombo->setModel(&sessionsModel); ui->leaveButton->setMenu(new QMenu(this)); if (power.canShutdown()) { addLeaveEntry("system-shutdown", tr("Shutdown"), SLOT(shutdown())); } if (power.canRestart()) { addLeaveEntry("system-reboot", tr("Restart"), SLOT(restart())); } if (power.canHibernate()) { addLeaveEntry("system-suspend-hibernate", tr("Hibernate"), SLOT(hibernate())); } if (power.canSuspend()) { addLeaveEntry("system-suspend", tr("Suspend"), SLOT(suspend())); } ui->userCombo->setCurrentIndex(-1); ui->sessionCombo->setCurrentIndex(0); setCurrentSession(m_Greeter.defaultSessionHint()); connect(ui->userCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(userChanged())); connect(ui->otherUserInput, SIGNAL(editingFinished()), this, SLOT(userChanged())); connect(ui->loginButton, SIGNAL(clicked(bool)), this, SLOT(loginClicked())); connect(&m_Greeter, SIGNAL(showPrompt(QString, QLightDM::Greeter::PromptType)), this, SLOT(onPrompt(QString, QLightDM::Greeter::PromptType))); connect(&m_Greeter, SIGNAL(authenticationComplete()), this, SLOT(authenticationComplete())); if (m_Greeter.showManualLoginHint()) { ui->userCombo->setCurrentIndex(ui->userCombo->count() - 1); // 'other..' } else { QString user = Cache().getLastUser(); if (user.isEmpty()) { user = m_Greeter.selectUserHint(); } setCurrentUser(user); } ui->passwordInput->setEnabled(false); ui->passwordInput->clear(); } void LoginForm::userChanged() { setCurrentSession(Cache().getLastSession(currentUser())); if (m_Greeter.inAuthentication()) { m_Greeter.cancelAuthentication(); } if (! currentUser().isEmpty()) { m_Greeter.authenticate(currentUser()); ui->passwordInput->setFocus(); } else if (ui->userCombo->currentIndex() == ui->userCombo->count() - 1) { ui->otherUserInput->setFocus(); } } void LoginForm::loginClicked() { m_Greeter.respond(ui->passwordInput->text().trimmed()); ui->passwordInput->clear(); ui->passwordInput->setEnabled(false); } void LoginForm::onPrompt(QString prompt, QLightDM::Greeter::PromptType promptType) { ui->passwordInput->setEnabled(true); ui->passwordInput->setFocus(); } void LoginForm::addLeaveEntry(QString iconName, QString text, const char* slot) { QMenu* menu = ui->leaveButton->menu(); QAction *action = menu->addAction(QIcon::fromTheme(iconName), text); connect(action, SIGNAL(triggered(bool)), &power, slot); } QString LoginForm::currentUser() { QModelIndex index = usersModel.index(ui->userCombo->currentIndex(), 0, QModelIndex()); return usersModel.data(index, NameRole).toString(); } void LoginForm::setCurrentUser(QString user) { for (int i = 0; i < ui->userCombo->count() - 1; i++) { if (user == usersModel.data(usersModel.index(i, 0), NameRole).toString()) { ui->userCombo->setCurrentIndex(i); return; } } } QString LoginForm::currentSession() { QModelIndex index = sessionsModel.index(ui->sessionCombo->currentIndex(), 0, QModelIndex()); return sessionsModel.data(index, QLightDM::SessionsModel::KeyRole).toString(); } void LoginForm::setCurrentSession(QString session) { for (int i = 0; i < ui->sessionCombo->count(); i++) { if (session == sessionsModel.data(sessionsModel.index(i, 0), KeyRole).toString()) { ui->sessionCombo->setCurrentIndex(i); return; } } } void LoginForm::authenticationComplete() { if (m_Greeter.isAuthenticated()) { Cache settings; settings.setLastUser(currentUser()); settings.setLastSession(currentUser(), currentSession()); settings.sync(); m_Greeter.startSessionSync(currentSession()); } else { ui->passwordInput->clear(); userChanged(); } } void LoginForm::paintEvent(QPaintEvent *event) { ui->userCombo->setVisible(! m_Greeter.hideUsersHint()); ui->otherUserInput->setVisible(ui->userCombo->currentIndex() == usersModel.rowCount(QModelIndex()) - 1); adjustSize(); QWidget::paintEvent(event); } void LoginForm::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) { ui->loginButton->animateClick(); } else { QWidget::keyPressEvent(event); } } <|endoftext|>
<commit_before>// Copyright (c) 2009 - Decho Corp. #include "mordor/common/pch.h" #include "digest.h" #include "mordor/common/string.h" #include "mordor/common/timer.h" #include "parser.h" void HTTP::DigestAuth::authorize(const Response &challenge, Request &nextRequest, const std::string &username, const std::string &password) { ASSERT(challenge.status.status == UNAUTHORIZED || challenge.status.status == PROXY_AUTHENTICATION_REQUIRED); bool proxy = challenge.status.status == PROXY_AUTHENTICATION_REQUIRED; const ParameterizedList &authenticate = proxy ? challenge.response.proxyAuthenticate : challenge.response.wwwAuthenticate; ValueWithParameters &authorization = proxy ? nextRequest.request.proxyAuthorization : nextRequest.request.authorization; const StringMap *params = NULL; for (ParameterizedList::const_iterator it = authenticate.begin(); it != authenticate.end(); ++it) { if (stricmp(it->value.c_str(), "Digest") == 0) { params = &it->parameters; break; } } ASSERT(params); std::string realm, qop, nonce, opaque, algorithm; StringMap::const_iterator it; if ( (it = params->find("realm")) != params->end()) realm = it->second; if ( (it = params->find("qop")) != params->end()) qop = it->second; if ( (it = params->find("nonce")) != params->end()) nonce = it->second; if ( (it = params->find("opaque")) != params->end()) opaque = it->second; if ( (it = params->find("algorithm")) != params->end()) algorithm = it->second; if (algorithm.empty()) algorithm = "MD5"; StringSet qopValues; bool authQop = false; // If the server specified a quality of protection (qop), make sure it allows "auth" if (!qop.empty()) { ListParser parser(qopValues); parser.run(qop); if (parser.error() || !parser.complete()) throw BadMessageHeaderException(); if (qopValues.find("auth") == qopValues.end()) throw InvalidDigestQopException(qop); } // come up with a suitable client nonce std::ostringstream os; os << std::hex << TimerManager::now(); std::string cnonce = os.str(); std::string nc = "00000001"; // compute A1 std::string A1; if (algorithm == "MD5") A1 = username + ':' + realm + ':' + password; else if (algorithm == "MD5-sess") A1 = md5( username + ':' + realm + ':' + password ) + ':' + nonce + ':' + cnonce; else throw InvalidDigestAlgorithmException(algorithm); // compute A2 - our qop is always auth or unspecified os.str(""); os << nextRequest.requestLine.method << ':' << nextRequest.requestLine.uri; std::string A2 = os.str(); authorization.value = "Digest"; authorization.parameters["username"] = username; authorization.parameters["realm"] = realm; authorization.parameters["nonce"] = nonce; authorization.parameters["uri"] = nextRequest.requestLine.uri.toString(); authorization.parameters["algorithm"] = algorithm; std::string response; if (authQop) { qop = "auth"; response = md5( md5(A1) + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + md5(A2) ); authorization.parameters["qop"] = qop; authorization.parameters["nc"] = nc; authorization.parameters["cnonce"] = cnonce; } else { response = md5( md5(A1) + ':' + nonce + ':' + md5(A2) ); } authorization.parameters["response"] = response; if (!opaque.empty()) authorization.parameters["opaque"] = opaque; } <commit_msg>Fix digest authentication<commit_after>// Copyright (c) 2009 - Decho Corp. #include "mordor/common/pch.h" #include "digest.h" #include "mordor/common/string.h" #include "mordor/common/timer.h" #include "parser.h" void HTTP::DigestAuth::authorize(const Response &challenge, Request &nextRequest, const std::string &username, const std::string &password) { ASSERT(challenge.status.status == UNAUTHORIZED || challenge.status.status == PROXY_AUTHENTICATION_REQUIRED); bool proxy = challenge.status.status == PROXY_AUTHENTICATION_REQUIRED; const ParameterizedList &authenticate = proxy ? challenge.response.proxyAuthenticate : challenge.response.wwwAuthenticate; ValueWithParameters &authorization = proxy ? nextRequest.request.proxyAuthorization : nextRequest.request.authorization; const StringMap *params = NULL; for (ParameterizedList::const_iterator it = authenticate.begin(); it != authenticate.end(); ++it) { if (stricmp(it->value.c_str(), "Digest") == 0) { params = &it->parameters; break; } } ASSERT(params); std::string realm, qop, nonce, opaque, algorithm; StringMap::const_iterator it; if ( (it = params->find("realm")) != params->end()) realm = it->second; if ( (it = params->find("qop")) != params->end()) qop = it->second; if ( (it = params->find("nonce")) != params->end()) nonce = it->second; if ( (it = params->find("opaque")) != params->end()) opaque = it->second; if ( (it = params->find("algorithm")) != params->end()) algorithm = it->second; if (algorithm.empty()) algorithm = "MD5"; StringSet qopValues; bool authQop = false; // If the server specified a quality of protection (qop), make sure it allows "auth" if (!qop.empty()) { ListParser parser(qopValues); parser.run(qop); if (parser.error() || !parser.complete()) throw BadMessageHeaderException(); if (qopValues.find("auth") == qopValues.end()) throw InvalidDigestQopException(qop); authQop = true; } // come up with a suitable client nonce std::ostringstream os; os << std::hex << TimerManager::now(); std::string cnonce = os.str(); std::string nc = "00000001"; // compute A1 std::string A1; if (algorithm == "MD5") A1 = username + ':' + realm + ':' + password; else if (algorithm == "MD5-sess") A1 = md5( username + ':' + realm + ':' + password ) + ':' + nonce + ':' + cnonce; else throw InvalidDigestAlgorithmException(algorithm); // compute A2 - our qop is always auth or unspecified os.str(""); os << nextRequest.requestLine.method << ':' << nextRequest.requestLine.uri; std::string A2 = os.str(); authorization.value = "Digest"; authorization.parameters["username"] = username; authorization.parameters["realm"] = realm; authorization.parameters["nonce"] = nonce; authorization.parameters["uri"] = nextRequest.requestLine.uri.toString(); authorization.parameters["algorithm"] = algorithm; std::string response; if (authQop) { qop = "auth"; response = md5( md5(A1) + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + md5(A2) ); authorization.parameters["qop"] = qop; authorization.parameters["nc"] = nc; authorization.parameters["cnonce"] = cnonce; } else { response = md5( md5(A1) + ':' + nonce + ':' + md5(A2) ); } authorization.parameters["response"] = response; if (!opaque.empty()) authorization.parameters["opaque"] = opaque; } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/iceoryx_posh_config.hpp" #include "iceoryx_posh/internal/roudi/roudi.hpp" #include "iceoryx_posh/popo/publisher.hpp" #include "iceoryx_posh/popo/subscriber.hpp" #include "iceoryx_posh/roudi/iceoryx_roudi_components.hpp" #include "iceoryx_posh/runtime/posh_runtime_single_process.hpp" #include "iceoryx_utils/log/logmanager.hpp" #include <atomic> #include <chrono> #include <cstdint> #include <iostream> #include <mutex> #include <thread> std::atomic_bool keepRunning{true}; struct TransmissionData_t { uint64_t counter; }; void consoleOutput(const std::string& output) { static std::mutex consoleOutputMutex; std::lock_guard<std::mutex> lock(consoleOutputMutex); std::cout << output << std::endl; } void sender() { iox::popo::Publisher publisher({"Single", "Process", "Demo"}); publisher.offer(); uint64_t counter{0}; while (keepRunning.load()) { auto sample = static_cast<TransmissionData_t*>(publisher.allocateChunk(sizeof(TransmissionData_t))); sample->counter = counter++; consoleOutput(std::string("Sending: " + std::to_string(sample->counter))); publisher.sendChunk(sample); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } void receiver() { iox::popo::Subscriber subscriber({"Single", "Process", "Demo"}); uint64_t cacheQueueSize = 10; subscriber.subscribe(cacheQueueSize); while (keepRunning.load()) { if (iox::popo::SubscriptionState::SUBSCRIBED == subscriber.getSubscriptionState()) { const void* rawSample = nullptr; while (subscriber.getChunk(&rawSample)) { auto sample = static_cast<const TransmissionData_t*>(rawSample); consoleOutput(std::string("Receiving : " + std::to_string(sample->counter))); subscriber.releaseChunk(rawSample); } } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } int main() { // set the log level to error to see the essence of the example iox::log::LogManager::GetLogManager().SetDefaultLogLevel(iox::log::LogLevel::kError); iox::RouDiConfig_t defaultRouDiConfig = iox::RouDiConfig_t().setDefaults(); iox::roudi::IceOryxRouDiComponents roudiComponents(defaultRouDiConfig); iox::roudi::RouDi roudi( roudiComponents.m_rouDiMemoryManager, roudiComponents.m_portManager, iox::config::MonitoringMode::OFF, false); // create a single process runtime for inter thread communication iox::runtime::PoshRuntimeSingleProcess runtime("/singleProcessDemo"); std::thread receiverThread(receiver), senderThread(sender); // communicate for 2 seconds and then stop the example std::this_thread::sleep_for(std::chrono::seconds(2)); keepRunning.store(false); senderThread.join(); receiverThread.join(); } <commit_msg>iox-#324: fix missed example<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/iceoryx_posh_config.hpp" #include "iceoryx_posh/internal/roudi/roudi.hpp" #include "iceoryx_posh/popo/publisher.hpp" #include "iceoryx_posh/popo/subscriber.hpp" #include "iceoryx_posh/roudi/iceoryx_roudi_components.hpp" #include "iceoryx_posh/runtime/posh_runtime_single_process.hpp" #include "iceoryx_utils/log/logmanager.hpp" #include <atomic> #include <chrono> #include <cstdint> #include <iostream> #include <mutex> #include <thread> std::atomic_bool keepRunning{true}; struct TransmissionData_t { uint64_t counter; }; void consoleOutput(const std::string& output) { static std::mutex consoleOutputMutex; std::lock_guard<std::mutex> lock(consoleOutputMutex); std::cout << output << std::endl; } void sender() { iox::popo::Publisher publisher({"Single", "Process", "Demo"}); publisher.offer(); uint64_t counter{0}; while (keepRunning.load()) { auto sample = static_cast<TransmissionData_t*>(publisher.allocateChunk(sizeof(TransmissionData_t))); sample->counter = counter++; consoleOutput(std::string("Sending: " + std::to_string(sample->counter))); publisher.sendChunk(sample); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } void receiver() { iox::popo::Subscriber subscriber({"Single", "Process", "Demo"}); uint64_t cacheQueueSize = 10; subscriber.subscribe(cacheQueueSize); while (keepRunning.load()) { if (iox::popo::SubscriptionState::SUBSCRIBED == subscriber.getSubscriptionState()) { const void* rawSample = nullptr; while (subscriber.getChunk(&rawSample)) { auto sample = static_cast<const TransmissionData_t*>(rawSample); consoleOutput(std::string("Receiving : " + std::to_string(sample->counter))); subscriber.releaseChunk(rawSample); } } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } int main() { // set the log level to error to see the essence of the example iox::log::LogManager::GetLogManager().SetDefaultLogLevel(iox::log::LogLevel::kError); iox::RouDiConfig_t defaultRouDiConfig = iox::RouDiConfig_t().setDefaults(); iox::roudi::IceOryxRouDiComponents roudiComponents(defaultRouDiConfig); iox::roudi::RouDi roudi(roudiComponents.m_rouDiMemoryManager, roudiComponents.m_portManager, iox::roudi::RouDi::RoudiStartupParameters{iox::config::MonitoringMode::OFF, false}); // create a single process runtime for inter thread communication iox::runtime::PoshRuntimeSingleProcess runtime("/singleProcessDemo"); std::thread receiverThread(receiver), senderThread(sender); // communicate for 2 seconds and then stop the example std::this_thread::sleep_for(std::chrono::seconds(2)); keepRunning.store(false); senderThread.join(); receiverThread.join(); } <|endoftext|>
<commit_before>// =-=-=-=-=-=-=- #include "irods_buffer_encryption.hpp" #include "irods_log.hpp" // =-=-=-=-=-=-=- // ssl includes #include <openssl/rand.h> #include <openssl/err.h> #include <openssl/aes.h> #include <iostream> #include <sstream> #include <iomanip> #include "global.hpp" #include "md5.hpp" namespace irods { #if 0 class evp_lifetime_mgr { public: evp_lifetime_mgr() { OpenSSL_add_all_algorithms(); } ~evp_lifetime_mgr() { EVP_cleanup(); } }; // class evp_lifetime_mgr static evp_lifetime_mgr global_evp_lifetime_mgr_; #endif std::string buffer_crypt::gen_hash( unsigned char* _buf, int _sz ) { MD5_CTX ctx; MD5Init( &ctx ); MD5Update( &ctx, _buf, _sz ); unsigned char hash[16]; MD5Final( hash, &ctx ); std::stringstream ss; for ( int i = 0; i < 16; ++i ) { ss << std::setfill( '0' ) << std::setw( 2 ) << std::hex << ( int )hash[i]; } return ss.str(); } // =-=-=-=-=-=-=- // public - constructor buffer_crypt::buffer_crypt() : key_size_( 32 ), salt_size_( 8 ), num_hash_rounds_( 16 ), algorithm_( "AES-256-CBC" ) { std::transform( algorithm_.begin(), algorithm_.end(), algorithm_.begin(), ::tolower ); } buffer_crypt::buffer_crypt( int _key_sz, int _salt_sz, int _num_rnds, const char* _algo ) : key_size_( _key_sz ), salt_size_( _salt_sz ), num_hash_rounds_( _num_rnds ), algorithm_( _algo ) { std::transform( algorithm_.begin(), algorithm_.end(), algorithm_.begin(), ::tolower ); // =-=-=-=-=-=-=- // select some sane defaults if ( 0 == key_size_ ) { key_size_ = 32; } if ( 0 == salt_size_ ) { salt_size_ = 8; } if ( 0 == num_hash_rounds_ ) { num_hash_rounds_ = 16; } if ( algorithm_.empty() ) { algorithm_ = "aes-256-cbc"; } } // ctor // =-=-=-=-=-=-=- // public - destructor buffer_crypt::~buffer_crypt() { } // dtor // =-=-=-=-=-=-=- // public static - generate a random key irods::error buffer_crypt::generate_key( array_t& _out_key, int _key_size ) { // =-=-=-=-=-=-=- // generate random bytes _out_key.resize( _key_size ); const int rnd_err = RAND_bytes( &_out_key[0], _key_size ); if ( 1 != rnd_err ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, sizeof( err ) ); const std::string msg = std::string( "failed in RAND_bytes - " ) + err; return ERROR( ERR_get_error(), msg ); } return SUCCESS(); } // buffer_crypt::generate_key // =-=-=-=-=-=-=- // public static - hex encode byte array irods::error buffer_crypt::hex_encode( const array_t& _in_buf, std::string& _out_str ) { std::stringstream ss; for ( irods::buffer_crypt::array_t::size_type i = 0; i < _in_buf.size(); ++i ) { ss << std::setfill( '0' ) << std::setw( 2 ) << std::hex << static_cast<unsigned int>( _in_buf[i] ); } _out_str = ss.str(); return SUCCESS(); } // buffer_crypt::hex_encode // =-=-=-=-=-=-=- // public - create a hashed key and initialization vector irods::error buffer_crypt::initialization_vector( array_t& _out_iv ) { // =-=-=-=-=-=-=- // generate a random initialization vector unsigned char* iv = new unsigned char[ key_size_ ]; int rnd_err = RAND_bytes( iv, key_size_ ); if ( 1 != rnd_err ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in RAND_bytes - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // copy the iv to the out variable _out_iv.assign( &iv[0], &iv[ key_size_ ] ); // =-=-=-=-=-=-=- // clean up delete [] iv; return SUCCESS(); } // buffer_crypt::initialization_vector // =-=-=-=-=-=-=- // public - encryptor irods::error buffer_crypt::encrypt( const array_t& _key, const array_t& _iv, const array_t& _in_buf, array_t& _out_buf ) { // =-=-=-=-=-=-=- // create an encryption context EVP_CIPHER_CTX context; EVP_CIPHER_CTX_init( &context ); const EVP_CIPHER* algo = EVP_get_cipherbyname( algorithm_.c_str() ); if ( !algo ) { rodsLog( LOG_NOTICE, "buffer_crypt::encrypt - algorithm not supported [%s], default to aes-256-cbc", algorithm_.c_str() ); // default to aes 256 cbc algo = EVP_aes_256_cbc(); } int ret = EVP_EncryptInit_ex( &context, algo, NULL, &_key[0], &_iv[0] ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_EncryptInit_ex - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes int cipher_len = _in_buf.size() + AES_BLOCK_SIZE; unsigned char* cipher_text = new unsigned char[ cipher_len ] ; // =-=-=-=-=-=-=- // update ciphertext, cipher_len is filled with the length of ciphertext generated, ret = EVP_EncryptUpdate( &context, cipher_text, &cipher_len, &_in_buf[0], _in_buf.size() ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_EncryptUpdate - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // update ciphertext with the final remaining bytes int final_len = 0; ret = EVP_EncryptFinal_ex( &context, cipher_text + cipher_len, &final_len ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_EncryptFinal_ex - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // clean up and assign out variables before exit _out_buf.resize( cipher_len + final_len ); // =-=-=-=-=-=-=- // copy the iv to the out variable _out_buf.assign( &cipher_text[0], &cipher_text[ cipher_len + final_len ] ); delete [] cipher_text; if ( 0 == EVP_CIPHER_CTX_cleanup( &context ) ) { return ERROR( ERR_get_error(), "EVP_CIPHER_CTX_cleanup failed" ); } return SUCCESS(); } // encrypt // =-=-=-=-=-=-=- // public - decryptor irods::error buffer_crypt::decrypt( const array_t& _key, const array_t& _iv, const array_t& _in_buf, array_t& _out_buf ) { // =-=-=-=-=-=-=- // create an decryption context EVP_CIPHER_CTX context; EVP_CIPHER_CTX_init( &context ); const EVP_CIPHER* algo = EVP_get_cipherbyname( algorithm_.c_str() ); if ( !algo ) { rodsLog( LOG_NOTICE, "buffer_crypt::decrypt - algorithm not supported [%s], default to aes-256-cbc", algorithm_.c_str() ); // default to aes 256 cbc algo = EVP_aes_256_cbc(); } int ret = EVP_DecryptInit_ex( &context, algo, NULL, &_key[0], &_iv [0] ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_DecryptInit_ex - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // allocate a plain text buffer // because we have padding ON, we must allocate an extra cipher block size of memory int plain_len = 0; unsigned char* plain_text = new unsigned char[ _in_buf.size() + AES_BLOCK_SIZE ]; // =-=-=-=-=-=-=- // update the plain text, plain_len is filled with the length of the plain text ret = EVP_DecryptUpdate( &context, plain_text, &plain_len, &_in_buf[0], _in_buf.size() ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_DecryptUpdate - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // finalize the plain text, final_len is filled with the resulting length of the plain text int final_len = 0; ret = EVP_DecryptFinal_ex( &context, plain_text + plain_len, &final_len ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_DecryptFinal_ex - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // assign the plain text to the outvariable and clean up _out_buf.resize( plain_len + final_len ); // =-=-=-=-=-=-=- // copy the iv to the out variable _out_buf.assign( &plain_text[0], &plain_text[ plain_len + final_len ] ); delete [] plain_text; if ( 0 == EVP_CIPHER_CTX_cleanup( &context ) ) { return ERROR( ERR_get_error(), "EVP_CIPHER_CTX_cleanup failed" ); } return SUCCESS(); } // decrypt }; // namespace irods <commit_msg>Revert "[#2621] remove SSL table init for debug test in CI"<commit_after>// =-=-=-=-=-=-=- #include "irods_buffer_encryption.hpp" #include "irods_log.hpp" // =-=-=-=-=-=-=- // ssl includes #include <openssl/rand.h> #include <openssl/err.h> #include <openssl/aes.h> #include <iostream> #include <sstream> #include <iomanip> #include "global.hpp" #include "md5.hpp" namespace irods { class evp_lifetime_mgr { public: evp_lifetime_mgr() { OpenSSL_add_all_algorithms(); } ~evp_lifetime_mgr() { EVP_cleanup(); } }; // class evp_lifetime_mgr static evp_lifetime_mgr global_evp_lifetime_mgr_; std::string buffer_crypt::gen_hash( unsigned char* _buf, int _sz ) { MD5_CTX ctx; MD5Init( &ctx ); MD5Update( &ctx, _buf, _sz ); unsigned char hash[16]; MD5Final( hash, &ctx ); std::stringstream ss; for ( int i = 0; i < 16; ++i ) { ss << std::setfill( '0' ) << std::setw( 2 ) << std::hex << ( int )hash[i]; } return ss.str(); } // =-=-=-=-=-=-=- // public - constructor buffer_crypt::buffer_crypt() : key_size_( 32 ), salt_size_( 8 ), num_hash_rounds_( 16 ), algorithm_( "AES-256-CBC" ) { std::transform( algorithm_.begin(), algorithm_.end(), algorithm_.begin(), ::tolower ); } buffer_crypt::buffer_crypt( int _key_sz, int _salt_sz, int _num_rnds, const char* _algo ) : key_size_( _key_sz ), salt_size_( _salt_sz ), num_hash_rounds_( _num_rnds ), algorithm_( _algo ) { std::transform( algorithm_.begin(), algorithm_.end(), algorithm_.begin(), ::tolower ); // =-=-=-=-=-=-=- // select some sane defaults if ( 0 == key_size_ ) { key_size_ = 32; } if ( 0 == salt_size_ ) { salt_size_ = 8; } if ( 0 == num_hash_rounds_ ) { num_hash_rounds_ = 16; } if ( algorithm_.empty() ) { algorithm_ = "aes-256-cbc"; } } // ctor // =-=-=-=-=-=-=- // public - destructor buffer_crypt::~buffer_crypt() { } // dtor // =-=-=-=-=-=-=- // public static - generate a random key irods::error buffer_crypt::generate_key( array_t& _out_key, int _key_size ) { // =-=-=-=-=-=-=- // generate random bytes _out_key.resize( _key_size ); const int rnd_err = RAND_bytes( &_out_key[0], _key_size ); if ( 1 != rnd_err ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, sizeof( err ) ); const std::string msg = std::string( "failed in RAND_bytes - " ) + err; return ERROR( ERR_get_error(), msg ); } return SUCCESS(); } // buffer_crypt::generate_key // =-=-=-=-=-=-=- // public static - hex encode byte array irods::error buffer_crypt::hex_encode( const array_t& _in_buf, std::string& _out_str ) { std::stringstream ss; for ( irods::buffer_crypt::array_t::size_type i = 0; i < _in_buf.size(); ++i ) { ss << std::setfill( '0' ) << std::setw( 2 ) << std::hex << static_cast<unsigned int>( _in_buf[i] ); } _out_str = ss.str(); return SUCCESS(); } // buffer_crypt::hex_encode // =-=-=-=-=-=-=- // public - create a hashed key and initialization vector irods::error buffer_crypt::initialization_vector( array_t& _out_iv ) { // =-=-=-=-=-=-=- // generate a random initialization vector unsigned char* iv = new unsigned char[ key_size_ ]; int rnd_err = RAND_bytes( iv, key_size_ ); if ( 1 != rnd_err ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in RAND_bytes - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // copy the iv to the out variable _out_iv.assign( &iv[0], &iv[ key_size_ ] ); // =-=-=-=-=-=-=- // clean up delete [] iv; return SUCCESS(); } // buffer_crypt::initialization_vector // =-=-=-=-=-=-=- // public - encryptor irods::error buffer_crypt::encrypt( const array_t& _key, const array_t& _iv, const array_t& _in_buf, array_t& _out_buf ) { // =-=-=-=-=-=-=- // create an encryption context EVP_CIPHER_CTX context; EVP_CIPHER_CTX_init( &context ); const EVP_CIPHER* algo = EVP_get_cipherbyname( algorithm_.c_str() ); if ( !algo ) { rodsLog( LOG_NOTICE, "buffer_crypt::encrypt - algorithm not supported [%s]", algorithm_.c_str() ); // default to aes 256 cbc algo = EVP_aes_256_cbc(); } int ret = EVP_EncryptInit_ex( &context, algo, NULL, &_key[0], &_iv[0] ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_EncryptInit_ex - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes int cipher_len = _in_buf.size() + AES_BLOCK_SIZE; unsigned char* cipher_text = new unsigned char[ cipher_len ] ; // =-=-=-=-=-=-=- // update ciphertext, cipher_len is filled with the length of ciphertext generated, ret = EVP_EncryptUpdate( &context, cipher_text, &cipher_len, &_in_buf[0], _in_buf.size() ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_EncryptUpdate - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // update ciphertext with the final remaining bytes int final_len = 0; ret = EVP_EncryptFinal_ex( &context, cipher_text + cipher_len, &final_len ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_EncryptFinal_ex - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // clean up and assign out variables before exit _out_buf.resize( cipher_len + final_len ); // =-=-=-=-=-=-=- // copy the iv to the out variable _out_buf.assign( &cipher_text[0], &cipher_text[ cipher_len + final_len ] ); delete [] cipher_text; if ( 0 == EVP_CIPHER_CTX_cleanup( &context ) ) { return ERROR( ERR_get_error(), "EVP_CIPHER_CTX_cleanup failed" ); } return SUCCESS(); } // encrypt // =-=-=-=-=-=-=- // public - decryptor irods::error buffer_crypt::decrypt( const array_t& _key, const array_t& _iv, const array_t& _in_buf, array_t& _out_buf ) { // =-=-=-=-=-=-=- // create an decryption context EVP_CIPHER_CTX context; EVP_CIPHER_CTX_init( &context ); const EVP_CIPHER* algo = EVP_get_cipherbyname( algorithm_.c_str() ); if ( !algo ) { rodsLog( LOG_NOTICE, "buffer_crypt::decrypt - algorithm not supported [%s]", algorithm_.c_str() ); // default to aes 256 cbc algo = EVP_aes_256_cbc(); } int ret = EVP_DecryptInit_ex( &context, algo, NULL, &_key[0], &_iv [0] ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_DecryptInit_ex - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // allocate a plain text buffer // because we have padding ON, we must allocate an extra cipher block size of memory int plain_len = 0; unsigned char* plain_text = new unsigned char[ _in_buf.size() + AES_BLOCK_SIZE ]; // =-=-=-=-=-=-=- // update the plain text, plain_len is filled with the length of the plain text ret = EVP_DecryptUpdate( &context, plain_text, &plain_len, &_in_buf[0], _in_buf.size() ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_DecryptUpdate - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // finalize the plain text, final_len is filled with the resulting length of the plain text int final_len = 0; ret = EVP_DecryptFinal_ex( &context, plain_text + plain_len, &final_len ); if ( 0 == ret ) { char err[ 256 ]; ERR_error_string_n( ERR_get_error(), err, 256 ); std::string msg( "failed in EVP_DecryptFinal_ex - " ); msg += err; return ERROR( ERR_get_error(), msg ); } // =-=-=-=-=-=-=- // assign the plain text to the outvariable and clean up _out_buf.resize( plain_len + final_len ); // =-=-=-=-=-=-=- // copy the iv to the out variable _out_buf.assign( &plain_text[0], &plain_text[ plain_len + final_len ] ); delete [] plain_text; if ( 0 == EVP_CIPHER_CTX_cleanup( &context ) ) { return ERROR( ERR_get_error(), "EVP_CIPHER_CTX_cleanup failed" ); } return SUCCESS(); } // decrypt }; // namespace irods <|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_MAIN_MENU_MAIN_MENU_HPP #define RJ_GAME_MAIN_MENU_MAIN_MENU_HPP #include "background_main_menu.hpp" #include "overlay.hpp" #include <rectojump/core/game_window.hpp> #include <rectojump/core/render.hpp> #include <rectojump/game/background/background_manager.hpp> #include <rectojump/game/components/player.hpp> #include <rectojump/game/factory.hpp> #include <rectojump/global/common.hpp> #include <rectojump/global/config_settings.hpp> #include <rectojump/shared/level_manager/level_manager.hpp> #include <rectojump/shared/data_manager.hpp> #include <rectojump/shared/utils.hpp> #include <rectojump/ui/stacked_widget.hpp> #include <SFML/Graphics.hpp> namespace rj { template<typename Game_Handler> class main_menu { Game_Handler& m_gamehandler; game_window& m_gamewindow; data_manager& m_datamgr; level_manager& m_lvmgr; data_store_type& m_datastore; background_manager& m_backgroundmgr; background_main_menu<main_menu> m_background; // overlay overlay<main_menu> m_overlay; public: main_menu(Game_Handler& gh) : m_gamehandler{gh}, m_gamewindow{gh.gamewindow()}, m_datamgr{gh.datamgr()}, m_lvmgr{gh.levelmgr()}, m_datastore{gh.datastore()}, m_backgroundmgr{gh.backgroundmgr()}, m_background{*this}, m_overlay{*this} {this->init();} void update(dur duration) { m_background.update(duration); m_overlay.update(duration); } void render() { m_overlay.render(); } auto& gamehandler() noexcept {return m_gamehandler;} void on_activate() { // set the background m_backgroundmgr.set_bg_shape({settings::get_window_size<vec2f>(), to_rgb("#e3e3e3"), to_rgb("#e3e3e3")}); } private: void init() { this->on_activate(); } void init_input() { } }; } #endif // RJ_GAME_MAIN_MENU_MAIN_MENU_HPP <commit_msg>game > main_menu: changed background color<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_MAIN_MENU_MAIN_MENU_HPP #define RJ_GAME_MAIN_MENU_MAIN_MENU_HPP #include "background_main_menu.hpp" #include "overlay.hpp" #include <rectojump/core/game_window.hpp> #include <rectojump/core/render.hpp> #include <rectojump/game/background/background_manager.hpp> #include <rectojump/game/components/player.hpp> #include <rectojump/game/factory.hpp> #include <rectojump/global/common.hpp> #include <rectojump/global/config_settings.hpp> #include <rectojump/shared/level_manager/level_manager.hpp> #include <rectojump/shared/data_manager.hpp> #include <rectojump/shared/utils.hpp> #include <rectojump/ui/stacked_widget.hpp> #include <SFML/Graphics.hpp> namespace rj { template<typename Game_Handler> class main_menu { Game_Handler& m_gamehandler; game_window& m_gamewindow; data_manager& m_datamgr; level_manager& m_lvmgr; data_store_type& m_datastore; background_manager& m_backgroundmgr; background_main_menu<main_menu> m_background; // overlay overlay<main_menu> m_overlay; public: main_menu(Game_Handler& gh) : m_gamehandler{gh}, m_gamewindow{gh.gamewindow()}, m_datamgr{gh.datamgr()}, m_lvmgr{gh.levelmgr()}, m_datastore{gh.datastore()}, m_backgroundmgr{gh.backgroundmgr()}, m_background{*this}, m_overlay{*this} {this->init();} void update(dur duration) { m_background.update(duration); m_overlay.update(duration); } void render() { m_overlay.render(); } auto& gamehandler() noexcept {return m_gamehandler;} void on_activate() { // set the background m_backgroundmgr.set_bg_shape({settings::get_window_size<vec2f>(), to_rgb("#373737"), to_rgb("#373737")}); } private: void init() { this->on_activate(); } void init_input() { } }; } #endif // RJ_GAME_MAIN_MENU_MAIN_MENU_HPP <|endoftext|>
<commit_before>#ifndef _INCLUDED_ESA_COMPRESSOR_HPP_ #define _INCLUDED_ESA_COMPRESSOR_HPP_ #include <tudocomp/util.hpp> #include <tudocomp/compressors/lzss/LZSSCoding.hpp> #include <tudocomp/compressors/lzss/LZSSFactors.hpp> #include <tudocomp/compressors/lzss/LZSSLiterals.hpp> #include <tudocomp/compressors/esacomp/ESACompMaxLCP.hpp> #include <tudocomp/compressors/esacomp/ESACompBulldozer.hpp> #include <tudocomp/compressors/esacomp/ESACompNaive.hpp> #include <tudocomp/ds/TextDS.hpp> namespace tdc { /// Factorizes the input by finding redundant phrases in a re-ordered version /// of the LCP table. template<typename coder_t, typename strategy_t> class ESACompressor : public Compressor { private: typedef TextDS<> text_t; public: inline static Meta meta() { Meta m("compressor", "esacomp"); m.option("coder").templated<coder_t>(); m.option("strategy").templated<strategy_t, esacomp::ESACompMaxLCP>(); m.option("threshold").dynamic("6"); m.needs_sentinel_terminator(); return m; } /// Construct the class with an environment. inline ESACompressor(Env&& env) : Compressor(std::move(env)) {} inline virtual void compress(Input& input, Output& output) override { auto in = input.as_view(); DCHECK(in.ends_with(uint8_t(0))); text_t text(in, env()); // read options size_t threshold = env().option("threshold").as_integer(); //factor threshold lzss::FactorBuffer factors; { // Construct SA, ISA and LCP env().begin_stat_phase("Construct text ds"); text.require(text_t::SA | text_t::ISA | text_t::LCP); env().end_stat_phase(); // Factorize env().begin_stat_phase("Factorize using strategy"); strategy_t strategy(env().env_for_option("strategy")); strategy.factorize(text, threshold, factors); env().log_stat("threshold", threshold); env().log_stat("factors", factors.size()); env().end_stat_phase(); } // sort factors factors.sort(); // encode typename coder_t::Encoder coder(env().env_for_option("coder"), output, lzss::TextLiterals<text_t>(text, factors)); lzss::encode_text(coder, text, factors); //TODO is this correct? } inline virtual void decompress(Input& input, Output& output) override { //TODO: tell that forward-factors are allowed typename coder_t::Decoder decoder(env().env_for_option("coder"), input); auto outs = output.as_stream(); lzss::decode_text(decoder, outs, true); } }; } #endif <commit_msg>Added missing include...<commit_after>#ifndef _INCLUDED_ESA_COMPRESSOR_HPP_ #define _INCLUDED_ESA_COMPRESSOR_HPP_ #include <tudocomp/util.hpp> #include <tudocomp/compressors/lzss/LZSSCoding.hpp> #include <tudocomp/compressors/lzss/LZSSFactors.hpp> #include <tudocomp/compressors/lzss/LZSSLiterals.hpp> #include <tudocomp/compressors/esacomp/ESACompMaxLCP.hpp> #include <tudocomp/compressors/esacomp/ESACompBulldozer.hpp> #include <tudocomp/compressors/esacomp/ESACompNaive.hpp> #include <tudocomp/compressors/esacomp/LazyList.hpp> #include <tudocomp/ds/TextDS.hpp> namespace tdc { /// Factorizes the input by finding redundant phrases in a re-ordered version /// of the LCP table. template<typename coder_t, typename strategy_t> class ESACompressor : public Compressor { private: typedef TextDS<> text_t; public: inline static Meta meta() { Meta m("compressor", "esacomp"); m.option("coder").templated<coder_t>(); m.option("strategy").templated<strategy_t, esacomp::ESACompMaxLCP>(); m.option("threshold").dynamic("6"); m.needs_sentinel_terminator(); return m; } /// Construct the class with an environment. inline ESACompressor(Env&& env) : Compressor(std::move(env)) {} inline virtual void compress(Input& input, Output& output) override { auto in = input.as_view(); DCHECK(in.ends_with(uint8_t(0))); text_t text(in, env()); // read options size_t threshold = env().option("threshold").as_integer(); //factor threshold lzss::FactorBuffer factors; { // Construct SA, ISA and LCP env().begin_stat_phase("Construct text ds"); text.require(text_t::SA | text_t::ISA | text_t::LCP); env().end_stat_phase(); // Factorize env().begin_stat_phase("Factorize using strategy"); strategy_t strategy(env().env_for_option("strategy")); strategy.factorize(text, threshold, factors); env().log_stat("threshold", threshold); env().log_stat("factors", factors.size()); env().end_stat_phase(); } // sort factors factors.sort(); // encode typename coder_t::Encoder coder(env().env_for_option("coder"), output, lzss::TextLiterals<text_t>(text, factors)); lzss::encode_text(coder, text, factors); //TODO is this correct? } inline virtual void decompress(Input& input, Output& output) override { //TODO: tell that forward-factors are allowed typename coder_t::Decoder decoder(env().env_for_option("coder"), input); auto outs = output.as_stream(); lzss::decode_text(decoder, outs, true); } }; } #endif <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cstddef> #include <visionaray/array.h> #include <visionaray/material.h> namespace visionaray { //------------------------------------------------------------------------------------------------- // Public interface // template <typename T, typename ...Ts> template <template <typename> class M> inline generic_material<T, Ts...>::generic_material(M<typename T::scalar_type> const& material) : generic_material<T, Ts...>::base_type(material) { } template <typename T, typename ...Ts> VSNRAY_FUNC inline bool generic_material<T, Ts...>::is_emissive() const { return apply_visitor( is_emissive_visitor(), *this ); } template <typename T, typename ...Ts> VSNRAY_FUNC inline spectrum<typename T::scalar_type> generic_material<T, Ts...>::ambient() const { return apply_visitor( ambient_visitor(), *this ); } template <typename T, typename ...Ts> template <typename SR> VSNRAY_FUNC inline spectrum<typename SR::scalar_type> generic_material<T, Ts...>::shade(SR const& sr) const { return apply_visitor( shade_visitor<SR>(sr), *this ); } template <typename T, typename ...Ts> template <typename SR, typename U, typename Sampler> VSNRAY_FUNC inline spectrum<U> generic_material<T, Ts...>::sample( SR const& sr, vector<3, U>& refl_dir, U& pdf, Sampler& sampler ) const { return apply_visitor( sample_visitor<SR, U, Sampler>(sr, refl_dir, pdf, sampler), *this ); } //------------------------------------------------------------------------------------------------- // Private variant visitors // template <typename T, typename ...Ts> struct generic_material<T, Ts...>::is_emissive_visitor { using Base = generic_material<T, Ts...>; using return_type = bool; template <typename X> VSNRAY_FUNC bool operator()(X) const { return false; } VSNRAY_FUNC bool operator()(emissive<typename Base::scalar_type>) const { return true; } }; template <typename T, typename ...Ts> struct generic_material<T, Ts...>::ambient_visitor { using Base = generic_material<T, Ts...>; using return_type = spectrum<typename Base::scalar_type>; template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.ambient(); } }; template <typename T, typename ...Ts> template <typename SR> struct generic_material<T, Ts...>::shade_visitor { using return_type = spectrum<typename SR::scalar_type>; VSNRAY_FUNC shade_visitor(SR const& sr) : sr_(sr) {} template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.shade(sr_); } SR const& sr_; }; template <typename T, typename ...Ts> template <typename SR, typename U, typename Sampler> struct generic_material<T, Ts...>::sample_visitor { using return_type = spectrum<typename SR::scalar_type>; VSNRAY_FUNC sample_visitor(SR const& sr, vector<3, U>& refl_dir, U& pdf, Sampler& sampler) : sr_(sr) , refl_dir_(refl_dir) , pdf_(pdf) , sampler_(sampler) { } template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.sample(sr_, refl_dir_, pdf_, sampler_); } SR const& sr_; vector<3, U>& refl_dir_; U& pdf_; Sampler& sampler_; }; namespace simd { //------------------------------------------------------------------------------------------------- // SIMD type used internally. Contains N generic materials // template <size_t N, typename ...Ts> class generic_material { public: using scalar_type = float_from_simd_width_t<N>; using single_material = visionaray::generic_material<Ts...>; public: VSNRAY_FUNC generic_material(array<single_material, N> const& mats) : mats_(mats) { } VSNRAY_FUNC single_material& get(int i) { return mats_[i]; } VSNRAY_FUNC single_material const& get(int i) const { return mats_[i]; } VSNRAY_FUNC mask_type_t<scalar_type> is_emissive() const { using mask_t = mask_type_t<scalar_type>; using mask_array = aligned_array_t<mask_t>; mask_array arr; for (size_t i = 0; i < N; ++i) { arr[i] = mats_[i].is_emissive(); } return mask_t(arr); } VSNRAY_FUNC spectrum<scalar_type> ambient() const { array<spectrum<float>, N> amb; for (size_t i = 0; i < N; ++i) { amb[i] = mats_[i].ambient(); } return pack(amb); } template <typename SR> VSNRAY_FUNC spectrum<scalar_type> shade(SR const& sr) const { auto srs = unpack(sr); array<spectrum<float>, N> shaded; for (size_t i = 0; i < N; ++i) { shaded[i] = mats_[i].shade(srs[i]); } return pack(shaded); } template <typename SR, typename S /* sampler */> VSNRAY_FUNC spectrum<scalar_type> sample( SR const& sr, vector<3, scalar_type>& refl_dir, scalar_type& pdf, S& samp ) const { using float_array = aligned_array_t<scalar_type>; auto srs = unpack(sr); array<vector<3, float>, N> rds; float_array pdfs; array<spectrum<float>, N> sampled; for (size_t i = 0; i < N; ++i) { sampled[i] = mats_[i].sample(srs[i], rds[i], pdfs[i], samp.get_sampler(i)); } refl_dir = pack(rds); pdf = scalar_type(pdfs); return pack(sampled); } private: array<single_material, N> mats_; }; //------------------------------------------------------------------------------------------------- // Pack and unpack // template <typename ...Ts> VSNRAY_FUNC inline generic_material<4, Ts...> pack(array<visionaray::generic_material<Ts...>, 4> const& mats) { return generic_material<4, Ts...>(mats); } template <typename ...Ts> VSNRAY_FUNC inline array<visionaray::generic_material<Ts...>, 4> unpack(generic_material<4, Ts...> const& m4) { return array<visionaray::generic_material<Ts...>, 4>{{ m4.get(0), m4.get(1), m4.get(2), m4.get(3) }}; } template <typename ...Ts> inline generic_material<8, Ts...> pack(array<visionaray::generic_material<Ts...>, 8> const& mats) { return generic_material<8, Ts...>(mats); } template <typename ...Ts> inline array<visionaray::generic_material<Ts...>, 8> unpack(generic_material<8, Ts...> const& m8) { return array<visionaray::generic_material<Ts...>, 8>{{ m8.get(0), m8.get(1), m8.get(2), m8.get(3), m8.get(4), m8.get(5), m8.get(6), m8.get(7) }}; } template <typename ...Ts> inline generic_material<16, Ts...> pack(array<visionaray::generic_material<Ts...>, 16> const& mats) { return generic_material<16, Ts...>(mats); } template <typename ...Ts> inline array<visionaray::generic_material<Ts...>, 16> unpack(generic_material<16, Ts...> const& m16) { return array<visionaray::generic_material<Ts...>, 8>{{ m16.get( 0), m16.get( 1), m16.get( 2), m16.get( 3), m16.get( 4), m16.get( 5), m16.get( 6), m16.get( 7), m16.get( 8), m16.get( 9), m16.get(10), m16.get(11), m16.get(12), m16.get(13), m16.get(14), m16.get(15) }}; } } // simd } // visionaray <commit_msg>Layout<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cstddef> #include <visionaray/array.h> #include <visionaray/material.h> namespace visionaray { //------------------------------------------------------------------------------------------------- // Public interface // template <typename T, typename ...Ts> template <template <typename> class M> inline generic_material<T, Ts...>::generic_material(M<typename T::scalar_type> const& material) : generic_material<T, Ts...>::base_type(material) { } template <typename T, typename ...Ts> VSNRAY_FUNC inline bool generic_material<T, Ts...>::is_emissive() const { return apply_visitor( is_emissive_visitor(), *this ); } template <typename T, typename ...Ts> VSNRAY_FUNC inline spectrum<typename T::scalar_type> generic_material<T, Ts...>::ambient() const { return apply_visitor( ambient_visitor(), *this ); } template <typename T, typename ...Ts> template <typename SR> VSNRAY_FUNC inline spectrum<typename SR::scalar_type> generic_material<T, Ts...>::shade(SR const& sr) const { return apply_visitor( shade_visitor<SR>(sr), *this ); } template <typename T, typename ...Ts> template <typename SR, typename U, typename Sampler> VSNRAY_FUNC inline spectrum<U> generic_material<T, Ts...>::sample( SR const& sr, vector<3, U>& refl_dir, U& pdf, Sampler& sampler ) const { return apply_visitor( sample_visitor<SR, U, Sampler>(sr, refl_dir, pdf, sampler), *this ); } //------------------------------------------------------------------------------------------------- // Private variant visitors // template <typename T, typename ...Ts> struct generic_material<T, Ts...>::is_emissive_visitor { using Base = generic_material<T, Ts...>; using return_type = bool; template <typename X> VSNRAY_FUNC bool operator()(X) const { return false; } VSNRAY_FUNC bool operator()(emissive<typename Base::scalar_type>) const { return true; } }; template <typename T, typename ...Ts> struct generic_material<T, Ts...>::ambient_visitor { using Base = generic_material<T, Ts...>; using return_type = spectrum<typename Base::scalar_type>; template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.ambient(); } }; template <typename T, typename ...Ts> template <typename SR> struct generic_material<T, Ts...>::shade_visitor { using return_type = spectrum<typename SR::scalar_type>; VSNRAY_FUNC shade_visitor(SR const& sr) : sr_(sr) {} template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.shade(sr_); } SR const& sr_; }; template <typename T, typename ...Ts> template <typename SR, typename U, typename Sampler> struct generic_material<T, Ts...>::sample_visitor { using return_type = spectrum<typename SR::scalar_type>; VSNRAY_FUNC sample_visitor(SR const& sr, vector<3, U>& refl_dir, U& pdf, Sampler& sampler) : sr_(sr) , refl_dir_(refl_dir) , pdf_(pdf) , sampler_(sampler) { } template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.sample(sr_, refl_dir_, pdf_, sampler_); } SR const& sr_; vector<3, U>& refl_dir_; U& pdf_; Sampler& sampler_; }; namespace simd { //------------------------------------------------------------------------------------------------- // SIMD type used internally. Contains N generic materials // template <size_t N, typename ...Ts> class generic_material { public: using scalar_type = float_from_simd_width_t<N>; using single_material = visionaray::generic_material<Ts...>; public: VSNRAY_FUNC generic_material(array<single_material, N> const& mats) : mats_(mats) { } VSNRAY_FUNC single_material& get(int i) { return mats_[i]; } VSNRAY_FUNC single_material const& get(int i) const { return mats_[i]; } VSNRAY_FUNC mask_type_t<scalar_type> is_emissive() const { using mask_t = mask_type_t<scalar_type>; using mask_array = aligned_array_t<mask_t>; mask_array arr; for (size_t i = 0; i < N; ++i) { arr[i] = mats_[i].is_emissive(); } return mask_t(arr); } VSNRAY_FUNC spectrum<scalar_type> ambient() const { array<spectrum<float>, N> amb; for (size_t i = 0; i < N; ++i) { amb[i] = mats_[i].ambient(); } return pack(amb); } template <typename SR> VSNRAY_FUNC spectrum<scalar_type> shade(SR const& sr) const { auto srs = unpack(sr); array<spectrum<float>, N> shaded; for (size_t i = 0; i < N; ++i) { shaded[i] = mats_[i].shade(srs[i]); } return pack(shaded); } template <typename SR, typename S /* sampler */> VSNRAY_FUNC spectrum<scalar_type> sample( SR const& sr, vector<3, scalar_type>& refl_dir, scalar_type& pdf, S& samp ) const { using float_array = aligned_array_t<scalar_type>; auto srs = unpack(sr); array<vector<3, float>, N> rds; float_array pdfs; array<spectrum<float>, N> sampled; for (size_t i = 0; i < N; ++i) { sampled[i] = mats_[i].sample(srs[i], rds[i], pdfs[i], samp.get_sampler(i)); } refl_dir = pack(rds); pdf = scalar_type(pdfs); return pack(sampled); } private: array<single_material, N> mats_; }; //------------------------------------------------------------------------------------------------- // Pack and unpack // template <typename ...Ts> VSNRAY_FUNC inline generic_material<4, Ts...> pack(array<visionaray::generic_material<Ts...>, 4> const& mats) { return generic_material<4, Ts...>(mats); } template <typename ...Ts> VSNRAY_FUNC inline array<visionaray::generic_material<Ts...>, 4> unpack(generic_material<4, Ts...> const& m4) { return array<visionaray::generic_material<Ts...>, 4>{{ m4.get(0), m4.get(1), m4.get(2), m4.get(3) }}; } template <typename ...Ts> inline generic_material<8, Ts...> pack(array<visionaray::generic_material<Ts...>, 8> const& mats) { return generic_material<8, Ts...>(mats); } template <typename ...Ts> inline array<visionaray::generic_material<Ts...>, 8> unpack(generic_material<8, Ts...> const& m8) { return array<visionaray::generic_material<Ts...>, 8>{{ m8.get(0), m8.get(1), m8.get(2), m8.get(3), m8.get(4), m8.get(5), m8.get(6), m8.get(7) }}; } template <typename ...Ts> inline generic_material<16, Ts...> pack(array<visionaray::generic_material<Ts...>, 16> const& mats) { return generic_material<16, Ts...>(mats); } template <typename ...Ts> inline array<visionaray::generic_material<Ts...>, 16> unpack(generic_material<16, Ts...> const& m16) { return array<visionaray::generic_material<Ts...>, 8>{{ m16.get( 0), m16.get( 1), m16.get( 2), m16.get( 3), m16.get( 4), m16.get( 5), m16.get( 6), m16.get( 7), m16.get( 8), m16.get( 9), m16.get(10), m16.get(11), m16.get(12), m16.get(13), m16.get(14), m16.get(15) }}; } } // simd } // visionaray <|endoftext|>
<commit_before>/** * File : D.cpp * Author : Kazune Takahashi * Created : 1/12/2019, 9:15:17 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const ll infty = 1000000007; int N, Q; ll A[100010]; ll X[100010]; set<ll> S; map<ll, ll> M; ll Y[100010]; ll Z[100010]; void flush() { for (auto i = 0; i < Q; i++) { cout << M[X[i]] << endl; } } int main() { cin >> N >> Q; for (auto i = 0; i < N; i++) { cin >> A[i]; } for (auto i = 0; i < Q; i++) { cin >> X[i]; S.insert(X[i]); } reverse(A, A + N); Y[N + 1] = 0; Y[N] = 0; Y[N - 1] = A[N - 1]; Y[N - 2] = A[N - 2]; for (auto i = N - 3; i >= 0; i--) { Y[i] = A[i] + Y[i + 2]; } Z[0] = A[0]; for (auto i = 1; i < N; i++) { Z[i] = A[i] + Z[i - 1]; } auto it = S.begin(); for (auto i = N; i >= 0; i--) { int second = i / 2; int first = i - second; ll score; if (first == 0) { score = Y[0]; } else if (first == second) { score = Z[first - 1] + Y[i]; } else { score = Z[first - 1] + Y[i + 1]; } ll upper; if (second == 0) { upper = infty; } else { ll maxi = X[first - 1]; ll mini = X[first + second - 1]; cerr << "maxi = " << maxi << ", mini = " << mini << endl; upper = (maxi + mini + 1) / 2; } cerr << "i = " << i << ", upper = " << upper << endl; while (it != S.end()) { if (*it <= upper) { M[*it] = score; it++; } else { break; } } } flush(); }<commit_msg>submit D.cpp to 'D - Nearest Card Game' (aising2019) [C++14 (GCC 5.4.1)]<commit_after>/** * File : D.cpp * Author : Kazune Takahashi * Created : 1/12/2019, 9:15:17 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const ll infty = 1000000007; int N, Q; ll A[100010]; ll X[100010]; set<ll> S; map<ll, ll> M; ll Y[100010]; ll Z[100010]; void flush() { for (auto i = 0; i < Q; i++) { cout << M[X[i]] << endl; } } int main() { cin >> N >> Q; for (auto i = 0; i < N; i++) { cin >> A[i]; } for (auto i = 0; i < Q; i++) { cin >> X[i]; S.insert(X[i]); } reverse(A, A + N); Y[N + 1] = 0; Y[N] = 0; Y[N - 1] = A[N - 1]; Y[N - 2] = A[N - 2]; for (auto i = N - 3; i >= 0; i--) { Y[i] = A[i] + Y[i + 2]; } Z[0] = A[0]; for (auto i = 1; i < N; i++) { Z[i] = A[i] + Z[i - 1]; } auto it = S.begin(); for (auto i = N; i >= 0; i--) { int second = i / 2; int first = i - second; ll score; if (first == 0) { score = Y[0]; } else if (first == second) { score = Z[first - 1] + Y[i]; } else { score = Z[first - 1] + Y[i + 1]; } ll upper; if (second == 0) { upper = infty; } else { ll maxi = A[first - 1]; ll mini = A[first + second - 1]; // cerr << "maxi = " << maxi << ", mini = " << mini << endl; upper = (maxi + mini + 1) / 2; } // cerr << "i = " << i << ", upper = " << upper << endl; while (it != S.end()) { if (*it <= upper) { M[*it] = score; it++; } else { break; } } } flush(); }<|endoftext|>
<commit_before>// TODO: make cursor the fixed point of the zoom // TODO: compute area for selfintersecting polygons // TODO: polygon editing: move caption, change color, move segments (?), add points (?), delete points (?) // TODO: set scale by two points GPS coordinates // TODO: result printing // TODO: make it possible to reset selection; perhaps, it's time to use 3 modes instead of 2: normal draw, draw etalon, edit? // TODO: won't it be easier to use weak pointers (e.g., QPointers) to figures? // TODO: reduce number of digits after the decimal point #include <cassert> #include <cmath> #include <QInputDialog> #include <QLabel> #include <QPainter> #include <QPaintEvent> #include <QScrollArea> #include <QScrollBar> #include "canvaswidget.h" #include "mainwindow.h" #include "paint_utils.h" #include "shape.h" const int rulerMargin = 16; const int rulerThickness = 2; const int rulerFrameThickness = 1; const int rulerTextMargin = 3; const int rulerSerifsSize = 8; const int rulerMaxLength = 180; const int rulerMinLength = 40; const QColor rulerBodyColor = Qt::black; const QColor rulerFrameColor = Qt::white; const int maxImageSize = 4096; CanvasWidget::CanvasWidget(const QPixmap* image, MainWindow* mainWindow, QScrollArea* scrollArea, QLabel* scaleLabel, QLabel* statusLabel, QWidget* parent) : QWidget(parent), mainWindow_(mainWindow), scrollArea_(scrollArea), scaleLabel_(scaleLabel), statusLabel_(statusLabel), originalImage_(image) { acceptableScales_ << 0.01 << 0.015 << 0.02 << 0.025 << 0.03 << 0.04 << 0.05 << 0.06 << 0.07 << 0.08 << 0.09; acceptableScales_ << 0.10 << 0.12 << 0.14 << 0.17 << 0.20 << 0.23 << 0.26 << 0.30 << 0.35 << 0.40 << 0.45; acceptableScales_ << 0.50 << 0.60 << 0.70 << 0.80 << 0.90; acceptableScales_ << 1.00 << 1.25 << 1.50 << 1.75 << 2.00 << 2.50 << 3.00 << 4.00; iScale_ = acceptableScales_.indexOf(1.00); scrollArea_->viewport()->installEventFilter(this); setFocusPolicy(Qt::StrongFocus); setMouseTracking(true); shapeType_ = DEFAULT_TYPE; isDefiningEtalon_ = true; showRuler_ = false; etalonFigure_ = 0; activeFigure_ = 0; clearEtalon(); scaleChanged(); } CanvasWidget::~CanvasWidget() { delete originalImage_; } void CanvasWidget::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.setFont(mainWindow_->getInscriptionFont()); painter.setRenderHint(QPainter::Antialiasing, true); painter.drawPixmap(event->rect().topLeft(), image_, event->rect()); foreach (const Figure& figure, figures_) figure.draw(painter); if (showRuler_) drawRuler(painter, event->rect()); event->accept(); } void CanvasWidget::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Delete) { if (!selection_.isEmpty() && !selection_.figure->isEtalon()) { removeFigure(selection_.figure); updateAll(); } } else { QWidget::keyPressEvent(event); } } void CanvasWidget::mousePressEvent(QMouseEvent* event) { updateMousePos(event->pos()); if (event->buttons() == Qt::LeftButton) { selection_ = hover_; if (hover_.isEmpty()) { if (!activeFigure_) { if (isDefiningEtalon_) { clearEtalon(); removeFigure(etalonFigure_); } addActiveFigure(); } bool polygonFinished = activeFigure_->addPoint(originalPointUnderMouse_); if (polygonFinished) finishPlotting(); } updateAll(); } else if (event->buttons() == Qt::RightButton) { scrollStartPoint_ = event->globalPos(); scrollStartHValue_ = scrollArea_->horizontalScrollBar()->value(); scrollStartVValue_ = scrollArea_->verticalScrollBar() ->value(); } event->accept(); } void CanvasWidget::mouseReleaseEvent(QMouseEvent* /*event*/) { updateHover(); } void CanvasWidget::mouseMoveEvent(QMouseEvent* event) { if (event->buttons() == Qt::NoButton) { updateMousePos(event->pos()); updateAll(); } else if (event->buttons() == Qt::LeftButton) { updateMousePos(event->pos()); selection_.dragTo(originalPointUnderMouse_); if (!selection_.isEmpty() && selection_.figure->isEtalon()) defineEtalon(selection_.figure); updateAll(); } else if (event->buttons() == Qt::RightButton) { QPoint scrollBy = scrollStartPoint_ - event->globalPos(); scrollArea_->horizontalScrollBar()->setValue(scrollStartHValue_ + scrollBy.x()); scrollArea_->verticalScrollBar() ->setValue(scrollStartVValue_ + scrollBy.y()); } event->accept(); } // TODO: deal with case when double-click is the first click void CanvasWidget::mouseDoubleClickEvent(QMouseEvent* event) { if (event->buttons() == Qt::LeftButton) finishPlotting(); event->accept(); } bool CanvasWidget::eventFilter(QObject* object, QEvent* event__) { if (object == scrollArea_->viewport() && event__->type() == QEvent::Wheel) { QWheelEvent* event = static_cast<QWheelEvent*>(event__); int numSteps = event->delta() / 120; iScale_ = qBound(0, iScale_ + numSteps, acceptableScales_.size() - 1); int size = qMax(originalImage_->width(), originalImage_->height()); while (size * acceptableScales_[iScale_] > maxImageSize && acceptableScales_[iScale_] > 1.) iScale_--; scaleChanged(); return true; } return false; } void CanvasWidget::setMode(ShapeType newMode) { shapeType_ = newMode; resetAll(); } bool CanvasWidget::hasEtalon() const { return originalMetersPerPixel_ > 0.; } QPixmap CanvasWidget::getModifiedImage() { int oldIScale = iScale_; iScale_ = acceptableScales_.indexOf(1.00); scaleChanged(); QPixmap resultingImage(size()); render(&resultingImage); iScale_ = oldIScale; scaleChanged(); return resultingImage; } void CanvasWidget::toggleEtalonDefinition(bool isDefiningEtalon) { if (isDefiningEtalon_ == isDefiningEtalon) return; isDefiningEtalon_ = isDefiningEtalon; resetAll(); } void CanvasWidget::toggleRuler(bool showRuler) { if (showRuler_ == showRuler) return; showRuler_ = showRuler; update(); } void CanvasWidget::addActiveFigure() { assert(!activeFigure_); figures_.append(Figure(shapeType_, isDefiningEtalon_, this)); activeFigure_ = &figures_.last(); } void CanvasWidget::removeFigure(const Figure* figure) { if (!figure) return; if (etalonFigure_ == figure) etalonFigure_ = 0; if (activeFigure_ == figure) activeFigure_ = 0; if (selection_.figure == figure) selection_.reset(); if (hover_.figure == figure) hover_.reset(); bool erased = false; for (auto it = figures_.begin(); it != figures_.end(); ++it) { if (&(*it) == figure) { figures_.erase(it); erased = true; break; } } assert(erased); } void CanvasWidget::drawRuler(QPainter& painter, const QRect& rect) { int maxLength = qMin(rulerMaxLength, rect.width() - 2 * rulerMargin); if (!hasEtalon() || maxLength < rulerMinLength) return; double pixelLengthF; double metersLength; double base = 1e10; while (base > 1e-10) { if ((pixelLengthF = (metersLength = base * 5.) / metersPerPixel_) < maxLength) break; if ((pixelLengthF = (metersLength = base * 2.) / metersPerPixel_) < maxLength) break; if ((pixelLengthF = (metersLength = base * 1.) / metersPerPixel_) < maxLength) break; base /= 10.; } int pixelLength = pixelLengthF; QList<QRect> ruler; int rulerLeft = rect.left() + rulerMargin; int rulerY = rect.bottom() - rulerMargin; ruler.append(QRect(rulerLeft, rulerY - rulerThickness / 2, pixelLength, rulerThickness)); ruler.append(QRect(rulerLeft - rulerThickness, rulerY - rulerSerifsSize / 2, rulerThickness, rulerSerifsSize)); ruler.append(QRect(rulerLeft + pixelLength , rulerY - rulerSerifsSize / 2, rulerThickness, rulerSerifsSize)); drawFramed(painter, ruler, rulerFrameThickness, rulerBodyColor, rulerFrameColor); QString rulerLabel = QString::number(metersLength) + " " + linearUnitSuffix; QPoint labelPos(rulerLeft + rulerFrameThickness + rulerTextMargin, rulerY - rulerThickness / 2 - rulerFrameThickness - rulerTextMargin - painter.fontMetrics().descent()); drawTextWithBackground(painter, rulerLabel, labelPos); } void CanvasWidget::updateMousePos(QPoint mousePos) { pointUnderMouse_ = mousePos; originalPointUnderMouse_ = pointUnderMouse_ / scale_; } void CanvasWidget::updateHover() { Selection newHover; if (activeFigure_) { newHover.reset(); } else { SelectionFinder selectionFinder(pointUnderMouse_); for (auto it = figures_.begin(); it != figures_.end(); ++it) if (it->isFinished()) it->testSelection(selectionFinder); newHover = selectionFinder.bestSelection(); } if (hover_ != newHover) { hover_ = newHover; update(); } } void CanvasWidget::updateStatus() { QString statusString; if (activeFigure_) statusString = activeFigure_->statusString(); else if (!selection_.isEmpty()) statusString = selection_.figure->statusString(); statusLabel_->setText(statusString); } void CanvasWidget::defineEtalon(Figure* newEtalonFigure) { assert(newEtalonFigure && newEtalonFigure->isFinished()); bool isResizing = (etalonFigure_ == newEtalonFigure); etalonFigure_ = newEtalonFigure; const Shape originalShapeDrawn = newEtalonFigure->originalShape(); double originalEtalonPixelLength = 0.; QString prompt; switch (originalShapeDrawn.dimensionality()) { case SHAPE_1D: originalEtalonPixelLength = originalShapeDrawn.length(); prompt = QString::fromUtf8("Укажите длину эталона (%1): ").arg(linearUnitSuffix); break; case SHAPE_2D: originalEtalonPixelLength = std::sqrt(originalShapeDrawn.area()); prompt = QString::fromUtf8("Укажите площадь эталона (%1): ").arg(squareUnitSuffix); break; } bool userInputIsOk = true; if (!isResizing) etalonMetersSize_ = QInputDialog::getDouble(this, mainWindow_->appName(), prompt, 1., 0.001, 1e9, 3, &userInputIsOk); if (originalShapeDrawn.isValid() && originalEtalonPixelLength > 0. && userInputIsOk) { double etalonMetersLength; switch (originalShapeDrawn.dimensionality()) { case SHAPE_1D: etalonMetersLength = etalonMetersSize_; break; case SHAPE_2D: etalonMetersLength = std::sqrt(etalonMetersSize_); break; } originalMetersPerPixel_ = etalonMetersLength / originalEtalonPixelLength; metersPerPixel_ = originalMetersPerPixel_ / scale_; } else { clearEtalon(true); } if (!isResizing) mainWindow_->toggleEtalonDefinition(false); } void CanvasWidget::clearEtalon(bool invalidateOnly) { if (!invalidateOnly) etalonMetersSize_ = 0; originalMetersPerPixel_ = 0.; metersPerPixel_ = 0.; } void CanvasWidget::finishPlotting() { assert(activeFigure_); activeFigure_->finish(); Figure *oldActiveFigure = activeFigure_; activeFigure_ = 0; if (isDefiningEtalon_) defineEtalon(oldActiveFigure); selection_.setFigure(oldActiveFigure); updateAll(); } void CanvasWidget::resetAll() { removeFigure(activeFigure_); updateAll(); } void CanvasWidget::scaleChanged() { scale_ = acceptableScales_[iScale_]; image_ = originalImage_->scaled(originalImage_->size() * scale_, Qt::KeepAspectRatio, Qt::SmoothTransformation); metersPerPixel_ = originalMetersPerPixel_ / scale_; setFixedSize(image_.size()); scaleLabel_->setText(QString::number(scale_ * 100.) + "%"); updateAll(); } void CanvasWidget::updateAll() { updateHover(); updateStatus(); update(); } <commit_msg>Do not allow to move points outside the picture<commit_after>// TODO: make cursor the fixed point of the zoom // TODO: compute area for selfintersecting polygons // TODO: polygon editing: move caption, change color, move segments (?), add points (?), delete points (?) // TODO: set scale by two points GPS coordinates // TODO: result printing // TODO: make it possible to reset selection; perhaps, it's time to use 3 modes instead of 2: normal draw, draw etalon, edit? // TODO: won't it be easier to use weak pointers (e.g., QPointers) to figures? // TODO: reduce number of digits after the decimal point #include <cassert> #include <cmath> #include <QInputDialog> #include <QLabel> #include <QPainter> #include <QPaintEvent> #include <QScrollArea> #include <QScrollBar> #include "canvaswidget.h" #include "mainwindow.h" #include "paint_utils.h" #include "shape.h" const int rulerMargin = 16; const int rulerThickness = 2; const int rulerFrameThickness = 1; const int rulerTextMargin = 3; const int rulerSerifsSize = 8; const int rulerMaxLength = 180; const int rulerMinLength = 40; const QColor rulerBodyColor = Qt::black; const QColor rulerFrameColor = Qt::white; const int maxImageSize = 4096; CanvasWidget::CanvasWidget(const QPixmap* image, MainWindow* mainWindow, QScrollArea* scrollArea, QLabel* scaleLabel, QLabel* statusLabel, QWidget* parent) : QWidget(parent), mainWindow_(mainWindow), scrollArea_(scrollArea), scaleLabel_(scaleLabel), statusLabel_(statusLabel), originalImage_(image) { acceptableScales_ << 0.01 << 0.015 << 0.02 << 0.025 << 0.03 << 0.04 << 0.05 << 0.06 << 0.07 << 0.08 << 0.09; acceptableScales_ << 0.10 << 0.12 << 0.14 << 0.17 << 0.20 << 0.23 << 0.26 << 0.30 << 0.35 << 0.40 << 0.45; acceptableScales_ << 0.50 << 0.60 << 0.70 << 0.80 << 0.90; acceptableScales_ << 1.00 << 1.25 << 1.50 << 1.75 << 2.00 << 2.50 << 3.00 << 4.00; iScale_ = acceptableScales_.indexOf(1.00); scrollArea_->viewport()->installEventFilter(this); setFocusPolicy(Qt::StrongFocus); setMouseTracking(true); shapeType_ = DEFAULT_TYPE; isDefiningEtalon_ = true; showRuler_ = false; etalonFigure_ = 0; activeFigure_ = 0; clearEtalon(); scaleChanged(); } CanvasWidget::~CanvasWidget() { delete originalImage_; } void CanvasWidget::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.setFont(mainWindow_->getInscriptionFont()); painter.setRenderHint(QPainter::Antialiasing, true); painter.drawPixmap(event->rect().topLeft(), image_, event->rect()); foreach (const Figure& figure, figures_) figure.draw(painter); if (showRuler_) drawRuler(painter, event->rect()); event->accept(); } void CanvasWidget::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Delete) { if (!selection_.isEmpty() && !selection_.figure->isEtalon()) { removeFigure(selection_.figure); updateAll(); } } else { QWidget::keyPressEvent(event); } } void CanvasWidget::mousePressEvent(QMouseEvent* event) { updateMousePos(event->pos()); if (event->buttons() == Qt::LeftButton) { selection_ = hover_; if (hover_.isEmpty()) { if (!activeFigure_) { if (isDefiningEtalon_) { clearEtalon(); removeFigure(etalonFigure_); } addActiveFigure(); } bool polygonFinished = activeFigure_->addPoint(originalPointUnderMouse_); if (polygonFinished) finishPlotting(); } updateAll(); } else if (event->buttons() == Qt::RightButton) { scrollStartPoint_ = event->globalPos(); scrollStartHValue_ = scrollArea_->horizontalScrollBar()->value(); scrollStartVValue_ = scrollArea_->verticalScrollBar() ->value(); } event->accept(); } void CanvasWidget::mouseReleaseEvent(QMouseEvent* /*event*/) { updateHover(); } void CanvasWidget::mouseMoveEvent(QMouseEvent* event) { if (event->buttons() == Qt::NoButton) { updateMousePos(event->pos()); updateAll(); } else if (event->buttons() == Qt::LeftButton) { updateMousePos(event->pos()); selection_.dragTo(originalPointUnderMouse_); if (!selection_.isEmpty() && selection_.figure->isEtalon()) defineEtalon(selection_.figure); updateAll(); } else if (event->buttons() == Qt::RightButton) { QPoint scrollBy = scrollStartPoint_ - event->globalPos(); scrollArea_->horizontalScrollBar()->setValue(scrollStartHValue_ + scrollBy.x()); scrollArea_->verticalScrollBar() ->setValue(scrollStartVValue_ + scrollBy.y()); } event->accept(); } // TODO: deal with case when double-click is the first click void CanvasWidget::mouseDoubleClickEvent(QMouseEvent* event) { if (event->buttons() == Qt::LeftButton) finishPlotting(); event->accept(); } bool CanvasWidget::eventFilter(QObject* object, QEvent* event__) { if (object == scrollArea_->viewport() && event__->type() == QEvent::Wheel) { QWheelEvent* event = static_cast<QWheelEvent*>(event__); int numSteps = event->delta() / 120; iScale_ = qBound(0, iScale_ + numSteps, acceptableScales_.size() - 1); int size = qMax(originalImage_->width(), originalImage_->height()); while (size * acceptableScales_[iScale_] > maxImageSize && acceptableScales_[iScale_] > 1.) iScale_--; scaleChanged(); return true; } return false; } void CanvasWidget::setMode(ShapeType newMode) { shapeType_ = newMode; resetAll(); } bool CanvasWidget::hasEtalon() const { return originalMetersPerPixel_ > 0.; } QPixmap CanvasWidget::getModifiedImage() { int oldIScale = iScale_; iScale_ = acceptableScales_.indexOf(1.00); scaleChanged(); QPixmap resultingImage(size()); render(&resultingImage); iScale_ = oldIScale; scaleChanged(); return resultingImage; } void CanvasWidget::toggleEtalonDefinition(bool isDefiningEtalon) { if (isDefiningEtalon_ == isDefiningEtalon) return; isDefiningEtalon_ = isDefiningEtalon; resetAll(); } void CanvasWidget::toggleRuler(bool showRuler) { if (showRuler_ == showRuler) return; showRuler_ = showRuler; update(); } void CanvasWidget::addActiveFigure() { assert(!activeFigure_); figures_.append(Figure(shapeType_, isDefiningEtalon_, this)); activeFigure_ = &figures_.last(); } void CanvasWidget::removeFigure(const Figure* figure) { if (!figure) return; if (etalonFigure_ == figure) etalonFigure_ = 0; if (activeFigure_ == figure) activeFigure_ = 0; if (selection_.figure == figure) selection_.reset(); if (hover_.figure == figure) hover_.reset(); bool erased = false; for (auto it = figures_.begin(); it != figures_.end(); ++it) { if (&(*it) == figure) { figures_.erase(it); erased = true; break; } } assert(erased); } void CanvasWidget::drawRuler(QPainter& painter, const QRect& rect) { int maxLength = qMin(rulerMaxLength, rect.width() - 2 * rulerMargin); if (!hasEtalon() || maxLength < rulerMinLength) return; double pixelLengthF; double metersLength; double base = 1e10; while (base > 1e-10) { if ((pixelLengthF = (metersLength = base * 5.) / metersPerPixel_) < maxLength) break; if ((pixelLengthF = (metersLength = base * 2.) / metersPerPixel_) < maxLength) break; if ((pixelLengthF = (metersLength = base * 1.) / metersPerPixel_) < maxLength) break; base /= 10.; } int pixelLength = pixelLengthF; QList<QRect> ruler; int rulerLeft = rect.left() + rulerMargin; int rulerY = rect.bottom() - rulerMargin; ruler.append(QRect(rulerLeft, rulerY - rulerThickness / 2, pixelLength, rulerThickness)); ruler.append(QRect(rulerLeft - rulerThickness, rulerY - rulerSerifsSize / 2, rulerThickness, rulerSerifsSize)); ruler.append(QRect(rulerLeft + pixelLength , rulerY - rulerSerifsSize / 2, rulerThickness, rulerSerifsSize)); drawFramed(painter, ruler, rulerFrameThickness, rulerBodyColor, rulerFrameColor); QString rulerLabel = QString::number(metersLength) + " " + linearUnitSuffix; QPoint labelPos(rulerLeft + rulerFrameThickness + rulerTextMargin, rulerY - rulerThickness / 2 - rulerFrameThickness - rulerTextMargin - painter.fontMetrics().descent()); drawTextWithBackground(painter, rulerLabel, labelPos); } void CanvasWidget::updateMousePos(QPoint mousePos) { mousePos.setX(qBound(0, mousePos.x(), image_.width())); mousePos.setY(qBound(0, mousePos.y(), image_.height())); pointUnderMouse_ = mousePos; originalPointUnderMouse_ = pointUnderMouse_ / scale_; } void CanvasWidget::updateHover() { Selection newHover; if (activeFigure_) { newHover.reset(); } else { SelectionFinder selectionFinder(pointUnderMouse_); for (auto it = figures_.begin(); it != figures_.end(); ++it) if (it->isFinished()) it->testSelection(selectionFinder); newHover = selectionFinder.bestSelection(); } if (hover_ != newHover) { hover_ = newHover; update(); } } void CanvasWidget::updateStatus() { QString statusString; if (activeFigure_) statusString = activeFigure_->statusString(); else if (!selection_.isEmpty()) statusString = selection_.figure->statusString(); statusLabel_->setText(statusString); } void CanvasWidget::defineEtalon(Figure* newEtalonFigure) { assert(newEtalonFigure && newEtalonFigure->isFinished()); bool isResizing = (etalonFigure_ == newEtalonFigure); etalonFigure_ = newEtalonFigure; const Shape originalShapeDrawn = newEtalonFigure->originalShape(); double originalEtalonPixelLength = 0.; QString prompt; switch (originalShapeDrawn.dimensionality()) { case SHAPE_1D: originalEtalonPixelLength = originalShapeDrawn.length(); prompt = QString::fromUtf8("Укажите длину эталона (%1): ").arg(linearUnitSuffix); break; case SHAPE_2D: originalEtalonPixelLength = std::sqrt(originalShapeDrawn.area()); prompt = QString::fromUtf8("Укажите площадь эталона (%1): ").arg(squareUnitSuffix); break; } bool userInputIsOk = true; if (!isResizing) etalonMetersSize_ = QInputDialog::getDouble(this, mainWindow_->appName(), prompt, 1., 0.001, 1e9, 3, &userInputIsOk); if (originalShapeDrawn.isValid() && originalEtalonPixelLength > 0. && userInputIsOk) { double etalonMetersLength; switch (originalShapeDrawn.dimensionality()) { case SHAPE_1D: etalonMetersLength = etalonMetersSize_; break; case SHAPE_2D: etalonMetersLength = std::sqrt(etalonMetersSize_); break; } originalMetersPerPixel_ = etalonMetersLength / originalEtalonPixelLength; metersPerPixel_ = originalMetersPerPixel_ / scale_; } else { clearEtalon(true); } if (!isResizing) mainWindow_->toggleEtalonDefinition(false); } void CanvasWidget::clearEtalon(bool invalidateOnly) { if (!invalidateOnly) etalonMetersSize_ = 0; originalMetersPerPixel_ = 0.; metersPerPixel_ = 0.; } void CanvasWidget::finishPlotting() { assert(activeFigure_); activeFigure_->finish(); Figure *oldActiveFigure = activeFigure_; activeFigure_ = 0; if (isDefiningEtalon_) defineEtalon(oldActiveFigure); selection_.setFigure(oldActiveFigure); updateAll(); } void CanvasWidget::resetAll() { removeFigure(activeFigure_); updateAll(); } void CanvasWidget::scaleChanged() { scale_ = acceptableScales_[iScale_]; image_ = originalImage_->scaled(originalImage_->size() * scale_, Qt::KeepAspectRatio, Qt::SmoothTransformation); metersPerPixel_ = originalMetersPerPixel_ / scale_; setFixedSize(image_.size()); scaleLabel_->setText(QString::number(scale_ * 100.) + "%"); updateAll(); } void CanvasWidget::updateAll() { updateHover(); updateStatus(); update(); } <|endoftext|>
<commit_before>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/instantiate.h" #include "library/trace.h" #include "library/num.h" #include "library/string.h" #include "library/pp_options.h" #include "library/tactic/tactic_state.h" #include "library/tactic/cases_tactic.h" #include "library/equations_compiler/equations.h" #include "library/equations_compiler/util.h" namespace lean { #define trace_match(Code) lean_trace(name({"eqn_compiler", "elim_match"}), Code) struct elim_match_fn { environment m_env; options m_opts; metavar_context m_mctx; elim_match_fn(environment const & env, options const & opts, metavar_context const & mctx): m_env(env), m_opts(opts), m_mctx(mctx) {} struct equation { list<pair<name, name>> m_renames; local_context m_lctx; list<expr> m_patterns; expr m_rhs; expr m_ref; /* for reporting errors */ unsigned m_idx; }; struct program { name m_fn_name; /* for debugging purposes */ /* Metavariable containing the context for the program */ expr m_goal; /* Variables that still need to be matched/processed */ list<name> m_var_stack; list<equation> m_equations; }; type_context mk_type_context(local_context const & lctx) { return mk_type_context_for(m_env, m_opts, m_mctx, lctx); } format nest(format const & fmt) const { return ::lean::nest(get_pp_indent(m_opts), fmt); } unsigned get_arity(local_context const & lctx, expr const & e) { /* Naive way to retrieve the arity of the function being defined */ lean_assert(is_equations(e)); type_context ctx = mk_type_context(lctx); unpack_eqns ues(ctx, e); return ues.get_arity_of(0); } bool is_constructor(expr const & e) const { return static_cast<bool>(eqns_env_interface(m_env).is_constructor(e)); } bool is_constructor_app(expr const & e) const { return is_constructor(get_app_fn(e)); } bool is_value(expr const & e) const { return to_num(e) || to_char(e) || to_string(e) || is_constructor(e); } expr whnf_pattern(type_context & ctx, expr const & e) { return ctx.whnf_pred(e, [&](expr const & e) { return !is_constructor_app(e) && !is_value(e); }); } pair<expr, list<name>> mk_main_goal(local_context lctx, expr fn_type, unsigned arity) { type_context ctx = mk_type_context(lctx); buffer<name> vars; name x("_x"); for (unsigned i = 0; i < arity; i++) { fn_type = ctx.whnf(fn_type); if (!is_pi(fn_type)) throw_ill_formed_eqns(); expr var = ctx.push_local(x.append_after(i+1), binding_domain(fn_type)); vars.push_back(mlocal_name(var)); fn_type = instantiate(binding_body(fn_type), var); } m_mctx = ctx.mctx(); expr m = m_mctx.mk_metavar_decl(ctx.lctx(), fn_type); return mk_pair(m, to_list(vars)); } optional<equation> mk_equation(local_context const & lctx, expr const & eqn, unsigned idx) { expr it = eqn; it = binding_body(it); /* consume fn header */ if (is_no_equation(it)) return optional<equation>(); type_context ctx = mk_type_context(lctx); buffer<expr> locals; while (is_lambda(it)) { expr type = instantiate_rev(binding_domain(it), locals); expr local = ctx.push_local(binding_name(it), type); locals.push_back(local); it = binding_body(it); } lean_assert(is_equation(it)); equation E; E.m_lctx = ctx.lctx(); E.m_rhs = instantiate_rev(equation_rhs(it), locals); /* The function being defined is not recursive. So, E.m_rhs must be closed even if we "consumed" the fn header in the beginning of the method. */ lean_assert(closed(E.m_rhs)); buffer<expr> patterns; get_app_args(equation_lhs(it), patterns); for (expr & p : patterns) { p = whnf_pattern(ctx, instantiate_rev(p, locals)); } E.m_patterns = to_list(patterns); E.m_ref = eqn; E.m_idx = idx; return optional<equation>(E); } list<equation> mk_equations(local_context const & lctx, buffer<expr> const & eqns) { buffer<equation> R; unsigned idx = 0; for (expr const & eqn : eqns) { if (auto r = mk_equation(lctx, eqn, idx)) { R.push_back(*r); lean_assert(length(R[0].m_patterns) == length(r->m_patterns)); } else { lean_assert(eqns.size() == 1); return list<equation>(); } idx++; } return to_list(R); } program mk_program(local_context const & lctx, expr const & e) { lean_assert(is_equations(e)); buffer<expr> eqns; to_equations(e, eqns); unsigned arity = get_arity(lctx, e); program P; P.m_fn_name = binding_name(eqns[0]); expr fn_type = binding_domain(eqns[0]); std::tie(P.m_goal, P.m_var_stack) = mk_main_goal(lctx, fn_type, arity); P.m_equations = mk_equations(lctx, eqns); return P; } format pp_equation(equation const & eqn) { format r; auto pp = mk_pp_ctx(m_env, m_opts, m_mctx, eqn.m_lctx); bool first = true; for (expr const & p : eqn.m_patterns) { if (first) first = false; else r += format(" "); r += paren(pp(p)); } r += space() + format(":=") + nest(line() + pp(eqn.m_rhs)); return group(r); } format pp_program(program const & P) { format r; r += format("program") + space() + format(P.m_fn_name); metavar_decl mdecl = *m_mctx.get_metavar_decl(P.m_goal); local_context lctx = mdecl.get_context(); auto pp = mk_pp_ctx(m_env, m_opts, m_mctx, lctx); format vstack; for (name const & x : P.m_var_stack) { local_decl x_decl = *lctx.get_local_decl(x); vstack += line() + paren(format(x_decl.get_pp_name()) + space() + colon() + space() + pp(x_decl.get_type())); } r += group(nest(vstack)); for (equation const & eqn : P.m_equations) { r += nest(line() + pp_equation(eqn)); } return r; } template<typename Pred> bool all_next_pattern(program const & P, Pred && p) const { for (equation const & eqn : P.m_equations) { lean_assert(eqn.m_patterns); if (!p(head(eqn.m_patterns))) return false; } return true; } /* Return true iff the next pattern in all equations is a variable. */ bool is_variable_transition(program const & P) const { return all_next_pattern(P, is_local); } /* Return true iff the next pattern in all equations is an inaccessible term. */ bool is_inaccessible_transition(program const & P) const { return all_next_pattern(P, is_inaccessible); } /* Return true iff the next pattern in all equations is a constructor. */ bool is_constructor_transition(program const & P) const { return all_next_pattern(P, [&](expr const & p) { return is_constructor_app(p); }); } /* Return true iff the next pattern of every equation is a constructor or variable, and there are at least one equation where it is a variable and another where it is a constructor. */ bool is_complete_transition(program const & P) const { bool has_variable = false; bool has_constructor = false; bool r = all_next_pattern(P, [&](expr const & p) { if (is_local(p)) { has_variable = true; return true; } else if (is_constructor_app(p)) { has_constructor = true; return true; } else { return false; } }); return r && has_variable && has_constructor; } /* Return true iff the equations are of the form v_1 ... := ... ... v_n ... := ... x_1 ... := ... ... x_m ... := ... where v_i's are values and x_j's are variables. This transition is used to compile patterns containing numerals, characters, strings and enumeration types. It is much more efficient than using complete_transition followed by constructor_transition. This optimization addresses issue #1089 raised by Jared Roesch. */ bool is_value_transition(program const & P) const { bool found_value = false; bool found_var = false; for (equation const & eqn : P.m_equations) { lean_assert(eqn.m_patterns); expr const & p = head(eqn.m_patterns); if (is_value(p)) { found_value = true; if (found_var) return false; } if (is_local(p)) { found_var = true; } else { return false; } } return found_value && found_var; } expr operator()(local_context const & lctx, expr const & eqns) { lean_assert(equations_num_fns(eqns) == 1); DEBUG_CODE({ type_context ctx = mk_type_context(lctx); lean_assert(!is_recursive_eqns(ctx, eqns)); }); program P = mk_program(lctx, eqns); trace_match(tout() << "processing:\n" << pp_program(P) << "\n";); lean_unreachable(); } }; expr elim_match(environment & env, options const & opts, metavar_context & mctx, local_context const & lctx, expr const & eqns) { return elim_match_fn(env, opts, mctx)(lctx, eqns); } void initialize_elim_match() { register_trace_class({"eqn_compiler", "elim_match"}); } void finalize_elim_match() { } } <commit_msg>fix(library/equations_compiler/elim_match): cover more cases in value transition<commit_after>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/instantiate.h" #include "library/trace.h" #include "library/num.h" #include "library/string.h" #include "library/pp_options.h" #include "library/tactic/tactic_state.h" #include "library/tactic/cases_tactic.h" #include "library/equations_compiler/equations.h" #include "library/equations_compiler/util.h" namespace lean { #define trace_match(Code) lean_trace(name({"eqn_compiler", "elim_match"}), Code) struct elim_match_fn { environment m_env; options m_opts; metavar_context m_mctx; elim_match_fn(environment const & env, options const & opts, metavar_context const & mctx): m_env(env), m_opts(opts), m_mctx(mctx) {} struct equation { list<pair<name, name>> m_renames; local_context m_lctx; list<expr> m_patterns; expr m_rhs; expr m_ref; /* for reporting errors */ unsigned m_idx; }; struct program { name m_fn_name; /* for debugging purposes */ /* Metavariable containing the context for the program */ expr m_goal; /* Variables that still need to be matched/processed */ list<name> m_var_stack; list<equation> m_equations; }; type_context mk_type_context(local_context const & lctx) { return mk_type_context_for(m_env, m_opts, m_mctx, lctx); } format nest(format const & fmt) const { return ::lean::nest(get_pp_indent(m_opts), fmt); } unsigned get_arity(local_context const & lctx, expr const & e) { /* Naive way to retrieve the arity of the function being defined */ lean_assert(is_equations(e)); type_context ctx = mk_type_context(lctx); unpack_eqns ues(ctx, e); return ues.get_arity_of(0); } bool is_constructor(expr const & e) const { return static_cast<bool>(eqns_env_interface(m_env).is_constructor(e)); } bool is_constructor_app(expr const & e) const { return is_constructor(get_app_fn(e)); } bool is_value(expr const & e) const { return to_num(e) || to_char(e) || to_string(e) || is_constructor(e); } expr whnf_pattern(type_context & ctx, expr const & e) { return ctx.whnf_pred(e, [&](expr const & e) { return !is_constructor_app(e) && !is_value(e); }); } pair<expr, list<name>> mk_main_goal(local_context lctx, expr fn_type, unsigned arity) { type_context ctx = mk_type_context(lctx); buffer<name> vars; name x("_x"); for (unsigned i = 0; i < arity; i++) { fn_type = ctx.whnf(fn_type); if (!is_pi(fn_type)) throw_ill_formed_eqns(); expr var = ctx.push_local(x.append_after(i+1), binding_domain(fn_type)); vars.push_back(mlocal_name(var)); fn_type = instantiate(binding_body(fn_type), var); } m_mctx = ctx.mctx(); expr m = m_mctx.mk_metavar_decl(ctx.lctx(), fn_type); return mk_pair(m, to_list(vars)); } optional<equation> mk_equation(local_context const & lctx, expr const & eqn, unsigned idx) { expr it = eqn; it = binding_body(it); /* consume fn header */ if (is_no_equation(it)) return optional<equation>(); type_context ctx = mk_type_context(lctx); buffer<expr> locals; while (is_lambda(it)) { expr type = instantiate_rev(binding_domain(it), locals); expr local = ctx.push_local(binding_name(it), type); locals.push_back(local); it = binding_body(it); } lean_assert(is_equation(it)); equation E; E.m_lctx = ctx.lctx(); E.m_rhs = instantiate_rev(equation_rhs(it), locals); /* The function being defined is not recursive. So, E.m_rhs must be closed even if we "consumed" the fn header in the beginning of the method. */ lean_assert(closed(E.m_rhs)); buffer<expr> patterns; get_app_args(equation_lhs(it), patterns); for (expr & p : patterns) { p = whnf_pattern(ctx, instantiate_rev(p, locals)); } E.m_patterns = to_list(patterns); E.m_ref = eqn; E.m_idx = idx; return optional<equation>(E); } list<equation> mk_equations(local_context const & lctx, buffer<expr> const & eqns) { buffer<equation> R; unsigned idx = 0; for (expr const & eqn : eqns) { if (auto r = mk_equation(lctx, eqn, idx)) { R.push_back(*r); lean_assert(length(R[0].m_patterns) == length(r->m_patterns)); } else { lean_assert(eqns.size() == 1); return list<equation>(); } idx++; } return to_list(R); } program mk_program(local_context const & lctx, expr const & e) { lean_assert(is_equations(e)); buffer<expr> eqns; to_equations(e, eqns); unsigned arity = get_arity(lctx, e); program P; P.m_fn_name = binding_name(eqns[0]); expr fn_type = binding_domain(eqns[0]); std::tie(P.m_goal, P.m_var_stack) = mk_main_goal(lctx, fn_type, arity); P.m_equations = mk_equations(lctx, eqns); return P; } format pp_equation(equation const & eqn) { format r; auto pp = mk_pp_ctx(m_env, m_opts, m_mctx, eqn.m_lctx); bool first = true; for (expr const & p : eqn.m_patterns) { if (first) first = false; else r += format(" "); r += paren(pp(p)); } r += space() + format(":=") + nest(line() + pp(eqn.m_rhs)); return group(r); } format pp_program(program const & P) { format r; r += format("program") + space() + format(P.m_fn_name); metavar_decl mdecl = *m_mctx.get_metavar_decl(P.m_goal); local_context lctx = mdecl.get_context(); auto pp = mk_pp_ctx(m_env, m_opts, m_mctx, lctx); format vstack; for (name const & x : P.m_var_stack) { local_decl x_decl = *lctx.get_local_decl(x); vstack += line() + paren(format(x_decl.get_pp_name()) + space() + colon() + space() + pp(x_decl.get_type())); } r += group(nest(vstack)); for (equation const & eqn : P.m_equations) { r += nest(line() + pp_equation(eqn)); } return r; } template<typename Pred> bool all_next_pattern(program const & P, Pred && p) const { for (equation const & eqn : P.m_equations) { lean_assert(eqn.m_patterns); if (!p(head(eqn.m_patterns))) return false; } return true; } /* Return true iff the next pattern in all equations is a variable. */ bool is_variable_transition(program const & P) const { return all_next_pattern(P, is_local); } /* Return true iff the next pattern in all equations is an inaccessible term. */ bool is_inaccessible_transition(program const & P) const { return all_next_pattern(P, is_inaccessible); } /* Return true iff the next pattern in all equations is a constructor. */ bool is_constructor_transition(program const & P) const { return all_next_pattern(P, [&](expr const & p) { return is_constructor_app(p); }); } /* Return true iff the next pattern of every equation is a constructor or variable, and there are at least one equation where it is a variable and another where it is a constructor. */ bool is_complete_transition(program const & P) const { bool has_variable = false; bool has_constructor = false; bool r = all_next_pattern(P, [&](expr const & p) { if (is_local(p)) { has_variable = true; return true; } else if (is_constructor_app(p)) { has_constructor = true; return true; } else { return false; } }); return r && has_variable && has_constructor; } /* Return true iff the next pattern of every equation is a value or variable, and there are at least one equation where it is a variable and another where it is a value. */ bool is_value_transition(program const & P) const { bool has_value = false; bool has_variable = false; bool r = all_next_pattern(P, [&](expr const & p) { if (is_local(p)) { has_variable = true; return true; } else if (is_value(p)) { has_value = true; return true; } else { return false; } }); return r && has_value && has_variable; } expr operator()(local_context const & lctx, expr const & eqns) { lean_assert(equations_num_fns(eqns) == 1); DEBUG_CODE({ type_context ctx = mk_type_context(lctx); lean_assert(!is_recursive_eqns(ctx, eqns)); }); program P = mk_program(lctx, eqns); trace_match(tout() << "processing:\n" << pp_program(P) << "\n";); lean_unreachable(); } }; expr elim_match(environment & env, options const & opts, metavar_context & mctx, local_context const & lctx, expr const & eqns) { return elim_match_fn(env, opts, mctx)(lctx, eqns); } void initialize_elim_match() { register_trace_class({"eqn_compiler", "elim_match"}); } void finalize_elim_match() { } } <|endoftext|>
<commit_before>/** * @file llinventoryitemslist.cpp * @brief A list of inventory items represented by LLFlatListView. * * Class LLInventoryItemsList implements a flat list of inventory items. * Class LLPanelInventoryListItem displays inventory item as an element * of LLInventoryItemsList. * * $LicenseInfo:firstyear=2010&license=viewergpl$ * * Copyright (c) 2010, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llinventoryitemslist.h" // llcommon #include "llcommonutils.h" // llui #include "lliconctrl.h" #include "lltextutil.h" #include "llcallbacklist.h" #include "llinventoryfunctions.h" #include "llinventorymodel.h" #include "lltrans.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// static const S32 WIDGET_SPACING = 3; LLPanelInventoryListItemBase* LLPanelInventoryListItemBase::create(LLViewerInventoryItem* item) { LLPanelInventoryListItemBase* list_item = NULL; if (item) { list_item = new LLPanelInventoryListItemBase(item); list_item->init(); } return list_item; } void LLPanelInventoryListItemBase::draw() { if (getNeedsRefresh()) { updateItem(); setNeedsRefresh(false); } LLPanel::draw(); } void LLPanelInventoryListItemBase::updateItem() { setIconImage(mIconImage); setTitle(mItem->getName(), mHighlightedText); } void LLPanelInventoryListItemBase::addWidgetToLeftSide(const std::string& name, bool show_widget/* = true*/) { LLUICtrl* ctrl = findChild<LLUICtrl>(name); if(ctrl) { addWidgetToLeftSide(ctrl, show_widget); } } void LLPanelInventoryListItemBase::addWidgetToLeftSide(LLUICtrl* ctrl, bool show_widget/* = true*/) { mLeftSideWidgets.push_back(ctrl); setShowWidget(ctrl, show_widget); } void LLPanelInventoryListItemBase::addWidgetToRightSide(const std::string& name, bool show_widget/* = true*/) { LLUICtrl* ctrl = findChild<LLUICtrl>(name); if(ctrl) { addWidgetToRightSide(ctrl, show_widget); } } void LLPanelInventoryListItemBase::addWidgetToRightSide(LLUICtrl* ctrl, bool show_widget/* = true*/) { mRightSideWidgets.push_back(ctrl); setShowWidget(ctrl, show_widget); } void LLPanelInventoryListItemBase::setShowWidget(const std::string& name, bool show) { LLUICtrl* widget = findChild<LLUICtrl>(name); if(widget) { setShowWidget(widget, show); } } void LLPanelInventoryListItemBase::setShowWidget(LLUICtrl* ctrl, bool show) { // Enable state determines whether widget may become visible in setWidgetsVisible() ctrl->setEnabled(show); } BOOL LLPanelInventoryListItemBase::postBuild() { setIconCtrl(getChild<LLIconCtrl>("item_icon")); setTitleCtrl(getChild<LLTextBox>("item_name")); mIconImage = LLInventoryIcon::getIcon(mItem->getType(), mItem->getInventoryType(), mItem->getIsLinkType(), mItem->getFlags(), FALSE); setNeedsRefresh(true); setWidgetsVisible(false); reshapeWidgets(); return TRUE; } void LLPanelInventoryListItemBase::setValue(const LLSD& value) { if (!value.isMap()) return; if (!value.has("selected")) return; childSetVisible("selected_icon", value["selected"]); } void LLPanelInventoryListItemBase::onMouseEnter(S32 x, S32 y, MASK mask) { childSetVisible("hovered_icon", true); LLPanel::onMouseEnter(x, y, mask); } void LLPanelInventoryListItemBase::onMouseLeave(S32 x, S32 y, MASK mask) { childSetVisible("hovered_icon", false); LLPanel::onMouseLeave(x, y, mask); } S32 LLPanelInventoryListItemBase::notify(const LLSD& info) { S32 rv = 0; if(info.has("match_filter")) { mHighlightedText = info["match_filter"].asString(); std::string test(mItem->getName()); LLStringUtil::toUpper(test); if(mHighlightedText.empty() || std::string::npos != test.find(mHighlightedText)) { rv = 0; // substring is found } else { rv = -1; } setNeedsRefresh(true); } else { rv = LLPanel::notify(info); } return rv; } LLPanelInventoryListItemBase::LLPanelInventoryListItemBase(LLViewerInventoryItem* item) : LLPanel() , mItem(item) , mIconCtrl(NULL) , mTitleCtrl(NULL) , mWidgetSpacing(WIDGET_SPACING) , mLeftWidgetsWidth(0) , mRightWidgetsWidth(0) , mNeedsRefresh(false) { } void LLPanelInventoryListItemBase::init() { LLUICtrlFactory::getInstance()->buildPanel(this, "panel_inventory_item.xml"); } class WidgetVisibilityChanger { public: WidgetVisibilityChanger(bool visible) : mVisible(visible){} void operator()(LLUICtrl* widget) { // Disabled widgets never become visible. see LLPanelInventoryListItemBase::setShowWidget() widget->setVisible(mVisible && widget->getEnabled()); } private: bool mVisible; }; void LLPanelInventoryListItemBase::setWidgetsVisible(bool visible) { std::for_each(mLeftSideWidgets.begin(), mLeftSideWidgets.end(), WidgetVisibilityChanger(visible)); std::for_each(mRightSideWidgets.begin(), mRightSideWidgets.end(), WidgetVisibilityChanger(visible)); } void LLPanelInventoryListItemBase::reshapeWidgets() { // disabled reshape left for now to reserve space for 'delete' button in LLPanelClothingListItem /*reshapeLeftWidgets();*/ reshapeRightWidgets(); reshapeMiddleWidgets(); } void LLPanelInventoryListItemBase::setIconImage(const LLUIImagePtr& image) { if(image) { mIconImage = image; mIconCtrl->setImage(mIconImage); } } void LLPanelInventoryListItemBase::setTitle(const std::string& title, const std::string& highlit_text) { LLTextUtil::textboxSetHighlightedVal( mTitleCtrl, LLStyle::Params(), title, highlit_text); } void LLPanelInventoryListItemBase::reshapeLeftWidgets() { S32 widget_left = 0; mLeftWidgetsWidth = 0; widget_array_t::const_iterator it = mLeftSideWidgets.begin(); const widget_array_t::const_iterator it_end = mLeftSideWidgets.end(); for( ; it_end != it; ++it) { LLUICtrl* widget = *it; if(!widget->getVisible()) { continue; } LLRect widget_rect(widget->getRect()); widget_rect.setLeftTopAndSize(widget_left, widget_rect.mTop, widget_rect.getWidth(), widget_rect.getHeight()); widget->setShape(widget_rect); widget_left += widget_rect.getWidth() + getWidgetSpacing(); mLeftWidgetsWidth = widget_rect.mRight; } } void LLPanelInventoryListItemBase::reshapeRightWidgets() { S32 widget_right = getLocalRect().getWidth(); S32 widget_left = widget_right; widget_array_t::const_reverse_iterator it = mRightSideWidgets.rbegin(); const widget_array_t::const_reverse_iterator it_end = mRightSideWidgets.rend(); for( ; it_end != it; ++it) { LLUICtrl* widget = *it; if(!widget->getVisible()) { continue; } LLRect widget_rect(widget->getRect()); widget_left = widget_right - widget_rect.getWidth(); widget_rect.setLeftTopAndSize(widget_left, widget_rect.mTop, widget_rect.getWidth(), widget_rect.getHeight()); widget->setShape(widget_rect); widget_right = widget_left - getWidgetSpacing(); } mRightWidgetsWidth = getLocalRect().getWidth() - widget_left; } void LLPanelInventoryListItemBase::reshapeMiddleWidgets() { LLRect icon_rect(mIconCtrl->getRect()); icon_rect.setLeftTopAndSize(mLeftWidgetsWidth + getWidgetSpacing(), icon_rect.mTop, icon_rect.getWidth(), icon_rect.getHeight()); mIconCtrl->setShape(icon_rect); S32 name_left = icon_rect.mRight + getWidgetSpacing(); S32 name_right = getLocalRect().getWidth() - mRightWidgetsWidth - getWidgetSpacing(); LLRect name_rect(mTitleCtrl->getRect()); name_rect.set(name_left, name_rect.mTop, name_right, name_rect.mBottom); mTitleCtrl->setShape(name_rect); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// LLInventoryItemsList::Params::Params() {} LLInventoryItemsList::LLInventoryItemsList(const LLInventoryItemsList::Params& p) : LLFlatListViewEx(p) , mNeedsRefresh(false) , mForceRefresh(false) { // TODO: mCommitOnSelectionChange is set to "false" in LLFlatListView // but reset to true in all derived classes. This settings might need to // be added to LLFlatListView::Params() and/or set to "true" by default. setCommitOnSelectionChange(true); setNoFilteredItemsMsg(LLTrans::getString("InventoryNoMatchingItems")); gIdleCallbacks.addFunction(idle, this); } // virtual LLInventoryItemsList::~LLInventoryItemsList() {} void LLInventoryItemsList::refreshList(const LLInventoryModel::item_array_t item_array) { getIDs().clear(); LLInventoryModel::item_array_t::const_iterator it = item_array.begin(); for( ; item_array.end() != it; ++it) { getIDs().push_back((*it)->getUUID()); } mNeedsRefresh = true; } boost::signals2::connection LLInventoryItemsList::setRefreshCompleteCallback(const commit_signal_t::slot_type& cb) { return mRefreshCompleteSignal.connect(cb); } void LLInventoryItemsList::doIdle() { if (!mNeedsRefresh) return; if (isInVisibleChain() || mForceRefresh) { refresh(); mRefreshCompleteSignal(this, LLSD()); } } //static void LLInventoryItemsList::idle(void* user_data) { LLInventoryItemsList* self = static_cast<LLInventoryItemsList*>(user_data); if ( self ) { // Do the real idle self->doIdle(); } } void LLInventoryItemsList::refresh() { static const unsigned ADD_LIMIT = 50; uuid_vec_t added_items; uuid_vec_t removed_items; computeDifference(getIDs(), added_items, removed_items); bool add_limit_exceeded = false; unsigned nadded = 0; uuid_vec_t::const_iterator it = added_items.begin(); for( ; added_items.end() != it; ++it) { if(nadded >= ADD_LIMIT) { add_limit_exceeded = true; break; } LLViewerInventoryItem* item = gInventory.getItem(*it); // Do not rearrange items on each adding, let's do that on filter call addNewItem(item, false); ++nadded; } it = removed_items.begin(); for( ; removed_items.end() != it; ++it) { removeItemByUUID(*it); } // Filter, rearrange and notify parent about shape changes filterItems(); bool needs_refresh = add_limit_exceeded; setNeedsRefresh(needs_refresh); setForceRefresh(needs_refresh); } void LLInventoryItemsList::computeDifference( const uuid_vec_t& vnew, uuid_vec_t& vadded, uuid_vec_t& vremoved) { uuid_vec_t vcur; { std::vector<LLSD> vcur_values; getValues(vcur_values); for (size_t i=0; i<vcur_values.size(); i++) vcur.push_back(vcur_values[i].asUUID()); } LLCommonUtils::computeDifference(vnew, vcur, vadded, vremoved); } void LLInventoryItemsList::addNewItem(LLViewerInventoryItem* item, bool rearrange /*= true*/) { if (!item) { llwarns << "No inventory item. Couldn't create flat list item." << llendl; llassert(item != NULL); } LLPanelInventoryListItemBase *list_item = LLPanelInventoryListItemBase::create(item); if (!list_item) return; bool is_item_added = addItem(list_item, item->getUUID(), ADD_BOTTOM, rearrange); if (!is_item_added) { llwarns << "Couldn't add flat list item." << llendl; llassert(is_item_added); } } // EOF <commit_msg>Fixed potential crash in LLInventoryItemsList - unsubscribed from callback in destructor. Reviewed by Mike Antipov.<commit_after>/** * @file llinventoryitemslist.cpp * @brief A list of inventory items represented by LLFlatListView. * * Class LLInventoryItemsList implements a flat list of inventory items. * Class LLPanelInventoryListItem displays inventory item as an element * of LLInventoryItemsList. * * $LicenseInfo:firstyear=2010&license=viewergpl$ * * Copyright (c) 2010, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llinventoryitemslist.h" // llcommon #include "llcommonutils.h" // llui #include "lliconctrl.h" #include "lltextutil.h" #include "llcallbacklist.h" #include "llinventoryfunctions.h" #include "llinventorymodel.h" #include "lltrans.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// static const S32 WIDGET_SPACING = 3; LLPanelInventoryListItemBase* LLPanelInventoryListItemBase::create(LLViewerInventoryItem* item) { LLPanelInventoryListItemBase* list_item = NULL; if (item) { list_item = new LLPanelInventoryListItemBase(item); list_item->init(); } return list_item; } void LLPanelInventoryListItemBase::draw() { if (getNeedsRefresh()) { updateItem(); setNeedsRefresh(false); } LLPanel::draw(); } void LLPanelInventoryListItemBase::updateItem() { setIconImage(mIconImage); setTitle(mItem->getName(), mHighlightedText); } void LLPanelInventoryListItemBase::addWidgetToLeftSide(const std::string& name, bool show_widget/* = true*/) { LLUICtrl* ctrl = findChild<LLUICtrl>(name); if(ctrl) { addWidgetToLeftSide(ctrl, show_widget); } } void LLPanelInventoryListItemBase::addWidgetToLeftSide(LLUICtrl* ctrl, bool show_widget/* = true*/) { mLeftSideWidgets.push_back(ctrl); setShowWidget(ctrl, show_widget); } void LLPanelInventoryListItemBase::addWidgetToRightSide(const std::string& name, bool show_widget/* = true*/) { LLUICtrl* ctrl = findChild<LLUICtrl>(name); if(ctrl) { addWidgetToRightSide(ctrl, show_widget); } } void LLPanelInventoryListItemBase::addWidgetToRightSide(LLUICtrl* ctrl, bool show_widget/* = true*/) { mRightSideWidgets.push_back(ctrl); setShowWidget(ctrl, show_widget); } void LLPanelInventoryListItemBase::setShowWidget(const std::string& name, bool show) { LLUICtrl* widget = findChild<LLUICtrl>(name); if(widget) { setShowWidget(widget, show); } } void LLPanelInventoryListItemBase::setShowWidget(LLUICtrl* ctrl, bool show) { // Enable state determines whether widget may become visible in setWidgetsVisible() ctrl->setEnabled(show); } BOOL LLPanelInventoryListItemBase::postBuild() { setIconCtrl(getChild<LLIconCtrl>("item_icon")); setTitleCtrl(getChild<LLTextBox>("item_name")); mIconImage = LLInventoryIcon::getIcon(mItem->getType(), mItem->getInventoryType(), mItem->getIsLinkType(), mItem->getFlags(), FALSE); setNeedsRefresh(true); setWidgetsVisible(false); reshapeWidgets(); return TRUE; } void LLPanelInventoryListItemBase::setValue(const LLSD& value) { if (!value.isMap()) return; if (!value.has("selected")) return; childSetVisible("selected_icon", value["selected"]); } void LLPanelInventoryListItemBase::onMouseEnter(S32 x, S32 y, MASK mask) { childSetVisible("hovered_icon", true); LLPanel::onMouseEnter(x, y, mask); } void LLPanelInventoryListItemBase::onMouseLeave(S32 x, S32 y, MASK mask) { childSetVisible("hovered_icon", false); LLPanel::onMouseLeave(x, y, mask); } S32 LLPanelInventoryListItemBase::notify(const LLSD& info) { S32 rv = 0; if(info.has("match_filter")) { mHighlightedText = info["match_filter"].asString(); std::string test(mItem->getName()); LLStringUtil::toUpper(test); if(mHighlightedText.empty() || std::string::npos != test.find(mHighlightedText)) { rv = 0; // substring is found } else { rv = -1; } setNeedsRefresh(true); } else { rv = LLPanel::notify(info); } return rv; } LLPanelInventoryListItemBase::LLPanelInventoryListItemBase(LLViewerInventoryItem* item) : LLPanel() , mItem(item) , mIconCtrl(NULL) , mTitleCtrl(NULL) , mWidgetSpacing(WIDGET_SPACING) , mLeftWidgetsWidth(0) , mRightWidgetsWidth(0) , mNeedsRefresh(false) { } void LLPanelInventoryListItemBase::init() { LLUICtrlFactory::getInstance()->buildPanel(this, "panel_inventory_item.xml"); } class WidgetVisibilityChanger { public: WidgetVisibilityChanger(bool visible) : mVisible(visible){} void operator()(LLUICtrl* widget) { // Disabled widgets never become visible. see LLPanelInventoryListItemBase::setShowWidget() widget->setVisible(mVisible && widget->getEnabled()); } private: bool mVisible; }; void LLPanelInventoryListItemBase::setWidgetsVisible(bool visible) { std::for_each(mLeftSideWidgets.begin(), mLeftSideWidgets.end(), WidgetVisibilityChanger(visible)); std::for_each(mRightSideWidgets.begin(), mRightSideWidgets.end(), WidgetVisibilityChanger(visible)); } void LLPanelInventoryListItemBase::reshapeWidgets() { // disabled reshape left for now to reserve space for 'delete' button in LLPanelClothingListItem /*reshapeLeftWidgets();*/ reshapeRightWidgets(); reshapeMiddleWidgets(); } void LLPanelInventoryListItemBase::setIconImage(const LLUIImagePtr& image) { if(image) { mIconImage = image; mIconCtrl->setImage(mIconImage); } } void LLPanelInventoryListItemBase::setTitle(const std::string& title, const std::string& highlit_text) { LLTextUtil::textboxSetHighlightedVal( mTitleCtrl, LLStyle::Params(), title, highlit_text); } void LLPanelInventoryListItemBase::reshapeLeftWidgets() { S32 widget_left = 0; mLeftWidgetsWidth = 0; widget_array_t::const_iterator it = mLeftSideWidgets.begin(); const widget_array_t::const_iterator it_end = mLeftSideWidgets.end(); for( ; it_end != it; ++it) { LLUICtrl* widget = *it; if(!widget->getVisible()) { continue; } LLRect widget_rect(widget->getRect()); widget_rect.setLeftTopAndSize(widget_left, widget_rect.mTop, widget_rect.getWidth(), widget_rect.getHeight()); widget->setShape(widget_rect); widget_left += widget_rect.getWidth() + getWidgetSpacing(); mLeftWidgetsWidth = widget_rect.mRight; } } void LLPanelInventoryListItemBase::reshapeRightWidgets() { S32 widget_right = getLocalRect().getWidth(); S32 widget_left = widget_right; widget_array_t::const_reverse_iterator it = mRightSideWidgets.rbegin(); const widget_array_t::const_reverse_iterator it_end = mRightSideWidgets.rend(); for( ; it_end != it; ++it) { LLUICtrl* widget = *it; if(!widget->getVisible()) { continue; } LLRect widget_rect(widget->getRect()); widget_left = widget_right - widget_rect.getWidth(); widget_rect.setLeftTopAndSize(widget_left, widget_rect.mTop, widget_rect.getWidth(), widget_rect.getHeight()); widget->setShape(widget_rect); widget_right = widget_left - getWidgetSpacing(); } mRightWidgetsWidth = getLocalRect().getWidth() - widget_left; } void LLPanelInventoryListItemBase::reshapeMiddleWidgets() { LLRect icon_rect(mIconCtrl->getRect()); icon_rect.setLeftTopAndSize(mLeftWidgetsWidth + getWidgetSpacing(), icon_rect.mTop, icon_rect.getWidth(), icon_rect.getHeight()); mIconCtrl->setShape(icon_rect); S32 name_left = icon_rect.mRight + getWidgetSpacing(); S32 name_right = getLocalRect().getWidth() - mRightWidgetsWidth - getWidgetSpacing(); LLRect name_rect(mTitleCtrl->getRect()); name_rect.set(name_left, name_rect.mTop, name_right, name_rect.mBottom); mTitleCtrl->setShape(name_rect); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// LLInventoryItemsList::Params::Params() {} LLInventoryItemsList::LLInventoryItemsList(const LLInventoryItemsList::Params& p) : LLFlatListViewEx(p) , mNeedsRefresh(false) , mForceRefresh(false) { // TODO: mCommitOnSelectionChange is set to "false" in LLFlatListView // but reset to true in all derived classes. This settings might need to // be added to LLFlatListView::Params() and/or set to "true" by default. setCommitOnSelectionChange(true); setNoFilteredItemsMsg(LLTrans::getString("InventoryNoMatchingItems")); gIdleCallbacks.addFunction(idle, this); } // virtual LLInventoryItemsList::~LLInventoryItemsList() { gIdleCallbacks.deleteFunction(idle, this); } void LLInventoryItemsList::refreshList(const LLInventoryModel::item_array_t item_array) { getIDs().clear(); LLInventoryModel::item_array_t::const_iterator it = item_array.begin(); for( ; item_array.end() != it; ++it) { getIDs().push_back((*it)->getUUID()); } mNeedsRefresh = true; } boost::signals2::connection LLInventoryItemsList::setRefreshCompleteCallback(const commit_signal_t::slot_type& cb) { return mRefreshCompleteSignal.connect(cb); } void LLInventoryItemsList::doIdle() { if (!mNeedsRefresh) return; if (isInVisibleChain() || mForceRefresh) { refresh(); mRefreshCompleteSignal(this, LLSD()); } } //static void LLInventoryItemsList::idle(void* user_data) { LLInventoryItemsList* self = static_cast<LLInventoryItemsList*>(user_data); if ( self ) { // Do the real idle self->doIdle(); } } void LLInventoryItemsList::refresh() { static const unsigned ADD_LIMIT = 50; uuid_vec_t added_items; uuid_vec_t removed_items; computeDifference(getIDs(), added_items, removed_items); bool add_limit_exceeded = false; unsigned nadded = 0; uuid_vec_t::const_iterator it = added_items.begin(); for( ; added_items.end() != it; ++it) { if(nadded >= ADD_LIMIT) { add_limit_exceeded = true; break; } LLViewerInventoryItem* item = gInventory.getItem(*it); // Do not rearrange items on each adding, let's do that on filter call addNewItem(item, false); ++nadded; } it = removed_items.begin(); for( ; removed_items.end() != it; ++it) { removeItemByUUID(*it); } // Filter, rearrange and notify parent about shape changes filterItems(); bool needs_refresh = add_limit_exceeded; setNeedsRefresh(needs_refresh); setForceRefresh(needs_refresh); } void LLInventoryItemsList::computeDifference( const uuid_vec_t& vnew, uuid_vec_t& vadded, uuid_vec_t& vremoved) { uuid_vec_t vcur; { std::vector<LLSD> vcur_values; getValues(vcur_values); for (size_t i=0; i<vcur_values.size(); i++) vcur.push_back(vcur_values[i].asUUID()); } LLCommonUtils::computeDifference(vnew, vcur, vadded, vremoved); } void LLInventoryItemsList::addNewItem(LLViewerInventoryItem* item, bool rearrange /*= true*/) { if (!item) { llwarns << "No inventory item. Couldn't create flat list item." << llendl; llassert(item != NULL); } LLPanelInventoryListItemBase *list_item = LLPanelInventoryListItemBase::create(item); if (!list_item) return; bool is_item_added = addItem(list_item, item->getUUID(), ADD_BOTTOM, rearrange); if (!is_item_added) { llwarns << "Couldn't add flat list item." << llendl; llassert(is_item_added); } } // EOF <|endoftext|>
<commit_before>/* Copyright 2013 - 2015 Yurii Litvinov and CyberTech Labs Ltd. * * 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 <QtCore/qglobal.h> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QApplication> #else #include <QtWidgets/QApplication> #endif #include <QtCore/QTimer> #include <QtCore/QCoreApplication> #include <QtCore/QEventLoop> #include <QtCore/QFileInfo> #include <trikKernel/configurer.h> #include <trikKernel/deinitializationHelper.h> #include <trikKernel/fileUtils.h> #include <trikKernel/applicationInitHelper.h> #include <trikKernel/paths.h> #include <trikControl/brickFactory.h> #include <trikControl/brickInterface.h> #include <trikScriptRunner/trikScriptRunner.h> #include <trikScriptRunner/trikPythonRunner.h> #include <trikNetwork/mailboxFactory.h> #include <trikNetwork/mailboxInterface.h> #include <QsLog.h> int main(int argc, char *argv[]) { QStringList params; for (int i = 1; i < argc; ++i) { params << QString(argv[i]); } QScopedPointer<QCoreApplication> app; if (params.contains("--no-display") || params.contains("-no-display")) { app.reset(new QCoreApplication(argc, argv)); } else { app.reset(new QApplication(argc, argv)); } app->setApplicationName("TrikRun"); // RAII-style code to ensure that after brick gets destroyed there will be an event loop that cleans it up. trikKernel::DeinitializationHelper helper; Q_UNUSED(helper); trikKernel::ApplicationInitHelper initHelper(*app); initHelper.commandLineParser().addPositionalArgument("file", QObject::tr("File with script to execute") + " " + QObject::tr("(optional of -js or -py option is specified)")); initHelper.commandLineParser().addOption("js", "js-script" , QObject::tr("JavaScript Script to be executed directly from command line.") + "\n" + QObject::tr("\tExample: ./trikRun -js \"brick.smile(); script.wait(2000);\"")); initHelper.commandLineParser().addOption("py", "py-script" , QObject::tr("Python Script to be executed directly from command line.") + "\n" + QObject::tr("\tExample: ./trikRun -py \"brick.smile(); script.wait(2000);\"")); // FIXME: example initHelper.commandLineParser().addFlag("no-display", "no-display" , QObject::tr("Disable display support. When this flag is active, trikRun can work without QWS or even " "physical display")); initHelper.commandLineParser().addApplicationDescription(QObject::tr("Runner of JavaScript and Python files.")); if (!initHelper.parseCommandLine()) { return 0; } initHelper.init(); QLOG_INFO() << "TrikRun started"; enum ScriptType { JAVASCRIPT, PYTHON }; const auto run = [&](const QString &script, ScriptType stype) { QScopedPointer<trikControl::BrickInterface> brick( trikControl::BrickFactory::create(initHelper.configPath(), trikKernel::Paths::mediaPath()) ); trikKernel::Configurer configurer(initHelper.configPath() + "/system-config.xml" , initHelper.configPath() + "/model-config.xml"); QScopedPointer<trikNetwork::MailboxInterface> mailbox(trikNetwork::MailboxFactory::create(configurer)); trikScriptRunner::TrikScriptRunnerInterface * result; switch (stype) { case JAVASCRIPT: result = new trikScriptRunner::TrikScriptRunner(*brick, mailbox.data()); break; case PYTHON: result = new trikScriptRunner::TrikPythonRunner(*brick, mailbox.data()); break; default: QLOG_ERROR() << "No such script engine"; return 1; } QObject::connect(result, SIGNAL(completed(QString, int)), app.data(), SLOT(quit())); result->run(script); return app->exec(); }; if (initHelper.commandLineParser().isSet("js")) { return run(initHelper.commandLineParser().value("js"), JAVASCRIPT); } else if (initHelper.commandLineParser().isSet("py")) { return run(initHelper.commandLineParser().value("py"), PYTHON); } else { const QStringList positionalArgs = initHelper.commandLineParser().positionalArgs(); if (positionalArgs.size() == 1) { const QFileInfo fileInfo(positionalArgs[0]); ScriptType stype; if (fileInfo.suffix() == "js" || fileInfo.suffix() == "qts") { stype = JAVASCRIPT; } else if (fileInfo.suffix() == "py") { stype = PYTHON; } else { QLOG_ERROR() << "No such script engine"; return 1; } return run(trikKernel::FileUtils::readFromFile(positionalArgs[0]), stype); } else { initHelper.commandLineParser().showHelp(); return 1; } } } <commit_msg>fix includes<commit_after>/* Copyright 2013 - 2015 Yurii Litvinov and CyberTech Labs Ltd. * * 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 <QtCore/qglobal.h> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QApplication> #else #include <QtWidgets/QApplication> #endif #include <QtCore/QTimer> #include <QtCore/QCoreApplication> #include <QtCore/QEventLoop> #include <QtCore/QFileInfo> #include <trikKernel/configurer.h> #include <trikKernel/deinitializationHelper.h> #include <trikKernel/fileUtils.h> #include <trikKernel/applicationInitHelper.h> #include <trikKernel/paths.h> #include <trikControl/brickFactory.h> #include <trikControl/brickInterface.h> #include "trikScriptRunner/trikScriptRunnerInterface.h" #include "trikScriptRunner/trikScriptRunner.h" #include "trikScriptRunner/trikPythonRunner.h" #include <trikNetwork/mailboxFactory.h> #include <trikNetwork/mailboxInterface.h> #include <QsLog.h> int main(int argc, char *argv[]) { QStringList params; for (int i = 1; i < argc; ++i) { params << QString(argv[i]); } QScopedPointer<QCoreApplication> app; if (params.contains("--no-display") || params.contains("-no-display")) { app.reset(new QCoreApplication(argc, argv)); } else { app.reset(new QApplication(argc, argv)); } app->setApplicationName("TrikRun"); // RAII-style code to ensure that after brick gets destroyed there will be an event loop that cleans it up. trikKernel::DeinitializationHelper helper; Q_UNUSED(helper); trikKernel::ApplicationInitHelper initHelper(*app); initHelper.commandLineParser().addPositionalArgument("file", QObject::tr("File with script to execute") + " " + QObject::tr("(optional of -js or -py option is specified)")); initHelper.commandLineParser().addOption("js", "js-script" , QObject::tr("JavaScript Script to be executed directly from command line.") + "\n" + QObject::tr("\tExample: ./trikRun -js \"brick.smile(); script.wait(2000);\"")); initHelper.commandLineParser().addOption("py", "py-script" , QObject::tr("Python Script to be executed directly from command line.") + "\n" + QObject::tr("\tExample: ./trikRun -py \"brick.smile(); script.wait(2000);\"")); // FIXME: example initHelper.commandLineParser().addFlag("no-display", "no-display" , QObject::tr("Disable display support. When this flag is active, trikRun can work without QWS or even " "physical display")); initHelper.commandLineParser().addApplicationDescription(QObject::tr("Runner of JavaScript and Python files.")); if (!initHelper.parseCommandLine()) { return 0; } initHelper.init(); QLOG_INFO() << "TrikRun started"; enum ScriptType { JAVASCRIPT, PYTHON }; const auto run = [&](const QString &script, ScriptType stype) { QScopedPointer<trikControl::BrickInterface> brick( trikControl::BrickFactory::create(initHelper.configPath(), trikKernel::Paths::mediaPath()) ); trikKernel::Configurer configurer(initHelper.configPath() + "/system-config.xml" , initHelper.configPath() + "/model-config.xml"); QScopedPointer<trikNetwork::MailboxInterface> mailbox(trikNetwork::MailboxFactory::create(configurer)); trikScriptRunner::TrikScriptRunnerInterface * result; switch (stype) { case JAVASCRIPT: result = new trikScriptRunner::TrikScriptRunner(*brick, mailbox.data()); break; case PYTHON: result = new trikScriptRunner::TrikPythonRunner(*brick, mailbox.data()); break; default: QLOG_ERROR() << "No such script engine"; return 1; } QObject::connect(result, SIGNAL(completed(QString, int)), app.data(), SLOT(quit())); result->run(script); return app->exec(); }; if (initHelper.commandLineParser().isSet("js")) { return run(initHelper.commandLineParser().value("js"), JAVASCRIPT); } else if (initHelper.commandLineParser().isSet("py")) { return run(initHelper.commandLineParser().value("py"), PYTHON); } else { const QStringList positionalArgs = initHelper.commandLineParser().positionalArgs(); if (positionalArgs.size() == 1) { const QFileInfo fileInfo(positionalArgs[0]); ScriptType stype; if (fileInfo.suffix() == "js" || fileInfo.suffix() == "qts") { stype = JAVASCRIPT; } else if (fileInfo.suffix() == "py") { stype = PYTHON; } else { QLOG_ERROR() << "No such script engine"; return 1; } return run(trikKernel::FileUtils::readFromFile(positionalArgs[0]), stype); } else { initHelper.commandLineParser().showHelp(); return 1; } } } <|endoftext|>
<commit_before>#include <boomhs/collision.hpp> #include <boomhs/components.hpp> #include <boomhs/frame_time.hpp> #include <common/log.hpp> #include <common/timer.hpp> #include <common/type_macros.hpp> #include <gl_sdl/sdl_window.hpp> #include <opengl/bind.hpp> #include <opengl/factory.hpp> #include <opengl/gpu.hpp> #include <opengl/renderer.hpp> #include <opengl/shader.hpp> #include <opengl/vertex_attribute.hpp> #include <cstdlib> using namespace boomhs; using namespace boomhs::math; using namespace common; using namespace gl_sdl; using namespace opengl; namespace OR = opengl::render; auto make_program_and_bbox(common::Logger& logger) { std::vector<opengl::AttributePointerInfo> apis; { auto const attr_type = AttributeType::POSITION; apis.emplace_back(AttributePointerInfo{0, GL_FLOAT, attr_type, 3}); } auto va = make_vertex_attribute(apis); auto sp = make_shader_program(logger, "wireframe.vert", "wireframe.frag", MOVE(va)) .expect_moveout("Error loading wireframe shader program"); CubeRenderable const cr{glm::vec3{0}, glm::vec3{1}}; auto const vertices = OF::cube_vertices(cr.min, cr.max); return PAIR(MOVE(sp), gpu::copy_cube_gpu(logger, vertices, sp.va())); } auto make_program_and_rectangle(common::Logger& logger, Rectangle const& rect, Rectangle const& view_rect) { auto const TOP_LEFT = glm::vec2{rect.left(), rect.top()}; //auto const TL_NDC = math::space_conversions::screen_to_ndc(TOP_LEFT, view_rect); auto const BOTTOM_RIGHT = glm::vec2{rect.right(), rect.bottom()}; //auto const BR_NDC = math::space_conversions::screen_to_ndc(BOTTOM_RIGHT, view_rect); Rectangle const ndc_rect{TOP_LEFT.x, TOP_LEFT.y, BOTTOM_RIGHT.x, BOTTOM_RIGHT.y}; OF::RectInfo const ri{ndc_rect, std::nullopt, std::nullopt, std::nullopt}; RectBuffer buffer = OF::make_rectangle(ri); std::vector<opengl::AttributePointerInfo> apis; { auto const attr_type = AttributeType::POSITION; apis.emplace_back(AttributePointerInfo{0, GL_FLOAT, attr_type, 3}); } auto va = make_vertex_attribute(apis); auto sp = make_shader_program(logger, "2dcolor.vert", "2dcolor.frag", MOVE(va)) .expect_moveout("Error loading 2dcolor shader program"); return PAIR(MOVE(sp), gpu::copy_rectangle(logger, sp.va(), buffer)); } auto calculate_pm(ScreenDimensions const& sd) { auto constexpr NEAR = 1.0f; auto constexpr FAR = -1.0f; Frustum const f{ static_cast<float>(sd.left()), static_cast<float>(sd.right()), static_cast<float>(sd.bottom()), static_cast<float>(sd.top()), NEAR, FAR}; return glm::ortho(f.left, f.right, f.bottom, f.top, f.near, f.far); } void draw_bbox(common::Logger& logger, ScreenDimensions const& sd, ShaderProgram& sp, DrawInfo& dinfo, DrawState& ds) { auto const pm = calculate_pm(sd); Color const wire_color = LOC::BLUE; Transform tr; auto const model_matrix = tr.model_matrix(); BIND_UNTIL_END_OF_SCOPE(logger, sp); sp.set_uniform_color(logger, "u_wirecolor", wire_color); auto const pos = glm::vec3{0, 5, 0}; auto const forward = -constants::Y_UNIT_VECTOR; auto const up = -constants::Z_UNIT_VECTOR; auto const vm = glm::lookAt(pos, pos + forward, up); //auto const vm = glm::mat4{}; BIND_UNTIL_END_OF_SCOPE(logger, dinfo); auto const camera_matrix = pm * vm; render::set_mvpmatrix(logger, camera_matrix, model_matrix, sp); render::draw(logger, ds, GL_LINES, sp, dinfo); } void draw_rectangle(common::Logger& logger, ScreenDimensions const& sd, ShaderProgram& sp, DrawInfo& dinfo, Color const& color, DrawState& ds) { auto const pm = calculate_pm(sd); BIND_UNTIL_END_OF_SCOPE(logger, sp); sp.set_uniform_matrix_4fv(logger, "u_projmatrix", pm); sp.set_uniform_color(logger, "u_color", color); BIND_UNTIL_END_OF_SCOPE(logger, dinfo); OR::draw_2delements(logger, GL_TRIANGLES, sp, dinfo.num_indices()); } bool process_event(common::Logger& logger, SDL_Event& event, Rectangle const& rect, Color* color) { bool const event_type_keydown = event.type == SDL_KEYDOWN; auto const key_pressed = event.key.keysym.sym; if (event_type_keydown) { switch (key_pressed) { case SDLK_F10: case SDLK_ESCAPE: return true; break; default: break; } } else if (event.type == SDL_MOUSEMOTION) { auto const& motion = event.motion; float const x = motion.x, y = motion.y; auto const p = glm::vec2{x, y}; if (collision::point_rectangle_intersects(p, rect)) { *color = LOC::GREEN; //LOG_ERROR_SPRINTF("mouse pos: %f:%f", p.x, p.y); } else { *color = LOC::RED; } } return event.type == SDL_QUIT; } int main(int argc, char **argv) { bool constexpr FULLSCREEN = false; int constexpr WIDTH = 1024, HEIGHT = 768; auto logger = common::LogFactory::make_stderr(); auto const on_error = [&logger](auto const& error) { LOG_ERROR(error); return EXIT_FAILURE; }; TRY_OR_ELSE_RETURN(auto sdl_gl, SDLGlobalContext::create(logger), on_error); TRY_OR_ELSE_RETURN(auto window, sdl_gl->make_window(logger, "Ortho Raycast Test", FULLSCREEN, WIDTH, HEIGHT), on_error); ScreenDimensions constexpr SCREEN_DIM{0, 0, WIDTH, HEIGHT}; OR::init(logger); OR::set_viewport(SCREEN_DIM); auto const view_rect = SCREEN_DIM.rect(); auto const color_rect = Rectangle{WIDTH / 4, HEIGHT / 4, WIDTH / 2, HEIGHT / 2}; auto rect_pair = make_program_and_rectangle(logger, color_rect, view_rect); auto bbox_pair = make_program_and_bbox(logger); Timer timer; FrameCounter fcounter; auto color = LOC::RED; SDL_Event event; bool quit = false; while (!quit) { auto const ft = FrameTime::from_timer(timer); while ((!quit) && (0 != SDL_PollEvent(&event))) { quit = process_event(logger, event, color_rect, &color); } OR::clear_screen(LOC::WHITE); DrawState ds; draw_rectangle(logger, SCREEN_DIM, rect_pair.first, rect_pair.second, color, ds); draw_bbox(logger, SCREEN_DIM, bbox_pair.first, bbox_pair.second, ds); // Update window with OpenGL rendering SDL_GL_SwapWindow(window.raw()); timer.update(); fcounter.update(); } return EXIT_SUCCESS; } <commit_msg>ortho raycast perspective cube mouse collision test works<commit_after>#include <boomhs/camera.hpp> #include <boomhs/collision.hpp> #include <boomhs/components.hpp> #include <boomhs/frame_time.hpp> #include <boomhs/raycast.hpp> #include <common/log.hpp> #include <common/timer.hpp> #include <common/type_macros.hpp> #include <gl_sdl/sdl_window.hpp> #include <opengl/bind.hpp> #include <opengl/factory.hpp> #include <opengl/gpu.hpp> #include <opengl/renderer.hpp> #include <opengl/shader.hpp> #include <opengl/vertex_attribute.hpp> #include <cstdlib> using namespace boomhs; using namespace boomhs::math; using namespace common; using namespace gl_sdl; using namespace opengl; static auto constexpr NEAR = 0.001f; static auto constexpr FAR = 100.0f; static auto constexpr FOV = glm::radians(110.0f); static auto constexpr AR = AspectRatio{4.0f, 3.0f}; static auto const FORWARD = constants::Z_UNIT_VECTOR; static auto const UP = -constants::Y_UNIT_VECTOR; static glm::vec3 CAMERA_POS{0, 0, -1}; namespace OR = opengl::render; auto make_program_and_bbox(common::Logger& logger, Cube const& cr) { std::vector<opengl::AttributePointerInfo> apis; { auto const attr_type = AttributeType::POSITION; apis.emplace_back(AttributePointerInfo{0, GL_FLOAT, attr_type, 3}); } auto va = make_vertex_attribute(apis); auto sp = make_shader_program(logger, "wireframe.vert", "wireframe.frag", MOVE(va)) .expect_moveout("Error loading wireframe shader program"); auto const vertices = OF::cube_vertices(cr.min, cr.max); return PAIR(MOVE(sp), gpu::copy_cube_wireframe_gpu(logger, vertices, sp.va())); } auto make_program_and_rectangle(common::Logger& logger, Rectangle const& rect, Rectangle const& view_rect) { auto const TOP_LEFT = glm::vec2{rect.left(), rect.top()}; //auto const TL_NDC = math::space_conversions::screen_to_ndc(TOP_LEFT, view_rect); auto const BOTTOM_RIGHT = glm::vec2{rect.right(), rect.bottom()}; //auto const BR_NDC = math::space_conversions::screen_to_ndc(BOTTOM_RIGHT, view_rect); Rectangle const ndc_rect{TOP_LEFT.x, TOP_LEFT.y, BOTTOM_RIGHT.x, BOTTOM_RIGHT.y}; OF::RectInfo const ri{ndc_rect, std::nullopt, std::nullopt, std::nullopt}; RectBuffer buffer = OF::make_rectangle(ri); std::vector<opengl::AttributePointerInfo> apis; { auto const attr_type = AttributeType::POSITION; apis.emplace_back(AttributePointerInfo{0, GL_FLOAT, attr_type, 3}); } auto va = make_vertex_attribute(apis); auto sp = make_shader_program(logger, "2dcolor.vert", "2dcolor.frag", MOVE(va)) .expect_moveout("Error loading 2dcolor shader program"); return PAIR(MOVE(sp), gpu::copy_rectangle(logger, sp.va(), buffer)); } auto calculate_pm(ScreenDimensions const& sd) { Frustum const f{ static_cast<float>(sd.left()), static_cast<float>(sd.right()), static_cast<float>(sd.bottom()), static_cast<float>(sd.top()), NEAR, FAR}; return glm::perspective(FOV, AR.compute(), f.near, f.far); //return glm::ortho(f.left, f.right, f.bottom, f.top, f.near, f.far); } auto calculate_vm() { return glm::lookAt(CAMERA_POS, CAMERA_POS + FORWARD, UP); } void draw_bbox(common::Logger& logger, glm::mat4 const& pm, glm::mat4 const& vm, Transform const& tr, ShaderProgram& sp, DrawInfo& dinfo, DrawState& ds, Color const& color) { auto const model_matrix = tr.model_matrix(); BIND_UNTIL_END_OF_SCOPE(logger, sp); sp.set_uniform_color(logger, "u_wirecolor", color); BIND_UNTIL_END_OF_SCOPE(logger, dinfo); auto const camera_matrix = pm * vm; render::set_mvpmatrix(logger, camera_matrix, model_matrix, sp); render::draw(logger, ds, GL_LINES, sp, dinfo); } void draw_rectangle_pm(common::Logger& logger, ScreenDimensions const& sd, ShaderProgram& sp, DrawInfo& dinfo, Color const& color, DrawState& ds) { auto const pm = calculate_pm(sd); BIND_UNTIL_END_OF_SCOPE(logger, sp); sp.set_uniform_matrix_4fv(logger, "u_projmatrix", pm); sp.set_uniform_color(logger, "u_color", color); BIND_UNTIL_END_OF_SCOPE(logger, dinfo); OR::draw_2delements(logger, GL_TRIANGLES, sp, dinfo.num_indices()); } bool process_event(common::Logger& logger, SDL_Event& event, Rectangle const& view_rect, glm::mat4 const& pm, glm::mat4 const& vm, Transform& tr, Rectangle const& pm_rect, Color* pm_rect_color, Cube const& cube, Color* wire_color) { bool const event_type_keydown = event.type == SDL_KEYDOWN; auto const key_pressed = event.key.keysym.sym; if (event_type_keydown) { switch (key_pressed) { case SDLK_F10: case SDLK_ESCAPE: return true; break; case SDLK_a: CAMERA_POS += glm::vec3{1, 0, 0}; break; case SDLK_d: CAMERA_POS += glm::vec3{-1, 0, 0}; break; case SDLK_w: CAMERA_POS += glm::vec3{0, 1, 0}; break; case SDLK_s: CAMERA_POS += glm::vec3{0, -1, 0}; break; case SDLK_e: CAMERA_POS += glm::vec3{0, 0, 1}; break; case SDLK_q: CAMERA_POS += glm::vec3{0, 0, -1}; break; default: break; } } else if (event.type == SDL_MOUSEMOTION) { auto const& motion = event.motion; float const x = motion.x, y = motion.y; auto const mouse_pos = glm::vec2{x, y}; if (collision::point_rectangle_intersects(mouse_pos, pm_rect)) { *pm_rect_color = LOC::GREEN; //LOG_ERROR_SPRINTF("mouse pos: %f:%f", p.x, p.y); } else { *pm_rect_color = LOC::RED; } glm::vec3 const ray_dir = Raycast::calculate_ray_into_screen(mouse_pos, pm, vm, view_rect); glm::vec3 const ray_start = CAMERA_POS; Ray const ray{ray_start, ray_dir}; float distance = 0.0f; if (collision::ray_cube_intersect(ray, tr, cube, distance)) { *wire_color = LOC::PURPLE; } else { *wire_color = LOC::BLUE; } } return event.type == SDL_QUIT; } int main(int argc, char **argv) { bool constexpr FULLSCREEN = false; int constexpr WIDTH = 1024, HEIGHT = 768; auto logger = common::LogFactory::make_stderr(); auto const on_error = [&logger](auto const& error) { LOG_ERROR(error); return EXIT_FAILURE; }; TRY_OR_ELSE_RETURN(auto sdl_gl, SDLGlobalContext::create(logger), on_error); TRY_OR_ELSE_RETURN(auto window, sdl_gl->make_window(logger, "Ortho Raycast Test", FULLSCREEN, WIDTH, HEIGHT), on_error); ScreenDimensions constexpr SCREEN_DIM{0, 0, WIDTH, HEIGHT}; OR::init(logger); OR::set_viewport(SCREEN_DIM); auto const view_rect = SCREEN_DIM.rect(); auto const color_rect = Rectangle{WIDTH / 4, HEIGHT / 4, WIDTH / 2, HEIGHT / 2}; //auto rect_pair = make_program_and_rectangle(logger, color_rect, view_rect); Cube const cr{glm::vec3{0}, glm::vec3{1}}; auto bbox_pair = make_program_and_bbox(logger, cr); Timer timer; FrameCounter fcounter; auto color = LOC::RED; Color wire_color = LOC::BLUE; SDL_Event event; bool quit = false; Transform tr; glm::mat4 pm; glm::mat4 vm; while (!quit) { pm = calculate_pm(SCREEN_DIM); vm = calculate_vm(); auto const ft = FrameTime::from_timer(timer); while ((!quit) && (0 != SDL_PollEvent(&event))) { quit = process_event(logger, event, view_rect, pm, vm, tr, color_rect, &color, cr, &wire_color); } LOG_ERROR_SPRINTF("cam pos: %s", glm::to_string(CAMERA_POS)); OR::clear_screen(LOC::WHITE); DrawState ds; //draw_rectangle_pm(logger, SCREEN_DIM, rect_pair.first, rect_pair.second, color, ds); draw_bbox(logger, pm, vm, tr, bbox_pair.first, bbox_pair.second, ds, wire_color); // Update window with OpenGL rendering SDL_GL_SwapWindow(window.raw()); timer.update(); fcounter.update(); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "src/associations.hpp" #include <sdbusplus/asio/connection.hpp> #include <sdbusplus/asio/object_server.hpp> /* @brief Will contain path and name of test application */ const char* appname = program_invocation_name; #include <gtest/gtest.h> /** @class AsioServerClassTest * * @brief Provide wrapper for creating asio::object_server for test suite */ class AsioServerClassTest : public testing::Test { protected: // Make this global to the whole test suite since we want to share // the asio::object_server accross the test cases // NOTE - latest googltest changed to SetUpTestSuite() static void SetUpTestCase() { boost::asio::io_context io; auto conn = std::make_shared<sdbusplus::asio::connection>(io); // Need a distinct name for the bus since multiple test applications // will be running at same time std::string dbusName = {"xyz.openbmc_project.ObjMgr.Test."}; std::string fullAppPath = {appname}; std::size_t fileNameLoc = fullAppPath.find_last_of("/\\"); dbusName += fullAppPath.substr(fileNameLoc + 1); conn->request_name(dbusName.c_str()); server = new sdbusplus::asio::object_server(conn); } // NOTE - latest googltest changed to TearDownTestSuite() static void TearDownTestCase() { delete server; server = nullptr; } static sdbusplus::asio::object_server* server; }; <commit_msg>tests: fix use-after-free<commit_after>#include "src/associations.hpp" #include <sdbusplus/asio/connection.hpp> #include <sdbusplus/asio/object_server.hpp> /* @brief Will contain path and name of test application */ const char* appname = program_invocation_name; #include <gtest/gtest.h> /** @class AsioServerClassTest * * @brief Provide wrapper for creating asio::object_server for test suite */ class AsioServerClassTest : public testing::Test { protected: // Make this global to the whole test suite since we want to share // the asio::object_server accross the test cases // NOTE - latest googltest changed to SetUpTestSuite() static void SetUpTestCase() { static boost::asio::io_context io; auto conn = std::make_shared<sdbusplus::asio::connection>(io); // Need a distinct name for the bus since multiple test applications // will be running at same time std::string dbusName = {"xyz.openbmc_project.ObjMgr.Test."}; std::string fullAppPath = {appname}; std::size_t fileNameLoc = fullAppPath.find_last_of("/\\"); dbusName += fullAppPath.substr(fileNameLoc + 1); conn->request_name(dbusName.c_str()); server = new sdbusplus::asio::object_server(conn); } // NOTE - latest googltest changed to TearDownTestSuite() static void TearDownTestCase() { delete server; server = nullptr; } static sdbusplus::asio::object_server* server; }; <|endoftext|>
<commit_before>/*! * @file logger_implement_access.cpp * @brief logger module implementation class For access log. * * L7VSD: Linux Virtual Server for Layer7 Load Balancing * Copyright (C) 2009 NTT COMWARE Corporation. * * This program 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 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 * 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 <iostream> #include <sstream> #include <iomanip> #include <limits.h> #include <log4cxx/logmanager.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/rolling/rollingfileappender.h> #include <log4cxx/rolling/fixedwindowrollingpolicy.h> #include <log4cxx/rolling/sizebasedtriggeringpolicy.h> #include <log4cxx/rolling/timebasedrollingpolicy.h> #include <log4cxx/consoleappender.h> #include <errno.h> #include <stdexcept> #include <boost/lexical_cast.hpp> #include "logger_implement_access.h" #include "logger_logrotate_utility.h" l7vs::logger_implement_access::logger_implement_access(const std::string &access_log_file_name):access_cnt(1),initialized( false ),rotate_default_flag( false ) { access_log_file_name_ = access_log_file_name; aclog_args.clear(); } bool l7vs::logger_implement_access::init(const bool rotate_default_flag,const appender_property& access_log_default_property,accesslog_rotate_map_type& rotatedata) { using namespace log4cxx; if (initialized) return true; bool rtnFlg = true; try { this->rotate_default_flag = rotate_default_flag; rtnFlg = this->setAcLoggerConf(access_log_default_property,rotatedata); } catch (const std::exception& e) { return false; } return (rtnFlg); } bool l7vs::logger_implement_access::setAcLoggerConf(const appender_property& access_log_default_property,accesslog_rotate_map_type& rotatedata) { bool lotate_check_flag = true; aclog_args = rotatedata; access_log_property.log_filename_value = access_log_file_name_; if( this->rotate_default_flag == false ) { lotate_check_flag = logger_logrotate_utility::acccess_log_LogrotateParamCheck( rotatedata , access_log_property ); } if ( lotate_check_flag == true ) { logger_logrotate_utility::set_appender(access_log_property,LOGGER_ACCESS_LAYOUT,access_log_property.log_filename_value); } return(lotate_check_flag); } void l7vs::logger_implement_access::addRef() { access_cnt++; } void l7vs::logger_implement_access::releaseRef() { access_cnt--; } bool l7vs::logger_implement_access::operator<=(const int access_num ) { return( access_cnt <= access_num ); } std::string l7vs::logger_implement_access::getAcLogFileName() { return( access_log_file_name_ ); } bool l7vs::logger_implement_access::checkRotateParameterComp(accesslog_rotate_map_type &rotatedata) { bool comp_flg = true; for( accesslog_rotate_map_type_iterator itr_comp_in = rotatedata.begin(); itr_comp_in != rotatedata.end(); itr_comp_in++ ) { accesslog_rotate_map_type_iterator itr_find = aclog_args.find( itr_comp_in->first ); if ( itr_find != aclog_args.end() ) { if( itr_comp_in->second != itr_find->second ) { comp_flg = false; } } else { comp_flg = false; } if( comp_flg == false ) { break; } } return(comp_flg); } bool l7vs::logger_implement_access::is_rotate_default_flag() { return(rotate_default_flag); } // OtH[}bg 2008/12/07 20:08:31 [INFO] [[AccessLog] (CL)192.168.2.1 --> 192.168.2.2 --UM-- 192.168.1.101:37259 --> (RS-DST)192.168.1.106:80 ] /*! * output access info log. * * @param virtualservice endpoint info * @param client endpoint info * @param realserver connect origin info * @param realserver connect destination info * @param add msg * @retrun void */ void l7vs::logger_implement_access::putLog( const std::string& vsinfo, const std::string& cl_con_org, const std::string& rs_con_org, const std::string& rs_con_dest, const std::string& msg){ std::stringstream buf; buf << boost::format( "[ [AccessLog] (CL)%s --> %s --UM-- %s --> (RS-DST)%s %s]" ) % LOGGER_ACCESS_PROCESS_ID % vsinfo % cl_con_org % rs_con_org % rs_con_dest % msg; try { log4cxx::Logger::getLogger( access_log_file_name_ )->forcedLog( log4cxx::Level::getInfo(), buf.str(), log4cxx::spi::LocationInfo("", "", 0)); } catch (const std::exception& ex) { std::ostringstream oss; oss << "Logging Error (Access Log) : " << ex.what(); logger_logrotate_utility::loglotation_utility_logic_error( 118, oss.str(), __FILE__, __LINE__ ); } } <commit_msg>putlog関数インライン化<commit_after>/*! * @file logger_implement_access.cpp * @brief logger module implementation class For access log. * * L7VSD: Linux Virtual Server for Layer7 Load Balancing * Copyright (C) 2009 NTT COMWARE Corporation. * * This program 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 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 * 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 <iostream> #include <sstream> #include <iomanip> #include <limits.h> #include <log4cxx/logmanager.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/rolling/rollingfileappender.h> #include <log4cxx/rolling/fixedwindowrollingpolicy.h> #include <log4cxx/rolling/sizebasedtriggeringpolicy.h> #include <log4cxx/rolling/timebasedrollingpolicy.h> #include <log4cxx/consoleappender.h> #include <errno.h> #include <stdexcept> #include <boost/lexical_cast.hpp> #include "logger_implement_access.h" #include "logger_logrotate_utility.h" l7vs::logger_implement_access::logger_implement_access( const std::string &access_log_file_name) :access_cnt ( 1 ), initialized ( false ), rotate_default_flag( false ) { access_log_file_name_ = access_log_file_name; aclog_args.clear(); } bool l7vs::logger_implement_access::init( const bool rotate_default_flag, const appender_property& access_log_default_property, accesslog_rotate_map_type& rotatedata) { using namespace log4cxx; if (initialized) return true; bool rtnFlg = true; try { this->rotate_default_flag = rotate_default_flag; rtnFlg = this->setAcLoggerConf(access_log_default_property,rotatedata); } catch (const std::exception& e) { return false; } return (rtnFlg); } bool l7vs::logger_implement_access::setAcLoggerConf( const appender_property& access_log_default_property, accesslog_rotate_map_type& rotatedata) { bool lotate_check_flag = true; aclog_args = rotatedata; access_log_property.log_filename_value = access_log_file_name_; if( this->rotate_default_flag == false ) { lotate_check_flag = logger_logrotate_utility::acccess_log_LogrotateParamCheck( rotatedata, access_log_property ); } if ( lotate_check_flag == true ) { logger_logrotate_utility::set_appender( access_log_property, LOGGER_ACCESS_LAYOUT, access_log_property.log_filename_value); } return(lotate_check_flag); } void l7vs::logger_implement_access::addRef() { access_cnt++; } void l7vs::logger_implement_access::releaseRef() { access_cnt--; } bool l7vs::logger_implement_access::operator<=(const int access_num ) { return( access_cnt <= access_num ); } std::string l7vs::logger_implement_access::getAcLogFileName() { return( access_log_file_name_ ); } bool l7vs::logger_implement_access::checkRotateParameterComp( accesslog_rotate_map_type &rotatedata) { bool comp_flg = true; accesslog_rotate_map_type_iterator itr_comp_in; accesslog_rotate_map_type_iterator itr_find; for( itr_comp_in = rotatedata.begin(); itr_comp_in != rotatedata.end() ; itr_comp_in++ ){ accesslog_rotate_map_type_iterator itr_find = aclog_args.find( itr_comp_in->first ); if ( itr_find != aclog_args.end() ) { if( itr_comp_in->second != itr_find->second ) { comp_flg = false; } } else { comp_flg = false; } if( comp_flg == false ) { break; } } return(comp_flg); } bool l7vs::logger_implement_access::is_rotate_default_flag() { return(rotate_default_flag); } <|endoftext|>
<commit_before>/* * Copyright 2002-2005 The Apache Software Foundation. * * 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. */ /* * XSEC * * TXFMOutputFile := Transform that outputs the byte stream to a file without changing * the actual data in any way * * $Id$ * */ #include <xsec/transformers/TXFMOutputFile.hpp> #include <xsec/framework/XSECException.hpp> XERCES_CPP_NAMESPACE_USE // Destructor TXFMOutputFile::~TXFMOutputFile() { f.close(); } // Methods to set the inputs void TXFMOutputFile::setInput(TXFMBase *newInput) { input = newInput; if (newInput->getOutputType() != TXFMBase::BYTE_STREAM) { throw XSECException(XSECException::TransformInputOutputFail, "OutputFile transform requires BYTE_STREAM input"); } keepComments = input->getCommentsStatus(); } bool TXFMOutputFile::setFile(char * const fileName) { // Open a file for outputting using std::ios; f.open(fileName, ios::binary|ios::out|ios::app); if (f.is_open()) { f.write("\n----- BEGIN -----\n", 19); return true; } return false; } // Methods to get tranform output type and input requirement TXFMBase::ioType TXFMOutputFile::getInputType(void) { return TXFMBase::BYTE_STREAM; } TXFMBase::ioType TXFMOutputFile::getOutputType(void) { return TXFMBase::BYTE_STREAM; } TXFMBase::nodeType TXFMOutputFile::getNodeType(void) { return TXFMBase::DOM_NODE_NONE; } // Methods to get output data unsigned int TXFMOutputFile::readBytes(XMLByte * const toFill, unsigned int maxToFill) { unsigned int sz; sz = input->readBytes(toFill, maxToFill); if (f.is_open()) f.write((char *) toFill, sz); return sz; } DOMDocument * TXFMOutputFile::getDocument() { return NULL; } DOMNode * TXFMOutputFile::getFragmentNode() { return NULL; }; const XMLCh * TXFMOutputFile::getFragmentId() { return NULL; // Empty string } <commit_msg>Add an END to bracket the output.<commit_after>/* * Copyright 2002-2005 The Apache Software Foundation. * * 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. */ /* * XSEC * * TXFMOutputFile := Transform that outputs the byte stream to a file without changing * the actual data in any way * * $Id$ * */ #include <xsec/transformers/TXFMOutputFile.hpp> #include <xsec/framework/XSECException.hpp> XERCES_CPP_NAMESPACE_USE // Destructor TXFMOutputFile::~TXFMOutputFile() { if (f.is_open()) f.write("\n----- END -----\n", 17); f.close(); } // Methods to set the inputs void TXFMOutputFile::setInput(TXFMBase *newInput) { input = newInput; if (newInput->getOutputType() != TXFMBase::BYTE_STREAM) { throw XSECException(XSECException::TransformInputOutputFail, "OutputFile transform requires BYTE_STREAM input"); } keepComments = input->getCommentsStatus(); } bool TXFMOutputFile::setFile(char * const fileName) { // Open a file for outputting using std::ios; f.open(fileName, ios::binary|ios::out|ios::app); if (f.is_open()) { f.write("\n----- BEGIN -----\n", 19); return true; } return false; } // Methods to get tranform output type and input requirement TXFMBase::ioType TXFMOutputFile::getInputType(void) { return TXFMBase::BYTE_STREAM; } TXFMBase::ioType TXFMOutputFile::getOutputType(void) { return TXFMBase::BYTE_STREAM; } TXFMBase::nodeType TXFMOutputFile::getNodeType(void) { return TXFMBase::DOM_NODE_NONE; } // Methods to get output data unsigned int TXFMOutputFile::readBytes(XMLByte * const toFill, unsigned int maxToFill) { unsigned int sz; sz = input->readBytes(toFill, maxToFill); if (f.is_open()) f.write((char *) toFill, sz); return sz; } DOMDocument * TXFMOutputFile::getDocument() { return NULL; } DOMNode * TXFMOutputFile::getFragmentNode() { return NULL; }; const XMLCh * TXFMOutputFile::getFragmentId() { return NULL; // Empty string } <|endoftext|>
<commit_before>/** * This file is part of the "tsdb" project * Copyright (c) 2015 Paul Asmuth, FnordCorp B.V. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <tsdb/LogPartitionReplication.h> #include <tsdb/ReplicationScheme.h> #include <stx/logging.h> #include <stx/io/fileutil.h> #include <stx/protobuf/msg.h> using namespace stx; namespace tsdb { const size_t LogPartitionReplication::kMaxBatchSizeRows = 512; const size_t LogPartitionReplication::kMaxBatchSizeBytes = 1024 * 1024 * 50; // 50 MB LogPartitionReplication::LogPartitionReplication( RefPtr<Partition> partition, RefPtr<ReplicationScheme> repl_scheme, http::HTTPConnectionPool* http) : PartitionReplication(partition, repl_scheme, http) {} bool LogPartitionReplication::needsReplication() const { auto replicas = repl_scheme_->replicasFor(snap_->key); if (replicas.size() == 0) { return false; } auto repl_state = fetchReplicationState(); auto head_offset = snap_->nrecs; for (const auto& r : replicas) { const auto& replica_offset = replicatedOffsetFor(repl_state, r.unique_id); if (replica_offset < head_offset) { return true; } } return false; } void LogPartitionReplication::replicateTo( const ReplicaRef& replica, uint64_t replicated_offset) { PartitionReader reader(snap_); size_t batch_size = 0; RecordEnvelopeList batch; reader.fetchRecords( replicated_offset, size_t(-1), [this, &batch, &replica, &replicated_offset, &batch_size] ( const SHA1Hash& record_id, const void* record_data, size_t record_size) { auto rec = batch.add_records(); rec->set_tsdb_namespace(snap_->state.tsdb_namespace()); rec->set_table_name(snap_->state.table_key()); rec->set_partition_sha1(snap_->key.toString()); rec->set_record_id(record_id.toString()); rec->set_record_data(record_data, record_size); batch_size += record_size; if (batch_size > kMaxBatchSizeBytes || batch.records().size() > kMaxBatchSizeRows) { uploadBatchTo(replica, batch); batch.mutable_records()->Clear(); batch_size = 0; } }); if (batch.records().size() > 0) { uploadBatchTo(replica, batch); } } void LogPartitionReplication::uploadBatchTo( const ReplicaRef& replica, const RecordEnvelopeList& batch) { auto body = msg::encode(batch); URI uri(StringUtil::format("http://$0/tsdb/insert", replica.addr)); http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery()); req.addHeader("Host", uri.hostAndPort()); req.addHeader("Content-Type", "application/fnord-msg"); req.addBody(body->data(), body->size()); auto res = http_->executeRequest(req); res.wait(); const auto& r = res.get(); if (r.statusCode() != 201) { RAISEF(kRuntimeError, "received non-201 response: $0", r.body().toString()); } } bool LogPartitionReplication::replicate() { auto replicas = repl_scheme_->replicasFor(snap_->key); if (replicas.size() == 0) { return true; } auto repl_state = fetchReplicationState(); auto head_offset = snap_->nrecs; bool dirty = false; bool success = true; for (const auto& r : replicas) { const auto& replica_offset = replicatedOffsetFor(repl_state, r.unique_id); if (replica_offset < head_offset) { logTrace( "tsdb", "Replicating partition $0/$1/$2 to $3", snap_->state.tsdb_namespace(), snap_->state.table_key(), snap_->key.toString(), r.addr); try { replicateTo(r, replica_offset); setReplicatedOffsetFor(&repl_state, r.unique_id, head_offset); dirty = true; } catch (const std::exception& e) { success = false; stx::logError( "tsdb", e, "Error while replicating partition $0/$1/$2 to $3", snap_->state.tsdb_namespace(), snap_->state.table_key(), snap_->key.toString(), r.addr); } } } if (dirty) { commitReplicationState(repl_state); } return success; } } // namespace tdsb <commit_msg>increase replication batch size again<commit_after>/** * This file is part of the "tsdb" project * Copyright (c) 2015 Paul Asmuth, FnordCorp B.V. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <tsdb/LogPartitionReplication.h> #include <tsdb/ReplicationScheme.h> #include <stx/logging.h> #include <stx/io/fileutil.h> #include <stx/protobuf/msg.h> using namespace stx; namespace tsdb { const size_t LogPartitionReplication::kMaxBatchSizeRows = 8192; const size_t LogPartitionReplication::kMaxBatchSizeBytes = 1024 * 1024 * 50; // 50 MB LogPartitionReplication::LogPartitionReplication( RefPtr<Partition> partition, RefPtr<ReplicationScheme> repl_scheme, http::HTTPConnectionPool* http) : PartitionReplication(partition, repl_scheme, http) {} bool LogPartitionReplication::needsReplication() const { auto replicas = repl_scheme_->replicasFor(snap_->key); if (replicas.size() == 0) { return false; } auto repl_state = fetchReplicationState(); auto head_offset = snap_->nrecs; for (const auto& r : replicas) { const auto& replica_offset = replicatedOffsetFor(repl_state, r.unique_id); if (replica_offset < head_offset) { return true; } } return false; } void LogPartitionReplication::replicateTo( const ReplicaRef& replica, uint64_t replicated_offset) { PartitionReader reader(snap_); size_t batch_size = 0; RecordEnvelopeList batch; reader.fetchRecords( replicated_offset, size_t(-1), [this, &batch, &replica, &replicated_offset, &batch_size] ( const SHA1Hash& record_id, const void* record_data, size_t record_size) { auto rec = batch.add_records(); rec->set_tsdb_namespace(snap_->state.tsdb_namespace()); rec->set_table_name(snap_->state.table_key()); rec->set_partition_sha1(snap_->key.toString()); rec->set_record_id(record_id.toString()); rec->set_record_data(record_data, record_size); batch_size += record_size; if (batch_size > kMaxBatchSizeBytes || batch.records().size() > kMaxBatchSizeRows) { uploadBatchTo(replica, batch); batch.mutable_records()->Clear(); batch_size = 0; } }); if (batch.records().size() > 0) { uploadBatchTo(replica, batch); } } void LogPartitionReplication::uploadBatchTo( const ReplicaRef& replica, const RecordEnvelopeList& batch) { auto body = msg::encode(batch); URI uri(StringUtil::format("http://$0/tsdb/insert", replica.addr)); http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery()); req.addHeader("Host", uri.hostAndPort()); req.addHeader("Content-Type", "application/fnord-msg"); req.addBody(body->data(), body->size()); auto res = http_->executeRequest(req); res.wait(); const auto& r = res.get(); if (r.statusCode() != 201) { RAISEF(kRuntimeError, "received non-201 response: $0", r.body().toString()); } } bool LogPartitionReplication::replicate() { auto replicas = repl_scheme_->replicasFor(snap_->key); if (replicas.size() == 0) { return true; } auto repl_state = fetchReplicationState(); auto head_offset = snap_->nrecs; bool dirty = false; bool success = true; for (const auto& r : replicas) { const auto& replica_offset = replicatedOffsetFor(repl_state, r.unique_id); if (replica_offset < head_offset) { logTrace( "tsdb", "Replicating partition $0/$1/$2 to $3", snap_->state.tsdb_namespace(), snap_->state.table_key(), snap_->key.toString(), r.addr); try { replicateTo(r, replica_offset); setReplicatedOffsetFor(&repl_state, r.unique_id, head_offset); dirty = true; } catch (const std::exception& e) { success = false; stx::logError( "tsdb", e, "Error while replicating partition $0/$1/$2 to $3", snap_->state.tsdb_namespace(), snap_->state.table_key(), snap_->key.toString(), r.addr); } } } if (dirty) { commitReplicationState(repl_state); } return success; } } // namespace tdsb <|endoftext|>
<commit_before>/* * Author: * - Vittoriano Muttillo <vittoriano.muttillo@gmail.com> * - Giacomo Valente <giakomo.87v@gmail.com> * * Copyright (c) 2015 Vittoriano Muttillo, Giacomo Valente. * * 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 <iostream> #include <unistd.h> #include <mraa.hpp> #include <grove.hpp> #include <jhd1313m1.hpp> #include <uln200xa.hpp> /** * Move photovoltaic panel following the maximum brightness of the sun.\n\n * The idea is to move photovoltaic panel (represented by a motor) according to * the movement of the sun, directing it towards the maximum light radiated * during the day using the maximum light intensity detected by two light * sensor placed parallel to each other.\n * The idea is to compute the sensors average light in a calibration step and * use this number to move motor according to the movement of light. * * Hhardware Sensors used:\n * GroveLight sensor connected to any analog port. * GroveLight sensor connected to any analog port * ULN200XA Stepper Motor connected to pin 6,7,8,9\n * Jhd1313m1 LCD connected to any I2C on the Grove Base Shield\n * Stepper Motor Driver Uln200xa connected in this way:\n * -- I1 -> pin D6\n * -- I2 -> pin D7\n * -- I3 -> pin D8\n * -- I4 -> pin D9\n * -- GND -> GND\n * -- Vcc -> 5V (Vcc)\n * -- Vm -> NC (Not Connected) * * Use a platform with I2C, Analog and GPIO capabilities */ using namespace std; // Threshold of light #define THRESHOLD 2 // Steps per revolution #define STEPS_PER_REV 4096 // Left and right light average static variables static int lightLAVG, lightRAVG; void solarTracker(upm::Jhd1313m1* lcd, upm::GroveLight* lightL, upm::GroveLight* lightR, upm::ULN200XA* uln200xa) { int lightLST, lightRST; // Since LCD displays data in string format, we need to convert (light value) // from integer to string lightLST = lightL->value(); char tdataL[10]; lightRST = lightR->value(); char tdataR[10]; sprintf(tdataL, "%d", lightLST); sprintf(tdataR, "%d", lightRST); // Writing light info on LCD lcd->setCursor(0, 0); lcd->write("Left: "); lcd->setCursor(1, 0); lcd->write("Right: "); lcd->setCursor(0, 6); lcd->write(tdataL); lcd->setCursor(1, 7); lcd->write(tdataR); /* To move the motor correctly, we have to choose the right direction. * To obtain it, we have three condition: * 1) The light sensors value is under a specific threshold (don't move) * 2) The Left light sensor value is under the average Left sensor value. * In this case we have two condition: * a) Left light sensor value is smaller than Right value (turn clockwise) * b) Left light sensor value is bigger than Right value (turn counter clockwise) * 3) The Right light sensor value is under the average Right sensor value. * In this case we have two condition: * a) Right light sensor value is smaller than Left value (turn clockwise) * b) Right light sensor value is bigger than Left value (turn counter clockwise) */ // 1) if ((lightLST < THRESHOLD) && (lightRST) < THRESHOLD) { // Lightless state lcd->setCursor(0, 0); lcd->write("No sun"); lcd->clear(); // 2) } else if (lightLST < lightLAVG) { // a) if (lightLST < lightRST) { // Rotating 1/32 revolution clockwise uln200xa->setDirection(ULN200XA_DIR_CW); // b) } else if (lightLST > lightRST) { // Rotating 1/32 revolution clockwise uln200xa->setDirection(ULN200XA_DIR_CCW); } uln200xa->stepperSteps(128); // 3) } else if (lightRST < lightRAVG) { // a) if (lightRST < lightLST) { // Rotating 1/32 revolution counter clockwise uln200xa->setDirection(ULN200XA_DIR_CCW); // b) } else if (lightRST > lightLST) { // Rotating 1/32 revolution counter clockwise uln200xa->setDirection(ULN200XA_DIR_CW); } uln200xa->stepperSteps(128); } sleep(1); } int main() { int i2CPort, aPin1, aPin2; string unknownPlatformMessage = "This sample uses the MRAA/UPM library for I/O access, " "you are running it on an unrecognized platform. " "You may need to modify the MRAA/UPM initialization code to " "ensure it works properly on your platform.\n\n"; // check which board we are running on Platform platform = getPlatformType(); switch (platform) { case INTEL_UP2: i2cPort = 0; // I2C Connector #ifdef USING_GROVE_PI_SHIELD //512 offset needed for the shield aPin1 = 1 + 512; // A1 Connector aPin2 = 2 + 512; // A2 Connector break; #else cerr << "Not using Grove provide your pinout here" << endl; return -1; #endif default: cerr << unknownPlatformMessage; } #ifdef USING_GROVE_PI_SHIELD addSubplatform(GROVEPI, "0"); #endif // check if running as root int euid = geteuid(); if (euid) { cerr << "This project uses Mraa I/O operations, but you're not running as 'root'.\n" "The IO operations below might fail.\n" "See the project's Readme for more info.\n\n"; } // LCD screen object (the lcd is connected to I2C port, bus 0) upm::Jhd1313m1 *lcd = new upm::Jhd1313m1(i2CPort); //Left light sensor object upm::GroveLight* lightL = new upm::GroveLight(aPin1); //Right light sensor object upm::GroveLight* lightR = new upm::GroveLight(aPin2); /* Instantiate a Stepper motor on a ULN200XA Dual H-Bridge. * Wire the pins so that I1 is pin D6, I2 is D7, I3 is D8 and I4 is D9 */ upm::ULN200XA* uln200xa = new upm::ULN200XA(STEPS_PER_REV, 6, 7, 8, 9); // Simple error checking if ((lcd == NULL) || (lightL == NULL) || (lightR == NULL) || (uln200xa == NULL)) { std::cerr << "Can't create all objects, exiting" << std::endl; return mraa::ERROR_UNSPECIFIED; } // Writing intro text lcd->setCursor(0, 0); lcd->write("Smart PV"); lcd->setCursor(1, 0); lcd->write("for Edison Board"); // Set speed of Grove Gear Stepper Motor with Drive uln200xa->setSpeed(7); // Calibration Step int brightL1, brightL2, brightR1, brightR2; // Rotating 1/8 revolution clockwise uln200xa->setDirection(ULN200XA_DIR_CW); uln200xa->stepperSteps(STEPS_PER_REV / 8); brightL1 = lightL->value(); brightR1 = lightR->value(); sleep(1); // Rotating 1/4 revolution counter clockwise uln200xa->setDirection(ULN200XA_DIR_CCW); uln200xa->stepperSteps(STEPS_PER_REV / 4); brightL2 = lightL->value(); brightR2 = lightR->value(); sleep(1); // Compute average light sensor value lightLAVG = (brightL1 + brightL2) / 2; lightRAVG = (brightR1 + brightR2) / 2; // Init text on display // Loop forever updating the lightL and lightR values every second while (true) { solarTracker(lcd, lightL, lightR, uln200xa); } return mraa::SUCCESS; } <commit_msg>Fix bugs in smart pv sample<commit_after>/* * Author: * - Vittoriano Muttillo <vittoriano.muttillo@gmail.com> * - Giacomo Valente <giakomo.87v@gmail.com> * * Copyright (c) 2015 Vittoriano Muttillo, Giacomo Valente. * * 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 <iostream> #include <unistd.h> #include <mraa.hpp> #include <grove.hpp> #include <jhd1313m1.hpp> #include <uln200xa.hpp> /** * Move photovoltaic panel following the maximum brightness of the sun.\n\n * The idea is to move photovoltaic panel (represented by a motor) according to * the movement of the sun, directing it towards the maximum light radiated * during the day using the maximum light intensity detected by two light * sensor placed parallel to each other.\n * The idea is to compute the sensors average light in a calibration step and * use this number to move motor according to the movement of light. * * Hhardware Sensors used:\n * GroveLight sensor connected to any analog port. * GroveLight sensor connected to any analog port * ULN200XA Stepper Motor connected to pin 6,7,8,9\n * Jhd1313m1 LCD connected to any I2C on the Grove Base Shield\n * Stepper Motor Driver Uln200xa connected in this way:\n * -- I1 -> pin D6\n * -- I2 -> pin D7\n * -- I3 -> pin D8\n * -- I4 -> pin D9\n * -- GND -> GND\n * -- Vcc -> 5V (Vcc)\n * -- Vm -> NC (Not Connected) * * Use a platform with I2C, Analog and GPIO capabilities */ using namespace std; using namespace mraa; // Threshold of light #define THRESHOLD 2 // Steps per revolution #define STEPS_PER_REV 4096 // Left and right light average static variables static int lightLAVG, lightRAVG; void solarTracker(upm::Jhd1313m1* lcd, upm::GroveLight* lightL, upm::GroveLight* lightR, upm::ULN200XA* uln200xa) { int lightLST, lightRST; // Since LCD displays data in string format, we need to convert (light value) // from integer to string lightLST = lightL->value(); char tdataL[10]; lightRST = lightR->value(); char tdataR[10]; sprintf(tdataL, "%d", lightLST); sprintf(tdataR, "%d", lightRST); // Writing light info on LCD lcd->setCursor(0, 0); lcd->write("Left: "); lcd->setCursor(1, 0); lcd->write("Right: "); lcd->setCursor(0, 6); lcd->write(tdataL); lcd->setCursor(1, 7); lcd->write(tdataR); /* To move the motor correctly, we have to choose the right direction. * To obtain it, we have three condition: * 1) The light sensors value is under a specific threshold (don't move) * 2) The Left light sensor value is under the average Left sensor value. * In this case we have two condition: * a) Left light sensor value is smaller than Right value (turn clockwise) * b) Left light sensor value is bigger than Right value (turn counter clockwise) * 3) The Right light sensor value is under the average Right sensor value. * In this case we have two condition: * a) Right light sensor value is smaller than Left value (turn clockwise) * b) Right light sensor value is bigger than Left value (turn counter clockwise) */ // 1) if ((lightLST < THRESHOLD) && (lightRST) < THRESHOLD) { // Lightless state lcd->setCursor(0, 0); lcd->write("No sun"); lcd->clear(); // 2) } else if (lightLST < lightLAVG) { // a) if (lightLST < lightRST) { // Rotating 1/32 revolution clockwise uln200xa->setDirection(ULN200XA_DIR_CW); // b) } else if (lightLST > lightRST) { // Rotating 1/32 revolution clockwise uln200xa->setDirection(ULN200XA_DIR_CCW); } uln200xa->stepperSteps(128); // 3) } else if (lightRST < lightRAVG) { // a) if (lightRST < lightLST) { // Rotating 1/32 revolution counter clockwise uln200xa->setDirection(ULN200XA_DIR_CCW); // b) } else if (lightRST > lightLST) { // Rotating 1/32 revolution counter clockwise uln200xa->setDirection(ULN200XA_DIR_CW); } uln200xa->stepperSteps(128); } sleep(1); } int main() { int i2cPort, aPin1, aPin2; string unknownPlatformMessage = "This sample uses the MRAA/UPM library for I/O access, " "you are running it on an unrecognized platform. " "You may need to modify the MRAA/UPM initialization code to " "ensure it works properly on your platform.\n\n"; // check which board we are running on Platform platform = getPlatformType(); switch (platform) { case INTEL_UP2: i2cPort = 0; // I2C Connector #ifdef USING_GROVE_PI_SHIELD //512 offset needed for the shield aPin1 = 1 + 512; // A1 Connector aPin2 = 2 + 512; // A2 Connector break; #else cerr << "Not using Grove provide your pinout here" << endl; return -1; #endif default: cerr << unknownPlatformMessage; } #ifdef USING_GROVE_PI_SHIELD addSubplatform(GROVEPI, "0"); #endif // check if running as root int euid = geteuid(); if (euid) { cerr << "This project uses Mraa I/O operations, but you're not running as 'root'.\n" "The IO operations below might fail.\n" "See the project's Readme for more info.\n\n"; } // LCD screen object (the lcd is connected to I2C port, bus 0) upm::Jhd1313m1 *lcd = new upm::Jhd1313m1(i2cPort); //Left light sensor object upm::GroveLight* lightL = new upm::GroveLight(aPin1); //Right light sensor object upm::GroveLight* lightR = new upm::GroveLight(aPin2); /* Instantiate a Stepper motor on a ULN200XA Dual H-Bridge. * Wire the pins so that I1 is pin D6, I2 is D7, I3 is D8 and I4 is D9 */ upm::ULN200XA* uln200xa = new upm::ULN200XA(STEPS_PER_REV, 6, 7, 8, 9); // Simple error checking if ((lcd == NULL) || (lightL == NULL) || (lightR == NULL) || (uln200xa == NULL)) { std::cerr << "Can't create all objects, exiting" << std::endl; return mraa::ERROR_UNSPECIFIED; } // Writing intro text lcd->setCursor(0, 0); lcd->write("Smart PV"); lcd->setCursor(1, 0); lcd->write("for Edison Board"); // Set speed of Grove Gear Stepper Motor with Drive uln200xa->setSpeed(7); // Calibration Step int brightL1, brightL2, brightR1, brightR2; // Rotating 1/8 revolution clockwise uln200xa->setDirection(ULN200XA_DIR_CW); uln200xa->stepperSteps(STEPS_PER_REV / 8); brightL1 = lightL->value(); brightR1 = lightR->value(); sleep(1); // Rotating 1/4 revolution counter clockwise uln200xa->setDirection(ULN200XA_DIR_CCW); uln200xa->stepperSteps(STEPS_PER_REV / 4); brightL2 = lightL->value(); brightR2 = lightR->value(); sleep(1); // Compute average light sensor value lightLAVG = (brightL1 + brightL2) / 2; lightRAVG = (brightR1 + brightR2) / 2; // Init text on display // Loop forever updating the lightL and lightR values every second while (true) { solarTracker(lcd, lightL, lightR, uln200xa); } return mraa::SUCCESS; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_META_IS_DETECTED_HPP #define STAN_MATH_PRIM_SCAL_META_IS_DETECTED_HPP #include <stan/math/prim/meta/void_t.hpp> #include <type_traits> namespace stan { template <typename, template <typename> class, typename = void> struct is_detected : std::false_type {}; /** * Checks whether a valid type is detected. Most commonly used to detect * attributes of objects. * @tparam T The type to be checked. * @tparam Op a template template type which attempts to define a member * of an object. */ template <typename T, template <typename...> class Op> struct is_detected<T, Op, void_t<Op<T>>> : std::true_type {}; } // namespace stan #endif <commit_msg>fix template parameter to be variadic for forward decleration of is_detected<commit_after>#ifndef STAN_MATH_PRIM_SCAL_META_IS_DETECTED_HPP #define STAN_MATH_PRIM_SCAL_META_IS_DETECTED_HPP #include <stan/math/prim/meta/void_t.hpp> #include <type_traits> namespace stan { template <typename, template <typename...> class, typename = void> struct is_detected : std::false_type {}; /** * Checks whether a valid type is detected. Most commonly used to detect * attributes of objects. * @tparam T The type to be checked. * @tparam Op a template template type which attempts to define a member * of an object. */ template <typename T, template <typename...> class Op> struct is_detected<T, Op, void_t<Op<T>>> : std::true_type {}; } // namespace stan #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_FUNCTOR_ODE_ADAMS_HPP #define STAN_MATH_REV_FUNCTOR_ODE_ADAMS_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/functor/cvodes_integrator.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <ostream> #include <vector> namespace stan { namespace math { /** * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of * times, { t1, t2, t3, ... } using the non-stiff Adams-Moulton solver from * CVODES. * * \p f must define an operator() with the signature as: * template<typename T_t, typename T_y, typename... T_Args> * Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1> * operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y, * std::ostream* msgs, const T_Args&... args); * * t is the time, y is the vector-valued state, msgs is a stream for error * messages, and args are optional arguments passed to the ODE solve function * (which are passed through to \p f without modification). * * @tparam F Type of ODE right hand side * @tparam T_0 Type of initial time * @tparam T_ts Type of output times * @tparam T_Args Types of pass-through parameters * * @param function_name Calling function name (for printing debugging messages) * @param f Right hand side of the ODE * @param y0 Initial state * @param t0 Initial time * @param ts Times at which to solve the ODE at. All values must be sorted and * not less than t0. * @param relative_tolerance Relative tolerance passed to CVODES * @param absolute_tolerance Absolute tolerance passed to CVODES * @param max_num_steps Upper limit on the number of integration steps to * take between each output (error if exceeded) * @param[in, out] msgs the print stream for warning messages * @param args Extra arguments passed unmodified through to ODE right hand side * @return Solution to ODE at times \p ts */ template <typename F, typename T_y0, typename T_t0, typename T_ts, typename... T_Args, require_eigen_col_vector_t<T_y0>* = nullptr> std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, T_Args...>, Eigen::Dynamic, 1>> ode_adams_tol_impl(const char* function_name, const F& f, const T_y0& y0, const T_t0& t0, const std::vector<T_ts>& ts, double relative_tolerance, double absolute_tolerance, long int max_num_steps, // NOLINT(runtime/int) std::ostream* msgs, const T_Args&... args) { const auto& args_ref_tuple = std::make_tuple(to_ref(args)...); return apply( [&](const auto&... args_refs) { cvodes_integrator<CV_ADAMS, F, T_y0, T_t0, T_ts, ref_type_t<T_Args>...> integrator(function_name, f, y0, t0, ts, relative_tolerance, absolute_tolerance, max_num_steps, msgs, args_refs...); return integrator(); }, args_ref_tuple); } /** * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of * times, { t1, t2, t3, ... } using the non-stiff Adams-Moulton solver from * CVODES. * * \p f must define an operator() with the signature as: * template<typename T_t, typename T_y, typename... T_Args> * Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1> * operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y, * std::ostream* msgs, const T_Args&... args); * * t is the time, y is the vector-valued state, msgs is a stream for error * messages, and args are optional arguments passed to the ODE solve function * (which are passed through to \p f without modification). * * @tparam F Type of ODE right hand side * @tparam T_0 Type of initial time * @tparam T_ts Type of output times * @tparam T_Args Types of pass-through parameters * * @param f Right hand side of the ODE * @param y0 Initial state * @param t0 Initial time * @param ts Times at which to solve the ODE at. All values must be sorted and * not less than t0. * @param relative_tolerance Relative tolerance passed to CVODES * @param absolute_tolerance Absolute tolerance passed to CVODES * @param max_num_steps Upper limit on the number of integration steps to * take between each output (error if exceeded) * @param[in, out] msgs the print stream for warning messages * @param args Extra arguments passed unmodified through to ODE right hand side * @return Solution to ODE at times \p ts */ template <typename F, typename T_y0, typename T_t0, typename T_ts, typename... T_Args, require_eigen_col_vector_t<T_y0>* = nullptr> std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, T_Args...>, Eigen::Dynamic, 1>> ode_adams_tol(const F& f, const T_y0& y0, const T_t0& t0, const std::vector<T_ts>& ts, double relative_tolerance, double absolute_tolerance, long int max_num_steps, // NOLINT(runtime/int) std::ostream* msgs, const T_Args&... args) { return ode_adams_tol_impl("ode_adams_tol", f, y0, t0, ts, relative_tolerance, absolute_tolerance, max_num_steps, msgs, args...); } /** * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of * times, { t1, t2, t3, ... } using the non-stiff Adams-Moulton * solver in CVODES with defaults for relative_tolerance, absolute_tolerance, * and max_num_steps. * * \p f must define an operator() with the signature as: * template<typename T_t, typename T_y, typename... T_Args> * Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1> * operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y, * std::ostream* msgs, const T_Args&... args); * * t is the time, y is the vector-valued state, msgs is a stream for error * messages, and args are optional arguments passed to the ODE solve function * (which are passed through to \p f without modification). * * @tparam F Type of ODE right hand side * @tparam T_0 Type of initial time * @tparam T_ts Type of output times * @tparam T_Args Types of pass-through parameters * * @param f Right hand side of the ODE * @param y0 Initial state * @param t0 Initial time * @param ts Times at which to solve the ODE at. All values must be sorted and * not less than t0. * @param[in, out] msgs the print stream for warning messages * @param args Extra arguments passed unmodified through to ODE right hand side * @return Solution to ODE at times \p ts */ template <typename F, typename T_y0, typename T_t0, typename T_ts, typename... T_Args, require_eigen_col_vector_t<T_y0>* = nullptr> std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, T_Args...>, Eigen::Dynamic, 1>> ode_adams(const F& f, const T_y0& y0, const T_t0& t0, const std::vector<T_ts>& ts, std::ostream* msgs, const T_Args&... args) { double relative_tolerance = 1e-10; double absolute_tolerance = 1e-10; long int max_num_steps = 1e8; // NOLINT(runtime/int) return ode_adams_tol_impl("ode_adams", f, y0, t0, ts, relative_tolerance, absolute_tolerance, max_num_steps, msgs, args...); } } // namespace math } // namespace stan #endif <commit_msg>reroute ode_adams to ode_bdf_adjoint<commit_after>#ifndef STAN_MATH_REV_FUNCTOR_ODE_ADAMS_HPP #define STAN_MATH_REV_FUNCTOR_ODE_ADAMS_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/functor/cvodes_integrator.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <ostream> #include <vector> namespace stan { namespace math { /** * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of * times, { t1, t2, t3, ... } using the non-stiff Adams-Moulton solver from * CVODES. * * \p f must define an operator() with the signature as: * template<typename T_t, typename T_y, typename... T_Args> * Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1> * operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y, * std::ostream* msgs, const T_Args&... args); * * t is the time, y is the vector-valued state, msgs is a stream for error * messages, and args are optional arguments passed to the ODE solve function * (which are passed through to \p f without modification). * * @tparam F Type of ODE right hand side * @tparam T_0 Type of initial time * @tparam T_ts Type of output times * @tparam T_Args Types of pass-through parameters * * @param function_name Calling function name (for printing debugging messages) * @param f Right hand side of the ODE * @param y0 Initial state * @param t0 Initial time * @param ts Times at which to solve the ODE at. All values must be sorted and * not less than t0. * @param relative_tolerance Relative tolerance passed to CVODES * @param absolute_tolerance Absolute tolerance passed to CVODES * @param max_num_steps Upper limit on the number of integration steps to * take between each output (error if exceeded) * @param[in, out] msgs the print stream for warning messages * @param args Extra arguments passed unmodified through to ODE right hand side * @return Solution to ODE at times \p ts */ template <typename F, typename T_y0, typename T_t0, typename T_ts, typename... T_Args, require_eigen_col_vector_t<T_y0>* = nullptr> std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, T_Args...>, Eigen::Dynamic, 1>> ode_adams_tol_impl(const char* function_name, const F& f, const T_y0& y0, const T_t0& t0, const std::vector<T_ts>& ts, double relative_tolerance, double absolute_tolerance, long int max_num_steps, // NOLINT(runtime/int) std::ostream* msgs, const T_Args&... args) { /* const auto& args_ref_tuple = std::make_tuple(to_ref(args)...); return apply( [&](const auto&... args_refs) { cvodes_integrator<CV_ADAMS, F, T_y0, T_t0, T_ts, ref_type_t<T_Args>...> integrator(function_name, f, y0, t0, ts, relative_tolerance, absolute_tolerance, max_num_steps, msgs, args_refs...); return integrator(); }, args_ref_tuple); */ return ode_bdf_adjoint_tol(f, y0, t0, ts, relative_tolerance, absolute_tolerance, max_num_steps, msgs, args...); } /** * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of * times, { t1, t2, t3, ... } using the non-stiff Adams-Moulton solver from * CVODES. * * \p f must define an operator() with the signature as: * template<typename T_t, typename T_y, typename... T_Args> * Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1> * operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y, * std::ostream* msgs, const T_Args&... args); * * t is the time, y is the vector-valued state, msgs is a stream for error * messages, and args are optional arguments passed to the ODE solve function * (which are passed through to \p f without modification). * * @tparam F Type of ODE right hand side * @tparam T_0 Type of initial time * @tparam T_ts Type of output times * @tparam T_Args Types of pass-through parameters * * @param f Right hand side of the ODE * @param y0 Initial state * @param t0 Initial time * @param ts Times at which to solve the ODE at. All values must be sorted and * not less than t0. * @param relative_tolerance Relative tolerance passed to CVODES * @param absolute_tolerance Absolute tolerance passed to CVODES * @param max_num_steps Upper limit on the number of integration steps to * take between each output (error if exceeded) * @param[in, out] msgs the print stream for warning messages * @param args Extra arguments passed unmodified through to ODE right hand side * @return Solution to ODE at times \p ts */ template <typename F, typename T_y0, typename T_t0, typename T_ts, typename... T_Args, require_eigen_col_vector_t<T_y0>* = nullptr> std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, T_Args...>, Eigen::Dynamic, 1>> ode_adams_tol(const F& f, const T_y0& y0, const T_t0& t0, const std::vector<T_ts>& ts, double relative_tolerance, double absolute_tolerance, long int max_num_steps, // NOLINT(runtime/int) std::ostream* msgs, const T_Args&... args) { return ode_adams_tol_impl("ode_adams_tol", f, y0, t0, ts, relative_tolerance, absolute_tolerance, max_num_steps, msgs, args...); } /** * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of * times, { t1, t2, t3, ... } using the non-stiff Adams-Moulton * solver in CVODES with defaults for relative_tolerance, absolute_tolerance, * and max_num_steps. * * \p f must define an operator() with the signature as: * template<typename T_t, typename T_y, typename... T_Args> * Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1> * operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y, * std::ostream* msgs, const T_Args&... args); * * t is the time, y is the vector-valued state, msgs is a stream for error * messages, and args are optional arguments passed to the ODE solve function * (which are passed through to \p f without modification). * * @tparam F Type of ODE right hand side * @tparam T_0 Type of initial time * @tparam T_ts Type of output times * @tparam T_Args Types of pass-through parameters * * @param f Right hand side of the ODE * @param y0 Initial state * @param t0 Initial time * @param ts Times at which to solve the ODE at. All values must be sorted and * not less than t0. * @param[in, out] msgs the print stream for warning messages * @param args Extra arguments passed unmodified through to ODE right hand side * @return Solution to ODE at times \p ts */ template <typename F, typename T_y0, typename T_t0, typename T_ts, typename... T_Args, require_eigen_col_vector_t<T_y0>* = nullptr> std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, T_Args...>, Eigen::Dynamic, 1>> ode_adams(const F& f, const T_y0& y0, const T_t0& t0, const std::vector<T_ts>& ts, std::ostream* msgs, const T_Args&... args) { double relative_tolerance = 1e-10; double absolute_tolerance = 1e-10; long int max_num_steps = 1e8; // NOLINT(runtime/int) return ode_adams_tol_impl("ode_adams", f, y0, t0, ts, relative_tolerance, absolute_tolerance, max_num_steps, msgs, args...); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include "hexmap_widget.h" #include <QMouseEvent> #include <asdf_multiplat/main/asdf_multiplat.h> #include <asdf_multiplat/data/content_manager.h> #include "mainwindow.h" #include "ui_mainwindow.h" /// https://doc-snapshots.qt.io/qt5-dev/qopenglwidget.html using namespace std; using namespace glm; namespace { constexpr float zoom_per_scroll_tick = 0.1f; } using tool_type_e = asdf::hexmap::editor::editor_t::tool_type_e; hexmap_widget_t::hexmap_widget_t(QWidget* _parent) : QOpenGLWidget(_parent) , data_map(editor.map_data) { setFocusPolicy(Qt::StrongFocus); setFocus(); } void hexmap_widget_t::initializeGL() { // Set up the rendering context, load shaders and other resources, etc.: asdf::app.renderer = make_unique<asdf::asdf_renderer_t>(); //do this before content init. Content needs GL_State to exist asdf::app.renderer->init(); //loads screen shader, among other things asdf::Content.init(); //needed for Content::shader_path auto shader = asdf::Content.create_shader("hexmap", 330); asdf::Content.shaders.add_resource(shader); editor.init(); hex_map = editor.rendered_map.get(); hex_map->camera.position.z = 10; hex_map_initialized(editor); } void hexmap_widget_t::resizeGL(int w, int h) { hex_map->camera.viewport.size_d2 = vec2(w,h) / 2.0f; hex_map->camera.viewport.bottom_left = -1.0f * hex_map->camera.viewport.size_d2; emit camera_changed(hex_map->camera); } void hexmap_widget_t::paintGL() { glDisable(GL_DEPTH_TEST); auto& gl_clear_color = asdf::app.renderer->gl_clear_color; glClearColor(gl_clear_color.r , gl_clear_color.g , gl_clear_color.b , gl_clear_color.a); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); editor.render(); } glm::uvec2 hexmap_widget_t::map_size() const { return data_map.hex_grid.size; } glm::vec2 hexmap_widget_t::camera_pos() const { return vec2(hex_map->camera.position.x, hex_map->camera.position.y); } void hexmap_widget_t::camera_pos(glm::vec2 const& p, bool emit_signal) { hex_map->camera.position.x = p.x; hex_map->camera.position.y = p.y; if(emit_signal) emit camera_changed(hex_map->camera); } // there may be a better solution than a switch statement asdf::mouse_button_e asdf_button_from_qt(Qt::MouseButton button) { switch(button) { case Qt::NoButton: return asdf::mouse_no_button; case Qt::LeftButton: return asdf::mouse_left; case Qt::RightButton: return asdf::mouse_right; case Qt::MiddleButton: return asdf::mouse_middle; case Qt::ExtraButton1: return asdf::mouse_4; case Qt::ExtraButton2: return asdf::mouse_5; default: return asdf::mouse_no_button; } } void hexmap_widget_t::mousePressEvent(QMouseEvent* event) { auto& mouse = asdf::app.mouse_state; asdf::mouse_button_event_t asdf_event { mouse , asdf_button_from_qt(event->button()) , (event->flags() & Qt::MouseEventCreatedDoubleClick) > 0 }; LOG("x,y: %i, %i", event->x(), event->y()); mouse.mouse_down(asdf_event, adjusted_screen_coords(event->x(), event->y())); update(); } void hexmap_widget_t::mouseReleaseEvent(QMouseEvent* event) { auto& mouse = asdf::app.mouse_state; asdf::mouse_button_event_t asdf_event { mouse , asdf_button_from_qt(event->button()) , (event->flags() & Qt::MouseEventCreatedDoubleClick) > 0 }; mouse.mouse_up(asdf_event, adjusted_screen_coords(event->x(), event->y())); update(); } void hexmap_widget_t::mouseMoveEvent(QMouseEvent* event) { auto& mouse = asdf::app.mouse_state; asdf::mouse_motion_event_t asdf_event { mouse }; mouse.mouse_move(asdf_event, adjusted_screen_coords(event->x(), event->y())); update(); //lazy } void hexmap_widget_t::wheelEvent(QWheelEvent* event) { if(keyboard_mods == Qt::NoModifier) { main_window->ui->hexmap_vscroll->event(event); ///FIXME can this be solved without holding onto main_window? } else if(keyboard_mods == Qt::ShiftModifier) { main_window->ui->hexmap_hscroll->event(event); } else if(keyboard_mods == Qt::ControlModifier) { float num_steps = event->angleDelta().y() / 15.0f; hex_map->camera.position.z += num_steps * zoom_per_scroll_tick; update(); emit camera_changed(hex_map->camera); } } void hexmap_widget_t::keyPressEvent(QKeyEvent* event) { keyboard_mods = event->modifiers(); SDL_Keysym sdl_key_event; //being lazy and reusing sdl event for now sdl_key_event.sym = event->nativeVirtualKey(); //supposedly virtual keys are a standard sdl_key_event.mod = 0; sdl_key_event.mod |= KMOD_SHIFT * (event->modifiers() & Qt::ShiftModifier) > 0; sdl_key_event.mod |= KMOD_CTRL * (event->modifiers() & Qt::ControlModifier) > 0; sdl_key_event.mod |= KMOD_ALT * (event->modifiers() & Qt::AltModifier) > 0; sdl_key_event.mod |= KMOD_GUI * (event->modifiers() & Qt::MetaModifier) > 0; auto prev_tool = editor.current_tool; editor.input->on_key_down(sdl_key_event); if(prev_tool != editor.current_tool) emit editor_tool_changed(editor.current_tool); /// TODO only call this when editor does not handle key QWidget::keyPressEvent(event); } void hexmap_widget_t::keyReleaseEvent(QKeyEvent *event) { keyboard_mods = event->modifiers(); } // QT mouse coords have 0,0 at the top-left of the widget // adjust such that 0,0 is the center glm::ivec2 hexmap_widget_t::adjusted_screen_coords(int x, int y) const { return glm::ivec2(x - width()/2, height()/2 - y); } void hexmap_widget_t::set_editor_tool(tool_type_e new_tool) { editor.set_tool(new_tool); emit editor_tool_changed(new_tool); } void hexmap_widget_t::set_palette_item(QModelIndex const& index) { switch(editor.current_tool) { case tool_type_e::terrain_paint: editor.current_tile_id = index.row(); break; case tool_type_e::place_objects: editor.current_object_id = index.row(); break; default: break; } } <commit_msg>fixed hexmap_qt to use create_shader_highest_supported()<commit_after>#include "hexmap_widget.h" #include <QMouseEvent> #include <asdf_multiplat/main/asdf_multiplat.h> #include <asdf_multiplat/data/content_manager.h> #include "mainwindow.h" #include "ui_mainwindow.h" /// https://doc-snapshots.qt.io/qt5-dev/qopenglwidget.html using namespace std; using namespace glm; namespace { constexpr float zoom_per_scroll_tick = 0.1f; } using tool_type_e = asdf::hexmap::editor::editor_t::tool_type_e; hexmap_widget_t::hexmap_widget_t(QWidget* _parent) : QOpenGLWidget(_parent) , data_map(editor.map_data) { setFocusPolicy(Qt::StrongFocus); setFocus(); } void hexmap_widget_t::initializeGL() { // Set up the rendering context, load shaders and other resources, etc.: asdf::app.renderer = make_unique<asdf::asdf_renderer_t>(); //do this before content init. Content needs GL_State to exist asdf::app.renderer->init(); //loads screen shader, among other things asdf::Content.init(); //needed for Content::shader_path auto shader = asdf::Content.create_shader_highest_supported("hexmap"); asdf::Content.shaders.add_resource(shader); editor.init(); hex_map = editor.rendered_map.get(); hex_map->camera.position.z = 10; hex_map_initialized(editor); } void hexmap_widget_t::resizeGL(int w, int h) { hex_map->camera.viewport.size_d2 = vec2(w,h) / 2.0f; hex_map->camera.viewport.bottom_left = -1.0f * hex_map->camera.viewport.size_d2; emit camera_changed(hex_map->camera); } void hexmap_widget_t::paintGL() { glDisable(GL_DEPTH_TEST); auto& gl_clear_color = asdf::app.renderer->gl_clear_color; glClearColor(gl_clear_color.r , gl_clear_color.g , gl_clear_color.b , gl_clear_color.a); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); editor.render(); } glm::uvec2 hexmap_widget_t::map_size() const { return data_map.hex_grid.size; } glm::vec2 hexmap_widget_t::camera_pos() const { return vec2(hex_map->camera.position.x, hex_map->camera.position.y); } void hexmap_widget_t::camera_pos(glm::vec2 const& p, bool emit_signal) { hex_map->camera.position.x = p.x; hex_map->camera.position.y = p.y; if(emit_signal) emit camera_changed(hex_map->camera); } // there may be a better solution than a switch statement asdf::mouse_button_e asdf_button_from_qt(Qt::MouseButton button) { switch(button) { case Qt::NoButton: return asdf::mouse_no_button; case Qt::LeftButton: return asdf::mouse_left; case Qt::RightButton: return asdf::mouse_right; case Qt::MiddleButton: return asdf::mouse_middle; case Qt::ExtraButton1: return asdf::mouse_4; case Qt::ExtraButton2: return asdf::mouse_5; default: return asdf::mouse_no_button; } } void hexmap_widget_t::mousePressEvent(QMouseEvent* event) { auto& mouse = asdf::app.mouse_state; asdf::mouse_button_event_t asdf_event { mouse , asdf_button_from_qt(event->button()) , (event->flags() & Qt::MouseEventCreatedDoubleClick) > 0 }; LOG("x,y: %i, %i", event->x(), event->y()); mouse.mouse_down(asdf_event, adjusted_screen_coords(event->x(), event->y())); update(); } void hexmap_widget_t::mouseReleaseEvent(QMouseEvent* event) { auto& mouse = asdf::app.mouse_state; asdf::mouse_button_event_t asdf_event { mouse , asdf_button_from_qt(event->button()) , (event->flags() & Qt::MouseEventCreatedDoubleClick) > 0 }; mouse.mouse_up(asdf_event, adjusted_screen_coords(event->x(), event->y())); update(); } void hexmap_widget_t::mouseMoveEvent(QMouseEvent* event) { auto& mouse = asdf::app.mouse_state; asdf::mouse_motion_event_t asdf_event { mouse }; mouse.mouse_move(asdf_event, adjusted_screen_coords(event->x(), event->y())); update(); //lazy } void hexmap_widget_t::wheelEvent(QWheelEvent* event) { if(keyboard_mods == Qt::NoModifier) { main_window->ui->hexmap_vscroll->event(event); ///FIXME can this be solved without holding onto main_window? } else if(keyboard_mods == Qt::ShiftModifier) { main_window->ui->hexmap_hscroll->event(event); } else if(keyboard_mods == Qt::ControlModifier) { float num_steps = event->angleDelta().y() / 15.0f; hex_map->camera.position.z += num_steps * zoom_per_scroll_tick; update(); emit camera_changed(hex_map->camera); } } void hexmap_widget_t::keyPressEvent(QKeyEvent* event) { keyboard_mods = event->modifiers(); SDL_Keysym sdl_key_event; //being lazy and reusing sdl event for now sdl_key_event.sym = event->nativeVirtualKey(); //supposedly virtual keys are a standard sdl_key_event.mod = 0; sdl_key_event.mod |= KMOD_SHIFT * (event->modifiers() & Qt::ShiftModifier) > 0; sdl_key_event.mod |= KMOD_CTRL * (event->modifiers() & Qt::ControlModifier) > 0; sdl_key_event.mod |= KMOD_ALT * (event->modifiers() & Qt::AltModifier) > 0; sdl_key_event.mod |= KMOD_GUI * (event->modifiers() & Qt::MetaModifier) > 0; auto prev_tool = editor.current_tool; editor.input->on_key_down(sdl_key_event); if(prev_tool != editor.current_tool) emit editor_tool_changed(editor.current_tool); /// TODO only call this when editor does not handle key QWidget::keyPressEvent(event); } void hexmap_widget_t::keyReleaseEvent(QKeyEvent *event) { keyboard_mods = event->modifiers(); } // QT mouse coords have 0,0 at the top-left of the widget // adjust such that 0,0 is the center glm::ivec2 hexmap_widget_t::adjusted_screen_coords(int x, int y) const { return glm::ivec2(x - width()/2, height()/2 - y); } void hexmap_widget_t::set_editor_tool(tool_type_e new_tool) { editor.set_tool(new_tool); emit editor_tool_changed(new_tool); } void hexmap_widget_t::set_palette_item(QModelIndex const& index) { switch(editor.current_tool) { case tool_type_e::terrain_paint: editor.current_tile_id = index.row(); break; case tool_type_e::place_objects: editor.current_object_id = index.row(); break; default: break; } } <|endoftext|>
<commit_before>#ifndef tut_polymorphism_hpp #define tut_polymorphism_hpp #include <cstddef> #include <functional> #include "../xtd/castable.hpp" namespace tut { // This tutorial gives an introduction to the data abstraction-style in C++ (DAS). // // DAS is a simple, powerful, composable, and efficient style of C++ programming. It is the // combination of four major implementation techniques - // // 1) data abstractions rather than OOP objects // 2) stand-alone functions rather than member functions // 3) composable mixins rather than OOP inheritance // 4) the following types of polymorphism rather than OOP polymorphism - // a) ad-hoc polymorphism (function overloading) // b) structural polymorphism (function templates without specialization) // c) static polymorphisms (function template with specialization) // // Subtype polymorphism should be used only when necessary, such as in mixins and plugins. // // In these tutorial and with the library code provided in this repository, I hope to // demonstrate the validity of DAS programming in C++ as an alternative to OOP. // // So let's get started! // Here we have a data abstraction, or 'DA'. You can tell it is different from an OOP object as // it has no public functions (save for ctors, dtors, and operators). Its has better generic // usage (especially with respect to the above preferred forms of polymorphism) and exposes a // much simpler and more extensible interface. Adding a new function to a DA is as easy as // opening up its containing namespace and plopping one in. // // Also unlike objects, DA's do only what they must in order to implement a localized // semantics rather than doing as much as possible for the wider system. // // For example, if you have a simulant DA in a simulation, it won't be that simulant's role to // hold on to a shader and texture handle to in order to render itself. Instead, the DA will be // a bag of data properties with consistency invariants. To perform specialized tasks like // rendering or physics, the simulant DA sends data messages that describe the desired // rendering or physics results to a renderer or physics system. It is up to these // specialized systems to manage resources and perform the tasks that the data messages // describe. // // The downside to DAs is that they are considered novel in some C++ shops, and may therfore // pose adoption difficulties in practice. class data_abstraction { private: // A private field. Note that having a single, const private field is rarely a good enough // reason to use a DA, but we're just giving a toy example to keeps things simple. const int value; protected: // Here we have a friend declaration that allows us to implement our interface. I make it // protected because that seems to gel with the ordering in more involved DA types, but you // can make them private if your prefer. friend int func(const data_abstraction&); public: // A public constructor that initializes the private value. data_abstraction(int value) : value(value) { } }; // Here we expose our DA's interface with stand-alone functions. For more on why stand-alone // functions are considered superior to OO-style member functions, see - // http://www.gotw.ca/gotw/084.htm and - // http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197 int func(const data_abstraction& da) { return da.value * 5; } // Unlike with OO interfaces, extending a DA is easy; even if you're in a different file or // code base, just open up the DA's namespace and add functions to you heart's content! int func_ex(const data_abstraction& da) { return func(da) + 5; } // Structural, or 'static duck-type', polymorphism is easy, useful, and usually politically // viable in C++ shops. However, it's not the most powerful form of static polymorphism in // C++, and its applicability is therefore limited. template<typename T> int pow(const T& t) { return func(t) * func(t); } // An extended pow function. template<typename T> int pow_ex(const T& t) { return func_ex(t) * func_ex(t); } // Template specialization provides a powerful form of static polymorphism in C++. On the plus // side, it's generally efficient, and in simpler forms, is easy to understand. On the minus, // once this approach starts invoking multiple different functions on the generalized type, it // starts becoming more like a limited form of type classes. That, in itself is quite a good // thing, but considering that C++ Concepts still haven't made it into the language, code that // leverages this form of polymorphism in complicated ways can be increasingly difficult for // many devs to deal with. template<typename T> T op(const T& a, const T& b) { return a + b; } // Int specialization of op. template<> int op(const int& a, const int& b) { return a * b; } // Float specialization of op. template<> float op(const float& a, const float& b) { return a / b; } // Note that function templates shadow rather than overload, so if you want to have the same // generic function with a different number of parameters, you do as the standard library does // and suffix the name with the number parameters. This is the same approach as taken in most // functional languages. Usually the original function remains un-numbered, so you can apply // this after-the-fact. template<typename T> T op3(const T& a, const T& b, const T& c) { return a + b + c; } // As you can see, a great variety of computation and program characteristics can be cleanly, // efficiently, and most importantly _generically_ expressed using just the above concepts. // However, we will still need late-binding to achieve certain types of abstractions. This // is where DAS mixins come in. // // What is a mixin in the context of data-abstraction style? // // Mixins in this context are a bit different than what most C++ articles about mixins present. // Rather than being programming components that allow the injection of capabilities into a // class a posteriori via template arguments, our mixins are simple data abstractions that each // provide a single orthogonal capability to another data abstraction via inheritance. // // A good example of a mixin is implemented in '../hpp/xtd/castable.hpp'. By inheriting from // this mixin, you get dynamic castability capabilities via - // 1) A common base type xtd::castable. // 2) Virtual try_cast functions, with default template impl functions to ease overriding. // 3) A completely general public interface, including casting with smart ptrs. // // The following is a type that leverages the castable mixin - class widget : public xtd::castable { private: const int upc; const float age; const bool replacable; protected: // Override xtd::castable::try_cast_const from mixin. void const* try_cast_const(const char* type_name) const override { return try_cast_const_impl<castable>(this, type_name); } // Override xtd::castable::try_cast from mixin. void* try_cast(const char* type_name) override { return try_cast_impl<castable>(this, type_name); } friend int get_upc(const widget& widget); friend bool should_replace(const widget& widget, float age_max); public: // Construct our widget. widget(int upc, float age, bool replacable) : upc(upc), age(age), replacable(replacable) { } }; // Get the upc of a widget. int get_upc(const widget& widget) { return widget.upc; } // Query that a widget should be replaced. bool should_replace(const widget& widget, float age_max) { return widget.replacable && widget.age > age_max; } // Query that a widget should be replaced with a give product. bool should_replace_with(const widget& widget, float age_max, int upc) { return should_replace(widget, age_max) && get_upc(widget) == upc; } } #endif <commit_msg>Clearer explanation on why stand-alone functions.<commit_after>#ifndef tut_polymorphism_hpp #define tut_polymorphism_hpp #include <cstddef> #include <functional> #include "../xtd/castable.hpp" namespace tut { // This tutorial gives an introduction to the data abstraction-style in C++ (DAS). // // DAS is a simple, powerful, composable, and efficient style of C++ programming. It is the // combination of four major implementation techniques - // // 1) data abstractions rather than OOP objects // 2) stand-alone functions rather than member functions // 3) composable mixins rather than OOP inheritance // 4) the following types of polymorphism rather than OOP polymorphism - // a) ad-hoc polymorphism (function overloading) // b) structural polymorphism (function templates without specialization) // c) static polymorphisms (function template with specialization) // // Subtype polymorphism should be used only when necessary, such as in mixins and plugins. // // In these tutorial and with the library code provided in this repository, I hope to // demonstrate the validity of DAS programming in C++ as an alternative to OOP. // // So let's get started! // Here we have a data abstraction, or 'DA'. You can tell it is different from an OOP object as // it has no public functions (save for ctors, dtors, and operators). Its has better generic // usage (especially with respect to the above preferred forms of polymorphism) and exposes a // much simpler and more extensible interface. Adding a new function to a DA is as easy as // opening up its containing namespace and plopping one in. // // Also unlike objects, DA's do only what they must in order to implement a localized // semantics rather than doing as much as possible for the wider system. // // For example, if you have a simulant DA in a simulation, it won't be that simulant's role to // hold on to a shader and texture handle to in order to render itself. Instead, the DA will be // a bag of data properties with consistency invariants. To perform specialized tasks like // rendering or physics, the simulant DA sends data messages that describe the desired // rendering or physics results to a renderer or physics system. It is up to these // specialized systems to manage resources and perform the tasks that the data messages // describe. // // The downside to DAs is that they are considered novel in some C++ shops, and may therfore // pose adoption difficulties in practice. class data_abstraction { private: // A private field. Note that having a single, const private field is rarely a good enough // reason to use a DA, but we're just giving a toy example to keeps things simple. const int value; protected: // Here we have a friend declaration that allows us to implement our interface. I make it // protected because that seems to gel with the ordering in more involved DA types, but you // can make them private if your prefer. friend int func(const data_abstraction&); public: // A public constructor that initializes the private value. data_abstraction(int value) : value(value) { } }; // Here we expose our DA's interface with stand-alone functions. Stand-alone functions are // preferable to methods because they are much more amenable to use in generic programming. For // more on this see - http://www.gotw.ca/gotw/084.htm and - // http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197 int func(const data_abstraction& da) { return da.value * 5; } // Unlike with OO interfaces, extending a DA is easy; even if you're in a different file or // code base, just open up the DA's namespace and add functions to you heart's content! int func_ex(const data_abstraction& da) { return func(da) + 5; } // Structural, or 'static duck-type', polymorphism is easy, useful, and usually politically // viable in C++ shops. However, it's not the most powerful form of static polymorphism in // C++, and its applicability is therefore limited. template<typename T> int pow(const T& t) { return func(t) * func(t); } // An extended pow function. template<typename T> int pow_ex(const T& t) { return func_ex(t) * func_ex(t); } // Template specialization provides a powerful form of static polymorphism in C++. On the plus // side, it's generally efficient, and in simpler forms, is easy to understand. On the minus, // once this approach starts invoking multiple different functions on the generalized type, it // starts becoming more like a limited form of type classes. That, in itself is quite a good // thing, but considering that C++ Concepts still haven't made it into the language, code that // leverages this form of polymorphism in complicated ways can be increasingly difficult for // many devs to deal with. template<typename T> T op(const T& a, const T& b) { return a + b; } // Int specialization of op. template<> int op(const int& a, const int& b) { return a * b; } // Float specialization of op. template<> float op(const float& a, const float& b) { return a / b; } // Note that function templates shadow rather than overload, so if you want to have the same // generic function with a different number of parameters, you do as the standard library does // and suffix the name with the number parameters. This is the same approach as taken in most // functional languages. Usually the original function remains un-numbered, so you can apply // this after-the-fact. template<typename T> T op3(const T& a, const T& b, const T& c) { return a + b + c; } // As you can see, a great variety of computation and program characteristics can be cleanly, // efficiently, and most importantly _generically_ expressed using just the above concepts. // However, we will still need late-binding to achieve certain types of abstractions. This // is where DAS mixins come in. // // What is a mixin in the context of data-abstraction style? // // Mixins in this context are a bit different than what most C++ articles about mixins present. // Rather than being programming components that allow the injection of capabilities into a // class a posteriori via template arguments, our mixins are simple data abstractions that each // provide a single orthogonal capability to another data abstraction via inheritance. // // A good example of a mixin is implemented in '../hpp/xtd/castable.hpp'. By inheriting from // this mixin, you get dynamic castability capabilities via - // 1) A common base type xtd::castable. // 2) Virtual try_cast functions, with default template impl functions to ease overriding. // 3) A completely general public interface, including casting with smart ptrs. // // The following is a type that leverages the castable mixin - class widget : public xtd::castable { private: const int upc; const float age; const bool replacable; protected: // Override xtd::castable::try_cast_const from mixin. void const* try_cast_const(const char* type_name) const override { return try_cast_const_impl<castable>(this, type_name); } // Override xtd::castable::try_cast from mixin. void* try_cast(const char* type_name) override { return try_cast_impl<castable>(this, type_name); } friend int get_upc(const widget& widget); friend bool should_replace(const widget& widget, float age_max); public: // Construct our widget. widget(int upc, float age, bool replacable) : upc(upc), age(age), replacable(replacable) { } }; // Get the upc of a widget. int get_upc(const widget& widget) { return widget.upc; } // Query that a widget should be replaced. bool should_replace(const widget& widget, float age_max) { return widget.replacable && widget.age > age_max; } // Query that a widget should be replaced with a give product. bool should_replace_with(const widget& widget, float age_max, int upc) { return should_replace(widget, age_max) && get_upc(widget) == upc; } } #endif <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "cpp_utils/assert.hpp" #include "cpp_utils/string.hpp" #include "writer.hpp" #include "console.hpp" namespace { std::string success_to_string(int success) { success = std::min(success, 100); success = std::max(success, 0); std::stringstream ss; ss << R"=====(<div class="progress">)====="; ss << R"=====(<div class="progress-bar" role="progressbar" style="width:)=====" << success << R"=====(%;" aria-valuenow=")=====" << success << R"=====(" aria-valuemin="0" aria-valuemax="100">)=====" << success << R"=====(%</div>)====="; ss << R"=====(</div>)====="; return ss.str(); } std::string edit_to_string(const std::string& module, const std::string& id){ std::stringstream ss; // Add the delete button ss << R"=====(<form class="small-form-inline" method="POST" action="/api/)====="; ss << module; ss << R"=====(/delete/">)====="; ss << R"=====(<input type="hidden" name="server" value="yes">)====="; ss << R"=====(<input type="hidden" name="back_page" value="__budget_this_page__">)====="; ss << R"=====(<input type="hidden" name="input_id" value=")====="; ss << id; ss << R"=====(">)====="; ss << R"=====(<button type="submit" class="btn btn-sm btn-danger">Delete</button>)====="; ss << R"=====(</form>)====="; // Add the edit button ss << R"=====(<form class="small-form-inline" method="POST" action="/)====="; ss << module; ss << R"=====(/edit/">)====="; ss << R"=====(<input type="hidden" name="server" value="yes">)====="; ss << R"=====(<input type="hidden" name="back_page" value="__budget_this_page__">)====="; ss << R"=====(<input type="hidden" name="input_id" value=")====="; ss << id; ss << R"=====(">)====="; ss << R"=====(<button type="submit" class="btn btn-sm btn-warning">Edit</button>)====="; ss << R"=====(</form>)====="; return ss.str(); } std::string html_format(const std::string& v){ if(v.substr(0, 5) == "::red"){ auto value = v.substr(5); return "<span style=\"color:red;\">" + value + "</span>"; } else if(v.substr(0, 6) == "::blue"){ auto value = v.substr(6); return "<span style=\"color:blue;\">" + value + "</span>"; } else if(v.substr(0, 7) == "::green"){ auto value = v.substr(7); return "<span style=\"color:green;\">" + value + "</span>"; } else if(v.substr(0, 9) == "::success"){ auto value = v.substr(9); auto success = budget::to_number<unsigned long>(value); return success_to_string(success); } else if(v.substr(0, 8) == "::edit::"){ auto value = v.substr(8); if(value.find("::") == std::string::npos){ return v; } auto module = value.substr(0, value.find("::")); auto id = value.substr(value.find("::") + 2, value.size()); return edit_to_string(module, id); } return v; } } // end of anonymous namespace budget::html_writer::html_writer(std::ostream& os) : os(os) {} budget::writer& budget::html_writer::operator<<(const std::string& value){ os << html_format(value); return *this; } budget::writer& budget::html_writer::operator<<(const double& value){ os << value; return *this; } budget::writer& budget::html_writer::operator<<(const budget::money& m) { os << m; return *this; } budget::writer& budget::html_writer::operator<<(const budget::month& m) { os << m.as_short_string(); return *this; } budget::writer& budget::html_writer::operator<<(const budget::year& y) { os << y.value; return *this; } budget::writer& budget::html_writer::operator<<(const budget::end_of_line_t&) { os << "\n"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::p_begin_t&) { os << "<p>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::p_end_t&) { os << "</p>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::title_begin_t&) { os << "<h2>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::title_end_t&) { os << "</h2>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::year_month_selector& m) { os << "<div class=\"selector\">"; auto previous_month = m.current_month; auto previous_year = m.current_year; auto next_month = m.current_month; auto next_year = m.current_year; if (m.current_month == 1) { previous_month = 12; previous_year = m.current_year - 1; } else { previous_month = m.current_month - 1; previous_year = m.current_year; } if (m.current_month == 12) { next_month = 1; next_year = m.current_year + 1; } else { next_month = m.current_month + 1; next_year = m.current_year; } os << "<a href=\"/" << m.page << "/" << previous_year << "/" << previous_month.value << "/\">&lt;&lt;</a>"; os << "&nbsp;"; os << "<a href=\"/" << m.page << "/" << next_year << "/" << next_month.value << "/\">&gt;&gt;</a>"; os << "</div>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::year_selector& m) { os << "<div class=\"selector\">"; auto previous_year = m.current_year - 1; auto next_year = m.current_year + 1; os << "<a href=\"/" << m.page << "/" << previous_year << "/\">&lt;&lt;</a>"; os << "&nbsp;"; os << "<a href=\"/" << m.page << "/" << next_year << "/\">&gt;&gt;</a>"; os << "</div>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::add_button& b) { os << "<a href=\"/" << b.module << "/add/\" class=\"btn btn-info\" role=\"button\">New</a>\n"; return *this; } void budget::html_writer::display_table(std::vector<std::string>& columns, std::vector<std::vector<std::string>>& contents, size_t groups, std::vector<size_t> lines, size_t left, size_t foot){ cpp_assert(groups > 0, "There must be at least 1 group"); cpp_unused(left); cpp_unused(lines); for (auto& row : contents) { if (row.size() < columns.size()) { std::cerr << "Invalid number of columns in row" << std::endl; return; } for (auto& cell : row) { cpp::trim(cell); } } size_t extend = columns.size(); size_t edit = columns.size(); for (size_t i = 0; i < columns.size(); ++i) { for (auto& row : contents) { if (row[i].size() >= 9 && row[i].substr(0, 9) == "::success") { extend = i; break; } if (row[i].size() >= 6 && row[i].substr(0, 6) == "::edit") { edit = i; break; } } if (extend == i || edit == i) { break; } } bool small = columns.empty(); // TODO Improve this heuristic! if(small){ os << "<div class=\"row\">"; os << "<div class=\"col-md-4\">&nbsp;</div>"; os << "<div class=\"col-md-4\">"; } else { os << "<div class=\"table-responsive\">"; } os << "<table class=\"table table-sm small-text\">"; // Display the header if (columns.size()) { os << "<thead>"; os << "<tr>"; for (size_t i = 0; i < columns.size(); ++i) { auto& column = columns[i]; if(column == "ID"){ continue; } std::string style; // TODO: This is only a bad hack, at best if(i == extend){ style = " class=\"extend-only\""; } if(i == edit){ style = " class=\"not-sortable\""; } if (groups > 1) { os << "<th colspan=\"" << groups << "\"" << style << ">" << column << "</th>"; } else { os << "<th" << style << ">" << column << "</th>"; } } os << "</tr>"; os << "</thead>"; } // Display the contents os << "<tbody>"; for(size_t i = 0; i < contents.size() - foot; ++i){ auto& row = contents[i]; os << "<tr>"; for(size_t j = 0; j < row.size(); ++j){ if (columns.size() && groups == 1 && columns[j] == "ID") { continue; } std::string value = html_format(row[j]); if(value.empty()){ os << "<td>&nbsp;</td>"; } else { if(columns.empty() && j == 0){ os << "<th scope=\"row\">" << value << "</th>"; } else { os << "<td>" << value << "</td>"; } } } os << "</tr>"; } os << "</tbody>"; if (foot) { os << "<tfoot>"; for (size_t i = contents.size() - foot; i < contents.size(); ++i) { auto& row = contents[i]; os << "<tr>"; for (size_t j = 0; j < row.size(); ++j) { if (columns.size() && groups == 1 && columns[j] == "ID") { continue; } std::string value = html_format(row[j]); if (value.empty()) { os << "<td>&nbsp;</td>"; } else { os << "<td>" << value << "</td>"; } } os << "</tr>"; } os << "</tfoot>"; } os << "</table>"; if (small) { os << "</div>"; // middle column os << "<div class=\"col-md-4\">&nbsp;</div>"; os << "</div>"; // row } else { os << "</div>"; // table-responsive } } bool budget::html_writer::is_web() { return true; } void budget::html_writer::display_graph(const std::string& title, std::vector<std::string>& categories, std::vector<std::string> series_names, std::vector<std::vector<float>>& series_values){ os << R"=====(<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>)====="; os << R"=====(<script langage="javascript">)====="; os << R"=====(Highcharts.chart('container', {)====="; os << R"=====(chart: {type: 'column'},)====="; os << R"=====(credits: {enabled: true},)====="; os << "title: { text: '" << title << "'},"; os << "xAxis: { categories: ["; for (auto& category : categories) { os << "'" << category << "',"; } os << "]},"; os << "series: ["; for(size_t i = 0; i < series_names.size(); ++i){ os << "{ name: '" << series_names[i] << "',"; os << "data: ["; for(auto& value : series_values[i]){ os << value << ","; } os << "]},"; } os << "]"; os << R"=====(});)====="; os << R"=====(</script>)====="; } void budget::html_writer::defer_script(const std::string& script){ std::stringstream ss; ss << R"=====(<script langage="javascript">)=====" << '\n'; ss << R"=====($(function(){)=====" << '\n'; ss << script; ss << R"=====(});)====="; ss << R"=====(</script>)====="; scripts.emplace_back(ss.str()); } void budget::html_writer::load_deferred_scripts(){ // The javascript for Boostrap and JQuery os << R"=====( <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script> )====="; if(!scripts.empty()){ // The javascript for Boostrap and JQuery os << R"=====( <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/highcharts-more.js"></script> <script src="https://code.highcharts.com/modules/solid-gauge.js"></script> <script src="https://code.highcharts.com/modules/series-label.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> )====="; // The javascript for datables os << R"=====( <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css/"></link> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script> )====="; // Add the custom scripts for(auto& script : scripts){ os << script << '\n'; } } } <commit_msg>Fix datatables CSS<commit_after>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "cpp_utils/assert.hpp" #include "cpp_utils/string.hpp" #include "writer.hpp" #include "console.hpp" namespace { std::string success_to_string(int success) { success = std::min(success, 100); success = std::max(success, 0); std::stringstream ss; ss << R"=====(<div class="progress">)====="; ss << R"=====(<div class="progress-bar" role="progressbar" style="width:)=====" << success << R"=====(%;" aria-valuenow=")=====" << success << R"=====(" aria-valuemin="0" aria-valuemax="100">)=====" << success << R"=====(%</div>)====="; ss << R"=====(</div>)====="; return ss.str(); } std::string edit_to_string(const std::string& module, const std::string& id){ std::stringstream ss; // Add the delete button ss << R"=====(<form class="small-form-inline" method="POST" action="/api/)====="; ss << module; ss << R"=====(/delete/">)====="; ss << R"=====(<input type="hidden" name="server" value="yes">)====="; ss << R"=====(<input type="hidden" name="back_page" value="__budget_this_page__">)====="; ss << R"=====(<input type="hidden" name="input_id" value=")====="; ss << id; ss << R"=====(">)====="; ss << R"=====(<button type="submit" class="btn btn-sm btn-danger">Delete</button>)====="; ss << R"=====(</form>)====="; // Add the edit button ss << R"=====(<form class="small-form-inline" method="POST" action="/)====="; ss << module; ss << R"=====(/edit/">)====="; ss << R"=====(<input type="hidden" name="server" value="yes">)====="; ss << R"=====(<input type="hidden" name="back_page" value="__budget_this_page__">)====="; ss << R"=====(<input type="hidden" name="input_id" value=")====="; ss << id; ss << R"=====(">)====="; ss << R"=====(<button type="submit" class="btn btn-sm btn-warning">Edit</button>)====="; ss << R"=====(</form>)====="; return ss.str(); } std::string html_format(const std::string& v){ if(v.substr(0, 5) == "::red"){ auto value = v.substr(5); return "<span style=\"color:red;\">" + value + "</span>"; } else if(v.substr(0, 6) == "::blue"){ auto value = v.substr(6); return "<span style=\"color:blue;\">" + value + "</span>"; } else if(v.substr(0, 7) == "::green"){ auto value = v.substr(7); return "<span style=\"color:green;\">" + value + "</span>"; } else if(v.substr(0, 9) == "::success"){ auto value = v.substr(9); auto success = budget::to_number<unsigned long>(value); return success_to_string(success); } else if(v.substr(0, 8) == "::edit::"){ auto value = v.substr(8); if(value.find("::") == std::string::npos){ return v; } auto module = value.substr(0, value.find("::")); auto id = value.substr(value.find("::") + 2, value.size()); return edit_to_string(module, id); } return v; } } // end of anonymous namespace budget::html_writer::html_writer(std::ostream& os) : os(os) {} budget::writer& budget::html_writer::operator<<(const std::string& value){ os << html_format(value); return *this; } budget::writer& budget::html_writer::operator<<(const double& value){ os << value; return *this; } budget::writer& budget::html_writer::operator<<(const budget::money& m) { os << m; return *this; } budget::writer& budget::html_writer::operator<<(const budget::month& m) { os << m.as_short_string(); return *this; } budget::writer& budget::html_writer::operator<<(const budget::year& y) { os << y.value; return *this; } budget::writer& budget::html_writer::operator<<(const budget::end_of_line_t&) { os << "\n"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::p_begin_t&) { os << "<p>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::p_end_t&) { os << "</p>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::title_begin_t&) { os << "<h2>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::title_end_t&) { os << "</h2>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::year_month_selector& m) { os << "<div class=\"selector\">"; auto previous_month = m.current_month; auto previous_year = m.current_year; auto next_month = m.current_month; auto next_year = m.current_year; if (m.current_month == 1) { previous_month = 12; previous_year = m.current_year - 1; } else { previous_month = m.current_month - 1; previous_year = m.current_year; } if (m.current_month == 12) { next_month = 1; next_year = m.current_year + 1; } else { next_month = m.current_month + 1; next_year = m.current_year; } os << "<a href=\"/" << m.page << "/" << previous_year << "/" << previous_month.value << "/\">&lt;&lt;</a>"; os << "&nbsp;"; os << "<a href=\"/" << m.page << "/" << next_year << "/" << next_month.value << "/\">&gt;&gt;</a>"; os << "</div>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::year_selector& m) { os << "<div class=\"selector\">"; auto previous_year = m.current_year - 1; auto next_year = m.current_year + 1; os << "<a href=\"/" << m.page << "/" << previous_year << "/\">&lt;&lt;</a>"; os << "&nbsp;"; os << "<a href=\"/" << m.page << "/" << next_year << "/\">&gt;&gt;</a>"; os << "</div>"; return *this; } budget::writer& budget::html_writer::operator<<(const budget::add_button& b) { os << "<a href=\"/" << b.module << "/add/\" class=\"btn btn-info\" role=\"button\">New</a>\n"; return *this; } void budget::html_writer::display_table(std::vector<std::string>& columns, std::vector<std::vector<std::string>>& contents, size_t groups, std::vector<size_t> lines, size_t left, size_t foot){ cpp_assert(groups > 0, "There must be at least 1 group"); cpp_unused(left); cpp_unused(lines); for (auto& row : contents) { if (row.size() < columns.size()) { std::cerr << "Invalid number of columns in row" << std::endl; return; } for (auto& cell : row) { cpp::trim(cell); } } size_t extend = columns.size(); size_t edit = columns.size(); for (size_t i = 0; i < columns.size(); ++i) { for (auto& row : contents) { if (row[i].size() >= 9 && row[i].substr(0, 9) == "::success") { extend = i; break; } if (row[i].size() >= 6 && row[i].substr(0, 6) == "::edit") { edit = i; break; } } if (extend == i || edit == i) { break; } } bool small = columns.empty(); // TODO Improve this heuristic! if(small){ os << "<div class=\"row\">"; os << "<div class=\"col-md-4\">&nbsp;</div>"; os << "<div class=\"col-md-4\">"; } else { os << "<div class=\"table-responsive\">"; } os << "<table class=\"table table-sm small-text\">"; // Display the header if (columns.size()) { os << "<thead>"; os << "<tr>"; for (size_t i = 0; i < columns.size(); ++i) { auto& column = columns[i]; if(column == "ID"){ continue; } std::string style; // TODO: This is only a bad hack, at best if(i == extend){ style = " class=\"extend-only\""; } if(i == edit){ style = " class=\"not-sortable\""; } if (groups > 1) { os << "<th colspan=\"" << groups << "\"" << style << ">" << column << "</th>"; } else { os << "<th" << style << ">" << column << "</th>"; } } os << "</tr>"; os << "</thead>"; } // Display the contents os << "<tbody>"; for(size_t i = 0; i < contents.size() - foot; ++i){ auto& row = contents[i]; os << "<tr>"; for(size_t j = 0; j < row.size(); ++j){ if (columns.size() && groups == 1 && columns[j] == "ID") { continue; } std::string value = html_format(row[j]); if(value.empty()){ os << "<td>&nbsp;</td>"; } else { if(columns.empty() && j == 0){ os << "<th scope=\"row\">" << value << "</th>"; } else { os << "<td>" << value << "</td>"; } } } os << "</tr>"; } os << "</tbody>"; if (foot) { os << "<tfoot>"; for (size_t i = contents.size() - foot; i < contents.size(); ++i) { auto& row = contents[i]; os << "<tr>"; for (size_t j = 0; j < row.size(); ++j) { if (columns.size() && groups == 1 && columns[j] == "ID") { continue; } std::string value = html_format(row[j]); if (value.empty()) { os << "<td>&nbsp;</td>"; } else { os << "<td>" << value << "</td>"; } } os << "</tr>"; } os << "</tfoot>"; } os << "</table>"; if (small) { os << "</div>"; // middle column os << "<div class=\"col-md-4\">&nbsp;</div>"; os << "</div>"; // row } else { os << "</div>"; // table-responsive } } bool budget::html_writer::is_web() { return true; } void budget::html_writer::display_graph(const std::string& title, std::vector<std::string>& categories, std::vector<std::string> series_names, std::vector<std::vector<float>>& series_values){ os << R"=====(<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>)====="; os << R"=====(<script langage="javascript">)====="; os << R"=====(Highcharts.chart('container', {)====="; os << R"=====(chart: {type: 'column'},)====="; os << R"=====(credits: {enabled: true},)====="; os << "title: { text: '" << title << "'},"; os << "xAxis: { categories: ["; for (auto& category : categories) { os << "'" << category << "',"; } os << "]},"; os << "series: ["; for(size_t i = 0; i < series_names.size(); ++i){ os << "{ name: '" << series_names[i] << "',"; os << "data: ["; for(auto& value : series_values[i]){ os << value << ","; } os << "]},"; } os << "]"; os << R"=====(});)====="; os << R"=====(</script>)====="; } void budget::html_writer::defer_script(const std::string& script){ std::stringstream ss; ss << R"=====(<script langage="javascript">)=====" << '\n'; ss << R"=====($(function(){)=====" << '\n'; ss << script; ss << R"=====(});)====="; ss << R"=====(</script>)====="; scripts.emplace_back(ss.str()); } void budget::html_writer::load_deferred_scripts(){ // The javascript for Boostrap and JQuery os << R"=====( <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script> )====="; if(!scripts.empty()){ // The javascript for Boostrap and JQuery os << R"=====( <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/highcharts-more.js"></script> <script src="https://code.highcharts.com/modules/solid-gauge.js"></script> <script src="https://code.highcharts.com/modules/series-label.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> )====="; // The javascript for datables os << R"=====( <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css"></link> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script> )====="; // Add the custom scripts for(auto& script : scripts){ os << script << '\n'; } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 The Android Open Source Project * * 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. */ // OpenGL ES 2.0 code #include <jni.h> #include <android/log.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <string> #include <vector> #include <stdio.h> #include <stdlib.h> #include <math.h> #define LOG_TAG "libgl2jni" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) static std::string gVertexShader; static std::string gFragmentShader; //Counter Clockwise float triangleVertices[] = { // 1 // / \ // / \ // 2/____ \3 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f }; float squareVertices[] = { // 2___1 // | | // | | // |___3 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, // 2____ // | | // | | // 3___1 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f }; //Column major! Transpose it if you want it to agree with your books. //glTranslatef( -1.5f, 0.0f, -6.0f); float triangleTransformMatrix[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.5f, 0.0f, -6.0f, 1.0f }; //glTranslatef( -1.5f, 0.0f, -6.0f); //glTranslatef(3.0f, 0.0f, 0.0f ); //= glTranslate( 1.5f, 0.0, -6.0f ); float squareTransformMatrix[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.5f, 0.0f, -6.0f, 1.0f }; //We start off with a identity and later will fill in for the projection space transform.. float projectionMatrix[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; GLuint vertexAttributePosition; GLuint modelMatrixAttributePosition; GLuint projectionMatrixAttributePosition; GLuint gProgram; static void printGLString(const char *name, GLenum s) { const char *v = (const char *) glGetString(s); LOGI("GL %s = %s\n", name, v); } static void checkGlError(const char* op) { for (GLint error = glGetError(); error; error = glGetError()) { LOGI("after %s() glError (0x%x)\n", op, error); } } float radians( float degrees ) { return degrees * ( 3.14159f / 180.0f ); } float cotangent(float angle) { return 1.0f / tan( radians(angle)); } float[] perspective(float fovy, float aspect, float zNear, float zFar) { float ret[16]; float A; float B; float d; A = (2 * zNear * zFar) / (zFar - zNear); B = (zFar + zNear) / (zFar - zNear); d = cotangent(fovy / 2); return { d / aspect, 0, 0, 0, 0, d, 0, 0, 0, 0, -B, -1, 0, 0, -A, 0 }; } static int android_read(void* cookie, char* buf, int size) { return AAsset_read((AAsset*)cookie, buf, size); } static int android_write(void* cookie, const char* buf, int size) { return EACCES; // can't provide write access to the apk } static fpos_t android_seek(void* cookie, fpos_t offset, int whence) { return AAsset_seek((AAsset*)cookie, offset, whence); } static int android_close(void* cookie) { AAsset_close((AAsset*)cookie); return 0; } FILE* android_fopen(const char* fname, const char* mode, AAssetManager *assetManager) { if(mode[0] == 'w') return NULL; AAsset* asset = AAssetManager_open( assetManager, fname, 0); if(!asset) return NULL; return funopen(asset, android_read, android_write, android_seek, android_close); } std::string readShaderToString( FILE* fileDescriptor ) { const unsigned N=1024; std::string total; while (true) { char buffer[ N ]; size_t read = fread((void *)&buffer[0], 1, N, fileDescriptor); if (read) { for ( int c = 0; c < read; ++c ) { total.push_back( buffer[ c ] ); } } if (read < N) { break; } } return total; } void loadShaders( JNIEnv* env, jobject& obj ) { AAssetManager *asset_manager = AAssetManager_fromJava( env, obj ); FILE* fd; fd = android_fopen( "vertex.glsl", "r", asset_manager ); gVertexShader = readShaderToString( fd ); fclose( fd ); fd = android_fopen( "fragment.glsl", "r", asset_manager ); gFragmentShader = readShaderToString( fd ); fclose( fd ); } GLuint loadShader(GLenum shaderType, const char* pSource) { GLuint shader = glCreateShader(shaderType); if (shader) { glShaderSource(shader, 1, &pSource, NULL); glCompileShader(shader); GLint compiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint infoLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen) { char* buf = (char*) malloc(infoLen); if (buf) { glGetShaderInfoLog(shader, infoLen, NULL, buf); LOGE("Could not compile shader %d:\n%s\n", shaderType, buf); free(buf); } glDeleteShader(shader); shader = 0; } } } return shader; } GLuint createProgram(const char* pVertexSource, const char* pFragmentSource) { GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource); if (!vertexShader) { return 0; } GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource); if (!pixelShader) { return 0; } GLuint program = glCreateProgram(); if (program) { glAttachShader(program, vertexShader); checkGlError("glAttachShader"); glAttachShader(program, pixelShader); checkGlError("glAttachShader"); glLinkProgram(program); GLint linkStatus = GL_FALSE; glGetProgramiv(program, GL_LINK_STATUS, &linkStatus); if (linkStatus != GL_TRUE) { GLint bufLength = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength); if (bufLength) { char* buf = (char*) malloc(bufLength); if (buf) { glGetProgramInfoLog(program, bufLength, NULL, buf); LOGE("Could not link program:\n%s\n", buf); free(buf); } } glDeleteProgram(program); program = 0; } } return program; } bool setupGraphics(int w, int h) { printGLString("Version", GL_VERSION); printGLString("Vendor", GL_VENDOR); printGLString("Renderer", GL_RENDERER); printGLString("Extensions", GL_EXTENSIONS); LOGI("setupGraphics(%d, %d)", w, h); gProgram = createProgram(gVertexShader.c_str(), gFragmentShader.c_str()); if (!gProgram) { LOGE("Could not create program."); return false; } vertexAttributePosition = glGetAttribLocation( gProgram, "aPosition" ); matrixAttributePosition = glGetUniformLocation( gProgram, "uMVP" ); glViewport(0, 0, w, h); checkGlError("glViewport"); return true; } void renderFrame() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); checkGlError("glClearColor"); glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); checkGlError("glClear"); glUseProgram(gProgram); checkGlError("glUseProgram"); glVertexAttribPointer ( vertexAttributePosition, 3, GL_FLOAT, GL_FALSE, 0, triangleVertices ); glEnableVertexAttribArray ( vertexAttributePosition ); glUniformMatrix4fv( matrixAttributePosition, false, 1, triangleTransformMatrix ); glDrawArrays ( GL_TRIANGLES, 0, 3 ); } extern "C" { JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_onCreate(JNIEnv * env, void* reserved, jobject assetManager ); JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_init(JNIEnv * env, jobject obj, jint width, jint height); JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_step(JNIEnv * env, jobject obj); }; JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_onCreate(JNIEnv * env, void* reserved, jobject assetManager ) { loadShaders( env, assetManager ); } JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_init(JNIEnv * env, jobject obj, jint width, jint height) { setupGraphics(width, height); } JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_step(JNIEnv * env, jobject obj) { renderFrame(); } <commit_msg>Change perspective calculation<commit_after>/* * Copyright (C) 2009 The Android Open Source Project * * 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. */ // OpenGL ES 2.0 code #include <jni.h> #include <android/log.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <string> #include <vector> #include <stdio.h> #include <stdlib.h> #include <math.h> #define LOG_TAG "libgl2jni" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) static std::string gVertexShader; static std::string gFragmentShader; //Counter Clockwise float triangleVertices[] = { // 1 // / \ // / \ // 2/____ \3 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f }; float squareVertices[] = { // 2___1 // | | // | | // |___3 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, // 2____ // | | // | | // 3___1 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f }; //Column major! Transpose it if you want it to agree with your books. //glTranslatef( -1.5f, 0.0f, -6.0f); float triangleTransformMatrix[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.5f, 0.0f, -6.0f, 1.0f }; //glTranslatef( -1.5f, 0.0f, -6.0f); //glTranslatef(3.0f, 0.0f, 0.0f ); //= glTranslate( 1.5f, 0.0, -6.0f ); float squareTransformMatrix[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.5f, 0.0f, -6.0f, 1.0f }; //We start off with a identity and later will fill in for the projection space transform.. float projectionMatrix[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; GLuint vertexAttributePosition; GLuint modelMatrixAttributePosition; GLuint projectionMatrixAttributePosition; GLuint gProgram; static void printGLString(const char *name, GLenum s) { const char *v = (const char *) glGetString(s); LOGI("GL %s = %s\n", name, v); } static void checkGlError(const char* op) { for (GLint error = glGetError(); error; error = glGetError()) { LOGI("after %s() glError (0x%x)\n", op, error); } } float radians( float degrees ) { return degrees * ( 3.14159f / 180.0f ); } float cotangent(float angle) { return 1.0f / tan( radians(angle)); } void perspective(float fovy, float aspect, float zNear, float zFar ) { float A; float B; float d; A = (2.0f * zNear * zFar) / (zFar - zNear); B = (zFar + zNear) / (zFar - zNear); d = cotangent(fovy / 2.0f ); projectionMatrix[0] = d / aspect; projectionMatrix[5] = d; projectionMatrix[10] = -B; projectionMatrix[11] = -1.0f; projectionMatrix[14] = -A; } static int android_read(void* cookie, char* buf, int size) { return AAsset_read((AAsset*)cookie, buf, size); } static int android_write(void* cookie, const char* buf, int size) { return EACCES; // can't provide write access to the apk } static fpos_t android_seek(void* cookie, fpos_t offset, int whence) { return AAsset_seek((AAsset*)cookie, offset, whence); } static int android_close(void* cookie) { AAsset_close((AAsset*)cookie); return 0; } FILE* android_fopen(const char* fname, const char* mode, AAssetManager *assetManager) { if(mode[0] == 'w') return NULL; AAsset* asset = AAssetManager_open( assetManager, fname, 0); if(!asset) return NULL; return funopen(asset, android_read, android_write, android_seek, android_close); } std::string readShaderToString( FILE* fileDescriptor ) { const unsigned N=1024; std::string total; while (true) { char buffer[ N ]; size_t read = fread((void *)&buffer[0], 1, N, fileDescriptor); if (read) { for ( int c = 0; c < read; ++c ) { total.push_back( buffer[ c ] ); } } if (read < N) { break; } } return total; } void loadShaders( JNIEnv* env, jobject& obj ) { AAssetManager *asset_manager = AAssetManager_fromJava( env, obj ); FILE* fd; fd = android_fopen( "vertex.glsl", "r", asset_manager ); gVertexShader = readShaderToString( fd ); fclose( fd ); fd = android_fopen( "fragment.glsl", "r", asset_manager ); gFragmentShader = readShaderToString( fd ); fclose( fd ); } GLuint loadShader(GLenum shaderType, const char* pSource) { GLuint shader = glCreateShader(shaderType); if (shader) { glShaderSource(shader, 1, &pSource, NULL); glCompileShader(shader); GLint compiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint infoLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen) { char* buf = (char*) malloc(infoLen); if (buf) { glGetShaderInfoLog(shader, infoLen, NULL, buf); LOGE("Could not compile shader %d:\n%s\n", shaderType, buf); free(buf); } glDeleteShader(shader); shader = 0; } } } return shader; } GLuint createProgram(const char* pVertexSource, const char* pFragmentSource) { GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource); if (!vertexShader) { return 0; } GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource); if (!pixelShader) { return 0; } GLuint program = glCreateProgram(); if (program) { glAttachShader(program, vertexShader); checkGlError("glAttachShader"); glAttachShader(program, pixelShader); checkGlError("glAttachShader"); glLinkProgram(program); GLint linkStatus = GL_FALSE; glGetProgramiv(program, GL_LINK_STATUS, &linkStatus); if (linkStatus != GL_TRUE) { GLint bufLength = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength); if (bufLength) { char* buf = (char*) malloc(bufLength); if (buf) { glGetProgramInfoLog(program, bufLength, NULL, buf); LOGE("Could not link program:\n%s\n", buf); free(buf); } } glDeleteProgram(program); program = 0; } } return program; } bool setupGraphics(int w, int h) { printGLString("Version", GL_VERSION); printGLString("Vendor", GL_VENDOR); printGLString("Renderer", GL_RENDERER); printGLString("Extensions", GL_EXTENSIONS); LOGI("setupGraphics(%d, %d)", w, h); gProgram = createProgram(gVertexShader.c_str(), gFragmentShader.c_str()); if (!gProgram) { LOGE("Could not create program."); return false; } vertexAttributePosition = glGetAttribLocation( gProgram, "aPosition" ); matrixAttributePosition = glGetUniformLocation( gProgram, "uMVP" ); glViewport(0, 0, w, h); checkGlError("glViewport"); return true; } void renderFrame() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); checkGlError("glClearColor"); glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); checkGlError("glClear"); glUseProgram(gProgram); checkGlError("glUseProgram"); glVertexAttribPointer ( vertexAttributePosition, 3, GL_FLOAT, GL_FALSE, 0, triangleVertices ); glEnableVertexAttribArray ( vertexAttributePosition ); glUniformMatrix4fv( matrixAttributePosition, false, 1, triangleTransformMatrix ); glDrawArrays ( GL_TRIANGLES, 0, 3 ); } extern "C" { JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_onCreate(JNIEnv * env, void* reserved, jobject assetManager ); JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_init(JNIEnv * env, jobject obj, jint width, jint height); JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_step(JNIEnv * env, jobject obj); }; JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_onCreate(JNIEnv * env, void* reserved, jobject assetManager ) { loadShaders( env, assetManager ); } JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_init(JNIEnv * env, jobject obj, jint width, jint height) { setupGraphics(width, height); } JNIEXPORT void JNICALL Java_br_odb_nehe_lesson02_GL2JNILib_step(JNIEnv * env, jobject obj) { renderFrame(); } <|endoftext|>
<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL. // // Simple example of use of Producer::RenderSurface to create an OpenGL // graphics window, and OSG for rendering. #include <osg/Timer> #include <osg/GraphicsContext> #include <osg/GraphicsThread> #include <osgUtil/UpdateVisitor> #include <osgUtil/CullVisitor> #include <osgUtil/SceneView> #include <osgUtil/GLObjectsVisitor> #include <osgDB/ReadFile> #include <osgDB/DynamicLibrary> #include <osgDB/Registry> #include <map> #include <list> #include <iostream> //////////////////////////////////////////////////////////////////////////////// // // // **************** THIS IS AN EXPERIMENTAL IMPLEMENTATION *************** // ************************** PLEASE DO NOT COPY ************************ // // /////////////////////////////////////////////////////////////////////////////// // Compile operation, that compile OpenGL objects. struct CompileOperation : public osg::GraphicsThread::Operation { CompileOperation(osg::Node* scene): osg::GraphicsThread::Operation("Compile",false), _scene(scene) { } virtual void operator () (osg::GraphicsContext* context) { std::cout<<"Compile"<<std::endl; osgUtil::GLObjectsVisitor compileVisitor; compileVisitor.setState(context->getState()); // do the compile traversal _scene->accept(compileVisitor); } osg::ref_ptr<osg::Node> _scene; }; // Cull operation, that does a cull on the scene graph. struct CullOperation : public osg::GraphicsThread::Operation { CullOperation(osg::CameraNode* camera, osgUtil::SceneView* sceneView): osg::GraphicsThread::Operation("Cull",true), _camera(camera), _sceneView(sceneView) { } virtual void operator () (osg::GraphicsContext* context) { _sceneView->setState(context->getState()); _sceneView->setProjectionMatrix(_camera->getProjectionMatrix()); _sceneView->setViewMatrix(_camera->getViewMatrix()); _sceneView->setViewport(_camera->getViewport()); _sceneView->cull(); } osg::CameraNode* _camera; osg::ref_ptr<osgUtil::SceneView> _sceneView; }; // Draw operation, that does a draw on the scene graph. struct DrawOperation : public osg::GraphicsThread::Operation { DrawOperation(osgUtil::SceneView* sceneView): osg::GraphicsThread::Operation("Draw",true), _sceneView(sceneView) { } virtual void operator () (osg::GraphicsContext*) { _sceneView->draw(); } osg::ref_ptr<osgUtil::SceneView> _sceneView; }; // main does the following steps to create a multi-thread, multiple camera/graphics context view of a scene graph. // // 1) load the scene graph // // 2) create a list of camera, each with their own graphis context, with a graphics thread for each context. // // 3) set up the graphic threads so that the do an initial compile OpenGL objects operation, this is done once, and then this compile op is disgarded // // 4) set up the graphics thread so that it has all the graphics ops required for the main loop, these ops are: // 4.a) frame begin barrair, syncronizes all the waiting graphic threads so they don't run while update is occuring // 4.b) frame operation - the cull and draw for each camera // 4.c) frame end barrier, releases the update thread once all graphic threads have dispatched all their OpenGL commands // 4.d) pre swap barrier, barrier which ensures that all graphics threads have sent their data down to the gfx card. // 4.e) swap buffers, do the swap buffers on all the graphics contexts. // // 5. The main loop: // 5.a) update // 5.b) join the frame begin barrrier, releasing all the graphics threads to do their stuff // 5.c) block on the frame end barrier, waiting till all the graphics threads have done their cull/draws. // 5.d) check to see if any of the windows has been closed. // int main( int argc, char **argv ) { if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } // load the osgProducer library manually. osg::ref_ptr<osgDB::DynamicLibrary> osgProducerLib = osgDB::DynamicLibrary::loadLibrary(osgDB::Registry::instance()->createLibraryNameForNodeKit("osgProducer")); // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } // set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly osg::ref_ptr<osg::FrameStamp> frameStamp = new osg::FrameStamp; unsigned int frameNum = 0; osgUtil::UpdateVisitor updateVisitor; updateVisitor.setFrameStamp(frameStamp.get()); unsigned int numberCameras = 3; unsigned int xpos = 0; unsigned int ypos = 400; unsigned int width = 400; unsigned int height = 400; typedef std::list< osg::ref_ptr<osg::CameraNode> > CameraList; typedef std::set< osg::GraphicsContext* > GraphicsContextSet; CameraList cameraList; GraphicsContextSet graphicsContextSet; // create the cameras, graphic contexts and graphic threads. bool shareContexts = false; osg::GraphicsContext* previousContext = 0; for(unsigned int i=0; i< numberCameras; ++i) { osg::ref_ptr<osg::CameraNode> camera = new osg::CameraNode; camera->addChild(loadedModel.get()); osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->_windowName = "osgcamera"; traits->_x = xpos; traits->_y = ypos; traits->_width = width; traits->_height = height; traits->_windowDecoration = true; traits->_doubleBuffer = true; traits->_sharedContext = shareContexts ? previousContext : 0; xpos += width; osg::ref_ptr<osg::GraphicsContext> gfxc = osg::GraphicsContext::createGraphicsContext(traits.get()); if (!gfxc) { std::cout<<"Unable to create window."<<std::endl; return 1; } camera->setGraphicsContext(gfxc.get()); // initialize the view to look at the center of the scene graph const osg::BoundingSphere& bs = loadedModel->getBound(); osg::Matrix viewMatrix; viewMatrix.makeLookAt(bs.center()-osg::Vec3(0.0,2.0f*bs.radius(),0.0),bs.center(),osg::Vec3(0.0f,0.0f,1.0f)); camera->setViewport(0,0,traits->_width,traits->_height); camera->setProjectionMatrixAsPerspective(50.0f,1.4f,1.0f,10000.0f); camera->setViewMatrix(viewMatrix); // graphics thread will realize the window. gfxc->createGraphicsThread(); cameraList.push_back(camera); previousContext = gfxc.get(); } // build the list of unique graphics contexts. CameraList::iterator citr; for(citr = cameraList.begin(); citr != cameraList.end(); ++citr) { graphicsContextSet.insert(const_cast<osg::GraphicsContext*>((*citr)->getGraphicsContext())); } std::cout<<"Number of cameras = "<<cameraList.size()<<std::endl; std::cout<<"Number of graphics contexts = "<<graphicsContextSet.size()<<std::endl; // first the compile of the GL Objects, do it syncronously. GraphicsContextSet::iterator gitr; osg::ref_ptr<CompileOperation> compileOp = new CompileOperation(loadedModel.get()); for(gitr = graphicsContextSet.begin(); gitr != graphicsContextSet.end(); ++gitr) { osg::GraphicsContext* context = *gitr; context->getGraphicsThread()->add(compileOp.get(), false); } // second the begin frame barrier to all graphics threads osg::ref_ptr<osg::BarrierOperation> frameBeginBarrierOp = new osg::BarrierOperation(graphicsContextSet.size()+1, osg::BarrierOperation::NO_OPERATION); for(gitr = graphicsContextSet.begin(); gitr != graphicsContextSet.end(); ++gitr) { osg::GraphicsContext* context = *gitr; context->getGraphicsThread()->add(frameBeginBarrierOp.get(), false); } osg::ref_ptr<osg::BarrierOperation> glFinishBarrierOp = new osg::BarrierOperation(graphicsContextSet.size(), osg::BarrierOperation::GL_FINISH); // we can put a finish in to gate rendering throughput, so that each new frame starts with a clean sheet. // you should only enable one of these, doFinishBeforeNewDraw will allow for the better parallism of the two finish approaches // note, both are disabled right now, as glFinish is spin locking the CPU, not something that we want... bool doFinishBeforeNewDraw = false; bool doFinishAfterSwap = false; // third add the frame for each camera. for(citr = cameraList.begin(); citr != cameraList.end(); ++citr) { osg::CameraNode* camera = citr->get(); // create a scene view to do the cull and draw osgUtil::SceneView* sceneView = new osgUtil::SceneView; sceneView->setDefaults(); sceneView->setFrameStamp(frameStamp.get()); if (camera->getNumChildren()>=1) { sceneView->setSceneData(camera->getChild(0)); } // cull traversal operation camera->getGraphicsContext()->getGraphicsThread()->add( new CullOperation(camera, sceneView), false); // optionally add glFinish barrier to ensure that all OpenGL commands are completed before we start dispatching a new frame if (doFinishBeforeNewDraw) camera->getGraphicsContext()->getGraphicsThread()->add( glFinishBarrierOp.get(), false); // draw traversal operation. camera->getGraphicsContext()->getGraphicsThread()->add( new DrawOperation(sceneView), false); } // fourth add the frame end barrier, the pre swap barrier and finally the swap buffers to each graphics thread. // The frame end barrier tells the main thead that the draw dispatch/read phase of the scene graph is complete. // The pre swap barrier is an optional extra, which does a flush before joining the barrier, using this all graphics threads // are held back until they have all dispatched their fifo to the graphics hardware. // The swapOp just issues a swap buffers for each of the graphics contexts. osg::ref_ptr<osg::BarrierOperation> frameEndBarrierOp = new osg::BarrierOperation(graphicsContextSet.size()+1, osg::BarrierOperation::NO_OPERATION); osg::ref_ptr<osg::BarrierOperation> preSwapBarrierOp = new osg::BarrierOperation(graphicsContextSet.size(), osg::BarrierOperation::GL_FLUSH); osg::ref_ptr<osg::SwapBuffersOperation> swapOp = new osg::SwapBuffersOperation(); for(gitr = graphicsContextSet.begin(); gitr != graphicsContextSet.end(); ++gitr) { osg::GraphicsContext* context = *gitr; context->getGraphicsThread()->add(frameEndBarrierOp.get(), false); // context->getGraphicsThread()->add(preSwapBarrierOp.get(), false); context->getGraphicsThread()->add(swapOp.get(), false); // optionally add finish barrier to ensure that we don't do any other graphics work till the current OpenGL commands are complete. if (doFinishAfterSwap) context->getGraphicsThread()->add(glFinishBarrierOp.get(), false); } // record the timer tick at the start of rendering. osg::Timer_t start_tick = osg::Timer::instance()->tick(); osg::Timer_t previous_tick = start_tick; bool done = false; unsigned int maxNumFrames = 50; // main loop - update scene graph, dispatch frame, wait for frame done. while( !done && frameNum<maxNumFrames) { osg::Timer_t current_tick = osg::Timer::instance()->tick(); frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,current_tick)); frameStamp->setFrameNumber(frameNum++); //std::cout<<"Frame rate "<<1.0/osg::Timer::instance()->delta_s(previous_tick,current_tick)<<std::endl; previous_tick = current_tick; // do the update traversal. loadedModel->accept(updateVisitor); // dispatch the frame. frameBeginBarrierOp->block(); // wait till the frame is done. frameEndBarrierOp->block(); // check if any of the windows are closed for(gitr = graphicsContextSet.begin(); gitr != graphicsContextSet.end(); ++gitr) { osg::GraphicsContext* context = *gitr; if (!context->isRealized()) done = true; } } // delete the cameras, associated contexts and threads. cameraList.clear(); std::cout<<"Exiting application"<<std::endl; return 0; } <commit_msg>Added commandline arguments for controlling number of cameras through to the windowing library to use.<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL. // // Simple example of use of Producer::RenderSurface to create an OpenGL // graphics window, and OSG for rendering. #include <osg/Timer> #include <osg/GraphicsContext> #include <osg/GraphicsThread> #include <osgUtil/UpdateVisitor> #include <osgUtil/CullVisitor> #include <osgUtil/SceneView> #include <osgUtil/GLObjectsVisitor> #include <osgDB/ReadFile> #include <osgDB/DynamicLibrary> #include <osgDB/Registry> #include <map> #include <list> #include <iostream> //////////////////////////////////////////////////////////////////////////////// // // // **************** THIS IS AN EXPERIMENTAL IMPLEMENTATION *************** // ************************** PLEASE DO NOT COPY ************************ // // /////////////////////////////////////////////////////////////////////////////// // Compile operation, that compile OpenGL objects. struct CompileOperation : public osg::GraphicsThread::Operation { CompileOperation(osg::Node* scene): osg::GraphicsThread::Operation("Compile",false), _scene(scene) { } virtual void operator () (osg::GraphicsContext* context) { std::cout<<"Compile"<<std::endl; osgUtil::GLObjectsVisitor compileVisitor; compileVisitor.setState(context->getState()); // do the compile traversal _scene->accept(compileVisitor); } osg::ref_ptr<osg::Node> _scene; }; // Cull operation, that does a cull on the scene graph. struct CullOperation : public osg::GraphicsThread::Operation { CullOperation(osg::CameraNode* camera, osgUtil::SceneView* sceneView): osg::GraphicsThread::Operation("Cull",true), _camera(camera), _sceneView(sceneView) { } virtual void operator () (osg::GraphicsContext* context) { _sceneView->setState(context->getState()); _sceneView->setProjectionMatrix(_camera->getProjectionMatrix()); _sceneView->setViewMatrix(_camera->getViewMatrix()); _sceneView->setViewport(_camera->getViewport()); _sceneView->cull(); } osg::CameraNode* _camera; osg::ref_ptr<osgUtil::SceneView> _sceneView; }; // Draw operation, that does a draw on the scene graph. struct DrawOperation : public osg::GraphicsThread::Operation { DrawOperation(osgUtil::SceneView* sceneView): osg::GraphicsThread::Operation("Draw",true), _sceneView(sceneView) { } virtual void operator () (osg::GraphicsContext*) { _sceneView->draw(); } osg::ref_ptr<osgUtil::SceneView> _sceneView; }; // main does the following steps to create a multi-thread, multiple camera/graphics context view of a scene graph. // // 1) load the scene graph // // 2) create a list of camera, each with their own graphis context, with a graphics thread for each context. // // 3) set up the graphic threads so that the do an initial compile OpenGL objects operation, this is done once, and then this compile op is disgarded // // 4) set up the graphics thread so that it has all the graphics ops required for the main loop, these ops are: // 4.a) frame begin barrair, syncronizes all the waiting graphic threads so they don't run while update is occuring // 4.b) frame operation - the cull and draw for each camera // 4.c) frame end barrier, releases the update thread once all graphic threads have dispatched all their OpenGL commands // 4.d) pre swap barrier, barrier which ensures that all graphics threads have sent their data down to the gfx card. // 4.e) swap buffers, do the swap buffers on all the graphics contexts. // // 5. The main loop: // 5.a) update // 5.b) join the frame begin barrrier, releasing all the graphics threads to do their stuff // 5.c) block on the frame end barrier, waiting till all the graphics threads have done their cull/draws. // 5.d) check to see if any of the windows has been closed. // int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); std::string windowingLibrary("osgProducer"); while (arguments.read("--windowing",windowingLibrary)) {} // load the osgProducer library manually. osg::ref_ptr<osgDB::DynamicLibrary> windowingLib = osgDB::DynamicLibrary::loadLibrary(osgDB::Registry::instance()->createLibraryNameForNodeKit(windowingLibrary)); if (!windowingLib) { std::cout<<"Error: failed to loading windowing library: "<<windowingLibrary<<std::endl; } unsigned int numberCameras = 3; while (arguments.read("--cameras",numberCameras)) {} unsigned int xpos = 0; unsigned int ypos = 400; unsigned int width = 400; unsigned int height = 400; while (arguments.read("--xpos",xpos)) {} while (arguments.read("--ypos",ypos)) {} while (arguments.read("--height",height)) {} while (arguments.read("--width",width)) {} unsigned int maxNumFrames = 1000; while (arguments.read("--max-num-frames",maxNumFrames)) {} // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } // set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly osg::ref_ptr<osg::FrameStamp> frameStamp = new osg::FrameStamp; unsigned int frameNum = 0; osgUtil::UpdateVisitor updateVisitor; updateVisitor.setFrameStamp(frameStamp.get()); typedef std::list< osg::ref_ptr<osg::CameraNode> > CameraList; typedef std::set< osg::GraphicsContext* > GraphicsContextSet; CameraList cameraList; GraphicsContextSet graphicsContextSet; // create the cameras, graphic contexts and graphic threads. bool shareContexts = false; osg::GraphicsContext* previousContext = 0; for(unsigned int i=0; i< numberCameras; ++i) { osg::ref_ptr<osg::CameraNode> camera = new osg::CameraNode; camera->addChild(loadedModel.get()); osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->_windowName = "osgcamera"; traits->_x = xpos; traits->_y = ypos; traits->_width = width; traits->_height = height; traits->_windowDecoration = true; traits->_doubleBuffer = true; traits->_sharedContext = shareContexts ? previousContext : 0; xpos += width; osg::ref_ptr<osg::GraphicsContext> gfxc = osg::GraphicsContext::createGraphicsContext(traits.get()); if (!gfxc) { std::cout<<"Unable to create window."<<std::endl; return 1; } camera->setGraphicsContext(gfxc.get()); // initialize the view to look at the center of the scene graph const osg::BoundingSphere& bs = loadedModel->getBound(); osg::Matrix viewMatrix; viewMatrix.makeLookAt(bs.center()-osg::Vec3(0.0,2.0f*bs.radius(),0.0),bs.center(),osg::Vec3(0.0f,0.0f,1.0f)); camera->setViewport(0,0,traits->_width,traits->_height); camera->setProjectionMatrixAsPerspective(50.0f,1.4f,1.0f,10000.0f); camera->setViewMatrix(viewMatrix); // graphics thread will realize the window. gfxc->createGraphicsThread(); cameraList.push_back(camera); previousContext = gfxc.get(); } // build the list of unique graphics contexts. CameraList::iterator citr; for(citr = cameraList.begin(); citr != cameraList.end(); ++citr) { graphicsContextSet.insert(const_cast<osg::GraphicsContext*>((*citr)->getGraphicsContext())); } std::cout<<"Number of cameras = "<<cameraList.size()<<std::endl; std::cout<<"Number of graphics contexts = "<<graphicsContextSet.size()<<std::endl; // first the compile of the GL Objects, do it syncronously. GraphicsContextSet::iterator gitr; osg::ref_ptr<CompileOperation> compileOp = new CompileOperation(loadedModel.get()); for(gitr = graphicsContextSet.begin(); gitr != graphicsContextSet.end(); ++gitr) { osg::GraphicsContext* context = *gitr; context->getGraphicsThread()->add(compileOp.get(), false); } // second the begin frame barrier to all graphics threads osg::ref_ptr<osg::BarrierOperation> frameBeginBarrierOp = new osg::BarrierOperation(graphicsContextSet.size()+1, osg::BarrierOperation::NO_OPERATION); for(gitr = graphicsContextSet.begin(); gitr != graphicsContextSet.end(); ++gitr) { osg::GraphicsContext* context = *gitr; context->getGraphicsThread()->add(frameBeginBarrierOp.get(), false); } osg::ref_ptr<osg::BarrierOperation> glFinishBarrierOp = new osg::BarrierOperation(graphicsContextSet.size(), osg::BarrierOperation::GL_FINISH); // we can put a finish in to gate rendering throughput, so that each new frame starts with a clean sheet. // you should only enable one of these, doFinishBeforeNewDraw will allow for the better parallism of the two finish approaches // note, both are disabled right now, as glFinish is spin locking the CPU, not something that we want... bool doFinishBeforeNewDraw = false; bool doFinishAfterSwap = false; // third add the frame for each camera. for(citr = cameraList.begin(); citr != cameraList.end(); ++citr) { osg::CameraNode* camera = citr->get(); // create a scene view to do the cull and draw osgUtil::SceneView* sceneView = new osgUtil::SceneView; sceneView->setDefaults(); sceneView->setFrameStamp(frameStamp.get()); if (camera->getNumChildren()>=1) { sceneView->setSceneData(camera->getChild(0)); } // cull traversal operation camera->getGraphicsContext()->getGraphicsThread()->add( new CullOperation(camera, sceneView), false); // optionally add glFinish barrier to ensure that all OpenGL commands are completed before we start dispatching a new frame if (doFinishBeforeNewDraw) camera->getGraphicsContext()->getGraphicsThread()->add( glFinishBarrierOp.get(), false); // draw traversal operation. camera->getGraphicsContext()->getGraphicsThread()->add( new DrawOperation(sceneView), false); } // fourth add the frame end barrier, the pre swap barrier and finally the swap buffers to each graphics thread. // The frame end barrier tells the main thead that the draw dispatch/read phase of the scene graph is complete. // The pre swap barrier is an optional extra, which does a flush before joining the barrier, using this all graphics threads // are held back until they have all dispatched their fifo to the graphics hardware. // The swapOp just issues a swap buffers for each of the graphics contexts. osg::ref_ptr<osg::BarrierOperation> frameEndBarrierOp = new osg::BarrierOperation(graphicsContextSet.size()+1, osg::BarrierOperation::NO_OPERATION); osg::ref_ptr<osg::BarrierOperation> preSwapBarrierOp = new osg::BarrierOperation(graphicsContextSet.size(), osg::BarrierOperation::GL_FLUSH); osg::ref_ptr<osg::SwapBuffersOperation> swapOp = new osg::SwapBuffersOperation(); for(gitr = graphicsContextSet.begin(); gitr != graphicsContextSet.end(); ++gitr) { osg::GraphicsContext* context = *gitr; context->getGraphicsThread()->add(frameEndBarrierOp.get(), false); // context->getGraphicsThread()->add(preSwapBarrierOp.get(), false); context->getGraphicsThread()->add(swapOp.get(), false); // optionally add finish barrier to ensure that we don't do any other graphics work till the current OpenGL commands are complete. if (doFinishAfterSwap) context->getGraphicsThread()->add(glFinishBarrierOp.get(), false); } // record the timer tick at the start of rendering. osg::Timer_t start_tick = osg::Timer::instance()->tick(); osg::Timer_t previous_tick = start_tick; bool done = false; // main loop - update scene graph, dispatch frame, wait for frame done. while( !done && frameNum<maxNumFrames) { osg::Timer_t current_tick = osg::Timer::instance()->tick(); frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,current_tick)); frameStamp->setFrameNumber(frameNum++); //std::cout<<"Frame rate "<<1.0/osg::Timer::instance()->delta_s(previous_tick,current_tick)<<std::endl; previous_tick = current_tick; // do the update traversal. loadedModel->accept(updateVisitor); // dispatch the frame. frameBeginBarrierOp->block(); // wait till the frame is done. frameEndBarrierOp->block(); // check if any of the windows are closed for(gitr = graphicsContextSet.begin(); gitr != graphicsContextSet.end(); ++gitr) { osg::GraphicsContext* context = *gitr; if (!context->isRealized()) done = true; } } std::cout<<"Exiting application"<<std::endl; return 0; } <|endoftext|>
<commit_before>#ifndef PARSER_HH #define PARSER_HH #include <cstdlib> // size_t #include <map> class Bookmark; class BookmarkContainer; class Parser { enum Language { C_FAMILY, SCRIPT, ERLANG, PYTHON, ALL }; enum State { NORMAL, COMMENT_START, C_COMMENT, C_COMMENT_END, DOUBLE_QUOTE, DOUBLE_QUOTE_1, DOUBLE_QUOTE_2, DOUBLE_QUOTE_3, DOUBLE_QUOTE_4, DOUBLE_QUOTE_5, SINGLE_QUOTE_1, SINGLE_QUOTE_2, SINGLE_QUOTE_3, SINGLE_QUOTE_4, SINGLE_QUOTE_5, SINGLE_QUOTE, ESCAPE_DOUBLE, ESCAPE_SINGLE, SKIP_TO_EOL, SPACE, NO_STATE }; enum Action { NA, ADD_CHAR, ADD_SLASH_AND_CHAR, ADD_BOOKMARK, ADD_SPACE }; struct Value; struct Cell; struct Key; typedef std::map<Key, Value> Matrix; public: Parser(BookmarkContainer& container): timeForNewBookmark(true), itsContainer(container) {} const char* process(bool wordMode); private: State processChar(State state, const Matrix& matrix, size_t i); void performAction(Action action, char c, size_t i); Bookmark addChar(char c, int originalIndex); const Matrix& codeBehavior() const; const Matrix& textBehavior() const; Language getLanguage(const std::string& fileName); const char* stateToString(State s); bool timeForNewBookmark; BookmarkContainer& itsContainer; char* itsProcessedText; }; #endif <commit_msg>Fix missing include (compilation error)<commit_after>#ifndef PARSER_HH #define PARSER_HH #include <cstdlib> // size_t #include <map> #include <string> class Bookmark; class BookmarkContainer; class Parser { enum Language { C_FAMILY, SCRIPT, ERLANG, PYTHON, ALL }; enum State { NORMAL, COMMENT_START, C_COMMENT, C_COMMENT_END, DOUBLE_QUOTE, DOUBLE_QUOTE_1, DOUBLE_QUOTE_2, DOUBLE_QUOTE_3, DOUBLE_QUOTE_4, DOUBLE_QUOTE_5, SINGLE_QUOTE_1, SINGLE_QUOTE_2, SINGLE_QUOTE_3, SINGLE_QUOTE_4, SINGLE_QUOTE_5, SINGLE_QUOTE, ESCAPE_DOUBLE, ESCAPE_SINGLE, SKIP_TO_EOL, SPACE, NO_STATE }; enum Action { NA, ADD_CHAR, ADD_SLASH_AND_CHAR, ADD_BOOKMARK, ADD_SPACE }; struct Value; struct Cell; struct Key; typedef std::map<Key, Value> Matrix; public: Parser(BookmarkContainer& container): timeForNewBookmark(true), itsContainer(container) {} const char* process(bool wordMode); private: State processChar(State state, const Matrix& matrix, size_t i); void performAction(Action action, char c, size_t i); Bookmark addChar(char c, int originalIndex); const Matrix& codeBehavior() const; const Matrix& textBehavior() const; Language getLanguage(const std::string& fileName); const char* stateToString(State s); bool timeForNewBookmark; BookmarkContainer& itsContainer; char* itsProcessedText; }; #endif <|endoftext|>
<commit_before>/* * Vulkan Example - Using different pipelines in one single renderpass * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "vulkanexamplebase.h" #include "VulkanglTFModel.h" #define ENABLE_VALIDATION false class VulkanExample: public VulkanExampleBase { public: vkglTF::Model scene; vks::Buffer uniformBuffer; // Same uniform buffer layout as shader struct UBOVS { glm::mat4 projection; glm::mat4 modelView; glm::vec4 lightPos = glm::vec4(0.0f, 2.0f, 1.0f, 0.0f); } uboVS; VkPipelineLayout pipelineLayout; VkDescriptorSet descriptorSet; VkDescriptorSetLayout descriptorSetLayout; struct { VkPipeline phong; VkPipeline wireframe; VkPipeline toon; } pipelines; VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION) { title = "Pipeline state objects"; camera.type = Camera::CameraType::lookat; camera.setPosition(glm::vec3(0.0f, 0.0f, -10.5f)); camera.setRotation(glm::vec3(-25.0f, 15.0f, 0.0f)); camera.setRotationSpeed(0.5f); camera.setPerspective(60.0f, (float)(width / 3.0f) / (float)height, 0.1f, 256.0f); } ~VulkanExample() { // Clean up used Vulkan resources // Note : Inherited destructor cleans up resources stored in base class vkDestroyPipeline(device, pipelines.phong, nullptr); if (deviceFeatures.fillModeNonSolid) { vkDestroyPipeline(device, pipelines.wireframe, nullptr); } vkDestroyPipeline(device, pipelines.toon, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); uniformBuffer.destroy(); } // Enable physical device features required for this example virtual void getEnabledFeatures() { // Fill mode non solid is required for wireframe display if (deviceFeatures.fillModeNonSolid) { enabledFeatures.fillModeNonSolid = VK_TRUE; // Wide lines must be present for line width > 1.0f if (deviceFeatures.wideLines) { enabledFeatures.wideLines = VK_TRUE; } }; } void buildCommandBuffers() { VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); VkClearValue clearValues[2]; clearValues[0].color = defaultClearColor; clearValues[1].depthStencil = { 1.0f, 0 }; VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); renderPassBeginInfo.renderPass = renderPass; renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent.width = width; renderPassBeginInfo.renderArea.extent.height = height; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; for (int32_t i = 0; i < drawCmdBuffers.size(); ++i) { // Set target frame buffer renderPassBeginInfo.framebuffer = frameBuffers[i]; VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo)); vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor); vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, NULL); scene.bindBuffers(drawCmdBuffers[i]); // Left : Solid colored viewport.width = (float)width / 3.0; vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.phong); scene.draw(drawCmdBuffers[i]); // Center : Toon viewport.x = (float)width / 3.0; vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.toon); // Line width > 1.0f only if wide lines feature is supported if (deviceFeatures.wideLines) { vkCmdSetLineWidth(drawCmdBuffers[i], 2.0f); } scene.draw(drawCmdBuffers[i]); if (deviceFeatures.fillModeNonSolid) { // Right : Wireframe viewport.x = (float)width / 3.0 + (float)width / 3.0; vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.wireframe); scene.draw(drawCmdBuffers[i]); } drawUI(drawCmdBuffers[i]); vkCmdEndRenderPass(drawCmdBuffers[i]); VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i])); } } void loadAssets() { const uint32_t glTFLoadingFlags = vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::PreMultiplyVertexColors | vkglTF::FileLoadingFlags::FlipY; scene.loadFromFile(getAssetPath() + "models/treasure_smooth.gltf", vulkanDevice, queue, glTFLoadingFlags); } void setupDescriptorPool() { std::vector<VkDescriptorPoolSize> poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1) }; VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo( poolSizes.size(), poolSizes.data(), 2); VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); } void setupDescriptorSetLayout() { std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { // Binding 0 : Vertex shader uniform buffer vks::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0) }; VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo( setLayoutBindings.data(), setLayoutBindings.size()); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo( &descriptorSetLayout, 1); VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout)); } void setupDescriptorSet() { VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo( descriptorPool, &descriptorSetLayout, 1); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); std::vector<VkWriteDescriptorSet> writeDescriptorSets = { // Binding 0 : Vertex shader uniform buffer vks::initializers::writeDescriptorSet( descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffer.descriptor) }; vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); } void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH, }; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelineLayout, renderPass); pipelineCI.pInputAssemblyState = &inputAssemblyState; pipelineCI.pRasterizationState = &rasterizationState; pipelineCI.pColorBlendState = &colorBlendState; pipelineCI.pMultisampleState = &multisampleState; pipelineCI.pViewportState = &viewportState; pipelineCI.pDepthStencilState = &depthStencilState; pipelineCI.pDynamicState = &dynamicState; pipelineCI.stageCount = shaderStages.size(); pipelineCI.pStages = shaderStages.data(); pipelineCI.pVertexInputState = vkglTF::Vertex::getPipelineVertexInputState({vkglTF::VertexComponent::Position, vkglTF::VertexComponent::Normal, vkglTF::VertexComponent::Color}); // Create the graphics pipeline state objects // We are using this pipeline as the base for the other pipelines (derivatives) // Pipeline derivatives can be used for pipelines that share most of their state // Depending on the implementation this may result in better performance for pipeline // switching and faster creation time pipelineCI.flags = VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT; // Textured pipeline // Phong shading pipeline shaderStages[0] = loadShader(getShadersPath() + "pipelines/phong.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getShadersPath() + "pipelines/phong.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.phong)); // All pipelines created after the base pipeline will be derivatives pipelineCI.flags = VK_PIPELINE_CREATE_DERIVATIVE_BIT; // Base pipeline will be our first created pipeline pipelineCI.basePipelineHandle = pipelines.phong; // It's only allowed to either use a handle or index for the base pipeline // As we use the handle, we must set the index to -1 (see section 9.5 of the specification) pipelineCI.basePipelineIndex = -1; // Toon shading pipeline shaderStages[0] = loadShader(getShadersPath() + "pipelines/toon.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getShadersPath() + "pipelines/toon.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.toon)); // Pipeline for wire frame rendering // Non solid rendering is not a mandatory Vulkan feature if (deviceFeatures.fillModeNonSolid) { rasterizationState.polygonMode = VK_POLYGON_MODE_LINE; shaderStages[0] = loadShader(getShadersPath() + "pipelines/wireframe.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getShadersPath() + "pipelines/wireframe.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.wireframe)); } } // Prepare and initialize uniform buffer containing shader uniforms void prepareUniformBuffers() { // Create the vertex shader uniform buffer block VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffer, sizeof(uboVS))); // Map persistent VK_CHECK_RESULT(uniformBuffer.map()); updateUniformBuffers(); } void updateUniformBuffers() { uboVS.projection = camera.matrices.perspective; uboVS.modelView = camera.matrices.view; memcpy(uniformBuffer.mapped, &uboVS, sizeof(uboVS)); } void draw() { VulkanExampleBase::prepareFrame(); submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer]; VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VulkanExampleBase::submitFrame(); } void prepare() { VulkanExampleBase::prepare(); loadAssets(); prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); buildCommandBuffers(); prepared = true; } virtual void render() { if (!prepared) return; draw(); if (camera.updated) { updateUniformBuffers(); } } virtual void viewChanged() { camera.setPerspective(60.0f, (float)(width / 3.0f) / (float)height, 0.1f, 256.0f); updateUniformBuffers(); } virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay) { if (!deviceFeatures.fillModeNonSolid) { if (overlay->header("Info")) { overlay->text("Non solid fill modes not supported!"); } } } }; VULKAN_EXAMPLE_MAIN() <commit_msg>Fixes to dynamic state behavior in pipelines demo<commit_after>/* * Vulkan Example - Using different pipelines in one single renderpass * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "vulkanexamplebase.h" #include "VulkanglTFModel.h" #define ENABLE_VALIDATION false class VulkanExample: public VulkanExampleBase { public: vkglTF::Model scene; vks::Buffer uniformBuffer; // Same uniform buffer layout as shader struct UBOVS { glm::mat4 projection; glm::mat4 modelView; glm::vec4 lightPos = glm::vec4(0.0f, 2.0f, 1.0f, 0.0f); } uboVS; VkPipelineLayout pipelineLayout; VkDescriptorSet descriptorSet; VkDescriptorSetLayout descriptorSetLayout; struct { VkPipeline phong; VkPipeline wireframe; VkPipeline toon; } pipelines; VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION) { title = "Pipeline state objects"; camera.type = Camera::CameraType::lookat; camera.setPosition(glm::vec3(0.0f, 0.0f, -10.5f)); camera.setRotation(glm::vec3(-25.0f, 15.0f, 0.0f)); camera.setRotationSpeed(0.5f); camera.setPerspective(60.0f, (float)(width / 3.0f) / (float)height, 0.1f, 256.0f); } ~VulkanExample() { // Clean up used Vulkan resources // Note : Inherited destructor cleans up resources stored in base class vkDestroyPipeline(device, pipelines.phong, nullptr); if (enabledFeatures.fillModeNonSolid) { vkDestroyPipeline(device, pipelines.wireframe, nullptr); } vkDestroyPipeline(device, pipelines.toon, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); uniformBuffer.destroy(); } // Enable physical device features required for this example virtual void getEnabledFeatures() { // Fill mode non solid is required for wireframe display if (deviceFeatures.fillModeNonSolid) { enabledFeatures.fillModeNonSolid = VK_TRUE; }; // Wide lines must be present for line width > 1.0f if (deviceFeatures.wideLines) { enabledFeatures.wideLines = VK_TRUE; } } void buildCommandBuffers() { VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); VkClearValue clearValues[2]; clearValues[0].color = defaultClearColor; clearValues[1].depthStencil = { 1.0f, 0 }; VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); renderPassBeginInfo.renderPass = renderPass; renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent.width = width; renderPassBeginInfo.renderArea.extent.height = height; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; for (int32_t i = 0; i < drawCmdBuffers.size(); ++i) { // Set target frame buffer renderPassBeginInfo.framebuffer = frameBuffers[i]; VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo)); vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor); vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, NULL); scene.bindBuffers(drawCmdBuffers[i]); // Left : Solid colored viewport.width = (float)width / 3.0; vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.phong); vkCmdSetLineWidth(drawCmdBuffers[i], 1.0f); scene.draw(drawCmdBuffers[i]); // Center : Toon viewport.x = (float)width / 3.0; vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.toon); // Line width > 1.0f only if wide lines feature is supported if (enabledFeatures.wideLines) { vkCmdSetLineWidth(drawCmdBuffers[i], 2.0f); } scene.draw(drawCmdBuffers[i]); if (enabledFeatures.fillModeNonSolid) { // Right : Wireframe viewport.x = (float)width / 3.0 + (float)width / 3.0; vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.wireframe); scene.draw(drawCmdBuffers[i]); } drawUI(drawCmdBuffers[i]); vkCmdEndRenderPass(drawCmdBuffers[i]); VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i])); } } void loadAssets() { const uint32_t glTFLoadingFlags = vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::PreMultiplyVertexColors | vkglTF::FileLoadingFlags::FlipY; scene.loadFromFile(getAssetPath() + "models/treasure_smooth.gltf", vulkanDevice, queue, glTFLoadingFlags); } void setupDescriptorPool() { std::vector<VkDescriptorPoolSize> poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1) }; VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo( poolSizes.size(), poolSizes.data(), 2); VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); } void setupDescriptorSetLayout() { std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { // Binding 0 : Vertex shader uniform buffer vks::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0) }; VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo( setLayoutBindings.data(), setLayoutBindings.size()); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo( &descriptorSetLayout, 1); VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout)); } void setupDescriptorSet() { VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo( descriptorPool, &descriptorSetLayout, 1); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); std::vector<VkWriteDescriptorSet> writeDescriptorSets = { // Binding 0 : Vertex shader uniform buffer vks::initializers::writeDescriptorSet( descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffer.descriptor) }; vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); } void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH, }; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelineLayout, renderPass); pipelineCI.pInputAssemblyState = &inputAssemblyState; pipelineCI.pRasterizationState = &rasterizationState; pipelineCI.pColorBlendState = &colorBlendState; pipelineCI.pMultisampleState = &multisampleState; pipelineCI.pViewportState = &viewportState; pipelineCI.pDepthStencilState = &depthStencilState; pipelineCI.pDynamicState = &dynamicState; pipelineCI.stageCount = shaderStages.size(); pipelineCI.pStages = shaderStages.data(); pipelineCI.pVertexInputState = vkglTF::Vertex::getPipelineVertexInputState({vkglTF::VertexComponent::Position, vkglTF::VertexComponent::Normal, vkglTF::VertexComponent::Color}); // Create the graphics pipeline state objects // We are using this pipeline as the base for the other pipelines (derivatives) // Pipeline derivatives can be used for pipelines that share most of their state // Depending on the implementation this may result in better performance for pipeline // switching and faster creation time pipelineCI.flags = VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT; // Textured pipeline // Phong shading pipeline shaderStages[0] = loadShader(getShadersPath() + "pipelines/phong.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getShadersPath() + "pipelines/phong.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.phong)); // All pipelines created after the base pipeline will be derivatives pipelineCI.flags = VK_PIPELINE_CREATE_DERIVATIVE_BIT; // Base pipeline will be our first created pipeline pipelineCI.basePipelineHandle = pipelines.phong; // It's only allowed to either use a handle or index for the base pipeline // As we use the handle, we must set the index to -1 (see section 9.5 of the specification) pipelineCI.basePipelineIndex = -1; // Toon shading pipeline shaderStages[0] = loadShader(getShadersPath() + "pipelines/toon.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getShadersPath() + "pipelines/toon.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.toon)); // Pipeline for wire frame rendering // Non solid rendering is not a mandatory Vulkan feature if (enabledFeatures.fillModeNonSolid) { rasterizationState.polygonMode = VK_POLYGON_MODE_LINE; shaderStages[0] = loadShader(getShadersPath() + "pipelines/wireframe.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getShadersPath() + "pipelines/wireframe.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.wireframe)); } } // Prepare and initialize uniform buffer containing shader uniforms void prepareUniformBuffers() { // Create the vertex shader uniform buffer block VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffer, sizeof(uboVS))); // Map persistent VK_CHECK_RESULT(uniformBuffer.map()); updateUniformBuffers(); } void updateUniformBuffers() { uboVS.projection = camera.matrices.perspective; uboVS.modelView = camera.matrices.view; memcpy(uniformBuffer.mapped, &uboVS, sizeof(uboVS)); } void draw() { VulkanExampleBase::prepareFrame(); submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer]; VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VulkanExampleBase::submitFrame(); } void prepare() { VulkanExampleBase::prepare(); loadAssets(); prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); buildCommandBuffers(); prepared = true; } virtual void render() { if (!prepared) return; draw(); if (camera.updated) { updateUniformBuffers(); } } virtual void viewChanged() { camera.setPerspective(60.0f, (float)(width / 3.0f) / (float)height, 0.1f, 256.0f); updateUniformBuffers(); } virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay) { if (!enabledFeatures.fillModeNonSolid) { if (overlay->header("Info")) { overlay->text("Non solid fill modes not supported!"); } } } }; VULKAN_EXAMPLE_MAIN() <|endoftext|>
<commit_before>// @COPYRIGHT@ // Licensed under MIT license. // See LICENSE.TXT file in the project root for more information. // ============================================================== #ifndef __SHADOW_MEMORY__ #define __SHADOW_MEMORY__ #include<stdint.h> #include<atomic> #include<stdlib.h> #include<sys/mman.h> #include<tuple> // 64KB shadow pages #define PAGE_OFFSET_BITS (16LL) #define PAGE_OFFSET(addr) ( addr & 0xFFFF) #define PAGE_OFFSET_MASK ( 0xFFFF) #define SHADOW_PAGE_SIZE (1 << PAGE_OFFSET_BITS) // 2 level page table #define PTR_SIZE (sizeof(struct Status *)) #define LEVEL_1_PAGE_TABLE_BITS (20) #define LEVEL_1_PAGE_TABLE_ENTRIES (1 << LEVEL_1_PAGE_TABLE_BITS ) #define LEVEL_1_PAGE_TABLE_SIZE (LEVEL_1_PAGE_TABLE_ENTRIES * PTR_SIZE ) #define LEVEL_2_PAGE_TABLE_BITS (12) #define LEVEL_2_PAGE_TABLE_ENTRIES (1 << LEVEL_2_PAGE_TABLE_BITS ) #define LEVEL_2_PAGE_TABLE_SIZE (LEVEL_2_PAGE_TABLE_ENTRIES * PTR_SIZE ) #define LEVEL_1_PAGE_TABLE_SLOT(addr) ((((uint64_t)addr) >> (LEVEL_2_PAGE_TABLE_BITS + PAGE_OFFSET_BITS)) & 0xfffff) #define LEVEL_2_PAGE_TABLE_SLOT(addr) ((((uint64_t)addr) >> (PAGE_OFFSET_BITS)) & 0xFFF) #define SHADOW_STRUCT_SIZE (sizeof (T)) using namespace std; #define PIN_ExitProcess(a) exit(a) /* template <typename... Ts> struct ShadowType { tuple<Ts[SHADOW_PAGE_SIZE]...> f; void * operator new(size_t sz) { void * p = mmap(0, sz, PROT_WRITE | PROT_READ, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if(p == MAP_FAILED) { perror("mmap l2pg"); PIN_ExitProcess(-1); } return p; } void operator delete(void *p) { munmap(p, sizeof(ShadowType<Ts...>)); } }; */ template<class ...Args> using ShadowTuple = std::tuple<Args[SHADOW_PAGE_SIZE]...>; #if 1 template <typename... Ts> class ConcurrentShadowMemory { // All fwd declarations atomic< atomic< ShadowTuple<Ts...> *> *> * pageDirectory; // Given a address generated by the program, returns the corresponding shadow address FLOORED to SHADOW_PAGE_SIZE // If the shadow page does not exist a new one is MMAPed public: inline ConcurrentShadowMemory() { pageDirectory = (atomic< atomic< ShadowTuple<Ts...> *> *> *) mmap(0, LEVEL_1_PAGE_TABLE_SIZE, PROT_WRITE | PROT_READ, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if(pageDirectory == MAP_FAILED) { perror("mmap pageDirectory"); PIN_ExitProcess(-1); } } inline ~ConcurrentShadowMemory(){ for(uint64_t i = 0; i < LEVEL_1_PAGE_TABLE_ENTRIES; i++) { atomic< ShadowTuple<Ts...> *> * l1Page; if( (l1Page=pageDirectory[i].load(memory_order_relaxed)) != 0) { for(uint64_t j = 0; j < LEVEL_2_PAGE_TABLE_ENTRIES; j++) { ShadowTuple<Ts...> * l2Page; if( (l2Page=l1Page[j].load(memory_order_relaxed)) != 0){ delete l2Page; } } if(0 != munmap(l1Page, LEVEL_2_PAGE_TABLE_SIZE)) { perror("munmap pageDirectory"); PIN_ExitProcess(-1); } } } if(0 != munmap(pageDirectory, LEVEL_1_PAGE_TABLE_SIZE)){ perror("munmap pageDirectory"); PIN_ExitProcess(-1); } } inline ShadowTuple<Ts...> & GetOrCreateShadowBaseAddress(const size_t address) { atomic< atomic< ShadowTuple<Ts...> *> *> * l1Ptr = & pageDirectory[LEVEL_1_PAGE_TABLE_SLOT(address)]; atomic< ShadowTuple<Ts...> *> * v1; if ( (v1=l1Ptr->load(memory_order_consume)) == 0) { atomic< ShadowTuple<Ts...> *> * l1pg = (atomic< ShadowTuple<Ts...> *> *) mmap(0, LEVEL_2_PAGE_TABLE_SIZE, PROT_WRITE | PROT_READ, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if(l1pg == MAP_FAILED) { perror("mmap l1pg"); PIN_ExitProcess(-1); } atomic<ShadowTuple<Ts...> *> * nullVal = 0; if(!l1Ptr->compare_exchange_strong(nullVal, l1pg, memory_order_acq_rel, memory_order_relaxed)) { free(l1pg); v1 = l1Ptr->load(memory_order_consume); } else { v1 = l1pg; } } atomic<ShadowTuple<Ts...> *> * l2Ptr = & v1[LEVEL_2_PAGE_TABLE_SLOT(address)]; ShadowTuple<Ts...> * v2; if( (v2=l2Ptr->load(memory_order_consume)) == 0 ){ ShadowTuple<Ts...> * l2pg = new ShadowTuple<Ts...>; if(l2pg == MAP_FAILED) { perror("mmap l2pg"); PIN_ExitProcess(-1); } ShadowTuple<Ts...> * nullVal = 0; if( !l2Ptr->compare_exchange_strong(nullVal, l2pg, memory_order_acq_rel, memory_order_relaxed)){ delete l2pg; v2 = l2Ptr->load(memory_order_consume); } else { v2 = l2pg; } } return (*v2); } }; template<int I, typename... Ts> typename std::tuple_element<I, tuple<Ts...> >::type * GetOrCreateShadowAddress(ConcurrentShadowMemory<Ts...> & sm, const size_t address) { auto shadowPage = sm.GetOrCreateShadowBaseAddress(address); return &(get<I>(shadowPage)[PAGE_OFFSET((uint64_t)address)]); } #endif template <typename... Ts> class ShadowMemory { // All fwd declarations ShadowTuple<Ts...> *** pageDirectory; // Given a address generated by the program, returns the corresponding shadow address FLOORED to SHADOW_PAGE_SIZE // If the shadow page does not exist a new one is MMAPed public: inline ShadowMemory() { pageDirectory = (ShadowTuple<Ts...> ***) mmap(0, LEVEL_1_PAGE_TABLE_SIZE, PROT_WRITE | PROT_READ, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if(pageDirectory == MAP_FAILED) { perror("mmap pageDirectory"); PIN_ExitProcess(-1); } } inline ~ShadowMemory(){ for(uint64_t i = 0; i < LEVEL_1_PAGE_TABLE_ENTRIES; i++) { ShadowTuple<Ts...> ** l1Page; if( (l1Page=pageDirectory[i]) != 0) { for(uint64_t j = 0; j < LEVEL_2_PAGE_TABLE_ENTRIES; j++) { ShadowTuple<Ts...> * l2Page; if( (l2Page=l1Page[j]) != 0){ delete l2Page; } } if(0 != munmap(l1Page, LEVEL_2_PAGE_TABLE_SIZE)) { perror("munmap pageDirectory"); PIN_ExitProcess(-1); } } } if(0 != munmap(pageDirectory, LEVEL_1_PAGE_TABLE_SIZE)){ perror("munmap pageDirectory"); PIN_ExitProcess(-1); } } inline ShadowTuple<Ts...> & GetOrCreateShadowBaseAddress(const size_t address) { ShadowTuple<Ts...> *** l1Ptr = & pageDirectory[LEVEL_1_PAGE_TABLE_SLOT(address)]; ShadowTuple<Ts...> ** v1; if ( (v1=*l1Ptr) == 0) { ShadowTuple<Ts...> ** l1pg = (ShadowTuple<Ts...> **) mmap(0, LEVEL_2_PAGE_TABLE_SIZE, PROT_WRITE | PROT_READ, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if(l1pg == MAP_FAILED) { perror("mmap l1pg"); PIN_ExitProcess(-1); } v1 = l1pg; } ShadowTuple<Ts...> ** l2Ptr = & v1[LEVEL_2_PAGE_TABLE_SLOT(address)]; ShadowTuple<Ts...> * v2; if( (v2=*l2Ptr) == 0 ){ ShadowTuple<Ts...> * l2pg = new ShadowTuple<Ts...>; if(l2pg == MAP_FAILED) { perror("mmap l2pg"); PIN_ExitProcess(-1); } v2 = l2pg; } return v2; } }; template<int I, typename... Ts> typename std::tuple_element<I, tuple<Ts...> >::type * GetOrCreateShadowAddress(ShadowMemory<Ts...> & sm, const size_t address) { auto shadowPage = sm.GetOrCreateShadowBaseAddress(address); return &(get<I>(shadowPage)[PAGE_OFFSET((uint64_t)address)]); } //#define ConcurrentShadowMemory ShadowMemory #if 1 ShadowMemory<int> s; ConcurrentShadowMemory <int> cs; int main(){ for(int i = 0; i < 0xffff; i++){ GetOrCreateShadowAddress<0>(s, 0x12345678)[0] = 1234; int j = GetOrCreateShadowAddress<0>(s, 0x12345678)[0]; GetOrCreateShadowAddress<0>(cs, 0x12345678)[0] = 1234; j = GetOrCreateShadowAddress<0>(cs, 0x12345678)[0]; } return 0; } #endif #endif // __SHADOW_MEMORY__ <commit_msg>Removed accidentally commited shadow memory test<commit_after>// @COPYRIGHT@ // Licensed under MIT license. // See LICENSE.TXT file in the project root for more information. // ============================================================== #ifndef __SHADOW_MEMORY__ #define __SHADOW_MEMORY__ #include<stdint.h> #include<atomic> #include<stdlib.h> #include<sys/mman.h> #include<tuple> // 64KB shadow pages #define PAGE_OFFSET_BITS (16LL) #define PAGE_OFFSET(addr) ( addr & 0xFFFF) #define PAGE_OFFSET_MASK ( 0xFFFF) #define SHADOW_PAGE_SIZE (1 << PAGE_OFFSET_BITS) // 2 level page table #define PTR_SIZE (sizeof(struct Status *)) #define LEVEL_1_PAGE_TABLE_BITS (20) #define LEVEL_1_PAGE_TABLE_ENTRIES (1 << LEVEL_1_PAGE_TABLE_BITS ) #define LEVEL_1_PAGE_TABLE_SIZE (LEVEL_1_PAGE_TABLE_ENTRIES * PTR_SIZE ) #define LEVEL_2_PAGE_TABLE_BITS (12) #define LEVEL_2_PAGE_TABLE_ENTRIES (1 << LEVEL_2_PAGE_TABLE_BITS ) #define LEVEL_2_PAGE_TABLE_SIZE (LEVEL_2_PAGE_TABLE_ENTRIES * PTR_SIZE ) #define LEVEL_1_PAGE_TABLE_SLOT(addr) ((((uint64_t)addr) >> (LEVEL_2_PAGE_TABLE_BITS + PAGE_OFFSET_BITS)) & 0xfffff) #define LEVEL_2_PAGE_TABLE_SLOT(addr) ((((uint64_t)addr) >> (PAGE_OFFSET_BITS)) & 0xFFF) #define SHADOW_STRUCT_SIZE (sizeof (T)) using namespace std; #define PIN_ExitProcess(a) exit(a) /* template <typename... Ts> struct ShadowType { tuple<Ts[SHADOW_PAGE_SIZE]...> f; void * operator new(size_t sz) { void * p = mmap(0, sz, PROT_WRITE | PROT_READ, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if(p == MAP_FAILED) { perror("mmap l2pg"); PIN_ExitProcess(-1); } return p; } void operator delete(void *p) { munmap(p, sizeof(ShadowType<Ts...>)); } }; */ template<class ...Args> using ShadowTuple = std::tuple<Args[SHADOW_PAGE_SIZE]...>; #if 1 template <typename... Ts> class ConcurrentShadowMemory { // All fwd declarations atomic< atomic< ShadowTuple<Ts...> *> *> * pageDirectory; // Given a address generated by the program, returns the corresponding shadow address FLOORED to SHADOW_PAGE_SIZE // If the shadow page does not exist a new one is MMAPed public: inline ConcurrentShadowMemory() { pageDirectory = (atomic< atomic< ShadowTuple<Ts...> *> *> *) mmap(0, LEVEL_1_PAGE_TABLE_SIZE, PROT_WRITE | PROT_READ, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if(pageDirectory == MAP_FAILED) { perror("mmap pageDirectory"); PIN_ExitProcess(-1); } } inline ~ConcurrentShadowMemory(){ for(uint64_t i = 0; i < LEVEL_1_PAGE_TABLE_ENTRIES; i++) { atomic< ShadowTuple<Ts...> *> * l1Page; if( (l1Page=pageDirectory[i].load(memory_order_relaxed)) != 0) { for(uint64_t j = 0; j < LEVEL_2_PAGE_TABLE_ENTRIES; j++) { ShadowTuple<Ts...> * l2Page; if( (l2Page=l1Page[j].load(memory_order_relaxed)) != 0){ delete l2Page; } } if(0 != munmap(l1Page, LEVEL_2_PAGE_TABLE_SIZE)) { perror("munmap pageDirectory"); PIN_ExitProcess(-1); } } } if(0 != munmap(pageDirectory, LEVEL_1_PAGE_TABLE_SIZE)){ perror("munmap pageDirectory"); PIN_ExitProcess(-1); } } inline ShadowTuple<Ts...> & GetOrCreateShadowBaseAddress(const size_t address) { atomic< atomic< ShadowTuple<Ts...> *> *> * l1Ptr = & pageDirectory[LEVEL_1_PAGE_TABLE_SLOT(address)]; atomic< ShadowTuple<Ts...> *> * v1; if ( (v1=l1Ptr->load(memory_order_consume)) == 0) { atomic< ShadowTuple<Ts...> *> * l1pg = (atomic< ShadowTuple<Ts...> *> *) mmap(0, LEVEL_2_PAGE_TABLE_SIZE, PROT_WRITE | PROT_READ, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if(l1pg == MAP_FAILED) { perror("mmap l1pg"); PIN_ExitProcess(-1); } atomic<ShadowTuple<Ts...> *> * nullVal = 0; if(!l1Ptr->compare_exchange_strong(nullVal, l1pg, memory_order_acq_rel, memory_order_relaxed)) { free(l1pg); v1 = l1Ptr->load(memory_order_consume); } else { v1 = l1pg; } } atomic<ShadowTuple<Ts...> *> * l2Ptr = & v1[LEVEL_2_PAGE_TABLE_SLOT(address)]; ShadowTuple<Ts...> * v2; if( (v2=l2Ptr->load(memory_order_consume)) == 0 ){ ShadowTuple<Ts...> * l2pg = new ShadowTuple<Ts...>; if(l2pg == MAP_FAILED) { perror("mmap l2pg"); PIN_ExitProcess(-1); } ShadowTuple<Ts...> * nullVal = 0; if( !l2Ptr->compare_exchange_strong(nullVal, l2pg, memory_order_acq_rel, memory_order_relaxed)){ delete l2pg; v2 = l2Ptr->load(memory_order_consume); } else { v2 = l2pg; } } return (*v2); } }; template<int I, typename... Ts> typename std::tuple_element<I, tuple<Ts...> >::type * GetOrCreateShadowAddress(ConcurrentShadowMemory<Ts...> & sm, const size_t address) { auto shadowPage = sm.GetOrCreateShadowBaseAddress(address); return &(get<I>(shadowPage)[PAGE_OFFSET((uint64_t)address)]); } #endif template <typename... Ts> class ShadowMemory { // All fwd declarations ShadowTuple<Ts...> *** pageDirectory; // Given a address generated by the program, returns the corresponding shadow address FLOORED to SHADOW_PAGE_SIZE // If the shadow page does not exist a new one is MMAPed public: inline ShadowMemory() { pageDirectory = (ShadowTuple<Ts...> ***) mmap(0, LEVEL_1_PAGE_TABLE_SIZE, PROT_WRITE | PROT_READ, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if(pageDirectory == MAP_FAILED) { perror("mmap pageDirectory"); PIN_ExitProcess(-1); } } inline ~ShadowMemory(){ for(uint64_t i = 0; i < LEVEL_1_PAGE_TABLE_ENTRIES; i++) { ShadowTuple<Ts...> ** l1Page; if( (l1Page=pageDirectory[i]) != 0) { for(uint64_t j = 0; j < LEVEL_2_PAGE_TABLE_ENTRIES; j++) { ShadowTuple<Ts...> * l2Page; if( (l2Page=l1Page[j]) != 0){ delete l2Page; } } if(0 != munmap(l1Page, LEVEL_2_PAGE_TABLE_SIZE)) { perror("munmap pageDirectory"); PIN_ExitProcess(-1); } } } if(0 != munmap(pageDirectory, LEVEL_1_PAGE_TABLE_SIZE)){ perror("munmap pageDirectory"); PIN_ExitProcess(-1); } } inline ShadowTuple<Ts...> & GetOrCreateShadowBaseAddress(const size_t address) { ShadowTuple<Ts...> *** l1Ptr = & pageDirectory[LEVEL_1_PAGE_TABLE_SLOT(address)]; ShadowTuple<Ts...> ** v1; if ( (v1=*l1Ptr) == 0) { ShadowTuple<Ts...> ** l1pg = (ShadowTuple<Ts...> **) mmap(0, LEVEL_2_PAGE_TABLE_SIZE, PROT_WRITE | PROT_READ, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); if(l1pg == MAP_FAILED) { perror("mmap l1pg"); PIN_ExitProcess(-1); } v1 = l1pg; } ShadowTuple<Ts...> ** l2Ptr = & v1[LEVEL_2_PAGE_TABLE_SLOT(address)]; ShadowTuple<Ts...> * v2; if( (v2=*l2Ptr) == 0 ){ ShadowTuple<Ts...> * l2pg = new ShadowTuple<Ts...>; if(l2pg == MAP_FAILED) { perror("mmap l2pg"); PIN_ExitProcess(-1); } v2 = l2pg; } return v2; } }; template<int I, typename... Ts> typename std::tuple_element<I, tuple<Ts...> >::type * GetOrCreateShadowAddress(ShadowMemory<Ts...> & sm, const size_t address) { auto shadowPage = sm.GetOrCreateShadowBaseAddress(address); return &(get<I>(shadowPage)[PAGE_OFFSET((uint64_t)address)]); } //#define ConcurrentShadowMemory ShadowMemory #if 0 ShadowMemory<int> s; ConcurrentShadowMemory <int> cs; int main(){ for(int i = 0; i < 0xffff; i++){ GetOrCreateShadowAddress<0>(s, 0x12345678)[0] = 1234; int j = GetOrCreateShadowAddress<0>(s, 0x12345678)[0]; GetOrCreateShadowAddress<0>(cs, 0x12345678)[0] = 1234; j = GetOrCreateShadowAddress<0>(cs, 0x12345678)[0]; } return 0; } #endif #endif // __SHADOW_MEMORY__ <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <assert.h> #include <sys/time.h> #include <cstdlib> #include <log4cxx/logger.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/ndc.h> using namespace log4cxx; using namespace log4cxx::xml; using namespace log4cxx::helpers; #include "hdf5.h" #include "swmr-testdata.h" using namespace std; class SWMRWriter { public: SWMRWriter(const char * fname); ~SWMRWriter(); void create_file(); void get_test_data(); void write_test_data(unsigned int niter, unsigned int nframes_cache); private: LoggerPtr log; hid_t fid; string filename; Image_t *pimg; }; SWMRWriter::SWMRWriter (const char* fname) { this->log = Logger::getLogger("SWMRWriter"); LOG4CXX_DEBUG(log, "SWMRWriter constructor. Filename: " << fname); this->filename = fname; this->fid = -1; this->pimg = NULL; } void SWMRWriter::create_file() { hid_t fapl; /* File access property list */ hid_t fcpl; /* Create file access property list */ fapl = H5Pcreate(H5P_FILE_ACCESS); assert( fapl >= 0); /* Set to use the latest library format */ assert (H5Pset_libver_bounds(fapl, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST) >= 0); /* Create file creation property list */ if((fcpl = H5Pcreate(H5P_FILE_CREATE)) < 0) assert( fcpl >= 0); /* Creating the file with SWMR write access*/ LOG4CXX_INFO(log, "Creating file: " << filename); this->fid = H5Fcreate(this->filename.c_str(), H5F_ACC_TRUNC | H5F_ACC_SWMR_WRITE, fcpl, fapl); assert( this->fid >= 0); /* Close file access property list */ assert (H5Pclose(fapl) >= 0); } void SWMRWriter::get_test_data () { LOG4CXX_DEBUG(log, "Getting test data from swmr_testdata"); this->pimg = (Image_t *)calloc(1, sizeof(Image_t)); this->pimg->pdata = (const unsigned int*)swmr_testdata[0]; this->pimg->dims[0] = 4; this->pimg->dims[1] = 3; } void SWMRWriter::write_test_data (unsigned int niter, unsigned int nframes_cache) { hid_t dataspace, dataset; hid_t filespace, memspace; hid_t prop; herr_t status; hsize_t chunk_dims[3]; hsize_t max_dims[3]; hsize_t img_dims[3]; hsize_t offset[3] = {0,0,0}; hsize_t size[3]; assert (this->pimg != NULL); chunk_dims[0] = this->pimg->dims[0]; chunk_dims[1] = this->pimg->dims[1]; chunk_dims[2] = nframes_cache; max_dims[0] = this->pimg->dims[0]; max_dims[1] = this->pimg->dims[1]; max_dims[2] = H5S_UNLIMITED; img_dims[0] = this->pimg->dims[0]; img_dims[1] = this->pimg->dims[1]; img_dims[2] = 1; size[0] = this->pimg->dims[0]; size[1] = this->pimg->dims[1]; size[2] = 1; /* Create the dataspace with the given dimensions - and max dimensions */ dataspace = H5Screate_simple(3, img_dims, max_dims); assert( dataspace >= 0); /* Enable chunking */ prop = H5Pcreate (H5P_DATASET_CREATE); status = H5Pset_chunk (prop, 3, chunk_dims); assert( status >= 0); /* Create dataset */ LOG4CXX_DEBUG(log, "Creating dataset"); dataset = H5Dcreate2 (this->fid, "data", H5T_NATIVE_INT, dataspace, H5P_DEFAULT, prop, H5P_DEFAULT); LOG4CXX_DEBUG(log, "Starting write loop. Iterations: " << niter); for (int i = 0; i < niter; i++) { /* Extend the dataset */ LOG4CXX_TRACE(log, "Extending. Size: " << size[2] << ", " << size[1] << ", " << size[0]); status = H5Dset_extent(dataset, size); assert( status >= 0); /* Select a hyperslab */ filespace = H5Dget_space(dataset); status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL, img_dims, NULL); assert( status >= 0); /* Write the data to the hyperslab */ LOG4CXX_TRACE(log, "Writing. Offset: " << offset[2] << ", " << offset[1] << ", " << offset[0]); status = H5Dwrite(dataset, H5T_NATIVE_INT, dataspace, filespace, H5P_DEFAULT, this->pimg->pdata); assert( status >= 0); LOG4CXX_TRACE(log, "Write complete"); /* Increment offsets and dimensions as appropriate */ offset[2]++; size[2]++; } LOG4CXX_DEBUG(log, "Closing intermediate open HDF objects"); H5Dclose(dataset); H5Pclose(prop); H5Sclose(dataspace); H5Sclose(filespace); } SWMRWriter::~SWMRWriter () { LOG4CXX_DEBUG(log, "SWMRWriter destructor"); if (this->fid >= 0){ assert (H5Fclose(this->fid) >= 0); this->fid = -1; if (this->pimg != NULL) { free(this->pimg); this->pimg = NULL; } } } int main() { DOMConfigurator::configure("Log4cxxConfig.xml"); LoggerPtr log(Logger::getLogger("main")); LOG4CXX_INFO(log, "Creating a SWMR Writer object"); SWMRWriter swr = SWMRWriter("swmr.h5"); LOG4CXX_INFO(log, "Creating file"); swr.create_file(); LOG4CXX_INFO(log, "Getting test data"); swr.get_test_data(); LOG4CXX_INFO(log, "Writing 4 iterations"); swr.write_test_data(4, 1); return 0; } <commit_msg>fixing wrong destructor if brackets<commit_after>#include <iostream> #include <string> #include <assert.h> #include <sys/time.h> #include <cstdlib> #include <log4cxx/logger.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/ndc.h> using namespace log4cxx; using namespace log4cxx::xml; using namespace log4cxx::helpers; #include "hdf5.h" #include "swmr-testdata.h" using namespace std; class SWMRWriter { public: SWMRWriter(const char * fname); ~SWMRWriter(); void create_file(); void get_test_data(); void write_test_data(unsigned int niter, unsigned int nframes_cache); private: LoggerPtr log; hid_t fid; string filename; Image_t *pimg; }; SWMRWriter::SWMRWriter (const char* fname) { this->log = Logger::getLogger("SWMRWriter"); LOG4CXX_DEBUG(log, "SWMRWriter constructor. Filename: " << fname); this->filename = fname; this->fid = -1; this->pimg = NULL; } void SWMRWriter::create_file() { hid_t fapl; /* File access property list */ hid_t fcpl; /* Create file access property list */ fapl = H5Pcreate(H5P_FILE_ACCESS); assert( fapl >= 0); /* Set to use the latest library format */ assert (H5Pset_libver_bounds(fapl, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST) >= 0); /* Create file creation property list */ if((fcpl = H5Pcreate(H5P_FILE_CREATE)) < 0) assert( fcpl >= 0); /* Creating the file with SWMR write access*/ LOG4CXX_INFO(log, "Creating file: " << filename); this->fid = H5Fcreate(this->filename.c_str(), H5F_ACC_TRUNC | H5F_ACC_SWMR_WRITE, fcpl, fapl); assert( this->fid >= 0); /* Close file access property list */ assert (H5Pclose(fapl) >= 0); } void SWMRWriter::get_test_data () { LOG4CXX_DEBUG(log, "Getting test data from swmr_testdata"); this->pimg = (Image_t *)calloc(1, sizeof(Image_t)); this->pimg->pdata = (const unsigned int*)swmr_testdata[0]; this->pimg->dims[0] = 4; this->pimg->dims[1] = 3; } void SWMRWriter::write_test_data (unsigned int niter, unsigned int nframes_cache) { hid_t dataspace, dataset; hid_t filespace, memspace; hid_t prop; herr_t status; hsize_t chunk_dims[3]; hsize_t max_dims[3]; hsize_t img_dims[3]; hsize_t offset[3] = {0,0,0}; hsize_t size[3]; assert (this->pimg != NULL); chunk_dims[0] = this->pimg->dims[0]; chunk_dims[1] = this->pimg->dims[1]; chunk_dims[2] = nframes_cache; max_dims[0] = this->pimg->dims[0]; max_dims[1] = this->pimg->dims[1]; max_dims[2] = H5S_UNLIMITED; img_dims[0] = this->pimg->dims[0]; img_dims[1] = this->pimg->dims[1]; img_dims[2] = 1; size[0] = this->pimg->dims[0]; size[1] = this->pimg->dims[1]; size[2] = 1; /* Create the dataspace with the given dimensions - and max dimensions */ dataspace = H5Screate_simple(3, img_dims, max_dims); assert( dataspace >= 0); /* Enable chunking */ prop = H5Pcreate (H5P_DATASET_CREATE); status = H5Pset_chunk (prop, 3, chunk_dims); assert( status >= 0); /* Create dataset */ LOG4CXX_DEBUG(log, "Creating dataset"); dataset = H5Dcreate2 (this->fid, "data", H5T_NATIVE_INT, dataspace, H5P_DEFAULT, prop, H5P_DEFAULT); LOG4CXX_DEBUG(log, "Starting write loop. Iterations: " << niter); for (int i = 0; i < niter; i++) { /* Extend the dataset */ LOG4CXX_TRACE(log, "Extending. Size: " << size[2] << ", " << size[1] << ", " << size[0]); status = H5Dset_extent(dataset, size); assert( status >= 0); /* Select a hyperslab */ filespace = H5Dget_space(dataset); status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL, img_dims, NULL); assert( status >= 0); /* Write the data to the hyperslab */ LOG4CXX_TRACE(log, "Writing. Offset: " << offset[2] << ", " << offset[1] << ", " << offset[0]); status = H5Dwrite(dataset, H5T_NATIVE_INT, dataspace, filespace, H5P_DEFAULT, this->pimg->pdata); assert( status >= 0); LOG4CXX_TRACE(log, "Write complete"); /* Increment offsets and dimensions as appropriate */ offset[2]++; size[2]++; } LOG4CXX_DEBUG(log, "Closing intermediate open HDF objects"); H5Dclose(dataset); H5Pclose(prop); H5Sclose(dataspace); H5Sclose(filespace); } SWMRWriter::~SWMRWriter () { LOG4CXX_DEBUG(log, "SWMRWriter destructor"); if (this->fid >= 0){ assert (H5Fclose(this->fid) >= 0); this->fid = -1; } if (this->pimg != NULL) { free(this->pimg); this->pimg = NULL; } } int main() { DOMConfigurator::configure("Log4cxxConfig.xml"); LoggerPtr log(Logger::getLogger("main")); LOG4CXX_INFO(log, "Creating a SWMR Writer object"); SWMRWriter swr = SWMRWriter("swmr.h5"); LOG4CXX_INFO(log, "Creating file"); swr.create_file(); LOG4CXX_INFO(log, "Getting test data"); swr.get_test_data(); LOG4CXX_INFO(log, "Writing 4 iterations"); swr.write_test_data(4, 1); return 0; } <|endoftext|>
<commit_before>#include "loginform.h" #include "ui_loginform.h" #include <QDebug> #include <QCompleter> #include <QAbstractListModel> #include <QModelIndex> #include <QFile> #include <QTextStream> #include <QStringList> #include <QPixmap> #include <QMessageBox> #include <QModelIndex> #include <QMenu> #include <QProcess> #include <razorqt/razorsettings.h> #ifdef USING_LIGHTDM_QT_1 #include <QLightDM/System> #endif LoginForm::LoginForm(QWidget *parent) : QWidget(parent), ui(new Ui::LoginForm) { if (! m_Greeter.connectSync()) { close(); } ui->setupUi(this); setStyleSheet(razorTheme->qss("razor-lightdm-greeter/razor-lightdm-greeter")); ui->hostnameLabel->setFocus(); // Setup users m_UsersModel = new QLightDM::UsersModel(); QStringList userIds; for (int i = 0; i < m_UsersModel->rowCount(QModelIndex()); i++) { QModelIndex index = m_UsersModel->index(i); QString userId = m_UsersModel->data(index, Qt::UserRole).toString(); userIds << userId; } QCompleter *completer = new QCompleter(userIds); completer->setCompletionMode(QCompleter::InlineCompletion); ui->userIdInput->setCompleter(completer); // Setup sessions m_SessionsModel = new QLightDM::SessionsModel(); ui->sessionCombo->setModel(m_SessionsModel); for (int row = 0; row < ui->sessionCombo->model()->rowCount(); row++) { QModelIndex index = ui->sessionCombo->model()->index(row, 0); if (QString("Razor Desktop") == ui->sessionCombo->model()->data(index, Qt::DisplayRole).toString()) { ui->sessionCombo->setCurrentIndex(row); break; } } QPixmap icon(QString(SHARE_DIR) + "/graphics/rqt-2.svg"); ui->iconLabel->setPixmap(icon.scaled(ui->iconLabel->size())); #ifdef USING_LIGHTDM_QT_1 ui->hostnameLabel->setText(QLightDM::hostname()); connect(&m_Greeter, SIGNAL(showPrompt(QString,QLightDM::PromptType)), this, SLOT(onPrompt(QString,QLightDM::PromptType))); #else ui->hostnameLabel->setText(m_Greeter.hostname()); connect(&m_Greeter, SIGNAL(showPrompt(QString,QLightDM::Greeter::PromptType)), this, SLOT(onPrompt(QString,QLightDM::Greeter::PromptType))); #endif connect(ui->loginButton, SIGNAL(pressed()), this, SLOT(doLogin())); connect(ui->loginButton, SIGNAL(clicked(bool)), this, SLOT(doLogin())); connect(ui->cancelButton, SIGNAL(clicked()), SLOT(doCancel())); connect(&m_Greeter, SIGNAL(authenticationComplete()), this, SLOT(authenticationDone())); connect(ui->leaveButton, SIGNAL(clicked()), SLOT(doLeave())); connect(&m_razorPowerProcess, SIGNAL(finished(int)), this, SLOT(razorPowerDone())); } LoginForm::~LoginForm() { delete ui; } void LoginForm::doLogin() { m_Greeter.authenticate(ui->userIdInput->text()); } #ifdef USING_LIGHTDM_QT_1 void LoginForm::onPrompt(QString prompt, QLightDM::PromptType promptType) { // We only handle password prompt m_Greeter.respond(ui->passwordInput->text()); } #else void LoginForm::onPrompt(QString prompt, QLightDM::Greeter::PromptType promptType) { // We only handle password prompt m_Greeter.respond(ui->passwordInput->text()); } #endif void LoginForm::authenticationDone() { if (m_Greeter.isAuthenticated()) { QString session = ui->sessionCombo->itemData(ui->sessionCombo->currentIndex(), QLightDM::SessionsModel::IdRole).toString(); m_Greeter.startSessionSync(session); } else { doCancel(); } } void LoginForm::doCancel() { ui->hostnameLabel->setFocus(); ui->userIdInput->setText(""); ui->passwordInput->setText(""); } void LoginForm::doLeave() { m_razorPowerProcess.start("razor-power"); setEnabled(false); } void LoginForm::razorPowerDone() { setEnabled(true); } void LoginForm::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { emit ui->loginButton->click(); } } <commit_msg>Fix build for razorqt-lightdm-greeter<commit_after>#include "loginform.h" #include "ui_loginform.h" #include <QDebug> #include <QCompleter> #include <QAbstractListModel> #include <QModelIndex> #include <QFile> #include <QTextStream> #include <QStringList> #include <QPixmap> #include <QMessageBox> #include <QModelIndex> #include <QMenu> #include <QProcess> #include <razorqt/razorsettings.h> #ifdef USING_LIGHTDM_QT_1 #include <QLightDM/System> #endif LoginForm::LoginForm(QWidget *parent) : QWidget(parent), ui(new Ui::LoginForm) { if (! m_Greeter.connectSync()) { close(); } ui->setupUi(this); setStyleSheet(razorTheme.qss("razor-lightdm-greeter/razor-lightdm-greeter")); ui->hostnameLabel->setFocus(); // Setup users m_UsersModel = new QLightDM::UsersModel(); QStringList userIds; for (int i = 0; i < m_UsersModel->rowCount(QModelIndex()); i++) { QModelIndex index = m_UsersModel->index(i); QString userId = m_UsersModel->data(index, Qt::UserRole).toString(); userIds << userId; } QCompleter *completer = new QCompleter(userIds); completer->setCompletionMode(QCompleter::InlineCompletion); ui->userIdInput->setCompleter(completer); // Setup sessions m_SessionsModel = new QLightDM::SessionsModel(); ui->sessionCombo->setModel(m_SessionsModel); for (int row = 0; row < ui->sessionCombo->model()->rowCount(); row++) { QModelIndex index = ui->sessionCombo->model()->index(row, 0); if (QString("Razor Desktop") == ui->sessionCombo->model()->data(index, Qt::DisplayRole).toString()) { ui->sessionCombo->setCurrentIndex(row); break; } } QPixmap icon(QString(SHARE_DIR) + "/graphics/rqt-2.svg"); ui->iconLabel->setPixmap(icon.scaled(ui->iconLabel->size())); #ifdef USING_LIGHTDM_QT_1 ui->hostnameLabel->setText(QLightDM::hostname()); connect(&m_Greeter, SIGNAL(showPrompt(QString,QLightDM::PromptType)), this, SLOT(onPrompt(QString,QLightDM::PromptType))); #else ui->hostnameLabel->setText(m_Greeter.hostname()); connect(&m_Greeter, SIGNAL(showPrompt(QString,QLightDM::Greeter::PromptType)), this, SLOT(onPrompt(QString,QLightDM::Greeter::PromptType))); #endif connect(ui->loginButton, SIGNAL(pressed()), this, SLOT(doLogin())); connect(ui->loginButton, SIGNAL(clicked(bool)), this, SLOT(doLogin())); connect(ui->cancelButton, SIGNAL(clicked()), SLOT(doCancel())); connect(&m_Greeter, SIGNAL(authenticationComplete()), this, SLOT(authenticationDone())); connect(ui->leaveButton, SIGNAL(clicked()), SLOT(doLeave())); connect(&m_razorPowerProcess, SIGNAL(finished(int)), this, SLOT(razorPowerDone())); } LoginForm::~LoginForm() { delete ui; } void LoginForm::doLogin() { m_Greeter.authenticate(ui->userIdInput->text()); } #ifdef USING_LIGHTDM_QT_1 void LoginForm::onPrompt(QString prompt, QLightDM::PromptType promptType) { // We only handle password prompt m_Greeter.respond(ui->passwordInput->text()); } #else void LoginForm::onPrompt(QString prompt, QLightDM::Greeter::PromptType promptType) { // We only handle password prompt m_Greeter.respond(ui->passwordInput->text()); } #endif void LoginForm::authenticationDone() { if (m_Greeter.isAuthenticated()) { QString session = ui->sessionCombo->itemData(ui->sessionCombo->currentIndex(), QLightDM::SessionsModel::IdRole).toString(); m_Greeter.startSessionSync(session); } else { doCancel(); } } void LoginForm::doCancel() { ui->hostnameLabel->setFocus(); ui->userIdInput->setText(""); ui->passwordInput->setText(""); } void LoginForm::doLeave() { m_razorPowerProcess.start("razor-power"); setEnabled(false); } void LoginForm::razorPowerDone() { setEnabled(true); } void LoginForm::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { emit ui->loginButton->click(); } } <|endoftext|>
<commit_before> /* * * Copyright (C) 2016 Luxon Jean-Pierre * gumichan01.olympe.in * * * Luxon Jean-Pierre (Gumichan01) * luxon.jean.pierre@gmail.com * */ #include "utf8_string.hpp" utf8_string::utf8_string() : utf8_str_length(0){} utf8_string::utf8_string(const std::string &str) : utf8_string() { for(auto c : str) { utf8_data.push_back(c); } } <commit_msg>Implemented utf8_size()<commit_after> /* * * Copyright (C) 2016 Luxon Jean-Pierre * gumichan01.olympe.in * * * Luxon Jean-Pierre (Gumichan01) * luxon.jean.pierre@gmail.com * */ #include "utf8_string.hpp" utf8_string::utf8_string() : utf8_str_length(0){} utf8_string::utf8_string(const std::string &str) : utf8_string() { for(auto c : str) { utf8_data.push_back(c); } } utf8_len_t utf8_string::utf8_size() { return utf8_data.size(); } <|endoftext|>
<commit_before>// Copyright (C) 2017 Rob Caelers <rob.caelers@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <iostream> #include <string> #include "os/Wifi.hpp" #include "os/BeaconScanner.hpp" #include "os/Slot.hpp" #include "os/Task.hpp" #include "os/MainLoop.hpp" #include "os/Mqtt.hpp" #include "esp_log.h" #include "driver/gpio.h" #include "nvs_flash.h" #include "user_config.h" static const char tag[] = "BEACON-SCANNER"; extern const uint8_t ca_start[] asm("_binary_CA_crt_start"); extern const uint8_t ca_end[] asm("_binary_CA_crt_end"); extern const uint8_t certificate_start[] asm("_binary_esp32_crt_start"); extern const uint8_t certificate_end[] asm("_binary_esp32_crt_end"); extern const uint8_t private_key_start[] asm("_binary_esp32_key_start"); extern const uint8_t private_key_end[] asm("_binary_esp32_key_end"); class Main { public: Main(): #ifdef CONFIG_BT_ENABLED beacon_scanner(os::BeaconScanner::instance()), #endif wifi(os::Wifi::instance()), task("main_task", std::bind(&Main::main_task, this)) { gpio_pad_select_gpio(LED_GPIO); gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT); } private: void on_wifi_system_event(system_event_t event) { ESP_LOGI(tag, "-> System event %d", event.event_id); } void on_wifi_connected(bool connected) { if (connected) { ESP_LOGI(tag, "-> Wifi connected"); } else { ESP_LOGI(tag, "-> Wifi disconnected"); } } void on_mqtt_connected(bool connected) { if (connected) { ESP_LOGI(tag, "-> MQTT connected"); #ifdef CONFIG_BT_ENABLED beacon_scanner.start(); #endif } else { ESP_LOGI(tag, "-> MQTT disconnected"); #ifdef CONFIG_BT_ENABLED beacon_scanner.stop(); #endif } } #ifdef CONFIG_BT_ENABLED void on_beacon_scanner_scan_result(os::BeaconScanner::ScanResult result) { static int led_state = 0; ESP_LOGI(tag, "-> BT result %s %d", result.mac.c_str(), result.rssi); led_state ^= 1; gpio_set_level(LED_GPIO, led_state); #ifdef CONFIG_AWS_IOT_SDK mqtt.publish("beacon", result.mac); #endif } #endif void main_task() { wifi.set_ssid(WIFI_SSID); wifi.set_passphase(WIFI_PASS); wifi.set_host_name("scan"); wifi.set_auto_connect(true); wifi.system_event_signal().connect(os::Slot<void(system_event_t)>(loop, std::bind(&Main::on_wifi_system_event, this, std::placeholders::_1))); wifi.connected().connect(os::Slot<void(bool)>(loop, std::bind(&Main::on_wifi_connected, this, std::placeholders::_1))); #ifdef CONFIG_BT_ENABLED beacon_scanner.scan_result_signal().connect(os::Slot<void(os::BeaconScanner::ScanResult)>(loop, std::bind(&Main::on_beacon_scanner_scan_result, this, std::placeholders::_1))); #endif wifi.connect(); #ifdef CONFIG_AWS_IOT_SDK mqtt.connected().connect(os::Slot<void(bool)>(loop, std::bind(&Main::on_mqtt_connected, this, std::placeholders::_1))); mqtt.init(MQTT_HOST, reinterpret_cast<const char *>(ca_start), reinterpret_cast<const char *>(certificate_start), reinterpret_cast<const char *>(private_key_start)); #endif loop.run(); } #ifdef CONFIG_BT_ENABLED os::BeaconScanner &beacon_scanner; #endif os::Wifi &wifi; os::MainLoop loop; os::Task task; #ifdef CONFIG_AWS_IOT_SDK os::Mqtt mqtt; #endif const static gpio_num_t LED_GPIO = GPIO_NUM_5; }; extern "C" void app_main() { nvs_flash_init(); new Main(); while(1) { vTaskDelay(1000 / portTICK_PERIOD_MS); } } <commit_msg>Print free heap space at startup<commit_after>// Copyright (C) 2017 Rob Caelers <rob.caelers@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <iostream> #include <string> #include "os/Wifi.hpp" #include "os/BeaconScanner.hpp" #include "os/Slot.hpp" #include "os/Task.hpp" #include "os/MainLoop.hpp" #include "os/Mqtt.hpp" extern "C" { #include "esp_heap_caps.h" } #include "esp_log.h" #include "driver/gpio.h" #include "nvs_flash.h" #include "user_config.h" static const char tag[] = "BEACON-SCANNER"; extern const uint8_t ca_start[] asm("_binary_CA_crt_start"); extern const uint8_t ca_end[] asm("_binary_CA_crt_end"); extern const uint8_t certificate_start[] asm("_binary_esp32_crt_start"); extern const uint8_t certificate_end[] asm("_binary_esp32_crt_end"); extern const uint8_t private_key_start[] asm("_binary_esp32_key_start"); extern const uint8_t private_key_end[] asm("_binary_esp32_key_end"); class Main { public: Main(): #ifdef CONFIG_BT_ENABLED beacon_scanner(os::BeaconScanner::instance()), #endif wifi(os::Wifi::instance()), task("main_task", std::bind(&Main::main_task, this)) { gpio_pad_select_gpio(LED_GPIO); gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT); } private: void on_wifi_system_event(system_event_t event) { ESP_LOGI(tag, "-> System event %d", event.event_id); } void on_wifi_connected(bool connected) { if (connected) { ESP_LOGI(tag, "-> Wifi connected"); } else { ESP_LOGI(tag, "-> Wifi disconnected"); } } void on_mqtt_connected(bool connected) { if (connected) { ESP_LOGI(tag, "-> MQTT connected"); #ifdef CONFIG_BT_ENABLED beacon_scanner.start(); #endif } else { ESP_LOGI(tag, "-> MQTT disconnected"); #ifdef CONFIG_BT_ENABLED beacon_scanner.stop(); #endif } } #ifdef CONFIG_BT_ENABLED void on_beacon_scanner_scan_result(os::BeaconScanner::ScanResult result) { static int led_state = 0; ESP_LOGI(tag, "-> BT result %s %d", result.mac.c_str(), result.rssi); led_state ^= 1; gpio_set_level(LED_GPIO, led_state); #ifdef CONFIG_AWS_IOT_SDK mqtt.publish("beacon", result.mac); #endif } #endif void main_task() { wifi.set_ssid(WIFI_SSID); wifi.set_passphase(WIFI_PASS); wifi.set_host_name("scan"); wifi.set_auto_connect(true); wifi.system_event_signal().connect(os::Slot<void(system_event_t)>(loop, std::bind(&Main::on_wifi_system_event, this, std::placeholders::_1))); wifi.connected().connect(os::Slot<void(bool)>(loop, std::bind(&Main::on_wifi_connected, this, std::placeholders::_1))); #ifdef CONFIG_BT_ENABLED beacon_scanner.scan_result_signal().connect(os::Slot<void(os::BeaconScanner::ScanResult)>(loop, std::bind(&Main::on_beacon_scanner_scan_result, this, std::placeholders::_1))); #endif wifi.connect(); #ifdef CONFIG_AWS_IOT_SDK mqtt.connected().connect(os::Slot<void(bool)>(loop, std::bind(&Main::on_mqtt_connected, this, std::placeholders::_1))); mqtt.init(MQTT_HOST, reinterpret_cast<const char *>(ca_start), reinterpret_cast<const char *>(certificate_start), reinterpret_cast<const char *>(private_key_start)); #endif heap_caps_print_heap_info(0); loop.run(); } #ifdef CONFIG_BT_ENABLED os::BeaconScanner &beacon_scanner; #endif os::Wifi &wifi; os::MainLoop loop; os::Task task; #ifdef CONFIG_AWS_IOT_SDK os::Mqtt mqtt; #endif const static gpio_num_t LED_GPIO = GPIO_NUM_5; }; extern "C" void app_main() { nvs_flash_init(); heap_caps_print_heap_info(0); new Main(); while(1) { vTaskDelay(1000 / portTICK_PERIOD_MS); } } <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef WITHOUT_HSA_BACKEND #include "top.hpp" #include "os/os.hpp" #include "device/device.hpp" #include "rocsettings.hpp" #include "device/rocm/rocglinterop.hpp" namespace roc { // ================================================================================================ Settings::Settings() { // Initialize the HSA device default settings // Set this to true when we drop the flag doublePrecision_ = ::CL_KHR_FP64; enableLocalMemory_ = HSA_LOCAL_MEMORY_ENABLE; enableCoarseGrainSVM_ = HSA_ENABLE_COARSE_GRAIN_SVM; maxWorkGroupSize_ = 1024; preferredWorkGroupSize_ = 256; maxWorkGroupSize2DX_ = 16; maxWorkGroupSize2DY_ = 16; maxWorkGroupSize3DX_ = 4; maxWorkGroupSize3DY_ = 4; maxWorkGroupSize3DZ_ = 4; kernargPoolSize_ = HSA_KERNARG_POOL_SIZE; // Determine if user is requesting Non-Coherent mode // for system memory. By default system memory is // operates or is programmed to be in Coherent mode. // Users can turn it off for hardware that does not // support this feature naturally char* nonCoherentMode = getenv("OPENCL_USE_NC_MEMORY_POLICY"); enableNCMode_ = (nonCoherentMode) ? true : false; // Disable image DMA by default (ROCM runtime doesn't support it) imageDMA_ = false; stagedXferRead_ = true; stagedXferWrite_ = true; stagedXferSize_ = GPU_STAGING_BUFFER_SIZE * Ki; // Initialize transfer buffer size to 1MB by default xferBufSize_ = 1024 * Ki; const static size_t MaxPinnedXferSize = 128; pinnedXferSize_ = std::min(GPU_PINNED_XFER_SIZE, MaxPinnedXferSize) * Mi; pinnedMinXferSize_ = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_); sdmaCopyThreshold_ = GPU_FORCE_BLIT_COPY_SIZE * Ki; // Don't support Denormals for single precision by default singleFpDenorm_ = false; apuSystem_ = false; // Device enqueuing settings numDeviceEvents_ = 1024; numWaitEvents_ = 8; useLightning_ = (!flagIsDefault(GPU_ENABLE_LC)) ? GPU_ENABLE_LC : true; lcWavefrontSize64_ = true; imageBufferWar_ = false; hmmFlags_ = (!flagIsDefault(ROC_HMM_FLAGS)) ? ROC_HMM_FLAGS : 0; rocr_backend_ = true; cpu_wait_for_signal_ = !AMD_DIRECT_DISPATCH; cpu_wait_for_signal_ = (!flagIsDefault(ROC_CPU_WAIT_FOR_SIGNAL)) ? ROC_CPU_WAIT_FOR_SIGNAL : cpu_wait_for_signal_; system_scope_signal_ = ROC_SYSTEM_SCOPE_SIGNAL; skip_copy_sync_ = ROC_SKIP_COPY_SYNC; } // ================================================================================================ bool Settings::create(bool fullProfile, uint32_t gfxipMajor, uint32_t gfxipMinor, uint32_t gfxStepping, bool enableXNACK, bool coop_groups) { customHostAllocator_ = false; if (fullProfile) { pinnedXferSize_ = 0; stagedXferSize_ = 0; xferBufSize_ = 0; apuSystem_ = true; } else { pinnedXferSize_ = std::max(pinnedXferSize_, pinnedMinXferSize_); stagedXferSize_ = std::max(stagedXferSize_, pinnedMinXferSize_ + 4 * Ki); } enableXNACK_ = enableXNACK; hsailExplicitXnack_ = enableXNACK; // Enable extensions enableExtension(ClKhrByteAddressableStore); enableExtension(ClKhrGlobalInt32BaseAtomics); enableExtension(ClKhrGlobalInt32ExtendedAtomics); enableExtension(ClKhrLocalInt32BaseAtomics); enableExtension(ClKhrLocalInt32ExtendedAtomics); enableExtension(ClKhrInt64BaseAtomics); enableExtension(ClKhrInt64ExtendedAtomics); enableExtension(ClKhr3DImageWrites); enableExtension(ClAmdMediaOps); enableExtension(ClAmdMediaOps2); enableExtension(ClKhrImage2dFromBuffer); if (MesaInterop::Supported()) { enableExtension(ClKhrGlSharing); } // Enable platform extension enableExtension(ClAmdDeviceAttributeQuery); // Enable KHR double precision extension enableExtension(ClKhrFp64); enableExtension(ClKhrSubGroups); enableExtension(ClKhrDepthImages); enableExtension(ClAmdCopyBufferP2P); enableExtension(ClKhrFp16); supportDepthsRGB_ = true; if (useLightning_) { enableExtension(ClAmdAssemblyProgram); // enable subnormals for gfx900 and later if (gfxipMajor >= 9) { singleFpDenorm_ = true; enableCoopGroups_ = GPU_ENABLE_COOP_GROUPS & coop_groups; enableCoopMultiDeviceGroups_ = GPU_ENABLE_COOP_GROUPS & coop_groups; } } else { // Also enable AMD double precision extension? enableExtension(ClAmdFp64); } if (gfxipMajor >= 10) { enableWave32Mode_ = true; enableWgpMode_ = GPU_ENABLE_WGP_MODE; if (gfxipMinor == 1) { // GFX10.1 HW doesn't support custom pitch. Enable double copy workaround // TODO: This should be updated when ROCr support custom pitch imageBufferWar_ = GPU_IMAGE_BUFFER_WAR; } } if (!flagIsDefault(GPU_ENABLE_WAVE32_MODE)) { enableWave32Mode_ = GPU_ENABLE_WAVE32_MODE; } lcWavefrontSize64_ = !enableWave32Mode_; // Enable fgs kernel arg segment only for a specific HW fgs_kernel_arg_ = gfxipMajor == 9 && gfxStepping == 10; fgs_kernel_arg_ = (!flagIsDefault(ROC_USE_FGS_KERNARG)) ? ROC_USE_FGS_KERNARG : fgs_kernel_arg_; // Override current device settings override(); return true; } // ================================================================================================ void Settings::override() { // Limit reported workgroup size if (GPU_MAX_WORKGROUP_SIZE != 0) { preferredWorkGroupSize_ = GPU_MAX_WORKGROUP_SIZE; } if (GPU_MAX_WORKGROUP_SIZE_2D_X != 0) { maxWorkGroupSize2DX_ = GPU_MAX_WORKGROUP_SIZE_2D_X; } if (GPU_MAX_WORKGROUP_SIZE_2D_Y != 0) { maxWorkGroupSize2DY_ = GPU_MAX_WORKGROUP_SIZE_2D_Y; } if (GPU_MAX_WORKGROUP_SIZE_3D_X != 0) { maxWorkGroupSize3DX_ = GPU_MAX_WORKGROUP_SIZE_3D_X; } if (GPU_MAX_WORKGROUP_SIZE_3D_Y != 0) { maxWorkGroupSize3DY_ = GPU_MAX_WORKGROUP_SIZE_3D_Y; } if (GPU_MAX_WORKGROUP_SIZE_3D_Z != 0) { maxWorkGroupSize3DZ_ = GPU_MAX_WORKGROUP_SIZE_3D_Z; } if (!flagIsDefault(GPU_XFER_BUFFER_SIZE)) { xferBufSize_ = GPU_XFER_BUFFER_SIZE * Ki; } if (!flagIsDefault(GPU_PINNED_MIN_XFER_SIZE)) { pinnedMinXferSize_ = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_); } if (!flagIsDefault(AMD_GPU_FORCE_SINGLE_FP_DENORM)) { switch (AMD_GPU_FORCE_SINGLE_FP_DENORM) { case 0: singleFpDenorm_ = false; break; case 1: singleFpDenorm_ = true; break; default: break; } } if (!flagIsDefault(GPU_ENABLE_COOP_GROUPS)) { enableCoopGroups_ = GPU_ENABLE_COOP_GROUPS; enableCoopMultiDeviceGroups_ = GPU_ENABLE_COOP_GROUPS; } } } // namespace roc #endif // WITHOUT_HSA_BACKEND <commit_msg>SWDEV-344280 - Use coarse grain sysmem for kernel arg on MI200<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef WITHOUT_HSA_BACKEND #include "top.hpp" #include "os/os.hpp" #include "device/device.hpp" #include "rocsettings.hpp" #include "device/rocm/rocglinterop.hpp" namespace roc { // ================================================================================================ Settings::Settings() { // Initialize the HSA device default settings // Set this to true when we drop the flag doublePrecision_ = ::CL_KHR_FP64; enableLocalMemory_ = HSA_LOCAL_MEMORY_ENABLE; enableCoarseGrainSVM_ = HSA_ENABLE_COARSE_GRAIN_SVM; maxWorkGroupSize_ = 1024; preferredWorkGroupSize_ = 256; maxWorkGroupSize2DX_ = 16; maxWorkGroupSize2DY_ = 16; maxWorkGroupSize3DX_ = 4; maxWorkGroupSize3DY_ = 4; maxWorkGroupSize3DZ_ = 4; kernargPoolSize_ = HSA_KERNARG_POOL_SIZE; // Determine if user is requesting Non-Coherent mode // for system memory. By default system memory is // operates or is programmed to be in Coherent mode. // Users can turn it off for hardware that does not // support this feature naturally char* nonCoherentMode = getenv("OPENCL_USE_NC_MEMORY_POLICY"); enableNCMode_ = (nonCoherentMode) ? true : false; // Disable image DMA by default (ROCM runtime doesn't support it) imageDMA_ = false; stagedXferRead_ = true; stagedXferWrite_ = true; stagedXferSize_ = GPU_STAGING_BUFFER_SIZE * Ki; // Initialize transfer buffer size to 1MB by default xferBufSize_ = 1024 * Ki; const static size_t MaxPinnedXferSize = 128; pinnedXferSize_ = std::min(GPU_PINNED_XFER_SIZE, MaxPinnedXferSize) * Mi; pinnedMinXferSize_ = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_); sdmaCopyThreshold_ = GPU_FORCE_BLIT_COPY_SIZE * Ki; // Don't support Denormals for single precision by default singleFpDenorm_ = false; apuSystem_ = false; // Device enqueuing settings numDeviceEvents_ = 1024; numWaitEvents_ = 8; useLightning_ = (!flagIsDefault(GPU_ENABLE_LC)) ? GPU_ENABLE_LC : true; lcWavefrontSize64_ = true; imageBufferWar_ = false; hmmFlags_ = (!flagIsDefault(ROC_HMM_FLAGS)) ? ROC_HMM_FLAGS : 0; rocr_backend_ = true; cpu_wait_for_signal_ = !AMD_DIRECT_DISPATCH; cpu_wait_for_signal_ = (!flagIsDefault(ROC_CPU_WAIT_FOR_SIGNAL)) ? ROC_CPU_WAIT_FOR_SIGNAL : cpu_wait_for_signal_; system_scope_signal_ = ROC_SYSTEM_SCOPE_SIGNAL; skip_copy_sync_ = ROC_SKIP_COPY_SYNC; // Use coarse grain system memory for kernel arguments by default (to keep GPU cache) fgs_kernel_arg_ = false; } // ================================================================================================ bool Settings::create(bool fullProfile, uint32_t gfxipMajor, uint32_t gfxipMinor, uint32_t gfxStepping, bool enableXNACK, bool coop_groups) { customHostAllocator_ = false; if (fullProfile) { pinnedXferSize_ = 0; stagedXferSize_ = 0; xferBufSize_ = 0; apuSystem_ = true; } else { pinnedXferSize_ = std::max(pinnedXferSize_, pinnedMinXferSize_); stagedXferSize_ = std::max(stagedXferSize_, pinnedMinXferSize_ + 4 * Ki); } enableXNACK_ = enableXNACK; hsailExplicitXnack_ = enableXNACK; // Enable extensions enableExtension(ClKhrByteAddressableStore); enableExtension(ClKhrGlobalInt32BaseAtomics); enableExtension(ClKhrGlobalInt32ExtendedAtomics); enableExtension(ClKhrLocalInt32BaseAtomics); enableExtension(ClKhrLocalInt32ExtendedAtomics); enableExtension(ClKhrInt64BaseAtomics); enableExtension(ClKhrInt64ExtendedAtomics); enableExtension(ClKhr3DImageWrites); enableExtension(ClAmdMediaOps); enableExtension(ClAmdMediaOps2); enableExtension(ClKhrImage2dFromBuffer); if (MesaInterop::Supported()) { enableExtension(ClKhrGlSharing); } // Enable platform extension enableExtension(ClAmdDeviceAttributeQuery); // Enable KHR double precision extension enableExtension(ClKhrFp64); enableExtension(ClKhrSubGroups); enableExtension(ClKhrDepthImages); enableExtension(ClAmdCopyBufferP2P); enableExtension(ClKhrFp16); supportDepthsRGB_ = true; if (useLightning_) { enableExtension(ClAmdAssemblyProgram); // enable subnormals for gfx900 and later if (gfxipMajor >= 9) { singleFpDenorm_ = true; enableCoopGroups_ = GPU_ENABLE_COOP_GROUPS & coop_groups; enableCoopMultiDeviceGroups_ = GPU_ENABLE_COOP_GROUPS & coop_groups; } } else { // Also enable AMD double precision extension? enableExtension(ClAmdFp64); } if (gfxipMajor >= 10) { enableWave32Mode_ = true; enableWgpMode_ = GPU_ENABLE_WGP_MODE; if (gfxipMinor == 1) { // GFX10.1 HW doesn't support custom pitch. Enable double copy workaround // TODO: This should be updated when ROCr support custom pitch imageBufferWar_ = GPU_IMAGE_BUFFER_WAR; } } if (!flagIsDefault(GPU_ENABLE_WAVE32_MODE)) { enableWave32Mode_ = GPU_ENABLE_WAVE32_MODE; } lcWavefrontSize64_ = !enableWave32Mode_; // Override current device settings override(); return true; } // ================================================================================================ void Settings::override() { // Limit reported workgroup size if (GPU_MAX_WORKGROUP_SIZE != 0) { preferredWorkGroupSize_ = GPU_MAX_WORKGROUP_SIZE; } if (GPU_MAX_WORKGROUP_SIZE_2D_X != 0) { maxWorkGroupSize2DX_ = GPU_MAX_WORKGROUP_SIZE_2D_X; } if (GPU_MAX_WORKGROUP_SIZE_2D_Y != 0) { maxWorkGroupSize2DY_ = GPU_MAX_WORKGROUP_SIZE_2D_Y; } if (GPU_MAX_WORKGROUP_SIZE_3D_X != 0) { maxWorkGroupSize3DX_ = GPU_MAX_WORKGROUP_SIZE_3D_X; } if (GPU_MAX_WORKGROUP_SIZE_3D_Y != 0) { maxWorkGroupSize3DY_ = GPU_MAX_WORKGROUP_SIZE_3D_Y; } if (GPU_MAX_WORKGROUP_SIZE_3D_Z != 0) { maxWorkGroupSize3DZ_ = GPU_MAX_WORKGROUP_SIZE_3D_Z; } if (!flagIsDefault(GPU_XFER_BUFFER_SIZE)) { xferBufSize_ = GPU_XFER_BUFFER_SIZE * Ki; } if (!flagIsDefault(GPU_PINNED_MIN_XFER_SIZE)) { pinnedMinXferSize_ = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_); } if (!flagIsDefault(AMD_GPU_FORCE_SINGLE_FP_DENORM)) { switch (AMD_GPU_FORCE_SINGLE_FP_DENORM) { case 0: singleFpDenorm_ = false; break; case 1: singleFpDenorm_ = true; break; default: break; } } if (!flagIsDefault(GPU_ENABLE_COOP_GROUPS)) { enableCoopGroups_ = GPU_ENABLE_COOP_GROUPS; enableCoopMultiDeviceGroups_ = GPU_ENABLE_COOP_GROUPS; } if (!flagIsDefault(ROC_USE_FGS_KERNARG)) { fgs_kernel_arg_ = ROC_USE_FGS_KERNARG; } } } // namespace roc #endif // WITHOUT_HSA_BACKEND <|endoftext|>
<commit_before>#include "C3DFileAdapter.h" #ifdef WITH_EZC3D // TODO manage the header into one include #include "../ezc3d/Header.h" #include "../ezc3d/Parameters.h" #include "../ezc3d/Data.h" #else #include "btkAcquisitionFileReader.h" #include "btkAcquisition.h" #include "btkForcePlatformsExtractor.h" #include "btkGroundReactionWrenchFilter.h" #endif namespace { #ifdef WITH_BTK // Function to convert Eigen matrix to SimTK matrix. This can become a lambda // funciton inside extendRead in future. template<typename _Scalar, int _Rows, int _Cols> SimTK::Matrix_<double> convertToSimtkMatrix(const Eigen::Matrix<_Scalar, _Rows, _Cols>& eigenMat) { SimTK::Matrix_<double> simtkMat{static_cast<int>(eigenMat.rows()), static_cast<int>(eigenMat.cols())}; for(int r = 0; r < eigenMat.rows(); ++r) for(int c = 0; c < eigenMat.cols(); ++c) simtkMat(r, c) = eigenMat(r, c); return simtkMat; } #endif } // anonymous namespace namespace OpenSim { const std::string C3DFileAdapter::_markers{"markers"}; const std::string C3DFileAdapter::_forces{"forces"}; const std::unordered_map<std::string, size_t> C3DFileAdapter::_unit_index{{"marker", 0}, {"angle" , 1}, {"force" , 2}, {"moment", 3}, {"power" , 4}, {"scalar", 5}}; C3DFileAdapter* C3DFileAdapter::clone() const { return new C3DFileAdapter{*this}; } void C3DFileAdapter::write(const C3DFileAdapter::Tables& tables, const std::string& fileName) { throw Exception{"Writing C3D not supported yet."}; } C3DFileAdapter::OutputTables C3DFileAdapter::extendRead(const std::string& fileName) const { #ifdef WITH_EZC3D auto c3d = ezc3d::c3d(fileName); #else auto reader = btk::AcquisitionFileReader::New(); reader->SetFilename(fileName); reader->Update(); auto acquisition = reader->GetOutput(); #endif EventTable event_table{}; #ifdef WITH_EZC3D for (size_t i=0; i<c3d.header().eventsTime().size(); ++i) { std::string eventDescriptionStr(""); if (c3d.parameters().isGroup("EVENT") && c3d.parameters().group("EVENT").isParameter("DESCRIPTION")){ const auto& eventDescription(c3d.parameters().group("EVENT").parameter("DESCRIPTION").valuesAsString()); if (eventDescription.size() >= i){ eventDescriptionStr = eventDescription[i]; } } event_table.push_back( { c3d.header().eventsLabel(i), static_cast<double>(c3d.header().eventsTime(i)), static_cast<int>(c3d.header().eventsTime(i) / c3d.header().frameRate()), eventDescriptionStr }); } #else auto events = acquisition->GetEvents(); for (auto it = events->Begin(); it != events->End(); ++it) { auto et = *it; event_table.push_back({ et->GetLabel(), et->GetTime(), et->GetFrame(), et->GetDescription() }); } #endif OutputTables tables{}; #ifndef WITH_EZC3D auto marker_pts = btk::PointCollection::New(); for(auto it = acquisition->BeginPoint(); it != acquisition->EndPoint(); ++it) { auto pt = *it; if(pt->GetType() == btk::Point::Marker) marker_pts->InsertItem(pt); } if(marker_pts->GetItemNumber() != 0) { int marker_nrow = marker_pts->GetFrontItem()->GetFrameNumber(); int marker_ncol = marker_pts->GetItemNumber(); std::vector<double> marker_times(marker_nrow); SimTK::Matrix_<SimTK::Vec3> marker_matrix(marker_nrow, marker_ncol); std::vector<std::string> marker_labels{}; for (auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) { marker_labels.push_back(SimTK::Value<std::string>((*it)->GetLabel())); } double time_step{1.0 / acquisition->GetPointFrequency()}; for(int f = 0; f < marker_nrow; ++f) { SimTK::RowVector_<SimTK::Vec3> row{ marker_pts->GetItemNumber(), SimTK::Vec3(SimTK::NaN) }; int m{0}; for(auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) { auto pt = *it; // BTK reads empty values as zero, but sets a "residual" value // to -1 and it is how it knows to export these values as // blank, instead of 0, when exporting to .trc // See: BTKCore/Code/IO/btkTRCFileIO.cpp#L359-L360 // Read in value if it is not zero or residual is not -1 if (!pt->GetValues().row(f).isZero() || //not precisely zero (pt->GetResiduals().coeff(f) != -1) ) {//residual is not -1 row[m] = SimTK::Vec3{ pt->GetValues().coeff(f, 0), pt->GetValues().coeff(f, 1), pt->GetValues().coeff(f, 2) }; } ++m; } marker_matrix.updRow(f) = row; marker_times[f] = 0 + f * time_step; //TODO: 0 should be start_time } // Create the data auto marker_table = std::make_shared<TimeSeriesTableVec3>(marker_times, marker_matrix, marker_labels); marker_table-> updTableMetaData(). setValueForKey("DataRate", std::to_string(acquisition->GetPointFrequency())); marker_table-> updTableMetaData(). setValueForKey("Units", acquisition->GetPointUnit()); marker_table->updTableMetaData().setValueForKey("events", event_table); tables.emplace(_markers, marker_table); } else { // insert empty table std::vector<double> emptyTimes; std::vector<std::string> emptyLabels; SimTK::Matrix_<SimTK::Vec3> noData; auto emptyMarkersTable = std::make_shared<TimeSeriesTableVec3>(emptyTimes, noData, emptyLabels); tables.emplace(_markers, emptyMarkersTable); } // This is probably the right way to get the raw forces data from force // platforms. Extract the collection of force platforms. auto force_platforms_extractor = btk::ForcePlatformsExtractor::New(); force_platforms_extractor->SetInput(acquisition); auto force_platform_collection = force_platforms_extractor->GetOutput(); force_platforms_extractor->Update(); std::vector<SimTK::Matrix_<double>> fpCalMatrices{}; std::vector<SimTK::Matrix_<double>> fpCorners{}; std::vector<SimTK::Matrix_<double>> fpOrigins{}; std::vector<unsigned> fpTypes{}; auto fp_force_pts = btk::PointCollection::New(); auto fp_moment_pts = btk::PointCollection::New(); auto fp_position_pts = btk::PointCollection::New(); for(auto platform = force_platform_collection->Begin(); platform != force_platform_collection->End(); ++platform) { const auto& calMatrix = (*platform)->GetCalMatrix(); const auto& corners = (*platform)->GetCorners(); const auto& origins = (*platform)->GetOrigin(); fpCalMatrices.push_back(convertToSimtkMatrix(calMatrix)); fpCorners.push_back(convertToSimtkMatrix(corners)); fpOrigins.push_back(convertToSimtkMatrix(origins)); fpTypes.push_back(static_cast<unsigned>((*platform)->GetType())); // Get ground reaction wrenches for the force platform. auto ground_reaction_wrench_filter = btk::GroundReactionWrenchFilter::New(); ground_reaction_wrench_filter->setLocation( btk::GroundReactionWrenchFilter::Location(getLocationForForceExpression())); ground_reaction_wrench_filter->SetInput(*platform); auto wrench_collection = ground_reaction_wrench_filter->GetOutput(); ground_reaction_wrench_filter->Update(); for(auto wrench = wrench_collection->Begin(); wrench != wrench_collection->End(); ++wrench) { // Forces time series. fp_force_pts->InsertItem((*wrench)->GetForce()); // Moment time series. fp_moment_pts->InsertItem((*wrench)->GetMoment()); // Position time series. fp_position_pts->InsertItem((*wrench)->GetPosition()); } } if(fp_force_pts->GetItemNumber() != 0) { std::vector<std::string> labels{}; ValueArray<std::string> units{}; for(int fp = 1; fp <= fp_force_pts->GetItemNumber(); ++fp) { auto fp_str = std::to_string(fp); labels.push_back(SimTK::Value<std::string>("f" + fp_str)); auto force_unit = acquisition->GetPointUnits(). at(_unit_index.at("force")); units.upd().push_back(SimTK::Value<std::string>(force_unit)); labels.push_back(SimTK::Value<std::string>("p" + fp_str)); auto position_unit = acquisition->GetPointUnits(). at(_unit_index.at("marker")); units.upd().push_back(SimTK::Value<std::string>(position_unit)); labels.push_back(SimTK::Value<std::string>("m" + fp_str)); auto moment_unit = acquisition->GetPointUnits(). at(_unit_index.at("moment")); units.upd().push_back(SimTK::Value<std::string>(moment_unit)); } const int nf = fp_force_pts->GetFrontItem()->GetFrameNumber(); std::vector<double> force_times(nf); SimTK::Matrix_<SimTK::Vec3> force_matrix(nf, (int)labels.size()); double time_step{1.0 / acquisition->GetAnalogFrequency()}; for(int f = 0; f < nf; ++f) { SimTK::RowVector_<SimTK::Vec3> row{fp_force_pts->GetItemNumber() * 3}; int col{0}; for(auto fit = fp_force_pts->Begin(), mit = fp_moment_pts->Begin(), pit = fp_position_pts->Begin(); fit != fp_force_pts->End(); ++fit, ++mit, ++pit) { row[col] = SimTK::Vec3{(*fit)->GetValues().coeff(f, 0), (*fit)->GetValues().coeff(f, 1), (*fit)->GetValues().coeff(f, 2)}; ++col; row[col] = SimTK::Vec3{(*pit)->GetValues().coeff(f, 0), (*pit)->GetValues().coeff(f, 1), (*pit)->GetValues().coeff(f, 2)}; ++col; row[col] = SimTK::Vec3{(*mit)->GetValues().coeff(f, 0), (*mit)->GetValues().coeff(f, 1), (*mit)->GetValues().coeff(f, 2)}; ++col; } force_matrix.updRow(f) = row; force_times[f] = 0 + f * time_step; //TODO: 0 should be start_time } auto& force_table = *(new TimeSeriesTableVec3(force_times, force_matrix, labels)); TimeSeriesTableVec3::DependentsMetaData force_dep_metadata = force_table.getDependentsMetaData(); // add units to the dependent meta data force_dep_metadata.setValueArrayForKey("units", units); force_table.setDependentsMetaData(force_dep_metadata); force_table. updTableMetaData(). setValueForKey("CalibrationMatrices", std::move(fpCalMatrices)); force_table. updTableMetaData(). setValueForKey("Corners", std::move(fpCorners)); force_table. updTableMetaData(). setValueForKey("Origins", std::move(fpOrigins)); force_table. updTableMetaData(). setValueForKey("Types", std::move(fpTypes)); force_table. updTableMetaData(). setValueForKey("DataRate", std::to_string(acquisition->GetAnalogFrequency())); tables.emplace(_forces, std::shared_ptr<TimeSeriesTableVec3>(&force_table)); force_table.updTableMetaData().setValueForKey("events", event_table); } else { // insert empty table std::vector<double> emptyTimes; std::vector<std::string> emptyLabels; SimTK::Matrix_<SimTK::Vec3> noData; auto emptyforcesTable = std::make_shared<TimeSeriesTableVec3>(emptyTimes, noData, emptyLabels); tables.emplace(_forces, emptyforcesTable); } return tables; #endif } void C3DFileAdapter::extendWrite(const InputTables& absTables, const std::string& fileName) const { throw Exception{"Writing to C3D not supported yet."}; } } // namespace OpenSim <commit_msg>Included markers from ezc3d<commit_after>#include "C3DFileAdapter.h" #ifdef WITH_EZC3D // TODO manage the header into one include #include "../ezc3d/Header.h" #include "../ezc3d/Parameters.h" #include "../ezc3d/Data.h" #else #include "btkAcquisitionFileReader.h" #include "btkAcquisition.h" #include "btkForcePlatformsExtractor.h" #include "btkGroundReactionWrenchFilter.h" #endif namespace { #ifdef WITH_BTK // Function to convert Eigen matrix to SimTK matrix. This can become a lambda // funciton inside extendRead in future. template<typename _Scalar, int _Rows, int _Cols> SimTK::Matrix_<double> convertToSimtkMatrix(const Eigen::Matrix<_Scalar, _Rows, _Cols>& eigenMat) { SimTK::Matrix_<double> simtkMat{static_cast<int>(eigenMat.rows()), static_cast<int>(eigenMat.cols())}; for(int r = 0; r < eigenMat.rows(); ++r) for(int c = 0; c < eigenMat.cols(); ++c) simtkMat(r, c) = eigenMat(r, c); return simtkMat; } #endif } // anonymous namespace namespace OpenSim { const std::string C3DFileAdapter::_markers{"markers"}; const std::string C3DFileAdapter::_forces{"forces"}; const std::unordered_map<std::string, size_t> C3DFileAdapter::_unit_index{{"marker", 0}, {"angle" , 1}, {"force" , 2}, {"moment", 3}, {"power" , 4}, {"scalar", 5}}; C3DFileAdapter* C3DFileAdapter::clone() const { return new C3DFileAdapter{*this}; } void C3DFileAdapter::write(const C3DFileAdapter::Tables& tables, const std::string& fileName) { throw Exception{"Writing C3D not supported yet."}; } C3DFileAdapter::OutputTables C3DFileAdapter::extendRead(const std::string& fileName) const { #ifdef WITH_EZC3D auto c3d = ezc3d::c3d(fileName); #else auto reader = btk::AcquisitionFileReader::New(); reader->SetFilename(fileName); reader->Update(); auto acquisition = reader->GetOutput(); #endif EventTable event_table{}; #ifdef WITH_EZC3D for (size_t i=0; i<c3d.header().eventsTime().size(); ++i) { std::string eventDescriptionStr(""); if (c3d.parameters().isGroup("EVENT") && c3d.parameters().group("EVENT").isParameter("DESCRIPTION")){ const auto& eventDescription(c3d.parameters().group("EVENT").parameter("DESCRIPTION").valuesAsString()); if (eventDescription.size() >= i){ eventDescriptionStr = eventDescription[i]; } } event_table.push_back( { c3d.header().eventsLabel(i), static_cast<double>(c3d.header().eventsTime(i)), static_cast<int>(c3d.header().eventsTime(i) / c3d.header().frameRate()), eventDescriptionStr }); } #else auto events = acquisition->GetEvents(); for (auto it = events->Begin(); it != events->End(); ++it) { auto et = *it; event_table.push_back({ et->GetLabel(), et->GetTime(), et->GetFrame(), et->GetDescription() }); } #endif OutputTables tables{}; #ifdef WITH_EZC3D int nbFrames(static_cast<int>(c3d.data().nbFrames())); int nbMarkers(c3d.parameters().group("POINT").parameter("USED").valuesAsInt()[0]); double pointFrequency(static_cast<double>( c3d.parameters().group("POINT").parameter("RATE").valuesAsFloat()[0])); #else auto marker_pts = btk::PointCollection::New(); for(auto it = acquisition->BeginPoint(); it != acquisition->EndPoint(); ++it) { auto pt = *it; if(pt->GetType() == btk::Point::Marker) marker_pts->InsertItem(pt); } int nbFrames(marker_pts->GetFrontItem()->GetFrameNumber()); int nbMarkers(marker_pts->GetItemNumber()); double pointFrequency(acquisition->GetPointFrequency()); #endif if(nbMarkers != 0) { int marker_nrow = nbFrames; int marker_ncol = nbMarkers; std::vector<double> marker_times(marker_nrow); SimTK::Matrix_<SimTK::Vec3> marker_matrix(marker_nrow, marker_ncol); std::vector<std::string> marker_labels{}; #ifdef WITH_EZC3D for (auto label : c3d.parameters().group("POINT").parameter("LABELS").valuesAsString()) { marker_labels.push_back(SimTK::Value<std::string>(label)); } #else for (auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) { marker_labels.push_back(SimTK::Value<std::string>((*it)->GetLabel())); } #endif double time_step{1.0 / pointFrequency}; for(int f = 0; f < marker_nrow; ++f) { SimTK::RowVector_<SimTK::Vec3> row{ nbMarkers, SimTK::Vec3(SimTK::NaN) }; int m{0}; // C3D standard is to read empty values as zero, but sets a // "residual" value to -1 and it is how it knows to export these // values as blank, instead of 0, when exporting to .trc // See: C3D documention 3D Point Residuals // Read in value if it is not zero or residual is not -1 #ifdef WITH_EZC3D for(auto pt : c3d.data().frame(f).points().points()) { if (!pt.isempty() ) {//residual is not -1 row[m] = SimTK::Vec3{ static_cast<double>(pt.x()), static_cast<double>(pt.y()), static_cast<double>(pt.z()) }; } ++m; } #else for(auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) { auto pt = *it; if (!pt->GetValues().row(f).isZero() || //not precisely zero (pt->GetResiduals().coeff(f) != -1) ) {//residual is not -1 row[m] = SimTK::Vec3{ pt->GetValues().coeff(f, 0), pt->GetValues().coeff(f, 1), pt->GetValues().coeff(f, 2) }; } ++m; } #endif marker_matrix.updRow(f) = row; marker_times[f] = 0 + f * time_step; //TODO: 0 should be start_time } // Create the data auto marker_table = std::make_shared<TimeSeriesTableVec3>(marker_times, marker_matrix, marker_labels); marker_table-> updTableMetaData(). setValueForKey("DataRate", std::to_string(pointFrequency)); marker_table-> updTableMetaData(). setValueForKey("Units", #ifdef WITH_EZC3D c3d.parameters().group("POINT").parameter("UNITS").valuesAsString()[0] #else acquisition->GetPointUnit() #endif ); marker_table->updTableMetaData().setValueForKey("events", event_table); tables.emplace(_markers, marker_table); } else { // insert empty table std::vector<double> emptyTimes; std::vector<std::string> emptyLabels; SimTK::Matrix_<SimTK::Vec3> noData; auto emptyMarkersTable = std::make_shared<TimeSeriesTableVec3>(emptyTimes, noData, emptyLabels); tables.emplace(_markers, emptyMarkersTable); } #ifndef WITH_EZC3D // This is probably the right way to get the raw forces data from force // platforms. Extract the collection of force platforms. auto force_platforms_extractor = btk::ForcePlatformsExtractor::New(); force_platforms_extractor->SetInput(acquisition); auto force_platform_collection = force_platforms_extractor->GetOutput(); force_platforms_extractor->Update(); std::vector<SimTK::Matrix_<double>> fpCalMatrices{}; std::vector<SimTK::Matrix_<double>> fpCorners{}; std::vector<SimTK::Matrix_<double>> fpOrigins{}; std::vector<unsigned> fpTypes{}; auto fp_force_pts = btk::PointCollection::New(); auto fp_moment_pts = btk::PointCollection::New(); auto fp_position_pts = btk::PointCollection::New(); for(auto platform = force_platform_collection->Begin(); platform != force_platform_collection->End(); ++platform) { const auto& calMatrix = (*platform)->GetCalMatrix(); const auto& corners = (*platform)->GetCorners(); const auto& origins = (*platform)->GetOrigin(); fpCalMatrices.push_back(convertToSimtkMatrix(calMatrix)); fpCorners.push_back(convertToSimtkMatrix(corners)); fpOrigins.push_back(convertToSimtkMatrix(origins)); fpTypes.push_back(static_cast<unsigned>((*platform)->GetType())); // Get ground reaction wrenches for the force platform. auto ground_reaction_wrench_filter = btk::GroundReactionWrenchFilter::New(); ground_reaction_wrench_filter->setLocation( btk::GroundReactionWrenchFilter::Location(getLocationForForceExpression())); ground_reaction_wrench_filter->SetInput(*platform); auto wrench_collection = ground_reaction_wrench_filter->GetOutput(); ground_reaction_wrench_filter->Update(); for(auto wrench = wrench_collection->Begin(); wrench != wrench_collection->End(); ++wrench) { // Forces time series. fp_force_pts->InsertItem((*wrench)->GetForce()); // Moment time series. fp_moment_pts->InsertItem((*wrench)->GetMoment()); // Position time series. fp_position_pts->InsertItem((*wrench)->GetPosition()); } } if(fp_force_pts->GetItemNumber() != 0) { std::vector<std::string> labels{}; ValueArray<std::string> units{}; for(int fp = 1; fp <= fp_force_pts->GetItemNumber(); ++fp) { auto fp_str = std::to_string(fp); labels.push_back(SimTK::Value<std::string>("f" + fp_str)); auto force_unit = acquisition->GetPointUnits(). at(_unit_index.at("force")); units.upd().push_back(SimTK::Value<std::string>(force_unit)); labels.push_back(SimTK::Value<std::string>("p" + fp_str)); auto position_unit = acquisition->GetPointUnits(). at(_unit_index.at("marker")); units.upd().push_back(SimTK::Value<std::string>(position_unit)); labels.push_back(SimTK::Value<std::string>("m" + fp_str)); auto moment_unit = acquisition->GetPointUnits(). at(_unit_index.at("moment")); units.upd().push_back(SimTK::Value<std::string>(moment_unit)); } const int nf = fp_force_pts->GetFrontItem()->GetFrameNumber(); std::vector<double> force_times(nf); SimTK::Matrix_<SimTK::Vec3> force_matrix(nf, (int)labels.size()); double time_step{1.0 / acquisition->GetAnalogFrequency()}; for(int f = 0; f < nf; ++f) { SimTK::RowVector_<SimTK::Vec3> row{fp_force_pts->GetItemNumber() * 3}; int col{0}; for(auto fit = fp_force_pts->Begin(), mit = fp_moment_pts->Begin(), pit = fp_position_pts->Begin(); fit != fp_force_pts->End(); ++fit, ++mit, ++pit) { row[col] = SimTK::Vec3{(*fit)->GetValues().coeff(f, 0), (*fit)->GetValues().coeff(f, 1), (*fit)->GetValues().coeff(f, 2)}; ++col; row[col] = SimTK::Vec3{(*pit)->GetValues().coeff(f, 0), (*pit)->GetValues().coeff(f, 1), (*pit)->GetValues().coeff(f, 2)}; ++col; row[col] = SimTK::Vec3{(*mit)->GetValues().coeff(f, 0), (*mit)->GetValues().coeff(f, 1), (*mit)->GetValues().coeff(f, 2)}; ++col; } force_matrix.updRow(f) = row; force_times[f] = 0 + f * time_step; //TODO: 0 should be start_time } auto& force_table = *(new TimeSeriesTableVec3(force_times, force_matrix, labels)); TimeSeriesTableVec3::DependentsMetaData force_dep_metadata = force_table.getDependentsMetaData(); // add units to the dependent meta data force_dep_metadata.setValueArrayForKey("units", units); force_table.setDependentsMetaData(force_dep_metadata); force_table. updTableMetaData(). setValueForKey("CalibrationMatrices", std::move(fpCalMatrices)); force_table. updTableMetaData(). setValueForKey("Corners", std::move(fpCorners)); force_table. updTableMetaData(). setValueForKey("Origins", std::move(fpOrigins)); force_table. updTableMetaData(). setValueForKey("Types", std::move(fpTypes)); force_table. updTableMetaData(). setValueForKey("DataRate", std::to_string(acquisition->GetAnalogFrequency())); tables.emplace(_forces, std::shared_ptr<TimeSeriesTableVec3>(&force_table)); force_table.updTableMetaData().setValueForKey("events", event_table); } else { // insert empty table std::vector<double> emptyTimes; std::vector<std::string> emptyLabels; SimTK::Matrix_<SimTK::Vec3> noData; auto emptyforcesTable = std::make_shared<TimeSeriesTableVec3>(emptyTimes, noData, emptyLabels); tables.emplace(_forces, emptyforcesTable); } #endif return tables; } void C3DFileAdapter::extendWrite(const InputTables& absTables, const std::string& fileName) const { throw Exception{"Writing to C3D not supported yet."}; } } // namespace OpenSim <|endoftext|>